SDL GPU backend, TESR Batching/caching API, Tracy Integration (#1993)

This commit is contained in:
Jason Mitchell authored and GitHub committed 2026-08-08 15:53:58 -07:00
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));
}
}
@@ -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));
}
}
@@ -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);
}
}
}
}
@@ -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;
}
}
@@ -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);
}
}
}
@@ -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");
}
}
@@ -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();
}
}
}
@@ -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();
}
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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");
}
}