rasterized occlusion culling #38

Merged
embeddedt merged 20 commits from rdh/celeritas:raster into stonecutter 2026-09-04 22:15:05 -04:00
49 changed files with 7538 additions and 98 deletions

No files matched your search

+22
View File
@@ -152,6 +152,18 @@ tasks.register('jmh', JavaExec) {
} }
} }
tasks.register('rasterCullReport', JavaExec) {
group = 'verification'
description = 'Reports visible section counts per world and camera placement.'
classpath = sourceSets.jmh.runtimeClasspath
mainClass = 'org.embeddedt.embeddium.impl.render.chunk.occlusion.bench.RasterCullReport'
maxHeapSize = '1g'
// e.g. ./gradlew :common:rasterCullReport -Dreport.renderDistance=64
systemProperties System.getProperties().findAll { it.key.toString().startsWith('report.') }
}
publishing { publishing {
publications { publications {
mavenJava(MavenPublication) { mavenJava(MavenPublication) {
@@ -229,3 +241,13 @@ def transformedAttr = Attribute.of("rfgDeobfuscatorTransformed", Boolean)
attribute(transformedAttr, true) attribute(transformedAttr, true)
} }
} }
tasks.register('rasterStats', JavaExec) {
group = 'verification'
classpath = sourceSets.jmh.runtimeClasspath
mainClass = 'org.embeddedt.embeddium.impl.render.chunk.occlusion.bench.RasterStatsReport'
maxHeapSize = '1g'
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() }) }
}
@@ -101,4 +101,58 @@ public final class VoxelSlice {
return occluder.computeVisibilityEncoding(); return occluder.computeVisibilityEncoding();
} }
public int[] occlusionData() {
if (this.empty) {
return null;
}
var occluder = new SectionVisibilityBuilder();
byte[] blocks = this.blocks;
for (int y = 0; y < 16; y++) {
for (int z = 0; z < 16; z++) {
int row = ((y + 1) * AREA) + ((z + 1) * SIZE) + 1;
for (int x = 0; x < 16; x++) {
int block = blocks[row + x];
if (VoxelWorld.isOpaque(block)) {
occluder.markOpaque(x, y, z);
}
if (VoxelWorld.isRenderable(block)) {
occluder.markRenderable(x, y, z);
}
}
}
}
return occluder.computeOccluderBoxes();
}
public long[] opacityBits() {
var bits = new long[64];
if (this.empty) {
return bits;
}
byte[] blocks = this.blocks;
for (int y = 0; y < 16; y++) {
for (int z = 0; z < 16; z++) {
int row = ((y + 1) * AREA) + ((z + 1) * SIZE) + 1;
for (int x = 0; x < 16; x++) {
if (VoxelWorld.isOpaque(blocks[row + x])) {
int index = x | (z << 4) | (y << 8);
bits[index >> 6] |= 1L << (index & 63);
}
}
}
}
return bits;
}
} }
@@ -87,9 +87,9 @@ public class MultiDrawBench {
BenchPlatform.ensureInitialized(); BenchPlatform.ensureInitialized();
this.syntheticWorld = new SyntheticWorld(this.world, this.renderDistance, SyntheticWorld.DEFAULT_SEED, this.syntheticWorld = new SyntheticWorld(this.world, this.renderDistance, SyntheticWorld.DEFAULT_SEED,
this.caveWidth, true, 0.0D, false); this.caveWidth, true, 0.0D, false, false);
this.lattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, false); this.lattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, false, false);
for (RenderSection section : this.syntheticWorld.getConstructionOrder()) { for (RenderSection section : this.syntheticWorld.getConstructionOrder()) {
this.lattice.attach(section); this.lattice.attach(section);
@@ -0,0 +1,131 @@
package org.embeddedt.embeddium.impl.render.chunk.occlusion.bench;
import org.embeddedt.embeddium.impl.render.chunk.bench.voxel.VoxelSlice;
import org.embeddedt.embeddium.impl.render.chunk.bench.voxel.VoxelWorld;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry.AreaFinder;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry.BoxFinder;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OperationsPerInvocation;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
/**
* Per-section cost of generating occluder boxes, which a real integration must pay on the chunk
* build thread.
*
* <p>{@link #visibilityFloodFill} is the yardstick, not a baseline to subtract: it is the per-section
* occlusion work meshing already does today and therefore a known-affordable cost. Read the result as
* a ratio against it.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Fork(2)
@Warmup(iterations = 2, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 3, time = 1, timeUnit = TimeUnit.SECONDS)
public class BoxFinderBench {
private static final int SECTION_SAMPLE = 512;
@State(Scope.Benchmark)
public static class Sections {
@Param({ "SURFACE", "CAVES" })
public WorldType world;
public long[][] opacity;
public VoxelSlice[] slices;
@Setup
public void setup() {
var voxelWorld = new VoxelWorld(this.world);
var sampledSlices = new ArrayList<VoxelSlice>(SECTION_SAMPLE);
var sampledOpacity = new ArrayList<long[]>(SECTION_SAMPLE);
// Spiral out from the origin column so the sample spans terrain, caves and sky rather
// than whichever corner a raster scan happens to start in.
outer:
for (int radius = 0; radius < 64; radius++) {
for (int x = -radius; x <= radius; x++) {
for (int z = -radius; z <= radius; z++) {
if (Math.max(Math.abs(x), Math.abs(z)) != radius) {
continue;
}
for (int y = SyntheticWorld.MIN_SECTION_Y; y < SyntheticWorld.MAX_SECTION_Y; y++) {
var slice = voxelWorld.slice(x, y, z);
if (slice.isEmpty()) {
continue;
}
long[] bits = slice.opacityBits();
// Sections with no opaque blocks produce no occluders and would be
// skipped in production.
if (isAllClear(bits)) {
continue;
}
sampledSlices.add(slice);
sampledOpacity.add(bits);
if (sampledOpacity.size() == SECTION_SAMPLE) {
break outer;
}
}
}
}
}
if (sampledOpacity.size() < SECTION_SAMPLE) {
throw new IllegalStateException("only found " + sampledOpacity.size()
+ " non-empty sections for world " + this.world);
}
this.opacity = sampledOpacity.toArray(new long[0][]);
this.slices = sampledSlices.toArray(new VoxelSlice[0]);
}
private static boolean isAllClear(long[] bits) {
for (long word : bits) {
if (word != 0) {
return false;
}
}
return true;
}
}
@State(Scope.Thread)
public static class Finder {
public final BoxFinder boxFinder = new BoxFinder(new AreaFinder());
}
@Benchmark
@OperationsPerInvocation(SECTION_SAMPLE)
public void findBoxes(Sections sections, Finder finder, Blackhole bh) {
for (long[] bits : sections.opacity) {
finder.boxFinder.findBoxes(bits, 0);
bh.consume(finder.boxFinder.boxes.size());
}
}
@Benchmark
@OperationsPerInvocation(SECTION_SAMPLE)
public void visibilityFloodFill(Sections sections, Blackhole bh) {
for (VoxelSlice slice : sections.slices) {
bh.consume(slice.computeVisibility());
}
}
}
@@ -28,12 +28,17 @@ public final class Cameras {
} }
public static Viewport viewport(double x, double y, double z, float yawDegrees, float pitchDegrees, int renderDistance) { public static Viewport viewport(double x, double y, double z, float yawDegrees, float pitchDegrees, int renderDistance) {
return viewport(x, y, z, yawDegrees, pitchDegrees, renderDistance, FOV_DEGREES);
}
public static Viewport viewport(double x, double y, double z, float yawDegrees, float pitchDegrees, int renderDistance,
float fovDegrees) {
Matrix4f matrix = new Matrix4f() Matrix4f matrix = new Matrix4f()
.perspective((float) Math.toRadians(FOV_DEGREES), ASPECT, NEAR_PLANE, farPlane(renderDistance)) .perspective((float) Math.toRadians(fovDegrees), ASPECT, NEAR_PLANE, farPlane(renderDistance))
.rotateX((float) Math.toRadians(pitchDegrees)) .rotateX((float) Math.toRadians(pitchDegrees))
.rotateY((float) Math.toRadians(yawDegrees + 180.0f)); .rotateY((float) Math.toRadians(yawDegrees + 180.0f));
return new Viewport(new SimpleFrustum(new FrustumIntersection(matrix)), new Vector3d(x, y, z)); return new Viewport(new SimpleFrustum(new FrustumIntersection(matrix)), new Vector3d(x, y, z), matrix);
} }
public static Viewport viewport(double x, double y, double z, int renderDistance) { public static Viewport viewport(double x, double y, double z, int renderDistance) {
@@ -45,6 +45,9 @@ public class OcclusionCullerBench {
@Param({ "true" }) @Param({ "true" })
public boolean scatteredAlloc; public boolean scatteredAlloc;
@Param({ "false" })
public boolean rasterOcclusion;
public SyntheticWorld syntheticWorld; public SyntheticWorld syntheticWorld;
public SectionLattice lattice; public SectionLattice lattice;
@@ -62,12 +65,14 @@ public class OcclusionCullerBench {
public void setup() { public void setup() {
BenchPlatform.ensureInitialized(); BenchPlatform.ensureInitialized();
this.syntheticWorld = new SyntheticWorld(this.world, this.renderDistance, this.scatteredAlloc); this.syntheticWorld = new SyntheticWorld(this.world, this.renderDistance, this.scatteredAlloc,
this.rasterOcclusion);
this.searchDistance = this.syntheticWorld.getSearchDistance(); this.searchDistance = this.syntheticWorld.getSearchDistance();
this.numRegions = BenchPlatform.regionManager().getRegionIdsLength(); this.numRegions = BenchPlatform.regionManager().getRegionIdsLength();
this.lattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, false); this.lattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, false,
this.rasterOcclusion);
for (RenderSection section : this.syntheticWorld.getConstructionOrder()) { for (RenderSection section : this.syntheticWorld.getConstructionOrder()) {
this.lattice.attach(section); this.lattice.attach(section);
@@ -0,0 +1,127 @@
package org.embeddedt.embeddium.impl.render.chunk.occlusion.bench;
import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionLattice;
import org.embeddedt.embeddium.impl.render.viewport.Viewport;
public final class RasterCullReport {
private static final int RENDER_DISTANCE = Integer.getInteger("report.renderDistance", 32);
private static final float FOV = Float.parseFloat(System.getProperty("report.fov", "70"));
private static final int YAW_STEPS = 8;
private static final WorldType[] WORLDS = { WorldType.SURFACE, WorldType.CAVES };
private RasterCullReport() {
}
private record Placement(String name, double y, float pitch) {
}
public static void main(String[] args) {
BenchPlatform.ensureInitialized();
if (Boolean.getBoolean("report.fovscan")) {
fovScan();
return;
}
System.out.printf("%-8s %-8s %10s %10s %8s %10s %10s%n",
"world", "camera", "baseline", "occluded", "delta", "backtrack", "buffer");
System.out.println("-".repeat(80));
for (WorldType world : WORLDS) {
var syntheticWorld = new SyntheticWorld(world, RENDER_DISTANCE, true, true);
float searchDistance = syntheticWorld.getSearchDistance();
int numRegions = BenchPlatform.regionManager().getRegionIdsLength();
var baselineLattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y,
false, false);
var rasterLattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y,
false, true);
for (RenderSection section : syntheticWorld.getConstructionOrder()) {
baselineLattice.attach(section);
rasterLattice.attach(section);
}
int frame = 0;
for (Placement placement : placements()) {
long baseline = 0;
long occluded = 0;
long backtracks = 0;
for (int step = 0; step < YAW_STEPS; step++) {
Viewport viewport = Cameras.viewport(8.5, placement.y(), 8.5,
(360.0f / YAW_STEPS) * step, placement.pitch(), RENDER_DISTANCE, FOV);
var without = new CountingVisitor();
baselineLattice.ensureWindowCovers(viewport.getChunkCoord(), searchDistance);
baselineLattice.findVisible(without, viewport, searchDistance, numRegions, true, true, ++frame);
var with = new CountingVisitor();
rasterLattice.ensureWindowCovers(viewport.getChunkCoord(), searchDistance);
rasterLattice.findVisible(with, viewport, searchDistance, numRegions, true, true, ++frame);
baseline += without.visible;
occluded += with.visible;
backtracks += rasterLattice.rasterBacktrackCount();
}
long meanBaseline = baseline / YAW_STEPS;
long meanOccluded = occluded / YAW_STEPS;
double delta = meanBaseline == 0 ? 0.0
: ((meanOccluded - meanBaseline) * 100.0) / meanBaseline;
System.out.printf("%-8s %-8s %10d %10d %7.1f%% %10d %10s%n", world, placement.name(),
meanBaseline, meanOccluded, delta, backtracks / YAW_STEPS, rasterLattice.rasterBufferSize());
}
}
}
/** Sweeps the field of view up and back down and prints the buffer size chosen at each step. */
private static void fovScan() {
var world = new SyntheticWorld(WorldType.SURFACE, RENDER_DISTANCE, true, true);
float searchDistance = world.getSearchDistance();
int numRegions = BenchPlatform.regionManager().getRegionIdsLength();
var lattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, false, true);
for (RenderSection section : world.getConstructionOrder()) {
lattice.attach(section);
}
double y = Cameras.surfaceCameraY(0, 0);
int frame = 0;
var line = new StringBuilder("rd=" + RENDER_DISTANCE + " fov sweep 30..130..30:");
int[] fovs = new int[41];
for (int i = 0; i <= 20; i++) {
fovs[i] = 30 + (i * 5);
fovs[40 - i] = fovs[i];
}
for (int i = 0; i < fovs.length; i++) {
int fov = fovs[i];
Viewport viewport = Cameras.viewport(8.5, y, 8.5, Cameras.DEFAULT_YAW, Cameras.DEFAULT_PITCH, RENDER_DISTANCE, fov);
lattice.ensureWindowCovers(viewport.getChunkCoord(), searchDistance);
lattice.findVisible(new CountingVisitor(), viewport, searchDistance, numRegions, true, true, ++frame);
line.append(' ').append(fov).append(':').append(lattice.rasterBufferSize());
if (i == 20) {
line.append(" |");
}
}
System.out.println(line);
}
private static Placement[] placements() {
double surfaceY = Cameras.surfaceCameraY(0, 0);
return new Placement[] {
new Placement("surface", surfaceY, Cameras.DEFAULT_PITCH),
new Placement("treetop", surfaceY + 16.0, Cameras.DEFAULT_PITCH),
new Placement("high", 200.0, -45.0f),
};
}
}
@@ -0,0 +1,102 @@
package org.embeddedt.embeddium.impl.render.chunk.occlusion.bench;
import grondag.bitraster.AbstractRasterizer;
import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.RasterOccluder;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionLattice;
import org.embeddedt.embeddium.impl.render.viewport.Viewport;
/**
* Per-frame rasterizer work counters and a test/occlude time split for one world, run with
* {@code -Dbitraster.stats=true} (the {@code rasterStats} Gradle task sets it). Args: world, and optionally
* {@code yscan lo hi} to print visible counts (raster/baseline) per yaw step as the camera height varies.
*/
public final class RasterStatsReport {
private static final int RENDER_DISTANCE = Integer.getInteger("report.renderDistance", 32);
private static final int YAW_STEPS = 8;
private static final int WARM = 150;
public static void main(String[] args) {
BenchPlatform.ensureInitialized();
WorldType worldType = args.length > 0 ? WorldType.valueOf(args[0]) : WorldType.SURFACE;
var world = new SyntheticWorld(worldType, RENDER_DISTANCE, true, true);
float searchDistance = world.getSearchDistance();
int numRegions = BenchPlatform.regionManager().getRegionIdsLength();
var lattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, false, true);
for (RenderSection section : world.getConstructionOrder()) lattice.attach(section);
double y = Cameras.surfaceCameraY(0, 0);
if (args.length > 1 && args[1].equals("yscan")) {
var base = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, false, false);
for (RenderSection section : world.getConstructionOrder()) base.attach(section);
int f = 0;
double lo = args.length > 2 ? Double.parseDouble(args[2]) : -1.0, hi = args.length > 3 ? Double.parseDouble(args[3]) : 3.0;
for (double dy = lo; dy <= hi; dy += 0.125) {
StringBuilder sb = new StringBuilder(String.format("y=%7.3f ", y + dy));
for (int step = 0; step < YAW_STEPS; step++) {
Viewport v = Cameras.viewport(8.5, y + dy, 8.5, (360.0f / YAW_STEPS) * step, Cameras.DEFAULT_PITCH, RENDER_DISTANCE);
var a = new CountingVisitor(); var b = new CountingVisitor();
base.ensureWindowCovers(v.getChunkCoord(), searchDistance);
base.findVisible(a, v, searchDistance, numRegions, true, true, ++f);
lattice.ensureWindowCovers(v.getChunkCoord(), searchDistance);
lattice.findVisible(b, v, searchDistance, numRegions, true, true, ++f);
sb.append(String.format("%5d/%5d ", b.visible, a.visible));
}
System.out.println(sb);
}
return;
}
Viewport[] ring = Cameras.yawRing(8.5, y, 8.5, YAW_STEPS, Cameras.DEFAULT_PITCH, RENDER_DISTANCE);
int frame = 0;
for (int w = 0; w < WARM; w++) {
for (Viewport v : ring) {
lattice.ensureWindowCovers(v.getChunkCoord(), searchDistance);
lattice.findVisible(new CountingVisitor(), v, searchDistance, numRegions, true, true, ++frame);
}
}
reset();
long visible = 0;
long t0 = System.nanoTime();
for (Viewport v : ring) {
var c = new CountingVisitor();
lattice.ensureWindowCovers(v.getChunkCoord(), searchDistance);
lattice.findVisible(c, v, searchDistance, numRegions, true, true, ++frame);
visible += c.visible;
}
long total = System.nanoTime() - t0;
int n = YAW_STEPS;
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);
System.out.printf("sections tested=%d occluded=%d regionSkip=%d vertexHit=%d%n", RasterOccluder.STAT_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",
AbstractRasterizer.STAT_DRAW_CALLS / n, AbstractRasterizer.STAT_DRAW_QUADS / n,
(AbstractRasterizer.STAT_D_INNER + AbstractRasterizer.STAT_D_COVER) / n,
AbstractRasterizer.STAT_TEST_CALLS / n, AbstractRasterizer.STAT_TEST_QUADS / n, AbstractRasterizer.STAT_TEST_TILES / n,
AbstractRasterizer.STAT_EVENT_ROWS / n);
printExtra(n);
System.out.printf("draw noop polygons=%d boxes drawn by range near/mid/far/extreme=%d/%d/%d/%d%n", AbstractRasterizer.STAT_D_NOOP / n,
AbstractRasterizer.STAT_D_RANGE0 / n, AbstractRasterizer.STAT_D_RANGE1 / n, AbstractRasterizer.STAT_D_RANGE2 / n, AbstractRasterizer.STAT_D_RANGE3 / 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 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,
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);
}
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;
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 = AbstractRasterizer.STAT_T_BOX_HIDDEN = 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;
AbstractRasterizer.STAT_DRAW_CALLS = AbstractRasterizer.STAT_DRAW_QUADS = 0;
AbstractRasterizer.STAT_TEST_CALLS = AbstractRasterizer.STAT_TEST_QUADS = AbstractRasterizer.STAT_TEST_TILES = AbstractRasterizer.STAT_EVENT_ROWS = 0;
}
}
@@ -89,7 +89,7 @@ public class ShadowOcclusionCullerBench {
this.numRegions = BenchPlatform.regionManager().getRegionIdsLength(); this.numRegions = BenchPlatform.regionManager().getRegionIdsLength();
// hasShadowPass: allocates the second visit-state array the shadow search stamps. // hasShadowPass: allocates the second visit-state array the shadow search stamps.
this.lattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, true); this.lattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, true, false);
for (RenderSection section : syntheticWorld.getConstructionOrder()) { for (RenderSection section : syntheticWorld.getConstructionOrder()) {
this.lattice.attach(section); this.lattice.attach(section);
@@ -43,20 +43,27 @@ public final class SyntheticWorld {
private final int sectionCount; private final int sectionCount;
public SyntheticWorld(WorldType type, int renderDistance) { public SyntheticWorld(WorldType type, int renderDistance) {
this(type, renderDistance, DEFAULT_SEED, VoxelWorld.DEFAULT_CAVE_WIDTH, false, 0.0D, false); this(type, renderDistance, DEFAULT_SEED, VoxelWorld.DEFAULT_CAVE_WIDTH, false, 0.0D, false, false);
} }
public SyntheticWorld(WorldType type, int renderDistance, boolean scatteredAlloc) { public SyntheticWorld(WorldType type, int renderDistance, boolean scatteredAlloc) {
this(type, renderDistance, DEFAULT_SEED, VoxelWorld.DEFAULT_CAVE_WIDTH, scatteredAlloc, 0.0D, false); this(type, renderDistance, DEFAULT_SEED, VoxelWorld.DEFAULT_CAVE_WIDTH, scatteredAlloc, 0.0D, false, false);
}
public SyntheticWorld(WorldType type, int renderDistance, boolean scatteredAlloc, boolean occluderBoxes) {
this(type, renderDistance, DEFAULT_SEED, VoxelWorld.DEFAULT_CAVE_WIDTH, scatteredAlloc, 0.0D, false,
occluderBoxes);
} }
/** /**
* @param scatteredAlloc shuffled allocation order (models a long-lived session) * @param scatteredAlloc shuffled allocation order (models a long-lived session)
* @param unloadedProbability fraction of sections absent from the box * @param unloadedProbability fraction of sections absent from the box
* @param allFlagged full visuals mask on every section (sensitivity knob, not realistic) * @param allFlagged full visuals mask on every section (sensitivity knob, not realistic)
* @param occluderBoxes generate occluder boxes; far dearer per section than the visibility fill,
* and dead weight unless a report is measuring the rasterizer
*/ */
public SyntheticWorld(WorldType type, int renderDistance, long seed, double caveWidth, boolean scatteredAlloc, public SyntheticWorld(WorldType type, int renderDistance, long seed, double caveWidth, boolean scatteredAlloc,
double unloadedProbability, boolean allFlagged) { double unloadedProbability, boolean allFlagged, boolean occluderBoxes) {
this.type = type; this.type = type;
this.renderDistance = renderDistance; this.renderDistance = renderDistance;
this.seed = seed; this.seed = seed;
@@ -102,7 +109,11 @@ public final class SyntheticWorld {
// arithmetic moves off this thread — pass 2 still allocates every section itself, in order, because the // arithmetic moves off this thread — pass 2 still allocates every section itself, in order, because the
// heap layout of those sections is exactly what scatteredAlloc exists to control and letting worker // heap layout of those sections is exactly what scatteredAlloc exists to control and letting worker
// threads allocate them into their own TLABs would quietly change what the benchmark measures. // threads allocate them into their own TLABs would quietly change what the benchmark measures.
long[] visibility = this.computeVisibility(radius, width); int[][] boxes = occluderBoxes
? new int[width * width * (MAX_SECTION_Y - MIN_SECTION_Y)][]
: null;
long[] visibility = this.computeVisibility(radius, width, boxes);
// Pass 2: allocate sections in the requested order. // Pass 2: allocate sections in the requested order.
this.sections = new Long2ReferenceOpenHashMap<>(present, 0.75f); this.sections = new Long2ReferenceOpenHashMap<>(present, 0.75f);
@@ -114,8 +125,14 @@ public final class SyntheticWorld {
var section = new RenderSection(regionFor(regionManager, regions, x, y, z), x, y, z); var section = new RenderSection(regionFor(regionManager, regions, x, y, z), x, y, z);
section.setInfo(new BenchSectionData(visibility[gridIndex(x, y, z, radius, width)], x, y, z, var info = new BenchSectionData(visibility[gridIndex(x, y, z, radius, width)], x, y, z,
allFlagged)); allFlagged);
if (boxes != null) {
info.occluderBoxes = boxes[gridIndex(x, y, z, radius, width)];
}
section.setInfo(info);
applyPendingUpdate(section, x, y, z); applyPendingUpdate(section, x, y, z);
this.sections.put(packed, section); this.sections.put(packed, section);
@@ -211,14 +228,14 @@ public final class SyntheticWorld {
* {@code VoxelWorld}'s heightmap cache. Output does not depend on the striping: visibility is a pure * {@code VoxelWorld}'s heightmap cache. Output does not depend on the striping: visibility is a pure
* function of position. * function of position.
*/ */
private long[] computeVisibility(int radius, int width) { private long[] computeVisibility(int radius, int width, int[][] occluderBoxes) {
final int height = MAX_SECTION_Y - MIN_SECTION_Y; final int height = MAX_SECTION_Y - MIN_SECTION_Y;
var visibility = new long[width * width * height]; var visibility = new long[width * width * height];
int workers = Math.min(Runtime.getRuntime().availableProcessors(), width); int workers = Math.min(Runtime.getRuntime().availableProcessors(), width);
if (workers <= 1) { if (workers <= 1) {
this.computeVisibilityStripe(this.voxelWorld, visibility, radius, width, 0, 1); this.computeVisibilityStripe(this.voxelWorld, visibility, occluderBoxes, radius, width, 0, 1);
return visibility; return visibility;
} }
@@ -231,7 +248,7 @@ public final class SyntheticWorld {
// seed generate identical blocks. They are dropped with the threads, releasing those caches. // seed generate identical blocks. They are dropped with the threads, releasing those caches.
threads[w] = new Thread(() -> this.computeVisibilityStripe( threads[w] = new Thread(() -> this.computeVisibilityStripe(
new VoxelWorld(this.type, this.seed, this.voxelWorld.getCaveWidth()), new VoxelWorld(this.type, this.seed, this.voxelWorld.getCaveWidth()),
visibility, radius, width, worker, workers), "bench-worldgen-" + worker); visibility, occluderBoxes, radius, width, worker, workers), "bench-worldgen-" + worker);
threads[w].start(); threads[w].start();
} }
@@ -249,8 +266,8 @@ public final class SyntheticWorld {
} }
/** Runs the real visibility flood fill over every section in this worker's share of the columns. */ /** Runs the real visibility flood fill over every section in this worker's share of the columns. */
private void computeVisibilityStripe(VoxelWorld world, long[] visibility, int radius, int width, private void computeVisibilityStripe(VoxelWorld world, long[] visibility, int[][] occluderBoxes,
int worker, int workers) { int radius, int width, int worker, int workers) {
for (int xi = worker; xi < width; xi += workers) { for (int xi = worker; xi < width; xi += workers) {
int x = xi - radius; int x = xi - radius;
@@ -262,7 +279,14 @@ public final class SyntheticWorld {
continue; continue;
} }
visibility[gridIndex(x, y, z, radius, width)] = world.slice(x, y, z).computeVisibility(); var slice = world.slice(x, y, z);
int index = gridIndex(x, y, z, radius, width);
if (occluderBoxes != null) {
occluderBoxes[index] = slice.occlusionData();
}
visibility[index] = slice.computeVisibility();
} }
} }
} }
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,243 @@
/*
* Copyright 2019, 2020 grondag
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package grondag.bitraster;
public class Constants {
public static final int UP = 1 << 1;
public static final int DOWN = 1 << 0;
public static final int EAST = 1 << 5;
public static final int WEST = 1 << 4;
public static final int NORTH = 1 << 2;
public static final int SOUTH = 1 << 3;
public static final int TILE_AXIS_SHIFT = 3;
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_INDEX_MASK = TILE_PIXEL_DIAMETER - 1;
static final int TILE_PIXEL_INVERSE_MASK = ~TILE_PIXEL_INDEX_MASK;
static final int PRECISION_BITS = 4;
static final int PRECISE_FRACTION_MASK = (1 << PRECISION_BITS) - 1;
static final int PRECISE_INTEGER_MASK = ~PRECISE_FRACTION_MASK;
static final int PRECISE_PIXEL_SIZE = 1 << PRECISION_BITS;
static final int PRECISE_PIXEL_CENTER = PRECISE_PIXEL_SIZE / 2;
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
// fixed it at 2048px square.
/**
* Occlusion buffer size along one axis in tiles of eight pixels. Any width in range is allowed, not just
* 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 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
// pitch still reaches a sampled pixel centre. One pixel covers centre sampling exactly; occluders are never grown.
static final int TEST_DILATION_PIXELS = 1;
public static final int CAMERA_PRECISION_BITS = 12;
static final int CAMERA_PRECISION_UNITY = 1 << CAMERA_PRECISION_BITS;
static final int CAMERA_PRECISION_CHUNK_MAX = 18 * CAMERA_PRECISION_UNITY;
static final int CAMERA_PRECISION_HALF = CAMERA_PRECISION_UNITY / 2;
static final int BOUNDS_IN = 0;
static final int BOUNDS_OUTSIDE_OR_TOO_SMALL = 1;
static final int B_NEGATIVE = 8;
static final int B_ZERO = 16;
static final int B_POSITIVE = 32;
static final int A_NEGATIVE = 1;
static final int A_ZERO = 2;
static final int A_POSITIVE = 4;
static final int EDGE_TOP = B_NEGATIVE | A_ZERO;
static final int EDGE_BOTTOM = B_POSITIVE | A_ZERO;
static final int EDGE_RIGHT = B_ZERO | A_NEGATIVE;
static final int EDGE_LEFT = B_ZERO | A_POSITIVE;
static final int EDGE_TOP_RIGHT = B_NEGATIVE | A_NEGATIVE;
static final int EDGE_TOP_LEFT = B_NEGATIVE | A_POSITIVE;
static final int EDGE_BOTTOM_RIGHT = B_POSITIVE | A_NEGATIVE;
static final int EDGE_BOTTOM_LEFT = B_POSITIVE | A_POSITIVE;
static final int EDGE_POINT = A_ZERO | B_ZERO;
// subtract 1 to fit in 2 bits
static final int EVENT_0_LEFT = A_POSITIVE - 1;
static final int EVENT_0_FLAT = A_ZERO - 1;
static final int EVENT_0_RIGHT = A_NEGATIVE - 1;
static final int EVENT_POSITION_MASK = 3;
static final int EVENT_1_LEFT = EVENT_0_LEFT << 2;
static final int EVENT_1_FLAT = EVENT_0_FLAT << 2;
static final int EVENT_1_RIGHT = EVENT_0_RIGHT << 2;
static final int EVENT_2_LEFT = EVENT_1_LEFT << 2;
static final int EVENT_2_FLAT = EVENT_1_FLAT << 2;
static final int EVENT_2_RIGHT = EVENT_1_RIGHT << 2;
static final int EVENT_3_LEFT = EVENT_2_LEFT << 2;
static final int EVENT_3_FLAT = EVENT_2_FLAT << 2;
static final int EVENT_3_RIGHT = EVENT_2_RIGHT << 2;
static final int EVENT_012_RRR = EVENT_0_RIGHT | EVENT_1_RIGHT | EVENT_2_RIGHT;
static final int EVENT_012_LRR = EVENT_0_LEFT | EVENT_1_RIGHT | EVENT_2_RIGHT;
static final int EVENT_012_FRR = EVENT_0_FLAT | EVENT_1_RIGHT | EVENT_2_RIGHT;
static final int EVENT_012_RLR = EVENT_0_RIGHT | EVENT_1_LEFT | EVENT_2_RIGHT;
static final int EVENT_012_LLR = EVENT_0_LEFT | EVENT_1_LEFT | EVENT_2_RIGHT;
static final int EVENT_012_FLR = EVENT_0_FLAT | EVENT_1_LEFT | EVENT_2_RIGHT;
static final int EVENT_012_RFR = EVENT_0_RIGHT | EVENT_1_FLAT | EVENT_2_RIGHT;
static final int EVENT_012_LFR = EVENT_0_LEFT | EVENT_1_FLAT | EVENT_2_RIGHT;
static final int EVENT_012_FFR = EVENT_0_FLAT | EVENT_1_FLAT | EVENT_2_RIGHT;
static final int EVENT_012_RRL = EVENT_0_RIGHT | EVENT_1_RIGHT | EVENT_2_LEFT;
static final int EVENT_012_LRL = EVENT_0_LEFT | EVENT_1_RIGHT | EVENT_2_LEFT;
static final int EVENT_012_FRL = EVENT_0_FLAT | EVENT_1_RIGHT | EVENT_2_LEFT;
static final int EVENT_012_RLL = EVENT_0_RIGHT | EVENT_1_LEFT | EVENT_2_LEFT;
static final int EVENT_012_LLL = EVENT_0_LEFT | EVENT_1_LEFT | EVENT_2_LEFT;
static final int EVENT_012_FLL = EVENT_0_FLAT | EVENT_1_LEFT | EVENT_2_LEFT;
static final int EVENT_012_RFL = EVENT_0_RIGHT | EVENT_1_FLAT | EVENT_2_LEFT;
static final int EVENT_012_LFL = EVENT_0_LEFT | EVENT_1_FLAT | EVENT_2_LEFT;
static final int EVENT_012_FFL = EVENT_0_FLAT | EVENT_1_FLAT | EVENT_2_LEFT;
static final int EVENT_012_LRF = EVENT_0_LEFT | EVENT_1_RIGHT | EVENT_2_FLAT;
static final int EVENT_012_RRF = EVENT_0_RIGHT | EVENT_1_RIGHT | EVENT_2_FLAT;
static final int EVENT_012_FRF = EVENT_0_FLAT | EVENT_1_RIGHT | EVENT_2_FLAT;
////
static final int EVENT_012_RLF = EVENT_0_RIGHT | EVENT_1_LEFT | EVENT_2_FLAT;
static final int EVENT_012_LLF = EVENT_0_LEFT | EVENT_1_LEFT | EVENT_2_FLAT;
static final int EVENT_012_FLF = EVENT_0_FLAT | EVENT_1_LEFT | EVENT_2_FLAT;
static final int EVENT_012_RFF = EVENT_0_RIGHT | EVENT_1_FLAT | EVENT_2_FLAT;
static final int EVENT_012_LFF = EVENT_0_LEFT | EVENT_1_FLAT | EVENT_2_FLAT;
static final int EVENT_012_FFF = EVENT_0_FLAT | EVENT_1_FLAT | EVENT_2_FLAT;
static final int EVENT_0123_RRRR = EVENT_0_RIGHT | EVENT_1_RIGHT | EVENT_2_RIGHT | EVENT_3_RIGHT;
static final int EVENT_0123_LRRR = EVENT_0_LEFT | EVENT_1_RIGHT | EVENT_2_RIGHT | EVENT_3_RIGHT;
static final int EVENT_0123_FRRR = EVENT_0_FLAT | EVENT_1_RIGHT | EVENT_2_RIGHT | EVENT_3_RIGHT;
static final int EVENT_0123_RLRR = EVENT_0_RIGHT | EVENT_1_LEFT | EVENT_2_RIGHT | EVENT_3_RIGHT;
static final int EVENT_0123_LLRR = EVENT_0_LEFT | EVENT_1_LEFT | EVENT_2_RIGHT | EVENT_3_RIGHT;
static final int EVENT_0123_FLRR = EVENT_0_FLAT | EVENT_1_LEFT | EVENT_2_RIGHT | EVENT_3_RIGHT;
static final int EVENT_0123_RFRR = EVENT_0_RIGHT | EVENT_1_FLAT | EVENT_2_RIGHT | EVENT_3_RIGHT;
static final int EVENT_0123_LFRR = EVENT_0_LEFT | EVENT_1_FLAT | EVENT_2_RIGHT | EVENT_3_RIGHT;
static final int EVENT_0123_FFRR = EVENT_0_FLAT | EVENT_1_FLAT | EVENT_2_RIGHT | EVENT_3_RIGHT;
static final int EVENT_0123_RRLR = EVENT_0_RIGHT | EVENT_1_RIGHT | EVENT_2_LEFT | EVENT_3_RIGHT;
static final int EVENT_0123_LRLR = EVENT_0_LEFT | EVENT_1_RIGHT | EVENT_2_LEFT | EVENT_3_RIGHT;
static final int EVENT_0123_FRLR = EVENT_0_FLAT | EVENT_1_RIGHT | EVENT_2_LEFT | EVENT_3_RIGHT;
static final int EVENT_0123_RLLR = EVENT_0_RIGHT | EVENT_1_LEFT | EVENT_2_LEFT | EVENT_3_RIGHT;
static final int EVENT_0123_LLLR = EVENT_0_LEFT | EVENT_1_LEFT | EVENT_2_LEFT | EVENT_3_RIGHT;
static final int EVENT_0123_FLLR = EVENT_0_FLAT | EVENT_1_LEFT | EVENT_2_LEFT | EVENT_3_RIGHT;
static final int EVENT_0123_RFLR = EVENT_0_RIGHT | EVENT_1_FLAT | EVENT_2_LEFT | EVENT_3_RIGHT;
static final int EVENT_0123_LFLR = EVENT_0_LEFT | EVENT_1_FLAT | EVENT_2_LEFT | EVENT_3_RIGHT;
static final int EVENT_0123_FFLR = EVENT_0_FLAT | EVENT_1_FLAT | EVENT_2_LEFT | EVENT_3_RIGHT;
static final int EVENT_0123_LRFR = EVENT_0_LEFT | EVENT_1_RIGHT | EVENT_2_FLAT | EVENT_3_RIGHT;
static final int EVENT_0123_RRFR = EVENT_0_RIGHT | EVENT_1_RIGHT | EVENT_2_FLAT | EVENT_3_RIGHT;
static final int EVENT_0123_FRFR = EVENT_0_FLAT | EVENT_1_RIGHT | EVENT_2_FLAT | EVENT_3_RIGHT;
static final int EVENT_0123_RLFR = EVENT_0_RIGHT | EVENT_1_LEFT | EVENT_2_FLAT | EVENT_3_RIGHT;
static final int EVENT_0123_LLFR = EVENT_0_LEFT | EVENT_1_LEFT | EVENT_2_FLAT | EVENT_3_RIGHT;
static final int EVENT_0123_FLFR = EVENT_0_FLAT | EVENT_1_LEFT | EVENT_2_FLAT | EVENT_3_RIGHT;
static final int EVENT_0123_RFFR = EVENT_0_RIGHT | EVENT_1_FLAT | EVENT_2_FLAT | EVENT_3_RIGHT;
static final int EVENT_0123_LFFR = EVENT_0_LEFT | EVENT_1_FLAT | EVENT_2_FLAT | EVENT_3_RIGHT;
static final int EVENT_0123_FFFR = EVENT_0_FLAT | EVENT_1_FLAT | EVENT_2_FLAT | EVENT_3_RIGHT;
static final int EVENT_0123_RRRL = EVENT_0_RIGHT | EVENT_1_RIGHT | EVENT_2_RIGHT | EVENT_3_LEFT;
static final int EVENT_0123_LRRL = EVENT_0_LEFT | EVENT_1_RIGHT | EVENT_2_RIGHT | EVENT_3_LEFT;
static final int EVENT_0123_FRRL = EVENT_0_FLAT | EVENT_1_RIGHT | EVENT_2_RIGHT | EVENT_3_LEFT;
static final int EVENT_0123_RLRL = EVENT_0_RIGHT | EVENT_1_LEFT | EVENT_2_RIGHT | EVENT_3_LEFT;
static final int EVENT_0123_LLRL = EVENT_0_LEFT | EVENT_1_LEFT | EVENT_2_RIGHT | EVENT_3_LEFT;
static final int EVENT_0123_FLRL = EVENT_0_FLAT | EVENT_1_LEFT | EVENT_2_RIGHT | EVENT_3_LEFT;
static final int EVENT_0123_RFRL = EVENT_0_RIGHT | EVENT_1_FLAT | EVENT_2_RIGHT | EVENT_3_LEFT;
static final int EVENT_0123_LFRL = EVENT_0_LEFT | EVENT_1_FLAT | EVENT_2_RIGHT | EVENT_3_LEFT;
static final int EVENT_0123_FFRL = EVENT_0_FLAT | EVENT_1_FLAT | EVENT_2_RIGHT | EVENT_3_LEFT;
static final int EVENT_0123_RRLL = EVENT_0_RIGHT | EVENT_1_RIGHT | EVENT_2_LEFT | EVENT_3_LEFT;
static final int EVENT_0123_LRLL = EVENT_0_LEFT | EVENT_1_RIGHT | EVENT_2_LEFT | EVENT_3_LEFT;
static final int EVENT_0123_FRLL = EVENT_0_FLAT | EVENT_1_RIGHT | EVENT_2_LEFT | EVENT_3_LEFT;
static final int EVENT_0123_RLLL = EVENT_0_RIGHT | EVENT_1_LEFT | EVENT_2_LEFT | EVENT_3_LEFT;
static final int EVENT_0123_LLLL = EVENT_0_LEFT | EVENT_1_LEFT | EVENT_2_LEFT | EVENT_3_LEFT;
static final int EVENT_0123_FLLL = EVENT_0_FLAT | EVENT_1_LEFT | EVENT_2_LEFT | EVENT_3_LEFT;
static final int EVENT_0123_RFLL = EVENT_0_RIGHT | EVENT_1_FLAT | EVENT_2_LEFT | EVENT_3_LEFT;
static final int EVENT_0123_LFLL = EVENT_0_LEFT | EVENT_1_FLAT | EVENT_2_LEFT | EVENT_3_LEFT;
static final int EVENT_0123_FFLL = EVENT_0_FLAT | EVENT_1_FLAT | EVENT_2_LEFT | EVENT_3_LEFT;
static final int EVENT_0123_LRFL = EVENT_0_LEFT | EVENT_1_RIGHT | EVENT_2_FLAT | EVENT_3_LEFT;
static final int EVENT_0123_RRFL = EVENT_0_RIGHT | EVENT_1_RIGHT | EVENT_2_FLAT | EVENT_3_LEFT;
static final int EVENT_0123_FRFL = EVENT_0_FLAT | EVENT_1_RIGHT | EVENT_2_FLAT | EVENT_3_LEFT;
static final int EVENT_0123_RLFL = EVENT_0_RIGHT | EVENT_1_LEFT | EVENT_2_FLAT | EVENT_3_LEFT;
static final int EVENT_0123_LLFL = EVENT_0_LEFT | EVENT_1_LEFT | EVENT_2_FLAT | EVENT_3_LEFT;
static final int EVENT_0123_FLFL = EVENT_0_FLAT | EVENT_1_LEFT | EVENT_2_FLAT | EVENT_3_LEFT;
static final int EVENT_0123_RFFL = EVENT_0_RIGHT | EVENT_1_FLAT | EVENT_2_FLAT | EVENT_3_LEFT;
static final int EVENT_0123_LFFL = EVENT_0_LEFT | EVENT_1_FLAT | EVENT_2_FLAT | EVENT_3_LEFT;
static final int EVENT_0123_FFFL = EVENT_0_FLAT | EVENT_1_FLAT | EVENT_2_FLAT | EVENT_3_LEFT;
static final int EVENT_0123_RRRF = EVENT_0_RIGHT | EVENT_1_RIGHT | EVENT_2_RIGHT | EVENT_3_FLAT;
static final int EVENT_0123_LRRF = EVENT_0_LEFT | EVENT_1_RIGHT | EVENT_2_RIGHT | EVENT_3_FLAT;
static final int EVENT_0123_FRRF = EVENT_0_FLAT | EVENT_1_RIGHT | EVENT_2_RIGHT | EVENT_3_FLAT;
static final int EVENT_0123_RLRF = EVENT_0_RIGHT | EVENT_1_LEFT | EVENT_2_RIGHT | EVENT_3_FLAT;
static final int EVENT_0123_LLRF = EVENT_0_LEFT | EVENT_1_LEFT | EVENT_2_RIGHT | EVENT_3_FLAT;
static final int EVENT_0123_FLRF = EVENT_0_FLAT | EVENT_1_LEFT | EVENT_2_RIGHT | EVENT_3_FLAT;
static final int EVENT_0123_RFRF = EVENT_0_RIGHT | EVENT_1_FLAT | EVENT_2_RIGHT | EVENT_3_FLAT;
static final int EVENT_0123_LFRF = EVENT_0_LEFT | EVENT_1_FLAT | EVENT_2_RIGHT | EVENT_3_FLAT;
static final int EVENT_0123_FFRF = EVENT_0_FLAT | EVENT_1_FLAT | EVENT_2_RIGHT | EVENT_3_FLAT;
static final int EVENT_0123_RRLF = EVENT_0_RIGHT | EVENT_1_RIGHT | EVENT_2_LEFT | EVENT_3_FLAT;
static final int EVENT_0123_LRLF = EVENT_0_LEFT | EVENT_1_RIGHT | EVENT_2_LEFT | EVENT_3_FLAT;
static final int EVENT_0123_FRLF = EVENT_0_FLAT | EVENT_1_RIGHT | EVENT_2_LEFT | EVENT_3_FLAT;
static final int EVENT_0123_RLLF = EVENT_0_RIGHT | EVENT_1_LEFT | EVENT_2_LEFT | EVENT_3_FLAT;
static final int EVENT_0123_LLLF = EVENT_0_LEFT | EVENT_1_LEFT | EVENT_2_LEFT | EVENT_3_FLAT;
static final int EVENT_0123_FLLF = EVENT_0_FLAT | EVENT_1_LEFT | EVENT_2_LEFT | EVENT_3_FLAT;
static final int EVENT_0123_RFLF = EVENT_0_RIGHT | EVENT_1_FLAT | EVENT_2_LEFT | EVENT_3_FLAT;
static final int EVENT_0123_LFLF = EVENT_0_LEFT | EVENT_1_FLAT | EVENT_2_LEFT | EVENT_3_FLAT;
static final int EVENT_0123_FFLF = EVENT_0_FLAT | EVENT_1_FLAT | EVENT_2_LEFT | EVENT_3_FLAT;
static final int EVENT_0123_LRFF = EVENT_0_LEFT | EVENT_1_RIGHT | EVENT_2_FLAT | EVENT_3_FLAT;
static final int EVENT_0123_RRFF = EVENT_0_RIGHT | EVENT_1_RIGHT | EVENT_2_FLAT | EVENT_3_FLAT;
static final int EVENT_0123_FRFF = EVENT_0_FLAT | EVENT_1_RIGHT | EVENT_2_FLAT | EVENT_3_FLAT;
static final int EVENT_0123_RLFF = EVENT_0_RIGHT | EVENT_1_LEFT | EVENT_2_FLAT | EVENT_3_FLAT;
static final int EVENT_0123_LLFF = EVENT_0_LEFT | EVENT_1_LEFT | EVENT_2_FLAT | EVENT_3_FLAT;
static final int EVENT_0123_FLFF = EVENT_0_FLAT | EVENT_1_LEFT | EVENT_2_FLAT | EVENT_3_FLAT;
static final int EVENT_0123_RFFF = EVENT_0_RIGHT | EVENT_1_FLAT | EVENT_2_FLAT | EVENT_3_FLAT;
static final int EVENT_0123_LFFF = EVENT_0_LEFT | EVENT_1_FLAT | EVENT_2_FLAT | EVENT_3_FLAT;
static final int EVENT_0123_FFFF = EVENT_0_FLAT | EVENT_1_FLAT | EVENT_2_FLAT | EVENT_3_FLAT;
static final int PV_PX = 0;
static final int PV_PY = 1;
static final int PV_X = 2;
static final int PV_Y = 3;
static final int PV_Z = 4;
static final int PV_W = 5;
static final int PROJECTED_VERTEX_STRIDE = 6;
static final int V000 = 0;
static final int V001 = V000 + PROJECTED_VERTEX_STRIDE;
static final int V010 = V001 + PROJECTED_VERTEX_STRIDE;
static final int V011 = V010 + PROJECTED_VERTEX_STRIDE;
static final int V100 = V011 + PROJECTED_VERTEX_STRIDE;
static final int V101 = V100 + PROJECTED_VERTEX_STRIDE;
static final int V110 = V101 + PROJECTED_VERTEX_STRIDE;
static final int V111 = V110 + PROJECTED_VERTEX_STRIDE;
static final int IDX_AX0 = V111 + PROJECTED_VERTEX_STRIDE;
static final int IDX_AY0 = IDX_AX0 + 1;
static final int IDX_AX1 = IDX_AY0 + 1;
static final int IDX_AY1 = IDX_AX1 + 1;
static final int IDX_BX0 = IDX_AY1 + 1;
static final int IDX_BY0 = IDX_BX0 + 1;
static final int IDX_BX1 = IDX_BY0 + 1;
static final int IDX_BY1 = IDX_BX1 + 1;
static final int IDX_CX0 = IDX_BY1 + 1;
static final int IDX_CY0 = IDX_CX0 + 1;
static final int IDX_CX1 = IDX_CY0 + 1;
static final int IDX_CY1 = IDX_CX1 + 1;
static final int IDX_DX0 = IDX_CY1 + 1;
static final int IDX_DY0 = IDX_DX0 + 1;
static final int IDX_DX1 = IDX_DY0 + 1;
static final int IDX_DY1 = IDX_DX1 + 1;
static final int IDX_EX0 = IDX_DY1 + 1;
static final int IDX_EY0 = IDX_EX0 + 1;
static final int IDX_EX1 = IDX_EY0 + 1;
static final int IDX_EY1 = IDX_EX1 + 1;
static final int IDX_FX0 = IDX_EY1 + 1;
static final int IDX_FY0 = IDX_FX0 + 1;
static final int IDX_FX1 = IDX_FY0 + 1;
static final int IDX_FY1 = IDX_FX1 + 1;
static final int VERTEX_DATA_LENGTH = IDX_FY1 + 1;
}
@@ -0,0 +1,57 @@
/*
* Copyright 2019, 2020 grondag
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package grondag.bitraster;
import static grondag.bitraster.Constants.TILE_AXIS_SHIFT;
import static grondag.bitraster.Constants.TILE_PIXEL_INDEX_MASK;
abstract class Indexer {
private Indexer() {
}
// only handle 0-7 values
static int mortonNumber(int x, int y) {
int z = (x & 0b001) | ((y & 0b001) << 1);
z |= ((x & 0b010) << 1) | ((y & 0b010) << 2);
return z | ((x & 0b100) << 2) | ((y & 0b100) << 3);
}
static int pixelIndex(int x, int y) {
return ((y & TILE_PIXEL_INDEX_MASK) << TILE_AXIS_SHIFT) | (x & TILE_PIXEL_INDEX_MASK);
}
static boolean isPixelClear(long word, int x, int y) {
return (word & (1L << pixelIndex(x, y))) == 0;
}
static long pixelMask(int x, int y) {
return 1L << pixelIndex(x, y);
}
/**
* REQUIRES 0-7 inputs!
*/
static boolean testPixelInWordPreMasked(long word, int x, int y) {
return (word & (1L << ((y << TILE_AXIS_SHIFT) | x))) == 0;
}
static long setPixelInWordPreMasked(long word, int x, int y) {
return word | (1L << ((y << TILE_AXIS_SHIFT) | x));
}
}
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,383 @@
/*
* Copyright 2019, 2020 grondag
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package grondag.bitraster;
public class Matrix4L {
public static final int MATRIX_PRECISION_BITS = 16;
public static final long MATRIX_PRECISION_UNITY = 1 << MATRIX_PRECISION_BITS;
public static final long MATRIX_PRECISION_HALF = MATRIX_PRECISION_UNITY / 2;
public static final float FLOAT_CONVERSION = 1f / MATRIX_PRECISION_UNITY;
private long a00;
private long a01;
private long a02;
private long a03;
private long a10;
private long a11;
private long a12;
private long a13;
private long a20;
private long a21;
private long a22;
private long a23;
private long a30;
private long a31;
private long a32;
private long a33;
@Override
public String toString() {
return String.format("[%d, %d, %d, %d], [%d, %d, %d, %d], [%d, %d, %d, %d], [%d, %d, %d, %d]",
a00, a01, a02, a03, a10, a11, a12, a13, a20, a21, a22, a23, a30, a31, a32, a33);
}
public void set(
float a00, float a01, float a02, float a03,
float a10, float a11, float a12, float a13,
float a20, float a21, float a22, float a23,
float a30, float a31, float a32, float a33
) {
this.a00 = Math.round(a00 * MATRIX_PRECISION_UNITY);
this.a01 = Math.round(a01 * MATRIX_PRECISION_UNITY);
this.a02 = Math.round(a02 * MATRIX_PRECISION_UNITY);
this.a03 = Math.round(a03 * MATRIX_PRECISION_UNITY);
this.a10 = Math.round(a10 * MATRIX_PRECISION_UNITY);
this.a11 = Math.round(a11 * MATRIX_PRECISION_UNITY);
this.a12 = Math.round(a12 * MATRIX_PRECISION_UNITY);
this.a13 = Math.round(a13 * MATRIX_PRECISION_UNITY);
this.a20 = Math.round(a20 * MATRIX_PRECISION_UNITY);
this.a21 = Math.round(a21 * MATRIX_PRECISION_UNITY);
this.a22 = Math.round(a22 * MATRIX_PRECISION_UNITY);
this.a23 = Math.round(a23 * MATRIX_PRECISION_UNITY);
this.a30 = Math.round(a30 * MATRIX_PRECISION_UNITY);
this.a31 = Math.round(a31 * MATRIX_PRECISION_UNITY);
this.a32 = Math.round(a32 * MATRIX_PRECISION_UNITY);
this.a33 = Math.round(a33 * MATRIX_PRECISION_UNITY);
}
public void copyFrom(Matrix4L other) {
a00 = other.a00;
a01 = other.a01;
a02 = other.a02;
a03 = other.a03;
a10 = other.a10;
a11 = other.a11;
a12 = other.a12;
a13 = other.a13;
a20 = other.a20;
a21 = other.a21;
a22 = other.a22;
a23 = other.a23;
a30 = other.a30;
a31 = other.a31;
a32 = other.a32;
a33 = other.a33;
}
public boolean matches(Matrix4L other) {
return a00 == other.a00
&& a01 == other.a01
&& a02 == other.a02
&& a03 == other.a03
&& a10 == other.a10
&& a11 == other.a11
&& a12 == other.a12
&& a13 == other.a13
&& a20 == other.a20
&& a21 == other.a21
&& a22 == other.a22
&& a23 == other.a23
&& a30 == other.a30
&& a31 == other.a31
&& a32 == other.a32
&& a33 == other.a33;
}
public void loadIdentity() {
a00 = MATRIX_PRECISION_UNITY;
a01 = 0;
a02 = 0;
a03 = 0;
a10 = 0;
a11 = MATRIX_PRECISION_UNITY;
a12 = 0;
a13 = 0;
a20 = 0;
a21 = 0;
a22 = MATRIX_PRECISION_UNITY;
a23 = 0;
a30 = 0;
a31 = 0;
a32 = 0;
a33 = MATRIX_PRECISION_UNITY;
}
public void multiply(Matrix4L other) {
final long f = a00 * other.a00 + a01 * other.a10 + a02 * other.a20 + a03 * other.a30;
final long g = a00 * other.a01 + a01 * other.a11 + a02 * other.a21 + a03 * other.a31;
final long h = a00 * other.a02 + a01 * other.a12 + a02 * other.a22 + a03 * other.a32;
final long i = a00 * other.a03 + a01 * other.a13 + a02 * other.a23 + a03 * other.a33;
final long j = a10 * other.a00 + a11 * other.a10 + a12 * other.a20 + a13 * other.a30;
final long k = a10 * other.a01 + a11 * other.a11 + a12 * other.a21 + a13 * other.a31;
final long l = a10 * other.a02 + a11 * other.a12 + a12 * other.a22 + a13 * other.a32;
final long m = a10 * other.a03 + a11 * other.a13 + a12 * other.a23 + a13 * other.a33;
final long n = a20 * other.a00 + a21 * other.a10 + a22 * other.a20 + a23 * other.a30;
final long o = a20 * other.a01 + a21 * other.a11 + a22 * other.a21 + a23 * other.a31;
final long p = a20 * other.a02 + a21 * other.a12 + a22 * other.a22 + a23 * other.a32;
final long q = a20 * other.a03 + a21 * other.a13 + a22 * other.a23 + a23 * other.a33;
final long r = a30 * other.a00 + a31 * other.a10 + a32 * other.a20 + a33 * other.a30;
final long s = a30 * other.a01 + a31 * other.a11 + a32 * other.a21 + a33 * other.a31;
final long t = a30 * other.a02 + a31 * other.a12 + a32 * other.a22 + a33 * other.a32;
final long u = a30 * other.a03 + a31 * other.a13 + a32 * other.a23 + a33 * other.a33;
a00 = ((f + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS);
a01 = ((g + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS);
a02 = ((h + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS);
a03 = ((i + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS);
a10 = ((j + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS);
a11 = ((k + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS);
a12 = ((l + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS);
a13 = ((m + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS);
a20 = ((n + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS);
a21 = ((o + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS);
a22 = ((p + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS);
a23 = ((q + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS);
a30 = ((r + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS);
a31 = ((s + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS);
a32 = ((t + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS);
a33 = ((u + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS);
}
public void translate(long x, long y, long z, int precision) {
final int shift = MATRIX_PRECISION_BITS - precision;
assert shift >= 0;
final long t_a03 = x << shift;
final long t_a13 = y << shift;
final long t_a23 = z << shift;
final long i = a00 * t_a03 + a01 * t_a13 + a02 * t_a23 + a03;
final long m = a10 * t_a03 + a11 * t_a13 + a12 * t_a23 + a13;
final long q = a20 * t_a03 + a21 * t_a13 + a22 * t_a23 + a23;
final long u = a30 * t_a03 + a31 * t_a13 + a32 * t_a23 + a33;
a03 += ((i + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS);
a13 += ((m + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS);
a23 += ((q + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS);
a33 += ((u + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS);
}
public float a00f() {
return FLOAT_CONVERSION * a00;
}
public float a01f() {
return FLOAT_CONVERSION * a01;
}
public float a02f() {
return FLOAT_CONVERSION * a02;
}
public float a03f() {
return FLOAT_CONVERSION * a03;
}
public float a10f() {
return FLOAT_CONVERSION * a10;
}
public float a11f() {
return FLOAT_CONVERSION * a11;
}
public float a12f() {
return FLOAT_CONVERSION * a12;
}
public float a13f() {
return FLOAT_CONVERSION * a13;
}
public float a20f() {
return FLOAT_CONVERSION * a20;
}
public float a21f() {
return FLOAT_CONVERSION * a21;
}
public float a22f() {
return FLOAT_CONVERSION * a22;
}
public float a23f() {
return FLOAT_CONVERSION * a23;
}
public float a30f() {
return FLOAT_CONVERSION * a30;
}
public float a31f() {
return FLOAT_CONVERSION * a31;
}
public float a32f() {
return FLOAT_CONVERSION * a32;
}
public float a33f() {
return FLOAT_CONVERSION * a33;
}
public long a00() {
return a00;
}
public long a01() {
return a01;
}
public long a02() {
return a02;
}
public long a03() {
return a03;
}
public long a10() {
return a10;
}
public long a11() {
return a11;
}
public long a12() {
return a12;
}
public long a13() {
return a13;
}
public long a20() {
return a20;
}
public long a21() {
return a21;
}
public long a22() {
return a22;
}
public long a23() {
return a23;
}
public long a30() {
return a30;
}
public long a31() {
return a31;
}
public long a32() {
return a32;
}
public long a33() {
return a33;
}
/**
* Computes X component of transformed vector. Assumes input W is 1.
* Result has standard precision.
*/
public long transformVec4X(int x, int y, int z) {
return a00 * x + a01 * y + a02 * z + a03;
}
/**
* Computes Y component of transformed vector. Assumes input W is 1.
* Result has standard precision.
*/
public long transformVec4Y(int x, int y, int z) {
return a10 * x + a11 * y + a12 * z + a13;
}
/**
* Computes Z component of transformed vector. Assumes input W is 1.
* Result has standard precision.
*/
public long transformVec4Z(int x, int y, int z) {
return a20 * x + a21 * y + a22 * z + a23;
}
/**
* Computes W component of transformed vector. Assumes input W is 1.
* Result has standard precision.
*/
public long transformVec4W(int x, int y, int z) {
return a30 * x + a31 * y + a32 * z + a33;
}
/**
* Computes X component of transformed vector.
* Result has standard precision.
*/
public long transformVec4X(int x, int y, int z, int w) {
return a00 * x + a01 * y + a02 * z + a03 * w;
}
/**
* Computes Y component of transformed vector.
* Result has standard precision.
*/
public long transformVec4Y(int x, int y, int z, int w) {
return a10 * x + a11 * y + a12 * z + a13 * w;
}
/**
* Computes Z component of transformed vector.
* Result has standard precision.
*/
public long transformVec4Z(int x, int y, int z, int w) {
return a20 * x + a21 * y + a22 * z + a23 * w;
}
/**
* Computes W component of transformed vector.
* Result has standard precision.
*/
public long transformVec4W(int x, int y, int z, int w) {
return a30 * x + a31 * y + a32 * z + a33 * w;
}
}
@@ -0,0 +1,120 @@
/*
* Copyright 2019, 2020 grondag
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package grondag.bitraster;
/**
* For crude but simple microbenchmarks - for small scope, in-game situations
* where JMH would be more than I want.
*/
public class MicroTimer {
private final int sampleSize;
private final String label;
private int hits;
private long elapsed;
private long min;
private long max;
private long started;
private int subsetHits;
private long subsetElapsed;
private long subsetMin;
private long subsetMax;
public MicroTimer(String label, int sampleSize) {
this.label = label;
this.sampleSize = sampleSize;
}
public int hits() {
return hits;
}
public long elapsed() {
return elapsed;
}
public void start() {
started = System.nanoTime();
}
/**
* Returns true if timer output stats this sample. For use if want to output
* supplementary information at same time.
*/
public boolean stop(boolean subset) {
final long t = System.nanoTime() - started;
elapsed += t;
if (t < min) {
min = t;
}
if (t > max) {
max = t;
}
if (subset) {
++subsetHits;
subsetElapsed += t;
if (t < subsetMin) {
subsetMin = t;
}
if (t > subsetMax) {
subsetMax = t;
}
}
final long h = ++hits;
if (h == sampleSize) {
reportAndClear();
return true;
} else {
return false;
}
}
public void reportAndClear() {
if (hits == 0) {
hits = 1;
}
System.out.println(String.format("Avg %s duration = %,d ns, min = %d, max = %d, total duration = %,d, total runs = %,d", label,
elapsed / hits, min, max, elapsed / 1000000, hits));
if (subsetHits > 0) {
if (subsetElapsed == 0) {
subsetElapsed = 1;
}
System.out.println(String.format("Subset avg duration = %,d ns, min = %d, max = %d, total duration = %,d, (%d) total runs = %,d",
subsetElapsed / subsetHits, subsetMin, subsetMax, subsetElapsed / 1000000, subsetElapsed * 100L / elapsed, subsetHits));
subsetHits = 0;
subsetElapsed = 0;
subsetMax = Long.MIN_VALUE;
subsetMin = Long.MAX_VALUE;
}
hits = 0;
elapsed = 0;
max = Long.MIN_VALUE;
min = Long.MAX_VALUE;
}
}
@@ -0,0 +1,92 @@
/*
* Copyright 2019, 2020 grondag
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package grondag.bitraster;
import static grondag.bitraster.Constants.PROJECTED_VERTEX_STRIDE;
import static grondag.bitraster.Constants.DEFAULT_SIZE_TILES;
import static grondag.bitraster.Constants.PV_PX;
import static grondag.bitraster.Constants.PV_PY;
import static grondag.bitraster.Constants.PV_X;
import static grondag.bitraster.Constants.PV_Y;
public final class OrthoRasterizer extends AbstractRasterizer {
public OrthoRasterizer() {
this(DEFAULT_SIZE_TILES, DEFAULT_SIZE_TILES);
}
public OrthoRasterizer(int tileWidth, int tileHeight) {
super(tileWidth, tileHeight);
}
@Override
int prepareBounds(int v0, int v1, int v2, int v3) {
return prepareBoundsNoClip(v0, v1, v2, v3);
}
@Override
boolean setupBoxVertices(int[] corners, int x0, int y0, int z0, int x1, int y1, int z1) {
transformBoxCorners(x0, y0, z0, x1, y1, z1);
final int[] data = vertexData;
final float[] cx = cornerX, cy = cornerY;
for (int baseIndex : corners) {
final int corner = baseIndex / PROJECTED_VERTEX_STRIDE;
final float tx = cx[corner];
final float ty = cy[corner];
data[baseIndex + PV_X] = Float.floatToRawIntBits(tx);
data[baseIndex + PV_Y] = Float.floatToRawIntBits(ty);
data[baseIndex + PV_PX] = Math.round(tx * halfPreciseWidth) + halfPreciseWidth;
data[baseIndex + PV_PY] = Math.round(ty * halfPreciseHeight) + halfPreciseHeight;
}
return true;
}
@Override
boolean isPointClear(float x, float y, float z) {
final float fx = x + offsetX;
final float fy = y + offsetY;
final float fz = z + offsetZ;
final float tx = m00 * fx + m01 * fy + m02 * fz + m03;
final float ty = m10 * fx + m11 * fy + m12 * fz + m13;
return isProjectedPointClear(tx, ty, 1f);
}
@Override void setupVertex(final int baseIndex, final int x, final int y, final int z) {
final int[] data = vertexData;
final float fx = x + offsetX;
final float fy = y + offsetY;
final float fz = z + offsetZ;
final float tx = m00 * fx + m01 * fy + m02 * fz + m03;
final float ty = m10 * fx + m11 * fy + m12 * fz + m13;
data[baseIndex + PV_X] = Float.floatToRawIntBits(tx);
data[baseIndex + PV_Y] = Float.floatToRawIntBits(ty);
final int px = Math.round(tx * halfPreciseWidth) + halfPreciseWidth;
final int py = Math.round(ty * halfPreciseHeight) + halfPreciseHeight;
data[baseIndex + PV_PX] = px;
data[baseIndex + PV_PY] = py;
}
}
@@ -0,0 +1,89 @@
/*
* Copyright 2019, 2020 grondag
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package grondag.bitraster;
public abstract class PackedBox {
public static final int RANGE_NEAR = 0;
public static final int RANGE_MID = 1;
public static final int RANGE_FAR = 2;
public static final int RANGE_EXTREME = 3;
public static final int CHUNK_DIST_NEAR = 1;
public static final int CHUNK_DIST_MID = 2;
public static final int CHUNK_DIST_FAR = 8;
public static final int SQUARE_CHUNK_DIST_NEAR = CHUNK_DIST_NEAR * CHUNK_DIST_NEAR * 3;
public static final int SQUARE_CHUNK_DIST_MID = CHUNK_DIST_MID * CHUNK_DIST_MID * 3;
public static final int SQUARE_CHUNK_DIST_FAR = CHUNK_DIST_FAR * CHUNK_DIST_FAR * 3;
public static final int EMPTY_BOX = 0;
private static final int SHIFT_X0 = 0;
private static final int SHIFT_Y0 = SHIFT_X0 + 5;
private static final int SHIFT_Z0 = SHIFT_Y0 + 5;
private static final int SHIFT_X1 = SHIFT_Z0 + 5;
private static final int SHIFT_Y1 = SHIFT_X1 + 5;
private static final int SHIFT_Z1 = SHIFT_Y1 + 5;
private static final int SHIFT_RANGE = SHIFT_Z1 + 5;
public static final int FULL_BOX = pack(0, 0, 0, 16, 16, 16, RANGE_EXTREME);
private PackedBox() {
}
public static int rangeFromSquareChunkDist(int squareChunkDist) {
if (squareChunkDist <= SQUARE_CHUNK_DIST_MID) {
return squareChunkDist > SQUARE_CHUNK_DIST_NEAR ? RANGE_MID : RANGE_NEAR;
} else {
return squareChunkDist > SQUARE_CHUNK_DIST_FAR ? RANGE_EXTREME : RANGE_FAR;
}
}
public static int pack(int x0, int y0, int z0, int x1, int y1, int z1, int range) {
return x0 | (y0 << SHIFT_Y0) | (z0 << SHIFT_Z0)
| ((x1) << SHIFT_X1) | ((y1) << SHIFT_Y1) | ((z1) << SHIFT_Z1)
| (range << SHIFT_RANGE);
}
public static int range(int packed) {
return (packed >>> SHIFT_RANGE) & 3;
}
public static int x0(int packed) {
return (packed & 31);
}
public static int y0(int packed) {
return (packed >>> SHIFT_Y0) & 31;
}
public static int z0(int packed) {
return (packed >>> SHIFT_Z0) & 31;
}
public static int x1(int packed) {
return ((packed >>> SHIFT_X1) & 31);
}
public static int y1(int packed) {
return ((packed >>> SHIFT_Y1) & 31);
}
public static int z1(int packed) {
return ((packed >>> SHIFT_Z1) & 31);
}
public static String toString(int packed) {
return "(" + x0(packed) + ", " + y0(packed) + ", " + z0(packed) + "), ("
+ x1(packed) + ", " + y1(packed) + ", " + z1(packed) + ")";
}
}
@@ -0,0 +1,811 @@
/*
* Copyright 2019, 2020 grondag
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package grondag.bitraster;
import static grondag.bitraster.Constants.DEFAULT_SIZE_TILES;
import static grondag.bitraster.Constants.BOUNDS_IN;
import static grondag.bitraster.Constants.BOUNDS_OUTSIDE_OR_TOO_SMALL;
import static grondag.bitraster.Constants.EVENT_POSITION_MASK;
import static grondag.bitraster.Constants.IDX_AX0;
import static grondag.bitraster.Constants.IDX_AX1;
import static grondag.bitraster.Constants.IDX_AY0;
import static grondag.bitraster.Constants.IDX_AY1;
import static grondag.bitraster.Constants.IDX_BX0;
import static grondag.bitraster.Constants.IDX_BX1;
import static grondag.bitraster.Constants.IDX_BY0;
import static grondag.bitraster.Constants.IDX_BY1;
import static grondag.bitraster.Constants.IDX_CX0;
import static grondag.bitraster.Constants.IDX_CX1;
import static grondag.bitraster.Constants.IDX_CY0;
import static grondag.bitraster.Constants.IDX_CY1;
import static grondag.bitraster.Constants.IDX_DX0;
import static grondag.bitraster.Constants.IDX_DX1;
import static grondag.bitraster.Constants.IDX_DY0;
import static grondag.bitraster.Constants.IDX_DY1;
import static grondag.bitraster.Constants.PRECISION_BITS;
import static grondag.bitraster.Constants.PROJECTED_VERTEX_STRIDE;
import static grondag.bitraster.Constants.PV_PX;
import static grondag.bitraster.Constants.PV_PY;
import static grondag.bitraster.Constants.PV_W;
import static grondag.bitraster.Constants.PV_X;
import static grondag.bitraster.Constants.PV_Y;
import static grondag.bitraster.Constants.PV_Z;
import static grondag.bitraster.Constants.SCANT_PRECISE_PIXEL_CENTER;
public final class PerspectiveRasterizer extends AbstractRasterizer {
public PerspectiveRasterizer() {
this(DEFAULT_SIZE_TILES, DEFAULT_SIZE_TILES);
}
public PerspectiveRasterizer(int tileWidth, int tileHeight) {
super(tileWidth, tileHeight);
}
/** Holds results of {@link #clipNear(int, int)}. */
private int clipX, clipY;
@Override void setupVertex(final int baseIndex, final int x, final int y, final int z) {
final int[] data = vertexData;
final float fx = x + offsetX;
final float fy = y + offsetY;
final float fz = z + offsetZ;
final float tx = m00 * fx + m01 * fy + m02 * fz + m03;
final float ty = m10 * fx + m11 * fy + m12 * fz + m13;
final float tz = m20 * fx + m21 * fy + m22 * fz + m23;
final float w = m30 * fx + m31 * fy + m32 * fz + m33;
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);
if (w != 0) {
final float iw = 1f / w;
final int px = roundToInt(tx * iw * halfPreciseWidth) + halfPreciseWidth;
final int py = roundToInt(ty * iw * halfPreciseHeight) + halfPreciseHeight;
data[baseIndex + PV_PX] = px;
data[baseIndex + PV_PY] = py;
}
}
@Override
boolean setupBoxVertices(int[] corners, int x0, int y0, int z0, int x1, int y1, int z1) {
transformBoxCorners(x0, y0, z0, x1, y1, z1);
final int[] data = vertexData;
final float[] cx = cornerX, cy = cornerY, cw = cornerW, cz = cornerZ;
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) {
final int corner = baseIndex / PROJECTED_VERTEX_STRIDE;
final float w = cw[corner];
final float tz = cz[corner];
// same acceptance as needsNearClip
if (!(w > 0 && tz > 0 && tz <= w)) {
return 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 true;
}
@Override
boolean isPointClear(float x, float y, float z) {
final float fx = x + offsetX;
final float fy = y + offsetY;
final float fz = z + offsetZ;
final float w = m30 * fx + m31 * fy + m32 * fz + m33;
// behind the eye; callers only ask about points well past the near plane
if (w <= 0) {
return false;
}
final float tx = m00 * fx + m01 * fy + m02 * fz + m03;
final float ty = m10 * fx + m11 * fy + m12 * fz + m13;
return isProjectedPointClear(tx, ty, 1f / w);
}
private void clipNear(int internal, int external) {
final int[] data = vertexData;
final float intX = Float.intBitsToFloat(data[internal + PV_X]);
final float intY = Float.intBitsToFloat(data[internal + PV_Y]);
final float intZ = Float.intBitsToFloat(data[internal + PV_Z]);
final float intW = Float.intBitsToFloat(data[internal + PV_W]);
final float extX = Float.intBitsToFloat(data[external + PV_X]);
final float extY = Float.intBitsToFloat(data[external + PV_Y]);
final float extZ = Float.intBitsToFloat(data[external + PV_Z]);
final float extW = Float.intBitsToFloat(data[external + PV_W]);
// intersection point is the projection plane, at which point Z == 1
// and w will be 0 but projection division isn't needed, so force output to W = 1
// see https://www.cs.usfca.edu/~cruse/math202s11/homocoords.pdf
final float wt = intZ / -(extZ - intZ);
// note again that projection division isn't needed
final float x = (intX + (extX - intX) * wt);
final float y = (intY + (extY - intY) * wt);
final float w = (intW + (extW - intW) * wt);
final float iw = 1f / w;
clipX = roundToInt(iw * x * halfPreciseWidth) + halfPreciseWidth;
clipY = roundToInt(iw * y * halfPreciseHeight) + halfPreciseHeight;
}
@Override
int prepareBounds(int v0, int v1, int v2, int v3) {
// puts bits in lexical order
final int split = needsNearClip(v3) | (needsNearClip(v2) << 1) | (needsNearClip(v1) << 2) | (needsNearClip(v0) << 3);
switch (split) {
case 0b0000:
return prepareBounds0000(v0, v1, v2, v3);
case 0b0001:
return prepareBounds0001(v0, v1, v2, v3);
case 0b0010:
return prepareBounds0001(v3, v0, v1, v2);
case 0b0100:
return prepareBounds0001(v2, v3, v0, v1);
case 0b1000:
return prepareBounds0001(v1, v2, v3, v0);
case 0b0011:
return prepareBounds0011(v0, v1, v2, v3);
case 0b1001:
return prepareBounds0011(v1, v2, v3, v0);
case 0b1100:
return prepareBounds0011(v2, v3, v0, v1);
case 0b0110:
return prepareBounds0011(v3, v0, v1, v2);
case 0b0111:
return prepareBounds0111(v0, v1, v2, v3);
case 0b1011:
return prepareBounds0111(v1, v2, v3, v0);
case 0b1101:
return prepareBounds0111(v2, v3, v0, v1);
case 0b1110:
return prepareBounds0111(v3, v0, v1, v2);
case 0b1111:
return BOUNDS_OUTSIDE_OR_TOO_SMALL;
default:
assert false : "Occlusion edge case";
// NOOP
}
return BOUNDS_OUTSIDE_OR_TOO_SMALL;
}
private int prepareBounds0000(int v0, int v1, int v2, int v3) {
final int[] data = vertexData;
int ax0, ay0, ax1, ay1;
int bx0, by0, bx1, by1;
int cx0, cy0, cx1, cy1;
int dx0, dy0, dx1, dy1;
int minY = 0, maxY = 0, minX = 0, maxX = 0;
ax0 = data[v0 + PV_PX];
ay0 = data[v0 + PV_PY];
bx0 = data[v1 + PV_PX];
by0 = data[v1 + PV_PY];
cx0 = data[v2 + PV_PX];
cy0 = data[v2 + PV_PY];
dx0 = data[v3 + PV_PX];
dy0 = data[v3 + PV_PY];
ax1 = bx0;
ay1 = by0;
bx1 = cx0;
by1 = cy0;
cx1 = dx0;
cy1 = dy0;
dx1 = ax0;
dy1 = ay0;
minX = ax0;
maxX = ax0;
if (bx0 < minX) {
minX = bx0;
} else if (bx0 > maxX) {
maxX = bx0;
}
if (cx0 < minX) {
minX = cx0;
} else if (cx0 > maxX) {
maxX = cx0;
}
if (dx0 < minX) {
minX = dx0;
} else if (dx0 > maxX) {
maxX = dx0;
}
minY = ay0;
maxY = ay0;
if (by0 < minY) {
minY = by0;
} else if (by0 > maxY) {
maxY = by0;
}
if (cy0 < minY) {
minY = cy0;
} else if (cy0 > maxY) {
maxY = cy0;
}
if (dy0 < minY) {
minY = dy0;
} else if (dy0 > maxY) {
maxY = dy0;
}
if (maxY <= 0 || minY >= preciseHeight) {
return BOUNDS_OUTSIDE_OR_TOO_SMALL;
}
if (maxX <= 0 || minX >= preciseWidth) {
return BOUNDS_OUTSIDE_OR_TOO_SMALL;
}
if (minX < 0) {
minX = 0;
}
if (maxX >= preciseWidthClamp) {
maxX = preciseWidthClamp;
if (minX > preciseWidthClamp) {
minX = preciseWidthClamp;
}
}
if (minY < 0) {
minY = 0;
}
if (maxY >= preciseHeightClamp) {
maxY = preciseHeightClamp;
if (minY > preciseHeightClamp) {
minY = preciseHeightClamp;
}
}
final int minPixelX = ((minX + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS);
final int minPixelY = ((minY + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS);
final int maxPixelX = ((maxX + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS);
final int maxPixelY = ((maxY + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS);
final int position0 = edgePosition(ax0, ay0, ax1, ay1);
final int position1 = edgePosition(bx0, by0, bx1, by1);
final int position2 = edgePosition(cx0, cy0, cx1, cy1);
final int position3 = edgePosition(dx0, dy0, dx1, dy1);
this.minPixelX = minPixelX;
this.minPixelY = minPixelY;
this.maxPixelX = maxPixelX;
this.maxPixelY = maxPixelY;
data[IDX_AX0] = ax0;
data[IDX_AY0] = ay0;
data[IDX_AX1] = ax1;
data[IDX_AY1] = ay1;
data[IDX_BX0] = bx0;
data[IDX_BY0] = by0;
data[IDX_BX1] = bx1;
data[IDX_BY1] = by1;
data[IDX_CX0] = cx0;
data[IDX_CY0] = cy0;
data[IDX_CX1] = cx1;
data[IDX_CY1] = cy1;
data[IDX_DX0] = dx0;
data[IDX_DY0] = dy0;
data[IDX_DX1] = dx1;
data[IDX_DY1] = dy1;
pos0 = position0;
pos1 = position1;
pos2 = position2;
pos3 = position3;
final int eventKey = (position0 - 1) & EVENT_POSITION_MASK
| (((position1 - 1) & EVENT_POSITION_MASK) << 2)
| (((position2 - 1) & EVENT_POSITION_MASK) << 4)
| (((position3 - 1) & EVENT_POSITION_MASK) << 6);
prepareEvents(eventKey);
return BOUNDS_IN;
}
private int prepareBounds0001(int v0, int v1, int v2, int ext3) {
final int[] data = vertexData;
int ax0, ay0, ax1, ay1;
int bx0, by0, bx1, by1;
int cx0, cy0, cx1, cy1;
int dx0, dy0, dx1, dy1;
int minY = 0, maxY = 0, minX = 0, maxX = 0;
ax0 = data[v0 + PV_PX];
ay0 = data[v0 + PV_PY];
ax1 = data[v1 + PV_PX];
ay1 = data[v1 + PV_PY];
bx0 = ax1;
by0 = ay1;
bx1 = data[v2 + PV_PX];
by1 = data[v2 + PV_PY];
cx0 = bx1;
cy0 = by1;
clipNear(v2, ext3);
cx1 = clipX;
cy1 = clipY;
clipNear(v0, ext3);
dx0 = clipX;
dy0 = clipY;
dx1 = ax0;
dy1 = ay0;
minX = ax0;
maxX = ax0;
// ax1 = bx0 and dx1 = ax0, so no need to test those
if (bx0 < minX) {
minX = bx0;
} else if (bx0 > maxX) {
maxX = bx0;
}
if (cx0 < minX) {
minX = cx0;
} else if (cx0 > maxX) {
maxX = cx0;
}
if (cx1 < minX) {
minX = cx1;
} else if (cx1 > maxX) {
maxX = cx1;
}
if (dx0 < minX) {
minX = dx0;
} else if (dx0 > maxX) {
maxX = dx0;
}
minY = ay0;
maxY = ay0;
if (by0 < minY) {
minY = by0;
} else if (by0 > maxY) {
maxY = by0;
}
if (cy0 < minY) {
minY = cy0;
} else if (cy0 > maxY) {
maxY = cy0;
}
if (cy1 < minY) {
minY = cy1;
} else if (cy1 > maxY) {
maxY = cy1;
}
if (dy0 < minY) {
minY = dy0;
} else if (dy0 > maxY) {
maxY = dy0;
}
if (maxY <= 0 || minY >= preciseHeight) {
return BOUNDS_OUTSIDE_OR_TOO_SMALL;
}
if (maxX <= 0 || minX >= preciseWidth) {
return BOUNDS_OUTSIDE_OR_TOO_SMALL;
}
if (minX < 0) {
minX = 0;
}
if (maxX >= preciseWidthClamp) {
maxX = preciseWidthClamp;
if (minX > preciseWidthClamp) {
minX = preciseWidthClamp;
}
}
if (minY < 0) {
minY = 0;
}
if (maxY >= preciseHeightClamp) {
maxY = preciseHeightClamp;
if (minY > preciseHeightClamp) {
minY = preciseHeightClamp;
}
}
final int minPixelX = ((minX + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS);
final int minPixelY = ((minY + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS);
final int maxPixelX = ((maxX + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS);
final int maxPixelY = ((maxY + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS);
final int position0 = edgePosition(ax0, ay0, ax1, ay1);
final int position1 = edgePosition(bx0, by0, bx1, by1);
final int position2 = edgePosition(cx0, cy0, cx1, cy1);
final int position3 = edgePosition(dx0, dy0, dx1, dy1);
this.minPixelX = minPixelX;
this.minPixelY = minPixelY;
this.maxPixelX = maxPixelX;
this.maxPixelY = maxPixelY;
data[IDX_AX0] = ax0;
data[IDX_AY0] = ay0;
data[IDX_AX1] = ax1;
data[IDX_AY1] = ay1;
data[IDX_BX0] = bx0;
data[IDX_BY0] = by0;
data[IDX_BX1] = bx1;
data[IDX_BY1] = by1;
data[IDX_CX0] = cx0;
data[IDX_CY0] = cy0;
data[IDX_CX1] = cx1;
data[IDX_CY1] = cy1;
data[IDX_DX0] = dx0;
data[IDX_DY0] = dy0;
data[IDX_DX1] = dx1;
data[IDX_DY1] = dy1;
pos0 = position0;
pos1 = position1;
pos2 = position2;
pos3 = position3;
final int eventKey = (position0 - 1) & EVENT_POSITION_MASK
| (((position1 - 1) & EVENT_POSITION_MASK) << 2)
| (((position2 - 1) & EVENT_POSITION_MASK) << 4)
| (((position3 - 1) & EVENT_POSITION_MASK) << 6);
prepareEvents(eventKey);
return BOUNDS_IN;
}
private int prepareBounds0011(int v0, int v1, int ext2, int ext3) {
final int[] data = vertexData;
int ax0, ay0, ax1, ay1;
int bx0, by0, bx1, by1;
int cx0, cy0, cx1, cy1;
int dx0, dy0, dx1, dy1;
int minY = 0, maxY = 0, minX = 0, maxX = 0;
ax0 = data[v0 + PV_PX];
ay0 = data[v0 + PV_PY];
ax1 = data[v1 + PV_PX];
ay1 = data[v1 + PV_PY];
bx0 = ax1;
by0 = ay1;
clipNear(v1, ext2);
bx1 = clipX;
by1 = clipY;
// force line c to be a single, existing point - entire line is clipped and should not influence anything
cx0 = ax0;
cy0 = ay0;
cx1 = ax0;
cy1 = ay0;
clipNear(v0, ext3);
dx0 = clipX;
dy0 = clipY;
dx1 = ax0;
dy1 = ay0;
minX = ax0;
maxX = ax0;
if (bx0 < minX) {
minX = bx0;
} else if (bx0 > maxX) {
maxX = bx0;
}
if (bx1 < minX) {
minX = bx1;
} else if (bx1 > maxX) {
maxX = bx1;
}
if (dx0 < minX) {
minX = dx0;
} else if (dx0 > maxX) {
maxX = dx0;
}
minY = ay0;
maxY = ay0;
if (by0 < minY) {
minY = by0;
} else if (by0 > maxY) {
maxY = by0;
}
if (by1 < minY) {
minY = by1;
} else if (by1 > maxY) {
maxY = by1;
}
if (dy0 < minY) {
minY = dy0;
} else if (dy0 > maxY) {
maxY = dy0;
}
if (maxY <= 0 || minY >= preciseHeight) {
return BOUNDS_OUTSIDE_OR_TOO_SMALL;
}
if (maxX <= 0 || minX >= preciseWidth) {
return BOUNDS_OUTSIDE_OR_TOO_SMALL;
}
if (minX < 0) {
minX = 0;
}
if (maxX >= preciseWidthClamp) {
maxX = preciseWidthClamp;
if (minX > preciseWidthClamp) {
minX = preciseWidthClamp;
}
}
if (minY < 0) {
minY = 0;
}
if (maxY >= preciseHeightClamp) {
maxY = preciseHeightClamp;
if (minY > preciseHeightClamp) {
minY = preciseHeightClamp;
}
}
final int minPixelX = ((minX + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS);
final int minPixelY = ((minY + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS);
final int maxPixelX = ((maxX + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS);
final int maxPixelY = ((maxY + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS);
final int position0 = edgePosition(ax0, ay0, ax1, ay1);
final int position1 = edgePosition(bx0, by0, bx1, by1);
final int position2 = edgePosition(cx0, cy0, cx1, cy1);
final int position3 = edgePosition(dx0, dy0, dx1, dy1);
this.minPixelX = minPixelX;
this.minPixelY = minPixelY;
this.maxPixelX = maxPixelX;
this.maxPixelY = maxPixelY;
data[IDX_AX0] = ax0;
data[IDX_AY0] = ay0;
data[IDX_AX1] = ax1;
data[IDX_AY1] = ay1;
data[IDX_BX0] = bx0;
data[IDX_BY0] = by0;
data[IDX_BX1] = bx1;
data[IDX_BY1] = by1;
data[IDX_CX0] = cx0;
data[IDX_CY0] = cy0;
data[IDX_CX1] = cx1;
data[IDX_CY1] = cy1;
data[IDX_DX0] = dx0;
data[IDX_DY0] = dy0;
data[IDX_DX1] = dx1;
data[IDX_DY1] = dy1;
pos0 = position0;
pos1 = position1;
pos2 = position2;
pos3 = position3;
final int eventKey = (position0 - 1) & EVENT_POSITION_MASK
| (((position1 - 1) & EVENT_POSITION_MASK) << 2)
| (((position2 - 1) & EVENT_POSITION_MASK) << 4)
| (((position3 - 1) & EVENT_POSITION_MASK) << 6);
prepareEvents(eventKey);
return BOUNDS_IN;
}
private int prepareBounds0111(int v0, int ext1, int ext2, int ext3) {
final int[] data = vertexData;
int ax0, ay0, ax1, ay1;
int bx0, by0, bx1, by1;
int cx0, cy0, cx1, cy1;
int dx0, dy0, dx1, dy1;
int minY = 0, maxY = 0, minX = 0, maxX = 0;
ax0 = data[v0 + PV_PX];
ay0 = data[v0 + PV_PY];
clipNear(v0, ext1);
ax1 = clipX;
ay1 = clipY;
// force lines b & c to be a single, existing point - entire line is clipped and should not influence anything
bx0 = ax0;
by0 = ay0;
bx1 = ax0;
by1 = ay0;
cx0 = ax0;
cy0 = ay0;
cx1 = ax0;
cy1 = ay0;
clipNear(v0, ext3);
dx0 = clipX;
dy0 = clipY;
dx1 = ax0;
dy1 = ay0;
minX = ax0;
maxX = ax0;
if (ax1 < minX) {
minX = ax1;
} else if (ax1 > maxX) {
maxX = ax1;
}
if (dx0 < minX) {
minX = dx0;
} else if (dx0 > maxX) {
maxX = dx0;
}
minY = ay0;
maxY = ay0;
if (ay1 < minY) {
minY = ay1;
} else if (ay1 > maxY) {
maxY = ay1;
}
if (dy0 < minY) {
minY = dy0;
} else if (dy0 > maxY) {
maxY = dy0;
}
if (maxY <= 0 || minY >= preciseHeight) {
return BOUNDS_OUTSIDE_OR_TOO_SMALL;
}
if (maxX <= 0 || minX >= preciseWidth) {
return BOUNDS_OUTSIDE_OR_TOO_SMALL;
}
if (minX < 0) {
minX = 0;
}
if (maxX >= preciseWidthClamp) {
maxX = preciseWidthClamp;
if (minX > preciseWidthClamp) {
minX = preciseWidthClamp;
}
}
if (minY < 0) {
minY = 0;
}
if (maxY >= preciseHeightClamp) {
maxY = preciseHeightClamp;
if (minY > preciseHeightClamp) {
minY = preciseHeightClamp;
}
}
final int minPixelX = ((minX + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS);
final int minPixelY = ((minY + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS);
final int maxPixelX = ((maxX + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS);
final int maxPixelY = ((maxY + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS);
final int position0 = edgePosition(ax0, ay0, ax1, ay1);
final int position1 = edgePosition(bx0, by0, bx1, by1);
final int position2 = edgePosition(cx0, cy0, cx1, cy1);
final int position3 = edgePosition(dx0, dy0, dx1, dy1);
this.minPixelX = minPixelX;
this.minPixelY = minPixelY;
this.maxPixelX = maxPixelX;
this.maxPixelY = maxPixelY;
data[IDX_AX0] = ax0;
data[IDX_AY0] = ay0;
data[IDX_AX1] = ax1;
data[IDX_AY1] = ay1;
data[IDX_BX0] = bx0;
data[IDX_BY0] = by0;
data[IDX_BX1] = bx1;
data[IDX_BY1] = by1;
data[IDX_CX0] = cx0;
data[IDX_CY0] = cy0;
data[IDX_CX1] = cx1;
data[IDX_CY1] = cy1;
data[IDX_DX0] = dx0;
data[IDX_DY0] = dy0;
data[IDX_DX1] = dx1;
data[IDX_DY1] = dy1;
pos0 = position0;
pos1 = position1;
pos2 = position2;
pos3 = position3;
final int eventKey = (position0 - 1) & EVENT_POSITION_MASK
| (((position1 - 1) & EVENT_POSITION_MASK) << 2)
| (((position2 - 1) & EVENT_POSITION_MASK) << 4)
| (((position3 - 1) & EVENT_POSITION_MASK) << 6);
prepareEvents(eventKey);
return BOUNDS_IN;
}
}
@@ -0,0 +1,38 @@
/*
* Copyright 2019, 2020 grondag
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package grondag.bitraster;
public class Util {
static void printMask(long mask) {
String s = "0000000000000000000000000000000000000000000000000000000000000000" + Long.toBinaryString(mask);
s = s.substring(s.length() - 64);
printSpaced(s.substring(0, 8));
printSpaced(s.substring(8, 16));
printSpaced(s.substring(16, 24));
printSpaced(s.substring(24, 32));
printSpaced(s.substring(32, 40));
printSpaced(s.substring(40, 48));
printSpaced(s.substring(48, 56));
printSpaced(s.substring(56, 64));
System.out.println();
}
public static void printSpaced(String s) {
System.out.println(s.replace("0", "- ").replace("1", "X "));
}
}
@@ -76,6 +76,8 @@ public class SodiumGameOptions implements OptionStorage<SodiumGameOptions> {
public boolean useNoErrorGLContext = true; public boolean useNoErrorGLContext = true;
public AsyncOcclusionMode asyncOcclusionMode = AsyncOcclusionMode.ONLY_SHADOW; public AsyncOcclusionMode asyncOcclusionMode = AsyncOcclusionMode.ONLY_SHADOW;
public boolean useRasterOcclusionCulling = false;
} }
public static class AdvancedSettings { public static class AdvancedSettings {
@@ -157,6 +157,16 @@ public class CommonOptionPages {
.setBinding((opts, value) -> opts.performance.useFasterClouds = value, opts -> opts.performance.useFasterClouds) .setBinding((opts, value) -> opts.performance.useFasterClouds = value, opts -> opts.performance.useFasterClouds)
.build()) .build())
//?} //?}
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setId(StandardOptions.Option.RASTER_OCCLUSION_CULLING.cast())
.setName(TextComponent.translatable("celeritas.options.raster_occlusion_culling.name"))
.setTooltip(TextComponent.translatable("celeritas.options.raster_occlusion_culling.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.VARIES)
.setBinding((opts, value) -> opts.performance.useRasterOcclusionCulling = value, opts -> opts.performance.useRasterOcclusionCulling)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
)
.build()); .build());
return new OptionPage(StandardOptions.Pages.PERFORMANCE, TextComponent.translatable("sodium.options.pages.performance"), List.copyOf(groups)); return new OptionPage(StandardOptions.Pages.PERFORMANCE, TextComponent.translatable("sodium.options.pages.performance"), List.copyOf(groups));
@@ -15,10 +15,10 @@ import org.jetbrains.annotations.Nullable;
* *
* <p>Bit layout: * <p>Bit layout:
* <pre> * <pre>
* 63 53 52 51 49 48 46 45 0 * 63 54 53 52 51 49 48 46 45 0
* +--------------------+--+-----------+----------+-------------------+ * +--------------------+--+--+-----------+----------+-------------------+
* | spare |IF| pending | visuals | visibility graph | * | spare |OD|IF| pending | visuals | visibility graph |
* +--------------------+--+-----------+----------+-------------------+ * +--------------------+--+--+-----------+----------+-------------------+
* </pre> * </pre>
* <ul> * <ul>
* <li>Bits {@code 0..45}: {@link VisibilityEncoding} entries. Entry * <li>Bits {@code 0..45}: {@link VisibilityEncoding} entries. Entry
@@ -30,7 +30,8 @@ import org.jetbrains.annotations.Nullable;
* <li>Bits {@code 49..51}: pending update type; zero means none, otherwise * <li>Bits {@code 49..51}: pending update type; zero means none, otherwise
* {@code ChunkUpdateType.ordinal() + 1}.</li> * {@code ChunkUpdateType.ordinal() + 1}.</li>
* <li>Bit {@code 52}: a build is in flight.</li> * <li>Bit {@code 52}: a build is in flight.</li>
* <li>Bits {@code 53..63}: reserved.</li> * <li>Bit {@code 53}: the section's built data has occluder boxes.</li>
* <li>Bits {@code 54..63}: reserved.</li>
* </ul> * </ul>
* *
* <p>The visibility graph uses only bits {@code 0..45}, but * <p>The visibility graph uses only bits {@code 0..45}, but
@@ -57,12 +58,6 @@ public final class PackedSectionMetadata {
private static final int VISUALS_FLAGS_SHIFT = 46; private static final int VISUALS_FLAGS_SHIFT = 46;
private static final long VISUALS_FLAGS_MASK = 0b111L; private static final long VISUALS_FLAGS_MASK = 0b111L;
/**
* Fields whose changes can alter the result of a visibility search or its
* render-list output: visibility graph data and visual-presence flags.
*/
public static final long GRAPH_INPUT_MASK = VISIBILITY_MASK | (VISUALS_FLAGS_MASK << VISUALS_FLAGS_SHIFT);
// Bits 49..51: 0 means no pending update; otherwise ordinal + 1. // Bits 49..51: 0 means no pending update; otherwise ordinal + 1.
private static final int PENDING_UPDATE_SHIFT = 49; private static final int PENDING_UPDATE_SHIFT = 49;
private static final long PENDING_UPDATE_MASK = 0b111L; private static final long PENDING_UPDATE_MASK = 0b111L;
@@ -71,6 +66,16 @@ public final class PackedSectionMetadata {
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;
// Bit 53: the section's built data has occluder boxes.
private static final int HAS_OCCLUDER_DATA_BIT = 53;
private static final long HAS_OCCLUDER_DATA_FLAG = 1L << HAS_OCCLUDER_DATA_BIT;
/**
* Fields whose changes can alter the result of a visibility search or its
* render-list output: visibility graph data and visual-presence flags.
*/
public static final long GRAPH_INPUT_MASK = VISIBILITY_MASK | (VISUALS_FLAGS_MASK << VISUALS_FLAGS_SHIFT);
/** Returns only the visibility graph field. */ /** Returns only the visibility graph field. */
public static long getVisibilityData(long packed) { public static long getVisibilityData(long packed) {
return packed & VISIBILITY_MASK; return packed & VISIBILITY_MASK;
@@ -125,6 +130,18 @@ public final class PackedSectionMetadata {
return (packed & BUILD_IN_FLIGHT_FLAG) != 0; return (packed & BUILD_IN_FLIGHT_FLAG) != 0;
} }
/** Returns whether the section's built data has occluder boxes. */
public static boolean hasOccluderData(long packed) {
return (packed & HAS_OCCLUDER_DATA_FLAG) != 0;
}
/**
* Replaces the has-occluder-data flag and preserves every other field.
*/
public static long withHasOccluderData(long packed, boolean hasOccluderData) {
return hasOccluderData ? (packed | HAS_OCCLUDER_DATA_FLAG) : (packed & ~HAS_OCCLUDER_DATA_FLAG);
}
/* /*
* Compact collector metadata: includes only the info the VisibleChunkCollector cares about. * Compact collector metadata: includes only the info the VisibleChunkCollector cares about.
* *
@@ -143,9 +143,10 @@ public class RenderSection extends AbstractSection {
public void updateCachedContextDataFlags() { public void updateCachedContextDataFlags() {
int flags = this.contextData != null ? this.contextData.getVisualBitmaskForSection() : 0; int flags = this.contextData != null ? this.contextData.getVisualBitmaskForSection() : 0;
long visibilityData = this.contextData != null ? this.contextData.visibilityData : VisibilityEncoding.NULL; long visibilityData = this.contextData != null ? this.contextData.visibilityData : VisibilityEncoding.NULL;
boolean hasOccluderData = this.contextData != null && this.contextData.occluderBoxes != null;
this.writeMetadata(PackedSectionMetadata.withVisibilityData( this.writeMetadata(PackedSectionMetadata.withHasOccluderData(PackedSectionMetadata.withVisibilityData(
PackedSectionMetadata.withVisualsFlags(this.packedMetadata, flags), visibilityData)); PackedSectionMetadata.withVisualsFlags(this.packedMetadata, flags), visibilityData), hasOccluderData));
} }
// The sole writer of packedMetadata: stores the new word and notifies the mirror. // The sole writer of packedMetadata: stores the new word and notifies the mirror.
@@ -139,7 +139,7 @@ public abstract class RenderSectionManager {
this.minSection = minSection; this.minSection = minSection;
this.maxSection = maxSection; this.maxSection = maxSection;
AsyncOcclusionMode asyncMode = this.getAsyncOcclusionMode(); AsyncOcclusionMode asyncMode = this.getAsyncOcclusionMode();
this.sectionGraph = new SectionGraph(this.minSection, this.maxSection, asyncMode, hasShadowPass); this.sectionGraph = new SectionGraph(this.minSection, this.maxSection, asyncMode, hasShadowPass, this.useRasterOcclusionCulling());
this.renderListManager = new RenderListManager(this.sectionGraph, false, asyncMode, this.createSectionTicker()); this.renderListManager = new RenderListManager(this.sectionGraph, false, asyncMode, this.createSectionTicker());
if (hasShadowPass) { if (hasShadowPass) {
this.shadowRenderListManager = new RenderListManager(this.sectionGraph, true, asyncMode, this.createSectionTicker()); this.shadowRenderListManager = new RenderListManager(this.sectionGraph, true, asyncMode, this.createSectionTicker());
@@ -347,6 +347,8 @@ public abstract class RenderSectionManager {
protected abstract boolean useFogOcclusion(); protected abstract boolean useFogOcclusion();
protected abstract boolean useRasterOcclusionCulling();
private float getSearchDistance(@Nullable Matrix4fc projectionMatrix) { private float getSearchDistance(@Nullable Matrix4fc projectionMatrix) {
float distance; float distance;
@@ -2,7 +2,9 @@ package org.embeddedt.embeddium.impl.render.chunk.data;
import org.embeddedt.embeddium.impl.render.chunk.lists.RenderVisualsService; import org.embeddedt.embeddium.impl.render.chunk.lists.RenderVisualsService;
import org.jetbrains.annotations.MustBeInvokedByOverriders; import org.jetbrains.annotations.MustBeInvokedByOverriders;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Objects; import java.util.Objects;
/** /**
@@ -13,6 +15,8 @@ public class BuiltRenderSectionData {
public boolean hasBlockGeometry; public boolean hasBlockGeometry;
public long visibilityData; public long visibilityData;
public int @Nullable [] occluderBoxes;
public int getVisualBitmaskForSection() { public int getVisualBitmaskForSection() {
return this.hasBlockGeometry ? (1 << RenderVisualsService.HAS_BLOCK_GEOMETRY) : 0; return this.hasBlockGeometry ? (1 << RenderVisualsService.HAS_BLOCK_GEOMETRY) : 0;
} }
@@ -26,11 +30,12 @@ public class BuiltRenderSectionData {
public boolean equals(Object o) { public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false; if (o == null || getClass() != o.getClass()) return false;
BuiltRenderSectionData that = (BuiltRenderSectionData) o; BuiltRenderSectionData that = (BuiltRenderSectionData) o;
return hasBlockGeometry == that.hasBlockGeometry && visibilityData == that.visibilityData; return hasBlockGeometry == that.hasBlockGeometry && visibilityData == that.visibilityData
&& Arrays.equals(occluderBoxes, that.occluderBoxes);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(hasBlockGeometry, visibilityData); return (Objects.hash(hasBlockGeometry, visibilityData) * 31) + Arrays.hashCode(occluderBoxes);
} }
} }
@@ -34,8 +34,8 @@ public final class SectionGraph {
// runDeferredTasks() once every search has been joined. // runDeferredTasks() once every search has been joined.
private final ArrayDeque<Runnable> updateTasks = new ArrayDeque<>(); private final ArrayDeque<Runnable> updateTasks = new ArrayDeque<>();
public SectionGraph(int minSectionY, int maxSectionY, AsyncOcclusionMode asyncMode, boolean hasShadowPass) { public SectionGraph(int minSectionY, int maxSectionY, AsyncOcclusionMode asyncMode, boolean hasShadowPass, boolean rasterOcclusion) {
this.lattice = new SectionLattice(minSectionY, maxSectionY, hasShadowPass); this.lattice = new SectionLattice(minSectionY, maxSectionY, hasShadowPass, rasterOcclusion);
if (asyncMode != AsyncOcclusionMode.NONE) { if (asyncMode != AsyncOcclusionMode.NONE) {
this.executor = Executors.newSingleThreadExecutor(runnable -> { this.executor = Executors.newSingleThreadExecutor(runnable -> {
@@ -1,12 +1,16 @@
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 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;
import org.embeddedt.embeddium.impl.render.chunk.PackedSectionMetadata; import org.embeddedt.embeddium.impl.render.chunk.PackedSectionMetadata;
import org.embeddedt.embeddium.impl.render.chunk.lists.RenderVisualsService;
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
import org.embeddedt.embeddium.impl.render.viewport.CameraTransform; import org.embeddedt.embeddium.impl.render.viewport.CameraTransform;
import org.embeddedt.embeddium.impl.render.viewport.Viewport; import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.embeddedt.embeddium.impl.render.viewport.frustum.Frustum; import org.embeddedt.embeddium.impl.render.viewport.frustum.Frustum;
import org.jetbrains.annotations.Nullable;
import org.joml.Vector3ic; import org.joml.Vector3ic;
import static org.embeddedt.embeddium.impl.common.util.MathUtil.nearestToZero; import static org.embeddedt.embeddium.impl.common.util.MathUtil.nearestToZero;
@@ -114,13 +118,17 @@ public class OcclusionCuller {
private final RegionCullCache regionCullCache = new RegionCullCache(); private final RegionCullCache regionCullCache = new RegionCullCache();
private final @Nullable RasterOccluder rasterOccluder;
private boolean rasterActive;
private boolean isCameraInUnloadedSection; private boolean isCameraInUnloadedSection;
private boolean isMultiRootSearch; private boolean isMultiRootSearch;
public OcclusionCuller(SectionLattice lattice, int minSectionY, int maxSectionY) { public OcclusionCuller(SectionLattice lattice, int minSectionY, int maxSectionY, boolean rasterOcclusion) {
this.lattice = lattice; this.lattice = lattice;
this.minSectionY = minSectionY; this.minSectionY = minSectionY;
this.maxSectionY = maxSectionY; this.maxSectionY = maxSectionY;
this.rasterOccluder = rasterOcclusion ? new RasterOccluder() : null;
} }
/** /**
@@ -182,6 +190,12 @@ public class OcclusionCuller {
allowFrustumClamping = false; allowFrustumClamping = false;
} }
this.rasterActive = this.rasterOccluder != null && useOcclusionCulling && viewport.getVpMatrix() != null;
if (this.rasterActive) {
this.rasterOccluder.prepareScene(frame, viewport, searchDistance, numRegions);
}
this.process(visitor, viewport, searchDistance, useOcclusionCulling, allowFrustumClamping, frame); this.process(visitor, viewport, searchDistance, useOcclusionCulling, allowFrustumClamping, frame);
if (recordVisible) { if (recordVisible) {
@@ -212,6 +226,8 @@ public class OcclusionCuller {
final long[] queue = this.queue; final long[] queue = this.queue;
final long[] apertures = this.apertures; final long[] apertures = this.apertures;
final long[] visibleCells = this.visibleCells; final long[] visibleCells = this.visibleCells;
final int[] occluderBounds = this.lattice.occluderBounds;
final int[][] occluderData = this.lattice.occluderData;
int visibleCount = this.visibleCount; int visibleCount = this.visibleCount;
final int baseX = this.lattice.baseX, baseY = this.lattice.baseY, baseZ = this.lattice.baseZ; final int baseX = this.lattice.baseX, baseY = this.lattice.baseY, baseZ = this.lattice.baseZ;
@@ -250,10 +266,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
@@ -285,14 +301,24 @@ public class OcclusionCuller {
visible = aperture != FastFrustumClamping.EMPTY; visible = aperture != FastFrustumClamping.EMPTY;
} }
boolean traverse = visible;
if (this.rasterActive && visible) {
RasterOccluder.SectionVisibility result = this.rasterTest(occluderBounds, occluderData,
idx, chunkX, chunkY, chunkZ, camX, camY, camZ,
compactMeta, PackedSectionMetadata.hasOccluderData(sm), regionId, regionX, regionY, regionZ);
visible = result == RasterOccluder.SectionVisibility.VISIBLE;
traverse = result != RasterOccluder.SectionVisibility.HIDDEN;
}
int sectionIndex = LocalSectionIndex.pack(chunkX, chunkY, chunkZ); int sectionIndex = LocalSectionIndex.pack(chunkX, chunkY, chunkZ);
visitor.visit(idx, regionId, sectionIndex, compactMeta, visible); visitor.visit(idx, regionId, sectionIndex, compactMeta, visible);
if (!visible) { if (!traverse) {
continue; continue;
} }
if (visibleCells != null) { if (visible && visibleCells != null) {
visibleCells[visibleCount++] = entry; visibleCells[visibleCount++] = entry;
} }
@@ -335,6 +361,50 @@ public class OcclusionCuller {
this.visibleCount = visibleCount; this.visibleCount = visibleCount;
} }
private RasterOccluder.SectionVisibility rasterTest(int[] occluderBounds, int[][] occluderData,
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 dy = chunkY - camY;
int dz = chunkZ - camZ;
int squaredChunkDist = (dx * dx) + (dy * dy) + (dz * dz);
boolean hasGeometry =
(PackedSectionMetadata.getCompactVisualsFlags(meta) & (1 << RenderVisualsService.HAS_BLOCK_GEOMETRY)) != 0;
// the flag spares the many sections without data the loads below, which rarely hit cache
int bounds = hasOccluderData ? occluderBounds[idx] : PackedBox.FULL_BOX;
RasterOccluder.SectionVisibility result = occluder.testSection(chunkX << 4, chunkY << 4, chunkZ << 4, squaredChunkDist, bounds);
if (result == RasterOccluder.SectionVisibility.VISIBLE && hasGeometry && hasOccluderData) {
occluder.occludeSection(occluderData[idx]);
}
return result;
}
/** Current raster buffer size as {@code width x height} in pixels, or null when the raster is off. */
public String rasterBufferSize() {
return this.rasterOccluder == null ? null
: this.rasterOccluder.bufferWidth() + "x" + this.rasterOccluder.bufferHeight();
}
public int rasterBacktrackCount() {
return this.rasterOccluder == null ? 0 : this.rasterOccluder.backtrackCount();
}
// Visit each selected neighbour using both its linear array offset and // Visit each selected neighbour using both its linear array offset and
// its packed-coordinate offset. The lattice border makes idx + delta safe. // its packed-coordinate offset. The lattice border makes idx + delta safe.
private void visitNeighbors(long[] visitState, long[] queue, int[] delta, int idx, int xyz, int outgoing, long frameStamp) { private void visitNeighbors(long[] visitState, long[] queue, int[] delta, int idx, int xyz, int outgoing, long frameStamp) {
@@ -0,0 +1,323 @@
package org.embeddedt.embeddium.impl.render.chunk.occlusion;
import grondag.bitraster.AbstractRasterizer;
import grondag.bitraster.BoxOccluder;
import grondag.bitraster.Constants;
import grondag.bitraster.Matrix4L;
import grondag.bitraster.PackedBox;
import grondag.bitraster.PerspectiveRasterizer;
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.joml.Matrix4fc;
import java.util.Arrays;
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 */
public static final int NEAR_SQUARED_CHUNK_DIST = 3;
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. */
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 enum SectionVisibility {
/** nothing of the section is visible, and nothing behind it can be reached through it */
HIDDEN,
/** the section draws nothing visible, but the space it occupies is not fully covered, so
* traversal must continue through it or geometry behind it would be lost */
TRAVERSABLE,
/** the section is visible and can be used to occlude other sections */
VISIBLE
}
public RasterOccluder() {
super(new PerspectiveRasterizer());
}
@Override
public boolean isBoxVisible(int packedBox, int fuzz) {
return isBoxVisibleFromPerspective(packedBox, fuzz);
}
@Override
public void occludeBox(int packedBox) {
occludeFromPerspective(packedBox);
}
/**
* Clears the buffer for a new search. The matrix already carries rotation and projection but no
* camera translation, so it is supplied as the projection with an identity model matrix;
* {@link #prepareRegion} applies the camera-relative offset per section.
*/
public void prepareScene(int viewVersion, Viewport viewport, float searchDistance, int numRegions) {
Matrix4fc vpMatrix = viewport.getVpMatrix();
if (vpMatrix == null) {
throw new IllegalStateException("viewport supplies no view matrix");
}
var transform = viewport.getTransform();
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);
invalidate();
prepareScene(viewVersion, transform.x, transform.y, transform.z,
Matrix4L::loadIdentity, m -> copyMatrix(vpMatrix, m));
}
/**
* {@link Matrix4L} indexes {@code a<row><col>} while JOML indexes {@code m<col><row>}, so this
* transposes. Feeding it straight through instead still produces plausible-looking output.
*/
private static void copyMatrix(Matrix4fc src, Matrix4L dst) {
dst.set(
src.m00(), src.m10(), src.m20(), src.m30(),
src.m01(), src.m11(), src.m21(), src.m31(),
src.m02(), src.m12(), src.m22(), src.m32(),
src.m03(), src.m13(), src.m23(), src.m33());
}
/**
* Sizes each axis of the buffer so that a block at the search distance spans at least one pixel along it,
* which is what keeps a one-block gap between occluders from closing under pixel-centre sampling. The
* projection scale of an axis is the length of the matching row of the view-projection matrix: for a
* perspective matrix those rows are {@code (1/(aspect tan(fov/2)), 0, 0, 0)} and {@code (0, 1/tan(fov/2), 0, 0)},
* and the camera rotation they are multiplied by preserves length. Bobbing folded into the matrix adds 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.
*
* <p>Sizes are not limited to powers of two, so each axis holds close to what it needs rather than up to
* 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) {
// orthographic or degenerate matrices have no perspective row; keep whatever we have
float perspectiveRow = (float) Math.sqrt((vp.m03() * vp.m03()) + (vp.m13() * vp.m13()) + (vp.m23() * vp.m23()));
if (!(perspectiveRow > 0.5f) || !(searchDistance > 0)) {
return;
}
float scaleX = (float) Math.sqrt((vp.m00() * vp.m00()) + (vp.m10() * vp.m10()) + (vp.m20() * vp.m20()));
float scaleY = (float) Math.sqrt((vp.m01() * vp.m01()) + (vp.m11() * vp.m11()) + (vp.m21() * vp.m21()));
if (!(scaleX > 0) || !(scaleY > 0)) {
return;
}
// pixels per block at distance d along an axis is size * scale / (2d)
float required = 2.0f * searchDistance * PIXELS_PER_BLOCK;
int widthTiles = chooseAxisTiles(bufferWidth() >> Constants.TILE_AXIS_SHIFT, required / scaleX);
int heightTiles = chooseAxisTiles(bufferHeight() >> Constants.TILE_AXIS_SHIFT, required / scaleY);
resizeBuffer(widthTiles, heightTiles);
}
/**
* 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 (required > currentTiles) {
return required;
}
int shrunk = Math.min(Constants.MAX_SIZE_TILES, required + SIZE_STEP_TILES);
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;
}
if (!isTileBoxUntouched(this.regionTiles[regionId])) {
regionVersion[regionId] = REGION_TOUCHED;
return false;
}
regionVersion[regionId] = current;
}
return state == REGION_ON_SCREEN
|| isSectionCenterOnScreen(this.regionClip, regionId * 3,
chunkX - (originX >> 4), chunkY - (originY >> 4), chunkZ - (originZ >> 4));
}
/**
* 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.
* must run before occlude(), or a section would occlude itself.
*/
public SectionVisibility testSection(int originX, int originY, int originZ, int squaredChunkDist, int bounds) {
if (!AbstractRasterizer.STATS) {
return testSection0(originX, originY, originZ, squaredChunkDist, bounds);
}
long t0 = System.nanoTime();
try {
STAT_SECTIONS++;
var result = testSection0(originX, originY, originZ, squaredChunkDist, bounds);
if (squaredChunkDist <= NEAR_SQUARED_CHUNK_DIST) {
STAT_NEAR++;
} else if (bounds == PackedBox.FULL_BOX) {
STAT_AIR_TESTS++;
if (result == SectionVisibility.VISIBLE) STAT_AIR_VISIBLE++;
}
return result;
} finally {
STAT_TEST_NANOS += System.nanoTime() - t0;
}
}
/** Draws the section's occluder boxes for the region prepared by the last {@link #testSection}. */
public void occludeSection(int[] data) {
if (!AbstractRasterizer.STATS) {
occlude(data);
return;
}
long t0 = System.nanoTime();
STAT_OCCLUDED_SECTIONS++;
occlude(data);
STAT_OCCLUDE_NANOS += System.nanoTime() - t0;
}
private SectionVisibility testSection0(int originX, int originY, int originZ, int squaredChunkDist, int bounds) {
prepareRegion(originX, originY, originZ,
PackedBox.rangeFromSquareChunkDist(squaredChunkDist), squaredChunkDist);
if (squaredChunkDist <= NEAR_SQUARED_CHUNK_DIST) {
return SectionVisibility.VISIBLE;
}
if (isBoxCenterClear(bounds)) {
if (AbstractRasterizer.STATS) STAT_CENTER_HIT++;
return SectionVisibility.VISIBLE;
}
// tests are dilated by a pixel inside the rasterizer, so no world-space fuzz is needed
if (isBoxVisible(bounds, 0)) {
return SectionVisibility.VISIBLE;
}
if (squaredChunkDist < maxSquaredChunkDistance()) {
this.backtrackCount++;
}
// only worth asking when the bounds were tighter than the section itself
if (bounds != PackedBox.FULL_BOX && (isBoxCenterClear(PackedBox.FULL_BOX) || isBoxVisible(PackedBox.FULL_BOX, 0))) {
return SectionVisibility.TRAVERSABLE;
}
return SectionVisibility.HIDDEN;
}
// the buffer holds coverage only, with no depth, so it's correct only if sections are drawn
// front to back. our bfs visits in hop-count order, which approximates that but does not
// guarantee it, so this reports how often the approximation was wrong.
public int backtrackCount() {
return this.backtrackCount;
}
}
@@ -0,0 +1,30 @@
package org.embeddedt.embeddium.impl.render.chunk.occlusion;
import grondag.bitraster.PackedBox;
final class RenderableBounds {
private int minX = 16, minY = 16, minZ = 16;
private int maxX = -1, maxY = -1, maxZ = -1;
void mark(int x, int y, int z) {
if (x < this.minX) this.minX = x;
if (y < this.minY) this.minY = y;
if (z < this.minZ) this.minZ = z;
if (x > this.maxX) this.maxX = x;
if (y > this.maxY) this.maxY = y;
if (z > this.maxZ) this.maxZ = z;
}
boolean isEmpty() {
return this.maxX < 0;
}
int packed() {
if (isEmpty()) {
return PackedBox.FULL_BOX;
}
return PackedBox.pack(this.minX, this.minY, this.minZ,
this.maxX + 1, this.maxY + 1, this.maxZ + 1, PackedBox.RANGE_EXTREME);
}
}
@@ -115,6 +115,8 @@ public final class SectionLattice {
// Non-null only when the lattice serves a shadow pass as well. // Non-null only when the lattice serves a shadow pass as well.
@Nullable @Nullable
private final ShadowOcclusionCuller shadowCuller; private final ShadowOcclusionCuller shadowCuller;
// Whether the raster occluder is in use; gates maintenance of occluderData/occluderBounds, which only it reads.
private final boolean rasterOcclusion;
private final int minSectionY, maxSectionY; private final int minSectionY, maxSectionY;
@@ -137,6 +139,11 @@ public final class SectionLattice {
long[] shadowVisitState; long[] shadowVisitState;
long[] sectionMeta; long[] sectionMeta;
int[] regionOfCell; int[] regionOfCell;
int[] @Nullable [] occluderData;
int @Nullable [] occluderBounds;
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
@@ -191,13 +198,14 @@ public final class SectionLattice {
* @param hasShadowPass whether the lattice must also support {@link #findShadowVisible}, which costs a second * @param hasShadowPass whether the lattice must also support {@link #findShadowVisible}, which costs a second
* visit-state array * visit-state array
*/ */
public SectionLattice(int minSectionY, int maxSectionY, boolean hasShadowPass) { public SectionLattice(int minSectionY, int maxSectionY, boolean hasShadowPass, boolean rasterOcclusion) {
this.minSectionY = minSectionY; this.minSectionY = minSectionY;
this.maxSectionY = maxSectionY; this.maxSectionY = maxSectionY;
this.baseY = minSectionY - 1; this.baseY = minSectionY - 1;
this.dimY = (maxSectionY - minSectionY) + 2; this.dimY = (maxSectionY - minSectionY) + 2;
this.culler = new OcclusionCuller(this, minSectionY, maxSectionY); this.culler = new OcclusionCuller(this, minSectionY, maxSectionY, rasterOcclusion);
this.shadowCuller = hasShadowPass ? new ShadowOcclusionCuller(this) : null; this.shadowCuller = hasShadowPass ? new ShadowOcclusionCuller(this) : null;
this.rasterOcclusion = rasterOcclusion;
if (this.dimY > MAX_DIM) { if (this.dimY > MAX_DIM) {
throw new IllegalStateException("World height " + this.dimY + " exceeds occlusion lattice limit " + MAX_DIM); throw new IllegalStateException("World height " + this.dimY + " exceeds occlusion lattice limit " + MAX_DIM);
@@ -269,7 +277,18 @@ public final class SectionLattice {
long previous = this.sectionMeta[idx]; long previous = this.sectionMeta[idx];
this.sectionMeta[idx] = packedMetadata; this.sectionMeta[idx] = packedMetadata;
return ((previous ^ packedMetadata) & PackedSectionMetadata.GRAPH_INPUT_MASK) != 0; boolean occluderChanged = false;
if (this.rasterOcclusion) {
int[] data = PackedSectionMetadata.hasOccluderData(packedMetadata) ? occluderDataOf(this.latticeSection[idx]) : null;
// A rebuild allocates a fresh array, so identity is enough to detect
// new boxes even when the packed metadata is otherwise unchanged.
occluderChanged = this.occluderData[idx] != data;
this.occluderData[idx] = data;
this.occluderBounds[idx] = boundsOf(data);
}
return occluderChanged || ((previous ^ packedMetadata) & PackedSectionMetadata.GRAPH_INPUT_MASK) != 0;
} }
/** /**
@@ -459,6 +478,14 @@ public final class SectionLattice {
return this.snapshot(this.visitState, this.mainSnapshotBuffers); return this.snapshot(this.visitState, this.mainSnapshotBuffers);
} }
public String rasterBufferSize() {
return this.culler.rasterBufferSize();
}
public int rasterBacktrackCount() {
return this.culler.rasterBacktrackCount();
}
/** /**
* Run the shadow-pass search over the currently installed lattice cells, using the shadow visit-state array * Run the shadow-pass search over the currently installed lattice cells, using the shadow visit-state array
* so the main search's state is left intact. * so the main search's state is left intact.
@@ -527,6 +554,8 @@ public final class SectionLattice {
this.sectionMeta = new long[slots]; this.sectionMeta = new long[slots];
this.regionOfCell = new int[slots]; this.regionOfCell = new int[slots];
this.latticeSection = new RenderSection[slots]; this.latticeSection = new RenderSection[slots];
this.occluderData = this.rasterOcclusion ? new int[slots][] : null;
this.occluderBounds = this.rasterOcclusion ? new int[slots] : null;
// 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.
@@ -545,6 +574,10 @@ public final class SectionLattice {
Arrays.fill(this.sectionMeta, VisibilityEncoding.NULL); Arrays.fill(this.sectionMeta, VisibilityEncoding.NULL);
Arrays.fill(this.regionOfCell, -1); Arrays.fill(this.regionOfCell, -1);
Arrays.fill(this.latticeSection, null); Arrays.fill(this.latticeSection, null);
if (this.rasterOcclusion) {
Arrays.fill(this.occluderData, null);
Arrays.fill(this.occluderBounds, 0);
}
this.baseX = newBaseX; this.baseX = newBaseX;
this.baseZ = newBaseZ; this.baseZ = newBaseZ;
@@ -624,6 +657,10 @@ public final class SectionLattice {
System.arraycopy(this.sectionMeta, srcOff, this.sectionMeta, destOff, len); System.arraycopy(this.sectionMeta, srcOff, this.sectionMeta, destOff, len);
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);
if (this.rasterOcclusion) {
System.arraycopy(this.occluderData, srcOff, this.occluderData, destOff, len);
System.arraycopy(this.occluderBounds, srcOff, this.occluderBounds, destOff, len);
}
} }
/** /**
@@ -657,6 +694,10 @@ public final class SectionLattice {
System.arraycopy(this.sectionMeta, srcOff, this.sectionMeta, destOff, runLen); System.arraycopy(this.sectionMeta, srcOff, this.sectionMeta, destOff, runLen);
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);
if (this.rasterOcclusion) {
System.arraycopy(this.occluderData, srcOff, this.occluderData, destOff, runLen);
System.arraycopy(this.occluderBounds, srcOff, this.occluderBounds, destOff, runLen);
}
} }
} }
@@ -742,6 +783,10 @@ public final class SectionLattice {
this.sectionMeta[idx] = VisibilityEncoding.NULL; this.sectionMeta[idx] = VisibilityEncoding.NULL;
this.regionOfCell[idx] = -1; this.regionOfCell[idx] = -1;
this.latticeSection[idx] = null; this.latticeSection[idx] = null;
if (this.rasterOcclusion) {
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));
@@ -789,6 +834,15 @@ public final class SectionLattice {
// Install only into the interior. An attached section outside the current // Install only into the interior. An attached section outside the current
// window remains in sections and is picked up by a later rebase. // window remains in sections and is picked up by a later rebase.
private static int @Nullable [] occluderDataOf(@Nullable RenderSection section) {
var built = section != null ? section.getBuiltContext() : null;
return built != null ? built.occluderBoxes : null;
}
private static int boundsOf(int @Nullable [] occluderData) {
return occluderData != null ? SectionVisibilityBuilder.bounds(occluderData) : 0;
}
private void install(RenderSection section) { private void install(RenderSection section) {
if (this.visitState == null) { if (this.visitState == null) {
return; return;
@@ -806,7 +860,15 @@ 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(); long packedMetadata = section.getPackedMetadata();
this.sectionMeta[idx] = packedMetadata;
if (this.rasterOcclusion) {
int[] data = PackedSectionMetadata.hasOccluderData(packedMetadata) ? occluderDataOf(section) : null;
this.occluderData[idx] = data;
this.occluderBounds[idx] = boundsOf(data);
}
this.installedCount++; this.installedCount++;
} }
@@ -826,6 +888,10 @@ public final class SectionLattice {
this.sectionMeta[idx] = VisibilityEncoding.NULL; this.sectionMeta[idx] = VisibilityEncoding.NULL;
this.regionOfCell[idx] = -1; this.regionOfCell[idx] = -1;
this.latticeSection[idx] = null; this.latticeSection[idx] = null;
if (this.rasterOcclusion) {
this.occluderData[idx] = null;
this.occluderBounds[idx] = 0;
}
this.installedCount--; this.installedCount--;
} }
} }
@@ -2,7 +2,11 @@ package org.embeddedt.embeddium.impl.render.chunk.occlusion;
import it.unimi.dsi.fastutil.ints.IntArrayFIFOQueue; import it.unimi.dsi.fastutil.ints.IntArrayFIFOQueue;
import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntArrayList;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry.BoxFinder;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry.OccluderBoxes;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.BitSet; import java.util.BitSet;
/** /**
@@ -12,7 +16,7 @@ import java.util.BitSet;
public class SectionVisibilityBuilder { public class SectionVisibilityBuilder {
private static final int SECTION_AXIS_SIZE = 16; private static final int SECTION_AXIS_SIZE = 16;
private static final int SECTION_AXIS_MASK = SECTION_AXIS_SIZE - 1; private static final int SECTION_AXIS_MASK = SECTION_AXIS_SIZE - 1;
private static final int TOTAL_BLOCKS = SECTION_AXIS_SIZE * SECTION_AXIS_SIZE * SECTION_AXIS_SIZE; static final int TOTAL_BLOCKS = SECTION_AXIS_SIZE * SECTION_AXIS_SIZE * SECTION_AXIS_SIZE;
private static final int BLOCKS_ON_ONE_FACE = SECTION_AXIS_SIZE * SECTION_AXIS_SIZE; private static final int BLOCKS_ON_ONE_FACE = SECTION_AXIS_SIZE * SECTION_AXIS_SIZE;
private static final int BITS_PER_AXIS = 4; private static final int BITS_PER_AXIS = 4;
private static final int X_SHIFT = 0; private static final int X_SHIFT = 0;
@@ -25,6 +29,7 @@ public class SectionVisibilityBuilder {
private static final int[] INDICES_TO_INITIATE_FLOODFILL = buildFloodfillIndices(); private static final int[] INDICES_TO_INITIATE_FLOODFILL = buildFloodfillIndices();
private final BitSet blocks; private final BitSet blocks;
private final RenderableBounds renderableBounds = new RenderableBounds();
private static int[] buildFloodfillIndices() { private static int[] buildFloodfillIndices() {
IntArrayList indicesList = new IntArrayList(TOTAL_BLOCKS - (SECTION_AXIS_SIZE - 2) * (SECTION_AXIS_SIZE - 2) * (SECTION_AXIS_SIZE - 2)); IntArrayList indicesList = new IntArrayList(TOTAL_BLOCKS - (SECTION_AXIS_SIZE - 2) * (SECTION_AXIS_SIZE - 2) * (SECTION_AXIS_SIZE - 2));
@@ -62,16 +67,50 @@ public class SectionVisibilityBuilder {
this.blocks.set(getIndex(x & 15, y & 15, z & 15)); this.blocks.set(getIndex(x & 15, y & 15, z & 15));
} }
public void markRenderable(int x, int y, int z) {
this.renderableBounds.mark(x & 15, y & 15, z & 15);
}
public int @Nullable [] computeOccluderBoxes() {
return dataFrom(this.blocks, this.renderableBounds);
}
static int bounds(int[] data) {
return data[0];
}
private static int @Nullable [] dataFrom(BitSet blocks, RenderableBounds bounds) {
if (blocks.isEmpty() && bounds.isEmpty()) {
return null;
}
int[] boxes = blocks.isEmpty() ? null
: OccluderBoxes.from(Arrays.copyOf(blocks.toLongArray(), BoxFinder.INTERIOR_CACHE_WORDS));
int count = boxes == null ? 0 : boxes.length;
int[] data = new int[count + 1];
data[0] = bounds.packed();
if (boxes != null) {
System.arraycopy(boxes, 0, data, 1, count);
}
return data;
}
private long computeWithFloodFill() { private long computeWithFloodFill() {
long resultEncoding = 0; long resultEncoding = 0;
var blocks = this.blocks; // The fill marks cells as visited by setting their bit, which would corrupt the opacity data other
// callers (computeOccluderBoxes()) still need. Clone it into scratch space instead of mutating
// this.blocks in place; opaque cells start pre-marked since the fill must not pass through them.
BitSet visited = (BitSet) this.blocks.clone();
BitSet escapedFaces = new BitSet(GraphDirection.COUNT); BitSet escapedFaces = new BitSet(GraphDirection.COUNT);
IntArrayFIFOQueue queue = new IntArrayFIFOQueue(); IntArrayFIFOQueue queue = new IntArrayFIFOQueue();
for (int i : INDICES_TO_INITIATE_FLOODFILL) { for (int i : INDICES_TO_INITIATE_FLOODFILL) {
if (!blocks.get(i)) { if (!visited.get(i)) {
escapedFaces.clear(); escapedFaces.clear();
queue.clear(); queue.clear();
this.exploreFrom(escapedFaces, queue, i); exploreFrom(visited, escapedFaces, queue, i);
for (int dir = escapedFaces.nextSetBit(0); dir >= 0; dir = escapedFaces.nextSetBit(dir+1)) { for (int dir = escapedFaces.nextSetBit(0); dir >= 0; dir = escapedFaces.nextSetBit(dir+1)) {
for (int dir2 = escapedFaces.nextSetBit(0); dir2 >= 0; dir2 = escapedFaces.nextSetBit(dir2+1)) { for (int dir2 = escapedFaces.nextSetBit(0); dir2 >= 0; dir2 = escapedFaces.nextSetBit(dir2+1)) {
resultEncoding |= 1L << VisibilityEncoding.bit(dir, dir2); resultEncoding |= 1L << VisibilityEncoding.bit(dir, dir2);
@@ -82,20 +121,19 @@ public class SectionVisibilityBuilder {
return resultEncoding; return resultEncoding;
} }
private void exploreFrom(BitSet escapedFaces, IntArrayFIFOQueue queue, int startIndex) { private static void exploreFrom(BitSet visited, BitSet escapedFaces, IntArrayFIFOQueue queue, int startIndex) {
queue.enqueue(startIndex); queue.enqueue(startIndex);
var blocks = this.blocks;
// Mark the start location as handled // Mark the start location as handled
blocks.set(startIndex, true); visited.set(startIndex, true);
while (!queue.isEmpty()) { while (!queue.isEmpty()) {
int idx = queue.dequeueInt(); int idx = queue.dequeueInt();
for (int dir = 0; dir < GraphDirection.COUNT; dir++) { for (int dir = 0; dir < GraphDirection.COUNT; dir++) {
int neighborIdx = getNeighborIndex(idx, dir); int neighborIdx = getNeighborIndex(idx, dir);
if (neighborIdx >= 0) { if (neighborIdx >= 0) {
// We can move within the section in that direction // We can move within the section in that direction
if (!blocks.get(neighborIdx)) { if (!visited.get(neighborIdx)) {
// Mark this location as handled // Mark this location as handled
blocks.set(neighborIdx, true); visited.set(neighborIdx, true);
queue.enqueue(neighborIdx); queue.enqueue(neighborIdx);
} }
} else { } else {
@@ -154,7 +192,7 @@ public class SectionVisibilityBuilder {
} }
} }
private static int getIndex(int x, int y, int z) { static int getIndex(int x, int y, int z) {
return (y << Y_SHIFT) | (z << Z_SHIFT) | (x << X_SHIFT); return (y << Y_SHIFT) | (z << Z_SHIFT) | (x << X_SHIFT);
} }
} }
@@ -0,0 +1,220 @@
/*
* Ported from Canvas (https://github.com/vram-guild/canvas), Copyright 2019, 2020 grondag.
* Licensed under the GNU Lesser General Public License v3.0.
*/
package org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry;
import it.unimi.dsi.fastutil.ints.AbstractIntComparator;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntArrays;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
public class Area {
public static final int AREA_COUNT;
public static final int SECTION_COUNT;
private static final int[] AREA_KEY_TO_INDEX = new int[0x10000];
private static final int[] AREA_INDEX_TO_KEY;
private static final int[] SECTION_KEYS;
private static final int[] SECTION_INDEX;
private static final long[] AREA_BITS;
static {
final IntOpenHashSet areas = new IntOpenHashSet();
areas.add(Area.areaKey(0, 0, 15, 15));
areas.add(Area.areaKey(1, 0, 15, 15));
areas.add(Area.areaKey(0, 0, 14, 15));
areas.add(Area.areaKey(0, 1, 15, 15));
areas.add(Area.areaKey(0, 0, 15, 14));
for (int x0 = 0; x0 <= 15; x0++) {
for (int x1 = x0; x1 <= 15; x1++) {
for (int y0 = 0; y0 <= 15; y0++) {
for (int y1 = y0; y1 <= 15; y1++) {
areas.add(Area.areaKey(x0, y0, x1, y1));
}
}
}
}
AREA_COUNT = areas.size();
AREA_INDEX_TO_KEY = new int[AREA_COUNT];
AREA_BITS = new long[AREA_COUNT * 4];
int i = 0;
for (final int k : areas) {
AREA_INDEX_TO_KEY[i++] = k;
}
IntArrays.quickSort(AREA_INDEX_TO_KEY, new AbstractIntComparator() {
@Override
public int compare(int a, int b) {
final int result = Integer.compare(Area.size(b), Area.size(a));
// within same area size, prefer more compact rectangles
return result == 0 ? Integer.compare(Area.edgeCount(a), Area.edgeCount(b)) : result;
}
});
for (int j = 0; j < AREA_COUNT; j++) {
AREA_KEY_TO_INDEX[AREA_INDEX_TO_KEY[j]] = j;
}
final IntArrayList sections = new IntArrayList();
for (int j = 0; j < AREA_COUNT; ++j) {
final int a = AREA_INDEX_TO_KEY[j];
if ((Area.x0(a) == 0 && Area.x1(a) == 15) || (Area.y0(a) == 0 && Area.y1(a) == 15)) {
sections.add(indexToKey(j));
}
}
SECTION_COUNT = sections.size();
SECTION_KEYS = sections.toArray(new int[SECTION_COUNT]);
SECTION_INDEX = new int[SECTION_COUNT];
for (int k = 0; k < SECTION_COUNT; ++k) {
SECTION_INDEX[k] = keyToIndex(SECTION_KEYS[k]);
}
final long[] xMasks = new long[256];
final int[] yBits = new int[256];
final long[] yMasks = new long[16];
for (int x0 = 0; x0 <= 15; ++x0) {
for (int x1 = x0; x1 <= 15; ++x1) {
final long template = (0xFFFF << x0) & (0xFFFF >> (15 - x1));
xMasks[x0 | (x1 << 4)] = template | (template << 16) | (template << 32) | (template << 48);
}
}
for (int y0 = 0; y0 <= 15; ++y0) {
for (int y1 = y0; y1 <= 15; ++y1) {
yBits[y0 | (y1 << 4)] = (0xFFFF << y0) & (0xFFFF >> (15 - y1));
}
}
yMasks[0b0000] = 0L;
yMasks[0b0001] = 0x000000000000FFFFL;
yMasks[0b0010] = 0x00000000FFFF0000L;
yMasks[0b0100] = 0x0000FFFF00000000L;
yMasks[0b1000] = 0xFFFF000000000000L;
yMasks[0b0011] = 0x00000000FFFFFFFFL;
yMasks[0b0110] = 0x0000FFFFFFFF0000L;
yMasks[0b1100] = 0xFFFFFFFF00000000L;
yMasks[0b0111] = 0x0000FFFFFFFFFFFFL;
yMasks[0b1110] = 0xFFFFFFFFFFFF0000L;
yMasks[0b1111] = 0xFFFFFFFFFFFFFFFFL;
int j = 0;
for (int areaIndex = 0; areaIndex < AREA_COUNT; ++areaIndex) {
final int areaKey = indexToKey(areaIndex);
AREA_BITS[j++] = yMasks[(yBits[areaKey >> 8] >> (0 << 2)) & 0xF] & xMasks[areaKey & 0xFF];
AREA_BITS[j++] = yMasks[(yBits[areaKey >> 8] >> (1 << 2)) & 0xF] & xMasks[areaKey & 0xFF];
AREA_BITS[j++] = yMasks[(yBits[areaKey >> 8] >> (2 << 2)) & 0xF] & xMasks[areaKey & 0xFF];
AREA_BITS[j++] = yMasks[(yBits[areaKey >> 8] >> (3 << 2)) & 0xF] & xMasks[areaKey & 0xFF];
}
}
public static int keyToIndex(int key) {
return AREA_KEY_TO_INDEX[key];
}
public static int indexToKey(int index) {
return AREA_INDEX_TO_KEY[index];
}
public static int sectionToAreaIndex(int sectionIndex) {
return SECTION_INDEX[sectionIndex];
}
public static boolean isIncludedBySample(long[] sample, int sampleStart, int areaIndex) {
areaIndex <<= 2;
final long template = AREA_BITS[areaIndex];
final long template1 = AREA_BITS[++areaIndex];
final long template2 = AREA_BITS[++areaIndex];
final long template3 = AREA_BITS[++areaIndex];
return (template & sample[sampleStart]) == template
&& (template1 & sample[sampleStart + 1]) == template1
&& (template2 & sample[sampleStart + 2]) == template2
&& (template3 & sample[sampleStart + 3]) == template3;
}
public static boolean intersectsWithSample(long[] sample, int sampleStart, int areaIndex) {
areaIndex <<= 2;
return (AREA_BITS[areaIndex] & sample[sampleStart]) != 0
|| (AREA_BITS[++areaIndex] & sample[++sampleStart]) != 0
|| (AREA_BITS[++areaIndex] & sample[++sampleStart]) != 0
|| (AREA_BITS[++areaIndex] & sample[++sampleStart]) != 0;
}
public static boolean isAdditive(long[] sample, int sampleStart, int areaIndex) {
areaIndex <<= 2;
return (AREA_BITS[areaIndex] | sample[sampleStart]) != sample[sampleStart]
|| (AREA_BITS[++areaIndex] | sample[++sampleStart]) != sample[sampleStart]
|| (AREA_BITS[++areaIndex] | sample[++sampleStart]) != sample[sampleStart]
|| (AREA_BITS[++areaIndex] | sample[++sampleStart]) != sample[sampleStart];
}
public static void clearBits(long[] targetBits, int startIndex, int areaIndex) {
areaIndex <<= 2;
targetBits[startIndex] &= ~AREA_BITS[areaIndex];
targetBits[++startIndex] &= ~AREA_BITS[++areaIndex];
targetBits[++startIndex] &= ~AREA_BITS[++areaIndex];
targetBits[++startIndex] &= ~AREA_BITS[++areaIndex];
}
public static long bitsFromIndex(int areaIndex, int y) {
return AREA_BITS[(areaIndex << 2) + y];
}
public static int areaKey(int x0, int y0, int x1, int y1) {
return x0 | (x1 << 4) | (y0 << 8) | (y1 << 12);
}
public static int x0(int areaKey) {
return areaKey & 15;
}
public static int y0(int areaKey) {
return (areaKey >> 8) & 15;
}
public static int x1(int areaKey) {
return (areaKey >> 4) & 15;
}
public static int y1(int areaKey) {
return (areaKey >> 12) & 15;
}
public static int size(int areaKey) {
final int x0 = x0(areaKey);
final int y0 = y0(areaKey);
final int x1 = x1(areaKey);
final int y1 = y1(areaKey);
return (x1 - x0 + 1) * (y1 - y0 + 1);
}
public static int edgeCount(int areaKey) {
final int x0 = x0(areaKey);
final int y0 = y0(areaKey);
final int x1 = x1(areaKey);
final int y1 = y1(areaKey);
final int x = x1 - x0 + 1;
final int y = y1 - y0 + 1;
return x + y;
}
}
@@ -0,0 +1,183 @@
/*
* Ported from Canvas (https://github.com/vram-guild/canvas), Copyright 2019, 2020 grondag.
* Licensed under the GNU Lesser General Public License v3.0.
*/
package org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry;
import java.util.function.IntConsumer;
public class AreaFinder {
final long[] bits = new long[4];
// based on approach described here:
// https://stackoverflow.com/a/7497967
// https://stackoverflow.com/a/7773870
// https://www.drdobbs.com/database/the-maximal-rectangle-problem/184410529
public static int findLargest(long[] bitsIn) {
int bestX0 = 0;
int bestY0 = 0;
int bestX1 = -1;
int bestY1 = -1;
int bestArea = 0;
// height of prior rows
// four bits per position, values 0-15
long heights = 0;
for (int y = 0; y < 16; ++y) {
final int rowBits = (int) ((bitsIn[y >> 2] >> ((y & 3) << 4)) & 0xFFFF);
if (rowBits == 0) {
heights = 0;
continue;
}
// track start of runs up to current height
long stackX15 = 0; // 0-15
long stackH16 = 0; // 1-16
int stackSize = 0;
// height of first column is zero if closed, otherwise 1 + previous row first column height
int runHeight = (rowBits & 1) == 0 ? 0 : (1 + getVal15(heights, 0));
int runStart = 0;
// save height for use by next row, unless at top row
if (y != 15) heights = setVal15(heights, 0, runHeight);
// NB: inclusive of 16. The height @ 16 will always be zero, closing off last column
for (int x = 1; x <= 16; ++x) {
// height here is 0 if closed, otherwise 1 + height of row below
final int h = (rowBits & (1 << x)) == 0 ? 0 : (1 + getVal15(heights, x));
// if higher than last start new run
if (h > runHeight) {
// push current run onto stack
if (runHeight != 0) {
stackX15 = setVal15(stackX15, stackSize, runStart);
stackH16 = setVal16(stackH16, stackSize, runHeight);
++stackSize;
}
// new run starts here
runStart = x;
runHeight = h;
} else {
// if reduction in height, close out current run and
// also runs on stack until revert to a sustainable run
// or the stack is empty
while (h < runHeight) {
// check for largest area on current run
final int a = (x - runStart) * runHeight;
if (a > bestArea) {
bestArea = a;
bestX0 = runStart;
bestX1 = x - 1;
bestY0 = y - runHeight + 1;
bestY1 = y;
}
if (stackSize == 0) {
// if we have an empty stack but non-zero height,
// then run at current height effectively starts
// where the just-closed prior run started
runHeight = h;
// NB: no change to run start - continue from prior
} else { // stackSize > 0
--stackSize;
final int stackStart = getVal15(stackX15, stackSize);
final int stackHeight = getVal16(stackH16, stackSize);
if (stackHeight == h) {
// if stack run height is same as current, resume run, leave stack popped
runHeight = h;
runStart = stackStart;
} else if (stackHeight < h) {
// if stack run height is less new height, leave on the stack
++stackSize;
// and new run starts from current position
runHeight = h;
// NB: no change to run start - continue from prior
} else {
// stack area is higher than new height
// leave stack popped and loop to close out area on the stack
runHeight = stackHeight;
runStart = stackStart;
}
}
}
}
// track height of this column but don't overflow on last row/column
if (y != 15 && x < 16) heights = setVal15(heights, x, h);
}
}
return Area.areaKey(bestX0, bestY0, bestX1, bestY1);
}
private static int getVal16(long packed, int x) {
return 1 + getVal15(packed, x);
}
private static long setVal16(long packed, int x, int val) {
return setVal15(packed, x, val - 1);
}
private static int getVal15(long packed, int x) {
return (int) ((packed >>> (x << 2)) & 0xF);
}
private static long setVal15(long packed, int x, int val) {
final int shift = x << 2;
final long mask = 0xFL << shift;
return (packed & ~mask) | (((long) val) << shift);
}
public long[] bitsFromIndex(int areaIndex) {
final long[] result = bits;
result[0] = Area.bitsFromIndex(areaIndex, 0);
result[1] = Area.bitsFromIndex(areaIndex, 1);
result[2] = Area.bitsFromIndex(areaIndex, 2);
result[3] = Area.bitsFromIndex(areaIndex, 3);
return result;
}
public void find(long[] bitsIn, int sourceIndex, IntConsumer areaIndexConsumer) {
final long[] bits = this.bits;
System.arraycopy(bitsIn, sourceIndex, bits, 0, 4);
int bitCount = Long.bitCount(bits[0]) + Long.bitCount(bits[1]) + Long.bitCount(bits[2]) + Long.bitCount(bits[3]);
while (bitCount > 0) {
final int key = findLargest(bits);
final int index = Area.keyToIndex(key);
areaIndexConsumer.accept(index);
Area.clearBits(bits, 0, index);
bitCount -= Area.size(key);
}
}
public void findSections(long[] bitsIn, int sourceIndex, IntConsumer areaIndexConsumer) {
final long[] bits = this.bits;
System.arraycopy(bitsIn, sourceIndex, bits, 0, 4);
final int bitCount = Long.bitCount(bits[0]) + Long.bitCount(bits[1]) + Long.bitCount(bits[2]) + Long.bitCount(bits[3]);
if (bitCount == 0) {
return;
}
for (int i = 0; i < Area.SECTION_COUNT; ++i) {
final int areaIndex = Area.sectionToAreaIndex(i);
if (Area.isIncludedBySample(bits, 0, areaIndex)) {
areaIndexConsumer.accept(areaIndex);
}
}
}
}
@@ -0,0 +1,354 @@
/*
* Adapted from Canvas (https://github.com/vram-guild/canvas), Copyright 2019, 2020 grondag.
* Licensed under the GNU Lesser General Public License v3.0.
*/
package org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry;
import grondag.bitraster.PackedBox;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.longs.LongArrayList;
import java.util.Arrays;
import java.util.function.IntConsumer;
/**
* Decomposes a section's opaque voxels into disjoint occluder boxes. Input is 64 longs of occupancy
* for a 16x16x16 section.
*
* <p>Rectangles are found in the low two axes of the index and extended along the high one, so a
* caller with a different axis order permutes the resulting {@link PackedBox} instead of the input.
*
* <p>Boxes never cover a voxel the source left clear, but may leave some covered voxels out: two
* passes run and any residue is dropped. That costs culling, never correctness.
*/
public class BoxFinder {
/** One bit per voxel of a 16x16x16 section. */
public static final int INTERIOR_CACHE_WORDS = 64;
public static final int SLICE_WORD_COUNT = 4;
public final IntArrayList boxes = new IntArrayList();
public final AreaFinder areaFinder;
final long[] source = new long[INTERIOR_CACHE_WORDS];
final long[] filled = new long[INTERIOR_CACHE_WORDS];
/**
* Bits 0-15 indicate which slices contain the area with the same index of the value.
*/
final int[] areaSlices = new int[Area.AREA_COUNT];
private final LongArrayList sortedBoxes = new LongArrayList();
int mask;
private final IntConsumer markSliceConsumer = areaIndex -> areaSlices[areaIndex] |= mask;
private int voxelCount;
public BoxFinder(AreaFinder areaFinder) {
this.areaFinder = areaFinder;
}
public void findBoxes(long[] sourceBits, int sourceIndex) {
Arrays.fill(filled, 0L);
System.arraycopy(sourceBits, sourceIndex, source, 0, INTERIOR_CACHE_WORDS);
boxes.clear();
markSectionSlices();
buildSortedSections();
findSections();
clearSectionBits();
voxelCount = voxelCount(source, 0);
markBoxSlices();
markBoxNeighborSlices();
buildSortedBoxes();
findDisjointBoxes();
if (voxelCount > 0) {
clearSectionBits();
markBoxSlices();
markBoxNeighborSlices();
buildSortedBoxes();
findDisjointBoxes();
}
}
private void buildSortedSections() {
final LongArrayList sortedBoxes = this.sortedBoxes;
sortedBoxes.clear();
final int[] areaSlices = this.areaSlices;
if (areaSlices[0] != 0) {
// handle special case of full Z-plane
addBoxesFromSlice(Area.indexToKey(0), areaSlices[0]);
}
for (int i = 1; i < Area.SECTION_COUNT; ++i) {
final int areaIndex = Area.sectionToAreaIndex(i);
final int slice = areaSlices[areaIndex];
if (slice == 0xFFFF) {
final int areaKey = Area.indexToKey(areaIndex);
final int dy = (Area.y1(areaKey) - Area.y0(areaKey) + 1);
final int dx = (Area.x1(areaKey) - Area.x0(areaKey) + 1);
final long vol = (dx * dy * 16);
sortedBoxes.add((vol << 34) | (areaIndex << 10) | (16 << 5) | 0);
}
}
sortedBoxes.sort((a, b) -> Long.compare(b, a));
}
private void markBoxNeighborSlices() {
final int[] areaSlices = this.areaSlices;
for (int areaIndex = 0; areaIndex < Area.AREA_COUNT; ++areaIndex) {
int slice = areaSlices[areaIndex];
if (slice != 0) {
if ((slice & 1) == 1 && (slice & 2) == 0) {
// special case first slice - can only transfer up
if (Area.isIncludedBySample(source, SLICE_WORD_COUNT, areaIndex)) {
slice |= 2;
}
}
int mask = 2;
for (int z = 1; z < 15; z++) {
if ((slice & mask) != 0) {
// transfer to lower slice if not already present
final int lowMask = (mask >> 1);
if ((slice & lowMask) == 0) {
if (Area.isIncludedBySample(source, (z - 1) * SLICE_WORD_COUNT, areaIndex)) {
slice |= lowMask;
}
}
// transfer to upper slice if not already present
final int highMask = (mask << 1);
if ((slice & highMask) == 0) {
if (Area.isIncludedBySample(source, (z + 1) * SLICE_WORD_COUNT, areaIndex)) {
slice |= highMask;
}
}
}
mask <<= 1;
}
if ((slice & 0b1000000000000000) == 0b1000000000000000 && (slice & 0b0100000000000000) == 0) {
if (Area.isIncludedBySample(source, SLICE_WORD_COUNT * 14, areaIndex)) {
slice |= 0b0100000000000000;
}
}
areaSlices[areaIndex] = slice;
}
}
}
private void buildSortedBoxes() {
final LongArrayList sortedBoxes = this.sortedBoxes;
sortedBoxes.clear();
final int[] areaSlices = this.areaSlices;
for (int areaIndex = 0; areaIndex < Area.AREA_COUNT; ++areaIndex) {
final int slice = areaSlices[areaIndex];
if (slice != 0) {
addBoxesFromSlice(Area.indexToKey(areaIndex), slice);
}
}
sortedBoxes.sort((a, b) -> Long.compare(b, a));
}
private void addBoxesFromSlice(int areaKey, int slice) {
int z0 = -1;
int mask = 1;
final int x0 = Area.x0(areaKey);
final int y0 = Area.y0(areaKey);
final int x1 = Area.x1(areaKey);
final int y1 = Area.y1(areaKey);
final int areaIndex = Area.keyToIndex(areaKey);
for (int z = 0; z < 16; z++) {
if ((slice & mask) == 0) {
// no bit, end run if started
if (z0 != -1) {
final int dz = (z - z0);
final int dy = (y1 - y0 + 1);
final int dx = (x1 - x0 + 1);
final long vol = dx * dy * dz;
sortedBoxes.add((vol << 34) | (areaIndex << 10) | (z << 5) | z0);
z0 = -1;
}
} else {
// bit set, start run if not started
if (z0 == -1) {
z0 = z;
}
}
mask <<= 1;
}
// handle case when run extends to last bit
if (z0 != -1) {
final int dz = (16 - z0);
final int dy = (y1 - y0 + 1);
final int dx = (x1 - x0 + 1);
final long vol = dx * dy * dz;
sortedBoxes.add((vol << 34) | (areaIndex << 10) | (16 << 5) | z0);
}
}
// PERF: still slow on relative basis to rest of chunk baking
private void markBoxSlices() {
final long[] sourceBits = source;
final AreaFinder areaFinder = this.areaFinder;
final int[] areaSlices = this.areaSlices;
Arrays.fill(areaSlices, 0);
mask = 1;
int sourceIndex = 0;
for (int i = 0; i < 16; ++i) {
areaFinder.find(sourceBits, sourceIndex, markSliceConsumer);
sourceIndex += SLICE_WORD_COUNT;
mask <<= 1;
}
}
private void markSectionSlices() {
final long[] sourceBits = source;
final AreaFinder areaFinder = this.areaFinder;
final int[] areaSlices = this.areaSlices;
Arrays.fill(areaSlices, 0);
mask = 1;
int sourceIndex = 0;
for (int i = 0; i < 16; ++i) {
areaFinder.findSections(sourceBits, sourceIndex, markSliceConsumer);
sourceIndex += SLICE_WORD_COUNT;
mask <<= 1;
}
}
private void findSections() {
final LongArrayList sortedBoxes = this.sortedBoxes;
final int limit = sortedBoxes.size();
final IntArrayList boxes = this.boxes;
for (int i = 0; i < limit; i++) {
final long box = sortedBoxes.getLong(i);
final int areaIndex = (int) (box >> 10) & 0xFFFFFF;
final int z0 = (int) box & 31;
final int z1 = (int) (box >> 5) & 31;
if (isAdditive(areaIndex, z0, z1)) {
fill(areaIndex, z0, z1);
final int areaKey = Area.indexToKey(areaIndex);
boxes.add(PackedBox.pack(Area.x0(areaKey), Area.y0(areaKey), z0, Area.x1(areaKey) + 1, Area.y1(areaKey) + 1, z1, PackedBox.RANGE_EXTREME));
}
}
}
private void findDisjointBoxes() {
final LongArrayList sortedBoxes = this.sortedBoxes;
final int limit = sortedBoxes.size();
final IntArrayList boxes = this.boxes;
for (int i = 0; i < limit; i++) {
final long box = sortedBoxes.getLong(i);
final int areaIndex = (int) (box >> 10) & 0xFFFFFF;
final int z0 = (int) box & 31;
final int z1 = (int) (box >> 5) & 31;
if (!intersects(areaIndex, z0, z1)) {
fill(areaIndex, z0, z1);
final int vol = (int) (box >>> 34);
final int areaKey = Area.indexToKey(areaIndex);
boxes.add(PackedBox.pack(Area.x0(areaKey), Area.y0(areaKey), z0, Area.x1(areaKey) + 1, Area.y1(areaKey) + 1, z1, rangeFromVolume(vol)));
voxelCount -= vol;
if (voxelCount == 0) {
break;
}
}
}
}
private int rangeFromVolume(int maxArea) {
return maxArea <= 64 ? PackedBox.RANGE_NEAR : maxArea > 512 ? PackedBox.RANGE_FAR : PackedBox.RANGE_MID;
}
private int voxelCount(long[] sourceBits, int sourceIndex) {
int result = 0;
final int limit = sourceIndex + INTERIOR_CACHE_WORDS;
for (int i = sourceIndex; i < limit; ++i) {
final long bits = sourceBits[i];
result += Long.bitCount(bits);
}
return result;
}
private void fill(int areaIndex, int z0, int z1) {
final long[] filled = this.filled;
int index = z0 * SLICE_WORD_COUNT;
final long[] bits = areaFinder.bitsFromIndex(areaIndex);
for (int z = z0; z < z1; ++z) {
filled[index] |= bits[0];
filled[index + 1] |= bits[1];
filled[index + 2] |= bits[2];
filled[index + 3] |= bits[3];
index += SLICE_WORD_COUNT;
}
}
private boolean intersects(int areaIndex, int z0, int z1) {
final long[] filled = this.filled;
int index = z0 * SLICE_WORD_COUNT;
for (int z = z0; z < z1; ++z) {
if (Area.intersectsWithSample(filled, index, areaIndex)) {
return true;
}
index += SLICE_WORD_COUNT;
}
return false;
}
private boolean isAdditive(int areaIndex, int z0, int z1) {
final long[] filled = this.filled;
int index = z0 * SLICE_WORD_COUNT;
final long a0 = Area.bitsFromIndex(areaIndex, 0);
final long a1 = Area.bitsFromIndex(areaIndex, 1);
final long a2 = Area.bitsFromIndex(areaIndex, 2);
final long a3 = Area.bitsFromIndex(areaIndex, 3);
for (int z = z0; z < z1; ++z) {
if (((~filled[index++] & a0) | (~filled[index++] & a1) | (~filled[index++] & a2) | (~filled[index++] & a3)) != 0) {
return true;
}
}
return false;
}
private void clearSectionBits() {
for (int i = 0; i < INTERIOR_CACHE_WORDS; ++i) {
source[i] &= ~filled[i];
}
}
}
@@ -0,0 +1,62 @@
package org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry;
import grondag.bitraster.PackedBox;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
public final class OccluderBoxes {
/** Below this a box costs a rasterizer draw for negligible screen coverage. */
private static final int MIN_VOLUME = 8;
/** {@link BoxFinder} is far too large to allocate per section; build threads are pooled */
private static final ThreadLocal<BoxFinder> FINDER = ThreadLocal.withInitial(() -> new BoxFinder(new AreaFinder()));
private OccluderBoxes() {
}
public static int @Nullable [] from(long[] opacityBits) {
BoxFinder finder = FINDER.get();
finder.findBoxes(opacityBits, 0);
var found = finder.boxes;
int count = found.size();
if (count == 0) {
return null;
}
int[] boxes = new int[count];
int kept = 0;
for (int range = PackedBox.RANGE_EXTREME; range >= PackedBox.RANGE_NEAR; range--) {
for (int i = 0; i < count; i++) {
int box = found.getInt(i);
if (PackedBox.range(box) == range && volume(box) >= MIN_VOLUME) {
boxes[kept++] = toWorldAxes(box);
}
}
}
if (kept == 0) {
return null;
}
return kept == count ? boxes : Arrays.copyOf(boxes, kept);
}
private static int toWorldAxes(int box) {
return PackedBox.pack(
PackedBox.x0(box), PackedBox.z0(box), PackedBox.y0(box),
PackedBox.x1(box), PackedBox.z1(box), PackedBox.y1(box),
PackedBox.range(box)
);
}
private static int volume(int box) {
return (PackedBox.x1(box) - PackedBox.x0(box))
* (PackedBox.y1(box) - PackedBox.y0(box))
* (PackedBox.z1(box) - PackedBox.z0(box));
}
}
@@ -2,6 +2,9 @@ package org.embeddedt.embeddium.impl.render.viewport;
import org.embeddedt.embeddium.impl.render.viewport.frustum.Frustum; import org.embeddedt.embeddium.impl.render.viewport.frustum.Frustum;
import org.embeddedt.embeddium.impl.util.PositionUtil; import org.embeddedt.embeddium.impl.util.PositionUtil;
import org.jetbrains.annotations.Nullable;
import org.joml.Matrix4f;
import org.joml.Matrix4fc;
import org.joml.RoundingMode; import org.joml.RoundingMode;
import org.joml.Vector3d; import org.joml.Vector3d;
import org.joml.Vector3i; import org.joml.Vector3i;
@@ -14,10 +17,18 @@ public final class Viewport {
private final Vector3i chunkCoords; private final Vector3i chunkCoords;
private final Vector3i blockCoords; private final Vector3i blockCoords;
private final @Nullable Matrix4fc vpMatrix;
public Viewport(Frustum frustum, Vector3d position) { public Viewport(Frustum frustum, Vector3d position) {
this(frustum, position, null);
}
public Viewport(Frustum frustum, Vector3d position, @Nullable Matrix4fc vpMatrix) {
this.frustum = frustum; this.frustum = frustum;
this.transform = new CameraTransform(position.x, position.y, position.z); this.transform = new CameraTransform(position.x, position.y, position.z);
this.vpMatrix = vpMatrix == null ? null : new Matrix4f(vpMatrix);
this.chunkCoords = new Vector3i( this.chunkCoords = new Vector3i(
PositionUtil.posToSectionCoord(position.x), PositionUtil.posToSectionCoord(position.x),
PositionUtil.posToSectionCoord(position.y), PositionUtil.posToSectionCoord(position.y),
@@ -62,6 +73,10 @@ public final class Viewport {
return this.frustum.intersectAab(minX, minY, minZ, maxX, maxY, maxZ); return this.frustum.intersectAab(minX, minY, minZ, maxX, maxY, maxZ);
} }
public @Nullable Matrix4fc getVpMatrix() {
return this.vpMatrix;
}
public Frustum getFrustum() { public Frustum getFrustum() {
return this.frustum; return this.frustum;
} }
@@ -68,5 +68,6 @@ public final class StandardOptions {
public static final OptionIdentifier<Void> USE_FASTER_CLOUDS = OptionIdentifier.create(EMBEDDIUM_MOD_ID, "use_faster_clouds"); public static final OptionIdentifier<Void> USE_FASTER_CLOUDS = OptionIdentifier.create(EMBEDDIUM_MOD_ID, "use_faster_clouds");
public static final OptionIdentifier<Void> ASYNC_GRAPH_SEARCH = OptionIdentifier.create(EMBEDDIUM_MOD_ID, "async_graph_search"); public static final OptionIdentifier<Void> ASYNC_GRAPH_SEARCH = OptionIdentifier.create(EMBEDDIUM_MOD_ID, "async_graph_search");
public static final OptionIdentifier<Void> CHUNK_FADE_IN_DURATION = OptionIdentifier.create(EMBEDDIUM_MOD_ID, "chunk_fade_in_duration"); public static final OptionIdentifier<Void> CHUNK_FADE_IN_DURATION = OptionIdentifier.create(EMBEDDIUM_MOD_ID, "chunk_fade_in_duration");
public static final OptionIdentifier<Void> RASTER_OCCLUSION_CULLING = OptionIdentifier.create(EMBEDDIUM_MOD_ID, "raster_occlusion_culling");
} }
} }
@@ -57,6 +57,11 @@ public class VintageRenderSectionManager extends RenderSectionManager {
return true; return true;
} }
@Override
protected boolean useRasterOcclusionCulling() {
return false;
}
@Override @Override
protected boolean useFogOcclusion() { protected boolean useFogOcclusion() {
return CeleritasVintage.options().performance.useFogOcclusion; return CeleritasVintage.options().performance.useFogOcclusion;
@@ -18,6 +18,8 @@ celeritas.options.async_graph_search.tooltip=Performs occlusion/frustum culling
celeritas.options.chunk_fade_in_duration.name=Chunk Fade-In Duration celeritas.options.chunk_fade_in_duration.name=Chunk Fade-In Duration
celeritas.options.chunk_fade_in_duration.value=%s ms celeritas.options.chunk_fade_in_duration.value=%s ms
celeritas.options.chunk_fade_in_duration.tooltip=Controls how long it takes for newly loaded chunks to fully appear. Longer durations create a smoother transition between unloaded and loaded chunks, reducing visual popping, but may make distant terrain appear to 'fade in' more slowly. celeritas.options.chunk_fade_in_duration.tooltip=Controls how long it takes for newly loaded chunks to fully appear. Longer durations create a smoother transition between unloaded and loaded chunks, reducing visual popping, but may make distant terrain appear to 'fade in' more slowly.
celeritas.options.raster_occlusion_culling.name=Rasterized Occlusion Culling
celeritas.options.raster_occlusion_culling.tooltip=Rasterizes nearby terrain into a small software coverage buffer and uses it to skip chunks hidden behind solid terrain, such as a valley behind a hill. This can substantially reduce the amount of terrain drawn, but costs extra CPU time each frame, so it helps most when the GPU is the bottleneck.\n\nChanging this rebuilds all chunks.
sodium.option_impact.low=Low sodium.option_impact.low=Low
sodium.option_impact.medium=Medium sodium.option_impact.medium=Medium
sodium.option_impact.high=High sodium.option_impact.high=High
@@ -44,6 +44,11 @@ public class ArchaicRenderSectionManager extends RenderSectionManager {
return true; return true;
} }
@Override
protected boolean useRasterOcclusionCulling() {
return false;
}
@Override @Override
protected boolean useFogOcclusion() { protected boolean useFogOcclusion() {
return true; return true;
@@ -80,7 +85,8 @@ public class ArchaicRenderSectionManager extends RenderSectionManager {
ChunkRenderContext context = new ChunkRenderContext(new SectionPos(render.getChunkX(), render.getChunkY(), render.getChunkZ())); ChunkRenderContext context = new ChunkRenderContext(new SectionPos(render.getChunkX(), render.getChunkY(), render.getChunkZ()));
return new ChunkBuilderMeshingTask(render, context, frame, this.cameraPosition); return new ChunkBuilderMeshingTask(render, context, frame, this.cameraPosition,
this.useRasterOcclusionCulling());
} }
@Override @Override
@@ -43,6 +43,7 @@ public class ChunkBuilderMeshingTask extends ChunkBuilderTask<ChunkBuildOutput>
private final int buildTime; private final int buildTime;
private final Vector3d camera; private final Vector3d camera;
private final ChunkRenderContext renderContext; private final ChunkRenderContext renderContext;
private final boolean rasterOcclusion;
private static final MethodHandle RENDER_PASS_HANDLE; private static final MethodHandle RENDER_PASS_HANDLE;
@@ -64,11 +65,13 @@ public class ChunkBuilderMeshingTask extends ChunkBuilderTask<ChunkBuildOutput>
} }
} }
public ChunkBuilderMeshingTask(RenderSection render, ChunkRenderContext context, int time, Vector3d camera) { public ChunkBuilderMeshingTask(RenderSection render, ChunkRenderContext context, int time, Vector3d camera,
boolean rasterOcclusion) {
this.render = render; this.render = render;
this.buildTime = time; this.buildTime = time;
this.camera = camera; this.camera = camera;
this.renderContext = context; this.renderContext = context;
this.rasterOcclusion = rasterOcclusion;
} }
@Override @Override
@@ -163,6 +166,10 @@ public class ChunkBuilderMeshingTask extends ChunkBuilderTask<ChunkBuildOutput>
renderData.hasBlockGeometry = true; renderData.hasBlockGeometry = true;
} }
if (this.rasterOcclusion) {
renderData.occluderBoxes = occluder.computeOccluderBoxes();
}
renderData.visibilityData = occluder.computeVisibilityEncoding(); renderData.visibilityData = occluder.computeVisibilityEncoding();
return new ChunkBuildOutput(this.render, renderData, meshes, this.buildTime); return new ChunkBuildOutput(this.render, renderData, meshes, this.buildTime);
@@ -112,7 +112,8 @@ public class ModernRenderSectionManager extends RenderSectionManager {
return null; return null;
} }
return new ChunkBuilderMeshingTask(render, context, frame, this.cameraPosition); return new ChunkBuilderMeshingTask(render, context, frame, this.cameraPosition,
this.useRasterOcclusionCulling());
} }
@Override @Override
@@ -126,6 +127,11 @@ public class ModernRenderSectionManager extends RenderSectionManager {
return new GenericSectionSpriteTicker<>(SpriteUtil::markSpriteActive); return new GenericSectionSpriteTicker<>(SpriteUtil::markSpriteActive);
} }
@Override
protected boolean useRasterOcclusionCulling() {
return Celeritas.options().performance.useRasterOcclusionCulling;
}
@Override @Override
protected boolean useFogOcclusion() { protected boolean useFogOcclusion() {
// TODO: does *every* shaderpack really disable fog? // TODO: does *every* shaderpack really disable fog?
@@ -11,17 +11,15 @@ import net.minecraft.world.level.block.AirBlock;
import org.embeddedt.embeddium.api.render.chunk.SectionInfoBuilder; import org.embeddedt.embeddium.api.render.chunk.SectionInfoBuilder;
import org.embeddedt.embeddium.api.render.texture.SpriteUtil; import org.embeddedt.embeddium.api.render.texture.SpriteUtil;
import org.embeddedt.embeddium.impl.modern.render.chunk.compile.ModernChunkBuildContext; import org.embeddedt.embeddium.impl.modern.render.chunk.compile.ModernChunkBuildContext;
import org.embeddedt.embeddium.impl.modern.render.chunk.occlusion.ModernGraphDirection;
import org.embeddedt.embeddium.impl.render.chunk.RenderSection; import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
import org.embeddedt.embeddium.impl.render.chunk.compile.*; import org.embeddedt.embeddium.impl.render.chunk.compile.*;
import org.embeddedt.embeddium.impl.modern.render.chunk.compile.pipeline.BlockRenderCache; import org.embeddedt.embeddium.impl.modern.render.chunk.compile.pipeline.BlockRenderCache;
import org.embeddedt.embeddium.impl.modern.render.chunk.compile.pipeline.BlockRenderContext; import org.embeddedt.embeddium.impl.modern.render.chunk.compile.pipeline.BlockRenderContext;
import org.embeddedt.embeddium.impl.modern.render.chunk.compile.pipeline.GeometryCategory; import org.embeddedt.embeddium.impl.modern.render.chunk.compile.pipeline.GeometryCategory;
import org.embeddedt.embeddium.impl.render.chunk.compile.tasks.ChunkBuilderTask; import org.embeddedt.embeddium.impl.render.chunk.compile.tasks.ChunkBuilderTask;
import org.embeddedt.embeddium.impl.render.chunk.data.BuiltRenderSectionData;
import org.embeddedt.embeddium.impl.render.chunk.data.BuiltSectionMeshParts; import org.embeddedt.embeddium.impl.render.chunk.data.BuiltSectionMeshParts;
import org.embeddedt.embeddium.impl.render.chunk.data.MinecraftBuiltRenderSectionData; import org.embeddedt.embeddium.impl.render.chunk.data.MinecraftBuiltRenderSectionData;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.VisibilityEncoding; import org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionVisibilityBuilder;
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
import org.embeddedt.embeddium.impl.util.WorldUtil; import org.embeddedt.embeddium.impl.util.WorldUtil;
import org.embeddedt.embeddium.impl.util.task.CancellationToken; import org.embeddedt.embeddium.impl.util.task.CancellationToken;
@@ -32,7 +30,6 @@ import net.minecraft.CrashReportCategory;
import net.minecraft.ReportedException; import net.minecraft.ReportedException;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; import net.minecraft.client.renderer.blockentity.BlockEntityRenderer;
import net.minecraft.client.renderer.chunk.VisGraph;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.world.level.block.RenderShape; import net.minecraft.world.level.block.RenderShape;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
@@ -66,20 +63,23 @@ public class ChunkBuilderMeshingTask extends ChunkBuilderTask<ChunkBuildOutput>
private final int buildTime; private final int buildTime;
private final Vector3d camera; private final Vector3d camera;
private final boolean rasterOcclusion;
public ChunkBuilderMeshingTask(RenderSection render, ChunkRenderContext renderContext, int time, Vector3d camera) { public ChunkBuilderMeshingTask(RenderSection render, ChunkRenderContext renderContext, int time, Vector3d camera,
boolean rasterOcclusion) {
this.render = render; this.render = render;
this.renderContext = renderContext; this.renderContext = renderContext;
this.buildTime = time; this.buildTime = time;
this.camera = camera; this.camera = camera;
this.rasterOcclusion = rasterOcclusion;
} }
@Override @Override
public ChunkBuildOutput execute(ChunkBuildContext jobContext, CancellationToken cancellationToken) { public ChunkBuildOutput execute(ChunkBuildContext jobContext, CancellationToken cancellationToken) {
ModernChunkBuildContext buildContext = (ModernChunkBuildContext)jobContext; ModernChunkBuildContext buildContext = (ModernChunkBuildContext)jobContext;
MinecraftBuiltRenderSectionData<TextureAtlasSprite, BlockEntity> renderData = new MinecraftBuiltRenderSectionData<>(); MinecraftBuiltRenderSectionData<TextureAtlasSprite, BlockEntity> renderData = new MinecraftBuiltRenderSectionData<>();
VisGraph occluder = new VisGraph(); SectionVisibilityBuilder occluder = new SectionVisibilityBuilder();
ChunkBuildBuffers buffers = buildContext.buffers; ChunkBuildBuffers buffers = buildContext.buffers;
buffers.init(renderData, this.render.getSectionIndex()); buffers.init(renderData, this.render.getSectionIndex());
@@ -132,6 +132,10 @@ public class ChunkBuilderMeshingTask extends ChunkBuilderTask<ChunkBuildOutput>
blockPos.set(x, y, z); blockPos.set(x, y, z);
modelOffset.set(x & 15, y & 15, z & 15); modelOffset.set(x & 15, y & 15, z & 15);
if (this.rasterOcclusion) {
occluder.markRenderable(x, y, z);
}
//? if shaders && >=1.17 { //? if shaders && >=1.17 {
if (voxelizingLight && blockState.getBlock() instanceof net.minecraft.world.level.block.LightBlock) { if (voxelizingLight && blockState.getBlock() instanceof net.minecraft.world.level.block.LightBlock) {
cache.getSpecialBlockRenderer().voxelizeLightBlock(blockPos, blockState, buffers); cache.getSpecialBlockRenderer().voxelizeLightBlock(blockPos, blockState, buffers);
@@ -223,7 +227,7 @@ public class ChunkBuilderMeshingTask extends ChunkBuilderTask<ChunkBuildOutput>
} }
if (blockState.isSolidRender(/*? if <1.21.11 {*/ slice, blockPos /*?}*/)) { if (blockState.isSolidRender(/*? if <1.21.11 {*/ slice, blockPos /*?}*/)) {
occluder.setOpaque(blockPos); occluder.markOpaque(x, y, z);
} }
} }
} }
@@ -244,18 +248,17 @@ public class ChunkBuilderMeshingTask extends ChunkBuilderTask<ChunkBuildOutput>
renderData.hasBlockGeometry = true; renderData.hasBlockGeometry = true;
} }
encodeVisibilityData(occluder, renderData); if (this.rasterOcclusion) {
renderData.occluderBoxes = occluder.computeOccluderBoxes();
}
renderData.visibilityData = occluder.computeVisibilityEncoding();
postSectionDataBuiltEvent(renderData); postSectionDataBuiltEvent(renderData);
return new ChunkBuildOutput(this.render, renderData, meshes, this.buildTime); return new ChunkBuildOutput(this.render, renderData, meshes, this.buildTime);
} }
private static void encodeVisibilityData(VisGraph occluder, BuiltRenderSectionData renderData) {
var data = occluder.resolve();
renderData.visibilityData = VisibilityEncoding.encode((from, to) -> data.visibilityBetween(ModernGraphDirection.toEnum(from), ModernGraphDirection.toEnum(to)));
}
private static void postSectionDataBuiltEvent(MinecraftBuiltRenderSectionData<TextureAtlasSprite, BlockEntity> renderData) { private static void postSectionDataBuiltEvent(MinecraftBuiltRenderSectionData<TextureAtlasSprite, BlockEntity> renderData) {
ChunkDataBuiltEvent.BUS.post(new ChunkDataBuiltEvent(new SectionInfoBuilder() { ChunkDataBuiltEvent.BUS.post(new ChunkDataBuiltEvent(new SectionInfoBuilder() {
@Override @Override
@@ -1,22 +0,0 @@
package org.embeddedt.embeddium.impl.modern.render.chunk.occlusion;
import net.minecraft.core.Direction;
import static org.embeddedt.embeddium.impl.render.chunk.occlusion.GraphDirection.*;
public class ModernGraphDirection {
private static final Direction[] ENUMS;
static {
ENUMS = new Direction[COUNT];
ENUMS[DOWN] = Direction.DOWN;
ENUMS[UP] = Direction.UP;
ENUMS[NORTH] = Direction.NORTH;
ENUMS[SOUTH] = Direction.SOUTH;
ENUMS[WEST] = Direction.WEST;
ENUMS[EAST] = Direction.EAST;
}
public static Direction toEnum(int direction) {
return ENUMS[direction];
}
}
@@ -56,7 +56,11 @@ public class FrustumMixin implements ViewportProvider {
@Override @Override
public Viewport sodium$createViewport() { public Viewport sodium$createViewport() {
return new Viewport(new SimpleFrustum(this.intersection), new Vector3d(this.camX, this.camY, this.camZ)); //? if >=1.20 {
return new Viewport(new SimpleFrustum(this.intersection), new Vector3d(this.camX, this.camY, this.camZ), this.matrix);
//?} else {
/*return new Viewport(new SimpleFrustum(this.intersection), new Vector3d(this.camX, this.camY, this.camZ));
*///?}
} }
//? if <1.20 { //? if <1.20 {
@@ -17,5 +17,7 @@
"celeritas.options.async_graph_search.tooltip": "Performs occlusion/frustum culling asynchronously, up to one frame behind the current camera position. This can improve frametimes, particularly at higher render distances, but at the cost of chunks popping into view if the camera is turned too aggressively.", "celeritas.options.async_graph_search.tooltip": "Performs occlusion/frustum culling asynchronously, up to one frame behind the current camera position. This can improve frametimes, particularly at higher render distances, but at the cost of chunks popping into view if the camera is turned too aggressively.",
"celeritas.options.chunk_fade_in_duration.name": "Chunk Fade-In Duration", "celeritas.options.chunk_fade_in_duration.name": "Chunk Fade-In Duration",
"celeritas.options.chunk_fade_in_duration.value": "%s ms", "celeritas.options.chunk_fade_in_duration.value": "%s ms",
"celeritas.options.chunk_fade_in_duration.tooltip": "Controls how long it takes for newly loaded chunks to fully appear. Longer durations create a smoother transition between unloaded and loaded chunks, reducing visual popping, but may make distant terrain appear to 'fade in' more slowly." "celeritas.options.chunk_fade_in_duration.tooltip": "Controls how long it takes for newly loaded chunks to fully appear. Longer durations create a smoother transition between unloaded and loaded chunks, reducing visual popping, but may make distant terrain appear to 'fade in' more slowly.",
"celeritas.options.raster_occlusion_culling.name": "Rasterized Occlusion Culling",
"celeritas.options.raster_occlusion_culling.tooltip": "Rasterizes nearby terrain into a small software coverage buffer and uses it to skip chunks hidden behind solid terrain, such as a valley behind a hill. This can substantially reduce the amount of terrain drawn, but costs extra CPU time each frame, so it helps most when the GPU is the bottleneck.\n\nChanging this rebuilds all chunks."
} }
@@ -59,6 +59,11 @@ public class PrimitiveRenderSectionManager extends RenderSectionManager {
return true; return true;
} }
@Override
protected boolean useRasterOcclusionCulling() {
return false;
}
@Override @Override
protected boolean useFogOcclusion() { protected boolean useFogOcclusion() {
return true; return true;