diff --git a/common/build.gradle b/common/build.gradle index d56ce91c5..f4775219d 100644 --- a/common/build.gradle +++ b/common/build.gradle @@ -145,10 +145,9 @@ tasks.register('jmh', JavaExec) { // collector's per-frame allocation, not a requirement. maxHeapSize = '1g' - doFirst { - if (project.hasProperty('jmhargs')) { - args(project.property('jmhargs').toString().split('\\s+').findAll { !it.isEmpty() }) - } + // Read at configuration time: the configuration cache forbids touching the project from doFirst. + if (project.hasProperty('jmhargs')) { + args(project.property('jmhargs').toString().split('\\s+').findAll { !it.isEmpty() }) } } @@ -161,7 +160,15 @@ tasks.register('rasterCullReport', JavaExec) { maxHeapSize = '1g' // e.g. ./gradlew :common:rasterCullReport -Dreport.renderDistance=64 - systemProperties System.getProperties().findAll { it.key.toString().startsWith('report.') } + // Read through a provider so the configuration cache tracks them: taken from System.getProperties() at + // configuration time they are invisible to it, and a cached configuration is reused whatever -D flags are passed. + forwardReportProperties(it) +} + +/** Forwards every -Dreport.* on the Gradle command line to the task's JVM, in a configuration-cache-safe way. */ +def forwardReportProperties(JavaExec task) { + def reportProperties = providers.systemPropertiesPrefixedBy('report.') + task.jvmArgumentProviders.add({ reportProperties.get().collect { k, v -> "-D$k=$v".toString() } } as CommandLineArgumentProvider) } publishing { @@ -248,6 +255,6 @@ tasks.register('rasterStats', JavaExec) { mainClass = 'org.embeddedt.embeddium.impl.render.chunk.occlusion.bench.RasterStatsReport' maxHeapSize = '1g' jvmArgs '-Dbitraster.stats=true' - systemProperties System.getProperties().findAll { it.key.toString().startsWith('report.') } - doFirst { if (project.hasProperty('statargs')) args(project.property('statargs').toString().split('\\s+').findAll { !it.isEmpty() }) } + forwardReportProperties(it) + if (project.hasProperty('statargs')) args(project.property('statargs').toString().split('\\s+').findAll { !it.isEmpty() }) } diff --git a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/bench/voxel/VoxelWorld.java b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/bench/voxel/VoxelWorld.java index 506212b79..45f889147 100644 --- a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/bench/voxel/VoxelWorld.java +++ b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/bench/voxel/VoxelWorld.java @@ -33,6 +33,11 @@ public final class VoxelWorld { /** Fraction of terrain-skin blocks replaced by {@link #CUTOUT}, out of 256. Confined to the surface. */ private static final int CUTOUT_ROLL = 40; // ~16% of the skin + /** Blocks from the camera column at which the CLIFF world's ground steps up; past the standing probe's reach. */ + public static final int CLIFF_RADIUS = 8 * 16; + /** Not a multiple of 16: the plateau surface must sit inside a section, or the outward-only search never reaches it. */ + public static final int CLIFF_RISE = 36; + private final WorldType type; private final long seed; private final double caveWidth; @@ -71,6 +76,10 @@ public final class VoxelWorld { return by < SEA_LEVEL ? WATER : AIR; } + if (this.isSolidGround()) { + return SOLID; + } + if (by < surface - CAVE_MARGIN) { return row.isCave(bx) ? AIR : SOLID; } @@ -87,6 +96,11 @@ public final class VoxelWorld { return new CaveRow(this, lattice, by, bz); } + /** {@return whether everything below the surface is solid, with no caves and no cutouts} */ + private boolean isSolidGround() { + return this.type == WorldType.PLAINS || this.type == WorldType.HILLS || this.type == WorldType.CLIFF; + } + /** {@return whether this world has no blocks at all} */ boolean isVoid() { return this.type == WorldType.EMPTY; @@ -156,6 +170,18 @@ public final class VoxelWorld { return Integer.MAX_VALUE; } + if (this.type == WorldType.FLAT || this.type == WorldType.PLAINS || this.type == WorldType.CLIFF) { + // the SURFACE height at the origin, so Cameras.surfaceCameraY(0, 0) is at eye height here too + int base = (int) Math.floor(sectionHeight(0.0, 0.0) * 16.0); + + if (this.type == WorldType.CLIFF) { + long dx = bx - 8, dz = bz - 8; + return (dx * dx) + (dz * dz) >= (long) CLIFF_RADIUS * CLIFF_RADIUS ? base + CLIFF_RISE : base; + } + + return base; + } + return (int) Math.floor(sectionHeight(bx * (1.0 / 16.0), bz * (1.0 / 16.0)) * 16.0); } diff --git a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/BudgetMode.java b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/BudgetMode.java new file mode 100644 index 000000000..e5631ae34 --- /dev/null +++ b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/BudgetMode.java @@ -0,0 +1,26 @@ +package org.embeddedt.embeddium.impl.render.chunk.occlusion.bench; + +import org.embeddedt.embeddium.impl.render.chunk.occlusion.RasterBudget; + +/** How the raster test budget behaves in a benchmark; see {@link RasterBudget}. */ +public enum BudgetMode { + /** The controller adjusts the budget from measured yield, as in the game. */ + ADAPTIVE, + /** Pinned at {@link RasterBudget#FLOOR}: the standing probe alone, which is the cost when yield is low. */ + FLOOR, + /** Pinned unbounded: every far section is tested, the pre-budget behaviour. */ + MAX; + + public void apply(RasterBudget budget) { + switch (this) { + case ADAPTIVE -> budget.pin(0); + case FLOOR -> budget.pin(RasterBudget.FLOOR); + case MAX -> budget.pin(RasterBudget.UNBOUNDED); + } + } + + public static BudgetMode fromProperty(String key, BudgetMode fallback) { + String value = System.getProperty(key); + return value == null ? fallback : valueOf(value.trim().toUpperCase()); + } +} diff --git a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/HeadlessGl.java b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/HeadlessGl.java index f72ac74fd..63335a747 100644 --- a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/HeadlessGl.java +++ b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/HeadlessGl.java @@ -9,9 +9,11 @@ import org.lwjgl.egl.EGL15; import org.lwjgl.egl.EGLCapabilities; import org.lwjgl.opengl.GL; import org.lwjgl.opengl.GL11C; +import org.lwjgl.system.Configuration; import org.lwjgl.system.JNI; import org.lwjgl.system.MemoryStack; +import java.nio.ByteBuffer; import java.nio.IntBuffer; /** @@ -36,6 +38,8 @@ public final class HeadlessGl { return; } + Configuration.OPENGL_EXPLICIT_INIT.set(true); + long display = openDisplay(); try (MemoryStack stack = MemoryStack.stackPush()) { @@ -65,6 +69,7 @@ public final class HeadlessGl { } } + GL.create((ByteBuffer name) -> EGL10.eglGetProcAddress(name)); GL.createCapabilities(); // GLRenderDevice requires this; the benchmarks never touch vanilla GL state. diff --git a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/OcclusionCullerBench.java b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/OcclusionCullerBench.java index 2c2c5547c..a125b0ed5 100644 --- a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/OcclusionCullerBench.java +++ b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/OcclusionCullerBench.java @@ -48,6 +48,10 @@ public class OcclusionCullerBench { @Param({ "false" }) public boolean rasterOcclusion; + /** Only meaningful with {@code rasterOcclusion=true}. FLOOR measures the standing per-frame cost of the probe. */ + @Param({ "ADAPTIVE" }) + public BudgetMode rasterBudget; + /** ALL_GEOMETRY models the first search after a renderer reload, where every built section is pending. */ @Param({ "HASHED" }) public SyntheticWorld.PendingMode pending; @@ -82,6 +86,8 @@ public class OcclusionCullerBench { this.lattice.attach(section); } + this.rasterBudget.apply(this.lattice.rasterBudget()); + double y = Cameras.surfaceCameraY(0, 0); this.staticViewport = Cameras.viewport(8.5, y, 8.5, this.renderDistance); diff --git a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterCullReport.java b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterCullReport.java index 9ee12d257..f1910d006 100644 --- a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterCullReport.java +++ b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterCullReport.java @@ -1,6 +1,7 @@ package org.embeddedt.embeddium.impl.render.chunk.occlusion.bench; import org.embeddedt.embeddium.impl.render.chunk.RenderSection; +import org.embeddedt.embeddium.impl.render.chunk.occlusion.RasterBudget; import org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionLattice; import org.embeddedt.embeddium.impl.render.viewport.Viewport; @@ -8,7 +9,15 @@ public final class RasterCullReport { private static final int RENDER_DISTANCE = Integer.getInteger("report.renderDistance", 32); private static final float FOV = Float.parseFloat(System.getProperty("report.fov", "70")); private static final int YAW_STEPS = 8; - private static final WorldType[] WORLDS = { WorldType.SURFACE, WorldType.CAVES }; + /** Frames the adaptive budget is given to settle before a placement is measured; covers a probe. */ + private static final int WARM_FRAMES = RasterBudget.PROBE_PERIOD + 32; + private static final int TIMED_ROUNDS = 5; + private static final WorldType[] WORLDS = worlds(); + + private static WorldType[] worlds() { + String list = System.getProperty("report.worlds", "PLAINS,HILLS,CLIFF,FLAT,SURFACE,CAVES"); + return java.util.Arrays.stream(list.split(",")).map(String::trim).map(WorldType::valueOf).toArray(WorldType[]::new); + } private RasterCullReport() { } @@ -24,9 +33,15 @@ public final class RasterCullReport { return; } - System.out.printf("%-8s %-8s %10s %10s %8s %10s %10s%n", - "world", "camera", "baseline", "occluded", "delta", "backtrack", "buffer"); - System.out.println("-".repeat(80)); + if (Boolean.getBoolean("report.transition")) { + transitionReport(); + return; + } + + System.out.printf("%-8s %-8s %10s %10s %8s %10s %8s %6s %6s %7s %7s %7s %9s %10s%n", + "world", "camera", "baseline", "occluded", "delta", "budgeted", "bdelta", "limit", "yield", + "ms:base", "raster", "budget", "backtrack", "buffer", "bbuffer"); + System.out.println("-".repeat(150)); for (WorldType world : WORLDS) { var syntheticWorld = new SyntheticWorld(world, RENDER_DISTANCE, true, true); @@ -37,45 +52,228 @@ public final class RasterCullReport { false, false); var rasterLattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, false, true); + var budgetedLattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, + false, true); for (RenderSection section : syntheticWorld.getConstructionOrder()) { baselineLattice.attach(section); rasterLattice.attach(section); + budgetedLattice.attach(section); } + BudgetMode.MAX.apply(rasterLattice.rasterBudget()); + BudgetMode.ADAPTIVE.apply(budgetedLattice.rasterBudget()); + int frame = 0; for (Placement placement : placements()) { - long baseline = 0; - long occluded = 0; - long backtracks = 0; + Viewport[] ring = new Viewport[YAW_STEPS]; for (int step = 0; step < YAW_STEPS; step++) { - Viewport viewport = Cameras.viewport(8.5, placement.y(), 8.5, + ring[step] = Cameras.viewport(8.5, placement.y(), 8.5, (360.0f / YAW_STEPS) * step, placement.pitch(), RENDER_DISTANCE, FOV); + } - var without = new CountingVisitor(); - baselineLattice.ensureWindowCovers(viewport.getChunkCoord(), searchDistance); - baselineLattice.findVisible(without, viewport, searchDistance, numRegions, true, true, ++frame); + // Let the controller settle on this placement, and the JIT on all three lattices, before measuring. + for (int warm = 0; warm < WARM_FRAMES; warm++) { + Viewport viewport = ring[warm % YAW_STEPS]; + frame = runRing(baselineLattice, new Viewport[] { viewport }, searchDistance, numRegions, frame, null); + frame = runRing(rasterLattice, new Viewport[] { viewport }, searchDistance, numRegions, frame, null); + frame = runRing(budgetedLattice, new Viewport[] { viewport }, searchDistance, numRegions, frame, null); + } - var with = new CountingVisitor(); + // Fastest of several rounds, so a GC or a scheduling hiccup does not stand in for the cost. + long[] visible = new long[3]; + long[] nanos = { Long.MAX_VALUE, Long.MAX_VALUE, Long.MAX_VALUE }; + SectionLattice[] lattices = { baselineLattice, rasterLattice, budgetedLattice }; + + for (int round = 0; round < TIMED_ROUNDS; round++) { + for (int i = 0; i < lattices.length; i++) { + long[] count = new long[1]; + long t0 = System.nanoTime(); + frame = runRing(lattices[i], ring, searchDistance, numRegions, frame, count); + nanos[i] = Math.min(nanos[i], System.nanoTime() - t0); + visible[i] = count[0]; + } + } + + long backtracks = 0; + + for (Viewport viewport : ring) { rasterLattice.ensureWindowCovers(viewport.getChunkCoord(), searchDistance); - rasterLattice.findVisible(with, viewport, searchDistance, numRegions, true, true, ++frame); - - baseline += without.visible; - occluded += with.visible; + rasterLattice.findVisible(new CountingVisitor(), viewport, searchDistance, numRegions, true, true, ++frame); backtracks += rasterLattice.rasterBacktrackCount(); } - long meanBaseline = baseline / YAW_STEPS; - long meanOccluded = occluded / YAW_STEPS; - double delta = meanBaseline == 0 ? 0.0 - : ((meanOccluded - meanBaseline) * 100.0) / meanBaseline; + long meanBaseline = visible[0] / YAW_STEPS; + long meanOccluded = visible[1] / YAW_STEPS; + long meanBudgeted = visible[2] / YAW_STEPS; + var budget = budgetedLattice.rasterBudget(); - System.out.printf("%-8s %-8s %10d %10d %7.1f%% %10d %10s%n", world, placement.name(), - meanBaseline, meanOccluded, delta, backtracks / YAW_STEPS, rasterLattice.rasterBufferSize()); + System.out.printf("%-8s %-8s %10d %10d %7.1f%% %10d %7.1f%% %6s %5.1f%% %7.3f %7.3f %7.3f %9d %10s %10s%n", world, placement.name(), + meanBaseline, meanOccluded, percentDelta(meanBaseline, meanOccluded), + meanBudgeted, percentDelta(meanBaseline, meanBudgeted), + describe(budget), budget.yield() * 100.0f, + nanos[0] / 1e6 / YAW_STEPS, nanos[1] / 1e6 / YAW_STEPS, nanos[2] / 1e6 / YAW_STEPS, + backtracks / YAW_STEPS, rasterLattice.rasterBufferSize(), budgetedLattice.rasterBufferSize()); + } + + rampReport(world, budgetedLattice, searchDistance, numRegions, frame); + } + } + + /** Searches every viewport of the ring once, summing visible counts into {@code visibleOut[0]} when given. */ + private static int runRing(SectionLattice lattice, Viewport[] ring, float searchDistance, int numRegions, int frame, long[] visibleOut) { + for (Viewport viewport : ring) { + var visitor = new CountingVisitor(); + lattice.ensureWindowCovers(viewport.getChunkCoord(), searchDistance); + lattice.findVisible(visitor, viewport, searchDistance, numRegions, true, true, ++frame); + + if (visibleOut != null) { + visibleOut[0] += visitor.visible; } } + + return frame; + } + + private static double percentDelta(long baseline, long value) { + return baseline == 0 ? 0.0 : ((value - baseline) * 100.0) / baseline; + } + + private static String describe(RasterBudget budget) { + return budget.wasProbe() ? "probe" : budget.wasFullPass() ? "full" : Integer.toString(budget.limit()); + } + + /** + * Settles the controller, from the floor, on the placement with the least occlusion, then jumps to the one with + * the most and counts frames until the budget stops changing, over two probe periods. This is the latency a + * player sees walking into a cave. The trace lists each frame at which the budget's state changed. + */ + private static void rampReport(WorldType world, SectionLattice lattice, float searchDistance, int numRegions, int frame) { + Placement[] placements = placements(); + Placement from = placements[placements.length - 1]; + Placement to = placements[0]; + var budget = lattice.rasterBudget(); + budget.copyFrom(new RasterBudget()); + + for (int warm = 0; warm < WARM_FRAMES; warm++) { + Viewport viewport = Cameras.viewport(8.5, from.y(), 8.5, (360.0f / YAW_STEPS) * (warm % YAW_STEPS), + from.pitch(), RENDER_DISTANCE, FOV); + lattice.ensureWindowCovers(viewport.getChunkCoord(), searchDistance); + lattice.findVisible(new CountingVisitor(), viewport, searchDistance, numRegions, true, true, ++frame); + } + + int startBudget = budget.limit(); + var trace = new StringBuilder(); + int settledAt = -1; + int previous = startBudget; + String previousState = null; + + for (int i = 0; i < 2 * RasterBudget.PROBE_PERIOD; i++) { + Viewport viewport = Cameras.viewport(8.5, to.y(), 8.5, (360.0f / YAW_STEPS) * (i % YAW_STEPS), + to.pitch(), RENDER_DISTANCE, FOV); + lattice.ensureWindowCovers(viewport.getChunkCoord(), searchDistance); + lattice.findVisible(new CountingVisitor(), viewport, searchDistance, numRegions, true, true, ++frame); + + String state = describe(budget); + + if (!state.equals(previousState)) { + trace.append(' ').append(i).append(':').append(state); + } + + if (budget.limit() != previous) { + settledAt = -1; + } else if (settledAt < 0) { + settledAt = i; + } + + previous = budget.limit(); + previousState = state; + } + + System.out.printf("%-8s ramp %s -> %s: limit %d -> %s, settled after %d frames, trace:%s%n", world, from.name(), to.name(), + startBudget, describe(budget), settledAt, trace); + } + + /** + * Carries a controller settled on open ground (PLAINS, where the raster culls nothing) into terrain with caves + * beneath (FLAT, where it culls a quarter of the sections), and back, and prints every frame of both ramps: the + * limit, what the adaptive search reports visible against the unbudgeted raster and no raster at all, and the + * time of each. This is what a player sees walking from a field into a forest with caves, and it is where a + * count-based ration could produce a single expensive frame. + */ + private static void transitionReport() { + int numRegions; + var plains = new SyntheticWorld(WorldType.PLAINS, RENDER_DISTANCE, true, true); + var flat = new SyntheticWorld(WorldType.FLAT, RENDER_DISTANCE, true, true); + numRegions = BenchPlatform.regionManager().getRegionIdsLength(); + float searchDistance = plains.getSearchDistance(); + + SectionLattice[][] lattices = new SectionLattice[2][3]; + SyntheticWorld[] worlds = { plains, flat }; + + for (int w = 0; w < 2; w++) { + for (int i = 0; i < 3; i++) { + lattices[w][i] = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, false, i != 0); + + for (RenderSection section : worlds[w].getConstructionOrder()) { + lattices[w][i].attach(section); + } + } + + BudgetMode.MAX.apply(lattices[w][1].rasterBudget()); + BudgetMode.ADAPTIVE.apply(lattices[w][2].rasterBudget()); + } + + double y = Cameras.surfaceCameraY(0, 0); + Viewport[] ring = Cameras.yawRing(8.5, y, 8.5, YAW_STEPS, Cameras.DEFAULT_PITCH, RENDER_DISTANCE); + int frame = 0; + + // Warm the JIT on everything, and settle both adaptive controllers on their own world. + for (int warm = 0; warm < WARM_FRAMES * 2; warm++) { + for (SectionLattice[] set : lattices) { + for (SectionLattice lattice : set) { + frame = runRing(lattice, new Viewport[] { ring[warm % YAW_STEPS] }, searchDistance, numRegions, frame, null); + } + } + } + + frame = transition("PLAINS -> FLAT", lattices[0][2], lattices[1], ring, searchDistance, numRegions, frame); + // the FLAT controller is now at whatever the ramp left it, which is the state a player carries back out + transition("FLAT -> PLAINS", lattices[1][2], lattices[0], ring, searchDistance, numRegions, frame); + } + + private static int transition(String name, SectionLattice from, SectionLattice[] to, Viewport[] ring, + float searchDistance, int numRegions, int frame) { + var budget = to[2].rasterBudget(); + budget.copyFrom(from.rasterBudget()); + + System.out.printf("%n%s (rd=%d), controller arrives with limit=%d yield=%.1f%%%n", name, RENDER_DISTANCE, + budget.limit(), budget.yield() * 100.0f); + System.out.printf("%5s %6s %6s %9s %9s %9s %8s %8s %8s%n", + "frame", "limit", "yield", "vis:base", "raster", "adaptive", "ms:base", "raster", "adaptive"); + + for (int i = 0; i < 24; i++) { + Viewport viewport = ring[i % YAW_STEPS]; + long[] visible = new long[3]; + double[] ms = new double[3]; + + for (int l = 0; l < 3; l++) { + var visitor = new CountingVisitor(); + to[l].ensureWindowCovers(viewport.getChunkCoord(), searchDistance); + long t0 = System.nanoTime(); + to[l].findVisible(visitor, viewport, searchDistance, numRegions, true, true, ++frame); + ms[l] = (System.nanoTime() - t0) / 1e6; + visible[l] = visitor.visible; + } + + System.out.printf("%5d %6s %5.1f%% %9d %9d %9d %8.3f %8.3f %8.3f%n", i, + describe(budget), budget.yield() * 100.0f, + visible[0], visible[1], visible[2], ms[0], ms[1], ms[2]); + } + + return frame; } /** Sweeps the field of view up and back down and prints the buffer size chosen at each step. */ @@ -118,10 +316,14 @@ public final class RasterCullReport { private static Placement[] placements() { double surfaceY = Cameras.surfaceCameraY(0, 0); + // Ordered from most to least occluded: the ramp report jumps from the last to the first. return new Placement[] { new Placement("surface", surfaceY, Cameras.DEFAULT_PITCH), new Placement("treetop", surfaceY + 16.0, Cameras.DEFAULT_PITCH), - new Placement("high", 200.0, -45.0f), + // looking up: nothing in view has occluder data, so the raster tests nothing + new Placement("sky", 200.0, -45.0f), + // looking down on the terrain from far above: everything is a shell, nothing occludes anything + new Placement("aerial", surfaceY + 96.0, 45.0f), }; } } diff --git a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterStatsReport.java b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterStatsReport.java index 3eb6d0d2b..f8d98fcf2 100644 --- a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterStatsReport.java +++ b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterStatsReport.java @@ -15,6 +15,11 @@ public final class RasterStatsReport { private static final int RENDER_DISTANCE = Integer.getInteger("report.renderDistance", 32); private static final int YAW_STEPS = 8; private static final int WARM = 150; + private static final int TIMED_ROUNDS = 5; + private static final BudgetMode BUDGET_MODE = BudgetMode.fromProperty("report.budget", BudgetMode.ADAPTIVE); + /** Camera height above the surface eye height, and pitch; e.g. dy=96 pitch=45 looks down on the terrain from above. */ + private static final double CAMERA_DY = Double.parseDouble(System.getProperty("report.dy", "0")); + private static final float CAMERA_PITCH = Float.parseFloat(System.getProperty("report.pitch", Float.toString(Cameras.DEFAULT_PITCH))); public static void main(String[] args) { BenchPlatform.ensureInitialized(); @@ -25,8 +30,9 @@ public final class RasterStatsReport { int numRegions = BenchPlatform.regionManager().getRegionIdsLength(); var lattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, false, true); for (RenderSection section : world.getConstructionOrder()) lattice.attach(section); + BUDGET_MODE.apply(lattice.rasterBudget()); - double y = Cameras.surfaceCameraY(0, 0); + double y = Cameras.surfaceCameraY(0, 0) + CAMERA_DY; if (args.length > 1 && args[1].equals("yscan")) { var base = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, false, false); @@ -48,31 +54,56 @@ public final class RasterStatsReport { } return; } - Viewport[] ring = Cameras.yawRing(8.5, y, 8.5, YAW_STEPS, Cameras.DEFAULT_PITCH, RENDER_DISTANCE); + Viewport[] ring = Cameras.yawRing(8.5, y, 8.5, YAW_STEPS, CAMERA_PITCH, RENDER_DISTANCE); int frame = 0; + // A lattice without the raster, timed over the same ring, so the raster's cost can be read as a difference. + var base = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, false, false); + for (RenderSection section : world.getConstructionOrder()) base.attach(section); + for (int w = 0; w < WARM; w++) { for (Viewport v : ring) { lattice.ensureWindowCovers(v.getChunkCoord(), searchDistance); lattice.findVisible(new CountingVisitor(), v, searchDistance, numRegions, true, true, ++frame); + base.ensureWindowCovers(v.getChunkCoord(), searchDistance); + base.findVisible(new CountingVisitor(), v, searchDistance, numRegions, true, true, ++frame); } } - reset(); - long visible = 0; - long t0 = System.nanoTime(); - for (Viewport v : ring) { - var c = new CountingVisitor(); - lattice.ensureWindowCovers(v.getChunkCoord(), searchDistance); - lattice.findVisible(c, v, searchDistance, numRegions, true, true, ++frame); - visible += c.visible; + // Several timed rounds, keeping the fastest, so a GC or a scheduling hiccup does not stand in for the cost. + long visible = 0, baseVisible = 0; + long total = Long.MAX_VALUE, baseTotal = Long.MAX_VALUE; + for (int round = 0; round < TIMED_ROUNDS; round++) { + reset(); + visible = 0; + long t0 = System.nanoTime(); + for (Viewport v : ring) { + var c = new CountingVisitor(); + lattice.ensureWindowCovers(v.getChunkCoord(), searchDistance); + lattice.findVisible(c, v, searchDistance, numRegions, true, true, ++frame); + visible += c.visible; + } + total = Math.min(total, System.nanoTime() - t0); + + baseVisible = 0; + t0 = System.nanoTime(); + for (Viewport v : ring) { + var c = new CountingVisitor(); + base.ensureWindowCovers(v.getChunkCoord(), searchDistance); + base.findVisible(c, v, searchDistance, numRegions, true, true, ++frame); + baseVisible += c.visible; + } + baseTotal = Math.min(baseTotal, System.nanoTime() - t0); } - long total = System.nanoTime() - t0; int n = YAW_STEPS; - System.out.printf("world=%s visible/frame=%d total=%.3fms test=%.3fms occlude=%.3fms%n", worldType, visible / n, - total / 1e6 / n, RasterOccluder.STAT_TEST_NANOS / 1e6 / n, RasterOccluder.STAT_OCCLUDE_NANOS / 1e6 / n); - System.out.printf("sections tested=%d occluded=%d emptySkip=%d vertexHit=%d%n", RasterOccluder.STAT_SECTIONS / n, - RasterOccluder.STAT_OCCLUDED_SECTIONS / n, RasterOccluder.STAT_EMPTY_SKIP / n, AbstractRasterizer.STAT_T_VERTEX / n); + System.out.printf("world=%s dy=%.0f pitch=%.0f | no raster: visible/frame=%d total=%.3fms%n", worldType, CAMERA_DY, CAMERA_PITCH, + baseVisible / n, baseTotal / 1e6 / n); + System.out.printf("raster: visible/frame=%d total=%.3fms (+%.3fms) test=%.3fms occlude=%.3fms%n", visible / n, + total / 1e6 / n, (total - baseTotal) / 1e6 / n, RasterOccluder.STAT_TEST_NANOS / 1e6 / n, RasterOccluder.STAT_OCCLUDE_NANOS / 1e6 / n); + System.out.printf("sections tested=%d occluded=%d emptySkip=%d budgetSkip=%d vertexHit=%d%n", RasterOccluder.STAT_SECTIONS / n, + RasterOccluder.STAT_OCCLUDED_SECTIONS / n, RasterOccluder.STAT_EMPTY_SKIP / n, RasterOccluder.STAT_BUDGET_SKIP / n, + AbstractRasterizer.STAT_T_VERTEX / n); + System.out.println("budget (" + BUDGET_MODE + "): " + lattice.rasterBudget()); System.out.printf("draw calls=%d polygons=%d tiles=%d | test calls=%d polygons=%d tiles=%d | eventRows=%d%n", AbstractRasterizer.STAT_DRAW_CALLS / n, AbstractRasterizer.STAT_DRAW_QUADS / n, (AbstractRasterizer.STAT_D_INNER + AbstractRasterizer.STAT_D_COVER) / n, @@ -92,7 +123,7 @@ public final class RasterStatsReport { private static void reset() { AbstractRasterizer.STAT_D_NOOP = AbstractRasterizer.STAT_D_RANGE0 = AbstractRasterizer.STAT_D_RANGE1 = AbstractRasterizer.STAT_D_RANGE2 = AbstractRasterizer.STAT_D_RANGE3 = 0; - RasterOccluder.STAT_CENTER_HIT = RasterOccluder.STAT_NEAR = RasterOccluder.STAT_AIR_TESTS = RasterOccluder.STAT_AIR_VISIBLE = RasterOccluder.STAT_EMPTY_SKIP = AbstractRasterizer.STAT_T_VERTEX = 0; + RasterOccluder.STAT_CENTER_HIT = RasterOccluder.STAT_NEAR = RasterOccluder.STAT_AIR_TESTS = RasterOccluder.STAT_AIR_VISIBLE = RasterOccluder.STAT_EMPTY_SKIP = RasterOccluder.STAT_BUDGET_SKIP = AbstractRasterizer.STAT_T_VERTEX = 0; AbstractRasterizer.STAT_T_EMPTY = AbstractRasterizer.STAT_T_INNER = AbstractRasterizer.STAT_T_COVER = AbstractRasterizer.STAT_T_HIDDEN = AbstractRasterizer.STAT_T_BOX_HIDDEN = 0; AbstractRasterizer.STAT_D_INNER = AbstractRasterizer.STAT_D_COVER = 0; RasterOccluder.STAT_TEST_NANOS = RasterOccluder.STAT_OCCLUDE_NANOS = RasterOccluder.STAT_SECTIONS = RasterOccluder.STAT_OCCLUDED_SECTIONS = 0; diff --git a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/WorldType.java b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/WorldType.java index 2d22ac219..12608a6ce 100644 --- a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/WorldType.java +++ b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/WorldType.java @@ -6,6 +6,17 @@ public enum WorldType { EMPTY, /** Sine heightmap with caves and water. Closest to a real overworld; the default. */ SURFACE, + /** Level ground at the SURFACE world's height at the origin, with caves beneath. Nothing above ground occludes anything. */ + FLAT, + /** + * Level solid ground, no caves and no cutouts. The search cannot enter the ground, so everything it reaches + * is the one surface layer and the raster has nothing to cull: the worst case for its cost. + */ + PLAINS, + /** SURFACE heightmap over solid ground, no caves and no cutouts. Hills hide only what lies behind them. */ + HILLS, + /** PLAINS with a plateau beyond {@code VoxelWorld.CLIFF_RADIUS}. The cliff hides the plateau surface, from beyond the floor's reach. */ + CLIFF, /** Stone to the top of the world with caves. Heavily occluded. */ CAVES } diff --git a/common/src/main/java/grondag/bitraster/AbstractRasterizer.java b/common/src/main/java/grondag/bitraster/AbstractRasterizer.java index b1c2c5420..45897e68a 100644 --- a/common/src/main/java/grondag/bitraster/AbstractRasterizer.java +++ b/common/src/main/java/grondag/bitraster/AbstractRasterizer.java @@ -675,8 +675,9 @@ public abstract class AbstractRasterizer { } /** - * Sets the buffer to {@code 8 * tileWidth} by {@code 8 * tileHeight} pixels, reallocating and clearing it - * if the size changed. Safe between frames only: the current polygon and scene contents are discarded. + * Sets the buffer to {@code 8 * tileWidth} by {@code 8 * tileHeight} pixels and clears it if the size changed, + * reallocating only past the largest size used so far. Safe between frames only: the current polygon and scene + * contents are discarded. */ public final void resize(int tileWidth, int tileHeight) { if (tileWidth < MIN_SIZE_TILES || tileWidth > MAX_SIZE_TILES || tileHeight < MIN_SIZE_TILES || tileHeight > MAX_SIZE_TILES) { @@ -704,15 +705,22 @@ public abstract class AbstractRasterizer { preciseWidthClamp = preciseWidth - PRECISE_PIXEL_CENTER; preciseHeightClamp = preciseHeight - PRECISE_PIXEL_CENTER; - eventData = new int[pixelHeight * 2]; - tiles = new long[tileCount]; - fullBits = new long[(tileCount + 63) >> 6]; + // CELERITAS: keep arrays that are large enough already, since the raster budget alternates between a small + // buffer and a large one; only the leading part is used, so it is cleared here as a new array would be + if (eventData == null || eventData.length < pixelHeight * 2) eventData = new int[pixelHeight * 2]; + if (tiles == null || tiles.length < tileCount) tiles = new long[tileCount]; + if (fullBits == null || fullBits.length < fullBitsWords()) fullBits = new long[fullBitsWords()]; + clear(); + } + + private int fullBitsWords() { + return (tileCount + 63) >> 6; } /** Marks every pixel clear. */ final void clear() { - Arrays.fill(tiles, 0L); - Arrays.fill(fullBits, 0L); + Arrays.fill(tiles, 0, tileCount, 0L); + Arrays.fill(fullBits, 0, fullBitsWords(), 0L); } final int tileIndexFromPixelXY(int x, int y) { @@ -743,9 +751,9 @@ public abstract class AbstractRasterizer { offsetY = source.offsetY; offsetZ = source.offsetZ; System.arraycopy(source.vertexData, 0, vertexData, 0, VERTEX_DATA_LENGTH); - System.arraycopy(source.eventData, 0, eventData, 0, eventData.length); + System.arraycopy(source.eventData, 0, eventData, 0, pixelHeight * 2); System.arraycopy(source.tiles, 0, tiles, 0, tileCount); - System.arraycopy(source.fullBits, 0, fullBits, 0, fullBits.length); + System.arraycopy(source.fullBits, 0, fullBits, 0, fullBitsWords()); } // CELERITAS: work counters for RasterStatsReport. STATS is a constant so the JIT drops the increments when off. diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java index 946471435..cff19fbd9 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java @@ -109,6 +109,7 @@ public class OcclusionCuller { // When non-null, receives the queue entry ((packedLocalXYZ << 32) | latticeIndex) of every cell reported // visible, in traversal order; the count is published to SectionLattice.visibleCount at the end of the search. + // The count is kept either way, for the raster budget. // Used as the root set of the shadow search. private long[] visibleCells; private int visibleCount; @@ -117,6 +118,7 @@ public class OcclusionCuller { private final RegionCullCache regionCullCache = new RegionCullCache(); private final @Nullable RasterOccluder rasterOccluder; + private final RasterBudget rasterBudget = new RasterBudget(); private boolean rasterActive; private boolean isCameraInUnloadedSection; @@ -195,12 +197,17 @@ public class OcclusionCuller { this.rasterActive = this.rasterOccluder != null && useOcclusionCulling && viewport.getVpMatrix() != null; if (this.rasterActive) { - this.rasterOccluder.prepareScene(frame, viewport, searchDistance); + this.rasterBudget.beginFrame(this.maxSquaredChunkDistance(searchDistance)); + this.rasterOccluder.prepareScene(frame, viewport, this.rasterTestDistance(searchDistance)); this.occludeCameraSection(viewport); } this.process(visitor, viewport, searchDistance, useOcclusionCulling, allowFrustumClamping, frame); + if (this.rasterActive) { + this.rasterBudget.endFrame(this.visibleCount); + } + if (recordVisible) { this.lattice.visibleCount = this.visibleCount; } @@ -321,8 +328,12 @@ public class OcclusionCuller { continue; } - if (visible && visibleCells != null) { - visibleCells[visibleCount++] = entry; + if (visible) { + if (visibleCells != null) { + visibleCells[visibleCount] = entry; + } + + visibleCount++; } int connections; @@ -364,6 +375,25 @@ public class OcclusionCuller { this.visibleCount = visibleCount; } + /** An upper bound on the squared chunk distance of any section the search can reach. */ + private int maxSquaredChunkDistance(float searchDistance) { + // the distance test is cylindrical, so dy is bounded by the search distance, not the world height + int radius = (int) Math.ceil(searchDistance / 16.0f) + 2; + return 2 * radius * radius; + } + + /** Farthest distance in blocks at which this search will test a section, for sizing the coverage buffer. */ + private float rasterTestDistance(float searchDistance) { + int testable = this.rasterBudget.testableLimit(); + + if (testable == RasterBudget.UNBOUNDED) { + return searchDistance; + } + + // one chunk of slack, since the squared distance is measured between section origins + return Math.min(searchDistance, ((float) Math.sqrt(testable) + 1.0f) * 16.0f); + } + private void occludeCameraSection(Viewport viewport) { int idx = this.cameraSectionIndex; @@ -403,14 +433,28 @@ public class OcclusionCuller { int dz = chunkZ - camZ; int squaredChunkDist = (dx * dx) + (dy * dy) + (dz * dz); + // Near sections are always drawn (and never tested, see testSection). Farther ones are rationed by the + // budget: one beyond its limit is neither tested nor drawn, which is conservative for a coverage-only + // buffer, and costs nothing. + boolean near = squaredChunkDist <= RasterOccluder.NEAR_SQUARED_CHUNK_DIST; + + if (!near && !this.rasterBudget.shouldTest(squaredChunkDist)) { + if (AbstractRasterizer.STATS) RasterOccluder.STAT_BUDGET_SKIP++; + return RasterOccluder.SectionVisibility.VISIBLE; + } + boolean hasGeometry = (PackedSectionMetadata.getCompactVisualsFlags(meta) & (1 << RenderVisualsService.HAS_BLOCK_GEOMETRY)) != 0; RasterOccluder.SectionVisibility result = occluder.testSection(chunkX << 4, chunkY << 4, chunkZ << 4, squaredChunkDist, occluderBounds[idx]); - if (result == RasterOccluder.SectionVisibility.VISIBLE && hasGeometry) { - occluder.occludeSection(occluderData[idx]); + if (result == RasterOccluder.SectionVisibility.VISIBLE) { + if (hasGeometry) { + occluder.occludeSection(occluderData[idx]); + } + } else { + this.rasterBudget.recordCulled(); } return result; @@ -426,6 +470,10 @@ public class OcclusionCuller { return this.rasterOccluder == null ? 0 : this.rasterOccluder.backtrackCount(); } + public RasterBudget rasterBudget() { + return this.rasterBudget; + } + // Visit each selected neighbour using both its linear array offset and // its packed-coordinate offset. The lattice border makes idx + delta safe. private void visitNeighbors(long[] visitState, long[] queue, int[] delta, int idx, int xyz, int outgoing, long frameStamp) { @@ -616,9 +664,11 @@ public class OcclusionCuller { int xyz = this.lattice.packXyz(origin.x(), origin.y(), origin.z()); if (this.visibleCells != null) { - this.visibleCells[this.visibleCount++] = ((long) xyz << 32) | (idx & 0xFFFFFFFFL); + this.visibleCells[this.visibleCount] = ((long) xyz << 32) | (idx & 0xFFFFFFFFL); } + this.visibleCount++; + int outgoing; if (useOcclusionCulling) { diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterBudget.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterBudget.java new file mode 100644 index 000000000..f269a932e --- /dev/null +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterBudget.java @@ -0,0 +1,214 @@ +package org.embeddedt.embeddium.impl.render.chunk.occlusion; + +/** + * Limits how far from the camera the raster tests and draws sections, so its per-frame cost tracks how much it + * is culling. Sections beyond the limit are treated as visible, which is always conservative. + * + *

The limit is a squared chunk distance. Each frame the yield of the tests inside it (fraction not visible) + * feeds a moving average: above {@link #HIGH_YIELD} the limit doubles, below {@link #LOW_YIELD} it halves, in + * between it holds. It never drops below {@link #FLOOR}, which acts as a standing probe, and stops at the ceiling + * the search supplies, at which point the search is a full, unbudgeted pass. + * + *

Limiting by distance rather than by count matters: the search runs roughly front to back, so everything + * inside the limit is drawn before anything it could hide, and the yield measured there is representative. + * + *

Representative of the inside, that is: an occluder beyond the limit is never drawn, so whatever it hides is + * never seen to be hidden, and a cliff a few chunks off would hold the limit at the floor for as long as the + * camera stood there. So every {@link #PROBE_PERIOD} frames one frame runs unbudgeted, and when that pass pays + * for itself the limit jumps straight to it. + * + *

Yield cannot say whether it pays: a hidden section also stops the search behind it, so one cull removes a + * single section from the frame on gentle hills and dozens on cave-riddled terrain, at a similar yield. The probe + * instead compares the frame's visible count against the average of the frames before it, which, the camera + * having barely moved, is what the pass removed, and charges that against the tests it added. + */ +public final class RasterBudget { + /** Smallest squared chunk distance the limit can take. */ + public static final int FLOOR = 12; + + public static final int HIGH_YIELD = percent(15); + public static final int LOW_YIELD = percent(5); + + /** Below this many tests in a frame the average is not updated. */ + public static final int MIN_SAMPLE = 16; + + /** The first this many far sections are tested regardless of the limit, so enclosed spaces get a full pass. */ + public static final int CHEAP_PASS = 32; + + /** Every this many frames one runs unbudgeted, to find occlusion the limit cannot reach. */ + public static final int PROBE_PERIOD = 64; + + /** A probe pays when it removes at least one section from the frame for every this many tests it adds. */ + public static final int TESTS_PER_REMOVED = 2; + + private static final int EMA_SHIFT = 2; + private static final int Q = 16; + + public static final int UNBOUNDED = Integer.MAX_VALUE; + + private int limit = FLOOR; + private int yieldEma; + private int ceiling = UNBOUNDED; + + private int frameLimit = FLOOR; + + /** Nothing beyond this is tested this frame; twice the limit's distance, or unbounded on a full pass. */ + private int testable = UNBOUNDED; + + /** Non-zero holds the limit fixed; for benchmarks. */ + private int pinned; + + private int frames; + private boolean probing; + + /** Moving averages, in 1/16ths, of the visible count and the tests of non-probe frames; -1 before the first. */ + private int visibleEma = -1; + private int testedEma; + + private int farReached; + private int farthest; + private int tested; + private int culled; + + /** @param ceiling squared chunk distance no reachable section exceeds */ + public void beginFrame(int ceiling) { + this.ceiling = Math.max(FLOOR, ceiling); + this.probing = this.pinned == 0 && this.limit < this.ceiling && ++this.frames % PROBE_PERIOD == 0 + && this.visibleEma >= 0; + this.frameLimit = this.probing ? UNBOUNDED : this.limit(); + this.testable = this.frameLimit >= this.ceiling ? UNBOUNDED + : Math.min(this.ceiling, saturatingDouble(saturatingDouble(this.frameLimit))); + this.farReached = 0; + this.farthest = 0; + this.tested = 0; + this.culled = 0; + } + + /** Called once per far section with occluder data; true if it should be tested and drawn. */ + public boolean shouldTest(int squaredChunkDist) { + this.farReached++; + + if (squaredChunkDist > this.farthest) { + this.farthest = squaredChunkDist; + } + + if (squaredChunkDist > this.testable || (squaredChunkDist > this.frameLimit && this.farReached > CHEAP_PASS)) { + return false; + } + + this.tested++; + return true; + } + + public void recordCulled() { + this.culled++; + } + + /** @param visible sections the search found visible this frame */ + public void endFrame(int visible) { + if (!this.probing) { + if (this.visibleEma < 0) { + this.visibleEma = visible << 4; + this.testedEma = this.tested << 4; + } else { + this.visibleEma += ((visible << 4) - this.visibleEma) >> EMA_SHIFT; + this.testedEma += ((this.tested << 4) - this.testedEma) >> EMA_SHIFT; + } + } + + if (this.tested < MIN_SAMPLE) return; + + int yield = (int) (((long) this.culled << Q) / this.tested); + + if (this.probing) { + int removed = (this.visibleEma >> 4) - visible; + int added = this.tested - (this.testedEma >> 4); + + if (removed > 0 && (long) removed * TESTS_PER_REMOVED >= added) { + this.limit = this.ceiling; + this.yieldEma = yield; + } + + return; + } + + this.yieldEma += (yield - this.yieldEma) >> EMA_SHIFT; + + if (this.pinned != 0) { + return; + } + + if (this.yieldEma >= HIGH_YIELD && yield >= HIGH_YIELD) { + this.limit = Math.min(saturatingDouble(this.limit), this.ceiling); + } else if (this.yieldEma <= LOW_YIELD) { + this.limit = Math.max(this.limit >> 1, FLOOR); + } else { + this.limit = Math.max(Math.min(this.limit, this.ceiling), FLOOR); + } + } + + /** Holds the limit at a fixed value ({@link #UNBOUNDED} for a full pass); zero restores adaptive behaviour. */ + public void pin(int limit) { + this.pinned = limit; + + if (limit != 0) { + this.limit = limit; + } + } + + public void copyFrom(RasterBudget other) { + this.limit = other.limit; + this.yieldEma = other.yieldEma; + this.visibleEma = other.visibleEma; + this.testedEma = other.testedEma; + } + + public int limit() { + return this.pinned != 0 ? this.pinned : this.limit; + } + + /** Squared chunk distance beyond which nothing is tested this frame; the coverage buffer is sized to it. */ + public int testableLimit() { + return this.testable; + } + + public int farReached() { + return this.farReached; + } + + public int tested() { + return this.tested; + } + + public int culled() { + return this.culled; + } + + /** Moving-average yield in [0, 1]. */ + public float yield() { + return this.yieldEma / (float) (1 << Q); + } + + public boolean wasFullPass() { + return this.tested == this.farReached; + } + + public boolean wasProbe() { + return this.probing; + } + + @Override + public String toString() { + return String.format("limit=%s%s yield=%.1f%% far=%d farthest=%d tested=%d culled=%d", + this.limit() == UNBOUNDED ? "max" : Integer.toString(this.limit()), this.probing ? " (probe)" : "", + this.yield() * 100.0f, this.farReached, this.farthest, this.tested, this.culled); + } + + private static int percent(int value) { + return (int) (((long) value << Q) / 100); + } + + private static int saturatingDouble(int value) { + return value >= (1 << 30) ? Integer.MAX_VALUE : value << 1; + } +} diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterOccluder.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterOccluder.java index 2d8c3693f..fdefa57d5 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterOccluder.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterOccluder.java @@ -16,7 +16,7 @@ public final class RasterOccluder extends BoxOccluder { private int backtrackCount; /** Work counters for benchmarks; only maintained when {@link AbstractRasterizer#STATS} is set. */ - public static long STAT_CENTER_HIT, STAT_AIR_TESTS, STAT_AIR_VISIBLE, STAT_NEAR, STAT_EMPTY_SKIP; + public static long STAT_CENTER_HIT, STAT_AIR_TESTS, STAT_AIR_VISIBLE, STAT_NEAR, STAT_EMPTY_SKIP, STAT_BUDGET_SKIP; public static long STAT_TEST_NANOS, STAT_OCCLUDE_NANOS, STAT_SECTIONS, STAT_OCCLUDED_SECTIONS; public enum SectionVisibility { @@ -47,8 +47,12 @@ public final class RasterOccluder extends BoxOccluder { * Clears the buffer for a new search. The matrix already carries rotation and projection but no * camera translation, so it is supplied as the projection with an identity model matrix; * {@link #prepareRegion} applies the camera-relative offset per section. + * + * @param testDistance farthest distance in blocks at which a section will be tested this search; the buffer + * is sized to resolve one-block gaps out to it, so a search that tests only nearby + * sections gets a smaller buffer and draws its occluders into fewer tiles */ - public void prepareScene(int viewVersion, Viewport viewport, float searchDistance) { + public void prepareScene(int viewVersion, Viewport viewport, float testDistance) { Matrix4fc vpMatrix = viewport.getVpMatrix(); if (vpMatrix == null) { @@ -59,7 +63,7 @@ public final class RasterOccluder extends BoxOccluder { this.backtrackCount = 0; - chooseBufferSize(vpMatrix, searchDistance); + chooseBufferSize(vpMatrix, testDistance); invalidate(); prepareScene(viewVersion, transform.x, transform.y, transform.z, Matrix4L::loadIdentity, m -> copyMatrix(vpMatrix, m)); diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java index e320643fb..7a4e794ed 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java @@ -487,6 +487,11 @@ public final class SectionLattice { return this.culler.rasterBacktrackCount(); } + /** The main search's raster test budget; see {@link RasterBudget}. */ + public RasterBudget rasterBudget() { + return this.culler.rasterBudget(); + } + /** * Run the shadow-pass search over the currently installed lattice cells, using the shadow visit-state array * so the main search's state is left intact. diff --git a/common/src/test/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterBudgetTest.java b/common/src/test/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterBudgetTest.java new file mode 100644 index 000000000..6f424f75c --- /dev/null +++ b/common/src/test/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterBudgetTest.java @@ -0,0 +1,319 @@ +package org.embeddedt.embeddium.impl.render.chunk.occlusion; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class RasterBudgetTest { + /** Squared chunk distance of the farthest section in the synthetic frames; a 32 chunk render distance. */ + private static final int FARTHEST = 32 * 32; + + /** The bound the culler would hand the controller for such a search. */ + private static final int CEILING = FARTHEST + 1; + + /** + * Runs one frame over far sections spread evenly in squared distance from just past the near range to + * {@link #FARTHEST}, where a fraction {@code culledFraction} of admitted tests cull. + */ + private static void frame(RasterBudget budget, int far, double culledFraction) { + frame(budget, far, FARTHEST, culledFraction); + } + + /** As {@link #frame(RasterBudget, int, double)}, with the sections spread only out to {@code farthest}. */ + private static void frame(RasterBudget budget, int far, int farthest, double culledFraction) { + frame(budget, far, farthest, culledFraction, 1); + } + + /** As {@link #frame(RasterBudget, int, double)}, where each cull also hides {@code removedPerCull - 1} sections behind it. */ + private static void frame(RasterBudget budget, int far, double culledFraction, int removedPerCull) { + frame(budget, far, FARTHEST, culledFraction, removedPerCull); + } + + private static void frame(RasterBudget budget, int far, int farthest, double culledFraction, int removedPerCull) { + budget.beginFrame(CEILING); + int admitted = 0; + + for (int i = 0; i < far; i++) { + int squaredDist = spread(i, far, farthest); + + if (budget.shouldTest(squaredDist)) { + admitted++; + if (admitted * culledFraction >= budget.culled() + 1) { + budget.recordCulled(); + } + } + } + + budget.endFrame(Math.max(0, far - budget.culled() * removedPerCull)); + } + + /** A frame where every admitted test beyond {@code hiddenPast} culls and none nearer does: a cliff at that distance. */ + private static void frameHiddenBeyond(RasterBudget budget, int far, int hiddenPast) { + budget.beginFrame(CEILING); + + for (int i = 0; i < far; i++) { + int squaredDist = spread(i, far, FARTHEST); + + if (budget.shouldTest(squaredDist) && squaredDist > hiddenPast) { + budget.recordCulled(); + } + } + + budget.endFrame(far - budget.culled()); + } + + /** The {@code i}th of {@code far} squared distances spread evenly from just past the near range to {@code farthest}. */ + private static int spread(int i, int far, int farthest) { + return RasterOccluder.NEAR_SQUARED_CHUNK_DIST + 1 + + (int) ((long) i * (farthest - RasterOccluder.NEAR_SQUARED_CHUNK_DIST - 1) / Math.max(1, far - 1)); + } + + @Test + void startsAtFloorAndTestsOnlyTheNearShell() { + var budget = new RasterBudget(); + frame(budget, 5000, 0.0); + assertEquals(RasterBudget.FLOOR, budget.limit()); + assertFalse(budget.wasFullPass()); + assertTrue(budget.tested() < 5000 / 10, "tested " + budget.tested()); + assertTrue(budget.tested() >= RasterBudget.MIN_SAMPLE, "tested " + budget.tested()); + } + + @Test + void lowYieldSettlesAtFloor() { + var budget = new RasterBudget(); + + for (int i = 0; i < 40; i++) { + frame(budget, 5000, 0.01); + } + + assertEquals(RasterBudget.FLOOR, budget.limit()); + assertFalse(budget.wasFullPass()); + } + + @Test + void highYieldRampsToFullPassByDoubling() { + var budget = new RasterBudget(); + int previous = budget.limit(); + int frames = 0; + + do { + frame(budget, 4000, 0.9); + frames++; + assertTrue(budget.limit() <= previous * 2, "limit grew faster than doubling"); + previous = budget.limit(); + } while (!budget.wasFullPass() && frames < 32); + + assertTrue(budget.wasFullPass(), "never reached a full pass"); + // 12 -> 1025 is seven doublings, plus a couple of frames for the average to cross the threshold + assertTrue(frames <= 10, "took " + frames + " frames"); + assertEquals(CEILING, budget.limit(), "limit should stop at the ceiling"); + } + + @Test + void fullPassComesBackDownWhenYieldDrops() { + var budget = new RasterBudget(); + + for (int i = 0; i < 12; i++) { + frame(budget, 4000, 0.9); + } + assertTrue(budget.wasFullPass()); + + int frames = 0; + + while (budget.limit() != RasterBudget.FLOOR && frames < 40) { + frame(budget, 4000, 0.0); + frames++; + } + + assertEquals(RasterBudget.FLOOR, budget.limit()); + // the average needs about ten frames to decay below the low threshold, then seven halvings + assertTrue(frames <= 20, "took " + frames + " frames"); + } + + @Test + void midYieldHolds() { + var budget = new RasterBudget(); + + // ramp a step, then feed a yield inside the dead band until the average has decayed into it + frame(budget, 4000, 1.0); + + while (budget.yield() >= 0.15f) { + frame(budget, 4000, 0.10); + } + + int held = budget.limit(); + assertTrue(held > RasterBudget.FLOOR); + assertFalse(budget.wasFullPass()); + + for (int i = 0; i < 20; i++) { + frame(budget, 4000, 0.10); + } + + assertEquals(held, budget.limit()); + } + + @Test + void tooSmallASampleLeavesEverythingAlone() { + var budget = new RasterBudget(); + frame(budget, 4000, 0.9); + frame(budget, 4000, 0.9); + int limit = budget.limit(); + float yield = budget.yield(); + + // a handful of sections, all within the testable distance + frame(budget, RasterBudget.MIN_SAMPLE - 1, budget.limit(), 1.0); + + assertTrue(budget.wasFullPass()); + assertEquals(limit, budget.limit()); + assertEquals(yield, budget.yield()); + } + + @Test + void fewFarSectionsAreTestedInFullWithoutMovingTheLimit() { + var budget = new RasterBudget(); + // an enclosed space: few sections, none beyond twice the floor's distance + frame(budget, RasterBudget.CHEAP_PASS, RasterBudget.FLOOR * 4, 0.0); + assertTrue(budget.wasFullPass()); + assertEquals(RasterBudget.FLOOR, budget.limit()); + + // the next frame reaches many more: only the first CHEAP_PASS beyond the limit are admitted + frame(budget, 4000, 0.0); + assertFalse(budget.wasFullPass()); + assertTrue(budget.tested() >= RasterBudget.CHEAP_PASS, "tested " + budget.tested()); + assertTrue(budget.tested() < 4000 / 10, "tested " + budget.tested()); + } + + @Test + void nothingIsTestedBeyondTwiceTheLimitsDistance() { + var budget = new RasterBudget(); + budget.beginFrame(CEILING); + assertEquals(RasterBudget.FLOOR * 4, budget.testableLimit()); + + // a cheap frame, whose few sections lie beyond the testable distance, still admits none of them + for (int i = 0; i < RasterBudget.CHEAP_PASS / 2; i++) { + assertFalse(budget.shouldTest(RasterBudget.FLOOR * 4 + 1)); + } + assertTrue(budget.shouldTest(RasterBudget.FLOOR * 4)); + budget.endFrame(0); + + budget.pin(RasterBudget.UNBOUNDED); + budget.beginFrame(CEILING); + assertEquals(RasterBudget.UNBOUNDED, budget.testableLimit()); + } + + @Test + void pinnedLimitNeverMovesAndNeverProbes() { + var budget = new RasterBudget(); + budget.pin(RasterBudget.UNBOUNDED); + + for (int i = 0; i < 20; i++) { + frame(budget, 4000, 0.0); + assertTrue(budget.wasFullPass()); + } + + budget.pin(RasterBudget.FLOOR); + + for (int i = 0; i < RasterBudget.PROBE_PERIOD + 2; i++) { + frame(budget, 4000, 1.0); + assertEquals(RasterBudget.FLOOR, budget.limit()); + assertFalse(budget.wasFullPass()); + assertFalse(budget.wasProbe()); + } + } + + @Test + void probeFindsOcclusionBeyondTheFloorsReach() { + var budget = new RasterBudget(); + // hidden only past twice the floor's distance, which is as far as the floor ever tests + int hiddenPast = RasterBudget.FLOOR * 4; + + for (int i = 1; i < RasterBudget.PROBE_PERIOD; i++) { + frameHiddenBeyond(budget, 4000, hiddenPast); + assertEquals(RasterBudget.FLOOR, budget.limit(), "frame " + i); + assertFalse(budget.wasProbe()); + } + + frameHiddenBeyond(budget, 4000, hiddenPast); + assertTrue(budget.wasProbe()); + assertTrue(budget.wasFullPass()); + assertEquals(CEILING, budget.limit(), "the probe should start a full pass at once"); + + // and the full pass measures the same yield, so it stays + for (int i = 0; i < 8; i++) { + frameHiddenBeyond(budget, 4000, hiddenPast); + assertFalse(budget.wasProbe()); + assertTrue(budget.wasFullPass()); + assertEquals(CEILING, budget.limit()); + } + } + + @Test + void probeThatFindsNothingChangesNothing() { + var budget = new RasterBudget(); + + for (int i = 1; i < RasterBudget.PROBE_PERIOD; i++) { + frame(budget, 4000, 0.03); + } + + int limit = budget.limit(); + float yield = budget.yield(); + + frame(budget, 4000, 0.03); + assertTrue(budget.wasProbe()); + assertTrue(budget.wasFullPass()); + assertEquals(limit, budget.limit()); + assertEquals(yield, budget.yield(), "a probe's yield is not blended into the average"); + + frame(budget, 4000, 0.03); + assertFalse(budget.wasProbe()); + assertFalse(budget.wasFullPass()); + } + + @Test + void probeFromTheFloorStartsAFullPassThatRemovesEnough() { + var budget = new RasterBudget(); + + // below the yield that doubles the limit, but each cull hides a cave system + for (int i = 1; i < RasterBudget.PROBE_PERIOD; i++) { + frame(budget, 4000, 0.1, 20); + assertEquals(RasterBudget.FLOOR, budget.limit(), "frame " + i); + } + + frame(budget, 4000, 0.1, 20); + assertTrue(budget.wasProbe()); + assertEquals(CEILING, budget.limit()); + } + + @Test + void probeIgnoresAHighYieldThatRemovesTooLittleForItsTests() { + var budget = new RasterBudget(); + // gentle hills: the far quarter of what the probe tests culls, but each cull hides only itself + int hiddenPast = (FARTHEST * 3) / 4; + + for (int i = 1; i < RasterBudget.PROBE_PERIOD; i++) { + frameHiddenBeyond(budget, 4000, hiddenPast); + } + + frameHiddenBeyond(budget, 4000, hiddenPast); + assertTrue(budget.wasProbe()); + assertTrue(budget.culled() * 100 >= budget.tested() * 15, "the probe's yield alone would have paid"); + assertEquals(RasterBudget.FLOOR, budget.limit()); + } + + @Test + void fullPassIsNotProbed() { + var budget = new RasterBudget(); + + for (int i = 0; i < 16; i++) { + frame(budget, 4000, 0.9); + } + assertEquals(CEILING, budget.limit()); + + for (int i = 0; i < 2 * RasterBudget.PROBE_PERIOD; i++) { + frame(budget, 4000, 0.9); + assertFalse(budget.wasProbe(), "frame " + i); + } + } +} diff --git a/forge122/src/main/resources/assets/celeritas/lang/en_US.lang b/forge122/src/main/resources/assets/celeritas/lang/en_US.lang index b7558d209..519a29e11 100644 --- a/forge122/src/main/resources/assets/celeritas/lang/en_US.lang +++ b/forge122/src/main/resources/assets/celeritas/lang/en_US.lang @@ -19,7 +19,7 @@ celeritas.options.chunk_fade_in_duration.name=Chunk Fade-In Duration celeritas.options.chunk_fade_in_duration.value=%s ms celeritas.options.chunk_fade_in_duration.tooltip=Controls how long it takes for newly loaded chunks to fully appear. Longer durations create a smoother transition between unloaded and loaded chunks, reducing visual popping, but may make distant terrain appear to 'fade in' more slowly. celeritas.options.raster_occlusion_culling.name=Rasterized Occlusion Culling -celeritas.options.raster_occlusion_culling.tooltip=Rasterizes nearby terrain into a small software coverage buffer and uses it to skip chunks hidden behind solid terrain, such as a valley behind a hill. This can substantially reduce the amount of terrain drawn, but costs extra CPU time each frame, so it helps most when the GPU is the bottleneck.\n\nChanging this rebuilds all chunks. +celeritas.options.raster_occlusion_culling.tooltip=Rasterizes nearby terrain into a small software coverage buffer and uses it to skip chunks hidden behind solid terrain, such as a valley behind a hill. This can substantially reduce the amount of terrain drawn. This helps most when the GPU is the bottleneck.\n\nChanging this rebuilds all chunks. sodium.option_impact.low=Low sodium.option_impact.medium=Medium sodium.option_impact.high=High diff --git a/modern/src/main/resources/assets/embeddium/lang/en_us.json b/modern/src/main/resources/assets/embeddium/lang/en_us.json index a200b8570..eb9632d0c 100644 --- a/modern/src/main/resources/assets/embeddium/lang/en_us.json +++ b/modern/src/main/resources/assets/embeddium/lang/en_us.json @@ -19,5 +19,5 @@ "celeritas.options.chunk_fade_in_duration.value": "%s ms", "celeritas.options.chunk_fade_in_duration.tooltip": "Controls how long it takes for newly loaded chunks to fully appear. Longer durations create a smoother transition between unloaded and loaded chunks, reducing visual popping, but may make distant terrain appear to 'fade in' more slowly.", "celeritas.options.raster_occlusion_culling.name": "Rasterized Occlusion Culling", - "celeritas.options.raster_occlusion_culling.tooltip": "Rasterizes nearby terrain into a small software coverage buffer and uses it to skip chunks hidden behind solid terrain, such as a valley behind a hill. This can substantially reduce the amount of terrain drawn, but costs extra CPU time each frame, so it helps most when the GPU is the bottleneck.\n\nChanging this rebuilds all chunks." + "celeritas.options.raster_occlusion_culling.tooltip": "Rasterizes nearby terrain into a small software coverage buffer and uses it to skip chunks hidden behind solid terrain, such as a valley behind a hill. This can substantially reduce the amount of terrain drawn. This helps most when the GPU is the bottleneck.\n\nChanging this rebuilds all chunks." }