Smarter translucency sorting #42
No files matched your search
@@ -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<TerrainRenderPass, TranslucentQuadAnalyzer.SortState> translucencySortStates = Collections.emptyMap();
|
||||
private Map<TerrainRenderPass, SortState.Resortable> 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<TerrainRenderPass, TranslucentQuadAnalyzer.SortState> 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<TerrainRenderPass, SortState.Resortable> 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() {
|
||||
|
||||
+17
-46
@@ -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<TerrainRenderPass, BuiltSectionMeshParts> meshes) {
|
||||
Map<TerrainRenderPass, TranslucentQuadAnalyzer.SortState> sortStates = new Reference2ObjectArrayMap<>();
|
||||
Map<TerrainRenderPass, SortState.Resortable> 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<String> getSortingStrings() {
|
||||
List<String> list = new ArrayList<>();
|
||||
|
||||
int[] sectionCounts = new int[TranslucentQuadAnalyzer.Level.VALUES.length];
|
||||
|
||||
for (Iterator<ChunkRenderList> 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<TerrainRenderPass> computeRenderPassTimingsMap() {
|
||||
Object2LongOpenHashMap<TerrainRenderPass> map = new Object2LongOpenHashMap<>();
|
||||
for (var entry : renderPassDrawTimers.entrySet()) {
|
||||
|
||||
+4
-3
@@ -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() {
|
||||
|
||||
+2
-2
@@ -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<String> getDefines() {
|
||||
return List.of();
|
||||
|
||||
+9
-63
@@ -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);
|
||||
}
|
||||
}
|
||||
+6
-6
@@ -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<ChunkSortOutput> {
|
||||
private final RenderSection render;
|
||||
private final float cameraX, cameraY, cameraZ;
|
||||
private final int frame;
|
||||
private final Map<TerrainRenderPass, TranslucentQuadAnalyzer.SortState> translucentMeshes;
|
||||
private final Map<TerrainRenderPass, SortState.Resortable> translucentMeshes;
|
||||
private final RenderPassConfiguration<?> renderPassConfiguration;
|
||||
|
||||
public ChunkBuilderSortTask(RenderSection render, float cameraX, float cameraY, float cameraZ, int frame, Map<TerrainRenderPass, TranslucentQuadAnalyzer.SortState> translucentMeshes, RenderPassConfiguration<?> renderPassConfiguration) {
|
||||
public ChunkBuilderSortTask(RenderSection render, float cameraX, float cameraY, float cameraZ, int frame, Map<TerrainRenderPass, SortState.Resortable> translucentMeshes, RenderPassConfiguration<?> renderPassConfiguration) {
|
||||
this.render = render;
|
||||
this.cameraX = cameraX;
|
||||
this.cameraY = cameraY;
|
||||
@@ -32,11 +32,11 @@ public class ChunkBuilderSortTask extends ChunkBuilderTask<ChunkSortOutput> {
|
||||
@Override
|
||||
public ChunkSortOutput execute(ChunkBuildContext context, CancellationToken cancellationSource) {
|
||||
var meshes = new Reference2ReferenceOpenHashMap<TerrainRenderPass, ChunkSortOutput.SortedMesh>();
|
||||
for(Map.Entry<TerrainRenderPass, TranslucentQuadAnalyzer.SortState> entry : translucentMeshes.entrySet()) {
|
||||
for(Map.Entry<TerrainRenderPass, SortState.Resortable> 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
|
||||
));
|
||||
|
||||
+2
-2
@@ -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<ModelQuadFacing, VertexRange> ranges) {
|
||||
public record BuiltSectionMeshParts(NativeBuffer vertexBuffer, @Nullable NativeBuffer indexBuffer, @Nullable SortState sortState, Map<ModelQuadFacing, VertexRange> ranges) {
|
||||
public void free() {
|
||||
vertexBuffer.free();
|
||||
if (indexBuffer != null) {
|
||||
|
||||
+10
-10
@@ -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()]++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
-73
@@ -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);
|
||||
if (hasDistinctNormals) {
|
||||
// The order depends on the camera, so copy the centers and re-sort whenever it moves
|
||||
return new SortState.Dynamic(quadCenters.toFloatArray());
|
||||
}
|
||||
|
||||
return finalState;
|
||||
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() {
|
||||
|
||||
+76
@@ -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.
|
||||
* <p>
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user