From 4f9b82400068388b8388cb77f8404b5a2f39f34e Mon Sep 17 00:00:00 2001 From: rdh Date: Tue, 8 Sep 2026 16:06:28 -0400 Subject: [PATCH 01/23] cleanup and restructuring --- .../impl/render/chunk/RenderSection.java | 41 ++++---- .../render/chunk/RenderSectionManager.java | 63 ++++-------- .../chunk/compile/ChunkBuildBuffers.java | 7 +- .../compile/sorting/ChunkPrimitiveType.java | 4 +- .../compile/sorting/QuadPrimitiveType.java | 72 ++------------ .../compile/tasks/ChunkBuilderSortTask.java | 12 +-- .../chunk/data/BuiltSectionMeshParts.java | 4 +- .../render/chunk/lists/RenderListManager.java | 20 ++-- .../impl/render/chunk/sorting/SortState.java | 77 +++++++++++++++ .../sorting/TranslucentQuadAnalyzer.java | 95 ++++--------------- .../chunk/sorting/TranslucentSorter.java | 76 +++++++++++++++ .../builder/ChunkMeshBufferBuilder.java | 3 +- 12 files changed, 243 insertions(+), 231 deletions(-) create mode 100644 common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/SortState.java create mode 100644 common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java 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 db4eceffe..28b4d3ffd 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 @@ -8,7 +8,7 @@ import org.embeddedt.embeddium.impl.render.chunk.occlusion.VisibilityEncoding; import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; import org.embeddedt.embeddium.impl.util.task.CancellationToken; -import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer; +import org.embeddedt.embeddium.impl.render.chunk.sorting.SortState; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -50,17 +50,24 @@ public class RenderSection extends AbstractSection { void onMetadataChanged(RenderSection section); } + /** Marks a section with no translucent render passes at all, which the debug overlay does not count */ + public static final int NO_TRANSLUCENT_GEOMETRY = -1; + /** - * 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 - * render passes. + * A mapping from translucent render passes to the sort state for that particular pass, holding the data needed to + * resort that pass' geometry as the camera moves. Only passes that actually need resorting appear here, so this is + * empty for sections whose translucent geometry (if any) was sorted once at mesh time. */ @Getter @NotNull - private Map translucencySortStates = Collections.emptyMap(); + private Map translucencySortStates = Collections.emptyMap(); + /** + * The {@link SortState#debugIndex()} of the most expensive sort among this section's translucent passes, or + * {@link #NO_TRANSLUCENT_GEOMETRY} if it has none. Only consumed by the debug overlay. + */ @Getter - private TranslucentQuadAnalyzer.Level highestSortingLevel = TranslucentQuadAnalyzer.Level.NONE; + private int highestSortingIndex = NO_TRANSLUCENT_GEOMETRY; @Getter @Setter @@ -179,22 +186,14 @@ public class RenderSection extends AbstractSection { return this.getVisualsServiceFlags() != 0; } - public void setTranslucencySortStates(@NotNull Map sortStates) { + /** + * @param sortStates the passes needing a resort as the camera moves; every entry implies dynamic sorting + * @param highestSortingIndex the highest variant seen before compaction, or {@link #NO_TRANSLUCENT_GEOMETRY} + */ + public void setTranslucencySortStates(@NotNull Map sortStates, int highestSortingIndex) { this.translucencySortStates = Map.copyOf(sortStates); - - TranslucentQuadAnalyzer.Level level = TranslucentQuadAnalyzer.Level.NONE; - boolean needsDynamicSorting = false; - - if (!sortStates.isEmpty()) { - // Find highest level among all sort states - for (TranslucentQuadAnalyzer.SortState state : sortStates.values()) { - level = state.level().ordinal() > level.ordinal() ? state.level() : level; - needsDynamicSorting |= state.requiresDynamicSorting(); - } - } - - this.highestSortingLevel = level; - this.needsDynamicTranslucencySorting = needsDynamicSorting; + this.highestSortingIndex = highestSortingIndex; + this.needsDynamicTranslucencySorting = !sortStates.isEmpty(); } public @Nullable CancellationToken getBuildCancellationToken() { diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java index b237bfe54..1e47362d0 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java @@ -28,7 +28,6 @@ import org.embeddedt.embeddium.impl.render.chunk.lists.SectionTicker; import org.embeddedt.embeddium.impl.render.chunk.lists.SortedRenderLists; import org.embeddedt.embeddium.impl.render.chunk.metrics.RenderSectionMetricsTracker; import org.embeddedt.embeddium.impl.render.chunk.occlusion.AsyncOcclusionMode; -import org.embeddedt.embeddium.impl.render.chunk.occlusion.VisibilityEncoding; import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegionManager; import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderFogComponent; @@ -39,7 +38,7 @@ import org.embeddedt.embeddium.impl.render.viewport.Viewport; import org.embeddedt.embeddium.impl.render.viewport.frustum.ShadowSearchFrustum; import org.embeddedt.embeddium.impl.util.PositionUtil; import org.embeddedt.embeddium.impl.util.iterator.ByteIterator; -import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer; +import org.embeddedt.embeddium.impl.render.chunk.sorting.SortState; import org.embeddedt.embeddium.impl.util.suppliers.ExpiringSupplier; import org.jetbrains.annotations.MustBeInvokedByOverriders; import org.jetbrains.annotations.Nullable; @@ -600,13 +599,25 @@ public abstract class RenderSectionManager { } private void updateTranslucencyInfo(RenderSection render, Map meshes) { - Map sortStates = new Reference2ObjectArrayMap<>(); + Map sortStates = new Reference2ObjectArrayMap<>(); + int highestIndex = RenderSection.NO_TRANSLUCENT_GEOMETRY; + for(var entry : meshes.entrySet()) { - if(entry.getKey().isSorted()) { - sortStates.put(entry.getKey(), Objects.requireNonNull(entry.getValue().sortState()).compactForStorage()); + if(!entry.getKey().isSorted()) { + continue; + } + + var state = Objects.requireNonNull(entry.getValue().sortState()); + + highestIndex = Math.max(highestIndex, state.debugIndex()); + + // Only resortable states survive compaction; everything else is already in its final order. + if(state.compactForStorage() instanceof SortState.Resortable resortable) { + sortStates.put(entry.getKey(), resortable); } } - render.setTranslucencySortStates(sortStates.isEmpty() ? Collections.emptyMap() : sortStates); + + render.setTranslucencySortStates(sortStates.isEmpty() ? Collections.emptyMap() : sortStates, highestIndex); } // Section MetadataSink: mirrors a section's packed metadata into the graph-search lattice on every @@ -965,46 +976,6 @@ public abstract class RenderSectionManager { return Collections.unmodifiableCollection(this.sectionByPosition.values()); } - private Collection getSortingStrings() { - List list = new ArrayList<>(); - - int[] sectionCounts = new int[TranslucentQuadAnalyzer.Level.VALUES.length]; - - for (Iterator it = this.getCurrentRenderListManager().getRenderLists().iterator(); it.hasNext(); ) { - var renderList = it.next(); - var region = renderList.getRegion(); - var listIter = renderList.sectionsWithGeometryIterator(); - if(listIter != null) { - while(listIter.hasNext()) { - RenderSection section = region.getSection(listIter.nextByteAsInt()); - // Do not count sections without translucent data - if(section == null || section.getTranslucencySortStates().isEmpty()) { - continue; - } - - sectionCounts[section.getHighestSortingLevel().ordinal()]++; - } - } - } - - StringBuilder sb = new StringBuilder(); - sb.append("Sorting: "); - TranslucentQuadAnalyzer.Level[] values = TranslucentQuadAnalyzer.Level.VALUES; - for (int i = 0; i < values.length; i++) { - TranslucentQuadAnalyzer.Level level = values[i]; - sb.append(level.name()); - sb.append('='); - sb.append(sectionCounts[level.ordinal()]); - if((i + 1) < values.length) { - sb.append(", "); - } - } - - list.add(sb.toString()); - - return list; - } - private Object2LongMap computeRenderPassTimingsMap() { Object2LongOpenHashMap map = new Object2LongOpenHashMap<>(); for (var entry : renderPassDrawTimers.entrySet()) { diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/ChunkBuildBuffers.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/ChunkBuildBuffers.java index 45de97b44..a90c9a7c3 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/ChunkBuildBuffers.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/ChunkBuildBuffers.java @@ -13,7 +13,7 @@ import org.embeddedt.embeddium.impl.render.chunk.data.BuiltSectionMeshParts; import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; import org.embeddedt.embeddium.impl.render.chunk.terrain.material.Material; import org.embeddedt.embeddium.impl.common.util.NativeBuffer; -import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer; +import org.embeddedt.embeddium.impl.render.chunk.sorting.SortState; import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder; import java.nio.ByteBuffer; @@ -90,7 +90,7 @@ public final class ChunkBuildBuffers { int vertexCount = 0; ModelQuadFacing[] facingsToUpload = pass.isSorted() ? ONLY_UNASSIGNED : ModelQuadFacing.VALUES; - TranslucentQuadAnalyzer.SortState sortState = pass.isSorted() ? builder.getVertexBuffer(ModelQuadFacing.UNASSIGNED).getSortState() : null; + SortState sortState = pass.isSorted() ? builder.getVertexBuffer(ModelQuadFacing.UNASSIGNED).getSortState() : null; for (ModelQuadFacing facing : facingsToUpload) { var buffer = builder.getVertexBuffer(facing); @@ -134,7 +134,8 @@ public final class ChunkBuildBuffers { mergedIndexBuffer = null; } - return new BuiltSectionMeshParts(mergedBuffer, mergedIndexBuffer, TranslucentQuadAnalyzer.SortState.compacted(sortState), vertexRanges); + // Uncompacted: the consumer needs the sorting level before it throws away the data behind it. + return new BuiltSectionMeshParts(mergedBuffer, mergedIndexBuffer, sortState, vertexRanges); } public void destroy() { diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/sorting/ChunkPrimitiveType.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/sorting/ChunkPrimitiveType.java index a93a4ecbd..280293740 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/sorting/ChunkPrimitiveType.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/sorting/ChunkPrimitiveType.java @@ -1,6 +1,6 @@ package org.embeddedt.embeddium.impl.render.chunk.compile.sorting; -import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer; +import org.embeddedt.embeddium.impl.render.chunk.sorting.SortState; import org.jetbrains.annotations.Nullable; import java.nio.ByteBuffer; @@ -45,7 +45,7 @@ public interface ChunkPrimitiveType { * @param y y position of the camera * @param z z position of the camera */ - void generateSortedIndexBuffer(ByteBuffer indexBuffer, int numPrimitives, @Nullable TranslucentQuadAnalyzer.SortState chunkData, float x, float y, float z); + void generateSortedIndexBuffer(ByteBuffer indexBuffer, int numPrimitives, @Nullable SortState chunkData, float x, float y, float z); default List getDefines() { return List.of(); diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/sorting/QuadPrimitiveType.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/sorting/QuadPrimitiveType.java index db57d7b2b..183caa2c8 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/sorting/QuadPrimitiveType.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/sorting/QuadPrimitiveType.java @@ -1,12 +1,11 @@ package org.embeddedt.embeddium.impl.render.chunk.compile.sorting; -import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer; -import org.embeddedt.embeddium.impl.util.sorting.MergeSort; +import org.embeddedt.embeddium.impl.render.chunk.sorting.SortState; +import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentSorter; import org.jetbrains.annotations.Nullable; import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL; import java.nio.ByteBuffer; -import java.util.BitSet; public final class QuadPrimitiveType implements ChunkPrimitiveType { /** @@ -22,8 +21,6 @@ public final class QuadPrimitiveType implements ChunkPrimitiveType { private static final int VERTICES_PER_PRIMITIVE = 4; - private static final int FAKE_STATIC_CAMERA_OFFSET = 1000; - public QuadPrimitiveType(boolean triangulating) { this.triangulating = triangulating; } @@ -97,70 +94,19 @@ public final class QuadPrimitiveType implements ChunkPrimitiveType { } } - private static void buildStaticDistanceArray(float[] centers, float[] distanceArray, float x, float y, float z, - float normX, float normY, float normZ, int quadCount, BitSet normalSigns) { - for (int quadIdx = 0; quadIdx < quadCount; ++quadIdx) { - int centerIdx = quadIdx * 3; - - // Compute distance using projection of vector from camera->quad center onto shared normal, flipped by sign - // to accommodate backwards-facing quads in the same plane extensions - - float qX = centers[centerIdx + 0] - x; - float qY = centers[centerIdx + 1] - y; - float qZ = centers[centerIdx + 2] - z; - - distanceArray[quadIdx] = (normX * qX + normY * qY + normZ * qZ) * (normalSigns.get(quadIdx) ? 1 : -1); - } - } - - private static void buildDynamicDistanceArray(float[] centers, float[] distanceArray, int quadCount, float x, - float y, float z) { - // Sort using distance to camera directly - for (int quadIdx = 0; quadIdx < quadCount; ++quadIdx) { - int centerIdx = quadIdx * 3; - - float qX = centers[centerIdx + 0] - x; - float qY = centers[centerIdx + 1] - y; - float qZ = centers[centerIdx + 2] - z; - distanceArray[quadIdx] = qX * qX + qY * qY + qZ * qZ; - } - } - @Override - public void generateSortedIndexBuffer(ByteBuffer indexBuffer, int quadCount, @Nullable TranslucentQuadAnalyzer.SortState chunkData, float x, float y, float z) { - if (chunkData == null || chunkData.level() == TranslucentQuadAnalyzer.Level.NONE || chunkData.centersLength() < 3) { + public void generateSortedIndexBuffer(ByteBuffer indexBuffer, int quadCount, @Nullable SortState chunkData, float x, float y, float z) { + int[] order = chunkData != null ? TranslucentSorter.order(chunkData, x, y, z) : null; + + if (order == null) { generateSimpleIndexBuffer(indexBuffer, quadCount); return; } - if (quadCount != (chunkData.centersLength() / 3)) { - throw new IllegalStateException(String.format("Mismatched SortState (%d) vs given quad count (%d)", chunkData.centersLength() / 3, quadCount)); + if (quadCount != order.length) { + throw new IllegalStateException(String.format("Mismatched SortState (%d) vs given quad count (%d)", order.length, quadCount)); } - float[] centers = chunkData.centers(); - int[] indicesArray = new int[quadCount]; - float[] distanceArray = new float[quadCount]; - boolean isStatic = chunkData.level() == TranslucentQuadAnalyzer.Level.STATIC; - for (int quadIdx = 0; quadIdx < quadCount; ++quadIdx) { - indicesArray[quadIdx] = quadIdx; - } - - if (isStatic) { - buildStaticDistanceArray(centers, distanceArray, - centers[0] + chunkData.sharedNormal().x * FAKE_STATIC_CAMERA_OFFSET, - centers[1] + chunkData.sharedNormal().y * FAKE_STATIC_CAMERA_OFFSET, - centers[2] + chunkData.sharedNormal().z * FAKE_STATIC_CAMERA_OFFSET, - chunkData.sharedNormal().x, - chunkData.sharedNormal().y, - chunkData.sharedNormal().z, - quadCount, - chunkData.normalSigns()); - } else { - buildDynamicDistanceArray(centers, distanceArray, quadCount, x, y, z); - } - - MergeSort.mergeSort(indicesArray, distanceArray); - - generateIndexBuffer(indexBuffer, indicesArray); + generateIndexBuffer(indexBuffer, order); } } diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/tasks/ChunkBuilderSortTask.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/tasks/ChunkBuilderSortTask.java index ca447e802..daad1f93d 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/tasks/ChunkBuilderSortTask.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/tasks/ChunkBuilderSortTask.java @@ -8,7 +8,7 @@ import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkSortOutput; import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; import org.embeddedt.embeddium.impl.common.util.NativeBuffer; import org.embeddedt.embeddium.impl.util.task.CancellationToken; -import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer; +import org.embeddedt.embeddium.impl.render.chunk.sorting.SortState; import java.util.Map; @@ -16,10 +16,10 @@ public class ChunkBuilderSortTask extends ChunkBuilderTask { private final RenderSection render; private final float cameraX, cameraY, cameraZ; private final int frame; - private final Map translucentMeshes; + private final Map translucentMeshes; private final RenderPassConfiguration renderPassConfiguration; - public ChunkBuilderSortTask(RenderSection render, float cameraX, float cameraY, float cameraZ, int frame, Map translucentMeshes, RenderPassConfiguration renderPassConfiguration) { + public ChunkBuilderSortTask(RenderSection render, float cameraX, float cameraY, float cameraZ, int frame, Map translucentMeshes, RenderPassConfiguration renderPassConfiguration) { this.render = render; this.cameraX = cameraX; this.cameraY = cameraY; @@ -32,11 +32,11 @@ public class ChunkBuilderSortTask extends ChunkBuilderTask { @Override public ChunkSortOutput execute(ChunkBuildContext context, CancellationToken cancellationSource) { var meshes = new Reference2ReferenceOpenHashMap(); - for(Map.Entry entry : translucentMeshes.entrySet()) { + for(Map.Entry entry : translucentMeshes.entrySet()) { var sortInfo = entry.getValue(); var primitiveType = this.renderPassConfiguration.getPrimitiveTypeForPass(entry.getKey()); - var newIndexBuffer = new NativeBuffer(primitiveType.getIndexBufferSize(sortInfo.centersLength() / 3)); - primitiveType.generateSortedIndexBuffer(newIndexBuffer.getDirectBuffer(), sortInfo.centersLength() / 3, sortInfo, cameraX - this.render.getOriginX(), cameraY - this.render.getOriginY(), cameraZ - this.render.getOriginZ()); + var newIndexBuffer = new NativeBuffer(primitiveType.getIndexBufferSize(sortInfo.quadCount())); + primitiveType.generateSortedIndexBuffer(newIndexBuffer.getDirectBuffer(), sortInfo.quadCount(), sortInfo, cameraX - this.render.getOriginX(), cameraY - this.render.getOriginY(), cameraZ - this.render.getOriginZ()); meshes.put(entry.getKey(), new ChunkSortOutput.SortedMesh( newIndexBuffer )); diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/data/BuiltSectionMeshParts.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/data/BuiltSectionMeshParts.java index a13aff9e9..6809b2ad9 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/data/BuiltSectionMeshParts.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/data/BuiltSectionMeshParts.java @@ -6,13 +6,13 @@ import org.embeddedt.embeddium.impl.gl.util.VertexRange; import org.embeddedt.embeddium.impl.common.util.NativeBuffer; import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing; import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkBuildBuffers; -import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer; +import org.embeddedt.embeddium.impl.render.chunk.sorting.SortState; import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; import org.jetbrains.annotations.Nullable; import java.util.Map; -public record BuiltSectionMeshParts(NativeBuffer vertexBuffer, @Nullable NativeBuffer indexBuffer, @Nullable TranslucentQuadAnalyzer.SortState sortState, Map ranges) { +public record BuiltSectionMeshParts(NativeBuffer vertexBuffer, @Nullable NativeBuffer indexBuffer, @Nullable SortState sortState, Map ranges) { public void free() { vertexBuffer.free(); if (indexBuffer != null) { diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/RenderListManager.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/RenderListManager.java index 32960b5ae..12ae2164a 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/RenderListManager.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/RenderListManager.java @@ -5,7 +5,8 @@ import lombok.Getter; import lombok.Setter; import org.embeddedt.embeddium.impl.render.chunk.occlusion.AsyncOcclusionMode; import org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionLattice; -import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer; +import org.embeddedt.embeddium.impl.render.chunk.RenderSection; +import org.embeddedt.embeddium.impl.render.chunk.sorting.SortState; import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; import org.embeddedt.embeddium.impl.render.viewport.Viewport; import org.jetbrains.annotations.NotNull; @@ -65,13 +66,12 @@ public class RenderListManager { StringBuilder sb = new StringBuilder(); sb.append("Sorting: "); - TranslucentQuadAnalyzer.Level[] values = TranslucentQuadAnalyzer.Level.VALUES; - for (int i = 0; i < values.length; i++) { - TranslucentQuadAnalyzer.Level level = values[i]; - sb.append(level.name()); + String[] names = SortState.DEBUG_NAMES; + for (int i = 0; i < names.length; i++) { + sb.append(names[i]); sb.append('='); - sb.append(sortingSectionCounts[level.ordinal()]); - if((i + 1) < values.length) { + sb.append(sortingSectionCounts[i]); + if((i + 1) < names.length) { sb.append(", "); } } @@ -226,7 +226,7 @@ public class RenderListManager { var iterator = renderLists.iterator(); - int[] sectionCounts = new int[TranslucentQuadAnalyzer.Level.VALUES.length]; + int[] sectionCounts = new int[SortState.DEBUG_NAMES.length]; boolean isSorting = renderLists.getPasses().stream().anyMatch(TerrainRenderPass::isSorted); @@ -265,11 +265,11 @@ public class RenderListManager { var section = region.getSection(sectionIndex); // Do not count sections without translucent data - if(section == null || section.getTranslucencySortStates().isEmpty()) { + if(section == null || section.getHighestSortingIndex() == RenderSection.NO_TRANSLUCENT_GEOMETRY) { continue; } - sectionCounts[section.getHighestSortingLevel().ordinal()]++; + sectionCounts[section.getHighestSortingIndex()]++; } } } diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/SortState.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/SortState.java new file mode 100644 index 000000000..e2bba4f39 --- /dev/null +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/SortState.java @@ -0,0 +1,77 @@ +package org.embeddedt.embeddium.impl.render.chunk.sorting; + +public sealed interface SortState permits SortState.None, SortState.Static, SortState.Resortable { + SortState NONE = new None(); + + /** Variant names for the debug overlay, indexed by {@link #debugIndex()} and ordered by sorting cost */ + String[] DEBUG_NAMES = { "NONE", "STATIC", "DYNAMIC" }; + + /** Position in {@link #DEBUG_NAMES}, doubling as the cost ranking used to pick a section's highest variant */ + int debugIndex(); + + int quadCount(); + + SortState compactForStorage(); + + default boolean requiresDynamicSorting() { + return this instanceof Resortable; + } + + /** A state whose order depends on the camera, and so survives compaction to be re-sorted on every move */ + sealed interface Resortable extends SortState permits Dynamic { + @Override + default Resortable compactForStorage() { + return this; + } + } + + /** Any draw order is correct */ + record None() implements SortState { + @Override + public int debugIndex() { + return 0; + } + + @Override + public int quadCount() { + return 0; + } + + @Override + public SortState compactForStorage() { + return this; + } + } + + /** One camera-independent order, computed once during meshing */ + record Static(int[] order) implements SortState { + @Override + public int debugIndex() { + return 1; + } + + @Override + public int quadCount() { + return order.length; + } + + // The order is consumed by the index buffer written at build time, and can never change afterwards + @Override + public SortState compactForStorage() { + return NONE; + } + } + + /** Resortable, so the quad centers are kept for every re-sort */ + record Dynamic(float[] centers) implements Resortable { + @Override + public int debugIndex() { + return 2; + } + + @Override + public int quadCount() { + return centers.length / 3; + } + } +} diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentQuadAnalyzer.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentQuadAnalyzer.java index 9ec7ed1f7..6324ba49b 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentQuadAnalyzer.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentQuadAnalyzer.java @@ -14,65 +14,15 @@ public class TranslucentQuadAnalyzer { private final Vector3f currentNormal = new Vector3f(); private final Vector3f globalNormal = new Vector3f(); private final BitSet normalSigns = new BitSet(EXPECTED_QUADS); - private static final BitSet EMPTY = new BitSet(); private int currentVertex; private boolean hasDistinctNormals; - public enum Level { - /** - * No sorting is required of the current section. - */ - NONE, - /** - * Sorting is required once during meshing. - */ - STATIC, - /** - * Sorting is required any time the camera moves. - */ - DYNAMIC; - - public static final Level[] VALUES = values(); - - public boolean requiresDynamicSorting() { - return this.ordinal() >= Level.DYNAMIC.ordinal(); - } - } - public TranslucentQuadAnalyzer() { for(int i = 0; i < 4; i++) { vertexPositions[i] = new Vector3f(); } } - public record SortState(Level level, float[] centers, int centersLength, BitSet normalSigns, Vector3f sharedNormal) { - public static final SortState NONE = new SortState(Level.NONE, null, 0, null, null); - - public boolean requiresDynamicSorting() { - return level.requiresDynamicSorting(); - } - - public SortState compactForStorage() { - if(this == NONE || requiresDynamicSorting()) { - return this; - } else { - return new SortState(level, null, 0, null, null); - } - } - - public static SortState compacted(SortState state) { - return state != null ? state.compactForStorage() : null; - } - } - - private static BitSet cloneBits(BitSet bits) { - if(bits.isEmpty()) { - return EMPTY; - } else { - return (BitSet)bits.clone(); - } - } - private boolean areAllQuadsOnSamePlane() { // Let globalNormal = (a, b, c). Any plane with this normal vector is denoted by the equation ax + by + cz = d, // for some real number d. @@ -104,35 +54,26 @@ public class TranslucentQuadAnalyzer { } public SortState getSortState() { - if(quadCenters.isEmpty()) { + int quadCount = quadCenters.size() / 3; + + if (quadCount == 0) { return SortState.NONE; - } else { - Level sortLevel; - - // Figure out what sort level is required - if(hasDistinctNormals) { - // Must use dynamic sort - sortLevel = Level.DYNAMIC; - } else { - // If all quads are on the same plane we can use NONE sorting, otherwise we need to sort statically to put - // them in the right order - sortLevel = areAllQuadsOnSamePlane() ? Level.NONE : Level.STATIC; - } - - SortState finalState; - - if (sortLevel == Level.NONE) { - finalState = SortState.NONE; - } else if (sortLevel.requiresDynamicSorting()) { - // Clone everything - finalState = new SortState(sortLevel, quadCenters.toArray(new float[0]), quadCenters.size(), cloneBits(normalSigns), new Vector3f(globalNormal)); - } else { - // Just make a thin wrapper around our backing objects - finalState = new SortState(sortLevel, quadCenters.elements(), quadCenters.size(), normalSigns, globalNormal); - } - - return finalState; } + + if (hasDistinctNormals) { + // The order depends on the camera, so copy the centers and re-sort whenever it moves + return new SortState.Dynamic(quadCenters.toFloatArray()); + } + + if (areAllQuadsOnSamePlane()) { + // Coplanar quads never occlude each other, so any order is correct + return SortState.NONE; + } + + // Parallel but spread over several planes: the order cannot change, so sort once here and keep only the + // result. The backing array and the sign bits are consumed before we return, so neither needs copying. + return new SortState.Static(TranslucentSorter.sortNormalRelative(quadCenters.elements(), quadCount, + globalNormal.x, globalNormal.y, globalNormal.z, normalSigns)); } public void clear() { diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java new file mode 100644 index 000000000..1173c99e6 --- /dev/null +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java @@ -0,0 +1,76 @@ +package org.embeddedt.embeddium.impl.render.chunk.sorting; + +import org.embeddedt.embeddium.impl.util.sorting.MergeSort; +import org.jetbrains.annotations.Nullable; + +import java.util.BitSet; + +public final class TranslucentSorter { + /** + * How far along the shared normal the imaginary camera used by {@link #sortNormalRelative} sits. Any value + * comfortably beyond the section is equivalent, since only the ordering of the projections matters. + */ + private static final int FAKE_STATIC_CAMERA_OFFSET = 1000; + + private TranslucentSorter() { + } + + /** + * Orders quads by their distance to the camera, farthest first. + */ + public static int[] sortByDistance(float[] centers, int quadCount, float camX, float camY, float camZ) { + float[] distances = new float[quadCount]; + + for (int quadIdx = 0; quadIdx < quadCount; quadIdx++) { + int centerIdx = quadIdx * 3; + + float qX = centers[centerIdx + 0] - camX; + float qY = centers[centerIdx + 1] - camY; + float qZ = centers[centerIdx + 2] - camZ; + + distances[quadIdx] = qX * qX + qY * qY + qZ * qZ; + } + + return MergeSort.mergeSort(distances); + } + + /** + * Orders quads that all share the normal {@code (nx, ny, nz)}, up to a sign given by {@code flipped}. Because + * such quads only ever occlude each other along that normal, the resulting order is correct from any camera + * position, and can be computed once during meshing. + *

+ * Distance is measured by projecting onto the shared normal from a camera placed far along it. Quads facing the + * camera are ordered back to front and are drawn before the quads facing away, which are ordered front to back. + */ + public static int[] sortNormalRelative(float[] centers, int quadCount, float nx, float ny, float nz, BitSet flipped) { + float camX = centers[0] + nx * FAKE_STATIC_CAMERA_OFFSET; + float camY = centers[1] + ny * FAKE_STATIC_CAMERA_OFFSET; + float camZ = centers[2] + nz * FAKE_STATIC_CAMERA_OFFSET; + + float[] distances = new float[quadCount]; + + for (int quadIdx = 0; quadIdx < quadCount; quadIdx++) { + int centerIdx = quadIdx * 3; + + float qX = centers[centerIdx + 0] - camX; + float qY = centers[centerIdx + 1] - camY; + float qZ = centers[centerIdx + 2] - camZ; + + distances[quadIdx] = (nx * qX + ny * qY + nz * qZ) * (flipped.get(quadIdx) ? 1 : -1); + } + + return MergeSort.mergeSort(distances); + } + + public static int @Nullable [] order(SortState state, float camX, float camY, float camZ) { + if (state instanceof SortState.Static staticState) { + return staticState.order(); + } + + if (state instanceof SortState.Dynamic dynamic) { + return sortByDistance(dynamic.centers(), dynamic.quadCount(), camX, camY, camZ); + } + + return null; + } +} diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/vertex/builder/ChunkMeshBufferBuilder.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/vertex/builder/ChunkMeshBufferBuilder.java index e4dd0c449..096fa6385 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/vertex/builder/ChunkMeshBufferBuilder.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/vertex/builder/ChunkMeshBufferBuilder.java @@ -2,6 +2,7 @@ package org.embeddedt.embeddium.impl.render.chunk.vertex.builder; import org.embeddedt.embeddium.impl.render.chunk.terrain.material.Material; import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder; +import org.embeddedt.embeddium.impl.render.chunk.sorting.SortState; import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer; import org.jetbrains.annotations.Nullable; import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL; @@ -106,7 +107,7 @@ public class ChunkMeshBufferBuilder { } @Nullable - public TranslucentQuadAnalyzer.SortState getSortState() { + public SortState getSortState() { return this.analyzer != null ? this.analyzer.getSortState() : null; } -- 2.54.1 From b6f7d745340951390f1cb2ac755de9462537ebe2 Mon Sep 17 00:00:00 2001 From: rdh Date: Tue, 8 Sep 2026 21:21:34 -0400 Subject: [PATCH 02/23] skip translucency sorting for outward faces on the section bounds also moved all the analysis out of the analyzer, it's just a recorder now --- .../impl/render/chunk/sorting/QuadSet.java | 68 +++++++ .../sorting/TranslucentQuadAnalyzer.java | 185 ------------------ .../sorting/TranslucentQuadRecorder.java | 146 ++++++++++++++ .../chunk/sorting/TranslucentSorter.java | 147 +++++++++++++- .../builder/ChunkMeshBufferBuilder.java | 6 +- 5 files changed, 362 insertions(+), 190 deletions(-) create mode 100644 common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/QuadSet.java delete mode 100644 common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentQuadAnalyzer.java create mode 100644 common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentQuadRecorder.java diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/QuadSet.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/QuadSet.java new file mode 100644 index 000000000..9b4a0fd0b --- /dev/null +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/QuadSet.java @@ -0,0 +1,68 @@ +package org.embeddedt.embeddium.impl.render.chunk.sorting; + +public record QuadSet(int count, float[] centers, float[] bounds, float[] normals, float[] dots, byte[] facings) { + static final float EPSILON = 1e-4f; + + public QuadSet { + if (count < 0) { + throw new IllegalArgumentException("count must be non-negative"); + } + + if (centers.length != count * 3) { + throw new IllegalArgumentException("centers length must be count * 3"); + } + + if (bounds.length != count * 6) { + throw new IllegalArgumentException("bounds length must be count * 6"); + } + + if (normals.length != count * 3) { + throw new IllegalArgumentException("normals length must be count * 3"); + } + + if (dots.length != count) { + throw new IllegalArgumentException("dots length must be count"); + } + + if (facings.length != count) { + throw new IllegalArgumentException("facings length must be count"); + } + } + + /** + * The smallest projection of the quad's bounds onto {@code (nx, ny, nz)}. The nearest corner is the one that is + * lowest along each axis the direction points up, and highest along each axis it points down, so no corner + * enumeration is needed. + */ + public float minDot(int quad, float nx, float ny, float nz) { + int boundOffset = quad * 6; + + return nx * (nx >= 0 ? bounds[boundOffset + 0] : bounds[boundOffset + 3]) + + ny * (ny >= 0 ? bounds[boundOffset + 1] : bounds[boundOffset + 4]) + + nz * (nz >= 0 ? bounds[boundOffset + 2] : bounds[boundOffset + 5]); + } + + /** + * The largest projection of the quad's bounds onto {@code (nx, ny, nz)}: {@link #minDot} with the corner choices + * reversed. + */ + public float maxDot(int quad, float nx, float ny, float nz) { + int boundOffset = quad * 6; + + return nx * (nx >= 0 ? bounds[boundOffset + 3] : bounds[boundOffset + 0]) + + ny * (ny >= 0 ? bounds[boundOffset + 4] : bounds[boundOffset + 1]) + + nz * (nz >= 0 ? bounds[boundOffset + 5] : bounds[boundOffset + 2]); + } + + public boolean isCoplanar(int a, int b) { + int ao = a * 3, bo = b * 3; + float normalDot = normals[ao] * normals[bo] + normals[ao + 1] * normals[bo + 1] + normals[ao + 2] * normals[bo + 2]; + + if (Math.abs(Math.abs(normalDot) - 1.0f) > EPSILON) { + return false; + } + + float offsetB = normalDot < 0 ? -dots[b] : dots[b]; + return Math.abs(dots[a] - offsetB) < EPSILON; + } +} diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentQuadAnalyzer.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentQuadAnalyzer.java deleted file mode 100644 index 6324ba49b..000000000 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentQuadAnalyzer.java +++ /dev/null @@ -1,185 +0,0 @@ -package org.embeddedt.embeddium.impl.render.chunk.sorting; - -import it.unimi.dsi.fastutil.floats.FloatArrayList; -import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder; -import org.joml.Vector3f; - -import java.util.BitSet; - -public class TranslucentQuadAnalyzer { - // X/Y/Z for each quad center - private static final int EXPECTED_QUADS = 1000; - private final FloatArrayList quadCenters = new FloatArrayList(EXPECTED_QUADS * 3); - private final Vector3f[] vertexPositions = new Vector3f[4]; - private final Vector3f currentNormal = new Vector3f(); - private final Vector3f globalNormal = new Vector3f(); - private final BitSet normalSigns = new BitSet(EXPECTED_QUADS); - private int currentVertex; - private boolean hasDistinctNormals; - - public TranslucentQuadAnalyzer() { - for(int i = 0; i < 4; i++) { - vertexPositions[i] = new Vector3f(); - } - } - - private boolean areAllQuadsOnSamePlane() { - // Let globalNormal = (a, b, c). Any plane with this normal vector is denoted by the equation ax + by + cz = d, - // for some real number d. - // - // Next, we know that any quad has either globalNormal or -globalNormal as a normal vector. Suppose a quad q has center (x, y, z). - // We define the "plane extension" of q as the unique plane in 3D space that q resides within. In particular, - // any quad's plane extension (when all share parallel normals) is uniquely determined by the choice of d. - // - // If all quads are on the same plane, we don't need to sort at all. Otherwise, we need to use a static sort. - // Recalling that d is given by ax + by + cz, and that we know all those variables for any quad, we can - // easily determine if all quads reside in the same plane by computing this expression for each quad center, - // and checking that we obtain at most one value. - - var centerArray = quadCenters.elements(); - - float a = globalNormal.x, b = globalNormal.y, c = globalNormal.z; - float d = a * centerArray[0] + b * centerArray[1] + c * centerArray[2]; - int nQuads = quadCenters.size() / 3; - for(int quadIdx = 1; quadIdx < nQuads; quadIdx++) { - int centerOff = quadIdx * 3; - float candidateD = a * centerArray[centerOff + 0] + b * centerArray[centerOff + 1] + c * centerArray[centerOff + 2]; - if(Math.abs(candidateD - d) >= 1.0E-5F) { - // Different planes - return false; - } - } - - return true; - } - - public SortState getSortState() { - int quadCount = quadCenters.size() / 3; - - if (quadCount == 0) { - return SortState.NONE; - } - - if (hasDistinctNormals) { - // The order depends on the camera, so copy the centers and re-sort whenever it moves - return new SortState.Dynamic(quadCenters.toFloatArray()); - } - - if (areAllQuadsOnSamePlane()) { - // Coplanar quads never occlude each other, so any order is correct - return SortState.NONE; - } - - // Parallel but spread over several planes: the order cannot change, so sort once here and keep only the - // result. The backing array and the sign bits are consumed before we return, so neither needs copying. - return new SortState.Static(TranslucentSorter.sortNormalRelative(quadCenters.elements(), quadCount, - globalNormal.x, globalNormal.y, globalNormal.z, normalSigns)); - } - - public void clear() { - quadCenters.clear(); - currentVertex = 0; - globalNormal.zero(); - normalSigns.clear(); - hasDistinctNormals = false; - } - - private void calculateNormal() { - final Vector3f v0 = vertexPositions[0]; - - final float x0 = v0.x; - final float y0 = v0.y; - final float z0 = v0.z; - - final Vector3f v1 = vertexPositions[1]; - - final float x1 = v1.x; - final float y1 = v1.y; - final float z1 = v1.z; - - final Vector3f v2 = vertexPositions[2]; - - final float x2 = v2.x; - final float y2 = v2.y; - final float z2 = v2.z; - - final Vector3f v3 = vertexPositions[3]; - - final float x3 = v3.x; - final float y3 = v3.y; - final float z3 = v3.z; - - final float dx0 = x2 - x0; - final float dy0 = y2 - y0; - final float dz0 = z2 - z0; - final float dx1 = x3 - x1; - final float dy1 = y3 - y1; - final float dz1 = z3 - z1; - - float normX = dy0 * dz1 - dz0 * dy1; - float normY = dz0 * dx1 - dx0 * dz1; - float normZ = dx0 * dy1 - dy0 * dx1; - - float l = (float) Math.sqrt(normX * normX + normY * normY + normZ * normZ); - - if (l != 0) { - normX /= l; - normY /= l; - normZ /= l; - } - - currentNormal.set(normX, normY, normZ); - } - - private void captureQuad() { - // The four positions in vertexPositions form a quad. Find its center - float totalX = 0, totalY = 0, totalZ = 0; - for (Vector3f vertex : vertexPositions) { - totalX += vertex.x; - totalY += vertex.y; - totalZ += vertex.z; - } - - var centers = quadCenters; - int currentQuadIndex = centers.size() / 3; - - centers.ensureCapacity(centers.size() + 3); - centers.add(totalX / 4); - centers.add(totalY / 4); - centers.add(totalZ / 4); - - if(!hasDistinctNormals) { - calculateNormal(); - - if(globalNormal.x == 0 && globalNormal.y == 0 && globalNormal.z == 0) { - // No normal has been tracked thus far, choose this one - globalNormal.set(currentNormal); - } else { - float dotProduct = globalNormal.dot(currentNormal); - // Technically, only 1 and -1 imply that the quads share a normal. However, if the dot products - // are very, very similar, we pretend they share a normal for optimization purposes. This is an - // approximation that allows very slightly slanted water in edges of underwater lakes to be counted as - // STATIC rather than DYNAMIC. - if (Math.abs(dotProduct) >= 0.98) { - if (dotProduct < 0) { - // Flag this quad as being flipped relative to the global normal - normalSigns.set(currentQuadIndex); - } - } else { - hasDistinctNormals = true; - } - } - } - } - - public void capture(ChunkVertexEncoder.Vertex vertex) { - int i = currentVertex; - vertexPositions[i].set(vertex.x, vertex.y, vertex.z); - i++; - if(i == 4) { - captureQuad(); - i = 0; - } - currentVertex = i; - } -} diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentQuadRecorder.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentQuadRecorder.java new file mode 100644 index 000000000..98cfcf166 --- /dev/null +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentQuadRecorder.java @@ -0,0 +1,146 @@ +package org.embeddedt.embeddium.impl.render.chunk.sorting; + +import it.unimi.dsi.fastutil.bytes.ByteArrayList; +import it.unimi.dsi.fastutil.floats.FloatArrayList; +import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder; +import org.embeddedt.embeddium.impl.util.QuadUtil; +import org.joml.Vector3f; + +public class TranslucentQuadRecorder { + private static final int EXPECTED_QUADS = 1000; + + private final FloatArrayList quadCenters = new FloatArrayList(EXPECTED_QUADS * 3); + private final FloatArrayList quadBounds = new FloatArrayList(EXPECTED_QUADS * 6); + private final FloatArrayList quadNormals = new FloatArrayList(EXPECTED_QUADS * 3); + private final FloatArrayList quadDots = new FloatArrayList(EXPECTED_QUADS); + private final ByteArrayList quadFacings = new ByteArrayList(EXPECTED_QUADS); + + private final Vector3f[] vertexPositions = new Vector3f[4]; + private final Vector3f currentNormal = new Vector3f(); + private int currentVertex; + + public TranslucentQuadRecorder() { + for(int i = 0; i < 4; i++) { + vertexPositions[i] = new Vector3f(); + } + } + + public SortState getSortState() { + return TranslucentSorter.analyze(this.toQuadSet()); + } + + public void clear() { + quadCenters.clear(); + quadBounds.clear(); + quadNormals.clear(); + quadDots.clear(); + quadFacings.clear(); + currentVertex = 0; + } + + private void calculateNormal() { + final Vector3f v0 = vertexPositions[0]; + + final float x0 = v0.x; + final float y0 = v0.y; + final float z0 = v0.z; + + final Vector3f v1 = vertexPositions[1]; + + final float x1 = v1.x; + final float y1 = v1.y; + final float z1 = v1.z; + + final Vector3f v2 = vertexPositions[2]; + + final float x2 = v2.x; + final float y2 = v2.y; + final float z2 = v2.z; + + final Vector3f v3 = vertexPositions[3]; + + final float x3 = v3.x; + final float y3 = v3.y; + final float z3 = v3.z; + + final float dx0 = x2 - x0; + final float dy0 = y2 - y0; + final float dz0 = z2 - z0; + final float dx1 = x3 - x1; + final float dy1 = y3 - y1; + final float dz1 = z3 - z1; + + float normX = dy0 * dz1 - dz0 * dy1; + float normY = dz0 * dx1 - dx0 * dz1; + float normZ = dx0 * dy1 - dy0 * dx1; + + float l = (float) Math.sqrt(normX * normX + normY * normY + normZ * normZ); + + if (l != 0) { + normX /= l; + normY /= l; + normZ /= l; + } + + currentNormal.set(normX, normY, normZ); + } + + private void captureQuad() { + // The four positions in vertexPositions form a quad. Find its center and axis-aligned bounds + float totalX = 0, totalY = 0, totalZ = 0; + float minX = Float.POSITIVE_INFINITY, minY = Float.POSITIVE_INFINITY, minZ = Float.POSITIVE_INFINITY; + float maxX = Float.NEGATIVE_INFINITY, maxY = Float.NEGATIVE_INFINITY, maxZ = Float.NEGATIVE_INFINITY; + + for (Vector3f vertex : vertexPositions) { + totalX += vertex.x; + totalY += vertex.y; + totalZ += vertex.z; + + minX = Math.min(minX, vertex.x); + minY = Math.min(minY, vertex.y); + minZ = Math.min(minZ, vertex.z); + maxX = Math.max(maxX, vertex.x); + maxY = Math.max(maxY, vertex.y); + maxZ = Math.max(maxZ, vertex.z); + } + + float centerX = totalX / 4, centerY = totalY / 4, centerZ = totalZ / 4; + + quadCenters.add(centerX); + quadCenters.add(centerY); + quadCenters.add(centerZ); + + quadBounds.add(minX); + quadBounds.add(minY); + quadBounds.add(minZ); + quadBounds.add(maxX); + quadBounds.add(maxY); + quadBounds.add(maxZ); + + calculateNormal(); + + quadNormals.add(currentNormal.x); + quadNormals.add(currentNormal.y); + quadNormals.add(currentNormal.z); + + quadDots.add(currentNormal.x * centerX + currentNormal.y * centerY + currentNormal.z * centerZ); + + quadFacings.add((byte) QuadUtil.findNormalFace(currentNormal.x, currentNormal.y, currentNormal.z).ordinal()); + } + + public void capture(ChunkVertexEncoder.Vertex vertex) { + int i = currentVertex; + vertexPositions[i].set(vertex.x, vertex.y, vertex.z); + i++; + if(i == 4) { + captureQuad(); + i = 0; + } + currentVertex = i; + } + + public QuadSet toQuadSet() { + return new QuadSet(quadCenters.size() / 3, quadCenters.toFloatArray(), quadBounds.toFloatArray(), + quadNormals.toFloatArray(), quadDots.toFloatArray(), quadFacings.toByteArray()); + } +} diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java index 1173c99e6..28596f69d 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java @@ -1,5 +1,6 @@ package org.embeddedt.embeddium.impl.render.chunk.sorting; +import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing; import org.embeddedt.embeddium.impl.util.sorting.MergeSort; import org.jetbrains.annotations.Nullable; @@ -12,6 +13,12 @@ public final class TranslucentSorter { */ private static final int FAKE_STATIC_CAMERA_OFFSET = 1000; + /** + * How closely two normals must agree to be treated as parallel. Only +/-1 truly imply a shared normal, but + * accepting near misses lets very slightly slanted water (the edges of underwater lakes) sort statically. + */ + private static final float PARALLEL_THRESHOLD = 0.98f; + private TranslucentSorter() { } @@ -24,7 +31,7 @@ public final class TranslucentSorter { for (int quadIdx = 0; quadIdx < quadCount; quadIdx++) { int centerIdx = quadIdx * 3; - float qX = centers[centerIdx + 0] - camX; + float qX = centers[centerIdx] - camX; float qY = centers[centerIdx + 1] - camY; float qZ = centers[centerIdx + 2] - camZ; @@ -52,7 +59,7 @@ public final class TranslucentSorter { for (int quadIdx = 0; quadIdx < quadCount; quadIdx++) { int centerIdx = quadIdx * 3; - float qX = centers[centerIdx + 0] - camX; + float qX = centers[centerIdx] - camX; float qY = centers[centerIdx + 1] - camY; float qZ = centers[centerIdx + 2] - camZ; @@ -73,4 +80,140 @@ public final class TranslucentSorter { return null; } + + /** + * Decides the cheapest sort a section's translucent geometry can get away with. First match wins: + *

    + *
  1. no quads, or none that cover any pixels
  2. + *
  3. everything in one plane
  4. + *
  5. every quad flat on the section's bounding box, facing outward
  6. + *
  7. all normals parallel, so one order works from everywhere
  8. + *
  9. otherwise the order depends on the camera
  10. + *
+ */ + public static SortState analyze(QuadSet quads) { + int quadCount = quads.count(); + + if (quadCount == 0) { + return SortState.NONE; + } + + int reference = firstNonDegenerateQuad(quads); + + if (reference < 0) { + // every quad is degenerate, so none of them cover a pixel and no order can be wrong + return SortState.NONE; + } + + if (allCoplanarWith(quads, reference)) { + // quads in one plane never occlude each other + return SortState.NONE; + } + + if (allOutwardOnBoundingBox(quads)) { + // each quad is on a different face of the section's bounding box, facing away from the inside, so no + // two of them can ever overlap on screen + return SortState.NONE; + } + + float[] normals = quads.normals(); + int referenceOffset = reference * 3; + float nx = normals[referenceOffset], ny = normals[referenceOffset + 1], nz = normals[referenceOffset + 2]; + + BitSet flipped = new BitSet(quadCount); + + for (int quadIdx = 0; quadIdx < quadCount; quadIdx++) { + int normalOffset = quadIdx * 3; + float dot = nx * normals[normalOffset] + ny * normals[normalOffset + 1] + nz * normals[normalOffset + 2]; + + if (Math.abs(dot) < PARALLEL_THRESHOLD) { + // distinct normals, so which quad is in front depends on where the camera is + return new SortState.Dynamic(quads.centers()); + } + + if (dot < 0) { + // this quad faces the opposite way to the reference + flipped.set(quadIdx); + } + } + + // parallel but spread over several planes: the order cannot change, so sort once and keep only the result + return new SortState.Static(sortNormalRelative(quads.centers(), quadCount, nx, ny, nz, flipped)); + } + + /** + * The first quad with a non-zero normal, or -1 if every quad is degenerate + */ + private static int firstNonDegenerateQuad(QuadSet quads) { + float[] normals = quads.normals(); + + for (int quadIdx = 0; quadIdx < quads.count(); quadIdx++) { + int normalOffset = quadIdx * 3; + + if (normals[normalOffset] != 0 || normals[normalOffset + 1] != 0 || normals[normalOffset + 2] != 0) { + return quadIdx; + } + } + + return -1; + } + + private static boolean allCoplanarWith(QuadSet quads, int reference) { + for (int quadIdx = 0; quadIdx < quads.count(); quadIdx++) { + if (!quads.isCoplanar(reference, quadIdx)) { + return false; + } + } + + return true; + } + + /** + * Whether every quad lies flat on the outer shell of the union of all their bounds, facing outward. Faces may be + * missing (a block against an opaque neighbour), but an inward or interior face fails, because it can be seen + * through the others. + */ + private static boolean allOutwardOnBoundingBox(QuadSet quads) { + float[] bounds = quads.bounds(); + int quadCount = quads.count(); + + float[] boxMin = { bounds[0], bounds[1], bounds[2] }; + float[] boxMax = { bounds[3], bounds[4], bounds[5] }; + + for (int quadIdx = 1; quadIdx < quadCount; quadIdx++) { + int boundsOffset = quadIdx * 6; + + for (int axis = 0; axis < 3; axis++) { + boxMin[axis] = Math.min(boxMin[axis], bounds[boundsOffset + axis]); + boxMax[axis] = Math.max(boxMax[axis], bounds[boundsOffset + 3 + axis]); + } + } + + byte[] facings = quads.facings(); + + for (int quadIdx = 0; quadIdx < quadCount; quadIdx++) { + ModelQuadFacing facing = ModelQuadFacing.VALUES[facings[quadIdx]]; + + if (!facing.isDirection()) { + // A slanted or degenerate quad is not flat on any face of the box + return false; + } + + float nx = facing.getStepX(), ny = facing.getStepY(), nz = facing.getStepZ(); + + // the largest projection is the far side of the box, and a quad lying in a plane has no thickness at all + float quadMin = quads.minDot(quadIdx, nx, ny, nz); + float quadMax = quads.maxDot(quadIdx, nx, ny, nz); + + int axis = facing.getAxis().ordinal(); + boolean positive = facing.getAxis().getFacing(true) == facing; + float boxFar = positive ? boxMax[axis] : -boxMin[axis]; + + if (Math.abs(quadMax - quadMin) > QuadSet.EPSILON || Math.abs(quadMax - boxFar) > QuadSet.EPSILON) { + return false; + } + } + + return true; + } } diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/vertex/builder/ChunkMeshBufferBuilder.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/vertex/builder/ChunkMeshBufferBuilder.java index 096fa6385..a07083d83 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/vertex/builder/ChunkMeshBufferBuilder.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/vertex/builder/ChunkMeshBufferBuilder.java @@ -3,7 +3,7 @@ package org.embeddedt.embeddium.impl.render.chunk.vertex.builder; import org.embeddedt.embeddium.impl.render.chunk.terrain.material.Material; import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder; import org.embeddedt.embeddium.impl.render.chunk.sorting.SortState; -import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer; +import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadRecorder; import org.jetbrains.annotations.Nullable; import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL; import java.nio.ByteBuffer; @@ -13,7 +13,7 @@ public class ChunkMeshBufferBuilder { private final int stride; private final int initialCapacity; - private final TranslucentQuadAnalyzer analyzer; + private final TranslucentQuadRecorder analyzer; private ByteBuffer buffer; private int count; @@ -29,7 +29,7 @@ public class ChunkMeshBufferBuilder { this.capacity = 0; this.initialCapacity = initialCapacity; - this.analyzer = collectSortState ? new TranslucentQuadAnalyzer() : null; + this.analyzer = collectSortState ? new TranslucentQuadRecorder() : null; } public void push(ChunkVertexEncoder.Vertex[] vertices, Material material) { -- 2.54.1 From 407e19394613c9e75ea87781cb552c88f526d75a Mon Sep 17 00:00:00 2001 From: rdh Date: Tue, 8 Sep 2026 21:56:02 -0400 Subject: [PATCH 03/23] move quad index arithmetic into QuadSet accessors --- .../impl/render/chunk/sorting/QuadSet.java | 61 ++++++++++++++++++- .../chunk/sorting/TranslucentSorter.java | 29 +++------ 2 files changed, 66 insertions(+), 24 deletions(-) diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/QuadSet.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/QuadSet.java index 9b4a0fd0b..16216f3e7 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/QuadSet.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/QuadSet.java @@ -1,5 +1,7 @@ package org.embeddedt.embeddium.impl.render.chunk.sorting; +import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing; + public record QuadSet(int count, float[] centers, float[] bounds, float[] normals, float[] dots, byte[] facings) { static final float EPSILON = 1e-4f; @@ -55,8 +57,7 @@ public record QuadSet(int count, float[] centers, float[] bounds, float[] normal } public boolean isCoplanar(int a, int b) { - int ao = a * 3, bo = b * 3; - float normalDot = normals[ao] * normals[bo] + normals[ao + 1] * normals[bo + 1] + normals[ao + 2] * normals[bo + 2]; + float normalDot = normalDot(a, b); if (Math.abs(Math.abs(normalDot) - 1.0f) > EPSILON) { return false; @@ -65,4 +66,60 @@ public record QuadSet(int count, float[] centers, float[] bounds, float[] normal float offsetB = normalDot < 0 ? -dots[b] : dots[b]; return Math.abs(dots[a] - offsetB) < EPSILON; } + + public float normalDot(int a, int b) { + int ao = a * 3, bo = b * 3; + + return normals[ao] * normals[bo] + normals[ao + 1] * normals[bo + 1] + normals[ao + 2] * normals[bo + 2]; + } + + public boolean isDegenerate(int quad) { + int normalOffset = quad * 3; + + return normals[normalOffset] == 0 && normals[normalOffset + 1] == 0 && normals[normalOffset + 2] == 0; + } + + public float normalX(int quad) { + return normals[quad * 3]; + } + + public float normalY(int quad) { + return normals[quad * 3 + 1]; + } + + public float normalZ(int quad) { + return normals[quad * 3 + 2]; + } + + public ModelQuadFacing facing(int quad) { + return ModelQuadFacing.VALUES[facings[quad]]; + } + + public Bounds union() { + float minX = Float.POSITIVE_INFINITY, minY = Float.POSITIVE_INFINITY, minZ = Float.POSITIVE_INFINITY; + float maxX = Float.NEGATIVE_INFINITY, maxY = Float.NEGATIVE_INFINITY, maxZ = Float.NEGATIVE_INFINITY; + + for (int quad = 0; quad < count; quad++) { + int boundOffset = quad * 6; + + minX = Math.min(minX, bounds[boundOffset + 0]); + minY = Math.min(minY, bounds[boundOffset + 1]); + minZ = Math.min(minZ, bounds[boundOffset + 2]); + maxX = Math.max(maxX, bounds[boundOffset + 3]); + maxY = Math.max(maxY, bounds[boundOffset + 4]); + maxZ = Math.max(maxZ, bounds[boundOffset + 5]); + } + + return new Bounds(minX, minY, minZ, maxX, maxY, maxZ); + } + + public record Bounds(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { + public float minDot(float nx, float ny, float nz) { + return nx * (nx >= 0 ? minX : maxX) + ny * (ny >= 0 ? minY : maxY) + nz * (nz >= 0 ? minZ : maxZ); + } + + public float maxDot(float nx, float ny, float nz) { + return nx * (nx >= 0 ? maxX : minX) + ny * (ny >= 0 ? maxY : minY) + nz * (nz >= 0 ? maxZ : minZ); + } + } } diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java index 28596f69d..5f8f38d60 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java @@ -174,25 +174,10 @@ public final class TranslucentSorter { * through the others. */ private static boolean allOutwardOnBoundingBox(QuadSet quads) { - float[] bounds = quads.bounds(); - int quadCount = quads.count(); + QuadSet.Bounds box = quads.union(); - float[] boxMin = { bounds[0], bounds[1], bounds[2] }; - float[] boxMax = { bounds[3], bounds[4], bounds[5] }; - - for (int quadIdx = 1; quadIdx < quadCount; quadIdx++) { - int boundsOffset = quadIdx * 6; - - for (int axis = 0; axis < 3; axis++) { - boxMin[axis] = Math.min(boxMin[axis], bounds[boundsOffset + axis]); - boxMax[axis] = Math.max(boxMax[axis], bounds[boundsOffset + 3 + axis]); - } - } - - byte[] facings = quads.facings(); - - for (int quadIdx = 0; quadIdx < quadCount; quadIdx++) { - ModelQuadFacing facing = ModelQuadFacing.VALUES[facings[quadIdx]]; + for (int quadIdx = 0; quadIdx < quads.count(); quadIdx++) { + ModelQuadFacing facing = quads.facing(quadIdx); if (!facing.isDirection()) { // A slanted or degenerate quad is not flat on any face of the box @@ -205,11 +190,11 @@ public final class TranslucentSorter { float quadMin = quads.minDot(quadIdx, nx, ny, nz); float quadMax = quads.maxDot(quadIdx, nx, ny, nz); - int axis = facing.getAxis().ordinal(); - boolean positive = facing.getAxis().getFacing(true) == facing; - float boxFar = positive ? boxMax[axis] : -boxMin[axis]; + if (Math.abs(quadMax - quadMin) > QuadSet.EPSILON) { + return false; + } - if (Math.abs(quadMax - quadMin) > QuadSet.EPSILON || Math.abs(quadMax - boxFar) > QuadSet.EPSILON) { + if (Math.abs(quadMax - box.maxDot(nx, ny, nz)) > QuadSet.EPSILON) { return false; } } -- 2.54.1 From d6a8cc08685ae83ab46c30c97ebf4f00fe077647 Mon Sep 17 00:00:00 2001 From: rdh Date: Tue, 8 Sep 2026 22:18:19 -0400 Subject: [PATCH 04/23] prepare for the static toposort --- .../impl/render/chunk/sorting/QuadSet.java | 6 ++++ .../impl/render/chunk/sorting/SortState.java | 4 +-- .../chunk/sorting/TranslucentSorter.java | 35 ++++++++++++++----- 3 files changed, 34 insertions(+), 11 deletions(-) diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/QuadSet.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/QuadSet.java index 16216f3e7..3c853b58a 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/QuadSet.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/QuadSet.java @@ -122,4 +122,10 @@ public record QuadSet(int count, float[] centers, float[] bounds, float[] normal return nx * (nx >= 0 ? maxX : minX) + ny * (ny >= 0 ? maxY : minY) + nz * (nz >= 0 ? maxZ : minZ); } } + + /** if p must be drawn before q */ + public boolean isSeenThrough(int p, int q) { + return !isCoplanar(p, q) && minDot(p, normalX(q), normalY(q), normalZ(q)) < dots[q] - EPSILON + && maxDot(q, normalX(p), normalY(p), normalZ(p)) > dots[p] + EPSILON; + } } diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/SortState.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/SortState.java index e2bba4f39..85f81a5a2 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/SortState.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/SortState.java @@ -1,6 +1,6 @@ package org.embeddedt.embeddium.impl.render.chunk.sorting; -public sealed interface SortState permits SortState.None, SortState.Static, SortState.Resortable { +public sealed interface SortState { SortState NONE = new None(); /** Variant names for the debug overlay, indexed by {@link #debugIndex()} and ordered by sorting cost */ @@ -39,7 +39,7 @@ public sealed interface SortState permits SortState.None, SortState.Static, Sort @Override public SortState compactForStorage() { - return this; + return NONE; } } diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java index 5f8f38d60..06c28e337 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java @@ -116,19 +116,17 @@ public final class TranslucentSorter { return SortState.NONE; } - float[] normals = quads.normals(); - int referenceOffset = reference * 3; - float nx = normals[referenceOffset], ny = normals[referenceOffset + 1], nz = normals[referenceOffset + 2]; + float nx = quads.normalX(reference), ny = quads.normalY(reference), nz = quads.normalZ(reference); BitSet flipped = new BitSet(quadCount); + boolean allParallel = true; for (int quadIdx = 0; quadIdx < quadCount; quadIdx++) { - int normalOffset = quadIdx * 3; - float dot = nx * normals[normalOffset] + ny * normals[normalOffset + 1] + nz * normals[normalOffset + 2]; + float dot = quads.normalDot(quadIdx, reference); if (Math.abs(dot) < PARALLEL_THRESHOLD) { - // distinct normals, so which quad is in front depends on where the camera is - return new SortState.Dynamic(quads.centers()); + allParallel = false; + break; } if (dot < 0) { @@ -137,8 +135,20 @@ public final class TranslucentSorter { } } - // parallel but spread over several planes: the order cannot change, so sort once and keep only the result - return new SortState.Static(sortNormalRelative(quads.centers(), quadCount, nx, ny, nz, flipped)); + if (allParallel) { + // parallel but spread over several planes: the order cannot change, so sort once and keep only the result + return new SortState.Static(sortNormalRelative(quads.centers(), quadCount, nx, ny, nz, flipped)); + } + + if (quadCount <= MAX_TOPO_QUADS) { + int[] order = topologicalOrder(quads); + + if (order != null) { + return new SortState.Static(order); + } + } + + return new SortState.Dynamic(quads.centers()); } /** @@ -201,4 +211,11 @@ public final class TranslucentSorter { return true; } + + public static final int MAX_TOPO_QUADS = 2048; + + /** returns null if the relation has a cycle */ + public static int @Nullable [] topologicalOrder(QuadSet quads) { + return null; + } } -- 2.54.1 From b3a509d36f8b458ed9ad47041f10dacbe00b4cd2 Mon Sep 17 00:00:00 2001 From: rdh Date: Wed, 9 Sep 2026 19:07:07 -0400 Subject: [PATCH 05/23] toposort! --- .../chunk/sorting/TranslucentSorter.java | 51 ++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java index 06c28e337..fd89fc6fa 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java @@ -1,5 +1,7 @@ package org.embeddedt.embeddium.impl.render.chunk.sorting; +import it.unimi.dsi.fastutil.ints.IntArrayFIFOQueue; +import it.unimi.dsi.fastutil.ints.IntArrayList; import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing; import org.embeddedt.embeddium.impl.util.sorting.MergeSort; import org.jetbrains.annotations.Nullable; @@ -216,6 +218,53 @@ public final class TranslucentSorter { /** returns null if the relation has a cycle */ public static int @Nullable [] topologicalOrder(QuadSet quads) { - return null; + int n = quads.count(); + + IntArrayList[] successors = new IntArrayList[n]; + int[] predecessors = new int[n]; + + // build the graph up + for (int quadIdx = 0; quadIdx < n; quadIdx++) { + for (int otherIdx = 0; otherIdx < n; otherIdx++) { + if (quadIdx != otherIdx && quads.isSeenThrough(quadIdx, otherIdx)) { + if (successors[quadIdx] == null) { + successors[quadIdx] = new IntArrayList(); + } + + successors[quadIdx].add(otherIdx); + predecessors[otherIdx]++; + } + } + } + + // kahn's algorithm: emit quads with no predecessors and remove them from the graph + // until either all quads are emitted or a cycle is detected + IntArrayFIFOQueue ready = new IntArrayFIFOQueue(n); + for (int quadIdx = 0; quadIdx < n; quadIdx++) { + if (predecessors[quadIdx] == 0) { + ready.enqueue(quadIdx); + } + } + + int[] out = new int[n]; + int o = 0; + + while (!ready.isEmpty()) { + int current = ready.dequeueInt(); + out[o++] = current; + + IntArrayList next = successors[current]; + if (next == null) continue; + + for (int i = 0; i < next.size(); i++) { + int successor = next.getInt(i); + + if (--predecessors[successor] == 0) { + ready.enqueue(successor); + } + } + } + + return o == n ? out : null; } } -- 2.54.1 From 5418c0e64f154a9524ee31989f8a37a26cf232c5 Mon Sep 17 00:00:00 2001 From: rdh Date: Thu, 10 Sep 2026 15:17:36 -0400 Subject: [PATCH 06/23] partition tree works omg --- .../render/chunk/sorting/PartitionTree.java | 255 ++++++++++++++++++ .../impl/render/chunk/sorting/QuadSet.java | 8 + .../impl/render/chunk/sorting/SortState.java | 6 +- .../chunk/sorting/TranslucentSorter.java | 7 + 4 files changed, 273 insertions(+), 3 deletions(-) create mode 100644 common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java new file mode 100644 index 000000000..f48910add --- /dev/null +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java @@ -0,0 +1,255 @@ +package org.embeddedt.embeddium.impl.render.chunk.sorting; + +import it.unimi.dsi.fastutil.floats.FloatArrayList; +import it.unimi.dsi.fastutil.floats.FloatArrays; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.ints.IntArrays; +import org.jetbrains.annotations.Nullable; + +public final class PartitionTree implements SortState.Resortable { + + private final Node root; + private final int quadCount; + private final float[][] cutPlanes; + + private PartitionTree(Node root, int quadCount, float[][] cutPlanes) { + this.root = root; + this.quadCount = quadCount; + this.cutPlanes = cutPlanes; + } + + // null when some slab has no free cut + public static @Nullable PartitionTree build(QuadSet quads) { + int[] all = new int[quads.count()]; + for (int i = 0; i < all.length; i++) all[i] = i; + + FloatArrayList[] cuts = { new FloatArrayList(), new FloatArrayList(), new FloatArrayList() }; + Node root = partition(quads, all, 2, cuts); + if (root == null) return null; + + float[][] cutPlanes = new float[3][]; + for (int a = 0; a < 3; a++) { + cutPlanes[a] = sortAndDedup(cuts[a]); + } + return new PartitionTree(root, quads.count(), cutPlanes); + } + + private static float[] sortAndDedup(FloatArrayList floats) { + float[] array = floats.toFloatArray(); + FloatArrays.quickSort(array); + + int n = 0; + for (int i = 0; i < array.length; i++) { + if (n == 0 || array[i] != array[n - 1]) { + array[n++] = array[i]; + } + } + return FloatArrays.copy(array, 0, n); + } + + private static Node partition(QuadSet quads, int[] group, int parentAxis, FloatArrayList[] collectedCuts) { + if (group.length <= 1 || isAllCoplanar(quads, group)) { + return new Leaf(group); + } + + int axis = -1; + float[] planes = FloatArrays.EMPTY_ARRAY; + for (int i = 0; i < 3; i++) { + axis = (parentAxis + 1 + i) % 3; + planes = cutsOn(quads, group, axis); + if (planes.length > 0) break; + } + if (planes.length == 0) { + return null; // unpartitionable + } + + int slabCount = planes.length + 1; + IntArrayList[] onPlaneLists = new IntArrayList[planes.length]; + for (int i = 0; i < planes.length; i++) onPlaneLists[i] = new IntArrayList(); + IntArrayList[] slabLists = new IntArrayList[slabCount]; + for (int i = 0; i < slabCount; i++) slabLists[i] = new IntArrayList(); + + for (int quad : group) { + float lo = quads.boundsMin(quad, axis), hi = quads.boundsMax(quad, axis); + + // slab = number of planes at or below this quad's lo + int slab = 0; + while (slab < planes.length && planes[slab] <= lo + QuadSet.EPSILON) slab++; + + if (hi - lo <= QuadSet.EPSILON && slab > 0 && Math.abs(planes[slab - 1] - lo) <= QuadSet.EPSILON) { + onPlaneLists[slab - 1].add(quad); + } else { + slabLists[slab].add(quad); + } + } + + Node[] slabs = new Node[slabCount]; + for (int i = 0; i < slabCount; i++) { + int[] slabGroup = slabLists[i].toIntArray(); + if (slabGroup.length == 0) { + slabs[i] = EMPTY; + continue; + } + Node child = partition(quads, slabGroup, axis, collectedCuts); + if (child == null) return null; + slabs[i] = child; + } + + int[][] onPlane = new int[planes.length][]; + for (int i = 0; i < planes.length; i++) { + onPlane[i] = onPlaneLists[i].toIntArray(); + } + + for (float plane : planes) { + collectedCuts[axis].add(plane); + } + return new Split(axis, planes, slabs, onPlane); + } + + private static boolean isAllCoplanar(QuadSet quads, int[] group) { + for (int i = 1; i < group.length; i++) { + if (!quads.isCoplanar(group[0], group[i])) { + return false; + } + } + return true; + } + + private static float[] cutsOn(QuadSet quads, int[] group, int axis) { + int n = group.length; + + // a quad either spans an interval on this axis, or lies flat on a single plane + float[] starts = new float[n], ends = new float[n], points = new float[n]; + int startCount = 0, endCount = 0, pointCount = 0; + + for (int quad : group) { + float lo = quads.boundsMin(quad, axis), hi = quads.boundsMax(quad, axis); + + if (hi - lo <= QuadSet.EPSILON) { + points[pointCount++] = lo; + } else { + starts[startCount++] = lo; + ends[endCount++] = hi; + } + } + + FloatArrays.quickSort(starts, 0, startCount); + FloatArrays.quickSort(ends, 0, endCount); + FloatArrays.quickSort(points, 0, pointCount); + + FloatArrayList cuts = new FloatArrayList(); + + int nextStart = 0, nextEnd = 0, nextPoint = 0; + int opened = 0; + int below = 0; + int sinceCut = 0; + + // only ends/planes can be cuts since a gap is always available at the last end before it, + // and a cut anywhere else in that gap would separate the same quads + while (nextEnd < endCount || nextPoint < pointCount) { + float plane = nextPoint == pointCount ? ends[nextEnd] + : nextEnd == endCount ? points[nextPoint] + : Math.min(ends[nextEnd], points[nextPoint]); + + // ends first, then quads on the plane, then starts: a quad beginning here is not yet in the way + while (nextEnd < endCount && ends[nextEnd] <= plane + QuadSet.EPSILON) { + nextEnd++; + below++; + sinceCut++; + } + + int onPlane = 0; + + while (nextPoint < pointCount && points[nextPoint] <= plane + QuadSet.EPSILON) { + nextPoint++; + onPlane++; + } + + while (nextStart < startCount && starts[nextStart] < plane - QuadSet.EPSILON) { + nextStart++; + opened++; + } + + int above = n - below - onPlane; + boolean free = opened == nextEnd; // nothing spans the plane + boolean useful = (below > 0 ? 1 : 0) + (onPlane > 0 ? 1 : 0) + (above > 0 ? 1 : 0) >= 2; + boolean separatesSomethingNew = onPlane > 0 || sinceCut > 0; + + if (free && useful && separatesSomethingNew) { + cuts.add(plane); + sinceCut = 0; + } + + // quads on this plane are behind the next one either way + below += onPlane; + sinceCut += onPlane; + } + + return cuts.toFloatArray(); + } + + public float[] cutPlanes(int axis) { + return cutPlanes[axis]; + } + + public int @Nullable [] order(float camX, float camY, float camZ) { + int[] order = new int[quadCount]; + write(root, camX, camY, camZ, order, 0); + return order; + } + + // returns the position just past the last quad written + private static int write(Node node, float camX, float camY, float camZ, int[] order, int pos) { + if (node instanceof Leaf leaf) { + System.arraycopy(leaf.quads, 0, order, pos, leaf.quads.length); + return pos + leaf.quads.length; + } + + Split split = (Split) node; + float camCoord = switch (split.axis) { + case 0 -> camX; + case 1 -> camY; + case 2 -> camZ; + default -> throw new AssertionError(); + }; + + int slab = 0; + while (slab < split.planes.length && split.planes[slab] <= camCoord + QuadSet.EPSILON) slab++; + + // slabs below the camera's, farthest first, each followed by the plane above it + for (int i = 0; i < slab; i++) { + pos = write(split.slabs[i], camX, camY, camZ, order, pos); + pos = writePlane(split.onPlane[i], order, pos); + } + + // slabs above the camera's, farthest first, each followed by the plane below it + for (int i = split.slabs.length - 1; i > slab; i--) { + pos = write(split.slabs[i], camX, camY, camZ, order, pos); + pos = writePlane(split.onPlane[i - 1], order, pos); + } + + // the camera's own slab is nearest, drawn last + return write(split.slabs[slab], camX, camY, camZ, order, pos); + } + + private static int writePlane(int[] quads, int[] order, int pos) { + System.arraycopy(quads, 0, order, pos, quads.length); + return pos + quads.length; + } + + @Override + public int debugIndex() { + return 2; + } + + @Override + public int quadCount() { + return quadCount; + } + + private static final Node EMPTY = new Leaf(IntArrays.EMPTY_ARRAY); + + sealed interface Node permits Leaf, Split {} + record Leaf(int[] quads) implements Node {} + record Split(int axis, float[] planes, Node[] slabs, int[][] onPlane) implements Node {} +} diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/QuadSet.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/QuadSet.java index 3c853b58a..18f9c6f1e 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/QuadSet.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/QuadSet.java @@ -128,4 +128,12 @@ public record QuadSet(int count, float[] centers, float[] bounds, float[] normal return !isCoplanar(p, q) && minDot(p, normalX(q), normalY(q), normalZ(q)) < dots[q] - EPSILON && maxDot(q, normalX(p), normalY(p), normalZ(p)) > dots[p] + EPSILON; } + + public float boundsMin(int quad, int axis) { + return bounds[quad * 6 + axis]; + } + + public float boundsMax(int quad, int axis) { + return bounds[quad * 6 + 3 + axis]; + } } diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/SortState.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/SortState.java index 85f81a5a2..3d05ff1cf 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/SortState.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/SortState.java @@ -4,7 +4,7 @@ public sealed interface SortState { SortState NONE = new None(); /** Variant names for the debug overlay, indexed by {@link #debugIndex()} and ordered by sorting cost */ - String[] DEBUG_NAMES = { "NONE", "STATIC", "DYNAMIC" }; + String[] DEBUG_NAMES = { "NONE", "STATIC", "TREE", "DYNAMIC" }; /** Position in {@link #DEBUG_NAMES}, doubling as the cost ranking used to pick a section's highest variant */ int debugIndex(); @@ -18,7 +18,7 @@ public sealed interface SortState { } /** A state whose order depends on the camera, and so survives compaction to be re-sorted on every move */ - sealed interface Resortable extends SortState permits Dynamic { + sealed interface Resortable extends SortState permits Dynamic, PartitionTree { @Override default Resortable compactForStorage() { return this; @@ -66,7 +66,7 @@ public sealed interface SortState { record Dynamic(float[] centers) implements Resortable { @Override public int debugIndex() { - return 2; + return 3; } @Override diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java index fd89fc6fa..62672bc86 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java @@ -80,6 +80,10 @@ public final class TranslucentSorter { return sortByDistance(dynamic.centers(), dynamic.quadCount(), camX, camY, camZ); } + if (state instanceof PartitionTree tree) { + return tree.order(camX, camY, camZ); + } + return null; } @@ -150,6 +154,9 @@ public final class TranslucentSorter { } } + PartitionTree tree = PartitionTree.build(quads); + if (tree != null) return tree; + return new SortState.Dynamic(quads.centers()); } -- 2.54.1 From 8a61753c87f2868a3e97f6e896a553a799db9a8a Mon Sep 17 00:00:00 2001 From: rdh Date: Thu, 10 Sep 2026 16:54:27 -0400 Subject: [PATCH 07/23] resort trees only when crossing cut planes --- .../impl/render/chunk/RenderSection.java | 14 +++++ .../render/chunk/RenderSectionManager.java | 61 ++++++++++++------- .../render/chunk/sorting/PartitionTree.java | 16 +++++ 3 files changed, 70 insertions(+), 21 deletions(-) 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 28b4d3ffd..d194ef9a0 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 @@ -8,6 +8,7 @@ import org.embeddedt.embeddium.impl.render.chunk.occlusion.VisibilityEncoding; import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; import org.embeddedt.embeddium.impl.util.task.CancellationToken; +import org.embeddedt.embeddium.impl.render.chunk.sorting.PartitionTree; import org.embeddedt.embeddium.impl.render.chunk.sorting.SortState; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -73,6 +74,9 @@ public class RenderSection extends AbstractSection { @Setter private boolean needsDynamicTranslucencySorting; + @Getter + private boolean treeSorted; + // Pending Update State // The in-flight build job for this section, if one exists. Serves two purposes: @@ -194,6 +198,16 @@ public class RenderSection extends AbstractSection { this.translucencySortStates = Map.copyOf(sortStates); this.highestSortingIndex = highestSortingIndex; this.needsDynamicTranslucencySorting = !sortStates.isEmpty(); + this.treeSorted = !sortStates.isEmpty() && sortStates.values().stream().allMatch(state -> state instanceof PartitionTree); + } + + public boolean crossesAnyCutPlane(double lastX, double lastY, double lastZ, double camX, double camY, double camZ) { + for (SortState.Resortable state : this.translucencySortStates.values()) { + if (((PartitionTree) state).crossesCutPlane(lastX, lastY, lastZ, camX, camY, camZ)) { + return true; + } + } + return false; } public @Nullable CancellationToken getBuildCancellationToken() { diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java index 1e47362d0..7137695e2 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java @@ -300,29 +300,42 @@ public abstract class RenderSectionManager { continue; } - double dx = cameraPosition.x - section.lastCameraX; - double dy = cameraPosition.y - section.lastCameraY; - double dz = cameraPosition.z - section.lastCameraZ; - double camDelta = (dx * dx) + (dy * dy) + (dz * dz); + if (section.isTreeSorted()) { + boolean crossed = section.crossesAnyCutPlane( + section.lastCameraX - section.getOriginX(), section.lastCameraY - section.getOriginY(), section.lastCameraZ - section.getOriginZ(), + cameraPosition.x - section.getOriginX(), cameraPosition.y - section.getOriginY(), cameraPosition.z - section.getOriginZ() + ); - if (camDelta < 1) { - // Didn't move enough, ignore - continue; + if (!crossed) { + continue; + } + } else { + double dx = cameraPosition.x - section.lastCameraX; + double dy = cameraPosition.y - section.lastCameraY; + double dz = cameraPosition.z - section.lastCameraZ; + double camDelta = (dx * dx) + (dy * dy) + (dz * dz); + + if (camDelta < 1) { + // Didn't move enough, ignore + continue; + } + + boolean cameraChangedSection = camSectionX != PositionUtil.posToSectionCoord(section.lastCameraX) || + camSectionY != PositionUtil.posToSectionCoord(section.lastCameraY) || + camSectionZ != PositionUtil.posToSectionCoord(section.lastCameraZ); + + if (!cameraChangedSection && !section.isAlignedWithSectionOnGrid(camSectionX, camSectionY, camSectionZ)) { + continue; + } } - boolean cameraChangedSection = camSectionX != PositionUtil.posToSectionCoord(section.lastCameraX) || - camSectionY != PositionUtil.posToSectionCoord(section.lastCameraY) || - camSectionZ != PositionUtil.posToSectionCoord(section.lastCameraZ); + section.setPendingUpdate(update); + // Inject it into the appropriate list + rebuildLists.get(update).add(section); - if (cameraChangedSection || section.isAlignedWithSectionOnGrid(camSectionX, camSectionY, camSectionZ)) { - section.setPendingUpdate(update); - // Inject it into the appropriate list - rebuildLists.get(update).add(section); - - section.lastCameraX = cameraPosition.x; - section.lastCameraY = cameraPosition.y; - section.lastCameraZ = cameraPosition.z; - } + section.lastCameraX = cameraPosition.x; + section.lastCameraY = cameraPosition.y; + section.lastCameraZ = cameraPosition.z; } } } @@ -618,6 +631,10 @@ public abstract class RenderSectionManager { } render.setTranslucencySortStates(sortStates.isEmpty() ? Collections.emptyMap() : sortStates, highestIndex); + + render.lastCameraX = this.cameraPosition.x; + render.lastCameraY = this.cameraPosition.y; + render.lastCameraZ = this.cameraPosition.z; } // Section MetadataSink: mirrors a section's packed metadata into the graph-search lattice on every @@ -1024,11 +1041,13 @@ public abstract class RenderSectionManager { var rebuildLists = this.getCurrentRenderListManager().getRebuildLists(); - list.add(String.format("Chunk Queues: U=%02d (P0=%03d | P1=%03d | P2=%03d)", + list.add(String.format("Chunk Queues: U=%02d (P0=%03d | P1=%03d | P2=%03d) S=%03d/%03d", this.buildResults.size(), rebuildLists.getUpdateCount(ChunkUpdateType.IMPORTANT_REBUILD), rebuildLists.getUpdateCount(ChunkUpdateType.REBUILD), - rebuildLists.getUpdateCount(ChunkUpdateType.INITIAL_BUILD) + rebuildLists.getUpdateCount(ChunkUpdateType.INITIAL_BUILD), + rebuildLists.getUpdateCount(ChunkUpdateType.IMPORTANT_SORT), + rebuildLists.getUpdateCount(ChunkUpdateType.SORT) )); var debugStats = renderListManager.getDebugStatistics(); diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java index f48910add..8b0d8006f 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java @@ -237,6 +237,22 @@ public final class PartitionTree implements SortState.Resortable { return pos + quads.length; } + public boolean crossesCutPlane(double lastX, double lastY, double lastZ, double camX, double camY, double camZ) { + return crossesOnAxis(0, lastX, camX) || crossesOnAxis(1, lastY, camY) || crossesOnAxis(2, lastZ, camZ); + } + + private boolean crossesOnAxis(int axis, double from, double to) { + double lo = Math.min(from, to), hi = Math.max(from, to); + + for (float cut : cutPlanes[axis]) { + if (cut > lo && cut <= hi) { + return true; + } + } + + return false; + } + @Override public int debugIndex() { return 2; -- 2.54.1 From 8627794f2a9f68c47a9e8abfaec6d8b7a902c263 Mon Sep 17 00:00:00 2001 From: rdh Date: Sun, 13 Sep 2026 16:00:16 -0400 Subject: [PATCH 08/23] index cut planes into per-section buckets removes the need to check every section for if the camera has crossed a cut plane --- .../impl/render/chunk/RenderSection.java | 9 - .../render/chunk/RenderSectionManager.java | 113 +++++++++---- .../render/chunk/sorting/CutPlaneIndex.java | 155 ++++++++++++++++++ .../render/chunk/sorting/PartitionTree.java | 20 +++ 4 files changed, 255 insertions(+), 42 deletions(-) create mode 100644 common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/CutPlaneIndex.java 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 d194ef9a0..a66a9e9af 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 @@ -201,15 +201,6 @@ public class RenderSection extends AbstractSection { this.treeSorted = !sortStates.isEmpty() && sortStates.values().stream().allMatch(state -> state instanceof PartitionTree); } - public boolean crossesAnyCutPlane(double lastX, double lastY, double lastZ, double camX, double camY, double camZ) { - for (SortState.Resortable state : this.translucencySortStates.values()) { - if (((PartitionTree) state).crossesCutPlane(lastX, lastY, lastZ, camX, camY, camZ)) { - return true; - } - } - return false; - } - public @Nullable CancellationToken getBuildCancellationToken() { return this.buildCancellationToken; } diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java index 7137695e2..56f3e0432 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java @@ -38,6 +38,8 @@ import org.embeddedt.embeddium.impl.render.viewport.Viewport; import org.embeddedt.embeddium.impl.render.viewport.frustum.ShadowSearchFrustum; import org.embeddedt.embeddium.impl.util.PositionUtil; import org.embeddedt.embeddium.impl.util.iterator.ByteIterator; +import org.embeddedt.embeddium.impl.render.chunk.sorting.CutPlaneIndex; +import org.embeddedt.embeddium.impl.render.chunk.sorting.PartitionTree; import org.embeddedt.embeddium.impl.render.chunk.sorting.SortState; import org.embeddedt.embeddium.impl.util.suppliers.ExpiringSupplier; import org.jetbrains.annotations.MustBeInvokedByOverriders; @@ -82,9 +84,16 @@ public abstract class RenderSectionManager { private final int renderDistance; - protected @Nullable Vector3ic lastCameraPosition; + /** {@link #cameraPosition}, rounded down to block coordinates */ + protected @Nullable Vector3ic cameraBlockPosition; + protected Vector3d cameraPosition = new Vector3d(); + /** last frame's exact camera position */ + protected @Nullable Vector3d previousCameraPosition; + + private final CutPlaneIndex cutPlaneIndex = new CutPlaneIndex<>(); + @Getter private final RenderPassConfiguration renderPassConfiguration; @@ -199,7 +208,9 @@ public abstract class RenderSectionManager { * per-frame camera bookkeeping. */ public void update(Viewport positionedViewport, int frame, boolean spectator) { - this.updateCameraPosition(positionedViewport); + if (!this.shadowPassRanThisFrame) { + this.updateCameraPosition(positionedViewport); + } if (this.shadowPassRanThisFrame) { // The shadow pass searched for this frame if the graph was dirty then. Any needsUpdate raised by @@ -239,7 +250,11 @@ public abstract class RenderSectionManager { } private void updateCameraPosition(Viewport positionedViewport) { - this.lastCameraPosition = positionedViewport.getBlockCoord(); + if (this.cameraBlockPosition != null) { + this.previousCameraPosition = this.cameraPosition; + } + + this.cameraBlockPosition = positionedViewport.getBlockCoord(); var transform = positionedViewport.getTransform(); this.cameraPosition = new Vector3d(transform.x, transform.y, transform.z); } @@ -257,7 +272,7 @@ public abstract class RenderSectionManager { } private void checkTranslucencyChange() { - if(lastCameraPosition == null) + if(cameraBlockPosition == null) return; int camSectionX = PositionUtil.posToSectionCoord(cameraPosition.x); @@ -265,6 +280,7 @@ public abstract class RenderSectionManager { int camSectionZ = PositionUtil.posToSectionCoord(cameraPosition.z); this.scheduleTranslucencyUpdates(camSectionX, camSectionY, camSectionZ); + this.scheduleTreeSortedUpdates(); } private void scheduleTranslucencyUpdates(int camSectionX, int camSectionY, int camSectionZ) { @@ -288,8 +304,8 @@ public abstract class RenderSectionManager { while (sectionIterator.hasNext()) { var section = region.getSection(sectionIterator.nextByteAsInt()); - if (section == null || !section.isNeedsDynamicTranslucencySorting()) { - // Sections without sortable translucent data are not relevant + // tree-sorted sections are retriggered by scheduleTreeSortedUpdates() instead + if (section == null || !section.isNeedsDynamicTranslucencySorting() || section.isTreeSorted()) { continue; } @@ -300,33 +316,22 @@ public abstract class RenderSectionManager { continue; } - if (section.isTreeSorted()) { - boolean crossed = section.crossesAnyCutPlane( - section.lastCameraX - section.getOriginX(), section.lastCameraY - section.getOriginY(), section.lastCameraZ - section.getOriginZ(), - cameraPosition.x - section.getOriginX(), cameraPosition.y - section.getOriginY(), cameraPosition.z - section.getOriginZ() - ); + double dx = cameraPosition.x - section.lastCameraX; + double dy = cameraPosition.y - section.lastCameraY; + double dz = cameraPosition.z - section.lastCameraZ; + double camDelta = (dx * dx) + (dy * dy) + (dz * dz); - if (!crossed) { - continue; - } - } else { - double dx = cameraPosition.x - section.lastCameraX; - double dy = cameraPosition.y - section.lastCameraY; - double dz = cameraPosition.z - section.lastCameraZ; - double camDelta = (dx * dx) + (dy * dy) + (dz * dz); + if (camDelta < 1) { + // Didn't move enough, ignore + continue; + } - if (camDelta < 1) { - // Didn't move enough, ignore - continue; - } + boolean cameraChangedSection = camSectionX != PositionUtil.posToSectionCoord(section.lastCameraX) || + camSectionY != PositionUtil.posToSectionCoord(section.lastCameraY) || + camSectionZ != PositionUtil.posToSectionCoord(section.lastCameraZ); - boolean cameraChangedSection = camSectionX != PositionUtil.posToSectionCoord(section.lastCameraX) || - camSectionY != PositionUtil.posToSectionCoord(section.lastCameraY) || - camSectionZ != PositionUtil.posToSectionCoord(section.lastCameraZ); - - if (!cameraChangedSection && !section.isAlignedWithSectionOnGrid(camSectionX, camSectionY, camSectionZ)) { - continue; - } + if (!cameraChangedSection && !section.isAlignedWithSectionOnGrid(camSectionX, camSectionY, camSectionZ)) { + continue; } section.setPendingUpdate(update); @@ -340,6 +345,33 @@ public abstract class RenderSectionManager { } } + /** Resorts tree-sorted sections whose cut planes this frame's movement crossed, visible or not */ + private void scheduleTreeSortedUpdates() { + if (this.previousCameraPosition == null || this.cutPlaneIndex.size() == 0) { + return; + } + + var rebuildLists = this.getCurrentRenderListManager().getRebuildLists().byUpdateType(); + var allowImportant = allowImportantRebuilds(); + + this.cutPlaneIndex.query( + this.previousCameraPosition.x, this.previousCameraPosition.y, this.previousCameraPosition.z, + this.cameraPosition.x, this.cameraPosition.y, this.cameraPosition.z, + section -> { + ChunkUpdateType update = ChunkUpdateType.getPromotionUpdateType(section.getPendingUpdate(), + (allowImportant && this.shouldPrioritizeRebuild(section)) ? ChunkUpdateType.IMPORTANT_SORT : ChunkUpdateType.SORT); + + if (update == null) { + // We wouldn't be able to resort this section anyway + return; + } + + section.setPendingUpdate(update); + rebuildLists.get(update).add(section); + } + ); + } + /** * {@return true if the renderer should respect per-frame queue limits and not try to update as many chunks as * possible per frame} @@ -440,6 +472,8 @@ public abstract class RenderSectionManager { this.sectionMetricsTracker.removeSection(section); + this.cutPlaneIndex.remove(section); + section.delete(); this.markGraphDirty(); @@ -632,6 +666,18 @@ public abstract class RenderSectionManager { render.setTranslucencySortStates(sortStates.isEmpty() ? Collections.emptyMap() : sortStates, highestIndex); + if (render.isTreeSorted()) { + List trees = new ArrayList<>(sortStates.size()); + for (var state : sortStates.values()) { + trees.add((PartitionTree) state); + } + + this.cutPlaneIndex.put(render, PartitionTree.mergeCutPlanes(trees), render.getOriginX(), render.getOriginY(), render.getOriginZ()); + } else { + // a rebuild that is no longer tree-sorted must drop its stale planes + this.cutPlaneIndex.remove(render); + } + render.lastCameraX = this.cameraPosition.x; render.lastCameraY = this.cameraPosition.y; render.lastCameraZ = this.cameraPosition.z; @@ -904,7 +950,7 @@ public abstract class RenderSectionManager { private static final float NEARBY_REBUILD_DISTANCE = MathUtil.square(16.0f); private boolean shouldPrioritizeRebuild(RenderSection section) { - return this.lastCameraPosition != null && section.getSquaredDistanceFromBlockCenter(this.lastCameraPosition.x(), this.lastCameraPosition.y(), this.lastCameraPosition.z()) < NEARBY_REBUILD_DISTANCE; + return this.cameraBlockPosition != null && section.getSquaredDistanceFromBlockCenter(this.cameraBlockPosition.x(), this.cameraBlockPosition.y(), this.cameraBlockPosition.z()) < NEARBY_REBUILD_DISTANCE; } /** @@ -1041,13 +1087,14 @@ public abstract class RenderSectionManager { var rebuildLists = this.getCurrentRenderListManager().getRebuildLists(); - list.add(String.format("Chunk Queues: U=%02d (P0=%03d | P1=%03d | P2=%03d) S=%03d/%03d", + list.add(String.format("Chunk Queues: U=%02d (P0=%03d | P1=%03d | P2=%03d) S=%03d/%03d I=%03d", this.buildResults.size(), rebuildLists.getUpdateCount(ChunkUpdateType.IMPORTANT_REBUILD), rebuildLists.getUpdateCount(ChunkUpdateType.REBUILD), rebuildLists.getUpdateCount(ChunkUpdateType.INITIAL_BUILD), rebuildLists.getUpdateCount(ChunkUpdateType.IMPORTANT_SORT), - rebuildLists.getUpdateCount(ChunkUpdateType.SORT) + rebuildLists.getUpdateCount(ChunkUpdateType.SORT), + this.cutPlaneIndex.size() )); var debugStats = renderListManager.getDebugStatistics(); diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/CutPlaneIndex.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/CutPlaneIndex.java new file mode 100644 index 000000000..866d27cce --- /dev/null +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/CutPlaneIndex.java @@ -0,0 +1,155 @@ +package org.embeddedt.embeddium.impl.render.chunk.sorting; + +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.longs.LongArrayList; +import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet; + +import java.util.function.Consumer; + +public final class CutPlaneIndex { + /** movements larger than this many buckets rescan every owner instead of walking the buckets */ + static final int MAX_BUCKET_SPAN = 64; + + private record Registration(float[][] cuts, int[] origin, long[][] buckets) { + } + + @SuppressWarnings("unchecked") + private final Long2ObjectOpenHashMap>[] bucketsByAxis = new Long2ObjectOpenHashMap[] { + new Long2ObjectOpenHashMap<>(), new Long2ObjectOpenHashMap<>(), new Long2ObjectOpenHashMap<>() + }; + + private final Reference2ObjectOpenHashMap> registrations = new Reference2ObjectOpenHashMap<>(); + + private final ReferenceOpenHashSet reported = new ReferenceOpenHashSet<>(); + + public void put(T owner, float[][] cutsByAxis, int originX, int originY, int originZ) { + remove(owner); + + if (cutsByAxis[0].length == 0 && cutsByAxis[1].length == 0 && cutsByAxis[2].length == 0) { + // a leaf's order can never change, so it's not worth indexing + return; + } + + int[] origin = { originX, originY, originZ }; + long[][] buckets = new long[3][]; + + for (int axis = 0; axis < 3; axis++) { + LongArrayList keys = new LongArrayList(); + long lastKey = 0; + boolean first = true; + + // cutsByAxis[axis] is sorted, so equal bucket keys are adjacent + for (float cut : cutsByAxis[axis]) { + long key = bucketKey(cut, origin[axis]); + if (first || key != lastKey) { + keys.add(key); + lastKey = key; + first = false; + } + } + + buckets[axis] = keys.toLongArray(); + + for (long key : buckets[axis]) { + this.bucketsByAxis[axis].computeIfAbsent(key, k -> new ReferenceOpenHashSet<>()).add(owner); + } + } + + this.registrations.put(owner, new Registration<>(cutsByAxis, origin, buckets)); + } + + public void remove(T owner) { + Registration registration = this.registrations.remove(owner); + + if (registration == null) { + return; + } + + for (int axis = 0; axis < 3; axis++) { + var map = this.bucketsByAxis[axis]; + + for (long key : registration.buckets[axis]) { + ReferenceOpenHashSet owners = map.get(key); + if (owners == null) continue; + + owners.remove(owner); + + if (owners.isEmpty()) { + map.remove(key); + } + } + } + } + + public void query(double fromX, double fromY, double fromZ, double toX, double toY, double toZ, Consumer out) { + if (this.registrations.isEmpty()) { + return; + } + + try { + queryAxis(0, fromX, toX, out); + queryAxis(1, fromY, toY, out); + queryAxis(2, fromZ, toZ, out); + } finally { + this.reported.clear(); + } + } + + private void queryAxis(int axis, double from, double to, Consumer out) { + double lo = Math.min(from, to), hi = Math.max(from, to); + + if (lo == hi) return; + + long loBucket = (long) Math.floor(lo); + long hiBucket = (long) Math.floor(hi); + + if (hiBucket - loBucket > MAX_BUCKET_SPAN) { + var iterator = this.registrations.reference2ObjectEntrySet().fastIterator(); + while (iterator.hasNext()) { + var entry = iterator.next(); + considerCandidate(entry.getKey(), entry.getValue(), axis, lo, hi, out); + } + return; + } + + var map = this.bucketsByAxis[axis]; + + for (long bucket = loBucket; bucket <= hiBucket; bucket++) { + ReferenceOpenHashSet candidates = map.get(bucket); + + if (candidates == null) { + continue; + } + + for (T candidate : candidates) { + considerCandidate(candidate, this.registrations.get(candidate), axis, lo, hi, out); + } + } + } + + private void considerCandidate(T owner, Registration registration, int axis, double lo, double hi, Consumer out) { + if (registration == null || this.reported.contains(owner)) { + return; + } + + double loLocal = lo - registration.origin[axis]; + double hiLocal = hi - registration.origin[axis]; + + for (float cut : registration.cuts[axis]) { + if (cut > loLocal && cut <= hiLocal) { + this.reported.add(owner); + out.accept(owner); + return; + } + } + } + + private static long bucketKey(float localCoord, int origin) { + return (long) Math.floor((double) localCoord + (double) origin); + } + + public int size() { + return this.registrations.size(); + } +} diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java index 8b0d8006f..699f11058 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java @@ -6,6 +6,8 @@ import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntArrays; import org.jetbrains.annotations.Nullable; +import java.util.Collection; + public final class PartitionTree implements SortState.Resortable { private final Node root; @@ -34,6 +36,24 @@ public final class PartitionTree implements SortState.Resortable { return new PartitionTree(root, quads.count(), cutPlanes); } + public static float[][] mergeCutPlanes(Collection trees) { + FloatArrayList[] merged = { new FloatArrayList(), new FloatArrayList(), new FloatArrayList() }; + + for (PartitionTree tree : trees) { + for (int axis = 0; axis < 3; axis++) { + for (float cut : tree.cutPlanes(axis)) { + merged[axis].add(cut); + } + } + } + + float[][] result = new float[3][]; + for (int axis = 0; axis < 3; axis++) { + result[axis] = sortAndDedup(merged[axis]); + } + return result; + } + private static float[] sortAndDedup(FloatArrayList floats) { float[] array = floats.toFloatArray(); FloatArrays.quickSort(array); -- 2.54.1 From 62a85cea4d4637755ad8d235902a7693b9a9e0d8 Mon Sep 17 00:00:00 2001 From: rdh Date: Sun, 13 Sep 2026 19:41:23 -0400 Subject: [PATCH 09/23] primary intersector detection just a heuristic, but easier to make than full quad splitting if we find intersecting geometry, split it and render the intersecting stuff first see page 30, "Handling of Special Cases" --- .../render/chunk/sorting/PartitionTree.java | 57 ++++++++++++++++++- 1 file changed, 55 insertions(+), 2 deletions(-) diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java index 699f11058..1603e7b42 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java @@ -80,7 +80,7 @@ public final class PartitionTree implements SortState.Resortable { if (planes.length > 0) break; } if (planes.length == 0) { - return null; // unpartitionable + return partitionIntersectors(quads, group, collectedCuts); } int slabCount = planes.length + 1; @@ -126,6 +126,54 @@ public final class PartitionTree implements SortState.Resortable { return new Split(axis, planes, slabs, onPlane); } + private static @Nullable Node partitionIntersectors(QuadSet quads, int[] group, FloatArrayList[] collectedCuts) { + int n = group.length; + if (n > TranslucentSorter.MAX_TOPO_QUADS) return null; + + int[] degree = new int[n]; + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + if (intersects(quads, group[i], group[j])) { + degree[i]++; + degree[j]++; + } + } + } + + boolean[] primary = new boolean[n]; + int count = 0; + while (true) { + int best = -1; + for (int i = 0; i < n; i++) { + if (degree[i] > 0 && (best < 0 || degree[i] > degree[best])) best = i; + } + if (best < 0) break; + primary[best] = true; + count++; + degree[best] = 0; + for (int j = 0; j < n; j++) { + if (!primary[j] && intersects(quads, group[best], group[j])) degree[j]--; + } + } + if (count == 0 || count == n) return null; + + int[] first = new int[count], rest = new int[n - count]; + for (int i = 0, f = 0, r = 0; i < n; i++) { + if (primary[i]) first[f++] = group[i]; else rest[r++] = group[i]; + } + Node a = partition(quads, first, 2, collectedCuts); + Node b = a == null ? null : partition(quads, rest, 2, collectedCuts); + return b == null ? null : new Fixed(a, b); + } + + private static boolean intersects(QuadSet quads, int p, int q) { + for (int axis = 0; axis < 3; axis++) { + if (quads.boundsMin(p, axis) >= quads.boundsMax(q, axis) - QuadSet.EPSILON + || quads.boundsMin(q, axis) >= quads.boundsMax(p, axis) - QuadSet.EPSILON) return false; + } + return true; + } + private static boolean isAllCoplanar(QuadSet quads, int[] group) { for (int i = 1; i < group.length; i++) { if (!quads.isCoplanar(group[0], group[i])) { @@ -225,6 +273,10 @@ public final class PartitionTree implements SortState.Resortable { return pos + leaf.quads.length; } + if (node instanceof Fixed fixed) { + return write(fixed.rest, camX, camY, camZ, order, write(fixed.first, camX, camY, camZ, order, pos)); + } + Split split = (Split) node; float camCoord = switch (split.axis) { case 0 -> camX; @@ -285,7 +337,8 @@ public final class PartitionTree implements SortState.Resortable { private static final Node EMPTY = new Leaf(IntArrays.EMPTY_ARRAY); - sealed interface Node permits Leaf, Split {} + sealed interface Node permits Leaf, Split, Fixed {} record Leaf(int[] quads) implements Node {} record Split(int axis, float[] planes, Node[] slabs, int[][] onPlane) implements Node {} + record Fixed(Node first, Node rest) implements Node {} } -- 2.54.1 From 6418e3e5f099c30b2dfca1324e6f5e50868b2c05 Mon Sep 17 00:00:00 2001 From: embeddedt <42941056+embeddedt@users.noreply.github.com> Date: Sun, 13 Sep 2026 19:53:24 -0400 Subject: [PATCH 10/23] Track DYNAMIC-sorted sections more efficiently --- .../render/chunk/PackedSectionMetadata.java | 36 +++++++++--------- .../impl/render/chunk/RenderSection.java | 38 +++++++++++++++---- .../render/chunk/RenderSectionManager.java | 8 ++-- .../render/chunk/lists/ChunkRenderList.java | 14 +++++++ .../chunk/lists/RenderVisualsService.java | 1 + 5 files changed, 68 insertions(+), 29 deletions(-) diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java index aa96a8b11..f0f331245 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java @@ -15,7 +15,7 @@ import org.jetbrains.annotations.Nullable; * *

Bit layout: *

- * 63                 54 53 52 51       49 48      46 45                0
+ * 63                 55 54 53 52       50 49      46 45                0
  * +--------------------+--+--+-----------+----------+-------------------+
  * |       spare        |OD|IF| pending   | visuals  | visibility graph  |
  * +--------------------+--+--+-----------+----------+-------------------+
@@ -26,12 +26,12 @@ import org.jetbrains.annotations.Nullable;
  *       another. Each eight-bit row uses its six low bits; the two padding
  *       positions are not part of the visibility field (the final row's
  *       padding is reused by the visual flags).
- *   
  • Bits {@code 46..48}: {@link RenderVisualsService} visual flags.
  • - *
  • Bits {@code 49..51}: pending update type; zero means none, otherwise + *
  • Bits {@code 46..49}: {@link RenderVisualsService} visual flags.
  • + *
  • Bits {@code 50..52}: pending update type; zero means none, otherwise * {@code ChunkUpdateType.ordinal() + 1}.
  • - *
  • Bit {@code 52}: a build is in flight.
  • - *
  • Bit {@code 53}: the section's built data has occluder boxes.
  • - *
  • Bits {@code 54..63}: reserved.
  • + *
  • Bit {@code 53}: a build is in flight.
  • + *
  • Bit {@code 54}: the section's built data has occluder boxes.
  • + *
  • Bits {@code 55..63}: reserved.
  • * * *

    The visibility graph uses only bits {@code 0..45}, but @@ -54,20 +54,20 @@ public final class PackedSectionMetadata { private static final int VISIBILITY_BITS = 46; public static final long VISIBILITY_MASK = (1L << VISIBILITY_BITS) - 1; - // Bits 46..48: RenderVisualsService.HAS_* flags. + // Bits 46..49: RenderVisualsService flags. private static final int VISUALS_FLAGS_SHIFT = 46; - private static final long VISUALS_FLAGS_MASK = 0b111L; + private static final long VISUALS_FLAGS_MASK = 0b1111L; - // Bits 49..51: 0 means no pending update; otherwise ordinal + 1. - private static final int PENDING_UPDATE_SHIFT = 49; + // Bits 50..52: 0 means no pending update; otherwise ordinal + 1. + private static final int PENDING_UPDATE_SHIFT = 50; 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; + // Bit 53: a build cancellation token is currently attached. + private static final int BUILD_IN_FLIGHT_BIT = 53; private static final long BUILD_IN_FLIGHT_FLAG = 1L << BUILD_IN_FLIGHT_BIT; - // Bit 53: the section's built data has occluder boxes. - private static final int HAS_OCCLUDER_DATA_BIT = 53; + // Bit 54: the section's built data has occluder boxes. + private static final int HAS_OCCLUDER_DATA_BIT = 54; private static final long HAS_OCCLUDER_DATA_FLAG = 1L << HAS_OCCLUDER_DATA_BIT; /** @@ -90,14 +90,14 @@ public final class PackedSectionMetadata { return (packed & ~VISIBILITY_MASK) | (visibilityData & VISIBILITY_MASK); } - /** Returns the three visual-presence flags. */ + /** Returns the four visual 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. + * Replaces the visual flags and preserves every other field. + * Only the four low bits of {@code flags} are stored. */ public static long withVisualsFlags(long packed, int flags) { return (packed & ~(VISUALS_FLAGS_MASK << VISUALS_FLAGS_SHIFT)) @@ -145,7 +145,7 @@ public final class PackedSectionMetadata { /* * Compact collector metadata: includes only the info the VisibleChunkCollector cares about. * - * 6 5 3 2 0 + * 7 6 4 3 0 * +--+-------+--------+ * |IF|pending|visuals | * +--+-------+--------+ 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 a66a9e9af..94b30bbc6 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 @@ -70,12 +70,15 @@ public class RenderSection extends AbstractSection { @Getter private int highestSortingIndex = NO_TRANSLUCENT_GEOMETRY; - @Getter - @Setter - private boolean needsDynamicTranslucencySorting; + public enum SortMode { + NONE, + TREE, + DYNAMIC + } @Getter - private boolean treeSorted; + @NotNull + private SortMode sortMode = SortMode.NONE; // Pending Update State @@ -154,7 +157,13 @@ public class RenderSection extends AbstractSection { } public void updateCachedContextDataFlags() { - int flags = this.contextData != null ? this.contextData.getVisualBitmaskForSection() : 0; + int flags = 0; + if (this.contextData != null) { + flags = this.contextData.getVisualBitmaskForSection(); + if (this.sortMode == SortMode.DYNAMIC) { + flags |= 1 << RenderVisualsService.NEEDS_DYNAMIC_SORT; + } + } long visibilityData = this.contextData != null ? this.contextData.visibilityData : VisibilityEncoding.NULL; boolean hasOccluderData = this.contextData != null && this.contextData.occluderBoxes != null; @@ -197,8 +206,23 @@ public class RenderSection extends AbstractSection { public void setTranslucencySortStates(@NotNull Map sortStates, int highestSortingIndex) { this.translucencySortStates = Map.copyOf(sortStates); this.highestSortingIndex = highestSortingIndex; - this.needsDynamicTranslucencySorting = !sortStates.isEmpty(); - this.treeSorted = !sortStates.isEmpty() && sortStates.values().stream().allMatch(state -> state instanceof PartitionTree); + if (sortStates.isEmpty()) { + this.sortMode = SortMode.NONE; + } else if (sortStates.values().stream().allMatch(state -> state instanceof PartitionTree)) { + this.sortMode = SortMode.TREE; + } else { + this.sortMode = SortMode.DYNAMIC; + } + this.updateCachedContextDataFlags(); + } + + public void clearTranslucencySortStates() { + this.translucencySortStates = Collections.emptyMap(); + this.sortMode = SortMode.NONE; + } + + public boolean isTreeSorted() { + return this.sortMode == SortMode.TREE; } public @Nullable CancellationToken getBuildCancellationToken() { diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java index 56f3e0432..85480eea7 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java @@ -297,7 +297,7 @@ public abstract class RenderSectionManager { if (!region.hasSectionsInPass(translucentPass)) { continue; } - ByteIterator sectionIterator = entry.sectionsWithGeometryIterator(); + ByteIterator sectionIterator = entry.sectionsNeedingDynamicSortIterator(); if (sectionIterator == null) { continue; } @@ -305,7 +305,7 @@ public abstract class RenderSectionManager { var section = region.getSection(sectionIterator.nextByteAsInt()); // tree-sorted sections are retriggered by scheduleTreeSortedUpdates() instead - if (section == null || !section.isNeedsDynamicTranslucencySorting() || section.isTreeSorted()) { + if (section == null || section.getSortMode() != RenderSection.SortMode.DYNAMIC) { continue; } @@ -789,7 +789,7 @@ public abstract class RenderSectionManager { if (!type.isSort()) { // Prevent further sorts from being performed on this section - section.setNeedsDynamicTranslucencySorting(false); + section.clearTranslucencySortStates(); } } else { var result = new ChunkJobResult.Success<>(new ChunkBuildOutput(section, RenderSection.EMPTY_DATA, Reference2ReferenceMaps.emptyMap(), frame), -1); @@ -806,7 +806,7 @@ public abstract class RenderSectionManager { protected abstract @Nullable ChunkBuilderTask createRebuildTask(RenderSection render, int frame); public ChunkBuilderSortTask createSortTask(RenderSection render, int frame) { - if(!render.isNeedsDynamicTranslucencySorting()) + if(render.getTranslucencySortStates().isEmpty()) return null; return new ChunkBuilderSortTask(render, (float)cameraPosition.x, (float)cameraPosition.y, (float)cameraPosition.z, frame, render.getTranslucencySortStates(), this.renderPassConfiguration); } diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/ChunkRenderList.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/ChunkRenderList.java index 9ee315bd5..4a45e7743 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/ChunkRenderList.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/ChunkRenderList.java @@ -19,6 +19,9 @@ public class ChunkRenderList { private final byte[] sectionsWithEntities = new byte[RenderRegion.REGION_SIZE]; private int sectionsWithEntitiesCount = 0; + private final byte[] sectionsNeedingDynamicSort = new byte[RenderRegion.REGION_SIZE]; + private int sectionsNeedingDynamicSortCount = 0; + private int size; public ChunkRenderList(RenderRegion region) { @@ -40,6 +43,17 @@ public class ChunkRenderList { this.sectionsWithEntities[this.sectionsWithEntitiesCount] = (byte) index; this.sectionsWithEntitiesCount += (flags >>> RenderVisualsService.HAS_BLOCK_ENTITIES) & 1; + + this.sectionsNeedingDynamicSort[this.sectionsNeedingDynamicSortCount] = (byte) index; + this.sectionsNeedingDynamicSortCount += (flags >>> RenderVisualsService.NEEDS_DYNAMIC_SORT) & 1; + } + + public @Nullable ByteIterator sectionsNeedingDynamicSortIterator() { + if (this.sectionsNeedingDynamicSortCount == 0) { + return null; + } + + return new ByteArrayIterator(this.sectionsNeedingDynamicSort, this.sectionsNeedingDynamicSortCount); } public @Nullable ByteIterator sectionsWithGeometryIterator() { diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/RenderVisualsService.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/RenderVisualsService.java index 18b4bd527..996a93c48 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/RenderVisualsService.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/RenderVisualsService.java @@ -4,4 +4,5 @@ public class RenderVisualsService { public static final int HAS_BLOCK_GEOMETRY = 0; public static final int HAS_SPRITES = 1; public static final int HAS_BLOCK_ENTITIES = 2; + public static final int NEEDS_DYNAMIC_SORT = 3; } -- 2.54.1 From 8c18e3eac8e718e878efbc2fafa2cddb75e893d5 Mon Sep 17 00:00:00 2001 From: rdh Date: Sun, 13 Sep 2026 21:52:57 -0400 Subject: [PATCH 11/23] update section metadata when clearing sort states --- .../org/embeddedt/embeddium/impl/render/chunk/RenderSection.java | 1 + 1 file changed, 1 insertion(+) 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 94b30bbc6..6581789aa 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 @@ -219,6 +219,7 @@ public class RenderSection extends AbstractSection { public void clearTranslucencySortStates() { this.translucencySortStates = Collections.emptyMap(); this.sortMode = SortMode.NONE; + this.updateCachedContextDataFlags(); } public boolean isTreeSorted() { -- 2.54.1 From 00724cb613a441065bd3b699bbee3b30a99e501b Mon Sep 17 00:00:00 2001 From: rdh Date: Sun, 13 Sep 2026 23:30:55 -0400 Subject: [PATCH 12/23] add tree sort statistics to the debug overlay --- .../render/chunk/RenderSectionManager.java | 28 +++++++++++++++++-- .../executor/ChunkJobMetricsTracker.java | 8 ++++-- .../render/chunk/sorting/CutPlaneIndex.java | 10 +++++++ 3 files changed, 41 insertions(+), 5 deletions(-) diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java index 85480eea7..e20726f8a 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java @@ -38,6 +38,7 @@ import org.embeddedt.embeddium.impl.render.viewport.Viewport; import org.embeddedt.embeddium.impl.render.viewport.frustum.ShadowSearchFrustum; import org.embeddedt.embeddium.impl.util.PositionUtil; import org.embeddedt.embeddium.impl.util.iterator.ByteIterator; +import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkSortOutput; import org.embeddedt.embeddium.impl.render.chunk.sorting.CutPlaneIndex; import org.embeddedt.embeddium.impl.render.chunk.sorting.PartitionTree; import org.embeddedt.embeddium.impl.render.chunk.sorting.SortState; @@ -94,6 +95,10 @@ public abstract class RenderSectionManager { private final CutPlaneIndex cutPlaneIndex = new CutPlaneIndex<>(); + private final ChunkJobMetricsTracker.MetricsData treeSortMetrics = new ChunkJobMetricsTracker.MetricsData(); + private long treeStatsWindowStart = System.nanoTime(); + private int treeTriggersThisSecond, treeTriggersLastSecond; + @Getter private final RenderPassConfiguration renderPassConfiguration; @@ -272,6 +277,14 @@ public abstract class RenderSectionManager { } private void checkTranslucencyChange() { + long now = System.nanoTime(); + if (now - this.treeStatsWindowStart >= ChunkJobMetricsTracker.OBSERVATION_COUNT_TIME) { + this.treeTriggersLastSecond = this.treeTriggersThisSecond; + this.treeTriggersThisSecond = 0; + this.treeSortMetrics.flipInterval(); + this.treeStatsWindowStart = now; + } + if(cameraBlockPosition == null) return; @@ -358,6 +371,8 @@ public abstract class RenderSectionManager { this.previousCameraPosition.x, this.previousCameraPosition.y, this.previousCameraPosition.z, this.cameraPosition.x, this.cameraPosition.y, this.cameraPosition.z, section -> { + this.treeTriggersThisSecond++; + ChunkUpdateType update = ChunkUpdateType.getPromotionUpdateType(section.getPendingUpdate(), (allowImportant && this.shouldPrioritizeRebuild(section)) ? ChunkUpdateType.IMPORTANT_SORT : ChunkUpdateType.SORT); @@ -732,6 +747,10 @@ public abstract class RenderSectionManager { while ((result = this.buildResults.poll()) != null) { if (result instanceof ChunkJobResult.Success successfulResult) { this.jobMetricsTracker.collectMetrics(successfulResult); + + if (successfulResult.output() instanceof ChunkSortOutput sort && sort.render.isTreeSorted() && successfulResult.executionTimeNanos() >= 0) { + this.treeSortMetrics.collect(successfulResult.executionTimeNanos()); + } results.add(successfulResult); } else if (result instanceof ChunkJobResult.Failure failure) { failure.abort(); @@ -1087,14 +1106,13 @@ public abstract class RenderSectionManager { var rebuildLists = this.getCurrentRenderListManager().getRebuildLists(); - list.add(String.format("Chunk Queues: U=%02d (P0=%03d | P1=%03d | P2=%03d) S=%03d/%03d I=%03d", + list.add(String.format("Chunk Queues: U=%02d (P0=%03d | P1=%03d | P2=%03d) S=%03d/%03d", this.buildResults.size(), rebuildLists.getUpdateCount(ChunkUpdateType.IMPORTANT_REBUILD), rebuildLists.getUpdateCount(ChunkUpdateType.REBUILD), rebuildLists.getUpdateCount(ChunkUpdateType.INITIAL_BUILD), rebuildLists.getUpdateCount(ChunkUpdateType.IMPORTANT_SORT), - rebuildLists.getUpdateCount(ChunkUpdateType.SORT), - this.cutPlaneIndex.size() + rebuildLists.getUpdateCount(ChunkUpdateType.SORT) )); var debugStats = renderListManager.getDebugStatistics(); @@ -1118,6 +1136,10 @@ public abstract class RenderSectionManager { if (renderListManager.getRenderLists().getPasses().stream().anyMatch(TerrainRenderPass::isSorted)) { list.add(debugStats.getSortingString()); + list.add(String.format("Tree Sort: %d planes, %d trig/s, %d sorts/s, %s avg", + this.cutPlaneIndex.planeCount(), this.treeTriggersLastSecond, + this.treeSortMetrics.getObservationsInLastTimeInterval(), + TimeUtil.stringifyTime((long) this.treeSortMetrics.getAverageNanos(0), TimeUnit.NANOSECONDS))); } return list; diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/executor/ChunkJobMetricsTracker.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/executor/ChunkJobMetricsTracker.java index 7add606b6..6cbd3da96 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/executor/ChunkJobMetricsTracker.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/executor/ChunkJobMetricsTracker.java @@ -64,6 +64,11 @@ public class ChunkJobMetricsTracker { } } + public void flipInterval() { + this.observationsInLastTimeInterval = this.observationsInCurrentTimeInterval; + this.observationsInCurrentTimeInterval = 0; + } + public int getObservationsInLastTimeInterval() { return this.observationsInLastTimeInterval; } @@ -103,8 +108,7 @@ public class ChunkJobMetricsTracker { long time = System.nanoTime(); if ((time - lastTimeIntervalFlip) >= OBSERVATION_COUNT_TIME) { for (var data : metricsByTask.values()) { - data.observationsInLastTimeInterval = data.observationsInCurrentTimeInterval; - data.observationsInCurrentTimeInterval = 0; + data.flipInterval(); } lastTimeIntervalFlip = time; } diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/CutPlaneIndex.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/CutPlaneIndex.java index 866d27cce..8c7d99863 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/CutPlaneIndex.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/CutPlaneIndex.java @@ -23,6 +23,8 @@ public final class CutPlaneIndex { private final ReferenceOpenHashSet reported = new ReferenceOpenHashSet<>(); + private int planeCount; + public void put(T owner, float[][] cutsByAxis, int originX, int originY, int originZ) { remove(owner); @@ -31,6 +33,8 @@ public final class CutPlaneIndex { return; } + this.planeCount += cutsByAxis[0].length + cutsByAxis[1].length + cutsByAxis[2].length; + int[] origin = { originX, originY, originZ }; long[][] buckets = new long[3][]; @@ -66,6 +70,8 @@ public final class CutPlaneIndex { return; } + this.planeCount -= registration.cuts[0].length + registration.cuts[1].length + registration.cuts[2].length; + for (int axis = 0; axis < 3; axis++) { var map = this.bucketsByAxis[axis]; @@ -152,4 +158,8 @@ public final class CutPlaneIndex { public int size() { return this.registrations.size(); } + + public int planeCount() { + return this.planeCount; + } } -- 2.54.1 From 63b910add31a676e0f709c45d2628e1002d8f4ac Mon Sep 17 00:00:00 2001 From: rdh Date: Sun, 13 Sep 2026 23:54:14 -0400 Subject: [PATCH 13/23] sort parallel groups statically inside the partition tree --- .../render/chunk/sorting/PartitionTree.java | 34 +++++++++++++++---- .../chunk/sorting/TranslucentSorter.java | 2 +- 2 files changed, 28 insertions(+), 8 deletions(-) diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java index 1603e7b42..fa25114d6 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java @@ -4,6 +4,7 @@ import it.unimi.dsi.fastutil.floats.FloatArrayList; import it.unimi.dsi.fastutil.floats.FloatArrays; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntArrays; +import org.embeddedt.embeddium.impl.util.sorting.MergeSort; import org.jetbrains.annotations.Nullable; import java.util.Collection; @@ -68,10 +69,15 @@ public final class PartitionTree implements SortState.Resortable { } private static Node partition(QuadSet quads, int[] group, int parentAxis, FloatArrayList[] collectedCuts) { - if (group.length <= 1 || isAllCoplanar(quads, group)) { + if (group.length <= 1) { return new Leaf(group); } + int[] parallel = parallelOrder(quads, group); + if (parallel != null) { + return new Leaf(parallel); + } + int axis = -1; float[] planes = FloatArrays.EMPTY_ARRAY; for (int i = 0; i < 3; i++) { @@ -174,13 +180,27 @@ public final class PartitionTree implements SortState.Resortable { return true; } - private static boolean isAllCoplanar(QuadSet quads, int[] group) { - for (int i = 1; i < group.length; i++) { - if (!quads.isCoplanar(group[0], group[i])) { - return false; - } + private static int @Nullable [] parallelOrder(QuadSet quads, int[] group) { + int reference = group[0]; + float nx = quads.normalX(reference), ny = quads.normalY(reference), nz = quads.normalZ(reference); + float[] centers = quads.centers(); + int far = TranslucentSorter.FAKE_STATIC_CAMERA_OFFSET; + float camX = centers[reference * 3] + nx * far, camY = centers[reference * 3 + 1] + ny * far, camZ = centers[reference * 3 + 2] + nz * far; + + float[] keys = new float[group.length]; + for (int i = 0; i < group.length; i++) { + int quad = group[i]; + float dot = quads.normalDot(quad, reference); + if (Math.abs(dot) < 1 - QuadSet.EPSILON) return null; + + int c = quad * 3; + keys[i] = (nx * (centers[c] - camX) + ny * (centers[c + 1] - camY) + nz * (centers[c + 2] - camZ)) * (dot < 0 ? 1 : -1); } - return true; + + int[] byKey = MergeSort.mergeSort(keys); + int[] order = new int[group.length]; + for (int i = 0; i < order.length; i++) order[i] = group[byKey[i]]; + return order; } private static float[] cutsOn(QuadSet quads, int[] group, int axis) { diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java index 62672bc86..1aaffffc8 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java @@ -13,7 +13,7 @@ public final class TranslucentSorter { * How far along the shared normal the imaginary camera used by {@link #sortNormalRelative} sits. Any value * comfortably beyond the section is equivalent, since only the ordering of the projections matters. */ - private static final int FAKE_STATIC_CAMERA_OFFSET = 1000; + static final int FAKE_STATIC_CAMERA_OFFSET = 1000; /** * How closely two normals must agree to be treated as parallel. Only +/-1 truly imply a shared normal, but -- 2.54.1 From 7e64f27a2eb86e9265e50ce49ade32355f2acca0 Mon Sep 17 00:00:00 2001 From: rdh Date: Mon, 14 Sep 2026 00:07:25 -0400 Subject: [PATCH 14/23] keep only the cuts carrying quads when everything between them is parallel A multi-partition node took up every free gap, so a run of parallel quads like a water surface between walls was sliced into one slab per block, and every gap plane was a trigger. When all quads between the planes are parallel, only cuts with quads lying on them are kept and merged slabs become static leaves. --- .../render/chunk/sorting/PartitionTree.java | 75 ++++++++++++++----- 1 file changed, 58 insertions(+), 17 deletions(-) diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java index fa25114d6..4ae11fa58 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java @@ -89,26 +89,19 @@ public final class PartitionTree implements SortState.Resortable { return partitionIntersectors(quads, group, collectedCuts); } - int slabCount = planes.length + 1; - IntArrayList[] onPlaneLists = new IntArrayList[planes.length]; - for (int i = 0; i < planes.length; i++) onPlaneLists[i] = new IntArrayList(); - IntArrayList[] slabLists = new IntArrayList[slabCount]; - for (int i = 0; i < slabCount; i++) slabLists[i] = new IntArrayList(); + Buckets buckets = bucket(quads, group, axis, planes); - for (int quad : group) { - float lo = quads.boundsMin(quad, axis), hi = quads.boundsMax(quad, axis); - - // slab = number of planes at or below this quad's lo - int slab = 0; - while (slab < planes.length && planes[slab] <= lo + QuadSet.EPSILON) slab++; - - if (hi - lo <= QuadSet.EPSILON && slab > 0 && Math.abs(planes[slab - 1] - lo) <= QuadSet.EPSILON) { - onPlaneLists[slab - 1].add(quad); - } else { - slabLists[slab].add(quad); - } + // gaps between quads that are all parallel would only slice one static leaf into pieces, each gap a trigger + // plane: keep just the cuts carrying quads on the plane (some do, else the group itself was parallel) + float[] carrying = planesWithQuads(planes, buckets.onPlane); + if (carrying.length > 0 && carrying.length < planes.length && allParallel(quads, buckets.slabs)) { + planes = carrying; + buckets = bucket(quads, group, axis, planes); } + IntArrayList[] onPlaneLists = buckets.onPlane, slabLists = buckets.slabs; + int slabCount = planes.length + 1; + Node[] slabs = new Node[slabCount]; for (int i = 0; i < slabCount; i++) { int[] slabGroup = slabLists[i].toIntArray(); @@ -132,6 +125,54 @@ public final class PartitionTree implements SortState.Resortable { return new Split(axis, planes, slabs, onPlane); } + private record Buckets(IntArrayList[] onPlane, IntArrayList[] slabs) {} + + /** sorts the group into the quads lying on each plane and those in each slab between the planes */ + private static Buckets bucket(QuadSet quads, int[] group, int axis, float[] planes) { + IntArrayList[] onPlane = new IntArrayList[planes.length]; + for (int i = 0; i < planes.length; i++) onPlane[i] = new IntArrayList(); + IntArrayList[] slabs = new IntArrayList[planes.length + 1]; + for (int i = 0; i <= planes.length; i++) slabs[i] = new IntArrayList(); + + for (int quad : group) { + float lo = quads.boundsMin(quad, axis), hi = quads.boundsMax(quad, axis); + + // slab = number of planes at or below this quad's lo + int slab = 0; + while (slab < planes.length && planes[slab] <= lo + QuadSet.EPSILON) slab++; + + if (hi - lo <= QuadSet.EPSILON && slab > 0 && Math.abs(planes[slab - 1] - lo) <= QuadSet.EPSILON) { + onPlane[slab - 1].add(quad); + } else { + slabs[slab].add(quad); + } + } + return new Buckets(onPlane, slabs); + } + + private static float[] planesWithQuads(float[] planes, IntArrayList[] onPlane) { + FloatArrayList kept = new FloatArrayList(planes.length); + for (int i = 0; i < planes.length; i++) { + if (!onPlane[i].isEmpty()) kept.add(planes[i]); + } + return kept.toFloatArray(); + } + + private static boolean allParallel(QuadSet quads, IntArrayList[] slabs) { + int reference = -1; + for (IntArrayList slab : slabs) { + for (int i = 0; i < slab.size(); i++) { + int quad = slab.getInt(i); + if (reference < 0) { + reference = quad; + } else if (Math.abs(quads.normalDot(quad, reference)) < 1 - QuadSet.EPSILON) { + return false; + } + } + } + return true; + } + private static @Nullable Node partitionIntersectors(QuadSet quads, int[] group, FloatArrayList[] collectedCuts) { int n = group.length; if (n > TranslucentSorter.MAX_TOPO_QUADS) return null; -- 2.54.1 From 232d5878f8a8b8d18ed6b1184688127dacffa475 Mon Sep 17 00:00:00 2001 From: rdh Date: Mon, 14 Sep 2026 00:07:26 -0400 Subject: [PATCH 15/23] sort groups without a free cut topologically before splitting intersectors conforms to the thesis's ordering of the fallbacks, since no free cut doesn't imply a cycle, so an acyclic group takes a static order instead of sinking the whole section to distance sorting --- .../impl/render/chunk/sorting/PartitionTree.java | 5 +++++ .../render/chunk/sorting/TranslucentSorter.java | 13 ++++++++++--- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java index 4ae11fa58..cd0f6fb56 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java @@ -86,6 +86,11 @@ public final class PartitionTree implements SortState.Resortable { if (planes.length > 0) break; } if (planes.length == 0) { + // no free cut does not imply a cycle: a camera-independent order may still exist + int[] topological = group.length <= TranslucentSorter.MAX_TOPO_QUADS ? TranslucentSorter.topologicalOrder(quads, group) : null; + if (topological != null) { + return new Leaf(topological); + } return partitionIntersectors(quads, group, collectedCuts); } diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java index 1aaffffc8..5c7fc34eb 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java @@ -225,7 +225,14 @@ public final class TranslucentSorter { /** returns null if the relation has a cycle */ public static int @Nullable [] topologicalOrder(QuadSet quads) { - int n = quads.count(); + int[] all = new int[quads.count()]; + for (int i = 0; i < all.length; i++) all[i] = i; + return topologicalOrder(quads, all); + } + + /** the group's quads in an order correct from every camera, or null if their visibility relation has a cycle */ + static int @Nullable [] topologicalOrder(QuadSet quads, int[] group) { + int n = group.length; IntArrayList[] successors = new IntArrayList[n]; int[] predecessors = new int[n]; @@ -233,7 +240,7 @@ public final class TranslucentSorter { // build the graph up for (int quadIdx = 0; quadIdx < n; quadIdx++) { for (int otherIdx = 0; otherIdx < n; otherIdx++) { - if (quadIdx != otherIdx && quads.isSeenThrough(quadIdx, otherIdx)) { + if (quadIdx != otherIdx && quads.isSeenThrough(group[quadIdx], group[otherIdx])) { if (successors[quadIdx] == null) { successors[quadIdx] = new IntArrayList(); } @@ -258,7 +265,7 @@ public final class TranslucentSorter { while (!ready.isEmpty()) { int current = ready.dequeueInt(); - out[o++] = current; + out[o++] = group[current]; IntArrayList next = successors[current]; if (next == null) continue; -- 2.54.1 From 2f691b6ac0eed98c8287a2fe3ca3fc8e65b43bba Mon Sep 17 00:00:00 2001 From: rdh Date: Mon, 14 Sep 2026 00:13:19 -0400 Subject: [PATCH 16/23] subtract the section origin from the camera before rounding it to float --- .../embeddium/impl/render/chunk/RenderSectionManager.java | 2 +- .../render/chunk/compile/tasks/ChunkBuilderSortTask.java | 6 +++--- .../terrain/compile/task/ChunkBuilderMeshingTask.java | 2 +- .../render/chunk/compile/tasks/ChunkBuilderMeshingTask.java | 2 +- .../terrain/compile/task/ChunkBuilderMeshingTask.java | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java index e20726f8a..995b12ef0 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java @@ -827,7 +827,7 @@ public abstract class RenderSectionManager { public ChunkBuilderSortTask createSortTask(RenderSection render, int frame) { if(render.getTranslucencySortStates().isEmpty()) return null; - return new ChunkBuilderSortTask(render, (float)cameraPosition.x, (float)cameraPosition.y, (float)cameraPosition.z, frame, render.getTranslucencySortStates(), this.renderPassConfiguration); + return new ChunkBuilderSortTask(render, cameraPosition.x, cameraPosition.y, cameraPosition.z, frame, render.getTranslucencySortStates(), this.renderPassConfiguration); } public void markGraphDirty() { diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/tasks/ChunkBuilderSortTask.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/tasks/ChunkBuilderSortTask.java index daad1f93d..d1453eedd 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/tasks/ChunkBuilderSortTask.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/tasks/ChunkBuilderSortTask.java @@ -14,12 +14,12 @@ import java.util.Map; public class ChunkBuilderSortTask extends ChunkBuilderTask { private final RenderSection render; - private final float cameraX, cameraY, cameraZ; + private final double cameraX, cameraY, cameraZ; private final int frame; private final Map translucentMeshes; private final RenderPassConfiguration renderPassConfiguration; - public ChunkBuilderSortTask(RenderSection render, float cameraX, float cameraY, float cameraZ, int frame, Map translucentMeshes, RenderPassConfiguration renderPassConfiguration) { + public ChunkBuilderSortTask(RenderSection render, double cameraX, double cameraY, double cameraZ, int frame, Map translucentMeshes, RenderPassConfiguration renderPassConfiguration) { this.render = render; this.cameraX = cameraX; this.cameraY = cameraY; @@ -36,7 +36,7 @@ public class ChunkBuilderSortTask extends ChunkBuilderTask { var sortInfo = entry.getValue(); var primitiveType = this.renderPassConfiguration.getPrimitiveTypeForPass(entry.getKey()); var newIndexBuffer = new NativeBuffer(primitiveType.getIndexBufferSize(sortInfo.quadCount())); - primitiveType.generateSortedIndexBuffer(newIndexBuffer.getDirectBuffer(), sortInfo.quadCount(), sortInfo, cameraX - this.render.getOriginX(), cameraY - this.render.getOriginY(), cameraZ - this.render.getOriginZ()); + primitiveType.generateSortedIndexBuffer(newIndexBuffer.getDirectBuffer(), sortInfo.quadCount(), sortInfo, (float) (cameraX - this.render.getOriginX()), (float) (cameraY - this.render.getOriginY()), (float) (cameraZ - this.render.getOriginZ())); meshes.put(entry.getKey(), new ChunkSortOutput.SortedMesh( newIndexBuffer )); diff --git a/forge122/src/main/java/org/taumc/celeritas/impl/render/terrain/compile/task/ChunkBuilderMeshingTask.java b/forge122/src/main/java/org/taumc/celeritas/impl/render/terrain/compile/task/ChunkBuilderMeshingTask.java index efea91f59..c90f87c14 100644 --- a/forge122/src/main/java/org/taumc/celeritas/impl/render/terrain/compile/task/ChunkBuilderMeshingTask.java +++ b/forge122/src/main/java/org/taumc/celeritas/impl/render/terrain/compile/task/ChunkBuilderMeshingTask.java @@ -145,7 +145,7 @@ public class ChunkBuilderMeshingTask extends ChunkBuilderTask buildContext.convertVanillaDataToCeleritasData(buffers); - Reference2ReferenceMap meshes = BuiltSectionMeshParts.groupFromBuildBuffers(buffers,(float)camera.x - minX, (float)camera.y - minY, (float)camera.z - minZ); + Reference2ReferenceMap meshes = BuiltSectionMeshParts.groupFromBuildBuffers(buffers, (float) (camera.x - minX), (float) (camera.y - minY), (float) (camera.z - minZ)); if (!meshes.isEmpty()) { renderData.hasBlockGeometry = true; diff --git a/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/compile/tasks/ChunkBuilderMeshingTask.java b/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/compile/tasks/ChunkBuilderMeshingTask.java index c9967c88d..45b641bfa 100644 --- a/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/compile/tasks/ChunkBuilderMeshingTask.java +++ b/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/compile/tasks/ChunkBuilderMeshingTask.java @@ -248,7 +248,7 @@ public class ChunkBuilderMeshingTask extends ChunkBuilderTask throw fillCrashInfo(CrashReport.forThrowable(ex, "Encountered exception while building chunk meshes"), slice, blockPos); } - Reference2ReferenceMap meshes = BuiltSectionMeshParts.groupFromBuildBuffers(buffers,(float)camera.x - minX, (float)camera.y - minY, (float)camera.z - minZ); + Reference2ReferenceMap meshes = BuiltSectionMeshParts.groupFromBuildBuffers(buffers, (float) (camera.x - minX), (float) (camera.y - minY), (float) (camera.z - minZ)); if (!meshes.isEmpty()) { renderData.hasBlockGeometry = true; diff --git a/ornithe/src/main/java/org/taumc/celeritas/impl/render/terrain/compile/task/ChunkBuilderMeshingTask.java b/ornithe/src/main/java/org/taumc/celeritas/impl/render/terrain/compile/task/ChunkBuilderMeshingTask.java index ed881f660..2391ce402 100644 --- a/ornithe/src/main/java/org/taumc/celeritas/impl/render/terrain/compile/task/ChunkBuilderMeshingTask.java +++ b/ornithe/src/main/java/org/taumc/celeritas/impl/render/terrain/compile/task/ChunkBuilderMeshingTask.java @@ -168,7 +168,7 @@ public class ChunkBuilderMeshingTask extends ChunkBuilderTask } - Reference2ReferenceMap meshes = BuiltSectionMeshParts.groupFromBuildBuffers(buffers,(float)camera.x - minX, (float)camera.y - minY, (float)camera.z - minZ); + Reference2ReferenceMap meshes = BuiltSectionMeshParts.groupFromBuildBuffers(buffers, (float) (camera.x - minX), (float) (camera.y - minY), (float) (camera.z - minZ)); if (!meshes.isEmpty()) { renderData.hasBlockGeometry = true; -- 2.54.1 From 61ca849523910e30d072aba715151b8dceb3eb15 Mon Sep 17 00:00:00 2001 From: rdh Date: Mon, 14 Sep 2026 00:29:14 -0400 Subject: [PATCH 17/23] catch cut plane crossings during a rebuild's flight The initial order is sorted for the camera at submission, but its planes only enter the index at upload, so a crossing in between was never noticed and the section kept a stale order until the next one. The camera is now recorded at submission and tested against the new planes at upload, for the latest build only, so a stale result cannot disturb a newer in-flight one. --- .../render/chunk/RenderSectionManager.java | 70 +++++++++++++------ 1 file changed, 47 insertions(+), 23 deletions(-) diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java index 995b12ef0..5ea753c86 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java @@ -364,29 +364,29 @@ public abstract class RenderSectionManager { return; } - var rebuildLists = this.getCurrentRenderListManager().getRebuildLists().byUpdateType(); - var allowImportant = allowImportantRebuilds(); - this.cutPlaneIndex.query( this.previousCameraPosition.x, this.previousCameraPosition.y, this.previousCameraPosition.z, this.cameraPosition.x, this.cameraPosition.y, this.cameraPosition.z, section -> { this.treeTriggersThisSecond++; - - ChunkUpdateType update = ChunkUpdateType.getPromotionUpdateType(section.getPendingUpdate(), - (allowImportant && this.shouldPrioritizeRebuild(section)) ? ChunkUpdateType.IMPORTANT_SORT : ChunkUpdateType.SORT); - - if (update == null) { - // We wouldn't be able to resort this section anyway - return; - } - - section.setPendingUpdate(update); - rebuildLists.get(update).add(section); + this.scheduleTreeSort(section); } ); } + private void scheduleTreeSort(RenderSection section) { + ChunkUpdateType update = ChunkUpdateType.getPromotionUpdateType(section.getPendingUpdate(), + (allowImportantRebuilds() && this.shouldPrioritizeRebuild(section)) ? ChunkUpdateType.IMPORTANT_SORT : ChunkUpdateType.SORT); + + if (update == null) { + // We wouldn't be able to resort this section anyway + return; + } + + section.setPendingUpdate(update); + this.getCurrentRenderListManager().getRebuildLists().byUpdateType().get(update).add(section); + } + /** * {@return true if the renderer should respect per-frame queue limits and not try to update as many chunks as * possible per frame} @@ -632,6 +632,10 @@ public abstract class RenderSectionManager { for (var holder : filtered) { var result = holder.output(); + + // whether this result belongs to the most recently submitted build + boolean latest = result.buildTime >= result.render.getLastSubmittedFrame(); + if (result instanceof ChunkBuildOutput buildResult) { boolean changed = this.updateSectionInfo(result.render, buildResult.info); @@ -643,15 +647,12 @@ public abstract class RenderSectionManager { } // We only change the translucency info on full rebuilds, as sorts can keep using the same data - this.updateTranslucencyInfo(result.render, buildResult.meshes); + this.updateTranslucencyInfo(result.render, buildResult.meshes, latest); } var job = result.render.getBuildCancellationToken(); - // Only clear the token if this result belongs to the most recently submitted build. - // A stale result from an earlier submission must not clear the token for a newer - // in-flight job, which is identified by a higher lastSubmittedFrame. - if (job != null && result.buildTime >= result.render.getLastSubmittedFrame()) { + if (job != null && latest) { result.render.setBuildCancellationToken(null); } @@ -660,7 +661,11 @@ public abstract class RenderSectionManager { } } - private void updateTranslucencyInfo(RenderSection render, Map meshes) { + /** + * @param latestBuild whether the meshes come from the most recent submission; a stale build keeps its planes + * indexed but leaves the camera bookkeeping to the build still in flight + */ + private void updateTranslucencyInfo(RenderSection render, Map meshes, boolean latestBuild) { Map sortStates = new Reference2ObjectArrayMap<>(); int highestIndex = RenderSection.NO_TRANSLUCENT_GEOMETRY; @@ -688,14 +693,28 @@ public abstract class RenderSectionManager { } this.cutPlaneIndex.put(render, PartitionTree.mergeCutPlanes(trees), render.getOriginX(), render.getOriginY(), render.getOriginZ()); + + // The build sorted for the camera at submission (see submitRebuildTasks). A crossing since then happened + // before the planes were indexed, so it has to be caught here or the order stays stale until the next one. + int ox = render.getOriginX(), oy = render.getOriginY(), oz = render.getOriginZ(); + for (PartitionTree tree : trees) { + if (latestBuild && tree.crossesCutPlane(render.lastCameraX - ox, render.lastCameraY - oy, render.lastCameraZ - oz, + this.cameraPosition.x - ox, this.cameraPosition.y - oy, this.cameraPosition.z - oz)) { + this.treeTriggersThisSecond++; + this.scheduleTreeSort(render); + break; + } + } } else { // a rebuild that is no longer tree-sorted must drop its stale planes this.cutPlaneIndex.remove(render); } - render.lastCameraX = this.cameraPosition.x; - render.lastCameraY = this.cameraPosition.y; - render.lastCameraZ = this.cameraPosition.z; + if (latestBuild) { + render.lastCameraX = this.cameraPosition.x; + render.lastCameraY = this.cameraPosition.y; + render.lastCameraZ = this.cameraPosition.z; + } } // Section MetadataSink: mirrors a section's packed metadata into the graph-search lattice on every @@ -809,6 +828,11 @@ public abstract class RenderSectionManager { if (!type.isSort()) { // Prevent further sorts from being performed on this section section.clearTranslucencySortStates(); + + // the meshing task sorts its translucent geometry for this camera + section.lastCameraX = this.cameraPosition.x; + section.lastCameraY = this.cameraPosition.y; + section.lastCameraZ = this.cameraPosition.z; } } else { var result = new ChunkJobResult.Success<>(new ChunkBuildOutput(section, RenderSection.EMPTY_DATA, Reference2ReferenceMaps.emptyMap(), frame), -1); -- 2.54.1 From e6f2061e3879e6f297ef393b86f8e7c2fb60143c Mon Sep 17 00:00:00 2001 From: rdh Date: Mon, 14 Sep 2026 00:58:50 -0400 Subject: [PATCH 18/23] stream the partition tree readout straight into the index buffer --- .../compile/sorting/QuadPrimitiveType.java | 80 ++++++++++++------- .../render/chunk/sorting/PartitionTree.java | 55 +++++++++---- 2 files changed, 88 insertions(+), 47 deletions(-) diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/sorting/QuadPrimitiveType.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/sorting/QuadPrimitiveType.java index 183caa2c8..2cb38d6a9 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/sorting/QuadPrimitiveType.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/sorting/QuadPrimitiveType.java @@ -1,5 +1,6 @@ package org.embeddedt.embeddium.impl.render.chunk.compile.sorting; +import org.embeddedt.embeddium.impl.render.chunk.sorting.PartitionTree; import org.embeddedt.embeddium.impl.render.chunk.sorting.SortState; import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentSorter; import org.jetbrains.annotations.Nullable; @@ -43,24 +44,26 @@ public final class QuadPrimitiveType implements ChunkPrimitiveType { } long ptr = LWJGL.memAddress(indexBuffer); - int elementsPerPrimitive = this.getIndexBufferElementsPerPrimitive(); - boolean triangulating = this.triangulating; - for (int primitiveIndex = 0; primitiveIndex < numPrimitives; primitiveIndex++) { - int indexOffset = primitiveIndex * elementsPerPrimitive; - int vertexOffset = primitiveIndex * VERTICES_PER_PRIMITIVE; + this.writePrimitive(ptr, primitiveIndex, primitiveIndex); + } + } - LWJGL.memPutInt(ptr + (indexOffset + 0) * 4, vertexOffset + 0); - LWJGL.memPutInt(ptr + (indexOffset + 1) * 4, vertexOffset + 1); - LWJGL.memPutInt(ptr + (indexOffset + 2) * 4, vertexOffset + 2); + /** writes the indices of the given quad as the primitive at the given position */ + private void writePrimitive(long ptr, int primitiveIndex, int quad) { + int indexOffset = primitiveIndex * this.getIndexBufferElementsPerPrimitive(); + int vertexOffset = quad * VERTICES_PER_PRIMITIVE; - if (triangulating) { - LWJGL.memPutInt(ptr + (indexOffset + 3) * 4, vertexOffset + 2); - LWJGL.memPutInt(ptr + (indexOffset + 4) * 4, vertexOffset + 3); - LWJGL.memPutInt(ptr + (indexOffset + 5) * 4, vertexOffset + 0); - } else { - LWJGL.memPutInt(ptr + (indexOffset + 3) * 4, vertexOffset + 3); - } + LWJGL.memPutInt(ptr + (indexOffset + 0) * 4, vertexOffset + 0); + LWJGL.memPutInt(ptr + (indexOffset + 1) * 4, vertexOffset + 1); + LWJGL.memPutInt(ptr + (indexOffset + 2) * 4, vertexOffset + 2); + + if (this.triangulating) { + LWJGL.memPutInt(ptr + (indexOffset + 3) * 4, vertexOffset + 2); + LWJGL.memPutInt(ptr + (indexOffset + 4) * 4, vertexOffset + 3); + LWJGL.memPutInt(ptr + (indexOffset + 5) * 4, vertexOffset + 0); + } else { + LWJGL.memPutInt(ptr + (indexOffset + 3) * 4, vertexOffset + 3); } } @@ -71,31 +74,48 @@ public final class QuadPrimitiveType implements ChunkPrimitiveType { } long ptr = LWJGL.memAddress(indexBuffer); - int elementsPerPrimitive = this.getIndexBufferElementsPerPrimitive(); - boolean triangulating = this.triangulating; - for (int primitiveIndex = 0; primitiveIndex < primitiveMapping.length; primitiveIndex++) { - int indexOffset = primitiveIndex * elementsPerPrimitive; + this.writePrimitive(ptr, primitiveIndex, primitiveMapping[primitiveIndex]); + } + } - // Map to the desired primitive - int vertexOffset = primitiveMapping[primitiveIndex] * VERTICES_PER_PRIMITIVE; + /** streams a partition tree's readout straight into the index buffer */ + private final class BufferSink implements PartitionTree.Sink { + private final long ptr; + private int primitiveIndex; - LWJGL.memPutInt(ptr + (indexOffset + 0) * 4, vertexOffset + 0); - LWJGL.memPutInt(ptr + (indexOffset + 1) * 4, vertexOffset + 1); - LWJGL.memPutInt(ptr + (indexOffset + 2) * 4, vertexOffset + 2); + private BufferSink(long ptr) { + this.ptr = ptr; + } - if (triangulating) { - LWJGL.memPutInt(ptr + (indexOffset + 3) * 4, vertexOffset + 2); - LWJGL.memPutInt(ptr + (indexOffset + 4) * 4, vertexOffset + 3); - LWJGL.memPutInt(ptr + (indexOffset + 5) * 4, vertexOffset + 0); - } else { - LWJGL.memPutInt(ptr + (indexOffset + 3) * 4, vertexOffset + 3); + @Override + public void accept(int[] quads) { + for (int quad : quads) { + writePrimitive(this.ptr, this.primitiveIndex++, quad); } } } @Override public void generateSortedIndexBuffer(ByteBuffer indexBuffer, int quadCount, @Nullable SortState chunkData, float x, float y, float z) { + if (chunkData instanceof PartitionTree tree) { + int bufferSize = getIndexBufferSize(quadCount); + if (indexBuffer.capacity() != bufferSize) { + throw new IllegalStateException("Given index buffer has length " + indexBuffer.capacity() + " but we expected " + bufferSize); + } + if (quadCount != tree.quadCount()) { + throw new IllegalStateException(String.format("Mismatched SortState (%d) vs given quad count (%d)", tree.quadCount(), quadCount)); + } + + var sink = new BufferSink(LWJGL.memAddress(indexBuffer)); + tree.order(x, y, z, sink); + + if (sink.primitiveIndex != quadCount) { + throw new IllegalStateException(String.format("Partition tree wrote %d of %d quads", sink.primitiveIndex, quadCount)); + } + return; + } + int[] order = chunkData != null ? TranslucentSorter.order(chunkData, x, y, z) : null; if (order == null) { diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java index cd0f6fb56..ac800672e 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java @@ -326,21 +326,32 @@ public final class PartitionTree implements SortState.Resortable { return cutPlanes[axis]; } - public int @Nullable [] order(float camX, float camY, float camZ) { - int[] order = new int[quadCount]; - write(root, camX, camY, camZ, order, 0); - return order; + /** Receives the quads of one leaf or one plane at a time, farthest first */ + public interface Sink { + void accept(int[] quads); } - // returns the position just past the last quad written - private static int write(Node node, float camX, float camY, float camZ, int[] order, int pos) { + public int @Nullable [] order(float camX, float camY, float camZ) { + var sink = new ArraySink(new int[quadCount]); + order(camX, camY, camZ, sink); + return sink.order; + } + + /** The draw order for the camera position, streamed so the caller can write it out without an array in between */ + public void order(float camX, float camY, float camZ, Sink sink) { + write(root, camX, camY, camZ, sink); + } + + private static void write(Node node, float camX, float camY, float camZ, Sink sink) { if (node instanceof Leaf leaf) { - System.arraycopy(leaf.quads, 0, order, pos, leaf.quads.length); - return pos + leaf.quads.length; + sink.accept(leaf.quads); + return; } if (node instanceof Fixed fixed) { - return write(fixed.rest, camX, camY, camZ, order, write(fixed.first, camX, camY, camZ, order, pos)); + write(fixed.first, camX, camY, camZ, sink); + write(fixed.rest, camX, camY, camZ, sink); + return; } Split split = (Split) node; @@ -356,23 +367,33 @@ public final class PartitionTree implements SortState.Resortable { // slabs below the camera's, farthest first, each followed by the plane above it for (int i = 0; i < slab; i++) { - pos = write(split.slabs[i], camX, camY, camZ, order, pos); - pos = writePlane(split.onPlane[i], order, pos); + write(split.slabs[i], camX, camY, camZ, sink); + sink.accept(split.onPlane[i]); } // slabs above the camera's, farthest first, each followed by the plane below it for (int i = split.slabs.length - 1; i > slab; i--) { - pos = write(split.slabs[i], camX, camY, camZ, order, pos); - pos = writePlane(split.onPlane[i - 1], order, pos); + write(split.slabs[i], camX, camY, camZ, sink); + sink.accept(split.onPlane[i - 1]); } // the camera's own slab is nearest, drawn last - return write(split.slabs[slab], camX, camY, camZ, order, pos); + write(split.slabs[slab], camX, camY, camZ, sink); } - private static int writePlane(int[] quads, int[] order, int pos) { - System.arraycopy(quads, 0, order, pos, quads.length); - return pos + quads.length; + private static final class ArraySink implements Sink { + private final int[] order; + private int pos; + + private ArraySink(int[] order) { + this.order = order; + } + + @Override + public void accept(int[] quads) { + System.arraycopy(quads, 0, order, pos, quads.length); + pos += quads.length; + } } public boolean crossesCutPlane(double lastX, double lastY, double lastZ, double camX, double camY, double camZ) { -- 2.54.1 From dfa29fcd5ef06e7b917502a1bb349fb57ec9979c Mon Sep 17 00:00:00 2001 From: rdh Date: Mon, 14 Sep 2026 01:03:44 -0400 Subject: [PATCH 19/23] faster toposort dfs over implicit edges replaces kahn's algorithm, which had to build every edge before it could see a cycle --- .../chunk/sorting/TranslucentSorter.java | 80 +++++++++---------- 1 file changed, 40 insertions(+), 40 deletions(-) diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java index 5c7fc34eb..77bca3a2a 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java @@ -1,7 +1,5 @@ package org.embeddedt.embeddium.impl.render.chunk.sorting; -import it.unimi.dsi.fastutil.ints.IntArrayFIFOQueue; -import it.unimi.dsi.fastutil.ints.IntArrayList; import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing; import org.embeddedt.embeddium.impl.util.sorting.MergeSort; import org.jetbrains.annotations.Nullable; @@ -230,55 +228,57 @@ public final class TranslucentSorter { return topologicalOrder(quads, all); } - /** the group's quads in an order correct from every camera, or null if their visibility relation has a cycle */ + /** + * The group's quads in an order correct from every camera, or null if their visibility relation has a cycle. + * A depth-first search over implicit edges: an acyclic group costs every pair, a cyclic one only until the first + * back edge, which dense cyclic geometry produces almost immediately. + */ static int @Nullable [] topologicalOrder(QuadSet quads, int[] group) { int n = group.length; - IntArrayList[] successors = new IntArrayList[n]; - int[] predecessors = new int[n]; - - // build the graph up - for (int quadIdx = 0; quadIdx < n; quadIdx++) { - for (int otherIdx = 0; otherIdx < n; otherIdx++) { - if (quadIdx != otherIdx && quads.isSeenThrough(group[quadIdx], group[otherIdx])) { - if (successors[quadIdx] == null) { - successors[quadIdx] = new IntArrayList(); - } - - successors[quadIdx].add(otherIdx); - predecessors[otherIdx]++; - } - } - } - - // kahn's algorithm: emit quads with no predecessors and remove them from the graph - // until either all quads are emitted or a cycle is detected - IntArrayFIFOQueue ready = new IntArrayFIFOQueue(n); - for (int quadIdx = 0; quadIdx < n; quadIdx++) { - if (predecessors[quadIdx] == 0) { - ready.enqueue(quadIdx); - } - } - + // 0 = unvisited, 1 = on the stack, 2 = finished + byte[] state = new byte[n]; + int[] stack = new int[n], next = new int[n]; int[] out = new int[n]; - int o = 0; + int finished = 0; - while (!ready.isEmpty()) { - int current = ready.dequeueInt(); - out[o++] = group[current]; + for (int root = 0; root < n; root++) { + if (state[root] != 0) continue; - IntArrayList next = successors[current]; - if (next == null) continue; + int depth = 0; + stack[0] = root; + next[0] = 0; + state[root] = 1; - for (int i = 0; i < next.size(); i++) { - int successor = next.getInt(i); + while (depth >= 0) { + int current = stack[depth]; + int candidate = next[depth]; - if (--predecessors[successor] == 0) { - ready.enqueue(successor); + // advance to the next quad that must be drawn after the current one + while (candidate < n && (state[candidate] == 2 || candidate == current + || !quads.isSeenThrough(group[current], group[candidate]))) { + candidate++; } + + if (candidate == n) { + state[current] = 2; + out[n - 1 - finished++] = group[current]; // reverse postorder: predecessors first + depth--; + continue; + } + + if (state[candidate] == 1) { + return null; // back edge: a cycle + } + + next[depth] = candidate + 1; + depth++; + stack[depth] = candidate; + next[depth] = 0; + state[candidate] = 1; } } - return o == n ? out : null; + return out; } } -- 2.54.1 From 7cf7c5367c500ef72c059e56eb56346fc44a4700 Mon Sep 17 00:00:00 2001 From: rdh Date: Mon, 14 Sep 2026 01:03:45 -0400 Subject: [PATCH 20/23] try a static order on small groups before cutting them a group of at most 256 quads that sorts topologically becomes one leaf, and every plane below it is gone --- .../render/chunk/sorting/PartitionTree.java | 30 ++++++++++++++----- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java index ac800672e..a92f2b672 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java @@ -21,13 +21,19 @@ public final class PartitionTree implements SortState.Resortable { this.cutPlanes = cutPlanes; } + static final int STATIC_LEAF_QUADS = 256; + // null when some slab has no free cut public static @Nullable PartitionTree build(QuadSet quads) { + return build(quads, STATIC_LEAF_QUADS); + } + + static @Nullable PartitionTree build(QuadSet quads, int staticLeafQuads) { int[] all = new int[quads.count()]; for (int i = 0; i < all.length; i++) all[i] = i; FloatArrayList[] cuts = { new FloatArrayList(), new FloatArrayList(), new FloatArrayList() }; - Node root = partition(quads, all, 2, cuts); + Node root = partition(quads, all, 2, cuts, staticLeafQuads); if (root == null) return null; float[][] cutPlanes = new float[3][]; @@ -68,7 +74,7 @@ public final class PartitionTree implements SortState.Resortable { return FloatArrays.copy(array, 0, n); } - private static Node partition(QuadSet quads, int[] group, int parentAxis, FloatArrayList[] collectedCuts) { + private static Node partition(QuadSet quads, int[] group, int parentAxis, FloatArrayList[] collectedCuts, int staticLeafQuads) { if (group.length <= 1) { return new Leaf(group); } @@ -78,6 +84,14 @@ public final class PartitionTree implements SortState.Resortable { return new Leaf(parallel); } + boolean triedStatic = group.length <= staticLeafQuads; + if (triedStatic) { + int[] topological = TranslucentSorter.topologicalOrder(quads, group); + if (topological != null) { + return new Leaf(topological); + } + } + int axis = -1; float[] planes = FloatArrays.EMPTY_ARRAY; for (int i = 0; i < 3; i++) { @@ -87,11 +101,11 @@ public final class PartitionTree implements SortState.Resortable { } if (planes.length == 0) { // no free cut does not imply a cycle: a camera-independent order may still exist - int[] topological = group.length <= TranslucentSorter.MAX_TOPO_QUADS ? TranslucentSorter.topologicalOrder(quads, group) : null; + int[] topological = !triedStatic && group.length <= TranslucentSorter.MAX_TOPO_QUADS ? TranslucentSorter.topologicalOrder(quads, group) : null; if (topological != null) { return new Leaf(topological); } - return partitionIntersectors(quads, group, collectedCuts); + return partitionIntersectors(quads, group, collectedCuts, staticLeafQuads); } Buckets buckets = bucket(quads, group, axis, planes); @@ -114,7 +128,7 @@ public final class PartitionTree implements SortState.Resortable { slabs[i] = EMPTY; continue; } - Node child = partition(quads, slabGroup, axis, collectedCuts); + Node child = partition(quads, slabGroup, axis, collectedCuts, staticLeafQuads); if (child == null) return null; slabs[i] = child; } @@ -178,7 +192,7 @@ public final class PartitionTree implements SortState.Resortable { return true; } - private static @Nullable Node partitionIntersectors(QuadSet quads, int[] group, FloatArrayList[] collectedCuts) { + private static @Nullable Node partitionIntersectors(QuadSet quads, int[] group, FloatArrayList[] collectedCuts, int staticLeafQuads) { int n = group.length; if (n > TranslucentSorter.MAX_TOPO_QUADS) return null; @@ -213,8 +227,8 @@ public final class PartitionTree implements SortState.Resortable { for (int i = 0, f = 0, r = 0; i < n; i++) { if (primary[i]) first[f++] = group[i]; else rest[r++] = group[i]; } - Node a = partition(quads, first, 2, collectedCuts); - Node b = a == null ? null : partition(quads, rest, 2, collectedCuts); + Node a = partition(quads, first, 2, collectedCuts, staticLeafQuads); + Node b = a == null ? null : partition(quads, rest, 2, collectedCuts, staticLeafQuads); return b == null ? null : new Fixed(a, b); } -- 2.54.1 From 2a75492cab77dfce8e1dea90b076083c94265497 Mon Sep 17 00:00:00 2001 From: rdh Date: Wed, 16 Sep 2026 00:29:53 -0400 Subject: [PATCH 21/23] toposort the other way quads with no relation should come out in ascending index order --- .../render/chunk/sorting/TranslucentSorter.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java index 77bca3a2a..c5f932021 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java @@ -242,12 +242,12 @@ public final class TranslucentSorter { int[] out = new int[n]; int finished = 0; - for (int root = 0; root < n; root++) { + for (int root = n - 1; root >= 0; root--) { if (state[root] != 0) continue; int depth = 0; stack[0] = root; - next[0] = 0; + next[0] = n - 1; state[root] = 1; while (depth >= 0) { @@ -255,12 +255,12 @@ public final class TranslucentSorter { int candidate = next[depth]; // advance to the next quad that must be drawn after the current one - while (candidate < n && (state[candidate] == 2 || candidate == current + while (candidate >= 0 && (state[candidate] == 2 || candidate == current || !quads.isSeenThrough(group[current], group[candidate]))) { - candidate++; + candidate--; } - if (candidate == n) { + if (candidate < 0) { state[current] = 2; out[n - 1 - finished++] = group[current]; // reverse postorder: predecessors first depth--; @@ -271,10 +271,10 @@ public final class TranslucentSorter { return null; // back edge: a cycle } - next[depth] = candidate + 1; + next[depth] = candidate - 1; depth++; stack[depth] = candidate; - next[depth] = 0; + next[depth] = n - 1; state[candidate] = 1; } } -- 2.54.1 From fd362d1b76166896917529b813a149573188acb4 Mon Sep 17 00:00:00 2001 From: rdh Date: Wed, 16 Sep 2026 00:30:18 -0400 Subject: [PATCH 22/23] skip degenerate quads in the parallel check --- .../embeddium/impl/render/chunk/sorting/TranslucentSorter.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java index c5f932021..f441d3633 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java @@ -126,6 +126,8 @@ public final class TranslucentSorter { boolean allParallel = true; for (int quadIdx = 0; quadIdx < quadCount; quadIdx++) { + if (quads.isDegenerate(quadIdx)) continue; + float dot = quads.normalDot(quadIdx, reference); if (Math.abs(dot) < PARALLEL_THRESHOLD) { -- 2.54.1 From b80485bcbba1a939ef70b549d3ce1832aec4f675 Mon Sep 17 00:00:00 2001 From: embeddedt <42941056+embeddedt@users.noreply.github.com> Date: Wed, 16 Sep 2026 09:19:24 -0400 Subject: [PATCH 23/23] Fix dynamic section sorting potentially lagging slightly --- .../impl/render/chunk/RenderSectionManager.java | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java index 5ea753c86..a6bfaea65 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java @@ -705,16 +705,18 @@ public abstract class RenderSectionManager { break; } } + + // any crossing up to now was just handled. Dynamic sections keep the submission camera so that + // scheduleTranslucencyUpdates still sees movement made during the build. + if (latestBuild) { + render.lastCameraX = this.cameraPosition.x; + render.lastCameraY = this.cameraPosition.y; + render.lastCameraZ = this.cameraPosition.z; + } } else { // a rebuild that is no longer tree-sorted must drop its stale planes this.cutPlaneIndex.remove(render); } - - if (latestBuild) { - render.lastCameraX = this.cameraPosition.x; - render.lastCameraY = this.cameraPosition.y; - render.lastCameraZ = this.cameraPosition.z; - } } // Section MetadataSink: mirrors a section's packed metadata into the graph-search lattice on every -- 2.54.1