From 94d5587030750e8bd8c0d3509467dfdac2e814bc Mon Sep 17 00:00:00 2001 From: embeddedt <42941056+embeddedt@users.noreply.github.com> Date: Sun, 16 Aug 2026 19:14:52 -0400 Subject: [PATCH 01/11] Create packed metadata for sections --- .../render/chunk/PackedSectionMetadata.java | 94 +++++++++++++++++++ .../impl/render/chunk/RenderSection.java | 40 +++++--- 2 files changed, 120 insertions(+), 14 deletions(-) create mode 100644 common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java new file mode 100644 index 000000000..a76520fa7 --- /dev/null +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java @@ -0,0 +1,94 @@ +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}. + * + *
+ * 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
+ *
+ * The visibility encoding structurally cannot occupy anything above bit 45 ({@code 5 * 8 + 5}), so bits 46 and
+ * up are free. They are not, however, harmless: {@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 must mask with {@link #VISIBILITY_MASK} first. See
+ * {@code OcclusionCuller.process} and {@code OcclusionCuller.initWithinWorld}.
+ *
+ * Note: {@link RenderSection} keeps this whole word in sync (including the visibility encoding) via + * {@code updateCachedContextDataFlags()}, but nothing reads it back out for traversal yet - {@code OcclusionNode} + * still keeps its own separate copy of the visibility encoding that the search actually consumes, until the + * traversal is migrated onto the flat lattice described above.
+ */ +public final class PackedSectionMetadata { + private PackedSectionMetadata() { + } + + // Bits 0..45: visibility encoding, see VisibilityEncoding + private static final int VISIBILITY_BITS = 46; + public static final long VISIBILITY_MASK = (1L << VISIBILITY_BITS) - 1; + + // Bits 46..48: visuals flags (RenderVisualsService.HAS_*) + private static final int VISUALS_FLAGS_SHIFT = 46; + private static final long VISUALS_FLAGS_MASK = 0b111L; + + // Bits 49..51: pending update type; 0 = none, otherwise ChunkUpdateType.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) + private static final int BUILD_IN_FLIGHT_BIT = 52; + private static final long BUILD_IN_FLIGHT_FLAG = 1L << BUILD_IN_FLIGHT_BIT; + + public static long getVisibilityData(long packed) { + return packed & VISIBILITY_MASK; + } + + public static long withVisibilityData(long packed, long visibilityData) { + return (packed & ~VISIBILITY_MASK) | (visibilityData & VISIBILITY_MASK); + } + + public static int getVisualsFlags(long packed) { + return (int) ((packed >>> VISUALS_FLAGS_SHIFT) & VISUALS_FLAGS_MASK); + } + + public static long withVisualsFlags(long packed, int flags) { + return (packed & ~(VISUALS_FLAGS_MASK << VISUALS_FLAGS_SHIFT)) + | (((long) flags & VISUALS_FLAGS_MASK) << VISUALS_FLAGS_SHIFT); + } + + 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]; + } + + 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); + } + + public static boolean isBuildInFlight(long packed) { + return (packed & BUILD_IN_FLIGHT_FLAG) != 0; + } + + public static long withBuildInFlight(long packed, boolean inFlight) { + return inFlight ? (packed | BUILD_IN_FLIGHT_FLAG) : (packed & ~BUILD_IN_FLIGHT_FLAG); + } +} diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSection.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSection.java index 0fd92acdf..e10147b76 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSection.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSection.java @@ -35,9 +35,12 @@ public class RenderSection extends AbstractSection { // Rendering State private BuiltRenderSectionData contextData; - private boolean hasAnythingToRender; - @Getter - private int visualsServiceFlags; + + // Packed encoding of the visibility encoding, visuals flags, pending update type, and build-in-flight bit; + // see PackedSectionMetadata for the bit layout. Kept in sync with contextData in updateCachedContextDataFlags(). + // Note: OcclusionNode still keeps its own separate copy of the visibility encoding for the graph traversal - + // this field isn't consumed by the traversal yet, it's just populated ahead of that migration. + private long packedMetadata; /** * A mapping from translucent render passes to the sort state for that particular pass (which contains data needed @@ -64,9 +67,6 @@ public class RenderSection extends AbstractSection { @Nullable private CancellationToken buildCancellationToken = null; - @Nullable - private ChunkUpdateType pendingUpdateType; - private int lastBuiltFrame = -1; private int lastSubmittedFrame = -1; @@ -97,7 +97,7 @@ public class RenderSection extends AbstractSection { public void delete() { if (this.buildCancellationToken != null) { this.buildCancellationToken.setCancelled(); - this.buildCancellationToken = null; + this.setBuildCancellationToken(null); } this.setInfo(null); @@ -133,12 +133,23 @@ public class RenderSection extends AbstractSection { } public void updateCachedContextDataFlags() { - this.visualsServiceFlags = this.contextData != null ? this.contextData.getVisualBitmaskForSection() : 0; - this.hasAnythingToRender = this.visualsServiceFlags != 0; + int flags = this.contextData != null ? this.contextData.getVisualBitmaskForSection() : 0; + long visibilityData = this.contextData != null ? this.contextData.visibilityData : VisibilityEncoding.NULL; + + this.packedMetadata = PackedSectionMetadata.withVisibilityData( + PackedSectionMetadata.withVisualsFlags(this.packedMetadata, flags), visibilityData); + } + + public int getVisualsServiceFlags() { + return PackedSectionMetadata.getVisualsFlags(this.packedMetadata); + } + + public long getVisibilityData() { + return PackedSectionMetadata.getVisibilityData(this.packedMetadata); } public boolean hasAnythingToRender() { - return this.hasAnythingToRender; + return this.getVisualsServiceFlags() != 0; } public void setTranslucencySortStates(@NotNull Map
+ * 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;
+ }
}
diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/RenderListManager.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/RenderListManager.java
index cce67550e..f31435418 100644
--- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/RenderListManager.java
+++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/RenderListManager.java
@@ -106,7 +106,7 @@ public class RenderListManager {
var visitor = new VisibleChunkCollector(frame, regionIdsLength, targetQueueSize);
Supplier
+ * Sections are grouped into 8x4x8-section regions (128x64x128 blocks) with dense ids. Once per frame a region
+ * is classified as:
+ * Note: {@link RenderSection} keeps this whole word in sync (including the visibility encoding) via
- * {@code updateCachedContextDataFlags()}, but nothing reads it back out for traversal yet - {@code OcclusionNode}
- * still keeps its own separate copy of the visibility encoding that the search actually consumes, until the
- * traversal is migrated onto the flat lattice described above. 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. A search has four phases:
+ * Occlusion traversal accumulates the directions through which each cell
+ * was reached, then asks {@link VisibilityEncoding} which outgoing directions
+ * are possible. Expansion is additionally restricted to directions pointing
+ * away from the camera, preventing paths from backtracking through the search
+ * origin. If the camera is in an unloaded section, the search remains useful
+ * as a frustum/render-distance scan but disables graph occlusion for that
+ * search.
+ *
+ * The queue and visitation buffers are reused between searches. A single
+ * invocation must run at a time, and the lattice's dimensions, coordinates,
+ * installed membership, and metadata must remain stable until the invocation
+ * completes. The owning {@code RenderListManager} provides that coordination.
+ */
public class OcclusionCuller {
- private final Long2ReferenceMap Reached sections are reported even when {@code visible} is false;
+ * the flag controls whether the section contributes renderable work and
+ * whether traversal expands through it. The caller must have prepared the
+ * lattice with {@link SectionLattice#ensureWindowCovers} and must not
+ * mutate its structure or metadata until this method returns.
+ *
+ * @param useOcclusionCulling whether section visibility metadata should
+ * restrict graph expansion
+ */
public void findVisible(Visitor visitor,
Viewport viewport,
float searchDistance,
@@ -47,46 +135,104 @@ public class OcclusionCuller {
boolean useOcclusionCulling,
int frame)
{
- final var queues = this.queue;
- queues.reset();
+ // Pre-size so enqueue/record are bare stores: at most one entry per installed cell.
+ int installed = this.lattice.installedCount;
+ if (this.queue.length < installed) {
+ this.queue = new long[Math.max(installed, this.queue.length * 2)];
+ }
+ if (this.visitBuffer.length < installed) {
+ this.visitBuffer = new int[Math.max(installed, this.visitBuffer.length * 2)];
+ }
+ this.tail = 0;
+ this.vtail = 0;
- final var cache = this.regionCullCache;
-
- cache.begin(viewport, searchDistance, numRegions);
+ this.regionCullCache.begin(viewport, searchDistance, numRegions);
this.isCameraInUnloadedSection = false;
- this.init(visitor, queues.write(), viewport, searchDistance, useOcclusionCulling, frame);
- if(this.isCameraInUnloadedSection) {
+ this.init(viewport, searchDistance, useOcclusionCulling, frame);
+ if (this.isCameraInUnloadedSection) {
useOcclusionCulling = false;
}
- while (queues.flip()) {
- processQueue(visitor, viewport, searchDistance, useOcclusionCulling, frame, queues.read(), queues.write(), cache);
+ this.process(viewport, searchDistance, useOcclusionCulling, frame);
+
+ this.replay(visitor);
+ }
+
+ // Replay records in the same order in which cells were processed. The
+ // visitor runs after the search so the hot loop need not resolve section
+ // objects. It must not feed changes back into this already-completed search.
+ private void replay(Visitor visitor) {
+ final int[] visitBuffer = this.visitBuffer;
+ final int[] regionOfCell = this.lattice.regionOfCell;
+ final long[] sectionMeta = this.lattice.sectionMeta;
+
+ int count = this.vtail;
+
+ for (int i = 0; i < count; i++) {
+ int entry = visitBuffer[i];
+ int idx = visitIndex(entry);
+
+ visitor.visit(idx, regionOfCell[idx], visitSection(entry), sectionMeta[idx], visitVisible(entry));
}
}
- private static void processQueue(Visitor visitor,
- Viewport viewport,
- float searchDistance,
- boolean useOcclusionCulling,
- int frame,
- ReadQueue The lattice is a dense, flat window around the camera. It gives the
+ * traversal constant-time access to a section and to its six neighbours,
+ * while avoiding an object allocation for every cell on the hot path.
+ *
+ * This class has two layers of state:
+ * The arrays are parallel: for a given lattice index,
+ * {@code latticeSection}, {@code sectionMeta}, and {@code regionOfCell}
+ * describe the same cell. X and Z are camera-windowed, while Y covers the
+ * entire world height. The window is allocated lazily by
+ * {@link #ensureWindowCovers}. The first call allocates the arrays and then
+ * establishes their base coordinates; later calls rebase when the camera
+ * approaches an edge or the window grows. Each rebase re-installs every
+ * attached section that falls in the new window.
+ *
+ * The installable interior ({@code [1, dim-2]} on each axis) is wrapped by
+ * a permanent one-cell ring of sentinel cells (index {@code 0} and
+ * {@code dim-1}). Every installable cell therefore has a valid array index one
+ * step away in all six directions, so traversal can add a value from
+ * {@link #delta} without a bounds check: the neighbour is always in-array,
+ * whether it holds another cell or a sentinel. The border ring is never
+ * installable, even when the window holds no sections.
+ *
+ * The normal lifecycle is construction with no lattice allocation, followed
+ * by {@link #ensureWindowCovers}, which allocates and establishes the window,
+ * then attachment/detachment and metadata updates between searches, and finally
+ * {@link #findVisible}. Structural state is single-threaded: attachment,
+ * detachment, metadata updates, allocation, and rebasing must not overlap the
+ * search. The search may run asynchronously and writes per-frame visit state
+ * itself, but its array lengths, window coordinates, and installed membership
+ * must remain stable for its duration. {@code RenderListManager} enforces this
+ * boundary.
+ */
+public final class SectionLattice {
+ private static final int SLACK = 4;
+
+ /*
+ * visitState representation:
+ *
+ * 63 40 39 8 7 0
+ * +----------------------+---------------------+---------+
+ * | unused | frame stamp | dir bits |
+ * +----------------------+---------------------+---------+
+ *
+ * The frame stamp is the unsigned 32-bit search frame in bits 8..39;
+ * the low byte accumulates incoming GraphDirectionSet bits. SENTINEL is
+ * larger than every valid stamped value, so empty cells fail the ordered
+ * visit gate. INITIAL is smaller than every frame stamp, so an installed
+ * but unvisited cell is eligible for the current search.
+ */
+ static final int FRAME_SHIFT = 8;
+ static final int DIR_MASK = 0xFF;
+
+ // Empty slot, including the permanent border ring.
+ static final long SENTINEL = Long.MAX_VALUE;
+ // Installed slot that has not yet been visited by a search.
+ static final long INITIAL = -1L;
+
+ /*
+ * Packed local coordinate: (lx << 20) | (ly << 10) | lz. Each local axis
+ * therefore needs fewer than 1024 positions. MAX_DIM must stay within
+ * that 10-bit limit, independently of MAX_LATTICE_SLOTS, which limits
+ * the total number of cells (and therefore the allocation size).
+ * packXyz produces this representation; XYZ_LOCAL_MASK extracts an axis;
+ * XYZ_STEP is the corresponding per-direction increment.
+ */
+ static final int XYZ_SHIFT = 10;
+ static final int XYZ_LOCAL_MASK = (1 << XYZ_SHIFT) - 1;
+ static final int[] XYZ_STEP = new int[GraphDirection.COUNT];
+
+ static {
+ for (int dir = 0; dir < GraphDirection.COUNT; dir++) {
+ XYZ_STEP[dir] = GraphDirection.x(dir) * (1 << (2 * XYZ_SHIFT))
+ + GraphDirection.y(dir) * (1 << XYZ_SHIFT)
+ + GraphDirection.z(dir);
+ }
+ }
+
+ private static final int MAX_DIM = 1 << XYZ_SHIFT;
+ private static final int MAX_LATTICE_SLOTS = 1 << 22;
+
+ private final Long2ReferenceMap Used by deferred visitor replay to resolve the section lazily; the
+ * caller must provide an index belonging to an installed cell.
+ */
+ public RenderSection sectionAt(int latticeIndex) {
+ return this.latticeSection[latticeIndex];
+ }
+
+ /**
+ * Encodes a frame for the ordered visit gate. The low byte is reserved for
+ * incoming direction bits, so the 32-bit frame occupies bits 8..39.
+ */
+ static long frameStamp(int frame) {
+ return (frame & 0xFFFFFFFFL) << FRAME_SHIFT;
+ }
+
+ /**
+ * Tests whether an installed section was marked visible in or after the
+ * requested frame. Sections without an installed slot are never visible.
+ */
+ public boolean isSectionVisible(int x, int y, int z, int minVisibleFrame) {
+ int idx = this.installedIndex(x, y, z);
+
+ // The frame in which the slot was last marked visible by the search. Narrowing (int) after the logical
+ // shift recovers the 32-bit frame; an uninstalled section (idx < 0) is treated as never-visible.
+ return idx >= 0 && (int) (this.visitState[idx] >>> FRAME_SHIFT) >= minVisibleFrame;
+ }
+
+ /**
+ * Returns the actual installed slot at a world position.
+ *
+ * This is intentionally stricter than {@link #indexOf}: {@code indexOf}
+ * computes a possible interior slot, whereas this method also verifies
+ * that a section is attached and installed there.
+ */
+ private int installedIndex(int x, int y, int z) {
+ if (this.visitState == null) {
+ return -1;
+ }
+
+ int idx = this.indexOf(x, y, z);
+ return idx >= 0 && this.latticeSection[idx] != null ? idx : -1;
+ }
+
+ /**
+ * Ensure the lattice window covers the search radius around the camera.
+ *
+ * The traversal can reach {@code radius} sections from the camera and
+ * then inspect one more neighbour, so every section in that reach must be
+ * in the installable interior rather than merely in the backing array.
+ * The extra cell is what makes the border safe for unchecked neighbour
+ * access. {@link #SLACK} leaves room for camera movement before another
+ * rebase is needed.
+ *
+ * The window is allocated lazily and grows when necessary. If the
+ * camera or dimensions make the current window invalid, all attached
+ * sections are reinstalled against the new base coordinates.
+ *
+ * Call this on the render thread before dispatching a search. The
+ * asynchronous search must not observe allocation, rebasing, attachment,
+ * detachment, or metadata updates while it is running.
+ */
+ public void ensureWindowCovers(Vector3ic cameraSectionPos, float searchDistance) {
+ int radius = MathUtil.mojfloor(searchDistance / 16.0f);
+ int neededDimXZ = 2 * (radius + SLACK) + 3;
+
+ if (this.visitState == null || neededDimXZ > this.dimX) {
+ this.allocate(neededDimXZ);
+ }
+
+ int lx = cameraSectionPos.x() - this.baseX;
+ int lz = cameraSectionPos.z() - this.baseZ;
+
+ // Include the neighbour of the outermost section the traversal can visit.
+ int reach = radius + 1;
+
+ boolean valid = this.established
+ && lx - reach >= 1 && lx + reach <= this.dimX - 2
+ && lz - reach >= 1 && lz + reach <= this.dimZ - 2;
+
+ if (!valid) {
+ this.rebase(cameraSectionPos.x() - this.dimX / 2, cameraSectionPos.z() - this.dimZ / 2);
+ this.established = true;
+ }
+ }
+
+ /**
+ * Run the visibility search over the currently installed lattice cells.
+ * The caller must have completed {@link #ensureWindowCovers} and must keep
+ * lattice structure and metadata stable until this method returns.
+ */
+ public void findVisible(OcclusionCuller.Visitor visitor,
+ Viewport viewport,
+ float searchDistance,
+ int numRegions,
+ boolean useOcclusionCulling,
+ int frame) {
+ this.culler.findVisible(visitor, viewport, searchDistance, numRegions, useOcclusionCulling, frame);
+ }
+
+ private void allocate(int newDimXZ) {
+ long slotsLong = (long) newDimXZ * newDimXZ * this.dimY;
+
+ if (newDimXZ > MAX_DIM || slotsLong >= MAX_LATTICE_SLOTS) {
+ throw new IllegalStateException("Occlusion lattice window too large (dimXZ=" + newDimXZ
+ + ", slots=" + slotsLong + "); this render distance is not supported");
+ }
+
+ this.dimX = newDimXZ;
+ this.dimZ = newDimXZ;
+ this.strideZ = this.dimY;
+ this.strideX = this.dimY * this.dimZ;
+
+ for (int dir = 0; dir < GraphDirection.COUNT; dir++) {
+ this.delta[dir] = GraphDirection.x(dir) * this.strideX
+ + GraphDirection.z(dir) * this.strideZ
+ + GraphDirection.y(dir);
+ }
+
+ int slots = (int) slotsLong;
+ this.visitState = new long[slots];
+ this.sectionMeta = new long[slots];
+ this.regionOfCell = new int[slots];
+ this.latticeSection = new RenderSection[slots];
+
+ // Existing coordinates are no longer valid after resizing; the next
+ // ensureWindowCovers must rebase and reinstall every attached section.
+ this.established = false;
+ }
+
+ /**
+ * Clear the old window, move its X/Z origin, and reinstall every attached
+ * section that falls in the new interior. Sections outside the interior
+ * remain authoritative in {@link #sections} but are not traversable.
+ */
+ private void rebase(int newBaseX, int newBaseZ) {
+ Arrays.fill(this.visitState, SENTINEL);
+ Arrays.fill(this.sectionMeta, VisibilityEncoding.NULL);
+ Arrays.fill(this.regionOfCell, -1);
+ Arrays.fill(this.latticeSection, null);
+
+ this.baseX = newBaseX;
+ this.baseZ = newBaseZ;
+ this.installedCount = 0;
+
+ for (RenderSection section : this.sections.values()) {
+ this.install(section);
+ }
+ }
+
+ /**
+ * Computes the potential lattice slot for a world position.
+ *
+ * @return the slot if the position is in the installable interior, or
+ * {@code -1} if it is outside the window, in the sentinel border,
+ * or outside the supported world-height range. This method does
+ * not test whether a section is actually installed at the slot.
+ */
+ int indexOf(int x, int y, int z) {
+ int lx = x - this.baseX;
+ int ly = y - this.baseY;
+ int lz = z - this.baseZ;
+
+ if (lx < 1 || lx > this.dimX - 2
+ || ly < 1 || ly > this.dimY - 2
+ || lz < 1 || lz > this.dimZ - 2) {
+ return -1;
+ }
+
+ return (lx * this.dimZ + lz) * this.dimY + ly;
+ }
+
+ /**
+ * Packs a world position's local coordinates into 10 bits per axis for
+ * the traversal queue. The caller must pass a position in this lattice's
+ * addressable window; {@code MAX_DIM} guarantees that each coordinate fits
+ * in its 10-bit field, while {@code MAX_LATTICE_SLOTS} limits the total
+ * backing-array size.
+ */
+ int packXyz(int x, int y, int z) {
+ return ((x - this.baseX) << (2 * XYZ_SHIFT)) | ((y - this.baseY) << XYZ_SHIFT) | (z - this.baseZ);
+ }
+
+ // Install only into the interior. An attached section outside the current
+ // window remains in sections and is picked up by a later rebase.
+ private void install(RenderSection section) {
+ if (this.visitState == null) {
+ return;
+ }
+
+ int idx = this.indexOf(section.getChunkX(), section.getChunkY(), section.getChunkZ());
+
+ if (idx < 0) {
+ return;
+ }
+
+ this.visitState[idx] = INITIAL;
+ this.latticeSection[idx] = section;
+ this.regionOfCell[idx] = section.getRegion().getId();
+ this.sectionMeta[idx] = section.getPackedMetadata();
+ this.installedCount++;
+ }
+
+ // Remove the section's complete parallel-array entry. Write SENTINEL
+ // first so traversal can never treat the remaining fields as live.
+ private void uninstall(RenderSection section) {
+ int idx = this.installedIndex(section.getChunkX(), section.getChunkY(), section.getChunkZ());
+
+ if (idx < 0) {
+ return;
+ }
+
+ this.visitState[idx] = SENTINEL;
+ this.sectionMeta[idx] = VisibilityEncoding.NULL;
+ this.regionOfCell[idx] = -1;
+ this.latticeSection[idx] = null;
+ this.installedCount--;
+ }
+}
--
2.54.1
From 066cda9d90253e47b3071abcf99b0e9fd5c6577d Mon Sep 17 00:00:00 2001
From: embeddedt <42941056+embeddedt@users.noreply.github.com>
Date: Mon, 17 Aug 2026 19:49:06 -0400
Subject: [PATCH 05/11] Improve docs and simplify region cull cache
---
.../render/chunk/PackedSectionMetadata.java | 101 ++++++++++-----
.../chunk/occlusion/RegionCullCache.java | 115 ++++++++++++------
2 files changed, 145 insertions(+), 71 deletions(-)
diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java
index e4f381a6d..574886d45 100644
--- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java
+++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java
@@ -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}.
*
- * {@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.
*
- * Bit layout:
* 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}.
*
- * 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. {@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);
}
diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RegionCullCache.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RegionCullCache.java
index 158d55ddb..ff53b4855 100644
--- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RegionCullCache.java
+++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RegionCullCache.java
@@ -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}.
- *
- * 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.
+ *
+ * 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.
+ *
+ * The classification contract is:
* 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;
--
2.54.1
From a0d478d012fa3c4197d5c192c1f6ca936d9db302 Mon Sep 17 00:00:00 2001
From: embeddedt <42941056+embeddedt@users.noreply.github.com>
Date: Mon, 17 Aug 2026 22:57:57 -0400
Subject: [PATCH 06/11] Optimize rebasing the lattice
---
.../chunk/occlusion/SectionLattice.java | 225 +++++++++++++++++-
1 file changed, 215 insertions(+), 10 deletions(-)
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 6baf00826..b9900e075 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
@@ -37,9 +37,11 @@ import java.util.Arrays;
* describe the same cell. X and Z are camera-windowed, while Y covers the
* entire world height. The window is allocated lazily by
* {@link #ensureWindowCovers}. The first call allocates the arrays and then
- * establishes their base coordinates; later calls rebase when the camera
- * approaches an edge or the window grows. Each rebase re-installs every
- * attached section that falls in the new window.
+ * establishes their base coordinates. If a later camera position no longer
+ * fits, a same-sized window is normally slid in place: the overlapping cells
+ * are copied, and only the newly exposed X/Z band is looked up in
+ * {@code sections}. A resize or a move with no overlap falls back to a full
+ * {@link #rebase}.
*
* The installable interior ({@code [1, dim-2]} on each axis) is wrapped by
* a permanent one-cell ring of sentinel cells (index {@code 0} and
@@ -281,9 +283,12 @@ public final class SectionLattice {
* access. {@link #SLACK} leaves room for camera movement before another
* rebase is needed.
*
- * The window is allocated lazily and grows when necessary. If the
- * camera or dimensions make the current window invalid, all attached
- * sections are reinstalled against the new base coordinates.
+ * The window is allocated lazily and grows when necessary. A first
+ * allocation or resize invalidates the old coordinates and requires a full
+ * rebuild. Otherwise, when the camera makes the current window invalid,
+ * the existing window is typically slid to the centered base: overlapping cells are
+ * retained and only the newly exposed band is resolved through the
+ * authoritative section map.
*
* Call this on the render thread before dispatching a search. The
* asynchronous search must not observe allocation, rebasing, attachment,
@@ -308,7 +313,18 @@ public final class SectionLattice {
&& lz - reach >= 1 && lz + reach <= this.dimZ - 2;
if (!valid) {
- this.rebase(cameraSectionPos.x() - this.dimX / 2, cameraSectionPos.z() - this.dimZ / 2);
+ int newBaseX = cameraSectionPos.x() - this.dimX / 2;
+ int newBaseZ = cameraSectionPos.z() - this.dimZ / 2;
+
+ if (this.established) {
+ // The current window is valid to slide from: reuse its retained
+ // contents and only resolve the newly exposed cells.
+ this.shiftRebase(newBaseX, newBaseZ);
+ } else {
+ // Fresh or resized arrays have no reusable contents.
+ this.rebase(newBaseX, newBaseZ);
+ }
+
this.established = true;
}
}
@@ -358,9 +374,8 @@ public final class SectionLattice {
}
/**
- * Clear the old window, move its X/Z origin, and reinstall every attached
- * section that falls in the new interior. Sections outside the interior
- * remain authoritative in {@link #sections} but are not traversable.
+ * Rebuilds the lattice from scratch after allocation, resizing, or a
+ * non-overlapping camera jump.
*/
private void rebase(int newBaseX, int newBaseZ) {
Arrays.fill(this.visitState, SENTINEL);
@@ -377,6 +392,196 @@ public final class SectionLattice {
}
}
+ /**
+ * Slide the existing window to a new X/Z origin without rebuilding it.
+ *
+ * {@code dX} and {@code dZ} are the changes in world-space base
+ * coordinates.
+ *
+ * Before overwriting the old array cells, {@link #dropLeaving} removes
+ * the installed-count contribution of cells outside that intersection.
+ * After the move, {@link #fillNewBand} clears the cells that entered the
+ * window and installs only sections found in the authoritative map. Thus
+ * the map is consulted only for the exposed band, rather than once for
+ * every attached section as in {@link #rebase}.
+ *
+ * When the old and new interiors do not intersect, there is no useful
+ * data to preserve and this method delegates to {@link #rebase}.
+ */
+ private void shiftRebase(int newBaseX, int newBaseZ) {
+ int dX = newBaseX - this.baseX;
+ int dZ = newBaseZ - this.baseZ;
+
+ int interiorXHi = this.dimX - 2;
+ int interiorZHi = this.dimZ - 2;
+
+ int xLo = Math.max(1, 1 - dX);
+ int xHi = Math.min(interiorXHi, interiorXHi - dX);
+ int zLo = Math.max(1, 1 - dZ);
+ int zHi = Math.min(interiorZHi, interiorZHi - dZ);
+
+ if (xLo > xHi || zLo > zHi) {
+ // No overlap: sliding would move nothing, so reinstall wholesale.
+ this.rebase(newBaseX, newBaseZ);
+ return;
+ }
+
+ this.dropLeaving(xLo + dX, xHi + dX, zLo + dZ, zHi + dZ);
+
+ if (dZ == 0) {
+ this.shiftContentsXOnly(dX, xLo, xHi);
+ } else {
+ this.shiftContents(dX, dZ, xLo, xHi, zLo, zHi);
+ }
+
+ // The arrays now describe cells relative to the new origin.
+ this.baseX = newBaseX;
+ this.baseZ = newBaseZ;
+
+ this.fillNewBand(xLo, xHi, zLo, zHi);
+ }
+
+ /**
+ * Move retained contents for a pure X shift.
+ *
+ * Whole X planes (including their permanent sentinel rows) translate
+ * uniformly by {@code dX}, so the retained planes form one contiguous
+ * range. A single {@link System#arraycopy} per parallel array performs the
+ * overlapping move safely.
+ */
+ private void shiftContentsXOnly(int dX, int xLo, int xHi) {
+ int destOff = xLo * this.strideX;
+ int srcOff = (xLo + dX) * this.strideX;
+ int len = (xHi - xLo + 1) * this.strideX;
+
+ System.arraycopy(this.visitState, srcOff, this.visitState, destOff, len);
+ System.arraycopy(this.sectionMeta, srcOff, this.sectionMeta, destOff, len);
+ System.arraycopy(this.regionOfCell, srcOff, this.regionOfCell, destOff, len);
+ System.arraycopy(this.latticeSection, srcOff, this.latticeSection, destOff, len);
+ }
+
+ /**
+ * Move retained contents for a shift that includes Z.
+ *
+ * A Z shift cannot cross an X-plane boundary, so it moves one
+ * contiguous {@code Z/Y} block per retained X-plane. The loop direction
+ * keeps a plane's source intact until it has been copied;
+ * {@link System#arraycopy} handles overlap within that block.
+ */
+ private void shiftContents(int dX, int dZ, int xLo, int xHi, int zLo, int zHi) {
+ // Each Z within [zLo, zHi] contributes a full contiguous Y run, so the
+ // whole per-plane block is one run. The Y sentinels carried along are
+ // copied from equivalent source sentinels and stay empty.
+ int runLen = (zHi - zLo + 1) * this.strideZ;
+
+ // When data moves to lower indices (dX > 0) copy ascending so a source
+ // plane is read before a later write can reach it; descend otherwise.
+ int first = dX < 0 ? xHi : xLo;
+ int last = dX < 0 ? xLo : xHi;
+ int step = dX < 0 ? -1 : 1;
+
+ for (int lx = first; lx != last + step; lx += step) {
+ int destOff = lx * this.strideX + zLo * this.strideZ;
+ int srcOff = (lx + dX) * this.strideX + (zLo + dZ) * this.strideZ;
+
+ System.arraycopy(this.visitState, srcOff, this.visitState, destOff, runLen);
+ System.arraycopy(this.sectionMeta, srcOff, this.sectionMeta, destOff, runLen);
+ System.arraycopy(this.regionOfCell, srcOff, this.regionOfCell, destOff, runLen);
+ System.arraycopy(this.latticeSection, srcOff, this.latticeSection, destOff, runLen);
+ }
+ }
+
+ /**
+ * Account for cells that leave the window before their slots are reused.
+ *
+ * The source rectangle is the old interior that supplies the retained
+ * destination rectangle. Every installed cell outside it loses its slot,
+ * so its contribution to {@link #installedCount} is decremented here.
+ * Those sections remain in {@link #sections}; their stale array entries
+ * are subsequently overwritten by {@link #shiftContentsXOnly} or
+ * {@link #shiftContents}, then cleared by {@link #fillNewBand}.
+ *
+ * Because the old and new windows differ by a translation, the retained
+ * source rectangle touches an edge in each shifted axis. Its complement is
+ * therefore two non-overlapping rectangles: an X-only strip and a Z-only
+ * strip. Iterating those rectangles avoids testing rectangle membership for
+ * every cell.
+ */
+ private void dropLeaving(int srcXLo, int srcXHi, int srcZLo, int srcZHi) {
+ int interiorXHi = this.dimX - 2;
+ int interiorZHi = this.dimZ - 2;
+ int interiorYHi = this.dimY - 2;
+
+ int xBandLo = srcXLo == 1 ? srcXHi + 1 : 1;
+ int xBandHi = srcXLo == 1 ? interiorXHi : srcXLo - 1;
+ int zBandLo = srcZLo == 1 ? srcZHi + 1 : 1;
+ int zBandHi = srcZLo == 1 ? interiorZHi : srcZLo - 1;
+
+ this.dropLeavingRectangle(xBandLo, xBandHi, 1, interiorZHi, interiorYHi);
+ this.dropLeavingRectangle(srcXLo, srcXHi, zBandLo, zBandHi, interiorYHi);
+ }
+
+ private void dropLeavingRectangle(int xLo, int xHi, int zLo, int zHi, int interiorYHi) {
+ for (int lx = xLo; lx <= xHi; lx++) {
+ for (int lz = zLo; lz <= zHi; lz++) {
+ int col = lx * this.strideX + lz * this.strideZ;
+ for (int ly = 1; ly <= interiorYHi; ly++) {
+ if (this.latticeSection[col + ly] != null) {
+ this.installedCount--;
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Clear and repopulate the L-shaped band of cells that entered the window.
+ *
+ * As with {@link #dropLeaving}, the band is visited as two
+ * non-overlapping rectangles: the X-only strip outside the retained X
+ * range, followed by the Z-only strip inside the retained X range.
+ */
+ private void fillNewBand(int keepXLo, int keepXHi, int keepZLo, int keepZHi) {
+ int interiorXHi = this.dimX - 2;
+ int interiorZHi = this.dimZ - 2;
+ int interiorYHi = this.dimY - 2;
+
+ int xBandLo = keepXLo == 1 ? keepXHi + 1 : 1;
+ int xBandHi = keepXLo == 1 ? interiorXHi : keepXLo - 1;
+ int zBandLo = keepZLo == 1 ? keepZHi + 1 : 1;
+ int zBandHi = keepZLo == 1 ? interiorZHi : keepZLo - 1;
+
+ this.fillBandRectangle(xBandLo, xBandHi, 1, interiorZHi, interiorYHi);
+ this.fillBandRectangle(keepXLo, keepXHi, zBandLo, zBandHi, interiorYHi);
+ }
+
+ private void fillBandRectangle(int xLo, int xHi, int zLo, int zHi, int interiorYHi) {
+ for (int lx = xLo; lx <= xHi; lx++) {
+ int worldX = this.baseX + lx;
+
+ for (int lz = zLo; lz <= zHi; lz++) {
+ int worldZ = this.baseZ + lz;
+ int col = lx * this.strideX + lz * this.strideZ;
+
+ for (int ly = 1; ly <= interiorYHi; ly++) {
+ int idx = col + ly;
+
+ this.visitState[idx] = SENTINEL;
+ this.sectionMeta[idx] = VisibilityEncoding.NULL;
+ this.regionOfCell[idx] = -1;
+ this.latticeSection[idx] = null;
+
+ RenderSection section = this.sections.get(
+ PositionUtil.packSection(worldX, this.baseY + ly, worldZ));
+
+ if (section != null) {
+ this.install(section);
+ }
+ }
+ }
+ }
+ }
+
/**
* Computes the potential lattice slot for a world position.
*
--
2.54.1
From 841096aac6c836b838002bb5b9874988f229dc00 Mon Sep 17 00:00:00 2001
From: embeddedt <42941056+embeddedt@users.noreply.github.com>
Date: Tue, 18 Aug 2026 18:53:49 -0400
Subject: [PATCH 07/11] Unroll and inline some neighbor-visiting code in the
hot loop
---
.../chunk/occlusion/OcclusionCuller.java | 50 ++++++++++++++++++-
1 file changed, 48 insertions(+), 2 deletions(-)
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 276466e6b..8b87b0b03 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
@@ -204,8 +204,16 @@ public class OcclusionCuller {
int head = 0;
int vtail = this.vtail;
+ int tail = this.tail;
- while (head < this.tail) {
+ // Constant neighbour strides / packed-coord steps, hoisted so the unrolled expansion below uses
+ // immediates instead of per-edge array loads. delta[EAST]=+strideX, delta[SOUTH]=+strideZ, Y-stride=1.
+ final int strideX = delta[GraphDirection.EAST];
+ final int strideZ = delta[GraphDirection.SOUTH];
+ final int xStep = 1 << (2 * XYZ_SHIFT);
+ final int yStep = 1 << XYZ_SHIFT;
+
+ while (head < tail) {
long entry = queue[head++];
int idx = (int) entry;
int xyz = (int) (entry >>> 32);
@@ -253,9 +261,47 @@ public class OcclusionCuller {
// We can only traverse outwards from the centre of the search.
connections &= getOutwardDirections(chunkX, chunkY, chunkZ, camX, camY, camZ);
- this.visitNeighbors(visitState, queue, delta, idx, xyz, connections, frameStamp);
+ // Unrolled variant of visitNeighbors, with delta, step, incoming values inlined into each branch.
+ // The unrolling measurably improves performance here.
+ if ((connections & (1 << GraphDirection.DOWN)) != 0) {
+ final int n = idx - 1;
+ long ns = visitState[n];
+ if (ns < frameStamp) { ns = frameStamp; queue[tail++] = ((long) (xyz - yStep) << 32) | (n & 0xFFFFFFFFL); }
+ visitState[n] = ns | (1 << GraphDirection.UP);
+ }
+ if ((connections & (1 << GraphDirection.UP)) != 0) {
+ final int n = idx + 1;
+ long ns = visitState[n];
+ if (ns < frameStamp) { ns = frameStamp; queue[tail++] = ((long) (xyz + yStep) << 32) | (n & 0xFFFFFFFFL); }
+ visitState[n] = ns | (1 << GraphDirection.DOWN);
+ }
+ if ((connections & (1 << GraphDirection.NORTH)) != 0) {
+ final int n = idx - strideZ;
+ long ns = visitState[n];
+ if (ns < frameStamp) { ns = frameStamp; queue[tail++] = ((long) (xyz - 1) << 32) | (n & 0xFFFFFFFFL); }
+ visitState[n] = ns | (1 << GraphDirection.SOUTH);
+ }
+ if ((connections & (1 << GraphDirection.SOUTH)) != 0) {
+ final int n = idx + strideZ;
+ long ns = visitState[n];
+ if (ns < frameStamp) { ns = frameStamp; queue[tail++] = ((long) (xyz + 1) << 32) | (n & 0xFFFFFFFFL); }
+ visitState[n] = ns | (1 << GraphDirection.NORTH);
+ }
+ if ((connections & (1 << GraphDirection.WEST)) != 0) {
+ final int n = idx - strideX;
+ long ns = visitState[n];
+ if (ns < frameStamp) { ns = frameStamp; queue[tail++] = ((long) (xyz - xStep) << 32) | (n & 0xFFFFFFFFL); }
+ visitState[n] = ns | (1 << GraphDirection.EAST);
+ }
+ if ((connections & (1 << GraphDirection.EAST)) != 0) {
+ final int n = idx + strideX;
+ long ns = visitState[n];
+ if (ns < frameStamp) { ns = frameStamp; queue[tail++] = ((long) (xyz + xStep) << 32) | (n & 0xFFFFFFFFL); }
+ visitState[n] = ns | (1 << GraphDirection.WEST);
+ }
}
+ this.tail = tail;
this.vtail = vtail;
}
--
2.54.1
From 244dae560820339161977b020c9b2e56d1f69f33 Mon Sep 17 00:00:00 2001
From: embeddedt <42941056+embeddedt@users.noreply.github.com>
Date: Tue, 18 Aug 2026 19:11:54 -0400
Subject: [PATCH 08/11] Remove visit buffering
It *reduces* performance and makes the code more complex
---
.../render/chunk/PackedSectionMetadata.java | 35 +++++
.../chunk/lists/VisibleChunkCollector.java | 8 +-
.../chunk/occlusion/OcclusionCuller.java | 120 +++++-------------
3 files changed, 71 insertions(+), 92 deletions(-)
diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java
index 574886d45..620d71fa2 100644
--- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java
+++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java
@@ -125,6 +125,41 @@ public final class PackedSectionMetadata {
return (packed & BUILD_IN_FLIGHT_FLAG) != 0;
}
+ /*
+ * Compact collector metadata: includes only the info the VisibleChunkCollector cares about.
+ *
+ * 6 5 3 2 0
+ * +--+-------+--------+
+ * |IF|pending|visuals |
+ * +--+-------+--------+
+ */
+ private static final int COMPACT_META_SHIFT = VISUALS_FLAGS_SHIFT;
+ private static final long COMPACT_META_FIELDS =
+ (VISUALS_FLAGS_MASK << VISUALS_FLAGS_SHIFT)
+ | (PENDING_UPDATE_MASK << PENDING_UPDATE_SHIFT)
+ | BUILD_IN_FLIGHT_FLAG;
+ private static final int COMPACT_META_MASK = (int) (COMPACT_META_FIELDS >>> COMPACT_META_SHIFT);
+ private static final int COMPACT_PENDING_SHIFT = PENDING_UPDATE_SHIFT - COMPACT_META_SHIFT;
+ private static final int COMPACT_BUILD_IN_FLIGHT_BIT = BUILD_IN_FLIGHT_BIT - COMPACT_META_SHIFT;
+
+ public static int toCompactMeta(long packed) {
+ return (int) (packed >>> COMPACT_META_SHIFT) & COMPACT_META_MASK;
+ }
+
+ public static int getCompactVisualsFlags(int meta) {
+ return meta & (int) VISUALS_FLAGS_MASK;
+ }
+
+ /** @return the pending update type, or {@code null} when the field is zero */
+ public static @Nullable ChunkUpdateType getCompactPendingUpdate(int meta) {
+ int encoded = (meta >>> COMPACT_PENDING_SHIFT) & (int) PENDING_UPDATE_MASK;
+ return encoded == 0 ? null : ChunkUpdateType.VALUES[encoded - 1];
+ }
+
+ public static boolean isCompactBuildInFlight(int meta) {
+ return (meta & (1 << COMPACT_BUILD_IN_FLIGHT_BIT)) != 0;
+ }
+
/**
* Replaces the build-in-flight flag and preserves every other field.
*/
diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/VisibleChunkCollector.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/VisibleChunkCollector.java
index 70fb58504..5f96ea97d 100644
--- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/VisibleChunkCollector.java
+++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/VisibleChunkCollector.java
@@ -51,7 +51,7 @@ public class VisibleChunkCollector implements OcclusionCuller.Visitor {
}
@Override
- public void visit(int latticeIndex, int regionId, int sectionIndex, long metaBits, boolean visible) {
+ public void visit(int latticeIndex, int regionId, int sectionIndex, int meta, boolean visible) {
// Note: even if a section does not have render objects, we must ensure the render list is initialized and put
// into the sorted queue of lists, so that we maintain the correct order of draw calls.
ChunkRenderList renderList = this.renderListsByRegion[regionId];
@@ -61,17 +61,17 @@ public class VisibleChunkCollector implements OcclusionCuller.Visitor {
}
if (visible) {
- int visualsFlags = PackedSectionMetadata.getVisualsFlags(metaBits);
+ int visualsFlags = PackedSectionMetadata.getCompactVisualsFlags(meta);
if (visualsFlags != 0) {
renderList.add(sectionIndex, visualsFlags);
}
- ChunkUpdateType type = PackedSectionMetadata.getPendingUpdate(metaBits);
+ ChunkUpdateType type = PackedSectionMetadata.getCompactPendingUpdate(meta);
// Skip sections with an in-flight build to avoid redundant work. This is an advisory
// check only: submitRebuildTasks() will validate getPendingUpdate() independently before
// scheduling, so a stale read here cannot cause a double submission.
- if (type != null && !PackedSectionMetadata.isBuildInFlight(metaBits)) {
+ if (type != null && !PackedSectionMetadata.isCompactBuildInFlight(meta)) {
this.addToRebuildLists(this.lattice.sectionAt(latticeIndex), type);
}
}
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 8b87b0b03..9cd81db42 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
@@ -19,15 +19,14 @@ import static org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionLattice
* Performs a visibility search over the installed cells of a
* {@link SectionLattice}.
*
- * A search has four phases:
+ * A search has three phases:
* Occlusion traversal accumulates the directions through which each cell
@@ -38,7 +37,7 @@ import static org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionLattice
* as a frustum/render-distance scan but disables graph occlusion for that
* search.
*
- * The queue and visitation buffers are reused between searches. A single
+ * The queue is reused between searches. A single
* invocation must run at a time, and the lattice's dimensions, coordinates,
* installed membership, and metadata must remain stable until the invocation
* completes. The owning {@code RenderListManager} provides that coordination.
@@ -67,43 +66,8 @@ public class OcclusionCuller {
private long[] queue = new long[256];
private int tail;
- /*
- * Deferred visitation buffer. The hot loop records primitive data without
- * touching section objects; replay() invokes the visitor afterwards.
- * Each installed cell is recorded at most once, so this buffer is also
- * bounded by installedCount.
- *
- * Entry representation:
- * 31 9 8 1 0
- * +----------------------+----------+-+
- * | lattice index | section |V|
- * +----------------------+----------+-+
- *
- * The section field is the 8-bit section index within its render region;
- * V is the final visible flag.
- */
- private static final int VISIT_INDEX_SHIFT = 9;
- private static final int VISIT_SECTION_SHIFT = 1;
- private static final int VISIT_SECTION_MASK = 0xFF;
- private int[] visitBuffer = new int[256];
- private int vtail;
- private static int packVisit(int latticeIndex, int sectionIndex, boolean visible) {
- return (latticeIndex << VISIT_INDEX_SHIFT) | (sectionIndex << VISIT_SECTION_SHIFT) | (visible ? 1 : 0);
- }
-
- private static int visitIndex(int entry) {
- return entry >>> VISIT_INDEX_SHIFT;
- }
-
- private static int visitSection(int entry) {
- return (entry >>> VISIT_SECTION_SHIFT) & VISIT_SECTION_MASK;
- }
-
- private static boolean visitVisible(int entry) {
- return (entry & 1) != 0;
- }
private final RegionCullCache regionCullCache = new RegionCullCache();
@@ -135,55 +99,34 @@ public class OcclusionCuller {
boolean useOcclusionCulling,
int frame)
{
- // Pre-size so enqueue/record are bare stores: at most one entry per installed cell.
+ // Pre-size so enqueue is a bare store: at most one entry per installed cell.
int installed = this.lattice.installedCount;
if (this.queue.length < installed) {
this.queue = new long[Math.max(installed, this.queue.length * 2)];
}
- if (this.visitBuffer.length < installed) {
- this.visitBuffer = new int[Math.max(installed, this.visitBuffer.length * 2)];
- }
this.tail = 0;
- this.vtail = 0;
this.regionCullCache.begin(viewport, searchDistance, numRegions);
this.isCameraInUnloadedSection = false;
- this.init(viewport, searchDistance, useOcclusionCulling, frame);
+ this.init(visitor, viewport, searchDistance, useOcclusionCulling, frame);
if (this.isCameraInUnloadedSection) {
useOcclusionCulling = false;
}
- this.process(viewport, searchDistance, useOcclusionCulling, frame);
-
- this.replay(visitor);
- }
-
- // Replay records in the same order in which cells were processed. The
- // visitor runs after the search so the hot loop need not resolve section
- // objects. It must not feed changes back into this already-completed search.
- private void replay(Visitor visitor) {
- final int[] visitBuffer = this.visitBuffer;
- final int[] regionOfCell = this.lattice.regionOfCell;
- final long[] sectionMeta = this.lattice.sectionMeta;
-
- int count = this.vtail;
-
- for (int i = 0; i < count; i++) {
- int entry = visitBuffer[i];
- int idx = visitIndex(entry);
-
- visitor.visit(idx, regionOfCell[idx], visitSection(entry), sectionMeta[idx], visitVisible(entry));
- }
+ this.process(visitor, viewport, searchDistance, useOcclusionCulling, frame);
}
/**
- * Process the BFS queue. Each queued cell is classified once, recorded for
- * replay, and expanded only when it is visible. Occlusion metadata selects
- * the possible exits; the outward-direction mask then prevents moving back
- * toward the camera.
+ * Process the BFS queue. Each queued cell is classified once, reported
+ * directly to the visitor, and expanded only when it is visible. Occlusion
+ * metadata selects the possible exits; the outward-direction mask then
+ * prevents moving back toward the camera. The visitor is invoked in
+ * traversal order, with every argument already in registers; it must not
+ * feed changes back into the running search.
*/
- private void process(Viewport viewport,
+ private void process(Visitor visitor,
+ Viewport viewport,
float searchDistance,
boolean useOcclusionCulling,
int frame)
@@ -193,7 +136,6 @@ public class OcclusionCuller {
final int[] regionOfCell = this.lattice.regionOfCell;
final int[] delta = this.lattice.delta;
final long[] queue = this.queue;
- final int[] visitBuffer = this.visitBuffer;
final int baseX = this.lattice.baseX, baseY = this.lattice.baseY, baseZ = this.lattice.baseZ;
final RegionCullCache cache = this.regionCullCache;
@@ -203,7 +145,6 @@ public class OcclusionCuller {
final long frameStamp = SectionLattice.frameStamp(frame);
int head = 0;
- int vtail = this.vtail;
int tail = this.tail;
// Constant neighbour strides / packed-coord steps, hoisted so the unrolled expansion below uses
@@ -222,7 +163,10 @@ public class OcclusionCuller {
int chunkY = baseY + ((xyz >>> XYZ_SHIFT) & XYZ_LOCAL_MASK);
int chunkZ = baseZ + (xyz & XYZ_LOCAL_MASK);
- int classification = cache.classify(regionOfCell[idx],
+ int regionId = regionOfCell[idx];
+ long sm = sectionMeta[idx];
+ int compactMeta = PackedSectionMetadata.toCompactMeta(sm);
+ int classification = cache.classify(regionId,
regionOrigin(chunkX, RenderRegion.REGION_WIDTH_SH, RenderRegion.REGION_BLOCK_WIDTH),
regionOrigin(chunkY, RenderRegion.REGION_HEIGHT_SH, RenderRegion.REGION_BLOCK_HEIGHT),
regionOrigin(chunkZ, RenderRegion.REGION_LENGTH_SH, RenderRegion.REGION_BLOCK_LENGTH));
@@ -240,7 +184,7 @@ public class OcclusionCuller {
}
int sectionIndex = LocalSectionIndex.pack(chunkX, chunkY, chunkZ);
- visitBuffer[vtail++] = packVisit(idx, sectionIndex, visible);
+ visitor.visit(idx, regionId, sectionIndex, compactMeta, visible);
if (!visible) {
continue;
@@ -253,7 +197,7 @@ public class OcclusionCuller {
// accumulated in this cell.
int incoming = (int) (visitState[idx] & DIR_MASK);
connections = VisibilityEncoding.getConnections(
- sectionMeta[idx] & PackedSectionMetadata.VISIBILITY_MASK, incoming);
+ sm & PackedSectionMetadata.VISIBILITY_MASK, incoming);
} else {
connections = GraphDirectionSet.ALL;
}
@@ -302,7 +246,6 @@ public class OcclusionCuller {
}
this.tail = tail;
- this.vtail = vtail;
}
// Visit each selected neighbour using both its linear array offset and
@@ -398,7 +341,8 @@ public class OcclusionCuller {
* inline; an out-of-height or unloaded camera is handled by scanning a
* horizontal plane of nearby loaded sections.
*/
- private void init(Viewport viewport,
+ private void init(Visitor visitor,
+ Viewport viewport,
float searchDistance,
boolean useOcclusionCulling,
int frame)
@@ -423,13 +367,13 @@ public class OcclusionCuller {
origin.y(), GraphDirectionSet.of(GraphDirection.UP) | GraphDirectionSet.of(GraphDirection.DOWN));
this.isCameraInUnloadedSection = true;
} else {
- this.initWithinWorld(viewport, useOcclusionCulling, frame);
+ this.initWithinWorld(visitor, viewport, useOcclusionCulling, frame);
}
}
- // The loaded camera section is the root: it is recorded immediately, not
+ // The loaded camera section is the root: it is visited immediately, not
// queued, and its visible paths seed the BFS with no incoming direction.
- private void initWithinWorld(Viewport viewport, boolean useOcclusionCulling, int frame) {
+ private void initWithinWorld(Visitor visitor, Viewport viewport, boolean useOcclusionCulling, int frame) {
final long[] visitState = this.lattice.visitState;
final long[] queue = this.queue;
final int[] delta = this.lattice.delta;
@@ -442,17 +386,17 @@ public class OcclusionCuller {
long frameStamp = SectionLattice.frameStamp(frame);
visitState[idx] = frameStamp;
- // Record the origin as visited; it is processed inline rather than
+ // Visit the origin immediately; it is processed inline rather than
// enqueued so the BFS starts with its neighbours.
int sectionIndex = LocalSectionIndex.pack(origin.x(), origin.y(), origin.z());
- this.visitBuffer[this.vtail++] = packVisit(idx, sectionIndex, true);
+ long sm = this.lattice.sectionMeta[idx];
+ visitor.visit(idx, this.lattice.regionOfCell[idx], sectionIndex, PackedSectionMetadata.toCompactMeta(sm), true);
int outgoing;
if (useOcclusionCulling) {
// The camera is inside this chunk, so there are no incoming directions; enqueue any path out.
- outgoing = VisibilityEncoding.getConnections(
- this.lattice.sectionMeta[idx] & PackedSectionMetadata.VISIBILITY_MASK);
+ outgoing = VisibilityEncoding.getConnections(sm & PackedSectionMetadata.VISIBILITY_MASK);
} else {
outgoing = GraphDirectionSet.ALL;
}
@@ -552,9 +496,9 @@ public class OcclusionCuller {
* @param latticeIndex installed {@link SectionLattice} slot for the section
* @param regionId owning render-region identifier
* @param sectionIndex section's compact local index within its region
- * @param metaBits packed section metadata mirrored by the lattice
+ * @param meta compact collector metadata
* @param visible whether the section passed the visibility tests
*/
- void visit(int latticeIndex, int regionId, int sectionIndex, long metaBits, boolean visible);
+ void visit(int latticeIndex, int regionId, int sectionIndex, int meta, boolean visible);
}
}
--
2.54.1
From c4208b3604ff19ac4b72db6887e17b3ba6516dda Mon Sep 17 00:00:00 2001
From: embeddedt <42941056+embeddedt@users.noreply.github.com>
Date: Tue, 18 Aug 2026 19:30:14 -0400
Subject: [PATCH 09/11] Fix race conditions when reading visibility state
---
.../render/chunk/lists/RenderListManager.java | 21 ++--
.../chunk/occlusion/SectionLattice.java | 101 +++++++++++++++---
2 files changed, 103 insertions(+), 19 deletions(-)
diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/RenderListManager.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/RenderListManager.java
index e74366847..d5d3afec6 100644
--- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/RenderListManager.java
+++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/RenderListManager.java
@@ -42,6 +42,14 @@ public class RenderListManager {
private int pendingLastUpdatedFrame;
+ @NotNull
+ private SectionLattice.VisibilitySnapshot visibilitySnapshot = SectionLattice.VisibilitySnapshot.EMPTY;
+
+ // Snapshot produced by the in-progress search. Written on the async thread; read on the render thread
+ // in finishPreviousGraphUpdate() after join() establishes happens-before, then published to visibilitySnapshot.
+ @Nullable
+ private SectionLattice.VisibilitySnapshot pendingVisibilitySnapshot;
+
// Tasks deferred by submitUpdateTask() while an async search is running. Drained on the
// render thread in finishPreviousGraphUpdate() after join() establishes happens-before.
private final ArrayDeque {@link SectionLattice#findVisible} runs asynchronously and mutates the
+ * live lattice while another thread queries section visibility. Rather than
+ * read the live arrays across that boundary, a search returns a snapshot: a
+ * copy of {@code visitState} plus the window geometry that indexes it. The
+ * snapshot's array is not the live lattice, so a running search's mutations
+ * cannot race a query against it.
+ *
+ * To avoid a per-frame allocation, {@code visitState} is a buffer
+ * recycled from {@code snapshotBuffers} rather than a fresh clone. The
+ * lattice alternates between two buffers so the buffer a new search
+ * overwrites is never the one backing the currently published snapshot; see
+ * {@link SectionLattice#snapshot()}.
+ *
+ * @param visitState the search's per-cell visit state; a recycled buffer
+ * that stays valid until the search two generations later
+ * overwrites it
*/
- public boolean isSectionVisible(int x, int y, int z, int minVisibleFrame) {
- int idx = this.installedIndex(x, y, z);
+ public record VisibilitySnapshot(long[] visitState, int baseX, int baseY, int baseZ,
+ int dimX, int dimY, int dimZ) {
+ /** A snapshot with no window, reporting every section as not visible. */
+ public static final VisibilitySnapshot EMPTY =
+ new VisibilitySnapshot(new long[0], 0, 0, 0, 0, 0, 0);
- // The frame in which the slot was last marked visible by the search. Narrowing (int) after the logical
- // shift recovers the 32-bit frame; an uninstalled section (idx < 0) is treated as never-visible.
- return idx >= 0 && (int) (this.visitState[idx] >>> FRAME_SHIFT) >= minVisibleFrame;
+ /**
+ * Tests whether the section at a world position was marked visible in or
+ * after the requested frame. Positions outside the captured window, or
+ * never visited, are treated as never-visible.
+ */
+ public boolean isSectionVisible(int x, int y, int z, int minVisibleFrame) {
+ int lx = x - this.baseX;
+ int ly = y - this.baseY;
+ int lz = z - this.baseZ;
+
+ // Same interior test as SectionLattice.indexOf: only cells strictly
+ // inside the sentinel border can hold a section, so anything outside
+ // it (including an empty snapshot) is never visible.
+ if (lx < 1 || lx > this.dimX - 2
+ || ly < 1 || ly > this.dimY - 2
+ || lz < 1 || lz > this.dimZ - 2) {
+ return false;
+ }
+
+ int idx = (lx * this.dimZ + lz) * this.dimY + ly;
+
+ // The frame in which the slot was last marked visible by the search. Narrowing (int) after the logical
+ // shift recovers the 32-bit frame; an unvisited or empty cell holds INITIAL/SENTINEL, which decode to a
+ // value below any real frame and are therefore treated as never-visible.
+ return (int) (this.visitState[idx] >>> FRAME_SHIFT) >= minVisibleFrame;
+ }
+ }
+
+ private VisibilitySnapshot snapshot() {
+ if (this.visitState == null) {
+ return VisibilitySnapshot.EMPTY;
+ }
+
+ int parity = this.snapshotParity;
+ this.snapshotParity ^= 1;
+
+ long[] dst = this.snapshotBuffers[parity];
+
+ if (dst == null || dst.length != this.visitState.length) {
+ dst = new long[this.visitState.length];
+ this.snapshotBuffers[parity] = dst;
+ }
+
+ System.arraycopy(this.visitState, 0, dst, 0, dst.length);
+
+ return new VisibilitySnapshot(dst, this.baseX, this.baseY, this.baseZ,
+ this.dimX, this.dimY, this.dimZ);
}
/**
@@ -333,14 +404,18 @@ public final class SectionLattice {
* Run the visibility search over the currently installed lattice cells.
* The caller must have completed {@link #ensureWindowCovers} and must keep
* lattice structure and metadata stable until this method returns.
+ *
+ * @return a snapshot of the visit state this search produced
*/
- public void findVisible(OcclusionCuller.Visitor visitor,
- Viewport viewport,
- float searchDistance,
- int numRegions,
- boolean useOcclusionCulling,
- int frame) {
+ public VisibilitySnapshot findVisible(OcclusionCuller.Visitor visitor,
+ Viewport viewport,
+ float searchDistance,
+ int numRegions,
+ boolean useOcclusionCulling,
+ int frame) {
this.culler.findVisible(visitor, viewport, searchDistance, numRegions, useOcclusionCulling, frame);
+
+ return this.snapshot();
}
private void allocate(int newDimXZ) {
--
2.54.1
From 8273d92807ca59bff220aff0e613ee219b205c6c Mon Sep 17 00:00:00 2001
From: embeddedt <42941056+embeddedt@users.noreply.github.com>
Date: Tue, 18 Aug 2026 19:40:21 -0400
Subject: [PATCH 10/11] Assert the number of update types fits in 3 bits
---
.../embeddium/impl/render/chunk/ChunkUpdateType.java | 7 +++++++
1 file changed, 7 insertions(+)
diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/ChunkUpdateType.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/ChunkUpdateType.java
index 7f3faef38..5659bca48 100644
--- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/ChunkUpdateType.java
+++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/ChunkUpdateType.java
@@ -67,4 +67,11 @@ public enum ChunkUpdateType {
public boolean isSort() {
return this == SORT || this == IMPORTANT_SORT;
}
+
+ static {
+ if (VALUES.length > 7) {
+ // See PackedSectionMetadata, OcclusionCuller, etc.
+ throw new AssertionError("The occlusion system currently assumes there are at most 7 update types");
+ }
+ }
}
--
2.54.1
From 7704538a2367df614fc494d1c48a98451ef774fc Mon Sep 17 00:00:00 2001
From: embeddedt <42941056+embeddedt@users.noreply.github.com>
Date: Tue, 18 Aug 2026 19:50:45 -0400
Subject: [PATCH 11/11] Extend the region frustum optimization to Iris frustums
---
.../iris/shadows/frustum/BoxCuller.java | 10 ++++
.../frustum/CullEverythingFrustum.java | 5 ++
.../AdvancedShadowCullingFrustum.java | 47 +++++++++++++++++++
.../ReversedAdvancedShadowCullingFrustum.java | 25 ++++++++++
.../frustum/fallback/BoxCullingFrustum.java | 9 ++++
.../frustum/fallback/NonCullingFrustum.java | 5 ++
6 files changed, 101 insertions(+)
diff --git a/modern/src/main/shaders_java/net/irisshaders/iris/shadows/frustum/BoxCuller.java b/modern/src/main/shaders_java/net/irisshaders/iris/shadows/frustum/BoxCuller.java
index ae61ef5ad..3fe9ee333 100644
--- a/modern/src/main/shaders_java/net/irisshaders/iris/shadows/frustum/BoxCuller.java
+++ b/modern/src/main/shaders_java/net/irisshaders/iris/shadows/frustum/BoxCuller.java
@@ -54,6 +54,16 @@ public class BoxCuller {
return maxZ < -this.maxDistance || minZ > this.maxDistance;
}
+ /**
+ * Camera-relative variant of a "fully inside" test: returns true only when the entire box lies within the
+ * allowed distance bounds on every axis, meaning no sub-box of it could ever be culled.
+ */
+ public boolean isFullyInsideSodium(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) {
+ return minX >= -this.maxDistance && maxX <= this.maxDistance
+ && minY >= -this.maxDistance && maxY <= this.maxDistance
+ && minZ >= -this.maxDistance && maxZ <= this.maxDistance;
+ }
+
@Override
public String toString() {
return "Box Culling active; max distance " + maxDistance;
diff --git a/modern/src/main/shaders_java/net/irisshaders/iris/shadows/frustum/CullEverythingFrustum.java b/modern/src/main/shaders_java/net/irisshaders/iris/shadows/frustum/CullEverythingFrustum.java
index f3f6787ee..280eb15e4 100644
--- a/modern/src/main/shaders_java/net/irisshaders/iris/shadows/frustum/CullEverythingFrustum.java
+++ b/modern/src/main/shaders_java/net/irisshaders/iris/shadows/frustum/CullEverythingFrustum.java
@@ -33,4 +33,9 @@ public class CullEverythingFrustum extends Frustum implements ViewportProvider,
public boolean testAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
return false;
}
+
+ @Override
+ public int intersectAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
+ return OUTSIDE;
+ }
}
diff --git a/modern/src/main/shaders_java/net/irisshaders/iris/shadows/frustum/advanced/AdvancedShadowCullingFrustum.java b/modern/src/main/shaders_java/net/irisshaders/iris/shadows/frustum/advanced/AdvancedShadowCullingFrustum.java
index fb22d5e46..3ee61561a 100644
--- a/modern/src/main/shaders_java/net/irisshaders/iris/shadows/frustum/advanced/AdvancedShadowCullingFrustum.java
+++ b/modern/src/main/shaders_java/net/irisshaders/iris/shadows/frustum/advanced/AdvancedShadowCullingFrustum.java
@@ -387,6 +387,53 @@ public class AdvancedShadowCullingFrustum extends Frustum implements ViewportPro
return (boxCuller == null || !boxCuller.isCulledSodium(minX, minY, minZ, maxX, maxY, maxZ)) && this.checkCornerVisibility(minX, minY, minZ, maxX, maxY, maxZ) > 0;
}
+ /**
+ * Tri-state variant of {@link #checkCornerVisibility}, ported from JOML's {@code FrustumIntersection#intersectAab}.
+ * Unlike {@link #checkCornerVisibility}, this additionally tests the near corner against each plane so that boxes
+ * lying entirely within the frustum can be reported as fully inside.
+ */
+ protected int intersectCorners(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
+ boolean inside = true;
+
+ for (int i = 0; i < planeCount; ++i) {
+ Vector4f plane = this.planes[i];
+ float px = plane.x();
+ float py = plane.y();
+ float pz = plane.z();
+ float pw = plane.w();
+
+ // If the far corner (the one furthest along the plane normal) is behind the plane, the box is fully outside.
+ if (Math.fma(px, px < 0 ? minX : maxX, Math.fma(py, py < 0 ? minY : maxY, pz * (pz < 0 ? minZ : maxZ))) < -pw) {
+ return OUTSIDE;
+ }
+
+ // If the near corner is behind the plane, the box straddles it and can be at most partially inside.
+ if (Math.fma(px, px < 0 ? maxX : minX, Math.fma(py, py < 0 ? maxY : minY, pz * (pz < 0 ? maxZ : minZ))) < -pw) {
+ inside = false;
+ }
+ }
+
+ return inside ? FULLY_INSIDE : PARTIALLY_INSIDE;
+ }
+
+ @Override
+ public int intersectAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
+ if (boxCuller != null && boxCuller.isCulledSodium(minX, minY, minZ, maxX, maxY, maxZ)) {
+ return OUTSIDE;
+ }
+
+ int result = intersectCorners(minX, minY, minZ, maxX, maxY, maxZ);
+
+ // A box can only be fully inside if it is also fully within the box culler's bounds; otherwise a sub-box could
+ // be culled and the region must be treated as partial.
+ if (result == FULLY_INSIDE && boxCuller != null
+ && !boxCuller.isFullyInsideSodium(minX, minY, minZ, maxX, maxY, maxZ)) {
+ return PARTIALLY_INSIDE;
+ }
+
+ return result;
+ }
+
private final Vector3d position = new Vector3d();
@Override
diff --git a/modern/src/main/shaders_java/net/irisshaders/iris/shadows/frustum/advanced/ReversedAdvancedShadowCullingFrustum.java b/modern/src/main/shaders_java/net/irisshaders/iris/shadows/frustum/advanced/ReversedAdvancedShadowCullingFrustum.java
index 4d7527c83..e3c712d97 100644
--- a/modern/src/main/shaders_java/net/irisshaders/iris/shadows/frustum/advanced/ReversedAdvancedShadowCullingFrustum.java
+++ b/modern/src/main/shaders_java/net/irisshaders/iris/shadows/frustum/advanced/ReversedAdvancedShadowCullingFrustum.java
@@ -58,4 +58,29 @@ public class ReversedAdvancedShadowCullingFrustum extends AdvancedShadowCullingF
return this.checkCornerVisibility(minX, minY, minZ, maxX, maxY, maxZ) > 0;
}
+
+ @Override
+ public int intersectAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
+ if (distanceCuller != null && distanceCuller.isCulledSodium(minX, minY, minZ, maxX, maxY, maxZ)) {
+ return OUTSIDE;
+ }
+
+ if (boxCuller != null && !boxCuller.isCulledSodium(minX, minY, minZ, maxX, maxY, maxZ)) {
+ // The box overlaps the kept voxel region, so it is visible. It is only fully inside when the entire box
+ // stays within both the voxel region and the outer distance bound, so no sub-box could be culled.
+ boolean fullyInside = boxCuller.isFullyInsideSodium(minX, minY, minZ, maxX, maxY, maxZ)
+ && (distanceCuller == null || distanceCuller.isFullyInsideSodium(minX, minY, minZ, maxX, maxY, maxZ));
+ return fullyInside ? FULLY_INSIDE : PARTIALLY_INSIDE;
+ }
+
+ // Outside the voxel region: fall back to the shadow planes, still bounded by the distance culler.
+ int result = intersectCorners(minX, minY, minZ, maxX, maxY, maxZ);
+
+ if (result == FULLY_INSIDE && distanceCuller != null
+ && !distanceCuller.isFullyInsideSodium(minX, minY, minZ, maxX, maxY, maxZ)) {
+ return PARTIALLY_INSIDE;
+ }
+
+ return result;
+ }
}
diff --git a/modern/src/main/shaders_java/net/irisshaders/iris/shadows/frustum/fallback/BoxCullingFrustum.java b/modern/src/main/shaders_java/net/irisshaders/iris/shadows/frustum/fallback/BoxCullingFrustum.java
index ac7b267df..5920a4cfc 100644
--- a/modern/src/main/shaders_java/net/irisshaders/iris/shadows/frustum/fallback/BoxCullingFrustum.java
+++ b/modern/src/main/shaders_java/net/irisshaders/iris/shadows/frustum/fallback/BoxCullingFrustum.java
@@ -50,4 +50,13 @@ public class BoxCullingFrustum extends Frustum implements ViewportProvider, org.
public boolean testAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
return !boxCuller.isCulledSodium(minX, minY, minZ, maxX, maxY, maxZ);
}
+
+ @Override
+ public int intersectAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
+ if (boxCuller.isCulledSodium(minX, minY, minZ, maxX, maxY, maxZ)) {
+ return OUTSIDE;
+ }
+
+ return boxCuller.isFullyInsideSodium(minX, minY, minZ, maxX, maxY, maxZ) ? FULLY_INSIDE : PARTIALLY_INSIDE;
+ }
}
diff --git a/modern/src/main/shaders_java/net/irisshaders/iris/shadows/frustum/fallback/NonCullingFrustum.java b/modern/src/main/shaders_java/net/irisshaders/iris/shadows/frustum/fallback/NonCullingFrustum.java
index a555276d0..5b2bd1d97 100644
--- a/modern/src/main/shaders_java/net/irisshaders/iris/shadows/frustum/fallback/NonCullingFrustum.java
+++ b/modern/src/main/shaders_java/net/irisshaders/iris/shadows/frustum/fallback/NonCullingFrustum.java
@@ -37,4 +37,9 @@ public class NonCullingFrustum extends Frustum implements ViewportProvider, org.
public boolean testAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
return true;
}
+
+ @Override
+ public int intersectAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
+ return FULLY_INSIDE;
+ }
}
--
2.54.1
+ *
+ */
+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;
+ }
+}
diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/region/RenderRegion.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/region/RenderRegion.java
index ef6ca508a..df1e9a454 100644
--- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/region/RenderRegion.java
+++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/region/RenderRegion.java
@@ -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;
diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/viewport/Viewport.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/viewport/Viewport.java
index 88dd58c86..b1e4d4318 100644
--- a/common/src/main/java/org/embeddedt/embeddium/impl/render/viewport/Viewport.java
+++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/viewport/Viewport.java
@@ -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);
}
--
2.54.1
From 450dc85f594ee8fac16197f708071a35b0f8c7f9 Mon Sep 17 00:00:00 2001
From: embeddedt <42941056+embeddedt@users.noreply.github.com>
Date: Sun, 16 Aug 2026 21:45:24 -0400
Subject: [PATCH 04/11] Implement a better storage system for occlusion node
data
---
.../render/chunk/PackedSectionMetadata.java | 19 +-
.../impl/render/chunk/RenderSection.java | 38 +-
.../render/chunk/RenderSectionManager.java | 21 +-
.../render/chunk/lists/ChunkRenderList.java | 5 +-
.../render/chunk/lists/RenderListManager.java | 93 +--
.../chunk/lists/VisibleChunkCollector.java | 52 +-
.../chunk/occlusion/OcclusionCuller.java | 538 ++++++++++++------
.../render/chunk/occlusion/OcclusionNode.java | 108 ----
.../chunk/occlusion/SectionLattice.java | 448 +++++++++++++++
9 files changed, 904 insertions(+), 418 deletions(-)
delete mode 100644 common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionNode.java
create mode 100644 common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java
diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java
index a76520fa7..e4f381a6d 100644
--- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java
+++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java
@@ -9,9 +9,9 @@ import org.jetbrains.annotations.Nullable;
* Why
* 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, chased through a second randomly-placed
- * {@code OcclusionNode}. Packed into one word they are a single load out of a flat array the traversal already
- * has the index for - see {@code OcclusionCuller}'s lattice - and the visitor can be handed plain ints.
+ * 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.
*
* Layout
*
@@ -31,10 +31,9 @@ import org.jetbrains.annotations.Nullable;
*
The small "meta bits" form
* Bits 46..52 - everything except the visibility encoding - are what the visitor actually consumes.
*
- *
+ *
+ *
+ *
+ *
+ * The lattice is therefore an index of {@code sections}, not a second
+ * collection or an overflow cache; {@code latticeSection} only contains the
+ * subset that is currently installed.
+ *
+ * Why
- * 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.
+ * Layout
+ *
- * 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 |
+ * +--------------------+--+-----------+----------+-------------------+
*
- * The visibility encoding structurally cannot occupy anything above bit 45 ({@code 5 * 8 + 5}), so bits 46 and
- * up are free. They are not, however, harmless: {@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 must mask with {@link #VISIBILITY_MASK} first. See
- * {@code OcclusionCuller.process} and {@code OcclusionCuller.initWithinWorld}.
+ *
+ *
*
- * The small "meta bits" form
- * Bits 46..52 - everything except the visibility encoding - are what the visitor actually consumes.
+ *
- *
+ * The bounds include padding and floating-point slack, so a conclusive result
+ * must never incorrectly reject or accept a section.
+ *
+ *
- *
*
*