diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/common/util/MathUtil.java b/common/src/main/java/org/embeddedt/embeddium/impl/common/util/MathUtil.java index a87dca30a..4f806aae4 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/common/util/MathUtil.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/common/util/MathUtil.java @@ -37,4 +37,18 @@ public class MathUtil { public static boolean roughlyEqual(float a, float b) { return Math.abs(b - a) < 0.00001f; } + + /** + * Returns the value nearest to zero in [min, max]. + *
+ * 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/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"); + } + } } 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..620d71fa2 --- /dev/null +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java @@ -0,0 +1,169 @@ +package org.embeddedt.embeddium.impl.render.chunk; + +import org.jetbrains.annotations.Nullable; + +/** + * 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: + *
+ * 63 53 52 51 49 48 46 45 0 + * +--------------------+--+-----------+----------+-------------------+ + * | spare |IF| pending | visuals | visibility graph | + * +--------------------+--+-----------+----------+-------------------+ + *+ *
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}. + * + *
{@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 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: RenderVisualsService.HAS_* flags.
+ private static final int VISUALS_FLAGS_SHIFT = 46;
+ private static final long VISUALS_FLAGS_MASK = 0b111L;
+
+ /**
+ * 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: 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.
+ 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;
+ }
+
+ /*
+ * 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.
+ */
+ 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..95afcf0f1 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,20 @@ 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. The graph search reads a mirror of this in SectionLattice, so
+ // mutate it only through writeMetadata(), which notifies the mirror.
+ private long packedMetadata;
+
+ // Notified on every packedMetadata change to keep the lattice mirror in sync. Null until the section is
+ // attached to its manager (the initial constructor write predates attachment).
+ @Nullable
+ private MetadataSink metadataSink;
+
+ public interface MetadataSink {
+ void onMetadataChanged(RenderSection section);
+ }
/**
* A mapping from translucent render passes to the sort state for that particular pass (which contains data needed
@@ -64,9 +75,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 +105,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 +141,39 @@ 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.writeMetadata(PackedSectionMetadata.withVisibilityData(
+ PackedSectionMetadata.withVisualsFlags(this.packedMetadata, flags), visibilityData));
+ }
+
+ // The sole writer of packedMetadata: stores the new word and notifies the mirror.
+ private void writeMetadata(long packed) {
+ this.packedMetadata = packed;
+ if (this.metadataSink != null) {
+ this.metadataSink.onMetadataChanged(this);
+ }
+ }
+
+ public long getPackedMetadata() {
+ return this.packedMetadata;
+ }
+
+ public void setMetadataSink(@Nullable MetadataSink sink) {
+ this.metadataSink = sink;
+ }
+
+ 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 A search has three 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 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.
+ */
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,
+ int numRegions,
boolean useOcclusionCulling,
int frame)
{
- final var queues = this.queue;
- queues.reset();
+ // 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)];
+ }
+ this.tail = 0;
+
+ this.regionCullCache.begin(viewport, searchDistance, numRegions);
this.isCameraInUnloadedSection = false;
- this.init(visitor, queues.write(), viewport, searchDistance, useOcclusionCulling, frame);
- if(this.isCameraInUnloadedSection) {
+ this.init(visitor, viewport, searchDistance, useOcclusionCulling, frame);
+ if (this.isCameraInUnloadedSection) {
useOcclusionCulling = false;
}
- while (queues.flip()) {
- processQueue(visitor, viewport, searchDistance, useOcclusionCulling, frame, queues.read(), queues.write());
- }
+ this.process(visitor, viewport, searchDistance, useOcclusionCulling, frame);
}
- private static void processQueue(Visitor visitor,
- Viewport viewport,
- float searchDistance,
- boolean useOcclusionCulling,
- int frame,
- ReadQueue 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 {
+ // 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 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];
+
+ // Search configuration, refreshed by begin().
+ private Viewport viewport;
+ private CameraTransform camera;
+ private float maxDistance;
+
+ /**
+ * 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;
+ if (numRegions > this.classification.length) {
+ this.grow(numRegions);
+ }
+ Arrays.fill(this.classification, 0, numRegions, UNCOMPUTED);
+ }
+
+ /**
+ * 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) {
+
+ byte result = this.classification[regionId];
+
+ if (result == UNCOMPUTED) {
+ result = (byte) this.compute(regionOriginX, regionOriginY, regionOriginZ);
+ this.classification[regionId] = result;
+ }
+
+ return result;
+ }
+
+ // Grow the classification array; contents are reset by the next begin().
+ private void grow(int minimumCapacity) {
+ 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;
+
+ 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 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;
+ 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 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 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(
+ (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) {
+ // 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;
+ }
+
+ if (hi < 0.0f) {
+ return -hi;
+ }
+
+ return 0.0f;
+ }
+}
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
new file mode 100644
index 000000000..96eeead6c
--- /dev/null
+++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java
@@ -0,0 +1,728 @@
+package org.embeddedt.embeddium.impl.render.chunk.occlusion;
+
+import it.unimi.dsi.fastutil.longs.Long2ReferenceMap;
+import it.unimi.dsi.fastutil.longs.Long2ReferenceOpenHashMap;
+import org.embeddedt.embeddium.impl.common.util.MathUtil;
+import org.embeddedt.embeddium.impl.render.chunk.PackedSectionMetadata;
+import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
+import org.embeddedt.embeddium.impl.render.viewport.Viewport;
+import org.embeddedt.embeddium.impl.util.PositionUtil;
+import org.jetbrains.annotations.Nullable;
+import org.joml.Vector3ic;
+
+import java.util.Arrays;
+
+/**
+ * Camera-centered spatial index backing the occlusion visibility traversal.
+ *
+ * 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. 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
+ * {@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;
+ }
+
+ /**
+ * Self-contained view of the lattice's visibility state, safe to query from
+ * a thread other than the one mutating the lattice.
+ *
+ * {@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 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);
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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. 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,
+ * 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) {
+ 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;
+ }
+ }
+
+ /**
+ * 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 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) {
+ 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;
+ }
+
+ /**
+ * 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);
+ 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);
+ }
+ }
+
+ /**
+ * 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.
+ *
+ * @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--;
+ }
+}
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 06c09955a..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,6 +58,10 @@ public final class Viewport {
);
}
+ 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);
+ }
+
public CameraTransform getTransform() {
return this.transform;
}
diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/viewport/frustum/Frustum.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/viewport/frustum/Frustum.java
index 38a96c0ca..ad9dc61d4 100644
--- a/common/src/main/java/org/embeddedt/embeddium/impl/render/viewport/frustum/Frustum.java
+++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/viewport/frustum/Frustum.java
@@ -1,5 +1,22 @@
package org.embeddedt.embeddium.impl.render.viewport.frustum;
public interface Frustum {
+ /**
+ * Returned when the box is known to be fully inside the frustum.
+ */
+ int FULLY_INSIDE = 0;
+ /**
+ * Returned when the box is at least partially within the frustum.
+ */
+ int PARTIALLY_INSIDE = 1;
+ /**
+ * Returned when the box is outside the frustum.
+ */
+ int OUTSIDE = 2;
+
boolean testAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ);
+
+ default int intersectAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
+ return testAab(minX, minY, minZ, maxX, maxY, maxZ) ? PARTIALLY_INSIDE : OUTSIDE;
+ }
}
diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/viewport/frustum/SimpleFrustum.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/viewport/frustum/SimpleFrustum.java
index d4bea1ed2..18883f924 100644
--- a/common/src/main/java/org/embeddedt/embeddium/impl/render/viewport/frustum/SimpleFrustum.java
+++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/viewport/frustum/SimpleFrustum.java
@@ -13,4 +13,13 @@ public final class SimpleFrustum implements Frustum {
public boolean testAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
return this.frustum.testAab(minX, minY, minZ, maxX, maxY, maxZ);
}
+
+ @Override
+ public int intersectAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
+ return switch (this.frustum.intersectAab(minX, minY, minZ, maxX, maxY, maxZ)) {
+ case FrustumIntersection.INSIDE -> Frustum.FULLY_INSIDE;
+ case FrustumIntersection.INTERSECT -> Frustum.PARTIALLY_INSIDE;
+ default -> Frustum.OUTSIDE;
+ };
+ }
}
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;
+ }
}
+ *
+ *
+ *
+ *
+ * The bounds include padding and floating-point slack, so a conclusive result
+ * must never incorrectly reject or accept a section.
+ *
+ *
+ *
+ * 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.
+ *
+ *