Merge pull request #243 from rdbtCVS/perf/visibility-shortcuts-20261014
perf(mesher): short-circuit section visibility flood fills
This commit is contained in:
@@ -78,17 +78,30 @@ impl Default for SectionMesh {
|
||||
pub const ALL_VISIBLE: u64 = (1 << 36) - 1;
|
||||
/// VisGraph.resolve: flood fill non-opaque cells and connect the faces each region touches.
|
||||
fn visibility(pad: &Padded, info: &[Info]) -> u64 {
|
||||
let mut seen = vec![false; 4096];
|
||||
// Opaque cells are already visited: resolve each state's opacity once,
|
||||
// then reuse this map for the flood fill and the uniform-section shortcuts.
|
||||
let mut seen = [false; 4096];
|
||||
let mut opaque_count = 0;
|
||||
for y in 0..16 {
|
||||
for z in 0..16 {
|
||||
let row = pi(0, y, z);
|
||||
for x in 0..16 {
|
||||
let opaque = info[pad.blocks[row + x] as usize].solid;
|
||||
seen[(y as usize) << 8 | (z as usize) << 4 | x] = opaque;
|
||||
opaque_count += usize::from(opaque);
|
||||
}
|
||||
}
|
||||
}
|
||||
if opaque_count == 0 {
|
||||
return ALL_VISIBLE;
|
||||
}
|
||||
if opaque_count == 4096 {
|
||||
return 0;
|
||||
}
|
||||
let mut result = 0u64;
|
||||
let opaque = |x: i32, y: i32, z: i32| info[pad.blocks[pi(x, y, z)] as usize].solid;
|
||||
let mut stack = Vec::new();
|
||||
for start in 0..4096usize {
|
||||
let (x, y, z) = (
|
||||
(start & 15) as i32,
|
||||
(start >> 8) as i32,
|
||||
((start >> 4) & 15) as i32,
|
||||
);
|
||||
if seen[start] || opaque(x, y, z) {
|
||||
if seen[start] {
|
||||
continue;
|
||||
}
|
||||
let mut faces = 0u8;
|
||||
@@ -114,6 +127,11 @@ fn visibility(pad: &Padded, info: &[Info]) -> u64 {
|
||||
if x == 15 {
|
||||
faces |= 1 << 5;
|
||||
}
|
||||
// A single connected region touching all six faces sets every
|
||||
// pair (including the diagonal); unvisited cavities cannot add more.
|
||||
if faces == 0b11_1111 {
|
||||
return ALL_VISIBLE;
|
||||
}
|
||||
for (dx, dy, dz) in [
|
||||
(1, 0, 0),
|
||||
(-1, 0, 0),
|
||||
@@ -127,7 +145,7 @@ fn visibility(pad: &Padded, info: &[Info]) -> u64 {
|
||||
continue;
|
||||
}
|
||||
let n = (ny << 8 | nz << 4 | nx) as usize;
|
||||
if !seen[n] && !opaque(nx, ny, nz) {
|
||||
if !seen[n] {
|
||||
seen[n] = true;
|
||||
stack.push(n);
|
||||
}
|
||||
@@ -142,9 +160,14 @@ fn visibility(pad: &Padded, info: &[Info]) -> u64 {
|
||||
}
|
||||
}
|
||||
}
|
||||
if result == ALL_VISIBLE {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod visibility_tests;
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Tint {
|
||||
None,
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
//! Exact pre-optimization reference, correctness fixtures, and opt-in benchmark.
|
||||
use super::*;
|
||||
|
||||
fn reference(pad: &Padded, info: &[Info]) -> u64 {
|
||||
let mut seen = vec![false; 4096];
|
||||
let mut result = 0u64;
|
||||
let opaque = |x: i32, y: i32, z: i32| info[pad.blocks[pi(x, y, z)] as usize].solid;
|
||||
let mut stack = Vec::new();
|
||||
for start in 0..4096usize {
|
||||
let (x, y, z) = (
|
||||
(start & 15) as i32,
|
||||
(start >> 8) as i32,
|
||||
((start >> 4) & 15) as i32,
|
||||
);
|
||||
if seen[start] || opaque(x, y, z) {
|
||||
continue;
|
||||
}
|
||||
let mut faces = 0u8;
|
||||
seen[start] = true;
|
||||
stack.push(start);
|
||||
while let Some(c) = stack.pop() {
|
||||
let (x, y, z) = ((c & 15) as i32, (c >> 8) as i32, ((c >> 4) & 15) as i32);
|
||||
if y == 0 {
|
||||
faces |= 1 << 0;
|
||||
}
|
||||
if y == 15 {
|
||||
faces |= 1 << 1;
|
||||
}
|
||||
if z == 0 {
|
||||
faces |= 1 << 2;
|
||||
}
|
||||
if z == 15 {
|
||||
faces |= 1 << 3;
|
||||
}
|
||||
if x == 0 {
|
||||
faces |= 1 << 4;
|
||||
}
|
||||
if x == 15 {
|
||||
faces |= 1 << 5;
|
||||
}
|
||||
for (dx, dy, dz) in [
|
||||
(1, 0, 0),
|
||||
(-1, 0, 0),
|
||||
(0, 1, 0),
|
||||
(0, -1, 0),
|
||||
(0, 0, 1),
|
||||
(0, 0, -1),
|
||||
] {
|
||||
let (nx, ny, nz) = (x + dx, y + dy, z + dz);
|
||||
if !(0..16).contains(&nx) || !(0..16).contains(&ny) || !(0..16).contains(&nz) {
|
||||
continue;
|
||||
}
|
||||
let n = (ny << 8 | nz << 4 | nx) as usize;
|
||||
if !seen[n] && !opaque(nx, ny, nz) {
|
||||
seen[n] = true;
|
||||
stack.push(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
for a in 0..6 {
|
||||
if faces & (1 << a) != 0 {
|
||||
for b in 0..6 {
|
||||
if faces & (1 << b) != 0 {
|
||||
result |= 1 << (a * 6 + b);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn info(solid: bool) -> Info {
|
||||
Info {
|
||||
solid,
|
||||
full: false,
|
||||
permeable: false,
|
||||
shade: 1.0,
|
||||
emission: 0,
|
||||
emissive: false,
|
||||
fluid: FluidState::EMPTY,
|
||||
model: false,
|
||||
block_entity: false,
|
||||
tints: [Tint::None; 2],
|
||||
tint_count: 0,
|
||||
offset: None,
|
||||
legacy_solid: false,
|
||||
overlay: false,
|
||||
leaves: false,
|
||||
blocks_flow: false,
|
||||
ice: false,
|
||||
sturdy: 0,
|
||||
face: [0; 6],
|
||||
cover: [0.0; 6],
|
||||
}
|
||||
}
|
||||
|
||||
fn fixture(mut opaque: impl FnMut(i32, i32, i32) -> bool) -> Padded {
|
||||
// Multiple opaque and non-opaque state IDs, plus an opaque padding border.
|
||||
let mut pad = Padded {
|
||||
blocks: vec![1; P * P * P],
|
||||
light: Vec::new(),
|
||||
};
|
||||
for y in 0..16 {
|
||||
for z in 0..16 {
|
||||
for x in 0..16 {
|
||||
pad.blocks[pi(x, y, z)] = u16::from(opaque(x, y, z)) + 2 * ((x + y + z) as u16 & 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
pad
|
||||
}
|
||||
|
||||
fn random(seed: &mut u64) -> u64 {
|
||||
*seed ^= *seed << 13;
|
||||
*seed ^= *seed >> 7;
|
||||
*seed ^= *seed << 17;
|
||||
*seed
|
||||
}
|
||||
|
||||
fn cases() -> Vec<(&'static str, Padded)> {
|
||||
let mut cases = vec![
|
||||
("open", fixture(|_, _, _| false)),
|
||||
("closed", fixture(|_, _, _| true)),
|
||||
("terrain_half", fixture(|_, y, _| y < 8)),
|
||||
("dividing_wall", fixture(|x, _, _| x == 8)),
|
||||
(
|
||||
"sealed_cavity",
|
||||
fixture(|x, y, z| [x, y, z].iter().any(|&v| v == 0 || v == 15)),
|
||||
),
|
||||
(
|
||||
"disconnected_all_pairs",
|
||||
fixture(|x, y, z| {
|
||||
!((x == 8 && z == 8)
|
||||
|| ((y == 0 || y == 15) && !((7..=9).contains(&x) && (7..=9).contains(&z))))
|
||||
}),
|
||||
),
|
||||
("checkerboard", fixture(|x, y, z| (x + y + z) % 2 == 0)),
|
||||
(
|
||||
"six_face_tunnel",
|
||||
fixture(|x, y, z| [x, y, z].iter().filter(|&&v| v == 8).count() < 2),
|
||||
),
|
||||
(
|
||||
"open_with_cavity",
|
||||
fixture(|x, y, z| {
|
||||
[x, y, z].iter().all(|&v| (4..=11).contains(&v))
|
||||
&& [x, y, z].iter().any(|&v| v == 4 || v == 11)
|
||||
}),
|
||||
),
|
||||
];
|
||||
for (name, percent) in [
|
||||
("opaque_1pct", 1),
|
||||
("opaque_25pct", 25),
|
||||
("opaque_50pct", 50),
|
||||
("opaque_75pct", 75),
|
||||
("opaque_99pct", 99),
|
||||
] {
|
||||
let mut seed = 0x1234_5678_9abc_def0;
|
||||
cases.push((name, fixture(|_, _, _| random(&mut seed) % 100 < percent)));
|
||||
}
|
||||
cases
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visibility_matches_reference() {
|
||||
let info = [info(false), info(true), info(false), info(true)];
|
||||
for (name, pad) in cases() {
|
||||
assert_eq!(visibility(&pad, &info), reference(&pad, &info), "{name}");
|
||||
}
|
||||
// All 256 open/closed octant combinations, including disconnected regions.
|
||||
for mask in 0..256u16 {
|
||||
let pad = fixture(|x, y, z| mask & (1 << ((x / 8) + 2 * (z / 8) + 4 * (y / 8))) != 0);
|
||||
assert_eq!(
|
||||
visibility(&pad, &info),
|
||||
reference(&pad, &info),
|
||||
"octants {mask}"
|
||||
);
|
||||
}
|
||||
// Randomized distributions include percolating regions and isolated cells.
|
||||
let mut seed = 0x8765_4321_abcd_ef01;
|
||||
for percent in [1, 10, 25, 50, 75, 90, 99] {
|
||||
for _ in 0..32 {
|
||||
let pad = fixture(|_, _, _| random(&mut seed) % 100 < percent);
|
||||
assert_eq!(visibility(&pad, &info), reference(&pad, &info));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visibility_preserves_every_face_pair() {
|
||||
let info = [info(false), info(true), info(false), info(true)];
|
||||
// Each subset of six arms is one connected cavity. Its exact flags are
|
||||
// the Cartesian product of the touched faces, including self-visibility.
|
||||
for mask in 0..64u8 {
|
||||
let pad = fixture(|x, y, z| {
|
||||
let arm = (x == 8
|
||||
&& z == 8
|
||||
&& ((y <= 8 && mask & 1 != 0) || (y >= 8 && mask & 2 != 0)))
|
||||
|| (x == 8 && y == 8 && ((z <= 8 && mask & 4 != 0) || (z >= 8 && mask & 8 != 0)))
|
||||
|| (y == 8 && z == 8 && ((x <= 8 && mask & 16 != 0) || (x >= 8 && mask & 32 != 0)));
|
||||
!(arm || (x == 8 && y == 8 && z == 8))
|
||||
});
|
||||
let mut expected = 0;
|
||||
for a in 0..6 {
|
||||
for b in 0..6 {
|
||||
if mask & (1 << a) != 0 && mask & (1 << b) != 0 {
|
||||
expected |= 1 << (6 * a + b);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(visibility(&pad, &info), expected, "arms {mask}");
|
||||
assert_eq!(reference(&pad, &info), expected);
|
||||
}
|
||||
assert_eq!(visibility(&fixture(|_, _, _| false), &info), ALL_VISIBLE);
|
||||
assert_eq!(visibility(&fixture(|_, _, _| true), &info), 0);
|
||||
// Bottom and top sheets each touch five faces; a separate vertical tube
|
||||
// supplies Down <-> Up. Their union is all flags, with no six-face region.
|
||||
let (_, pad) = cases()
|
||||
.into_iter()
|
||||
.find(|(name, _)| *name == "disconnected_all_pairs")
|
||||
.unwrap();
|
||||
assert_eq!(visibility(&pad, &info), ALL_VISIBLE);
|
||||
assert_eq!(reference(&pad, &info), ALL_VISIBLE);
|
||||
// Two disconnected corner cells must never connect opposite faces.
|
||||
let pad = fixture(|x, y, z| !((x == 0 && y == 0 && z == 0) || (x == 15 && y == 15 && z == 15)));
|
||||
let flags = visibility(&pad, &info);
|
||||
assert_eq!(flags, reference(&pad, &info));
|
||||
assert_eq!(flags & (1 << 1), 0); // Down -> Up
|
||||
assert_ne!(flags & 1, 0); // Down -> Down
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "opt-in optimized microbenchmark; see docs/visibility-benchmark.md"]
|
||||
fn visibility_benchmark() {
|
||||
use std::{hint::black_box, time::Instant};
|
||||
const WARMUP: usize = 200;
|
||||
const ITERATIONS: usize = 1000;
|
||||
const SAMPLES: usize = 11;
|
||||
let info = [info(false), info(true), info(false), info(true)];
|
||||
println!(
|
||||
"case,opaque_cells,before_ns,after_ns,speedup; warmup={WARMUP}, iterations={ITERATIONS}, samples={SAMPLES}"
|
||||
);
|
||||
for (name, pad) in cases() {
|
||||
assert_eq!(visibility(&pad, &info), reference(&pad, &info), "{name}");
|
||||
let opaque = (0..4096)
|
||||
.filter(|&i| info[pad.blocks[pi(i & 15, i >> 8, (i >> 4) & 15)] as usize].solid)
|
||||
.count();
|
||||
for _ in 0..WARMUP {
|
||||
black_box(reference(black_box(&pad), black_box(&info)));
|
||||
black_box(visibility(black_box(&pad), black_box(&info)));
|
||||
}
|
||||
let measure = |f: fn(&Padded, &[Info]) -> u64| {
|
||||
let start = Instant::now();
|
||||
for _ in 0..ITERATIONS {
|
||||
black_box(f(black_box(&pad), black_box(&info)));
|
||||
}
|
||||
start.elapsed().as_nanos() as f64 / ITERATIONS as f64
|
||||
};
|
||||
let mut before = Vec::new();
|
||||
let mut after = Vec::new();
|
||||
for sample in 0..SAMPLES {
|
||||
// Alternate order to reduce drift bias.
|
||||
if sample % 2 == 0 {
|
||||
before.push(measure(reference));
|
||||
after.push(measure(visibility));
|
||||
} else {
|
||||
after.push(measure(visibility));
|
||||
before.push(measure(reference));
|
||||
}
|
||||
}
|
||||
before.sort_by(f64::total_cmp);
|
||||
after.sort_by(f64::total_cmp);
|
||||
let (before, after) = (before[SAMPLES / 2], after[SAMPLES / 2]);
|
||||
println!(
|
||||
"{name},{opaque},{before:.1},{after:.1},{:.2}x",
|
||||
before / after
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
# Section visibility shortcuts
|
||||
|
||||
The helper in `crates/horizon-client/src/mesher.rs` returns the same 36 face-pair bits
|
||||
as the original flood fill. It initializes its visited map with opaque cells,
|
||||
resolving state opacity once per cell, and returns directly for fully open or
|
||||
fully closed sections. During traversal, touching all six faces ends the fill;
|
||||
so does accumulating all pairs across separate completed regions.
|
||||
|
||||
The visited map uses 4 KiB of worker stack instead of a 4 KiB heap allocation.
|
||||
Mixed sections still use the original growable traversal stack. There is no
|
||||
persistent cache or additional per-section storage. Every call scans all 4096
|
||||
interior cells before traversal; cases that previously visited very few open
|
||||
cells may benefit less, and their measurements are included below.
|
||||
|
||||
## Reproduction
|
||||
|
||||
From the repository root:
|
||||
|
||||
```sh
|
||||
export CARGO_INCREMENTAL=0
|
||||
export CARGO_TARGET_DIR=/home/bob/Documents/horizon/target
|
||||
cargo test -p horizon-client --lib --profile fast mesher::visibility_tests
|
||||
cargo test -p horizon-client --lib --profile fast mesher::visibility_tests::visibility_benchmark -- --ignored --exact --nocapture --test-threads=1
|
||||
```
|
||||
|
||||
The ignored test calls the actual production helper with `Padded` sections and
|
||||
full-layout `Info` entries. Its reference is the exact helper from main commit
|
||||
`73a019967e9665c6b96332988c13cb66679d8477`, with only its name changed. Both receive
|
||||
identical inputs, validate equal outputs, and use `black_box` for inputs and
|
||||
results. Each case warms up each implementation 200 times, then runs 11 samples
|
||||
of 1000 calls each, alternating measurement order. Times are median nanoseconds
|
||||
per section; padding construction and state-table construction are excluded.
|
||||
|
||||
No prepared section/assets fixtures were found in the bounded project/cache
|
||||
search. These are deterministic synthetic, production-sized 16×16×16 sections
|
||||
with a two-block padding border and four state IDs (two of each opacity).
|
||||
They cover terrain, isolated cells, sealed and exposed cavities, narrow tunnels,
|
||||
disconnected components, and seeded random opacity densities. Independent tests
|
||||
also cover all 64 face subsets, all 256 octant masks, and 224 randomized sections.
|
||||
|
||||
The mesher already skips uniform all-air sections before calling this helper.
|
||||
The open case describes other fully non-opaque sections and the helper itself.
|
||||
These timings do not establish overall meshing, startup, or FPS improvements.
|
||||
|
||||
## Measurements
|
||||
|
||||
Measured 2026-10-15 on AMD Ryzen 5 5600X (6 cores / 12 threads), Linux
|
||||
7.2.8-zen1-2-zen, x86_64, rustc 1.99.0 (b940084d7, LLVM 23.1.1). Cargo `fast`
|
||||
uses opt-level 3, no LTO, 16 codegen units; incremental compilation was disabled.
|
||||
The benchmark runs one test thread. Shared-target Cargo builds were serialized
|
||||
with the benchmark by Cargo's build-directory lock.
|
||||
|
||||
| Case | Opaque cells | Before ns | After ns | Speedup |
|
||||
| --- | ---: | ---: | ---: | ---: |
|
||||
| Fully open | 0 | 27,019.3 | 2,691.6 | 10.04× |
|
||||
| Fully closed | 4,096 | 4,823.5 | 2,788.7 | 1.73× |
|
||||
| Terrain lower half | 2,048 | 15,274.3 | 14,258.1 | 1.07× |
|
||||
| Dividing wall | 256 | 25,006.6 | 24,107.5 | 1.04× |
|
||||
| Sealed cavity | 1,352 | 19,953.7 | 17,591.7 | 1.13× |
|
||||
| Disconnected all pairs | 3,586 | 7,915.9 | 6,301.4 | 1.26× |
|
||||
| Checkerboard | 2,048 | 26,846.5 | 18,697.4 | 1.44× |
|
||||
| Six-face tunnel | 4,050 | 5,236.7 | 2,972.3 | 1.76× |
|
||||
| Open with sealed cavity | 296 | 26,140.3 | 9,688.8 | 2.70× |
|
||||
| Random 1% opaque | 38 | 27,657.9 | 9,061.1 | 3.05× |
|
||||
| Random 25% opaque | 1,043 | 24,931.4 | 7,722.5 | 3.23× |
|
||||
| Random 50% opaque | 2,050 | 19,811.5 | 5,754.7 | 3.44× |
|
||||
| Random 75% opaque | 3,053 | 13,598.2 | 10,474.1 | 1.30× |
|
||||
| Random 99% opaque | 4,064 | 5,330.7 | 4,023.7 | 1.32× |
|
||||
|
||||
No case regressed in this run; the 4–7% gains in wall/terrain cases are small
|
||||
and more susceptible to timing noise. No distribution-weighted aggregate is
|
||||
reported because real-world section frequencies were unavailable.
|
||||
|
||||
Validation passed: the two focused correctness tests, the opt-in benchmark
|
||||
(with output equality assertions), `cargo fmt --all -- --check`, and
|
||||
`cargo clippy -p horizon-client --lib --tests --profile fast -- -D warnings`.
|
||||
The full parity suite and workspace-wide Clippy were not run.
|
||||
Reference in New Issue
Block a user