Smarter translucency sorting #42

Merged
embeddedt merged 24 commits from rdh/celeritas:ts into stonecutter 2026-09-16 11:25:42 -04:00
5 changed files with 362 additions and 190 deletions
Showing only changes of commit b6f7d74534 - Show all commits

No files matched your search

@@ -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;
}
}
@@ -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;
}
}
@@ -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());
}
}
@@ -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:
* <ol>
* <li>no quads, or none that cover any pixels</li>
* <li>everything in one plane</li>
* <li>every quad flat on the section's bounding box, facing outward</li>
* <li>all normals parallel, so one order works from everywhere</li>
* <li>otherwise the order depends on the camera</li>
* </ol>
*/
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;
}
}
@@ -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) {