Major occlusion search optimizations #34

Merged
embeddedt merged 11 commits from occlusion-opts into stonecutter 2026-08-18 19:59:03 -04:00
7 changed files with 211 additions and 22 deletions
Showing only changes of commit 094d4a21be - Show all commits

No files matched your search

@@ -37,4 +37,18 @@ public class MathUtil {
public static boolean roughlyEqual(float a, float b) {
return Math.abs(b - a) < 0.00001f;
}
/**
* Returns the value nearest to zero in [min, max].
* <p>
* In other words, if zero is inside [min, max], returns 0. Otherwise, returns whichever endpoint is closer to zero.
*/
@SuppressWarnings("ManualMinMaxCalculation") // we know what we are doing.
public static int nearestToZero(int min, int max) {
// this compiles to slightly better code than Math.min(Math.max(0, min), max)
int clamped = 0;
if (min > 0) { clamped = min; }
if (max < 0) { clamped = max; }
return clamped;
}
}
@@ -106,7 +106,7 @@ public class RenderListManager {
var visitor = new VisibleChunkCollector(frame, regionIdsLength, targetQueueSize);
Supplier<VisibleChunkCollector> occlusionTask = () -> {
this.occlusionCuller.findVisible(visitor, viewport, searchDistance, useOcclusionCulling, frame);
this.occlusionCuller.findVisible(visitor, viewport, searchDistance, regionIdsLength, useOcclusionCulling, frame);
// WARNING: when asyncGraphExecutor != null, this runs on the async thread.
// SectionTicker.onRenderListUpdated() must be safe to call off the render thread.
@@ -2,8 +2,10 @@ package org.embeddedt.embeddium.impl.render.chunk.occlusion;
import it.unimi.dsi.fastutil.longs.Long2ReferenceMap;
import org.embeddedt.embeddium.impl.common.util.MathUtil;
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.embeddedt.embeddium.impl.util.PositionUtil;
import org.embeddedt.embeddium.impl.util.collections.DoubleBufferedQueue;
import org.embeddedt.embeddium.impl.util.collections.ReadQueue;
@@ -16,16 +18,22 @@ import org.embeddedt.embeddium.api.render.chunk.RenderSectionDistanceFilterEvent
import org.jetbrains.annotations.NotNull;
import org.joml.Vector3ic;
import java.util.Arrays;
import java.util.Objects;
import static org.embeddedt.embeddium.impl.common.util.MathUtil.nearestToZero;
public class OcclusionCuller {
private final Long2ReferenceMap<OcclusionNode> sections;
private final int minSectionY, maxSectionY;
private final DoubleBufferedQueue<OcclusionNode> queue = new DoubleBufferedQueue<>();
private final RegionCullCache regionCullCache = new RegionCullCache();
private boolean isCameraInUnloadedSection;
public OcclusionCuller(Long2ReferenceMap<OcclusionNode> sections, int minSectionY, int maxSectionY) {
this.sections = sections;
this.minSectionY = minSectionY;
@@ -35,12 +43,17 @@ public class OcclusionCuller {
public void findVisible(Visitor visitor,
Viewport viewport,
float searchDistance,
int numRegions,
boolean useOcclusionCulling,
int frame)
{
final var queues = this.queue;
queues.reset();
final var cache = this.regionCullCache;
cache.begin(viewport, searchDistance, numRegions);
this.isCameraInUnloadedSection = false;
this.init(visitor, queues.write(), viewport, searchDistance, useOcclusionCulling, frame);
if(this.isCameraInUnloadedSection) {
@@ -48,7 +61,7 @@ public class OcclusionCuller {
}
while (queues.flip()) {
processQueue(visitor, viewport, searchDistance, useOcclusionCulling, frame, queues.read(), queues.write());
processQueue(visitor, viewport, searchDistance, useOcclusionCulling, frame, queues.read(), queues.write(), cache);
}
}
@@ -58,12 +71,21 @@ public class OcclusionCuller {
boolean useOcclusionCulling,
int frame,
ReadQueue<OcclusionNode> readQueue,
WriteQueue<OcclusionNode> writeQueue)
WriteQueue<OcclusionNode> writeQueue,
RegionCullCache regionCullCache)
{
OcclusionNode section;
while ((section = readQueue.dequeue()) != null) {
boolean visible = isSectionVisible(section, viewport, searchDistance);
int classification = regionCullCache.classify(section.getRenderRegionId(), section.getRegionOriginX(), section.getRegionOriginY(), section.getRegionOriginZ());
boolean visible;
if (classification == Frustum.PARTIALLY_INSIDE) {
visible = isWithinRenderDistance(viewport.getTransform(), section, searchDistance) && isWithinFrustum(viewport, section);
} else {
visible = classification == Frustum.FULLY_INSIDE;
}
visitor.visit(section, visible);
if (!visible) {
@@ -92,10 +114,6 @@ public class OcclusionCuller {
}
}
private static boolean isSectionVisible(OcclusionNode section, Viewport viewport, float maxDistance) {
return isWithinRenderDistance(viewport.getTransform(), section, maxDistance) && isWithinFrustum(viewport, section);
}
private static void visitNeighbors(final WriteQueue<OcclusionNode> queue, OcclusionNode section, int outgoing, int frame) {
// Only traverse into neighbors which are actually present.
// This avoids a null-check on each invocation to enqueue, and since the compiler will see that a null
@@ -179,15 +197,6 @@ public class OcclusionCuller {
//return DistanceFilterHolder.INSTANCE.isWithinDistance(dx, dy, dz, maxDistance);
}
@SuppressWarnings("ManualMinMaxCalculation") // we know what we are doing.
private static int nearestToZero(int min, int max) {
// this compiles to slightly better code than Math.min(Math.max(0, min), max)
int clamped = 0;
if (min > 0) { clamped = min; }
if (max < 0) { clamped = max; }
return clamped;
}
// The bounding box of a chunk section must be large enough to contain all possible geometry within it. Block models
// can extend outside a block volume by +/- 1.0 blocks on all axis. Additionally, we make use of a small epsilon
// to deal with floating point imprecision during a frustum check (see GH#2132).
@@ -4,8 +4,9 @@ import lombok.Getter;
import lombok.Setter;
import org.embeddedt.embeddium.impl.render.chunk.AbstractSection;
import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
public class OcclusionNode extends AbstractSection {
public final class OcclusionNode extends AbstractSection {
private int incomingDirections;
private int lastVisibleFrame = -1;
@@ -92,4 +93,16 @@ public class OcclusionNode extends AbstractSection {
public RenderSection getRenderSection() {
return this.section;
}
public int getRegionOriginX() {
return (this.getChunkX() >> RenderRegion.REGION_WIDTH_SH) * RenderRegion.REGION_BLOCK_WIDTH;
}
public int getRegionOriginY() {
return (this.getChunkY() >> RenderRegion.REGION_HEIGHT_SH) * RenderRegion.REGION_BLOCK_HEIGHT;
}
public int getRegionOriginZ() {
return (this.getChunkZ() >> RenderRegion.REGION_LENGTH_SH) * RenderRegion.REGION_BLOCK_LENGTH;
}
}
@@ -0,0 +1,149 @@
package org.embeddedt.embeddium.impl.render.chunk.occlusion;
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 java.util.Arrays;
import static org.embeddedt.embeddium.impl.common.util.MathUtil.nearestToZero;
import static org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion.*;
/**
* Per-region memoization of the two per-section visibility predicates used by {@link OcclusionCuller}.
* <p>
* Sections are grouped into 8x4x8-section regions (128x64x128 blocks) with dense ids. Once per frame a region
* is classified as:
* <ul>
* <li>{@link Frustum#OUTSIDE} - <i>every</i> section in the region is guaranteed to fail
* {@code isWithinRenderDistance(..) &amp;&amp; isWithinFrustum(..)}</li>
* <li>{@link Frustum#FULLY_INSIDE} - <i>every</i> section in the region is guaranteed to pass both</li>
* <li>{@link Frustum#PARTIALLY_INSIDE} - unknown; the caller must run the exact per-section tests</li>
* </ul>
*/
final class RegionCullCache {
/** 1.125 (= 9.125 - 8) plus 1/32 of slack to swallow float rounding in the camera-relative transform. */
private static final float FRUSTUM_PAD = 1.125f + 0.03125f;
/** Slack on the distance bounds; float error at these magnitudes is on the order of 1e-4. */
private static final float DISTANCE_EPSILON = 0.001f;
private static final int INITIAL_CAPACITY = 64;
private byte[] classification = new byte[INITIAL_CAPACITY];
private int[] stamp = new int[INITIAL_CAPACITY];
private int currentStamp;
// Per-frame state, refreshed by begin().
private Viewport viewport;
private CameraTransform camera;
private float maxDistance;
RegionCullCache() {
Arrays.fill(this.stamp, -1);
}
void begin(Viewport viewport, float searchDistance, int numRegions) {
this.viewport = viewport;
this.camera = viewport.getTransform();
this.maxDistance = searchDistance;
this.currentStamp++;
if (numRegions >= this.stamp.length) {
this.grow(numRegions);
}
}
/**
* @param regionId dense region id; used only as a memoization slot
* @param regionOriginX block coordinate of the region's minimum corner
*/
int classify(int regionId, int regionOriginX, int regionOriginY, int regionOriginZ) {
if (this.stamp[regionId] != this.currentStamp) {
this.stamp[regionId] = this.currentStamp;
this.classification[regionId] = (byte) this.compute(regionOriginX, regionOriginY, regionOriginZ);
}
return this.classification[regionId];
}
private void grow(int minimumCapacity) {
int capacity = Math.max(minimumCapacity, this.stamp.length * 2);
int oldLength = this.stamp.length;
this.stamp = Arrays.copyOf(this.stamp, capacity);
this.classification = Arrays.copyOf(this.classification, capacity);
Arrays.fill(this.stamp, oldLength, capacity, -1);
}
private int compute(int regionOriginX, int regionOriginY, int regionOriginZ) {
final CameraTransform t = this.camera;
final float maxDistance = this.maxDistance;
final int ax = regionOriginX - t.intX, bx = ax + REGION_BLOCK_WIDTH;
final int ay = regionOriginY - t.intY, by = ay + REGION_BLOCK_HEIGHT;
final int az = regionOriginZ - t.intZ, bz = az + REGION_BLOCK_LENGTH;
// Signed range of the per-axis "nearest point of a member section's box" value.
final float loX = nearestToZero(ax, ax + 16) - t.fracX;
final float hiX = nearestToZero(bx - 16, bx) - t.fracX;
final float loY = nearestToZero(ay, ay + 16) - t.fracY;
final float hiY = nearestToZero(by - 16, by) - t.fracY;
final float loZ = nearestToZero(az, az + 16) - t.fracZ;
final float hiZ = nearestToZero(bz - 16, bz) - t.fracZ;
// Upper bound on every member's |d|, inflated by epsilon.
final float farX = maxAbs(loX, hiX) + DISTANCE_EPSILON;
final float farY = maxAbs(loY, hiY) + DISTANCE_EPSILON;
final float farZ = maxAbs(loZ, hiZ) + DISTANCE_EPSILON;
// Lower bound on every member's |d|, deflated by epsilon.
final float nearX = Math.max(0.0f, minAbs(loX, hiX) - DISTANCE_EPSILON);
final float nearY = Math.max(0.0f, minAbs(loY, hiY) - DISTANCE_EPSILON);
final float nearZ = Math.max(0.0f, minAbs(loZ, hiZ) - DISTANCE_EPSILON);
final float maxDistanceSq = maxDistance * maxDistance;
boolean distanceOut = ((nearX * nearX) + (nearZ * nearZ)) >= maxDistanceSq || nearY >= maxDistance;
if (distanceOut) {
return Frustum.OUTSIDE;
}
boolean distanceIn = ((farX * farX) + (farZ * farZ)) < maxDistanceSq && farY < maxDistance;
int result = this.viewport.intersectCameraRelativeBox(
(ax - t.fracX) - FRUSTUM_PAD,
(ay - t.fracY) - FRUSTUM_PAD,
(az - t.fracZ) - FRUSTUM_PAD,
(bx - t.fracX) + FRUSTUM_PAD,
(by - t.fracY) + FRUSTUM_PAD,
(bz - t.fracZ) + FRUSTUM_PAD);
if (result == Frustum.FULLY_INSIDE) {
// Region must be fully within render distance to propagate that result
return distanceIn ? Frustum.FULLY_INSIDE : Frustum.PARTIALLY_INSIDE;
} else {
return result;
}
}
private static float maxAbs(float lo, float hi) {
return Math.max(Math.abs(lo), Math.abs(hi));
}
private static float minAbs(float lo, float hi) {
if (lo > 0.0f) {
return lo;
}
if (hi < 0.0f) {
return -hi;
}
return 0.0f;
}
}
@@ -24,13 +24,17 @@ public class RenderRegion {
public static final int REGION_HEIGHT = 4;
public static final int REGION_LENGTH = 8;
public static final int REGION_BLOCK_WIDTH = REGION_WIDTH * 16;
public static final int REGION_BLOCK_HEIGHT = REGION_HEIGHT * 16;
public static final int REGION_BLOCK_LENGTH = REGION_LENGTH * 16;
private static final int REGION_WIDTH_M = RenderRegion.REGION_WIDTH - 1;
private static final int REGION_HEIGHT_M = RenderRegion.REGION_HEIGHT - 1;
private static final int REGION_LENGTH_M = RenderRegion.REGION_LENGTH - 1;
protected static final int REGION_WIDTH_SH = Integer.bitCount(REGION_WIDTH_M);
protected static final int REGION_HEIGHT_SH = Integer.bitCount(REGION_HEIGHT_M);
protected static final int REGION_LENGTH_SH = Integer.bitCount(REGION_LENGTH_M);
public static final int REGION_WIDTH_SH = Integer.bitCount(REGION_WIDTH_M);
public static final int REGION_HEIGHT_SH = Integer.bitCount(REGION_HEIGHT_M);
public static final int REGION_LENGTH_SH = Integer.bitCount(REGION_LENGTH_M);
public static final int REGION_SIZE = REGION_WIDTH * REGION_HEIGHT * REGION_LENGTH;
@@ -58,7 +58,7 @@ public final class Viewport {
);
}
public int intersectCameraRelativeBox(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) {
public int intersectCameraRelativeBox(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
return this.frustum.intersectAab(minX, minY, minZ, maxX, maxY, maxZ);
}