mirror of
https://github.com/GTNewHorizons/Angelica.git
synced 2026-11-25 14:44:28 +00:00
SDL GPU backend, TESR Batching/caching API, Tracy Integration (#1993)
This commit is contained in:
1 parent
413df76ad4
commit
8da561d3b6
647 files changed
+60152
-5331
No files matched your search
@@ -0,0 +1,39 @@
|
||||
package com.gtnewhorizons.angelica.api.tesr;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
|
||||
class TesrMaterialInternTest {
|
||||
|
||||
@Test
|
||||
void equalSettingsBuildSameInstance() {
|
||||
final TesrMaterial a = TesrMaterial.builder().color(1f, 0.5f, 0.25f, 1f).translucent().stream().build();
|
||||
final TesrMaterial b = TesrMaterial.builder().color(1f, 0.5f, 0.25f, 1f).translucent().stream().build();
|
||||
assertSame(a, b);
|
||||
}
|
||||
|
||||
@Test
|
||||
void differingSettingsBuildDistinctInstances() {
|
||||
final TesrMaterial a = TesrMaterial.builder().color(1f, 0.5f, 0.25f, 1f).translucent().build();
|
||||
final TesrMaterial b = TesrMaterial.builder().color(1f, 0.5f, 0.25f, 1f).additive().build();
|
||||
assertNotSame(a, b);
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultsFoldToCurrentState() {
|
||||
assertSame(TesrMaterial.CURRENT_STATE, TesrMaterial.builder().build());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shaderIdentitySplitsOtherwiseEqualMaterials() {
|
||||
final TesrShader s1 = TesrShaders.register("test:intern_a", () -> {}, () -> {});
|
||||
final TesrShader s2 = TesrShaders.register("test:intern_b", () -> {}, () -> {});
|
||||
final TesrMaterial a = TesrMaterial.builder().translucent().shader(s1).build();
|
||||
final TesrMaterial b = TesrMaterial.builder().translucent().shader(s2).build();
|
||||
final TesrMaterial c = TesrMaterial.builder().translucent().shader(s1).build();
|
||||
assertNotSame(a, b);
|
||||
assertSame(a, c);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.gtnewhorizons.angelica.api.tesr;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class TesrShadersTest {
|
||||
|
||||
private static final Runnable NOOP = () -> {};
|
||||
|
||||
@Test
|
||||
void registerReturnsHandleWithAccessors() {
|
||||
final Runnable bind = () -> {};
|
||||
final Runnable release = () -> {};
|
||||
final TesrShader shader = TesrShaders.register("test:accessors", bind, release);
|
||||
assertEquals("test:accessors", shader.name());
|
||||
assertSame(bind, shader.bind());
|
||||
assertSame(release, shader.release());
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateNameThrows() {
|
||||
TesrShaders.register("test:duplicate", NOOP, NOOP);
|
||||
assertThrows(IllegalStateException.class, () -> TesrShaders.register("test:duplicate", NOOP, NOOP));
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedNamesThrow() {
|
||||
assertThrows(IllegalArgumentException.class, () -> TesrShaders.register("nonamespace", NOOP, NOOP));
|
||||
assertThrows(IllegalArgumentException.class, () -> TesrShaders.register(":path", NOOP, NOOP));
|
||||
assertThrows(IllegalArgumentException.class, () -> TesrShaders.register("ns:", NOOP, NOOP));
|
||||
assertThrows(IllegalArgumentException.class, () -> TesrShaders.register("a:b:c", NOOP, NOOP));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullRunnablesThrow() {
|
||||
assertThrows(NullPointerException.class, () -> TesrShaders.register("test:null_bind", null, NOOP));
|
||||
assertThrows(NullPointerException.class, () -> TesrShaders.register("test:null_release", NOOP, null));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.gtnewhorizons.angelica.arch;
|
||||
|
||||
import com.tngtech.archunit.base.DescribedPredicate;
|
||||
import com.tngtech.archunit.core.domain.JavaClass;
|
||||
import com.tngtech.archunit.core.domain.JavaClasses;
|
||||
import com.tngtech.archunit.core.importer.ClassFileImporter;
|
||||
import com.tngtech.archunit.core.importer.ImportOption;
|
||||
import com.tngtech.archunit.lang.ArchRule;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
|
||||
|
||||
/**
|
||||
* Enforces the :sdl-gpu module boundary
|
||||
*/
|
||||
class SDLGPUEncapsulationTest {
|
||||
|
||||
private static final String SDLGPU_ROOT = "com.gtnewhorizons.angelica.sdlgpu";
|
||||
|
||||
private static final Set<String> PUBLIC_ENTRIES = Set.of(
|
||||
SDLGPU_ROOT + ".SDLGPURenderBackend", // ServiceLoader
|
||||
SDLGPU_ROOT + ".SDLGPULWJGLService", // ServiceLoader
|
||||
SDLGPU_ROOT + ".SDLGPUGate", // Mixins, MixinInitGLStateManager
|
||||
SDLGPU_ROOT + ".SDLGPUDisplayBridge", // MixinForgeHooksClient_SDLGPUDisplay
|
||||
SDLGPU_ROOT + ".device.SDLDrawable", // MixinForgeHooksClient_SDLGPUDisplay
|
||||
SDLGPU_ROOT + ".shader.ShaderManager" // Iris, IrisGLSMBridge
|
||||
);
|
||||
|
||||
private static final DescribedPredicate<JavaClass> SDLGPU_INTERNAL =
|
||||
new DescribedPredicate<>("sdlgpu internals (anything under " + SDLGPU_ROOT + " not on the allow-list)") {
|
||||
@Override
|
||||
public boolean test(JavaClass c) {
|
||||
final String name = c.getName();
|
||||
return name.startsWith(SDLGPU_ROOT + ".") && !PUBLIC_ENTRIES.contains(name);
|
||||
}
|
||||
};
|
||||
|
||||
private static final JavaClasses CLASSES = new ClassFileImporter()
|
||||
.withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS)
|
||||
.importPaths("build/classes/java/main", "build/classes/java/mixin");
|
||||
|
||||
private static final ArchRule NO_SDLGPU_INTERNALS_FROM_OUTSIDE = noClasses()
|
||||
.that().resideOutsideOfPackage(SDLGPU_ROOT + "..")
|
||||
.should().dependOnClassesThat(SDLGPU_INTERNAL)
|
||||
.because("only the allow-listed classes may be referenced by name from outside :sdl-gpu");
|
||||
|
||||
@Test
|
||||
void noSdlGpuInternalsFromOutside() {
|
||||
NO_SDLGPU_INTERNALS_FROM_OUTSIDE.check(CLASSES);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.gtnewhorizons.angelica.client;
|
||||
|
||||
import com.gtnewhorizons.angelica.mixins.interfaces.ChatLineFormattedAccessor;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
|
||||
class ChatLineFormattedCacheTest {
|
||||
|
||||
private static final class Line implements ChatLineFormattedAccessor {
|
||||
private String formatted;
|
||||
private long formattedEpoch = Long.MIN_VALUE;
|
||||
|
||||
@Override
|
||||
public String angelica$getFormatted(long epoch) {
|
||||
return formattedEpoch == epoch ? formatted : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void angelica$setFormatted(String formatted, long epoch) {
|
||||
this.formatted = formatted;
|
||||
this.formattedEpoch = epoch;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFreshLineHasNothingCached() {
|
||||
assertNull(new Line().angelica$getFormatted(0L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSameEpochReturnsTheCachedInstance() {
|
||||
final Line line = new Line();
|
||||
final String formatted = "§ahello";
|
||||
line.angelica$setFormatted(formatted, 1234L);
|
||||
assertSame(formatted, line.angelica$getFormatted(1234L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTranslationEpochChangeInvalidates() {
|
||||
final Line line = new Line();
|
||||
line.angelica$setFormatted("§aold locale", 1234L);
|
||||
assertNull(line.angelica$getFormatted(5678L), "a language reload must force a rebuild");
|
||||
|
||||
line.angelica$setFormatted("§anew locale", 5678L);
|
||||
assertEquals("§anew locale", line.angelica$getFormatted(5678L));
|
||||
assertNull(line.angelica$getFormatted(1234L), "the stale epoch never comes back");
|
||||
}
|
||||
|
||||
@Test
|
||||
void obfuscatedCodesAreCachedVerbatim() {
|
||||
final Line line = new Line();
|
||||
final String formatted = "§kMAGIC§r plain";
|
||||
line.angelica$setFormatted(formatted, 7L);
|
||||
assertEquals(formatted, line.angelica$getFormatted(7L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void zeroIsAUsableEpoch() {
|
||||
final Line line = new Line();
|
||||
line.angelica$setFormatted("x", 0L);
|
||||
assertEquals("x", line.angelica$getFormatted(0L));
|
||||
}
|
||||
}
|
||||
+5
-4
@@ -1,5 +1,6 @@
|
||||
package com.gtnewhorizons.angelica.client.rendering;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
@@ -57,7 +58,7 @@ class DeferredDrawBatcherTest {
|
||||
|
||||
// Create entries with interleaved keys: A, B, A, B, A
|
||||
final int flags = VertexFlags.convertToFlags(true, true, false, true);
|
||||
var entries = new java.util.ArrayList<DeferredBatchTessellator.DrawRange>();
|
||||
var entries = new ArrayList<DeferredBatchTessellator.DrawRange>();
|
||||
entries.add(new DeferredBatchTessellator.DrawRange(keyA, 0, 128, 4, GL11.GL_QUADS, flags));
|
||||
entries.add(new DeferredBatchTessellator.DrawRange(keyB, 128, 128, 4, GL11.GL_QUADS, flags));
|
||||
entries.add(new DeferredBatchTessellator.DrawRange(keyA, 256, 128, 4, GL11.GL_QUADS, flags));
|
||||
@@ -97,7 +98,7 @@ class DeferredDrawBatcherTest {
|
||||
long key = DeferredDrawBatcher.packStateKey(1, 0x0302, 0x0001, true, true, true, true);
|
||||
|
||||
final int flags = VertexFlags.convertToFlags(true, true, false, true);
|
||||
var entries = new java.util.ArrayList<DeferredBatchTessellator.DrawRange>();
|
||||
var entries = new ArrayList<DeferredBatchTessellator.DrawRange>();
|
||||
entries.add(new DeferredBatchTessellator.DrawRange(key, 0, 128, 4, GL11.GL_QUADS, flags));
|
||||
entries.add(new DeferredBatchTessellator.DrawRange(key, 128, 256, 8, GL11.GL_QUADS, flags));
|
||||
entries.add(new DeferredBatchTessellator.DrawRange(key, 384, 128, 4, GL11.GL_QUADS, flags));
|
||||
@@ -119,7 +120,7 @@ class DeferredDrawBatcherTest {
|
||||
long key = DeferredDrawBatcher.packStateKey(1, 0x0302, 0x0001, true, true, true, true);
|
||||
|
||||
final int flags = VertexFlags.convertToFlags(true, true, false, true);
|
||||
var entries = new java.util.ArrayList<DeferredBatchTessellator.DrawRange>();
|
||||
var entries = new ArrayList<DeferredBatchTessellator.DrawRange>();
|
||||
entries.add(new DeferredBatchTessellator.DrawRange(key, 0, 128, 4, GL11.GL_QUADS, flags));
|
||||
entries.add(new DeferredBatchTessellator.DrawRange(key, 128, 128, 4, GL11.GL_TRIANGLES, flags));
|
||||
entries.add(new DeferredBatchTessellator.DrawRange(key, 256, 128, 4, GL11.GL_QUADS, flags));
|
||||
@@ -194,7 +195,7 @@ class DeferredDrawBatcherTest {
|
||||
final int flags = VertexFlags.convertToFlags(true, true, false, true);
|
||||
|
||||
// Simulate sequential byte offsets as would be produced by interceptDraw
|
||||
var ranges = new java.util.ArrayList<DeferredBatchTessellator.DrawRange>();
|
||||
var ranges = new ArrayList<DeferredBatchTessellator.DrawRange>();
|
||||
int offset = 0;
|
||||
for (int i = 0; i < 5; i++) {
|
||||
int byteLen = (i + 1) * 128; // 128, 256, 384, 512, 640
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
package com.gtnewhorizons.angelica.compat.bop;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class BopFogBlendTest {
|
||||
|
||||
private static final float EPSILON = 1e-4f;
|
||||
|
||||
private static float[] reference(BopFogBlend.ColorSource source, double posX, double posZ, int playerX,
|
||||
int playerY, int playerZ, int distance) {
|
||||
|
||||
float rBiomeFog = 0, gBiomeFog = 0, bBiomeFog = 0, weightBiomeFog = 0;
|
||||
for (int x = -distance; x <= distance; ++x) {
|
||||
for (int z = -distance; z <= distance; ++z) {
|
||||
final int fogColour = source.fogColour(playerX + x, playerY, playerZ + z);
|
||||
if (fogColour == BopFogBlend.NO_FOG) continue;
|
||||
|
||||
float rPart = (fogColour & 0xFF0000) >> 16;
|
||||
float gPart = (fogColour & 0x00FF00) >> 8;
|
||||
float bPart = fogColour & 0x0000FF;
|
||||
float weightPart = 1;
|
||||
|
||||
if (x == -distance) {
|
||||
final double xDiff = 1 - (posX - playerX);
|
||||
rPart *= xDiff;
|
||||
gPart *= xDiff;
|
||||
bPart *= xDiff;
|
||||
weightPart *= xDiff;
|
||||
} else if (x == distance) {
|
||||
final double xDiff = posX - playerX;
|
||||
rPart *= xDiff;
|
||||
gPart *= xDiff;
|
||||
bPart *= xDiff;
|
||||
weightPart *= xDiff;
|
||||
}
|
||||
|
||||
if (z == -distance) {
|
||||
final double zDiff = 1 - (posZ - playerZ);
|
||||
rPart *= zDiff;
|
||||
gPart *= zDiff;
|
||||
bPart *= zDiff;
|
||||
weightPart *= zDiff;
|
||||
} else if (z == distance) {
|
||||
final double zDiff = posZ - playerZ;
|
||||
rPart *= zDiff;
|
||||
gPart *= zDiff;
|
||||
bPart *= zDiff;
|
||||
weightPart *= zDiff;
|
||||
}
|
||||
|
||||
rBiomeFog += rPart;
|
||||
gBiomeFog += gPart;
|
||||
bBiomeFog += bPart;
|
||||
weightBiomeFog += weightPart;
|
||||
}
|
||||
}
|
||||
return new float[] { rBiomeFog, gBiomeFog, bBiomeFog, weightBiomeFog };
|
||||
}
|
||||
|
||||
/** Deterministic pseudo-random grid: every column is either a fog biome with a stable colour, or plain. */
|
||||
private record Grid(long seed, int fogPercent) implements BopFogBlend.ColorSource {
|
||||
|
||||
@Override
|
||||
public int fogColour(int x, int y, int z) {
|
||||
long h = seed;
|
||||
h = h * 31 + x;
|
||||
h = h * 31 + y;
|
||||
h = h * 31 + z;
|
||||
h ^= h >>> 27;
|
||||
h *= 0x9E3779B97F4A7C15L;
|
||||
h ^= h >>> 31;
|
||||
if (Math.floorMod(h, 100) >= fogPercent) return BopFogBlend.NO_FOG;
|
||||
return (int) (h >>> 8) & 0xFFFFFF;
|
||||
}
|
||||
}
|
||||
|
||||
private final float[] out = new float[4];
|
||||
private final Object world = new Object();
|
||||
|
||||
@BeforeEach
|
||||
void reset() {
|
||||
BopFogBlend.invalidate();
|
||||
}
|
||||
|
||||
private void assertMatchesReference(BopFogBlend.ColorSource source, double posX, double posZ, int px, int py,
|
||||
int pz, int distance, int generation) {
|
||||
|
||||
final float[] expected = reference(source, posX, posZ, px, py, pz, distance);
|
||||
BopFogBlend.accumulate(world, generation, source, posX, posZ, px, py, pz, distance, out);
|
||||
for (int i = 0; i < 4; i++) {
|
||||
final float tolerance = Math.max(EPSILON, Math.abs(expected[i]) * EPSILON);
|
||||
assertEquals(expected[i], out[i], tolerance, "component " + i);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void matchesReferenceOverRandomGridsAndPositions() {
|
||||
final Random random = new Random(12345);
|
||||
for (int iteration = 0; iteration < 200; iteration++) {
|
||||
final Grid grid = new Grid(random.nextLong(), random.nextInt(101));
|
||||
final int px = random.nextInt(4000) - 2000;
|
||||
final int py = random.nextInt(256);
|
||||
final int pz = random.nextInt(4000) - 2000;
|
||||
final double posX = px + random.nextDouble();
|
||||
final double posZ = pz + random.nextDouble();
|
||||
final int distance = random.nextInt(21);
|
||||
assertMatchesReference(grid, posX, posZ, px, py, pz, distance, iteration);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void noFogBiomesAccumulateNothing() {
|
||||
final BopFogBlend.ColorSource none = (x, y, z) -> BopFogBlend.NO_FOG;
|
||||
BopFogBlend.accumulate(world, 0, none, 10.5, 20.25, 10, 64, 20, 20, out);
|
||||
assertArrayEquals(new float[] { 0, 0, 0, 0 }, out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void fullCoverageMatchesReference() {
|
||||
final BopFogBlend.ColorSource all = (x, y, z) -> 0x203040;
|
||||
assertMatchesReference(all, 10.5, 20.5, 10, 64, 20, 20, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void borderOnlyCoverageMatchesReference() {
|
||||
final int distance = 12;
|
||||
final BopFogBlend.ColorSource borderOnly = (x, y, z) -> {
|
||||
final int dx = Math.abs(x - 100);
|
||||
final int dz = Math.abs(z - 200);
|
||||
return (dx == distance || dz == distance) ? 0xFF8040 : BopFogBlend.NO_FOG;
|
||||
};
|
||||
assertMatchesReference(borderOnly, 100.75, 200.125, 100, 64, 200, distance, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void interiorIsReusedAcrossSubBlockMovementAndRebuiltOnCrossing() {
|
||||
final Grid grid = new Grid(99, 60);
|
||||
for (double frac = 0.05; frac < 1.0; frac += 0.1) {
|
||||
assertMatchesReference(grid, 40 + frac, 80 + frac, 40, 64, 80, 16, 7);
|
||||
}
|
||||
assertMatchesReference(grid, 41.5, 80.5, 41, 64, 80, 16, 7);
|
||||
assertMatchesReference(grid, 41.5, 80.5, 41, 65, 80, 16, 7);
|
||||
assertMatchesReference(grid, 41.5, 80.5, 41, 65, 80, 12, 7);
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyTheBorderIsWalkedWhileTheBlockPositionHolds() {
|
||||
final int distance = 20;
|
||||
final int[] lookups = { 0 };
|
||||
final BopFogBlend.ColorSource counting = (x, y, z) -> {
|
||||
lookups[0]++;
|
||||
return 0x102030;
|
||||
};
|
||||
|
||||
BopFogBlend.accumulate(world, 0, counting, 100.1, 200.1, 100, 64, 200, distance, out);
|
||||
assertEquals((2 * distance + 1) * (2 * distance + 1), lookups[0], "first call must walk every column");
|
||||
|
||||
lookups[0] = 0;
|
||||
BopFogBlend.accumulate(world, 0, counting, 100.9, 200.9, 100, 64, 200, distance, out);
|
||||
assertEquals(8 * distance, lookups[0], "a sub-block move must only re-walk the border strips");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNewGenerationRebuildsTheInterior() {
|
||||
final int[] answer = { 0x101010 };
|
||||
final BopFogBlend.ColorSource shifting = (x, y, z) -> answer[0];
|
||||
|
||||
BopFogBlend.accumulate(world, 1, shifting, 0.5, 0.5, 0, 64, 0, 8, out);
|
||||
final float firstInteriorRed = out[0];
|
||||
|
||||
answer[0] = 0x202020;
|
||||
BopFogBlend.accumulate(world, 2, shifting, 0.5, 0.5, 0, 64, 0, 8, out);
|
||||
assertEquals(firstInteriorRed * 2, out[0], firstInteriorRed * EPSILON,
|
||||
"a generation bump must rebuild the cached interior, not serve the stale sum");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNewWorldRebuildsTheInterior() {
|
||||
final int[] answer = { 0x101010 };
|
||||
final BopFogBlend.ColorSource shifting = (x, y, z) -> answer[0];
|
||||
|
||||
BopFogBlend.accumulate(world, 0, shifting, 0.5, 0.5, 0, 64, 0, 8, out);
|
||||
final float firstInteriorRed = out[0];
|
||||
|
||||
answer[0] = 0x202020;
|
||||
BopFogBlend.accumulate(new Object(), 0, shifting, 0.5, 0.5, 0, 64, 0, 8, out);
|
||||
assertEquals(firstInteriorRed * 2, out[0], firstInteriorRed * EPSILON);
|
||||
}
|
||||
|
||||
@Test
|
||||
void zeroDistanceMatchesReference() {
|
||||
final BopFogBlend.ColorSource all = (x, y, z) -> 0x804020;
|
||||
assertMatchesReference(all, 5.5, 6.25, 5, 64, 6, 0, 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.gtnewhorizons.angelica.compat.bop;
|
||||
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraft.world.biome.BiomeGenBase;
|
||||
import net.minecraft.world.chunk.IChunkProvider;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class FogBiomeCacheTest {
|
||||
|
||||
private static World worldWith(BiomeGenBase biome, boolean chunkLoaded) {
|
||||
final World world = Mockito.mock(World.class);
|
||||
final IChunkProvider provider = Mockito.mock(IChunkProvider.class);
|
||||
when(world.getBiomeGenForCoords(anyInt(), anyInt())).thenReturn(biome);
|
||||
when(world.getChunkProvider()).thenReturn(provider);
|
||||
when(provider.chunkExists(anyInt(), anyInt())).thenReturn(chunkLoaded);
|
||||
return world;
|
||||
}
|
||||
|
||||
@Test
|
||||
void repeatLookupsHitTheCache() {
|
||||
final BiomeGenBase biome = Mockito.mock(BiomeGenBase.class);
|
||||
final World world = worldWith(biome, true);
|
||||
|
||||
assertSame(biome, FogBiomeCache.get(world, 100, -7));
|
||||
assertSame(biome, FogBiomeCache.get(world, 100, -7));
|
||||
verify(world, times(1)).getBiomeGenForCoords(anyInt(), anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unloadedChunksAreNotCached() {
|
||||
final BiomeGenBase biome = Mockito.mock(BiomeGenBase.class);
|
||||
final World world = worldWith(biome, false);
|
||||
|
||||
FogBiomeCache.get(world, 5000, 5000);
|
||||
FogBiomeCache.get(world, 5000, 5000);
|
||||
verify(world, times(2)).getBiomeGenForCoords(anyInt(), anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void worldChangeClearsTheCache() {
|
||||
final BiomeGenBase a = Mockito.mock(BiomeGenBase.class);
|
||||
final BiomeGenBase b = Mockito.mock(BiomeGenBase.class);
|
||||
final World worldA = worldWith(a, true);
|
||||
final World worldB = worldWith(b, true);
|
||||
|
||||
assertSame(a, FogBiomeCache.get(worldA, 0, 0));
|
||||
assertSame(b, FogBiomeCache.get(worldB, 0, 0), "same coords in a new world must re-resolve");
|
||||
assertSame(a, FogBiomeCache.get(worldA, 0, 0), "switching back re-resolves rather than serving worldB state");
|
||||
}
|
||||
|
||||
@Test
|
||||
void negativeCoordinatesDoNotCollide() {
|
||||
final BiomeGenBase biome = Mockito.mock(BiomeGenBase.class);
|
||||
final World world = worldWith(biome, true);
|
||||
|
||||
FogBiomeCache.get(world, -1, 0);
|
||||
FogBiomeCache.get(world, 0, -1);
|
||||
FogBiomeCache.get(world, -1, -1);
|
||||
verify(world, times(3)).getBiomeGenForCoords(anyInt(), anyInt());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.gtnewhorizons.angelica.rendering;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class OverridesMethodTest {
|
||||
|
||||
static class Base {
|
||||
public double dist(double x, double y, double z) { return 0; }
|
||||
public boolean pass(int p) { return p == 0; }
|
||||
}
|
||||
|
||||
static class Plain extends Base {}
|
||||
|
||||
static class Direct extends Base {
|
||||
@Override public double dist(double x, double y, double z) { return 1; }
|
||||
}
|
||||
|
||||
static class Inherited extends Direct {}
|
||||
|
||||
interface DefaultDist {
|
||||
default double dist(double x, double y, double z) { return 2; }
|
||||
}
|
||||
|
||||
static class WithInterfaceDefault extends Base implements DefaultDist {}
|
||||
|
||||
private static final String[] DIST = { "dist" };
|
||||
private static final String[] PASS = { "pass" };
|
||||
private static final Class<?>[] DIST_PARAMS = { double.class, double.class, double.class };
|
||||
|
||||
@Test
|
||||
void baseDeclarationIsNotAnOverride() {
|
||||
assertFalse(TileEntityRenderBoundsRegistry.overridesMethod(Base.class, Base.class, DIST, DIST_PARAMS));
|
||||
assertFalse(TileEntityRenderBoundsRegistry.overridesMethod(Plain.class, Base.class, DIST, DIST_PARAMS));
|
||||
assertFalse(TileEntityRenderBoundsRegistry.overridesMethod(Plain.class, Base.class, PASS, int.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void directOverrideDetected() {
|
||||
assertTrue(TileEntityRenderBoundsRegistry.overridesMethod(Direct.class, Base.class, DIST, DIST_PARAMS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void inheritedOverrideDetected() {
|
||||
assertTrue(TileEntityRenderBoundsRegistry.overridesMethod(Inherited.class, Base.class, DIST, DIST_PARAMS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void classMethodBeatsInterfaceDefault() {
|
||||
assertFalse(TileEntityRenderBoundsRegistry.overridesMethod(WithInterfaceDefault.class, Base.class, DIST, DIST_PARAMS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unresolvableNameTreatedAsOverriding() {
|
||||
assertTrue(TileEntityRenderBoundsRegistry.overridesMethod(Plain.class, Base.class, new String[] { "func_145835_a" }, DIST_PARAMS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void wrongParametersTreatedAsOverriding() {
|
||||
assertTrue(TileEntityRenderBoundsRegistry.overridesMethod(Plain.class, Base.class, DIST, double.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void firstMatchingCandidateNameWins() {
|
||||
assertTrue(TileEntityRenderBoundsRegistry.overridesMethod(Direct.class, Base.class, new String[] { "func_145835_a", "dist" }, DIST_PARAMS));
|
||||
assertFalse(TileEntityRenderBoundsRegistry.overridesMethod(Plain.class, Base.class, new String[] { "func_145835_a", "dist" }, DIST_PARAMS));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.gtnewhorizons.angelica.rendering.celeritas;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static com.gtnewhorizons.angelica.rendering.celeritas.SectionAgeMath.STEP_NANOS;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class SectionAgeMathTest {
|
||||
|
||||
@Test
|
||||
void quantizeRoundsDownToStep() {
|
||||
assertEquals(0L, SectionAgeMath.quantize(0L));
|
||||
assertEquals(0L, SectionAgeMath.quantize(STEP_NANOS - 1));
|
||||
assertEquals(STEP_NANOS, SectionAgeMath.quantize(STEP_NANOS));
|
||||
assertEquals(7 * STEP_NANOS, SectionAgeMath.quantize(7 * STEP_NANOS + 42));
|
||||
|
||||
assertEquals(-STEP_NANOS, SectionAgeMath.quantize(-1L));
|
||||
assertEquals(-2 * STEP_NANOS, SectionAgeMath.quantize(-STEP_NANOS - 1));
|
||||
assertEquals(-STEP_NANOS, SectionAgeMath.quantize(-STEP_NANOS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void freshStateNeverSkips() {
|
||||
final long[] state = SectionAgeMath.newState();
|
||||
assertFalse(SectionAgeMath.canSkip(state, 0L, 0L));
|
||||
assertFalse(SectionAgeMath.canSkip(state, 123L, SectionAgeMath.quantize(456L)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsaturatedSkipsOnlyWithinTheSameStep() {
|
||||
final long[] state = SectionAgeMath.newState();
|
||||
final long newest = 1_000L;
|
||||
final long tsQ = SectionAgeMath.quantize(50 * STEP_NANOS + 3);
|
||||
SectionAgeMath.record(state, newest, tsQ, false);
|
||||
|
||||
assertTrue(SectionAgeMath.canSkip(state, newest, tsQ));
|
||||
assertFalse(SectionAgeMath.canSkip(state, newest, tsQ + STEP_NANOS), "next step must rebuild");
|
||||
assertFalse(SectionAgeMath.canSkip(state, newest + 1, tsQ), "newer section load must rebuild");
|
||||
}
|
||||
|
||||
@Test
|
||||
void saturatedSkipsAcrossStepsUntilNewestChanges() {
|
||||
final long[] state = SectionAgeMath.newState();
|
||||
final long newest = 1_000L;
|
||||
final long tsQ = SectionAgeMath.quantize(400 * STEP_NANOS);
|
||||
SectionAgeMath.record(state, newest, tsQ, true);
|
||||
|
||||
assertTrue(SectionAgeMath.canSkip(state, newest, tsQ));
|
||||
assertTrue(SectionAgeMath.canSkip(state, newest, tsQ + 10_000 * STEP_NANOS), "saturation is time-independent");
|
||||
assertFalse(SectionAgeMath.canSkip(state, newest + 1, tsQ), "a new section load ends saturation");
|
||||
|
||||
SectionAgeMath.record(state, newest + 1, tsQ + STEP_NANOS, false);
|
||||
assertTrue(SectionAgeMath.canSkip(state, newest + 1, tsQ + STEP_NANOS));
|
||||
assertFalse(SectionAgeMath.canSkip(state, newest + 1, tsQ + 2 * STEP_NANOS));
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package com.gtnewhorizons.angelica.rendering.celeritas;
|
||||
|
||||
import it.unimi.dsi.fastutil.floats.FloatArrayList;
|
||||
import net.minecraft.util.AxisAlignedBB;
|
||||
import org.embeddedt.embeddium.impl.render.viewport.CameraTransform;
|
||||
import org.joml.FrustumIntersection;
|
||||
import org.joml.Matrix4f;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class SectionFrustumGateTest {
|
||||
|
||||
private static FrustumIntersection knownFrustum() {
|
||||
return new FrustumIntersection(new Matrix4f().perspective((float) Math.toRadians(90), 1.0f, 0.1f, 100.0f));
|
||||
}
|
||||
|
||||
@Test
|
||||
void triStateVerdictsAgainstKnownPerspective() {
|
||||
final FrustumIntersection frustum = knownFrustum();
|
||||
|
||||
assertEquals(FrustumIntersection.INSIDE, frustum.intersectAab(-1, -1, -50, 1, 1, -40));
|
||||
assertEquals(FrustumIntersection.INTERSECT, frustum.intersectAab(-1, -1, -5, 1, 1, 5));
|
||||
assertTrue(frustum.intersectAab(-1, -1, 10, 1, 1, 20) >= 0);
|
||||
assertTrue(frustum.intersectAab(-100, -1, -20, -50, 1, -10) >= 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sectionVerdictIsSoundForContainedBoxes() {
|
||||
final Random rng = new Random(0x5EC7104);
|
||||
|
||||
for (int iter = 0; iter < 2000; iter++) {
|
||||
final Matrix4f m = new Matrix4f()
|
||||
.perspective((float) Math.toRadians(30 + rng.nextInt(90)), 0.5f + rng.nextFloat() * 2.0f, 0.05f, 64 + rng.nextFloat() * 448)
|
||||
.rotateX((rng.nextFloat() - 0.5f) * (float) Math.PI)
|
||||
.rotateY(rng.nextFloat() * 2.0f * (float) Math.PI);
|
||||
final FrustumIntersection frustum = new FrustumIntersection(m);
|
||||
|
||||
for (int s = 0; s < 50; s++) {
|
||||
final float ox = (rng.nextFloat() - 0.5f) * 512;
|
||||
final float oy = (rng.nextFloat() - 0.5f) * 512;
|
||||
final float oz = (rng.nextFloat() - 0.5f) * 512;
|
||||
|
||||
final int verdict = frustum.intersectAab(ox, oy, oz, ox + 16, oy + 16, oz + 16);
|
||||
|
||||
final float lx = rng.nextFloat() * 15, ly = rng.nextFloat() * 15, lz = rng.nextFloat() * 15;
|
||||
final float hx = lx + rng.nextFloat() * (16 - lx);
|
||||
final float hy = ly + rng.nextFloat() * (16 - ly);
|
||||
final float hz = lz + rng.nextFloat() * (16 - lz);
|
||||
|
||||
final boolean boxVisible = frustum.testAab(ox + lx, oy + ly, oz + lz, ox + hx, oy + hy, oz + hz);
|
||||
|
||||
if (verdict == FrustumIntersection.INSIDE) {
|
||||
assertTrue(boxVisible, "box in INSIDE section must be visible");
|
||||
} else if (verdict >= 0) {
|
||||
assertFalse(boxVisible, "box in plane-culled section must be culled");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void packedLocalBoundsMatchLegacyDoubleFormulation() {
|
||||
final Random rng = new Random(0xA3B1D);
|
||||
|
||||
for (int iter = 0; iter < 5000; iter++) {
|
||||
final int ox = (rng.nextInt(4_000_000) - 2_000_000) & ~15;
|
||||
final int oy = rng.nextInt(16) << 4;
|
||||
final int oz = (rng.nextInt(4_000_000) - 2_000_000) & ~15;
|
||||
|
||||
final CameraTransform t = new CameraTransform(ox + (rng.nextDouble() - 0.5) * 1024, oy + (rng.nextDouble() - 0.5) * 256, oz + (rng.nextDouble() - 0.5) * 1024);
|
||||
|
||||
final double minX = ox + rng.nextDouble() * 15;
|
||||
final double minY = oy + rng.nextDouble() * 15;
|
||||
final double minZ = oz + rng.nextDouble() * 15;
|
||||
final AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox(minX, minY, minZ, minX + rng.nextDouble() * (ox + 16 - minX), minY + rng.nextDouble() * (oy + 16 - minY), minZ + rng.nextDouble() * (oz + 16 - minZ));
|
||||
|
||||
final FloatArrayList packed = new FloatArrayList();
|
||||
AngelicaBuiltRenderSectionData.packSectionLocalBounds(packed, aabb, ox, oy, oz);
|
||||
|
||||
final float fx = (ox - t.intX) - t.fracX;
|
||||
final float fy = (oy - t.intY) - t.fracY;
|
||||
final float fz = (oz - t.intZ) - t.fracZ;
|
||||
|
||||
final double[] world = { aabb.minX, aabb.minY, aabb.minZ, aabb.maxX, aabb.maxY, aabb.maxZ };
|
||||
final float[] origin = { fx, fy, fz, fx, fy, fz };
|
||||
final int[] camInt = { t.intX, t.intY, t.intZ, t.intX, t.intY, t.intZ };
|
||||
final float[] camFrac = { t.fracX, t.fracY, t.fracZ, t.fracX, t.fracY, t.fracZ };
|
||||
|
||||
for (int i = 0; i < 6; i++) {
|
||||
final float legacyCoord = (float) (world[i] - camInt[i]) - camFrac[i];
|
||||
final float packedCoord = origin[i] + packed.getFloat(i);
|
||||
assertEquals(legacyCoord, packedCoord, 1e-3f, "coord " + i + " diverged at iter " + iter);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.gtnewhorizons.angelica.rendering.celeritas;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class TeDistanceMathTest {
|
||||
|
||||
private static double distSq(double x1, double y1, double z1, double x2, double y2, double z2) {
|
||||
final double dx = x1 - x2, dy = y1 - y2, dz = z1 - z2;
|
||||
return dx * dx + dy * dy + dz * dz;
|
||||
}
|
||||
|
||||
@Test
|
||||
void cameraInsideSectionIsZero() {
|
||||
assertEquals(0.0, TeDistanceMath.distSqToSection(8, 8, 8, 0, 0, 0));
|
||||
assertEquals(0.0, TeDistanceMath.distSqToSection(16, 0, 16, 0, 0, 0));
|
||||
assertEquals(0.0, TeDistanceMath.distSqToSection(-32, 5, 100.5, -32, 0, 96));
|
||||
}
|
||||
|
||||
@Test
|
||||
void matchesClampFormulation() {
|
||||
final Random rng = new Random(0xD157);
|
||||
for (int iter = 0; iter < 10_000; iter++) {
|
||||
final int ox = (rng.nextInt(4_000_000) - 2_000_000) & ~15;
|
||||
final int oy = rng.nextInt(16) << 4;
|
||||
final int oz = (rng.nextInt(4_000_000) - 2_000_000) & ~15;
|
||||
final double camX = ox + (rng.nextDouble() - 0.5) * 512;
|
||||
final double camY = oy + (rng.nextDouble() - 0.5) * 512;
|
||||
final double camZ = oz + (rng.nextDouble() - 0.5) * 512;
|
||||
|
||||
final double cx = Math.max(ox, Math.min(camX, ox + 16));
|
||||
final double cy = Math.max(oy, Math.min(camY, oy + 16));
|
||||
final double cz = Math.max(oz, Math.min(camZ, oz + 16));
|
||||
final double expected = distSq(camX, camY, camZ, cx, cy, cz);
|
||||
|
||||
assertEquals(expected, TeDistanceMath.distSqToSection(camX, camY, camZ, ox, oy, oz), 1e-9, "clamp formulation diverged at iter " + iter);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void lowerBoundsEveryPointInSection() {
|
||||
final Random rng = new Random(0xB0C5);
|
||||
for (int iter = 0; iter < 2_000; iter++) {
|
||||
final int ox = (rng.nextInt(200_000) - 100_000) & ~15;
|
||||
final int oy = rng.nextInt(16) << 4;
|
||||
final int oz = (rng.nextInt(200_000) - 100_000) & ~15;
|
||||
final double camX = ox + (rng.nextDouble() - 0.5) * 256;
|
||||
final double camY = oy + (rng.nextDouble() - 0.5) * 256;
|
||||
final double camZ = oz + (rng.nextDouble() - 0.5) * 256;
|
||||
|
||||
final double sectionDistSq = TeDistanceMath.distSqToSection(camX, camY, camZ, ox, oy, oz);
|
||||
|
||||
for (int s = 0; s < 30; s++) {
|
||||
final double px = ox + rng.nextDouble() * 16;
|
||||
final double py = oy + rng.nextDouble() * 16;
|
||||
final double pz = oz + rng.nextDouble() * 16;
|
||||
final double pointDistSq = distSq(camX, camY, camZ, px, py, pz);
|
||||
assertTrue(pointDistSq >= sectionDistSq - 1e-9, "point dist " + pointDistSq + " < section dist " + sectionDistSq + " at iter " + iter);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.gtnewhorizons.angelica.rendering.culling;
|
||||
|
||||
import com.gtnewhorizons.angelica.glsm.GLCoreTest;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import com.gtnewhorizons.angelica.glsm.RenderSystem;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
import org.lwjgl.opengl.GL20;
|
||||
import org.lwjgl.opengl.GL43;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
@GLCoreTest
|
||||
class CullingShaderCompileTest {
|
||||
|
||||
private static String source(String name) throws IOException {
|
||||
try (InputStream in = CullingShaderCompileTest.class.getResourceAsStream("/assets/angelica/shaders/culling/" + name)) {
|
||||
assertNotNull(in, "missing shader resource: " + name);
|
||||
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
|
||||
private static void assertCompiles(String name) throws IOException {
|
||||
assumeTrue(RenderSystem.supportsCompute(), "compute shaders unsupported");
|
||||
final int shader = GLStateManager.glCreateShader(GL43.GL_COMPUTE_SHADER);
|
||||
try {
|
||||
GLStateManager.glShaderSource(shader, source(name));
|
||||
GLStateManager.glCompileShader(shader);
|
||||
final int status = GLStateManager.glGetShaderi(shader, GL20.GL_COMPILE_STATUS);
|
||||
assertEquals(GL11.GL_TRUE, status, () -> name + " failed to compile:\n" + GLStateManager.glGetShaderInfoLog(shader, 4096));
|
||||
} finally {
|
||||
GLStateManager.glDeleteShader(shader);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void chunkCullCompiles() throws IOException {
|
||||
assertCompiles("chunk_cull.csh");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package com.gtnewhorizons.angelica.rendering.culling;
|
||||
|
||||
import org.joml.Matrix4f;
|
||||
import org.joml.Vector3f;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class FrustumExtractorTest {
|
||||
private static final float EPS = 1e-4f;
|
||||
|
||||
@Test
|
||||
void uboSizeIs160() {
|
||||
assertEquals(160, FrustumExtractor.UBO_SIZE_BYTES);
|
||||
assertEquals(0, FrustumExtractor.UBO_SIZE_BYTES % 16, "std140 requires a 16-byte multiple");
|
||||
}
|
||||
|
||||
@Test
|
||||
void patchBatchEntryBase_writesAtOffset128_andWriteStd140Resets() {
|
||||
final ByteBuffer out = FrustumExtractor.allocateUboByteBuffer();
|
||||
FrustumExtractor.patchBatchEntryBase(777, out);
|
||||
assertEquals(777, out.getInt(128));
|
||||
FrustumExtractor.writeStd140(new Matrix4f(), 0, 0, out);
|
||||
assertEquals(0, out.getInt(128), "writeStd140 must reset entryBase");
|
||||
}
|
||||
|
||||
@Test
|
||||
void identityMatrix_planesAreUnitNormalsAtUnitDistance() {
|
||||
final Matrix4f identity = new Matrix4f();
|
||||
final ByteBuffer out = FrustumExtractor.allocateUboByteBuffer();
|
||||
FrustumExtractor.writeStd140(identity, 0, 0, out);
|
||||
|
||||
assertPlane(out, 0, 1f, 0f, 0f, 1f);
|
||||
assertPlane(out, 16, -1f, 0f, 0f, 1f);
|
||||
assertPlane(out, 32, 0f, 1f, 0f, 1f);
|
||||
assertPlane(out, 48, 0f, -1f, 0f, 1f);
|
||||
assertPlane(out, 64, 0f, 0f, 1f, 1f);
|
||||
assertPlane(out, 80, 0f, 0f, -1f, 1f);
|
||||
}
|
||||
|
||||
@Test
|
||||
void identityMatrix_left_correct() {
|
||||
final Matrix4f identity = new Matrix4f();
|
||||
final ByteBuffer out = FrustumExtractor.allocateUboByteBuffer();
|
||||
FrustumExtractor.writeStd140(identity, 0, 0, out);
|
||||
assertPlane(out, 0, 1f, 0f, 0f, 1f);
|
||||
}
|
||||
|
||||
@Test
|
||||
void perspectiveAxisAlignedPoint_insideFrustum() {
|
||||
final Matrix4f proj = new Matrix4f().perspective((float) Math.toRadians(70.0), 16f / 9f, 0.1f, 1000.0f);
|
||||
final ByteBuffer out = FrustumExtractor.allocateUboByteBuffer();
|
||||
FrustumExtractor.writeStd140(proj, 0, 0, out);
|
||||
|
||||
assertTrue(insideAllPlanes(out, new Vector3f(0f, 0f, -10f)), "point ahead should be inside");
|
||||
assertTrue(!insideAllPlanes(out, new Vector3f(0f, 0f, 10f)), "point behind should be outside");
|
||||
}
|
||||
|
||||
@Test
|
||||
void visibleCountStored() {
|
||||
final Matrix4f mvp = new Matrix4f();
|
||||
final ByteBuffer out = FrustumExtractor.allocateUboByteBuffer();
|
||||
FrustumExtractor.writeStd140(mvp, 4242, 0, out);
|
||||
assertEquals(4242, out.getInt(96), "visibleCount at offset 96");
|
||||
assertEquals(0, out.getInt(100));
|
||||
assertEquals(0, out.getInt(104));
|
||||
assertEquals(0, out.getInt(108));
|
||||
}
|
||||
|
||||
private static void assertPlane(ByteBuffer out, int offset, float a, float b, float c, float d) {
|
||||
final float len = (float) Math.sqrt(a * a + b * b + c * c);
|
||||
final float inv = len == 0.0f ? 1.0f : 1.0f / len;
|
||||
assertEquals(a * inv, out.getFloat(offset + 0), EPS, "a @" + offset);
|
||||
assertEquals(b * inv, out.getFloat(offset + 4), EPS, "b @" + offset);
|
||||
assertEquals(c * inv, out.getFloat(offset + 8), EPS, "c @" + offset);
|
||||
assertEquals(d * inv, out.getFloat(offset + 12), EPS, "d @" + offset);
|
||||
}
|
||||
|
||||
private static boolean insideAllPlanes(ByteBuffer out, Vector3f p) {
|
||||
for (int i = 0; i < 6; i++) {
|
||||
final float a = out.getFloat(i * 16 + 0);
|
||||
final float b = out.getFloat(i * 16 + 4);
|
||||
final float c = out.getFloat(i * 16 + 8);
|
||||
final float d = out.getFloat(i * 16 + 12);
|
||||
if (a * p.x + b * p.y + c * p.z + d < 0.0f) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+645
@@ -0,0 +1,645 @@
|
||||
package com.gtnewhorizons.angelica.rendering.culling;
|
||||
|
||||
import org.embeddedt.embeddium.impl.render.chunk.multidraw.DrawCommandSink;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataUnsafe;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.QuadPrimitiveType;
|
||||
import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities;
|
||||
import com.gtnewhorizons.angelica.config.GpuCullingMode;
|
||||
import com.gtnewhorizons.angelica.glsm.GLCoreTest;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import com.gtnewhorizons.angelica.glsm.RenderSystem;
|
||||
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexAttribute;
|
||||
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexAttributeBinding;
|
||||
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexAttributeFormat;
|
||||
import org.embeddedt.embeddium.impl.gl.array.GlVertexArray;
|
||||
import org.embeddedt.embeddium.impl.gl.buffer.GlBufferUsage;
|
||||
import org.embeddedt.embeddium.impl.gl.buffer.GlMutableBuffer;
|
||||
import org.embeddedt.embeddium.impl.gl.device.CommandList;
|
||||
import org.embeddedt.embeddium.impl.gl.device.GLRenderDevice;
|
||||
import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
|
||||
import org.embeddedt.embeddium.impl.gl.tessellation.GlPrimitiveType;
|
||||
import org.embeddedt.embeddium.impl.gl.tessellation.GlVertexArrayTessellation;
|
||||
import org.embeddedt.embeddium.impl.gl.tessellation.TessellationBinding;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.multidraw.BatchAssembler;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.multidraw.DirectMultiDrawEmitter;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.multidraw.IndirectMultiDrawEmitter;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.multidraw.MultiDrawEmitter;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
|
||||
import org.joml.Matrix4f;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.lwjgl.BufferUtils;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
import org.lwjgl.opengl.GL20;
|
||||
import org.lwjgl.opengl.GL30;
|
||||
import org.lwjgl.opengl.GL43;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.FloatBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
@GLCoreTest
|
||||
class IndirectCullDrawParityTest {
|
||||
|
||||
private static final int FBO_SIZE = 128;
|
||||
private static final int GRID = 16;
|
||||
private static final int FACINGS = 7;
|
||||
private static final int CMD_INTS = 5;
|
||||
|
||||
private static final int SOLID_PASS = 0;
|
||||
private static final int CUTOUT_PASS = 1;
|
||||
private static final int SORTED_PASS = 2;
|
||||
|
||||
private static final int[] SOLID_MASKS = { 0x7F, 0x55, 0x2A, 0x63, 0x1C };
|
||||
private static final int[] CUTOUT_MASKS = { 0x33, 0x4D, 0x7F };
|
||||
private static final int REGION1_SOLID_SECTIONS = 3;
|
||||
|
||||
private static CommandList commandList;
|
||||
private static int program;
|
||||
|
||||
private static final class Section {
|
||||
int passIndex;
|
||||
int sliceMask;
|
||||
int slot = -1;
|
||||
final int[] quadCount = new int[FACINGS];
|
||||
final int[] vertexOffset = new int[FACINGS];
|
||||
final int[] elementCount = new int[FACINGS];
|
||||
final int[] indexOffset = new int[FACINGS];
|
||||
ByteBuffer srd;
|
||||
|
||||
long srdAddress() { return MemoryUtilities.memAddress(srd); }
|
||||
|
||||
void writeSrd() {
|
||||
srd.putInt(0, sliceMask);
|
||||
srd.putInt(4, 0);
|
||||
for (int f = 0; f < FACINGS; f++) {
|
||||
final int off = 8 + f * 12;
|
||||
srd.putInt(off + 0, vertexOffset[f]);
|
||||
srd.putInt(off + 4, elementCount[f]);
|
||||
srd.putInt(off + 8, indexOffset[f]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Scene {
|
||||
final List<Section> solid = new ArrayList<>();
|
||||
final List<Section> cutout = new ArrayList<>();
|
||||
final List<Section> sorted = new ArrayList<>();
|
||||
FloatBuffer vertices;
|
||||
ByteBuffer sharedIndices;
|
||||
ByteBuffer sortedIndices;
|
||||
int totalQuads;
|
||||
|
||||
List<Section> all() {
|
||||
final List<Section> all = new ArrayList<>(solid);
|
||||
all.addAll(cutout);
|
||||
all.addAll(sorted);
|
||||
return all;
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeAll
|
||||
static void setUpDevice() {
|
||||
GLRenderDevice.VANILLA_STATE_RESETTER = () -> {};
|
||||
RenderDevice.enterManagedCode();
|
||||
commandList = RenderDevice.INSTANCE.createCommandList();
|
||||
program = buildProgram();
|
||||
GpuCulling.setMode(GpuCullingMode.COMPUTE);
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void tearDownDevice() {
|
||||
GpuCulling.setMode(GpuCullingMode.CPU_ONLY);
|
||||
if (program != 0) GLStateManager.glDeleteProgram(program);
|
||||
RenderDevice.exitManagedCode();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void resetGlState() {
|
||||
GLStateManager.glUseProgram(0);
|
||||
GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0);
|
||||
GLStateManager.glDisable(GL11.GL_DEPTH_TEST);
|
||||
GLStateManager.glViewport(0, 0, 800, 600);
|
||||
}
|
||||
|
||||
static final String FLAT_VS = "#version 330 core\n"
|
||||
+ "layout(location = 0) in vec3 a_Pos;\n"
|
||||
+ "void main() { gl_Position = vec4(a_Pos, 1.0); }\n";
|
||||
static final String FLAT_FS = "#version 330 core\n"
|
||||
+ "out vec4 fragColor;\n"
|
||||
+ "void main() { fragColor = vec4(1.0); }\n";
|
||||
|
||||
static int compileShader(int type, String src) {
|
||||
final int shader = GLStateManager.glCreateShader(type);
|
||||
GLStateManager.glShaderSource(shader, src);
|
||||
GLStateManager.glCompileShader(shader);
|
||||
assertEquals(GL11.GL_TRUE, GLStateManager.glGetShaderi(shader, GL20.GL_COMPILE_STATUS), () -> "shader failed to compile:\n" + GLStateManager.glGetShaderInfoLog(shader, 4096));
|
||||
return shader;
|
||||
}
|
||||
|
||||
private static int buildProgram() {
|
||||
final int vsh = compileShader(GL20.GL_VERTEX_SHADER, FLAT_VS);
|
||||
final int fsh = compileShader(GL20.GL_FRAGMENT_SHADER, FLAT_FS);
|
||||
final int prog = GLStateManager.glCreateProgram();
|
||||
GLStateManager.glAttachShader(prog, vsh);
|
||||
GLStateManager.glAttachShader(prog, fsh);
|
||||
GLStateManager.glLinkProgram(prog);
|
||||
assertEquals(GL11.GL_TRUE, GLStateManager.glGetProgrami(prog, GL20.GL_LINK_STATUS), () -> "parity program failed to link:\n" + GLStateManager.glGetProgramInfoLog(prog, 4096));
|
||||
GLStateManager.glDeleteShader(vsh);
|
||||
GLStateManager.glDeleteShader(fsh);
|
||||
return prog;
|
||||
}
|
||||
|
||||
private static Scene buildScene() {
|
||||
final Scene scene = new Scene();
|
||||
for (int s = 0; s < SOLID_MASKS.length; s++) {
|
||||
scene.solid.add(newSection(SOLID_PASS, SOLID_MASKS[s], s));
|
||||
}
|
||||
for (int s = 0; s < CUTOUT_MASKS.length; s++) {
|
||||
scene.cutout.add(newSection(CUTOUT_PASS, CUTOUT_MASKS[s], SOLID_MASKS.length + s));
|
||||
}
|
||||
for (int s = 0; s < SOLID_MASKS.length; s++) {
|
||||
scene.sorted.add(newSection(SORTED_PASS, SOLID_MASKS[s], s + 1));
|
||||
}
|
||||
|
||||
int quad = 0;
|
||||
int vertex = 0;
|
||||
int maxQuadsPerDraw = 0;
|
||||
int sortedIndexInts = 0;
|
||||
final List<float[]> quadRects = new ArrayList<>();
|
||||
for (Section section : allOf(scene)) {
|
||||
final int sectionFirstVertex = vertex;
|
||||
for (int f = 0; f < FACINGS; f++) {
|
||||
section.vertexOffset[f] = vertex;
|
||||
section.elementCount[f] = 6 * section.quadCount[f];
|
||||
section.indexOffset[f] = section.passIndex == SORTED_PASS ? sortedIndexInts * 4 : 0;
|
||||
if (section.passIndex == SORTED_PASS) sortedIndexInts += section.elementCount[f];
|
||||
for (int q = 0; q < section.quadCount[f]; q++) {
|
||||
quadRects.add(quadRect(quad));
|
||||
quad++;
|
||||
vertex += 4;
|
||||
}
|
||||
}
|
||||
maxQuadsPerDraw = Math.max(maxQuadsPerDraw, (vertex - sectionFirstVertex) / 4);
|
||||
section.writeSrd();
|
||||
}
|
||||
scene.totalQuads = quad;
|
||||
assertTrue(quad <= GRID * GRID, "scene overflows the NDC cell grid");
|
||||
|
||||
scene.vertices = BufferUtils.createFloatBuffer(vertex * 3);
|
||||
for (float[] rect : quadRects) {
|
||||
final float x0 = rect[0], y0 = rect[1], x1 = rect[2], y1 = rect[3], z = rect[4];
|
||||
scene.vertices.put(x0).put(y0).put(z);
|
||||
scene.vertices.put(x1).put(y0).put(z);
|
||||
scene.vertices.put(x1).put(y1).put(z);
|
||||
scene.vertices.put(x0).put(y1).put(z);
|
||||
}
|
||||
scene.vertices.flip();
|
||||
|
||||
scene.sharedIndices = BufferUtils.createByteBuffer(6 * maxQuadsPerDraw * 4).order(ByteOrder.nativeOrder());
|
||||
for (int q = 0; q < maxQuadsPerDraw; q++) {
|
||||
putQuadIndices(scene.sharedIndices, 4 * q);
|
||||
}
|
||||
scene.sharedIndices.flip();
|
||||
|
||||
scene.sortedIndices = BufferUtils.createByteBuffer(sortedIndexInts * 4).order(ByteOrder.nativeOrder());
|
||||
for (Section section : scene.sorted) {
|
||||
for (int f = 0; f < FACINGS; f++) {
|
||||
if ((section.sliceMask & (1 << f)) == 0) continue;
|
||||
for (int q = 0; q < section.quadCount[f]; q++) {
|
||||
putQuadIndices(scene.sortedIndices, 4 * q);
|
||||
}
|
||||
}
|
||||
}
|
||||
scene.sortedIndices.flip();
|
||||
return scene;
|
||||
}
|
||||
|
||||
private static List<Section> allOf(Scene scene) {
|
||||
return scene.all();
|
||||
}
|
||||
|
||||
private static Section newSection(int passIndex, int sliceMask, int seed) {
|
||||
final Section section = new Section();
|
||||
section.passIndex = passIndex;
|
||||
section.sliceMask = sliceMask;
|
||||
for (int f = 0; f < FACINGS; f++) {
|
||||
if ((sliceMask & (1 << f)) != 0) {
|
||||
section.quadCount[f] = 1 + ((seed + f) % 3);
|
||||
}
|
||||
}
|
||||
section.srd = MemoryUtilities.memAlloc(92).order(ByteOrder.nativeOrder());
|
||||
return section;
|
||||
}
|
||||
|
||||
private static float[] quadRect(int quadIndex) {
|
||||
final int cx = quadIndex % GRID;
|
||||
final int cy = quadIndex / GRID;
|
||||
final float cell = 2.0f / GRID;
|
||||
final float x0 = -1.0f + cx * cell + cell * 0.1f;
|
||||
final float y0 = -1.0f + cy * cell + cell * 0.1f;
|
||||
final float z = -0.9f + 1.8f * quadIndex / (GRID * GRID);
|
||||
return new float[] { x0, y0, x0 + cell * 0.8f, y0 + cell * 0.8f, z };
|
||||
}
|
||||
|
||||
private static void putQuadIndices(ByteBuffer out, int base) {
|
||||
out.putInt(base).putInt(base + 1).putInt(base + 2);
|
||||
out.putInt(base + 2).putInt(base + 3).putInt(base);
|
||||
}
|
||||
|
||||
private static GlMutableBuffer upload(ByteBuffer data) {
|
||||
final GlMutableBuffer buffer = commandList.createMutableBuffer();
|
||||
commandList.uploadData(buffer, data, GlBufferUsage.STATIC_DRAW);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
private static GlVertexArrayTessellation tessellation(GlMutableBuffer vertexBuffer, GlMutableBuffer indexBuffer) {
|
||||
final GlVertexAttribute position = new GlVertexAttribute(GlVertexAttributeFormat.FLOAT, "a_Pos", 3, false, 0, 12, false);
|
||||
final TessellationBinding[] bindings = {
|
||||
TessellationBinding.forVertexBuffer(vertexBuffer, new GlVertexAttributeBinding[] { new GlVertexAttributeBinding(0, position) }),
|
||||
TessellationBinding.forElementBuffer(indexBuffer),
|
||||
};
|
||||
final GlVertexArrayTessellation tess = new GlVertexArrayTessellation(new GlVertexArray(), bindings);
|
||||
tess.init(commandList);
|
||||
return tess;
|
||||
}
|
||||
|
||||
private static int newFbo(int[] texturesOut) {
|
||||
final int depthTex = GLStateManager.glGenTextures();
|
||||
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, depthTex);
|
||||
GLStateManager.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL30.GL_DEPTH_COMPONENT32F, FBO_SIZE, FBO_SIZE, 0, GL11.GL_DEPTH_COMPONENT, GL11.GL_FLOAT, (ByteBuffer) null);
|
||||
GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
|
||||
GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
|
||||
final int colorTex = GLStateManager.glGenTextures();
|
||||
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, colorTex);
|
||||
GLStateManager.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, FBO_SIZE, FBO_SIZE, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, (ByteBuffer) null);
|
||||
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0);
|
||||
|
||||
final int fbo = GLStateManager.glGenFramebuffers();
|
||||
GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, fbo);
|
||||
GLStateManager.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_DEPTH_ATTACHMENT, GL11.GL_TEXTURE_2D, depthTex, 0);
|
||||
GLStateManager.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL11.GL_TEXTURE_2D, colorTex, 0);
|
||||
assertEquals(GL30.GL_FRAMEBUFFER_COMPLETE, GLStateManager.glCheckFramebufferStatus(GL30.GL_FRAMEBUFFER), "parity FBO incomplete");
|
||||
texturesOut[0] = depthTex;
|
||||
texturesOut[1] = colorTex;
|
||||
return fbo;
|
||||
}
|
||||
|
||||
private static void beginDrawing(int fbo) {
|
||||
GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, fbo);
|
||||
GLStateManager.glViewport(0, 0, FBO_SIZE, FBO_SIZE);
|
||||
GLStateManager.glEnable(GL11.GL_DEPTH_TEST);
|
||||
GLStateManager.glDepthFunc(GL11.GL_LESS);
|
||||
GLStateManager.glDepthMask(true);
|
||||
GLStateManager.disableCull();
|
||||
GLStateManager.glClearDepth(1.0);
|
||||
GLStateManager.glClearColor(0f, 0f, 0f, 0f);
|
||||
GLStateManager.glClear(GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_COLOR_BUFFER_BIT);
|
||||
GLStateManager.glUseProgram(program);
|
||||
}
|
||||
|
||||
private static FloatBuffer readDepth(int fbo) {
|
||||
GLStateManager.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, fbo);
|
||||
final FloatBuffer depth = BufferUtils.createFloatBuffer(FBO_SIZE * FBO_SIZE);
|
||||
GLStateManager.glReadPixels(0, 0, FBO_SIZE, FBO_SIZE, GL11.GL_DEPTH_COMPONENT, GL11.GL_FLOAT, depth);
|
||||
return depth;
|
||||
}
|
||||
|
||||
private static int coveredPixels(FloatBuffer depth) {
|
||||
int covered = 0;
|
||||
for (int i = 0; i < depth.capacity(); i++) {
|
||||
if (depth.get(i) < 1.0f) covered++;
|
||||
}
|
||||
return covered;
|
||||
}
|
||||
|
||||
private static void assertDepthParity(int directFbo, int gpuFbo, String label) {
|
||||
final FloatBuffer direct = readDepth(directFbo);
|
||||
final FloatBuffer gpu = readDepth(gpuFbo);
|
||||
final int covered = coveredPixels(direct);
|
||||
assertTrue(covered > 100, label + ": direct path drew almost nothing (" + covered + " covered pixels); scene setup is broken");
|
||||
assertEquals(covered, coveredPixels(gpu), label + ": covered pixel count differs between direct and GPU-culled indirect");
|
||||
for (int i = 0; i < direct.capacity(); i++) {
|
||||
if (direct.get(i) != gpu.get(i)) {
|
||||
final int x = i % FBO_SIZE;
|
||||
final int y = i / FBO_SIZE;
|
||||
assertEquals(direct.get(i), gpu.get(i), label + ": depth mismatch at (" + x + "," + y + "); the GPU-culled indirect path rendered different geometry than the direct path");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static RenderRegion newRegionKey() {
|
||||
try {
|
||||
for (Constructor<?> ctor : RenderRegion.class.getDeclaredConstructors()) {
|
||||
if (ctor.getParameterCount() == 5) {
|
||||
ctor.setAccessible(true);
|
||||
return (RenderRegion) ctor.newInstance(0, 0, 0, 0, null);
|
||||
}
|
||||
}
|
||||
} catch (ReflectiveOperationException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
throw new IllegalStateException("RenderRegion constructor shape changed");
|
||||
}
|
||||
|
||||
private static int reflectInt(GpuIndirectMultiDrawEmitter emitter, String fieldName) {
|
||||
try {
|
||||
final Field field = GpuIndirectMultiDrawEmitter.class.getDeclaredField(fieldName);
|
||||
field.setAccessible(true);
|
||||
return field.getInt(emitter);
|
||||
} catch (ReflectiveOperationException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static ByteBuffer frustumUbo(int indexPointerMask) {
|
||||
final ByteBuffer ubo = FrustumExtractor.allocateUboByteBuffer();
|
||||
final Matrix4f identity = new Matrix4f();
|
||||
FrustumExtractor.writeStd140(identity, 0, indexPointerMask, ubo);
|
||||
FrustumExtractor.patchCameraWorld(0f, 0f, 0f, ubo);
|
||||
FrustumExtractor.patchBypassFrustum(true, ubo);
|
||||
FrustumExtractor.patchPrimitiveRatio(QuadPrimitiveType.TRIANGULATED.getVerticesPerPrimitive(), QuadPrimitiveType.TRIANGULATED.getIndexBufferElementsPerPrimitive(), ubo);
|
||||
return ubo;
|
||||
}
|
||||
|
||||
private static void metaUpdate(SectionMetaBuffer meta, Section section, int localSectionIndex) {
|
||||
section.slot = meta.update(section.passIndex, 0, 0, 0, localSectionIndex, section.srdAddress(), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
assertTrue(section.slot >= 0, "meta rejected section for pass " + section.passIndex + " local index " + localSectionIndex);
|
||||
}
|
||||
|
||||
private static void pushSectionCommands(DrawCommandSink sink, long srdAddress, int sliceMask, int indexPointerMask) {
|
||||
for (int facing = 0; facing < FACINGS; facing++) {
|
||||
if (((sliceMask >> facing) & 1) == 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
sink.push(SectionRenderDataUnsafe.Strategy.FULL.getVertexOffset(srdAddress, facing),
|
||||
SectionRenderDataUnsafe.Strategy.FULL.getElementCount(srdAddress, facing, QuadPrimitiveType.TRIANGULATED),
|
||||
SectionRenderDataUnsafe.Strategy.FULL.getIndexOffset(srdAddress, facing) & indexPointerMask);
|
||||
}
|
||||
}
|
||||
|
||||
private static void renderCpuEmitter(Scene scene, int fbo, GlVertexArrayTessellation tessNonSorted, GlVertexArrayTessellation tessSorted, MultiDrawEmitter emitter) {
|
||||
beginDrawing(fbo);
|
||||
|
||||
renderCpuPass(emitter, tessNonSorted, 0, List.of(
|
||||
scene.solid.subList(0, REGION1_SOLID_SECTIONS),
|
||||
scene.solid.subList(REGION1_SOLID_SECTIONS, scene.solid.size())));
|
||||
renderCpuPass(emitter, tessNonSorted, 0, List.of(scene.cutout));
|
||||
renderCpuPass(emitter, tessSorted, 0xFFFFFFFF, List.of(scene.sorted));
|
||||
}
|
||||
|
||||
private static void renderCpuPass(MultiDrawEmitter emitter, GlVertexArrayTessellation tessellation, int indexPointerMask, List<List<Section>> regions) {
|
||||
final DrawCommandSink sink = emitter.getCommandSink();
|
||||
|
||||
if (!emitter.batchesWholePass()) {
|
||||
for (List<Section> region : regions) {
|
||||
sink.clear();
|
||||
for (Section section : region) {
|
||||
pushSectionCommands(sink, section.srdAddress(), section.sliceMask, indexPointerMask);
|
||||
}
|
||||
emitter.executeBatch(commandList, tessellation, GlPrimitiveType.TRIANGLES);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
int sectionCount = 0;
|
||||
for (List<Section> region : regions) {
|
||||
sectionCount += region.size();
|
||||
}
|
||||
|
||||
emitter.beginPass(commandList, sectionCount);
|
||||
|
||||
final int[] commandCounts = new int[regions.size()];
|
||||
for (int r = 0; r < regions.size(); r++) {
|
||||
sink.clear();
|
||||
for (Section section : regions.get(r)) {
|
||||
pushSectionCommands(sink, section.srdAddress(), section.sliceMask, indexPointerMask);
|
||||
}
|
||||
commandCounts[r] = sink.size();
|
||||
}
|
||||
|
||||
emitter.finishAssembly(commandList);
|
||||
|
||||
int firstCommand = 0;
|
||||
for (int count : commandCounts) {
|
||||
emitter.selectDrawRange(firstCommand, count);
|
||||
firstCommand += count;
|
||||
emitter.executeBatch(commandList, tessellation, GlPrimitiveType.TRIANGLES);
|
||||
}
|
||||
|
||||
emitter.onPassFinished(commandList);
|
||||
}
|
||||
|
||||
private static final class GpuFramePasses {
|
||||
final List<int[]> expectedCombined = new ArrayList<>();
|
||||
final List<int[]> expectedSorted = new ArrayList<>();
|
||||
int combinedIndirectBuffer;
|
||||
int sortedIndirectBuffer;
|
||||
}
|
||||
|
||||
private static GpuFramePasses renderGpu(Scene scene, int fbo, GlVertexArrayTessellation tessNonSorted, GlVertexArrayTessellation tessSorted, GpuIndirectMultiDrawEmitter gpu, RenderRegion region1, RenderRegion region2, String frameLabel) {
|
||||
final GpuFramePasses result = new GpuFramePasses();
|
||||
beginDrawing(fbo);
|
||||
|
||||
gpu.beginCombinedPasses(0, 0);
|
||||
assertTrue(gpu.isComputeActiveThisPass(), "compute path unexpectedly inactive");
|
||||
gpu.setFrustumUboBytes(frustumUbo(0));
|
||||
gpu.syncSectionMetaIfDirty();
|
||||
|
||||
int outputBase = 0;
|
||||
outputBase = walkSections(scene.solid.subList(0, REGION1_SOLID_SECTIONS), gpu, region1, outputBase, result.expectedCombined, 0);
|
||||
outputBase = walkSections(scene.solid.subList(REGION1_SOLID_SECTIONS, scene.solid.size()), gpu, region2, outputBase, result.expectedCombined, 0);
|
||||
gpu.startSecondPass();
|
||||
walkSections(scene.cutout, gpu, region1, outputBase, result.expectedCombined, 0);
|
||||
gpu.finishCombinedBuild();
|
||||
|
||||
gpu.prepareRegion(region1);
|
||||
gpu.executeBatch(commandList, tessNonSorted, GlPrimitiveType.TRIANGLES);
|
||||
gpu.prepareRegion(region2);
|
||||
gpu.executeBatch(commandList, tessNonSorted, GlPrimitiveType.TRIANGLES);
|
||||
gpu.endPass();
|
||||
|
||||
assertTrue(gpu.selectPreparedSecondPass(), "prepared cutout pass was not selectable");
|
||||
gpu.prepareRegion(region1);
|
||||
gpu.executeBatch(commandList, tessNonSorted, GlPrimitiveType.TRIANGLES);
|
||||
gpu.endPass();
|
||||
result.combinedIndirectBuffer = reflectInt(gpu, "indirectSsboGlId");
|
||||
assertIndirectBufferMatches(result.combinedIndirectBuffer, result.expectedCombined, frameLabel + " combined solid+cutout pass");
|
||||
|
||||
gpu.beginCullPass(0xFFFFFFFF);
|
||||
gpu.setFrustumUboBytes(frustumUbo(0xFFFFFFFF));
|
||||
gpu.syncSectionMetaIfDirty();
|
||||
walkSections(scene.sorted, gpu, region1, 0, result.expectedSorted, 0xFFFFFFFF);
|
||||
gpu.prepareRegion(region1);
|
||||
gpu.executeBatch(commandList, tessSorted, GlPrimitiveType.TRIANGLES);
|
||||
gpu.endPass();
|
||||
result.sortedIndirectBuffer = reflectInt(gpu, "indirectSsboGlId");
|
||||
assertIndirectBufferMatches(result.sortedIndirectBuffer, result.expectedSorted, frameLabel + " sorted pass");
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static int walkSections(List<Section> sections, GpuIndirectMultiDrawEmitter gpu, RenderRegion region, int outputBase, List<int[]> expectedCommands, int indexPointerMask) {
|
||||
gpu.reserveSections(sections.size());
|
||||
final int drawStart = outputBase;
|
||||
int drawCount = 0;
|
||||
int entryStart = -1;
|
||||
int entryCount = 0;
|
||||
int maxElems = 0;
|
||||
for (int i = 0; i < sections.size(); i++) {
|
||||
final Section section = sections.get(i);
|
||||
final int entryIdx = gpu.appendSection(section.slot, section.sliceMask, outputBase);
|
||||
if (entryStart < 0) entryStart = entryIdx;
|
||||
entryCount++;
|
||||
|
||||
final boolean mergeRuns = indexPointerMask == 0;
|
||||
final long runs = mergeRuns ? BatchAssembler.packRuns(section.sliceMask & 0x7F) : 0L;
|
||||
final int runCount = mergeRuns ? BatchAssembler.runCount(runs) : Integer.bitCount(section.sliceMask & 0x7F);
|
||||
final long srd = section.srdAddress();
|
||||
final SectionRenderDataUnsafe.Strategy layout = SectionRenderDataUnsafe.Strategy.FULL;
|
||||
final int sectionBase = layout.getVertexOffset(srd, 0);
|
||||
final int indexBase = layout.getIndexOffset(srd, 0) / 4;
|
||||
int singleFacing = -1;
|
||||
for (int run = 0; run < runCount; run++) {
|
||||
if (!mergeRuns) {
|
||||
do { singleFacing++; } while ((section.sliceMask & (1 << singleFacing)) == 0);
|
||||
}
|
||||
final int firstFacing = mergeRuns ? BatchAssembler.runFirst(runs, run) : singleFacing;
|
||||
final int lastFacing = mergeRuns ? BatchAssembler.runLast(runs, run) : singleFacing;
|
||||
final int startVertex = layout.getVertexOffset(srd, firstFacing);
|
||||
final int endVertex = layout.getRunVertexEnd(srd, lastFacing, QuadPrimitiveType.TRIANGULATED);
|
||||
final int elements = SectionRenderDataUnsafe.elementsForVertices(endVertex - startVertex, QuadPrimitiveType.TRIANGULATED);
|
||||
final int firstIndex = indexBase
|
||||
+ SectionRenderDataUnsafe.elementsForVertices(startVertex - sectionBase, QuadPrimitiveType.TRIANGULATED);
|
||||
expectedCommands.add(new int[] { elements, 1, firstIndex & indexPointerMask, startVertex, 0 });
|
||||
outputBase++;
|
||||
drawCount++;
|
||||
maxElems = Math.max(maxElems, elements);
|
||||
}
|
||||
}
|
||||
if (drawCount > 0) {
|
||||
gpu.recordRegion(region, drawStart, drawCount, entryStart, entryCount, maxElems);
|
||||
}
|
||||
return outputBase;
|
||||
}
|
||||
|
||||
private static void assertIndirectBufferMatches(int bufferId, List<int[]> expected, String label) {
|
||||
assertNotEquals(0, bufferId, label + ": no indirect buffer was created");
|
||||
final ByteBuffer readback = BufferUtils.createByteBuffer(expected.size() * CMD_INTS * 4).order(ByteOrder.nativeOrder());
|
||||
GLStateManager.glBindBuffer(GL43.GL_SHADER_STORAGE_BUFFER, bufferId);
|
||||
GLStateManager.glGetBufferSubData(GL43.GL_SHADER_STORAGE_BUFFER, 0L, readback);
|
||||
GLStateManager.glBindBuffer(GL43.GL_SHADER_STORAGE_BUFFER, 0);
|
||||
final String[] fieldNames = { "count", "instanceCount", "firstIndex", "baseVertex", "baseInstance" };
|
||||
for (int c = 0; c < expected.size(); c++) {
|
||||
for (int i = 0; i < CMD_INTS; i++) {
|
||||
assertEquals(expected.get(c)[i], readback.getInt((c * CMD_INTS + i) * 4), label + ": command " + c + " field " + fieldNames[i] + " differs from the CPU-computed command stream");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void gpuCulledIndirectMatchesDirectAcrossFrames() {
|
||||
assumeTrue(RenderSystem.supportsCompute(), "compute shaders unsupported");
|
||||
final Scene scene = buildScene();
|
||||
final GpuDrivenChunkCuller culler = new GpuDrivenChunkCuller();
|
||||
assertTrue(culler.ensureReady(), "chunk_cull.csh failed to load on a real driver");
|
||||
final SectionMetaBuffer meta = new SectionMetaBuffer();
|
||||
final GpuIndirectMultiDrawEmitter gpu = new GpuIndirectMultiDrawEmitter(culler, meta);
|
||||
final RenderRegion region1 = newRegionKey();
|
||||
final RenderRegion region2 = newRegionKey();
|
||||
|
||||
final DirectMultiDrawEmitter direct = new DirectMultiDrawEmitter();
|
||||
final IndirectMultiDrawEmitter cpuIndirect = new IndirectMultiDrawEmitter();
|
||||
GlMutableBuffer vertexBuffer = null;
|
||||
GlMutableBuffer sharedIndexBuffer = null;
|
||||
GlMutableBuffer sortedIndexBuffer = null;
|
||||
GlVertexArrayTessellation tessNonSorted = null;
|
||||
GlVertexArrayTessellation tessSorted = null;
|
||||
final int[] directTex = new int[2];
|
||||
final int[] cpuTex = new int[2];
|
||||
final int[] gpuTex = new int[2];
|
||||
int directFbo = 0;
|
||||
int cpuFbo = 0;
|
||||
int gpuFbo = 0;
|
||||
try {
|
||||
final ByteBuffer vertexBytes = BufferUtils.createByteBuffer(scene.vertices.capacity() * 4).order(ByteOrder.nativeOrder());
|
||||
vertexBytes.asFloatBuffer().put(scene.vertices.duplicate());
|
||||
vertexBuffer = upload(vertexBytes);
|
||||
sharedIndexBuffer = upload(scene.sharedIndices.duplicate().order(ByteOrder.nativeOrder()));
|
||||
sortedIndexBuffer = upload(scene.sortedIndices.duplicate().order(ByteOrder.nativeOrder()));
|
||||
tessNonSorted = tessellation(vertexBuffer, sharedIndexBuffer);
|
||||
tessSorted = tessellation(vertexBuffer, sortedIndexBuffer);
|
||||
directFbo = newFbo(directTex);
|
||||
cpuFbo = newFbo(cpuTex);
|
||||
gpuFbo = newFbo(gpuTex);
|
||||
|
||||
int local = 0;
|
||||
for (Section section : scene.solid) metaUpdate(meta, section, local++);
|
||||
local = 0;
|
||||
for (Section section : scene.cutout) metaUpdate(meta, section, local++);
|
||||
local = 0;
|
||||
for (Section section : scene.sorted) metaUpdate(meta, section, local++);
|
||||
|
||||
for (int frame = 1; frame <= 2; frame++) {
|
||||
renderCpuEmitter(scene, directFbo, tessNonSorted, tessSorted, direct);
|
||||
renderCpuEmitter(scene, cpuFbo, tessNonSorted, tessSorted, cpuIndirect);
|
||||
renderGpu(scene, gpuFbo, tessNonSorted, tessSorted, gpu, region1, region2, "frame " + frame);
|
||||
assertDepthParity(directFbo, cpuFbo, "frame " + frame + " (celeritas CPU indirect emitter)");
|
||||
assertDepthParity(directFbo, gpuFbo, "frame " + frame + " (GPU-culled indirect emitter)");
|
||||
}
|
||||
|
||||
final Section mutated = scene.solid.get(0);
|
||||
int shrinkFacing = -1;
|
||||
for (int f = 0; f < FACINGS; f++) {
|
||||
if ((mutated.sliceMask & (1 << f)) != 0 && mutated.quadCount[f] > 1) { shrinkFacing = f; break; }
|
||||
}
|
||||
assertTrue(shrinkFacing >= 0, "scene has no shrinkable facing");
|
||||
mutated.quadCount[shrinkFacing]--;
|
||||
mutated.elementCount[shrinkFacing] -= 6;
|
||||
|
||||
for (int f = shrinkFacing + 1; f < FACINGS; f++) {
|
||||
mutated.vertexOffset[f] -= 4;
|
||||
if (mutated.passIndex == SORTED_PASS) mutated.indexOffset[f] -= 6 * 4;
|
||||
}
|
||||
mutated.writeSrd();
|
||||
metaUpdate(meta, mutated, 0);
|
||||
|
||||
renderCpuEmitter(scene, directFbo, tessNonSorted, tessSorted, direct);
|
||||
renderCpuEmitter(scene, cpuFbo, tessNonSorted, tessSorted, cpuIndirect);
|
||||
renderGpu(scene, gpuFbo, tessNonSorted, tessSorted, gpu, region1, region2, "frame 3 (after section mesh update)");
|
||||
assertDepthParity(directFbo, cpuFbo, "frame 3 (celeritas CPU indirect emitter)");
|
||||
assertDepthParity(directFbo, gpuFbo, "frame 3 (GPU-culled indirect emitter)");
|
||||
} finally {
|
||||
direct.delete();
|
||||
cpuIndirect.delete();
|
||||
gpu.delete();
|
||||
meta.shutdown();
|
||||
culler.shutdown();
|
||||
if (tessNonSorted != null) tessNonSorted.delete(commandList);
|
||||
if (tessSorted != null) tessSorted.delete(commandList);
|
||||
if (vertexBuffer != null) commandList.deleteBuffer(vertexBuffer);
|
||||
if (sharedIndexBuffer != null) commandList.deleteBuffer(sharedIndexBuffer);
|
||||
if (sortedIndexBuffer != null) commandList.deleteBuffer(sortedIndexBuffer);
|
||||
GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0);
|
||||
if (directFbo != 0) GLStateManager.glDeleteFramebuffers(directFbo);
|
||||
if (cpuFbo != 0) GLStateManager.glDeleteFramebuffers(cpuFbo);
|
||||
if (gpuFbo != 0) GLStateManager.glDeleteFramebuffers(gpuFbo);
|
||||
for (int tex : directTex) if (tex != 0) GLStateManager.glDeleteTextures(tex);
|
||||
for (int tex : cpuTex) if (tex != 0) GLStateManager.glDeleteTextures(tex);
|
||||
for (int tex : gpuTex) if (tex != 0) GLStateManager.glDeleteTextures(tex);
|
||||
for (Section section : scene.all()) MemoryUtilities.memFree(section.srd);
|
||||
}
|
||||
}
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
package com.gtnewhorizons.angelica.rendering.culling;
|
||||
|
||||
import com.gtnewhorizons.angelica.glsm.CompatUniformManager;
|
||||
import com.gtnewhorizons.angelica.glsm.GLCoreTest;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import com.gtnewhorizons.angelica.glsm.RenderSystem;
|
||||
import org.joml.Matrix4f;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.lwjgl.BufferUtils;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
import org.lwjgl.opengl.GL15;
|
||||
import org.lwjgl.opengl.GL20;
|
||||
import org.lwjgl.opengl.GL40;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.FloatBuffer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
@GLCoreTest
|
||||
class MultiDrawCompatStompTest {
|
||||
|
||||
private static final Matrix4f SENTINEL = new Matrix4f().scaling(2f, 3f, 4f).setTranslation(5f, 6f, 7f);
|
||||
private static final Matrix4f LEGACY_CAMERA = new Matrix4f().rotationY(0.7f).setTranslation(-11f, -22f, -33f);
|
||||
|
||||
private static final String IRIS_MVM_VS = "#version 330 core\n"
|
||||
+ "uniform mat4 iris_ModelViewMatrix;\n"
|
||||
+ "layout(location = 0) in vec3 a_Pos;\n"
|
||||
+ "void main() { gl_Position = iris_ModelViewMatrix * vec4(a_Pos, 1.0); }\n";
|
||||
|
||||
private int vsh;
|
||||
private int fsh;
|
||||
private int program;
|
||||
private int vao;
|
||||
private int indirectBuffer;
|
||||
private int elementBuffer;
|
||||
private int location;
|
||||
|
||||
private static void putMatrix(Matrix4f m, FloatBuffer buf) {
|
||||
buf.clear();
|
||||
m.get(buf);
|
||||
buf.position(0).limit(16);
|
||||
}
|
||||
|
||||
private static Matrix4f readUniform(int program, int location) {
|
||||
final FloatBuffer buf = BufferUtils.createFloatBuffer(16);
|
||||
GLStateManager.glGetUniform(program, location, buf);
|
||||
return new Matrix4f(buf);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void armSentinel() {
|
||||
vsh = IndirectCullDrawParityTest.compileShader(GL20.GL_VERTEX_SHADER, IRIS_MVM_VS);
|
||||
fsh = IndirectCullDrawParityTest.compileShader(GL20.GL_FRAGMENT_SHADER, IndirectCullDrawParityTest.FLAT_FS);
|
||||
program = GLStateManager.glCreateProgram();
|
||||
GLStateManager.glAttachShader(program, vsh);
|
||||
GLStateManager.glAttachShader(program, fsh);
|
||||
GLStateManager.glLinkProgram(program);
|
||||
assertEquals(GL11.GL_TRUE, GLStateManager.glGetProgrami(program, GL20.GL_LINK_STATUS), () -> "program failed to link:\n" + GLStateManager.glGetProgramInfoLog(program, 4096));
|
||||
assertTrue(CompatUniformManager.hasProgram(program), "program with iris_ModelViewMatrix was not registered by CompatUniformManager at link");
|
||||
location = GLStateManager.glGetUniformLocation(program, "iris_ModelViewMatrix");
|
||||
assertTrue(location >= 0, "iris_ModelViewMatrix location not found");
|
||||
|
||||
vao = GLStateManager.glGenVertexArrays();
|
||||
GLStateManager.glBindVertexArray(vao);
|
||||
elementBuffer = GLStateManager.glGenBuffers();
|
||||
GLStateManager.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, elementBuffer);
|
||||
GLStateManager.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, BufferUtils.createByteBuffer(12), GL15.GL_STATIC_DRAW);
|
||||
indirectBuffer = GLStateManager.glGenBuffers();
|
||||
GLStateManager.glBindBuffer(GL40.GL_DRAW_INDIRECT_BUFFER, indirectBuffer);
|
||||
final ByteBuffer zeroCommand = BufferUtils.createByteBuffer(20).order(ByteOrder.nativeOrder());
|
||||
GLStateManager.glBufferData(GL40.GL_DRAW_INDIRECT_BUFFER, zeroCommand, GL15.GL_STATIC_DRAW);
|
||||
|
||||
final FloatBuffer matBuf = BufferUtils.createFloatBuffer(16);
|
||||
GLStateManager.glUseProgram(program);
|
||||
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
|
||||
putMatrix(LEGACY_CAMERA, matBuf);
|
||||
GLStateManager.glLoadMatrix(matBuf);
|
||||
putMatrix(SENTINEL, matBuf);
|
||||
GLStateManager.glUniformMatrix4(location, false, matBuf);
|
||||
assertEquals(SENTINEL, readUniform(program, location), "sentinel upload did not take");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
GLStateManager.glBindBuffer(GL40.GL_DRAW_INDIRECT_BUFFER, 0);
|
||||
GLStateManager.glBindVertexArray(0);
|
||||
GLStateManager.glUseProgram(0);
|
||||
if (vao != 0) GLStateManager.glDeleteVertexArrays(vao);
|
||||
if (indirectBuffer != 0) GLStateManager.glDeleteBuffers(indirectBuffer);
|
||||
if (elementBuffer != 0) GLStateManager.glDeleteBuffers(elementBuffer);
|
||||
GLStateManager.glDeleteProgram(program);
|
||||
GLStateManager.glDeleteShader(vsh);
|
||||
GLStateManager.glDeleteShader(fsh);
|
||||
final FloatBuffer identity = BufferUtils.createFloatBuffer(16);
|
||||
new Matrix4f().get(identity);
|
||||
GLStateManager.glLoadMatrix(identity);
|
||||
}
|
||||
|
||||
@Test
|
||||
void multiDrawIndirectDoesNotStompIrisMatrix() {
|
||||
assumeTrue(RenderSystem.supportsMultiDrawIndirect(), "glMultiDrawElementsIndirect needs GL 4.3 / ARB_multi_draw_indirect; macOS core profile caps at 4.1");
|
||||
|
||||
GLStateManager.glMultiDrawElementsIndirect(GL11.GL_TRIANGLES, GL11.GL_UNSIGNED_INT, 0L, 1, 0);
|
||||
assertEquals(SENTINEL, readUniform(program, location), "glMultiDrawElementsIndirect stomped iris_ModelViewMatrix from the legacy matrix stack; celeritas-managed programs own this uniform and the shadow pass renders with the camera view if it is overwritten");
|
||||
}
|
||||
|
||||
@Test
|
||||
void baseVertexDrawsDoNotStompIrisMatrixButRegularDrawDoes() {
|
||||
GLStateManager.glDrawElementsBaseVertex(GL11.GL_TRIANGLES, 0, GL11.GL_UNSIGNED_INT, 0L, 0);
|
||||
assertEquals(SENTINEL, readUniform(program, location), "glDrawElementsBaseVertex stomped iris_ModelViewMatrix; the Individual draw emitter renders shadows with the camera view if it is overwritten");
|
||||
|
||||
GLStateManager.glDrawRangeElementsBaseVertex(GL11.GL_TRIANGLES, 0, 0, 0, GL11.GL_UNSIGNED_INT, 0L, 0);
|
||||
assertEquals(SENTINEL, readUniform(program, location), "glDrawRangeElementsBaseVertex stomped iris_ModelViewMatrix");
|
||||
|
||||
GLStateManager.glDrawElements(GL11.GL_TRIANGLES, 0, GL11.GL_UNSIGNED_INT, 0L);
|
||||
final Matrix4f afterRegularDraw = readUniform(program, location);
|
||||
assertNotEquals(SENTINEL, afterRegularDraw, "regular glDrawElements no longer refreshes compat uniforms; entity/hand programs rely on the legacy-stack upload");
|
||||
assertTrue(afterRegularDraw.equals(LEGACY_CAMERA, 1e-6f), "regular draw refreshed iris_ModelViewMatrix but not from the legacy modelview stack");
|
||||
}
|
||||
}
|
||||
+305
@@ -0,0 +1,305 @@
|
||||
package com.gtnewhorizons.angelica.rendering.culling;
|
||||
|
||||
import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataUnsafe;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.QuadPrimitiveType;
|
||||
import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class SectionMetaBufferTest {
|
||||
@Test
|
||||
void slotLayout_originAndFencePosts() {
|
||||
final SectionMetaBuffer meta = new SectionMetaBuffer();
|
||||
final int[] vo = { 100, 200, 300, 400, 500, 600, 700 };
|
||||
final int[] ec = { 12, 24, 36, 48, 60, 72, 84 };
|
||||
final int[] io = { 4, 16, 32, 64, 128, 256, 512 };
|
||||
final int sliceMaskLow = 0x7F;
|
||||
final ByteBuffer src = SyntheticSectionData.row(sliceMaskLow, 0xDEADBEEF, vo, ec, io);
|
||||
|
||||
try {
|
||||
meta.update(0, 16, 32, 64, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
|
||||
final int slot = meta.lookupSlot(0, 16, 32, 64);
|
||||
assertEquals(0, slot, "first allocated slot should be 0");
|
||||
|
||||
final ByteBuffer mirror = meta.getMirrorForReadOnly();
|
||||
assertNotNull(mirror);
|
||||
|
||||
assertEquals(16, mirror.getInt(0), "origin.x");
|
||||
assertEquals(32, mirror.getInt(4), "origin.y");
|
||||
assertEquals(64, mirror.getInt(8), "origin.z");
|
||||
assertEquals(sliceMaskLow, mirror.getInt(SectionMetaBuffer.OFFSET_SLICE_MASK), "origin.w (sliceMask low)");
|
||||
|
||||
for (int facing = 0; facing < 7; facing++) {
|
||||
assertEquals(vo[facing], mirror.getInt(SectionMetaBuffer.OFFSET_POSTS + facing * 4), "post[" + facing + "] is facing " + facing + "'s first vertex");
|
||||
}
|
||||
assertEquals(vo[6] + (ec[6] / 6) * 4, mirror.getInt(SectionMetaBuffer.OFFSET_POSTS + 7 * 4), "post[7] closes the last facing's vertex range");
|
||||
assertEquals(io[0] / 4, mirror.getInt(SectionMetaBuffer.OFFSET_FIRST_INDEX_BASE), "firstIndexBase is the section's index base in elements");
|
||||
} finally {
|
||||
MemoryUtilities.memFree(src);
|
||||
meta.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void slotAllocation_isStablePerSection() {
|
||||
final SectionMetaBuffer meta = new SectionMetaBuffer();
|
||||
final int[] vo = { 0, 0, 0, 0, 0, 0, 0 };
|
||||
final int[] ec = { 0, 0, 0, 0, 0, 0, 0 };
|
||||
final int[] io = { 0, 0, 0, 0, 0, 0, 0 };
|
||||
final ByteBuffer src = SyntheticSectionData.row(0, 0, vo, ec, io);
|
||||
try {
|
||||
meta.update(0, 16, 32, 64, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
final int firstSlot = meta.lookupSlot(0, 16, 32, 64);
|
||||
meta.update(0, 16, 32, 64, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
assertEquals(firstSlot, meta.lookupSlot(0, 16, 32, 64), "slot must be stable across updates");
|
||||
|
||||
meta.update(0, 0, 0, 0, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
final int otherSlot = meta.lookupSlot(0, 0, 0, 0);
|
||||
assertEquals(firstSlot + 1, otherSlot, "fresh section -> next high-water slot");
|
||||
|
||||
meta.remove(0, 16, 32, 64, 0);
|
||||
assertEquals(-1, meta.lookupSlot(0, 16, 32, 64), "removed slot should not resolve");
|
||||
meta.update(0, 16, 32, 64, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
assertEquals(firstSlot, meta.lookupSlot(0, 16, 32, 64), "free-list reuse should reclaim the slot");
|
||||
} finally {
|
||||
MemoryUtilities.memFree(src);
|
||||
meta.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void localSectionIndex_unpacking() {
|
||||
final SectionMetaBuffer meta = new SectionMetaBuffer();
|
||||
final int[] vo = { 0, 0, 0, 0, 0, 0, 0 };
|
||||
final int[] ec = { 0, 0, 0, 0, 0, 0, 0 };
|
||||
final int[] io = { 0, 0, 0, 0, 0, 0, 0 };
|
||||
final ByteBuffer src = SyntheticSectionData.row(0, 0, vo, ec, io);
|
||||
try {
|
||||
final int x = 3, y = 2, z = 5;
|
||||
final int localIdx = (x << 5) | (z << 2) | y;
|
||||
meta.update(0, 0, 0, 0, localIdx, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
final ByteBuffer mirror = meta.getMirrorForReadOnly();
|
||||
assertEquals(x << 4, mirror.getInt(0), "origin.x = sectionX << 4");
|
||||
assertEquals(y << 4, mirror.getInt(4), "origin.y = sectionY << 4");
|
||||
assertEquals(z << 4, mirror.getInt(8), "origin.z = sectionZ << 4");
|
||||
} finally {
|
||||
MemoryUtilities.memFree(src);
|
||||
meta.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void distinctPasses_sameCoords_distinctSlots() {
|
||||
final SectionMetaBuffer meta = new SectionMetaBuffer();
|
||||
final int[] voA = { 1000, 0, 0, 0, 0, 0, 0 };
|
||||
final int[] voB = { 2000, 0, 0, 0, 0, 0, 0 };
|
||||
final int[] ecA = { 100, 0, 0, 0, 0, 0, 0 };
|
||||
final int[] ecB = { 0, 0, 0, 0, 0, 0, 200 }; // different facing pattern
|
||||
final int[] io = { 0, 0, 0, 0, 0, 0, 0 };
|
||||
final ByteBuffer srcA = SyntheticSectionData.row(0x33, 0, voA, ecA, io);
|
||||
final ByteBuffer srcB = SyntheticSectionData.row(0x40, 0, voB, ecB, io);
|
||||
try {
|
||||
meta.update(0, 16, 32, 64, 0, MemoryUtilities.memAddress(srcA), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
meta.update(1, 16, 32, 64, 0, MemoryUtilities.memAddress(srcB), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
final int slotA = meta.lookupSlot(0, 16, 32, 64);
|
||||
final int slotB = meta.lookupSlot(1, 16, 32, 64);
|
||||
assertEquals(0, slotA, "pass 0 -> slot 0");
|
||||
assertEquals(1, slotB, "pass 1 -> slot 1, distinct from pass 0's slot");
|
||||
|
||||
final ByteBuffer mirror = meta.getMirrorForReadOnly();
|
||||
final int stride = SectionMetaBuffer.BYTES_PER_SECTION;
|
||||
assertEquals(0x33, mirror.getInt(0 * stride + SectionMetaBuffer.OFFSET_SLICE_MASK), "slot 0 sliceMask comes from passA");
|
||||
assertEquals(0x40, mirror.getInt(1 * stride + SectionMetaBuffer.OFFSET_SLICE_MASK), "slot 1 sliceMask comes from passB");
|
||||
assertEquals(1000, mirror.getInt(0 * stride + SectionMetaBuffer.OFFSET_POSTS), "slot 0 post[0] from passA");
|
||||
assertEquals(2000, mirror.getInt(1 * stride + SectionMetaBuffer.OFFSET_POSTS), "slot 1 post[0] from passB");
|
||||
} finally {
|
||||
MemoryUtilities.memFree(srcA);
|
||||
MemoryUtilities.memFree(srcB);
|
||||
meta.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_returnsAllocatedSlot() {
|
||||
final SectionMetaBuffer meta = new SectionMetaBuffer();
|
||||
final int[] vo = { 0, 0, 0, 0, 0, 0, 0 };
|
||||
final int[] ec = { 0, 0, 0, 0, 0, 0, 0 };
|
||||
final int[] io = { 0, 0, 0, 0, 0, 0, 0 };
|
||||
final ByteBuffer src = SyntheticSectionData.row(0, 0, vo, ec, io);
|
||||
try {
|
||||
final int slotA = meta.update(0, 16, 32, 64, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
final int slotB = meta.update(0, 0, 0, 0, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
assertEquals(0, slotA, "first allocation -> slot 0");
|
||||
assertEquals(1, slotB, "second distinct section -> slot 1");
|
||||
assertEquals(slotA, meta.update(0, 16, 32, 64, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED), "re-update returns the stable slot");
|
||||
assertEquals(-1, meta.update(0, 0, 0, 0, 0, 0L, SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED), "null dataPtr -> -1");
|
||||
} finally {
|
||||
MemoryUtilities.memFree(src);
|
||||
meta.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void syncIfDirty_positionsAndClearsDirty() {
|
||||
final SectionMetaBuffer meta = new SectionMetaBuffer();
|
||||
final int[] zeros = { 0, 0, 0, 0, 0, 0, 0 };
|
||||
final ByteBuffer src = SyntheticSectionData.row(0, 0, zeros, zeros, zeros);
|
||||
try {
|
||||
meta.update(0, 16, 32, 64, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
meta.update(0, 0, 0, 0, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
assertTrue(meta.isDirty(), "dirty after update");
|
||||
final AtomicReference<ByteBuffer> seen = new AtomicReference<>();
|
||||
final boolean ran = meta.syncIfDirty(b -> { seen.set(b); return true; });
|
||||
assertTrue(ran, "sink must run when dirty + non-empty");
|
||||
assertFalse(meta.isDirty(), "dirty cleared by syncIfDirty");
|
||||
assertNotNull(seen.get());
|
||||
assertEquals(0, seen.get().position(), "position is zeroed for sink");
|
||||
assertEquals(2 * SectionMetaBuffer.BYTES_PER_SECTION, seen.get().limit(), "limit is hwm * BYTES_PER_SECTION");
|
||||
assertEquals(0, seen.get().position(), "position is zero");
|
||||
assertFalse(meta.syncIfDirty(_ -> { throw new AssertionError("must not run"); }), "second call with no updates must short-circuit");
|
||||
} finally {
|
||||
MemoryUtilities.memFree(src);
|
||||
meta.reset();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void syncIfDirty_refusedSinkKeepsDataPending() {
|
||||
final SectionMetaBuffer meta = new SectionMetaBuffer();
|
||||
final int[] zeros = { 0, 0, 0, 0, 0, 0, 0 };
|
||||
final ByteBuffer src = SyntheticSectionData.row(0, 0, zeros, zeros, zeros);
|
||||
try {
|
||||
meta.update(0, 16, 32, 64, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
final AtomicInteger offers = new AtomicInteger();
|
||||
|
||||
assertFalse(meta.syncIfDirty(b -> { offers.incrementAndGet(); return false; }), "a refused sink reports no sync");
|
||||
assertTrue(meta.isDirty(), "refused data stays pending");
|
||||
|
||||
final AtomicReference<ByteBuffer> seen = new AtomicReference<>();
|
||||
assertTrue(meta.syncIfDirty(b -> { offers.incrementAndGet(); seen.set(b); return true; }), "the same data is re-offered once the sink accepts");
|
||||
assertFalse(meta.isDirty(), "dirty clears only after the sink consumes");
|
||||
assertEquals(2, offers.get());
|
||||
assertEquals(SectionMetaBuffer.BYTES_PER_SECTION, seen.get().limit());
|
||||
} finally {
|
||||
MemoryUtilities.memFree(src);
|
||||
meta.reset();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void syncIfDirty_emptyMirrorStillClearsDirty() {
|
||||
final SectionMetaBuffer meta = new SectionMetaBuffer();
|
||||
try {
|
||||
assertFalse(meta.isDirty(), "fresh buffer is not dirty");
|
||||
assertFalse(meta.syncIfDirty(_ -> { throw new AssertionError("must not run"); }), "no updates -> false");
|
||||
} finally {
|
||||
meta.reset();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void reset_isIdempotent() {
|
||||
final SectionMetaBuffer meta = new SectionMetaBuffer();
|
||||
final int[] zeros = { 0, 0, 0, 0, 0, 0, 0 };
|
||||
final ByteBuffer src = SyntheticSectionData.row(0, 0, zeros, zeros, zeros);
|
||||
try {
|
||||
meta.update(0, 16, 32, 64, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
meta.reset();
|
||||
assertNull(meta.getMirrorForReadOnly(), "mirror gone after reset");
|
||||
assertEquals(-1, meta.lookupSlot(0, 16, 32, 64), "slot map cleared");
|
||||
meta.reset();
|
||||
meta.reset();
|
||||
meta.update(0, 16, 32, 64, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
assertEquals(0, meta.lookupSlot(0, 16, 32, 64), "reset is reusable, allocates fresh slot");
|
||||
} finally {
|
||||
MemoryUtilities.memFree(src);
|
||||
meta.reset();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrent_updates_and_syncs_doNotCrash() throws InterruptedException {
|
||||
final SectionMetaBuffer meta = new SectionMetaBuffer();
|
||||
final int[] zeros = { 0, 0, 0, 0, 0, 0, 0 };
|
||||
final ByteBuffer src = SyntheticSectionData.row(0, 0, zeros, zeros, zeros);
|
||||
final AtomicBoolean stop = new AtomicBoolean(false);
|
||||
final AtomicReference<Throwable> error = new AtomicReference<>();
|
||||
final long srcAddr = MemoryUtilities.memAddress(src);
|
||||
|
||||
final Thread writer = new Thread(() -> {
|
||||
try {
|
||||
int x = 0, y = 0, z = 0;
|
||||
while (!stop.get()) {
|
||||
meta.update(0, x << 4, y << 4, z << 4, 0, srcAddr, SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
x++;
|
||||
if (x > 63) { x = 0; y++; }
|
||||
if (y > 63) { y = 0; z++; }
|
||||
if (z > 63) z = 0;
|
||||
}
|
||||
} catch (Throwable t) { error.set(t); }
|
||||
}, "section-writer");
|
||||
|
||||
final Thread reader = new Thread(() -> {
|
||||
try {
|
||||
byte[] sink = new byte[1024 * 1024];
|
||||
while (!stop.get()) {
|
||||
meta.syncIfDirty(b -> {
|
||||
final int n = Math.min(b.remaining(), sink.length);
|
||||
for (int i = 0; i < n; i++) sink[i] = b.get(i);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
} catch (Throwable t) { error.set(t); }
|
||||
}, "section-reader");
|
||||
|
||||
writer.start();
|
||||
reader.start();
|
||||
Thread.sleep(2000);
|
||||
stop.set(true);
|
||||
writer.join(5000);
|
||||
reader.join(5000);
|
||||
|
||||
try {
|
||||
if (error.get() != null) throw new AssertionError("worker crashed", error.get());
|
||||
} finally {
|
||||
MemoryUtilities.memFree(src);
|
||||
meta.reset();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void perPassRemove_leavesSiblingPasses() {
|
||||
final SectionMetaBuffer meta = new SectionMetaBuffer();
|
||||
final int[] vo = { 0, 0, 0, 0, 0, 0, 0 };
|
||||
final int[] ec = { 0, 0, 0, 0, 0, 0, 0 };
|
||||
final int[] io = { 0, 0, 0, 0, 0, 0, 0 };
|
||||
final ByteBuffer src = SyntheticSectionData.row(0, 0, vo, ec, io);
|
||||
try {
|
||||
meta.update(0, 16, 32, 64, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
meta.update(1, 16, 32, 64, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
final int slotA = meta.lookupSlot(0, 16, 32, 64);
|
||||
final int slotB = meta.lookupSlot(1, 16, 32, 64);
|
||||
|
||||
meta.remove(0, 16, 32, 64, 0);
|
||||
assertEquals(-1, meta.lookupSlot(0, 16, 32, 64), "pass 0 slot must be gone");
|
||||
assertEquals(slotB, meta.lookupSlot(1, 16, 32, 64), "pass 1 slot must survive pass 0 removal");
|
||||
|
||||
meta.update(0, 0, 0, 0, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
assertEquals(slotA, meta.lookupSlot(0, 0, 0, 0), "free-list reuse claims pass 0's vacated slot");
|
||||
} finally {
|
||||
MemoryUtilities.memFree(src);
|
||||
meta.shutdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
package com.gtnewhorizons.angelica.rendering.culling;
|
||||
|
||||
import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataUnsafe;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.QuadPrimitiveType;
|
||||
import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class SectionMetaSlotLifecycleTest {
|
||||
|
||||
@Test
|
||||
void freedSlotsAreReusedInsteadOfGrowingTheHighWaterMark() {
|
||||
final SectionMetaBuffer meta = new SectionMetaBuffer();
|
||||
final ByteBuffer src = SyntheticSectionData.sliceMaskOnly(0x7F);
|
||||
final long ptr = MemoryUtilities.memAddress(src);
|
||||
try {
|
||||
for (int i = 0; i < 8; i++) meta.update(0, i * 64, 0, 0, 0, ptr, SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
assertEquals(8, meta.getHighWaterMark());
|
||||
|
||||
for (int i = 0; i < 8; i++) meta.remove(0, i * 64, 0, 0, 0);
|
||||
assertEquals(8, meta.getHighWaterMark(), "high-water mark is monotonic within a session");
|
||||
|
||||
for (int i = 0; i < 8; i++) meta.update(0, (100 + i) * 64, 0, 0, 0, ptr, SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
assertEquals(8, meta.getHighWaterMark(), "eight fresh sections must reuse the eight freed slots");
|
||||
} finally {
|
||||
MemoryUtilities.memFree(src);
|
||||
meta.reset();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void everySlotIsDistinctWhileLive() {
|
||||
final SectionMetaBuffer meta = new SectionMetaBuffer();
|
||||
final ByteBuffer src = SyntheticSectionData.sliceMaskOnly(0x7F);
|
||||
final long ptr = MemoryUtilities.memAddress(src);
|
||||
try {
|
||||
final int a = meta.update(0, 0, 0, 0, 0, ptr, SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
final int b = meta.update(0, 64, 0, 0, 0, ptr, SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
assertNotEquals(a, b);
|
||||
|
||||
meta.remove(0, 0, 0, 0, 0);
|
||||
final int c = meta.update(0, 128, 0, 0, 0, ptr, SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
assertEquals(a, c, "the freed slot is handed to the next section");
|
||||
assertNotEquals(b, c, "a live slot is never handed out twice");
|
||||
} finally {
|
||||
MemoryUtilities.memFree(src);
|
||||
meta.reset();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetReturnsTheBufferToEmpty() {
|
||||
final SectionMetaBuffer meta = new SectionMetaBuffer();
|
||||
final ByteBuffer src = SyntheticSectionData.sliceMaskOnly(0x7F);
|
||||
final long ptr = MemoryUtilities.memAddress(src);
|
||||
try {
|
||||
for (int i = 0; i < 5; i++) meta.update(0, i * 64, 0, 0, 0, ptr, SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
assertTrue(meta.getHighWaterMark() > 0);
|
||||
|
||||
meta.reset();
|
||||
assertEquals(0, meta.getHighWaterMark());
|
||||
assertEquals(-1, meta.lookupSlot(0, 0, 0, 0), "slots do not survive a reset");
|
||||
|
||||
assertEquals(0, meta.update(0, 0, 0, 0, 0, ptr, SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED), "allocation restarts from slot 0");
|
||||
} finally {
|
||||
MemoryUtilities.memFree(src);
|
||||
meta.reset();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void passesDoNotShareSlots() {
|
||||
final SectionMetaBuffer meta = new SectionMetaBuffer();
|
||||
final ByteBuffer src = SyntheticSectionData.sliceMaskOnly(0x7F);
|
||||
final long ptr = MemoryUtilities.memAddress(src);
|
||||
try {
|
||||
final int solid = meta.update(0, 0, 0, 0, 0, ptr, SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
final int cutout = meta.update(1, 0, 0, 0, 0, ptr, SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
final int translucent = meta.update(2, 0, 0, 0, 0, ptr, SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED);
|
||||
assertNotEquals(solid, cutout);
|
||||
assertNotEquals(cutout, translucent);
|
||||
assertEquals(3, meta.getHighWaterMark());
|
||||
|
||||
meta.remove(1, 0, 0, 0, 0);
|
||||
assertEquals(-1, meta.lookupSlot(1, 0, 0, 0));
|
||||
assertEquals(solid, meta.lookupSlot(0, 0, 0, 0), "removing one pass leaves its siblings alone");
|
||||
assertEquals(translucent, meta.lookupSlot(2, 0, 0, 0));
|
||||
} finally {
|
||||
MemoryUtilities.memFree(src);
|
||||
meta.reset();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNullDataPointerAllocatesNothing() {
|
||||
final SectionMetaBuffer meta = new SectionMetaBuffer();
|
||||
try {
|
||||
assertEquals(-1, meta.update(0, 0, 0, 0, 0, 0L, SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED));
|
||||
assertEquals(0, meta.getHighWaterMark());
|
||||
} finally {
|
||||
meta.reset();
|
||||
}
|
||||
}
|
||||
}
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
package com.gtnewhorizons.angelica.rendering.culling;
|
||||
|
||||
import com.gtnewhorizons.angelica.glsm.GLCoreTest;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import com.gtnewhorizons.angelica.glsm.RenderSystem;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.lwjgl.BufferUtils;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
import org.lwjgl.opengl.GL30;
|
||||
|
||||
import java.nio.FloatBuffer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@GLCoreTest
|
||||
class ShadowSnapshotBlitTest {
|
||||
|
||||
private static final int SIZE = 256;
|
||||
private static final float FAR = 1.0f;
|
||||
private static final float NEAR_PATCH = 0.25f;
|
||||
|
||||
private static int newDepthTexture() {
|
||||
final int tex = GLStateManager.glGenTextures();
|
||||
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, tex);
|
||||
GLStateManager.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_DEPTH_COMPONENT, SIZE, SIZE, 0, GL11.GL_DEPTH_COMPONENT, GL11.GL_FLOAT, (java.nio.ByteBuffer) null);
|
||||
GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
|
||||
GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
|
||||
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0);
|
||||
return tex;
|
||||
}
|
||||
|
||||
private static int newDepthFbo(int tex) {
|
||||
final int fbo = GLStateManager.glGenFramebuffers();
|
||||
GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, fbo);
|
||||
GLStateManager.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_DEPTH_ATTACHMENT, GL11.GL_TEXTURE_2D, tex, 0);
|
||||
assertEquals(GL30.GL_FRAMEBUFFER_COMPLETE, GLStateManager.glCheckFramebufferStatus(GL30.GL_FRAMEBUFFER), "depth-only FBO incomplete");
|
||||
return fbo;
|
||||
}
|
||||
|
||||
private static void fillPattern(int fbo) {
|
||||
GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, fbo);
|
||||
GLStateManager.glDepthMask(true);
|
||||
GLStateManager.glDisable(GL11.GL_SCISSOR_TEST);
|
||||
GLStateManager.glClearDepth(FAR);
|
||||
GLStateManager.glClear(GL11.GL_DEPTH_BUFFER_BIT);
|
||||
GLStateManager.glEnable(GL11.GL_SCISSOR_TEST);
|
||||
GLStateManager.glScissor(0, 0, SIZE / 2, SIZE / 2);
|
||||
GLStateManager.glClearDepth(NEAR_PATCH);
|
||||
GLStateManager.glClear(GL11.GL_DEPTH_BUFFER_BIT);
|
||||
GLStateManager.glDisable(GL11.GL_SCISSOR_TEST);
|
||||
}
|
||||
|
||||
private static float readDepth(int fbo, int x, int y) {
|
||||
GLStateManager.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, fbo);
|
||||
final FloatBuffer buf = BufferUtils.createFloatBuffer(1);
|
||||
GLStateManager.glReadPixels(x, y, 1, 1, GL11.GL_DEPTH_COMPONENT, GL11.GL_FLOAT, buf);
|
||||
return buf.get(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void depthSnapshotRoundTripsThroughBlit() {
|
||||
final int srcTex = newDepthTexture();
|
||||
final int srcFbo = newDepthFbo(srcTex);
|
||||
final int cacheTex = newDepthTexture();
|
||||
final int cacheFbo = newDepthFbo(cacheTex);
|
||||
try {
|
||||
fillPattern(srcFbo);
|
||||
assertEquals(NEAR_PATCH, readDepth(srcFbo, 10, 10), 1e-4f, "source pattern not written");
|
||||
assertEquals(FAR, readDepth(srcFbo, SIZE - 10, SIZE - 10), 1e-4f, "source background not written");
|
||||
|
||||
RenderSystem.blitFramebuffer(srcFbo, cacheFbo, 0, 0, SIZE, SIZE, 0, 0, SIZE, SIZE, GL11.GL_DEPTH_BUFFER_BIT, GL11.GL_NEAREST);
|
||||
assertEquals(NEAR_PATCH, readDepth(cacheFbo, 10, 10), 1e-4f, "capture blit did not copy the near patch into the cache");
|
||||
assertEquals(FAR, readDepth(cacheFbo, SIZE - 10, SIZE - 10), 1e-4f, "capture blit did not copy the far background into the cache");
|
||||
|
||||
GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, srcFbo);
|
||||
GLStateManager.glDepthMask(true);
|
||||
GLStateManager.glClearDepth(FAR);
|
||||
GLStateManager.glClear(GL11.GL_DEPTH_BUFFER_BIT);
|
||||
assertEquals(FAR, readDepth(srcFbo, 10, 10), 1e-4f, "source not cleared before restore");
|
||||
|
||||
RenderSystem.blitFramebuffer(cacheFbo, srcFbo, 0, 0, SIZE, SIZE, 0, 0, SIZE, SIZE, GL11.GL_DEPTH_BUFFER_BIT, GL11.GL_NEAREST);
|
||||
assertEquals(NEAR_PATCH, readDepth(srcFbo, 10, 10), 1e-4f, "restore blit did not bring the near patch back");
|
||||
assertEquals(FAR, readDepth(srcFbo, SIZE - 10, SIZE - 10), 1e-4f, "restore blit corrupted the far background");
|
||||
} finally {
|
||||
GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0);
|
||||
GLStateManager.glDeleteFramebuffers(srcFbo);
|
||||
GLStateManager.glDeleteFramebuffers(cacheFbo);
|
||||
GLStateManager.glDeleteTextures(srcTex);
|
||||
GLStateManager.glDeleteTextures(cacheTex);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void depthBlitIsNotAffectedByScissorState() {
|
||||
final int srcTex = newDepthTexture();
|
||||
final int srcFbo = newDepthFbo(srcTex);
|
||||
final int cacheTex = newDepthTexture();
|
||||
final int cacheFbo = newDepthFbo(cacheTex);
|
||||
try {
|
||||
fillPattern(srcFbo);
|
||||
GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, cacheFbo);
|
||||
GLStateManager.glClearDepth(FAR);
|
||||
GLStateManager.glClear(GL11.GL_DEPTH_BUFFER_BIT);
|
||||
|
||||
GLStateManager.glEnable(GL11.GL_SCISSOR_TEST);
|
||||
GLStateManager.glScissor(0, 0, 4, 4);
|
||||
RenderSystem.blitFramebuffer(srcFbo, cacheFbo, 0, 0, SIZE, SIZE, 0, 0, SIZE, SIZE, GL11.GL_DEPTH_BUFFER_BIT, GL11.GL_NEAREST);
|
||||
GLStateManager.glDisable(GL11.GL_SCISSOR_TEST);
|
||||
|
||||
assertEquals(NEAR_PATCH, readDepth(cacheFbo, 100, 100), 1e-4f, "scissor clipped the snapshot blit; the cache only received the scissor box");
|
||||
} finally {
|
||||
GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0);
|
||||
GLStateManager.glDeleteFramebuffers(srcFbo);
|
||||
GLStateManager.glDeleteFramebuffers(cacheFbo);
|
||||
GLStateManager.glDeleteTextures(srcTex);
|
||||
GLStateManager.glDeleteTextures(cacheTex);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void rawBlitStaysScissorClipped() {
|
||||
final int srcTex = newDepthTexture();
|
||||
final int srcFbo = newDepthFbo(srcTex);
|
||||
final int cacheTex = newDepthTexture();
|
||||
final int cacheFbo = newDepthFbo(cacheTex);
|
||||
try {
|
||||
fillPattern(srcFbo);
|
||||
GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, cacheFbo);
|
||||
GLStateManager.glClearDepth(FAR);
|
||||
GLStateManager.glClear(GL11.GL_DEPTH_BUFFER_BIT);
|
||||
|
||||
GLStateManager.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, srcFbo);
|
||||
GLStateManager.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, cacheFbo);
|
||||
GLStateManager.glEnable(GL11.GL_SCISSOR_TEST);
|
||||
GLStateManager.glScissor(0, 0, 4, 4);
|
||||
GLStateManager.glBlitFramebuffer(0, 0, SIZE, SIZE, 0, 0, SIZE, SIZE, GL11.GL_DEPTH_BUFFER_BIT, GL11.GL_NEAREST);
|
||||
GLStateManager.glDisable(GL11.GL_SCISSOR_TEST);
|
||||
|
||||
assertEquals(NEAR_PATCH, readDepth(cacheFbo, 1, 1), 1e-4f, "raw blit copied nothing inside the scissor box");
|
||||
assertEquals(FAR, readDepth(cacheFbo, 100, 100), 1e-4f, "raw glBlitFramebuffer ignored scissor");
|
||||
} finally {
|
||||
GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0);
|
||||
GLStateManager.glDeleteFramebuffers(srcFbo);
|
||||
GLStateManager.glDeleteFramebuffers(cacheFbo);
|
||||
GLStateManager.glDeleteTextures(srcTex);
|
||||
GLStateManager.glDeleteTextures(cacheTex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.gtnewhorizons.angelica.rendering.culling;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
|
||||
/** Off-heap SectionRenderData rows in the FULL layout. Callers own the buffer and must memFree it. */
|
||||
final class SyntheticSectionData {
|
||||
|
||||
private static final int BYTES = 92;
|
||||
private static final int FACINGS = 7;
|
||||
private static final int[] ZEROS = new int[FACINGS];
|
||||
|
||||
private SyntheticSectionData() {}
|
||||
|
||||
static ByteBuffer row(int sliceMaskLow, int sliceMaskHigh, int[] vertexOffsets, int[] elementCounts, int[] indexOffsets) {
|
||||
final ByteBuffer buf = MemoryUtilities.memAlloc(BYTES).order(ByteOrder.nativeOrder());
|
||||
buf.putInt(0, sliceMaskLow);
|
||||
buf.putInt(4, sliceMaskHigh);
|
||||
for (int facing = 0; facing < FACINGS; facing++) {
|
||||
final int off = 8 + facing * 12;
|
||||
buf.putInt(off + 0, vertexOffsets[facing]);
|
||||
buf.putInt(off + 4, elementCounts[facing]);
|
||||
buf.putInt(off + 8, indexOffsets[facing]);
|
||||
}
|
||||
return buf;
|
||||
}
|
||||
|
||||
static ByteBuffer sliceMaskOnly(int sliceMask) {
|
||||
return row(sliceMask, 0, ZEROS, ZEROS, ZEROS);
|
||||
}
|
||||
|
||||
static ByteBuffer singleQuadOnFacing0() {
|
||||
final int[] vertexOffsets = { 0, 4, 4, 4, 4, 4, 4 };
|
||||
final int[] elementCounts = { 6, 0, 0, 0, 0, 0, 0 };
|
||||
return row(0x01, 0, vertexOffsets, elementCounts, ZEROS);
|
||||
}
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
package com.gtnewhorizons.angelica.rendering.tesr;
|
||||
|
||||
import com.gtnewhorizons.angelica.api.tesr.TesrMeshSink;
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
|
||||
import com.gtnewhorizons.angelica.api.tesr.TesrMaterial;
|
||||
import com.gtnewhorizons.angelica.rendering.tesr.AngelicaTesrMeshCache.MeshBackend;
|
||||
import com.gtnewhorizons.angelica.rendering.tesr.TemplateBuffer;
|
||||
import net.minecraft.client.renderer.Tessellator;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.LongSupplier;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class AngelicaTesrMeshCacheTest {
|
||||
|
||||
private static final ResourceLocation TEX_A = new ResourceLocation("angelica", "test_a");
|
||||
private static final ResourceLocation TEX_B = new ResourceLocation("angelica", "test_b");
|
||||
|
||||
private final long[] now = { 1_000L };
|
||||
private final LongSupplier clock = () -> now[0];
|
||||
private final FakeBackend backend = new FakeBackend();
|
||||
private final RecordingReplay replay = new RecordingReplay();
|
||||
private final AngelicaTesrMeshCache cache = new AngelicaTesrMeshCache(backend, clock, replay);
|
||||
private final Object key = new Object();
|
||||
|
||||
@Test
|
||||
void firstFrameCapturesAndReplays() {
|
||||
cache.renderCached(key, sink -> sink.angelica$bucket(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, TEX_A));
|
||||
|
||||
assertEquals(1, backend.beginCaptures);
|
||||
assertTrue(cache.hasEntry(key));
|
||||
assertEquals(1, cache.version(key));
|
||||
assertEquals(1, replay.calls.size());
|
||||
assertSame(TEX_A, replay.calls.get(0).texture);
|
||||
}
|
||||
|
||||
@Test
|
||||
void cleanFrameReplaysWithoutRecapture() {
|
||||
cache.renderCached(key, this::oneBucket);
|
||||
cache.renderCached(key, sink -> { throw new AssertionError("builder must not run on a clean frame"); });
|
||||
|
||||
assertEquals(1, backend.beginCaptures);
|
||||
assertEquals(1, cache.version(key));
|
||||
assertEquals(2, replay.calls.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidateForcesRecapture() {
|
||||
cache.renderCached(key, this::oneBucket);
|
||||
cache.invalidate(key);
|
||||
assertFalse(cache.hasEntry(key));
|
||||
|
||||
cache.renderCached(key, this::oneBucket);
|
||||
assertEquals(2, backend.beginCaptures);
|
||||
}
|
||||
|
||||
@Test
|
||||
void lruEvicts() {
|
||||
cache.renderCached(key, this::oneBucket);
|
||||
|
||||
now[0] = 1_000L + AngelicaTesrMeshCache.LRU_TIMEOUT_MS; // boundary -> retained
|
||||
cache.tick();
|
||||
assertTrue(cache.hasEntry(key));
|
||||
|
||||
now[0] = 1_000L + AngelicaTesrMeshCache.LRU_TIMEOUT_MS + 1; // past timeout -> evicted
|
||||
cache.tick();
|
||||
assertFalse(cache.hasEntry(key));
|
||||
}
|
||||
|
||||
@Test
|
||||
void multiBucketOrderAndMaterialPassthrough() {
|
||||
final TesrMaterial material = TesrMaterial.builder().color(0.25f, 0.5f, 0.75f, 1f).build();
|
||||
cache.renderCached(key, sink -> {
|
||||
sink.angelica$bucket(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, TEX_A);
|
||||
sink.angelica$bucket(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, TEX_B, material);
|
||||
});
|
||||
|
||||
assertEquals(2, replay.calls.size());
|
||||
assertSame(TEX_A, replay.calls.get(0).texture);
|
||||
assertSame(TesrMaterial.CURRENT_STATE, replay.calls.get(0).material);
|
||||
assertSame(TEX_B, replay.calls.get(1).texture);
|
||||
assertSame(material, replay.calls.get(1).material);
|
||||
}
|
||||
|
||||
private void oneBucket(TesrMeshSink sink) {
|
||||
sink.angelica$bucket(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, TEX_A);
|
||||
}
|
||||
|
||||
private static final class FakeBackend implements MeshBackend {
|
||||
int beginCaptures;
|
||||
|
||||
@Override
|
||||
public Tessellator beginCapture(VertexFormat format) {
|
||||
beginCaptures++;
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TemplateBuffer endCaptureToTemplate() {
|
||||
return new TemplateBuffer(new int[8], 1, 7);
|
||||
}
|
||||
}
|
||||
|
||||
private record Recorded(TemplateBuffer template, ResourceLocation texture, TesrMaterial material) {}
|
||||
|
||||
private static final class RecordingReplay implements AngelicaTesrMeshCache.ReplaySink {
|
||||
final List<Recorded> calls = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public void queue(TemplateBuffer template, ResourceLocation texture, TesrMaterial material) {
|
||||
calls.add(new Recorded(template, texture, material));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.gtnewhorizons.angelica.rendering.tesr;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
|
||||
class EntityMaterialsTest {
|
||||
|
||||
private static final int SA = GL11.GL_SRC_ALPHA;
|
||||
private static final int OMSA = GL11.GL_ONE_MINUS_SRC_ALPHA;
|
||||
|
||||
@Test
|
||||
void mainModelStateMapsToCutout() {
|
||||
assertSame(EntityMaterials.CUTOUT, EntityMaterials.fromState(true, false, SA, OMSA, true, GL11.GL_GREATER, 0.1f, GL11.GL_LEQUAL, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shadowPassHalfAlphaRefMapsToCutoutHalf() {
|
||||
assertSame(EntityMaterials.CUTOUT_HALF, EntityMaterials.fromState(true, false, SA, OMSA, true, GL11.GL_GREATER, 0.5f, GL11.GL_LEQUAL, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void noAlphaNoBlendMapsToSolid() {
|
||||
assertSame(EntityMaterials.SOLID, EntityMaterials.fromState(true, false, SA, OMSA, false, GL11.GL_ALWAYS, 0f, GL11.GL_LEQUAL, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invisibilityMapsToTranslucent() {
|
||||
assertSame(EntityMaterials.TRANSLUCENT, EntityMaterials.fromState(true, true, SA, OMSA, true, GL11.GL_GREATER, 0.0039f, GL11.GL_LEQUAL, false));
|
||||
assertSame(EntityMaterials.TRANSLUCENT_DEPTH_WRITE, EntityMaterials.fromState(true, true, SA, OMSA, true, GL11.GL_GREATER, 0.0039f, GL11.GL_LEQUAL, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void eyesMapToAdditive() {
|
||||
assertSame(EntityMaterials.ADDITIVE, EntityMaterials.fromState(true, true, GL11.GL_ONE, GL11.GL_ONE, false, GL11.GL_ALWAYS, 0f, GL11.GL_LEQUAL, true));
|
||||
assertSame(EntityMaterials.ADDITIVE_NO_DEPTH_WRITE, EntityMaterials.fromState(true, true, GL11.GL_ONE, GL11.GL_ONE, false, GL11.GL_ALWAYS, 0f, GL11.GL_LEQUAL, false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void hurtOverlayMapsToOverlay() {
|
||||
assertSame(EntityMaterials.OVERLAY, EntityMaterials.fromState(false, true, SA, OMSA, false, GL11.GL_ALWAYS, 0f, GL11.GL_EQUAL, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void glintStateMapsToGlintOnlyWhenTexAnimated() {
|
||||
assertSame(EntityMaterials.GLINT, EntityMaterials.fromState(true, true, true, GL11.GL_SRC_COLOR, GL11.GL_ONE, true, GL11.GL_GREATER, 0.1f, GL11.GL_EQUAL, false));
|
||||
assertNull(EntityMaterials.fromState(true, false, true, GL11.GL_SRC_COLOR, GL11.GL_ONE, true, GL11.GL_GREATER, 0.1f, GL11.GL_EQUAL, false), () -> "glint blend without texture animation must stay live");
|
||||
assertNull(EntityMaterials.fromState(true, true, true, GL11.GL_SRC_COLOR, GL11.GL_ONE, true, GL11.GL_GREATER, 0.1f, GL11.GL_EQUAL, true), () -> "glint blend with depth write is not vanilla glint");
|
||||
}
|
||||
|
||||
@Test
|
||||
void texAnimatedAdditiveVariantsMap() {
|
||||
assertSame(EntityMaterials.ADDITIVE, EntityMaterials.fromState(true, true, true, GL11.GL_ONE, GL11.GL_ONE, false, GL11.GL_ALWAYS, 0f, GL11.GL_LEQUAL, true));
|
||||
assertSame(EntityMaterials.ADDITIVE_ALPHA_NO_DEPTH_WRITE, EntityMaterials.fromState(true, true, true, SA, GL11.GL_ONE, false, GL11.GL_ALWAYS, 0f, GL11.GL_LEQUAL, false));
|
||||
assertNull(EntityMaterials.fromState(true, true, true, SA, OMSA, false, GL11.GL_ALWAYS, 0f, GL11.GL_LEQUAL, true), () -> "animated standard-alpha (scrolling translucent) must stay live");
|
||||
assertNull(EntityMaterials.fromState(true, true, false, SA, OMSA, false, GL11.GL_ALWAYS, 0f, GL11.GL_LEQUAL, true), () -> "animated without blend must stay live");
|
||||
}
|
||||
|
||||
@Test
|
||||
void additiveAlphaMapsWithoutAnimation() {
|
||||
assertSame(EntityMaterials.ADDITIVE_ALPHA, EntityMaterials.fromState(true, false, true, SA, GL11.GL_ONE, false, GL11.GL_ALWAYS, 0f, GL11.GL_LEQUAL, true));
|
||||
assertSame(EntityMaterials.ADDITIVE_ALPHA_NO_DEPTH_WRITE, EntityMaterials.fromState(true, false, true, SA, GL11.GL_ONE, false, GL11.GL_ALWAYS, 0f, GL11.GL_LEQUAL, false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unrecognizedStatesFallBackToLive() {
|
||||
assertNull(EntityMaterials.fromState(true, true, GL11.GL_SRC_COLOR, GL11.GL_ONE, false, GL11.GL_ALWAYS, 0f, GL11.GL_EQUAL, false), () -> "glint blend at EQUAL must stay live");
|
||||
assertNull(EntityMaterials.fromState(true, false, SA, OMSA, true, GL11.GL_GREATER, 0.3f, GL11.GL_LEQUAL, true), () -> "nonstandard alpha ref must stay live");
|
||||
assertNull(EntityMaterials.fromState(false, false, SA, OMSA, false, GL11.GL_ALWAYS, 0f, GL11.GL_LEQUAL, true), () -> "texture off without overlay signature must stay live");
|
||||
assertNull(EntityMaterials.fromState(true, true, SA, OMSA, false, GL11.GL_ALWAYS, 0f, GL11.GL_EQUAL, true), () -> "textured EQUAL-depth re-render must stay live");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
package com.gtnewhorizons.angelica.rendering.tesr;
|
||||
|
||||
import com.gtnewhorizons.angelica.api.tesr.TesrMaterial;
|
||||
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
|
||||
import net.coderbot.batchedentityrendering.impl.AngelicaBufferSource;
|
||||
import net.coderbot.batchedentityrendering.impl.BatchVertexFormats;
|
||||
import net.coderbot.batchedentityrendering.impl.BufferSegment;
|
||||
import net.coderbot.batchedentityrendering.impl.BufferSourceProbe;
|
||||
import org.joml.Matrix4f;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.COLOR_INDEX;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.VERTEX_SIZE;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.X_INDEX;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class RetainedTesrGroupsTest {
|
||||
|
||||
private static final class TestLayer extends RenderLayer {
|
||||
TestLayer() {
|
||||
super("test", BatchVertexFormats.POSITION_COLOR_TEXTURE_LIGHTF_NORMAL, GL11.GL_QUADS, 256, () -> {}, () -> {});
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void retainedGroupAccumulatesInsteadOfStreaming() {
|
||||
final AngelicaBufferSource source = new AngelicaBufferSource();
|
||||
final RetainedTesrGroups groups = new RetainedTesrGroups(source);
|
||||
final TestLayer layer = new TestLayer();
|
||||
|
||||
groups.beginPass(new Matrix4f(), 0, 0, 0);
|
||||
groups.queue(template(), layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 5, null, false);
|
||||
|
||||
assertTrue(groups.hasDraws(layer));
|
||||
assertEquals(0, groups.streamedInstances);
|
||||
final List<RenderLayer> order = BufferSourceProbe.prepare(source);
|
||||
assertTrue(order.contains(layer), "declareUse must register the layer");
|
||||
assertNull(BufferSourceProbe.segmentsFor(source, layer), "retained instances must not produce dynamic segments");
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamingGroupStreamsIntoDynamicSegments() {
|
||||
final AngelicaBufferSource source = new AngelicaBufferSource();
|
||||
final RetainedTesrGroups groups = new RetainedTesrGroups(source);
|
||||
final TestLayer layer = new TestLayer();
|
||||
|
||||
groups.forceStreaming(layer, TesrMaterial.CURRENT_STATE, 5);
|
||||
assertEquals(1, groups.streamPromotions);
|
||||
|
||||
groups.beginPass(new Matrix4f(), 0, 0, 0);
|
||||
groups.queue(template(), layer, TesrMaterial.CURRENT_STATE, new Matrix4f().translation(1f, 2f, 3f), 0, -1, 5, null, false);
|
||||
groups.queue(template(), layer, TesrMaterial.CURRENT_STATE, new Matrix4f().translation(4f, 5f, 6f), 0, -1, 5, null, false);
|
||||
|
||||
assertFalse(groups.hasDraws(layer), "volatile group must not report retained draws");
|
||||
assertEquals(2, groups.streamedInstances);
|
||||
|
||||
BufferSourceProbe.prepare(source);
|
||||
final List<BufferSegment> segments = BufferSourceProbe.segmentsFor(source, layer);
|
||||
assertEquals(1, segments.size());
|
||||
assertEquals(8, segments.get(0).getVertexCount(), "both instances stream into one segment");
|
||||
assertEquals(5, segments.get(0).getBlockEntityId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stableTransformsDemoteStreamingGroup() {
|
||||
final AngelicaBufferSource source = new AngelicaBufferSource();
|
||||
final RetainedTesrGroups groups = new RetainedTesrGroups(source);
|
||||
final TestLayer layer = new TestLayer();
|
||||
final TemplateBuffer template = template();
|
||||
final Matrix4f fixed = new Matrix4f().translation(1f, 2f, 3f);
|
||||
|
||||
groups.forceStreaming(layer, TesrMaterial.CURRENT_STATE, 5);
|
||||
long streamedFrames = 0;
|
||||
for (int frame = 0; frame < RetainedTesrGroups.DEMOTE_AFTER_STABLE_FRAMES + 4; frame++) {
|
||||
groups.beginPass(new Matrix4f(), 0, 0, 0);
|
||||
groups.queue(template, layer, TesrMaterial.CURRENT_STATE, fixed, 0, -1, 5, null, false);
|
||||
if (groups.hasDraws(layer)) break;
|
||||
streamedFrames++;
|
||||
}
|
||||
|
||||
assertTrue(groups.hasDraws(layer), "identical frames must demote the group back to retained");
|
||||
assertTrue(streamedFrames >= RetainedTesrGroups.DEMOTE_AFTER_STABLE_FRAMES, "demotion must wait for the stability window, streamed " + streamedFrames);
|
||||
}
|
||||
|
||||
@Test
|
||||
void movingTransformsStayStreaming() {
|
||||
final AngelicaBufferSource source = new AngelicaBufferSource();
|
||||
final RetainedTesrGroups groups = new RetainedTesrGroups(source);
|
||||
final TestLayer layer = new TestLayer();
|
||||
final TemplateBuffer template = template();
|
||||
|
||||
groups.forceStreaming(layer, TesrMaterial.CURRENT_STATE, 5);
|
||||
for (int frame = 0; frame < RetainedTesrGroups.DEMOTE_AFTER_STABLE_FRAMES + 4; frame++) {
|
||||
groups.beginPass(new Matrix4f(), 0, 0, 0);
|
||||
groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f().translation(frame, 0f, 0f), 0, -1, 5, null, false);
|
||||
assertFalse(groups.hasDraws(layer), "moving group must keep streaming at frame " + frame);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void idleGapResetsVolatility() {
|
||||
final AngelicaBufferSource source = new AngelicaBufferSource();
|
||||
final RetainedTesrGroups groups = new RetainedTesrGroups(source);
|
||||
final TestLayer layer = new TestLayer();
|
||||
|
||||
groups.forceStreaming(layer, TesrMaterial.CURRENT_STATE, 5);
|
||||
for (long i = 0; i <= RetainedTesrGroups.IDLE_RESET_FRAMES + 1; i++) {
|
||||
groups.beginPass(new Matrix4f(), 0, 0, 0);
|
||||
}
|
||||
groups.queue(template(), layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 5, null, false);
|
||||
|
||||
assertTrue(groups.hasDraws(layer), "idle reset must demote the group back to retained");
|
||||
assertEquals(0, groups.streamedInstances);
|
||||
}
|
||||
|
||||
@Test
|
||||
void translucentStreamingGroupNeverDemotes() {
|
||||
final AngelicaBufferSource source = new AngelicaBufferSource();
|
||||
final RetainedTesrGroups groups = new RetainedTesrGroups(source);
|
||||
final TestLayer layer = new TestLayer();
|
||||
final TesrMaterial translucent = TesrMaterial.builder().translucent().build();
|
||||
final TemplateBuffer template = template();
|
||||
final Matrix4f fixed = new Matrix4f().translation(1f, 2f, 3f);
|
||||
|
||||
groups.forceStreaming(layer, translucent, 5);
|
||||
final int frames = RetainedTesrGroups.DEMOTE_AFTER_STABLE_FRAMES + 4;
|
||||
for (int frame = 0; frame < frames; frame++) {
|
||||
groups.beginPass(new Matrix4f(), 0, 0, 0);
|
||||
groups.queue(template, layer, translucent, fixed, 0, -1, 5, null, false);
|
||||
assertFalse(groups.hasDraws(layer), "translucent group must keep streaming at frame " + frame);
|
||||
}
|
||||
assertEquals(frames, groups.streamedInstances);
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamMaterialStreamsFromFirstQueue() {
|
||||
final AngelicaBufferSource source = new AngelicaBufferSource();
|
||||
final RetainedTesrGroups groups = new RetainedTesrGroups(source);
|
||||
final TestLayer layer = new TestLayer();
|
||||
final TesrMaterial stream = TesrMaterial.builder().translucent().stream().build();
|
||||
|
||||
groups.beginPass(new Matrix4f(), 0, 0, 0);
|
||||
groups.queue(template(), layer, stream, new Matrix4f().translation(1f, 2f, 3f), 0, -1, 5, null, false);
|
||||
|
||||
assertFalse(groups.hasDraws(layer), "stream group must not report retained draws");
|
||||
assertEquals(1, groups.streamedInstances);
|
||||
assertEquals(0, groups.streamPromotions, "streaming from birth is not a promotion");
|
||||
|
||||
BufferSourceProbe.prepare(source);
|
||||
final List<BufferSegment> segments = BufferSourceProbe.segmentsFor(source, layer);
|
||||
assertEquals(1, segments.size());
|
||||
assertEquals(5, segments.get(0).getBlockEntityId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamGroupNeverDemotesUnderStableTransforms() {
|
||||
for (final TesrMaterial material : new TesrMaterial[] {
|
||||
TesrMaterial.builder().stream().build(),
|
||||
TesrMaterial.builder().translucent().stream().build()}) {
|
||||
final AngelicaBufferSource source = new AngelicaBufferSource();
|
||||
final RetainedTesrGroups groups = new RetainedTesrGroups(source);
|
||||
final TestLayer layer = new TestLayer();
|
||||
final TemplateBuffer template = template();
|
||||
final Matrix4f fixed = new Matrix4f().translation(1f, 2f, 3f);
|
||||
|
||||
final int frames = RetainedTesrGroups.DEMOTE_AFTER_STABLE_FRAMES + 4;
|
||||
for (int frame = 0; frame < frames; frame++) {
|
||||
groups.beginPass(new Matrix4f(), 0, 0, 0);
|
||||
groups.queue(template, layer, material, fixed, 0, -1, 5, null, false);
|
||||
assertFalse(groups.hasDraws(layer), material.transparency() + " stream group must keep streaming at frame " + frame);
|
||||
}
|
||||
assertEquals(frames, groups.streamedInstances);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void idleGapKeepsStreamGroupStreaming() {
|
||||
final AngelicaBufferSource source = new AngelicaBufferSource();
|
||||
final RetainedTesrGroups groups = new RetainedTesrGroups(source);
|
||||
final TestLayer layer = new TestLayer();
|
||||
final TesrMaterial stream = TesrMaterial.builder().translucent().stream().build();
|
||||
|
||||
groups.beginPass(new Matrix4f(), 0, 0, 0);
|
||||
groups.queue(template(), layer, stream, new Matrix4f(), 0, -1, 5, null, false);
|
||||
for (long i = 0; i <= RetainedTesrGroups.IDLE_RESET_FRAMES + 1; i++) {
|
||||
groups.beginPass(new Matrix4f(), 0, 0, 0);
|
||||
}
|
||||
groups.queue(template(), layer, stream, new Matrix4f(), 0, -1, 5, null, false);
|
||||
|
||||
assertFalse(groups.hasDraws(layer), "idle reset must not move a stream group to retained");
|
||||
assertEquals(2, groups.streamedInstances);
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamGroupRoutesToInstanceArraysWhenInstancedCapable() {
|
||||
final AngelicaBufferSource source = new AngelicaBufferSource();
|
||||
final RetainedTesrGroups groups = new RetainedTesrGroups(source);
|
||||
final TestLayer layer = new TestLayer();
|
||||
final TesrMaterial stream = TesrMaterial.builder().translucent().stream().build();
|
||||
|
||||
groups.beginPass(new Matrix4f(), 0, 0, 0, new InstancedTemplateRenderer());
|
||||
groups.queue(template(), layer, stream, new Matrix4f().translation(1f, 2f, 3f), 0, -1, 5, null, false);
|
||||
|
||||
assertTrue(groups.hasDraws(layer), "instanced-capable stream group accumulates for the hook draw");
|
||||
assertEquals(0, groups.streamedInstances, "no segment streaming when instanced");
|
||||
BufferSourceProbe.prepare(source);
|
||||
assertNull(BufferSourceProbe.segmentsFor(source, layer));
|
||||
}
|
||||
|
||||
@Test
|
||||
void forceStreamSkipsInstanceArraysEvenWhenInstancedCapable() {
|
||||
final AngelicaBufferSource source = new AngelicaBufferSource();
|
||||
final RetainedTesrGroups groups = new RetainedTesrGroups(source);
|
||||
final TestLayer layer = new TestLayer();
|
||||
final TesrMaterial stream = TesrMaterial.builder().translucent().stream().build();
|
||||
|
||||
groups.beginPass(new Matrix4f(), 0, 0, 0, new InstancedTemplateRenderer());
|
||||
groups.queue(template(), layer, stream, new Matrix4f().translation(1f, 2f, 3f), 0, -1, 5, null, true);
|
||||
|
||||
assertFalse(groups.hasDraws(layer), "forceStream instance must not enter the instance arrays");
|
||||
assertEquals(1, groups.streamedInstances);
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamGroupTexMatrixFallsBackToSegmentStream() {
|
||||
final AngelicaBufferSource source = new AngelicaBufferSource();
|
||||
final RetainedTesrGroups groups = new RetainedTesrGroups(source);
|
||||
final TestLayer layer = new TestLayer();
|
||||
final TesrMaterial stream = TesrMaterial.builder().translucent().stream().build();
|
||||
|
||||
groups.beginPass(new Matrix4f(), 0, 0, 0, new InstancedTemplateRenderer());
|
||||
groups.queue(template(), layer, stream, new Matrix4f(), 0, -1, 5, new Matrix4f().translation(0.5f, 0.5f, 0f), false);
|
||||
|
||||
assertFalse(groups.hasDraws(layer), "texMatrix instance must not enter the instance arrays");
|
||||
assertEquals(1, groups.streamedInstances);
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamGroupDrawModeMismatchFallsBackToRetained() {
|
||||
final AngelicaBufferSource source = new AngelicaBufferSource();
|
||||
final RetainedTesrGroups groups = new RetainedTesrGroups(source);
|
||||
final TestLayer layer = new TestLayer();
|
||||
final TesrMaterial stream = TesrMaterial.builder().translucent().stream().build();
|
||||
final int[] data = new int[3 * VERTEX_SIZE];
|
||||
final TemplateBuffer triangles = new TemplateBuffer(data, 3, GL11.GL_TRIANGLES);
|
||||
|
||||
groups.beginPass(new Matrix4f(), 0, 0, 0);
|
||||
groups.queue(triangles, layer, stream, new Matrix4f(), 0, -1, 5, null, false);
|
||||
|
||||
assertTrue(groups.hasDraws(layer), "mismatched drawMode must fall back to retained accumulation");
|
||||
assertEquals(0, groups.streamedInstances);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sweepEvictsIdleGroupsAndKeepsLive() {
|
||||
final long[] clock = {1_000L};
|
||||
final AngelicaBufferSource source = new AngelicaBufferSource();
|
||||
final RetainedTesrGroups groups = new RetainedTesrGroups(source, () -> clock[0]);
|
||||
final TestLayer layer = new TestLayer();
|
||||
final TemplateBuffer template = template();
|
||||
|
||||
groups.beginPass(new Matrix4f(), 0, 0, 0);
|
||||
groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 1, null, false);
|
||||
groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 2, null, false);
|
||||
assertEquals(2, groups.groupCount());
|
||||
|
||||
clock[0] += RetainedTesrGroups.GROUP_TTL_MS + 1;
|
||||
groups.beginPass(new Matrix4f(), 0, 0, 0);
|
||||
groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 1, null, false);
|
||||
groups.sweep(clock[0]);
|
||||
|
||||
assertEquals(1, groups.groupCount(), "idle group must be evicted, live group kept");
|
||||
assertTrue(groups.hasDraws(layer), "live group still draws this frame");
|
||||
|
||||
groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 2, null, false);
|
||||
assertEquals(2, groups.groupCount(), "evicted id must be re-creatable");
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearEmptiesAllGroups() {
|
||||
final AngelicaBufferSource source = new AngelicaBufferSource();
|
||||
final RetainedTesrGroups groups = new RetainedTesrGroups(source);
|
||||
final TestLayer layer = new TestLayer();
|
||||
final TemplateBuffer template = template();
|
||||
|
||||
groups.beginPass(new Matrix4f(), 0, 0, 0);
|
||||
groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 1, null, false);
|
||||
groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 2, null, false);
|
||||
groups.clear();
|
||||
|
||||
assertEquals(0, groups.groupCount());
|
||||
assertFalse(groups.hasDraws(layer));
|
||||
|
||||
groups.beginPass(new Matrix4f(), 0, 0, 0);
|
||||
groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 1, null, false);
|
||||
assertEquals(1, groups.groupCount());
|
||||
assertTrue(groups.hasDraws(layer));
|
||||
}
|
||||
|
||||
private static TemplateBuffer template() {
|
||||
final int[] data = new int[4 * VERTEX_SIZE];
|
||||
for (int v = 0; v < 4; v++) {
|
||||
final int base = v * VERTEX_SIZE;
|
||||
data[base + X_INDEX] = Float.floatToRawIntBits(v);
|
||||
data[base + COLOR_INDEX] = 0xFFFFFFFF;
|
||||
}
|
||||
return new TemplateBuffer(data, 4, GL11.GL_QUADS);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package com.gtnewhorizons.angelica.rendering.tesr;
|
||||
|
||||
import org.joml.Matrix4f;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class TesrAnchorMathTest {
|
||||
|
||||
private static final double TE_X = 123456.25, TE_Y = 64.0, TE_Z = -98765.75;
|
||||
|
||||
private static Matrix4f cameraRelative(double camX, double camY, double camZ) {
|
||||
return new Matrix4f().translation((float) (TE_X - camX), (float) (TE_Y - camY), (float) (TE_Z - camZ));
|
||||
}
|
||||
|
||||
private static Matrix4f anchorRelative(double camX, double camY, double camZ, long ax, long ay, long az) {
|
||||
final Matrix4f m = cameraRelative(camX, camY, camZ);
|
||||
TesrAnchorMath.toAnchorRelative(m, camX, camY, camZ, ax, ay, az);
|
||||
return m;
|
||||
}
|
||||
|
||||
@Test
|
||||
void anchorCoordRoundsDownToGrid() {
|
||||
assertEquals(96, TesrAnchorMath.anchorCoord(100.5));
|
||||
assertEquals(112, TesrAnchorMath.anchorCoord(112.0));
|
||||
assertEquals(-16, TesrAnchorMath.anchorCoord(-0.5));
|
||||
assertEquals(-32, TesrAnchorMath.anchorCoord(-16.5));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReanchorTriggersOnlyBeyondThreshold() {
|
||||
assertFalse(TesrAnchorMath.shouldReanchor(100, 0, 0, 0, 0, 0));
|
||||
assertFalse(TesrAnchorMath.shouldReanchor(511, 0, 0, 0, 0, 0));
|
||||
assertTrue(TesrAnchorMath.shouldReanchor(513, 0, 0, 0, 0, 0));
|
||||
assertTrue(TesrAnchorMath.shouldReanchor(300, 300, 300, 0, 0, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anchorRelativeTranslationReconstructsWorldOffset() {
|
||||
final double camX = TE_X - 30.5, camY = TE_Y + 5.0, camZ = TE_Z + 12.25;
|
||||
final long ax = TesrAnchorMath.anchorCoord(camX);
|
||||
final long ay = TesrAnchorMath.anchorCoord(camY);
|
||||
final long az = TesrAnchorMath.anchorCoord(camZ);
|
||||
final Matrix4f mA = anchorRelative(camX, camY, camZ, ax, ay, az);
|
||||
assertEquals(TE_X - ax, mA.m30(), 1e-2f);
|
||||
assertEquals(TE_Y - ay, mA.m31(), 1e-2f);
|
||||
assertEquals(TE_Z - az, mA.m32(), 1e-2f);
|
||||
}
|
||||
|
||||
@Test
|
||||
void hashIsInvariantUnderCameraMotion() {
|
||||
final double camAX = TE_X - 20.0, camAY = TE_Y - 3.0, camAZ = TE_Z + 8.0;
|
||||
final long ax = TesrAnchorMath.anchorCoord(camAX);
|
||||
final long ay = TesrAnchorMath.anchorCoord(camAY);
|
||||
final long az = TesrAnchorMath.anchorCoord(camAZ);
|
||||
|
||||
final Matrix4f mA = anchorRelative(camAX, camAY, camAZ, ax, ay, az);
|
||||
final long h1 = TesrAnchorMath.instanceHash(42, mA, 0x00F000F0, -1);
|
||||
|
||||
final double camBX = camAX + 137.37, camBY = camAY + 41.03, camBZ = camAZ - 250.91;
|
||||
final Matrix4f mB = anchorRelative(camBX, camBY, camBZ, ax, ay, az);
|
||||
final long h2 = TesrAnchorMath.instanceHash(42, mB, 0x00F000F0, -1);
|
||||
|
||||
assertEquals(h1, h2, "camera-only motion must not change the rebuild hash");
|
||||
}
|
||||
|
||||
@Test
|
||||
void reanchorRoundTripKeepsWorldPosition() {
|
||||
final double camX = TE_X - 20.0, camY = TE_Y, camZ = TE_Z + 20.0;
|
||||
final long ax1 = TesrAnchorMath.anchorCoord(camX);
|
||||
final long ax2 = ax1 + 480;
|
||||
final Matrix4f m1 = anchorRelative(camX, camY, camZ, ax1, 0, 0);
|
||||
final Matrix4f m2 = anchorRelative(camX, camY, camZ, ax2, 0, 0);
|
||||
assertEquals(ax1 + m1.m30(), ax2 + m2.m30(), 1e-2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void hashChangesOnRealDifferences() {
|
||||
final Matrix4f mA = new Matrix4f().translation(1.5f, 2.5f, 3.5f);
|
||||
final long base = TesrAnchorMath.instanceHash(42, mA, 0x00F000F0, -1);
|
||||
assertNotEquals(base, TesrAnchorMath.instanceHash(43, mA, 0x00F000F0, -1), "template identity");
|
||||
assertNotEquals(base, TesrAnchorMath.instanceHash(42, mA, 0x00F000A0, -1), "packed light");
|
||||
assertNotEquals(base, TesrAnchorMath.instanceHash(42, mA, 0x00F000F0, 0xFF0000FF), "color");
|
||||
final Matrix4f moved = new Matrix4f(mA).translate(1f, 0f, 0f);
|
||||
assertNotEquals(base, TesrAnchorMath.instanceHash(42, moved, 0x00F000F0, -1), "transform");
|
||||
}
|
||||
|
||||
@Test
|
||||
void summedHashIsOrderIndependent() {
|
||||
final Matrix4f m1 = new Matrix4f().translation(1f, 2f, 3f);
|
||||
final Matrix4f m2 = new Matrix4f().translation(-4f, 5f, -6f).rotateY(0.5f);
|
||||
final long a = TesrAnchorMath.instanceHash(1, m1, 10, -1);
|
||||
final long b = TesrAnchorMath.instanceHash(2, m2, 20, -1);
|
||||
assertEquals(a + b, b + a);
|
||||
assertNotEquals(a, b);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.gtnewhorizons.angelica.rendering.tesr;
|
||||
|
||||
import com.gtnewhorizons.angelica.api.tesr.TesrMaterial;
|
||||
import com.gtnewhorizons.angelica.api.tesr.TesrShader;
|
||||
import com.gtnewhorizons.angelica.api.tesr.TesrShaders;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||
|
||||
class TesrLayerKeyTest {
|
||||
|
||||
private static final ResourceLocation TEX = new ResourceLocation("angelica", "textures/test.png");
|
||||
private static final TesrShader SHADER = TesrShaders.register("test:layer_key", () -> {}, () -> {});
|
||||
private static final TesrMaterial.SpecialRender NONE = TesrMaterial.SpecialRender.NONE;
|
||||
|
||||
@Test
|
||||
void scratchProbeMatchesCopiedKey() {
|
||||
final TesrBatchRenderer.LayerKey scratch = new TesrBatchRenderer.LayerKey().set(TEX, TesrMaterial.Transparency.OPAQUE, true, false, false, false, 0.1f, false, NONE, SHADER, false);
|
||||
final TesrBatchRenderer.LayerKey stored = scratch.copy();
|
||||
assertNotSame(scratch, stored);
|
||||
assertEquals(scratch, stored);
|
||||
assertEquals(scratch.hashCode(), stored.hashCode());
|
||||
|
||||
scratch.set(TEX, TesrMaterial.Transparency.OPAQUE, true, false, false, false, 0.1f, false, NONE, SHADER, false);
|
||||
assertEquals(stored, scratch, "re-set scratch still matches stored copy");
|
||||
}
|
||||
|
||||
@Test
|
||||
void fieldChangesBreakEquality() {
|
||||
final TesrBatchRenderer.LayerKey base = new TesrBatchRenderer.LayerKey().set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, false);
|
||||
final TesrBatchRenderer.LayerKey other = base.copy();
|
||||
|
||||
other.set(null, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, false);
|
||||
assertNotEquals(base, other);
|
||||
other.set(TEX, TesrMaterial.Transparency.TRANSLUCENT, false, false, false, false, 0f, false, NONE, null, false);
|
||||
assertNotEquals(base, other);
|
||||
other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0.5f, false, NONE, null, false);
|
||||
assertNotEquals(base, other);
|
||||
other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, true, 0f, false, NONE, null, false);
|
||||
assertNotEquals(base, other);
|
||||
other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, TesrMaterial.SpecialRender.GLINT, null, false);
|
||||
assertNotEquals(base, other);
|
||||
other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, SHADER, false);
|
||||
assertNotEquals(base, other);
|
||||
other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, true);
|
||||
assertNotEquals(base, other);
|
||||
|
||||
other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, false);
|
||||
assertEquals(base, other);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullTextureAndShaderHash() {
|
||||
final TesrBatchRenderer.LayerKey key = new TesrBatchRenderer.LayerKey().set(null, null, false, false, false, false, 0f, false, null, null, false);
|
||||
assertEquals(key, key.copy());
|
||||
assertEquals(key.hashCode(), key.copy().hashCode());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.gtnewhorizons.angelica.rendering.tesr;
|
||||
|
||||
import com.gtnewhorizons.angelica.api.tesr.TesrMeshProvider;
|
||||
import com.gtnewhorizons.angelica.api.tesr.TesrMeshSink;
|
||||
import net.minecraft.tileentity.TileEntity;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
|
||||
class TesrProviderDispatchTest {
|
||||
|
||||
private static final class FakeProvider implements TesrMeshProvider {
|
||||
private final Object key;
|
||||
FakeProvider(Object key) { this.key = key; }
|
||||
@Override public Object angelica$meshKey(TileEntity te) { return key; }
|
||||
@Override public void angelica$build(TesrMeshSink sink, TileEntity te) {}
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonProviderIsNotHandled() {
|
||||
assertFalse(TesrProviderDispatch.tryRender(new Object(), null, 0, 0, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullMeshKeyFallsBackToNormalRender() {
|
||||
assertFalse(TesrProviderDispatch.tryRender(new FakeProvider(null), null, 0, 0, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullTileEntityResolvesToZeroBlockEntityId() {
|
||||
assertEquals(0, TesrProviderDispatch.resolveBlockEntityId(null));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package com.gtnewhorizons.angelica.rendering.tesr;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.NormI8;
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
|
||||
import net.coderbot.batchedentityrendering.impl.BatchVertexFormats;
|
||||
import org.joml.Matrix4f;
|
||||
import org.joml.Vector3f;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetFloat;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutFloat;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutInt;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.COLOR_INDEX;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.LIGHT_INDEX;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.NORMAL_INDEX;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.TEX_X_INDEX;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.TEX_Y_INDEX;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.VERTEX_SIZE;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.X_INDEX;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.Y_INDEX;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.Z_INDEX;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class VertexTransformTest {
|
||||
|
||||
private static final float NORM_EPS = 1.5f / 127f;
|
||||
private static final VertexFormat DEST = BatchVertexFormats.POSITION_COLOR_TEXTURE_LIGHTF_NORMAL;
|
||||
private static final int OFF_POS = 0, OFF_COLOR = 12, OFF_TEX = 16, OFF_LIGHT = 24, OFF_NORMAL = 32;
|
||||
|
||||
private static int[] oneVertexUp() {
|
||||
final int[] data = new int[VERTEX_SIZE];
|
||||
data[COLOR_INDEX] = 0xFFFFFFFF;
|
||||
data[X_INDEX] = Float.floatToRawIntBits(0f);
|
||||
data[Y_INDEX] = Float.floatToRawIntBits(1f);
|
||||
data[Z_INDEX] = Float.floatToRawIntBits(0f);
|
||||
data[TEX_X_INDEX] = Float.floatToRawIntBits(0.25f);
|
||||
data[TEX_Y_INDEX] = Float.floatToRawIntBits(0.75f);
|
||||
data[NORMAL_INDEX] = NormI8.pack(0f, 1f, 0f);
|
||||
return data;
|
||||
}
|
||||
|
||||
private static TemplateBuffer template(int[] data) {
|
||||
return new TemplateBuffer(data, 1, 7);
|
||||
}
|
||||
|
||||
@Test
|
||||
void writeInstanceTranslatesPositionSetsColorLightKeepsUv() {
|
||||
final TemplateBuffer template = template(oneVertexUp());
|
||||
final Matrix4f mv = new Matrix4f().translation(10f, -2f, 3f);
|
||||
final ByteBuffer dest = ByteBuffer.allocateDirect(DEST.getVertexSize());
|
||||
final long addr = memAddress0(dest);
|
||||
|
||||
VertexTransform.writeInstance(addr, DEST, template, mv, new Vector3f(), 0xFF8040C0, 0x00F000F0, null);
|
||||
|
||||
assertEquals(10f, memGetFloat(addr + OFF_POS), 1e-6f);
|
||||
assertEquals(-1f, memGetFloat(addr + OFF_POS + 4), 1e-6f);
|
||||
assertEquals(3f, memGetFloat(addr + OFF_POS + 8), 1e-6f);
|
||||
assertEquals(0xFF8040C0, memGetInt(addr + OFF_COLOR));
|
||||
assertEquals(0.25f, memGetFloat(addr + OFF_TEX), 0f);
|
||||
assertEquals(0.75f, memGetFloat(addr + OFF_TEX + 4), 0f);
|
||||
assertEquals(240f, memGetFloat(addr + OFF_LIGHT), 0f); // 0x00F0
|
||||
assertEquals(240f, memGetFloat(addr + OFF_LIGHT + 4), 0f); // 0x00F0
|
||||
final int n = memGetInt(addr + OFF_NORMAL);
|
||||
assertEquals(0f, NormI8.unpackX(n), NORM_EPS);
|
||||
assertEquals(1f, NormI8.unpackY(n), NORM_EPS);
|
||||
assertEquals(0f, NormI8.unpackZ(n), NORM_EPS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void writeInstanceRotatesNormal() {
|
||||
final TemplateBuffer template = template(oneVertexUp());
|
||||
final Matrix4f mv = new Matrix4f().rotationX((float) Math.toRadians(90));
|
||||
final ByteBuffer dest = ByteBuffer.allocateDirect(DEST.getVertexSize());
|
||||
final long addr = memAddress0(dest);
|
||||
|
||||
VertexTransform.writeInstance(addr, DEST, template, mv, new Vector3f(), 0, 0, null);
|
||||
|
||||
final int n = memGetInt(addr + OFF_NORMAL);
|
||||
assertEquals(0f, NormI8.unpackX(n), NORM_EPS);
|
||||
assertEquals(0f, NormI8.unpackY(n), NORM_EPS);
|
||||
assertEquals(1f, NormI8.unpackZ(n), NORM_EPS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void writeInstanceModulatesBakedColorAndPreservesTemplate() {
|
||||
final int[] data = oneVertexUp();
|
||||
data[COLOR_INDEX] = 0xFF0080FF; // ABGR: a=255 b=0 g=128 r=255
|
||||
final TemplateBuffer template = template(data);
|
||||
final ByteBuffer dest = ByteBuffer.allocateDirect(DEST.getVertexSize());
|
||||
final long addr = memAddress0(dest);
|
||||
|
||||
VertexTransform.writeInstance(addr, DEST, template, new Matrix4f(), new Vector3f(), 0x80FFFFFF, 0, null);
|
||||
assertEquals(0x800080FF, memGetInt(addr + OFF_COLOR));
|
||||
|
||||
VertexTransform.writeInstance(addr, DEST, template, new Matrix4f(), new Vector3f(), -1, 0, null);
|
||||
assertEquals(0xFF0080FF, memGetInt(addr + OFF_COLOR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mulColorIsExactForWhiteAndRounds() {
|
||||
assertEquals(0x12345678, VertexTransform.mulColor(0x12345678, 0xFFFFFFFF));
|
||||
assertEquals(0x12345678, VertexTransform.mulColor(0xFFFFFFFF, 0x12345678));
|
||||
assertEquals(0x80, VertexTransform.mulColor(0xFF, 0x80));
|
||||
assertEquals(0x00, VertexTransform.mulColor(0x7F, 0x00));
|
||||
}
|
||||
|
||||
@Test
|
||||
void writeInstanceAppliesTextureMatrixToUvThenRestores() {
|
||||
final TemplateBuffer template = template(oneVertexUp());
|
||||
final ByteBuffer dest = ByteBuffer.allocateDirect(DEST.getVertexSize());
|
||||
final long addr = memAddress0(dest);
|
||||
final Matrix4f texMatrix = new Matrix4f().translation(0f, 0.1f, 0f).scale(1f, 0.5f, 1f);
|
||||
|
||||
VertexTransform.writeInstance(addr, DEST, template, new Matrix4f(), new Vector3f(), -1, 0, texMatrix);
|
||||
assertEquals(0.25f, memGetFloat(addr + OFF_TEX), 1e-6f);
|
||||
assertEquals(0.75f * 0.5f + 0.1f, memGetFloat(addr + OFF_TEX + 4), 1e-6f);
|
||||
|
||||
VertexTransform.writeInstance(addr, DEST, template, new Matrix4f(), new Vector3f(), -1, 0, null);
|
||||
assertEquals(0.25f, memGetFloat(addr + OFF_TEX), 0f);
|
||||
assertEquals(0.75f, memGetFloat(addr + OFF_TEX + 4), 0f);
|
||||
}
|
||||
|
||||
@Test
|
||||
void decodeReadsPositionUvNormalByUsage() {
|
||||
final VertexFormat src = DefaultVertexFormat.POSITION_TEXTURE_NORMAL;
|
||||
final ByteBuffer buf = ByteBuffer.allocateDirect(src.getVertexSize());
|
||||
final long addr = memAddress0(buf);
|
||||
memPutFloat(addr, 5f);
|
||||
memPutFloat(addr + 4, 6f);
|
||||
memPutFloat(addr + 8, 7f);
|
||||
memPutFloat(addr + 12, 0.1f);
|
||||
memPutFloat(addr + 16, 0.2f);
|
||||
memPutInt(addr + 20, NormI8.pack(1f, 0f, 0f));
|
||||
|
||||
final int[] out = VertexTransform.decode(addr, src, 1);
|
||||
|
||||
assertEquals(5f, Float.intBitsToFloat(out[X_INDEX]), 0f);
|
||||
assertEquals(6f, Float.intBitsToFloat(out[Y_INDEX]), 0f);
|
||||
assertEquals(7f, Float.intBitsToFloat(out[Z_INDEX]), 0f);
|
||||
assertEquals(0.1f, Float.intBitsToFloat(out[TEX_X_INDEX]), 0f);
|
||||
assertEquals(0.2f, Float.intBitsToFloat(out[TEX_Y_INDEX]), 0f);
|
||||
assertEquals(1f, NormI8.unpackX(out[NORMAL_INDEX]), NORM_EPS);
|
||||
}
|
||||
}
|
||||
+368
@@ -0,0 +1,368 @@
|
||||
package com.gtnewhorizons.angelica.rendering.voxelization;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities;
|
||||
import com.gtnewhorizons.angelica.config.GpuCullingMode;
|
||||
import com.gtnewhorizons.angelica.rendering.culling.GpuCulling;
|
||||
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat;
|
||||
import org.embeddedt.embeddium.impl.gl.util.VertexRange;
|
||||
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.ChunkPrimitiveType;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.QuadPrimitiveType;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataStorage;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataUnsafe;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderList;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderListIterable;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
|
||||
import org.embeddedt.embeddium.impl.render.viewport.CameraTransform;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class ShadowVoxelizerTest {
|
||||
|
||||
private static final ChunkPrimitiveType PRIMITIVE = QuadPrimitiveType.TRIANGULATED;
|
||||
|
||||
private static class RecordingSink implements ShadowVoxelizer.Sink {
|
||||
final List<float[]> regions = new ArrayList<>();
|
||||
final List<int[]> ranges = new ArrayList<>();
|
||||
int finishes;
|
||||
boolean refuseRegion;
|
||||
boolean refuseRange;
|
||||
|
||||
@Override
|
||||
public boolean region(RenderRegion region, GlVertexFormat format, float x, float y, float z) {
|
||||
if (refuseRegion) return false;
|
||||
regions.add(new float[]{x, y, z});
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean range(int vertexOffset, int vertexCount) {
|
||||
if (refuseRange) return false;
|
||||
ranges.add(new int[]{vertexOffset, vertexCount});
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void finish() {
|
||||
finishes++;
|
||||
}
|
||||
}
|
||||
|
||||
private static final ChunkVertexType VERTEX_TYPE = new ChunkVertexType() {
|
||||
@Override public float getPositionScale() { return 1f; }
|
||||
@Override public float getPositionOffset() { return 0f; }
|
||||
@Override public float getTextureScale() { return 1f; }
|
||||
@Override public GlVertexFormat getVertexFormat() { return null; }
|
||||
@Override public ChunkVertexEncoder createEncoder() { return null; }
|
||||
};
|
||||
|
||||
private static TerrainRenderPass pass(String name) {
|
||||
return new TerrainRenderPass(name, null, false, false, false, false, VERTEX_TYPE, PRIMITIVE, Map.of());
|
||||
}
|
||||
|
||||
private static RenderRegion region(int x, int y, int z) {
|
||||
try {
|
||||
for (Constructor<?> ctor : RenderRegion.class.getDeclaredConstructors()) {
|
||||
if (ctor.getParameterCount() == 5) {
|
||||
ctor.setAccessible(true);
|
||||
return (RenderRegion) ctor.newInstance(x, y, z, 0, null);
|
||||
}
|
||||
}
|
||||
} catch (ReflectiveOperationException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
throw new IllegalStateException("RenderRegion constructor shape changed");
|
||||
}
|
||||
|
||||
private SectionRenderDataStorage storage() {
|
||||
final SectionRenderDataUnsafe.Strategy layout = SectionRenderDataUnsafe.Strategy.COMPACT;
|
||||
final int bytes = (int) layout.getStride() * RenderRegion.REGION_SIZE;
|
||||
final ByteBuffer rows = MemoryUtilities.memAlloc(bytes).order(ByteOrder.nativeOrder());
|
||||
for (int i = 0; i < bytes; i++) rows.put(i, (byte) 0);
|
||||
allocated.add(rows);
|
||||
|
||||
final SectionRenderDataStorage storage = allocateInstance(SectionRenderDataStorage.class);
|
||||
setField(storage, SectionRenderDataStorage.class, "storageStrategy", layout);
|
||||
setField(storage, SectionRenderDataStorage.class, "primitiveType", PRIMITIVE);
|
||||
setField(storage, SectionRenderDataStorage.class, "pMeshDataArray", MemoryUtilities.memAddress(rows));
|
||||
return storage;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <T> T allocateInstance(Class<T> type) {
|
||||
try {
|
||||
final Class<?> unsafeClass = Class.forName("sun.misc.Unsafe");
|
||||
final Field theUnsafe = unsafeClass.getDeclaredField("theUnsafe");
|
||||
theUnsafe.setAccessible(true);
|
||||
final Object unsafe = theUnsafe.get(null);
|
||||
return (T) unsafeClass.getMethod("allocateInstance", Class.class).invoke(unsafe, type);
|
||||
} catch (ReflectiveOperationException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void setField(Object target, Class<?> owner, String name, Object value) {
|
||||
try {
|
||||
final Field field = owner.getDeclaredField(name);
|
||||
field.setAccessible(true);
|
||||
field.set(target, value);
|
||||
} catch (ReflectiveOperationException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static void attachStorage(RenderRegion region, TerrainRenderPass renderPass, SectionRenderDataStorage storage) {
|
||||
try {
|
||||
final Field field = RenderRegion.class.getDeclaredField("sectionRenderData");
|
||||
field.setAccessible(true);
|
||||
((Map<TerrainRenderPass, SectionRenderDataStorage>) field.get(region)).put(renderPass, storage);
|
||||
} catch (ReflectiveOperationException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static ChunkRenderList renderList(RenderRegion region, int... localSectionIndices) {
|
||||
final ChunkRenderList list = new ChunkRenderList(region);
|
||||
final byte[] sections = new byte[RenderRegion.REGION_SIZE];
|
||||
for (int i = 0; i < localSectionIndices.length; i++) {
|
||||
sections[i] = (byte) localSectionIndices[i];
|
||||
}
|
||||
setField(list, ChunkRenderList.class, "sectionsWithGeometry", sections);
|
||||
setField(list, ChunkRenderList.class, "sectionsWithGeometryCount", localSectionIndices.length);
|
||||
return list;
|
||||
}
|
||||
|
||||
private static ChunkRenderListIterable lists(ChunkRenderList... lists) {
|
||||
return reverse -> List.of(lists).iterator();
|
||||
}
|
||||
|
||||
private static void writeSection(SectionRenderDataStorage storage, int localSectionIndex, int baseVertex, int... vertsPerFacing) {
|
||||
final Map<ModelQuadFacing, VertexRange> ranges = new EnumMap<>(ModelQuadFacing.class);
|
||||
int vertex = baseVertex;
|
||||
for (int f = 0; f < vertsPerFacing.length; f++) {
|
||||
if (vertsPerFacing[f] > 0) {
|
||||
ranges.put(ModelQuadFacing.VALUES[f], new VertexRange(vertex, vertsPerFacing[f]));
|
||||
}
|
||||
vertex += vertsPerFacing[f];
|
||||
}
|
||||
storage.getStorageStrategy().writeMeshes(storage.getDataPointer(localSectionIndex), baseVertex, 0, ranges, PRIMITIVE);
|
||||
}
|
||||
|
||||
private static RecordingSink walk(ChunkRenderListIterable renderLists, TerrainRenderPass renderPass, CameraTransform camera, boolean faceCulling) {
|
||||
final RecordingSink sink = new RecordingSink();
|
||||
new ShadowVoxelizer().walkPass(renderLists, renderPass, null, camera, camera, faceCulling, sink);
|
||||
return sink;
|
||||
}
|
||||
|
||||
private final List<ByteBuffer> allocated = new ArrayList<>();
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
GpuCulling.setMode(GpuCullingMode.CPU_ONLY);
|
||||
allocated.forEach(MemoryUtilities::memFree);
|
||||
allocated.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
void emittedRangesAreIdenticalAcrossCullModes() {
|
||||
final TerrainRenderPass renderPass = pass("solid");
|
||||
final RenderRegion region = region(0, 0, 0);
|
||||
final SectionRenderDataStorage storage = storage();
|
||||
writeSection(storage, 0, 0, 4, 0, 8, 4, 0, 0, 12);
|
||||
writeSection(storage, 5, 100, 0, 16, 0, 0, 4, 0, 0);
|
||||
attachStorage(region, renderPass, storage);
|
||||
final ChunkRenderListIterable renderLists = lists(renderList(region, 0, 5));
|
||||
final CameraTransform camera = new CameraTransform(0, 0, 0);
|
||||
|
||||
GpuCulling.setMode(GpuCullingMode.CPU_ONLY);
|
||||
final RecordingSink cpu = walk(renderLists, renderPass, camera, false);
|
||||
GpuCulling.setMode(GpuCullingMode.COMPUTE);
|
||||
final RecordingSink compute = walk(renderLists, renderPass, camera, false);
|
||||
|
||||
assertFalse(cpu.ranges.isEmpty(), "the walk produced nothing to compare");
|
||||
assertEquals(cpu.ranges.size(), compute.ranges.size(), "range count differs between cull modes");
|
||||
for (int i = 0; i < cpu.ranges.size(); i++) {
|
||||
assertArrayEqualsInt(cpu.ranges.get(i), compute.ranges.get(i), "range " + i);
|
||||
}
|
||||
assertEquals(1, cpu.regions.size(), "one region announced once");
|
||||
assertEquals(1, compute.regions.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void regionOffsetIsCameraRelative() {
|
||||
final TerrainRenderPass renderPass = pass("solid");
|
||||
final RenderRegion region = region(1, 0, 3);
|
||||
final SectionRenderDataStorage storage = storage();
|
||||
writeSection(storage, 0, 0, 4, 0, 0, 0, 0, 0, 0);
|
||||
attachStorage(region, renderPass, storage);
|
||||
final CameraTransform camera = new CameraTransform(70.25, 12.5, -3.75);
|
||||
|
||||
final RecordingSink sink = walk(lists(renderList(region, 0)), renderPass, camera, false);
|
||||
|
||||
assertEquals(1, sink.regions.size());
|
||||
final float[] offset = sink.regions.get(0);
|
||||
assertEquals(region.getOriginX() - camera.intX - camera.fracX, offset[0], 0f, "x");
|
||||
assertEquals(region.getOriginY() - camera.intY - camera.fracY, offset[1], 0f, "y");
|
||||
assertEquals(region.getOriginZ() - camera.intZ - camera.fracZ, offset[2], 0f, "z");
|
||||
}
|
||||
|
||||
@Test
|
||||
void regionOffsetUsesTheRegionOriginNotA256BlockGrid() {
|
||||
final TerrainRenderPass renderPass = pass("solid");
|
||||
final RenderRegion region = region(1, 0, 0);
|
||||
final SectionRenderDataStorage storage = storage();
|
||||
writeSection(storage, 0, 0, 4, 0, 0, 0, 0, 0, 0);
|
||||
attachStorage(region, renderPass, storage);
|
||||
|
||||
final RecordingSink sink = walk(lists(renderList(region, 0)), renderPass, new CameraTransform(0, 0, 0), false);
|
||||
|
||||
assertEquals(128f, sink.regions.get(0)[0], 0f, "region 1 starts at block 128");
|
||||
}
|
||||
|
||||
@Test
|
||||
void contiguousFacingsCollapseToOneRange() {
|
||||
final TerrainRenderPass renderPass = pass("solid");
|
||||
final RenderRegion region = region(0, 0, 0);
|
||||
final SectionRenderDataStorage storage = storage();
|
||||
writeSection(storage, 0, 0, 4, 4, 4, 4, 4, 4, 4);
|
||||
attachStorage(region, renderPass, storage);
|
||||
|
||||
final RecordingSink sink = walk(lists(renderList(region, 0)), renderPass, new CameraTransform(0, 0, 0), false);
|
||||
|
||||
assertEquals(1, sink.ranges.size(), "seven adjacent facings are one vertex span, not seven dispatches");
|
||||
assertEquals(0, sink.ranges.get(0)[0]);
|
||||
assertEquals(28, sink.ranges.get(0)[1]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void gapsInTheFacingMaskSplitRuns() {
|
||||
final TerrainRenderPass renderPass = pass("solid");
|
||||
final RenderRegion region = region(0, 0, 0);
|
||||
final SectionRenderDataStorage storage = storage();
|
||||
writeSection(storage, 0, 0, 4, 0, 8, 0, 0, 0, 4);
|
||||
attachStorage(region, renderPass, storage);
|
||||
|
||||
final RecordingSink sink = walk(lists(renderList(region, 0)), renderPass, new CameraTransform(0, 0, 0), false);
|
||||
|
||||
assertEquals(3, sink.ranges.size());
|
||||
assertArrayEqualsInt(new int[]{0, 4}, sink.ranges.get(0), "facing 0");
|
||||
assertArrayEqualsInt(new int[]{4, 8}, sink.ranges.get(1), "facing 2");
|
||||
assertArrayEqualsInt(new int[]{12, 4}, sink.ranges.get(2), "facing 6");
|
||||
}
|
||||
|
||||
@Test
|
||||
void sectionsWithoutGeometryNeverAnnounceTheRegion() {
|
||||
final TerrainRenderPass renderPass = pass("solid");
|
||||
final RenderRegion region = region(0, 0, 0);
|
||||
final SectionRenderDataStorage storage = storage();
|
||||
writeSection(storage, 0, 0, 0, 0, 0, 0, 0, 0, 0);
|
||||
attachStorage(region, renderPass, storage);
|
||||
|
||||
final RecordingSink sink = walk(lists(renderList(region, 0)), renderPass, new CameraTransform(0, 0, 0), false);
|
||||
|
||||
assertTrue(sink.regions.isEmpty(), "an empty region must not open an encoder");
|
||||
assertTrue(sink.ranges.isEmpty());
|
||||
assertEquals(1, sink.finishes);
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingStorageForThePassIsSkipped() {
|
||||
final TerrainRenderPass renderPass = pass("solid");
|
||||
final RenderRegion region = region(0, 0, 0);
|
||||
|
||||
final RecordingSink sink = walk(lists(renderList(region, 0)), renderPass, new CameraTransform(0, 0, 0), false);
|
||||
|
||||
assertTrue(sink.ranges.isEmpty());
|
||||
assertEquals(1, sink.finishes);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unbindableRegionIsSkippedButThePassContinues() {
|
||||
final TerrainRenderPass renderPass = pass("solid");
|
||||
final RenderRegion regionA = region(0, 0, 0);
|
||||
final RenderRegion regionB = region(1, 0, 0);
|
||||
final SectionRenderDataStorage storageA = storage();
|
||||
final SectionRenderDataStorage storageB = storage();
|
||||
writeSection(storageA, 0, 0, 4, 0, 0, 0, 0, 0, 0);
|
||||
writeSection(storageB, 0, 0, 4, 0, 0, 0, 0, 0, 0);
|
||||
attachStorage(regionA, renderPass, storageA);
|
||||
attachStorage(regionB, renderPass, storageB);
|
||||
|
||||
final RecordingSink sink = new RecordingSink();
|
||||
sink.refuseRegion = true;
|
||||
new ShadowVoxelizer().walkPass(lists(renderList(regionA, 0), renderList(regionB, 0)), renderPass, null,
|
||||
new CameraTransform(0, 0, 0), new CameraTransform(0, 0, 0), false, sink);
|
||||
|
||||
assertTrue(sink.ranges.isEmpty(), "a region that cannot be bound emits nothing");
|
||||
assertEquals(1, sink.finishes, "the encoder is still closed exactly once");
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusedRangeSkipsOnlyThatRegion() {
|
||||
final TerrainRenderPass renderPass = pass("solid");
|
||||
final RenderRegion regionA = region(0, 0, 0);
|
||||
final RenderRegion regionB = region(1, 0, 0);
|
||||
final SectionRenderDataStorage storageA = storage();
|
||||
final SectionRenderDataStorage storageB = storage();
|
||||
writeSection(storageA, 0, 0, 4, 0, 4, 0, 0, 0, 0);
|
||||
writeSection(storageB, 0, 0, 4, 0, 0, 0, 0, 0, 0);
|
||||
attachStorage(regionA, renderPass, storageA);
|
||||
attachStorage(regionB, renderPass, storageB);
|
||||
|
||||
final RecordingSink sink = new RecordingSink() {
|
||||
@Override public boolean range(int vertexOffset, int vertexCount) {
|
||||
return regions.size() != 1 && super.range(vertexOffset, vertexCount);
|
||||
}
|
||||
};
|
||||
new ShadowVoxelizer().walkPass(lists(renderList(regionA, 0), renderList(regionB, 0)), renderPass, null, new CameraTransform(0, 0, 0), new CameraTransform(0, 0, 0), false, sink);
|
||||
|
||||
assertEquals(2, sink.regions.size(), "the second region is still attempted after the first is refused");
|
||||
assertEquals(1, sink.ranges.size(), "only the second region's range lands");
|
||||
assertEquals(1, sink.finishes);
|
||||
}
|
||||
|
||||
@Test
|
||||
void faceCullingNarrowsTheEmittedRangesTheSameWayInBothModes() {
|
||||
final TerrainRenderPass renderPass = pass("solid");
|
||||
final RenderRegion region = region(0, 0, 0);
|
||||
final SectionRenderDataStorage storage = storage();
|
||||
writeSection(storage, 0, 0, 4, 4, 4, 4, 4, 4, 4);
|
||||
attachStorage(region, renderPass, storage);
|
||||
final ChunkRenderListIterable renderLists = lists(renderList(region, 0));
|
||||
final CameraTransform camera = new CameraTransform(500, 200, 500);
|
||||
|
||||
GpuCulling.setMode(GpuCullingMode.CPU_ONLY);
|
||||
final RecordingSink cpu = walk(renderLists, renderPass, camera, true);
|
||||
GpuCulling.setMode(GpuCullingMode.COMPUTE);
|
||||
final RecordingSink compute = walk(renderLists, renderPass, camera, true);
|
||||
|
||||
assertFalse(cpu.ranges.isEmpty(), "face culling removed everything; the fixture is not exercising the path");
|
||||
assertTrue(cpu.ranges.size() < 7 || cpu.ranges.get(0)[1] < 28, "face culling did not narrow anything");
|
||||
assertEquals(cpu.ranges.size(), compute.ranges.size());
|
||||
for (int i = 0; i < cpu.ranges.size(); i++) {
|
||||
assertArrayEqualsInt(cpu.ranges.get(i), compute.ranges.get(i), "range " + i);
|
||||
}
|
||||
}
|
||||
|
||||
private static void assertArrayEqualsInt(int[] expected, int[] actual, String label) {
|
||||
assertEquals(expected[0], actual[0], label + " vertexOffset");
|
||||
assertEquals(expected[1], actual[1], label + " vertexCount");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package com.prupe.mcpatcher.mal.biome;
|
||||
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import net.minecraft.world.IBlockAccess;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class BlockCachedColorMapTest {
|
||||
|
||||
private static final class CountingMap implements IColorMap {
|
||||
|
||||
private final float[] scratch = new float[3];
|
||||
int calls;
|
||||
|
||||
@Override
|
||||
public boolean isHeightDependent() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getColorMultiplier() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getColorMultiplier(IBlockAccess blockAccess, int i, int j, int k) {
|
||||
return ColorUtils.float3ToInt(getColorMultiplierF(blockAccess, i, j, k));
|
||||
}
|
||||
|
||||
@Override
|
||||
public float[] getColorMultiplierF(IBlockAccess blockAccess, int i, int j, int k) {
|
||||
calls++;
|
||||
scratch[0] = i;
|
||||
scratch[1] = j;
|
||||
scratch[2] = k;
|
||||
return scratch;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void claimResources(Collection<ResourceLocation> resources) {}
|
||||
|
||||
@Override
|
||||
public IColorMap copy() {
|
||||
return new CountingMap();
|
||||
}
|
||||
}
|
||||
|
||||
private final IBlockAccess world = Mockito.mock(IBlockAccess.class);
|
||||
|
||||
@Test
|
||||
void repeatQueriesHitTheCache() {
|
||||
final CountingMap parent = new CountingMap();
|
||||
final ColorMapBase.BlockCached cached = new ColorMapBase.BlockCached(parent);
|
||||
|
||||
final float[] first = cached.getColorMultiplierF(world, 10, 64, -3);
|
||||
assertEquals(1, parent.calls);
|
||||
assertArrayEquals(new float[] { 10, 64, -3 }, first);
|
||||
|
||||
cached.getColorMultiplierF(world, 10, 64, -3);
|
||||
assertEquals(1, parent.calls, "second query for the same block must not hit the parent");
|
||||
}
|
||||
|
||||
@Test
|
||||
void cachedValueSurvivesParentScratchReuse() {
|
||||
final CountingMap parent = new CountingMap();
|
||||
final ColorMapBase.BlockCached cached = new ColorMapBase.BlockCached(parent);
|
||||
|
||||
final float[] a = cached.getColorMultiplierF(world, 1, 64, 1);
|
||||
cached.getColorMultiplierF(world, 2, 64, 2);
|
||||
assertArrayEquals(new float[] { 1, 64, 1 }, a, "parent scratch reuse must not corrupt cached entries");
|
||||
assertArrayEquals(new float[] { 1, 64, 1 }, cached.getColorMultiplierF(world, 1, 64, 1));
|
||||
assertEquals(2, parent.calls);
|
||||
}
|
||||
|
||||
@Test
|
||||
void distinctCoordinatesAreDistinctEntries() {
|
||||
final CountingMap parent = new CountingMap();
|
||||
final ColorMapBase.BlockCached cached = new ColorMapBase.BlockCached(parent);
|
||||
|
||||
cached.getColorMultiplierF(world, -1, 64, 0);
|
||||
cached.getColorMultiplierF(world, 0, 64, -1);
|
||||
cached.getColorMultiplierF(world, -1, 63, 0);
|
||||
assertEquals(3, parent.calls, "negative/asymmetric coords must not collide in the packed key");
|
||||
}
|
||||
|
||||
@Test
|
||||
void worldChangeClearsTheCache() {
|
||||
final CountingMap parent = new CountingMap();
|
||||
final ColorMapBase.BlockCached cached = new ColorMapBase.BlockCached(parent);
|
||||
|
||||
cached.getColorMultiplierF(world, 5, 64, 5);
|
||||
assertEquals(1, parent.calls);
|
||||
|
||||
final IBlockAccess otherWorld = Mockito.mock(IBlockAccess.class);
|
||||
cached.getColorMultiplierF(otherWorld, 5, 64, 5);
|
||||
assertEquals(2, parent.calls, "a different world must not serve cached colors");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,10 @@
|
||||
package me.flashyreese.mods.reeses_sodium_options.util;
|
||||
|
||||
import java.util.Collection;
|
||||
import me.jellysquid.mods.sodium.client.gui.options.OptionFlag;
|
||||
import me.jellysquid.mods.sodium.client.gui.options.OptionImpact;
|
||||
import me.jellysquid.mods.sodium.client.gui.options.control.Control;
|
||||
import me.jellysquid.mods.sodium.client.gui.options.storage.OptionStorage;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import me.jellysquid.mods.sodium.client.gui.options.Option;
|
||||
import me.jellysquid.mods.sodium.client.gui.options.OptionPage;
|
||||
@@ -99,16 +104,16 @@ class StringUtilsTest {
|
||||
|
||||
@Override public String getName() { return name; }
|
||||
@Override public String getTooltip() { return tooltip; }
|
||||
@Override public me.jellysquid.mods.sodium.client.gui.options.OptionImpact getImpact() { return null; }
|
||||
@Override public me.jellysquid.mods.sodium.client.gui.options.control.Control<Object> getControl() { return null; }
|
||||
@Override public OptionImpact getImpact() { return null; }
|
||||
@Override public Control<Object> getControl() { return null; }
|
||||
@Override public Object getValue() { return null; }
|
||||
@Override public void setValue(Object value) {}
|
||||
@Override public void reset() {}
|
||||
@Override public me.jellysquid.mods.sodium.client.gui.options.storage.OptionStorage<?> getStorage() { return null; }
|
||||
@Override public OptionStorage<?> getStorage() { return null; }
|
||||
@Override public boolean isAvailable() { return true; }
|
||||
@Override public boolean hasChanged() { return false; }
|
||||
@Override public void applyChanges() {}
|
||||
@Override public java.util.Collection<me.jellysquid.mods.sodium.client.gui.options.OptionFlag> getFlags() { return List.of(); }
|
||||
@Override public Collection<OptionFlag> getFlags() { return List.of(); }
|
||||
}
|
||||
|
||||
private static class MockOptionPage extends OptionPage {
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
package net.coderbot.batchedentityrendering.impl;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuad;
|
||||
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
|
||||
import net.coderbot.batchedentityrendering.impl.SegmentedBufferBuilderTest.TestLayer;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class AngelicaBufferSourceTest {
|
||||
|
||||
private static final ModelQuad QUAD = SegmentedBufferBuilderTest.quad();
|
||||
|
||||
@Test
|
||||
void sameLayerKeepsBuilderAffinity() {
|
||||
final AngelicaBufferSource source = new AngelicaBufferSource();
|
||||
final TestLayer layer = new TestLayer("a", TransparencyType.OPAQUE);
|
||||
final SegmentedBufferBuilder first = source.getBuffer(layer, 1);
|
||||
first.addQuad(QUAD);
|
||||
final SegmentedBufferBuilder second = source.getBuffer(layer, 2);
|
||||
assertSame(first, second);
|
||||
}
|
||||
|
||||
@Test
|
||||
void prepareGroupsSegmentsByLayerAndSortsOpaqueById() {
|
||||
final AngelicaBufferSource source = new AngelicaBufferSource();
|
||||
final TestLayer opaque = new TestLayer("opaque", TransparencyType.OPAQUE);
|
||||
final TestLayer translucent = new TestLayer("translucent", TransparencyType.GENERAL_TRANSPARENT);
|
||||
|
||||
source.getBuffer(opaque, 7).addQuad(QUAD);
|
||||
source.getBuffer(translucent, 9).addQuad(QUAD);
|
||||
source.getBuffer(opaque, 3).addQuad(QUAD);
|
||||
source.getBuffer(translucent, 2).addQuad(QUAD);
|
||||
|
||||
final List<RenderLayer> order = source.prepare();
|
||||
assertEquals(2, order.size());
|
||||
|
||||
assertSame(opaque, order.get(0));
|
||||
assertSame(translucent, order.get(1));
|
||||
|
||||
final List<BufferSegment> opaqueSegments = source.segmentsFor(opaque);
|
||||
assertNotNull(opaqueSegments);
|
||||
assertEquals(2, opaqueSegments.size());
|
||||
assertEquals(3, opaqueSegments.get(0).getBlockEntityId());
|
||||
assertEquals(7, opaqueSegments.get(1).getBlockEntityId());
|
||||
|
||||
final List<BufferSegment> translucentSegments = source.segmentsFor(translucent);
|
||||
assertEquals(2, translucentSegments.size());
|
||||
assertEquals(9, translucentSegments.get(0).getBlockEntityId());
|
||||
assertEquals(2, translucentSegments.get(1).getBlockEntityId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void affinityEvictionLosesNoSegments() {
|
||||
final AngelicaBufferSource source = new AngelicaBufferSource();
|
||||
final int layers = 40;
|
||||
for (int i = 0; i < layers; i++) {
|
||||
source.getBuffer(new TestLayer("layer" + i, TransparencyType.OPAQUE), i).addQuad(QUAD);
|
||||
}
|
||||
final List<RenderLayer> order = source.prepare();
|
||||
assertEquals(layers, order.size());
|
||||
int segments = 0;
|
||||
for (RenderLayer layer : order) {
|
||||
segments += source.segmentsFor(layer).size();
|
||||
}
|
||||
assertEquals(layers, segments);
|
||||
}
|
||||
|
||||
@Test
|
||||
void endBatchWithTypeCompactsOrder() {
|
||||
final AngelicaBufferSource source = new AngelicaBufferSource();
|
||||
final TestLayer opaqueA = new TestLayer("oa", TransparencyType.OPAQUE);
|
||||
final TestLayer translucent = new TestLayer("t", TransparencyType.GENERAL_TRANSPARENT);
|
||||
final TestLayer opaqueB = new TestLayer("ob", TransparencyType.OPAQUE);
|
||||
source.declareUse(opaqueA);
|
||||
source.declareUse(translucent);
|
||||
source.declareUse(opaqueB);
|
||||
|
||||
source.endBatchWithType(TransparencyType.OPAQUE, null);
|
||||
|
||||
final List<RenderLayer> remaining = source.prepare();
|
||||
assertEquals(1, remaining.size());
|
||||
assertSame(translucent, remaining.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void declaredLayersAppearInOrderWithoutSegments() {
|
||||
final AngelicaBufferSource source = new AngelicaBufferSource();
|
||||
final TestLayer retainedOnly = new TestLayer("retained", TransparencyType.OPAQUE);
|
||||
source.declareUse(retainedOnly);
|
||||
final List<RenderLayer> order = source.prepare();
|
||||
assertEquals(1, order.size());
|
||||
assertSame(retainedOnly, order.get(0));
|
||||
assertTrue(source.isEmpty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package net.coderbot.batchedentityrendering.impl;
|
||||
|
||||
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public final class BufferSourceProbe {
|
||||
|
||||
private BufferSourceProbe() {}
|
||||
|
||||
public static List<RenderLayer> prepare(AngelicaBufferSource source) {
|
||||
return source.prepare();
|
||||
}
|
||||
|
||||
public static List<BufferSegment> segmentsFor(AngelicaBufferSource source, RenderLayer layer) {
|
||||
return source.segmentsFor(layer);
|
||||
}
|
||||
}
|
||||
+263
@@ -0,0 +1,263 @@
|
||||
package net.coderbot.batchedentityrendering.impl;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuad;
|
||||
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
|
||||
import com.gtnewhorizons.angelica.rendering.tesr.TemplateBuffer;
|
||||
import org.joml.Matrix4f;
|
||||
import org.joml.Vector3f;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.List;
|
||||
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.COLOR_INDEX;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.VERTEX_SIZE;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.X_INDEX;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class SegmentedBufferBuilderTest {
|
||||
|
||||
static final class TestLayer extends RenderLayer implements BlendingStateHolder {
|
||||
private final TransparencyType transparencyType;
|
||||
|
||||
TestLayer(String name, TransparencyType transparencyType) {
|
||||
super(name, BatchVertexFormats.POSITION_COLOR_TEXTURE_LIGHTF_NORMAL, GL11.GL_QUADS, 256, () -> {}, () -> {});
|
||||
this.transparencyType = transparencyType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TransparencyType getTransparencyType() {
|
||||
return transparencyType;
|
||||
}
|
||||
}
|
||||
|
||||
static ModelQuad quad() {
|
||||
final ModelQuad q = new ModelQuad();
|
||||
for (int i = 0; i < 4; i++) {
|
||||
q.setX(i, i);
|
||||
q.setY(i, i);
|
||||
q.setZ(i, i);
|
||||
}
|
||||
return q;
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameKeyContinuesSegment() {
|
||||
final SegmentedBufferBuilder builder = new SegmentedBufferBuilder();
|
||||
final TestLayer layer = new TestLayer("a", TransparencyType.OPAQUE);
|
||||
builder.begin(layer, 5);
|
||||
builder.addQuad(quad());
|
||||
builder.begin(layer, 5);
|
||||
builder.addQuad(quad());
|
||||
final List<BufferSegment> segments = builder.getSegments();
|
||||
assertEquals(1, segments.size());
|
||||
assertEquals(0, segments.get(0).getFirstVertex());
|
||||
assertEquals(8, segments.get(0).getVertexCount());
|
||||
assertEquals(5, segments.get(0).getBlockEntityId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void keyChangeSplitsSegments() {
|
||||
final SegmentedBufferBuilder builder = new SegmentedBufferBuilder();
|
||||
final TestLayer a = new TestLayer("a", TransparencyType.OPAQUE);
|
||||
final TestLayer b = new TestLayer("b", TransparencyType.OPAQUE);
|
||||
builder.begin(a, 1);
|
||||
builder.addQuad(quad());
|
||||
builder.begin(a, 2);
|
||||
builder.addQuad(quad());
|
||||
builder.addQuad(quad());
|
||||
builder.begin(b, 2);
|
||||
builder.addQuad(quad());
|
||||
final List<BufferSegment> segments = builder.getSegments();
|
||||
assertEquals(3, segments.size());
|
||||
assertEquals(0, segments.get(0).getFirstVertex());
|
||||
assertEquals(4, segments.get(0).getVertexCount());
|
||||
assertEquals(1, segments.get(0).getBlockEntityId());
|
||||
assertEquals(4, segments.get(1).getFirstVertex());
|
||||
assertEquals(8, segments.get(1).getVertexCount());
|
||||
assertEquals(2, segments.get(1).getBlockEntityId());
|
||||
assertEquals(0, segments.get(2).getFirstVertex());
|
||||
assertEquals(4, segments.get(2).getVertexCount());
|
||||
assertEquals(b, segments.get(2).getRenderType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptySegmentsAreDropped() {
|
||||
final SegmentedBufferBuilder builder = new SegmentedBufferBuilder();
|
||||
final TestLayer a = new TestLayer("a", TransparencyType.OPAQUE);
|
||||
final TestLayer b = new TestLayer("b", TransparencyType.OPAQUE);
|
||||
builder.begin(a, 1);
|
||||
builder.begin(b, 1);
|
||||
builder.addQuad(quad());
|
||||
final List<BufferSegment> segments = builder.getSegments();
|
||||
assertEquals(1, segments.size());
|
||||
assertEquals(b, segments.get(0).getRenderType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void bufferGrowsPastInitialCapacity() {
|
||||
final SegmentedBufferBuilder builder = new SegmentedBufferBuilder();
|
||||
final TestLayer layer = new TestLayer("a", TransparencyType.OPAQUE);
|
||||
builder.begin(layer, 1);
|
||||
final ModelQuad q = quad();
|
||||
final int quads = 3000; // 3000 * 4 * 32B ~ 384KB > 256KB initial
|
||||
for (int i = 0; i < quads; i++) {
|
||||
builder.addQuad(q);
|
||||
}
|
||||
final List<BufferSegment> segments = builder.getSegments();
|
||||
assertEquals(1, segments.size());
|
||||
assertEquals(quads * 4, segments.get(0).getVertexCount());
|
||||
assertEquals(quads * 4, builder.getVertexCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetClearsFillState() {
|
||||
final SegmentedBufferBuilder builder = new SegmentedBufferBuilder();
|
||||
final TestLayer layer = new TestLayer("a", TransparencyType.OPAQUE);
|
||||
builder.begin(layer, 1);
|
||||
builder.addQuad(quad());
|
||||
builder.reset();
|
||||
assertTrue(builder.isEmpty());
|
||||
assertEquals(0, builder.getSegments().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void addTemplateInstanceTransformsAndExtendsSegment() {
|
||||
final SegmentedBufferBuilder builder = new SegmentedBufferBuilder();
|
||||
final TestLayer layer = new TestLayer("a", TransparencyType.OPAQUE);
|
||||
|
||||
builder.begin(layer, 3);
|
||||
builder.addTemplateInstance(template(), new Matrix4f().translation(10f, 20f, 30f), new Vector3f(), -1, 0, null);
|
||||
builder.addQuad(quad());
|
||||
|
||||
final List<BufferSegment> segments = builder.getSegments();
|
||||
assertEquals(1, segments.size());
|
||||
assertEquals(0, segments.get(0).getFirstVertex());
|
||||
assertEquals(8, segments.get(0).getVertexCount());
|
||||
assertEquals(3, segments.get(0).getBlockEntityId());
|
||||
|
||||
final ByteBuffer buffer = segments.get(0).getOwner().buffer;
|
||||
final int stride = layer.getVertexFormat().getVertexSize();
|
||||
for (int v = 0; v < 4; v++) {
|
||||
assertEquals(10f + v, buffer.getFloat(v * stride), 1e-6f, "x of vertex " + v);
|
||||
assertEquals(20f, buffer.getFloat(v * stride + 4), 1e-6f, "y of vertex " + v);
|
||||
assertEquals(30f, buffer.getFloat(v * stride + 8), 1e-6f, "z of vertex " + v);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void reclaimFreesIdleLayerBuffers() {
|
||||
final SegmentedBufferBuilder builder = new SegmentedBufferBuilder();
|
||||
final TestLayer layer = new TestLayer("a", TransparencyType.OPAQUE);
|
||||
final long t0 = 100_000L;
|
||||
|
||||
builder.begin(layer, 1);
|
||||
builder.addQuad(quad());
|
||||
builder.resetAndReclaim(t0, 10_000L);
|
||||
assertEquals(1, builder.bufferCount(), "used buffer survives its own batch");
|
||||
|
||||
builder.resetAndReclaim(t0 + 5_000L, 10_000L);
|
||||
assertEquals(1, builder.bufferCount(), "unused buffer survives within the idle window");
|
||||
|
||||
builder.resetAndReclaim(t0 + 10_001L, 10_000L);
|
||||
assertEquals(0, builder.bufferCount(), "buffer idle past the window is freed");
|
||||
}
|
||||
|
||||
@Test
|
||||
void allocatedBytesTracksBufferLifecycle() {
|
||||
final SegmentedBufferBuilder builder = new SegmentedBufferBuilder();
|
||||
final TestLayer a = new TestLayer("a", TransparencyType.OPAQUE);
|
||||
final TestLayer b = new TestLayer("b", TransparencyType.OPAQUE);
|
||||
final long t0 = 100_000L;
|
||||
assertEquals(0L, builder.allocatedBytes());
|
||||
|
||||
builder.begin(a, 1);
|
||||
builder.addQuad(quad());
|
||||
List<BufferSegment> segments = builder.getSegments();
|
||||
final SegmentedBufferBuilder.LayerBuffer aBuffer = segments.get(0).getOwner();
|
||||
final long aInitial = aBuffer.buffer.capacity();
|
||||
assertEquals(aInitial, builder.allocatedBytes(), "creation adds initial capacity");
|
||||
|
||||
builder.begin(a, 1);
|
||||
final ModelQuad q = quad();
|
||||
for (int i = 0; i < 3000; i++) {
|
||||
builder.addQuad(q);
|
||||
}
|
||||
builder.begin(b, 1);
|
||||
builder.addQuad(q);
|
||||
segments = builder.getSegments();
|
||||
final SegmentedBufferBuilder.LayerBuffer bBuffer = segments.get(segments.size() - 1).getOwner();
|
||||
final long aGrown = aBuffer.buffer.capacity();
|
||||
assertTrue(aGrown > aInitial, "layer a buffer grew");
|
||||
assertEquals(aGrown + bBuffer.buffer.capacity(), builder.allocatedBytes(), "growth adds capacity delta");
|
||||
|
||||
builder.resetAndReclaim(t0, 10_000L);
|
||||
assertEquals(aGrown + bBuffer.buffer.capacity(), builder.allocatedBytes(), "reclaim without eviction keeps bytes");
|
||||
|
||||
builder.resetAndReclaim(t0 + 10_001L, 10_000L);
|
||||
assertEquals(0L, builder.allocatedBytes(), "eviction subtracts capacity");
|
||||
|
||||
builder.begin(a, 1);
|
||||
builder.addQuad(q);
|
||||
assertEquals(aInitial, builder.allocatedBytes(), "recreation adds fresh capacity");
|
||||
builder.freeAll();
|
||||
assertEquals(0L, builder.allocatedBytes(), "freeAll zeroes");
|
||||
}
|
||||
|
||||
@Test
|
||||
void evictionThenReuseKeepsStateConsistent() {
|
||||
final SegmentedBufferBuilder builder = new SegmentedBufferBuilder();
|
||||
final TestLayer a = new TestLayer("a", TransparencyType.OPAQUE);
|
||||
final TestLayer b = new TestLayer("b", TransparencyType.OPAQUE);
|
||||
final long t0 = 100_000L;
|
||||
|
||||
builder.begin(a, 1);
|
||||
builder.addQuad(quad());
|
||||
builder.begin(b, 1);
|
||||
builder.addQuad(quad());
|
||||
builder.resetAndReclaim(t0, 10_000L);
|
||||
assertEquals(2, builder.bufferCount());
|
||||
|
||||
builder.resetAndReclaim(t0 + 10_001L, 10_000L);
|
||||
assertEquals(0, builder.bufferCount());
|
||||
assertEquals(0L, builder.allocatedBytes());
|
||||
assertTrue(builder.isEmpty());
|
||||
|
||||
builder.begin(a, 2);
|
||||
builder.addQuad(quad());
|
||||
final List<BufferSegment> segments = builder.getSegments();
|
||||
assertEquals(1, segments.size());
|
||||
assertEquals(2, segments.get(0).getBlockEntityId());
|
||||
assertEquals(1, builder.bufferCount());
|
||||
assertTrue(builder.allocatedBytes() > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void freeAllReleasesBuffersAndStaysUsable() {
|
||||
final SegmentedBufferBuilder builder = new SegmentedBufferBuilder();
|
||||
final TestLayer layer = new TestLayer("a", TransparencyType.OPAQUE);
|
||||
|
||||
builder.begin(layer, 1);
|
||||
builder.addQuad(quad());
|
||||
builder.freeAll();
|
||||
assertTrue(builder.isEmpty());
|
||||
assertEquals(0, builder.bufferCount());
|
||||
|
||||
builder.begin(layer, 1);
|
||||
builder.addQuad(quad());
|
||||
assertEquals(1, builder.getSegments().size());
|
||||
}
|
||||
|
||||
static TemplateBuffer template() {
|
||||
final int[] data = new int[4 * VERTEX_SIZE];
|
||||
for (int v = 0; v < 4; v++) {
|
||||
final int base = v * VERTEX_SIZE;
|
||||
data[base + X_INDEX] = Float.floatToRawIntBits(v);
|
||||
data[base + COLOR_INDEX] = 0xFFFFFFFF;
|
||||
}
|
||||
return new TemplateBuffer(data, 4, GL11.GL_QUADS);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package net.coderbot.iris.gl.uniform;
|
||||
|
||||
import com.gtnewhorizons.angelica.glsm.shader.UniformType;
|
||||
import org.joml.Vector3f;
|
||||
import org.joml.Vector3fc;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.ONCE;
|
||||
import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME;
|
||||
import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_TICK;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class ManifestCollectingHolderTest {
|
||||
|
||||
private static void declare(UniformHolder h) {
|
||||
final Vector3fc zero = new Vector3f();
|
||||
h.uniform1f(PER_FRAME, "frameTimeCounter", () -> 0.0f)
|
||||
.uniform1f(ONCE, "pi", () -> 3.14159f)
|
||||
.uniform3f(PER_FRAME, "cameraPosition", () -> zero)
|
||||
.uniform1i(PER_TICK, "worldTime", () -> 0)
|
||||
.uniform1f(PER_FRAME, "rainStrength", () -> 0.0f)
|
||||
.externallyManagedUniform("iris_ModelViewMatrix", UniformType.MAT4);
|
||||
}
|
||||
|
||||
private static UniformManifest harvest() {
|
||||
final ManifestCollectingHolder h = new ManifestCollectingHolder();
|
||||
declare(h);
|
||||
return h.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupsByFrequencyPreservingRegistrationOrderWithinGroup() {
|
||||
final List<UniformManifest.Entry> e = harvest().entries();
|
||||
|
||||
assertEquals(List.of("pi", "worldTime", "frameTimeCounter", "cameraPosition", "rainStrength"),
|
||||
e.stream().map(UniformManifest.Entry::name).toList(),
|
||||
"ONCE then PER_TICK then PER_FRAME, declaration order inside each group");
|
||||
|
||||
assertEquals(List.of(ONCE, PER_TICK, PER_FRAME, PER_FRAME, PER_FRAME),
|
||||
e.stream().map(UniformManifest.Entry::frequency).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void capturesDeclaredTypes() {
|
||||
final UniformManifest m = harvest();
|
||||
assertEquals(UniformType.VEC3, entry(m, "cameraPosition").type());
|
||||
assertEquals(UniformType.FLOAT, entry(m, "frameTimeCounter").type());
|
||||
assertEquals(UniformType.INT, entry(m, "worldTime").type());
|
||||
}
|
||||
|
||||
@Test
|
||||
void isDeterministicAcrossHarvests() {
|
||||
assertEquals(harvest().entries(), harvest().entries());
|
||||
}
|
||||
|
||||
@Test
|
||||
void externallyManagedUniformsStayOutOfTheBlock() {
|
||||
final UniformManifest m = harvest();
|
||||
assertTrue(m.externallyManagedNames().contains("iris_ModelViewMatrix"));
|
||||
assertFalse(m.entries().stream().anyMatch(e -> e.name().equals("iris_ModelViewMatrix")), "per-draw matrices are written by the backend and must remain loose uniforms");
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateDeclarationIsDroppedNotDuplicated() {
|
||||
final ManifestCollectingHolder h = new ManifestCollectingHolder();
|
||||
h.uniform1f(PER_FRAME, "rainStrength", () -> 0.0f);
|
||||
h.uniform1f(ONCE, "rainStrength", () -> 1.0f);
|
||||
|
||||
final List<UniformManifest.Entry> e = h.build().entries();
|
||||
assertEquals(1, e.size());
|
||||
assertEquals(PER_FRAME, e.get(0).frequency(), "first declaration wins");
|
||||
}
|
||||
|
||||
private static UniformManifest.Entry entry(UniformManifest m, String name) {
|
||||
return m.entries().stream().filter(x -> x.name().equals(name)).findFirst().orElseThrow();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package net.coderbot.iris.pipeline;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class MvBuiltinScanTest {
|
||||
|
||||
@Test
|
||||
void detectsVariableUsage() {
|
||||
String frag = "#version 120\nvoid main() { vec4 p = gl_ModelViewMatrix * vec4(1.0); gl_FragColor = p; }";
|
||||
assertTrue(DeferredWorldRenderingPipeline.referencesMvBuiltins(frag));
|
||||
}
|
||||
|
||||
@Test
|
||||
void detectsFtransformCall() {
|
||||
String vert = "#version 120\nvoid main() { gl_Position = ftransform(); }";
|
||||
assertTrue(DeferredWorldRenderingPipeline.referencesMvBuiltins(vert));
|
||||
}
|
||||
|
||||
@Test
|
||||
void ignoresCommentsAndUnrelated() {
|
||||
String frag = "#version 120\n// gl_ModelViewMatrix in a comment only\nvoid main() { gl_FragColor = vec4(1.0); }";
|
||||
assertFalse(DeferredWorldRenderingPipeline.referencesMvBuiltins(frag));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullSourceIsClean() {
|
||||
assertFalse(DeferredWorldRenderingPipeline.referencesMvBuiltins(null));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package net.coderbot.iris.pipeline;
|
||||
|
||||
import net.coderbot.iris.shadows.ShadowGraphGate;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class ShadowGraphGateTest {
|
||||
|
||||
@Test
|
||||
void nanAlwaysDirty() {
|
||||
assertTrue(ShadowGraphGate.shouldMarkDirty(Float.NaN, 0.25f));
|
||||
}
|
||||
|
||||
@Test
|
||||
void smallDeltaClean() {
|
||||
assertFalse(ShadowGraphGate.shouldMarkDirty(0.25f, 0.25f + 0.0004f));
|
||||
assertFalse(ShadowGraphGate.shouldMarkDirty(0.25f, 0.25f - 0.0004f));
|
||||
}
|
||||
|
||||
@Test
|
||||
void thresholdDeltaDirty() {
|
||||
assertTrue(ShadowGraphGate.shouldMarkDirty(0.25f, 0.25f + 0.001f));
|
||||
assertTrue(ShadowGraphGate.shouldMarkDirty(0.25f, 0.25f - 0.001f));
|
||||
}
|
||||
|
||||
@Test
|
||||
void wrapAroundIsNotADiscontinuity() {
|
||||
assertFalse(ShadowGraphGate.shouldMarkDirty(0.9999f, 0.0001f), "0.0002 across the wrap is below threshold");
|
||||
assertTrue(ShadowGraphGate.shouldMarkDirty(0.999f, 0.0006f), "0.0016 across the wrap is above threshold");
|
||||
assertFalse(ShadowGraphGate.shouldMarkDirty(0.0001f, 0.9999f), "wrap works in both directions");
|
||||
}
|
||||
}
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
package net.coderbot.iris.pipeline.transform;
|
||||
|
||||
import com.gtnewhorizons.angelica.glsm.RenderSystem;
|
||||
import com.gtnewhorizons.angelica.glsm.testutil.Reflect;
|
||||
import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.taumc.glsl.ShaderParser;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class AttributeTransformerInstancedTest {
|
||||
|
||||
private static final InputAvailability TEX_LM = new InputAvailability(true, true);
|
||||
|
||||
private static final String VERTEX = """
|
||||
#version 120
|
||||
attribute vec4 mc_Entity;
|
||||
attribute vec4 mc_midTexCoord;
|
||||
varying vec2 texcoord;
|
||||
varying vec2 lmcoord;
|
||||
varying vec4 color;
|
||||
varying float mats;
|
||||
varying vec2 midtex;
|
||||
varying vec3 nrm;
|
||||
void main() {
|
||||
texcoord = (gl_TextureMatrix[0] * gl_MultiTexCoord0).xy;
|
||||
lmcoord = (gl_TextureMatrix[1] * gl_MultiTexCoord1).xy;
|
||||
color = gl_Color;
|
||||
mats = mc_Entity.x;
|
||||
midtex = mc_midTexCoord.st;
|
||||
nrm = normalize(gl_NormalMatrix * gl_Normal);
|
||||
gl_Position = ftransform();
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String VERTEX_MV_INVERSE = """
|
||||
#version 120
|
||||
varying vec3 wpos;
|
||||
void main() {
|
||||
wpos = (gl_ModelViewMatrixInverse * (gl_ModelViewMatrix * gl_Vertex)).xyz;
|
||||
gl_Position = gl_ProjectionMatrix * gl_ModelViewMatrix * gl_Vertex;
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String FRAGMENT = """
|
||||
#version 120
|
||||
varying vec4 color;
|
||||
void main() {
|
||||
gl_FragData[0] = color;
|
||||
}
|
||||
""";
|
||||
|
||||
@BeforeAll
|
||||
static void initShaderTransformer() throws Exception {
|
||||
Reflect.setStatic(RenderSystem.class, "maxGlslVersion", 460);
|
||||
ShaderTransformer.init();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void clearCaches() {
|
||||
TransformPatcher.clearCache();
|
||||
ShaderTransformer.clearCache();
|
||||
}
|
||||
|
||||
private static String instancedVertex(String vertex) {
|
||||
Map<PatchShaderType, String> result = TransformPatcher.patchAttributesInstanced(vertex, null, null, null, FRAGMENT, TEX_LM, false);
|
||||
assertNotNull(result);
|
||||
String v = result.get(PatchShaderType.VERTEX);
|
||||
assertNotNull(v);
|
||||
ShaderParser.parseShader(v);
|
||||
return v;
|
||||
}
|
||||
|
||||
private static String squash(String s) {
|
||||
return s.replaceAll("\\s+", "");
|
||||
}
|
||||
|
||||
private static void assertHas(String shader, String snippet) {
|
||||
assertTrue(squash(shader).contains(squash(snippet)), "expected snippet: " + snippet);
|
||||
}
|
||||
|
||||
private static void assertLacks(String shader, String snippet) {
|
||||
assertFalse(squash(shader).contains(squash(snippet)), "unexpected snippet: " + snippet);
|
||||
}
|
||||
|
||||
private static int indexOfSquashed(String shader, String snippet) {
|
||||
return squash(shader).indexOf(squash(snippet));
|
||||
}
|
||||
|
||||
@Test
|
||||
void declaresInstanceAttribsAndGlobalMatrices() {
|
||||
final String v = instancedVertex(VERTEX);
|
||||
assertHas(v, "layout(location = 7) in vec4 iris_InstMat0");
|
||||
assertHas(v, "layout(location = 8) in vec4 iris_InstMat1");
|
||||
assertHas(v, "layout(location = 9) in vec4 iris_InstMat2");
|
||||
assertHas(v, "layout(location = 10) in vec4 iris_InstMat3");
|
||||
assertHas(v, "layout(location = 11) in vec4 iris_InstColor");
|
||||
assertHas(v, "layout(location = 12) in vec2 iris_InstLightmap");
|
||||
assertLacks(v, "uniform mat4 iris_ModelViewMatrix;");
|
||||
assertLacks(v, "uniform mat3 iris_NormalMatrix;");
|
||||
assertHas(v, "mat4 iris_ModelViewMatrix;");
|
||||
assertHas(v, "iris_ModelViewMatrix = mat4(iris_InstMat0, iris_InstMat1, iris_InstMat2, iris_InstMat3)");
|
||||
assertHas(v, "iris_NormalMatrix = mat3(normalize(iris_InstMat0.xyz), normalize(iris_InstMat1.xyz), normalize(iris_InstMat2.xyz))");
|
||||
}
|
||||
|
||||
@Test
|
||||
void lightmapComesFromInstanceAttribute() {
|
||||
final String v = instancedVertex(VERTEX);
|
||||
assertLacks(v, "layout(location = 3)");
|
||||
assertHas(v, "iris_MultiTexCoord1 = vec4(iris_InstLightmap, 0.0, 1.0)");
|
||||
assertHas(v, "iris_LightmapTextureMatrix * iris_MultiTexCoord1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void colorComposesInstanceColor() {
|
||||
assertHas(instancedVertex(VERTEX), "iris_Color * iris_ColorModulator * iris_InstColor");
|
||||
}
|
||||
|
||||
@Test
|
||||
void foldsEntityAndMidTexCoordAttributes() {
|
||||
final String v = instancedVertex(VERTEX);
|
||||
assertLacks(v, "mc_Entity");
|
||||
assertLacks(v, "mc_midTexCoord");
|
||||
assertHas(v, "vec4(-1.0, -1.0, 0.0, 1.0)");
|
||||
assertHas(v, "vec4(0.5, 0.5, 0.0, 1.0)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void mvInverseOnlyWhenReferenced() {
|
||||
assertLacks(instancedVertex(VERTEX), "inverse(iris_ModelViewMatrix)");
|
||||
|
||||
final String with = instancedVertex(VERTEX_MV_INVERSE);
|
||||
assertHas(with, "iris_ModelViewMatrixInverse = inverse(iris_ModelViewMatrix)");
|
||||
assertLacks(with, "uniform mat4 iris_ModelViewMatrixInverse;");
|
||||
}
|
||||
|
||||
@Test
|
||||
void assignmentBlockRunsFirstInMain() {
|
||||
final String v = instancedVertex(VERTEX);
|
||||
final int mainIdx = indexOfSquashed(v, "void main()");
|
||||
final int assignIdx = indexOfSquashed(v, "iris_ModelViewMatrix = mat4(");
|
||||
final int bodyUseIdx = indexOfSquashed(v, "iris_TextureMatrix * iris_MultiTexCoord0");
|
||||
assertTrue(mainIdx >= 0 && assignIdx > mainIdx);
|
||||
assertTrue(bodyUseIdx > assignIdx);
|
||||
}
|
||||
|
||||
@Test
|
||||
void standardPathUnchanged() {
|
||||
Map<PatchShaderType, String> result = TransformPatcher.patchAttributes(VERTEX, null, null, null, FRAGMENT, TEX_LM, false);
|
||||
assertNotNull(result);
|
||||
final String v = result.get(PatchShaderType.VERTEX);
|
||||
assertHas(v, "uniform mat4 iris_ModelViewMatrix;");
|
||||
assertHas(v, "layout(location = 3) in vec4 iris_MultiTexCoord1");
|
||||
assertHas(v, "mc_Entity");
|
||||
assertLacks(v, "iris_InstMat0");
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
package net.coderbot.iris.pipeline.transform;
|
||||
|
||||
import com.gtnewhorizons.angelica.glsm.RenderSystem;
|
||||
import com.gtnewhorizons.angelica.glsm.testutil.Reflect;
|
||||
import it.unimi.dsi.fastutil.objects.Object2ObjectMaps;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class DHGenericAttributeLocationTest {
|
||||
|
||||
private static final Map<String, Integer> EXPECTED = new LinkedHashMap<>();
|
||||
static {
|
||||
EXPECTED.put("vPosition", DHGenericTransformer.DH_GENERIC_LOC_POSITION);
|
||||
EXPECTED.put("iris_color", DHGenericTransformer.DH_GENERIC_LOC_COLOR);
|
||||
EXPECTED.put("aScale", DHGenericTransformer.DH_GENERIC_LOC_SCALE);
|
||||
EXPECTED.put("aTranslateChunk", DHGenericTransformer.DH_GENERIC_LOC_TRANSLATE_CHUNK);
|
||||
EXPECTED.put("aTranslateSubChunk", DHGenericTransformer.DH_GENERIC_LOC_TRANSLATE_SUB_CHUNK);
|
||||
EXPECTED.put("aMaterial", DHGenericTransformer.DH_GENERIC_LOC_MATERIAL);
|
||||
}
|
||||
|
||||
private static final String VERTEX = """
|
||||
#version 330 core
|
||||
out vec4 col;
|
||||
void main() {
|
||||
col = vec4(1.0);
|
||||
gl_Position = vec4(0.0);
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String FRAGMENT = """
|
||||
#version 330 core
|
||||
in vec4 col;
|
||||
void main() {
|
||||
gl_FragData[0] = col;
|
||||
}
|
||||
""";
|
||||
|
||||
@BeforeAll
|
||||
static void initShaderTransformer() throws Exception {
|
||||
Reflect.setStatic(RenderSystem.class, "maxGlslVersion", 460);
|
||||
ShaderTransformer.init();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void clearCaches() {
|
||||
TransformPatcher.clearCache();
|
||||
ShaderTransformer.clearCache();
|
||||
}
|
||||
|
||||
private static String patchedVertex() {
|
||||
final Map<PatchShaderType, String> result = TransformPatcher.patchDHGeneric("dh_generic_test", VERTEX, null, null, null, FRAGMENT, Object2ObjectMaps.emptyMap());
|
||||
assertNotNull(result);
|
||||
final String v = result.get(PatchShaderType.VERTEX);
|
||||
assertNotNull(v);
|
||||
return v;
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyDhGenericInputCarriesItsAuthoritativeLocation() {
|
||||
final String vertex = patchedVertex();
|
||||
|
||||
for (Map.Entry<String, Integer> e : EXPECTED.entrySet()) {
|
||||
final Matcher m = Pattern
|
||||
.compile("layout\\s*\\(\\s*location\\s*=\\s*(\\d+)\\s*\\)\\s*in\\s+\\w+\\s+" + e.getKey() + "\\s*;")
|
||||
.matcher(vertex);
|
||||
assertTrue(m.find(), () -> "no explicit location for '" + e.getKey() + "' in:\n" + vertex);
|
||||
assertEquals(e.getValue().intValue(), Integer.parseInt(m.group(1)), () -> e.getKey() + " must sit at DH's hardcoded index");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void noDhGenericInputIsLeftUnlocated() {
|
||||
final String vertex = patchedVertex();
|
||||
|
||||
for (String name : EXPECTED.keySet()) {
|
||||
final Matcher bare = Pattern.compile("(?m)^\\s*in\\s+\\w+\\s+" + name + "\\s*;").matcher(vertex);
|
||||
assertTrue(!bare.find(), () -> "'" + name + "' declared without a location in:\n" + vertex);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void locationsAreABijection() {
|
||||
assertEquals(EXPECTED.size(), EXPECTED.values().stream().distinct().count(), "two inputs sharing a location would collide at link time");
|
||||
assertEquals(0, EXPECTED.values().stream().min(Integer::compare).orElseThrow().intValue());
|
||||
assertEquals(5, EXPECTED.values().stream().max(Integer::compare).orElseThrow().intValue());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package net.coderbot.iris.pipeline.transform;
|
||||
|
||||
import org.taumc.glsl.ShaderParser;
|
||||
import org.taumc.glsl.grammar.GLSLParser;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class GlslAstHelpersTest {
|
||||
|
||||
@Test void zeroLiteralFor_basicTypes() {
|
||||
assertEquals("vec4(0.0)", GlslAstHelpers.zeroLiteralFor("image2D"));
|
||||
assertEquals("ivec4(0)", GlslAstHelpers.zeroLiteralFor("iimage2D"));
|
||||
assertEquals("uvec4(0u)", GlslAstHelpers.zeroLiteralFor("uimage3D"));
|
||||
assertEquals("vec4(0.0)", GlslAstHelpers.zeroLiteralFor("image1D"));
|
||||
assertEquals("vec4(0.0)", GlslAstHelpers.zeroLiteralFor(null));
|
||||
}
|
||||
|
||||
@Test void componentTypeFor_basicTypes() {
|
||||
assertEquals("vec4", GlslAstHelpers.componentTypeFor("image3D"));
|
||||
assertEquals("ivec4", GlslAstHelpers.componentTypeFor("iimage1D"));
|
||||
assertEquals("uvec4", GlslAstHelpers.componentTypeFor("uimage2D"));
|
||||
}
|
||||
|
||||
@Test void firstArgIdentifier_returnsCalleeFirstArg() {
|
||||
final var snippet = ShaderParser.parseSnippet("imageStore(target_img, ivec2(0), uvec4(0u))",
|
||||
GLSLParser::postfix_expression);
|
||||
assertEquals("target_img", GlslAstHelpers.firstArgIdentifier(snippet));
|
||||
}
|
||||
|
||||
@Test void deleteStatementContaining_unlinksStmt() {
|
||||
final String src = "#version 460 core\nvoid main(){ int x = 1; imageStore(t, 0, 0); int y = 2; }";
|
||||
final var parsed = ShaderParser.parseShader(src);
|
||||
final var calls = GlslAstHelpers.collectAll(parsed.full(), GLSLParser.Postfix_expressionContext.class);
|
||||
GLSLParser.Postfix_expressionContext target = null;
|
||||
for (var c : calls) {
|
||||
if ("imageStore".equals(GlslAstHelpers.extractCallName(c))) { target = c; break; }
|
||||
}
|
||||
assertTrue(target != null, "expected to find imageStore call in synthetic source");
|
||||
final boolean removed = GlslAstHelpers.deleteStatementContaining(target);
|
||||
assertTrue(removed);
|
||||
final var remaining = GlslAstHelpers.collectAll(parsed.full(), GLSLParser.Postfix_expressionContext.class);
|
||||
for (var c : remaining) {
|
||||
assertFalse("imageStore".equals(GlslAstHelpers.extractCallName(c)), "imageStore call should no longer be reachable in the tree");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
package net.coderbot.iris.pipeline.transform;
|
||||
|
||||
import com.gtnewhorizons.angelica.glsm.RenderSystem;
|
||||
import com.gtnewhorizons.angelica.glsm.testutil.Reflect;
|
||||
import org.antlr.v4.runtime.tree.ParseTree;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.taumc.glsl.ShaderParser;
|
||||
import org.taumc.glsl.ShaderPrinter;
|
||||
import org.taumc.glsl.Transformer;
|
||||
import org.taumc.glsl.grammar.GLSLParser;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class LocalZeroInitTransformerTest {
|
||||
|
||||
private static int savedMaxGlsl;
|
||||
|
||||
@BeforeAll
|
||||
static void initShaderTransformer() {
|
||||
savedMaxGlsl = Reflect.getStatic(RenderSystem.class, "maxGlslVersion");
|
||||
Reflect.setStatic(RenderSystem.class, "maxGlslVersion", 460);
|
||||
ShaderTransformer.clearCache();
|
||||
ShaderTransformer.init();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void restoreCapabilities() {
|
||||
Reflect.setStatic(RenderSystem.class, "maxGlslVersion", savedMaxGlsl);
|
||||
ShaderTransformer.clearCache();
|
||||
TransformPatcher.clearCache();
|
||||
ShaderTransformer.init();
|
||||
}
|
||||
|
||||
private static final Set<String> NUMERIC = Set.of(
|
||||
"float", "int", "uint",
|
||||
"vec2", "vec3", "vec4", "ivec2", "ivec3", "ivec4", "uvec2", "uvec3", "uvec4",
|
||||
"mat2", "mat3", "mat4",
|
||||
"mat2x2", "mat2x3", "mat2x4", "mat3x2", "mat3x3", "mat3x4", "mat4x2", "mat4x3", "mat4x4");
|
||||
|
||||
private record Declarator(String type, String name) {}
|
||||
|
||||
private static String run(String src) {
|
||||
final Transformer t = new Transformer(ShaderParser.parseShader(src).full());
|
||||
LocalZeroInitTransformer.transform(t);
|
||||
final StringBuilder sb = new StringBuilder();
|
||||
t.mutateTree(tree -> sb.append(ShaderPrinter.getFormattedShader(tree)));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static List<Declarator> uninitialized(String src) {
|
||||
final ParseTree tree = ShaderParser.parseShader(src).full();
|
||||
final List<Declarator> out = new ArrayList<>();
|
||||
for (GLSLParser.Declaration_statementContext stmt : GlslAstHelpers.collectAll(tree, GLSLParser.Declaration_statementContext.class)) {
|
||||
final GLSLParser.DeclarationContext declaration = stmt.declaration();
|
||||
if (declaration == null) continue;
|
||||
final GLSLParser.Init_declarator_listContext list = declaration.init_declarator_list();
|
||||
if (list == null) continue;
|
||||
final GLSLParser.Single_declarationContext single = list.single_declaration();
|
||||
if (single == null) continue;
|
||||
final String type = single.fully_specified_type() == null ? "" : single.fully_specified_type().getText();
|
||||
|
||||
final List<GLSLParser.Typeless_declarationContext> declarators = new ArrayList<>();
|
||||
declarators.add(single.typeless_declaration());
|
||||
declarators.addAll(list.typeless_declaration());
|
||||
for (GLSLParser.Typeless_declarationContext d : declarators) {
|
||||
if (d == null || d.initializer() != null) continue;
|
||||
out.add(new Declarator(type, d.IDENTIFIER().getText()));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static boolean isUninitialized(String src, String name) {
|
||||
return uninitialized(src).stream().anyMatch(d -> d.name().equals(name));
|
||||
}
|
||||
|
||||
@Test
|
||||
void accumulatorGetsZeroInitializer() {
|
||||
final String src =
|
||||
"#version 460 core\n" +
|
||||
"out vec4 fragColor;\n" +
|
||||
"vec4 accumulate() {\n" +
|
||||
" vec4 lightVolume;\n" +
|
||||
" for (int i = 0; i < 8; i++) lightVolume += vec4(float(i));\n" +
|
||||
" return lightVolume;\n" +
|
||||
"}\n" +
|
||||
"void main() { fragColor = accumulate(); }\n";
|
||||
|
||||
assertTrue(isUninitialized(src, "lightVolume"), "fixture must start uninitialized");
|
||||
final String out = run(src);
|
||||
assertTrue(uninitialized(out).isEmpty(), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void existingInitializersAreLeftAlone() {
|
||||
final String src =
|
||||
"#version 460 core\n" +
|
||||
"void main() {\n" +
|
||||
" vec3 a = vec3(1.0, 2.0, 3.0);\n" +
|
||||
" float b = 4.0;\n" +
|
||||
"}\n";
|
||||
|
||||
final String out = run(src);
|
||||
assertTrue(out.contains("vec3(1.0, 2.0, 3.0)"), out);
|
||||
assertTrue(out.contains("4.0"), out);
|
||||
assertTrue(uninitialized(out).isEmpty(), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void multiDeclaratorListInitializesOnlyBareNames() {
|
||||
final String src =
|
||||
"#version 460 core\n" +
|
||||
"void main() {\n" +
|
||||
" vec3 a, b = vec3(1.0), c;\n" +
|
||||
" a += b; c += b;\n" +
|
||||
"}\n";
|
||||
|
||||
final String out = run(src);
|
||||
assertTrue(uninitialized(out).isEmpty(), out);
|
||||
assertTrue(out.contains("vec3(1.0)"), "b must keep its own initializer: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void arrayDeclarationsAreSkippedInBothSpellings() {
|
||||
final String src =
|
||||
"#version 460 core\n" +
|
||||
"void main() {\n" +
|
||||
" float a[3];\n" +
|
||||
" float[3] b;\n" +
|
||||
" vec3 c[2];\n" +
|
||||
"}\n";
|
||||
|
||||
final String out = run(src);
|
||||
assertTrue(isUninitialized(out, "a"), out);
|
||||
assertTrue(isUninitialized(out, "b"), out);
|
||||
assertTrue(isUninitialized(out, "c"), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void structAndOpaqueLocalsAreSkipped() {
|
||||
final String src =
|
||||
"#version 460 core\n" +
|
||||
"struct Material { vec3 albedo; float rough; };\n" +
|
||||
"void main() {\n" +
|
||||
" Material m;\n" +
|
||||
" m.rough = 1.0;\n" +
|
||||
"}\n";
|
||||
|
||||
final String out = run(src);
|
||||
assertTrue(isUninitialized(out, "m"), "struct locals have no scalar zero constructor: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void qualifiedDeclarationsAreSkipped() {
|
||||
final String src =
|
||||
"#version 460 core\n" +
|
||||
"void main() {\n" +
|
||||
" const float k = 2.0;\n" +
|
||||
" precise float p;\n" +
|
||||
"}\n";
|
||||
|
||||
final String out = run(src);
|
||||
assertTrue(isUninitialized(out, "p"), out);
|
||||
assertTrue(out.contains("2.0"), "const initializer must survive: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void boolAndDoubleAreSkipped() {
|
||||
final String src =
|
||||
"#version 460 core\n" +
|
||||
"void main() {\n" +
|
||||
" bool flag;\n" +
|
||||
" double d;\n" +
|
||||
"}\n";
|
||||
|
||||
final String out = run(src);
|
||||
assertTrue(isUninitialized(out, "flag"), out);
|
||||
assertTrue(isUninitialized(out, "d"), out);
|
||||
}
|
||||
|
||||
private static int numericBareCount(String src) {
|
||||
return (int) uninitialized(src).stream().filter(d -> NUMERIC.contains(d.type())).count();
|
||||
}
|
||||
|
||||
@Test
|
||||
void patcherEmittedShapesLeaveNoBareNumericLocals() {
|
||||
TransformPatcher.clearCache();
|
||||
final Map<PatchShaderType, String> patched = TransformPatcher.patchComposite(PACK_SHAPED_VSH, null, PACK_SHAPED_FSH);
|
||||
|
||||
for (PatchShaderType stage : List.of(PatchShaderType.VERTEX, PatchShaderType.FRAGMENT)) {
|
||||
final String source = patched.get(stage);
|
||||
assertNotNull(source, stage + " produced no output");
|
||||
assertTrue(numericBareCount(source) > 0, stage + ": fixture must reach the transformer with bare numeric locals\n\n" + source);
|
||||
|
||||
final List<Declarator> leftover = uninitialized(run(source)).stream()
|
||||
.filter(d -> NUMERIC.contains(d.type()))
|
||||
.toList();
|
||||
assertEquals(List.of(), leftover, stage + " still has bare numeric locals\n\n" + run(source));
|
||||
}
|
||||
}
|
||||
|
||||
private static final String PACK_SHAPED_VSH = String.join("\n",
|
||||
"#version 330 core",
|
||||
"in vec4 iris_Vertex;",
|
||||
"in vec4 iris_Color;",
|
||||
"in vec2 mc_midTexCoord;",
|
||||
"out vec4 v_Color;",
|
||||
"out vec3 v_Accum;",
|
||||
"void main() {",
|
||||
" vec4 accum;",
|
||||
" mat3 tbn;",
|
||||
" float depth;",
|
||||
" ivec2 cell;",
|
||||
" accum += iris_Color;",
|
||||
" tbn[0] += vec3(mc_midTexCoord, 0.0);",
|
||||
" depth += iris_Vertex.z;",
|
||||
" cell += ivec2(1);",
|
||||
" v_Color = accum + vec4(float(cell.x));",
|
||||
" v_Accum = tbn[0] * depth;",
|
||||
" gl_Position = iris_Vertex;",
|
||||
"}",
|
||||
"");
|
||||
|
||||
private static final String PACK_SHAPED_FSH = String.join("\n",
|
||||
"#version 330 core",
|
||||
"in vec4 v_Color;",
|
||||
"in vec3 v_Accum;",
|
||||
"uniform sampler2D tex;",
|
||||
"void main() {",
|
||||
" vec3 lighting;",
|
||||
" vec2 uv;",
|
||||
" uint bits;",
|
||||
" lighting += v_Accum;",
|
||||
" uv += v_Color.xy;",
|
||||
" bits += 1u;",
|
||||
" gl_FragColor = vec4(lighting + texture(tex, uv).rgb, float(bits));",
|
||||
"}",
|
||||
"");
|
||||
}
|
||||
@@ -0,0 +1,645 @@
|
||||
package net.coderbot.iris.pipeline.transform;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class RwImageStoreExtractorTest {
|
||||
|
||||
@AfterEach
|
||||
void clearImageRegistry() {
|
||||
RwImageStoreExtractor.setActiveCustomImages(null);
|
||||
}
|
||||
|
||||
private static String norm(String s) {
|
||||
return s.replaceAll("\\s+", " ").trim();
|
||||
}
|
||||
|
||||
private static final String MINIMAL_VOX_VSH = String.join("\n",
|
||||
"#version 460 core",
|
||||
"#extension GL_ARB_shader_image_load_store : enable",
|
||||
"in vec4 iris_Vertex;",
|
||||
"in vec4 iris_Color;",
|
||||
"in vec4 iris_MultiTexCoord0;",
|
||||
"in vec3 iris_Normal;",
|
||||
"attribute vec4 mc_Entity;",
|
||||
"attribute vec4 at_midBlock;",
|
||||
"writeonly uniform uimage3D voxel_img;",
|
||||
"out vec2 texCoord;",
|
||||
"flat out int mat;",
|
||||
"uniform mat4 gbufferModelView;",
|
||||
"void main() {",
|
||||
" texCoord = iris_MultiTexCoord0.xy;",
|
||||
" mat = int(mc_Entity.x + 0.5);",
|
||||
" gl_Position = vec4(iris_Vertex.xyz, 1.0);",
|
||||
" if (gl_VertexID % 4 == 0) {",
|
||||
" imageStore(voxel_img, ivec3(at_midBlock.xyz), uvec4(uint(mat), 0u, 0u, 0u));",
|
||||
" }",
|
||||
"}",
|
||||
"");
|
||||
|
||||
private static final String NO_IMAGESTORE_VSH = String.join("\n",
|
||||
"#version 460 core",
|
||||
"in vec4 iris_Vertex;",
|
||||
"void main() { gl_Position = iris_Vertex; }",
|
||||
"");
|
||||
|
||||
@Test void detection_returnsNullWhenNoImageStore() {
|
||||
assertNull(RwImageStoreExtractor.tryExtract(NO_IMAGESTORE_VSH, PatchShaderType.VERTEX, "shadow"));
|
||||
}
|
||||
|
||||
@Test void detection_returnsNullOnNullInput() {
|
||||
assertNull(RwImageStoreExtractor.tryExtract(null, PatchShaderType.VERTEX, "shadow"));
|
||||
}
|
||||
|
||||
@Test void writtenImages_collectedFromImageStoreCalls() {
|
||||
final var result = RwImageStoreExtractor.tryExtract(MINIMAL_VOX_VSH, PatchShaderType.VERTEX, "shadow");
|
||||
assertNotNull(result);
|
||||
assertTrue(result.writtenImages().contains("voxel_img"));
|
||||
}
|
||||
|
||||
@Test void modeIsChunkWhenChunkAttrsPresent() {
|
||||
final var result = RwImageStoreExtractor.tryExtract(MINIMAL_VOX_VSH, PatchShaderType.VERTEX, "shadow");
|
||||
assertEquals(RwImageStoreExtractor.RwExtractMode.CHUNK, result.mode());
|
||||
}
|
||||
|
||||
@Test void compute_hasComputeVersionAndWorkgroup() {
|
||||
final var result = RwImageStoreExtractor.tryExtract(MINIMAL_VOX_VSH, PatchShaderType.VERTEX, "shadow");
|
||||
assertTrue(result.computeSource().startsWith("// _vg_mode: chunk\n"));
|
||||
assertTrue(result.computeSource().contains("#version 460 core"));
|
||||
assertTrue(result.computeSource().contains("layout(local_size_x = 64) in;"));
|
||||
}
|
||||
|
||||
@Test void compute_hasUniformsAndSsboBinding() {
|
||||
final var result = RwImageStoreExtractor.tryExtract(MINIMAL_VOX_VSH, PatchShaderType.VERTEX, "shadow");
|
||||
final String s = result.computeSource();
|
||||
assertTrue(s.contains("uniform int _vg_startVertex;"));
|
||||
assertTrue(s.contains("uniform int _vg_vertexCount;"));
|
||||
assertTrue(s.contains("readonly buffer _VgVbuf"));
|
||||
assertTrue(s.contains("layout(std430, binding = " + RwImageStoreExtractor.VG_VBUF_SSBO_BINDING + ") readonly buffer _VgVbuf"), "VBO SSBO must bind at the dedicated voxelization slot (not 0..8 which shaderpacks claim via buffer.N)");
|
||||
}
|
||||
|
||||
@Test void compute_ssboBindingDoesNotCollideWithShaderpackSlots() {
|
||||
assertTrue(RwImageStoreExtractor.VG_VBUF_SSBO_BINDING >= 9, "VG_VBUF_SSBO_BINDING must be >= 9 to avoid colliding with shaderpack buffer.N slots; got " + RwImageStoreExtractor.VG_VBUF_SSBO_BINDING);
|
||||
}
|
||||
|
||||
@Test void compute_renamesOriginalMainToVgBody() {
|
||||
final var result = RwImageStoreExtractor.tryExtract(MINIMAL_VOX_VSH, PatchShaderType.VERTEX, "shadow");
|
||||
final String s = result.computeSource();
|
||||
assertTrue(s.contains("_vg_body"), "expected _vg_body in compute output");
|
||||
assertFalse(norm(s).contains("void main ( ) { texCoord ="), "user-original main must be renamed");
|
||||
}
|
||||
|
||||
@Test void compute_synthesizedMainCallsUnpackAndBody() {
|
||||
final String s = RwImageStoreExtractor.tryExtract(MINIMAL_VOX_VSH, PatchShaderType.VERTEX, "shadow").computeSource();
|
||||
assertTrue(s.contains("gl_GlobalInvocationID"));
|
||||
assertTrue(s.contains("_vg_unpack(uint(id));"));
|
||||
assertTrue(s.contains("_vg_body();"));
|
||||
}
|
||||
|
||||
@Test void compute_hoistsAttributeDependentGlobalInitializers() {
|
||||
final String vsh = MINIMAL_VOX_VSH.replace(
|
||||
"void main() {",
|
||||
"float tAmin = fract(mc_Entity.y);\nvec4 iris_Entity = vec4(mc_Entity.x - 1.0, 0.0, 0.0, 1.0);\nvoid main() {");
|
||||
final String s = RwImageStoreExtractor.tryExtract(vsh, PatchShaderType.VERTEX, "shadow").computeSource();
|
||||
final String n = norm(s);
|
||||
assertFalse(n.contains("vec4 iris_Entity = "), "global initializers evaluate before the dispatch main decodes attributes; must be stripped");
|
||||
assertTrue(n.contains("iris_Entity = vec4 ( mc_Entity . x"), "every stripped initializer must be re-emitted as an assignment, not just the first");
|
||||
assertTrue(n.contains("tAmin = fract ( mc_Entity . y"), "every stripped initializer must be re-emitted as an assignment, not just the first");
|
||||
assertTrue(n.indexOf("_vg_body ( ) {") < n.indexOf("iris_Entity = vec4 ( mc_Entity . x"), "the assignment must run inside the body, after the attribute decode");
|
||||
assertTrue(n.indexOf("tAmin = fract") < n.indexOf("iris_Entity = vec4"), "hoisted assignments must keep declaration order");
|
||||
}
|
||||
|
||||
@Test void compute_keepsUnsizedArrayInitializersInPlace() {
|
||||
final String vsh = MINIMAL_VOX_VSH.replace(
|
||||
"void main() {",
|
||||
"vec3[] tintA = vec3[](vec3(1.0), vec3(0.5));\nvec3 tintB[] = vec3[](vec3(1.0), vec3(0.5));\nvoid main() {");
|
||||
final String s = RwImageStoreExtractor.tryExtract(vsh, PatchShaderType.VERTEX, "shadow").computeSource();
|
||||
final String n = norm(s);
|
||||
assertTrue(n.contains("tintA = vec3 [ ] ("), "tintA: unsized array initializer must stay on the declaration");
|
||||
assertTrue(n.contains("tintB [ ] = vec3 [ ] ("), "tintB: unsized array initializer must stay on the declaration");
|
||||
assertTrue(n.indexOf("tintA =") == n.lastIndexOf("tintA ="), "tintA: initializer must not additionally be hoisted into the body");
|
||||
}
|
||||
|
||||
@Test void compute_unpackHasExpectedAttributeReads() {
|
||||
final String s = RwImageStoreExtractor.tryExtract(MINIMAL_VOX_VSH, PatchShaderType.VERTEX, "shadow").computeSource();
|
||||
assertTrue(s.contains("iris_Vertex = vec4(uintBitsToFloat(_vg_vbuf.data[base + 0u])"));
|
||||
assertTrue(s.contains("iris_Color = vec4(float(_vg_vbuf.data[base + 3u] & 0xFFu)"));
|
||||
assertTrue(s.contains("mc_Entity = vec4(float(_vg_vbuf.data[base + 10u])"), "ATTRIBUTES-patch mc_Entity is delivered as vec4 raw");
|
||||
}
|
||||
|
||||
@Test void compute_dropsOutQualifierFromVaryings() {
|
||||
final String s = RwImageStoreExtractor.tryExtract(MINIMAL_VOX_VSH, PatchShaderType.VERTEX, "shadow").computeSource();
|
||||
assertFalse(norm(s).contains("out vec2 texCoord"), "out qualifier should be stripped\n\n" + s);
|
||||
assertTrue(norm(s).contains("vec2 texCoord"), "varying becomes a global");
|
||||
}
|
||||
|
||||
@Test void compute_vertInitOnlyAssignsUnpackedAttributes() {
|
||||
final String src = String.join("\n",
|
||||
"#version 460 core",
|
||||
"in vec3 a_PosId;",
|
||||
"writeonly uniform uimage3D voxel_img;",
|
||||
"void main() {",
|
||||
" gl_Position = vec4(a_PosId, 1.0);",
|
||||
" imageStore(voxel_img, ivec3(a_PosId), uvec4(1u, 0u, 0u, 0u));",
|
||||
"}",
|
||||
"");
|
||||
final String s = norm(RwImageStoreExtractor.tryExtract(src, PatchShaderType.VERTEX, "shadow").computeSource());
|
||||
assertTrue(s.contains("_vert_position = a_PosId"), "the used attribute is still decoded\n\n" + s);
|
||||
assertFalse(s.contains("a_TexCoord"), "an unused attribute must not be referenced\n\n" + s);
|
||||
assertFalse(s.contains("a_LightCoord"), "an unused attribute must not be referenced\n\n" + s);
|
||||
}
|
||||
|
||||
@Test void compute_dropsInterpolationQualifierFromVaryings() {
|
||||
final String s = norm(RwImageStoreExtractor.tryExtract(MINIMAL_VOX_VSH, PatchShaderType.VERTEX, "shadow").computeSource());
|
||||
assertFalse(s.contains("flat"), "flat is interface-only; a compute global carrying it does not compile\n\n" + s);
|
||||
assertTrue(s.contains("int mat"), "the varying still becomes a global");
|
||||
}
|
||||
|
||||
@Test void compute_dropsAuxiliaryStorageQualifierFromVaryings() {
|
||||
final String src = String.join("\n",
|
||||
"#version 460 core",
|
||||
"in vec4 iris_Vertex;",
|
||||
"writeonly uniform uimage3D voxel_img;",
|
||||
"centroid out vec2 texCoord;",
|
||||
"void main() {",
|
||||
" texCoord = iris_Vertex.xy;",
|
||||
" imageStore(voxel_img, ivec3(0), uvec4(1u, 0u, 0u, 0u));",
|
||||
"}",
|
||||
"");
|
||||
final String s = norm(RwImageStoreExtractor.tryExtract(src, PatchShaderType.VERTEX, "shadow").computeSource());
|
||||
assertFalse(s.contains("centroid"), "centroid is interface-only\n\n" + s);
|
||||
assertTrue(s.contains("vec2 texCoord"), "the varying still becomes a global");
|
||||
}
|
||||
|
||||
@Test void compute_stripsChunkVertexAttributeDeclarations() {
|
||||
final String s = RwImageStoreExtractor.tryExtract(MINIMAL_VOX_VSH, PatchShaderType.VERTEX, "shadow").computeSource();
|
||||
assertFalse(norm(s).contains("in vec4 iris_Vertex"));
|
||||
assertFalse(norm(s).contains("attribute vec4 mc_Entity"));
|
||||
}
|
||||
|
||||
@Test void raster_strippedHasNoImageStoreOrWriteonly() {
|
||||
final var result = RwImageStoreExtractor.tryExtract(MINIMAL_VOX_VSH, PatchShaderType.VERTEX, "shadow");
|
||||
final String r = result.strippedSource();
|
||||
assertFalse(r.contains("imageStore("), "raster should have no imageStore calls");
|
||||
assertFalse(r.contains("writeonly uniform uimage"), "raster should have no writeonly image decls");
|
||||
assertFalse(norm(r).contains("uniform uimage3D voxel_img"), "raster should have no uimage3D voxel_img decl");
|
||||
assertTrue(r.contains("main"), "raster keeps main");
|
||||
}
|
||||
|
||||
@Test void directives_preservedThroughRasterStrip() {
|
||||
final var result = RwImageStoreExtractor.tryExtract(MINIMAL_VOX_VSH, PatchShaderType.VERTEX, "shadow");
|
||||
final String r = result.strippedSource();
|
||||
assertTrue(r.contains("#version"), "raster keeps a version directive");
|
||||
assertTrue(r.contains("#extension GL_ARB_shader_image_load_store"), "raster preserves user #extension directive\n\n" + r);
|
||||
}
|
||||
|
||||
@Test void knownAttributes_includesAllNineCanonicals() {
|
||||
for (String name : new String[]{"iris_Vertex","iris_Color","iris_MultiTexCoord0","iris_MultiTexCoord1", "mc_midTexCoord","at_tangent","iris_Normal","mc_Entity","at_midBlock"}) {
|
||||
assertNotNull(RwImageStoreExtractor.CHUNK_VERTEX_ATTRS.get(name), "missing " + name);
|
||||
}
|
||||
}
|
||||
|
||||
@Test void knownAttributeVariants_includesCeleritasTypings() {
|
||||
final var variants = RwImageStoreExtractor.CHUNK_VERTEX_ATTRS;
|
||||
assertNotNull(variants.get("a_PosId").get("vec3"));
|
||||
assertNotNull(variants.get("a_PosId").get("uvec4"));
|
||||
assertNotNull(variants.get("a_Color").get("vec4"));
|
||||
assertNotNull(variants.get("a_TexCoord").get("vec2"));
|
||||
assertNotNull(variants.get("a_LightCoord").get("uint"));
|
||||
assertNotNull(variants.get("a_LightCoord").get("ivec2"));
|
||||
assertNotNull(variants.get("mc_Entity").get("vec4"));
|
||||
assertNotNull(variants.get("mc_Entity").get("uint"));
|
||||
assertNotNull(variants.get("mc_midTexCoord").get("vec4"));
|
||||
assertNotNull(variants.get("mc_midTexCoord").get("vec2"));
|
||||
}
|
||||
|
||||
private static final String CELERITAS_PATCHED_VOX_VSH = String.join("\n",
|
||||
"#version 460 core",
|
||||
"#extension GL_ARB_shader_image_load_store : enable",
|
||||
"",
|
||||
"#ifdef USE_VERTEX_COMPRESSION",
|
||||
"in uvec4 a_PosId;",
|
||||
"in vec4 a_Color;",
|
||||
"in vec2 a_TexCoord;",
|
||||
"in ivec2 a_LightCoord;",
|
||||
"void _vert_init() {",
|
||||
" uint dummy = a_PosId.w;",
|
||||
"}",
|
||||
"#else",
|
||||
"in vec3 a_PosId;",
|
||||
"in vec4 a_Color;",
|
||||
"in vec2 a_TexCoord;",
|
||||
"in uint a_LightCoord;",
|
||||
"void _vert_init() {",
|
||||
" vec3 p = a_PosId;",
|
||||
"}",
|
||||
"#endif",
|
||||
"",
|
||||
"vec3 _vert_position;",
|
||||
"vec2 _vert_tex_diffuse_coord;",
|
||||
"ivec2 _vert_tex_light_coord;",
|
||||
"vec4 _vert_color;",
|
||||
"uint _draw_id;",
|
||||
"uint _material_params;",
|
||||
"",
|
||||
"in uint mc_Entity;",
|
||||
"in vec2 mc_midTexCoord;",
|
||||
"in vec3 iris_Normal;",
|
||||
"in vec4 at_midBlock;",
|
||||
"",
|
||||
"writeonly uniform uimage3D voxel_img;",
|
||||
"",
|
||||
"uniform vec3 u_RegionOffset;",
|
||||
"out vec4 outColor;",
|
||||
"",
|
||||
"void main() {",
|
||||
" _vert_init();",
|
||||
" outColor = a_Color * vec4(iris_Normal, 1.0);",
|
||||
" gl_Position = vec4(a_PosId + u_RegionOffset, 1.0);",
|
||||
" if (mc_Entity > 0u) {",
|
||||
" imageStore(voxel_img, ivec3(at_midBlock.xyz * 127.0), uvec4(mc_Entity, 0u, 0u, 0u));",
|
||||
" }",
|
||||
"}",
|
||||
"");
|
||||
|
||||
@Test void celeritas_tryExtractProducesComputeSource() {
|
||||
final var result = RwImageStoreExtractor.tryExtract(CELERITAS_PATCHED_VOX_VSH, PatchShaderType.VERTEX, "CELERITAS_TERRAIN");
|
||||
assertNotNull(result);
|
||||
assertNotNull(result.computeSource(), "compute source must be built for celeritas-patched VSH");
|
||||
assertTrue(result.writtenImages().contains("voxel_img"));
|
||||
assertEquals(RwImageStoreExtractor.RwExtractMode.CHUNK, result.mode());
|
||||
}
|
||||
|
||||
@Test void celeritas_computeContainsLiveBranchGlobals() {
|
||||
final String s = RwImageStoreExtractor.tryExtract(CELERITAS_PATCHED_VOX_VSH, PatchShaderType.VERTEX, "CELERITAS_TERRAIN").computeSource();
|
||||
assertTrue(s.contains("vec3 a_PosId;"), "uncompressed (live) a_PosId global");
|
||||
assertTrue(s.contains("vec4 a_Color;"));
|
||||
assertTrue(s.contains("vec2 a_TexCoord;"));
|
||||
assertTrue(s.contains("uint a_LightCoord;"));
|
||||
assertTrue(s.contains("uint mc_Entity;"));
|
||||
assertTrue(s.contains("vec2 mc_midTexCoord;"));
|
||||
assertTrue(s.contains("vec3 iris_Normal;"));
|
||||
assertTrue(s.contains("vec4 at_midBlock;"));
|
||||
}
|
||||
|
||||
@Test void celeritas_computeContainsDeadBranchStubGlobals() {
|
||||
final String s = RwImageStoreExtractor.tryExtract(CELERITAS_PATCHED_VOX_VSH, PatchShaderType.VERTEX, "CELERITAS_TERRAIN").computeSource();
|
||||
assertTrue(s.contains("uvec4 a_PosId;"), "compressed-branch stub a_PosId");
|
||||
assertTrue(s.contains("ivec2 a_LightCoord;"), "compressed-branch stub a_LightCoord");
|
||||
assertTrue(s.contains("#ifdef USE_VERTEX_COMPRESSION"), "expected #ifdef guard around dual-branch globals");
|
||||
assertTrue(s.contains("#else"));
|
||||
assertTrue(s.contains("#endif"));
|
||||
}
|
||||
|
||||
@Test void celeritas_unpackContainsCeleritasFormulas() {
|
||||
final String s = RwImageStoreExtractor.tryExtract(CELERITAS_PATCHED_VOX_VSH, PatchShaderType.VERTEX, "CELERITAS_TERRAIN").computeSource();
|
||||
assertTrue(s.contains("a_PosId = vec3(uintBitsToFloat(_vg_vbuf.data[base + 0u])"));
|
||||
assertTrue(s.contains("a_TexCoord = vec2(uintBitsToFloat(_vg_vbuf.data[base + 4u])"));
|
||||
assertTrue(s.contains("a_LightCoord = _vg_vbuf.data[base + 6u]"));
|
||||
assertTrue(s.contains("mc_Entity = _vg_vbuf.data[base + 10u]"), "celeritas-typed mc_Entity must be delivered as the raw packed uint");
|
||||
assertTrue(s.contains("mc_midTexCoord = vec2(float(_vg_vbuf.data[base + 7u] & 0xFFFFu),"), "mc_midTexCoord is an unnormalized ushort delivered raw by the vertex stage, so the compute prelude must not rescale it");
|
||||
assertTrue(s.contains("a_PosId = uvec4(0u, 0u, 0u, 0u)"));
|
||||
assertTrue(s.contains("a_LightCoord = ivec2(0, 0)"));
|
||||
}
|
||||
|
||||
@Test void celeritas_computeDecodesVertexGlobals() {
|
||||
final String s = RwImageStoreExtractor.tryExtract(CELERITAS_PATCHED_VOX_VSH, PatchShaderType.VERTEX, "CELERITAS_TERRAIN").computeSource();
|
||||
assertTrue(s.contains("_vert_position = a_PosId;"), "uncompressed branch must decode position\n\n" + s);
|
||||
assertTrue(s.contains("_vert_position = vec3(a_PosId.xyz) * VERT_POS_SCALE + VERT_POS_OFFSET;"), "compressed branch must decode position\n\n" + s);
|
||||
assertTrue(s.contains("_draw_id = (_vg_draw_params >> 8) & 0xFFu;"), "_get_draw_translation depends on _draw_id\n\n" + s);
|
||||
}
|
||||
|
||||
@Test void celeritas_vertexDecodeComesAfterTheGlobalDeclarations() {
|
||||
final String s = RwImageStoreExtractor.tryExtract(CELERITAS_PATCHED_VOX_VSH, PatchShaderType.VERTEX, "CELERITAS_TERRAIN").computeSource();
|
||||
for (String global : new String[]{"_vert_position", "_vert_tex_diffuse_coord", "_vert_color", "_vert_tex_light_coord", "_draw_id", "_material_params"}) {
|
||||
final int declared = s.indexOf(global + " ;");
|
||||
final int assigned = s.indexOf(global + " =");
|
||||
assertTrue(declared >= 0, global + " should be declared by the celeritas header\n\n" + s);
|
||||
assertTrue(assigned < 0 || declared < assigned, global + " is assigned at " + assigned + " before its declaration at " + declared + "\n\n" + s);
|
||||
}
|
||||
}
|
||||
|
||||
@Test void celeritas_strippedHasNoImageStoreOrUimage() {
|
||||
final var result = RwImageStoreExtractor.tryExtract(CELERITAS_PATCHED_VOX_VSH, PatchShaderType.VERTEX, "CELERITAS_TERRAIN");
|
||||
final String r = result.strippedSource();
|
||||
assertFalse(r.contains("imageStore("));
|
||||
assertFalse(norm(r).contains("uniform uimage3D voxel_img"));
|
||||
}
|
||||
|
||||
private static final String MULTI_IMAGE_VSH = String.join("\n",
|
||||
"#version 460 core",
|
||||
"in vec4 iris_Vertex;",
|
||||
"in vec4 iris_Color;",
|
||||
"in vec4 iris_MultiTexCoord0;",
|
||||
"in vec3 iris_Normal;",
|
||||
"attribute vec4 mc_Entity;",
|
||||
"attribute vec4 at_midBlock;",
|
||||
"writeonly uniform uimage2D wsr_img;",
|
||||
"writeonly uniform uimage3D voxel_img;",
|
||||
"writeonly uniform uimage3D wsr_lod_img;",
|
||||
"void main() {",
|
||||
" imageStore(voxel_img, ivec3(0), uvec4(0u));",
|
||||
" imageStore(wsr_img, ivec2(0), uvec4(0u));",
|
||||
" imageStore(wsr_lod_img, ivec3(0), uvec4(0u));",
|
||||
"}",
|
||||
"");
|
||||
|
||||
@Test void compute_emitsExplicitBindingsForWriteonlyImages() {
|
||||
final String s = RwImageStoreExtractor.tryExtract(MULTI_IMAGE_VSH, PatchShaderType.VERTEX, "ATTRIBUTES").computeSource();
|
||||
assertTrue(s.contains("layout(binding = 0) writeonly uniform uimage3D voxel_img;"), "voxel_img must be binding 0 (alphabetical-first), missing in:\n" + s);
|
||||
assertTrue(s.contains("layout(binding = 1) writeonly uniform uimage2D wsr_img;"));
|
||||
assertTrue(s.contains("layout(binding = 2) writeonly uniform uimage3D wsr_lod_img;"));
|
||||
}
|
||||
|
||||
private static final String NON_WRITEONLY_PREPARE_VSH = String.join("\n",
|
||||
"#version 460 core",
|
||||
"layout(r32i) uniform iimage2D endcrystal_img;",
|
||||
"uniform mat4 gbufferModelView;",
|
||||
"void main() {",
|
||||
" ivec4 prev = imageLoad(endcrystal_img, ivec2(0, 0));",
|
||||
" imageStore(endcrystal_img, ivec2(0, 0), ivec4(prev.x + 1));",
|
||||
" gl_Position = vec4(0.0);",
|
||||
"}",
|
||||
"");
|
||||
|
||||
@Test void nonWriteonlyImage_stripsFromRaster() {
|
||||
final var result = RwImageStoreExtractor.tryExtract(NON_WRITEONLY_PREPARE_VSH, PatchShaderType.VERTEX, "prepare");
|
||||
assertNotNull(result);
|
||||
assertEquals(RwImageStoreExtractor.RwExtractMode.COMPOSITE_VSH, result.mode(), "no chunk attrs -> composite-vsh");
|
||||
final String r = result.strippedSource();
|
||||
assertFalse(r.contains("iimage2D"), "raster must have no iimage2D decl\n\n" + r);
|
||||
assertFalse(r.contains("imageStore("), "raster must have no imageStore call");
|
||||
assertTrue(r.contains("ivec4(0)"), "imageLoad must be replaced by ivec4(0)\n\n" + r);
|
||||
}
|
||||
|
||||
private static final String COMPOSITE_VSH = String.join("\n",
|
||||
"#version 460 core",
|
||||
"writeonly uniform uimage2D state_img;",
|
||||
"uniform mat4 gl_ModelViewProjectionMatrix;",
|
||||
"void main() {",
|
||||
" gl_Position = ftransform();",
|
||||
" imageStore(state_img, ivec2(gl_VertexID, 0), uvec4(1u));",
|
||||
"}",
|
||||
"");
|
||||
|
||||
@Test void compositeVsh_modeAndPrelude() {
|
||||
final var result = RwImageStoreExtractor.tryExtract(COMPOSITE_VSH, PatchShaderType.VERTEX, "composite");
|
||||
assertNotNull(result);
|
||||
assertEquals(RwImageStoreExtractor.RwExtractMode.COMPOSITE_VSH, result.mode());
|
||||
final String s = result.computeSource();
|
||||
assertTrue(s.startsWith("// _vg_mode: composite-vsh\n"), "sentinel comment on line 1\n\n" + s);
|
||||
assertTrue(s.contains("const vec4 _vg_quad[4]"), "quad table missing\n\n" + s);
|
||||
assertTrue(s.contains("#define gl_Vertex _vg_gl_vertex"));
|
||||
assertTrue(s.contains("#define gl_VertexID _vg_gl_vertex_id"));
|
||||
assertTrue(s.contains("vec4 iris_ftransform()"));
|
||||
assertTrue(s.contains("if (vid >= 4u) return;"));
|
||||
}
|
||||
|
||||
@Test void compositeVsh_rasterStillCompilesShape() {
|
||||
final var result = RwImageStoreExtractor.tryExtract(COMPOSITE_VSH, PatchShaderType.VERTEX, "composite");
|
||||
final String r = result.strippedSource();
|
||||
assertFalse(r.contains("imageStore("), "raster has no imageStore");
|
||||
assertFalse(r.contains("uimage2D"), "raster has no uimage2D decl");
|
||||
}
|
||||
|
||||
private static final String COMPOSITE_FSH = String.join("\n",
|
||||
"#version 460 core",
|
||||
"writeonly uniform uimage2D out_img;",
|
||||
"in vec2 texcoord;",
|
||||
"out vec4 outColor;",
|
||||
"void main() {",
|
||||
" ivec2 px = ivec2(gl_FragCoord.xy);",
|
||||
" imageStore(out_img, px, uvec4(uint(px.x), uint(px.y), 0u, 0u));",
|
||||
" outColor = vec4(0.0, 0.0, 0.0, 1.0);",
|
||||
"}",
|
||||
"");
|
||||
|
||||
@Test void compositeFsh_modeAndPrelude() {
|
||||
final var result = RwImageStoreExtractor.tryExtract(COMPOSITE_FSH, PatchShaderType.FRAGMENT, "composite_fsh");
|
||||
assertNotNull(result);
|
||||
assertEquals(RwImageStoreExtractor.RwExtractMode.COMPOSITE_FSH, result.mode());
|
||||
final String s = result.computeSource();
|
||||
assertTrue(s.startsWith("// _vg_mode: composite-fsh\n"));
|
||||
assertTrue(s.contains("layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;"));
|
||||
assertTrue(s.contains("uniform ivec2 _vg_target_size;"));
|
||||
assertTrue(s.contains("#define gl_FragCoord _vg_gl_fragcoord_raw"));
|
||||
assertTrue(s.contains("vec2(px) + 0.5"));
|
||||
}
|
||||
|
||||
@Test void compositeFsh_rasterKeepsOutColorButStripsImage() {
|
||||
final var result = RwImageStoreExtractor.tryExtract(COMPOSITE_FSH, PatchShaderType.FRAGMENT, "composite_fsh");
|
||||
final String r = result.strippedSource();
|
||||
assertFalse(r.contains("imageStore("));
|
||||
assertFalse(r.contains("uimage2D"));
|
||||
assertTrue(norm(r).contains("out vec4 outColor"), "raster keeps user output\n\n" + r);
|
||||
}
|
||||
|
||||
private static final String ATOMIC_IMAGE_VSH = String.join("\n",
|
||||
"#version 460 core",
|
||||
"in vec4 iris_Vertex;",
|
||||
"in vec4 iris_Color;",
|
||||
"in vec4 iris_MultiTexCoord0;",
|
||||
"in vec3 iris_Normal;",
|
||||
"attribute vec4 mc_Entity;",
|
||||
"attribute vec4 at_midBlock;",
|
||||
"layout(r32ui) uniform uimage3D counter_img;",
|
||||
"void main() {",
|
||||
" imageAtomicAdd(counter_img, ivec3(0, 0, 0), 1u);",
|
||||
" gl_Position = vec4(0.0);",
|
||||
"}",
|
||||
"");
|
||||
|
||||
@Test void imageAtomic_isClassifiedAsWrite() {
|
||||
final var result = RwImageStoreExtractor.tryExtract(ATOMIC_IMAGE_VSH, PatchShaderType.VERTEX, "atomic");
|
||||
assertNotNull(result);
|
||||
assertTrue(result.writtenImages().contains("counter_img"), "imageAtomicAdd must classify the image as written");
|
||||
assertFalse(result.strippedSource().contains("imageAtomicAdd("), "imageAtomic call must be stripped from raster");
|
||||
}
|
||||
|
||||
private static final String MIXED_IMAGES_VSH = String.join("\n",
|
||||
"#version 460 core",
|
||||
"in vec4 iris_Vertex;",
|
||||
"in vec4 iris_Color;",
|
||||
"in vec4 iris_MultiTexCoord0;",
|
||||
"in vec3 iris_Normal;",
|
||||
"attribute vec4 mc_Entity;",
|
||||
"attribute vec4 at_midBlock;",
|
||||
"uniform image2D voxel_a;",
|
||||
"uniform iimage2D voxel_b;",
|
||||
"uniform uimage3D voxel_c;",
|
||||
"void main() {",
|
||||
" vec4 a = imageLoad(voxel_a, ivec2(0));",
|
||||
" ivec4 b = imageLoad(voxel_b, ivec2(0));",
|
||||
" uvec4 c = imageLoad(voxel_c, ivec3(0));",
|
||||
" imageStore(voxel_a, ivec2(0), a);",
|
||||
" imageStore(voxel_b, ivec2(0), b);",
|
||||
" imageStore(voxel_c, ivec3(0), c);",
|
||||
" gl_Position = vec4(0.0);",
|
||||
"}",
|
||||
"");
|
||||
|
||||
@Test void mixedReadWrite_componentTypesCorrect() {
|
||||
final var result = RwImageStoreExtractor.tryExtract(MIXED_IMAGES_VSH, PatchShaderType.VERTEX, "mixed");
|
||||
assertNotNull(result);
|
||||
final String r = result.strippedSource();
|
||||
assertTrue(r.contains("vec4(0.0)"), "image2D imageLoad replaced by vec4(0.0)\n\n" + r);
|
||||
assertTrue(r.contains("ivec4(0)"), "iimage2D imageLoad replaced by ivec4(0)");
|
||||
assertTrue(r.contains("uvec4(0u)"), "uimage3D imageLoad replaced by uvec4(0u)");
|
||||
}
|
||||
|
||||
private static final String ATOMIC_NOT_WRITEONLY_VSH = String.join("\n",
|
||||
"#version 460 core",
|
||||
"in vec4 iris_Vertex;",
|
||||
"in vec4 iris_Color;",
|
||||
"in vec4 iris_MultiTexCoord0;",
|
||||
"in vec3 iris_Normal;",
|
||||
"in uint mc_Entity;",
|
||||
"in vec2 mc_midTexCoord;",
|
||||
"in vec4 at_midBlock;",
|
||||
"layout(r32i) uniform iimage2D endcrystal_img;",
|
||||
"void main() {",
|
||||
" imageAtomicAdd(endcrystal_img, ivec2(0, 0), 1);",
|
||||
" gl_Position = vec4(0.0);",
|
||||
"}",
|
||||
"");
|
||||
|
||||
@Test void atomicOnlyImage_doesNotGetWriteonlyQualifier() {
|
||||
final var result = RwImageStoreExtractor.tryExtract(ATOMIC_NOT_WRITEONLY_VSH, PatchShaderType.VERTEX, "atomic_only");
|
||||
assertNotNull(result);
|
||||
final String s = result.computeSource();
|
||||
assertFalse(s.contains("writeonly uniform iimage2D endcrystal_img"), "imageAtomic-only image must not get writeonly qualifier (atomics are read+write)\n\n" + s);
|
||||
assertTrue(s.contains("uniform iimage2D endcrystal_img"), "image decl still emitted in prelude\n\n" + s);
|
||||
}
|
||||
|
||||
@Test void writeonlyImage_stillGetsWriteonlyQualifier() {
|
||||
final var result = RwImageStoreExtractor.tryExtract(MULTI_IMAGE_VSH, PatchShaderType.VERTEX, "writeonly");
|
||||
final String s = result.computeSource();
|
||||
assertTrue(s.contains("writeonly uniform uimage3D voxel_img"),
|
||||
"imageStore-only image keeps writeonly qualifier\n\n" + s);
|
||||
}
|
||||
|
||||
private static final String IRIS_INJECTED_MC_ENTITY_VSH = String.join("\n",
|
||||
"#version 460 core",
|
||||
"in vec4 iris_Vertex;",
|
||||
"in vec4 iris_Color;",
|
||||
"in vec4 iris_MultiTexCoord0;",
|
||||
"in vec3 iris_Normal;",
|
||||
"in uint mc_Entity;",
|
||||
"in vec2 mc_midTexCoord;",
|
||||
"in vec4 at_midBlock;",
|
||||
"writeonly uniform uimage3D voxel_img;",
|
||||
"vec4 iris_Entity = vec4(int(mc_Entity >> 1u) - 1, mc_Entity & 1u, 0.0, 1.0);",
|
||||
"void main() {",
|
||||
" imageStore(voxel_img, ivec3(at_midBlock.xyz * 127.0), uvec4(iris_Entity.x, 0u, 0u, 0u));",
|
||||
" gl_Position = vec4(0.0);",
|
||||
"}",
|
||||
"");
|
||||
|
||||
@Test void astDeclaredMcEntity_emitsOnlyUintVariant() {
|
||||
final var result = RwImageStoreExtractor.tryExtract(IRIS_INJECTED_MC_ENTITY_VSH, PatchShaderType.VERTEX, "shadow");
|
||||
final String s = result.computeSource();
|
||||
assertFalse(s.contains("vec4 mc_Entity"), "mc_Entity declared in AST as uint must not emit a vec4 variant (Iris's iris_Entity uses mc_Entity >> 1u)\n\n" + s);
|
||||
assertTrue(s.contains("uint mc_Entity;"), "mc_Entity must be emitted as uint matching the AST decl\n\n" + s);
|
||||
assertFalse(s.contains("vec4 mc_midTexCoord"), "mc_midTexCoord declared in AST as vec2 must not emit a vec4 variant\n\n" + s);
|
||||
assertTrue(s.contains("vec2 mc_midTexCoord;"));
|
||||
}
|
||||
|
||||
@Test void celeritasIfdefAttrs_emitBothVariantsGuarded() {
|
||||
final var result = RwImageStoreExtractor.tryExtract(CELERITAS_PATCHED_VOX_VSH, PatchShaderType.VERTEX, "CELERITAS_TERRAIN");
|
||||
final String s = result.computeSource();
|
||||
assertTrue(s.contains("uvec4 a_PosId;"), "compressed-branch stub a_PosId\n\n" + s);
|
||||
assertTrue(s.contains("vec3 a_PosId;"), "uncompressed-branch live a_PosId\n\n" + s);
|
||||
}
|
||||
|
||||
private static final String IMAGE_STORE_AS_BRACELESS_IF_BODY_VSH = String.join("\n",
|
||||
"#version 460 core",
|
||||
"in vec4 iris_Vertex;",
|
||||
"in vec4 iris_Color;",
|
||||
"in vec4 iris_MultiTexCoord0;",
|
||||
"in vec3 iris_Normal;",
|
||||
"in uint mc_Entity;",
|
||||
"in vec2 mc_midTexCoord;",
|
||||
"in vec4 at_midBlock;",
|
||||
"writeonly uniform uimage3D voxel_img;",
|
||||
"void main() {",
|
||||
" if (gl_VertexID % 4 == 0)",
|
||||
" imageStore(voxel_img, ivec3(0), uvec4(0u));",
|
||||
" gl_Position = vec4(iris_Vertex.xyz, 1.0);",
|
||||
"}",
|
||||
"");
|
||||
|
||||
@Test void raster_brackelessIfBodyImageStore_stripDoesNotLeaveDanglingIf() {
|
||||
final var result = RwImageStoreExtractor.tryExtract(IMAGE_STORE_AS_BRACELESS_IF_BODY_VSH, PatchShaderType.VERTEX, "if_body");
|
||||
assertNotNull(result);
|
||||
final String r = result.strippedSource();
|
||||
assertFalse(r.contains("imageStore("), "imageStore must be removed\n\n" + r);
|
||||
final String nr = norm(r);
|
||||
assertTrue(nr.contains("if (gl_VertexID % 4 == 0) ;"), "if statement must have a valid empty body after strip\n\n" + r);
|
||||
}
|
||||
|
||||
@Test void raster_preservesIfdefBlockAndItsContents() {
|
||||
final var result = RwImageStoreExtractor.tryExtract(CELERITAS_PATCHED_VOX_VSH, PatchShaderType.VERTEX, "CELERITAS_TERRAIN");
|
||||
final String r = result.strippedSource();
|
||||
assertTrue(r.contains("#ifdef USE_VERTEX_COMPRESSION"), "raster must preserve the #ifdef block verbatim so _vert_init() resolves\n\n" + r);
|
||||
assertTrue(r.contains("#else"), "raster preserves the #else branch\n\n" + r);
|
||||
assertTrue(r.contains("#endif"), "raster preserves the #endif\n\n" + r);
|
||||
assertTrue(r.contains("void _vert_init()"), "raster must keep the _vert_init definition the user's main calls\n\n" + r);
|
||||
assertFalse(r.contains("imageStore("), "raster still strips imageStore\n\n" + r);
|
||||
assertFalse(norm(r).contains("uniform uimage3D voxel_img"), "raster still strips the image decl\n\n" + r);
|
||||
}
|
||||
|
||||
@Test void atomicCall_rewrittenToInlineCompoundStatement() {
|
||||
final var result = RwImageStoreExtractor.tryExtract(ATOMIC_NOT_WRITEONLY_VSH, PatchShaderType.VERTEX, "atomic");
|
||||
assertNotNull(result);
|
||||
final String c = result.computeSource();
|
||||
final String nc = norm(c);
|
||||
assertFalse(nc.contains("imageAtomicAdd ("), "imageAtomicAdd must be rewritten in compute output\n\n" + c);
|
||||
assertTrue(nc.contains("int _vg_prev = imageLoad ( endcrystal_img"), "inline emulation must load the prior value with the original global name\n\n" + c);
|
||||
assertTrue(nc.contains("imageStore ( endcrystal_img"), "inline emulation must write the new value back to the original global\n\n" + c);
|
||||
assertTrue(nc.contains("ivec4 ( _vg_prev +"), "inline emulation must compute prev + val in the destination vec\n\n" + c);
|
||||
}
|
||||
|
||||
@Test void atomicEmulation_droppedWriteonlyQualifier() {
|
||||
final var result = RwImageStoreExtractor.tryExtract(ATOMIC_NOT_WRITEONLY_VSH, PatchShaderType.VERTEX, "atomic");
|
||||
final String c = result.computeSource();
|
||||
assertFalse(c.contains("writeonly uniform iimage2D endcrystal_img"), "image used by imageAtomic* must not get writeonly qualifier (now load+store)\n\n" + c);
|
||||
assertTrue(c.contains("uniform iimage2D endcrystal_img"), "image decl present in prelude\n\n" + c);
|
||||
}
|
||||
|
||||
private static final String MIXED_ATOMIC_AND_STORE_VSH = String.join("\n",
|
||||
"#version 460 core",
|
||||
"in vec4 iris_Vertex;",
|
||||
"in vec4 iris_Color;",
|
||||
"in vec4 iris_MultiTexCoord0;",
|
||||
"in vec3 iris_Normal;",
|
||||
"in uint mc_Entity;",
|
||||
"in vec2 mc_midTexCoord;",
|
||||
"in vec4 at_midBlock;",
|
||||
"layout(r32i) uniform iimage2D dual_img;",
|
||||
"void main() {",
|
||||
" imageStore(dual_img, ivec2(0), ivec4(42, 0, 0, 0));",
|
||||
" imageAtomicAdd(dual_img, ivec2(1, 0), 1);",
|
||||
" gl_Position = vec4(0.0);",
|
||||
"}",
|
||||
"");
|
||||
|
||||
@Test void mixedAtomicAndStore_bothRewritten() {
|
||||
final var result = RwImageStoreExtractor.tryExtract(MIXED_ATOMIC_AND_STORE_VSH, PatchShaderType.VERTEX, "mixed_atom");
|
||||
assertNotNull(result);
|
||||
final String c = result.computeSource();
|
||||
final String nc = norm(c);
|
||||
assertFalse(nc.contains("imageAtomicAdd ("), "atomic call should be rewritten\n\n" + c);
|
||||
assertTrue(nc.contains("int _vg_prev = imageLoad ( dual_img"), "atomic call should be inlined as load+store on dual_img\n\n" + c);
|
||||
int storeCount = 0;
|
||||
int from = 0;
|
||||
while ((from = nc.indexOf("imageStore ( dual_img", from)) >= 0) { storeCount++; from++; }
|
||||
assertTrue(storeCount >= 2, "expected both the user's imageStore and the emulated imageStore on dual_img, got " + storeCount + ":\n\n" + c);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package net.coderbot.iris.pipeline.transform;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.taumc.glsl.ShaderParser;
|
||||
import org.taumc.glsl.ShaderPrinter;
|
||||
import org.taumc.glsl.Transformer;
|
||||
|
||||
import java.util.EnumMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class SamplerAliasDeduplicatorTest {
|
||||
|
||||
private static Transformer parse(String src) {
|
||||
return new Transformer(ShaderParser.parseShader(src).full());
|
||||
}
|
||||
|
||||
private static String format(Transformer t) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
t.mutateTree(tree -> sb.append(ShaderPrinter.getFormattedShader(tree)));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@Test
|
||||
void bothDeclared_aliasDropped_canonicalKept() {
|
||||
String src =
|
||||
"#version 330 core\n" +
|
||||
"uniform sampler2D tex;\n" +
|
||||
"uniform sampler2D textureAtlas;\n" +
|
||||
"out vec4 fragColor;\n" +
|
||||
"void main() {\n" +
|
||||
" fragColor = texture(textureAtlas, vec2(0.5)) + texture(tex, vec2(0.5));\n" +
|
||||
"}\n";
|
||||
|
||||
Transformer t = parse(src);
|
||||
Map<PatchShaderType, Transformer> trees = new EnumMap<>(PatchShaderType.class);
|
||||
trees.put(PatchShaderType.FRAGMENT, t);
|
||||
SamplerAliasDeduplicator.transformGrouped(trees, null);
|
||||
|
||||
String out = format(t);
|
||||
assertTrue(out.contains("uniform sampler2D tex"), "canonical declaration must remain");
|
||||
assertFalse(out.contains("uniform sampler2D textureAtlas"), "alias declaration must be removed: " + out);
|
||||
assertFalse(out.contains("textureAtlas"), "all references to alias must be rewritten: " + out);
|
||||
assertEquals(2, occurrences(out, "texture(tex"), "both references should now read from tex");
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyAliasDeclared_renamedToCanonical() {
|
||||
String src =
|
||||
"#version 330 core\n" +
|
||||
"uniform sampler2D textureAtlas;\n" +
|
||||
"out vec4 fragColor;\n" +
|
||||
"void main() { fragColor = texture(textureAtlas, vec2(0.5)); }\n";
|
||||
|
||||
Transformer t = parse(src);
|
||||
Map<PatchShaderType, Transformer> trees = new EnumMap<>(PatchShaderType.class);
|
||||
trees.put(PatchShaderType.FRAGMENT, t);
|
||||
SamplerAliasDeduplicator.transformGrouped(trees, null);
|
||||
|
||||
String out = format(t);
|
||||
assertTrue(out.contains("uniform sampler2D tex"), "alias should be promoted to canonical: " + out);
|
||||
assertFalse(out.contains("textureAtlas"), "no alias should remain: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void crossStage_consistentCanonical() {
|
||||
String vs =
|
||||
"#version 330 core\n" +
|
||||
"uniform sampler2D textureAtlas;\n" +
|
||||
"void main() { gl_Position = vec4(texture(textureAtlas, vec2(0.0)).xyz, 1.0); }\n";
|
||||
String fs =
|
||||
"#version 330 core\n" +
|
||||
"uniform sampler2D tex;\n" +
|
||||
"uniform sampler2D textureAtlas;\n" +
|
||||
"out vec4 fragColor;\n" +
|
||||
"void main() { fragColor = texture(textureAtlas, vec2(0.5)) + texture(tex, vec2(0.5)); }\n";
|
||||
|
||||
Transformer vt = parse(vs);
|
||||
Transformer ft = parse(fs);
|
||||
Map<PatchShaderType, Transformer> trees = new EnumMap<>(PatchShaderType.class);
|
||||
trees.put(PatchShaderType.VERTEX, vt);
|
||||
trees.put(PatchShaderType.FRAGMENT, ft);
|
||||
SamplerAliasDeduplicator.transformGrouped(trees, null);
|
||||
|
||||
String voutS = format(vt);
|
||||
String foutS = format(ft);
|
||||
|
||||
assertTrue(voutS.contains("uniform sampler2D tex"), "vertex must declare tex: " + voutS);
|
||||
assertFalse(voutS.contains("textureAtlas"), "vertex must not reference alias: " + voutS);
|
||||
assertTrue(foutS.contains("uniform sampler2D tex"), "fragment must declare tex: " + foutS);
|
||||
assertFalse(foutS.contains("uniform sampler2D textureAtlas"), "fragment alias decl must be gone: " + foutS);
|
||||
assertFalse(foutS.contains("textureAtlas"), "fragment must not reference alias: " + foutS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noMatch_unchanged() {
|
||||
String src =
|
||||
"#version 330 core\n" +
|
||||
"uniform sampler2D somethingElse;\n" +
|
||||
"out vec4 fragColor;\n" +
|
||||
"void main() { fragColor = texture(somethingElse, vec2(0.5)); }\n";
|
||||
|
||||
Transformer t = parse(src);
|
||||
Map<PatchShaderType, Transformer> trees = new EnumMap<>(PatchShaderType.class);
|
||||
trees.put(PatchShaderType.FRAGMENT, t);
|
||||
SamplerAliasDeduplicator.transformGrouped(trees, null);
|
||||
|
||||
String out = format(t);
|
||||
assertTrue(out.contains("uniform sampler2D somethingElse"), "untouched uniform must survive: " + out);
|
||||
assertFalse(out.contains("uniform sampler2D tex"), "no spurious tex declaration: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void depthAliasGroup_collapsesToDepthtex0() {
|
||||
String src =
|
||||
"#version 330 core\n" +
|
||||
"uniform sampler2D depthtex0;\n" +
|
||||
"uniform sampler2D gdepthtex;\n" +
|
||||
"out vec4 fragColor;\n" +
|
||||
"void main() { fragColor = texture(gdepthtex, vec2(0.5)) + texture(depthtex0, vec2(0.5)); }\n";
|
||||
|
||||
Transformer t = parse(src);
|
||||
Map<PatchShaderType, Transformer> trees = new EnumMap<>(PatchShaderType.class);
|
||||
trees.put(PatchShaderType.FRAGMENT, t);
|
||||
SamplerAliasDeduplicator.transformGrouped(trees, null);
|
||||
|
||||
String out = format(t);
|
||||
assertTrue(out.contains("uniform sampler2D depthtex0"));
|
||||
assertFalse(out.contains("gdepthtex"), out);
|
||||
}
|
||||
|
||||
private static int occurrences(String haystack, String needle) {
|
||||
int n = 0, i = 0;
|
||||
while ((i = haystack.indexOf(needle, i)) != -1) { n++; i += needle.length(); }
|
||||
return n;
|
||||
}
|
||||
}
|
||||
+310
@@ -0,0 +1,310 @@
|
||||
package net.coderbot.iris.pipeline.transform;
|
||||
|
||||
import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
|
||||
import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat;
|
||||
import com.gtnewhorizons.angelica.glsm.texture.PixelFormat;
|
||||
import com.gtnewhorizons.angelica.glsm.texture.PixelType;
|
||||
import com.gtnewhorizons.angelica.glsm.texture.TextureType;
|
||||
import net.coderbot.iris.gl.image.ImageInformation;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.taumc.glsl.ShaderParser;
|
||||
import org.taumc.glsl.ShaderPrinter;
|
||||
import org.taumc.glsl.Transformer;
|
||||
|
||||
import java.util.EnumMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class SamplerToStorageImageRewriterTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
SamplerToStorageImageRewriter.setActiveCandidates(Set.of());
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
SamplerToStorageImageRewriter.setActiveCandidates(Set.of());
|
||||
}
|
||||
|
||||
private static Transformer parse(String src) {
|
||||
return new Transformer(ShaderParser.parseShader(src).full());
|
||||
}
|
||||
|
||||
private static String format(Transformer t) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
t.mutateTree(tree -> sb.append(ShaderPrinter.getFormattedShader(tree)));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@Test
|
||||
void integerSampler_texelFetchOnly_rewrittenToImageLoad() {
|
||||
SamplerToStorageImageRewriter.setActiveCandidates(Set.of(
|
||||
new SamplerToStorageImageRewriter.Candidate("wsr_sampler", "wsr_img", "r16ui", 3, false)
|
||||
));
|
||||
|
||||
String src =
|
||||
"#version 460 core\n" +
|
||||
"uniform usampler3D wsr_sampler;\n" +
|
||||
"out vec4 fragColor;\n" +
|
||||
"void main() {\n" +
|
||||
" uint v = texelFetch(wsr_sampler, ivec3(1,2,3), 0).r;\n" +
|
||||
" fragColor = vec4(float(v));\n" +
|
||||
"}\n";
|
||||
|
||||
Transformer t = parse(src);
|
||||
Map<PatchShaderType, Transformer> trees = new EnumMap<>(PatchShaderType.class);
|
||||
trees.put(PatchShaderType.FRAGMENT, t);
|
||||
SamplerToStorageImageRewriter.transformGrouped(trees, null);
|
||||
|
||||
String out = format(t);
|
||||
assertFalse(out.contains("usampler3D wsr_sampler"), "old sampler declaration must be gone: " + out);
|
||||
assertTrue(out.contains("uimage3D wsr_img"), "image declaration must be injected: " + out);
|
||||
assertTrue(out.contains("readonly"), "image must be marked readonly: " + out);
|
||||
assertTrue(out.contains("layout(r16ui)"), "layout qualifier must be present: " + out);
|
||||
assertTrue(out.contains("imageLoad(wsr_img,"), "texelFetch must be rewritten to imageLoad: " + out);
|
||||
assertFalse(out.contains("texelFetch(wsr_img"), "texelFetch must not remain on image: " + out);
|
||||
assertFalse(out.contains("wsr_sampler"), "no reference to the old sampler name: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void filteredRead_abortsRewrite() {
|
||||
SamplerToStorageImageRewriter.setActiveCandidates(Set.of(
|
||||
new SamplerToStorageImageRewriter.Candidate("ff_sampler", "ff_img", "r16ui", 3, false)
|
||||
));
|
||||
|
||||
String src =
|
||||
"#version 460 core\n" +
|
||||
"uniform usampler3D ff_sampler;\n" +
|
||||
"out vec4 fragColor;\n" +
|
||||
"void main() {\n" +
|
||||
" uvec4 v = texture(ff_sampler, vec3(0.5, 0.5, 0.5));\n" +
|
||||
" fragColor = vec4(float(v.r));\n" +
|
||||
"}\n";
|
||||
|
||||
Transformer t = parse(src);
|
||||
Map<PatchShaderType, Transformer> trees = new EnumMap<>(PatchShaderType.class);
|
||||
trees.put(PatchShaderType.FRAGMENT, t);
|
||||
SamplerToStorageImageRewriter.transformGrouped(trees, null);
|
||||
|
||||
String out = format(t);
|
||||
assertTrue(out.contains("usampler3D ff_sampler"), "sampler must remain when filtered read present: " + out);
|
||||
assertFalse(out.contains("uimage3D"), "no image injected: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void legacyTexture2DRead_abortsRewrite() {
|
||||
SamplerToStorageImageRewriter.setActiveCandidates(Set.of(
|
||||
new SamplerToStorageImageRewriter.Candidate("puddle_sampler", "puddle_img", "r8ui", 2, false)
|
||||
));
|
||||
|
||||
String src =
|
||||
"#version 460 core\n" +
|
||||
"uniform usampler2D puddle_sampler;\n" +
|
||||
"out vec4 fragColor;\n" +
|
||||
"void main() {\n" +
|
||||
" float noPuddles = texture2D(puddle_sampler, vec2(0.5)).r;\n" +
|
||||
" fragColor = vec4(noPuddles);\n" +
|
||||
"}\n";
|
||||
|
||||
Transformer t = parse(src);
|
||||
Map<PatchShaderType, Transformer> trees = new EnumMap<>(PatchShaderType.class);
|
||||
trees.put(PatchShaderType.FRAGMENT, t);
|
||||
SamplerToStorageImageRewriter.transformGrouped(trees, null);
|
||||
|
||||
String out = format(t);
|
||||
assertTrue(out.contains("usampler2D puddle_sampler"), "sampler must remain when read with texture2D: " + out);
|
||||
assertFalse(out.contains("puddle_img"), "no image may be injected: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void legacyTexture3DRead_abortsRewrite() {
|
||||
SamplerToStorageImageRewriter.setActiveCandidates(Set.of(
|
||||
new SamplerToStorageImageRewriter.Candidate("voxel_sampler", "voxel_img", "r16ui", 3, false)
|
||||
));
|
||||
|
||||
String src =
|
||||
"#version 460 core\n" +
|
||||
"uniform usampler3D voxel_sampler;\n" +
|
||||
"out vec4 fragColor;\n" +
|
||||
"void main() {\n" +
|
||||
" fragColor = vec4(float(texture3D(voxel_sampler, vec3(0.5)).r));\n" +
|
||||
"}\n";
|
||||
|
||||
Transformer t = parse(src);
|
||||
Map<PatchShaderType, Transformer> trees = new EnumMap<>(PatchShaderType.class);
|
||||
trees.put(PatchShaderType.FRAGMENT, t);
|
||||
SamplerToStorageImageRewriter.transformGrouped(trees, null);
|
||||
|
||||
String out = format(t);
|
||||
assertTrue(out.contains("usampler3D voxel_sampler"), "sampler must remain: " + out);
|
||||
assertFalse(out.contains("voxel_img"), "no image may be injected: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void floatSamplerNotInCandidateSet_unchanged() {
|
||||
SamplerToStorageImageRewriter.setActiveCandidates(Set.of());
|
||||
|
||||
String src =
|
||||
"#version 460 core\n" +
|
||||
"uniform sampler3D ff_sampler;\n" +
|
||||
"out vec4 fragColor;\n" +
|
||||
"void main() {\n" +
|
||||
" fragColor = texelFetch(ff_sampler, ivec3(0), 0);\n" +
|
||||
"}\n";
|
||||
|
||||
Transformer t = parse(src);
|
||||
Map<PatchShaderType, Transformer> trees = new EnumMap<>(PatchShaderType.class);
|
||||
trees.put(PatchShaderType.FRAGMENT, t);
|
||||
SamplerToStorageImageRewriter.transformGrouped(trees, null);
|
||||
|
||||
String out = format(t);
|
||||
assertTrue(out.contains("sampler3D ff_sampler"), "float sampler must stay sampler: " + out);
|
||||
assertFalse(out.contains("uimage3D"), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void crossStage_samplerOnlyInFragment_vertexUntouched() {
|
||||
SamplerToStorageImageRewriter.setActiveCandidates(Set.of(
|
||||
new SamplerToStorageImageRewriter.Candidate("wsr_sampler", "wsr_img", "r16ui", 3, false)
|
||||
));
|
||||
|
||||
String vs =
|
||||
"#version 460 core\n" +
|
||||
"void main() { gl_Position = vec4(0.0); }\n";
|
||||
String fs =
|
||||
"#version 460 core\n" +
|
||||
"uniform usampler3D wsr_sampler;\n" +
|
||||
"out vec4 fragColor;\n" +
|
||||
"void main() {\n" +
|
||||
" uvec4 v = texelFetch(wsr_sampler, ivec3(0), 0);\n" +
|
||||
" fragColor = vec4(float(v.r));\n" +
|
||||
"}\n";
|
||||
|
||||
Transformer vt = parse(vs);
|
||||
Transformer ft = parse(fs);
|
||||
Map<PatchShaderType, Transformer> trees = new EnumMap<>(PatchShaderType.class);
|
||||
trees.put(PatchShaderType.VERTEX, vt);
|
||||
trees.put(PatchShaderType.FRAGMENT, ft);
|
||||
SamplerToStorageImageRewriter.transformGrouped(trees, null);
|
||||
|
||||
String fout = format(ft);
|
||||
assertFalse(fout.contains("usampler3D wsr_sampler"), fout);
|
||||
assertTrue(fout.contains("uimage3D wsr_img"), fout);
|
||||
assertTrue(fout.contains("imageLoad(wsr_img,"), fout);
|
||||
|
||||
String vout = format(vt);
|
||||
assertFalse(vout.contains("uimage3D"), "vertex must be untouched: " + vout);
|
||||
assertFalse(vout.contains("wsr_img"), vout);
|
||||
}
|
||||
|
||||
@Test
|
||||
void multipleCandidates_sameStage_rewriteAllWithoutAnchorBug() {
|
||||
SamplerToStorageImageRewriter.setActiveCandidates(Set.of(
|
||||
new SamplerToStorageImageRewriter.Candidate("wsr_sampler", "wsr_img", "r16ui", 3, false),
|
||||
new SamplerToStorageImageRewriter.Candidate("wsr_lod_sampler", "wsr_lod_img", "r8ui", 3, false),
|
||||
new SamplerToStorageImageRewriter.Candidate("voxel_sampler", "voxel_img", "r16ui", 3, false)
|
||||
));
|
||||
|
||||
String src =
|
||||
"#version 460 core\n" +
|
||||
"uniform mat4 someMatrix;\n" +
|
||||
"uniform usampler3D wsr_sampler;\n" +
|
||||
"uniform usampler3D wsr_lod_sampler;\n" +
|
||||
"uniform usampler3D voxel_sampler;\n" +
|
||||
"out vec4 fragColor;\n" +
|
||||
"void main() {\n" +
|
||||
" uint a = texelFetch(wsr_sampler, ivec3(0), 0).r;\n" +
|
||||
" uint b = texelFetch(wsr_lod_sampler, ivec3(0), 0).r;\n" +
|
||||
" uint c = texelFetch(voxel_sampler, ivec3(0), 0).r;\n" +
|
||||
" fragColor = vec4(float(a + b + c));\n" +
|
||||
"}\n";
|
||||
|
||||
Transformer t = parse(src);
|
||||
Map<PatchShaderType, Transformer> trees = new EnumMap<>(PatchShaderType.class);
|
||||
trees.put(PatchShaderType.FRAGMENT, t);
|
||||
SamplerToStorageImageRewriter.transformGrouped(trees, null);
|
||||
|
||||
String out = format(t);
|
||||
assertFalse(out.contains("usampler3D"), "no sampler declarations left: " + out);
|
||||
assertTrue(out.contains("uimage3D wsr_img"), out);
|
||||
assertTrue(out.contains("uimage3D wsr_lod_img"), out);
|
||||
assertTrue(out.contains("uimage3D voxel_img"), out);
|
||||
assertTrue(out.contains("imageLoad(wsr_img,"), out);
|
||||
assertTrue(out.contains("imageLoad(wsr_lod_img,"), out);
|
||||
assertTrue(out.contains("imageLoad(voxel_img,"), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void imageAlreadyDeclared_skipsRewrite() {
|
||||
SamplerToStorageImageRewriter.setActiveCandidates(Set.of(
|
||||
new SamplerToStorageImageRewriter.Candidate("wsr_sampler", "wsr_img", "r16ui", 3, false)
|
||||
));
|
||||
|
||||
String src =
|
||||
"#version 460 core\n" +
|
||||
"uniform usampler3D wsr_sampler;\n" +
|
||||
"layout(r16ui) writeonly uniform uimage3D wsr_img;\n" +
|
||||
"out vec4 fragColor;\n" +
|
||||
"void main() {\n" +
|
||||
" uvec4 v = texelFetch(wsr_sampler, ivec3(0), 0);\n" +
|
||||
" imageStore(wsr_img, ivec3(0), v);\n" +
|
||||
" fragColor = vec4(float(v.r));\n" +
|
||||
"}\n";
|
||||
|
||||
Transformer t = parse(src);
|
||||
Map<PatchShaderType, Transformer> trees = new EnumMap<>(PatchShaderType.class);
|
||||
trees.put(PatchShaderType.FRAGMENT, t);
|
||||
SamplerToStorageImageRewriter.transformGrouped(trees, null);
|
||||
|
||||
String out = format(t);
|
||||
assertTrue(out.contains("usampler3D wsr_sampler"), "sampler decl must remain: " + out);
|
||||
assertTrue(out.contains("writeonly"), "writeonly image decl must remain: " + out);
|
||||
assertEquals(1, occurrences(out, "uniform uimage3D wsr_img"), "exactly one uimage3D wsr_img declaration (no second readonly injected): " + out);
|
||||
assertFalse(out.contains("readonly"), "no readonly decl injected: " + out);
|
||||
assertTrue(out.contains("texelFetch(wsr_sampler"), "texelFetch must NOT be rewritten to imageLoad: " + out);
|
||||
assertTrue(out.contains("imageStore(wsr_img"), "imageStore on writer must survive: " + out);
|
||||
}
|
||||
|
||||
private static int occurrences(String haystack, String needle) {
|
||||
int n = 0, i = 0;
|
||||
while ((i = haystack.indexOf(needle, i)) != -1) { n++; i += needle.length(); }
|
||||
return n;
|
||||
}
|
||||
|
||||
@Test
|
||||
void noActiveCandidates_noOp() {
|
||||
String src =
|
||||
"#version 460 core\n" +
|
||||
"uniform usampler3D wsr_sampler;\n" +
|
||||
"out vec4 fragColor;\n" +
|
||||
"void main() { fragColor = vec4(float(texelFetch(wsr_sampler, ivec3(0), 0).r)); }\n";
|
||||
|
||||
Transformer t = parse(src);
|
||||
Map<PatchShaderType, Transformer> trees = new EnumMap<>(PatchShaderType.class);
|
||||
trees.put(PatchShaderType.FRAGMENT, t);
|
||||
SamplerToStorageImageRewriter.transformGrouped(trees, null);
|
||||
|
||||
String out = format(t);
|
||||
assertTrue(out.contains("usampler3D wsr_sampler"), "sampler must remain when no candidates: " + out);
|
||||
assertFalse(out.contains("uimage3D"), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void integerCustomImages_produceNoCandidates_onNonSdlBackend() {
|
||||
assertFalse(BackendManager.RENDER_BACKEND.isSDLGPU(), "test backend must not be SDL-GPU for this to mean anything");
|
||||
|
||||
final ImageInformation voxel = new ImageInformation("voxel_img", "voxel_sampler", TextureType.TEXTURE_3D,
|
||||
PixelFormat.RED_INTEGER, InternalTextureFormat.R16UI, PixelType.UNSIGNED_INT,
|
||||
512, 256, 512, true, false, 0.0f, 0.0f);
|
||||
|
||||
assertTrue(SamplerToStorageImageRewriter.buildCandidates(List.of(voxel)).isEmpty(), "integer custom images must not become storage images off SDL-GPU");
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,15 @@
|
||||
package net.coderbot.iris.pipeline.transform;
|
||||
|
||||
import com.gtnewhorizons.angelica.glsm.RenderSystem;
|
||||
import com.gtnewhorizons.angelica.glsm.testutil.Reflect;
|
||||
import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.taumc.glsl.ShaderParser;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -15,21 +19,206 @@ import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
class ShaderTransformerTest {
|
||||
|
||||
private static boolean savedImageLoadStore;
|
||||
|
||||
private static void setImageLoadStore(boolean value) throws Exception {
|
||||
Reflect.setStatic(RenderSystem.class, "supportsImageLoadStore", value);
|
||||
}
|
||||
|
||||
private static boolean getImageLoadStore() throws Exception {
|
||||
return Reflect.getStatic(RenderSystem.class, "supportsImageLoadStore");
|
||||
}
|
||||
|
||||
@BeforeAll
|
||||
static void initShaderTransformer() throws Exception {
|
||||
Field maxGlsl = RenderSystem.class.getDeclaredField("maxGlslVersion");
|
||||
maxGlsl.setAccessible(true);
|
||||
maxGlsl.setInt(null, 460);
|
||||
Reflect.setStatic(RenderSystem.class, "maxGlslVersion", 460);
|
||||
|
||||
savedImageLoadStore = getImageLoadStore();
|
||||
setImageLoadStore(true);
|
||||
|
||||
ShaderTransformer.clearCache();
|
||||
ShaderTransformer.init();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void restoreCapabilities() throws Exception {
|
||||
setImageLoadStore(savedImageLoadStore);
|
||||
ShaderTransformer.clearCache();
|
||||
TransformPatcher.clearCache();
|
||||
ShaderTransformer.init();
|
||||
}
|
||||
|
||||
private static int versionOf(String shader) {
|
||||
final Matcher m = Pattern.compile("#version\\s+(\\d+)").matcher(shader);
|
||||
assertTrue(m.find(), "no #version in\n\n" + shader);
|
||||
return Integer.parseInt(m.group(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void storageImageRewrite_hoistsEmittedVersion() {
|
||||
TransformPatcher.clearCache();
|
||||
ShaderTransformer.clearCache();
|
||||
SamplerToStorageImageRewriter.setActiveCandidates(Set.of(new SamplerToStorageImageRewriter.Candidate("voxel_sampler", "voxel_img", "r16ui", 3, false)));
|
||||
try {
|
||||
final String vertex = "#version 330 core\nvoid main(){ gl_Position = vec4(0.0); }";
|
||||
final String fragment = String.join("\n",
|
||||
"#version 330 core",
|
||||
"uniform usampler3D voxel_sampler;",
|
||||
"void main(){ gl_FragColor = vec4(float(texelFetch(voxel_sampler, ivec3(0), 0).r)); }",
|
||||
"");
|
||||
|
||||
final Map<PatchShaderType, String> out = TransformPatcher.patchComposite(vertex, null, fragment);
|
||||
assertNotNull(out);
|
||||
final String fsh = out.get(PatchShaderType.FRAGMENT);
|
||||
final String vsh = out.get(PatchShaderType.VERTEX);
|
||||
|
||||
assertTrue(fsh.contains("imageLoad"), "fixture must actually exercise the rewrite\n\n" + fsh);
|
||||
assertFalse(fsh.contains("usampler3D voxel_sampler"), fsh);
|
||||
|
||||
assertTrue(versionOf(fsh) >= 420, "injected imageLoad needs GLSL 420\n\n" + fsh);
|
||||
assertEquals(330, versionOf(vsh), "the vertex declares no candidate sampler and must not be inflated\n\n" + vsh);
|
||||
} finally {
|
||||
SamplerToStorageImageRewriter.setActiveCandidates(Set.of());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void filteredRead_doesNotHoistVersion() {
|
||||
TransformPatcher.clearCache();
|
||||
ShaderTransformer.clearCache();
|
||||
SamplerToStorageImageRewriter.setActiveCandidates(Set.of(new SamplerToStorageImageRewriter.Candidate("voxel_sampler", "voxel_img", "r16ui", 3, false)));
|
||||
try {
|
||||
final String vertex = "#version 330 core\nvoid main(){ gl_Position = vec4(0.0); }";
|
||||
final String fragment = String.join("\n",
|
||||
"#version 330 core",
|
||||
"uniform usampler3D voxel_sampler;",
|
||||
"void main(){ gl_FragColor = vec4(float(texture(voxel_sampler, vec3(0.5)).r)); }",
|
||||
"");
|
||||
|
||||
final Map<PatchShaderType, String> out = TransformPatcher.patchComposite(vertex, null, fragment);
|
||||
assertNotNull(out);
|
||||
final String fsh = out.get(PatchShaderType.FRAGMENT);
|
||||
|
||||
assertTrue(fsh.contains("usampler3D voxel_sampler"), "rewrite must abort on a filtered read\n\n" + fsh);
|
||||
assertFalse(fsh.contains("imageLoad"), fsh);
|
||||
assertEquals(330, versionOf(fsh), fsh);
|
||||
} finally {
|
||||
SamplerToStorageImageRewriter.setActiveCandidates(Set.of());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void noCandidates_versionUnchanged() {
|
||||
TransformPatcher.clearCache();
|
||||
ShaderTransformer.clearCache();
|
||||
final String vertex = "#version 330 core\nvoid main(){ gl_Position = vec4(0.0); }";
|
||||
final String fragment = "#version 330 core\nvoid main(){ gl_FragColor = vec4(1.0); }";
|
||||
|
||||
final Map<PatchShaderType, String> out = TransformPatcher.patchComposite(vertex, null, fragment);
|
||||
assertNotNull(out);
|
||||
assertTrue(out.get(PatchShaderType.VERTEX).startsWith("#version 330 core\n"), out.get(PatchShaderType.VERTEX));
|
||||
assertTrue(out.get(PatchShaderType.FRAGMENT).startsWith("#version 330 core\n"), out.get(PatchShaderType.FRAGMENT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void computeStorageImageRewrite_hoistsEmittedVersion() {
|
||||
TransformPatcher.clearCache();
|
||||
ShaderTransformer.clearCache();
|
||||
SamplerToStorageImageRewriter.setActiveCandidates(Set.of(new SamplerToStorageImageRewriter.Candidate("voxel_sampler", "voxel_img", "r16ui", 3, false)));
|
||||
try {
|
||||
final String compute = String.join("\n",
|
||||
"#version 330 core",
|
||||
"layout(local_size_x = 8) in;",
|
||||
"uniform usampler3D voxel_sampler;",
|
||||
"out vec4 unused;",
|
||||
"void main(){ unused = vec4(float(texelFetch(voxel_sampler, ivec3(gl_GlobalInvocationID), 0).x)); }",
|
||||
"");
|
||||
|
||||
final String out = TransformPatcher.patchCompute("shadowcomp", compute, null, null);
|
||||
assertNotNull(out);
|
||||
assertTrue(out.contains("imageLoad"), "fixture must actually exercise the rewrite\n\n" + out);
|
||||
assertTrue(versionOf(out) >= 420, "injected imageLoad needs GLSL 420\n\n" + out);
|
||||
} finally {
|
||||
SamplerToStorageImageRewriter.setActiveCandidates(Set.of());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void packDeclaredImageTypeHoistsWithoutImageLoad() {
|
||||
TransformPatcher.clearCache();
|
||||
ShaderTransformer.clearCache();
|
||||
final String vertex = "#version 330 core\nvoid main(){ gl_Position = vec4(0.0); }";
|
||||
final String fragment = String.join("\n",
|
||||
"#version 330 core",
|
||||
"layout(r16ui) readonly uniform uimage3D voxel_img;",
|
||||
"void main(){ gl_FragColor = vec4(float(imageSize(voxel_img).x)); }",
|
||||
"");
|
||||
|
||||
final Map<PatchShaderType, String> out = TransformPatcher.patchComposite(vertex, null, fragment);
|
||||
assertNotNull(out);
|
||||
final String fsh = out.get(PatchShaderType.FRAGMENT);
|
||||
assertTrue(versionOf(fsh) >= 420, "uimage3D declaration alone must hoist to 420\n\n" + fsh);
|
||||
}
|
||||
|
||||
@Test
|
||||
void computeIntegerSamplerBecomesStorageImage() {
|
||||
TransformPatcher.clearCache();
|
||||
ShaderTransformer.clearCache();
|
||||
SamplerToStorageImageRewriter.setActiveCandidates(Set.of(
|
||||
new SamplerToStorageImageRewriter.Candidate("voxel_sampler", "voxel_img", "r16ui", 3, false)));
|
||||
try {
|
||||
final String compute = String.join("\n",
|
||||
"#version 460 core",
|
||||
"layout(local_size_x = 8) in;",
|
||||
"uniform usampler3D voxel_sampler;",
|
||||
"layout(r16ui) writeonly uniform uimage3D floodfill_img;",
|
||||
"void main() {",
|
||||
" uint v = texelFetch(voxel_sampler, ivec3(gl_GlobalInvocationID), 0).x;",
|
||||
" imageStore(floodfill_img, ivec3(gl_GlobalInvocationID), uvec4(v, 0u, 0u, 0u));",
|
||||
"}",
|
||||
"");
|
||||
final String out = TransformPatcher.patchCompute("shadowcomp", compute, null, null);
|
||||
assertNotNull(out);
|
||||
final String norm = out.replaceAll("\\s+", " ");
|
||||
assertFalse(norm.contains("usampler3D voxel_sampler"),
|
||||
"an integer sampler cannot be bound on SDL_GPU and must become a storage image\n\n" + out);
|
||||
assertTrue(norm.contains("uimage3D voxel_img"), "expected the rewritten storage image\n\n" + out);
|
||||
assertTrue(norm.contains("imageLoad ( voxel_img"), "texelFetch must become imageLoad\n\n" + out);
|
||||
} finally {
|
||||
SamplerToStorageImageRewriter.setActiveCandidates(Set.of());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void samplerAliasesSurvive_onNonSdlBackend() {
|
||||
assertFalse(BackendManager.RENDER_BACKEND.isSDLGPU(), "test backend must not be SDL-GPU for this to mean anything");
|
||||
TransformPatcher.clearCache();
|
||||
ShaderTransformer.clearCache();
|
||||
|
||||
final String vertex = "#version 330 core\nvoid main(){gl_Position = vec4(0.0);}";
|
||||
final String fragment = String.join("\n",
|
||||
"#version 330 core",
|
||||
"uniform sampler2D gtexture;",
|
||||
"in vec2 uv;",
|
||||
"void main(){ gl_FragColor = texture2D(gtexture, uv); }",
|
||||
"");
|
||||
|
||||
final Map<PatchShaderType, String> transformed = TransformPatcher.patchComposite(vertex, null, fragment);
|
||||
assertNotNull(transformed);
|
||||
final String out = transformed.get(PatchShaderType.FRAGMENT);
|
||||
assertNotNull(out);
|
||||
assertTrue(out.contains("gtexture"), "the pack's own sampler name must survive off SDL-GPU\n\n" + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void transformIsDeterministicUnderConcurrency() throws ExecutionException, InterruptedException {
|
||||
TransformPatcher.clearCache();
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package net.coderbot.iris.rendertarget;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import it.unimi.dsi.fastutil.ints.IntArrayList;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class ParityFlipStateTest {
|
||||
|
||||
@Test
|
||||
void paritySetExcludesClearedBuffers() {
|
||||
ParityFlipState state = new ParityFlipState(true);
|
||||
state.finalizeParitySet(ImmutableSet.of(1, 2, 7), IntArrayList.of(2));
|
||||
assertTrue(state.isEnabled());
|
||||
assertEquals(ImmutableSet.of(1, 7), state.parityBuffers());
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyParitySetDisables() {
|
||||
ParityFlipState state = new ParityFlipState(true);
|
||||
state.finalizeParitySet(ImmutableSet.of(2), IntArrayList.of(2));
|
||||
assertFalse(state.isEnabled());
|
||||
state.onFrameStart();
|
||||
assertFalse(state.isOdd());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveXorsParityMembersOnOddFramesOnly() {
|
||||
ParityFlipState state = new ParityFlipState(true);
|
||||
state.finalizeParitySet(ImmutableSet.of(1, 7), IntArrayList.of());
|
||||
|
||||
ImmutableSet<Integer> even = ImmutableSet.of(1, 3);
|
||||
assertEquals(even, state.resolve(even));
|
||||
|
||||
state.onFrameStart();
|
||||
assertTrue(state.isOdd());
|
||||
assertEquals(ImmutableSet.of(3, 7), state.resolve(even));
|
||||
|
||||
state.onFrameStart();
|
||||
assertFalse(state.isOdd());
|
||||
assertEquals(even, state.resolve(even));
|
||||
}
|
||||
|
||||
@Test
|
||||
void disabledStateIsIdentity() {
|
||||
ParityFlipState state = new ParityFlipState(false);
|
||||
state.finalizeParitySet(ImmutableSet.of(1), IntArrayList.of());
|
||||
state.onFrameStart();
|
||||
assertFalse(state.isOdd());
|
||||
ImmutableSet<Integer> set = ImmutableSet.of(1, 2);
|
||||
assertEquals(set, state.resolve(set));
|
||||
assertFalse(state.affectsAny(new int[] { 1 }));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetForcesEvenAfterFullClear() {
|
||||
ParityFlipState state = new ParityFlipState(true);
|
||||
state.finalizeParitySet(ImmutableSet.of(1), IntArrayList.of());
|
||||
state.onFrameStart();
|
||||
assertTrue(state.isOdd());
|
||||
state.reset();
|
||||
assertFalse(state.isOdd());
|
||||
}
|
||||
|
||||
@Test
|
||||
void noToggleBeforeFinalize() {
|
||||
ParityFlipState state = new ParityFlipState(true);
|
||||
state.onFrameStart();
|
||||
assertFalse(state.isOdd());
|
||||
}
|
||||
|
||||
@Test
|
||||
void affectsAnyChecksDrawBuffers() {
|
||||
ParityFlipState state = new ParityFlipState(true);
|
||||
state.finalizeParitySet(ImmutableSet.of(4, 5), IntArrayList.of());
|
||||
assertTrue(state.affectsAny(new int[] { 0, 5 }));
|
||||
assertFalse(state.affectsAny(new int[] { 0, 1, 2 }));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package net.coderbot.iris.uniforms;
|
||||
|
||||
import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
|
||||
import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
|
||||
import com.gtnewhorizons.angelica.glsm.hooks.PerFrameUniformBlock;
|
||||
import net.coderbot.iris.gl.uniform.ManifestCollectingHolder;
|
||||
import net.coderbot.iris.gl.uniform.UniformManifest;
|
||||
import org.joml.Matrix4f;
|
||||
import org.joml.Matrix4fc;
|
||||
import org.joml.Vector3f;
|
||||
import org.joml.Vector3fc;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class PerFrameUniformBlockHarvesterTest {
|
||||
|
||||
private static UniformManifest manifest() {
|
||||
final ManifestCollectingHolder h = new ManifestCollectingHolder();
|
||||
final Vector3fc vec = new Vector3f();
|
||||
final Matrix4fc mat = new Matrix4f();
|
||||
h.uniform3f(PER_FRAME, "cameraPosition", () -> vec)
|
||||
.uniform3f(PER_FRAME, "fogColor", () -> vec)
|
||||
.uniform1f(PER_FRAME, "iris_FogStart", () -> 0.0f)
|
||||
.uniform1f(PER_FRAME, "iris_FogEnd", () -> 0.0f)
|
||||
.uniform1f(PER_FRAME, "iris_FogDensity", () -> 0.0f)
|
||||
.uniformMatrix(PER_FRAME, "gbufferModelView", () -> mat)
|
||||
.uniformMatrix(PER_FRAME, "gbufferModelViewInverse", () -> mat)
|
||||
.uniformMatrix(PER_FRAME, "gbufferProjection", () -> mat)
|
||||
.uniformMatrix(PER_FRAME, "shadowModelView", () -> mat);
|
||||
return h.build();
|
||||
}
|
||||
|
||||
private static List<String> blockNames() {
|
||||
final PerFrameUniformBlock block = PerFrameUniformBlockHarvester.toBlock(manifest(), manifest());
|
||||
return block.members().stream().map(PerFrameUniformBlock.Member::name).toList();
|
||||
}
|
||||
|
||||
@Test
|
||||
void liveStateUniformsAreExcluded() {
|
||||
final List<String> names = blockNames();
|
||||
for (String excluded : List.of("fogColor", "iris_FogStart", "iris_FogEnd", "iris_FogDensity", "gbufferModelView", "gbufferModelViewInverse", "gbufferProjection")) {
|
||||
assertFalse(names.contains(excluded), excluded + " reads live per-draw state and must stay on the push path");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void frameGlobalUniformsAreKept() {
|
||||
final List<String> names = blockNames();
|
||||
assertTrue(names.contains("cameraPosition"), "camera position is frame-scoped");
|
||||
assertTrue(names.contains("shadowModelView"), "shadow matrices are pure functions of pack directives");
|
||||
}
|
||||
|
||||
@Test
|
||||
void orderIsDeterministic() {
|
||||
assertEquals(blockNames(), blockNames());
|
||||
}
|
||||
|
||||
private static List<String> perPassNames() {
|
||||
final PerFrameUniformBlock block = PerFrameUniformBlockHarvester.toPerPassBlock(manifest(), manifest());
|
||||
return block.members().stream().map(PerFrameUniformBlock.Member::name).toList();
|
||||
}
|
||||
|
||||
@Test
|
||||
void perPassBlockHoldsExactlyTheLiveStateUniforms() {
|
||||
assertEquals(List.of("fogColor", "iris_FogStart", "iris_FogEnd", "iris_FogDensity", "gbufferModelView", "gbufferModelViewInverse", "gbufferProjection"), perPassNames());
|
||||
}
|
||||
|
||||
@Test
|
||||
void blocksAreDisjoint() {
|
||||
final List<String> perFrame = blockNames();
|
||||
for (String name : perPassNames()) {
|
||||
assertFalse(perFrame.contains(name), name + " must live in exactly one block");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void noBlockIsHarvestedOffTheSdlBackend() {
|
||||
assertFalse(BackendManager.RENDER_BACKEND.isSDLGPU(), "test backend must not be SDL-GPU for this guard to mean anything");
|
||||
GLSMHooks.perFrameUniformBlock = new PerFrameUniformBlock(List.of());
|
||||
GLSMHooks.perPassUniformBlock = new PerFrameUniformBlock(List.of());
|
||||
PerFrameUniformBlockHarvester.harvest(null);
|
||||
assertNull(GLSMHooks.perFrameUniformBlock, "harvest must clear the block on any non-SDL backend");
|
||||
assertNull(GLSMHooks.perPassUniformBlock, "harvest must clear the per-pass block on any non-SDL backend");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package net.coderbot.iris.uniforms;
|
||||
|
||||
import org.joml.Matrix4f;
|
||||
import org.joml.Matrix4fc;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PreviousMatrixSharingTest {
|
||||
|
||||
private final Matrix4f source = new Matrix4f();
|
||||
|
||||
@BeforeEach
|
||||
void resetFrameCounter() {
|
||||
SystemTimeUniforms.COUNTER.reset();
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameNameSharesOneInstance() {
|
||||
final MatrixUniforms.Previous a = MatrixUniforms.Previous.shared("testShared", () -> source);
|
||||
final MatrixUniforms.Previous b = MatrixUniforms.Previous.shared("testShared", () -> source);
|
||||
assertSame(a, b);
|
||||
assertNotSame(a, MatrixUniforms.Previous.shared("testSharedOther", () -> source));
|
||||
}
|
||||
|
||||
@Test
|
||||
void advancesOncePerFrameAndReturnsLastFrameValue() {
|
||||
final MatrixUniforms.Previous prev = new MatrixUniforms.Previous(() -> source);
|
||||
|
||||
source.translation(1f, 0f, 0f);
|
||||
assertEquals(new Matrix4f(), new Matrix4f(prev.get()), "first frame previous is identity");
|
||||
|
||||
SystemTimeUniforms.COUNTER.beginFrame();
|
||||
source.translation(2f, 0f, 0f);
|
||||
final Matrix4fc frame2First = new Matrix4f(prev.get());
|
||||
assertEquals(new Matrix4f().translation(1f, 0f, 0f), frame2First, "frame 2 sees frame 1 value");
|
||||
|
||||
source.translation(3f, 0f, 0f);
|
||||
assertEquals(frame2First, new Matrix4f(prev.get()));
|
||||
|
||||
SystemTimeUniforms.COUNTER.beginFrame();
|
||||
assertEquals(new Matrix4f().translation(2f, 0f, 0f), new Matrix4f(prev.get()), "frame 3 sees the value captured at frame 2's first read, not later mid-frame mutations");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package net.coderbot.iris.uniforms.custom;
|
||||
|
||||
import net.coderbot.iris.gl.uniform.UniformUpdateFrequency;
|
||||
import net.coderbot.iris.uniforms.custom.cached.Float3VectorCachedUniform;
|
||||
import net.coderbot.iris.uniforms.custom.cached.FloatCachedUniform;
|
||||
import org.joml.Vector3f;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
|
||||
class CachedUniformValueGenTest {
|
||||
|
||||
@Test
|
||||
void floatGenAdvancesOnlyOnChange() {
|
||||
final float[] value = {5.0f};
|
||||
final FloatCachedUniform u = new FloatCachedUniform("test", UniformUpdateFrequency.CUSTOM, () -> value[0]);
|
||||
|
||||
assertEquals(0, u.valueGen());
|
||||
u.update();
|
||||
assertEquals(1, u.valueGen(), "initial value differs from the 0-default cache");
|
||||
u.update();
|
||||
u.update();
|
||||
assertEquals(1, u.valueGen(), "unchanged value must not advance the generation");
|
||||
value[0] = 6.0f;
|
||||
u.update();
|
||||
assertEquals(2, u.valueGen());
|
||||
u.update();
|
||||
assertEquals(2, u.valueGen());
|
||||
}
|
||||
|
||||
@Test
|
||||
void vectorGenAdvancesOnlyOnChange() {
|
||||
final Vector3f value = new Vector3f(1, 2, 3);
|
||||
final Float3VectorCachedUniform u = new Float3VectorCachedUniform("test", UniformUpdateFrequency.CUSTOM, () -> value);
|
||||
|
||||
u.update();
|
||||
final int afterFirst = u.valueGen();
|
||||
u.update();
|
||||
assertEquals(afterFirst, u.valueGen(), "same vector content must not advance");
|
||||
value.set(1, 2, 4);
|
||||
u.update();
|
||||
assertEquals(afterFirst + 1, u.valueGen());
|
||||
}
|
||||
|
||||
@Test
|
||||
void perPassGenComparisonSkipsAndCatchesUp() {
|
||||
final float[] value = {1.0f};
|
||||
final FloatCachedUniform u = new FloatCachedUniform("test", UniformUpdateFrequency.CUSTOM, () -> value[0]);
|
||||
|
||||
int passA = -1;
|
||||
int passB = -1;
|
||||
|
||||
u.update();
|
||||
assertNotEquals(passA, u.valueGen(), "fresh pass must push even for gen 1");
|
||||
passA = u.valueGen();
|
||||
|
||||
u.update();
|
||||
assertEquals(passA, u.valueGen(), "unchanged next frame skips for the caught-up pass");
|
||||
assertNotEquals(passB, u.valueGen(), "a pass that never pushed still pushes despite no change this frame");
|
||||
passB = u.valueGen();
|
||||
|
||||
value[0] = 2.0f;
|
||||
u.update();
|
||||
assertNotEquals(passA, u.valueGen());
|
||||
assertNotEquals(passB, u.valueGen());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user