Major occlusion search optimizations #34

Merged
embeddedt merged 11 commits from occlusion-opts into stonecutter 2026-08-18 19:59:03 -04:00
2 changed files with 145 additions and 71 deletions
Showing only changes of commit 066cda9d90 - Show all commits

No files matched your search

@@ -3,96 +3,131 @@ package org.embeddedt.embeddium.impl.render.chunk;
import org.jetbrains.annotations.Nullable;
/**
* The canonical packed encoding of everything the visibility graph search and its visitor need to know about a
* section, in a single {@code long}.
* Packs the per-section state consumed by visibility traversal and render-list
* collection into one {@code long}.
*
* <h2>Why</h2>
* The search walks tens of thousands of sections per frame. Every field it needs off a {@link RenderSection}
* (visibility encoding, "does this have anything to render", pending update type, "is a build already in
* flight") used to be a load off a randomly-placed object. Packed into one word they are a single load out of a
* flat array the traversal already has the index for - the lattice's {@code sectionMeta}, see
* {@code SectionLattice} - and the visitor can be handed plain ints.
* <p>{@link RenderSection} owns the authoritative word. The
* {@link org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionLattice}
* mirrors it in a flat array so the hot traversal can read all of a section's
* state with one indexed load instead of following several object references.
* The visitor receives the unpacked fields without needing the section object
* during the search.
*
* <h2>Layout</h2>
* <p>Bit layout:
* <pre>
* bits 0..45 : visibility encoding ({@link VisibilityEncoding}: bit {@code (from * 8) + to}, from/to in [0, 6))
* bits 46..48 : visuals flags ({@link RenderVisualsService#HAS_BLOCK_GEOMETRY} / {@code HAS_SPRITES} /
* {@code HAS_BLOCK_ENTITIES}), i.e. {@code RenderSection.getVisualsServiceFlags()}
* bits 49..51 : pending update type; 0 = none, otherwise {@code ChunkUpdateType.ordinal() + 1}
* bit 52 : a build cancellation token is currently attached (a build is in flight)
* bits 53..63 : spare
* 63 53 52 51 49 48 46 45 0
* +--------------------+--+-----------+----------+-------------------+
* | spare |IF| pending | visuals | visibility graph |
* +--------------------+--+-----------+----------+-------------------+
* </pre>
* The visibility encoding structurally cannot occupy anything above bit 45 ({@code 5 * 8 + 5}), so bits 46 and
* up are free. <b>They are not, however, harmless</b>: {@link VisibilityEncoding#getConnections(long)} folds the
* top 32 bits of the word down onto the bottom 6 (bit 46 lands on EAST), so every read that feeds a
* {@code getConnections} call <b>must</b> mask with {@link #VISIBILITY_MASK} first. See
* {@code OcclusionCuller.process} and {@code OcclusionCuller.initWithinWorld}.
* <ul>
* <li>Bits {@code 0..45}: {@link VisibilityEncoding} entries. Entry
* {@code (from * 8) + to} describes visibility from one of six faces to
* another. Each eight-bit row uses its six low bits; the two padding
* positions are not part of the visibility field (the final row's
* padding is reused by the visual flags).</li>
* <li>Bits {@code 46..48}: {@link RenderVisualsService} visual flags.</li>
* <li>Bits {@code 49..51}: pending update type; zero means none, otherwise
* {@code ChunkUpdateType.ordinal() + 1}.</li>
* <li>Bit {@code 52}: a build is in flight.</li>
* <li>Bits {@code 53..63}: reserved.</li>
* </ul>
*
* <h2>The small "meta bits" form</h2>
* Bits 46..52 - everything except the visibility encoding - are what the visitor actually consumes.
* <p>The visibility graph uses only bits {@code 0..45}, but
* {@link VisibilityEncoding#getConnections(long)} folds high bits down into
* its direction result. Therefore every value passed to that method must first
* be masked with {@link #VISIBILITY_MASK}.
*
* <p>Note: {@link RenderSection} is the source of truth - it keeps this whole word in sync (including the
* visibility encoding) via {@code updateCachedContextDataFlags()} and notifies {@code SectionLattice}, which
* mirrors it into the flat {@code sectionMeta} array the search reads.</p>
* <p>{@link #GRAPH_INPUT_MASK} identifies the fields that affect the graph
* search or the render-list contents. Pending-update and build-in-flight bits
* are consumed separately by the visitor and do not change graph traversal by
* themselves.
*/
public final class PackedSectionMetadata {
private PackedSectionMetadata() {
}
// Bits 0..45: visibility encoding, see VisibilityEncoding
// Bits 0..45: visibility graph encoding. The 46-bit width is 6 * 8 - 2,
// because six directions occupy six entries in each eight-bit row and the
// final row is only needed through its sixth entry.
private static final int VISIBILITY_BITS = 46;
public static final long VISIBILITY_MASK = (1L << VISIBILITY_BITS) - 1;
// Bits 46..48: visuals flags (RenderVisualsService.HAS_*)
// Bits 46..48: RenderVisualsService.HAS_* flags.
private static final int VISUALS_FLAGS_SHIFT = 46;
private static final long VISUALS_FLAGS_MASK = 0b111L;
// The bits whose change alters a graph search's output (which sections traverse, which end up in the render
// list): the visibility encoding plus the visuals flags. Changes confined outside this mask (pending update
// type, build-in-flight) do not by themselves require re-running the search - their callers mark the graph
// dirty separately.
/**
* Fields whose changes can alter the result of a visibility search or its
* render-list output: visibility graph data and visual-presence flags.
*/
public static final long GRAPH_INPUT_MASK = VISIBILITY_MASK | (VISUALS_FLAGS_MASK << VISUALS_FLAGS_SHIFT);
// Bits 49..51: pending update type; 0 = none, otherwise ChunkUpdateType.ordinal() + 1
// Bits 49..51: 0 means no pending update; otherwise ordinal + 1.
private static final int PENDING_UPDATE_SHIFT = 49;
private static final long PENDING_UPDATE_MASK = 0b111L;
// Bit 52: a build cancellation token is currently attached (a build is in flight)
// Bit 52: a build cancellation token is currently attached.
private static final int BUILD_IN_FLIGHT_BIT = 52;
private static final long BUILD_IN_FLIGHT_FLAG = 1L << BUILD_IN_FLIGHT_BIT;
/** Returns only the visibility graph field. */
public static long getVisibilityData(long packed) {
return packed & VISIBILITY_MASK;
}
/**
* Replaces the visibility graph field and preserves every other field.
* Bits outside {@link #VISIBILITY_MASK} in {@code visibilityData} are
* discarded.
*/
public static long withVisibilityData(long packed, long visibilityData) {
return (packed & ~VISIBILITY_MASK) | (visibilityData & VISIBILITY_MASK);
}
/** Returns the three visual-presence flags. */
public static int getVisualsFlags(long packed) {
return (int) ((packed >>> VISUALS_FLAGS_SHIFT) & VISUALS_FLAGS_MASK);
}
/**
* Replaces the visual-presence flags and preserves every other field.
* Only the three low bits of {@code flags} are stored.
*/
public static long withVisualsFlags(long packed, int flags) {
return (packed & ~(VISUALS_FLAGS_MASK << VISUALS_FLAGS_SHIFT))
| (((long) flags & VISUALS_FLAGS_MASK) << VISUALS_FLAGS_SHIFT);
}
/**
* Decodes the pending update field.
*
* @return the pending update type, or {@code null} when the field is zero
*/
public static @Nullable ChunkUpdateType getPendingUpdate(long packed) {
int encoded = (int) ((packed >>> PENDING_UPDATE_SHIFT) & PENDING_UPDATE_MASK);
return encoded == 0 ? null : ChunkUpdateType.VALUES[encoded - 1];
}
/**
* Replaces the pending update field and preserves every other field.
* {@code null} clears the field; non-null values use ordinal plus one so
* zero remains the no-update sentinel.
*/
public static long withPendingUpdate(long packed, @Nullable ChunkUpdateType type) {
long encoded = type == null ? 0L : (type.ordinal() + 1L);
return (packed & ~(PENDING_UPDATE_MASK << PENDING_UPDATE_SHIFT))
| (encoded << PENDING_UPDATE_SHIFT);
}
/** Returns whether a section build is currently in flight. */
public static boolean isBuildInFlight(long packed) {
return (packed & BUILD_IN_FLIGHT_FLAG) != 0;
}
/**
* Replaces the build-in-flight flag and preserves every other field.
*/
public static long withBuildInFlight(long packed, boolean inFlight) {
return inFlight ? (packed | BUILD_IN_FLIGHT_FLAG) : (packed & ~BUILD_IN_FLIGHT_FLAG);
}
@@ -10,75 +10,106 @@ 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:
* Per-search memoization for region-level visibility classification.
*
* <p>Sections are grouped into dense 8x4x8-section regions
* ({@code 128x64x128} blocks). The cache computes a conservative result for
* each region once per search, then lets {@link OcclusionCuller} avoid the
* exact distance and frustum tests whenever the region result is conclusive.
* Region ids are dense and serve directly as cache indices.
*
* <p>The classification contract is:
* <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>
* <li>{@link Frustum#OUTSIDE}: every section is guaranteed to fail the
* combined render-distance/frustum visibility test;</li>
* <li>{@link Frustum#FULLY_INSIDE}: every section is guaranteed to pass both
* tests; and</li>
* <li>{@link Frustum#PARTIALLY_INSIDE}: the region bounds are inconclusive,
* so the caller must test each section exactly.</li>
* </ul>
* The bounds include padding and floating-point slack, so a conclusive result
* must never incorrectly reject or accept a section.
*
* <p>The cache is mutable and intended for one search at a time. Call
* {@link #begin(Viewport, float, int)} before {@link #classify}; it resets the
* classification array so no result leaks between searches.
*/
final class RegionCullCache {
/** 1.125 (= 9.125 - 8) plus 1/32 of slack to swallow float rounding in the camera-relative transform. */
// Sentinel stored in unclassified slots; distinct from every Frustum result.
private static final byte UNCOMPUTED = -1;
// Per-section frustum padding is 9.125 - 8 = 1.125 blocks. Add a
// further 1/32 block to absorb camera-relative floating-point rounding.
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. */
// Slack for distance bounds; errors at render-distance magnitudes are
// approximately 1e-4, so this keeps conservative comparisons stable.
private static final float DISTANCE_EPSILON = 0.001f;
private static final int INITIAL_CAPACITY = 64;
// Indexed by dense region id; UNCOMPUTED until classified in the current search.
private byte[] classification = new byte[INITIAL_CAPACITY];
private int[] stamp = new int[INITIAL_CAPACITY];
private int currentStamp;
// Per-frame state, refreshed by begin().
// Search configuration, refreshed by begin().
private Viewport viewport;
private CameraTransform camera;
private float maxDistance;
RegionCullCache() {
Arrays.fill(this.stamp, -1);
}
/**
* Start a search and configure the camera-relative bounds used by
* subsequent classifications.
*
* @param viewport current camera and frustum
* @param searchDistance maximum horizontal/vertical render distance
* @param numRegions exclusive upper bound of the dense region ids that
* may be passed to {@link #classify}
*/
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) {
if (numRegions > this.classification.length) {
this.grow(numRegions);
}
Arrays.fill(this.classification, 0, numRegions, UNCOMPUTED);
}
/**
* @param regionId dense region id; used only as a memoization slot
* @param regionOriginX block coordinate of the region's minimum corner
* Return the cached classification for a region, computing it on first
* use in the current search.
*
* @param regionId dense region id and cache slot
* @param regionOriginX block X coordinate of the region's minimum corner
* @param regionOriginY block Y coordinate of the region's minimum corner
* @param regionOriginZ block Z coordinate of the region's minimum corner
* @return one of the {@link Frustum} classification constants
* @implNote The origin must correspond to {@code regionId}; only the first
* classification for an id is computed in a search.
*/
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);
byte result = this.classification[regionId];
if (result == UNCOMPUTED) {
result = (byte) this.compute(regionOriginX, regionOriginY, regionOriginZ);
this.classification[regionId] = result;
}
return this.classification[regionId];
return result;
}
// Grow the classification array; contents are reset by the next begin().
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);
int capacity = Math.max(minimumCapacity, this.classification.length * 2);
this.classification = new byte[capacity];
}
/**
* Compute conservative region bounds. Distance is rejected first when the
* nearest possible section point is too far away; otherwise the padded
* region box is classified against the camera frustum.
*/
private int compute(int regionOriginX, int regionOriginY, int regionOriginZ) {
final CameraTransform t = this.camera;
final float maxDistance = this.maxDistance;
@@ -87,7 +118,8 @@ final class RegionCullCache {
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.
// Signed range of the nearest-point distance component for all member
// section boxes along each axis.
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;
@@ -95,24 +127,28 @@ final class RegionCullCache {
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.
// Upper bound on every member's absolute distance component.
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.
// Lower bound on every member's absolute distance component.
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;
// If even the nearest possible point fails the distance test, every
// section is out of range and the frustum need not be queried.
boolean distanceOut = ((nearX * nearX) + (nearZ * nearZ)) >= maxDistanceSq || nearY >= maxDistance;
if (distanceOut) {
return Frustum.OUTSIDE;
}
// Only claim FULLY_INSIDE when the farthest possible point is still
// strictly inside the distance bounds.
boolean distanceIn = ((farX * farX) + (farZ * farZ)) < maxDistanceSq && farY < maxDistance;
int result = this.viewport.intersectCameraRelativeBox(
@@ -124,17 +160,20 @@ final class RegionCullCache {
(bz - t.fracZ) + FRUSTUM_PAD);
if (result == Frustum.FULLY_INSIDE) {
// Region must be fully within render distance to propagate that result
// A fully-inside frustum result is conclusive only when distance
// is also conclusive for every member section.
return distanceIn ? Frustum.FULLY_INSIDE : Frustum.PARTIALLY_INSIDE;
} else {
return result;
}
}
// Largest absolute value in a signed interval.
private static float maxAbs(float lo, float hi) {
return Math.max(Math.abs(lo), Math.abs(hi));
}
// Smallest absolute value in a signed interval.
private static float minAbs(float lo, float hi) {
if (lo > 0.0f) {
return lo;