rasterized occlusion culling #38

Merged
embeddedt merged 20 commits from rdh/celeritas:raster into stonecutter 2026-09-04 22:15:05 -04:00
11 changed files with 861 additions and 306 deletions
Showing only changes of commit 254659b5ec - Show all commits

No files matched your search

+3
View File
@@ -160,6 +160,8 @@ tasks.register('rasterCullReport', JavaExec) {
mainClass = 'org.embeddedt.embeddium.impl.render.chunk.occlusion.bench.RasterCullReport' mainClass = 'org.embeddedt.embeddium.impl.render.chunk.occlusion.bench.RasterCullReport'
maxHeapSize = '1g' maxHeapSize = '1g'
// e.g. ./gradlew :common:rasterCullReport -Dreport.renderDistance=64
systemProperties System.getProperties().findAll { it.key.toString().startsWith('report.') }
} }
publishing { publishing {
@@ -246,5 +248,6 @@ tasks.register('rasterStats', JavaExec) {
mainClass = 'org.embeddedt.embeddium.impl.render.chunk.occlusion.bench.RasterStatsReport' mainClass = 'org.embeddedt.embeddium.impl.render.chunk.occlusion.bench.RasterStatsReport'
maxHeapSize = '1g' maxHeapSize = '1g'
jvmArgs '-Dbitraster.stats=true' jvmArgs '-Dbitraster.stats=true'
systemProperties System.getProperties().findAll { it.key.toString().startsWith('report.') }
doFirst { if (project.hasProperty('statargs')) args(project.property('statargs').toString().split('\\s+').findAll { !it.isEmpty() }) } doFirst { if (project.hasProperty('statargs')) args(project.property('statargs').toString().split('\\s+').findAll { !it.isEmpty() }) }
} }
@@ -12,7 +12,7 @@ import org.embeddedt.embeddium.impl.render.viewport.Viewport;
* {@code yscan lo hi} to print visible counts (raster/baseline) per yaw step as the camera height varies. * {@code yscan lo hi} to print visible counts (raster/baseline) per yaw step as the camera height varies.
*/ */
public final class RasterStatsReport { public final class RasterStatsReport {
private static final int RENDER_DISTANCE = 32; private static final int RENDER_DISTANCE = Integer.getInteger("report.renderDistance", 32);
private static final int YAW_STEPS = 8; private static final int YAW_STEPS = 8;
private static final int WARM = 150; private static final int WARM = 150;
@@ -71,8 +71,8 @@ public final class RasterStatsReport {
int n = YAW_STEPS; int n = YAW_STEPS;
System.out.printf("world=%s visible/frame=%d total=%.3fms test=%.3fms occlude=%.3fms%n", worldType, visible / n, System.out.printf("world=%s visible/frame=%d total=%.3fms test=%.3fms occlude=%.3fms%n", worldType, visible / n,
total / 1e6 / n, RasterOccluder.STAT_TEST_NANOS / 1e6 / n, RasterOccluder.STAT_OCCLUDE_NANOS / 1e6 / n); total / 1e6 / n, RasterOccluder.STAT_TEST_NANOS / 1e6 / n, RasterOccluder.STAT_OCCLUDE_NANOS / 1e6 / n);
System.out.printf("sections tested=%d occluded=%d%n", RasterOccluder.STAT_SECTIONS / n, System.out.printf("sections tested=%d occluded=%d regionSkip=%d vertexHit=%d%n", RasterOccluder.STAT_SECTIONS / n,
RasterOccluder.STAT_OCCLUDED_SECTIONS / n); RasterOccluder.STAT_OCCLUDED_SECTIONS / n, RasterOccluder.STAT_REGION_SKIP / n, AbstractRasterizer.STAT_T_VERTEX / n);
System.out.printf("draw calls=%d polygons=%d tiles=%d | test calls=%d polygons=%d tiles=%d | eventRows=%d%n", System.out.printf("draw calls=%d polygons=%d tiles=%d | test calls=%d polygons=%d tiles=%d | eventRows=%d%n",
AbstractRasterizer.STAT_DRAW_CALLS / n, AbstractRasterizer.STAT_DRAW_QUADS / n, AbstractRasterizer.STAT_DRAW_CALLS / n, AbstractRasterizer.STAT_DRAW_QUADS / n,
(AbstractRasterizer.STAT_D_INNER + AbstractRasterizer.STAT_D_COVER) / n, (AbstractRasterizer.STAT_D_INNER + AbstractRasterizer.STAT_D_COVER) / n,
@@ -84,16 +84,16 @@ public final class RasterStatsReport {
} }
private static void printExtra(int n) { private static void printExtra(int n) {
System.out.printf("centerHit=%d near=%d fullbox tests=%d fullbox visible=%d | test: empty=%d inner=%d cover=%d hidden=%d | draw tiles: inner=%d cover=%d%n", System.out.printf("centerHit=%d near=%d fullbox tests=%d fullbox visible=%d | test: empty=%d inner=%d cover=%d hidden=%d boxHidden=%d | draw tiles: inner=%d cover=%d%n",
RasterOccluder.STAT_CENTER_HIT / n, RasterOccluder.STAT_NEAR / n, RasterOccluder.STAT_AIR_TESTS / n, RasterOccluder.STAT_AIR_VISIBLE / n, RasterOccluder.STAT_CENTER_HIT / n, RasterOccluder.STAT_NEAR / n, RasterOccluder.STAT_AIR_TESTS / n, RasterOccluder.STAT_AIR_VISIBLE / n,
AbstractRasterizer.STAT_T_EMPTY / n, AbstractRasterizer.STAT_T_INNER / n, AbstractRasterizer.STAT_T_COVER / n, AbstractRasterizer.STAT_T_HIDDEN / n, AbstractRasterizer.STAT_T_EMPTY / n, AbstractRasterizer.STAT_T_INNER / n, AbstractRasterizer.STAT_T_COVER / n, AbstractRasterizer.STAT_T_HIDDEN / n, AbstractRasterizer.STAT_T_BOX_HIDDEN / n,
AbstractRasterizer.STAT_D_INNER / n, AbstractRasterizer.STAT_D_COVER / n); AbstractRasterizer.STAT_D_INNER / n, AbstractRasterizer.STAT_D_COVER / n);
} }
private static void reset() { private static void reset() {
AbstractRasterizer.STAT_D_NOOP = AbstractRasterizer.STAT_D_RANGE0 = AbstractRasterizer.STAT_D_RANGE1 = AbstractRasterizer.STAT_D_RANGE2 = AbstractRasterizer.STAT_D_RANGE3 = 0; AbstractRasterizer.STAT_D_NOOP = AbstractRasterizer.STAT_D_RANGE0 = AbstractRasterizer.STAT_D_RANGE1 = AbstractRasterizer.STAT_D_RANGE2 = AbstractRasterizer.STAT_D_RANGE3 = 0;
RasterOccluder.STAT_CENTER_HIT = RasterOccluder.STAT_NEAR = RasterOccluder.STAT_AIR_TESTS = RasterOccluder.STAT_AIR_VISIBLE = 0; RasterOccluder.STAT_CENTER_HIT = RasterOccluder.STAT_NEAR = RasterOccluder.STAT_AIR_TESTS = RasterOccluder.STAT_AIR_VISIBLE = RasterOccluder.STAT_REGION_SKIP = AbstractRasterizer.STAT_T_VERTEX = 0;
AbstractRasterizer.STAT_T_EMPTY = AbstractRasterizer.STAT_T_INNER = AbstractRasterizer.STAT_T_COVER = AbstractRasterizer.STAT_T_HIDDEN = 0; AbstractRasterizer.STAT_T_EMPTY = AbstractRasterizer.STAT_T_INNER = AbstractRasterizer.STAT_T_COVER = AbstractRasterizer.STAT_T_HIDDEN = AbstractRasterizer.STAT_T_BOX_HIDDEN = 0;
AbstractRasterizer.STAT_D_INNER = AbstractRasterizer.STAT_D_COVER = 0; AbstractRasterizer.STAT_D_INNER = AbstractRasterizer.STAT_D_COVER = 0;
RasterOccluder.STAT_TEST_NANOS = RasterOccluder.STAT_OCCLUDE_NANOS = RasterOccluder.STAT_SECTIONS = RasterOccluder.STAT_OCCLUDED_SECTIONS = 0; RasterOccluder.STAT_TEST_NANOS = RasterOccluder.STAT_OCCLUDE_NANOS = RasterOccluder.STAT_SECTIONS = RasterOccluder.STAT_OCCLUDED_SECTIONS = 0;
AbstractRasterizer.STAT_DRAW_CALLS = AbstractRasterizer.STAT_DRAW_QUADS = 0; AbstractRasterizer.STAT_DRAW_CALLS = AbstractRasterizer.STAT_DRAW_QUADS = 0;
File diff suppressed because it is too large. Load diff
@@ -992,12 +992,12 @@ public abstract class BoxOccluder {
/** /**
* Changes the buffer size; call before {@link #prepareScene} since the buffer is discarded. * Changes the buffer size; call before {@link #prepareScene} since the buffer is discarded.
* @param widthBits tiles across as a power of two, see {@link Constants#DEFAULT_SIZE_BITS} * @param tileWidth tiles across, see {@link Constants#DEFAULT_SIZE_TILES}
* @param heightBits tiles down, likewise * @param tileHeight tiles down, likewise
*/ */
public final void resizeBuffer(int widthBits, int heightBits) { public final void resizeBuffer(int tileWidth, int tileHeight) {
if (widthBits != raster.widthBits() || heightBits != raster.heightBits()) { if (tileWidth != raster.tileWidth() || tileHeight != raster.tileHeight()) {
raster.resize(widthBits, heightBits); raster.resize(tileWidth, tileHeight);
forceRedraw = true; forceRedraw = true;
} }
} }
@@ -1014,13 +1014,49 @@ public abstract class BoxOccluder {
regionSquaredChunkDist = squaredChunkDistance; regionSquaredChunkDist = squaredChunkDistance;
// PERF: could perhaps reuse CameraRelativeCenter values in BuildRenderRegion that are used by Frustum // PERF: could perhaps reuse CameraRelativeCenter values in BuildRenderRegion that are used by Frustum
offsetX = (int) ((originX << CAMERA_PRECISION_BITS) - viewX); offsetX = (int) (((long) originX << CAMERA_PRECISION_BITS) - viewX);
offsetY = (int) ((originY << CAMERA_PRECISION_BITS) - viewY); offsetY = (int) (((long) originY << CAMERA_PRECISION_BITS) - viewY);
offsetZ = (int) ((originZ << CAMERA_PRECISION_BITS) - viewZ); offsetZ = (int) (((long) originZ << CAMERA_PRECISION_BITS) - viewZ);
raster.setRegionOffset(offsetX, offsetY, offsetZ); raster.setRegionOffset(offsetX, offsetY, offsetZ);
} }
/**
* Screen tile bounds of a world-space box for the current scene, as {@link AbstractRasterizer#boxTileBounds}
* packs them. Does not disturb the region prepared by {@link #prepareRegion}.
*/
public final long boxTileBounds(int originX, int originY, int originZ, int sizeX, int sizeY, int sizeZ) {
final float scale = 1f / CAMERA_PRECISION_UNITY;
final float fx = (int) (((long) originX << CAMERA_PRECISION_BITS) - viewX) * scale;
final float fy = (int) (((long) originY << CAMERA_PRECISION_BITS) - viewY) * scale;
final float fz = (int) (((long) originZ << CAMERA_PRECISION_BITS) - viewZ) * scale;
return raster.boxTileBounds(fx, fy, fz, sizeX, sizeY, sizeZ);
}
/** Writes the clip-space x, y and w of a world-space point for the current scene; see {@link AbstractRasterizer#clipPoint}. */
public final void clipPoint(int x, int y, int z, float[] out, int offset) {
final float scale = 1f / CAMERA_PRECISION_UNITY;
final float fx = (int) (((long) x << CAMERA_PRECISION_BITS) - viewX) * scale;
final float fy = (int) (((long) y << CAMERA_PRECISION_BITS) - viewY) * scale;
final float fz = (int) (((long) z << CAMERA_PRECISION_BITS) - viewZ) * scale;
raster.clipPoint(fx, fy, fz, out, offset);
}
/** See {@link AbstractRasterizer#isSectionCenterOnScreen}. */
public final boolean isSectionCenterOnScreen(float[] base, int offset, int i, int j, int k) {
return raster.isSectionCenterOnScreen(base, offset, i, j, k);
}
/** See {@link AbstractRasterizer#touchedVersion}. */
public final int touchedVersion() {
return raster.touchedVersion();
}
/** See {@link AbstractRasterizer#isTileBoxUntouched}. */
public final boolean isTileBoxUntouched(int packedTileBounds) {
return raster.isTileBoxUntouched(packedTileBounds);
}
/** /**
* Check if needs redrawn and prep for redraw if so. * Check if needs redrawn and prep for redraw if so.
* When false, regions should be drawn only if their occluder version is not current. * When false, regions should be drawn only if their occluder version is not current.
@@ -1127,7 +1163,8 @@ public abstract class BoxOccluder {
final int[] silhouette = SILHOUETTES[outcome]; final int[] silhouette = SILHOUETTES[outcome];
if (silhouette != null && raster.setupBoxVertices(silhouette, x0, y0, z0, x1, y1, z1)) { if (silhouette != null && raster.setupBoxVertices(silhouette, x0, y0, z0, x1, y1, z1)) {
return raster.isPolygonPartiallyClear(silhouette, silhouette.length); return raster.isAnyVertexPixelClear(silhouette, silhouette.length)
|| raster.isPolygonPartiallyClear(silhouette, silhouette.length);
} }
return partiallyClearTests[outcome].apply(x0, y0, z0, x1, y1, z1); return partiallyClearTests[outcome].apply(x0, y0, z0, x1, y1, z1);
@@ -23,7 +23,7 @@ public class Constants {
public static final int WEST = 1 << 4; public static final int WEST = 1 << 4;
public static final int NORTH = 1 << 2; public static final int NORTH = 1 << 2;
public static final int SOUTH = 1 << 3; public static final int SOUTH = 1 << 3;
static final int TILE_AXIS_SHIFT = 3; public static final int TILE_AXIS_SHIFT = 3;
static final int TILE_AXIS_MASK = ~((1 << TILE_AXIS_SHIFT) - 1); static final int TILE_AXIS_MASK = ~((1 << TILE_AXIS_SHIFT) - 1);
static final int TILE_PIXEL_DIAMETER = 1 << TILE_AXIS_SHIFT; static final int TILE_PIXEL_DIAMETER = 1 << TILE_AXIS_SHIFT;
static final int TILE_PIXEL_INDEX_MASK = TILE_PIXEL_DIAMETER - 1; static final int TILE_PIXEL_INDEX_MASK = TILE_PIXEL_DIAMETER - 1;
@@ -36,10 +36,13 @@ public class Constants {
static final int SCANT_PRECISE_PIXEL_CENTER = PRECISE_PIXEL_CENTER - 1; static final int SCANT_PRECISE_PIXEL_CENTER = PRECISE_PIXEL_CENTER - 1;
// CELERITAS: the buffer size is chosen per rasterizer and per axis (see AbstractRasterizer.resize); upstream // CELERITAS: the buffer size is chosen per rasterizer and per axis (see AbstractRasterizer.resize); upstream
// fixed it at 2048px square. // fixed it at 2048px square.
/** Occlusion buffer size along one axis in tiles, as a power of two: 6 = 512 px, 7 = 1024 px, 8 = 2048 px. */ /**
public static final int MIN_SIZE_BITS = 6; * Occlusion buffer size along one axis in tiles of eight pixels. Any width in range is allowed, not just
public static final int DEFAULT_SIZE_BITS = 7; * powers of two, so an axis can be sized to what the search distance needs without rounding up to double it.
public static final int MAX_SIZE_BITS = 8; */
public static final int MIN_SIZE_TILES = 64;
public static final int DEFAULT_SIZE_TILES = 128;
public static final int MAX_SIZE_TILES = 256;
// CELERITAS: pixels added on every side of a tested polygon so that a visible strip narrower than the pixel // CELERITAS: pixels added on every side of a tested polygon so that a visible strip narrower than the pixel
// pitch still reaches a sampled pixel centre. One pixel covers centre sampling exactly; occluders are never grown. // pitch still reaches a sampled pixel centre. One pixel covers centre sampling exactly; occluders are never grown.
@@ -17,7 +17,7 @@
package grondag.bitraster; package grondag.bitraster;
import static grondag.bitraster.Constants.PROJECTED_VERTEX_STRIDE; import static grondag.bitraster.Constants.PROJECTED_VERTEX_STRIDE;
import static grondag.bitraster.Constants.DEFAULT_SIZE_BITS; import static grondag.bitraster.Constants.DEFAULT_SIZE_TILES;
import static grondag.bitraster.Constants.PV_PX; import static grondag.bitraster.Constants.PV_PX;
import static grondag.bitraster.Constants.PV_PY; import static grondag.bitraster.Constants.PV_PY;
import static grondag.bitraster.Constants.PV_X; import static grondag.bitraster.Constants.PV_X;
@@ -25,11 +25,11 @@ import static grondag.bitraster.Constants.PV_Y;
public final class OrthoRasterizer extends AbstractRasterizer { public final class OrthoRasterizer extends AbstractRasterizer {
public OrthoRasterizer() { public OrthoRasterizer() {
this(DEFAULT_SIZE_BITS, DEFAULT_SIZE_BITS); this(DEFAULT_SIZE_TILES, DEFAULT_SIZE_TILES);
} }
public OrthoRasterizer(int widthBits, int heightBits) { public OrthoRasterizer(int tileWidth, int tileHeight) {
super(widthBits, heightBits); super(tileWidth, tileHeight);
} }
@Override @Override
@@ -16,7 +16,7 @@
package grondag.bitraster; package grondag.bitraster;
import static grondag.bitraster.Constants.DEFAULT_SIZE_BITS; import static grondag.bitraster.Constants.DEFAULT_SIZE_TILES;
import static grondag.bitraster.Constants.BOUNDS_IN; import static grondag.bitraster.Constants.BOUNDS_IN;
import static grondag.bitraster.Constants.BOUNDS_OUTSIDE_OR_TOO_SMALL; import static grondag.bitraster.Constants.BOUNDS_OUTSIDE_OR_TOO_SMALL;
import static grondag.bitraster.Constants.EVENT_POSITION_MASK; import static grondag.bitraster.Constants.EVENT_POSITION_MASK;
@@ -48,11 +48,11 @@ import static grondag.bitraster.Constants.SCANT_PRECISE_PIXEL_CENTER;
public final class PerspectiveRasterizer extends AbstractRasterizer { public final class PerspectiveRasterizer extends AbstractRasterizer {
public PerspectiveRasterizer() { public PerspectiveRasterizer() {
this(DEFAULT_SIZE_BITS, DEFAULT_SIZE_BITS); this(DEFAULT_SIZE_TILES, DEFAULT_SIZE_TILES);
} }
public PerspectiveRasterizer(int widthBits, int heightBits) { public PerspectiveRasterizer(int tileWidth, int tileHeight) {
super(widthBits, heightBits); super(tileWidth, tileHeight);
} }
/** Holds results of {@link #clipNear(int, int)}. */ /** Holds results of {@link #clipNear(int, int)}. */
@@ -77,8 +77,8 @@ public final class PerspectiveRasterizer extends AbstractRasterizer {
if (w != 0) { if (w != 0) {
final float iw = 1f / w; final float iw = 1f / w;
final int px = Math.round(tx * iw * halfPreciseWidth) + halfPreciseWidth; final int px = roundToInt(tx * iw * halfPreciseWidth) + halfPreciseWidth;
final int py = Math.round(ty * iw * halfPreciseHeight) + halfPreciseHeight; final int py = roundToInt(ty * iw * halfPreciseHeight) + halfPreciseHeight;
data[baseIndex + PV_PX] = px; data[baseIndex + PV_PX] = px;
data[baseIndex + PV_PY] = py; data[baseIndex + PV_PY] = py;
@@ -90,32 +90,28 @@ public final class PerspectiveRasterizer extends AbstractRasterizer {
transformBoxCorners(x0, y0, z0, x1, y1, z1); transformBoxCorners(x0, y0, z0, x1, y1, z1);
final int[] data = vertexData; final int[] data = vertexData;
final float[] cx = cornerX, cy = cornerY, cz = cornerZ, cw = cornerW; final float[] cx = cornerX, cy = cornerY, cw = cornerW, cz = cornerZ;
boolean unclipped = true; final int halfPreciseWidth = this.halfPreciseWidth;
final int halfPreciseHeight = this.halfPreciseHeight;
// only the projected position is stored: the clip-space coordinates are needed by the near-clip
// fallback alone, and that path recomputes every vertex it uses through setupVertex
for (int baseIndex : corners) { for (int baseIndex : corners) {
final int corner = baseIndex / PROJECTED_VERTEX_STRIDE; final int corner = baseIndex / PROJECTED_VERTEX_STRIDE;
final float tx = cx[corner];
final float ty = cy[corner];
final float tz = cz[corner];
final float w = cw[corner]; final float w = cw[corner];
final float tz = cz[corner];
data[baseIndex + PV_X] = Float.floatToRawIntBits(tx);
data[baseIndex + PV_Y] = Float.floatToRawIntBits(ty);
data[baseIndex + PV_Z] = Float.floatToRawIntBits(tz);
data[baseIndex + PV_W] = Float.floatToRawIntBits(w);
// same acceptance as needsNearClip // same acceptance as needsNearClip
if (w > 0 && tz > 0 && tz <= w) { if (!(w > 0 && tz > 0 && tz <= w)) {
final float iw = 1f / w; return false;
data[baseIndex + PV_PX] = Math.round(tx * iw * halfPreciseWidth) + halfPreciseWidth;
data[baseIndex + PV_PY] = Math.round(ty * iw * halfPreciseHeight) + halfPreciseHeight;
} else {
unclipped = false;
} }
final float iw = 1f / w;
data[baseIndex + PV_PX] = roundToInt(cx[corner] * iw * halfPreciseWidth) + halfPreciseWidth;
data[baseIndex + PV_PY] = roundToInt(cy[corner] * iw * halfPreciseHeight) + halfPreciseHeight;
} }
return unclipped; return true;
} }
@Override @Override
@@ -162,8 +158,8 @@ public final class PerspectiveRasterizer extends AbstractRasterizer {
final float w = (intW + (extW - intW) * wt); final float w = (intW + (extW - intW) * wt);
final float iw = 1f / w; final float iw = 1f / w;
clipX = Math.round(iw * x * halfPreciseWidth) + halfPreciseWidth; clipX = roundToInt(iw * x * halfPreciseWidth) + halfPreciseWidth;
clipY = Math.round(iw * y * halfPreciseHeight) + halfPreciseHeight; clipY = roundToInt(iw * y * halfPreciseHeight) + halfPreciseHeight;
} }
@Override @Override
@@ -68,6 +68,7 @@ public final class PackedSectionMetadata {
private static final long PENDING_UPDATE_MASK = 0b111L; private static final long PENDING_UPDATE_MASK = 0b111L;
// Bit 52: a build cancellation token is currently attached. // Bit 52: a build cancellation token is currently attached.
// Bit 53 is reserved for SectionLattice.OCCLUDER_DATA_FLAG on the lattice's copy of the word.
private static final int BUILD_IN_FLIGHT_BIT = 52; private static final int BUILD_IN_FLIGHT_BIT = 52;
private static final long BUILD_IN_FLIGHT_FLAG = 1L << BUILD_IN_FLIGHT_BIT; private static final long BUILD_IN_FLIGHT_FLAG = 1L << BUILD_IN_FLIGHT_BIT;
@@ -1,5 +1,6 @@
package org.embeddedt.embeddium.impl.render.chunk.occlusion; package org.embeddedt.embeddium.impl.render.chunk.occlusion;
import grondag.bitraster.AbstractRasterizer;
import grondag.bitraster.PackedBox; import grondag.bitraster.PackedBox;
import org.embeddedt.embeddium.impl.common.util.MathUtil; import org.embeddedt.embeddium.impl.common.util.MathUtil;
import org.embeddedt.embeddium.impl.render.chunk.LocalSectionIndex; import org.embeddedt.embeddium.impl.render.chunk.LocalSectionIndex;
@@ -192,7 +193,7 @@ public class OcclusionCuller {
this.rasterActive = this.rasterOccluder != null && useOcclusionCulling && viewport.getVpMatrix() != null; this.rasterActive = this.rasterOccluder != null && useOcclusionCulling && viewport.getVpMatrix() != null;
if (this.rasterActive) { if (this.rasterActive) {
this.rasterOccluder.prepareScene(frame, viewport, searchDistance); this.rasterOccluder.prepareScene(frame, viewport, searchDistance, numRegions);
} }
this.process(visitor, viewport, searchDistance, useOcclusionCulling, allowFrustumClamping, frame); this.process(visitor, viewport, searchDistance, useOcclusionCulling, allowFrustumClamping, frame);
@@ -263,10 +264,10 @@ public class OcclusionCuller {
int regionId = regionOfCell[idx]; int regionId = regionOfCell[idx];
long sm = sectionMeta[idx]; long sm = sectionMeta[idx];
int compactMeta = PackedSectionMetadata.toCompactMeta(sm); int compactMeta = PackedSectionMetadata.toCompactMeta(sm);
int classification = cache.classify(regionId, int regionX = regionOrigin(chunkX, RenderRegion.REGION_WIDTH_SH, RenderRegion.REGION_BLOCK_WIDTH);
regionOrigin(chunkX, RenderRegion.REGION_WIDTH_SH, RenderRegion.REGION_BLOCK_WIDTH), int regionY = regionOrigin(chunkY, RenderRegion.REGION_HEIGHT_SH, RenderRegion.REGION_BLOCK_HEIGHT);
regionOrigin(chunkY, RenderRegion.REGION_HEIGHT_SH, RenderRegion.REGION_BLOCK_HEIGHT), int regionZ = regionOrigin(chunkZ, RenderRegion.REGION_LENGTH_SH, RenderRegion.REGION_BLOCK_LENGTH);
regionOrigin(chunkZ, RenderRegion.REGION_LENGTH_SH, RenderRegion.REGION_BLOCK_LENGTH)); int classification = cache.classify(regionId, regionX, regionY, regionZ);
// Fully-inside regions need no per-section tests and outside regions // Fully-inside regions need no per-section tests and outside regions
// are not traversed. Sections in a partial region are checked // are not traversed. Sections in a partial region are checked
@@ -301,7 +302,8 @@ public class OcclusionCuller {
boolean traverse = visible; boolean traverse = visible;
if (this.rasterActive && visible) { if (this.rasterActive && visible) {
RasterOccluder.SectionVisibility result = this.rasterTest(idx, chunkX, chunkY, chunkZ, camX, camY, camZ, compactMeta); RasterOccluder.SectionVisibility result = this.rasterTest(idx, chunkX, chunkY, chunkZ, camX, camY, camZ,
compactMeta, (sm & SectionLattice.OCCLUDER_DATA_FLAG) != 0, regionId, regionX, regionY, regionZ);
visible = result == RasterOccluder.SectionVisibility.VISIBLE; visible = result == RasterOccluder.SectionVisibility.VISIBLE;
traverse = result != RasterOccluder.SectionVisibility.HIDDEN; traverse = result != RasterOccluder.SectionVisibility.HIDDEN;
} }
@@ -356,7 +358,19 @@ public class OcclusionCuller {
this.visibleCount = visibleCount; this.visibleCount = visibleCount;
} }
private RasterOccluder.SectionVisibility rasterTest(int idx, int chunkX, int chunkY, int chunkZ, int camX, int camY, int camZ, int meta) { private RasterOccluder.SectionVisibility rasterTest(int idx, int chunkX, int chunkY, int chunkZ, int camX, int camY, int camZ,
int meta, boolean hasOccluderData,
int regionId, int regionX, int regionY, int regionZ) {
var occluder = this.rasterOccluder;
// A section with nothing to draw is visible wherever nothing has been drawn. One with geometry is
// tested against the bounds of what it draws, which may lie off screen even though the section is
// in the frustum, and that cull is worth keeping; such sections are rare above the horizon anyway.
if (!hasOccluderData && occluder.isSectionUntouched(regionId, regionX, regionY, regionZ, chunkX, chunkY, chunkZ)) {
if (AbstractRasterizer.STATS) RasterOccluder.STAT_REGION_SKIP++;
return RasterOccluder.SectionVisibility.VISIBLE;
}
int dx = chunkX - camX; int dx = chunkX - camX;
int dy = chunkY - camY; int dy = chunkY - camY;
int dz = chunkZ - camZ; int dz = chunkZ - camZ;
@@ -365,15 +379,13 @@ public class OcclusionCuller {
boolean hasGeometry = boolean hasGeometry =
(PackedSectionMetadata.getCompactVisualsFlags(meta) & (1 << RenderVisualsService.HAS_BLOCK_GEOMETRY)) != 0; (PackedSectionMetadata.getCompactVisualsFlags(meta) & (1 << RenderVisualsService.HAS_BLOCK_GEOMETRY)) != 0;
int[] data = this.lattice.occluderData[idx]; // the flag spares the many sections without data the loads below, which rarely hit cache
int bounds = hasOccluderData ? this.lattice.occluderBounds[idx] : PackedBox.FULL_BOX;
int bounds = data != null ? OccluderBoxBuilder.bounds(data) : PackedBox.FULL_BOX;
var occluder = this.rasterOccluder;
RasterOccluder.SectionVisibility result = occluder.testSection(chunkX << 4, chunkY << 4, chunkZ << 4, squaredChunkDist, bounds); RasterOccluder.SectionVisibility result = occluder.testSection(chunkX << 4, chunkY << 4, chunkZ << 4, squaredChunkDist, bounds);
if (result == RasterOccluder.SectionVisibility.VISIBLE && hasGeometry && data != null) { if (result == RasterOccluder.SectionVisibility.VISIBLE && hasGeometry && hasOccluderData) {
occluder.occludeSection(data); occluder.occludeSection(this.lattice.occluderData[idx]);
} }
return result; return result;
@@ -6,17 +6,48 @@ import grondag.bitraster.Constants;
import grondag.bitraster.Matrix4L; import grondag.bitraster.Matrix4L;
import grondag.bitraster.PackedBox; import grondag.bitraster.PackedBox;
import grondag.bitraster.PerspectiveRasterizer; import grondag.bitraster.PerspectiveRasterizer;
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
import org.embeddedt.embeddium.impl.render.viewport.Viewport; import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.joml.Matrix4fc; import org.joml.Matrix4fc;
import java.util.Arrays;
public final class RasterOccluder extends BoxOccluder { public final class RasterOccluder extends BoxOccluder {
/** Sections this close are drawn but never tested, since they're almost always visible and most costly to test */ /** Sections this close are drawn but never tested, since they're almost always visible and most costly to test */
public static final int NEAR_SQUARED_CHUNK_DIST = 3; public static final int NEAR_SQUARED_CHUNK_DIST = 3;
private int backtrackCount; private int backtrackCount;
/**
* Per-region screen bounds for the current scene, so that sections of a region whose screen area has
* had nothing drawn in it yet are visible without a test of their own. Most of the sections a surface
* camera reaches are sky, and nothing ever gets drawn above the horizon, so this resolves most of them.
*
* <p>{@code regionScene} stamps the scene the bounds were computed for. {@code regionVersion} holds the
* touched-map version at which the bounds were last found untouched, or {@link #REGION_TOUCHED} once they
* were not: drawing only ever adds coverage, so that verdict is final for the scene. A region that is not
* wholly on screen keeps the clip-space position of its first section centre in {@code regionClip}, from
* which any section centre's on-screen test is a few multiplies.
*/
private int[] regionScene = new int[0];
private int[] regionTiles = new int[0];
private int[] regionVersion = new int[0];
private byte[] regionState = new byte[0];
private float[] regionClip = new float[0];
private int scene;
/** {@code regionVersion} values that never match a touched-map version. */
private static final int REGION_TOUCHED = -1, REGION_UNVERIFIED = -2;
/** The region reaches the near plane or lies wholly off screen; its sections are all tested. */
private static final byte REGION_NO_BOUNDS = 0;
/** The region straddles a screen edge; each section centre is checked against the screen. */
private static final byte REGION_PARTLY_ON_SCREEN = 1;
/** Every point of the region is on screen. */
private static final byte REGION_ON_SCREEN = 2;
/** Work counters for benchmarks; only maintained when {@link AbstractRasterizer#STATS} is set. */ /** Work counters for benchmarks; only maintained when {@link AbstractRasterizer#STATS} is set. */
public static long STAT_CENTER_HIT, STAT_AIR_TESTS, STAT_AIR_VISIBLE, STAT_NEAR; public static long STAT_CENTER_HIT, STAT_AIR_TESTS, STAT_AIR_VISIBLE, STAT_NEAR, STAT_REGION_SKIP;
public static long STAT_TEST_NANOS, STAT_OCCLUDE_NANOS, STAT_SECTIONS, STAT_OCCLUDED_SECTIONS; public static long STAT_TEST_NANOS, STAT_OCCLUDE_NANOS, STAT_SECTIONS, STAT_OCCLUDED_SECTIONS;
public enum SectionVisibility { public enum SectionVisibility {
@@ -48,7 +79,7 @@ public final class RasterOccluder extends BoxOccluder {
* camera translation, so it is supplied as the projection with an identity model matrix; * camera translation, so it is supplied as the projection with an identity model matrix;
* {@link #prepareRegion} applies the camera-relative offset per section. * {@link #prepareRegion} applies the camera-relative offset per section.
*/ */
public void prepareScene(int viewVersion, Viewport viewport, float searchDistance) { public void prepareScene(int viewVersion, Viewport viewport, float searchDistance, int numRegions) {
Matrix4fc vpMatrix = viewport.getVpMatrix(); Matrix4fc vpMatrix = viewport.getVpMatrix();
if (vpMatrix == null) { if (vpMatrix == null) {
@@ -58,6 +89,16 @@ public final class RasterOccluder extends BoxOccluder {
var transform = viewport.getTransform(); var transform = viewport.getTransform();
this.backtrackCount = 0; this.backtrackCount = 0;
this.scene++;
if (this.regionScene.length < numRegions) {
int capacity = Math.max(numRegions, this.regionScene.length * 2);
this.regionScene = Arrays.copyOf(this.regionScene, capacity);
this.regionTiles = Arrays.copyOf(this.regionTiles, capacity);
this.regionVersion = Arrays.copyOf(this.regionVersion, capacity);
this.regionState = Arrays.copyOf(this.regionState, capacity);
this.regionClip = Arrays.copyOf(this.regionClip, capacity * 3);
}
chooseBufferSize(vpMatrix, searchDistance); chooseBufferSize(vpMatrix, searchDistance);
invalidate(); invalidate();
@@ -74,8 +115,9 @@ public final class RasterOccluder extends BoxOccluder {
* rotation and a translation, neither of which changes that. The axes differ by the aspect ratio, so a * rotation and a translation, neither of which changes that. The axes differ by the aspect ratio, so a
* widescreen view needs a wider buffer than it is tall. * widescreen view needs a wider buffer than it is tall.
* *
* <p>An axis only grows when the current buffer falls short and only shrinks when the next size down * <p>Sizes are not limited to powers of two, so each axis holds close to what it needs rather than up to
* would still have a quarter margin, so field-of-view animation cannot thrash it. * double it. An axis only grows when the current buffer falls short and only shrinks when it is more
* than a step above what is needed, so field-of-view animation cannot thrash it.
*/ */
private void chooseBufferSize(Matrix4fc vp, float searchDistance) { private void chooseBufferSize(Matrix4fc vp, float searchDistance) {
// orthographic or degenerate matrices have no perspective row; keep whatever we have // orthographic or degenerate matrices have no perspective row; keep whatever we have
@@ -92,35 +134,102 @@ public final class RasterOccluder extends BoxOccluder {
return; return;
} }
// pixels per block at distance d along an axis is size * scale / (2d); require at least one // pixels per block at distance d along an axis is size * scale / (2d)
int widthBits = chooseAxisBits(bufferWidth(), (2.0f * searchDistance) / scaleX); float required = 2.0f * searchDistance * PIXELS_PER_BLOCK;
int heightBits = chooseAxisBits(bufferHeight(), (2.0f * searchDistance) / scaleY); int widthTiles = chooseAxisTiles(bufferWidth() >> Constants.TILE_AXIS_SHIFT, required / scaleX);
resizeBuffer(widthBits, heightBits); int heightTiles = chooseAxisTiles(bufferHeight() >> Constants.TILE_AXIS_SHIFT, required / scaleY);
resizeBuffer(widthTiles, heightTiles);
} }
private static int chooseAxisBits(int currentPixels, float requiredPixels) { /**
int current = Integer.numberOfTrailingZeros(currentPixels) - 3; * Grows an axis to the smallest step that meets its requirement, and shrinks it only to one step above
* the requirement, so the two thresholds never meet: a requirement wavering about a step boundary neither
* grows nor shrinks the axis, and a sweeping field of view resizes at most once per step.
*/
private static int chooseAxisTiles(int currentTiles, float requiredPixels) {
int required = tilesFor(requiredPixels);
if (requiredPixels > currentPixels) { if (required > currentTiles) {
int bits = current; return required;
}
while (bits < Constants.MAX_SIZE_BITS && (8 << bits) < requiredPixels) { int shrunk = Math.min(Constants.MAX_SIZE_TILES, required + SIZE_STEP_TILES);
bits++;
return shrunk < currentTiles ? shrunk : currentTiles;
}
/** Tiles needed to hold the given pixels, rounded up to {@link #SIZE_STEP_TILES} and clamped to the buffer limits. */
private static int tilesFor(float pixels) {
int tiles = ((int) Math.ceil(pixels / (8 * SIZE_STEP_TILES))) * SIZE_STEP_TILES;
return Math.max(Constants.MIN_SIZE_TILES, Math.min(Constants.MAX_SIZE_TILES, tiles));
}
/** Axis sizes are multiples of this many tiles (64 pixels). */
private static final int SIZE_STEP_TILES = 8;
/**
* Pixels a block at the search distance must span along each axis. Halving this measured within a few
* percent of the same frame time and culled within a few sections of the same count on the synthetic
* worlds, so the buffer is not sized for speed: this is what keeps a one-block gap between occluders
* from closing under pixel-centre sampling.
*/
private static final float PIXELS_PER_BLOCK = 1.0f;
/**
* True if nothing has been drawn where the region projects and the given section's centre is on screen,
* in which case the section is visible: its centre pixel lies inside the region's screen rectangle, and
* an untouched pixel on screen is exactly what the centre test looks for. Costs one compare per section
* once the region's bounds are known, plus a few multiplies when the region is not wholly on screen, and
* a re-check of a handful of cell rows whenever something new has been drawn since.
*/
public boolean isSectionUntouched(int regionId, int originX, int originY, int originZ, int chunkX, int chunkY, int chunkZ) {
final int[] regionVersion = this.regionVersion;
if (this.regionScene[regionId] != this.scene) {
this.regionScene[regionId] = this.scene;
long bounds = boxTileBounds(originX, originY, originZ,
RenderRegion.REGION_BLOCK_WIDTH, RenderRegion.REGION_BLOCK_HEIGHT, RenderRegion.REGION_BLOCK_LENGTH);
this.regionTiles[regionId] = (int) bounds;
regionVersion[regionId] = REGION_UNVERIFIED;
if (bounds == AbstractRasterizer.NO_TILE_BOUNDS) {
this.regionState[regionId] = REGION_NO_BOUNDS;
} else if ((bounds & AbstractRasterizer.TILE_BOUNDS_ON_SCREEN) != 0) {
this.regionState[regionId] = REGION_ON_SCREEN;
} else {
this.regionState[regionId] = REGION_PARTLY_ON_SCREEN;
clipPoint(originX + 8, originY + 8, originZ + 8, this.regionClip, regionId * 3);
}
}
final byte state = this.regionState[regionId];
if (state == REGION_NO_BOUNDS) {
return false;
}
final int version = regionVersion[regionId];
final int current = touchedVersion();
if (version != current) {
if (version == REGION_TOUCHED) {
return false;
} }
return bits; if (!isTileBoxUntouched(this.regionTiles[regionId])) {
regionVersion[regionId] = REGION_TOUCHED;
return false;
}
regionVersion[regionId] = current;
} }
if (current > Constants.MIN_SIZE_BITS && requiredPixels * SHRINK_MARGIN <= (currentPixels >> 1)) { return state == REGION_ON_SCREEN
return current - 1; || isSectionCenterOnScreen(this.regionClip, regionId * 3,
} chunkX - (originX >> 4), chunkY - (originY >> 4), chunkZ - (originZ >> 4));
return current;
} }
/** The next size down must satisfy the requirement with this much to spare before we shrink to it. */
private static final float SHRINK_MARGIN = 1.25f;
/** /**
* tests the tight bounds of what the section draws first. a section whose geometry is hidden * tests the tight bounds of what the section draws first. a section whose geometry is hidden
* may still have unoccluded empty space, so a second test decides whether traversal continues. * may still have unoccluded empty space, so a second test decides whether traversal continues.
@@ -143,6 +143,19 @@ public final class SectionLattice {
* does not chase section and build-data pointers for every cell it visits. Null when absent. * does not chase section and build-data pointers for every cell it visits. Null when absent.
*/ */
int[][] occluderData; int[][] occluderData;
/**
* The packed bounds word of each cell's occluder data, mirrored densely so the raster test reads one
* array instead of chasing the pointer above into a second cache line; only a draw needs the boxes.
*/
int[] occluderBounds;
/**
* Set in a cell's {@link #sectionMeta} word when it has occluder data, so the raster test can skip the
* pointer load for the many cells, most of them sky, that have none. Bit 53 is outside every field of
* {@link PackedSectionMetadata}, and every reader masks the fields it wants.
*/
static final long OCCLUDER_DATA_FLAG = 1L << 53;
RenderSection[] latticeSection; RenderSection[] latticeSection;
// Queue entries ((packedLocalXYZ << 32) | latticeIndex) of the cells the last main search reported visible, in // Queue entries ((packedLocalXYZ << 32) | latticeIndex) of the cells the last main search reported visible, in
@@ -277,8 +290,10 @@ public final class SectionLattice {
} }
long previous = this.sectionMeta[idx]; long previous = this.sectionMeta[idx];
this.sectionMeta[idx] = packedMetadata; int[] data = occluderDataOf(this.latticeSection[idx]);
this.occluderData[idx] = occluderDataOf(this.latticeSection[idx]); this.sectionMeta[idx] = withOccluderFlag(packedMetadata, data);
this.occluderData[idx] = data;
this.occluderBounds[idx] = boundsOf(data);
return ((previous ^ packedMetadata) & PackedSectionMetadata.GRAPH_INPUT_MASK) != 0; return ((previous ^ packedMetadata) & PackedSectionMetadata.GRAPH_INPUT_MASK) != 0;
} }
@@ -547,6 +562,7 @@ public final class SectionLattice {
this.regionOfCell = new int[slots]; this.regionOfCell = new int[slots];
this.latticeSection = new RenderSection[slots]; this.latticeSection = new RenderSection[slots];
this.occluderData = new int[slots][]; this.occluderData = new int[slots][];
this.occluderBounds = new int[slots];
// Existing coordinates are no longer valid after resizing; the next // Existing coordinates are no longer valid after resizing; the next
// ensureWindowCovers must rebase and reinstall every attached section. // ensureWindowCovers must rebase and reinstall every attached section.
@@ -566,6 +582,7 @@ public final class SectionLattice {
Arrays.fill(this.regionOfCell, -1); Arrays.fill(this.regionOfCell, -1);
Arrays.fill(this.latticeSection, null); Arrays.fill(this.latticeSection, null);
Arrays.fill(this.occluderData, null); Arrays.fill(this.occluderData, null);
Arrays.fill(this.occluderBounds, 0);
this.baseX = newBaseX; this.baseX = newBaseX;
this.baseZ = newBaseZ; this.baseZ = newBaseZ;
@@ -646,6 +663,7 @@ public final class SectionLattice {
System.arraycopy(this.regionOfCell, srcOff, this.regionOfCell, destOff, len); System.arraycopy(this.regionOfCell, srcOff, this.regionOfCell, destOff, len);
System.arraycopy(this.latticeSection, srcOff, this.latticeSection, destOff, len); System.arraycopy(this.latticeSection, srcOff, this.latticeSection, destOff, len);
System.arraycopy(this.occluderData, srcOff, this.occluderData, destOff, len); System.arraycopy(this.occluderData, srcOff, this.occluderData, destOff, len);
System.arraycopy(this.occluderBounds, srcOff, this.occluderBounds, destOff, len);
} }
/** /**
@@ -680,6 +698,7 @@ public final class SectionLattice {
System.arraycopy(this.regionOfCell, srcOff, this.regionOfCell, destOff, runLen); System.arraycopy(this.regionOfCell, srcOff, this.regionOfCell, destOff, runLen);
System.arraycopy(this.latticeSection, srcOff, this.latticeSection, destOff, runLen); System.arraycopy(this.latticeSection, srcOff, this.latticeSection, destOff, runLen);
System.arraycopy(this.occluderData, srcOff, this.occluderData, destOff, runLen); System.arraycopy(this.occluderData, srcOff, this.occluderData, destOff, runLen);
System.arraycopy(this.occluderBounds, srcOff, this.occluderBounds, destOff, runLen);
} }
} }
@@ -766,6 +785,7 @@ public final class SectionLattice {
this.regionOfCell[idx] = -1; this.regionOfCell[idx] = -1;
this.latticeSection[idx] = null; this.latticeSection[idx] = null;
this.occluderData[idx] = null; this.occluderData[idx] = null;
this.occluderBounds[idx] = 0;
RenderSection section = this.sections.get( RenderSection section = this.sections.get(
PositionUtil.packSection(worldX, this.baseY + ly, worldZ)); PositionUtil.packSection(worldX, this.baseY + ly, worldZ));
@@ -818,6 +838,14 @@ public final class SectionLattice {
return built != null ? built.occluderBoxes : null; return built != null ? built.occluderBoxes : null;
} }
private static int boundsOf(int @Nullable [] occluderData) {
return occluderData != null ? OccluderBoxBuilder.bounds(occluderData) : 0;
}
private static long withOccluderFlag(long packedMetadata, int @Nullable [] occluderData) {
return occluderData != null ? packedMetadata | OCCLUDER_DATA_FLAG : packedMetadata;
}
private void install(RenderSection section) { private void install(RenderSection section) {
if (this.visitState == null) { if (this.visitState == null) {
return; return;
@@ -835,8 +863,10 @@ public final class SectionLattice {
} }
this.latticeSection[idx] = section; this.latticeSection[idx] = section;
this.regionOfCell[idx] = section.getRegion().getId(); this.regionOfCell[idx] = section.getRegion().getId();
this.sectionMeta[idx] = section.getPackedMetadata(); int[] data = occluderDataOf(section);
this.occluderData[idx] = occluderDataOf(section); this.sectionMeta[idx] = withOccluderFlag(section.getPackedMetadata(), data);
this.occluderData[idx] = data;
this.occluderBounds[idx] = boundsOf(data);
this.installedCount++; this.installedCount++;
} }
@@ -857,6 +887,7 @@ public final class SectionLattice {
this.regionOfCell[idx] = -1; this.regionOfCell[idx] = -1;
this.latticeSection[idx] = null; this.latticeSection[idx] = null;
this.occluderData[idx] = null; this.occluderData[idx] = null;
this.occluderBounds[idx] = 0;
this.installedCount--; this.installedCount--;
} }
} }