rasterized occlusion culling #38

Merged
embeddedt merged 20 commits from rdh/celeritas:raster into stonecutter 2026-09-04 22:15:05 -04:00
8 changed files with 226 additions and 32 deletions
Showing only changes of commit 5ea0f09aef - Show all commits

No files matched your search

@@ -87,7 +87,7 @@ public class MultiDrawBench {
BenchPlatform.ensureInitialized();
this.syntheticWorld = new SyntheticWorld(this.world, this.renderDistance, SyntheticWorld.DEFAULT_SEED,
this.caveWidth, true, 0.0D, false);
this.caveWidth, true, 0.0D, false, false);
this.lattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, false);
@@ -18,40 +18,56 @@ public final class RasterCullReport {
public static void main(String[] args) {
BenchPlatform.ensureInitialized();
System.out.printf("%-8s %-8s %10s %10s%n", "world", "camera", "visited", "visible");
System.out.println("-".repeat(42));
System.out.printf("%-8s %-8s %10s %10s %8s %10s%n",
"world", "camera", "baseline", "occluded", "delta", "backtrack");
System.out.println("-".repeat(66));
for (WorldType world : WORLDS) {
var syntheticWorld = new SyntheticWorld(world, RENDER_DISTANCE, true);
var syntheticWorld = new SyntheticWorld(world, RENDER_DISTANCE, true, true);
float searchDistance = syntheticWorld.getSearchDistance();
int numRegions = BenchPlatform.regionManager().getRegionIdsLength();
var lattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, false);
var baselineLattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y,
false, false);
var rasterLattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y,
false, true);
for (RenderSection section : syntheticWorld.getConstructionOrder()) {
lattice.attach(section);
baselineLattice.attach(section);
rasterLattice.attach(section);
}
int frame = 0;
for (Placement placement : placements()) {
long visited = 0;
long visible = 0;
long baseline = 0;
long occluded = 0;
long backtracks = 0;
for (int step = 0; step < YAW_STEPS; step++) {
Viewport viewport = Cameras.viewport(8.5, placement.y(), 8.5,
(360.0f / YAW_STEPS) * step, placement.pitch(), RENDER_DISTANCE);
var visitor = new CountingVisitor();
lattice.ensureWindowCovers(viewport.getChunkCoord(), searchDistance);
lattice.findVisible(visitor, viewport, searchDistance, numRegions, true, true, ++frame);
var without = new CountingVisitor();
baselineLattice.ensureWindowCovers(viewport.getChunkCoord(), searchDistance);
baselineLattice.findVisible(without, viewport, searchDistance, numRegions, true, true, ++frame);
visited += visitor.visited;
visible += visitor.visible;
var with = new CountingVisitor();
rasterLattice.ensureWindowCovers(viewport.getChunkCoord(), searchDistance);
rasterLattice.findVisible(with, viewport, searchDistance, numRegions, true, true, ++frame);
baseline += without.visible;
occluded += with.visible;
backtracks += rasterLattice.rasterBacktrackCount();
}
System.out.printf("%-8s %-8s %10d %10d%n", world, placement.name(),
visited / YAW_STEPS, visible / YAW_STEPS);
long meanBaseline = baseline / YAW_STEPS;
long meanOccluded = occluded / YAW_STEPS;
double delta = meanBaseline == 0 ? 0.0
: ((meanOccluded - meanBaseline) * 100.0) / meanBaseline;
System.out.printf("%-8s %-8s %10d %10d %7.1f%% %10d%n", world, placement.name(),
meanBaseline, meanOccluded, delta, backtracks / YAW_STEPS);
}
}
}
@@ -4,6 +4,7 @@ import it.unimi.dsi.fastutil.longs.Long2ReferenceMap;
import it.unimi.dsi.fastutil.longs.Long2ReferenceOpenHashMap;
import org.embeddedt.embeddium.impl.render.chunk.ChunkUpdateType;
import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry.OccluderBoxes;
import org.embeddedt.embeddium.impl.render.chunk.bench.voxel.VoxelWorld;
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegionManager;
@@ -43,20 +44,27 @@ public final class SyntheticWorld {
private final int sectionCount;
public SyntheticWorld(WorldType type, int renderDistance) {
this(type, renderDistance, DEFAULT_SEED, VoxelWorld.DEFAULT_CAVE_WIDTH, false, 0.0D, false);
this(type, renderDistance, DEFAULT_SEED, VoxelWorld.DEFAULT_CAVE_WIDTH, false, 0.0D, false, false);
}
public SyntheticWorld(WorldType type, int renderDistance, boolean scatteredAlloc) {
this(type, renderDistance, DEFAULT_SEED, VoxelWorld.DEFAULT_CAVE_WIDTH, scatteredAlloc, 0.0D, false);
this(type, renderDistance, DEFAULT_SEED, VoxelWorld.DEFAULT_CAVE_WIDTH, scatteredAlloc, 0.0D, false, false);
}
public SyntheticWorld(WorldType type, int renderDistance, boolean scatteredAlloc, boolean occluderBoxes) {
this(type, renderDistance, DEFAULT_SEED, VoxelWorld.DEFAULT_CAVE_WIDTH, scatteredAlloc, 0.0D, false,
occluderBoxes);
}
/**
* @param scatteredAlloc shuffled allocation order (models a long-lived session)
* @param unloadedProbability fraction of sections absent from the box
* @param allFlagged full visuals mask on every section (sensitivity knob, not realistic)
* @param occluderBoxes generate occluder boxes; far dearer per section than the visibility fill,
* and dead weight unless a report is measuring the rasterizer
*/
public SyntheticWorld(WorldType type, int renderDistance, long seed, double caveWidth, boolean scatteredAlloc,
double unloadedProbability, boolean allFlagged) {
double unloadedProbability, boolean allFlagged, boolean occluderBoxes) {
this.type = type;
this.renderDistance = renderDistance;
this.seed = seed;
@@ -102,7 +110,11 @@ public final class SyntheticWorld {
// arithmetic moves off this thread — pass 2 still allocates every section itself, in order, because the
// heap layout of those sections is exactly what scatteredAlloc exists to control and letting worker
// threads allocate them into their own TLABs would quietly change what the benchmark measures.
long[] visibility = this.computeVisibility(radius, width);
int[][] boxes = occluderBoxes
? new int[width * width * (MAX_SECTION_Y - MIN_SECTION_Y)][]
: null;
long[] visibility = this.computeVisibility(radius, width, boxes);
// Pass 2: allocate sections in the requested order.
this.sections = new Long2ReferenceOpenHashMap<>(present, 0.75f);
@@ -114,8 +126,14 @@ public final class SyntheticWorld {
var section = new RenderSection(regionFor(regionManager, regions, x, y, z), x, y, z);
section.setInfo(new BenchSectionData(visibility[gridIndex(x, y, z, radius, width)], x, y, z,
allFlagged));
var info = new BenchSectionData(visibility[gridIndex(x, y, z, radius, width)], x, y, z,
allFlagged);
if (boxes != null) {
info.occluderBoxes = boxes[gridIndex(x, y, z, radius, width)];
}
section.setInfo(info);
applyPendingUpdate(section, x, y, z);
this.sections.put(packed, section);
@@ -211,14 +229,14 @@ public final class SyntheticWorld {
* {@code VoxelWorld}'s heightmap cache. Output does not depend on the striping: visibility is a pure
* function of position.
*/
private long[] computeVisibility(int radius, int width) {
private long[] computeVisibility(int radius, int width, int[][] occluderBoxes) {
final int height = MAX_SECTION_Y - MIN_SECTION_Y;
var visibility = new long[width * width * height];
int workers = Math.min(Runtime.getRuntime().availableProcessors(), width);
if (workers <= 1) {
this.computeVisibilityStripe(this.voxelWorld, visibility, radius, width, 0, 1);
this.computeVisibilityStripe(this.voxelWorld, visibility, occluderBoxes, radius, width, 0, 1);
return visibility;
}
@@ -231,7 +249,7 @@ public final class SyntheticWorld {
// seed generate identical blocks. They are dropped with the threads, releasing those caches.
threads[w] = new Thread(() -> this.computeVisibilityStripe(
new VoxelWorld(this.type, this.seed, this.voxelWorld.getCaveWidth()),
visibility, radius, width, worker, workers), "bench-worldgen-" + worker);
visibility, occluderBoxes, radius, width, worker, workers), "bench-worldgen-" + worker);
threads[w].start();
}
@@ -249,8 +267,8 @@ public final class SyntheticWorld {
}
/** Runs the real visibility flood fill over every section in this worker's share of the columns. */
private void computeVisibilityStripe(VoxelWorld world, long[] visibility, int radius, int width,
int worker, int workers) {
private void computeVisibilityStripe(VoxelWorld world, long[] visibility, int[][] occluderBoxes,
int radius, int width, int worker, int workers) {
for (int xi = worker; xi < width; xi += workers) {
int x = xi - radius;
@@ -262,7 +280,14 @@ public final class SyntheticWorld {
continue;
}
visibility[gridIndex(x, y, z, radius, width)] = world.slice(x, y, z).computeVisibility();
var slice = world.slice(x, y, z);
int index = gridIndex(x, y, z, radius, width);
if (occluderBoxes != null) {
occluderBoxes[index] = OccluderBoxes.from(slice.opacityBits());
}
visibility[index] = slice.computeVisibility();
}
}
}
@@ -139,7 +139,7 @@ public abstract class RenderSectionManager {
this.minSection = minSection;
this.maxSection = maxSection;
AsyncOcclusionMode asyncMode = this.getAsyncOcclusionMode();
this.sectionGraph = new SectionGraph(this.minSection, this.maxSection, asyncMode, hasShadowPass);
this.sectionGraph = new SectionGraph(this.minSection, this.maxSection, asyncMode, hasShadowPass, this.useRasterOcclusionCulling());
this.renderListManager = new RenderListManager(this.sectionGraph, false, asyncMode, this.createSectionTicker());
if (hasShadowPass) {
this.shadowRenderListManager = new RenderListManager(this.sectionGraph, true, asyncMode, this.createSectionTicker());
@@ -34,8 +34,8 @@ public final class SectionGraph {
// runDeferredTasks() once every search has been joined.
private final ArrayDeque<Runnable> updateTasks = new ArrayDeque<>();
public SectionGraph(int minSectionY, int maxSectionY, AsyncOcclusionMode asyncMode, boolean hasShadowPass) {
this.lattice = new SectionLattice(minSectionY, maxSectionY, hasShadowPass);
public SectionGraph(int minSectionY, int maxSectionY, AsyncOcclusionMode asyncMode, boolean hasShadowPass, boolean rasterOcclusion) {
this.lattice = new SectionLattice(minSectionY, maxSectionY, hasShadowPass, rasterOcclusion);
if (asyncMode != AsyncOcclusionMode.NONE) {
this.executor = Executors.newSingleThreadExecutor(runnable -> {
@@ -3,10 +3,12 @@ package org.embeddedt.embeddium.impl.render.chunk.occlusion;
import org.embeddedt.embeddium.impl.common.util.MathUtil;
import org.embeddedt.embeddium.impl.render.chunk.LocalSectionIndex;
import org.embeddedt.embeddium.impl.render.chunk.PackedSectionMetadata;
import org.embeddedt.embeddium.impl.render.chunk.lists.RenderVisualsService;
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
import org.embeddedt.embeddium.impl.render.viewport.CameraTransform;
import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.embeddedt.embeddium.impl.render.viewport.frustum.Frustum;
import org.jetbrains.annotations.Nullable;
import org.joml.Vector3ic;
import static org.embeddedt.embeddium.impl.common.util.MathUtil.nearestToZero;
@@ -114,13 +116,17 @@ public class OcclusionCuller {
private final RegionCullCache regionCullCache = new RegionCullCache();
private final @Nullable RasterOccluder rasterOccluder;
private boolean rasterActive;
private boolean isCameraInUnloadedSection;
private boolean isMultiRootSearch;
public OcclusionCuller(SectionLattice lattice, int minSectionY, int maxSectionY) {
public OcclusionCuller(SectionLattice lattice, int minSectionY, int maxSectionY, boolean rasterOcclusion) {
this.lattice = lattice;
this.minSectionY = minSectionY;
this.maxSectionY = maxSectionY;
this.rasterOccluder = rasterOcclusion ? new RasterOccluder() : null;
}
/**
@@ -182,6 +188,12 @@ public class OcclusionCuller {
allowFrustumClamping = false;
}
this.rasterActive = this.rasterOccluder != null && useOcclusionCulling && viewport.getVpMatrix() != null;
if (this.rasterActive) {
this.rasterOccluder.prepareScene(frame, viewport);
}
this.process(visitor, viewport, searchDistance, useOcclusionCulling, allowFrustumClamping, frame);
if (recordVisible) {
@@ -285,6 +297,10 @@ public class OcclusionCuller {
visible = aperture != FastFrustumClamping.EMPTY;
}
if (this.rasterActive && visible) {
visible = this.rasterTest(idx, chunkX, chunkY, chunkZ, camX, camY, camZ, compactMeta);
}
int sectionIndex = LocalSectionIndex.pack(chunkX, chunkY, chunkZ);
visitor.visit(idx, regionId, sectionIndex, compactMeta, visible);
@@ -335,6 +351,34 @@ public class OcclusionCuller {
this.visibleCount = visibleCount;
}
private boolean rasterTest(int idx, int chunkX, int chunkY, int chunkZ, int camX, int camY, int camZ, int meta) {
int dx = chunkX - camX;
int dy = chunkY - camY;
int dz = chunkZ - camZ;
int squaredChunkDist = (dx * dx) + (dy * dy) + (dz * dz);
var occluder = this.rasterOccluder;
if (!occluder.isSectionVisible(chunkX << 4, chunkY << 4, chunkZ << 4, squaredChunkDist)) {
return false;
}
if ((PackedSectionMetadata.getCompactVisualsFlags(meta) & (1 << RenderVisualsService.HAS_BLOCK_GEOMETRY)) != 0) {
var section = this.lattice.latticeSection[idx];
var built = section != null ? section.getBuiltContext() : null;
if (built != null && built.occluderBoxes != null) {
occluder.drawOccluders(built.occluderBoxes, squaredChunkDist);
}
}
return true;
}
public int rasterBacktrackCount() {
return this.rasterOccluder == null ? 0 : this.rasterOccluder.backtrackCount();
}
// 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,101 @@
package org.embeddedt.embeddium.impl.render.chunk.occlusion;
import grondag.bitraster.BoxOccluder;
import grondag.bitraster.Matrix4L;
import grondag.bitraster.PackedBox;
import grondag.bitraster.PerspectiveRasterizer;
import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.joml.Matrix4fc;
public final class RasterOccluder extends BoxOccluder {
/** Sections this close are drawn but never tested, since they're almost always visible and most costly to test */
public static final int NEAR_SQUARED_CHUNK_DIST = 3;
/** Beyond 7 chunks, expand tests by a block to absorb rasterization error. From canvas's trial and error. */
private static final int FUZZ_SQUARED_CHUNK_DIST = 7 * 7;
private int maxDrawnSquaredDist;
private int backtrackCount;
public RasterOccluder() {
super(new PerspectiveRasterizer());
}
@Override
public boolean isBoxVisible(int packedBox, int fuzz) {
return isBoxVisibleFromPerspective(packedBox, fuzz);
}
@Override
public void occludeBox(int packedBox) {
occludeFromPerspective(packedBox);
}
/**
* 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.
*/
public void prepareScene(int viewVersion, Viewport viewport) {
Matrix4fc vpMatrix = viewport.getVpMatrix();
if (vpMatrix == null) {
throw new IllegalStateException("viewport supplies no view matrix");
}
var transform = viewport.getTransform();
this.maxDrawnSquaredDist = 0;
this.backtrackCount = 0;
invalidate();
prepareScene(viewVersion, transform.x, transform.y, transform.z,
Matrix4L::loadIdentity, m -> RasterMatrices.copy(vpMatrix, m));
}
/**
* {@return whether any part of the section is unoccluded}
*
* <p>Must be called before {@link #drawOccluders}, or a section would occlude itself.
*/
public boolean isSectionVisible(int originX, int originY, int originZ, int squaredChunkDist) {
prepareRegion(originX, originY, originZ,
PackedBox.rangeFromSquareChunkDist(squaredChunkDist), squaredChunkDist);
if (squaredChunkDist <= NEAR_SQUARED_CHUNK_DIST) {
return true;
}
boolean visible = isBoxVisible(PackedBox.FULL_BOX,
squaredChunkDist >= FUZZ_SQUARED_CHUNK_DIST ? 1 : 0);
if (!visible && squaredChunkDist < this.maxDrawnSquaredDist) {
this.backtrackCount++;
}
return visible;
}
public void drawOccluders(int[] boxes, int squaredChunkDist) {
int range = PackedBox.rangeFromSquareChunkDist(squaredChunkDist);
for (int box : boxes) {
if (range > PackedBox.range(box)) {
break;
}
occludeBox(box);
}
if (squaredChunkDist > this.maxDrawnSquaredDist) {
this.maxDrawnSquaredDist = squaredChunkDist;
}
}
// the buffer holds coverage only, with no depth, so it's correct only if sections are drawn
// front to back. our bfs visits in hop-count order, which approximates that but does not
// guarantee it, so this reports how often the approximation was wrong.
public int backtrackCount() {
return this.backtrackCount;
}
}
@@ -192,11 +192,15 @@ public final class SectionLattice {
* visit-state array
*/
public SectionLattice(int minSectionY, int maxSectionY, boolean hasShadowPass) {
this(minSectionY, maxSectionY, hasShadowPass, false);
}
public SectionLattice(int minSectionY, int maxSectionY, boolean hasShadowPass, boolean rasterOcclusion) {
this.minSectionY = minSectionY;
this.maxSectionY = maxSectionY;
this.baseY = minSectionY - 1;
this.dimY = (maxSectionY - minSectionY) + 2;
this.culler = new OcclusionCuller(this, minSectionY, maxSectionY);
this.culler = new OcclusionCuller(this, minSectionY, maxSectionY, rasterOcclusion);
this.shadowCuller = hasShadowPass ? new ShadowOcclusionCuller(this) : null;
if (this.dimY > MAX_DIM) {
@@ -459,6 +463,10 @@ public final class SectionLattice {
return this.snapshot(this.visitState, this.mainSnapshotBuffers);
}
public int rasterBacktrackCount() {
return this.culler.rasterBacktrackCount();
}
/**
* 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.