diff --git a/crates/horizon-client/examples/block_facts_bench.rs b/crates/horizon-client/examples/block_facts_bench.rs deleted file mode 100644 index f68dcf999..000000000 --- a/crates/horizon-client/examples/block_facts_bench.rs +++ /dev/null @@ -1,104 +0,0 @@ -//! Full production fact loading, including file reads, interning and temporary destruction. -//! cargo run --profile fast -p horizon-client --example block_facts_bench -- ROOT [SAMPLES] -//! Use SAMPLES=1 with an OS peak-RSS wrapper; `digest` checks all facts -//! and the shape sharing partition (including sharing between outlines and edges). -use horizon_client::blocks::BlockFacts; -use horizon_world::{DATA_VERSION, nbt::Tag, registry::BlockRegistry}; -use serde_json::Value; -use std::{ - collections::{HashMap, hash_map::DefaultHasher}, - fs, - hash::{Hash, Hasher}, - hint::black_box, - path::Path, - time::Instant, -}; -type Result = horizon_client::Result; - -fn tag(value: &Value) -> Result { - Ok(match value { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(n) => Tag::Int(i32::try_from(n.as_i64().ok_or("registry number")?)?), - Value::Array(a) => Tag::List(a.iter().map(tag).collect::>()?), - Value::Object(o) => Tag::Compound( - o.iter() - .map(|(k, v)| Ok((k.as_str().into(), tag(v)?))) - .collect::>()?, - ), - _ => return Err("registry value".into()), - }) -} -fn registry(root: &Path) -> Result { - let facts: Value = serde_json::from_slice(&fs::read(root.join("facts.json"))?)?; - Ok(BlockRegistry::from_nbt(&Tag::compound([ - ("DataVersion", Tag::Int(DATA_VERSION)), - ( - "states", - Tag::List( - facts["states"] - .as_array() - .ok_or("registry states")? - .iter() - .map(|s| tag(&s[4])) - .collect::>()?, - ), - ), - ("defaults", tag(&facts["defaults"])?), - ]))?) -} -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); - let root = Path::new( - args.first() - .ok_or("usage: block_facts_bench ROOT [SAMPLES|digest]")?, - ); - let setup = Instant::now(); - let registry = registry(root)?; - println!( - "registry_setup_ms={:.3}", - setup.elapsed().as_secs_f64() * 1000.0 - ); - if args.get(1).is_some_and(|s| s == "digest") { - let facts = BlockFacts::load(root, ®istry)?; - let mut hash = DefaultHasher::new(); - let mut shapes = HashMap::new(); - facts.air.hash(&mut hash); - for state in &facts.states { - format!("{state:?}").hash(&mut hash); - for shape in [&state.outline, &state.outline_edges] { - let next = shapes.len(); - shapes - .entry((shape.as_ptr(), shape.len())) - .or_insert(next) - .hash(&mut hash); - } - } - println!( - "states={} shared_shapes={} digest={:016x}", - facts.states.len(), - shapes.len(), - hash.finish() - ); - return Ok(()); - } - let samples: usize = args.get(1).map(|s| s.parse()).transpose()?.unwrap_or(9); - assert!(samples > 0); - // First load is reported separately; OS file caches are not forcibly evicted. - let load = || -> Result { - let start = Instant::now(); - let facts = black_box(BlockFacts::load(black_box(root), black_box(®istry))?); - let ms = start.elapsed().as_secs_f64() * 1000.0; - drop(facts); - Ok(ms) - }; - println!("first_load_ms={:.3}", load()?); - if samples > 1 { - load()?; - load()?; - let mut times = (0..samples).map(|_| load()).collect::>>()?; - println!("samples_ms={times:.3?}"); - times.sort_by(f64::total_cmp); - println!("median_ms={:.3}", times[times.len() / 2]); - } - Ok(()) -} diff --git a/crates/horizon-client/examples/chunk_bench.rs b/crates/horizon-client/examples/chunk_bench.rs deleted file mode 100644 index be619245f..000000000 --- a/crates/horizon-client/examples/chunk_bench.rs +++ /dev/null @@ -1,216 +0,0 @@ -//! Resident chunk storage benchmark: generates a block of vanilla terrain, then -//! reports the resident block/biome memory, the cost of lookups, meshing and -//! lighting on it. -//! -//! chunk_bench [--seed S] [--size N] -#![forbid(unsafe_code)] -use horizon_client::{ - assets::Assets, - biome::Biomes, - blocks::BlockFacts, - chunk::{Chunk, MIN_Y, SECTIONS}, - light::{LightTables, apply_lighting, light_chunk}, - mesher::{MeshTables, Mesher}, - models, - streaming::{ChunkGenerator, Proto}, - vanillagen::VanillaTerrain, -}; -use horizon_core::biome::BiomeZoom; -use std::{path::PathBuf, sync::Arc, time::Instant}; -type Result = std::result::Result>; - -fn main() -> Result<()> { - let args: Vec = std::env::args().skip(1).collect(); - let root = PathBuf::from(args.first().ok_or("usage: chunk_bench RESOURCES")?); - let flag = |name: &str, default: i64| -> i64 { - args.iter() - .position(|a| a == name) - .and_then(|i| args.get(i + 1)) - .and_then(|v| v.parse().ok()) - .unwrap_or(default) - }; - let (seed, size) = (flag("--seed", 12345), flag("--size", 8) as i32); - let assets = Assets::load(&root)?; - let render = assets.reload(&root)?; - let facts = BlockFacts::load(&root, assets.registry)?; - let biomes = Biomes::load(&root)?; - let tables = MeshTables::new( - &assets, - &render, - &facts, - models::load_visibility(&root, assets.registry)?, - )?; - let light = LightTables::load(&root, assets.registry, &facts)?; - let terrain = VanillaTerrain::new(&root.join("worldgen"), assets.registry, &biomes, seed)?; - let mut worker = terrain.worker(); - - // Protos for size+4 columns, decorated for the inner size+2, finished as size+2. - let started = Instant::now(); - let outer = size + 4; - let mut protos: Vec> = (0..outer * outer) - .map(|i| Some(terrain.proto(&mut worker, i % outer, i / outer))) - .collect(); - eprintln!("proto: {:.2}s", started.elapsed().as_secs_f64()); - let started = Instant::now(); - let inner = size + 2; - for z in 1..=inner { - for x in 1..=inner { - let mut region: [Proto; 9] = std::array::from_fn(|k| { - let (dx, dz) = (k as i32 % 3 - 1, k as i32 / 3 - 1); - protos[((z + dz) * outer + x + dx) as usize] - .take() - .expect("proto") - }); - terrain.decorate(&mut worker, &mut region); - for (k, p) in region.into_iter().enumerate() { - let (dx, dz) = (k as i32 % 3 - 1, k as i32 / 3 - 1); - protos[((z + dz) * outer + x + dx) as usize] = Some(p); - } - } - } - eprintln!("decorate: {:.2}s", started.elapsed().as_secs_f64()); - let started = Instant::now(); - let mut chunks: Vec = Vec::new(); - for z in 1..=inner { - for x in 1..=inner { - let proto = protos[(z * outer + x) as usize].take().expect("proto"); - let mut chunk = terrain.finish(proto); - chunk.x = x; - chunk.z = z; - chunks.push(chunk); - } - } - let finish = started.elapsed().as_secs_f64(); - println!( - "finish (proto -> resident chunk): {:.1} ms per chunk", - finish * 1e3 / chunks.len() as f64 - ); - - let chunks: Vec> = chunks.into_iter().map(Arc::new).collect(); - let at = |x: i32, z: i32| chunks[((z - 1) * inner + x - 1) as usize].clone(); - - // Light all inner-inner columns. - let started = Instant::now(); - let mut lit = Vec::new(); - for z in 2..inner { - for x in 2..inner { - let region: [[Option>; 3]; 3] = std::array::from_fn(|dz| { - std::array::from_fn(|dx| Some(at(x + dx as i32 - 1, z + dz as i32 - 1))) - }); - let borrowed = horizon_client::mesher::borrow(®ion); - lit.push(((x, z), light_chunk(&borrowed, &light, true))); - } - } - println!( - "light: {:.2} ms per column", - started.elapsed().as_secs_f64() * 1e3 / lit.len() as f64 - ); - let mut chunks: Vec = chunks.iter().map(|c| (**c).clone()).collect(); - for ((x, z), sections) in lit { - apply_lighting(&mut chunks[((z - 1) * inner + x - 1) as usize], sections); - } - let chunks: Vec> = chunks.into_iter().map(Arc::new).collect(); - let at = |x: i32, z: i32| chunks[((z - 1) * inner + x - 1) as usize].clone(); - - // Memory. - let (mut bytes, mut sections, mut uniform) = (0usize, 0usize, 0usize); - for chunk in &chunks { - bytes += chunk.heap_bytes(); - for s in &chunk.sections { - sections += 1; - uniform += usize::from(s.is_uniform(s.get(0))); - } - } - println!( - "resident: {} chunks, {} sections ({} uniform), {:.1} KiB per chunk ({:.2} MiB total)", - chunks.len(), - sections, - uniform, - bytes as f64 / 1024.0 / chunks.len() as f64, - bytes as f64 / 1048576.0 - ); - - // Meshing. - let mut mesher = Mesher { - nether_shading: false, - assets: &assets, - render: &render, - tables: &tables, - biomes: &biomes, - visibility: tables.visibility.clone(), - zoom: BiomeZoom::new(7), - blend_radius: 2, - smooth_lighting: true, - cutout_leaves: true, - cull_leaves: false, - }; - let mut best = f64::MAX; - let mut quads = 0usize; - for _ in 0..3 { - let started = Instant::now(); - let mut jobs = 0; - quads = 0; - for z in 2..inner { - for x in 2..inner { - let region: [[Option>; 3]; 3] = std::array::from_fn(|dz| { - std::array::from_fn(|dx| Some(at(x + dx as i32 - 1, z + dz as i32 - 1))) - }); - let borrowed = horizon_client::mesher::borrow(®ion); - for sy in 0..SECTIONS as i32 { - let mesh = mesher.mesh(&borrowed, sy); - quads += (mesh.solid.len() + mesh.translucent.len()) / 4; - jobs += 1; - } - } - } - best = best.min(started.elapsed().as_secs_f64() / f64::from(jobs)); - } - println!( - "mesh: {:.1} us per section ({} quads total)", - best * 1e6, - quads - ); - - // Random lookups, as collision and entity queries do. - let mut state = 0x9E37_79B9_7F4A_7C15u64; - let started = Instant::now(); - let mut sum = 0u64; - let lookups = 20_000_000u64; - for _ in 0..lookups { - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - let cx = 2 + (state % u64::from((inner - 2) as u32)) as i32; - let cz = 2 + ((state >> 8) % u64::from((inner - 2) as u32)) as i32; - let chunk = &chunks[((cz - 1) * inner + cx - 1) as usize]; - let (x, y, z) = ( - (state >> 16) as i32 & 15, - MIN_Y + ((state >> 24) % 384) as i32, - (state >> 40) as i32 & 15, - ); - sum += u64::from(chunk.get(x, y, z)); - } - println!( - "random get: {:.2} ns per lookup (checksum {sum})", - started.elapsed().as_secs_f64() * 1e9 / lookups as f64 - ); - // Coherent scan, as a column or area query does. - let started = Instant::now(); - let mut sum = 0u64; - for _ in 0..4 { - for chunk in &chunks { - for y in MIN_Y..MIN_Y + 384 { - for z in 0..16 { - for x in 0..16 { - sum += u64::from(chunk.get(x, y, z)); - } - } - } - } - } - println!( - "scan get: {:.2} ns per lookup (checksum {sum})", - started.elapsed().as_secs_f64() * 1e9 / (4.0 * chunks.len() as f64 * 98304.0) - ); - Ok(()) -} diff --git a/crates/horizon-client/examples/entity_geometry_bench.rs b/crates/horizon-client/examples/entity_geometry_bench.rs deleted file mode 100644 index 57104f58b..000000000 --- a/crates/horizon-client/examples/entity_geometry_bench.rs +++ /dev/null @@ -1,140 +0,0 @@ -//! Isolated production mob-model builder benchmark; no assets, Game, GPU or full-frame work. -//! CARGO_TARGET_DIR=/home/bob/Documents/horizon/target CARGO_INCREMENTAL=0 \ -//! cargo run --profile fast -p horizon-client --example entity_geometry_bench -use horizon_client::{ - mesher::Vertex, - mobs::{Part, Polygon, anim::Poses, render}, -}; -use std::{hint::black_box, time::Instant}; - -fn cube(name: String, position: f32) -> Part { - let polygons = (0..6) - .map(|face| { - let axis = face / 2; - let side = (face % 2) as f32; - let mut normal = [0.0; 3]; - normal[axis] = side * 2.0 - 1.0; - Polygon { - normal, - vertices: [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]].map(|uv| { - let mut vertex = [0.0; 5]; - vertex[axis] = side * 8.0; - vertex[(axis + 1) % 3] = uv[0] * 8.0; - vertex[(axis + 2) % 3] = uv[1] * 8.0; - vertex[3] = uv[0]; - vertex[4] = uv[1]; - vertex - }), - } - }) - .collect(); - Part { - name, - pose: [position, 0.0, 0.0, 0.1, 0.2, 0.0, 1.0, 1.0, 1.0], - polygons, - children: Vec::new(), - } -} - -fn build(model: &Part, poses: &Poses, count: usize, out: &mut Vec) { - for i in 0..count { - render::draw( - black_box(model), - glam::Mat4::from_translation(glam::Vec3::new((i % 32) as f32, 0.0, (i / 32) as f32)), - black_box(poses), - [0.125, 0.25, 0.5, 0.75], - 0xffc0_d0e0, - 0xf0f0, - 0, - out, - ); - } - black_box(out.as_slice()); -} - -fn measure(model: &Part, poses: &Poses, count: usize, iterations: usize, reuse: bool) -> f64 { - let mut retained = Vec::new(); - build(model, poses, count, &mut retained); // Untimed warmup. - let start = Instant::now(); - for _ in 0..iterations { - let mut out = if reuse { - std::mem::take(&mut retained) - } else { - Vec::new() - }; - out.clear(); - build(model, poses, count, &mut out); - if reuse { - retained = out; - } - } - start.elapsed().as_secs_f64() * 1e6 / iterations as f64 -} - -fn main() { - let mut model = cube("body".into(), 0.0); - model.children = (1..6).map(|i| cube(format!("part{i}"), i as f32)).collect(); - let poses = Poses::new(&model); - for count in [32, 256, 1024, 4096, 8192] { - let mut expected = Vec::new(); - build(&model, &poses, count, &mut expected); - let mut retained = Vec::new(); - build(&model, &poses, count, &mut retained); - let (pointer, capacity) = (retained.as_ptr(), retained.capacity()); - // Populated -> empty/reset -> smaller -> populated must never leave stale vertices. - for n in [0, count / 2, count, count] { - retained.clear(); - build(&model, &poses, n, &mut retained); - let mut fresh = Vec::new(); - build(&model, &poses, n, &mut fresh); - assert_eq!( - bytemuck::cast_slice::(&retained), - bytemuck::cast_slice::(&fresh) - ); - assert_eq!( - (retained.as_ptr(), retained.capacity()), - (pointer, capacity) - ); - } - assert_eq!( - bytemuck::cast_slice::(&retained), - bytemuck::cast_slice::(&expected) - ); - let iterations = (100_000 / count).clamp(40, 1000); - let mut fresh = Vec::new(); - let mut reused = Vec::new(); - let mut paired_speedups = Vec::new(); - // Alternate order, reporting medians over eleven warmed batches. - for batch in 0..11 { - let mut pair = [0.0; 2]; - for reuse in if batch % 2 == 0 { - [false, true] - } else { - [true, false] - } { - let time = measure(&model, &poses, count, iterations, reuse); - pair[usize::from(reuse)] = time; - if reuse { - reused.push(time); - } else { - fresh.push(time); - } - } - paired_speedups.push(pair[0] / pair[1]); - } - paired_speedups.sort_by(f64::total_cmp); - fresh.sort_by(f64::total_cmp); - reused.sort_by(f64::total_cmp); - println!( - "entities={count} vertices={} capacity={capacity} retained_bytes={} fresh_us={:.3} reused_us={:.3} speedup={:.3}x paired_speedup_median={:.3}x paired_speedup_range={:.3}..{:.3}x iterations={iterations} batches=11 byte_equivalence=pass pointer_capacity_reuse=pass", - retained.len(), - capacity * size_of::(), - fresh[5], - reused[5], - fresh[5] / reused[5], - paired_speedups[5], - paired_speedups[0], - paired_speedups[10] - ); - } -} diff --git a/crates/horizon-client/examples/json_readers_bench.rs b/crates/horizon-client/examples/json_readers_bench.rs deleted file mode 100644 index a9e370f0a..000000000 --- a/crates/horizon-client/examples/json_readers_bench.rs +++ /dev/null @@ -1,205 +0,0 @@ -//! Compare the exact read/deserialize sequences used by the model loaders. -//! Run with `cargo run -p horizon-client --profile fast --example json_readers_bench`. -//! Optional arguments: resource directory, repetitions (default 9). -use serde_json::{Map, Value, json}; -use std::{ - collections::BTreeMap, - fmt::Debug, - fs::{self, File}, - hint::black_box, - io::BufReader, - path::{Path, PathBuf}, - time::Instant, -}; - -type Result = horizon_client::Result; - -#[derive(Clone, Copy)] -enum Reader { - File, - Buffered, - Slice, -} -const READERS: [Reader; 3] = [Reader::File, Reader::Buffered, Reader::Slice]; - -// These match the map types and reader expressions at all three production sites. -macro_rules! reader { - ($name:ident, $map:ty) => { - fn $name(path: &Path, reader: Reader) -> Result<$map> { - Ok(match reader { - Reader::File => serde_json::from_reader(File::open(path)?)?, - Reader::Buffered => serde_json::from_reader(BufReader::new(File::open(path)?))?, - Reader::Slice => serde_json::from_slice(&fs::read(path)?)?, - }) - } - }; -} -reader!(prepare_facts, Map); -reader!(catalog_facts, BTreeMap); - -struct Fixture(PathBuf); -impl Fixture { - fn new() -> Result { - let root = - std::env::temp_dir().join(format!("horizon-json-readers-{}", std::process::id())); - fs::create_dir(&root)?; - Ok(Self(root)) - } -} -impl Drop for Fixture { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.0); - } -} - -fn fixtures(root: &Path) -> Result<()> { - let states: Vec<_> = (0..56) - .map(|i| { - json!({"facing": (["north", "east", "south", "west"][i % 4]), - "powered": if i / 4 % 2 == 0 { "false" } else { "true" }, - "age": (i / 8).to_string()}) - }) - .collect(); - let mut models = Map::new(); - let mut render = Map::new(); - for i in 0..1024 { - let name = format!("minecraft:fixture_block_{i:04}"); - models.insert( - name.clone(), - json!({ - "schema": {"facing": {"named": ["north", "east", "south", "west"]}, - "powered": {"named": ["false", "true"]}, "age": {"integer": [0, 6]}}, - "states": states - }), - ); - render.insert( - name, - json!({"rule": "never", "can_occlude": true, "bars_tag": false}), - ); - } - fs::write(root.join("model-states.json"), serde_json::to_vec(&models)?)?; - fs::write( - root.join("render-definitions.json"), - serde_json::to_vec(&render)?, - )?; - Ok(()) -} - -fn benchmark( - label: &str, - path: &Path, - repetitions: usize, - read: impl Fn(&Path, Reader) -> Result, -) -> Result<()> { - let expected = read(path, Reader::File)?; - for reader in READERS { - assert_eq!(expected, read(path, reader)?); - for _ in 0..2 { - black_box(read(black_box(path), reader)?); - } - } - drop(expected); - let mut samples: [Vec; 3] = std::array::from_fn(|_| Vec::new()); - for repetition in 0..repetitions { - // Rotate reader order to distribute drift across implementations. - for offset in 0..3 { - let index = (repetition + offset) % 3; - let start = Instant::now(); - let value = black_box(read(black_box(path), READERS[index])?); - samples[index].push(start.elapsed().as_secs_f64() * 1000.0); - drop(value); // Match the loaders: retain the parsed tree after loading. - } - } - let median: Vec<_> = samples - .iter_mut() - .map(|s| { - s.sort_by(f64::total_cmp); - s[s.len() / 2] - }) - .collect(); - println!( - "{label}: {} bytes, {repetitions} samples/reader, median ms: File={:.3}, BufReader={:.3}, read+slice={:.3}; slice speedup={:.2}x", - fs::metadata(path)?.len(), - median[0], - median[1], - median[2], - median[0] / median[2] - ); - Ok(()) -} - -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); - let fixture = if args.is_empty() { - Some(Fixture::new()?) - } else { - None - }; - let root = fixture - .as_ref() - .map(|f| f.0.clone()) - .unwrap_or_else(|| PathBuf::from(&args[0])); - if fixture.is_some() { - fixtures(&root)?; - println!( - "Generated representative fixtures: 1024 blocks, 57344 model states; warm filesystem cache." - ); - } - let repetitions = args.get(1).map(|s| s.parse()).transpose()?.unwrap_or(9); - assert!(repetitions > 0, "repetitions must be positive"); - benchmark( - "prepare model states", - &root.join("model-states.json"), - repetitions, - prepare_facts, - )?; - benchmark( - "catalog model states", - &root.join("model-states.json"), - repetitions, - catalog_facts, - )?; - benchmark( - "render definitions", - &root.join("render-definitions.json"), - repetitions, - catalog_facts, - ) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn reader_equivalence_and_errors() -> Result<()> { - let fixture = Fixture::new()?; - let path = fixture.0.join("test.json"); - fs::write(&path, br#"{"minecraft:stone":{"schema":{},"states":[{}]},"unicode":"\u2603","duplicate":1,"duplicate":2}"#)?; - let expected = prepare_facts(&path, Reader::File)?; - for reader in READERS { - assert_eq!(expected, prepare_facts(&path, reader)?); - assert_eq!( - expected.iter().collect::>(), - catalog_facts(&path, reader)?.iter().collect() - ); - } - for invalid in [b"{\"a\": ".as_slice(), b"{} trailing", b"{\"a\":\"\xff\"}"] { - fs::write(&path, invalid)?; - for reader in READERS { - let error = prepare_facts(&path, reader).unwrap_err(); - assert!(error.downcast_ref::().is_some()); - assert!(catalog_facts(&path, reader).is_err()); - } - } - fs::remove_file(&path)?; - for reader in READERS { - let error = prepare_facts(&path, reader).unwrap_err(); - assert_eq!( - error.downcast_ref::().unwrap().kind(), - std::io::ErrorKind::NotFound - ); - } - Ok(()) - } -} diff --git a/crates/horizon-client/examples/lan_flat.rs b/crates/horizon-client/examples/lan_flat.rs deleted file mode 100644 index f3dfea6b1..000000000 --- a/crates/horizon-client/examples/lan_flat.rs +++ /dev/null @@ -1,143 +0,0 @@ -//! Serve a small flat world on the LAN server without the game, for joining -//! with a real client while developing the protocol: -//! `cargo run --release --example lan_flat -- RESOURCES PORT`. -use horizon_client::{ - assets::Assets, - blocks::BlockFacts, - chunk::{Chunk, MIN_Y}, - lan::{ - Lan, - chunks::ChunkEncoder, - data::SyncData, - hub::{HostEvent, HostState, Hub, HubConfig, TickCtx}, - }, - world::World, -}; -use horizon_protocol::packets::play::Serverbound as S; -use std::{path::PathBuf, sync::Arc, time::Duration}; - -fn main() -> Result<(), Box> { - let mut args = std::env::args().skip(1); - let root = PathBuf::from(args.next().ok_or("RESOURCES PORT")?); - let port: u16 = args.next().ok_or("port")?.parse()?; - let assets = Assets::load(&root)?; - let facts = BlockFacts::load(&root, assets.registry)?; - let state = |name: &str| assets.registry.default_state(name).map_or(0, |s| s.0); - let sync = Arc::new(SyncData::load(&root)?); - let biomes: Vec = sync - .dynamic - .registries - .get("minecraft:worldgen/biome") - .map(|v| v.iter().map(|(n, _)| n.clone()).collect()) - .unwrap_or_default(); - let encoder = ChunkEncoder::new( - facts - .states - .iter() - .map(|s| (s.name.clone(), s.fluid_level > 0 || s.waterlogged)), - &sync.builtin, - &biomes, - &biomes, - ); - let (stone, dirt, grass) = ( - state("minecraft:stone"), - state("minecraft:dirt"), - state("minecraft:grass_block"), - ); - let mut world = World::new(facts.air, 0); - for cz in -8..=8 { - for cx in -8..=8 { - let mut chunk = Chunk::empty(cx, cz); - for z in 0..16 { - for x in 0..16 { - for y in MIN_Y..60 { - let v = if y == 59 { - grass - } else if y > 55 { - dirt - } else { - stone - }; - chunk.set(x, y, z, v); - } - } - } - chunk.lit = true; - world.chunks.insert((cx, cz), Arc::new(chunk)); - } - } - let lan = Lan::start(sync.clone(), port, "Flat - Example".into(), 8)?; - println!("listening on {}", lan.port); - let mut hub = Hub::new( - lan, - sync, - encoder, - HubConfig { - default_game_mode: 1, - guest_commands: true, - force_game_mode: false, - hardcore: false, - view_distance: 8, - simulation_distance: 8, - dimension: "minecraft:overworld".into(), - seed: 0, - max_players: 8, - dedicated: false, - integrated: false, - }, - ); - let mut next_entity = 100u32; - let host = HostState { - uuid: 42, - name: "Host".into(), - entity_id: 1, - position: [0.5, 60.0, 0.5], - yaw: 0.0, - pitch: 0.0, - head_yaw: 0.0, - on_ground: true, - game_mode: 1, - sneaking: false, - sprinting: false, - equipment: Default::default(), - health: 20.0, - attributes: Vec::new(), - bed: None, - living_flags: 0, - }; - loop { - world.game_time += 1; - world.day_time += 1; - let mut ctx = TickCtx { - world: &mut world, - host: Some(&host), - entities: &[], - next_entity: &mut next_entity, - spawn: [8.5, 60.0, 8.5], - difficulty: 2, - difficulty_locked: false, - clock_rate: 1.0, - tick_rate: 20.0, - tick_frozen: false, - tick_steps: (0, 0), - collision: None, - }; - for event in hub.tick(&mut ctx) { - match event { - HostEvent::Joined(conn) => hub.place_new_player(conn, &mut ctx), - HostEvent::Packet(_, packet) => { - if std::env::var_os("HORIZON_NET_DEBUG").is_some() - && !matches!(*packet, S::ClientTickEnd(_)) - { - eprintln!("[lan] {packet:?}"); - } - } - HostEvent::Chat { line, .. } | HostEvent::Warn(line) | HostEvent::Error(line) => { - println!("{line}") - } - HostEvent::Left(_) => {} - } - } - std::thread::sleep(Duration::from_millis(50)); - } -} diff --git a/crates/horizon-client/examples/load_bench.rs b/crates/horizon-client/examples/load_bench.rs deleted file mode 100644 index 5c30a71ff..000000000 --- a/crates/horizon-client/examples/load_bench.rs +++ /dev/null @@ -1,153 +0,0 @@ -//! Read-only saved chunk benchmark. All timings exclude resource/corpus setup. -//! -//! load_bench RESOURCES DIMENSION_DIR [--rounds N] [--limit N] [--checksum] -//! Add --profile-worker when a sampling collector cannot sample the main thread. -//! Reports warm filesystem SaveDir::load (read, inflate, NBT, decode and light), -//! plus isolated inflate/NBT and native decode. No files in the save are changed. -use horizon_client::{ - assets::Assets, - biome::Biomes, - blocks::BlockFacts, - save::{SaveDir, SaveTables, decode_with}, -}; -use horizon_world::{nbt::Limits, region::RegionFile}; -use sha2::{Digest, Sha256}; -use std::{hint::black_box, path::PathBuf, sync::Arc, time::Instant}; - -type Result = std::result::Result>; - -fn main() -> Result<()> { - if std::env::args().any(|a| a == "--profile-worker") { - std::thread::spawn(|| run().map_err(|e| e.to_string())) - .join() - .expect("benchmark worker") - .map_err(Into::into) - } else { - run() - } -} - -fn run() -> Result<()> { - let args: Vec = std::env::args().skip(1).collect(); - let usage = "load_bench RESOURCES DIMENSION_DIR [--rounds N] [--limit N] [--checksum]"; - let root = PathBuf::from(args.first().ok_or(usage)?); - let dimension = PathBuf::from(args.get(1).ok_or(usage)?); - let flag = |name: &str, default: usize| -> Result { - Ok(match args.iter().position(|a| a == name) { - Some(i) => args.get(i + 1).ok_or(usage)?.parse()?, - None => default, - }) - }; - let rounds = flag("--rounds", 5)?; - let limit = flag("--limit", 256)?; - if rounds == 0 || limit == 0 { - return Err("rounds and limit must be positive".into()); - } - let assets = Assets::load(&root)?; - let facts = BlockFacts::load(&root, assets.registry)?; - let biomes = Biomes::load(&root)?; - let tables = Arc::new(SaveTables::new(&assets).with_block_entities(&facts)); - let source = SaveDir::new(dimension.clone()); - let _ = source.tables.set(tables.clone()); - let mut paths: Vec<_> = std::fs::read_dir(dimension.join("region"))? - .map(|e| e.map(|e| e.path())) - .collect::>()?; - paths.retain(|p| p.extension().is_some_and(|e| e == "mca")); - paths.sort(); - let mut corpus = Vec::new(); - 'regions: for path in paths { - let mut region = RegionFile::open(path)?; - let mut positions: Vec<_> = region.chunks().map(|(pos, _)| pos).collect(); - positions.sort_by_key(|p| (p.x, p.z)); - for pos in positions { - let record = region.read(pos)?.ok_or("missing record")?; - let tag = record.nbt(Limits::default())?; - if decode_with(&tag, assets.registry, &biomes, Some(&tables)).is_none() { - continue; - } - corpus.push((pos, record, tag)); - if corpus.len() == limit { - break 'regions; - } - } - } - if corpus.is_empty() { - return Err("no full chunks in corpus".into()); - } - let mut records_hash = Sha256::new(); - for (pos, record, _) in &corpus { - records_hash.update(pos.x.to_le_bytes()); - records_hash.update(pos.z.to_le_bytes()); - records_hash.update((record.compressed.len() as u64).to_le_bytes()); - records_hash.update(&record.compressed); - } - println!( - "{}", - serde_json::json!({"corpus": dimension, "chunks": corpus.len(), "rounds": rounds, - "compressed_records_sha256": format!("{:x}", records_hash.finalize()), - "compressed_bytes": corpus.iter().map(|(_, r, _)| r.compressed.len()).sum::()}) - ); - // Prime SaveDir's region handles and the filesystem cache before measurement. - for (pos, _, _) in &corpus { - black_box( - source - .load(pos.x, pos.z, assets.registry, &biomes) - .ok_or("load failed")?, - ); - } - for round in 0..rounds { - let started = Instant::now(); - for (pos, _, _) in &corpus { - black_box( - source - .load(pos.x, pos.z, assets.registry, &biomes) - .ok_or("load failed")?, - ); - } - let load_s = started.elapsed().as_secs_f64(); - let started = Instant::now(); - for (_, record, _) in &corpus { - black_box(record.nbt(Limits::default())?); - } - let nbt_s = started.elapsed().as_secs_f64(); - let started = Instant::now(); - for (_, _, tag) in &corpus { - black_box( - decode_with(tag, assets.registry, &biomes, Some(&tables)).ok_or("decode failed")?, - ); - } - let decode_s = started.elapsed().as_secs_f64(); - println!( - "{}", - serde_json::json!({"round": round, "load_s": load_s, - "inflate_nbt_s": nbt_s, "decode_s": decode_s}) - ); - } - if args.iter().any(|a| a == "--checksum") { - let mut hash = Sha256::new(); - let mut light_loaded = 0; - for (pos, _, _) in &corpus { - let chunk = source - .load(pos.x, pos.z, assets.registry, &biomes) - .ok_or("load failed")?; - hash.update(pos.x.to_le_bytes()); - hash.update(pos.z.to_le_bytes()); - light_loaded += usize::from(chunk.light_loaded); - for section in &chunk.sections { - for i in 0..4096 { - hash.update(section.get(i).to_le_bytes()); - hash.update([section.light(i)]); - } - for i in 0..64 { - hash.update(section.biomes.get(i).to_le_bytes()); - } - } - } - println!( - "{}", - serde_json::json!({"blocks_biomes_light_sha256": format!("{:x}", hash.finalize()), - "light_loaded": light_loaded}) - ); - } - Ok(()) -} diff --git a/crates/horizon-client/examples/save_bench.rs b/crates/horizon-client/examples/save_bench.rs deleted file mode 100644 index 30625be65..000000000 --- a/crates/horizon-client/examples/save_bench.rs +++ /dev/null @@ -1,128 +0,0 @@ -//! The region writer on real chunks, without a window: how long a world's -//! chunks take to be encoded, compressed and written by `SaveDir`, against -//! the same encoding and compression done one chunk after another (what the -//! writer thread did alone before it had helpers). -//! -//! save_bench RESOURCES DIMENSION_DIR [--rounds N] -//! -//! DIMENSION_DIR is a saved dimension folder (`saves/W/dimensions/minecraft/ -//! overworld`); its chunks are read once, then each round saves them all into -//! a scratch folder with `save_later` + `flush`, and times the one-thread -//! baseline. The written chunks are checked byte for byte against the -//! baseline's compressed records. -use horizon_client::{ - assets::Assets, - biome::Biomes, - blocks::BlockFacts, - save::{SaveDir, SaveTables, encode_with}, -}; -use horizon_core::position::ChunkPos; -use horizon_world::{ - compression::Compression, - nbt::Limits, - region::{ChunkRecord, RegionFile}, -}; -use std::{path::PathBuf, sync::Arc, time::Instant}; - -type Result = std::result::Result>; - -fn main() -> Result<()> { - let args: Vec = std::env::args().skip(1).collect(); - let usage = "usage: save_bench RESOURCES DIMENSION_DIR [--rounds N]"; - let root = PathBuf::from(args.first().ok_or(usage)?); - let dimension = PathBuf::from(args.get(1).ok_or(usage)?); - let rounds: usize = args - .iter() - .position(|a| a == "--rounds") - .and_then(|i| args.get(i + 1)) - .and_then(|v| v.parse().ok()) - .unwrap_or(5); - - let assets = Assets::load(&root)?; - let facts = BlockFacts::load(&root, assets.registry)?; - let biomes = Arc::new(Biomes::load(&root)?); - let tables = Arc::new(SaveTables::new(&assets).with_block_entities(&facts)); - let registry = assets.registry; - - let source = SaveDir::new(dimension.clone()); - let _ = source.tables.set(tables.clone()); - let mut chunks = Vec::new(); - for entry in std::fs::read_dir(dimension.join("region"))? { - let path = entry?.path(); - if path.extension().is_none_or(|e| e != "mca") { - continue; - } - let region = RegionFile::open(&path)?; - for (pos, _) in region.chunks() { - if let Some(chunk) = source.load(pos.x, pos.z, registry, &biomes) { - chunks.push(Arc::new(chunk)); - } - } - } - chunks.sort_by_key(|c| (c.x, c.z)); - println!("{} chunks from {}", chunks.len(), dimension.display()); - - let scratch = std::env::temp_dir().join(format!("save_bench_{}", std::process::id())); - // Encoding and compressing on one thread (what the writer did alone), - // then SaveDir's writer with its helpers. - let mut times = [Vec::new(), Vec::new(), Vec::new()]; - let mut written = Vec::new(); - for round in 0..rounds { - let started = Instant::now(); - let tags: Vec<_> = chunks - .iter() - .map(|c| encode_with(c, registry, &biomes, Some(&tables), true)) - .collect(); - times[0].push(started.elapsed().as_secs_f64()); - let started = Instant::now(); - let baseline: Vec = tags - .iter() - .map(|tag| ChunkRecord::from_nbt(tag, Compression::Zlib, 0, Limits::default())) - .collect::>()?; - times[1].push(started.elapsed().as_secs_f64()); - drop(tags); - - let _ = std::fs::remove_dir_all(&scratch); - let save = SaveDir::new(scratch.clone()); - let _ = save.tables.set(tables.clone()); - let started = Instant::now(); - save.save_later(&chunks, registry, &biomes)?; - save.flush().unwrap(); - times[2].push(started.elapsed().as_secs_f64()); - drop(save); - - if round == 0 { - for (chunk, want) in chunks.iter().zip(&baseline) { - let path = scratch.join(format!("region/r.{}.{}.mca", chunk.x >> 5, chunk.z >> 5)); - let got = RegionFile::open(&path)? - .read(ChunkPos::new(chunk.x, chunk.z))? - .ok_or("a saved chunk is missing")?; - if got.compressed != want.compressed { - return Err(format!("chunk {} {} differs", chunk.x, chunk.z).into()); - } - } - written = baseline.iter().map(|r| r.compressed.len()).collect(); - } - } - let _ = std::fs::remove_dir_all(&scratch); - println!( - "{} KiB compressed, identical to the one-thread records", - written.iter().sum::() / 1024 - ); - let per_chunk = 1000.0 / chunks.len() as f64; - let names = [ - "one thread: encode", - "one thread: compress", - "SaveDir (encode, compress, write)", - ]; - for (name, t) in names.iter().zip(&mut times) { - t.sort_by(f64::total_cmp); - println!( - "{name}: best {:.0} ms, median {:.0} ms of {rounds} ({:.3} ms per chunk at best)", - t[0] * 1000.0, - t[t.len() / 2] * 1000.0, - t[0] * per_chunk - ); - } - Ok(()) -} diff --git a/crates/horizon-client/examples/save_parity.rs b/crates/horizon-client/examples/save_parity.rs deleted file mode 100644 index 3954e3bb3..000000000 --- a/crates/horizon-client/examples/save_parity.rs +++ /dev/null @@ -1,265 +0,0 @@ -//! Differential save test: load every full chunk of a world written by the -//! vanilla 26.3 server, light it, encode it again with Horizon's chunk writer -//! and compare the result with the original NBT: block states, biomes, -//! heightmaps, light layers (by value), block entities and scheduled ticks. -//! -//! cargo run --profile fast -p horizon-client --example save_parity -- \ -//! RESOURCES DIMENSION_DIR [--nether] -use horizon_client::{ - assets::Assets, - biome::Biomes, - blocks::BlockFacts, - chunk::{Chunk, MIN_Y, SECTIONS}, - light::{LightTables, apply_lighting, light_chunk}, - save::{self, SaveTables}, -}; -use horizon_core::position::ChunkPos; -use horizon_world::{ - chunk::BlockState, - nbt::{Limits, NamedTag, Tag}, - region::RegionFile, -}; -use std::{ - collections::{BTreeMap, HashMap}, - path::PathBuf, -}; - -/// Block state names per section index, decoded independently of Horizon. -fn block_names(tag: &Tag) -> BTreeMap> { - let mut out = BTreeMap::new(); - let Some(Tag::List(sections)) = tag.get("sections") else { - return out; - }; - for s in sections { - let Some(Tag::Byte(y)) = s.get("Y") else { - continue; - }; - let Some(states) = s.get("block_states") else { - continue; - }; - let Some(Tag::List(palette)) = states.get("palette") else { - continue; - }; - let names: Vec = palette - .iter() - .map(|p| { - let st = BlockState::from_nbt(p).expect("palette entry"); - format!("{}{:?}", st.name, st.properties) - }) - .collect(); - let bits = (usize::BITS - (names.len().max(1) - 1).leading_zeros()).max(4); - let per = 64 / bits as usize; - let data = match states.get("data") { - Some(Tag::LongArray(d)) => d.clone(), - _ => Vec::new(), - }; - let blocks = (0..4096) - .map(|i| { - if names.len() == 1 { - return names[0].clone(); - } - let v = (data[i / per] as u64 >> ((i % per) as u32 * bits)) & ((1 << bits) - 1); - names[v as usize].clone() - }) - .collect(); - out.insert(i64::from(*y), blocks); - } - out -} -fn light(tag: &Tag, key: &str) -> HashMap> { - let mut out = HashMap::new(); - if let Some(Tag::List(sections)) = tag.get("sections") { - for s in sections { - if let (Some(Tag::Byte(y)), Some(Tag::ByteArray(a))) = (s.get("Y"), s.get(key)) { - out.insert(i64::from(*y), a.clone()); - } - } - } - out -} -/// Light value with vanilla's reading of missing layers. -fn value( - layers: &HashMap>, - sy: i64, - i: usize, - sky: bool, - empty: bool, - top: i64, -) -> u8 { - let nibble = |a: &Vec, i: usize| (a[i >> 1] >> ((i & 1) * 4)) & 15; - if let Some(a) = layers.get(&sy) { - return nibble(a, i); - } - if !sky || !empty { - return 0; - } - ((sy + 1)..=top) - .find_map(|y| layers.get(&y)) - .map_or(15, |a| nibble(a, i & 255)) -} -fn count(tag: &Tag, key: &str) -> usize { - match tag.get(key) { - Some(Tag::List(l)) => l.len(), - _ => 0, - } -} - -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().skip(1).collect(); - let root = PathBuf::from( - args.first() - .ok_or("usage: save_parity RESOURCES DIMENSION_DIR")?, - ); - let dim = PathBuf::from(args.get(1).ok_or("missing dimension directory")?); - let sky_light = !args.iter().any(|a| a == "--nether"); - let assets = Assets::load(&root)?; - let facts = BlockFacts::load(&root, assets.registry)?; - let biomes = Biomes::load(&root)?; - let lights = LightTables::load(&root, assets.registry, &facts)?; - let tables = SaveTables::new(&assets).with_block_entities(&facts); - let mut originals: HashMap<(i32, i32), NamedTag> = HashMap::new(); - let mut chunks: HashMap<(i32, i32), Chunk> = HashMap::new(); - for entry in std::fs::read_dir(dim.join("region"))? { - let mut region = RegionFile::open(entry?.path())?; - let positions: Vec = region.chunks().map(|(p, _)| p).collect(); - for p in positions { - let Some(record) = region.read(p)? else { - continue; - }; - let tag = record.nbt(Limits::default())?; - if tag.tag.get("isLightOn") != Some(&Tag::Byte(1)) { - continue; - } - if let Some(c) = save::decode_with(&tag, assets.registry, &biomes, Some(&tables)) { - chunks.insert((c.x, c.z), c); - originals.insert((p.x, p.z), tag); - } - } - } - let mut keys: Vec<_> = chunks - .keys() - .copied() - .filter(|&(x, z)| { - (-1..=1).all(|dz| (-1..=1).all(|dx| chunks.contains_key(&(x + dx, z + dz)))) - }) - .collect(); - keys.sort_unstable(); - let ( - mut blocks_bad, - mut biomes_bad, - mut heightmaps_bad, - mut light_bad, - mut light_total, - mut other_bad, - ) = (0, 0, 0, 0u64, 0u64, 0); - for &(x, z) in &keys { - let region: [[Option<&Chunk>; 3]; 3] = std::array::from_fn(|dz| { - std::array::from_fn(|dx| chunks.get(&(x + dx as i32 - 1, z + dz as i32 - 1))) - }); - let mut chunk = chunks[&(x, z)].clone(); - apply_lighting(&mut chunk, light_chunk(®ion, &lights, sky_light)); - chunk.lit = true; - let ours = save::encode_with(&chunk, assets.registry, &biomes, Some(&tables), sky_light); - let theirs = &originals[&(x, z)]; - let (a, b) = (&ours.tag, &theirs.tag); - // Block states: compare every non-empty vanilla section. - let (na, nb) = (block_names(a), block_names(b)); - for (y, vb) in &nb { - match na.get(y) { - Some(va) if va == vb => {} - Some(va) => { - let n = va.iter().zip(vb).filter(|(p, q)| p != q).count(); - if blocks_bad < 5 { - let i = va.iter().zip(vb).position(|(p, q)| p != q).unwrap_or(0); - eprintln!( - "chunk {x} {z} section {y}: {n} blocks differ, e.g. {} vs {}", - va[i], vb[i] - ); - } - blocks_bad += 1; - } - None if vb.iter().all(|s| s.starts_with("minecraft:air")) => {} - None => blocks_bad += 1, - } - } - let biome_of = |t: &Tag| -> Vec { - match t.get("sections") { - Some(Tag::List(l)) => l.iter().filter_map(|s| s.get("biomes").cloned()).collect(), - _ => Vec::new(), - } - }; - if biome_of(a) != biome_of(b) { - biomes_bad += 1; - } - for kind in [ - "WORLD_SURFACE", - "OCEAN_FLOOR", - "MOTION_BLOCKING", - "MOTION_BLOCKING_NO_LEAVES", - ] { - let get = |t: &Tag| t.get("Heightmaps").and_then(|h| h.get(kind)).cloned(); - if get(a) != get(b) { - if heightmaps_bad < 5 { - eprintln!("chunk {x} {z}: heightmap {kind} differs"); - } - heightmaps_bad += 1; - } - } - for (key, sky) in [("SkyLight", true), ("BlockLight", false)] { - if sky && !sky_light { - continue; - } - let (la, lb) = (light(a, key), light(b, key)); - let top = i64::from((MIN_Y >> 4) + SECTIONS as i32); - for si in 0..SECTIONS { - let sy = i64::from((MIN_Y >> 4) + si as i32); - let empty = chunk.sections[si].is_uniform(tables_air(&assets)); - for i in 0..4096 { - light_total += 1; - if value(&la, sy, i, sky, empty, top) != value(&lb, sy, i, sky, empty, top) { - light_bad += 1; - } - } - } - } - for key in ["block_entities", "block_ticks", "fluid_ticks"] { - if count(a, key) != count(b, key) { - if other_bad < 5 { - eprintln!( - "chunk {x} {z}: {key} {} vs {}", - count(a, key), - count(b, key) - ); - } - other_bad += 1; - } - } - for key in [ - "structures", - "PostProcessing", - "InhabitedTime", - "Status", - "DataVersion", - "yPos", - ] { - if a.get(key) != b.get(key) { - if other_bad < 5 { - eprintln!("chunk {x} {z}: {key} differs"); - } - other_bad += 1; - } - } - } - println!( - "{} chunks: {blocks_bad} sections with different blocks, {biomes_bad} chunks with different biomes, \ - {heightmaps_bad} different heightmaps, {light_bad} of {light_total} light values differ, {other_bad} other differences", - keys.len() - ); - Ok(()) -} -fn tables_air(assets: &Assets) -> u32 { - assets - .registry - .default_state("minecraft:air") - .map_or(0, |s| s.0) -} diff --git a/crates/horizon-client/examples/streaming_bench.rs b/crates/horizon-client/examples/streaming_bench.rs deleted file mode 100644 index b8c56b28c..000000000 --- a/crates/horizon-client/examples/streaming_bench.rs +++ /dev/null @@ -1,284 +0,0 @@ -//! The chunk pipeline (generation, decoration, lighting, meshing) on its worker -//! pool, without a window: how fast a render distance fills with N workers, and -//! what the render thread pays for it in `Streaming::update`. -//! -//! streaming_bench RESOURCES [--threads N] [--radius R] [--seed S] [--fly CHUNKS_PER_S] [--seconds T] [--hz F] -//! [--dimension overworld|the_nether|the_end] [--center-x X] [--center-z Z] -//! -//! First the area around (0, 0) fills; then, with `--fly`, the centre moves along +x -//! at that speed for T seconds while frames run at F per second. Each phase reports -//! its wall time, chunks generated and sections meshed, and the time `update` -//! took on the calling thread (the render thread in the game): total, median, -//! p99 and slowest. Compile with HORIZON_BENCH_COUNT_ALLOCATIONS=1 to count the -//! allocations made on the calling thread during updates and by everything. -use horizon_client::{ - assets::Assets, - biome::Biomes, - blocks::BlockFacts, - light::LightTables, - mesher::MeshTables, - models, - streaming::{Streaming, WorkerContext}, - vanillagen::VanillaTerrain, - world::World, -}; -use std::{ - alloc::{GlobalAlloc, Layout, System}, - cell::Cell, - path::PathBuf, - sync::{ - Arc, - atomic::{AtomicU64, Ordering::Relaxed}, - }, - time::{Duration, Instant}, -}; - -const TRACK: bool = option_env!("HORIZON_BENCH_COUNT_ALLOCATIONS").is_some(); -static ALLOCATIONS: AtomicU64 = AtomicU64::new(0); -static BYTES: AtomicU64 = AtomicU64::new(0); -thread_local! { - static LOCAL: Cell<(u64, u64)> = const { Cell::new((0, 0)) }; -} -fn count(size: usize) { - if TRACK { - ALLOCATIONS.fetch_add(1, Relaxed); - BYTES.fetch_add(size as u64, Relaxed); - let _ = LOCAL.try_with(|c| { - let (n, b) = c.get(); - c.set((n + 1, b + size as u64)); - }); - } -} -struct CountingAllocator; -// Delegates every operation and layout unchanged to System. -unsafe impl GlobalAlloc for CountingAllocator { - unsafe fn alloc(&self, layout: Layout) -> *mut u8 { - count(layout.size()); - unsafe { System.alloc(layout) } - } - unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { - count(layout.size()); - unsafe { System.alloc_zeroed(layout) } - } - unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { - unsafe { System.dealloc(ptr, layout) }; - } - unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, size: usize) -> *mut u8 { - count(size); - unsafe { System.realloc(ptr, layout, size) } - } -} -#[global_allocator] -static ALLOCATOR: CountingAllocator = CountingAllocator; - -type Result = std::result::Result>; - -fn cpu_seconds() -> f64 { - std::fs::read_to_string("/proc/self/stat") - .ok() - .and_then(|stat| { - let fields = stat - .rsplit_once(')')? - .1 - .split_whitespace() - .collect::>(); - Some((fields[11].parse::().ok()? + fields[12].parse::().ok()?) / 100.0) - }) - .unwrap_or(0.0) -} - -#[derive(Default)] -struct Phase { - updates: Vec, - local: (u64, u64), - uploads: usize, - stage_samples: [u64; 7], - cpu_start: f64, -} -impl Phase { - fn update(&mut self, streaming: &mut Streaming, world: &mut World) { - if self.updates.is_empty() { - self.cpu_start = cpu_seconds(); - } - let before = LOCAL.with(Cell::get); - let started = Instant::now(); - let (uploads, _) = streaming.update(world); - self.updates.push(started.elapsed().as_secs_f64() * 1e3); - let after = LOCAL.with(Cell::get); - self.local.0 += after.0 - before.0; - self.local.1 += after.1 - before.1; - self.uploads += uploads.len(); - drop(uploads); - for (sum, (_, count)) in self.stage_samples.iter_mut().zip(streaming.stages()) { - *sum += count as u64; - } - } - fn report(&self, name: &str, wall: Duration, streaming: &Streaming, generated: u64) { - let mut sorted = self.updates.clone(); - sorted.sort_by(f64::total_cmp); - let at = |p: f64| sorted[((sorted.len() as f64 * p) as usize).min(sorted.len() - 1)]; - let total: f64 = sorted.iter().sum(); - println!( - "{name}: {:.2} s, {} chunks generated, {} sections meshed; update {:.1} ms total over {} calls, p50 {:.3} p99 {:.3} max {:.2} ms", - wall.as_secs_f64(), - streaming.generated_total - generated, - self.uploads, - total, - sorted.len(), - at(0.5), - at(0.99), - sorted.last().copied().unwrap_or(0.0), - ); - println!( - "BENCH {}", - serde_json::json!({ - "phase": name, "wall_s": wall.as_secs_f64(), - "cpu_s": cpu_seconds() - self.cpu_start, - "chunks": streaming.generated_total - generated, "sections": self.uploads, - "updates": self.updates.len(), "update_ms": total, - "mean_stages": self.stage_samples.map(|n| n as f64 / self.updates.len() as f64), - }) - ); - if TRACK { - println!( - " update allocations: {} ({:.1} MiB)", - self.local.0, - self.local.1 as f64 / 1048576.0 - ); - } - } -} - -/// Nothing queued or in flight. Sections at the edge of the area stay dirty -/// (their outer neighbours are never lit), so they don't count. -fn settled(streaming: &Streaming) -> bool { - streaming - .stages() - .iter() - .all(|&(name, n)| name == "protos" || n == 0) -} - -fn main() -> Result<()> { - let args: Vec = std::env::args().skip(1).collect(); - let root = PathBuf::from(args.first().ok_or("usage: streaming_bench RESOURCES")?); - let flag = |name: &str, default: f64| -> f64 { - args.iter() - .position(|a| a == name) - .and_then(|i| args.get(i + 1)) - .and_then(|v| v.parse().ok()) - .unwrap_or(default) - }; - let auto = std::thread::available_parallelism().map_or(2, |n| n.get() - 1); - let threads = flag("--threads", auto as f64) as usize; - let radius = flag("--radius", 8.0) as i32; - let seed = flag("--seed", 1234.0) as i64; - let fly = flag("--fly", 0.0); - let seconds = flag("--seconds", 10.0); - let hz = flag("--hz", 240.0); - let dimension = args - .iter() - .position(|a| a == "--dimension") - .and_then(|i| args.get(i + 1)) - .map(|d| { - if d.contains(':') { - d.clone() - } else { - format!("minecraft:{d}") - } - }) - .unwrap_or_else(|| "minecraft:overworld".into()); - let center = ( - flag("--center-x", 0.0) as i32, - flag("--center-z", 0.0) as i32, - ); - - let assets = Arc::new(Assets::load(&root)?); - let render = Arc::new(assets.reload(&root)?); - let facts = BlockFacts::load(&root, assets.registry)?; - let biomes = Arc::new(Biomes::load(&root)?); - let tables = Arc::new(MeshTables::new( - &assets, - &render, - &facts, - models::load_visibility(&root, assets.registry)?, - )?); - let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?); - let terrain = Arc::new(VanillaTerrain::for_dimension( - &root.join("worldgen"), - assets.registry, - &biomes, - seed, - &dimension, - )?); - let context = Arc::new(WorkerContext { - assets, - render: render.clone(), - tables, - biomes, - light, - }); - let mut world = World::new(facts.air, seed); - let mut streaming = Streaming::new(terrain, context, threads); - streaming.radius = radius; - streaming.center = center; - streaming.nether_shading = dimension == "minecraft:the_nether"; - streaming.sky_light = dimension != "minecraft:the_nether"; - println!( - "{threads} workers, radius {radius}, seed {seed}, dimension {dimension}, center {center:?}" - ); - let (allocations, bytes) = (ALLOCATIONS.load(Relaxed), BYTES.load(Relaxed)); - - // Fill: update as often as the game would uncapped, until settled. - let mut phase = Phase::default(); - let started = Instant::now(); - let mut quiet = 0; - while quiet < 20 { - let uploads = phase.uploads; - phase.update(&mut streaming, &mut world); - quiet = if settled(&streaming) && phase.uploads == uploads { - quiet + 1 - } else { - 0 - }; - std::thread::sleep(Duration::from_micros(500)); - } - phase.report("fill", started.elapsed(), &streaming, 0); - - if fly > 0.0 { - let mut phase = Phase::default(); - let generated = streaming.generated_total; - let frame = Duration::from_secs_f64(1.0 / hz); - let started = Instant::now(); - let mut behind = Vec::new(); - while started.elapsed().as_secs_f64() < seconds { - let next = Instant::now() + frame; - let x = center.0 + (started.elapsed().as_secs_f64() * fly) as i32; - streaming.center = (x, center.1); - phase.update(&mut streaming, &mut world); - // Columns within 2 chunks of the player still missing their meshes. - let near = (-2..=2) - .flat_map(|dz| (-2..=2).map(move |dx| (x + dx, center.1 + dz))) - .filter(|&(cx, cz)| !streaming.is_lit(cx, cz)) - .count(); - behind.push(near); - if let Some(wait) = next.checked_duration_since(Instant::now()) { - std::thread::sleep(wait); - } - } - phase.report("fly", started.elapsed(), &streaming, generated); - let unlit = behind.iter().filter(|&&n| n > 0).count(); - println!( - " frames with an unlit column within 2 chunks of the player: {unlit} of {} ({:.1}%)", - behind.len(), - unlit as f64 * 100.0 / behind.len().max(1) as f64 - ); - } - if TRACK { - println!( - "all threads: {} allocations ({:.1} MiB)", - ALLOCATIONS.load(Relaxed) - allocations, - (BYTES.load(Relaxed) - bytes) as f64 / 1048576.0 - ); - } - Ok(()) -} diff --git a/crates/horizon-client/examples/tick_chunk_membership_bench.rs b/crates/horizon-client/examples/tick_chunk_membership_bench.rs deleted file mode 100644 index 6b9cb8a0a..000000000 --- a/crates/horizon-client/examples/tick_chunk_membership_bench.rs +++ /dev/null @@ -1,143 +0,0 @@ -//! Resident-key synchronization used by Game (registration callback work excluded). -//! Run: CARGO_INCREMENTAL=0 cargo run -p horizon-client --profile fast --example tick_chunk_membership_bench -use horizon_client::{ - chunk::Chunk, chunk_map::ChunkMap, tick_chunk_membership::TickChunkMembership, -}; -use std::{collections::HashSet, hint::black_box, sync::Arc, time::Instant}; - -type Key = (i32, i32); -#[derive(Default)] -struct Old { - keys: HashSet, -} -impl Old { - fn sync(&mut self, map: &ChunkMap) -> (usize, usize) { - let loaded: HashSet<_> = map.keys().copied().collect(); - let mut counts = (0, 0); - for key in loaded.difference(&self.keys.clone()) { - black_box(key); - counts.0 += 1; - } - for key in self.keys.difference(&loaded) { - black_box(key); - counts.1 += 1; - } - self.keys = loaded; - counts - } -} -fn new_sync(cache: &mut TickChunkMembership, map: &ChunkMap) -> (usize, usize) { - if !cache.synchronize(map) { - return (0, 0); - } - let added = cache.take_added(); - for key in &added { - black_box(key); - } - for key in cache.removed() { - black_box(key); - } - let counts = (added.len(), cache.removed().len()); - cache.recycle_added(added); - counts -} -fn map(offset: i32) -> ChunkMap { - let mut map = ChunkMap::default(); - // Share a payload: the synchronization path reads only keys, not block data. - let chunk = Arc::new(Chunk::empty(0, 0)); - for x in -16..=16 { - for z in -16..=16 { - map.insert((x + offset, z), chunk.clone()); - } - } - map -} -fn run(new: bool, scenario: usize, iterations: usize) -> (f64, (usize, usize)) { - let mut a = map(0); - let b = map(33); - let chunk = Arc::new(Chunk::empty(0, 0)); - let mut old = Old::default(); - let mut cache = TickChunkMembership::default(); - for _ in 0..64 { - if new { - black_box(new_sync(&mut cache, &a)); - } else { - black_box(old.sync(&a)); - } - } - let mut total = (0, 0); - let start = Instant::now(); - for i in 0..iterations { - let resident = match scenario { - 0 => &a, - 1 => { - let (previous, next) = if i % 2 == 0 { - ((-16, -16), (-17, -16)) - } else { - ((-17, -16), (-16, -16)) - }; - a.remove(&previous); - a.insert(next, chunk.clone()); - &a - } - 2 => { - if i % 2 == 0 { - &b - } else { - &a - } - } - _ => unreachable!(), - }; - let counts = if new { - new_sync(black_box(&mut cache), black_box(resident)) - } else { - old.sync(black_box(resident)) - }; - total.0 += counts.0; - total.1 += counts.1; - } - ( - start.elapsed().as_secs_f64() * 1e9 / iterations as f64, - black_box(total), - ) -} -fn main() { - println!("1089 keys, 64 warmup calls, 9 samples; ns/sync, median"); - for (scenario, name, iterations) in [ - (0, "stable", 10_000), - (1, "one-key same-count replacement", 2_000), - (2, "whole-map replacement", 1_000), - ] { - let mut before = Vec::new(); - let mut after = Vec::new(); - for sample in 0..9 { - let (old, new) = if sample % 2 == 0 { - ( - run(false, scenario, iterations), - run(true, scenario, iterations), - ) - } else { - let new = run(true, scenario, iterations); - (run(false, scenario, iterations), new) - }; - assert_eq!(old.1, new.1); - let expected = match scenario { - 0 => (0, 0), - 1 => (iterations, iterations), - _ => (1089 * iterations, 1089 * iterations), - }; - assert_eq!(new.1, expected); - before.push(old.0); - after.push(new.0); - } - before.sort_by(f64::total_cmp); - after.sort_by(f64::total_cmp); - println!( - "{name}: {:.1} -> {:.1} ns, {:.2}x; {iterations} iterations/sample", - before[4], - after[4], - before[4] / after[4] - ); - } -} diff --git a/crates/horizon-world/examples/vanilla_diff.rs b/crates/horizon-world/examples/vanilla_diff.rs deleted file mode 100644 index 52eb77737..000000000 --- a/crates/horizon-world/examples/vanilla_diff.rs +++ /dev/null @@ -1,441 +0,0 @@ -//! Differential check of decorated chunks against a vanilla world. -//! -//! vanilla_diff --seed S -//! [--dimension minecraft:overworld] [--from CX CZ] [--size N] -//! [--threads T] [--show FROM->TO] [--limit N] [--reverse] [--shuffle SEED] -//! [--other ] -//! -//! Generates an (N+4)² chunk area with the Rust pipeline, decorates the inner -//! (N+2)² chunks (vanilla FEATURES writes reach one neighbor) and compares the -//! N² chunks starting at (CX, CZ) block by block with the region files of a -//! vanilla world generated for the same seed (with ticks frozen, see -//! docs/parity/worldgen.md). Prints mismatches grouped by vanilla → Rust block. -use horizon_core::position::{BlockPos, ChunkPos}; -use horizon_world::{ - DATA_VERSION, - chunk::{BlockSection, BlockState, ChunkData}, - nbt::{Limits, Tag}, - region::RegionFile, - registry::BlockRegistry, - worldgen::generator::{GeneratorData, OverworldGenerator, ProtoChunk}, -}; -use serde_json::Value; -use std::{ - collections::{BTreeMap, HashMap}, - fs, - path::{Path, PathBuf}, - sync::{ - Mutex, - atomic::{AtomicUsize, Ordering}, - }, -}; - -type Error = Box; - -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - Value::Object(o) => { - Tag::Compound(o.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - _ => panic!("invalid registry metadata"), - } -} - -fn registry(resources: &Path) -> Result<&'static BlockRegistry, Error> { - let facts: Value = serde_json::from_str(&fs::read_to_string(resources.join("facts.json"))?)?; - let registry = BlockRegistry::from_nbt(&Tag::compound([ - ("DataVersion", Tag::Int(DATA_VERSION)), - ( - "states", - Tag::List( - facts["states"] - .as_array() - .unwrap() - .iter() - .map(|v| tag(&v[4])) - .collect(), - ), - ), - ("defaults", tag(&facts["defaults"])), - ]))?; - Ok(Box::leak(Box::new(registry))) -} - -fn describe(state: &BlockState) -> String { - if state.properties.is_empty() { - return state.name.clone(); - } - let props: Vec = state - .properties - .iter() - .map(|(k, v)| format!("{k}={v}")) - .collect(); - format!("{}[{}]", state.name, props.join(",")) -} - -fn region_dir(world: &Path, dimension: &str) -> PathBuf { - let modern = world - .join("dimensions") - .join(dimension.replace(':', "/")) - .join("region"); - if modern.is_dir() { - return modern; - } - match dimension { - "minecraft:the_nether" => world.join("DIM-1/region"), - "minecraft:the_end" => world.join("DIM1/region"), - _ => world.join("region"), - } -} - -/// Terrain-stage chunks of the `full`² area at `origin`, row-major. -fn generate_area( - generator: &OverworldGenerator, - origin: (i32, i32), - full: i32, - threads: usize, -) -> Result, Error> { - let count = (full * full) as usize; - let next = AtomicUsize::new(0); - let slots: Vec>> = (0..count).map(|_| Mutex::new(None)).collect(); - std::thread::scope(|scope| -> Result<(), Error> { - let handles = (0..threads) - .map(|_| { - scope.spawn(|| -> Result<(), Error> { - let mut worker = generator.worker(); - loop { - let i = next.fetch_add(1, Ordering::Relaxed); - if i >= count { - return Ok(()); - } - let pos = ChunkPos::new( - origin.0 + (i as i32 % full), - origin.1 + (i as i32 / full), - ); - *slots[i].lock().unwrap() = Some(worker.generate_proto(pos)?); - } - }) - }) - .collect::>(); - handles.into_iter().try_for_each(|h| h.join().unwrap()) - })?; - Ok(slots - .into_iter() - .map(|s| s.into_inner().unwrap().unwrap()) - .collect()) -} - -/// Decorates the chunks at `order` (indices into the `full`² area, each with -/// all eight neighbors present) in that order, one FEATURES pass each. -fn decorate_area( - generator: &OverworldGenerator, - protos: Vec, - full: i32, - order: &[(i32, i32)], -) -> Result, Error> { - let mut chunks: Vec> = protos.into_iter().map(Some).collect(); - let mut worker = generator.worker(); - let (mut unsupported_roots, mut failed) = (0, 0); - let mut skipped = std::collections::BTreeSet::new(); - for &(x, z) in order { - let mut region = Vec::with_capacity(9); - for dz in -1..=1 { - for dx in -1..=1 { - region.push(chunks[((z + dz) * full + x + dx) as usize].take().unwrap()); - } - } - let mut region: [ProtoChunk; 9] = region.try_into().map_err(|_| "region")?; - let stats = worker.decorate(&mut region)?; - unsupported_roots += stats.unsupported; - failed += stats.failed; - skipped.extend(stats.skipped); - for (i, chunk) in region.into_iter().enumerate() { - let (dx, dz) = (i as i32 % 3 - 1, i as i32 / 3 - 1); - chunks[((z + dz) * full + x + dx) as usize] = Some(chunk); - } - } - println!("decoration: unsupported roots {unsupported_roots}, failed {failed}"); - if !skipped.is_empty() { - println!( - "skipped: {}", - skipped.into_iter().collect::>().join(" ") - ); - } - Ok(chunks.into_iter().map(Option::unwrap).collect()) -} - -/// Lazily opened region files of one dimension. -struct Regions { - dir: PathBuf, - files: HashMap<(i32, i32), Option>, -} -impl Regions { - fn new(dir: PathBuf) -> Self { - Self { - dir, - files: HashMap::new(), - } - } - fn chunk(&mut self, pos: ChunkPos) -> Result, Error> { - let key = (pos.x >> 5, pos.z >> 5); - let dir = &self.dir; - let file = self.files.entry(key).or_insert_with(|| { - RegionFile::open(dir.join(format!("r.{}.{}.mca", key.0, key.1))).ok() - }); - let Some(file) = file else { return Ok(None) }; - let Some(record) = file.read(pos)? else { - return Ok(None); - }; - Ok(Some(ChunkData::new(record.nbt(Limits::default())?)?)) - } -} - -fn main() -> Result<(), Error> { - let mut args = std::env::args().skip(1); - let resources = PathBuf::from(args.next().expect("client resource directory")); - let world = PathBuf::from(args.next().expect("vanilla world directory")); - let (mut seed, mut from, mut size, mut threads) = (0i64, (0, 0), 8i32, 4usize); - let mut dimension = String::from("minecraft:overworld"); - let mut show: Option = None; - let mut limit = 40usize; - let mut other: Option = None; - let (mut reverse, mut shuffle) = (false, 0i64); - while let Some(arg) = args.next() { - let mut next = || args.next().expect("argument value"); - match arg.as_str() { - "--seed" => seed = next().parse()?, - "--from" => from = (next().parse()?, next().parse()?), - "--size" => size = next().parse()?, - "--threads" => threads = next().parse()?, - "--dimension" => dimension = next(), - "--show" => show = Some(next()), - "--limit" => limit = next().parse()?, - "--other" => other = Some(PathBuf::from(next())), - "--reverse" => reverse = true, - "--shuffle" => shuffle = next().parse()?, - _ => return Err(format!("unknown argument {arg}").into()), - } - } - let registry = registry(&resources)?; - let data = GeneratorData::load(&resources.join("worldgen"), registry)?; - let generator = OverworldGenerator::for_dimension(data, seed, "minecraft:normal", &dimension)?; - let unsupported = generator.unsupported_features(); - println!("unsupported placed features: {}", unsupported.len()); - - // Rust: terrain for (size+4)², decoration for the inner (size+2)². - let full = size + 4; - let (x0, z0) = (from.0 - 2, from.1 - 2); - let mut order: Vec<(i32, i32)> = (1..full - 1) - .flat_map(|z| (1..full - 1).map(move |x| (x, z))) - .collect(); - if reverse { - let mut reversed = order.clone(); - reversed.reverse(); - let alternate = decorate_area( - &generator, - generate_area(&generator, (x0, z0), full, threads)?, - full, - &reversed, - )?; - let chunks = decorate_area( - &generator, - generate_area(&generator, (x0, z0), full, threads)?, - full, - &order, - )?; - let mut pairs: BTreeMap<(String, String), usize> = BTreeMap::new(); - let mut total = 0; - let name = |id| { - registry - .state(id) - .map(|s: &BlockState| s.name.trim_start_matches("minecraft:").to_owned()) - .unwrap_or_default() - }; - for (a, b) in chunks.iter().zip(&alternate) { - let p = a.position(); - if p.x < from.0 || p.z < from.1 || p.x >= from.0 + size || p.z >= from.1 + size { - continue; - } - for section in 0..a.terrain.height() as usize / 16 { - let (sa, sb) = ( - a.terrain.section(section).unwrap(), - b.terrain.section(section).unwrap(), - ); - for index in 0..4096 { - let (x, y) = (sa.get(index)?, sb.get(index)?); - if x != y { - total += 1; - *pairs.entry((name(x), name(y))).or_default() += 1; - } - } - } - } - println!("decoration order sensitivity (raster vs reverse): {total} blocks differ"); - let mut sorted: Vec<_> = pairs.into_iter().collect(); - sorted.sort_by_key(|p| std::cmp::Reverse(p.1)); - for ((v, r), n) in sorted.iter().take(limit) { - println!("{n:>9} {v} <-> {r}"); - } - return Ok(()); - } - if shuffle != 0 { - // Deterministic Fisher-Yates with a 64-bit LCG. - let mut state = shuffle as u64; - for i in (1..order.len()).rev() { - state = state - .wrapping_mul(6364136223846793005) - .wrapping_add(1442695040888963407); - order.swap(i, (state >> 33) as usize % (i + 1)); - } - } - let chunks = match other { - Some(_) => Vec::new(), - None => decorate_area( - &generator, - generate_area(&generator, (x0, z0), full, threads)?, - full, - &order, - )?, - }; - let (min_y, height) = match dimension.as_str() { - "minecraft:overworld" => (-64, 384), - _ => (0, 256), - }; - - // Vanilla region files. - let mut vanilla = Regions::new(region_dir(&world, &dimension)); - let mut second = other.map(|w| Regions::new(region_dir(&w, &dimension))); - let air = registry.default_state("minecraft:air").unwrap(); - let mut pairs: BTreeMap<(String, String), usize> = BTreeMap::new(); - let mut examples: Vec<[i32; 3]> = Vec::new(); - let (mut compared, mut differ, mut missing) = (0usize, 0usize, 0usize); - let mut per_chunk = Vec::new(); - for cz in from.1..from.1 + size { - for cx in from.0..from.0 + size { - let pos = ChunkPos::new(cx, cz); - let Some(theirs) = vanilla.chunk(pos)? else { - missing += 1; - continue; - }; - let ours = match &mut second { - Some(second) => match second.chunk(pos)? { - Some(chunk) => Some(chunk), - None => { - missing += 1; - continue; - } - }, - None => None, - }; - let status = match theirs.root().tag.get("Status") { - Some(Tag::String(s)) => s.to_string().unwrap_or_default(), - _ => String::new(), - }; - let rust = chunks.get(((cz - z0) * full + cx - x0) as usize); - if size == 1 { - println!( - "vanilla structures: {:?}", - theirs.root().tag.get("structures") - ); - if let Some(rust) = rust { - println!("rust structures: {:?}", rust.structures()); - } - } - if status != "minecraft:full" { - println!("chunk {cx} {cz}: vanilla status {status}"); - } - let mut chunk_differ = 0; - for section in 0..height as usize / 16 { - let base_y = min_y + section as i32 * 16; - let at = BlockPos::new(cx * 16, base_y, cz * 16); - let ours_loaded; - let ours: Option<&BlockSection> = match (&ours, rust) { - (Some(chunk), _) => { - ours_loaded = chunk.load_block_section(at, registry)?; - ours_loaded.as_ref() - } - (None, Some(rust)) => rust.terrain.section(section), - (None, None) => None, - }; - let theirs = theirs.load_block_section(at, registry)?; - for index in 0..4096 { - let a = ours.map_or(Ok(air), |s| s.get(index))?; - let b = theirs.as_ref().map_or(Ok(air), |s| s.get(index))?; - compared += 1; - if a == b { - continue; - } - differ += 1; - chunk_differ += 1; - let (va, ru) = ( - registry.state(b).map(describe).unwrap_or_default(), - registry.state(a).map(describe).unwrap_or_default(), - ); - let short = |s: &str| { - s.split('[') - .next() - .unwrap() - .trim_start_matches("minecraft:") - .to_owned() - }; - let pair = (short(&va), short(&ru)); - let p = [ - cx * 16 + (index & 15) as i32, - base_y + (index >> 8) as i32, - cz * 16 + ((index >> 4) & 15) as i32, - ]; - if let Some(filter) = &show { - let label = format!("{}->{}", pair.0, pair.1); - if &label == filter && examples.len() < limit { - examples.push(p); - println!(" {p:?}: vanilla {va} rust {ru}"); - } - } - *pairs.entry(pair).or_default() += 1; - } - } - per_chunk.push(((cx, cz), chunk_differ)); - } - } - println!( - "compared {compared} blocks in {} chunks ({missing} missing): {differ} differ ({:.4}%)", - per_chunk.len(), - differ as f64 * 100.0 / compared.max(1) as f64 - ); - let mut sorted: Vec<_> = pairs.into_iter().collect(); - sorted.sort_by_key(|p| std::cmp::Reverse(p.1)); - for ((v, r), n) in sorted.iter().take(limit) { - println!("{n:>9} vanilla {v} -> rust {r}"); - } - // Decoration order at chunk borders differs between runs (vanilla's own - // runs disagree), which mostly swaps blocks symmetrically. One-sided - // differences point at real generation differences. - let counts: BTreeMap<_, _> = sorted.iter().cloned().collect(); - let mut net: Vec<(i64, &(String, String))> = counts - .iter() - .map(|(pair, &n)| { - let back = counts - .get(&(pair.1.clone(), pair.0.clone())) - .copied() - .unwrap_or(0); - (n as i64 - back as i64, pair) - }) - .filter(|(n, _)| *n > 0) - .collect(); - net.sort_by_key(|p| std::cmp::Reverse(p.0)); - println!("one-sided differences:"); - for (n, (v, r)) in net.iter().take(limit) { - println!("{n:>9} vanilla {v} -> rust {r}"); - } - let clean = per_chunk.iter().filter(|(_, n)| *n == 0).count(); - println!("chunks identical: {clean}/{}", per_chunk.len()); - let mut worst = per_chunk.clone(); - worst.sort_by_key(|p| std::cmp::Reverse(p.1)); - for ((x, z), n) in worst.iter().take(8).filter(|(_, n)| *n > 0) { - println!(" chunk {x} {z}: {n}"); - } - Ok(()) -}