Major occlusion search optimizations #34

Merged
embeddedt merged 11 commits from occlusion-opts into stonecutter 2026-08-18 19:59:03 -04:00
9 changed files with 904 additions and 418 deletions
Showing only changes of commit 450dc85f59 - Show all commits

No files matched your search

@@ -9,9 +9,9 @@ import org.jetbrains.annotations.Nullable;
* <h2>Why</h2> * <h2>Why</h2>
* The search walks tens of thousands of sections per frame. Every field it needs off a {@link RenderSection} * 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 * (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 * flight") used to be a load off a randomly-placed object. Packed into one word they are a single load out of a
* {@code OcclusionNode}. Packed into one word they are a single load out of a flat array the traversal already * flat array the traversal already has the index for - the lattice's {@code sectionMeta}, see
* has the index for - see {@code OcclusionCuller}'s lattice - and the visitor can be handed plain ints. * {@code SectionLattice} - and the visitor can be handed plain ints.
* *
* <h2>Layout</h2> * <h2>Layout</h2>
* <pre> * <pre>
@@ -31,10 +31,9 @@ import org.jetbrains.annotations.Nullable;
* <h2>The small "meta bits" form</h2> * <h2>The small "meta bits" form</h2>
* Bits 46..52 - everything except the visibility encoding - are what the visitor actually consumes. * Bits 46..52 - everything except the visibility encoding - are what the visitor actually consumes.
* *
* <p>Note: {@link RenderSection} keeps this whole word in sync (including the visibility encoding) via * <p>Note: {@link RenderSection} is the source of truth - it keeps this whole word in sync (including the
* {@code updateCachedContextDataFlags()}, but nothing reads it back out for traversal yet - {@code OcclusionNode} * visibility encoding) via {@code updateCachedContextDataFlags()} and notifies {@code SectionLattice}, which
* still keeps its own separate copy of the visibility encoding that the search actually consumes, until the * mirrors it into the flat {@code sectionMeta} array the search reads.</p>
* traversal is migrated onto the flat lattice described above.</p>
*/ */
public final class PackedSectionMetadata { public final class PackedSectionMetadata {
private PackedSectionMetadata() { private PackedSectionMetadata() {
@@ -48,6 +47,12 @@ public final class PackedSectionMetadata {
private static final int VISUALS_FLAGS_SHIFT = 46; private static final int VISUALS_FLAGS_SHIFT = 46;
private static final long VISUALS_FLAGS_MASK = 0b111L; 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.
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: pending update type; 0 = none, otherwise ChunkUpdateType.ordinal() + 1
private static final int PENDING_UPDATE_SHIFT = 49; private static final int PENDING_UPDATE_SHIFT = 49;
private static final long PENDING_UPDATE_MASK = 0b111L; private static final long PENDING_UPDATE_MASK = 0b111L;
@@ -37,11 +37,19 @@ public class RenderSection extends AbstractSection {
private BuiltRenderSectionData contextData; private BuiltRenderSectionData contextData;
// Packed encoding of the visibility encoding, visuals flags, pending update type, and build-in-flight bit; // 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(). // see PackedSectionMetadata for the bit layout. The graph search reads a mirror of this in SectionLattice, so
// Note: OcclusionNode still keeps its own separate copy of the visibility encoding for the graph traversal - // mutate it only through writeMetadata(), which notifies the mirror.
// this field isn't consumed by the traversal yet, it's just populated ahead of that migration.
private long packedMetadata; 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 * A mapping from translucent render passes to the sort state for that particular pass (which contains data needed
* to perform a resort of the geometry as the camera moves). Will be empty for sections without any translucent * to perform a resort of the geometry as the camera moves). Will be empty for sections without any translucent
@@ -136,8 +144,24 @@ public class RenderSection extends AbstractSection {
int flags = this.contextData != null ? this.contextData.getVisualBitmaskForSection() : 0; int flags = this.contextData != null ? this.contextData.getVisualBitmaskForSection() : 0;
long visibilityData = this.contextData != null ? this.contextData.visibilityData : VisibilityEncoding.NULL; long visibilityData = this.contextData != null ? this.contextData.visibilityData : VisibilityEncoding.NULL;
this.packedMetadata = PackedSectionMetadata.withVisibilityData( this.writeMetadata(PackedSectionMetadata.withVisibilityData(
PackedSectionMetadata.withVisualsFlags(this.packedMetadata, flags), visibilityData); 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() { public int getVisualsServiceFlags() {
@@ -176,7 +200,7 @@ public class RenderSection extends AbstractSection {
public void setBuildCancellationToken(@Nullable CancellationToken token) { public void setBuildCancellationToken(@Nullable CancellationToken token) {
this.buildCancellationToken = token; this.buildCancellationToken = token;
this.packedMetadata = PackedSectionMetadata.withBuildInFlight(this.packedMetadata, token != null); this.writeMetadata(PackedSectionMetadata.withBuildInFlight(this.packedMetadata, token != null));
} }
public @Nullable ChunkUpdateType getPendingUpdate() { public @Nullable ChunkUpdateType getPendingUpdate() {
@@ -184,7 +208,7 @@ public class RenderSection extends AbstractSection {
} }
public void setPendingUpdate(@Nullable ChunkUpdateType type) { public void setPendingUpdate(@Nullable ChunkUpdateType type) {
this.packedMetadata = PackedSectionMetadata.withPendingUpdate(this.packedMetadata, type); this.writeMetadata(PackedSectionMetadata.withPendingUpdate(this.packedMetadata, type));
} }
/** /**
@@ -88,6 +88,10 @@ public abstract class RenderSectionManager {
@Nullable @Nullable
protected final RenderListManager shadowRenderListManager; protected final RenderListManager shadowRenderListManager;
// Shared by every section (one allocation, not one per section); installed on each RenderSection so its
// packedMetadata changes fan out to the list manager mirror(s).
private final RenderSection.MetadataSink metadataSink = this::pushSectionMetadata;
protected final ReferenceSet<RenderSection> sectionsWithGlobalEntities = new ReferenceOpenHashSet<>(); protected final ReferenceSet<RenderSection> sectionsWithGlobalEntities = new ReferenceOpenHashSet<>();
private final Object2ObjectOpenHashMap<TerrainRenderPass, TimerQueryManager> renderPassDrawTimers = new Object2ObjectOpenHashMap<>(); private final Object2ObjectOpenHashMap<TerrainRenderPass, TimerQueryManager> renderPassDrawTimers = new Object2ObjectOpenHashMap<>();
@@ -317,6 +321,7 @@ public abstract class RenderSectionManager {
RenderSection renderSection = new RenderSection(region, x, y, z); RenderSection renderSection = new RenderSection(region, x, y, z);
region.addSection(renderSection); region.addSection(renderSection);
renderSection.setMetadataSink(this.metadataSink);
this.sectionByPosition.put(key, renderSection); this.sectionByPosition.put(key, renderSection);
@@ -548,17 +553,21 @@ public abstract class RenderSectionManager {
render.setTranslucencySortStates(sortStates.isEmpty() ? Collections.emptyMap() : sortStates); render.setTranslucencySortStates(sortStates.isEmpty() ? Collections.emptyMap() : sortStates);
} }
// Section MetadataSink: mirrors a section's packed metadata into the graph-search lattice(s) on every
// packedMetadata mutation (visibility/visuals via setInfo, pending update, build-in-flight).
private void pushSectionMetadata(RenderSection section) {
long packed = section.getPackedMetadata();
this.renderListManager.updateSectionMetadata(section.getChunkX(), section.getChunkY(), section.getChunkZ(), packed);
if (this.shadowRenderListManager != null) {
this.shadowRenderListManager.updateSectionMetadata(section.getChunkX(), section.getChunkY(), section.getChunkZ(), packed);
}
}
@MustBeInvokedByOverriders @MustBeInvokedByOverriders
protected boolean updateSectionInfo(RenderSection render, @Nullable BuiltRenderSectionData info) { protected boolean updateSectionInfo(RenderSection render, @Nullable BuiltRenderSectionData info) {
boolean changed = render.setInfo(info); boolean changed = render.setInfo(info);
if (changed) { if (changed) {
long visibilityData = info != null ? info.visibilityData : VisibilityEncoding.NULL;
this.renderListManager.updateVisibilityData(render.getChunkX(), render.getChunkY(), render.getChunkZ(), visibilityData);
if (this.shadowRenderListManager != null) {
this.shadowRenderListManager.updateVisibilityData(render.getChunkX(), render.getChunkY(), render.getChunkZ(), visibilityData);
}
if (!(info instanceof MinecraftBuiltRenderSectionData<?, ?> data)) { if (!(info instanceof MinecraftBuiltRenderSectionData<?, ?> data)) {
this.sectionsWithGlobalEntities.remove(render); this.sectionsWithGlobalEntities.remove(render);
} else if (!data.globalBlockEntities.isEmpty()) { } else if (!data.globalBlockEntities.isEmpty()) {
@@ -25,16 +25,13 @@ public class ChunkRenderList {
this.region = region; this.region = region;
} }
public void add(RenderSection render) { public void add(int index, int flags) {
if (this.size >= RenderRegion.REGION_SIZE) { if (this.size >= RenderRegion.REGION_SIZE) {
throw new ArrayIndexOutOfBoundsException("Render list is full"); throw new ArrayIndexOutOfBoundsException("Render list is full");
} }
this.size++; this.size++;
int index = render.getSectionIndex();
int flags = render.getVisualsServiceFlags();
this.sectionsWithGeometry[this.sectionsWithGeometryCount] = (byte) index; this.sectionsWithGeometry[this.sectionsWithGeometryCount] = (byte) index;
this.sectionsWithGeometryCount += (flags >>> RenderVisualsService.HAS_BLOCK_GEOMETRY) & 1; this.sectionsWithGeometryCount += (flags >>> RenderVisualsService.HAS_BLOCK_GEOMETRY) & 1;
@@ -1,18 +1,13 @@
package org.embeddedt.embeddium.impl.render.chunk.lists; package org.embeddedt.embeddium.impl.render.chunk.lists;
import it.unimi.dsi.fastutil.longs.Long2ReferenceMap;
import it.unimi.dsi.fastutil.longs.Long2ReferenceOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.embeddedt.embeddium.impl.render.chunk.RenderSection; import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.GraphDirection; import org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionLattice;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.OcclusionCuller;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.OcclusionNode;
import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer; import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer;
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
import org.embeddedt.embeddium.impl.render.viewport.Viewport; import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.embeddedt.embeddium.impl.util.PositionUtil;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -31,12 +26,10 @@ public class RenderListManager {
@NotNull @NotNull
private ChunkRebuildLists rebuildLists; private ChunkRebuildLists rebuildLists;
private final OcclusionCuller occlusionCuller; private final SectionLattice lattice;
private final Long2ReferenceMap<OcclusionNode> occlusionNodes = new Long2ReferenceOpenHashMap<>();
// Non-null for the duration of an in-progress async graph search. Acts as a flag: // Non-null for the duration of an in-progress async graph search. Acts as a flag:
// structural mutations to occlusionNodes (attach/detach/rewire) are forbidden while set, // structural mutations to the lattice (attach/detach/rewire) are forbidden while set,
// and visibilityData updates are deferred to updateTasks rather than applied immediately. // and visibilityData updates are deferred to updateTasks rather than applied immediately.
private CompletableFuture<VisibleChunkCollector> currentOcclusionFuture; private CompletableFuture<VisibleChunkCollector> currentOcclusionFuture;
@@ -93,7 +86,7 @@ public class RenderListManager {
} else { } else {
this.asyncGraphExecutor = null; this.asyncGraphExecutor = null;
} }
this.occlusionCuller = new OcclusionCuller(this.occlusionNodes, minSectionY, maxSectionY); this.lattice = new SectionLattice(minSectionY, maxSectionY);
this.renderLists = SortedRenderLists.empty(); this.renderLists = SortedRenderLists.empty();
this.rebuildLists = ChunkRebuildLists.EMPTY; this.rebuildLists = ChunkRebuildLists.EMPTY;
} }
@@ -103,10 +96,12 @@ public class RenderListManager {
throw new IllegalStateException("Occlusion work in progress while trying to submit next task"); throw new IllegalStateException("Occlusion work in progress while trying to submit next task");
} }
var visitor = new VisibleChunkCollector(frame, regionIdsLength, targetQueueSize); var visitor = new VisibleChunkCollector(this.lattice, frame, regionIdsLength, targetQueueSize);
this.lattice.ensureWindowCovers(viewport.getChunkCoord(), searchDistance);
Supplier<VisibleChunkCollector> occlusionTask = () -> { Supplier<VisibleChunkCollector> occlusionTask = () -> {
this.occlusionCuller.findVisible(visitor, viewport, searchDistance, regionIdsLength, useOcclusionCulling, frame); this.lattice.findVisible(visitor, viewport, searchDistance, regionIdsLength, useOcclusionCulling, frame);
// WARNING: when asyncGraphExecutor != null, this runs on the async thread. // WARNING: when asyncGraphExecutor != null, this runs on the async thread.
// SectionTicker.onRenderListUpdated() must be safe to call off the render thread. // SectionTicker.onRenderListUpdated() must be safe to call off the render thread.
@@ -143,7 +138,7 @@ public class RenderListManager {
} }
// Run tasks deferred during the async search. The join() above establishes happens-before, // Run tasks deferred during the async search. The join() above establishes happens-before,
// so writes to OcclusionNode fields by the async thread are visible here. // so the async thread's writes to the lattice arrays are visible here.
Runnable task; Runnable task;
while ((task = updateTasks.poll()) != null) { while ((task = updateTasks.poll()) != null) {
@@ -170,36 +165,8 @@ public class RenderListManager {
} }
} }
private OcclusionNode getOcclusionNode(int x, int y, int z) { // Structural mutations to the lattice (adding/removing nodes, rewiring neighbor links)
return this.occlusionNodes.get(PositionUtil.packSection(x, y, z)); // are unsafe while the async search holds a reference to it via SectionLattice.
}
private void connectNeighborNodes(OcclusionNode render) {
for (int direction = 0; direction < GraphDirection.COUNT; direction++) {
OcclusionNode adj = this.getOcclusionNode(render.getChunkX() + GraphDirection.x(direction),
render.getChunkY() + GraphDirection.y(direction),
render.getChunkZ() + GraphDirection.z(direction));
if (adj != null) {
adj.setAdjacentNode(GraphDirection.opposite(direction), render);
render.setAdjacentNode(direction, adj);
}
}
}
private void disconnectNeighborNodes(OcclusionNode render) {
for (int direction = 0; direction < GraphDirection.COUNT; direction++) {
OcclusionNode adj = render.getAdjacent(direction);
if (adj != null) {
adj.setAdjacentNode(GraphDirection.opposite(direction), null);
render.setAdjacentNode(direction, null);
}
}
}
// Structural mutations to occlusionNodes (adding/removing nodes, rewiring neighbor links)
// are unsafe while the async thread holds a reference to the map via OcclusionCuller.
private void assertOcclusionNotRunning() { private void assertOcclusionNotRunning() {
if (this.currentOcclusionFuture != null) { if (this.currentOcclusionFuture != null) {
throw new IllegalStateException("Attempted to update occlusion graph during occlusion!"); throw new IllegalStateException("Attempted to update occlusion graph during occlusion!");
@@ -209,37 +176,19 @@ public class RenderListManager {
public void attachRenderSection(RenderSection section) { public void attachRenderSection(RenderSection section) {
this.assertOcclusionNotRunning(); this.assertOcclusionNotRunning();
var key = section.positionAsLong(); this.lattice.attach(section);
OcclusionNode occlusionNode = this.occlusionNodes.get(key);
if (occlusionNode != null) {
throw new IllegalStateException("Occlusion node already exists for section " + section);
}
var node = new OcclusionNode(section);
this.occlusionNodes.put(key, node);
this.connectNeighborNodes(node);
this.needsUpdate = true; this.needsUpdate = true;
} }
public void detachRenderSection(RenderSection section) { public void detachRenderSection(RenderSection section) {
this.assertOcclusionNotRunning(); this.assertOcclusionNotRunning();
var key = section.positionAsLong(); this.lattice.detach(section);
OcclusionNode occlusionNode = this.occlusionNodes.remove(key);
if (occlusionNode == null) {
throw new IllegalStateException("Occlusion node does not exist for section " + section);
}
this.disconnectNeighborNodes(occlusionNode);
this.needsUpdate = true; this.needsUpdate = true;
} }
// Runs the task immediately if no async search is active, otherwise defers it to // Runs the task immediately if no async search is active, otherwise defers it to
// finishPreviousGraphUpdate() to prevent concurrent writes to OcclusionNode fields. // finishPreviousGraphUpdate() to prevent concurrent writes to the lattice arrays.
private void submitUpdateTask(Runnable runnable) { private void submitUpdateTask(Runnable runnable) {
if (this.currentOcclusionFuture == null) { if (this.currentOcclusionFuture == null) {
runnable.run(); runnable.run();
@@ -248,28 +197,20 @@ public class RenderListManager {
} }
} }
public void updateVisibilityData(int x, int y, int z, long visibilityData) { public void updateSectionMetadata(int x, int y, int z, long packedMetadata) {
this.submitUpdateTask(() -> { this.submitUpdateTask(() -> {
var node = this.getOcclusionNode(x, y, z); if (this.lattice.updateSectionMetadata(x, y, z, packedMetadata)) {
if (node != null) {
node.setVisibilityData(visibilityData);
this.needsUpdate = true; this.needsUpdate = true;
} }
}); });
} }
public boolean isSectionVisible(int x, int y, int z) { public boolean isSectionVisible(int x, int y, int z) {
OcclusionNode render = this.getOcclusionNode(x, y, z);
if (render == null) {
return false;
}
// lastUpdatedFrame only advances in finishPreviousGraphUpdate(), so during an in-progress // lastUpdatedFrame only advances in finishPreviousGraphUpdate(), so during an in-progress
// async search this reflects the previous frame's committed result. A section can appear // async search this reflects the previous frame's committed result. A section can appear
// visible slightly early (if the async thread has already written its lastVisibleFrame for // visible slightly early (if the async thread has already written its lastVisibleFrame for
// the new frame), but can never appear invisible too early. // the new frame), but can never appear invisible too early.
return render.getLastVisibleFrame() >= this.lastUpdatedFrame; return this.lattice.isSectionVisible(x, y, z, this.lastUpdatedFrame);
} }
public void tickVisibleRenders() { public void tickVisibleRenders() {
@@ -4,12 +4,13 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import lombok.AccessLevel; import lombok.AccessLevel;
import lombok.Getter; import lombok.Getter;
import org.embeddedt.embeddium.impl.render.chunk.ChunkUpdateType; import org.embeddedt.embeddium.impl.render.chunk.ChunkUpdateType;
import org.embeddedt.embeddium.impl.render.chunk.PackedSectionMetadata;
import org.embeddedt.embeddium.impl.render.chunk.RenderSection; import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
import java.util.ArrayDeque; import java.util.ArrayDeque;
import java.util.EnumMap; import java.util.EnumMap;
import java.util.Queue; import java.util.Queue;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.OcclusionCuller; import org.embeddedt.embeddium.impl.render.chunk.occlusion.OcclusionCuller;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.OcclusionNode; import org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionLattice;
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
public class VisibleChunkCollector implements OcclusionCuller.Visitor { public class VisibleChunkCollector implements OcclusionCuller.Visitor {
@@ -23,9 +24,12 @@ public class VisibleChunkCollector implements OcclusionCuller.Visitor {
private final int targetQueueSize; private final int targetQueueSize;
private final SectionLattice lattice;
private boolean hasAdditionalUpdates; private boolean hasAdditionalUpdates;
public VisibleChunkCollector(int frame, int regionIdsLength, int targetQueueSize) { public VisibleChunkCollector(SectionLattice lattice, int frame, int regionIdsLength, int targetQueueSize) {
this.lattice = lattice;
this.frame = frame; this.frame = frame;
this.sortedRenderLists = new ObjectArrayList<>(); this.sortedRenderLists = new ObjectArrayList<>();
@@ -47,43 +51,41 @@ public class VisibleChunkCollector implements OcclusionCuller.Visitor {
} }
@Override @Override
public void visit(OcclusionNode node, boolean visible) { public void visit(int latticeIndex, int regionId, int sectionIndex, long metaBits, boolean visible) {
var section = node.getRenderSection();
// Note: even if a section does not have render objects, we must ensure the render list is initialized and put // 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. // into the sorted queue of lists, so that we maintain the correct order of draw calls.
int regionId = node.getRenderRegionId();
ChunkRenderList renderList = this.renderListsByRegion[regionId]; ChunkRenderList renderList = this.renderListsByRegion[regionId];
if (renderList == null) { if (renderList == null) {
renderList = this.createRenderList(section.getRegion()); renderList = this.createRenderList(this.lattice.sectionAt(latticeIndex).getRegion());
} }
if (visible) { if (visible) {
if (section.hasAnythingToRender()) { int visualsFlags = PackedSectionMetadata.getVisualsFlags(metaBits);
renderList.add(section); if (visualsFlags != 0) {
renderList.add(sectionIndex, visualsFlags);
} }
this.addToRebuildLists(section); ChunkUpdateType type = PackedSectionMetadata.getPendingUpdate(metaBits);
// 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)) {
this.addToRebuildLists(this.lattice.sectionAt(latticeIndex), type);
}
} }
} }
private void addToRebuildLists(RenderSection section) { private void addToRebuildLists(RenderSection section, ChunkUpdateType type) {
ChunkUpdateType type = section.getPendingUpdate(); Queue<RenderSection> queue = this.sortedRebuildLists.get(type);
// Skip sections with an in-flight build to avoid redundant work. This is an advisory // Do not limit the queue size for rebuilds
// check only: submitRebuildTasks() will validate getPendingUpdate() independently before if (type != ChunkUpdateType.INITIAL_BUILD || queue.size() < this.targetQueueSize) {
// scheduling, so a stale null read of the token here cannot cause a double submission. queue.add(section);
if (type != null && section.getBuildCancellationToken() == null) { } else {
Queue<RenderSection> queue = this.sortedRebuildLists.get(type); this.rebuildQueueOverflowCounts[type.ordinal()]++;
this.hasAdditionalUpdates = true;
// Do not limit the queue size for rebuilds
if (type != ChunkUpdateType.INITIAL_BUILD || queue.size() < this.targetQueueSize) {
queue.add(section);
} else {
this.rebuildQueueOverflowCounts[type.ordinal()]++;
this.hasAdditionalUpdates = true;
}
} }
} }
@@ -1,45 +1,133 @@
package org.embeddedt.embeddium.impl.render.chunk.occlusion; package org.embeddedt.embeddium.impl.render.chunk.occlusion;
import it.unimi.dsi.fastutil.longs.Long2ReferenceMap;
import org.embeddedt.embeddium.impl.common.util.MathUtil; import org.embeddedt.embeddium.impl.common.util.MathUtil;
import org.embeddedt.embeddium.impl.render.chunk.LocalSectionIndex;
import org.embeddedt.embeddium.impl.render.chunk.PackedSectionMetadata;
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
import org.embeddedt.embeddium.impl.render.viewport.CameraTransform; import org.embeddedt.embeddium.impl.render.viewport.CameraTransform;
import org.embeddedt.embeddium.impl.render.viewport.Viewport; import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.embeddedt.embeddium.impl.render.viewport.frustum.Frustum; import org.embeddedt.embeddium.impl.render.viewport.frustum.Frustum;
import org.embeddedt.embeddium.impl.util.PositionUtil;
import org.embeddedt.embeddium.impl.util.collections.DoubleBufferedQueue;
import org.embeddedt.embeddium.impl.util.collections.ReadQueue;
import org.embeddedt.embeddium.impl.util.collections.WriteQueue;
// TODO reintroduce
/*
import org.embeddedt.embeddium.api.render.chunk.RenderSectionDistanceFilter;
import org.embeddedt.embeddium.api.render.chunk.RenderSectionDistanceFilterEvent;
*/
import org.jetbrains.annotations.NotNull;
import org.joml.Vector3ic; import org.joml.Vector3ic;
import java.util.Arrays;
import java.util.Objects;
import static org.embeddedt.embeddium.impl.common.util.MathUtil.nearestToZero; import static org.embeddedt.embeddium.impl.common.util.MathUtil.nearestToZero;
import static org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionLattice.DIR_MASK;
import static org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionLattice.XYZ_STEP;
import static org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionLattice.XYZ_SHIFT;
import static org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionLattice.XYZ_LOCAL_MASK;
/**
* Performs a visibility search over the installed cells of a
* {@link SectionLattice}.
*
* <p>A search has four phases:
* <ol>
* <li>prepare reusable queues, visitation storage, and the region cull cache;</li>
* <li>seed the search from the camera section, or scan the appropriate
* world-height plane when the camera is outside the world or unloaded;</li>
* <li>process the queue in traversal order, applying region/frustum and
* render-distance tests before expanding visible cells through the
* occlusion graph; and</li>
* <li>replay compact visitation records to the {@link Visitor}.</li>
* </ol>
*
* <p>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.
*
* <p>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 { public class OcclusionCuller {
private final Long2ReferenceMap<OcclusionNode> sections; private final SectionLattice lattice;
private final int minSectionY, maxSectionY; private final int minSectionY, maxSectionY;
private final DoubleBufferedQueue<OcclusionNode> queue = new DoubleBufferedQueue<>(); // When stepping from a cell in dir, the neighbour is entered from the opposite face.
private static final int[] INCOMING = new int[GraphDirection.COUNT];
static {
for (int dir = 0; dir < GraphDirection.COUNT; dir++) {
INCOMING[dir] = GraphDirectionSet.of(GraphDirection.opposite(dir));
}
}
/*
* Single flat BFS queue. Each entry is
* (packedLocalXYZ << 32) | latticeIndex, where packedLocalXYZ contains
* the three 10-bit local coordinates used by SectionLattice. A live cell
* is enqueued at most once per search, so tail never exceeds
* lattice.installedCount and the queue needs no capacity check in the hot
* loop after it has been sized for the search.
*/
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(); private final RegionCullCache regionCullCache = new RegionCullCache();
private boolean isCameraInUnloadedSection; private boolean isCameraInUnloadedSection;
public OcclusionCuller(SectionLattice lattice, int minSectionY, int maxSectionY) {
public OcclusionCuller(Long2ReferenceMap<OcclusionNode> sections, int minSectionY, int maxSectionY) { this.lattice = lattice;
this.sections = sections;
this.minSectionY = minSectionY; this.minSectionY = minSectionY;
this.maxSectionY = maxSectionY; this.maxSectionY = maxSectionY;
} }
/**
* Search the current lattice and report each reached section to
* {@code visitor} in traversal order.
*
* <p>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, public void findVisible(Visitor visitor,
Viewport viewport, Viewport viewport,
float searchDistance, float searchDistance,
@@ -47,46 +135,104 @@ public class OcclusionCuller {
boolean useOcclusionCulling, boolean useOcclusionCulling,
int frame) int frame)
{ {
final var queues = this.queue; // Pre-size so enqueue/record are bare stores: at most one entry per installed cell.
queues.reset(); 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; this.regionCullCache.begin(viewport, searchDistance, numRegions);
cache.begin(viewport, searchDistance, numRegions);
this.isCameraInUnloadedSection = false; this.isCameraInUnloadedSection = false;
this.init(visitor, queues.write(), viewport, searchDistance, useOcclusionCulling, frame); this.init(viewport, searchDistance, useOcclusionCulling, frame);
if(this.isCameraInUnloadedSection) { if (this.isCameraInUnloadedSection) {
useOcclusionCulling = false; useOcclusionCulling = false;
} }
while (queues.flip()) { this.process(viewport, searchDistance, useOcclusionCulling, frame);
processQueue(visitor, viewport, searchDistance, useOcclusionCulling, frame, queues.read(), queues.write(), cache);
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, * Process the BFS queue. Each queued cell is classified once, recorded for
float searchDistance, * replay, and expanded only when it is visible. Occlusion metadata selects
boolean useOcclusionCulling, * the possible exits; the outward-direction mask then prevents moving back
int frame, * toward the camera.
ReadQueue<OcclusionNode> readQueue, */
WriteQueue<OcclusionNode> writeQueue, private void process(Viewport viewport,
RegionCullCache regionCullCache) float searchDistance,
boolean useOcclusionCulling,
int frame)
{ {
OcclusionNode section; final long[] visitState = this.lattice.visitState;
final long[] sectionMeta = this.lattice.sectionMeta;
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;
while ((section = readQueue.dequeue()) != null) { final RegionCullCache cache = this.regionCullCache;
int classification = regionCullCache.classify(section.getRenderRegionId(), section.getRegionOriginX(), section.getRegionOriginY(), section.getRegionOriginZ()); final CameraTransform transform = viewport.getTransform();
final Vector3ic camera = viewport.getChunkCoord();
final int camX = camera.x(), camY = camera.y(), camZ = camera.z();
final long frameStamp = SectionLattice.frameStamp(frame);
int head = 0;
int vtail = this.vtail;
while (head < this.tail) {
long entry = queue[head++];
int idx = (int) entry;
int xyz = (int) (entry >>> 32);
int chunkX = baseX + ((xyz >>> (2 * XYZ_SHIFT)) & XYZ_LOCAL_MASK);
int chunkY = baseY + ((xyz >>> XYZ_SHIFT) & XYZ_LOCAL_MASK);
int chunkZ = baseZ + (xyz & XYZ_LOCAL_MASK);
int classification = cache.classify(regionOfCell[idx],
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));
// Fully-inside regions need no per-section frustum test. Sections
// in a partial region are checked individually for both distance
// and frustum visibility; outside regions are not traversed.
boolean visible; boolean visible;
if (classification == Frustum.PARTIALLY_INSIDE) { if (classification == Frustum.PARTIALLY_INSIDE) {
visible = isWithinRenderDistance(viewport.getTransform(), section, searchDistance) && isWithinFrustum(viewport, section); visible = isWithinRenderDistance(transform, chunkX, chunkY, chunkZ, searchDistance)
&& isWithinFrustum(viewport, chunkX, chunkY, chunkZ);
} else { } else {
visible = classification == Frustum.FULLY_INSIDE; visible = classification == Frustum.FULLY_INSIDE;
} }
visitor.visit(section, visible); int sectionIndex = LocalSectionIndex.pack(chunkX, chunkY, chunkZ);
visitBuffer[vtail++] = packVisit(idx, sectionIndex, visible);
if (!visible) { if (!visible) {
continue; continue;
@@ -94,121 +240,119 @@ public class OcclusionCuller {
int connections; int connections;
{ if (useOcclusionCulling) {
if (useOcclusionCulling) { // Merge the outgoing paths reachable from every incoming path
// When using occlusion culling, we can only traverse into neighbors for which there is a path of // accumulated in this cell.
// visibility through this chunk. This is determined by taking all the incoming paths to this chunk and int incoming = (int) (visitState[idx] & DIR_MASK);
// creating a union of the outgoing paths from those. connections = VisibilityEncoding.getConnections(
connections = VisibilityEncoding.getConnections(section.getVisibilityData(), section.getIncomingDirections()); sectionMeta[idx] & PackedSectionMetadata.VISIBILITY_MASK, incoming);
} else { } else {
// Not using any occlusion culling, so traversing in any direction is legal. connections = GraphDirectionSet.ALL;
connections = GraphDirectionSet.ALL;
}
// We can only traverse *outwards* from the center of the graph search, so mask off any invalid
// directions.
connections &= getOutwardDirections(viewport.getChunkCoord(), section);
} }
visitNeighbors(writeQueue, section, connections, frame); // 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);
}
this.vtail = vtail;
}
// Visit each selected neighbour using both its linear array offset and
// its packed-coordinate offset. The lattice border makes idx + delta safe.
private void visitNeighbors(long[] visitState, long[] queue, int[] delta, int idx, int xyz, int outgoing, long frameStamp) {
while (outgoing != 0) {
int dir = Integer.numberOfTrailingZeros(outgoing);
outgoing &= outgoing - 1;
this.visitNode(visitState, queue, idx + delta[dir], xyz + XYZ_STEP[dir], INCOMING[dir], frameStamp);
} }
} }
private static void visitNeighbors(final WriteQueue<OcclusionNode> queue, OcclusionNode section, int outgoing, int frame) { /*
// Only traverse into neighbors which are actually present. * Ordered-compare visit gate. A slot is enqueued only on its first visit
// This avoids a null-check on each invocation to enqueue, and since the compiler will see that a null * this frame, while incoming directions are OR-ed even on later visits so
// is never encountered (after profiling), it will optimize it away. * the cell sees the union of all reachable entry paths. SENTINEL cells,
outgoing &= section.getAdjacentMask(); * including the border ring, never compare below frameStamp and therefore
* need no separate occupancy check.
*/
private void visitNode(long[] visitState, long[] queue, int idx, int xyz, int incoming, long frameStamp) {
long state = visitState[idx];
// Check if there are any valid connections left, and if not, early-exit. if (state < frameStamp) {
if (outgoing == GraphDirectionSet.NONE) { visitState[idx] = frameStamp | incoming;
return; queue[this.tail++] = ((long) xyz << 32) | (idx & 0xFFFFFFFFL);
} } else {
visitState[idx] = state | incoming;
// This helps the compiler move the checks for some invariants upwards.
queue.ensureCapacity(6);
if (GraphDirectionSet.contains(outgoing, GraphDirection.DOWN)) {
visitNode(queue, section.adjacentDown, GraphDirectionSet.of(GraphDirection.UP), frame);
}
if (GraphDirectionSet.contains(outgoing, GraphDirection.UP)) {
visitNode(queue, section.adjacentUp, GraphDirectionSet.of(GraphDirection.DOWN), frame);
}
if (GraphDirectionSet.contains(outgoing, GraphDirection.NORTH)) {
visitNode(queue, section.adjacentNorth, GraphDirectionSet.of(GraphDirection.SOUTH), frame);
}
if (GraphDirectionSet.contains(outgoing, GraphDirection.SOUTH)) {
visitNode(queue, section.adjacentSouth, GraphDirectionSet.of(GraphDirection.NORTH), frame);
}
if (GraphDirectionSet.contains(outgoing, GraphDirection.WEST)) {
visitNode(queue, section.adjacentWest, GraphDirectionSet.of(GraphDirection.EAST), frame);
}
if (GraphDirectionSet.contains(outgoing, GraphDirection.EAST)) {
visitNode(queue, section.adjacentEast, GraphDirectionSet.of(GraphDirection.WEST), frame);
} }
} }
private static void visitNode(final WriteQueue<OcclusionNode> queue, @NotNull OcclusionNode render, int incoming, int frame) { // Allow movement only away from the camera on each axis. A coordinate
if (render.getLastVisibleFrame() != frame) { // equal to the camera coordinate permits both directions on that axis.
// This is the first time we are visiting this section during the given frame, so we must private static int getOutwardDirections(int chunkX, int chunkY, int chunkZ, int camX, int camY, int camZ) {
// reset the state.
render.setLastVisibleFrame(frame);
render.setIncomingDirections(GraphDirectionSet.NONE);
queue.enqueue(render);
}
render.addIncomingDirections(incoming);
}
private static int getOutwardDirections(Vector3ic origin, OcclusionNode section) {
int planes = 0; int planes = 0;
planes |= section.getChunkX() <= origin.x() ? 1 << GraphDirection.WEST : 0; planes |= chunkX <= camX ? 1 << GraphDirection.WEST : 0;
planes |= section.getChunkX() >= origin.x() ? 1 << GraphDirection.EAST : 0; planes |= chunkX >= camX ? 1 << GraphDirection.EAST : 0;
planes |= section.getChunkY() <= origin.y() ? 1 << GraphDirection.DOWN : 0; planes |= chunkY <= camY ? 1 << GraphDirection.DOWN : 0;
planes |= section.getChunkY() >= origin.y() ? 1 << GraphDirection.UP : 0; planes |= chunkY >= camY ? 1 << GraphDirection.UP : 0;
planes |= section.getChunkZ() <= origin.z() ? 1 << GraphDirection.NORTH : 0; planes |= chunkZ <= camZ ? 1 << GraphDirection.NORTH : 0;
planes |= section.getChunkZ() >= origin.z() ? 1 << GraphDirection.SOUTH : 0; planes |= chunkZ >= camZ ? 1 << GraphDirection.SOUTH : 0;
return planes; return planes;
} }
private static boolean isWithinRenderDistance(CameraTransform camera, OcclusionNode section, float maxDistance) { // Convert a section coordinate to the origin of its containing render
// origin point of the chunk's bounding box (in view space) // region, in block coordinates.
int ox = section.getOriginX() - camera.intX; private static int regionOrigin(int chunkCoord, int shift, int blockSize) {
int oy = section.getOriginY() - camera.intY; return (chunkCoord >> shift) * blockSize;
int oz = section.getOriginZ() - camera.intZ; }
// coordinates of the point to compare (in view space) /**
// this is the closest point within the bounding box to the center (0, 0, 0) * Test the search's render-distance shape against a section bounding box.
* Horizontal distance is circular in X/Z, while vertical distance is
* tested independently so tall searches do not use a spherical cutoff.
*/
private static boolean isWithinRenderDistance(CameraTransform camera, int chunkX, int chunkY, int chunkZ, float maxDistance) {
// Origin point of the chunk's bounding box in view space.
int ox = (chunkX << 4) - camera.intX;
int oy = (chunkY << 4) - camera.intY;
int oz = (chunkZ << 4) - camera.intZ;
// Closest point within the bounding box to the camera at (0, 0, 0).
// Testing the closest point avoids rejecting a section whose near face
// is within range even when its origin is farther away.
float dx = nearestToZero(ox, ox + 16) - camera.fracX; float dx = nearestToZero(ox, ox + 16) - camera.fracX;
float dy = nearestToZero(oy, oy + 16) - camera.fracY; float dy = nearestToZero(oy, oy + 16) - camera.fracY;
float dz = nearestToZero(oz, oz + 16) - camera.fracZ; float dz = nearestToZero(oz, oz + 16) - camera.fracZ;
return ((((dx * dx) + (dz * dz)) < (maxDistance * maxDistance)) && (Math.abs(dy) < maxDistance)); return ((((dx * dx) + (dz * dz)) < (maxDistance * maxDistance)) && (Math.abs(dy) < maxDistance));
//return DistanceFilterHolder.INSTANCE.isWithinDistance(dx, dy, dz, maxDistance);
} }
// The bounding box of a chunk section must be large enough to contain all possible geometry within it. Block models // isBoxVisible takes a section centre and half-size. The half-size is
// can extend outside a block volume by +/- 1.0 blocks on all axis. Additionally, we make use of a small epsilon // 8 blocks for the section, plus model overhang and a small precision
// to deal with floating point imprecision during a frustum check (see GH#2132). // epsilon (see GH#2132).
private static final float CHUNK_SECTION_SIZE = 8.0f /* chunk bounds */ + 1.0f /* maximum model extent */ + 0.125f /* epsilon */; private static final float CHUNK_SECTION_SIZE = 8.0f /* section half-size */
+ 1.0f /* maximum model extent */
+ 0.125f /* epsilon */;
public static boolean isWithinFrustum(Viewport viewport, OcclusionNode section) { /**
return viewport.isBoxVisible(section.getCenterX(), section.getCenterY(), section.getCenterZ(), CHUNK_SECTION_SIZE); * Test a section's conservatively expanded bounding box against the
* viewport frustum.
*/
public static boolean isWithinFrustum(Viewport viewport, int chunkX, int chunkY, int chunkZ) {
return viewport.isBoxVisible((chunkX << 4) + 8, (chunkY << 4) + 8, (chunkZ << 4) + 8, CHUNK_SECTION_SIZE);
} }
private void init(Visitor visitor, /**
WriteQueue<OcclusionNode> queue, * Choose the search seed. A loaded in-world camera section is processed
Viewport viewport, * inline; an out-of-height or unloaded camera is handled by scanning a
* horizontal plane of nearby loaded sections.
*/
private void init(Viewport viewport,
float searchDistance, float searchDistance,
boolean useOcclusionCulling, boolean useOcclusionCulling,
int frame) int frame)
@@ -216,131 +360,155 @@ public class OcclusionCuller {
var origin = viewport.getChunkCoord(); var origin = viewport.getChunkCoord();
if (origin.y() < this.minSectionY) { if (origin.y() < this.minSectionY) {
// below the world // Below the world: seed the lowest section with an incoming path
this.initOutsideWorldHeight(queue, viewport, searchDistance, frame, // from below so traversal can proceed upward from the boundary.
this.initOutsideWorldHeight(viewport, searchDistance, frame,
this.minSectionY, GraphDirectionSet.of(GraphDirection.DOWN)); this.minSectionY, GraphDirectionSet.of(GraphDirection.DOWN));
} else if (origin.y() >= this.maxSectionY) { } else if (origin.y() >= this.maxSectionY) {
// above the world // Above the world: seed the highest section with an incoming path
this.initOutsideWorldHeight(queue, viewport, searchDistance, frame, // from above so traversal can proceed downward from the boundary.
this.initOutsideWorldHeight(viewport, searchDistance, frame,
this.maxSectionY - 1, GraphDirectionSet.of(GraphDirection.UP)); this.maxSectionY - 1, GraphDirectionSet.of(GraphDirection.UP));
} else if(this.getRenderSection(origin.x(), origin.y(), origin.z()) == null) { } else if (this.lattice.getRenderSection(origin.x(), origin.y(), origin.z()) == null) {
// inside the world height-wise, but in an unloaded section // Inside the world height-wise, but in an unloaded section. Seed
this.initOutsideWorldHeight(queue, viewport, searchDistance, frame, // both vertical entry paths and disable occlusion below because
// there is no camera section from which to obtain visibility data.
this.initOutsideWorldHeight(viewport, searchDistance, frame,
origin.y(), GraphDirectionSet.of(GraphDirection.UP) | GraphDirectionSet.of(GraphDirection.DOWN)); origin.y(), GraphDirectionSet.of(GraphDirection.UP) | GraphDirectionSet.of(GraphDirection.DOWN));
this.isCameraInUnloadedSection = true; this.isCameraInUnloadedSection = true;
} else { } else {
this.initWithinWorld(visitor, queue, viewport, useOcclusionCulling, frame); this.initWithinWorld(viewport, useOcclusionCulling, frame);
} }
} }
private void initWithinWorld(Visitor visitor, WriteQueue<OcclusionNode> queue, Viewport viewport, boolean useOcclusionCulling, int frame) { // The loaded camera section is the root: it is recorded immediately, not
// queued, and its visible paths seed the BFS with no incoming direction.
private void initWithinWorld(Viewport viewport, boolean useOcclusionCulling, int frame) {
final long[] visitState = this.lattice.visitState;
final long[] queue = this.queue;
final int[] delta = this.lattice.delta;
var origin = viewport.getChunkCoord(); var origin = viewport.getChunkCoord();
var section = this.getRenderSection(origin.x(), origin.y(), origin.z()); int idx = this.lattice.indexOf(origin.x(), origin.y(), origin.z());
Objects.requireNonNull(section); // The camera section is loaded and, after ensureWindowCovers, installed
// in the lattice interior.
long frameStamp = SectionLattice.frameStamp(frame);
visitState[idx] = frameStamp;
section.setLastVisibleFrame(frame); // Record the origin as visited; it is processed inline rather than
section.setIncomingDirections(GraphDirectionSet.NONE); // enqueued so the BFS starts with its neighbours.
int sectionIndex = LocalSectionIndex.pack(origin.x(), origin.y(), origin.z());
visitor.visit(section, true); this.visitBuffer[this.vtail++] = packVisit(idx, sectionIndex, true);
int outgoing; int outgoing;
if (useOcclusionCulling) { if (useOcclusionCulling) {
// Since the camera is located inside this chunk, there are no "incoming" directions. So we need to instead // The camera is inside this chunk, so there are no incoming directions; enqueue any path out.
// find any possible paths out of this chunk and enqueue those neighbors. outgoing = VisibilityEncoding.getConnections(
outgoing = VisibilityEncoding.getConnections(section.getVisibilityData()); this.lattice.sectionMeta[idx] & PackedSectionMetadata.VISIBILITY_MASK);
} else { } else {
// Occlusion culling is disabled, so we can traverse into any neighbor.
outgoing = GraphDirectionSet.ALL; outgoing = GraphDirectionSet.ALL;
} }
visitNeighbors(queue, section, outgoing, frame); int xyz = this.lattice.packXyz(origin.x(), origin.y(), origin.z());
this.visitNeighbors(visitState, queue, delta, idx, xyz, outgoing, frameStamp);
} }
// Enqueues sections that are inside the viewport using diamond spiral iteration to avoid sorting and ensure a /**
// consistent order. Innermost layers are enqueued first. Within each layer, iteration starts at the northernmost * Seed a boundary plane with nearby loaded sections in deterministic
// section and proceeds counterclockwise (N->W->S->E). * diamond-spiral order. The complete inner layers cover Manhattan distance
private void initOutsideWorldHeight(WriteQueue<OcclusionNode> queue, * through {@code radius}; the remaining layers fill the surrounding square
Viewport viewport, * out to the same X/Z radius without sorting. Each accepted section is
* given the supplied incoming direction set before normal BFS processing.
*/
private void initOutsideWorldHeight(Viewport viewport,
float searchDistance, float searchDistance,
int frame, int frame,
int height, int height,
int direction) int direction)
{ {
final long[] visitState = this.lattice.visitState;
final long[] queue = this.queue;
var origin = viewport.getChunkCoord(); var origin = viewport.getChunkCoord();
var radius = MathUtil.mojfloor(searchDistance / 16.0f); var radius = MathUtil.mojfloor(searchDistance / 16.0f);
long frameStamp = SectionLattice.frameStamp(frame);
// Layer 0 // Layer 0: the section directly below/above the camera, if loaded and visible.
this.tryVisitNode(queue, origin.x(), height, origin.z(), direction, frame, viewport); this.tryVisitNode(visitState, queue, origin.x(), height, origin.z(), direction, frameStamp, viewport);
// Complete layers, excluding layer 0 // Complete inner layers, excluding layer 0.
for (int layer = 1; layer <= radius; layer++) { for (int layer = 1; layer <= radius; layer++) {
for (int z = -layer; z < layer; z++) { for (int z = -layer; z < layer; z++) {
int x = Math.abs(z) - layer; int x = Math.abs(z) - layer;
this.tryVisitNode(queue, origin.x() + x, height, origin.z() + z, direction, frame, viewport); this.tryVisitNode(visitState, queue, origin.x() + x, height, origin.z() + z, direction, frameStamp, viewport);
} }
for (int z = layer; z > -layer; z--) { for (int z = layer; z > -layer; z--) {
int x = layer - Math.abs(z); int x = layer - Math.abs(z);
this.tryVisitNode(queue, origin.x() + x, height, origin.z() + z, direction, frame, viewport); this.tryVisitNode(visitState, queue, origin.x() + x, height, origin.z() + z, direction, frameStamp, viewport);
} }
} }
// Incomplete layers // Complete the surrounding square with the outer portions of the
// remaining diamond layers.
for (int layer = radius + 1; layer <= 2 * radius; layer++) { for (int layer = radius + 1; layer <= 2 * radius; layer++) {
int l = layer - radius; int l = layer - radius;
for (int z = -radius; z <= -l; z++) { for (int z = -radius; z <= -l; z++) {
int x = -z - layer; int x = -z - layer;
this.tryVisitNode(queue, origin.x() + x, height, origin.z() + z, direction, frame, viewport); this.tryVisitNode(visitState, queue, origin.x() + x, height, origin.z() + z, direction, frameStamp, viewport);
} }
for (int z = l; z <= radius; z++) { for (int z = l; z <= radius; z++) {
int x = z - layer; int x = z - layer;
this.tryVisitNode(queue, origin.x() + x, height, origin.z() + z, direction, frame, viewport); this.tryVisitNode(visitState, queue, origin.x() + x, height, origin.z() + z, direction, frameStamp, viewport);
} }
for (int z = radius; z >= l; z--) { for (int z = radius; z >= l; z--) {
int x = layer - z; int x = layer - z;
this.tryVisitNode(queue, origin.x() + x, height, origin.z() + z, direction, frame, viewport); this.tryVisitNode(visitState, queue, origin.x() + x, height, origin.z() + z, direction, frameStamp, viewport);
} }
for (int z = -l; z >= -radius; z--) { for (int z = -l; z >= -radius; z--) {
int x = layer + z; int x = layer + z;
this.tryVisitNode(queue, origin.x() + x, height, origin.z() + z, direction, frame, viewport); this.tryVisitNode(visitState, queue, origin.x() + x, height, origin.z() + z, direction, frameStamp, viewport);
} }
} }
} }
private void tryVisitNode(WriteQueue<OcclusionNode> queue, int x, int y, int z, int direction, int frame, Viewport viewport) { // Seed-only visit: reject unloaded/out-of-window cells before doing a
OcclusionNode section = this.getRenderSection(x, y, z); // frustum test, then pass the accepted cell through the normal visit gate.
private void tryVisitNode(long[] visitState, long[] queue, int x, int y, int z, int direction, long frameStamp, Viewport viewport) {
int idx = this.lattice.indexOf(x, y, z);
if (section == null || !isWithinFrustum(viewport, section)) { // Out of the window or empty: visitNode would reject SENTINEL anyway,
// but avoid the frustum test for cells that cannot be searched.
if (idx < 0 || visitState[idx] == SectionLattice.SENTINEL) {
return; return;
} }
visitNode(queue, section, direction, frame); if (!isWithinFrustum(viewport, x, y, z)) {
} return;
private OcclusionNode getRenderSection(int x, int y, int z) {
return this.sections.get(PositionUtil.packSection(x, y, z));
}
public interface Visitor {
void visit(OcclusionNode section, boolean visible);
}
/*
private static class DistanceFilterHolder {
private static final RenderSectionDistanceFilter INSTANCE;
static {
var event = new RenderSectionDistanceFilterEvent();
RenderSectionDistanceFilterEvent.BUS.post(event);
INSTANCE = event.getFilter();
} }
this.visitNode(visitState, queue, idx, this.lattice.packXyz(x, y, z), direction, frameStamp);
} }
/**
* Receives one record for each section reached by a search, in traversal
* order. A record can be non-visible: such a section is reported for
* ordering/region bookkeeping but does not expand the search.
*/ */
public interface Visitor {
/**
* @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 visible whether the section passed the visibility tests
*/
void visit(int latticeIndex, int regionId, int sectionIndex, long metaBits, boolean visible);
}
} }
@@ -1,108 +0,0 @@
package org.embeddedt.embeddium.impl.render.chunk.occlusion;
import lombok.Getter;
import lombok.Setter;
import org.embeddedt.embeddium.impl.render.chunk.AbstractSection;
import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
public final class OcclusionNode extends AbstractSection {
private int incomingDirections;
private int lastVisibleFrame = -1;
private int adjacentMask;
public OcclusionNode
adjacentDown,
adjacentUp,
adjacentNorth,
adjacentSouth,
adjacentWest,
adjacentEast;
/**
* The occlusion culling data which determines this chunk's connectedness on the visibility graph.
*/
@Getter
@Setter
private long visibilityData = VisibilityEncoding.NULL;
private final RenderSection section;
@Getter
private final int renderRegionId;
public OcclusionNode(RenderSection section) {
super(section.getChunkX(), section.getChunkY(), section.getChunkZ());
this.section = section;
this.renderRegionId = section.getRegion().getId();
}
public OcclusionNode getAdjacent(int direction) {
return switch (direction) {
case GraphDirection.DOWN -> this.adjacentDown;
case GraphDirection.UP -> this.adjacentUp;
case GraphDirection.NORTH -> this.adjacentNorth;
case GraphDirection.SOUTH -> this.adjacentSouth;
case GraphDirection.WEST -> this.adjacentWest;
case GraphDirection.EAST -> this.adjacentEast;
default -> null;
};
}
public void setAdjacentNode(int direction, OcclusionNode node) {
if (node == null) {
this.adjacentMask &= ~GraphDirectionSet.of(direction);
} else {
this.adjacentMask |= GraphDirectionSet.of(direction);
}
switch (direction) {
case GraphDirection.DOWN -> this.adjacentDown = node;
case GraphDirection.UP -> this.adjacentUp = node;
case GraphDirection.NORTH -> this.adjacentNorth = node;
case GraphDirection.SOUTH -> this.adjacentSouth = node;
case GraphDirection.WEST -> this.adjacentWest = node;
case GraphDirection.EAST -> this.adjacentEast = node;
default -> { }
}
}
public int getAdjacentMask() {
return this.adjacentMask;
}
public void setLastVisibleFrame(int frame) {
this.lastVisibleFrame = frame;
}
public int getLastVisibleFrame() {
return this.lastVisibleFrame;
}
public int getIncomingDirections() {
return this.incomingDirections;
}
public void addIncomingDirections(int directions) {
this.incomingDirections |= directions;
}
public void setIncomingDirections(int directions) {
this.incomingDirections = directions;
}
public RenderSection getRenderSection() {
return this.section;
}
public int getRegionOriginX() {
return (this.getChunkX() >> RenderRegion.REGION_WIDTH_SH) * RenderRegion.REGION_BLOCK_WIDTH;
}
public int getRegionOriginY() {
return (this.getChunkY() >> RenderRegion.REGION_HEIGHT_SH) * RenderRegion.REGION_BLOCK_HEIGHT;
}
public int getRegionOriginZ() {
return (this.getChunkZ() >> RenderRegion.REGION_LENGTH_SH) * RenderRegion.REGION_BLOCK_LENGTH;
}
}
@@ -0,0 +1,448 @@
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.
*
* <p>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.
*
* <p>This class has two layers of state:
* <ul>
* <li>{@code sections} is the authoritative set of every attached section.
* It is used for world-coordinate lookup and for rebuilding the window.</li>
* <li>The lattice is a dense X/Z window containing the attached sections
* that can participate in the current search. A section outside that
* window remains attached, but has no lattice slot until a rebase brings
* it inside the window.</li>
* </ul>
* 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.
*
* <p>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.
*
* <p>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.
*
* <p>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<RenderSection> sections = new Long2ReferenceOpenHashMap<>();
private final OcclusionCuller culler;
private final int minSectionY, maxSectionY;
/*
* Parallel primitive/object arrays, allocated lazily once the search
* distance determines the X/Z dimensions. The linear index is
* (lx * dimZ + lz) * dimY + ly, where local coordinates are relative to
* (baseX, baseY, baseZ). Package-private visibility lets OcclusionCuller
* read these arrays directly on its hot path.
*
* Invariants:
* - only local coordinates [1, dim-2] are installable;
* - the outer ring is always SENTINEL and has no section or metadata;
* - all parallel arrays describe the same cell;
* - installedCount equals the number of non-null latticeSection entries.
*/
long[] visitState;
long[] sectionMeta;
int[] regionOfCell;
RenderSection[] latticeSection;
// Y is never windowed: the complete world height plus one sentinel cell at each vertical edge.
final int dimY;
final int baseY;
int dimX, dimZ;
// baseX/baseZ become meaningful after the first rebase; baseY is fixed by the world-height bounds.
int baseX, baseZ;
// Linear offset for one neighbour step in each direction; the sentinel border makes every step safe.
final int[] delta = new int[GraphDirection.COUNT];
private int strideX, strideZ;
// True when the current dimensions, base coordinates, and installed placement are ready for a search.
private boolean established;
// Number of sections currently installed in the lattice, not total attached sections.
int installedCount;
public SectionLattice(int minSectionY, int maxSectionY) {
this.minSectionY = minSectionY;
this.maxSectionY = maxSectionY;
this.baseY = minSectionY - 1;
this.dimY = (maxSectionY - minSectionY) + 2;
this.culler = new OcclusionCuller(this, minSectionY, maxSectionY);
if (this.dimY > MAX_DIM) {
throw new IllegalStateException("World height " + this.dimY + " exceeds occlusion lattice limit " + MAX_DIM);
}
}
/**
* Returns the attached section at a world position, regardless of whether
* it currently has an installed lattice slot.
*
* @return the authoritative section at the position, or {@code null} if
* no section is attached
*/
@Nullable
public RenderSection getRenderSection(int x, int y, int z) {
return this.sections.get(PositionUtil.packSection(x, y, z));
}
/**
* Attach a section to the authoritative collection and install it when
* the lattice has been allocated and the section lies in its interior.
* Attaching before the first window allocation is valid; the section will
* be installed by the next allocation or rebase that covers it.
*/
public void attach(RenderSection section) {
var key = section.positionAsLong();
if (this.sections.get(key) != null) {
throw new IllegalStateException("Section already attached to lattice: " + section);
}
this.sections.put(key, section);
this.install(section);
}
/**
* Detach a section from the authoritative collection and remove its
* lattice slot, if it is currently installed.
*/
public void detach(RenderSection section) {
var key = section.positionAsLong();
RenderSection removed = this.sections.remove(key);
if (removed == null) {
throw new IllegalStateException("Section not attached to lattice: " + section);
}
this.uninstall(section);
}
/**
* Mirror a section's full packed metadata word into its slot.
*
* @return true if the change altered the graph search's output (see {@link PackedSectionMetadata#GRAPH_INPUT_MASK})
* and a re-search is therefore warranted
*/
public boolean updateSectionMetadata(int x, int y, int z, long packedMetadata) {
int idx = this.installedIndex(x, y, z);
if (idx < 0) {
// Not installed (unloaded, no window yet, or outside the current
// window): it is not traversed, and its metadata is read fresh
// from the section when it is eventually installed.
return false;
}
long previous = this.sectionMeta[idx];
this.sectionMeta[idx] = packedMetadata;
return ((previous ^ packedMetadata) & PackedSectionMetadata.GRAPH_INPUT_MASK) != 0;
}
/**
* Returns the section installed at a lattice index.
*
* <p>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.
*
* <p>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.
*
* <p>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.
*
* <p>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.
*
* <p>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--;
}
}