Adaptive raster culling #41

Merged
embeddedt merged 9 commits from adaptive-raster-culling into stonecutter 2026-09-17 10:10:54 -04:00
15 changed files with 732 additions and 45 deletions
Showing only changes of commit 40eab968c3 - Show all commits

No files matched your search

+12 -5
View File
@@ -145,12 +145,11 @@ tasks.register('jmh', JavaExec) {
// collector's per-frame allocation, not a requirement.
maxHeapSize = '1g'
doFirst {
// 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() })
}
}
}
tasks.register('rasterCullReport', JavaExec) {
group = 'verification'
@@ -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() })
}
@@ -71,6 +71,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 +91,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;
}
/** {@return whether this world has no blocks at all} */
boolean isVoid() {
return this.type == WorldType.EMPTY;
@@ -156,6 +165,11 @@ public final class VoxelWorld {
return Integer.MAX_VALUE;
}
if (this.type == WorldType.FLAT || this.type == WorldType.PLAINS) {
// the SURFACE height at the origin, so Cameras.surfaceCameraY(0, 0) is at eye height here too
return (int) Math.floor(sectionHeight(0.0, 0.0) * 16.0);
}
return (int) Math.floor(sectionHeight(bx * (1.0 / 16.0), bz * (1.0 / 16.0)) * 16.0);
}
@@ -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());
}
}
@@ -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);
@@ -8,7 +8,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. */
private static final int WARM_FRAMES = 48;
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,FLAT,SURFACE,CAVES");
return java.util.Arrays.stream(list.split(",")).map(String::trim).map(WorldType::valueOf).toArray(WorldType[]::new);
}
private RasterCullReport() {
}
@@ -24,9 +32,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 +51,218 @@ 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),
budget.wasFullPass() ? "full" : Integer.toString(budget.limit()), 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;
}
/**
* Settles the controller on the placement with the least occlusion, then jumps to the one with the most and
* counts frames until the budget stops changing. This is the latency a player sees walking into a cave.
*/
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();
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;
for (int i = 0; i < WARM_FRAMES; 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);
if (i < 16) {
trace.append(' ').append(budget.wasFullPass() ? "full" : Integer.toString(budget.limit()));
}
if (budget.limit() != previous) {
settledAt = -1;
} else if (settledAt < 0) {
settledAt = i;
}
previous = budget.limit();
}
System.out.printf("%-8s ramp %s -> %s: limit %d -> %s, settled after %d frames, trace:%s%n", world, from.name(), to.name(),
startBudget, budget.wasFullPass() ? "full" : Integer.toString(budget.limit()), 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,
budget.wasFullPass() ? "full" : Integer.toString(budget.limit()), 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 +305,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),
};
}
}
@@ -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,18 +54,28 @@ 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);
}
}
// 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();
long visible = 0;
visible = 0;
long t0 = System.nanoTime();
for (Viewport v : ring) {
var c = new CountingVisitor();
@@ -67,12 +83,27 @@ public final class RasterStatsReport {
lattice.findVisible(c, v, searchDistance, numRegions, true, true, ++frame);
visible += c.visible;
}
long total = System.nanoTime() - t0;
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);
}
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;
@@ -6,6 +6,15 @@ 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,
/** Stone to the top of the world with caves. Heavily occluded. */
CAVES
}
@@ -77,7 +77,7 @@ public class SodiumGameOptions implements OptionStorage<SodiumGameOptions> {
public AsyncOcclusionMode asyncOcclusionMode = AsyncOcclusionMode.ONLY_SHADOW;
public boolean useRasterOcclusionCulling = false;
public boolean useRasterOcclusionCulling = true;
}
public static class AdvancedSettings {
@@ -117,6 +117,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 +196,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();
}
if (recordVisible) {
this.lattice.visibleCount = this.visibleCount;
}
@@ -364,6 +370,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) {
int radius = (int) Math.ceil(searchDistance / 16.0f) + 1;
int height = (this.maxSectionY - this.minSectionY) + 1;
return (radius * radius) + (height * height);
}
/** 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,15 +428,29 @@ 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) {
if (result == RasterOccluder.SectionVisibility.VISIBLE) {
if (hasGeometry) {
occluder.occludeSection(occluderData[idx]);
}
} else {
this.rasterBudget.recordCulled();
}
return result;
}
@@ -426,6 +465,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) {
@@ -0,0 +1,156 @@
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.
*
* <p>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.
*
* <p>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.
*/
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;
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;
/** 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 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);
int limit = this.limit();
this.testable = limit >= this.ceiling ? UNBOUNDED : Math.min(this.ceiling, saturatingDouble(saturatingDouble(limit)));
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.limit() && this.farReached > CHEAP_PASS)) {
return false;
}
this.tested++;
return true;
}
public void recordCulled() {
this.culled++;
}
public void endFrame() {
if (this.tested >= MIN_SAMPLE) {
int yield = (int) (((long) this.culled << Q) / this.tested);
this.yieldEma += (yield - this.yieldEma) >> EMA_SHIFT;
}
if (this.pinned != 0 || this.tested < MIN_SAMPLE) {
return;
}
if (this.yieldEma >= 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;
}
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;
}
@Override
public String toString() {
return String.format("limit=%s yield=%.1f%% far=%d farthest=%d tested=%d culled=%d",
this.limit() == UNBOUNDED ? "max" : Integer.toString(this.limit()),
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;
}
}
@@ -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));
@@ -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.
@@ -0,0 +1,195 @@
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) {
budget.beginFrame(CEILING);
int admitted = 0;
for (int i = 0; i < far; i++) {
int squaredDist = RasterOccluder.NEAR_SQUARED_CHUNK_DIST + 1
+ (int) ((long) i * (farthest - RasterOccluder.NEAR_SQUARED_CHUNK_DIST - 1) / Math.max(1, far - 1));
if (budget.shouldTest(squaredDist)) {
admitted++;
if (admitted * culledFraction >= budget.culled() + 1) {
budget.recordCulled();
}
}
}
budget.endFrame();
}
@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();
budget.pin(RasterBudget.UNBOUNDED);
budget.beginFrame(CEILING);
assertEquals(RasterBudget.UNBOUNDED, budget.testableLimit());
}
@Test
void pinnedLimitNeverMoves() {
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 < 20; i++) {
frame(budget, 4000, 1.0);
assertEquals(RasterBudget.FLOOR, budget.limit());
assertFalse(budget.wasFullPass());
}
}
}
@@ -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
@@ -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."
}