diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8966854c2..17075add1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -64,9 +64,13 @@ jobs: cargo +stable clippy --workspace --all-targets -- -D warnings # The server build (released as horizon-engine): the game without sound or controllers. cargo +stable clippy -p horizon-client --all-targets --no-default-features -- -D warnings + # Libraries, binaries and integration tests, then doc tests: not the ~275 examples, which clippy above already + # type-checks and the parity job builds and runs (they were most of this step's build and link time). - name: Test Rust core and voxel kernel correctness if: steps.rust.outputs.required != 'false' - run: cargo +stable test --workspace + run: | + cargo +stable test --workspace --lib --bins --tests + cargo +stable test --workspace --doc parity: if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository uses: ./.github/workflows/parity.yml 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/ambient_fixture.rs b/crates/horizon-client/examples/probe/ambient_fixture.rs similarity index 98% rename from crates/horizon-client/examples/ambient_fixture.rs rename to crates/horizon-client/examples/probe/ambient_fixture.rs index d75a1b568..3fd507902 100644 --- a/crates/horizon-client/examples/ambient_fixture.rs +++ b/crates/horizon-client/examples/probe/ambient_fixture.rs @@ -1,8 +1,7 @@ //! Replays `tools/test_ambient_sound_parity.py` scripts through Horizon's //! ambient sound handlers over its `SoundEngine`: //! `ambient_fixture ROOT INPUT OUTPUT`. -#[path = "audio_common/mod.rs"] -mod common; +use crate::audio_common as common; use common::{Fake, d, f, flush}; use horizon_client::ambience::{Ambience, AmbientContext, AmbientSounds, Mood, bubble_column_in}; use horizon_client::sound_engine::{Bound, SoundEngine, TickContext, Ticking}; @@ -47,8 +46,8 @@ fn sounds(a: &[&str]) -> AmbientSounds { } } -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let mut engine = SoundEngine::new(SoundRegistry::load(std::path::Path::new(&args[1]))); engine.listening = true; let mut backend = Fake::default(); diff --git a/crates/horizon-client/examples/arrow_probe.rs b/crates/horizon-client/examples/probe/arrow_probe.rs similarity index 99% rename from crates/horizon-client/examples/arrow_probe.rs rename to crates/horizon-client/examples/probe/arrow_probe.rs index 63ff2df32..f72e6276e 100644 --- a/crates/horizon-client/examples/arrow_probe.rs +++ b/crates/horizon-client/examples/probe/arrow_probe.rs @@ -50,8 +50,8 @@ fn particle(k: ArrowParticle) -> &'static str { ArrowParticle::Splash => "splash", } } -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); if args.len() != 3 { return Err("usage: arrow_probe RESOURCES FIXTURE_DIRECTORY --describe|REFERENCE".into()); } diff --git a/crates/horizon-client/examples/audio_attributes_fixture.rs b/crates/horizon-client/examples/probe/audio_attributes_fixture.rs similarity index 97% rename from crates/horizon-client/examples/audio_attributes_fixture.rs rename to crates/horizon-client/examples/probe/audio_attributes_fixture.rs index 73f463fc4..4bbb3a239 100644 --- a/crates/horizon-client/examples/audio_attributes_fixture.rs +++ b/crates/horizon-client/examples/probe/audio_attributes_fixture.rs @@ -18,8 +18,8 @@ fn music(m: Option<&Music>) -> String { }) } -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let root = std::path::Path::new(&args[1]); let tables = MusicTables::load(root); let ambient = AmbientTables::load(root); diff --git a/crates/horizon-client/examples/audio_common/mod.rs b/crates/horizon-client/examples/probe/audio_common/mod.rs similarity index 100% rename from crates/horizon-client/examples/audio_common/mod.rs rename to crates/horizon-client/examples/probe/audio_common/mod.rs diff --git a/crates/horizon-client/examples/auto_jump_probe.rs b/crates/horizon-client/examples/probe/auto_jump_probe.rs similarity index 98% rename from crates/horizon-client/examples/auto_jump_probe.rs rename to crates/horizon-client/examples/probe/auto_jump_probe.rs index d8dee95df..c15565850 100644 --- a/crates/horizon-client/examples/auto_jump_probe.rs +++ b/crates/horizon-client/examples/probe/auto_jump_probe.rs @@ -24,8 +24,8 @@ fn db(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); let [root, input, output, scene_json] = &args[..] else { return Err("usage: auto_jump_probe RESOURCES INPUT OUTPUT SCENE_JSON".into()); }; diff --git a/crates/horizon-client/examples/block_entity_anim_fixture.rs b/crates/horizon-client/examples/probe/block_entity_anim_fixture.rs similarity index 99% rename from crates/horizon-client/examples/block_entity_anim_fixture.rs rename to crates/horizon-client/examples/probe/block_entity_anim_fixture.rs index e108c53b3..3a3a0ef14 100644 --- a/crates/horizon-client/examples/block_entity_anim_fixture.rs +++ b/crates/horizon-client/examples/probe/block_entity_anim_fixture.rs @@ -118,8 +118,8 @@ fn status(s: ShulkerStatus) -> &'static str { } } -fn main() -> Result<()> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [root, inputs, output] = args.as_slice() else { return Err("usage: block_entity_anim_fixture RESOURCES INPUTS OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/block_entity_render_fixture.rs b/crates/horizon-client/examples/probe/block_entity_render_fixture.rs similarity index 99% rename from crates/horizon-client/examples/block_entity_render_fixture.rs rename to crates/horizon-client/examples/probe/block_entity_render_fixture.rs index d844c4e44..a0e3471bc 100644 --- a/crates/horizon-client/examples/block_entity_render_fixture.rs +++ b/crates/horizon-client/examples/probe/block_entity_render_fixture.rs @@ -110,8 +110,8 @@ fn intern(s: &str) -> &'static str { } } -fn main() -> Result<()> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [root, inputs, textures, output] = args.as_slice() else { return Err("usage: block_entity_render_fixture RESOURCES INPUTS TEXTURES OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/block_entity_tickers_fixture.rs b/crates/horizon-client/examples/probe/block_entity_tickers_fixture.rs similarity index 98% rename from crates/horizon-client/examples/block_entity_tickers_fixture.rs rename to crates/horizon-client/examples/probe/block_entity_tickers_fixture.rs index f08c333f6..d375f1b74 100644 --- a/crates/horizon-client/examples/block_entity_tickers_fixture.rs +++ b/crates/horizon-client/examples/probe/block_entity_tickers_fixture.rs @@ -26,8 +26,8 @@ fn entity(name: &str) -> BlockEntity { .unwrap_or_else(|| panic!("no block entity for {name}")) } -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let input = std::fs::read_to_string(&args[1]).expect("input"); let mut out = String::new(); let mut entities = BlockEntities::default(); diff --git a/crates/horizon-client/examples/block_particles_fixture.rs b/crates/horizon-client/examples/probe/block_particles_fixture.rs similarity index 95% rename from crates/horizon-client/examples/block_particles_fixture.rs rename to crates/horizon-client/examples/probe/block_particles_fixture.rs index 63ef242b7..0e58d99ea 100644 --- a/crates/horizon-client/examples/block_particles_fixture.rs +++ b/crates/horizon-client/examples/probe/block_particles_fixture.rs @@ -8,8 +8,8 @@ use std::{ io::{BufRead, BufReader, BufWriter, Write}, path::Path, }; -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let root = Path::new(&args[1]); let assets = Assets::load(root)?; let render = assets.reload(root)?; diff --git a/crates/horizon-client/examples/block_transform_fixture.rs b/crates/horizon-client/examples/probe/block_transform_fixture.rs similarity index 96% rename from crates/horizon-client/examples/block_transform_fixture.rs rename to crates/horizon-client/examples/probe/block_transform_fixture.rs index 01d92a047..9d8d1d7db 100644 --- a/crates/horizon-client/examples/block_transform_fixture.rs +++ b/crates/horizon-client/examples/probe/block_transform_fixture.rs @@ -51,8 +51,8 @@ impl Around for Column { } } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: block_transform_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/breaking_fixture.rs b/crates/horizon-client/examples/probe/breaking_fixture.rs similarity index 96% rename from crates/horizon-client/examples/breaking_fixture.rs rename to crates/horizon-client/examples/probe/breaking_fixture.rs index da696b88e..c5a816ccd 100644 --- a/crates/horizon-client/examples/breaking_fixture.rs +++ b/crates/horizon-client/examples/probe/breaking_fixture.rs @@ -16,8 +16,8 @@ use std::{ }; /// The stage sprite origin the cracks carry (the oracle compares the geometry and UVs only). const STAGE: [f32; 2] = [0.25, 0.5]; -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let root = Path::new(&args[1]); let assets = Assets::load(root)?; let render = assets.reload(root)?; diff --git a/crates/horizon-client/examples/camera_probe.rs b/crates/horizon-client/examples/probe/camera_probe.rs similarity index 99% rename from crates/horizon-client/examples/camera_probe.rs rename to crates/horizon-client/examples/probe/camera_probe.rs index 2d7f716f0..38f3c23be 100644 --- a/crates/horizon-client/examples/camera_probe.rs +++ b/crates/horizon-client/examples/probe/camera_probe.rs @@ -323,8 +323,8 @@ fn avatar(c: &Value, out: &mut impl Write) -> Result<()> { Ok(()) } -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let input = BufReader::new(File::open(&args[1])?); let mut out = BufWriter::new(File::create(&args[2])?); for (n, line) in input.lines().enumerate() { diff --git a/crates/horizon-client/examples/cauldron_fixture.rs b/crates/horizon-client/examples/probe/cauldron_fixture.rs similarity index 98% rename from crates/horizon-client/examples/cauldron_fixture.rs rename to crates/horizon-client/examples/probe/cauldron_fixture.rs index 6aa942d42..95b075d70 100644 --- a/crates/horizon-client/examples/cauldron_fixture.rs +++ b/crates/horizon-client/examples/probe/cauldron_fixture.rs @@ -70,8 +70,8 @@ fn describe(state: &BlockState) -> String { format!("{}|{}", state.name, props.join(",")) } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: cauldron_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/chat_screen_fixture.rs b/crates/horizon-client/examples/probe/chat_screen_fixture.rs similarity index 95% rename from crates/horizon-client/examples/chat_screen_fixture.rs rename to crates/horizon-client/examples/probe/chat_screen_fixture.rs index c5cba6b9d..229d8d861 100644 --- a/crates/horizon-client/examples/chat_screen_fixture.rs +++ b/crates/horizon-client/examples/probe/chat_screen_fixture.rs @@ -5,6 +5,7 @@ //! the oracle's JSON form. //! //! usage: chat_screen_fixture RESOURCES REGISTRIES CASES OUTPUT +use crate::pack_screen_fixture; use horizon_client::{ chat::{ChatAction, ChatScreen, Commands}, command::vanilla, @@ -15,14 +16,11 @@ use horizon_client::{ use serde_json::{Value, json}; use std::{fmt::Write as _, fs, path::PathBuf}; use winit::keyboard::KeyCode as K; -#[path = "pack_screen_fixture.rs"] -#[allow(dead_code)] -mod pack_screen_fixture; #[path = "chat_screen_fixture/registries.rs"] mod registries; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [root, registries, inputs, output] = args.as_slice() else { return Err("usage: chat_screen_fixture RESOURCES REGISTRIES CASES OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/chat_screen_fixture/registries.rs b/crates/horizon-client/examples/probe/chat_screen_fixture/registries.rs similarity index 100% rename from crates/horizon-client/examples/chat_screen_fixture/registries.rs rename to crates/horizon-client/examples/probe/chat_screen_fixture/registries.rs diff --git a/crates/horizon-client/examples/cloud_fixture.rs b/crates/horizon-client/examples/probe/cloud_fixture.rs similarity index 92% rename from crates/horizon-client/examples/cloud_fixture.rs rename to crates/horizon-client/examples/probe/cloud_fixture.rs index 7c00bfb3a..4ba072dbb 100644 --- a/crates/horizon-client/examples/cloud_fixture.rs +++ b/crates/horizon-client/examples/probe/cloud_fixture.rs @@ -1,8 +1,8 @@ //! CloudRenderer face selection and mesh traversal, without a GPU. use horizon_client::clouds; use std::{fmt::Write, fs}; -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let mut output = String::new(); for (case, line) in fs::read_to_string(&args[1])?.lines().enumerate() { let values: Vec = line diff --git a/crates/horizon-client/examples/command_parse_fixture.rs b/crates/horizon-client/examples/probe/command_parse_fixture.rs similarity index 99% rename from crates/horizon-client/examples/command_parse_fixture.rs rename to crates/horizon-client/examples/probe/command_parse_fixture.rs index 1cc1f95d5..17437cd72 100644 --- a/crates/horizon-client/examples/command_parse_fixture.rs +++ b/crates/horizon-client/examples/probe/command_parse_fixture.rs @@ -132,8 +132,8 @@ fn tree(d: &Dispatcher, node: usize) -> Value { v } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); if args.get(1).map(String::as_str) == Some("tree") { let d = &vanilla::registered(false); let mut v = tree(d, 0); diff --git a/crates/horizon-client/examples/container_screen_probe.rs b/crates/horizon-client/examples/probe/container_screen_probe.rs similarity index 97% rename from crates/horizon-client/examples/container_screen_probe.rs rename to crates/horizon-client/examples/probe/container_screen_probe.rs index b89b23a2a..e82b5bdf5 100644 --- a/crates/horizon-client/examples/container_screen_probe.rs +++ b/crates/horizon-client/examples/probe/container_screen_probe.rs @@ -24,8 +24,8 @@ fn input_name(input: Input) -> &'static str { } } -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let input = BufReader::new(File::open(&args[1])?); let mut out = BufWriter::new(File::create(&args[2])?); for (n, line) in input.lines().enumerate() { diff --git a/crates/horizon-client/examples/creative_search_fixture.rs b/crates/horizon-client/examples/probe/creative_search_fixture.rs similarity index 95% rename from crates/horizon-client/examples/creative_search_fixture.rs rename to crates/horizon-client/examples/probe/creative_search_fixture.rs index 628e0486d..1f4f04b37 100644 --- a/crates/horizon-client/examples/creative_search_fixture.rs +++ b/crates/horizon-client/examples/probe/creative_search_fixture.rs @@ -11,8 +11,8 @@ use horizon_client::{ use serde_json::{Value, json}; use std::{fs, path::Path}; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let usage = "usage: creative_search_fixture RESOURCES CREATIVE_JSON VANILLA_JSON OUTPUT"; let names = Names::load(Path::new(args.get(1).ok_or(usage)?)); let creative = Creative::from_json(&serde_json::from_slice(&fs::read( diff --git a/crates/horizon-client/examples/probe/dispatch.rs b/crates/horizon-client/examples/probe/dispatch.rs new file mode 100644 index 000000000..b40cf1a6e --- /dev/null +++ b/crates/horizon-client/examples/probe/dispatch.rs @@ -0,0 +1,49 @@ +//! How the probe binary runs a probe. main.rs lists the probes and nothing else (tools/parity.py leaves it out of +//! the harnesses' dependencies); code every probe relies on goes here. +use std::process::ExitCode; + +/// `probes! { a, b, }` declares the binary's `main`, which runs the probe module named by its first argument. +macro_rules! probes { + ($($name:ident,)*) => { + fn run(name: &str) -> Option { + use std::process::Termination; + Some(match name { + $(stringify!($name) => $name::main().report(),)* + _ => return None, + }) + } + + fn main() -> std::process::ExitCode { + dispatch::main(&[$(stringify!($name)),*], run) + } + }; +} + +/// The probe's command line as its own example saw it: the program, then the arguments after the probe's name. +pub fn args() -> std::vec::IntoIter { + let mut args: Vec = std::env::args().collect(); + if args.len() > 1 { + args.remove(1); + } + args.into_iter() +} + +/// args(), as OsStrings. +pub fn args_os() -> std::vec::IntoIter { + let mut args: Vec<_> = std::env::args_os().collect(); + if args.len() > 1 { + args.remove(1); + } + args.into_iter() +} + +pub fn main(names: &[&str], run: fn(&str) -> Option) -> ExitCode { + let name = std::env::args().nth(1).unwrap_or_default(); + run(&name).unwrap_or_else(|| { + eprintln!( + "usage: probe [arguments...]\nprobes: {}", + names.join(" ") + ); + ExitCode::from(2) + }) +} diff --git a/crates/horizon-client/examples/emitter_particles_probe.rs b/crates/horizon-client/examples/probe/emitter_particles_probe.rs similarity index 96% rename from crates/horizon-client/examples/emitter_particles_probe.rs rename to crates/horizon-client/examples/probe/emitter_particles_probe.rs index 7469bb368..6349eb8dc 100644 --- a/crates/horizon-client/examples/emitter_particles_probe.rs +++ b/crates/horizon-client/examples/probe/emitter_particles_probe.rs @@ -14,8 +14,8 @@ fn d(v: f64) -> String { format!("{:016x}", v.to_bits()) } -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let mut out = BufWriter::new(File::create(&args[2])?); for (n, line) in BufReader::new(File::open(&args[1])?).lines().enumerate() { let c: Value = serde_json::from_str(&line?)?; diff --git a/crates/horizon-client/examples/enchanting_fixture.rs b/crates/horizon-client/examples/probe/enchanting_fixture.rs similarity index 94% rename from crates/horizon-client/examples/enchanting_fixture.rs rename to crates/horizon-client/examples/probe/enchanting_fixture.rs index 736b9189e..4c0fe6350 100644 --- a/crates/horizon-client/examples/enchanting_fixture.rs +++ b/crates/horizon-client/examples/probe/enchanting_fixture.rs @@ -10,8 +10,8 @@ use horizon_client::{ }; use std::{fmt::Write as _, fs, path::Path}; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: enchanting_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/entity_anim_fixture.rs b/crates/horizon-client/examples/probe/entity_anim_fixture.rs similarity index 99% rename from crates/horizon-client/examples/entity_anim_fixture.rs rename to crates/horizon-client/examples/probe/entity_anim_fixture.rs index e5a146ef9..0a2e2951f 100644 --- a/crates/horizon-client/examples/entity_anim_fixture.rs +++ b/crates/horizon-client/examples/probe/entity_anim_fixture.rs @@ -3,7 +3,7 @@ //! posed model with `mobs::render::draw` under the case's living-entity root //! transform and writes each drawn part's packed vertex normals. //! -//! cargo run --profile fast -p horizon-client --example entity_anim_fixture -- \ +//! cargo run --profile fast -p horizon-client --example probe -- entity_anim_fixture \ //! RESOURCES VANILLA.jsonl OUT.jsonl use horizon_client::mesher::Vertex; use horizon_client::mobs::{ @@ -288,8 +288,8 @@ fn entity_state(mob: &mut Mob, species: Species, case: &Value) { } } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().skip(1).collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().skip(1).collect(); let root = PathBuf::from(&args[0]); let types = MobTypes::load(&root)?; let animations = MobData::load_animations(&root); diff --git a/crates/horizon-client/examples/entity_components_probe.rs b/crates/horizon-client/examples/probe/entity_components_probe.rs similarity index 96% rename from crates/horizon-client/examples/entity_components_probe.rs rename to crates/horizon-client/examples/probe/entity_components_probe.rs index 0d4a51e8c..2b1c3233f 100644 --- a/crates/horizon-client/examples/entity_components_probe.rs +++ b/crates/horizon-client/examples/probe/entity_components_probe.rs @@ -61,8 +61,8 @@ fn species(id: &str) -> Species { } } -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let input = BufReader::new(File::open(&args[1])?); let mut out = BufWriter::new(File::create(&args[2])?); for (n, line) in input.lines().enumerate() { diff --git a/crates/horizon-client/examples/entity_death_loot_fixture.rs b/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs similarity index 99% rename from crates/horizon-client/examples/entity_death_loot_fixture.rs rename to crates/horizon-client/examples/probe/entity_death_loot_fixture.rs index a8eceb8ca..86ef275d9 100644 --- a/crates/horizon-client/examples/entity_death_loot_fixture.rs +++ b/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs @@ -53,8 +53,8 @@ fn line(s: &LootStack) -> String { out } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: entity_death_loot_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/entity_particles_probe.rs b/crates/horizon-client/examples/probe/entity_particles_probe.rs similarity index 95% rename from crates/horizon-client/examples/entity_particles_probe.rs rename to crates/horizon-client/examples/probe/entity_particles_probe.rs index ef38f1000..cdb0344df 100644 --- a/crates/horizon-client/examples/entity_particles_probe.rs +++ b/crates/horizon-client/examples/probe/entity_particles_probe.rs @@ -13,8 +13,8 @@ fn d(v: f64) -> String { format!("{:016x}", v.to_bits()) } -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let mut out = BufWriter::new(File::create(&args[2])?); for (n, line) in BufReader::new(File::open(&args[1])?).lines().enumerate() { let c: Value = serde_json::from_str(&line?)?; diff --git a/crates/horizon-client/examples/environment_fixture.rs b/crates/horizon-client/examples/probe/environment_fixture.rs similarity index 97% rename from crates/horizon-client/examples/environment_fixture.rs rename to crates/horizon-client/examples/probe/environment_fixture.rs index 7f331962a..27846fe82 100644 --- a/crates/horizon-client/examples/environment_fixture.rs +++ b/crates/horizon-client/examples/probe/environment_fixture.rs @@ -9,8 +9,8 @@ use horizon_client::{ }; use std::{collections::HashMap, fmt::Write as _, fs, path::Path}; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: environment_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/finalize_spawn_fixture.rs b/crates/horizon-client/examples/probe/finalize_spawn_fixture.rs similarity index 99% rename from crates/horizon-client/examples/finalize_spawn_fixture.rs rename to crates/horizon-client/examples/probe/finalize_spawn_fixture.rs index 9b1ba4f38..b1b25e723 100644 --- a/crates/horizon-client/examples/finalize_spawn_fixture.rs +++ b/crates/horizon-client/examples/probe/finalize_spawn_fixture.rs @@ -388,8 +388,8 @@ fn describe(m: &Mob, all: &[Mob], regs: &SpawnRegistries) -> String { t.join(" ") } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: finalize_spawn_fixture RESOURCES INPUT OUTPUT HALLOWEEN")?, diff --git a/crates/horizon-client/examples/fire_starter_sound_probe.rs b/crates/horizon-client/examples/probe/fire_starter_sound_probe.rs similarity index 91% rename from crates/horizon-client/examples/fire_starter_sound_probe.rs rename to crates/horizon-client/examples/probe/fire_starter_sound_probe.rs index 62fab117a..18c1b487a 100644 --- a/crates/horizon-client/examples/fire_starter_sound_probe.rs +++ b/crates/horizon-client/examples/probe/fire_starter_sound_probe.rs @@ -11,8 +11,8 @@ use std::{ io::{BufRead, BufReader, BufWriter, Write}, }; -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let input = BufReader::new(File::open(&args[1])?); let mut out = BufWriter::new(File::create(&args[2])?); for line in input.lines() { diff --git a/crates/horizon-client/examples/firework_tooltip_fixture.rs b/crates/horizon-client/examples/probe/firework_tooltip_fixture.rs similarity index 92% rename from crates/horizon-client/examples/firework_tooltip_fixture.rs rename to crates/horizon-client/examples/probe/firework_tooltip_fixture.rs index 7f10278b7..385776837 100644 --- a/crates/horizon-client/examples/firework_tooltip_fixture.rs +++ b/crates/horizon-client/examples/probe/firework_tooltip_fixture.rs @@ -4,8 +4,8 @@ use horizon_client::{enchant::Enchantments, item_data::parse_stack, item_tooltip::firework_lines}; use std::{error::Error, fmt::Write, path::PathBuf}; -fn main() -> Result<(), Box> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec = crate::args().collect(); let input = std::fs::read_to_string(&args[1])?; let root = input .lines() diff --git a/crates/horizon-client/examples/first_person_probe.rs b/crates/horizon-client/examples/probe/first_person_probe.rs similarity index 99% rename from crates/horizon-client/examples/first_person_probe.rs rename to crates/horizon-client/examples/probe/first_person_probe.rs index 7b1143114..cb4c38e58 100644 --- a/crates/horizon-client/examples/first_person_probe.rs +++ b/crates/horizon-client/examples/probe/first_person_probe.rs @@ -458,8 +458,8 @@ impl HandWorld for ResetWorld<'_, '_> { } } -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let input = BufReader::new(File::open(&args[1])?); let mut out = BufWriter::new(File::create(&args[2])?); for (n, line) in input.lines().enumerate() { diff --git a/crates/horizon-client/examples/frame_limiter_probe.rs b/crates/horizon-client/examples/probe/frame_limiter_probe.rs similarity index 97% rename from crates/horizon-client/examples/frame_limiter_probe.rs rename to crates/horizon-client/examples/probe/frame_limiter_probe.rs index 7a5d4e437..b11338afc 100644 --- a/crates/horizon-client/examples/frame_limiter_probe.rs +++ b/crates/horizon-client/examples/probe/frame_limiter_probe.rs @@ -50,8 +50,8 @@ impl LimiterClock for Script { } } -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let input = BufReader::new(File::open(&args[1])?); let mut out = BufWriter::new(File::create(&args[2])?); for (n, line) in input.lines().enumerate() { diff --git a/crates/horizon-client/examples/game_loop_probe.rs b/crates/horizon-client/examples/probe/game_loop_probe.rs similarity index 99% rename from crates/horizon-client/examples/game_loop_probe.rs rename to crates/horizon-client/examples/probe/game_loop_probe.rs index 66a428162..598f480e6 100644 --- a/crates/horizon-client/examples/game_loop_probe.rs +++ b/crates/horizon-client/examples/probe/game_loop_probe.rs @@ -291,8 +291,8 @@ fn key(c: &Value, out: &mut impl Write) -> Result<()> { Ok(()) } -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); let mut out = BufWriter::new(File::create(&args[1])?); for line in BufReader::new(File::open(&args[0])?).lines() { let c: Value = serde_json::from_str(&line?)?; diff --git a/crates/horizon-client/examples/ghost_recipe_fixture.rs b/crates/horizon-client/examples/probe/ghost_recipe_fixture.rs similarity index 96% rename from crates/horizon-client/examples/ghost_recipe_fixture.rs rename to crates/horizon-client/examples/probe/ghost_recipe_fixture.rs index 0860fd409..b8c6553be 100644 --- a/crates/horizon-client/examples/ghost_recipe_fixture.rs +++ b/crates/horizon-client/examples/probe/ghost_recipe_fixture.rs @@ -13,8 +13,8 @@ use horizon_client::{ use serde_json::Value; use std::{fmt::Write as _, fs, path::Path}; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let usage = "usage: ghost_recipe_fixture RESOURCES CASES OUTPUT"; let root = Path::new(args.get(1).ok_or(usage)?); let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?; diff --git a/crates/horizon-client/examples/held_drop_fixture.rs b/crates/horizon-client/examples/probe/held_drop_fixture.rs similarity index 98% rename from crates/horizon-client/examples/held_drop_fixture.rs rename to crates/horizon-client/examples/probe/held_drop_fixture.rs index a0c5d92ba..1275021bb 100644 --- a/crates/horizon-client/examples/held_drop_fixture.rs +++ b/crates/horizon-client/examples/probe/held_drop_fixture.rs @@ -2,7 +2,7 @@ use horizon_client::command::args::GameMode; use horizon_client::items::{ItemStack, take_held_drop}; -fn main() { +pub fn main() { for mode in [ GameMode::Survival, GameMode::Creative, diff --git a/crates/horizon-client/examples/hotbar_fixture.rs b/crates/horizon-client/examples/probe/hotbar_fixture.rs similarity index 94% rename from crates/horizon-client/examples/hotbar_fixture.rs rename to crates/horizon-client/examples/probe/hotbar_fixture.rs index beac564ec..4c89a919f 100644 --- a/crates/horizon-client/examples/hotbar_fixture.rs +++ b/crates/horizon-client/examples/probe/hotbar_fixture.rs @@ -10,8 +10,8 @@ use serde_json::Value; use std::path::Path; use std::{fmt::Write as _, fs}; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let usage = "usage: hotbar_fixture RESOURCES CASES OUTPUT"; let items = Items::catalog(Path::new(args.first().and(args.get(1)).ok_or(usage)?))?; let known = |id: &str| items.get(id).is_some(); diff --git a/crates/horizon-client/examples/hud_fixture.rs b/crates/horizon-client/examples/probe/hud_fixture.rs similarity index 98% rename from crates/horizon-client/examples/hud_fixture.rs rename to crates/horizon-client/examples/probe/hud_fixture.rs index 4a4c78869..a6f27fcda 100644 --- a/crates/horizon-client/examples/hud_fixture.rs +++ b/crates/horizon-client/examples/probe/hud_fixture.rs @@ -20,8 +20,8 @@ type Result = std::result::Result>; #[path = "hud_fixture/kinds.rs"] mod kinds; -fn main() -> Result<()> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [root, inputs, output] = args.as_slice() else { return Err("usage: hud_fixture RESOURCES INPUTS OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/hud_fixture/kinds.rs b/crates/horizon-client/examples/probe/hud_fixture/kinds.rs similarity index 100% rename from crates/horizon-client/examples/hud_fixture/kinds.rs rename to crates/horizon-client/examples/probe/hud_fixture/kinds.rs diff --git a/crates/horizon-client/examples/input_probe.rs b/crates/horizon-client/examples/probe/input_probe.rs similarity index 94% rename from crates/horizon-client/examples/input_probe.rs rename to crates/horizon-client/examples/probe/input_probe.rs index b628bce5d..ae66f77a6 100644 --- a/crates/horizon-client/examples/input_probe.rs +++ b/crates/horizon-client/examples/probe/input_probe.rs @@ -11,8 +11,8 @@ fn number(v: &Value) -> f32 { fn bits(v: f32) -> u32 { if v.is_nan() { 0x7fc00000 } else { v.to_bits() } } -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); let mut out = BufWriter::new(File::create(&args[1])?); for line in BufReader::new(File::open(&args[0])?).lines() { let f: Value = serde_json::from_str(&line?)?; diff --git a/crates/horizon-client/examples/interaction_input_fixture.rs b/crates/horizon-client/examples/probe/interaction_input_fixture.rs similarity index 96% rename from crates/horizon-client/examples/interaction_input_fixture.rs rename to crates/horizon-client/examples/probe/interaction_input_fixture.rs index bb408dd88..a6beffc05 100644 --- a/crates/horizon-client/examples/interaction_input_fixture.rs +++ b/crates/horizon-client/examples/probe/interaction_input_fixture.rs @@ -82,8 +82,8 @@ impl TargetUseWorld for World { } } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let input = std::io::BufReader::new(std::fs::File::open(&args[1])?); let mut out = std::io::BufWriter::new(std::fs::File::create(&args[2])?); for (i, line) in input.lines().enumerate() { diff --git a/crates/horizon-client/examples/lan_probe.rs b/crates/horizon-client/examples/probe/lan_probe.rs similarity index 96% rename from crates/horizon-client/examples/lan_probe.rs rename to crates/horizon-client/examples/probe/lan_probe.rs index 43ce51f9d..3be556e3b 100644 --- a/crates/horizon-client/examples/lan_probe.rs +++ b/crates/horizon-client/examples/probe/lan_probe.rs @@ -14,8 +14,8 @@ fn unhex(s: &str) -> Vec { .collect() } -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let cases = std::fs::read_to_string(&args[1]).unwrap(); let mut out = String::new(); let mut games: Vec = Vec::new(); diff --git a/crates/horizon-client/examples/light_parity.rs b/crates/horizon-client/examples/probe/light_parity.rs similarity index 98% rename from crates/horizon-client/examples/light_parity.rs rename to crates/horizon-client/examples/probe/light_parity.rs index f660189a2..41c2ba784 100644 --- a/crates/horizon-client/examples/light_parity.rs +++ b/crates/horizon-client/examples/probe/light_parity.rs @@ -2,7 +2,7 @@ //! server with Horizon's light engine and compare every SkyLight/BlockLight //! value with the arrays vanilla stored. //! -//! cargo run --profile fast -p horizon-client --example light_parity -- \ +//! cargo run --profile fast -p horizon-client --example probe -- light_parity \ //! RESOURCES DIMENSION_DIR [--nether] [--chunks X0 Z0 X1 Z1] use horizon_client::{ assets::Assets, @@ -21,8 +21,8 @@ use std::{collections::HashMap, path::PathBuf}; type Arrays = HashMap>, Option>)>; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().skip(1).collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().skip(1).collect(); let root = PathBuf::from( args.first() .ok_or("usage: light_parity RESOURCES DIMENSION_DIR")?, diff --git a/crates/horizon-client/examples/probe/main.rs b/crates/horizon-client/examples/probe/main.rs new file mode 100644 index 000000000..d110ea790 --- /dev/null +++ b/crates/horizon-client/examples/probe/main.rs @@ -0,0 +1,178 @@ +//! Every horizon-client parity probe in one binary: `probe [arguments]` runs `.rs` as its own +//! example did (tools/test_*_parity.py, tools/oracle_harness.py, tools/audio_harness.py). Linking ~80 examples, +//! each with the whole client in it, was most of the parity job's probe build; one binary builds it once. +//! +//! This file only lists the probes, so that adding one reruns no harness: tools/parity.py leaves it out of +//! their dependencies. How a probe runs is in dispatch.rs. +#[macro_use] +mod dispatch; + +use dispatch::{args, args_os}; + +mod ambient_fixture; +mod arrow_probe; +mod audio_attributes_fixture; +/// Sound-engine fakes the audio probes share. +mod audio_common; +mod auto_jump_probe; +mod block_entity_anim_fixture; +mod block_entity_render_fixture; +mod block_entity_tickers_fixture; +mod block_particles_fixture; +mod block_transform_fixture; +mod breaking_fixture; +mod camera_probe; +mod cauldron_fixture; +mod chat_screen_fixture; +mod cloud_fixture; +mod command_parse_fixture; +mod container_screen_probe; +mod creative_search_fixture; +mod emitter_particles_probe; +mod enchanting_fixture; +mod entity_anim_fixture; +mod entity_components_probe; +mod entity_death_loot_fixture; +mod entity_particles_probe; +mod environment_fixture; +mod finalize_spawn_fixture; +mod fire_starter_sound_probe; +mod firework_tooltip_fixture; +mod first_person_probe; +mod frame_limiter_probe; +mod game_loop_probe; +mod ghost_recipe_fixture; +mod held_drop_fixture; +mod hotbar_fixture; +mod hud_fixture; +mod input_probe; +mod interaction_input_fixture; +mod lan_probe; +mod light_parity; +mod marker_particles_probe; +mod menu_fixture; +mod mipmap_probe; +mod mob_ai_probe; +mod mob_attributes_fixture; +mod music_fixture; +mod natural_spawn_fixture; +mod options_probe; +mod pack_resources_fixture; +mod pack_screen_fixture; +mod pack_selection_fixture; +mod particle_providers_probe; +mod pick_block_data_fixture; +mod place_recipe_fixture; +mod player_sync_fixture; +mod raid_fixture; +mod random_tick_sections_probe; +mod recipe_book_fixture; +mod recipe_book_render_fixture; +mod recipe_book_view_fixture; +mod recipe_fixture; +mod scene_collision_probe; +mod scene_motion_probe; +mod scoreboard_fixture; +mod screen_layout_fixture; +mod section_mesh_fixture; +mod server_files_probe; +mod situational_music_fixture; +mod skin_image_fixture; +mod sound_engine_fixture; +mod sound_event_fixture; +mod spawn_rules_fixture; +mod sprint_probe; +mod subtitle_fixture; +mod tab_list_fixture; +mod team_rules_fixture; +mod toggle_keys_probe; +mod tooltip_display_fixture; +mod trading_fixture; +mod translucency_fixture; +mod weather_fixture; +mod world_border_render_fixture; +mod world_options_fixture; + +probes! { + ambient_fixture, + arrow_probe, + audio_attributes_fixture, + auto_jump_probe, + block_entity_anim_fixture, + block_entity_render_fixture, + block_entity_tickers_fixture, + block_particles_fixture, + block_transform_fixture, + breaking_fixture, + camera_probe, + cauldron_fixture, + chat_screen_fixture, + cloud_fixture, + command_parse_fixture, + container_screen_probe, + creative_search_fixture, + emitter_particles_probe, + enchanting_fixture, + entity_anim_fixture, + entity_components_probe, + entity_death_loot_fixture, + entity_particles_probe, + environment_fixture, + finalize_spawn_fixture, + fire_starter_sound_probe, + firework_tooltip_fixture, + first_person_probe, + frame_limiter_probe, + game_loop_probe, + ghost_recipe_fixture, + held_drop_fixture, + hotbar_fixture, + hud_fixture, + input_probe, + interaction_input_fixture, + lan_probe, + light_parity, + marker_particles_probe, + menu_fixture, + mipmap_probe, + mob_ai_probe, + mob_attributes_fixture, + music_fixture, + natural_spawn_fixture, + options_probe, + pack_resources_fixture, + pack_screen_fixture, + pack_selection_fixture, + particle_providers_probe, + pick_block_data_fixture, + place_recipe_fixture, + player_sync_fixture, + raid_fixture, + random_tick_sections_probe, + recipe_book_fixture, + recipe_book_render_fixture, + recipe_book_view_fixture, + recipe_fixture, + scene_collision_probe, + scene_motion_probe, + scoreboard_fixture, + screen_layout_fixture, + section_mesh_fixture, + server_files_probe, + situational_music_fixture, + skin_image_fixture, + sound_engine_fixture, + sound_event_fixture, + spawn_rules_fixture, + sprint_probe, + subtitle_fixture, + tab_list_fixture, + team_rules_fixture, + toggle_keys_probe, + tooltip_display_fixture, + trading_fixture, + translucency_fixture, + weather_fixture, + world_border_render_fixture, + world_options_fixture, +} diff --git a/crates/horizon-client/examples/marker_particles_probe.rs b/crates/horizon-client/examples/probe/marker_particles_probe.rs similarity index 97% rename from crates/horizon-client/examples/marker_particles_probe.rs rename to crates/horizon-client/examples/probe/marker_particles_probe.rs index edf624e73..190751d79 100644 --- a/crates/horizon-client/examples/marker_particles_probe.rs +++ b/crates/horizon-client/examples/probe/marker_particles_probe.rs @@ -22,8 +22,8 @@ use std::{ sync::Arc, }; -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new(".local/horizon-client/26.3"); let assets = Assets::load(root)?; let facts = BlockFacts::load(root, assets.registry)?; diff --git a/crates/horizon-client/examples/menu_fixture.rs b/crates/horizon-client/examples/probe/menu_fixture.rs similarity index 98% rename from crates/horizon-client/examples/menu_fixture.rs rename to crates/horizon-client/examples/probe/menu_fixture.rs index 1da4a0278..fd226ff88 100644 --- a/crates/horizon-client/examples/menu_fixture.rs +++ b/crates/horizon-client/examples/probe/menu_fixture.rs @@ -74,8 +74,8 @@ fn state(menu: &Menu) -> String { format!("{line} | inv{items}") } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: menu_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/mipmap_probe.rs b/crates/horizon-client/examples/probe/mipmap_probe.rs similarity index 94% rename from crates/horizon-client/examples/mipmap_probe.rs rename to crates/horizon-client/examples/probe/mipmap_probe.rs index 99155fb32..fa94f4e90 100644 --- a/crates/horizon-client/examples/mipmap_probe.rs +++ b/crates/horizon-client/examples/probe/mipmap_probe.rs @@ -4,8 +4,8 @@ //! rows like VanillaMipmapOracle. use std::{fmt::Write as _, fs, path::Path}; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().skip(1).collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().skip(1).collect(); let input = fs::read_to_string(&args[0])?; let mut lines = input.lines(); let root = Path::new(lines.next().ok_or("no resources root")?); diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/probe/mob_ai_probe.rs similarity index 99% rename from crates/horizon-client/examples/mob_ai_probe.rs rename to crates/horizon-client/examples/probe/mob_ai_probe.rs index a3abb54d9..d773a509b 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/probe/mob_ai_probe.rs @@ -759,8 +759,8 @@ fn villager(m: &Mob) -> String { s } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().skip(1).collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().skip(1).collect(); if args.len() != 3 { return Err("usage: mob_ai_probe RESOURCES SCENARIOS OUTPUT".into()); } diff --git a/crates/horizon-client/examples/mob_attributes_fixture.rs b/crates/horizon-client/examples/probe/mob_attributes_fixture.rs similarity index 95% rename from crates/horizon-client/examples/mob_attributes_fixture.rs rename to crates/horizon-client/examples/probe/mob_attributes_fixture.rs index 7f8359920..f1fcec701 100644 --- a/crates/horizon-client/examples/mob_attributes_fixture.rs +++ b/crates/horizon-client/examples/probe/mob_attributes_fixture.rs @@ -6,8 +6,8 @@ use horizon_client::mobs::{Mob, MobTypes}; use horizon_core::geometry::Vec3; use std::{fmt::Write as _, fs, path::Path, sync::Arc}; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: mob_attributes_fixture RESOURCES OUTPUT")?, diff --git a/crates/horizon-client/examples/music_fixture.rs b/crates/horizon-client/examples/probe/music_fixture.rs similarity index 97% rename from crates/horizon-client/examples/music_fixture.rs rename to crates/horizon-client/examples/probe/music_fixture.rs index 29ccb99b2..02aecb373 100644 --- a/crates/horizon-client/examples/music_fixture.rs +++ b/crates/horizon-client/examples/probe/music_fixture.rs @@ -1,7 +1,6 @@ //! Replays `tools/test_music_parity.py` scripts through Horizon's //! `MusicManager` over its `SoundEngine`: `music_fixture ROOT INPUT OUTPUT`. -#[path = "audio_common/mod.rs"] -mod common; +use crate::audio_common as common; use common::{Fake, describe, f, flush}; use horizon_client::music::{Music, MusicFrequency, MusicManager}; use horizon_client::sound_engine::{Bound, MUSIC, SoundEngine, TickContext}; @@ -21,8 +20,8 @@ fn music(spec: &str) -> Option { )) } -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let mut engine = SoundEngine::new(SoundRegistry::load(std::path::Path::new(&args[1]))); engine.listening = true; let mut backend = Fake::default(); diff --git a/crates/horizon-client/examples/natural_spawn_fixture.rs b/crates/horizon-client/examples/probe/natural_spawn_fixture.rs similarity index 99% rename from crates/horizon-client/examples/natural_spawn_fixture.rs rename to crates/horizon-client/examples/probe/natural_spawn_fixture.rs index e4c9b1ce6..c19adc4e1 100644 --- a/crates/horizon-client/examples/natural_spawn_fixture.rs +++ b/crates/horizon-client/examples/probe/natural_spawn_fixture.rs @@ -508,8 +508,8 @@ fn yaw_text(entity: &str, v: f32) -> String { } } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: natural_spawn_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/options_probe.rs b/crates/horizon-client/examples/probe/options_probe.rs similarity index 94% rename from crates/horizon-client/examples/options_probe.rs rename to crates/horizon-client/examples/probe/options_probe.rs index f186af994..97c76c030 100644 --- a/crates/horizon-client/examples/options_probe.rs +++ b/crates/horizon-client/examples/probe/options_probe.rs @@ -7,8 +7,8 @@ use horizon_client::{ }; use std::{fs, io::Write}; -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); let mut names: Vec<_> = fs::read_dir(&args[0])? .map(|e| e.map(|e| e.path())) .collect::>()?; diff --git a/crates/horizon-client/examples/pack_resources_fixture.rs b/crates/horizon-client/examples/probe/pack_resources_fixture.rs similarity index 97% rename from crates/horizon-client/examples/pack_resources_fixture.rs rename to crates/horizon-client/examples/probe/pack_resources_fixture.rs index 00238fa94..80dbf3496 100644 --- a/crates/horizon-client/examples/pack_resources_fixture.rs +++ b/crates/horizon-client/examples/probe/pack_resources_fixture.rs @@ -30,8 +30,8 @@ fn types(root: &std::path::Path, file: PathBuf, key: &str) -> String { }) .collect() } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let input = fs::read_to_string(&args[1])?; let mut lines = input.lines(); let root: Vec<&str> = lines.next().ok_or("empty input")?.split(' ').collect(); diff --git a/crates/horizon-client/examples/pack_screen_fixture.rs b/crates/horizon-client/examples/probe/pack_screen_fixture.rs similarity index 98% rename from crates/horizon-client/examples/pack_screen_fixture.rs rename to crates/horizon-client/examples/probe/pack_screen_fixture.rs index ca7cba7b8..881570990 100644 --- a/crates/horizon-client/examples/pack_screen_fixture.rs +++ b/crates/horizon-client/examples/probe/pack_screen_fixture.rs @@ -66,8 +66,8 @@ pub fn encode(draws: &[Draw]) -> Value { ) } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [root, inputs, output] = args.as_slice() else { return Err("usage: pack_screen_fixture RESOURCES CASES OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/pack_selection_fixture.rs b/crates/horizon-client/examples/probe/pack_selection_fixture.rs similarity index 96% rename from crates/horizon-client/examples/pack_selection_fixture.rs rename to crates/horizon-client/examples/probe/pack_selection_fixture.rs index 65ed2471a..91c587343 100644 --- a/crates/horizon-client/examples/pack_selection_fixture.rs +++ b/crates/horizon-client/examples/probe/pack_selection_fixture.rs @@ -35,8 +35,8 @@ fn lists(m: &SelectionModel) -> Value { json!({"unselected": side(false), "selected": side(true)}) } -fn main() -> Result<()> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [inputs, output] = args.as_slice() else { return Err("usage: pack_selection_fixture INPUTS OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/particle_providers_probe.rs b/crates/horizon-client/examples/probe/particle_providers_probe.rs similarity index 99% rename from crates/horizon-client/examples/particle_providers_probe.rs rename to crates/horizon-client/examples/probe/particle_providers_probe.rs index 8b8bd1e0d..c8cd9d88d 100644 --- a/crates/horizon-client/examples/particle_providers_probe.rs +++ b/crates/horizon-client/examples/probe/particle_providers_probe.rs @@ -140,8 +140,8 @@ fn world(assets: &Assets, facts: &BlockFacts, floor: bool, water: bool) -> Resul Ok(world) } -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let root = &Path::new(".local/horizon-client").join(horizon_core::VANILLA_VERSION); let assets = Assets::load(root)?; let facts = BlockFacts::load(root, assets.registry)?; diff --git a/crates/horizon-client/examples/pick_block_data_fixture.rs b/crates/horizon-client/examples/probe/pick_block_data_fixture.rs similarity index 96% rename from crates/horizon-client/examples/pick_block_data_fixture.rs rename to crates/horizon-client/examples/probe/pick_block_data_fixture.rs index b47f56733..7496ceb8e 100644 --- a/crates/horizon-client/examples/pick_block_data_fixture.rs +++ b/crates/horizon-client/examples/probe/pick_block_data_fixture.rs @@ -78,8 +78,8 @@ fn case(line: &str) -> Option { Some(out) } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let input = fs::read_to_string( args.get(1) .ok_or("usage: pick_block_data_fixture INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/place_recipe_fixture.rs b/crates/horizon-client/examples/probe/place_recipe_fixture.rs similarity index 97% rename from crates/horizon-client/examples/place_recipe_fixture.rs rename to crates/horizon-client/examples/probe/place_recipe_fixture.rs index 1e2b66dbf..e59750aaf 100644 --- a/crates/horizon-client/examples/place_recipe_fixture.rs +++ b/crates/horizon-client/examples/probe/place_recipe_fixture.rs @@ -28,8 +28,8 @@ fn state(menu: &Menu) -> String { ) } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let usage = "usage: place_recipe_fixture RESOURCES CASES ORDERS OUTPUT"; let root = Path::new(args.get(1).ok_or(usage)?); let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?; diff --git a/crates/horizon-client/examples/player_sync_fixture.rs b/crates/horizon-client/examples/probe/player_sync_fixture.rs similarity index 96% rename from crates/horizon-client/examples/player_sync_fixture.rs rename to crates/horizon-client/examples/probe/player_sync_fixture.rs index b50a672af..034aa6400 100644 --- a/crates/horizon-client/examples/player_sync_fixture.rs +++ b/crates/horizon-client/examples/probe/player_sync_fixture.rs @@ -8,8 +8,8 @@ fn number(value: &Value) -> f64 { f64::from_bits(u64::from_str_radix(value.as_str().unwrap(), 16).unwrap()) } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let input = std::io::BufReader::new(std::fs::File::open(&args[1])?); let mut out = std::io::BufWriter::new(std::fs::File::create(&args[2])?); for line in input.lines() { diff --git a/crates/horizon-client/examples/raid_fixture.rs b/crates/horizon-client/examples/probe/raid_fixture.rs similarity index 99% rename from crates/horizon-client/examples/raid_fixture.rs rename to crates/horizon-client/examples/probe/raid_fixture.rs index dfe517e51..648851474 100644 --- a/crates/horizon-client/examples/raid_fixture.rs +++ b/crates/horizon-client/examples/probe/raid_fixture.rs @@ -459,8 +459,8 @@ fn run_codec(c: &BTreeMap<&str, &str>) -> Result { Ok(log.join(" ; ")) } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: raid_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/random_tick_sections_probe.rs b/crates/horizon-client/examples/probe/random_tick_sections_probe.rs similarity index 98% rename from crates/horizon-client/examples/random_tick_sections_probe.rs rename to crates/horizon-client/examples/probe/random_tick_sections_probe.rs index 91c861f45..27eaf8196 100644 --- a/crates/horizon-client/examples/random_tick_sections_probe.rs +++ b/crates/horizon-client/examples/probe/random_tick_sections_probe.rs @@ -51,8 +51,8 @@ impl LevelAccess for Air { fn emit(&mut self, _: LevelEvent) {} } -fn main() -> Result<(), Box> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec = crate::args().collect(); let input = std::fs::read_to_string(&args[1])?; let root = input .lines() diff --git a/crates/horizon-client/examples/recipe_book_fixture.rs b/crates/horizon-client/examples/probe/recipe_book_fixture.rs similarity index 98% rename from crates/horizon-client/examples/recipe_book_fixture.rs rename to crates/horizon-client/examples/probe/recipe_book_fixture.rs index e165dea9b..7117d4bbe 100644 --- a/crates/horizon-client/examples/recipe_book_fixture.rs +++ b/crates/horizon-client/examples/probe/recipe_book_fixture.rs @@ -57,8 +57,8 @@ fn compound(tag: &Tag) -> String { out } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let usage = "usage: recipe_book_fixture RESOURCES CASES OUTPUT"; let root = Path::new(args.get(1).ok_or(usage)?); let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?; diff --git a/crates/horizon-client/examples/recipe_book_render_fixture.rs b/crates/horizon-client/examples/probe/recipe_book_render_fixture.rs similarity index 99% rename from crates/horizon-client/examples/recipe_book_render_fixture.rs rename to crates/horizon-client/examples/probe/recipe_book_render_fixture.rs index cd904db79..702471700 100644 --- a/crates/horizon-client/examples/recipe_book_render_fixture.rs +++ b/crates/horizon-client/examples/probe/recipe_book_render_fixture.rs @@ -30,8 +30,8 @@ fn round(v: f32) -> f32 { (v * 1e4).round() / 1e4 } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let usage = "usage: recipe_book_render_fixture RESOURCES CASES OUTPUT"; let root = Path::new(args.get(1).ok_or(usage)?); let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?; diff --git a/crates/horizon-client/examples/recipe_book_view_fixture.rs b/crates/horizon-client/examples/probe/recipe_book_view_fixture.rs similarity index 98% rename from crates/horizon-client/examples/recipe_book_view_fixture.rs rename to crates/horizon-client/examples/probe/recipe_book_view_fixture.rs index 8a1e5da0e..b94952ec5 100644 --- a/crates/horizon-client/examples/recipe_book_view_fixture.rs +++ b/crates/horizon-client/examples/probe/recipe_book_view_fixture.rs @@ -15,8 +15,8 @@ use horizon_client::{ use serde_json::Value; use std::{fmt::Write as _, fs, path::Path}; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let usage = "usage: recipe_book_view_fixture RESOURCES CASES OUTPUT"; let root = Path::new(args.get(1).ok_or(usage)?); let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?; diff --git a/crates/horizon-client/examples/recipe_fixture.rs b/crates/horizon-client/examples/probe/recipe_fixture.rs similarity index 97% rename from crates/horizon-client/examples/recipe_fixture.rs rename to crates/horizon-client/examples/probe/recipe_fixture.rs index e68258e4d..8bdffecd0 100644 --- a/crates/horizon-client/examples/recipe_fixture.rs +++ b/crates/horizon-client/examples/probe/recipe_fixture.rs @@ -12,8 +12,8 @@ use horizon_client::{ }; use std::{fs, path::Path}; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: recipe_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/scene_collision_probe.rs b/crates/horizon-client/examples/probe/scene_collision_probe.rs similarity index 97% rename from crates/horizon-client/examples/scene_collision_probe.rs rename to crates/horizon-client/examples/probe/scene_collision_probe.rs index ec20eee74..7f22a1173 100644 --- a/crates/horizon-client/examples/scene_collision_probe.rs +++ b/crates/horizon-client/examples/probe/scene_collision_probe.rs @@ -28,8 +28,8 @@ fn vector(value: &Value) -> Result { }; Ok(Vec3::new(number(0)?, number(1)?, number(2)?)) } -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); if args.len() != 3 { return Err("usage: scene_collision_probe RESOURCES FIXTURE_DIRECTORY RADIUS".into()); } @@ -78,6 +78,7 @@ fn main() -> Result<()> { let mut selected = collisions::EntityCollisions { blocks: scene, entities: &entities, + border: None, }; let movement = world_movement::resolve_world_movement( &mut selected, diff --git a/crates/horizon-client/examples/scene_motion_probe.rs b/crates/horizon-client/examples/probe/scene_motion_probe.rs similarity index 99% rename from crates/horizon-client/examples/scene_motion_probe.rs rename to crates/horizon-client/examples/probe/scene_motion_probe.rs index f4ff07ebf..21977eeab 100644 --- a/crates/horizon-client/examples/scene_motion_probe.rs +++ b/crates/horizon-client/examples/probe/scene_motion_probe.rs @@ -233,8 +233,8 @@ fn snapshot(out: &mut impl Write, player: &PlayerMotion) -> Result<()> { writeln!(out, "events {}", events.join(" | "))?; Ok(()) } -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); if args.len() != 3 { return Err( "usage: scene_motion_probe RESOURCES FIXTURE_DIRECTORY --describe|REFERENCE".into(), diff --git a/crates/horizon-client/examples/scoreboard_fixture.rs b/crates/horizon-client/examples/probe/scoreboard_fixture.rs similarity index 99% rename from crates/horizon-client/examples/scoreboard_fixture.rs rename to crates/horizon-client/examples/probe/scoreboard_fixture.rs index 1fe5bab91..4a2534b32 100644 --- a/crates/horizon-client/examples/scoreboard_fixture.rs +++ b/crates/horizon-client/examples/probe/scoreboard_fixture.rs @@ -370,8 +370,8 @@ fn score_json(sc: &sb::Score) -> Value { }) } -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let registries: Value = serde_json::from_str(&fs::read_to_string(&args[1]).expect("registries")).expect("json"); let list = |k: &str| -> Vec { diff --git a/crates/horizon-client/examples/screen_layout_fixture.rs b/crates/horizon-client/examples/probe/screen_layout_fixture.rs similarity index 98% rename from crates/horizon-client/examples/screen_layout_fixture.rs rename to crates/horizon-client/examples/probe/screen_layout_fixture.rs index f364037ab..1103f3647 100644 --- a/crates/horizon-client/examples/screen_layout_fixture.rs +++ b/crates/horizon-client/examples/probe/screen_layout_fixture.rs @@ -60,8 +60,8 @@ fn draw_json(d: &ScreenDraw) -> Value { } } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let usage = "usage: screen_layout_fixture RESOURCES INPUT OUTPUT"; let banners = Banners::load(Path::new(args.get(1).ok_or(usage)?)); let input = fs::read_to_string(args.get(2).ok_or(usage)?)?; diff --git a/crates/horizon-client/examples/section_mesh_fixture.rs b/crates/horizon-client/examples/probe/section_mesh_fixture.rs similarity index 99% rename from crates/horizon-client/examples/section_mesh_fixture.rs rename to crates/horizon-client/examples/probe/section_mesh_fixture.rs index 13f1a0f1a..98a4fdc34 100644 --- a/crates/horizon-client/examples/section_mesh_fixture.rs +++ b/crates/horizon-client/examples/probe/section_mesh_fixture.rs @@ -170,8 +170,8 @@ fn scene( } Ok(json!({"name": row["name"], "quads": quads})) } -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); if args.len() != 3 { return Err( "usage: section_mesh_fixture RESOURCES (INPUT.jsonl | facts) OUTPUT.jsonl".into(), diff --git a/crates/horizon-client/examples/server_files_probe.rs b/crates/horizon-client/examples/probe/server_files_probe.rs similarity index 99% rename from crates/horizon-client/examples/server_files_probe.rs rename to crates/horizon-client/examples/probe/server_files_probe.rs index ce146be78..85b33a764 100644 --- a/crates/horizon-client/examples/server_files_probe.rs +++ b/crates/horizon-client/examples/probe/server_files_probe.rs @@ -11,8 +11,8 @@ use horizon_client::server::{ use horizon_protocol::crypto::uuid_string; use std::{fmt::Write as _, path::Path}; -fn main() -> Result<(), Box> { - let mut args = std::env::args().skip(1); +pub fn main() -> Result<(), Box> { + let mut args = crate::args().skip(1); let root = std::path::PathBuf::from(args.next().ok_or("CASES OUTPUT")?); let output = args.next().ok_or("OUTPUT")?; let mut cases: Vec<_> = std::fs::read_dir(&root)? diff --git a/crates/horizon-client/examples/situational_music_fixture.rs b/crates/horizon-client/examples/probe/situational_music_fixture.rs similarity index 96% rename from crates/horizon-client/examples/situational_music_fixture.rs rename to crates/horizon-client/examples/probe/situational_music_fixture.rs index ae47426bb..898893c09 100644 --- a/crates/horizon-client/examples/situational_music_fixture.rs +++ b/crates/horizon-client/examples/probe/situational_music_fixture.rs @@ -5,8 +5,8 @@ use horizon_client::music::{BackgroundMusic, Music, MusicTables, Situation}; use horizon_client::sound_events::normalize; use std::io::Write; -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let tables = MusicTables::load(std::path::Path::new(&args[1])); let input = std::fs::read_to_string(&args[2]).expect("input"); let mut out = std::io::BufWriter::new(std::fs::File::create(&args[3]).expect("output")); diff --git a/crates/horizon-client/examples/skin_image_fixture.rs b/crates/horizon-client/examples/probe/skin_image_fixture.rs similarity index 90% rename from crates/horizon-client/examples/skin_image_fixture.rs rename to crates/horizon-client/examples/probe/skin_image_fixture.rs index 9373fb1f5..e85be6a16 100644 --- a/crates/horizon-client/examples/skin_image_fixture.rs +++ b/crates/horizon-client/examples/probe/skin_image_fixture.rs @@ -9,8 +9,8 @@ use std::{ }; type Result = std::result::Result>; -fn main() -> Result<()> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [inputs, output] = args.as_slice() else { return Err("usage: skin_image_fixture INPUTS OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/sound_engine_fixture.rs b/crates/horizon-client/examples/probe/sound_engine_fixture.rs similarity index 98% rename from crates/horizon-client/examples/sound_engine_fixture.rs rename to crates/horizon-client/examples/probe/sound_engine_fixture.rs index c42ea8bf9..327a8e9d1 100644 --- a/crates/horizon-client/examples/sound_engine_fixture.rs +++ b/crates/horizon-client/examples/probe/sound_engine_fixture.rs @@ -1,8 +1,7 @@ //! Replays `tools/test_sound_engine_parity.py` scripts through Horizon's //! `SoundEngine` with a backend recording what an OpenAL source would hold: //! `sound_engine_fixture ROOT INPUT OUTPUT`. -#[path = "audio_common/mod.rs"] -mod common; +use crate::audio_common as common; use common::{Fake, d, describe, f, flush, result_name}; use horizon_client::sound_engine::{ Attenuation, Backend, CartSound, InstanceId, SoundEngine, SoundInstance, TickContext, @@ -12,8 +11,8 @@ use horizon_core::random::LegacyRandom; use std::collections::BTreeMap; use std::io::Write; -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let mut engine = SoundEngine::new(SoundRegistry::load(std::path::Path::new(&args[1]))); engine.listening = true; let mut backend = Fake::default(); diff --git a/crates/horizon-client/examples/sound_event_fixture.rs b/crates/horizon-client/examples/probe/sound_event_fixture.rs similarity index 97% rename from crates/horizon-client/examples/sound_event_fixture.rs rename to crates/horizon-client/examples/probe/sound_event_fixture.rs index 57c6dd7be..6b52dfc9c 100644 --- a/crates/horizon-client/examples/sound_event_fixture.rs +++ b/crates/horizon-client/examples/probe/sound_event_fixture.rs @@ -9,8 +9,8 @@ fn bits(v: f32) -> String { format!("{:08x}", v.to_bits()) } -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let registry = SoundRegistry::load(std::path::Path::new(&args[1])); let mut engine = SoundEngine::new(registry); let input = std::fs::read_to_string(&args[2]).expect("input"); diff --git a/crates/horizon-client/examples/spawn_rules_fixture.rs b/crates/horizon-client/examples/probe/spawn_rules_fixture.rs similarity index 98% rename from crates/horizon-client/examples/spawn_rules_fixture.rs rename to crates/horizon-client/examples/probe/spawn_rules_fixture.rs index dc491be00..661194f6d 100644 --- a/crates/horizon-client/examples/spawn_rules_fixture.rs +++ b/crates/horizon-client/examples/probe/spawn_rules_fixture.rs @@ -136,8 +136,8 @@ fn reason(name: &str) -> Reason { } } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: spawn_rules_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/sprint_probe.rs b/crates/horizon-client/examples/probe/sprint_probe.rs similarity index 97% rename from crates/horizon-client/examples/sprint_probe.rs rename to crates/horizon-client/examples/probe/sprint_probe.rs index ab538ffe1..5c161da4f 100644 --- a/crates/horizon-client/examples/sprint_probe.rs +++ b/crates/horizon-client/examples/probe/sprint_probe.rs @@ -20,8 +20,8 @@ fn keys(mask: u64) -> Keys { analog: None, } } -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); let mut out = BufWriter::new(File::create(&args[1])?); for line in BufReader::new(File::open(&args[0])?).lines() { let f: Value = serde_json::from_str(&line?)?; diff --git a/crates/horizon-client/examples/subtitle_fixture.rs b/crates/horizon-client/examples/probe/subtitle_fixture.rs similarity index 97% rename from crates/horizon-client/examples/subtitle_fixture.rs rename to crates/horizon-client/examples/probe/subtitle_fixture.rs index ac8e8d4d8..8f690f130 100644 --- a/crates/horizon-client/examples/subtitle_fixture.rs +++ b/crates/horizon-client/examples/probe/subtitle_fixture.rs @@ -21,8 +21,8 @@ fn pose(m: [f32; 6]) -> Value { json!(m) } -fn main() -> Result<(), Box> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> Result<(), Box> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [root, inputs, output] = args.as_slice() else { return Err("usage: subtitle_fixture RESOURCES INPUTS OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/tab_list_fixture.rs b/crates/horizon-client/examples/probe/tab_list_fixture.rs similarity index 98% rename from crates/horizon-client/examples/tab_list_fixture.rs rename to crates/horizon-client/examples/probe/tab_list_fixture.rs index aca50e204..6ea822fba 100644 --- a/crates/horizon-client/examples/tab_list_fixture.rs +++ b/crates/horizon-client/examples/probe/tab_list_fixture.rs @@ -53,8 +53,8 @@ fn runs(t: &Text) -> Value { out.into_iter().map(|(r, k)| json!([r, k])).collect() } -fn main() -> Result<()> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [root, inputs, output] = args.as_slice() else { return Err("usage: tab_list_fixture RESOURCES INPUTS OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/team_rules_fixture.rs b/crates/horizon-client/examples/probe/team_rules_fixture.rs similarity index 97% rename from crates/horizon-client/examples/team_rules_fixture.rs rename to crates/horizon-client/examples/probe/team_rules_fixture.rs index ec56b67ee..9a2d716ff 100644 --- a/crates/horizon-client/examples/team_rules_fixture.rs +++ b/crates/horizon-client/examples/probe/team_rules_fixture.rs @@ -8,8 +8,8 @@ use horizon_client::scoreboard::{self as sb, CollisionRule, NameView, Scoreboard use serde_json::{Value, json}; use std::{fs, io::Write}; -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let mut out = std::io::BufWriter::new(fs::File::create(&args[2]).expect("output")); for line in fs::read_to_string(&args[1]).expect("inputs").lines() { let c: Value = serde_json::from_str(line).expect("case"); diff --git a/crates/horizon-client/examples/toggle_keys_probe.rs b/crates/horizon-client/examples/probe/toggle_keys_probe.rs similarity index 95% rename from crates/horizon-client/examples/toggle_keys_probe.rs rename to crates/horizon-client/examples/probe/toggle_keys_probe.rs index 01ef5fd4d..d05acdd5c 100644 --- a/crates/horizon-client/examples/toggle_keys_probe.rs +++ b/crates/horizon-client/examples/probe/toggle_keys_probe.rs @@ -11,8 +11,8 @@ use std::{ io::{BufRead, BufReader, BufWriter, Write}, }; -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let input = BufReader::new(File::open(&args[1])?); let mut out = BufWriter::new(File::create(&args[2])?); for (n, line) in input.lines().enumerate() { diff --git a/crates/horizon-client/examples/tooltip_display_fixture.rs b/crates/horizon-client/examples/probe/tooltip_display_fixture.rs similarity index 93% rename from crates/horizon-client/examples/tooltip_display_fixture.rs rename to crates/horizon-client/examples/probe/tooltip_display_fixture.rs index ec61159cd..8a7525785 100644 --- a/crates/horizon-client/examples/tooltip_display_fixture.rs +++ b/crates/horizon-client/examples/probe/tooltip_display_fixture.rs @@ -3,8 +3,8 @@ use horizon_client::{item_tooltip::TooltipDisplay, items::ItemStack}; use horizon_world::nbt::Tag; use std::{error::Error, fmt::Write}; -fn main() -> Result<(), Box> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec = crate::args().collect(); let mut output = String::new(); for line in std::fs::read_to_string(&args[1])?.lines() { let fields: Vec<&str> = line.split('\t').collect(); diff --git a/crates/horizon-client/examples/trading_fixture.rs b/crates/horizon-client/examples/probe/trading_fixture.rs similarity index 99% rename from crates/horizon-client/examples/trading_fixture.rs rename to crates/horizon-client/examples/probe/trading_fixture.rs index 58824257c..c2215d327 100644 --- a/crates/horizon-client/examples/trading_fixture.rs +++ b/crates/horizon-client/examples/probe/trading_fixture.rs @@ -231,8 +231,8 @@ fn prepare(m: &mut Merchant, gossips: &mut Gossips, kv: &HashMap } } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let usage = "usage: trading_fixture RESOURCES INPUT VANILLA_OUTPUT OUTPUT"; let root = Path::new(args.get(1).ok_or(usage)?); let input = fs::read_to_string(args.get(2).ok_or(usage)?)?; diff --git a/crates/horizon-client/examples/translucency_fixture.rs b/crates/horizon-client/examples/probe/translucency_fixture.rs similarity index 93% rename from crates/horizon-client/examples/translucency_fixture.rs rename to crates/horizon-client/examples/probe/translucency_fixture.rs index 11083d6b2..8ea42c1dc 100644 --- a/crates/horizon-client/examples/translucency_fixture.rs +++ b/crates/horizon-client/examples/probe/translucency_fixture.rs @@ -14,8 +14,8 @@ struct Case { cameras: Vec<[f64; 3]>, } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().skip(1).collect(); let [input, output] = args.as_slice() else { return Err("usage: translucency_fixture INPUT OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/weather_fixture.rs b/crates/horizon-client/examples/probe/weather_fixture.rs similarity index 95% rename from crates/horizon-client/examples/weather_fixture.rs rename to crates/horizon-client/examples/probe/weather_fixture.rs index 3cf6c31be..b85dd3e09 100644 --- a/crates/horizon-client/examples/weather_fixture.rs +++ b/crates/horizon-client/examples/probe/weather_fixture.rs @@ -8,8 +8,8 @@ fn bits(value: f32) -> String { format!("{:x}", value.to_bits()) } } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let mut output = String::new(); let mut parameters = weather::ParameterCache::default(); for (case, line) in fs::read_to_string(&args[1])?.lines().enumerate() { diff --git a/crates/horizon-client/examples/world_border_render_fixture.rs b/crates/horizon-client/examples/probe/world_border_render_fixture.rs similarity index 98% rename from crates/horizon-client/examples/world_border_render_fixture.rs rename to crates/horizon-client/examples/probe/world_border_render_fixture.rs index 1de15eeeb..535118959 100644 --- a/crates/horizon-client/examples/world_border_render_fixture.rs +++ b/crates/horizon-client/examples/probe/world_border_render_fixture.rs @@ -24,8 +24,8 @@ fn doubles(v: &[f64]) -> Value { v.iter().map(|f| f.to_bits() as i64).collect() } -fn main() -> Result<()> { - let args: Vec = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().skip(1).collect(); let [inputs, output] = args.as_slice() else { return Err("usage: world_border_render_fixture INPUTS OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/world_options_fixture.rs b/crates/horizon-client/examples/probe/world_options_fixture.rs similarity index 93% rename from crates/horizon-client/examples/world_options_fixture.rs rename to crates/horizon-client/examples/probe/world_options_fixture.rs index 5bbf9f1c7..5bd3026bc 100644 --- a/crates/horizon-client/examples/world_options_fixture.rs +++ b/crates/horizon-client/examples/probe/world_options_fixture.rs @@ -2,8 +2,8 @@ use horizon_protocol::{buf::Reader, packets::play::*}; use std::{error::Error, fmt::Write}; -fn main() -> Result<(), Box> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec = crate::args().collect(); let mut output = String::new(); for line in std::fs::read_to_string(&args[1])?.lines() { let fields: Vec<&str> = line.split('\t').collect(); 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-client/src/audio.rs b/crates/horizon-client/src/audio.rs index f101f53cd..e59ffd867 100644 --- a/crates/horizon-client/src/audio.rs +++ b/crates/horizon-client/src/audio.rs @@ -708,6 +708,13 @@ impl Audio { let seed = self.random.next_long(); self.play_seeded(event, at, volume, pitch, seed); } + /// `play` for this client only: a sound a packet's handler plays + /// (`playLocalSound`), which the guests play from that packet themselves. + pub fn play_unshared(&mut self, event: &str, at: Option<[f64; 3]>, volume: f32, pitch: f32) { + let capture = self.capture.take(); + self.play(event, at, volume, pitch); + self.capture = capture; + } /// `LivingEntity.handleDamageEvent`'s pitch, `(r - r) * 0.2 + 1`, drawn on the /// client (the entity's own random there, never the server's world random). pub fn hurt_pitch(&mut self) -> f32 { diff --git a/crates/horizon-client/src/banner.rs b/crates/horizon-client/src/banner.rs index 861294722..aa470a552 100644 --- a/crates/horizon-client/src/banner.rs +++ b/crates/horizon-client/src/banner.rs @@ -2,7 +2,7 @@ //! `banner_patterns` layers carried by banner items, shields and placed //! banners, and the loom rules of `LoomMenu` (selectable patterns, the //! six-layer limit and the result stack). -use crate::{block_entity_render::DYES, item_data, items::ItemStack, items::Items}; +use crate::{block_entity_render::DYES, items::ItemStack, items::Items}; use horizon_world::nbt::Tag; use serde_json::Value; use std::{collections::HashMap, fs, path::Path, sync::Arc}; @@ -261,12 +261,6 @@ pub fn layers_from_nbt(tag: Option<&Tag>) -> Vec { }) .collect() } -/// Keeps `item_data` linked: the `StackData` fields the banner code reads. -pub fn set_layers(stack: &mut ItemStack, layers: Vec) { - let data: &mut item_data::StackData = stack.data_mut(); - data.banner_patterns = layers; - stack.tidy(); -} #[cfg(test)] mod tests { diff --git a/crates/horizon-client/src/block_entities.rs b/crates/horizon-client/src/block_entities.rs index 93abb3711..03fff85ca 100644 --- a/crates/horizon-client/src/block_entities.rs +++ b/crates/horizon-client/src/block_entities.rs @@ -144,9 +144,6 @@ impl BlockEntities { pub fn set_states(&mut self, states: Vec) { self.states = states; } - pub fn take_states(&mut self) -> Vec { - std::mem::take(&mut self.states) - } pub fn ticking(&self, state: u32) -> Ticking { self.states.get(state as usize).copied().unwrap_or_default() } diff --git a/crates/horizon-client/src/block_entity_anim.rs b/crates/horizon-client/src/block_entity_anim.rs index 2a35c9835..d91748e73 100644 --- a/crates/horizon-client/src/block_entity_anim.rs +++ b/crates/horizon-client/src/block_entity_anim.rs @@ -382,10 +382,6 @@ impl Shulker { } out } - /// `getProgress(a)`: `Mth.lerp(a, progressOld, progress)`. - pub fn get_progress(&self, a: f32) -> f32 { - self.progress_old + a * (self.progress - self.progress_old) - } /// `ShulkerBoxBlock.canOpen`: a closed box only opens when its lid has room /// (`level.noCollision` of the half-block lid box, deflated by 1e-6). pub fn lid_box(pos: [i32; 3], facing: u8) -> [f64; 6] { @@ -668,14 +664,6 @@ impl Skull { self.animating = false; } } - /// `getAnimation(a)`. - pub fn get_animation(&self, a: f32) -> f32 { - if self.animating { - self.tick_count as f32 + a - } else { - self.tick_count as f32 - } - } } /// `DecoratedPotBlockEntity.WobbleStyle`. diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 21376d698..af4168307 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -875,13 +875,6 @@ impl BlockEntityRenderer { visibility: None, } } - /// The standing banner's pole-and-bar and flag models (`BannerRenderer.submitSpecial`). - pub fn banner_models(&self) -> Option<(&ModelPart, &ModelPart)> { - Some(( - self.models.get("standing_banner")?, - self.models.get("standing_banner_flag")?, - )) - } fn kind(&self, state: u32) -> &Kind { self.kinds.get(state as usize).unwrap_or(&Kind::None) } diff --git a/crates/horizon-client/src/bossbar.rs b/crates/horizon-client/src/bossbar.rs index a976258f9..eab31a5e5 100644 --- a/crates/horizon-client/src/bossbar.rs +++ b/crates/horizon-client/src/bossbar.rs @@ -46,7 +46,7 @@ impl BossBar { style: "progress".into(), value: 0, max: 100, - visible: false, + visible: true, player: false, } } diff --git a/crates/horizon-client/src/clock.rs b/crates/horizon-client/src/clock.rs index 3240944ba..27cc714bf 100644 --- a/crates/horizon-client/src/clock.rs +++ b/crates/horizon-client/src/clock.rs @@ -169,10 +169,6 @@ impl TickRateManager { self.frozen_ticks_to_run -= 1; } } - /// `isEntityFrozen` for an entity that is not (and does not carry) a player. - pub fn is_entity_frozen(&self, is_player_or_carries_player: bool) -> bool { - !self.runs_normally() && !is_player_or_carries_player - } } /// What `/tick sprint` reports when it ends. @@ -304,6 +300,10 @@ pub struct FixedStep { /// How many times `/tick step` started or stopped a step /// (`ServerTickRateManager.updateStepTicks` broadcasts each one). step_changes: u32, + /// In-frame ticks dropped since the last overload warning (`drop_ticks`). + dropped: u32, + /// When the last overload warning was due, on the frame clock. + last_overload_warning: std::time::Duration, } impl Default for FixedStep { @@ -320,6 +320,8 @@ impl Default for FixedStep { tick_count: 0, client: false, step_changes: 0, + dropped: 0, + last_overload_warning: std::time::Duration::ZERO, } } } @@ -434,6 +436,41 @@ impl FixedStep { pub fn sprinting(&self) -> bool { self.manager.is_sprinting() } + /// Whether a frame that ran its world in the frame, and whose ticks so + /// far took `spent`, may run another one. Vanilla's world ticks on the + /// integrated server's thread, so a slow tick costs its frames nothing: + /// the server falls behind and says so (`MinecraftServer.runServer`'s + /// "Can't keep up!"). In the frame, a world whose ticks take longer than + /// their length falls behind every frame, so every frame ran the client + /// timer's ten: at 57 ms a tick, 1.7 FPS. So a frame stops once its + /// ticks have taken a tick's length: ticks of a few milliseconds keep the + /// full ten, and a world that cannot keep up runs one tick a frame, + /// slower but drawn. A sprint (`/tick sprint`) runs its own frame's worth. + pub fn tick_fits(&self, spent: std::time::Duration) -> bool { + self.sprinting() || spent < self.tick_duration() + } + /// The frame skips its remaining `ticks` (`tick_fits`): the world runs + /// slower than its tick rate. Returns vanilla's overload warning when one + /// is due: a second's worth of ticks behind, at most every ten seconds + /// (`OVERLOADED_THRESHOLD_NANOS`, `OVERLOADED_WARNING_INTERVAL_NANOS`). + pub fn drop_ticks(&mut self, ticks: u32) -> Option { + self.dropped = self.dropped.saturating_add(ticks); + let tick = self.tick_duration(); + let behind = tick * self.dropped; + let threshold = std::time::Duration::from_secs(1) + tick * 20; + let interval = std::time::Duration::from_secs(10) + tick * 100; + if behind <= threshold || self.now < self.last_overload_warning + interval { + return None; + } + let warning = format!( + "Can't keep up! Is the server overloaded? Running {}ms or {} ticks behind", + behind.as_millis(), + self.dropped + ); + self.dropped = 0; + self.last_overload_warning = self.now; + Some(warning) + } /// `requestGameToSprint`: true when a sprint was already running. pub fn start_sprint(&mut self, ticks: u32) -> bool { self.manager @@ -494,6 +531,37 @@ impl FixedStep { mod tests { use super::*; + #[test] + fn a_frame_stops_ticking_after_a_ticks_length() { + let clock = FixedStep::default(); + let ms = std::time::Duration::from_millis; + // Ticks of 4 ms: the ten the timer allows fit in 50 ms. + assert!(clock.tick_fits(ms(4 * 9))); + // Ticks of 40 ms: the second one runs, not a third. + assert!(clock.tick_fits(ms(40))); + assert!(!clock.tick_fits(ms(80))); + // One tick longer than its length still runs, once a frame. + assert!(clock.tick_fits(ms(0))); + assert!(!clock.tick_fits(ms(120))); + } + #[test] + fn dropped_ticks_warn_once_a_second_behind_and_not_again_for_ten() { + let mut clock = FixedStep::default(); + let s = std::time::Duration::from_secs; + clock.now = s(20); + assert_eq!( + clock.drop_ticks(40), + None, + "two seconds: not past 1 s + 20 ticks" + ); + let warning = clock.drop_ticks(1).expect("past the threshold"); + assert!(warning.contains("2050ms or 41 ticks behind"), "{warning}"); + clock.now = s(25); + assert_eq!(clock.drop_ticks(100), None, "within ten seconds"); + clock.now = s(36); + assert!(clock.drop_ticks(0).unwrap().contains("100 ticks behind")); + } + #[test] fn timer_carries_fractions_and_caps_nothing_itself() { let mut t = Timer::new(20.0, 0); diff --git a/crates/horizon-client/src/collisions.rs b/crates/horizon-client/src/collisions.rs index 67f5d6027..cfca854dc 100644 --- a/crates/horizon-client/src/collisions.rs +++ b/crates/horizon-client/src/collisions.rs @@ -3,7 +3,7 @@ //! Entity-dependent rules use the defaults for players and the supported mobs. use crate::{Result, world::World}; use horizon_core::{ - geometry::{Aabb, Vec3, VoxelShape}, + geometry::{Aabb, Vec3, VoxelShape, border::BorderGeometry}, position::{BlockPos, ChunkPos}, }; use horizon_world::{ @@ -64,6 +64,9 @@ pub struct SceneCollisions<'w, 'r> { pub struct EntityCollisions<'a, W> { pub blocks: W, pub entities: &'a [Aabb], + /// The world border and the moving entity's x and z + /// (`CollisionGetter.borderCollision`); None: the blocks' answer. + pub border: Option<(&'a BorderGeometry, [f64; 2])>, } impl BlockCollisionWorld for EntityCollisions<'_, W> { type Error = W::Error; @@ -114,12 +117,20 @@ impl> EntityMovementWorld for EntityCo } Ok(shapes) } + /// `WorldBorder.isInsideCloseToBorder`: an entity inside the border and + /// near it collides with its walls. fn movement_border( &mut self, entity: EntityIdentity, bounds: Aabb, ) -> io::Result> { - self.blocks.movement_border(entity, bounds) + let Some((border, [x, z])) = self.border else { + return self.blocks.movement_border(entity, bounds); + }; + if !border.is_inside_close_to_border(x, z, bounds) { + return Ok(None); + } + border.collision_shape().map(Some).map_err(io::Error::other) } } impl SceneCollisions<'_, '_> { diff --git a/crates/horizon-client/src/command/args.rs b/crates/horizon-client/src/command/args.rs index 68d41e14f..ccced67a7 100644 --- a/crates/horizon-client/src/command/args.rs +++ b/crates/horizon-client/src/command/args.rs @@ -812,14 +812,6 @@ pub fn java_parse_int(s: &str) -> Option { } s.parse().ok() } -/// Long.parseLong. -pub fn java_parse_long(s: &str) -> Option { - let digits = s.strip_prefix(['-', '+']).unwrap_or(s); - if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) { - return None; - } - s.parse().ok() -} /// Double.parseDouble over the characters StringReader reads as a number. pub fn java_parse_double(s: &str) -> Option { let t = s.trim_matches(|c: char| c <= ' '); diff --git a/crates/horizon-client/src/command/component.rs b/crates/horizon-client/src/command/component.rs index 9bc0668d5..15a8fa6a0 100644 --- a/crates/horizon-client/src/command/component.rs +++ b/crates/horizon-client/src/command/component.rs @@ -1,7 +1,7 @@ //! ComponentSerialization.CODEC and Style.Serializer.MAP_CODEC decoding of //! SNBT text components, with the data-fixer-upper error messages //! (ComponentArgument, StyleArgument and component-valued item data). -use super::codec::{get, no_key, not_list, not_map, snbt}; +use super::codec::{get, no_key, not_list, not_map}; use horizon_world::nbt::{Compound, Tag}; /// A DataResult error: its message and whether it carries a partial result. @@ -362,7 +362,3 @@ pub fn decode_style(t: &Tag) -> Result<(), String> { _ => Err(not_map(t)), } } -#[allow(unused)] -fn _keep(t: &Tag) -> String { - snbt(t) -} diff --git a/crates/horizon-client/src/command/item.rs b/crates/horizon-client/src/command/item.rs index 7c8abe84a..f2abc91ef 100644 --- a/crates/horizon-client/src/command/item.rs +++ b/crates/horizon-client/src/command/item.rs @@ -632,10 +632,6 @@ pub fn parse_predicate(reader: &mut Reader, reg: &Registries) -> CmdResult String { - snbt(t) -} #[cfg(test)] mod tests { diff --git a/crates/horizon-client/src/command/mod.rs b/crates/horizon-client/src/command/mod.rs index e9aeaae51..a61c8c08d 100644 --- a/crates/horizon-client/src/command/mod.rs +++ b/crates/horizon-client/src/command/mod.rs @@ -183,9 +183,6 @@ impl<'a> Reader<'a> { pub fn read_int(&mut self) -> CmdResult { self.number("int") } - pub fn read_long(&mut self) -> CmdResult { - self.number("long") - } pub fn read_double(&mut self) -> CmdResult { self.number("double") } @@ -222,21 +219,6 @@ impl<'a> Reader<'a> { } Err(CommandError::tr_at("parsing.quote.expected.end", &[], self)) } - pub fn read_quoted_string(&mut self) -> CmdResult { - if !self.can_read() { - return Ok(String::new()); - } - let next = self.peek(); - if next != '"' && next != '\'' { - return Err(CommandError::tr_at( - "parsing.quote.expected.start", - &[], - self, - )); - } - self.skip(); - self.read_string_until(next) - } pub fn read_string(&mut self) -> CmdResult { if !self.can_read() { return Ok(String::new()); @@ -539,18 +521,6 @@ impl<'a> SuggestionsBuilder<'a> { } } } - /// The same with a tooltip per candidate. - pub fn suggest_matching_tooltip<'b>( - &mut self, - candidates: impl IntoIterator, - ) { - let lower = self.remaining_lower(); - for (c, tip) in candidates { - if args::matches_sub_str(&lower, &c.to_lowercase()) { - self.suggest_tooltip(c, tip); - } - } - } } /// String.compareToIgnoreCase. pub fn compare_ignore_case(a: &str, b: &str) -> std::cmp::Ordering { diff --git a/crates/horizon-client/src/command/snbt.rs b/crates/horizon-client/src/command/snbt.rs index 05fe6d9bc..7472c7ae3 100644 --- a/crates/horizon-client/src/command/snbt.rs +++ b/crates/horizon-client/src/command/snbt.rs @@ -1,8 +1,6 @@ //! SnbtGrammar and TagParser: vanilla's packrat SNBT grammar, with its //! error messages and completion suggestions, producing NBT tags. -use super::packrat::{ - Grammar, Reason, Rule, State, Sugg, Term, Value, alt, ch, chs, look, opt, seq, -}; +use super::packrat::{Grammar, Reason, State, Sugg, Term, Value, alt, ch, chs, look, opt, seq}; use super::{CmdResult, CommandError, Reader, SuggestionsBuilder}; use horizon_world::nbt::{Compound, JavaString, Tag}; use std::rc::Rc; @@ -981,5 +979,3 @@ pub fn rule_in( } } } -#[allow(unused)] -fn _rule_kind(_: Rule) {} diff --git a/crates/horizon-client/src/command/vanilla.rs b/crates/horizon-client/src/command/vanilla.rs index fd23b82cd..cdd4848d7 100644 --- a/crates/horizon-client/src/command/vanilla.rs +++ b/crates/horizon-client/src/command/vanilla.rs @@ -3,7 +3,7 @@ //! mode keywords are read back from the parsed literals. use super::{ Dispatcher, - args::{ArgType, GameMode, Resource, integer}, + args::{ArgType, Resource, integer}, }; use crate::gamerules::{RULES, Value}; @@ -509,10 +509,6 @@ fn clone_mode(d: &mut Dispatcher, node: usize) { d.executes(l, "clone"); } } -/// Game mode names for selector `gamemode=` and the argument. -pub fn game_modes() -> [&'static str; 4] { - GameMode::ALL.map(GameMode::name) -} /// The shared vanilla tree. /// Reorder node children as vanilla registers them (Brigadier keeps /// children in registration order; smart usage lists them that way). @@ -559,5 +555,3 @@ pub fn release_dispatcher() -> &'static Dispatcher { static TREE: std::sync::OnceLock = std::sync::OnceLock::new(); TREE.get_or_init(|| build_with(false)) } -#[allow(unused)] -const _: (u8, u8) = (ALL, GAMEMASTERS); diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 854332815..6ecdf0d93 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -252,24 +252,6 @@ impl BlockEntity { }; Some(Self::Chest(vec![None; size])) } - /// The vanilla block entity type id of a container block. - pub fn id_for_block(name: &str) -> Option<&'static str> { - Some(match name { - "minecraft:chest" => "minecraft:chest", - n if n.ends_with("copper_chest") => "minecraft:chest", - "minecraft:trapped_chest" => "minecraft:trapped_chest", - "minecraft:barrel" => "minecraft:barrel", - "minecraft:hopper" => "minecraft:hopper", - "minecraft:dispenser" => "minecraft:dispenser", - "minecraft:dropper" => "minecraft:dropper", - "minecraft:furnace" => "minecraft:furnace", - "minecraft:blast_furnace" => "minecraft:blast_furnace", - "minecraft:smoker" => "minecraft:smoker", - n if n.ends_with("shulker_box") => "minecraft:shulker_box", - "minecraft:crafter" => "minecraft:crafter", - _ => return None, - }) - } pub fn id(&self) -> &'static str { match self { Self::Chest(items) => match items.len() { diff --git a/crates/horizon-client/src/debug_chart.rs b/crates/horizon-client/src/debug_chart.rs index 35fd40bd4..3d9cc5556 100644 --- a/crates/horizon-client/src/debug_chart.rs +++ b/crates/horizon-client/src/debug_chart.rs @@ -17,8 +17,6 @@ use std::{ pub const CAPACITY: usize = 240; /// `AbstractDebugChart.CHART_HEIGHT`. pub const CHART_HEIGHT: i32 = 60; -/// `TpsDebugDimensions`: a tick sample's values. -pub const FULL_TICK: usize = 0; pub const TICK_SERVER_METHOD: usize = 1; pub const SCHEDULED_TASKS: usize = 2; pub const IDLE: usize = 3; @@ -252,10 +250,6 @@ impl Chart { pub fn width(max_width: i32) -> i32 { (CAPACITY as i32 + 2).min(max_width) } - /// `getFullHeight`: the box and the min/avg/max line above it. - pub fn full_height() -> i32 { - CHART_HEIGHT + 9 - } /// `AbstractDebugChart.extractRenderState`. pub fn draw( self, diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-client/src/enchant.rs index ca2ea6f5c..2fc9ef2fb 100644 --- a/crates/horizon-client/src/enchant.rs +++ b/crates/horizon-client/src/enchant.rs @@ -359,10 +359,6 @@ impl Enchantments { } out } - /// Whether a stack draws the enchantment glint. - pub fn has_glint(&self, stack: &ItemStack) -> bool { - stack.has_any_enchantments() || self.props(&stack.item).is_some_and(|p| p.glint) - } // ---- Enchanting table (EnchantmentHelper) ---- @@ -514,19 +510,6 @@ impl Enchantments { .is_some_and(|e| e.effects.get(component).is_some()) }) } - /// The highest level among enchantments on `stack` that have `component`. - pub fn component_level(&self, stack: &ItemStack, component: &str) -> u32 { - stack - .enchantments() - .iter() - .filter(|(id, _)| { - self.get(id) - .is_some_and(|e| e.effects.get(component).is_some()) - }) - .map(|(_, l)| *l) - .max() - .unwrap_or(0) - } /// `minecraft:attributes` contributions of `stack`: (attribute, id, amount, operation). pub fn attributes(&self, stack: &ItemStack) -> Vec<(String, String, f64, String)> { let mut out = Vec::new(); diff --git a/crates/horizon-client/src/first_person.rs b/crates/horizon-client/src/first_person.rs index 463d51437..02132d942 100644 --- a/crates/horizon-client/src/first_person.rs +++ b/crates/horizon-client/src/first_person.rs @@ -289,15 +289,6 @@ impl Default for HandHeights { } } } -/// What `FirstPersonHandsAndItems.tick` decides about a hand's visible item. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct HandChange { - /// The visible item is not the hand's item after the instant replacement - /// (`mainHandItem != nextMainHand`): the hand lowers. - pub changed: bool, - /// The visible item becomes the hand's item this tick. - pub replace: bool, -} impl HandHeights { /// `FirstPersonHandsAndItems.tick`'s heights. `changed` says per hand /// whether the visible item differs from the held one once diff --git a/crates/horizon-client/src/font.rs b/crates/horizon-client/src/font.rs index c5e5760f3..a25568df5 100644 --- a/crates/horizon-client/src/font.rs +++ b/crates/horizon-client/src/font.rs @@ -271,7 +271,10 @@ fn load_bitmap( .flatten(); // The sheet: its size, and its pixels when they are not in the atlas. let (sw, sh, sheet) = match in_atlas { - Some(rect) => (rect.w, rect.h, None), + Some(rect) => { + let (w, h) = rect.texels(atlas); + (w, h, None) + } None => match crate::hud::decode(&root.join(resource_path(file, "textures", ""))) { Ok((w, h, rgba)) => (w, h, Some(Arc::new((w, rgba)))), Err(_) => { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 27a465bd0..277c7f2fd 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -73,6 +73,7 @@ mod lan_crafting; mod lan_entities; mod lan_mobs; mod lan_mount_menu; +mod lan_particles; mod lan_pvp; mod lan_screen; mod lan_stations; @@ -1021,9 +1022,11 @@ pub struct UiResources { pub panorama: Arc, } impl UiResources { - pub fn load(root: &std::path::Path) -> Result { + /// From a resource root layering packs over `defaults`, the game's own + /// resources (`root` itself when no pack is on). + pub fn load(root: &std::path::Path, defaults: &std::path::Path) -> Result { Ok(Self { - atlas: HudAtlas::build(root)?, + atlas: HudAtlas::build_over(root, defaults)?, panorama: Arc::new(horizon_client::gfx::panorama::Faces::load(root)), }) } @@ -2575,6 +2578,17 @@ impl Game<'_> { LevelEvent::LevelEvent { id: 2004, pos, .. } => { self.spawner_burst([pos.x, pos.y, pos.z]) } + // LevelEventHandler 1505: the growth particles, then the sound. + LevelEvent::LevelEvent { + id: 1505, + pos, + data, + } => { + self.growth_particles(pos, data); + let at = [pos.x, pos.y, pos.z].map(|v| f64::from(v) + 0.5); + self.audio + .play("minecraft:item.bone_meal.use", Some(at), 1.0, 1.0); + } LevelEvent::LevelEvent { id: 2015, pos, @@ -2618,7 +2632,6 @@ impl Game<'_> { 1030 => Some(("minecraft:block.anvil.use", 1.0)), 1029 => Some(("minecraft:block.anvil.destroy", 1.0)), 1031 => Some(("minecraft:block.anvil.land", 0.3)), - 1505 => Some(("minecraft:item.bone_meal.use", 1.0)), 1042 => Some(("minecraft:block.grindstone.use", 1.0)), 1044 => Some(("minecraft:block.smithing_table.use", 1.0)), // LevelEvent.SOUND_PAGE_TURN (a lectern's page). @@ -3966,7 +3979,7 @@ impl Game<'_> { if self.use_delay > 0 { self.use_delay -= 1; } - self.apply_totem(); + self.tick_totem(); self.update_totem_ready(); self.tick_command_extras(); self.tick_mods(); @@ -4245,7 +4258,7 @@ impl Game<'_> { } } self.powder_snow_fire()?; - self.apply_totem(); + self.tick_totem(); let Some(player) = self.player.as_mut() else { return Ok(()); }; @@ -8100,13 +8113,15 @@ impl Game<'_> { } Ok(true) } - /// `BlockTransformer.transformBlock` for a held axe, hoe or shovel. - fn use_block_transformer( - &mut self, + /// What `BlockTransformer.transformBlock` would do with a held axe, hoe + /// or shovel on the block at `pos`, without doing it: the new state, its + /// sound, loot table, the durability it costs and its particle. + pub(super) fn block_transform( + &self, stack: &ItemStack, pos: [i32; 3], face: [i32; 3], - ) -> Result { + ) -> Option<(BlockStateId, String, Option, u32, String)> { use horizon_client::block_transform::Around; struct Column<'w> { world: &'w World, @@ -8126,14 +8141,11 @@ impl Game<'_> { }) } } - let Some(id) = self + let id = self .res .items() .get(&stack.item) - .and_then(|i| i.block_transformer.clone()) - else { - return Ok(false); - }; + .and_then(|i| i.block_transformer.clone())?; // playerHasBlockingItemUseIntent: a shield in the off hand is raised // instead, unless sneaking. let shield = self @@ -8142,7 +8154,7 @@ impl Game<'_> { .and_then(|s| self.res.items().get(&s.item)) .is_some_and(|i| i.blocks_attacks.is_some()); if shield && !self.keys.contains(&KeyCode::ShiftLeft) { - return Ok(false); + return None; } let face_name = match face { [0, -1, 0] => "down", @@ -8153,38 +8165,47 @@ impl Game<'_> { _ => "east", }; let registry = self.pack.assets.registry; - let (state, sound, loot, damage, particle) = { - let around = Column { - world: &self.world, - registry, - pos, - }; - let Some((_, t, state)) = - self.res - .transformers() - .apply(self.res.items(), registry, &id, face_name, &around) - else { - return Ok(false); - }; - ( - state, - t.sound.clone(), - t.loot.clone(), - t.damage, - t.particle.clone(), - ) + let around = Column { + world: &self.world, + registry, + pos, }; - let Ok(new) = registry.resolve(&state) else { - return Ok(false); - }; - self.level_set(pos, new)?; - // BlockTransformer.TransformParticle.send. - match particle.as_str() { + let (_, t, state) = + self.res + .transformers() + .apply(self.res.items(), registry, &id, face_name, &around)?; + let new = registry.resolve(&state).ok()?; + Some(( + new, + t.sound.clone(), + t.loot.clone(), + t.damage, + t.particle.clone(), + )) + } + /// `BlockTransformer.TransformParticle.send`: its level event. + pub(super) fn transform_particle(&mut self, particle: &str, pos: [i32; 3]) { + match particle { "scrape" => self.level_event_at(3005, pos, 0), "wax_on" => self.level_event_at(3003, pos, 0), "wax_off" => self.level_event_at(3004, pos, 0), _ => {} } + } + /// `BlockTransformer.transformBlock` for a held axe, hoe or shovel. + fn use_block_transformer( + &mut self, + stack: &ItemStack, + pos: [i32; 3], + face: [i32; 3], + ) -> Result { + let Some((new, sound, loot, damage, particle)) = self.block_transform(stack, pos, face) + else { + return Ok(false); + }; + self.level_set(pos, new)?; + // BlockTransformer.TransformParticle.send. + self.transform_particle(&particle, pos); if loot.as_deref() == Some("minecraft:till/rooted_dirt") { self.pop_resource( [pos[0] + face[0], pos[1] + face[1], pos[2] + face[2]], @@ -11275,7 +11296,17 @@ impl ApplicationHandler for Game<'_> { // For the "I'm playing" ping: an atomic, sent on when it changes. horizon_client::heartbeat::set_lan(self.is_published()); let steps = self.clock.advance(elapsed); - for _ in 0..steps { + // The world ticking in the frame: once its ticks took a + // tick's length, the rest are dropped (`FixedStep::tick_fits`). + let in_frame = self.remote.is_none(); + let mut spent = Duration::ZERO; + for step in 0..steps { + if in_frame && !self.clock.tick_fits(spent) { + if let Some(warning) = self.clock.drop_ticks(steps - step) { + log::warn!("{warning}"); + } + break; + } let started = Instant::now(); if self.title.is_none() && !self.pause { let tick = Instant::now(); @@ -11292,6 +11323,7 @@ impl ApplicationHandler for Game<'_> { self.tick_music(); self.tick_sound_engine(); self.clock.record(started.elapsed()); + spent += started.elapsed(); if let Some(report) = self.clock.take_sprint_report() { self.sprint_report(&report); } @@ -12109,7 +12141,20 @@ fn load_resources( // loads; the synchronous launch instead carries it in `Loaded`. let mut loaded_gui = None; let mut ui_ready = false; - if let Ok(ui) = UiResources::load(&root) { + let mut pack_error = None; + let ui = match UiResources::load(&root, vanilla_root) { + Ok(ui) => Some(ui), + // Minecraft.rollbackResourcePacks: the packs' textures don't fit, start + // with the game's own resources. + Err(e) if root != vanilla_root => { + log::warn!("Horizon: resource packs failed to load ({e}); using the default resources"); + pack_error = Some(e.to_string()); + root = vanilla_root.to_path_buf(); + None + } + Err(_) => None, + }; + if let Some(ui) = ui { if menu { horizon_client::telemetry::mark_ui_ready(); log::info!( @@ -12123,7 +12168,6 @@ fn load_resources( ui_ready = true; } progress.set(0); - let mut pack_error = None; let (assets, render) = match Assets::load(&root).and_then(|assets| { let render = assets.reload(&root)?; Ok((assets, render)) @@ -12150,7 +12194,7 @@ fn load_resources( let render = Arc::new(render); // The menu bundle must come from the same root as the world bundle. if !ui_ready || root != requested_root { - let ui = UiResources::load(&root)?; + let ui = UiResources::load(&root, vanilla_root)?; if menu { horizon_client::telemetry::mark_ui_ready(); log::info!( @@ -12561,6 +12605,10 @@ fn start_game<'a>( game.rest_loader = rest_loader; game.ui.vanilla_root = vanilla_root; if let Some(error) = pack_error { + // Minecraft.clearResourcePacksOnError: the selection is cleared and + // saved, so the next launch starts without the packs. + game.settings.resource_packs.clear(); + game.settings.save(&Game::options_path()); game.open_options_at(true, horizon_client::options_ui::Page::Packs); game.ui.options.resource_error = Some(error); } diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 20aeeb7fd..0247896f5 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -5,7 +5,7 @@ use horizon_client::{ chat::{Chat, ChatAction, ChatScreen, Commands, SYSTEM_INDICATOR}, command::Registries, gamerules::GameRules, - hud::{HudBatch, rgba}, + hud::HudBatch, screen_draw::Measure, text::{ClickEvent, Style, Text}, }; @@ -883,10 +883,6 @@ impl Game<'_> { .chat .add(&self.gui.atlas, message, None, self.ticks, focused); } - #[allow(dead_code)] - fn chat_debug_fill(&self, batch: &mut HudBatch) { - batch.fill(&self.gui.atlas, 0.0, 0.0, 1.0, 1.0, rgba(0, 0, 0, 0)); - } } /// `yyyy-MM-dd_HH.mm.ss[_n].png` (Util.getFilenameFormattedDateTime, local time /// approximated as UTC). diff --git a/crates/horizon-client/src/game/commands/terrain_cmds.rs b/crates/horizon-client/src/game/commands/terrain_cmds.rs index 46df0ce7d..df52f2251 100644 --- a/crates/horizon-client/src/game/commands/terrain_cmds.rs +++ b/crates/horizon-client/src/game/commands/terrain_cmds.rs @@ -248,8 +248,32 @@ impl Game<'_> { /// Every tick: the size change, the wall the player cannot pass and /// damage outside the border. + /// `BorderChangeListener.DelegateBorderChangeListener`'s packets: what + /// changed on the border since the guests were last told of it. + pub(in crate::game) fn lan_sync_border(&mut self, host: &mut crate::game::lan::LanHost) { + let now = horizon_client::lan::border::Sent::of(&self.border); + if let Some(sent) = host.border_sent.replace(now) { + for packet in sent.changes(&self.border) { + host.hub.broadcast(&packet); + } + } + } pub(in crate::game) fn tick_worldborder(&mut self) { self.border.tick(); + self.player_border(); + self.border_damage(); + } + /// The player's movement collides with the border as it is now + /// (`CollisionGetter.borderCollision`): from inside, its walls stop it. + pub(in crate::game) fn player_border(&mut self) { + if let Some(p) = self.player.as_mut() { + p.border = Some(self.border.geometry().clone()); + } + } + /// `LivingEntity.baseTick`: a player outside the border, further than + /// its safe zone, is hurt by the blocks beyond it. The game's player, or + /// a guest's in their turn (`as_guest`). + pub(in crate::game) fn border_damage(&mut self) { let Some((px, pz, half)) = self.player.as_ref().map(|p| { ( p.position.x, @@ -269,20 +293,6 @@ impl Game<'_> { let amount = (-dist * self.border.damage_per_block).floor().max(1.0) as f32; self.hurt_player_by("minecraft:outside_border", amount); } - // From inside the border the wall stops movement. - if self.border.distance(px, pz) >= 0.0 { - let [x, z] = self.border.clamp(px, pz, half); - if let Some(p) = self.player.as_mut() { - if x != px { - p.velocity.x = 0.0; - } - if z != pz { - p.velocity.z = 0.0; - } - p.position.x = x; - p.position.z = z; - } - } } pub(super) fn cmd_worldborder(&mut self, id: &str, ctx: &Context) -> R { let float2 = |v: f64| format!("{v:.2}"); diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index 7e02626d2..1f7504d8a 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -8,6 +8,7 @@ use horizon_client::{ text::Text, }; use horizon_core::random::RandomSource; +use horizon_protocol::packets::play::{self, Clientbound as C}; use horizon_world::attribute_map::ValueKind; use horizon_world::nbt::Tag; @@ -409,6 +410,8 @@ impl Game<'_> { ], _ => [1.0, 0.0, 0.0], }; + // The block state of a block particle, for its packet. + let mut block_state = None; let options = match ty { ParticleType::Dust => ParticleOptions::dust( rgb, @@ -470,6 +473,7 @@ impl Game<'_> { match block { Ok(Arg::Block(b)) => { let state = self.block_state(&b)?; + block_state = Some(state); let at = self .position_arg(ctx, "pos") .unwrap_or_else(|| self.source_position()) @@ -487,10 +491,9 @@ impl Game<'_> { let pos = self .position_arg(ctx, "pos") .unwrap_or_else(|| self.source_position()); - let delta = self.position_arg(ctx, "delta").map_or([0.0; 3], |d| { - let s = self.source_position(); - [d[0] - s[0], d[1] - s[1], d[2] - s[2]] - }); + // Vec3Argument.getVec3: the spread as given (relative parts from the + // source), not a position to measure from the source. + let delta = self.position_arg(ctx, "delta").unwrap_or([0.0; 3]); let speed = match ctx.get("speed") { Some(Arg::Float(v)) => *v, _ => 0.0, @@ -501,27 +504,74 @@ impl Game<'_> { }; // ParticleCommand.sendParticles: the viewers it reached, each within // 32 blocks (512 with `force`) of the particle's block centre. + // Without viewers, every player (PlayerList.getPlayers). let viewers = if ctx.get("viewers").is_some() { self.entities(ctx, "viewers", true)? } else { - vec![Target::Player] + let acting = self.lan_acting; + let guests = self.lan.iter().flat_map(|h| h.hub.guests.iter()); + self.player + .as_ref() + .map(|_| Target::Player) + .into_iter() + .chain( + guests + .filter(|g| g.placed && Some(g.conn) != acting) + .map(|g| Target::Guest(g.conn)), + ) + .collect() }; - let limit = if ctx.has("force") { 512.0 } else { 32.0 }; - let reached = viewers - .iter() - .filter(|&&t| { + let force = ctx.has("force"); + let limit = if force { 512.0 } else { 32.0 }; + let reached: Vec = viewers + .into_iter() + .filter(|&t| { self.target_position(t).is_some_and(|p| { let c = p.map(|v| v.floor() + 0.5); (c[0] - pos[0]).powi(2) + (c[1] - pos[1]).powi(2) + (c[2] - pos[2]).powi(2) < limit * limit }) }) - .count() as i32; - if reached == 0 { + .collect(); + if reached.is_empty() { return Err(err("commands.particle.failed", &[])); } - // `ServerLevel.sendParticles`: no count means one particle with the delta as velocity. - if count <= 0 { + // ServerLevel.sendParticles: each viewer a server serves is sent the + // particles (the player in place too when it is a guest); the + // window's own player draws them. + let packet = self + .network_particle(&options, block_state) + .map(|particle| { + C::LevelParticles(play::LevelParticles { + particle, + override_limiter: force, + always_show: false, + pos, + dist: delta.map(|d| d as f32), + max_speed: [speed; 3], + count: count.max(0), + randomization: 0, + }) + }); + let mut local = false; + for &t in &reached { + match (t, &packet) { + (Target::Player, Some(p)) if self.lan_acting.is_some() => { + self.guest_packets.push(p.clone()); + } + (Target::Player, _) => local = true, + (Target::Guest(conn), Some(p)) => { + if let Some(host) = self.lan.as_ref() { + host.hub.send_to(conn, p); + } + } + _ => {} + } + } + let reached = reached.len() as i32; + if !local { + } else if count <= 0 { + // No count: one particle with the delta as velocity. self.particles.create(&options, pos, delta); } else { for _ in 0..count { diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 9132c7723..f7e4c6b36 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -834,6 +834,12 @@ impl Game<'_> { "velocity": [p.velocity.x, p.velocity.y, p.velocity.z], "on_ground": p.ground.on_ground, "health": p.health.health(), + // The maximum the HUD's hearts last read (its cached value). + "max_health": p + .attributes + .lookup(p.attributes.key("minecraft:max_health").as_ref()) + .and_then(|h| p.attributes.instance(&h).ok()) + .map(|i| i.cached_value()), "food": p.health.food.food, }) }); @@ -971,6 +977,12 @@ impl Game<'_> { "flashes": self.lightning_seen[1], "flash": self.flash}); // Primed TNT, falling blocks, projectiles, tridents and end crystals. status["projectiles"] = json!(self.projectiles_status()); + // The particles made so far, by type. + status["particles"] = json!(self.particles.made()); + // The world border this side knows of. + status["border"] = json!({ "center": self.border.center(), "size": self.border.size() }); + // The scoreboard sidebar the HUD shows. + status["sidebar"] = self.sidebar_status(); status } } diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index d62c8ccc2..599158e3e 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -97,8 +97,58 @@ impl EndState { } } +impl EndState { + /// The eyes' entity ids, for a server to number them. + pub(super) fn eye_ids(&mut self) -> impl Iterator { + self.eyes.iter_mut().map(|e| &mut e.id) + } + /// The numbered eyes as a server's clients track them: (id, position, motion). + pub(super) fn eyes_tracked(&self) -> impl Iterator { + self.eyes + .iter() + .filter(|e| e.id != 0) + .map(|e| (e.id, e.position.to_array(), e.velocity.to_array())) + } + /// `handleAddEntity` for an eye of ender on a server's client: it flies + /// where the server says. + pub(super) fn add_remote_eye(&mut self, id: u32, at: [f64; 3], velocity: [f64; 3]) { + self.eyes.retain(|e| e.id != id); + let at = glam::DVec3::from_array(at); + self.eyes.push(EyeOfEnder { + id, + position: at, + previous: at, + velocity: glam::DVec3::from_array(velocity), + target: at, + life: 0, + survive: false, + }); + } + /// One tick of a server's client: `step` moves each toward where the + /// server put it. + pub(super) fn step_remote_eyes(&mut self, mut step: impl FnMut(u32, [f64; 3]) -> [f64; 3]) { + for e in &mut self.eyes { + e.previous = e.position; + e.life += 1; + e.position = glam::DVec3::from_array(step(e.id, e.position.to_array())); + } + } + pub(super) fn remove_remote_eye(&mut self, id: u32) { + self.eyes.retain(|e| e.id != id); + } + pub(super) fn clear_remote_eyes(&mut self) { + self.eyes.clear(); + } + /// Where each eye is, for `status`. + pub(super) fn eye_positions(&self) -> impl Iterator { + self.eyes.iter().map(|e| (e.id, e.position.to_array())) + } +} + /// The EyeOfEnder entity. struct EyeOfEnder { + /// Its entity id once a server's clients track it (0 until then). + id: u32, position: glam::DVec3, previous: glam::DVec3, velocity: glam::DVec3, @@ -1023,6 +1073,7 @@ impl Game<'_> { }; let survive = self.world.random.next_int_bound(5).unwrap_or(0) > 0; self.end.eyes.push(EyeOfEnder { + id: 0, position: start, previous: start, velocity: glam::DVec3::ZERO, diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 0923b4110..6ecba3a54 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -580,6 +580,7 @@ impl Game<'_> { self.particles.explosion(center, radius, block_count, &|b| { facts.is_air(world.block(b[0], b[1], b[2])) }); + self.lan_explode(center, radius, block_count); Ok(()) } /// `BlockBehaviour.onExplosionHit` (TNT: `wasExploded` primes a short fuse). diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 8467b6d3a..e7d2cb95e 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -66,6 +66,8 @@ pub(super) struct LanHost { /// whose respawn replaces their waypoint. pub waypoints: std::collections::HashMap, pub waypoint_dead: std::collections::HashSet, + /// The world border as the guests were last told of it (lan/border.rs). + pub border_sent: Option, /// Guests' commands waiting for the hub to be back in `self.lan`, where /// a command can reach every player (game/lan_actions.rs). pub commands: Vec, @@ -561,6 +563,7 @@ impl Game<'_> { owner: None, waypoints: Default::default(), waypoint_dead: Default::default(), + border_sent: None, commands: Vec::new(), states: Default::default(), }); @@ -891,6 +894,7 @@ impl Game<'_> { tick_frozen: self.clock.frozen(), tick_steps: self.clock.step_state(), collision: Some(self.collision), + border: &self.border, }; host.hub.movement_checks = ( self.ui.rules.bool("player_movement_check"), @@ -997,6 +1001,8 @@ impl Game<'_> { self.lan_update_streaming(&host); self.lan_update_models(&mut host); self.lan_update_waypoints(&mut host, state.as_ref()); + self.lan_sync_scoreboard(&mut host); + self.lan_sync_border(&mut host); drop(holding); lan::flush_all(host.hub.guests.iter().map(|g| &g.sender)); self.lan = Some(host); @@ -1073,6 +1079,7 @@ impl Game<'_> { tick_frozen: self.clock.frozen(), tick_steps: self.clock.step_state(), collision: Some(self.collision), + border: &self.border, }; host.hub.place_new_player(conn, &mut ctx); if elsewhere && let Err(e) = self.enter_level(Some(host), back) { @@ -1087,8 +1094,14 @@ impl Game<'_> { } for e in events { if let horizon_world::level::LevelEvent::LevelEvent { id, pos, data } = e { - // The acting guest does not predict the egg's teleport particles. - let except = if *id == 2015 { None } else { self.lan_acting }; + // The acting guest does not predict the egg's teleport + // particles, nor bone meal's growth (BoneMealItem.useOn's + // levelEvent names no player). + let except = if matches!(*id, 2015 | 1505) { + None + } else { + self.lan_acting + }; self.lan_events .push((*id, [pos.x, pos.y, pos.z], *data, except)); } diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 19c3a9a6c..aaefaad06 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -361,6 +361,7 @@ impl Game<'_> { self.apply_equipment(); play.equipped = Some(equipped); } + self.update_totem_ready(); Some(GuestSwap { conn, i, @@ -414,6 +415,8 @@ impl Game<'_> { /// The second half of `as_guest`: the guest's state back into their /// record, the game's back in place, and what the turn changed sent. pub(super) fn leave_guest(&mut self, host: &mut LanHost, swap: GuestSwap) { + // A totem that saved the guest this turn (its hurt set it off). + let totem = self.apply_totem(); let GuestSwap { conn, i, @@ -624,6 +627,16 @@ impl Game<'_> { let conn = g.conn; host.hub.set_game_mode(conn, new_mode); } + // LivingEntity.checkTotemDeathProtection's entity event, to every + // client around, the guest's own included; this window draws it too. + if let Some(body) = totem { + let id = host.hub.guests[i].entity_id; + host.hub + .entity_event(id, super::totem::TOTEM_EVENT, body.at); + if self.player.is_some() { + self.totem_event(body, false); + } + } host.play.insert(conn, play); self.stat_criteria_changed(&name, stat_events); if let Some(pos) = opened @@ -1581,6 +1594,7 @@ impl Game<'_> { tick_frozen: self.clock.frozen(), tick_steps: self.clock.step_state(), collision: Some(self.collision), + border: &self.border, }; host.hub.respawn(i, spawn, &ctx); if let Some(config) = elsewhere { @@ -1918,7 +1932,8 @@ impl Game<'_> { for d in travelled { game.movement_stats(Vec3::new(d[0], d[1], d[2])); } - // LivingEntity.baseTick ends with tickEffects. + // LivingEntity.baseTick: outside the world border, then tickEffects. + game.border_damage(); game.tick_mob_effects(); let Some(player) = game.player.as_mut() else { return Vec::new(); diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index f3098408c..db0c3e8b2 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -277,6 +277,8 @@ impl Game<'_> { self.rockets.iter_mut().for_each(|r| give(&mut r.id)); self.crystals.iter_mut().for_each(|c| give(&mut c.id)); self.bolts.iter_mut().for_each(|b| give(&mut b.id)); + self.potions.thrown_ids().for_each(&mut give); + self.end.eye_ids().for_each(&mut give); } /// Primed TNT, falling blocks, projectiles, tridents, firework rockets and @@ -359,6 +361,26 @@ impl Game<'_> { } out.push(e); } + // Thrown potions and bottles: ThrowableItemProjectile.DATA_ITEM_STACK + // (the potion's colour), which a plain bottle's type already has. + for (id, kind, stack, position, velocity) in self.potions.thrown_tracked() { + let mut e = state(id, kind, at(position), 0.0, false); + e.velocity = at(velocity); + if stack.extra.is_some() || stack.count != 1 { + e.meta.push(( + 8, + serializer::ITEM_STACK, + Value::Item(hub.stack(&Some(stack.clone()))), + )); + } + out.push(e); + } + // EyeOfEnder: its item is the plain eye (DATA_ITEM_STACK's default). + for (id, position, velocity) in self.end.eyes_tracked() { + let mut e = state(id, "minecraft:eye_of_ender", position, 0.0, false); + e.velocity = velocity; + out.push(e); + } for t in self.tridents.iter().filter(|t| t.id != 0) { let mut e = state(t.id, "minecraft:trident", at(t.position), t.yaw, false); e.pitch = t.pitch; diff --git a/crates/horizon-client/src/game/lan_particles.rs b/crates/horizon-client/src/game/lan_particles.rs new file mode 100644 index 000000000..2cacfabdb --- /dev/null +++ b/crates/horizon-client/src/game/lan_particles.rs @@ -0,0 +1,228 @@ +//! Particles a server sends its players and its clients draw: +//! `ClientboundLevelParticlesPacket` (`ServerLevel.sendParticles`, which +//! `/particle` uses) and `ClientboundExplodePacket` (`ServerLevel.explode`). +use super::Game; +use horizon_client::particles::{ParticleOptions, ParticleType}; +use horizon_core::random::RandomSource; +use horizon_protocol::{ + entity_data::{Particle, ParticleData}, + packets::play::{self, Clientbound as C}, +}; +use horizon_world::registry::BlockStateId; + +/// An ARGB colour as the options' RGBA. +fn rgba(argb: i32) -> [f32; 4] { + let c = |shift: i32| ((argb >> shift) & 255) as f32 / 255.0; + [c(16), c(8), c(0), c(24)] +} +/// The options' RGB as an RGB colour (`ARGB.colorFromFloat` without alpha). +fn rgb_int(c: [f32; 3]) -> i32 { + let b = |v: f32| ((v.clamp(0.0, 1.0) * 255.0).round() as i32) & 255; + (b(c[0]) << 16) | (b(c[1]) << 8) | b(c[2]) +} +fn rgb(c: [f32; 4]) -> [f32; 3] { + [c[0], c[1], c[2]] +} + +impl Game<'_> { + /// `ParticleTypes.STREAM_CODEC`'s value for `options`: the type's + /// network id and the data it carries (`state` for the block particles). + /// None while not serving, or for a particle whose data isn't sent from + /// here (items, vibrations, trails). + pub(super) fn network_particle( + &self, + options: &ParticleOptions, + state: Option, + ) -> Option { + let name = format!("minecraft:{}", options.ty.name()); + let id = self + .lan + .as_ref()? + .hub + .registry_id("minecraft:particle_type", &name)?; + use ParticleType as T; + let c = options.color; + let data = match options.ty { + T::Block | T::BlockMarker | T::FallingDust | T::DustPillar | T::BlockCrumble => { + Some(ParticleData::State(state?.0 as i32)) + } + T::Dust => Some(ParticleData::ColorScale(rgb_int(rgb(c)), options.scale)), + T::DustColorTransition => Some(ParticleData::ColorScale2( + rgb_int(rgb(c)), + rgb_int(options.to_color), + options.scale, + )), + T::Effect | T::InstantEffect => { + Some(ParticleData::ColorPower(rgb_int(rgb(c)), options.scale)) + } + T::EntityEffect | T::TintedLeaves => Some(ParticleData::Color( + (((c[3].clamp(0.0, 1.0) * 255.0).round() as i32) << 24) | rgb_int(rgb(c)), + )), + T::DragonBreath | T::SculkCharge => Some(ParticleData::Scalar(options.scale)), + T::Shriek => Some(ParticleData::Delay(options.scale as i32)), + T::Item | T::Trail | T::Vibration => return None, + _ => None, + }; + Some(Particle { id, data }) + } + + /// The options a server's particle stands for (None for a type or data + /// this client doesn't draw). + fn received_particle(&mut self, p: &Particle, at: [f64; 3]) -> Option { + let name = self + .remote + .as_ref()? + .builtin + .get("minecraft:particle_type")? + .name(p.id)? + .to_owned(); + let ty = ParticleType::from_name(&name)?; + Some(match &p.data { + None => ParticleOptions::simple(ty), + Some(ParticleData::State(s)) => { + let pos = at.map(|v| v.floor() as i32); + let (sprite, tint) = self + .particle_sprite(BlockStateId(*s as u32), pos) + .unwrap_or_else(|| ("block/stone".into(), 0xFFFFFF)); + ParticleOptions::block(ty, sprite, tint) + } + Some(ParticleData::ColorScale(c, scale)) => { + ParticleOptions::dust(rgb(rgba(*c)), *scale) + } + Some(ParticleData::ColorScale2(from, to, scale)) => { + ParticleOptions::dust_transition(rgb(rgba(*from)), rgb(rgba(*to)), *scale) + } + Some(ParticleData::ColorPower(c, power)) => ParticleOptions { + scale: *power, + ..ParticleOptions::colored(ty, [rgba(*c)[0], rgba(*c)[1], rgba(*c)[2], 1.0]) + }, + Some(ParticleData::Color(c)) => ParticleOptions::colored(ty, rgba(*c)), + Some(ParticleData::Scalar(v)) if ty == ParticleType::SculkCharge => { + ParticleOptions::sculk_charge(*v) + } + Some(ParticleData::Scalar(v)) => ParticleOptions { + scale: *v, + ..ParticleOptions::simple(ty) + }, + Some(ParticleData::Delay(d)) => ParticleOptions::shriek(*d), + Some(ParticleData::Trail(target, color, duration)) => { + ParticleOptions::trail(*target, *color as u32 & 0xFF_FFFF, *duration) + } + Some(_) => return None, + }) + } + + /// `ClientPacketListener.handleParticleEvent`: no count is one particle + /// moving by speed times spread; otherwise each is spread and sped up by + /// gaussians on each axis. + pub(super) fn remote_level_particles(&mut self, p: &play::LevelParticles) { + let Some(options) = self.received_particle(&p.particle, p.pos) else { + return; + }; + let (d, s) = (p.dist.map(f64::from), p.max_speed.map(f64::from)); + // ClientLevel.addParticle: the camera's 32 blocks unless the packet + // (`force`) or the type overrides the limiter. + let add = |particles: &mut horizon_client::particles::ParticleEngine, at, v| { + if p.override_limiter { + particles.create(&options, at, v); + } else { + particles.add(&options, at, v); + } + }; + if p.count == 0 { + add( + &mut self.particles, + p.pos, + [s[0] * d[0], s[1] * d[1], s[2] * d[2]], + ); + return; + } + for _ in 0..p.count { + let r = self.particles.random(); + let at = [ + p.pos[0] + r.next_gaussian() * d[0], + p.pos[1] + r.next_gaussian() * d[1], + p.pos[2] + r.next_gaussian() * d[2], + ]; + let v = [ + r.next_gaussian() * s[0], + r.next_gaussian() * s[1], + r.next_gaussian() * s[2], + ]; + add(&mut self.particles, at, v); + } + } + + /// `ClientPacketListener.handleExplosion`: the blast's particles (and its + /// sound, when the packet carries it). + pub(super) fn remote_explode(&mut self, p: &play::Explode) { + if p.play_sound { + let pitch = (1.0 + + (self.particles.random().next_float() - self.particles.random().next_float()) + * 0.2) + * 0.7; + self.audio.play( + "minecraft:entity.generic.explode", + Some(p.center), + 4.0, + pitch, + ); + } + let (world, facts) = (&self.world, self.res.facts()); + self.particles + .explosion(p.center, p.radius, p.block_count.max(0) as usize, &|b| { + facts.is_air(world.block(b[0], b[1], b[2])) + }); + } + + /// `ServerLevel.explode`'s packet to each player within 64 blocks. The + /// sound and the push reach them on their own (the level's sounds, the + /// players' motion), so the packet carries neither. + pub(super) fn lan_explode(&self, center: [f64; 3], radius: f32, block_count: usize) { + let Some(host) = self.lan.as_ref() else { + return; + }; + let particle = |name: &str| { + Some(Particle { + id: host.hub.registry_id("minecraft:particle_type", name)?, + data: None, + }) + }; + let emitter = if radius < 2.0 { + "minecraft:explosion" + } else { + "minecraft:explosion_emitter" + }; + let (Some(at_center), Some(poof), Some(smoke)) = ( + particle(emitter), + particle("minecraft:poof"), + particle("minecraft:smoke"), + ) else { + return; + }; + // Level.DEFAULT_EXPLOSION_BLOCK_PARTICLES. + let info = |particle, scaling| play::ExplosionParticle { + particle, + scaling, + speed: 1.0, + weight: 1, + }; + let packet = C::Explode(play::Explode { + center, + radius, + block_count: block_count as i32, + knockback: None, + particle: at_center, + sound: match host + .hub + .registry_id("minecraft:sound_event", "minecraft:entity.generic.explode") + { + Some(id) => (id, None), + None => (-1, Some(("minecraft:entity.generic.explode".into(), None))), + }, + block_particles: vec![info(poof, 0.5), info(smoke, 1.0)], + play_sound: false, + }); + host.hub.broadcast_near(center, 64.0, &packet, None); + } +} diff --git a/crates/horizon-client/src/game/lan_trading.rs b/crates/horizon-client/src/game/lan_trading.rs index 786399dac..83aafecc2 100644 --- a/crates/horizon-client/src/game/lan_trading.rs +++ b/crates/horizon-client/src/game/lan_trading.rs @@ -129,23 +129,6 @@ impl Game<'_> { } /// The screen title: the custom name, else the profession (the client /// adds the level itself). - #[allow(dead_code)] - fn merchant_title(&self, state: &MerchantState) -> String { - if let Some(name) = &state.name { - return name.clone(); - } - let e = &self.res.stations().enchantments; - let profession = state.session.profession.trim_start_matches("minecraft:"); - if state.session.villager { - e.translate(&format!("entity.minecraft.villager.{profession}")) - .unwrap_or(profession) - .to_owned() - } else { - e.translate("entity.minecraft.wandering_trader") - .unwrap_or("Wandering Trader") - .to_owned() - } - } /// `ServerPlayer.sendMerchantOffers`, when the offers changed. fn lan_send_offers( &mut self, diff --git a/crates/horizon-client/src/game/level_particles.rs b/crates/horizon-client/src/game/level_particles.rs index 47d06254d..d239c69d0 100644 --- a/crates/horizon-client/src/game/level_particles.rs +++ b/crates/horizon-client/src/game/level_particles.rs @@ -1,10 +1,10 @@ //! Level events whose client handler (`LevelEventHandler`) spawns particles -//! on a block: dragon egg teleportation (2015), a consumable's teleport -//! (2017), electric sparks (3002), waxing (3003), wax off (3004) and -//! scraping (3005). +//! on a block: bone meal's growth (1505), dragon egg teleportation (2015), a +//! consumable's teleport (2017), electric sparks (3002), waxing (3003), wax +//! off (3004) and scraping (3005). use super::Game; use horizon_client::particles::{self, ParticleOptions, ParticleType}; -use horizon_core::position::BlockPos; +use horizon_core::{position::BlockPos, random::RandomSource}; use horizon_world::level::LevelEvent; impl Game<'_> { @@ -42,6 +42,65 @@ impl Game<'_> { self.particles.add(&options, p, v); } } + /// `BoneMealItem.addGrowthParticles` (event 1505, `count` the data): + /// happy villager sparks over a spreading block's neighbourhood (grass, + /// nylium, netherrack, moss) or water, or inside a growing block. + pub(super) fn growth_particles(&mut self, pos: BlockPos, count: i32) { + let p = [pos.x, pos.y, pos.z]; + let state = self.world.block(p[0], p[1], p[2]); + let facts = self.res.facts(); + // ParticleUtils.spawnParticles(level, pos, count, xzSpread, ySpread, + // allowFloatingParticles, particle). + let (at, count, xz, height, floating) = match self.res.behaviours().bone_meal_spreads(state) + { + Some(spreads) => { + // BonemealableBlock.getParticlePos: below for rooted dirt + // (its hanging roots) and mangrove leaves (their propagule). + let at = match &*facts.get(state).name { + "minecraft:rooted_dirt" | "minecraft:mangrove_leaves" => [p[0], p[1] - 1, p[2]], + _ => p, + }; + if spreads { + (at, count * 3, 3.0, 1.0, false) + } else { + // ParticleUtils.spawnParticleInBlock: up to the + // block's shape (a full block when air). + let inside = self.world.block(at[0], at[1], at[2]); + let height = if facts.is_air(inside) { + 1.0 + } else { + facts + .get(inside) + .outline + .iter() + .map(|b| b[4]) + .fold(0.0, f64::max) + }; + (at, count, 0.5, height, true) + } + } + None if &*facts.get(state).name == "minecraft:water" => (p, count * 3, 3.0, 1.0, false), + None => return, + }; + let options = ParticleOptions::simple(ParticleType::HappyVillager); + for _ in 0..count.max(0) { + let r = self.particles.level_random(); + let v = [0.0; 3].map(|_: f64| r.next_gaussian() * 0.02); + let start = 0.5 - xz; + let x = f64::from(at[0]) + start + r.next_double() * xz * 2.0; + let y = f64::from(at[1]) + r.next_double() * height; + let z = f64::from(at[2]) + start + r.next_double() * xz * 2.0; + let below = [x.floor() as i32, y.floor() as i32 - 1, z.floor() as i32]; + if floating + || !self + .res + .facts() + .is_air(self.world.block(below[0], below[1], below[2])) + { + self.particles.add(&options, [x, y, z], v); + } + } + } /// Queue and play level event `id` at `pos` (`Level.levelEvent`). pub(super) fn level_event_at(&mut self, id: i32, pos: [i32; 3], data: i32) { self.level_events.push(LevelEvent::LevelEvent { diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index 94e61d948..ae2de00e6 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -133,7 +133,7 @@ impl Game<'_> { } fn reload_resources(&mut self, root: &Path) -> horizon_client::Result<()> { let render = std::sync::Arc::new(self.pack.assets.reload(root)?); - let mut atlas = HudAtlas::build(root)?; + let mut atlas = HudAtlas::build_over(root, &self.vanilla_root())?; atlas.font.uniform = self.settings.force_unicode; atlas.font.japanese = self.settings.japanese_glyphs; let gui = super::UiResources { diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 7b466b3bb..b17316e08 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -18,6 +18,8 @@ use horizon_core::{geometry::Vec3, random::RandomSource}; /// A thrown splash or lingering potion in flight. #[derive(Clone, Debug)] pub(super) struct ThrownPotion { + /// Its entity id once a server's clients track it (0 until then). + id: u32, stack: ItemStack, /// The position before the last tick, for drawing between ticks. previous: Vec3, @@ -47,6 +49,7 @@ impl Game<'_> { /// player's throws and dispensers both end up here). pub(super) fn launch_thrown(&mut self, stack: ItemStack, position: Vec3, velocity: Vec3) { self.potions.thrown.push(ThrownPotion { + id: 0, stack, previous: position, position, @@ -90,19 +93,78 @@ impl PotionState { pub(super) fn thrown_entities(&self) -> Vec<(&'static str, Vec3, Vec3)> { self.thrown .iter() - .map(|t| { - let kind = match &*t.stack.item { - "minecraft:lingering_potion" => "minecraft:lingering_potion", - "minecraft:experience_bottle" => "minecraft:experience_bottle", - _ => "minecraft:splash_potion", - }; - (kind, t.position, t.velocity) - }) + .map(|t| (thrown_kind(&t.stack), t.position, t.velocity)) .collect() } pub(super) fn clear_thrown(&mut self) { self.thrown.clear(); } + /// Their entity ids, for a server to number them. + pub(super) fn thrown_ids(&mut self) -> impl Iterator { + self.thrown.iter_mut().map(|t| &mut t.id) + } + /// The numbered ones as a server's clients track them: (id, entity + /// type, item, position, motion). + pub(super) fn thrown_tracked( + &self, + ) -> impl Iterator { + self.thrown.iter().filter(|t| t.id != 0).map(|t| { + ( + t.id, + thrown_kind(&t.stack), + &t.stack, + t.position, + t.velocity, + ) + }) + } + /// `handleAddEntity` for a thrown potion or bottle on a server's client: + /// drawn where the server says (its item comes in its entity data). + pub(super) fn add_remote_thrown(&mut self, id: u32, kind: &str, at: Vec3, velocity: Vec3) { + self.thrown.retain(|t| t.id != id); + let item = match kind { + "minecraft:lingering_potion" | "minecraft:experience_bottle" => kind, + _ => "minecraft:splash_potion", + }; + self.thrown.push(ThrownPotion { + id, + stack: ItemStack::new(item, 1), + previous: at, + position: at, + velocity, + age: 0, + }); + } + /// ThrowableItemProjectile.DATA_ITEM_STACK: the potion it shows. + pub(super) fn remote_thrown_item(&mut self, id: u32, stack: ItemStack) { + if let Some(t) = self.thrown.iter_mut().find(|t| t.id == id) { + t.stack = stack; + } + } + /// One tick of a server's client: `step` moves each toward where the + /// server put it. + pub(super) fn step_remote_thrown(&mut self, mut step: impl FnMut(u32, Vec3) -> Vec3) { + for t in &mut self.thrown { + t.previous = t.position; + t.age += 1; + t.position = step(t.id, t.position); + } + } + pub(super) fn remove_remote_thrown(&mut self, id: u32) { + self.thrown.retain(|t| t.id != id); + } + pub(super) fn has_thrown(&self, id: u32) -> bool { + self.thrown.iter().any(|t| t.id == id) + } +} + +/// The entity type of a thrown potion or bottle. +fn thrown_kind(stack: &ItemStack) -> &'static str { + match &*stack.item { + "minecraft:lingering_potion" => "minecraft:lingering_potion", + "minecraft:experience_bottle" => "minecraft:experience_bottle", + _ => "minecraft:splash_potion", + } } impl Game<'_> { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index dfde08d7f..fff79a7f2 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -101,7 +101,7 @@ fn place_interpolated(m: &mut Mob, at: PosRot) { pub(super) struct Remote { pub session: Session, pub brand: String, - builtin: Arc, + pub(super) builtin: Arc, lang: Arc, pub(super) registries: Arc, joined: bool, @@ -164,6 +164,8 @@ pub(super) struct Remote { level_players: HashMap, /// The local player's profile UUID (always in the level). profile: u128, + /// The local player's profile name: its score holder and team member. + pub(super) profile_name: String, destroying: Option<([i32; 3], u8, f32)>, destroy_delay: u32, input: horizon_client::interaction_input::InteractionInput, @@ -411,6 +413,7 @@ impl Game<'_> { online_mode: false, level_players: HashMap::new(), profile: 0, + profile_name: String::new(), destroying: None, destroy_delay: 0, input: Default::default(), @@ -795,6 +798,7 @@ impl Game<'_> { if let Some(r) = self.remote.as_mut() { r.joined = true; r.profile = uuid; + r.profile_name = name.clone(); r.status = format!("Joined as {name}; loading terrain..."); } } @@ -1725,29 +1729,12 @@ impl Game<'_> { self.block_entity_event(p.pos, i32::from(p.b0), i32::from(p.b1)); } } - C::LevelEvent(p) if p.kind == 2015 => { - self.dragon_egg_particles(p.pos, p.data); - } - C::LevelEvent(p) if p.kind == 2017 => { - self.consume_teleport_particles(p.pos, p.data); - } - C::LevelEvent(p) if p.kind == 2001 => { - // LevelEvent.PARTICLES_DESTROY_BLOCK: someone else broke a block. - let state = BlockStateId(p.data.max(0) as u32); - let s = self.res.facts().get(state).sounds.clone(); - let at = [ - f64::from(p.pos[0]) + 0.5, - f64::from(p.pos[1]) + 0.5, - f64::from(p.pos[2]) + 0.5, - ]; - self.audio.play( - &s.break_sound, - Some(at), - (s.volume + 1.0) / 2.0, - s.pitch * 0.8, - ); - self.destroy_particles(p.pos, state); - } + // ClientLevel.levelEvent: LevelEventHandler, as this client's own + // level plays them (particles and sounds: a spawner's burst, bone + // meal, waxing, a block broken by someone else). + C::LevelEvent(p) => self.level_event_at(p.kind, p.pos, p.data), + C::LevelParticles(p) => self.remote_level_particles(&p), + C::Explode(p) => self.remote_explode(&p), C::Sound(p) => { let name = match &p.sound.1 { Some((location, _)) => Some(location.clone()), @@ -2131,6 +2118,9 @@ impl Game<'_> { { m.health = 0.0; } + if p.event == super::totem::TOTEM_EVENT { + self.remote_totem(p.id); + } } C::Animate(p) => self.remote_animate(p.id, p.action), // ClientPacketListener.handleSwingAnimation: the entity swings @@ -2147,6 +2137,15 @@ impl Game<'_> { m.swing(); } } + // The player's own instances: its maximum health (the hearts the + // HUD draws and the health it may hold), reach, speed and so on. + // Then the received health again, which the old maximum clamped. + C::UpdateAttributes(p) if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) => { + if let Some(pl) = self.player.as_mut() { + horizon_client::lan::attributes::apply(&mut pl.attributes, &p.values); + } + self.apply_remote_health(); + } C::UpdateMobEffect(p) => self.remote_effect(&p), C::RemoveMobEffect(p) => { if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) @@ -3049,6 +3048,7 @@ impl Game<'_> { self.remote_handle_input(); // ClientLevel.tick: the border's size change. self.border.tick(); + self.player_border(); self.tick_remote_entities(running); // ClientLevel.tickBlockEntities: chest lids, shulker boxes, bells. self.tick_block_entity_anims(); @@ -3821,6 +3821,8 @@ impl Game<'_> { } if reacts { self.predict_use(&changes, seq); + } else if let Some(stack) = held.as_ref() { + self.predict_item_on_block(stack, &hit); } if held_block { if reacts @@ -3839,6 +3841,38 @@ impl Game<'_> { false } + /// `Item.useOn` on this client's level for the items whose effects are + /// the clicker's own (`Level.levelEvent(player, ...)` and + /// `playSound(player, ...)`: the server sends them to the others only): + /// honeycomb waxing copper, and an axe, hoe or shovel transforming a + /// block (stripping, scraping, removing wax, tilling, making a path). + fn predict_item_on_block(&mut self, stack: &ItemStack, hit: &super::Hit) { + let at = [ + f64::from(hit.pos[0]) + 0.5, + f64::from(hit.pos[1]) + 0.5, + f64::from(hit.pos[2]) + 0.5, + ]; + if &*stack.item == "minecraft:honeycomb" { + // HoneycombItem.useOn. + let registry = self.pack.assets.registry; + let clicked = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); + let waxes = registry + .state(clicked) + .and_then(|old| self.res.transformers().waxed(registry, old)) + .is_some(); + if waxes { + self.level_event_at(3003, hit.pos, 0); + self.audio + .play("minecraft:item.honeycomb.wax_on", Some(at), 1.0, 1.0); + } + } else if let Some((_, sound, _, _, particle)) = + self.block_transform(stack, hit.pos, hit.face) + { + self.transform_particle(&particle, hit.pos); + self.audio.play(&sound, Some(at), 1.0, 1.0); + } + } + /// MultiPlayerGameMode.useItemOn inside startPrediction: the blocks the /// use changed on this client's level at once, each kept as predicted /// under the use's sequence until the server acknowledges it (a use the diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs index c008611f6..82d0a11e2 100644 --- a/crates/horizon-client/src/game/remote_projectiles.rs +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -79,6 +79,15 @@ impl Game<'_> { self.rockets .push(super::fireworks::Rocket::remote(id, at, velocity)); } + "minecraft:splash_potion" + | "minecraft:lingering_potion" + | "minecraft:experience_bottle" => { + self.potions.add_remote_thrown(id, kind, at, velocity); + } + "minecraft:eye_of_ender" => { + self.end + .add_remote_eye(id, position, [velocity.x, velocity.y, velocity.z]) + } "minecraft:end_crystal" => self.crystals.push(super::dragon::Crystal { id, position: at, @@ -105,6 +114,17 @@ impl Game<'_> { /// `handleSetEntityData` for these types: what changes how they look. pub(super) fn remote_projectile_data(&mut self, id: i32, values: &[(u8, i32, Value)]) { let id = id as u32; + if self.potions.has_thrown(id) { + // ThrowableItemProjectile.DATA_ITEM_STACK: the potion it is. + for (index, _, value) in values { + if let (8, Value::Item(stack)) = (index, value) + && let Some(stack) = self.to_stack(stack) + { + self.potions.remote_thrown_item(id, stack); + } + } + return; + } for (index, _, value) in values { if let Some(t) = self.tnts.iter_mut().find(|t| t.id == id) { // PrimedTnt.DATA_FUSE_ID. @@ -184,6 +204,11 @@ impl Game<'_> { c.time += 1; c.position = step(c.id, c.position); } + self.potions.step_remote_thrown(&mut step); + self.end.step_remote_eyes(|id, at| { + let at = step(id, Vec3::new(at[0], at[1], at[2])); + [at.x, at.y, at.z] + }); } pub(super) fn remove_remote_projectile(&mut self, id: u32) { @@ -193,6 +218,8 @@ impl Game<'_> { self.tridents.retain(|t| t.id != id); self.rockets.retain(|r| r.id != id); self.crystals.retain(|c| c.id != id); + self.potions.remove_remote_thrown(id); + self.end.remove_remote_eye(id); } /// Every one a server sent (a new connection, level or dimension). @@ -203,6 +230,8 @@ impl Game<'_> { self.tridents.clear(); self.rockets.clear(); self.crystals.clear(); + self.potions.clear_thrown(); + self.end.clear_remote_eyes(); } /// Their kind and place, for `status`. @@ -225,6 +254,12 @@ impl Game<'_> { for p in &self.creatures.projectiles { out.push(json!({"id": p.id, "kind": format!("{:?}", p.kind).split([' ', '{']).next().unwrap_or(""), "position": at(p.position)})); } + for (kind, p, _) in self.potions.thrown_entities() { + out.push(json!({"kind": kind, "position": at(p)})); + } + for (id, p) in self.end.eye_positions() { + out.push(json!({"id": id, "kind": "minecraft:eye_of_ender", "position": p})); + } out } } diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 4d60c2df7..4905fb80f 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -324,6 +324,22 @@ impl Game<'_> { } } } + /// `ServerScoreboard`'s packets: each placed player's client is sent + /// what changed on the board since it was last sent it (all of it on + /// joining), lan/scoreboard.rs. + pub(super) fn lan_sync_scoreboard(&mut self, host: &mut super::lan::LanHost) { + if host.hub.guests.iter().all(|g| !g.placed) { + return; + } + self.load_scoreboard(); + let view = horizon_client::lan::scoreboard::View::of(&self.score.board); + for g in host.hub.guests.iter_mut().filter(|g| g.placed) { + if g.scoreboard != view { + g.send_all(&g.scoreboard.changes(&view)); + g.scoreboard = view.clone(); + } + } + } /// `ServerPlayer.doTick` score updates and the statistic criteria. pub(super) fn tick_scoreboard(&mut self) { self.load_scoreboard(); @@ -563,19 +579,42 @@ impl Game<'_> { // ---- the sidebar ----------------------------------------------------------- - /// `Hud.extractScoreboardSidebar` / `displayScoreboardSidebar`. - pub(super) fn draw_scoreboard(&self, batch: &mut HudBatch) { + /// The objective in the player's team's sidebar slot, else the sidebar's. + fn sidebar_objective(&self) -> Option<&sb::Objective> { let board = &self.score.board; if board.display.is_empty() { - return; + return None; } + // A server's client is in its team by its profile name. + let name = self + .remote + .as_ref() + .map_or(PLAYER_NAME, |r| r.profile_name.as_str()); let team_slot = board - .players_team(PLAYER_NAME) + .players_team(name) .and_then(|t| t.color.as_ref()) .map(|c| format!("sidebar.team.{c}")) .and_then(|slot| board.display_objective(&slot)); - let Some(objective) = team_slot.or_else(|| board.display_objective(sb::SLOT_SIDEBAR)) - else { + team_slot.or_else(|| board.display_objective(sb::SLOT_SIDEBAR)) + } + /// The sidebar the HUD shows: its objective and its lines, for `status`. + pub(super) fn sidebar_status(&self) -> serde_json::Value { + let board = &self.score.board; + let Some(objective) = self.sidebar_objective() else { + return serde_json::Value::Null; + }; + let scores: serde_json::Map = board + .scores + .iter() + .filter_map(|(holder, s)| Some((holder.clone(), s.get(&objective.name)?.value.into()))) + .collect(); + serde_json::json!({ "objective": objective.name, "title": objective.display_text().plain(), "scores": scores }) + } + + /// `Hud.extractScoreboardSidebar` / `displayScoreboardSidebar`. + pub(super) fn draw_scoreboard(&self, batch: &mut HudBatch) { + let board = &self.score.board; + let Some(objective) = self.sidebar_objective() else { return; }; let draws = hud_overlays::sidebar( diff --git a/crates/horizon-client/src/game/server_travel.rs b/crates/horizon-client/src/game/server_travel.rs index 1e94ec995..02b94c0f6 100644 --- a/crates/horizon-client/src/game/server_travel.rs +++ b/crates/horizon-client/src/game/server_travel.rs @@ -455,6 +455,7 @@ impl Game<'_> { tick_frozen: self.clock.frozen(), tick_steps: self.clock.step_state(), collision: Some(self.collision), + border: &self.border, } } } diff --git a/crates/horizon-client/src/game/totem.rs b/crates/horizon-client/src/game/totem.rs index 47b67d9f8..e26d66a1a 100644 --- a/crates/horizon-client/src/game/totem.rs +++ b/crates/horizon-client/src/game/totem.rs @@ -8,8 +8,12 @@ use horizon_client::{ const TOTEM: &str = "minecraft:totem_of_undying"; +/// `EntityEvent.TOTEM_OF_UNDYING`. +pub(super) const TOTEM_EVENT: i8 = 35; + impl Game<'_> { - /// Whether either hand holds a totem, for the next hurt. + /// Whether either hand holds a totem, for the next hurt: the window's + /// player once a tick, a server's player for each of its turns. pub(super) fn update_totem_ready(&mut self) { let ready = self.held().is_some_and(|s| &*s.item == TOTEM) || self.offhand.as_ref().is_some_and(|s| &*s.item == TOTEM); @@ -17,19 +21,21 @@ impl Game<'_> { p.health.totem_ready = ready; } } - /// A totem fired: use it up (main hand first), set health to 1, clear and - /// apply its effects, then the sound and particles. - pub(super) fn apply_totem(&mut self) { - let Some(p) = self.player.as_mut() else { - return; - }; + /// The server's half once a totem fired: use it up (main hand first), + /// count it, set health to 1, then clear and apply its effects. Returns + /// the player's body, for entity event 35, which the caller broadcasts. + pub(super) fn apply_totem(&mut self) -> Option { + let p = self.player.as_mut()?; if !p.health.totem_used { - return; + return None; } p.health.totem_used = false; let _ = p.set_health(1.0, false); - let at = [p.position.x, p.position.y, p.position.z]; - let height = f64::from(p.dimensions.height); + let body = Body { + at: [p.position.x, p.position.y, p.position.z], + width: f64::from(p.dimensions.width), + height: f64::from(p.dimensions.height), + }; let slot = if self.held().is_some_and(|s| &*s.item == TOTEM) { Some(self.selected) } else { @@ -45,6 +51,14 @@ impl Game<'_> { *cell = None; } } + self.stats.add("used", TOTEM, 1); + self.trigger_item( + "minecraft:used_totem", + &horizon_client::items::ItemStack::new(TOTEM, 1), + ); + // ItemStack.causeUseVibration: the totem's use effects make one. + let ctx = self.player_context(None); + self.post_game_event("minecraft:item_interact_finish", body.at, ctx); // DeathProtection.TOTEM_EFFECTS: clear, then regeneration II, absorption II, fire resistance. self.potions.effects.clear(); for (id, ticks, amp) in [ @@ -56,19 +70,64 @@ impl Game<'_> { self.add_player_effect(EffectInstance::new(e.id, ticks, amp)); } } - self.audio - .play("minecraft:item.totem.use", Some(at), 1.0, 1.0); - self.trigger_item( - "minecraft:used_totem", - &horizon_client::items::ItemStack::new("minecraft:totem_of_undying", 1), - ); + Some(body) + } + /// The window's player's totem: the server's half, then the event to + /// the guests and to this window's own client. + pub(super) fn tick_totem(&mut self) { + let Some(body) = self.apply_totem() else { + return; + }; + if let Some(host) = &self.lan { + host.hub + .entity_event(host.host_entity, TOTEM_EVENT, body.at); + } + self.totem_event(body, true); + } + /// Entity event 35 from a server, for this client's own player or an + /// entity it draws. + pub(super) fn remote_totem(&mut self, id: i32) { + let own = self.remote.as_ref().is_some_and(|r| r.entity_id == id); + let body = if own { + self.player.as_ref().map(|p| Body { + at: [p.position.x, p.position.y, p.position.z], + width: f64::from(p.dimensions.width), + height: f64::from(p.dimensions.height), + }) + } else { + self.mobs.iter().find(|m| m.id == id as u32).map(|m| Body { + at: [m.position.x, m.position.y, m.position.z], + width: f64::from(m.width()), + height: f64::from(m.height()), + }) + }; + if let Some(body) = body { + self.totem_event(body, own); + } + } + /// `ClientPacketListener.handleEntityEvent` 35: the totem particles (a + /// 30-tick emitter) and its sound, heard here only (`playLocalSound`), + /// and the player's own rumble. + pub(super) fn totem_event(&mut self, body: Body, own: bool) { self.particles.tracking_emitter_for( ParticleOptions::simple(ParticleType::TotemOfUndying), - at, - 0.6, - height, + body.at, + body.width, + body.height, 30, ); - self.pad_rumble(horizon_client::gamepad::Rumble::Totem); + self.audio + .play_unshared("minecraft:item.totem.use", Some(body.at), 1.0, 1.0); + if own { + self.pad_rumble(horizon_client::gamepad::Rumble::Totem); + } } } + +/// Where an entity event's entity stands and its size. +#[derive(Clone, Copy)] +pub(super) struct Body { + pub at: [f64; 3], + width: f64, + height: f64, +} diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 8371767c4..054ed25a9 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -1506,6 +1506,13 @@ impl Renderer { mapped_at_creation: false, }); let (atlas_pixels, atlas_width, atlas_height) = hud_atlas; + let limit = device.limits().max_texture_dimension_2d; + if atlas_width.max(atlas_height) > limit { + return Err(format!( + "the shared atlas is {atlas_width}x{atlas_height}; this GPU allows {limit}x{limit}" + ) + .into()); + } let atlas = device.create_texture_with_data( &queue, &wgpu::TextureDescriptor { @@ -2478,10 +2485,6 @@ impl Renderer { view_formats: &config.view_formats, }) } - /// Rendering to a texture instead of the window (`--offscreen`). - pub fn is_offscreen(&self) -> bool { - self.surface.is_none() - } /// Release the window surface before another renderer uses the same window. pub fn release_surface(&mut self) { self.surface = None; diff --git a/crates/horizon-client/src/gfx/lod.rs b/crates/horizon-client/src/gfx/lod.rs index 734110b5c..3ebec378b 100644 --- a/crates/horizon-client/src/gfx/lod.rs +++ b/crates/horizon-client/src/gfx/lod.rs @@ -119,10 +119,6 @@ impl Tile { } impl Renderer { - pub fn resident_lods(&self) -> usize { - self.lods.len() - } - pub fn upload_lod(&mut self, key: TileKey, mesh: &SectionMesh) { self.remove_lod(key); if let Some(bounds) = Bounds::mesh(mesh) diff --git a/crates/horizon-client/src/gossip.rs b/crates/horizon-client/src/gossip.rs index 9a964a3e6..9ea4a668d 100644 --- a/crates/horizon-client/src/gossip.rs +++ b/crates/horizon-client/src/gossip.rs @@ -7,7 +7,6 @@ use std::collections::BTreeMap; /// `ReputationEventType` amounts. pub const REPUTATION_CHANGE_PER_EVENT: i32 = 25; -pub const REPUTATION_CHANGE_PER_EVERLASTING_MEMORY: i32 = 20; pub const REPUTATION_CHANGE_PER_TRADE: i32 = 2; /// `GossipContainer.DISCARD_THRESHOLD`: values below this are forgotten. const DISCARD_THRESHOLD: i32 = 2; diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs index fe797af3e..6617ef009 100644 --- a/crates/horizon-client/src/graphics_ui.rs +++ b/crates/horizon-client/src/graphics_ui.rs @@ -486,14 +486,6 @@ impl Item { _ => return None, }) } - /// Caption and value text, split from the label ("Caption: Value"). - pub fn caption_value(self, s: &Settings) -> (String, String) { - let label = self.label(s).plain(); - match label.split_once(": ") { - Some((c, v)) => (c.to_owned(), v.to_owned()), - None => (label, String::new()), - } - } pub fn slider(self, s: &Settings) -> Option { match self { Item::Vanilla(o) => o.slider_position(s), diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 82e606947..cc922752e 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -9,6 +9,11 @@ use std::{ }; use wgpu::util::DeviceExt; +/// A sprite's atlas region, and its size in GUI pixels: the size of the +/// default resources' texture of that name, whatever the resolution of the +/// pack that replaced it (vanilla's GUI code draws in those units: `blit` +/// divides by the texture size it is given, sprites by their `gui.scaling` +/// size). Textures the default resources lack keep their own size. #[derive(Clone, Copy, Debug)] pub struct Rect { pub u0: f32, @@ -18,6 +23,15 @@ pub struct Rect { pub w: u32, pub h: u32, } +impl Rect { + /// The region's size in texels of an atlas this large. + pub fn texels(&self, (width, height): (u32, u32)) -> (u32, u32) { + ( + ((self.u1 - self.u0) * width as f32).round() as u32, + ((self.v1 - self.v0) * height as f32).round() as u32, + ) + } +} /// `TextureMetadataSection`'s `blur` and `clamp`: how vanilla samples a /// standalone texture (`ReloadableTexture.setSampler`: linear rather than /// nearest filtering, clamp-to-edge rather than repeat addressing). @@ -54,6 +68,9 @@ pub struct HudAtlas { } /// Atlas rows reserved for glyphs rasterized at run time. pub const GLYPH_ROWS: u32 = 512; +/// The largest atlas side: the 2D texture limit of the GPUs Horizon runs on +/// (Apple silicon, RADV and Intel allow 16384; NVIDIA 32768). +pub const MAX_ATLAS_SIZE: u32 = 16384; /// 128x128 atlas slots for map textures. A lobby paints its signs as walls of /// framed maps, so the pool holds a wall; too few slots re-upload every map /// every frame. 26.3's `MapTextureManager` keeps a texture per map instead. @@ -89,6 +106,15 @@ pub fn decode_bytes(data: &[u8]) -> Result<(u32, u32, Vec)> { } Ok((info.width, info.height, rgba)) } +/// A PNG's width and height, from its header alone. +fn png_size(path: &Path) -> Option<(u32, u32)> { + use std::io::Read; + let mut header = [0u8; 24]; + fs::File::open(path).ok()?.read_exact(&mut header).ok()?; + let field = |at: usize| u32::from_be_bytes(header[at..at + 4].try_into().unwrap_or_default()); + (header[..8] == *b"\x89PNG\r\n\x1a\n" && header[12..16] == *b"IHDR") + .then(|| (field(16), field(20))) +} fn walk(dir: &Path, out: &mut Vec) { let Ok(entries) = fs::read_dir(dir) else { return; @@ -201,8 +227,14 @@ impl HudAtlas { (g.rect, g.advance) } pub fn build(root: &Path) -> Result { + Self::build_over(root, root) + } + /// The atlas of a resource root that layers packs over `defaults` (the + /// game's own resources), whose textures give the sprites' GUI sizes. + pub fn build_over(root: &Path, defaults: &Path) -> Result { Self::pack( root, + defaults, &[ "gui", "item", @@ -265,14 +297,53 @@ impl HudAtlas { /// holding its textures. The pixels are dropped once the glyph widths are /// read, since nothing uploads them. pub fn fonts(root: &Path) -> Result { - let mut atlas = Self::pack(root, &["font"], false)?; + let mut atlas = Self::pack(root, root, &["font"], false)?; atlas.pixels = Vec::new(); Ok(atlas) } + /// Shelf placements of `images` (tallest first) in the narrowest atlas + /// width from 4096 up that keeps the atlas, glyph rows included, within + /// `max` texels a side; and the first row free for glyphs. High-resolution + /// packs fill a 4096-wide atlas past what GPUs allow (Faithful 64x needs + /// 32768 rows); vanilla's stitcher fails the reload when its atlases don't + /// fit, and the packs are then turned off (`Minecraft.clearResourcePacksOnError`). + fn layout(images: &[PackedImage], max: u32) -> Result<(u32, Vec<(u32, u32)>, u32)> { + let mut width = 4096.min(max); + loop { + let mut placements = Vec::with_capacity(images.len()); + let (mut x, mut y, mut row) = (0u32, 0u32, 0u32); + for (_, w, h, _) in images { + if x + w + 1 > width { + x = 0; + y += row + 1; + row = 0; + } + placements.push((x, y)); + x += w + 1; + row = row.max(*h); + } + let glyph_region = y + row + 1; + let wide_enough = images.iter().all(|i| i.1 < width); + if wide_enough && glyph_region + GLYPH_ROWS <= max { + return Ok((width, placements, glyph_region)); + } + if width >= max { + let texels: u64 = images.iter().map(|i| u64::from(i.1) * u64::from(i.2)).sum(); + return Err(format!( + "the textures ({} images, {texels} texels) do not fit a {max}x{max} atlas", + images.len() + ) + .into()); + } + width = (width * 2).min(max); + } + } /// Pack the textures under these folders of `textures/`, and for the /// `full` atlas the generated sprites and the run-time slots too. - fn pack(root: &Path, folders: &[&str], full: bool) -> Result { + fn pack(root: &Path, defaults: &Path, folders: &[&str], full: bool) -> Result { let textures = root.join("assets/minecraft/textures"); + let default_textures = + (defaults != root).then(|| defaults.join("assets/minecraft/textures")); let mut files = Vec::new(); for folder in folders { walk(&textures.join(folder), &mut files); @@ -281,7 +352,8 @@ impl HudAtlas { let s = p.to_string_lossy(); !s.contains("title/background") && !s.contains("realms") && !s.contains("presets") }); - let decode_one = |path: &PathBuf| -> Option<(PackedImage, Option)> { + type Decoded = (PackedImage, Option, Option<(u32, u32)>); + let decode_one = |path: &PathBuf| -> Option { let name = path .strip_prefix(&textures) .ok()? @@ -289,18 +361,29 @@ impl HudAtlas { .to_string_lossy() .replace('\\', "/"); let (w, mut h, pixels) = decode(path).ok()?; - let is_frame_strip = (name.starts_with("block/") || name.starts_with("item/")) && h > w; - let pixels = if is_frame_strip { + // Animated strips keep their first frame. + let frames = name.starts_with("block/") || name.starts_with("item/"); + let pixels = if frames && h > w { h = w; pixels[..(w * w * 4) as usize].to_vec() } else { pixels }; + // The default texture's size, when a pack's differs from it. + let gui_size = default_textures + .as_ref() + .and_then(|d| png_size(&d.join(format!("{name}.png")))) + .map(|(dw, dh)| (dw, if frames { dh.min(dw) } else { dh })) + .filter(|&size| size != (w, h)); let flags = fs::read_to_string(path.with_extension("png.mcmeta")) .ok() .and_then(|json| TextureFlags::from_mcmeta(&json)); - (w <= 1024 && (h <= 512 || name.starts_with("font/"))) - .then_some(((name, w, h, pixels), flags)) + let (gw, gh) = gui_size.unwrap_or((w, h)); + (gw <= 1024 && (gh <= 512 || name.starts_with("font/"))).then_some(( + (name, w, h, pixels), + flags, + gui_size, + )) }; let threads = std::thread::available_parallelism().map_or(2, |n| n.get()); let chunk = files.len().div_ceil(threads).max(1); @@ -317,11 +400,15 @@ impl HudAtlas { .collect() }); let mut flags = HashMap::new(); + let mut gui_sizes = HashMap::new(); let mut images: Vec = Vec::with_capacity(decoded.len()); - for (image, image_flags) in decoded { + for (image, image_flags, gui_size) in decoded { if let Some(f) = image_flags { flags.insert(image.0.clone(), f); } + if let Some(size) = gui_size { + gui_sizes.insert(image.0.clone(), size); + } images.push(image); } if full { @@ -351,21 +438,10 @@ impl HudAtlas { } } images.sort_by(|a, b| b.2.cmp(&a.2).then(b.1.cmp(&a.1))); - let width = 4096u32; - let mut placements = Vec::with_capacity(images.len()); - let (mut x, mut y, mut row) = (0u32, 0u32, 0u32); - for (_, w, h, _) in &images { - if x + w + 1 > width { - x = 0; - y += row + 1; - row = 0; - } - placements.push((x, y)); - x += w + 1; - row = row.max(*h); - } - let glyph_region = y + row + 1; - let height = (glyph_region + GLYPH_ROWS).next_power_of_two(); + let (width, placements, glyph_region) = Self::layout(&images, MAX_ATLAS_SIZE)?; + // A multiple of 1024 rather than a power of two: the default resources + // need 4096x5120 (8192 rows before), Faithful 32x 4096x12288 (16384). + let height = (glyph_region + GLYPH_ROWS).next_multiple_of(1024); let mut pixels = vec![0u8; (width * height * 4) as usize]; let mut sprites = HashMap::new(); for ((name, w, h, data), (px, py)) in images.iter().zip(placements) { @@ -376,6 +452,7 @@ impl HudAtlas { } let b = u32::from(bordered.contains(name)); let (px, py, w, h) = (px + b, py + b, w - 2 * b, h - 2 * b); + let (gw, gh) = gui_sizes.get(name).copied().unwrap_or((w, h)); sprites.insert( name.clone(), Rect { @@ -383,8 +460,8 @@ impl HudAtlas { v0: py as f32 / height as f32, u1: (px + w) as f32 / width as f32, v1: (py + h) as f32 / height as f32, - w, - h, + w: gw, + h: gh, }, ); } @@ -404,14 +481,15 @@ impl HudAtlas { .find(|a| a.layer == layer) .cloned() { - let image = animation.resized_pixels(animation.frame(0), rect.w, rect.h); + let (tw, th) = rect.texels((width, height)); + let image = animation.resized_pixels(animation.frame(0), tw, th); let x = (rect.u0 * width as f32).round() as usize; let y = (rect.v0 * height as f32).round() as usize; - for row in 0..rect.h as usize { + let row_bytes = tw as usize * 4; + for row in 0..th as usize { let dst = ((y + row) * width as usize + x) * 4; - let src = row * rect.w as usize * 4; - pixels[dst..dst + rect.w as usize * 4] - .copy_from_slice(&image[src..src + rect.w as usize * 4]); + let src = row * row_bytes; + pixels[dst..dst + row_bytes].copy_from_slice(&image[src..src + row_bytes]); } fire_animations.push((rect, animation)); } @@ -783,24 +861,6 @@ impl HudBatch { }; self.text_styled(atlas, &t, x, y, color, shadow) } - /// `text_styled` under a pose: GUI positions scaled by `scale`, then - /// moved to `origin` (Matrix3x2fStack translate + scale). - pub fn text_posed( - &mut self, - atlas: &HudAtlas, - text: &crate::text::Text, - at: [f32; 2], - color: u32, - scale: f32, - origin: [f32; 2], - ) -> f32 { - let start = self.vertices.len(); - let advance = self.text_styled(atlas, text, at[0], at[1], color, true); - for v in &mut self.vertices[start..] { - v.pos = [origin[0] + v.pos[0] * scale, origin[1] + v.pos[1] * scale]; - } - advance - } /// Font.drawInternal: styled glyphs, shadows first, with bold, italic, /// underline and strikethrough. `color` is the default colour and alpha. pub fn text_styled( @@ -1162,7 +1222,8 @@ impl HudRenderer { if frame == *previous { continue; } - let pixels = animation.resized_pixels(frame, rect.w, rect.h); + let (w, h) = rect.texels((texture.width(), texture.height())); + let pixels = animation.resized_pixels(frame, w, h); uploads.texture( encoder, wgpu::TexelCopyTextureInfo { @@ -1175,8 +1236,8 @@ impl HudRenderer { }, aspect: wgpu::TextureAspect::All, }, - rect.w, - rect.h, + w, + h, &pixels, ); *previous = frame; @@ -1340,6 +1401,87 @@ impl HudRenderer { mod tests { use super::*; + /// `count` images of `w x h`; layout reads only their sizes. + fn sized(count: usize, w: u32, h: u32) -> Vec { + (0..count) + .map(|i| (format!("i{i}"), w, h, Vec::new())) + .collect() + } + fn assert_inside(images: &[PackedImage], width: u32, placements: &[(u32, u32)], free: u32) { + for ((_, w, h, _), (x, y)) in images.iter().zip(placements) { + assert!( + x + w <= width && y + h < free, + "{x},{y} {w}x{h} outside {width}x{free}" + ); + } + } + fn write_png(root: &Path, name: &str, w: u32, h: u32) { + let path = root.join(format!("assets/minecraft/textures/{name}.png")); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + let mut encoder = png::Encoder::new(fs::File::create(path).unwrap(), w, h); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + let pixels = vec![255; (w * h * 4) as usize]; + encoder + .write_header() + .unwrap() + .write_image_data(&pixels) + .unwrap(); + } + #[test] + fn a_pack_texture_keeps_the_default_textures_gui_size() { + let temp = std::env::temp_dir().join(format!("horizon-gui-size-{}", std::process::id())); + let (defaults, pack) = (temp.join("defaults"), temp.join("pack")); + write_png(&defaults, "gui/container/inventory", 256, 256); + write_png(&defaults, "gui/sprites/widget/button", 200, 20); + write_png(&defaults, "block/stone", 16, 16); + write_png(&defaults, "item/compass", 16, 512); + // Faithful 64x's inventory (past the 512 rows a texture may have), + // 32x's button and stone, an animated strip, and a texture of its own. + write_png(&pack, "gui/container/inventory", 1024, 1024); + write_png(&pack, "gui/sprites/widget/button", 400, 40); + write_png(&pack, "block/stone", 32, 32); + write_png(&pack, "item/compass", 32, 1024); + write_png(&pack, "gui/sprites/pack_only", 30, 10); + let atlas = HudAtlas::build_over(&pack, &defaults).unwrap(); + let _ = fs::remove_dir_all(&temp); + let size = (atlas.width, atlas.height); + for (name, gui, texels) in [ + ("gui/container/inventory", (256, 256), (1024, 1024)), + ("gui/sprites/widget/button", (200, 20), (400, 40)), + ("block/stone", (16, 16), (32, 32)), + ("item/compass", (16, 16), (32, 32)), + ("gui/sprites/pack_only", (30, 10), (30, 10)), + ] { + let r = atlas.sprites[name]; + assert_eq!(((r.w, r.h), r.texels(size)), (gui, texels), "{name}"); + } + } + #[test] + fn the_default_textures_keep_a_4096_wide_atlas() { + let images = sized(400, 64, 64); + let (width, placements, free) = HudAtlas::layout(&images, MAX_ATLAS_SIZE).unwrap(); + assert_eq!(width, 4096); + assert_inside(&images, width, &placements, free); + } + #[test] + fn a_high_resolution_pack_widens_the_atlas_to_fit_the_gpu() { + // 34 rows of three 1024x512 GUI textures: 17442 rows at 4096 wide, + // past the 16384 GPUs allow (Faithful 64x needed 32768). + let images = sized(100, 1024, 512); + let (width, placements, free) = HudAtlas::layout(&images, MAX_ATLAS_SIZE).unwrap(); + assert_eq!(width, 8192); + assert!(free + GLYPH_ROWS <= MAX_ATLAS_SIZE); + assert_inside(&images, width, &placements, free); + } + #[test] + fn textures_that_cannot_fit_are_an_error_not_a_gpu_panic() { + let error = HudAtlas::layout(&sized(300, 1024, 1024), MAX_ATLAS_SIZE).unwrap_err(); + assert!(error.to_string().contains("do not fit a 16384x16384 atlas")); + // One image wider than the largest atlas. + assert!(HudAtlas::layout(&sized(1, 2048, 16), 2048).is_err()); + } + #[test] fn a_wrapped_border_repeats_the_opposite_edges() { // 2x2 texels a b / c d, one byte each in red. diff --git a/crates/horizon-client/src/item_render.rs b/crates/horizon-client/src/item_render.rs index 45531bedd..c2f5c8400 100644 --- a/crates/horizon-client/src/item_render.rs +++ b/crates/horizon-client/src/item_render.rs @@ -124,17 +124,6 @@ impl ItemRenderState { pub fn is_empty(&self) -> bool { self.layers.is_empty() } - /// `pickParticleMaterial`: a random layer's particle sprite. - pub fn pick_particle( - &self, - random: &mut impl horizon_core::random::RandomSource, - ) -> Option { - if self.layers.is_empty() { - return None; - } - let i = random.next_int_bound(self.layers.len() as i32).unwrap_or(0) as usize; - self.layers.get(i).map(|l| l.particle.clone()) - } /// `usesBlockLight` of the first layer (GUI lighting choice). pub fn uses_block_light(&self) -> bool { self.layers.first().is_some_and(|l| l.uses_block_light) diff --git a/crates/horizon-client/src/keybinds.rs b/crates/horizon-client/src/keybinds.rs index 5f8c0876b..a59aa627c 100644 --- a/crates/horizon-client/src/keybinds.rs +++ b/crates/horizon-client/src/keybinds.rs @@ -295,15 +295,6 @@ impl KeyBinds { self.keys.insert(n, key.to_owned()); } } - /// Load `key_` from options.txt; false for unknown mappings. - pub fn set_saved(&mut self, name: &str, key: &str) -> bool { - if MAPPINGS.iter().any(|m| m.0 == name) { - self.set(name, key); - true - } else { - false - } - } pub fn saved(&self) -> Vec<(&'static str, String)> { MAPPINGS .iter() diff --git a/crates/horizon-client/src/keymapping.rs b/crates/horizon-client/src/keymapping.rs index e598fbf71..e438c27ce 100644 --- a/crates/horizon-client/src/keymapping.rs +++ b/crates/horizon-client/src/keymapping.rs @@ -104,8 +104,6 @@ pub const SNEAK: usize = 0; pub const SPRINT: usize = 1; /// Attack (mouse). pub const ATTACK: usize = 2; -/// Use (mouse). -pub const USE: usize = 3; /// The `ToggleKeyMapping`s `Options` builds: sneak and sprint (keyboard, /// restored after a screen), attack (mouse, restored) and use (mouse, not diff --git a/crates/horizon-client/src/lan/attributes.rs b/crates/horizon-client/src/lan/attributes.rs index bc208b6f9..eef565409 100644 --- a/crates/horizon-client/src/lan/attributes.rs +++ b/crates/horizon-client/src/lan/attributes.rs @@ -5,7 +5,7 @@ //! changed since (`getAttributesToSync`), to the trackers and the player itself. use horizon_protocol::packets::play::{AttributeModifier, AttributeSnapshot}; use horizon_world::attributes::{ - Instance, Operation, + Instance, Modifier, Operation, entity::{AttributeId, EntityAttributes}, live::LiveAttributes, }; @@ -70,6 +70,48 @@ pub fn take_dirty i32>(map: &mut LiveAttributes) -> Vec i32>(map: &mut LiveAttributes, values: &[AttributeSnapshot]) { + for s in values { + let Some(key) = map + .keys() + .iter() + .find(|k| k.attribute().registry_id() == s.attribute) + .cloned() + else { + continue; + }; + let Ok(Some(handle)) = map.get_instance(Some(key)) else { + continue; + }; + let modifiers: Vec<_> = s + .modifiers + .iter() + .filter_map(|m| Modifier::new(&m.id, m.amount, operation(m.operation)).ok()) + .collect(); + let _ = map.edit(&handle, |instance, observer| { + instance.set_base_value(s.base, observer)?; + instance.remove_all(observer)?; + for m in modifiers { + instance.add_transient(m, observer)?; + } + Ok(()) + }); + } +} + +/// `AttributeModifier.Operation.BY_ID`. +fn operation(id: i32) -> Operation { + match id { + 1 => Operation::AddMultipliedBase, + 2 => Operation::AddMultipliedTotal, + _ => Operation::AddValue, + } +} + /// The client-syncable instances of a generic attribute map. pub fn generic_syncable(map: &EntityAttributes) -> impl Iterator + '_ { let catalog = map.catalog(); diff --git a/crates/horizon-client/src/lan/border.rs b/crates/horizon-client/src/lan/border.rs new file mode 100644 index 000000000..b4e3ffc63 --- /dev/null +++ b/crates/horizon-client/src/lan/border.rs @@ -0,0 +1,130 @@ +//! The world border a server's players see: all of it when they enter a +//! level (`PlayerList.sendLevelInfo`), then each change as +//! `BorderChangeListener` broadcasts it: a new centre, a new size, a size +//! change in progress, a new warning time or distance. +use crate::worldborder::WorldBorder; +use horizon_protocol::packets::play::{self, Clientbound as C}; + +/// `ClientboundInitializeBorderPacket`. +pub fn initialize(b: &WorldBorder) -> play::InitializeBorder { + let [center_x, center_z] = b.center(); + play::InitializeBorder { + center_x, + center_z, + old_size: b.size(), + new_size: b.target_size(), + lerp_time: b.remaining_ticks(), + absolute_max_size: b.absolute_max_size(), + warning_blocks: b.warning_distance, + warning_time: b.warning_time, + } +} + +/// The border as the players were last told of it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Sent { + center: [f64; 2], + size: f64, + target: f64, + remaining: i64, + warning_distance: i32, + warning_time: i32, +} + +impl Sent { + pub fn of(b: &WorldBorder) -> Self { + Self { + center: b.center(), + size: b.size(), + target: b.target_size(), + remaining: b.remaining_ticks(), + warning_distance: b.warning_distance, + warning_time: b.warning_time, + } + } + + /// The packets that tell the players what changed since `self`, other + /// than a size change going on (which each client runs itself). + pub fn changes(&self, b: &WorldBorder) -> Vec { + let now = Self::of(b); + let mut out = Vec::new(); + if now.center != self.center { + out.push(C::SetBorderCenter(play::SetBorderCenter { + x: now.center[0], + z: now.center[1], + })); + } + // A change going on counts down a tick at a time (or not at all + // while the game is frozen), towards the same size. + let going_on = self.remaining > 0 + && now.target == self.target + && (now.remaining == self.remaining || now.remaining == self.remaining - 1); + if now.remaining > 0 { + if !going_on { + out.push(C::SetBorderLerpSize(play::SetBorderLerpSize { + old_size: now.size, + new_size: now.target, + lerp_time: now.remaining, + })); + } + } else if now.size != self.size && !(self.remaining > 0 && now.size == self.target) { + out.push(C::SetBorderSize(play::SetBorderSize { size: now.size })); + } + if now.warning_time != self.warning_time { + out.push(C::SetBorderWarningDelay(play::SetBorderWarningDelay { + delay: now.warning_time, + })); + } + if now.warning_distance != self.warning_distance { + out.push(C::SetBorderWarningDistance( + play::SetBorderWarningDistance { + blocks: now.warning_distance, + }, + )); + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn kinds(packets: &[C]) -> Vec<&'static str> { + packets + .iter() + .map(|p| match p { + C::SetBorderCenter(_) => "center", + C::SetBorderSize(_) => "size", + C::SetBorderLerpSize(_) => "lerp", + C::SetBorderWarningDelay(_) => "delay", + C::SetBorderWarningDistance(_) => "distance", + _ => "other", + }) + .collect() + } + + #[test] + fn each_change_is_sent_once() { + let mut b = WorldBorder::default(); + let mut sent = Sent::of(&b); + assert!(sent.changes(&b).is_empty()); + b.set_center([4.0, -2.0]); + b.set_size(10.0); + b.warning_time = 30; + assert_eq!(kinds(&sent.changes(&b)), ["center", "size", "delay"]); + sent = Sent::of(&b); + // A change over 3 ticks: sent once, then each client runs it. + b.lerp_to(20.0, 3); + assert_eq!(kinds(&sent.changes(&b)), ["lerp"]); + for _ in 0..4 { + sent = Sent::of(&b); + b.tick(); + assert!(sent.changes(&b).is_empty(), "{:?}", sent.changes(&b)); + } + assert_eq!(b.size(), 20.0); + b.warning_distance = 1; + assert_eq!(kinds(&Sent::of(&b).changes(&b)), [] as [&str; 0]); + assert_eq!(kinds(&sent.changes(&b)), ["distance"]); + } +} diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 6ed7a2925..84e768879 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -15,7 +15,6 @@ use std::{ /// GameType ids. pub const SURVIVAL: i32 = 0; pub const CREATIVE: i32 = 1; -pub const ADVENTURE: i32 = 2; pub const SPECTATOR: i32 = 3; /// The body state a player's file keeps that lives on `PlayerMotion`. @@ -243,6 +242,8 @@ pub struct Guest { pub advancements_loaded: bool, pub advancements_visible: Vec, pub advancements_changed: std::collections::BTreeSet, + /// The server's scoreboard as this player's client has it (lan/scoreboard.rs). + pub scoreboard: super::scoreboard::View, /// Recipes unlocked since the client was last told /// (`ServerRecipeBook.addRecipes` sends them). pub recipes_unlocked: Vec, @@ -355,6 +356,7 @@ impl Guest { advancements_loaded: false, advancements_visible: Vec::new(), advancements_changed: Default::default(), + scoreboard: Default::default(), recipes_unlocked: Vec::new(), } } diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index c8f2e980d..640d6616c 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -111,6 +111,8 @@ pub struct TickCtx<'a> { /// Block collisions, for ServerGamePacketListenerImpl's moved-wrongly /// check (none: moves are not checked against blocks). pub collision: Option<&'a BlockCollisionRegistry<'a>>, + /// The level's world border (PlayerList.sendLevelInfo sends it). + pub border: &'a crate::worldborder::WorldBorder, } /// What the gameplay code has to do for a guest. @@ -172,13 +174,6 @@ pub struct Hub { fn string(s: &str) -> Tag { Tag::String(JavaString::from(s)) } -pub fn yellow_translation(key: &str, args: &[&str]) -> Tag { - let mut t = translatable(key, args); - if let Tag::Compound(map) = &mut t { - map.insert(JavaString::from("color"), string("yellow")); - } - t -} /// Player.getDisplayName for a player in no team: the name, suggesting /// `/tell NAME `, showing the player on hover and inserting the name. @@ -898,17 +893,7 @@ impl Hub { fn send_level_info(&mut self, i: usize, ctx: &TickCtx) { let spawn = ctx.spawn; let g = &self.guests[i]; - g.send(&C::InitializeBorder(play::InitializeBorder { - center_x: 0.0, - center_z: 0.0, - old_size: 59_999_968.0, - new_size: 59_999_968.0, - lerp_time: 0, - absolute_max_size: 29_999_984, - warning_blocks: 5, - // WorldBorder.DEFAULT_WARNING_TIME, in ticks. - warning_time: 300, - })); + g.send(&C::InitializeBorder(super::border::initialize(ctx.border))); g.send(&self.time_packet(ctx.world, ctx.clock_rate)); g.send(&self.default_spawn(spawn)); let w = &ctx.world.weather; @@ -1360,21 +1345,6 @@ impl Hub { (!batch.is_empty()).then_some(batch) } - /// Resend a chunk to everyone who has it (a block entity changed, relight). - pub fn resend_chunk(&mut self, world: &World, x: i32, z: i32) { - let Some(chunk) = world.chunks.get(&(x, z)) else { - return; - }; - let body = self.encoder.body_in(chunk, world); - for g in self - .guests - .iter() - .filter(|g| g.sent_chunks.contains(&(x, z))) - { - g.sender.send(body.clone()); - } - } - /// `ChunkHolder.broadcastChanges`' light part: the light sections that /// changed in a column go to the players for whom it is on the border of /// what they track (`ChunkMap.isChunkOnTrackedBorder`); the others light diff --git a/crates/horizon-client/src/lan/mod.rs b/crates/horizon-client/src/lan/mod.rs index c2f35bc8e..e2f0a719f 100644 --- a/crates/horizon-client/src/lan/mod.rs +++ b/crates/horizon-client/src/lan/mod.rs @@ -6,6 +6,7 @@ //! world that is not open to the network pays nothing. mod advancements; pub mod attributes; +pub mod border; pub mod chunks; mod command_order; pub mod command_suggestions; @@ -20,6 +21,7 @@ pub mod hub; pub mod menu; pub mod playerdata; mod recipes; +pub mod scoreboard; pub mod tracking; pub mod waypoints; @@ -272,9 +274,6 @@ impl Shared { pub fn max_players(&self) -> usize { self.max_players.load(Ordering::Relaxed) } - pub fn set_max_players(&self, n: usize) { - self.max_players.store(n, Ordering::Relaxed); - } pub fn release(&self, uuid: u128) { self.online.lock().unwrap().retain(|(u, _)| *u != uuid); } @@ -513,9 +512,6 @@ impl Lan { pub fn reserve(&self, uuid: u128) { self.shared.reserved.lock().unwrap().insert(uuid); } - pub fn set_motd(&self, motd: &str) { - *self.shared.motd.lock().unwrap() = motd.to_owned(); - } pub fn stop(&mut self) { self.shared.stop.store(true, Ordering::Relaxed); self.stop_listening(); diff --git a/crates/horizon-client/src/lan/scoreboard.rs b/crates/horizon-client/src/lan/scoreboard.rs new file mode 100644 index 000000000..cba0f914c --- /dev/null +++ b/crates/horizon-client/src/lan/scoreboard.rs @@ -0,0 +1,308 @@ +//! `ServerScoreboard`: what a player's client knows of the server's +//! scoreboard. Every team goes to every player; an objective goes once it +//! sits in a display slot (`startTrackingObjective`: its objective, its +//! slots, then its scores) and leaves when it sits in none +//! (`stopTrackingObjective`). A joining player gets it all +//! (`PlayerList.updateEntireScoreboard`). +//! +//! A server's commands change the board in place; each tick a player is +//! sent the packets that turn what it was last sent into what it should +//! have now, which are the ones `ServerScoreboard`'s callbacks send. +use crate::scoreboard::{NumberFormat, RenderType, Scoreboard, component_tag, display_slots}; +use crate::text::COLORS; +use horizon_protocol::packets::play::{ + self, Clientbound as C, ResetScore, SetDisplayObjective, SetObjective, SetPlayerTeam, SetScore, + TeamParameters, +}; +use horizon_world::nbt::Tag; +use std::collections::{BTreeMap, BTreeSet}; + +type Format = Option; + +/// The scoreboard as one player's client has it. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct View { + /// The tracked objectives: display name, render type (1 hearts), format. + objectives: BTreeMap, + /// `DisplaySlot` id to objective. + display: BTreeMap, + /// The tracked objectives' scores, by holder and objective. + scores: BTreeMap<(String, String), (i32, Option, Format)>, + /// Every team: its parameters and players, in the team's order. + teams: BTreeMap)>, +} + +fn format(f: Option<&NumberFormat>) -> Format { + f.map(|f| match f { + NumberFormat::Blank => play::NumberFormat::Blank, + NumberFormat::Styled(s) => play::NumberFormat::Styled(crate::scoreboard::json_to_tag(s)), + NumberFormat::Fixed(c) => play::NumberFormat::Fixed(component_tag(c)), + }) +} + +impl View { + /// What the board's state gives a client. + pub fn of(board: &Scoreboard) -> Self { + let slots = display_slots(); + let display: BTreeMap = board + .display + .iter() + .filter_map(|(slot, o)| Some((slots.iter().position(|s| s == slot)? as i32, o.clone()))) + .collect(); + let tracked: BTreeSet<&String> = display.values().collect(); + let objectives = board + .objectives + .iter() + .filter(|o| tracked.contains(&o.name)) + .map(|o| { + let render = i32::from(o.render_type == RenderType::Hearts); + ( + o.name.clone(), + ( + component_tag(&o.display_name), + render, + format(o.number_format.as_ref()), + ), + ) + }) + .collect(); + let scores = board + .scores + .iter() + .flat_map(|(holder, scores)| { + scores + .iter() + .filter(|(o, _)| tracked.contains(o)) + .map(move |(o, s)| { + ( + (holder.clone(), o.clone()), + ( + s.value, + s.display.as_ref().map(component_tag), + format(s.number_format.as_ref()), + ), + ) + }) + }) + .collect(); + let teams = board + .teams + .iter() + .map(|t| { + let params = TeamParameters { + display_name: component_tag(&t.display_name), + prefix: component_tag(&t.prefix), + suffix: component_tag(&t.suffix), + name_tag_visibility: t.nametag_visibility as i32, + collision_rule: t.collision_rule as i32, + color: t + .color + .as_deref() + .and_then(|c| COLORS.iter().position(|(_, n, _)| *n == c)) + .map(|i| i as i32), + options: i8::from(t.allow_friendly_fire) + | (i8::from(t.see_friendly_invisibles) << 1), + }; + ( + t.name.clone(), + (params, t.players.iter().cloned().collect()), + ) + }) + .collect(); + Self { + objectives, + display, + scores, + teams, + } + } + + /// The packets that take a client from `self` to `next`. + pub fn changes(&self, next: &View) -> Vec { + let mut out = Vec::new(); + let team = |name: &str, method, parameters, players| { + C::SetPlayerTeam(SetPlayerTeam { + name: name.to_owned(), + method, + parameters, + players, + }) + }; + for name in self.teams.keys().filter(|n| !next.teams.contains_key(*n)) { + out.push(team(name, 1, None, Vec::new())); + } + for (name, (params, players)) in &next.teams { + let Some((was, had)) = self.teams.get(name) else { + out.push(team(name, 0, Some(params.clone()), players.clone())); + continue; + }; + if was != params { + out.push(team(name, 2, Some(params.clone()), Vec::new())); + } + let joined: Vec<_> = players + .iter() + .filter(|p| !had.contains(p)) + .cloned() + .collect(); + if !joined.is_empty() { + out.push(team(name, 3, None, joined)); + } + let left: Vec<_> = had + .iter() + .filter(|p| !players.contains(p)) + .cloned() + .collect(); + if !left.is_empty() { + out.push(team(name, 4, None, left)); + } + } + for (name, display) in &next.objectives { + let method = match self.objectives.get(name) { + None => 0, + Some(was) if was != display => 2, + Some(_) => continue, + }; + out.push(C::SetObjective(SetObjective { + name: name.clone(), + method, + display: Some(display.clone()), + })); + } + let slots: BTreeSet = self + .display + .keys() + .chain(next.display.keys()) + .copied() + .collect(); + for slot in slots { + let objective = next.display.get(&slot); + if self.display.get(&slot) != objective { + out.push(C::SetDisplayObjective(SetDisplayObjective { + slot, + objective: objective.cloned().unwrap_or_default(), + })); + } + } + for ((holder, objective), (value, display, number_format)) in &next.scores { + let key = (holder.clone(), objective.clone()); + if self.scores.get(&key) != Some(&(*value, display.clone(), number_format.clone())) { + out.push(C::SetScore(SetScore { + owner: holder.clone(), + objective: objective.clone(), + score: *value, + display: display.clone(), + number_format: number_format.clone(), + })); + } + } + for (holder, objective) in self.scores.keys() { + let key = (holder.clone(), objective.clone()); + if !next.scores.contains_key(&key) && next.objectives.contains_key(objective) { + out.push(C::ResetScore(ResetScore { + owner: holder.clone(), + objective: Some(objective.clone()), + })); + } + } + for name in self + .objectives + .keys() + .filter(|n| !next.objectives.contains_key(*n)) + { + out.push(C::SetObjective(SetObjective { + name: name.clone(), + method: 1, + display: None, + })); + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn methods(packets: &[C]) -> Vec { + packets + .iter() + .map(|p| match p { + C::SetObjective(o) => format!("objective {} {}", o.name, o.method), + C::SetDisplayObjective(d) => format!("display {} {}", d.slot, d.objective), + C::SetScore(s) => format!("score {} {} {}", s.owner, s.objective, s.score), + C::ResetScore(r) => format!("reset {} {:?}", r.owner, r.objective), + C::SetPlayerTeam(t) => format!("team {} {} {:?}", t.name, t.method, t.players), + _ => "other".into(), + }) + .collect() + } + + #[test] + fn a_shown_objective_goes_with_its_scores_and_leaves_when_hidden() { + let mut board = Scoreboard::default(); + board.add_objective( + "audit", + "dummy", + json!("Audit"), + RenderType::Integer, + false, + None, + ); + board.score_mut("Alpha", "audit").value = 7; + let empty = View::default(); + // Not displayed: not tracked, nothing sent. + let hidden = View::of(&board); + assert!(empty.changes(&hidden).is_empty()); + board.set_display_objective("sidebar", Some("audit")); + let shown = View::of(&board); + assert_eq!( + methods(&hidden.changes(&shown)), + [ + "objective audit 0", + "display 1 audit", + "score Alpha audit 7" + ] + ); + board.score_mut("Alpha", "audit").value = 12; + board.score_mut("Beta", "audit").value = 3; + board.reset_one("Beta", "audit"); + let changed = View::of(&board); + assert_eq!(methods(&shown.changes(&changed)), ["score Alpha audit 12"]); + board.reset_one("Alpha", "audit"); + let reset = View::of(&board); + assert_eq!( + methods(&changed.changes(&reset)), + ["reset Alpha Some(\"audit\")"] + ); + board.set_display_objective("sidebar", None); + assert_eq!( + methods(&reset.changes(&View::of(&board))), + ["display 1 ", "objective audit 1"] + ); + } + + #[test] + fn teams_go_to_everyone_with_their_players() { + let mut board = Scoreboard::default(); + board.add_team("red"); + board.add_to_team("Alpha", "red"); + let first = View::of(&board); + assert_eq!( + methods(&View::default().changes(&first)), + ["team red 0 [\"Alpha\"]"] + ); + board.add_to_team("Beta", "red"); + board.remove_from_team("Alpha"); + let second = View::of(&board); + assert_eq!( + methods(&first.changes(&second)), + ["team red 3 [\"Beta\"]", "team red 4 [\"Alpha\"]"] + ); + board.remove_team("red"); + assert_eq!( + methods(&second.changes(&View::of(&board))), + ["team red 1 []"] + ); + } +} diff --git a/crates/horizon-client/src/lang.rs b/crates/horizon-client/src/lang.rs index 9f04ef27a..15f47285a 100644 --- a/crates/horizon-client/src/lang.rs +++ b/crates/horizon-client/src/lang.rs @@ -77,12 +77,6 @@ pub fn apply_deprecated(map: &mut HashMap, json: &[u8]) { } impl Language { - pub fn from_map(code: &str, map: HashMap) -> Self { - Self { - code: code.to_owned(), - map, - } - } /// ClientLanguage.loadFrom: en_us first, then the selected language, each /// from every namespace and every source in priority order (later sources /// override). diff --git a/crates/horizon-client/src/light.rs b/crates/horizon-client/src/light.rs index d7ea7d7fd..6cb4b65b1 100644 --- a/crates/horizon-client/src/light.rs +++ b/crates/horizon-client/src/light.rs @@ -203,7 +203,7 @@ impl LightTables { Ok(tables) } /// Assembled tables (tests and benchmarks): derives the packed light cache. - #[allow(dead_code)] + #[cfg(test)] fn from_parts(cells: Vec, occludes: Vec, faces: usize) -> Self { let mut tables = Self { cells, diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index 1410bf858..aa0d8fb2a 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -239,10 +239,6 @@ pub enum ArmPose { /// Raising a trident to throw it (or to launch with Riptide). ThrowTrident, } -/// HumanoidModel.setupAnim for piglins: `PiglinModel` poses the arms itself. -pub fn humanoid_item(p: &mut Poses, s: &State, _holding: bool) { - humanoid(p, s, &Hum::new(ArmPose::Empty, ArmPose::Empty)); -} /// HumanoidModel.setupAnim with empty hands (endermen). pub fn humanoid_pub(p: &mut Poses, s: &State, _m: &Mob) { humanoid(p, s, &Hum::new(ArmPose::Empty, ArmPose::Empty)); diff --git a/crates/horizon-client/src/mobs/creaking_heart.rs b/crates/horizon-client/src/mobs/creaking_heart.rs index e3c0e4cb7..1172b229c 100644 --- a/crates/horizon-client/src/mobs/creaking_heart.rs +++ b/crates/horizon-client/src/mobs/creaking_heart.rs @@ -152,10 +152,6 @@ pub fn protector(heart: &mut CreakingHeart, host: &impl HeartHost) -> Option bool { - protector(heart, host) == Some(id) -} fn distance_to_creaking(heart: &mut CreakingHeart, pos: [i32; 3], host: &impl HeartHost) -> f64 { protector(heart, host) .and_then(|id| host.mob(id)) diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index c12f9e7ee..7f73e32c4 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -76,9 +76,6 @@ pub struct GoalSelector { locked: [Option; 4], pub disabled: u8, } -fn flag_index(f: u8) -> usize { - f.trailing_zeros() as usize -} impl GoalSelector { pub fn add(&mut self, priority: i32, goal: impl Goal + 'static) { self.goals.push(Wrapped { @@ -174,10 +171,6 @@ impl GoalSelector { } self.locked = [None; 4]; } - #[allow(dead_code)] - fn locked_by(&self, flag: u8) -> Option { - self.locked[flag_index(flag)] - } } // --- random positions (DefaultRandomPos / LandRandomPos / RandomPos) ------- @@ -565,36 +558,6 @@ impl Mob { m.land_up_out_of_solid(w, p) }) } - /// LandRandomPos.getPosTowards - pub fn land_random_pos_towards( - &mut self, - w: &MobWorld, - h: i32, - v: i32, - to: [f64; 3], - ) -> Option<[f64; 3]> { - let (xd, zd) = (to[0] - self.position.x, to[2] - self.position.z); - self.pick_best(w, |m| { - let d = m.random_direction_within( - 0.0, - f64::from(h), - v, - 0, - xd, - zd, - std::f64::consts::FRAC_PI_2, - )?; - let p = m.toward(f64::from(h), d); - if p[1] < crate::chunk::MIN_Y - || p[1] >= 320 - || m.restricted(f64::from(h), p) - || !m.stable_destination(w, p) - { - return None; - } - m.land_up_out_of_solid(w, p) - }) - } pub fn target_info(&self, w: &MobWorld) -> Option { self.ai.target.and_then(|t| w.target_info(t)) } diff --git a/crates/horizon-client/src/mobs/happy_ghast.rs b/crates/horizon-client/src/mobs/happy_ghast.rs index c0ee860dd..6fc07e898 100644 --- a/crates/horizon-client/src/mobs/happy_ghast.rs +++ b/crates/horizon-client/src/mobs/happy_ghast.rs @@ -17,7 +17,6 @@ use horizon_core::{ // Happy ghast state: `head` the harness, `scratch[0]` 1 once set up as a // baby and 2 as an adult, `ai.home` the restriction, `counter` // the end tick of the follow-an-adult range pick. -pub const BABY_SCALE: f64 = 0.2375; /// `Attributes.FLYING_SPEED` and the speed `travel` uses (`* 5 / 3`). pub const FLYING_SPEED: f64 = 0.05; pub const AIR_SPEED: f32 = 0.05 * 5.0 / 3.0; diff --git a/crates/horizon-client/src/mobs/monster_brain.rs b/crates/horizon-client/src/mobs/monster_brain.rs index eeb2c42f2..1099e0bc3 100644 --- a/crates/horizon-client/src/mobs/monster_brain.rs +++ b/crates/horizon-client/src/mobs/monster_brain.rs @@ -250,10 +250,6 @@ pub fn nearest_players(m: &Mob) -> Vec { .and_then(|b| b.mem.nearest_players.value()) .unwrap_or_default() } -/// The damage the brain remembers (`HURT_BY`). -pub fn hurt_by_present(m: &Mob) -> bool { - brain(m).is_some_and(|b| b.mem.hurt_by.present()) -} /// `HURT_BY`'s damage source entity, if a living one. fn hurt_by_entity(m: &Mob, w: &MobWorld) -> Option { let t = brain(m)?.mem.hurt_by.value()?; diff --git a/crates/horizon-client/src/mobs/nautilus.rs b/crates/horizon-client/src/mobs/nautilus.rs index efeb5cc40..2fcf7eb46 100644 --- a/crates/horizon-client/src/mobs/nautilus.rs +++ b/crates/horizon-client/src/mobs/nautilus.rs @@ -76,14 +76,6 @@ pub fn finalize(m: &mut Mob, warm_ocean: bool) { m.extra.variant = u8::from(warm_ocean); } } -/// `checkNautilusSpawnRules`: 5 to 25 blocks below sea level, water below -/// and above. -pub fn spawn_rules_ok(w: &MobWorld, x: i32, y: i32, z: i32) -> bool { - let sea = 63; - (sea - 25..=sea - 5).contains(&y) - && w.fluid(x, y - 1, z) == Fluid::Water - && w.block_name(x, y + 1, z) == "minecraft:water" -} /// `getControllingPassenger`: a player on a saddled nautilus. pub fn controlled(m: &Mob) -> bool { m.rider.is_some() && m.extra.saddled diff --git a/crates/horizon-client/src/mobs/nav.rs b/crates/horizon-client/src/mobs/nav.rs index 24dafa48d..793303c6d 100644 --- a/crates/horizon-client/src/mobs/nav.rs +++ b/crates/horizon-client/src/mobs/nav.rs @@ -582,26 +582,4 @@ impl Mob { NavKind::Amphibious => !w.facts.is_air(w.world.block(p[0], p[1] - 1, p[2])), } } - pub fn should_recompute_path(&self, p: [i32; 3]) -> bool { - if self.ai.nav.delayed_recompute { - return false; - } - let Some(path) = &self.ai.nav.path else { - return false; - }; - if path.is_done() || path.nodes.is_empty() { - return false; - } - let Some(end) = path.end() else { return false }; - let mid = [ - (f64::from(end.x) + self.position.x) / 2.0, - (f64::from(end.y) + self.position.y) / 2.0, - (f64::from(end.z) + self.position.z) / 2.0, - ]; - let d = (f64::from(p[0]) + 0.5 - mid[0]).powi(2) - + (f64::from(p[1]) + 0.5 - mid[1]).powi(2) - + (f64::from(p[2]) + 0.5 - mid[2]).powi(2); - let r = (path.nodes.len() - path.next) as f64; - d < r * r - } } diff --git a/crates/horizon-client/src/mobs/spawn_selection.rs b/crates/horizon-client/src/mobs/spawn_selection.rs index 046583a1f..4e51722f1 100644 --- a/crates/horizon-client/src/mobs/spawn_selection.rs +++ b/crates/horizon-client/src/mobs/spawn_selection.rs @@ -769,19 +769,6 @@ pub fn weighted_pick(list: &[SpawnEntry], random: &mut impl RandomSource) -> Opt None } -/// `NaturalSpawner.getRandomSpawnMobAt`. -pub fn random_spawn_mob_at( - list: &[SpawnEntry], - category: &str, - reduced_water_ambient: bool, - random: &mut impl RandomSource, -) -> Option { - if category == "water_ambient" && reduced_water_ambient && random.next_float() < 0.98 { - return None; - } - weighted_pick(list, random) -} - /// `SpawnerData.count().sample(random)`: a constant draws nothing. pub fn sample_count(entry: &SpawnEntry, random: &mut impl RandomSource) -> u32 { if entry.constant { diff --git a/crates/horizon-client/src/mobs/spawning.rs b/crates/horizon-client/src/mobs/spawning.rs index 0bfd5d223..93e3fe119 100644 --- a/crates/horizon-client/src/mobs/spawning.rs +++ b/crates/horizon-client/src/mobs/spawning.rs @@ -30,25 +30,6 @@ pub struct BiomeFacts { pub fn placement_ok(species: Species, w: &MobWorld, x: i32, y: i32, z: i32) -> bool { super::spawn_rules::is_spawn_position_ok(species, w, x, y, z) } -/// `SpawnPlacements.checkSpawnRules` for a natural spawn. -pub fn spawn_rules_ok( - species: Species, - w: &MobWorld, - random: &mut impl RandomSource, - x: i32, - y: i32, - z: i32, -) -> bool { - super::spawn_rules::check_spawn_rules( - species, - w, - super::spawn_rules::Reason::Natural, - random, - x, - y, - z, - ) -} /// Mob.finalizeSpawn for natural, chunk-generation and summoned mobs. /// `DifficultyInstance`: the local difficulty at a position. #[derive(Clone, Copy, Debug)] diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index e02cfa176..194bd75ff 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -10,7 +10,7 @@ //! other `GateBehavior`s shuffle with a random of their own, seeded with //! `Brain::shuffle_seed` when the brain is built. use super::{ - Mob, MobEvent, MobWorld, Seen, Species, Who, + Mob, MobEvent, MobWorld, Species, Who, path::{Path, PathNode}, }; use horizon_core::{ @@ -4156,10 +4156,6 @@ pub fn woken(m: &mut Mob, now: i64) { pub fn potential_job_site(m: &Mob) -> Option<[i32; 3]> { mem_ref(m).and_then(|mm| mm.potential_job_site.value()) } -/// Whether a seen mob is a villager wanting to breed (`AgeableMob::canBreed`). -pub fn seen_can_breed(s: &Seen) -> bool { - s.species == Species::Villager && s.in_love -} /// The memories other villagers read: the interaction target, the path's /// nodes (while it is not done), whether a golem was seen lately and the /// last sleep. diff --git a/crates/horizon-client/src/mobs/world.rs b/crates/horizon-client/src/mobs/world.rs index 79bbaa30c..7836a49ef 100644 --- a/crates/horizon-client/src/mobs/world.rs +++ b/crates/horizon-client/src/mobs/world.rs @@ -1,7 +1,7 @@ //! What mobs read from the level: block solidity, ray clipping for line of //! sight (`ClipContext.Block.COLLIDER`), sky visibility, light-dependent //! values and the positions of other entities. -use super::{MobWorld, Seen, Species, Who, data}; +use super::{MobWorld, Seen, Who, data}; use crate::{ blocks::{BlockFacts, Fluid}, collisions::SceneCollisions, @@ -269,12 +269,6 @@ impl MobWorld<'_> { }); v.into_iter() } - pub fn count_species(&self, species: Species) -> usize { - self.others - .iter() - .filter(|s| s.species == species && s.alive) - .count() - } } /// Level.clip with VISUAL shapes and no fluids: the block the segment first diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index b5060bf04..9edbb4f2a 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -307,6 +307,9 @@ pub struct PlayerMotion { pub hurt_log: Vec, /// The last melee attacks made on mobs, newest last. pub attack_log: Vec, + /// The level's world border, whose walls stop the player's movement + /// from inside (the game keeps it current; None: no border). + pub border: Option, } fn attribute_error(error: impl std::fmt::Debug) -> io::Error { io::Error::other(format!("movement attribute: {error:?}")) @@ -461,6 +464,7 @@ impl PlayerMotion { powder_snow_entered: Vec::new(), hurt_log: Vec::new(), attack_log: Vec::new(), + border: None, }) } /// `Entity.getTicksRequiredToFreeze`. @@ -678,9 +682,11 @@ impl MotionWorld<'_, '_, '_> { fn movement_collisions( &self, ) -> crate::collisions::EntityCollisions<'_, SceneCollisions<'_, '_>> { + let at = [self.player.position.x, self.player.position.z]; crate::collisions::EntityCollisions { blocks: self.collisions(), entities: self.entities, + border: self.player.border.as_ref().map(|b| (b, at)), } } /// `Level.noCollision(player, bounds)`: blocks and the host's entity boxes. diff --git a/crates/horizon-client/src/packs.rs b/crates/horizon-client/src/packs.rs index 7bd4fd782..5daaaacad 100644 --- a/crates/horizon-client/src/packs.rs +++ b/crates/horizon-client/src/packs.rs @@ -804,11 +804,6 @@ impl SelectionModel { false } } - /// Whether activating the entry asks first (`handlePackSelection`'s - /// ConfirmScreen for an incompatible pack). - pub fn needs_confirmation(&self, selected: bool, i: usize) -> bool { - self.can_select(selected, i) && !self.unselected[i].compatible - } /// `moveUp` / `moveDown` when allowed. pub fn move_by(&mut self, selected: bool, i: usize, up: bool) -> bool { let ok = if up { diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index 55a7a5120..a5df97258 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -1158,6 +1158,8 @@ pub struct ParticleEngine { starters: Vec, /// Local sounds requested by particles (dripstone drips): (event, position, volume, pitch). pub sounds: Vec<(&'static str, [f64; 3], f32, f32)>, + /// How many of each type were made, for `horizon-ctl status`. + made: std::collections::BTreeMap<&'static str, u64>, /// The item particles' sprites (`BreakingItemParticle`'s slime ball, snowball /// and cobweb models, resolved for the ground), one per model layer. pub item_sprites: HashMap>, @@ -1183,6 +1185,7 @@ impl ParticleEngine { starters: Vec::new(), camera: [0.0; 3], sounds: Vec::new(), + made: Default::default(), item_sprites: HashMap::new(), }; let dir = root.join("assets/minecraft/particles"); @@ -1449,9 +1452,14 @@ impl ParticleEngine { pub fn create(&mut self, options: &ParticleOptions, p: [f64; 3], v: [f64; 3]) { let seed = self.seeds.next_long(); if let Some(particle) = self.make(options, p, v, seed) { + *self.made.entry(options.ty.name()).or_default() += 1; self.pending.push(particle); } } + /// How many particles of each type were made so far. + pub fn made(&self) -> &std::collections::BTreeMap<&'static str, u64> { + &self.made + } /// Parity probes: seed the provider (`ParticleEngine.random`), level and /// `SpellParticle.RANDOM` generators. pub fn seed_randoms(&mut self, provider: i64, level: i64, spell: i64) { diff --git a/crates/horizon-client/src/recipe_book.rs b/crates/horizon-client/src/recipe_book.rs index 27051bbc6..fa247a695 100644 --- a/crates/horizon-client/src/recipe_book.rs +++ b/crates/horizon-client/src/recipe_book.rs @@ -384,21 +384,6 @@ impl Book { order, } } - /// Which book a recipe id belongs to. - pub fn book_of(&self, id: &str) -> Option { - let e = self.entries.iter().find(|e| e.id == id)?; - Some(match e.category { - Category::CraftingBuilding - | Category::CraftingRedstone - | Category::CraftingEquipment - | Category::CraftingMisc => BookType::Crafting, - Category::FurnaceFood | Category::FurnaceBlocks | Category::FurnaceMisc => { - BookType::Furnace - } - Category::BlastBlocks | Category::BlastMisc => BookType::BlastFurnace, - Category::SmokerFood => BookType::Smoker, - }) - } /// `RecipeDisplayEntry.canCraft`: the recipe's placement ingredients /// (`craftingRequirements`) can all be found in `stock`. pub fn can_craft(&self, entry: &Entry, stock: &crate::menu::place::Stacked) -> bool { diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index dd86c8f9c..7819a9b0b 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -750,12 +750,6 @@ fn heightmaps(chunk: &Chunk, tables: &SaveTables) -> Tag { ) })) } -/// The heightmaps a ClientboundLevelChunkPacketData carries (the types with -/// sendToClient: WORLD_SURFACE, MOTION_BLOCKING, MOTION_BLOCKING_NO_LEAVES), -/// as (network id, packed longs) in Heightmap.Types order. -pub fn client_heightmaps(chunk: &Chunk, tables: &SaveTables) -> Vec<(i32, Vec)> { - client_heightmaps_in(&chunk.sections, tables, MIN_Y, SECTIONS as i32 * 16) -} /// The client heightmaps of a column's sections, in a level from `min_y`, /// `height` blocks high. pub fn client_heightmaps_in( diff --git a/crates/horizon-client/src/sculk.rs b/crates/horizon-client/src/sculk.rs index 58ac921ff..3affbda77 100644 --- a/crates/horizon-client/src/sculk.rs +++ b/crates/horizon-client/src/sculk.rs @@ -78,7 +78,6 @@ pub const RESONANCE: [&str; 15] = [ ]; pub const SHRIEK: &str = "minecraft:shriek"; pub const TENDRILS_CLICKING: &str = "minecraft:sculk_sensor_tendrils_clicking"; -pub const NO_VIBRATION_FREQUENCY: i32 = 0; /// `VibrationSystem.getGameEventFrequency`. pub fn frequency(event: &str) -> i32 { @@ -567,10 +566,6 @@ pub struct WardenSpawnTracker { } impl WardenSpawnTracker { pub const MAX_WARNING_LEVEL: i32 = 4; - /// Blocks around a shrieker within which players are warned. - pub const PLAYER_SEARCH_RADIUS: f64 = 16.0; - /// `AABB.ofSize(centre, 48, 48, 48)` for an existing warden. - pub const WARNING_CHECK_DIAMETER: f64 = 48.0; const DECREASE_EVERY: i32 = 12000; const INCREASE_COOLDOWN: i32 = 200; pub fn tick(&mut self) { diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 1fadacf57..97acc91c9 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -81,10 +81,6 @@ pub fn sound_source(event: &str) -> usize { index("master") } } -/// Volume multiplier of an event's source (master applied separately). -pub fn event_volume(event: &str) -> f32 { - source_volume(sound_source(event)) -} /// Volume multiplier of a sound source by index. pub fn source_volume(i: usize) -> f32 { if i == 0 { diff --git a/crates/horizon-client/src/tab_list.rs b/crates/horizon-client/src/tab_list.rs index 2c03f999f..0374e3fc2 100644 --- a/crates/horizon-client/src/tab_list.rs +++ b/crates/horizon-client/src/tab_list.rs @@ -317,9 +317,6 @@ impl TabList { self.visible = visible; } } - pub fn is_visible(&self) -> bool { - self.visible - } /// `reset`. pub fn reset(&mut self) { self.header = None; diff --git a/crates/horizon-client/src/text.rs b/crates/horizon-client/src/text.rs index 9f39155d1..11abb3328 100644 --- a/crates/horizon-client/src/text.rs +++ b/crates/horizon-client/src/text.rs @@ -455,9 +455,6 @@ impl Text { } out } - pub fn char_count(&self) -> usize { - self.spans.iter().map(|s| s.text.chars().count()).sum() - } } /// The style fields of a component's JSON. diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index b4958c600..f77ac93eb 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -1630,26 +1630,6 @@ fn caret_field<'a>( _ => None, } } -/// `yyyy/MM/dd HH:mm` (UTC) for a modification time in Unix seconds. -pub fn date_label(secs: u64) -> String { - date_string(secs) -} -fn date_string(secs: u64) -> String { - // Civil date from Unix time (days-from-civil inverse), UTC. - let days = (secs / 86400) as i64; - let (h, m) = ((secs % 86400) / 3600, (secs % 3600) / 60); - let z = days + 719_468; - let era = z.div_euclid(146_097); - let doe = z - era * 146_097; - let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; - let y = yoe + era * 400; - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let d = doy - (153 * mp + 2) / 5 + 1; - let mo = if mp < 10 { mp + 3 } else { mp - 9 }; - let y = if mo <= 2 { y + 1 } else { y }; - format!("{y}-{mo:02}-{d:02} {h:02}:{m:02}") -} #[cfg(test)] mod classic_tests { diff --git a/crates/horizon-client/src/ui.rs b/crates/horizon-client/src/ui.rs index b1ffab866..1c6e93067 100644 --- a/crates/horizon-client/src/ui.rs +++ b/crates/horizon-client/src/ui.rs @@ -7,9 +7,40 @@ use crate::{ }; use std::{collections::HashMap, path::Path, sync::RwLock, time::Instant}; -/// Nine-slice borders (left, top, right, bottom) from `.png.mcmeta` files. -static NINE_SLICE: RwLock>> = RwLock::new(None); +/// `GuiSpriteScaling.NineSlice`: the sprite's size in GUI pixels, whatever +/// its texture's resolution, its borders (left, top, right, bottom) in the +/// same units, and whether the edges and centre stretch rather than tile. +#[derive(Clone, Copy, Debug, PartialEq)] +struct NineSlice { + width: u32, + height: u32, + border: [u32; 4], + stretch_inner: bool, +} +/// Nine-slice scaling from `.png.mcmeta` files. +static NINE_SLICE: RwLock>> = RwLock::new(None); +/// A `gui.scaling` section of type `nine_slice`. +fn parse_nine_slice(v: &serde_json::Value) -> Option { + let s = &v["gui"]["scaling"]; + if s["type"] != "nine_slice" { + return None; + } + let size = |k: &str| s[k].as_u64().map(|n| n as u32); + let border = &s["border"]; + let border = if let Some(n) = border.as_u64() { + [n as u32; 4] + } else { + let g = |k: &str| border[k].as_u64().unwrap_or(0) as u32; + [g("left"), g("top"), g("right"), g("bottom")] + }; + Some(NineSlice { + width: size("width")?, + height: size("height")?, + border, + stretch_inner: s["stretch_inner"].as_bool().unwrap_or(false), + }) +} /// Read `gui.scaling` metadata for every GUI sprite under `root`. pub fn load_metadata(root: &Path) { let mut map = HashMap::new(); @@ -32,47 +63,48 @@ pub fn load_metadata(root: &Path) { let Ok(text) = std::fs::read_to_string(&p) else { continue; }; - let Ok(v) = serde_json::from_str::(&text) else { + let Some(nine_slice) = serde_json::from_str(&text) + .ok() + .as_ref() + .and_then(parse_nine_slice) + else { continue; }; - let s = &v["gui"]["scaling"]; - if s["type"] != "nine_slice" { - continue; - } - let border = &s["border"]; - let b = if let Some(n) = border.as_u64() { - [n as u32; 4] - } else { - let g = |k: &str| border[k].as_u64().unwrap_or(0) as u32; - [g("left"), g("top"), g("right"), g("bottom")] - }; let key = Path::new(stripped) .strip_prefix(&base) .map(|r| r.to_string_lossy().replace('\\', "/")) .unwrap_or_default(); - map.insert(key, b); + map.insert(key, nine_slice); } } *NINE_SLICE.write().unwrap_or_else(|e| e.into_inner()) = Some(map); } -fn border(sprite: &str) -> [u32; 4] { +/// The sprite's nine-slice metadata; without any (no resources loaded), its +/// GUI size and the widgets' usual borders. +fn scaling(sprite: &str, r: &Rect) -> NineSlice { NINE_SLICE .read() .unwrap_or_else(|e| e.into_inner()) .as_ref() .and_then(|m| m.get(sprite).copied()) - .unwrap_or(match sprite { - "gui/sprites/widget/button" - | "gui/sprites/widget/button_highlighted" - | "gui/sprites/widget/button_disabled" => [3; 4], - "gui/sprites/widget/slider_handle" | "gui/sprites/widget/slider_handle_highlighted" => { - [2, 2, 2, 3] - } - _ => [1; 4], + .unwrap_or(NineSlice { + width: r.w, + height: r.h, + border: match sprite { + "gui/sprites/widget/button" + | "gui/sprites/widget/button_highlighted" + | "gui/sprites/widget/button_disabled" => [3; 4], + "gui/sprites/widget/slider_handle" + | "gui/sprites/widget/slider_handle_highlighted" => [2, 2, 2, 3], + _ => [1; 4], + }, + stretch_inner: false, }) } -fn sub(r: Rect, x: f32, y: f32, w: f32, h: f32) -> Rect { - let (du, dv) = ((r.u1 - r.u0) / r.w as f32, (r.v1 - r.v0) / r.h as f32); +/// The region `[x, y, w, h]` of a sprite `size` GUI pixels large, in its +/// own units (`TextureAtlasSprite.getU(x / width)`). +fn sub(r: Rect, size: [f32; 2], [x, y, w, h]: [f32; 4]) -> Rect { + let (du, dv) = ((r.u1 - r.u0) / size[0], (r.v1 - r.v0) / size[1]); Rect { u0: r.u0 + x * du, v0: r.v0 + y * dv, @@ -82,8 +114,9 @@ fn sub(r: Rect, x: f32, y: f32, w: f32, h: f32) -> Rect { h: h as u32, } } -/// Tile `src` (a sub-rectangle of a sprite, in its pixels) over a target area. -fn tile(batch: &mut HudBatch, r: Rect, src: [f32; 4], dst: [f32; 4], color: u32) { +/// `blitTiledSprite`: `src` (a region of a sprite `size` large, in its +/// units) repeated over `dst` from its top left, the last row and column cut. +fn tile(batch: &mut HudBatch, r: Rect, size: [f32; 2], src: [f32; 4], dst: [f32; 4], color: u32) { let [sx, sy, sw, sh] = src; let [dx, dy, dw, dh] = dst; if sw <= 0.0 || sh <= 0.0 || dw <= 0.0 || dh <= 0.0 { @@ -95,13 +128,16 @@ fn tile(batch: &mut HudBatch, r: Rect, src: [f32; 4], dst: [f32; 4], color: u32) let mut x = 0.0; while x < dw { let w = sw.min(dw - x); - batch.rect_uv(dx + x, dy + y, w, h, sub(r, sx, sy, w, h), color); + batch.rect_uv(dx + x, dy + y, w, h, sub(r, size, [sx, sy, w, h]), color); x += sw; } y += sh; } } -/// GuiGraphics.blitSprite with nine-slice scaling (inner parts tiled). +/// `GuiGraphicsExtractor.blitNineSlicedSprite`: the corners at their size, +/// the edges and centre tiled (or stretched with `stretch_inner`), all in +/// the sprite's `gui.scaling` units, so a high-resolution pack's sprite draws +/// as the default one does. pub fn nine_slice( batch: &mut HudBatch, atlas: &HudAtlas, @@ -112,47 +148,73 @@ pub fn nine_slice( h: f32, color: u32, ) { - let Some(r) = atlas.sprites.get(sprite).copied() else { - return; + if let Some(r) = atlas.sprites.get(sprite) { + draw_nine_slice(batch, *r, scaling(sprite, r), [x, y, w, h], color); + } +} +fn draw_nine_slice( + batch: &mut HudBatch, + r: Rect, + n: NineSlice, + [x, y, w, h]: [f32; 4], + color: u32, +) { + let size = [n.width as f32, n.height as f32]; + let [sw, sh] = size; + let [l, t, rr, b] = n.border.map(|v| v as f32); + let (half_w, half_h) = ((w / 2.0).floor(), (h / 2.0).floor()); + let (l, rr, t, b) = (l.min(half_w), rr.min(half_w), t.min(half_h), b.min(half_h)); + // blitSprite(sprite, width, height, textureX, textureY, x, y, w, h). + let part = |batch: &mut HudBatch, tx: f32, ty: f32, dst: [f32; 4]| { + if dst[2] != 0.0 && dst[3] != 0.0 { + batch.rect_uv( + dst[0], + dst[1], + dst[2], + dst[3], + sub(r, size, [tx, ty, dst[2], dst[3]]), + color, + ); + } }; - let [l, t, rr, b] = border(sprite).map(|v| v as f32); - let (sw, sh) = (r.w as f32, r.h as f32); - let l = l.min(w / 2.0); - let rr = rr.min(w / 2.0); - let t = t.min(h / 2.0); - let b = b.min(h / 2.0); - let (cw, ch) = (w - l - rr, h - t - b); - let (scw, sch) = (sw - l - rr, sh - t - b); - // Corners. - batch.rect_uv(x, y, l, t, sub(r, 0.0, 0.0, l, t), color); - batch.rect_uv(x + w - rr, y, rr, t, sub(r, sw - rr, 0.0, rr, t), color); - batch.rect_uv(x, y + h - b, l, b, sub(r, 0.0, sh - b, l, b), color); - batch.rect_uv( - x + w - rr, - y + h - b, - rr, - b, - sub(r, sw - rr, sh - b, rr, b), - color, - ); - // Edges and centre. - tile(batch, r, [l, 0.0, scw, t], [x + l, y, cw, t], color); - tile( - batch, - r, - [l, sh - b, scw, b], - [x + l, y + h - b, cw, b], - color, - ); - tile(batch, r, [0.0, t, l, sch], [x, y + t, l, ch], color); - tile( - batch, - r, - [sw - rr, t, rr, sch], - [x + w - rr, y + t, rr, ch], - color, - ); - tile(batch, r, [l, t, scw, sch], [x + l, y + t, cw, ch], color); + // blitNineSliceInnerSegment. + let inner = |batch: &mut HudBatch, dst: [f32; 4], src: [f32; 4]| { + if dst[2] <= 0.0 || dst[3] <= 0.0 { + return; + } + if n.stretch_inner { + batch.rect_uv(dst[0], dst[1], dst[2], dst[3], sub(r, size, src), color); + } else { + tile(batch, r, size, src, dst, color); + } + }; + if w == sw && h == sh { + part(batch, 0.0, 0.0, [x, y, w, h]); + return; + } + if h == sh { + part(batch, 0.0, 0.0, [x, y, l, h]); + inner(batch, [x + l, y, w - rr - l, h], [l, 0.0, sw - rr - l, sh]); + part(batch, sw - rr, 0.0, [x + w - rr, y, rr, h]); + return; + } + if w == sw { + part(batch, 0.0, 0.0, [x, y, w, t]); + inner(batch, [x, y + t, w, h - b - t], [0.0, t, sw, sh - b - t]); + part(batch, 0.0, sh - b, [x, y + h - b, w, b]); + return; + } + let (cw, ch) = (w - rr - l, h - b - t); + let (scw, sch) = (sw - rr - l, sh - b - t); + part(batch, 0.0, 0.0, [x, y, l, t]); + inner(batch, [x + l, y, cw, t], [l, 0.0, scw, t]); + part(batch, sw - rr, 0.0, [x + w - rr, y, rr, t]); + part(batch, 0.0, sh - b, [x, y + h - b, l, b]); + inner(batch, [x + l, y + h - b, cw, b], [l, sh - b, scw, b]); + part(batch, sw - rr, sh - b, [x + w - rr, y + h - b, rr, b]); + inner(batch, [x, y + t, l, ch], [0.0, t, l, sch]); + inner(batch, [x + l, y + t, cw, ch], [l, t, scw, sch]); + inner(batch, [x + w - rr, y + t, rr, ch], [sw - rr, t, rr, sch]); } /// Repeat a whole texture with each copy drawn `size` GUI pixels square. pub fn tiled( @@ -169,7 +231,6 @@ pub fn tiled( let Some(r) = atlas.sprites.get(sprite).copied() else { return; }; - let scale = r.w as f32 / size; let mut yy = 0.0; while yy < h { let th = size.min(h - yy); @@ -181,7 +242,7 @@ pub fn tiled( y + yy, tw, th, - sub(r, 0.0, 0.0, tw * scale, th * scale), + sub(r, [size, size], [0.0, 0.0, tw, th]), color, ); xx += size; @@ -793,10 +854,6 @@ impl EditBox { text_color: rgba(224, 224, 224, 255), } } - /// When the field gained focus, for the cursor's blink. - pub fn focused_since(&mut self, at: Instant) { - self.focused_at = at; - } pub fn inner_width(&self) -> f32 { if self.bordered { self.width - 8.0 @@ -1128,6 +1185,130 @@ impl EditBox { #[cfg(test)] mod tests { use super::*; + + /// The quads' destination rectangles and their UVs. + fn quads(batch: &HudBatch) -> Vec<([f32; 4], [f32; 4])> { + batch + .vertices + .chunks(6) + .map(|q| { + let (a, c) = (q[0], q[2]); + ( + [a.pos[0], a.pos[1], c.pos[0], c.pos[1]], + [a.uv[0], a.uv[1], c.uv[0], c.uv[1]], + ) + }) + .collect() + } + /// Destination and UV rectangles equal to within f32 rounding. + fn assert_quad(actual: ([f32; 4], [f32; 4]), expected: ([f32; 4], [f32; 4])) { + let close = |a: [f32; 4], b: [f32; 4]| a.iter().zip(b).all(|(a, b)| (a - b).abs() < 1e-5); + assert!( + close(actual.0, expected.0) && close(actual.1, expected.1), + "{actual:?} != {expected:?}" + ); + } + /// A sprite filling the atlas, `w x h` texels as a 32x pack draws it. + fn sprite(w: u32, h: u32) -> Rect { + Rect { + u0: 0.0, + v0: 0.0, + u1: 1.0, + v1: 1.0, + w, + h, + } + } + fn faithful(json: &str) -> NineSlice { + parse_nine_slice(&serde_json::from_str(json).unwrap()).unwrap() + } + #[test] + fn a_high_resolution_button_slices_in_its_gui_units() { + // Faithful 32x's widget/button: 400x40 texels, gui.scaling 200x20. + let n = faithful( + r#"{"gui":{"scaling":{"type":"nine_slice","width":200,"height":20, + "border":{"left":20,"top":4,"right":20,"bottom":4}}}}"#, + ); + let mut batch = HudBatch::new([640, 480]); + draw_nine_slice( + &mut batch, + sprite(400, 40), + n, + [10.0, 5.0, 150.0, 20.0], + u32::MAX, + ); + let q = quads(&batch); + // Full height: left border, the centre tiled, right border + // (blitNineSlicedSprite's height == nineSlice.height case). + assert_quad(q[0], ([10.0, 5.0, 30.0, 25.0], [0.0, 0.0, 0.1, 1.0])); + assert_quad(q[1], ([30.0, 5.0, 140.0, 25.0], [0.1, 0.0, 0.65, 1.0])); + assert_quad(q[2], ([140.0, 5.0, 160.0, 25.0], [0.9, 0.0, 1.0, 1.0])); + assert_eq!(q.len(), 3); + } + #[test] + fn nine_slice_corners_and_a_stretched_centre() { + // Faithful 32x's tooltip/frame: 200x200 texels, 100x100, border 12, stretched. + let n = faithful( + r#"{"gui":{"scaling":{"type":"nine_slice","width":100,"height":100,"border":12,"stretch_inner":true}}}"#, + ); + let mut batch = HudBatch::new([640, 480]); + draw_nine_slice( + &mut batch, + sprite(200, 200), + n, + [0.0, 0.0, 300.0, 40.0], + u32::MAX, + ); + let q = quads(&batch); + assert_eq!(q.len(), 9); + // Top left corner: 12 GUI pixels, 12/100 of the sprite. + assert_quad(q[0], ([0.0, 0.0, 12.0, 12.0], [0.0, 0.0, 0.12, 0.12])); + // The centre is one stretched quad (blitNineSliceInnerSegment, stretch_inner). + assert_quad(q[7], ([12.0, 12.0, 288.0, 28.0], [0.12, 0.12, 0.88, 0.88])); + // Bottom right corner. + assert_quad(q[5], ([288.0, 28.0, 300.0, 40.0], [0.88, 0.88, 1.0, 1.0])); + } + #[test] + fn a_sprite_drawn_at_its_own_size_is_one_quad() { + let n = NineSlice { + width: 50, + height: 50, + border: [10; 4], + stretch_inner: false, + }; + let mut batch = HudBatch::new([640, 480]); + draw_nine_slice( + &mut batch, + sprite(100, 100), + n, + [4.0, 4.0, 50.0, 50.0], + u32::MAX, + ); + let q = quads(&batch); + assert_eq!(q.len(), 1); + assert_quad(q[0], ([4.0, 4.0, 54.0, 54.0], [0.0, 0.0, 1.0, 1.0])); + } + #[test] + fn borders_shrink_to_half_the_drawn_size() { + let n = NineSlice { + width: 20, + height: 20, + border: [8; 4], + stretch_inner: true, + }; + let mut batch = HudBatch::new([640, 480]); + // 9 wide: borders of floor(9 / 2) = 4, as vanilla's integer division. + draw_nine_slice( + &mut batch, + sprite(20, 20), + n, + [0.0, 0.0, 9.0, 30.0], + u32::MAX, + ); + let q = quads(&batch); + assert_quad(q[0], ([0.0, 0.0, 4.0, 8.0], [0.0, 0.0, 0.2, 0.4])); + assert_quad(q[2], ([5.0, 0.0, 9.0, 8.0], [0.8, 0.0, 1.0, 0.4])); + } #[test] fn append_fields_highlight_the_whole_value_and_blink_their_cursor() { use crate::hud::Blend; diff --git a/crates/horizon-client/src/worldborder.rs b/crates/horizon-client/src/worldborder.rs index 3ed4ea152..fa2380d74 100644 --- a/crates/horizon-client/src/worldborder.rs +++ b/crates/horizon-client/src/worldborder.rs @@ -7,7 +7,6 @@ pub use horizon_core::geometry::border::BorderStatus; /// `WorldBorder.MAX_SIZE` (the float 5.999997E7 as a double). pub const MAX_SIZE: f64 = 59_999_968.0; -pub const MAX_CENTER: f64 = 2.999_998_4e7; /// `BorderStatus.getColor`: the wall colour. pub fn status_color(status: BorderStatus) -> u32 { @@ -81,6 +80,10 @@ impl PartialEq for WorldBorder { } } impl WorldBorder { + /// Its extent, for collisions. + pub fn geometry(&self) -> &BorderGeometry { + &self.geometry + } pub fn center(&self) -> [f64; 2] { self.geometry.center() } diff --git a/crates/horizon-client/src/zip.rs b/crates/horizon-client/src/zip.rs index a0551c829..22cab132d 100644 --- a/crates/horizon-client/src/zip.rs +++ b/crates/horizon-client/src/zip.rs @@ -1,75 +1,35 @@ -//! Minimal read-only ZIP archive support (stored and deflated entries), used -//! for resource packs and the unifont glyph archive. -use std::{collections::BTreeMap, fs, io, path::Path}; +//! Read-only ZIP archives held in memory (resource packs, data packs and the +//! unifont glyph archive), on the `zip` crate. Like Java's `ZipFile` (what +//! vanilla's `FilePackResources` reads with), entries aren't CRC-checked. +use std::{ + collections::BTreeMap, + fs, + io::{self, Cursor, Read}, + path::Path, + sync::Arc, +}; +use zip::{CompressionMethod, ZipArchive}; -/// One archive held in memory with its central directory indexed by name. +/// One archive with its entries indexed by name (`\` read as `/`, folders +/// left out). pub struct Zip { - data: Vec, - entries: BTreeMap, + archive: ZipArchive>>, + entries: BTreeMap, } -#[derive(Clone, Copy)] -struct Entry { - method: u16, - compressed: usize, - size: usize, - header: usize, -} -fn invalid(message: &str) -> io::Error { - io::Error::new(io::ErrorKind::InvalidData, message) -} -fn u16_at(d: &[u8], at: usize) -> io::Result { - d.get(at..at + 2) - .map(|b| u16::from_le_bytes([b[0], b[1]])) - .ok_or_else(|| invalid("truncated zip")) -} -fn u32_at(d: &[u8], at: usize) -> io::Result { - d.get(at..at + 4) - .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])) - .ok_or_else(|| invalid("truncated zip")) +fn invalid(e: impl std::fmt::Display) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, e.to_string()) } impl Zip { pub fn open(path: &Path) -> io::Result { Self::from_bytes(fs::read(path)?) } pub fn from_bytes(data: Vec) -> io::Result { - // End of central directory: the last "PK\x05\x06" within 64 KiB of the end. - let min = data.len().saturating_sub(22 + 65_535); - let eocd = (min..=data.len().saturating_sub(22)) - .rev() - .find(|&i| data[i..i + 4] == [0x50, 0x4b, 0x05, 0x06]) - .ok_or_else(|| invalid("not a zip archive"))?; - let count = usize::from(u16_at(&data, eocd + 10)?); - let mut at = u32_at(&data, eocd + 16)? as usize; - let mut entries = BTreeMap::new(); - for _ in 0..count { - if u32_at(&data, at)? != 0x0201_4b50 { - return Err(invalid("bad central directory entry")); - } - let method = u16_at(&data, at + 10)?; - let compressed = u32_at(&data, at + 20)? as usize; - let size = u32_at(&data, at + 24)? as usize; - let name_len = usize::from(u16_at(&data, at + 28)?); - let extra_len = usize::from(u16_at(&data, at + 30)?); - let comment_len = usize::from(u16_at(&data, at + 32)?); - let header = u32_at(&data, at + 42)? as usize; - let name = data - .get(at + 46..at + 46 + name_len) - .ok_or_else(|| invalid("truncated zip name"))?; - let name = String::from_utf8_lossy(name).replace('\\', "/"); - if !name.ends_with('/') { - entries.insert( - name, - Entry { - method, - compressed, - size, - header, - }, - ); - } - at += 46 + name_len + extra_len + comment_len; - } - Ok(Self { data, entries }) + let archive = ZipArchive::new(Cursor::new(Arc::from(data))).map_err(invalid)?; + let entries = (0..archive.len()) + .filter_map(|i| Some((archive.name_for_index(i)?.replace('\\', "/"), i))) + .filter(|(name, _)| !name.ends_with('/')) + .collect(); + Ok(Self { archive, entries }) } pub fn names(&self) -> impl Iterator { self.entries.keys().map(String::as_str) @@ -78,30 +38,21 @@ impl Zip { self.entries.contains_key(name) } pub fn read(&self, name: &str) -> io::Result> { - let e = *self + let &index = self .entries .get(name) .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, name.to_owned()))?; - if u32_at(&self.data, e.header)? != 0x0403_4b50 { - return Err(invalid("bad local file header")); - } - let start = e.header - + 30 - + usize::from(u16_at(&self.data, e.header + 26)?) - + usize::from(u16_at(&self.data, e.header + 28)?); - let raw = self - .data - .get(start..start + e.compressed) - .ok_or_else(|| invalid("truncated zip entry"))?; - match e.method { - 0 => Ok(raw.to_vec()), - 8 => { - let out = miniz_oxide::inflate::decompress_to_vec_with_limit( - raw, - e.size.max(1) * 2 + 1024, - ) - .map_err(|_| invalid("corrupt deflate stream"))?; - Ok(out) + // A clone shares the bytes and the central directory: reading needs `&mut`. + let mut archive = self.archive.clone(); + let mut entry = archive.by_index_raw(index).map_err(invalid)?; + let (method, size) = (entry.compression(), entry.size() as usize); + let mut raw = Vec::with_capacity(entry.compressed_size() as usize); + entry.read_to_end(&mut raw)?; + match method { + CompressionMethod::Stored => Ok(raw), + CompressionMethod::Deflated => { + miniz_oxide::inflate::decompress_to_vec_with_limit(&raw, size.max(1) * 2 + 1024) + .map_err(|_| invalid("corrupt deflate stream")) } _ => Err(invalid("unsupported zip compression")), } @@ -163,10 +114,97 @@ mod tests { } #[test] fn reads_stored_and_deflated_entries() { + // Its CRCs are zero: Java's ZipFile doesn't check them either. let zip = Zip::from_bytes(archive()).unwrap(); assert_eq!(zip.names().collect::>(), ["a/b.txt", "pack.mcmeta"]); assert_eq!(zip.read("pack.mcmeta").unwrap(), b"{\"pack\":{}}"); assert_eq!(zip.read("a/b.txt").unwrap(), b"hello hello hello hello"); assert!(zip.read("missing").is_err()); } + + /// A pack as zip tools write it: folder entries, a nested pack root, + /// stored and deflated files, and a Windows-style name. + fn written() -> Vec { + use std::io::Write; + use zip::write::SimpleFileOptions; + let mut w = zip::ZipWriter::new(Cursor::new(Vec::new())); + let stored = SimpleFileOptions::default().compression_method(CompressionMethod::Stored); + let deflated = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated); + w.add_directory("Pack-main/", stored).unwrap(); + w.add_directory("Pack-main/assets/minecraft/", stored) + .unwrap(); + w.start_file("Pack-main/pack.mcmeta", stored).unwrap(); + w.write_all(b"{\"pack\":{\"pack_format\":64}}").unwrap(); + w.start_file("Pack-main/assets/minecraft/lang/en_us.json", deflated) + .unwrap(); + w.write_all("{\"a\":\"b\"}".repeat(100).as_bytes()).unwrap(); + w.start_file( + "Pack-main\\assets\\minecraft\\texts\\splashes.txt", + deflated, + ) + .unwrap(); + w.write_all(b"Also try Horizon!").unwrap(); + w.finish().unwrap().into_inner() + } + + #[test] + fn reads_nested_folders_and_skips_folder_entries() { + let zip = Zip::from_bytes(written()).unwrap(); + assert_eq!( + zip.names().collect::>(), + [ + "Pack-main/assets/minecraft/lang/en_us.json", + "Pack-main/assets/minecraft/texts/splashes.txt", + "Pack-main/pack.mcmeta", + ] + ); + assert!(zip.contains("Pack-main/pack.mcmeta")); + assert!(!zip.contains("Pack-main/")); + assert_eq!( + zip.read("Pack-main/assets/minecraft/lang/en_us.json") + .unwrap(), + "{\"a\":\"b\"}".repeat(100).as_bytes() + ); + assert_eq!( + zip.read("Pack-main/assets/minecraft/texts/splashes.txt") + .unwrap(), + b"Also try Horizon!" + ); + } + + #[test] + fn a_bad_entry_fails_alone() { + let mut bytes = written(); + // The deflated lang file's stream becomes a reserved block type. + let (start, len) = { + let mut archive = ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap(); + let index = archive + .index_for_name("Pack-main/assets/minecraft/lang/en_us.json") + .unwrap(); + let entry = archive.by_index_raw(index).unwrap(); + ( + entry.data_start() as usize, + entry.compressed_size() as usize, + ) + }; + bytes[start..start + len].fill(0xff); + let zip = Zip::from_bytes(bytes).unwrap(); + assert!( + zip.read("Pack-main/assets/minecraft/lang/en_us.json") + .is_err() + ); + assert_eq!( + zip.read("Pack-main/pack.mcmeta").unwrap(), + b"{\"pack\":{\"pack_format\":64}}" + ); + } + + #[test] + fn refuses_what_is_not_a_zip() { + assert!(Zip::from_bytes(b"PK not really".to_vec()).is_err()); + assert!(Zip::from_bytes(Vec::new()).is_err()); + let mut cut = written(); + cut.truncate(cut.len() / 2); + assert!(Zip::from_bytes(cut).is_err()); + } } diff --git a/crates/horizon-client/tests/lan_bot.rs b/crates/horizon-client/tests/lan_bot.rs index fdafcbb68..6dd1b8258 100644 --- a/crates/horizon-client/tests/lan_bot.rs +++ b/crates/horizon-client/tests/lan_bot.rs @@ -200,6 +200,7 @@ impl Server { tick_frozen: false, tick_steps: (0, 0), collision: None, + border: &horizon_client::worldborder::WorldBorder::default(), }; let events = self.hub.tick(&mut ctx); for event in events { diff --git a/crates/horizon-core/src/density/beardifier.rs b/crates/horizon-core/src/density/beardifier.rs index 5dec64189..b041be160 100644 --- a/crates/horizon-core/src/density/beardifier.rs +++ b/crates/horizon-core/src/density/beardifier.rs @@ -168,9 +168,6 @@ impl Beardifier { self.kernel_junctions = junctions; self } - pub fn affected_bounds(&self) -> Option { - self.affected - } fn sample_unchecked(&self, [x, y, z]: [i32; 3]) -> f32 { let mut value = 0.; // The kernel is a process-wide constant; resolving it once keeps the diff --git a/crates/horizon-core/src/geometry/shape/join.rs b/crates/horizon-core/src/geometry/shape/join.rs index 57c981e65..261c33802 100644 --- a/crates/horizon-core/src/geometry/shape/join.rs +++ b/crates/horizon-core/src/geometry/shape/join.rs @@ -13,8 +13,6 @@ impl ShapeOp { pub const XOR: Self = Self(6); pub const ONLY_FIRST: Self = Self(4); pub const ONLY_SECOND: Self = Self(2); - pub const FIRST: Self = Self(12); - pub const SECOND: Self = Self(10); pub const fn from_truth_table(bits: u8) -> Self { Self(bits & 15) } diff --git a/crates/horizon-core/src/paletted.rs b/crates/horizon-core/src/paletted.rs index d9ade23f2..802eac225 100644 --- a/crates/horizon-core/src/paletted.rs +++ b/crates/horizon-core/src/paletted.rs @@ -466,34 +466,6 @@ impl PalettedContainer { } } } - /// Block ids as 16-bit values (callers whose registry fits in 16 bits). - pub fn unpack_u16(&self, out: &mut [u16; 4096]) { - debug_assert_eq!(self.strategy.entries(), 4096); - match &self.palette { - Palette::Single(value) => out.fill(*value as u16), - Palette::List(list) => { - let bits = usize::from(self.bits); - let per = 64 / bits; - let m = mask(self.bits); - for (chunk, &word) in out.chunks_mut(per).zip(&self.words) { - for (slot, cell) in chunk.iter_mut().enumerate() { - let id = ((word >> (slot * bits)) & m) as usize; - *cell = list[id] as u16; - } - } - } - Palette::Global => { - let bits = usize::from(self.bits); - let per = 64 / bits; - let m = mask(self.bits); - for (chunk, &word) in out.chunks_mut(per).zip(&self.words) { - for (slot, cell) in chunk.iter_mut().enumerate() { - *cell = ((word >> (slot * bits)) & m) as u16; - } - } - } - } - } /// A container holding `values` in the smallest configuration for their /// distinct count, with palette ids in first-occurrence order, like a /// container unpacked from disk. diff --git a/crates/horizon-core/src/ticks/generation.rs b/crates/horizon-core/src/ticks/generation.rs index 4e1fdce6f..f81d9353e 100644 --- a/crates/horizon-core/src/ticks/generation.rs +++ b/crates/horizon-core/src/ticks/generation.rs @@ -91,9 +91,6 @@ impl WorldGenTickAccess { pub fn containers_mut(&mut self) -> &mut C { &mut self.containers } - pub fn into_containers(self) -> C { - self.containers - } pub fn schedule(&mut self, tick: ScheduledTick) -> Result { Ok(self.containers.container_at(tick.pos)?.schedule(tick)) } diff --git a/crates/horizon-core/src/ticks/mod.rs b/crates/horizon-core/src/ticks/mod.rs index f3cc83999..693aab130 100644 --- a/crates/horizon-core/src/ticks/mod.rs +++ b/crates/horizon-core/src/ticks/mod.rs @@ -636,7 +636,4 @@ impl LevelTicks { pub fn copy_area(&mut self, area: TickArea, offset: BlockPos) { self.schedule_copy(self.area_ticks(area), offset); } - pub fn copy_area_from(&mut self, source: &Self, area: TickArea, offset: BlockPos) { - self.schedule_copy(source.area_ticks(area), offset); - } } diff --git a/crates/horizon-friends/src/guest.rs b/crates/horizon-friends/src/guest.rs index 4f64bb1cc..492f4d482 100644 --- a/crates/horizon-friends/src/guest.rs +++ b/crates/horizon-friends/src/guest.rs @@ -296,14 +296,4 @@ impl Tunnel { })?; Ok((port, thread)) } - /// The protected stream itself (tests, or a client that reads it - /// directly). - pub fn into_stream( - self, - ) -> ( - crypto::SecureReader, - crypto::SecureWriter, - ) { - self.secure - } } diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 23ba00699..be3c4eb07 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -7,7 +7,7 @@ use crate::{ Vec3d, Writer, }, chunk::{ChunkData, LightData}, - entity_data::{EntityData, Value}, + entity_data::{EntityData, Particle, Value}, item::{Hashed, HashedSlot, Slot, Stack}, packet, packet_enum, packets::{ @@ -883,6 +883,116 @@ impl Codec for SetObjective { } } } +/// ClientboundLevelParticlesPacket: a particle, whether it ignores the +/// client's particle setting (`overrideLimiter`) and its distance limit +/// (`alwaysShow`), where, the spread and the speed on each axis, how many +/// (0: one, moving by speed times spread) and the randomization type +/// (0 default: gaussian spread and speed). +#[derive(Clone, Debug, PartialEq)] +pub struct LevelParticles { + pub particle: Particle, + pub override_limiter: bool, + pub always_show: bool, + pub pos: [f64; 3], + pub dist: [f32; 3], + pub max_speed: [f32; 3], + pub count: i32, + pub randomization: i32, +} +impl Codec for LevelParticles { + fn read(r: &mut Reader) -> Result { + Ok(Self { + particle: Particle::read(r)?, + override_limiter: r.bool()?, + always_show: r.bool()?, + pos: Vec3d::read(r)?, + dist: [r.f32()?, r.f32()?, r.f32()?], + max_speed: [r.f32()?, r.f32()?, r.f32()?], + count: r.varint()?, + randomization: r.varint()?, + }) + } + fn write(v: &Self, w: &mut Writer) { + v.particle.write(w); + w.bool(v.override_limiter); + w.bool(v.always_show); + Vec3d::write(&v.pos, w); + for f in v.dist.iter().chain(&v.max_speed) { + w.f32(*f); + } + w.varint(v.count); + w.varint(v.randomization); + } +} +/// `ExplosionParticleInfo` in a `WeightedList`: a particle the blast +/// scatters, its scaling and speed, then its weight. +#[derive(Clone, Debug, PartialEq)] +pub struct ExplosionParticle { + pub particle: Particle, + pub scaling: f32, + pub speed: f32, + pub weight: i32, +} +/// ClientboundExplodePacket: the centre, radius and blocks destroyed, the +/// push the receiving player takes, the particle at the centre, the sound, +/// the particles the blast scatters, and whether the sound plays. +#[derive(Clone, Debug, PartialEq)] +pub struct Explode { + pub center: [f64; 3], + pub radius: f32, + pub block_count: i32, + pub knockback: Option<[f64; 3]>, + pub particle: Particle, + pub sound: (i32, Option<(String, Option)>), + pub block_particles: Vec, + pub play_sound: bool, +} +impl Codec for Explode { + fn read(r: &mut Reader) -> Result { + let center = Vec3d::read(r)?; + let radius = r.f32()?; + let block_count = r.i32()?; + let knockback = >::read(r)?; + let particle = Particle::read(r)?; + let sound = SoundHolder::read(r)?; + let n = r.varint()?; + let mut block_particles = Vec::new(); + for _ in 0..n { + block_particles.push(ExplosionParticle { + particle: Particle::read(r)?, + scaling: r.f32()?, + speed: r.f32()?, + weight: r.varint()?, + }); + } + Ok(Self { + center, + radius, + block_count, + knockback, + particle, + sound, + block_particles, + play_sound: r.bool()?, + }) + } + fn write(v: &Self, w: &mut Writer) { + Vec3d::write(&v.center, w); + w.f32(v.radius); + w.i32(v.block_count); + >::write(&v.knockback, w); + v.particle.write(w); + SoundHolder::write(&v.sound, w); + w.varint(v.block_particles.len() as i32); + for b in &v.block_particles { + b.particle.write(w); + w.f32(b.scaling); + w.f32(b.speed); + w.varint(b.weight); + } + w.bool(v.play_sound); + } +} /// `ClientboundSetPlayerTeamPacket.Parameters`. #[derive(Clone, Debug, PartialEq)] pub struct TeamParameters { @@ -1566,6 +1676,8 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { TickingStep(TickingStep) = TICKING_STEP, UpdateAdvancements(UpdateAdvancements) = UPDATE_ADVANCEMENTS, UpdateAttributes(UpdateAttributes) = UPDATE_ATTRIBUTES, + LevelParticles(LevelParticles) = LEVEL_PARTICLES, + Explode(Explode) = EXPLODE, UpdateMobEffect(UpdateMobEffect) = UPDATE_MOB_EFFECT, UpdateTags(UpdateTags) = UPDATE_TAGS, TrackedWaypoint(TrackedWaypoint) = WAYPOINT, @@ -2270,6 +2382,34 @@ mod tests { passengers: vec![3, 300], }), Clientbound::SetEntityLink(SetEntityLink { source: 2, dest: 0 }), + Clientbound::LevelParticles(LevelParticles { + particle: Particle { + id: 21, + data: Some(crate::entity_data::ParticleData::ColorScale(0xFF0000, 1.5)), + }, + override_limiter: true, + always_show: false, + pos: [0.5, 101.0, 3.0], + dist: [0.2, 0.0, 0.2], + max_speed: [0.0; 3], + count: 60, + randomization: 0, + }), + Clientbound::Explode(Explode { + center: [1.0, 2.0, 3.0], + radius: 4.0, + block_count: 12, + knockback: Some([0.5, 0.1, 0.0]), + particle: Particle { id: 29, data: None }, + sound: (-1, Some(("minecraft:entity.generic.explode".into(), None))), + block_particles: vec![ExplosionParticle { + particle: Particle { id: 69, data: None }, + scaling: 0.5, + speed: 1.0, + weight: 1, + }], + play_sound: true, + }), Clientbound::ProjectilePower(ProjectilePower { id: 4, power: 0.1 }), Clientbound::SetEquipment(SetEquipment { id: 2, diff --git a/crates/horizon-server-files/src/user_cache.rs b/crates/horizon-server-files/src/user_cache.rs index c8ccd6cf0..38e779488 100644 --- a/crates/horizon-server-files/src/user_cache.rs +++ b/crates/horizon-server-files/src/user_cache.rs @@ -190,14 +190,6 @@ impl UserCache { result } - /// `get(UUID)`: a cached player by id (expired or not). - pub fn get_by_id(&mut self, id: u128) -> Option { - let index = *self.by_uuid.get(&id)?; - self.operations += 1; - self.infos[index].last_access = self.operations; - Some(self.infos[index].user.clone()) - } - /// The file's text: the 1000 most recently used entries, most recent /// first, as Gson writes them (compact, HTML-safe). pub fn to_json(&self) -> String { diff --git a/crates/horizon-server-files/src/user_lists.rs b/crates/horizon-server-files/src/user_lists.rs index 77de64e31..5bef4f38f 100644 --- a/crates/horizon-server-files/src/user_lists.rs +++ b/crates/horizon-server-files/src/user_lists.rs @@ -416,11 +416,6 @@ pub type WhiteList = UserList; pub type BanList = UserList>; pub type IpBanList = UserList>; -/// IpBanList.getIpFromAddress. -pub fn ip_of(address: &std::net::SocketAddr) -> String { - address.ip().to_string() -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/horizon-world/examples/active_effect_tick_fixture.rs b/crates/horizon-world/examples/probe/active_effect_tick_fixture.rs similarity index 99% rename from crates/horizon-world/examples/active_effect_tick_fixture.rs rename to crates/horizon-world/examples/probe/active_effect_tick_fixture.rs index 7a4ed3c29..1e366bf44 100644 --- a/crates/horizon-world/examples/active_effect_tick_fixture.rs +++ b/crates/horizon-world/examples/probe/active_effect_tick_fixture.rs @@ -512,9 +512,9 @@ fn run(f: Value, out: &mut dyn Write, make: fn(i64) -> R) { writeln!(w.out, "random {i} {} {}", r.next_long(), r.next_long()).unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); - let side = std::env::args().nth(2).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); + let side = crate::args().nth(2).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{side}.txt")))?); for line in fs::read_to_string(dir.join(format!("inputs-{side}.txt")))?.lines() { diff --git a/crates/horizon-world/examples/active_effects_fixture.rs b/crates/horizon-world/examples/probe/active_effects_fixture.rs similarity index 98% rename from crates/horizon-world/examples/active_effects_fixture.rs rename to crates/horizon-world/examples/probe/active_effects_fixture.rs index dba99cccd..70395e813 100644 --- a/crates/horizon-world/examples/active_effects_fixture.rs +++ b/crates/horizon-world/examples/probe/active_effects_fixture.rs @@ -304,9 +304,9 @@ fn run(f: Value, out: &mut dyn Write) { w.all(&s); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); - let side = std::env::args().nth(2).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); + let side = crate::args().nth(2).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{side}.txt")))?); for line in fs::read_to_string(dir.join(format!("inputs-{side}.txt")))?.lines() { diff --git a/crates/horizon-world/examples/anchor_fixture.rs b/crates/horizon-world/examples/probe/anchor_fixture.rs similarity index 94% rename from crates/horizon-world/examples/anchor_fixture.rs rename to crates/horizon-world/examples/probe/anchor_fixture.rs index c6c15e65e..230b05699 100644 --- a/crates/horizon-world/examples/anchor_fixture.rs +++ b/crates/horizon-world/examples/probe/anchor_fixture.rs @@ -18,8 +18,8 @@ fn anchor( a.to_json().unwrap_or_else(|_| "error".to_owned()) ) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/attribute_fixture.rs b/crates/horizon-world/examples/probe/attribute_fixture.rs similarity index 92% rename from crates/horizon-world/examples/attribute_fixture.rs rename to crates/horizon-world/examples/probe/attribute_fixture.rs index 450400c21..79cf4e236 100644 --- a/crates/horizon-world/examples/attribute_fixture.rs +++ b/crates/horizon-world/examples/probe/attribute_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_world::attributes::{ AttributeError, Definition, Instance, Modifier, Observer, Operation, Packed, }; @@ -10,13 +11,6 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } -} fn refs<'a>(mods: impl IntoIterator, pool: &[Modifier]) -> String { let s = mods .into_iter() @@ -43,9 +37,9 @@ impl Observer for Callback<'_> { self.out, "dirty {} {:016x} {} {:016x} {} {}", self.target, - bits(a.base_value()), + f64_bits(a.base_value()), a.is_dirty(), - bits(a.cached_value()), + f64_bits(a.cached_value()), a.modifiers().len(), a.permanent_modifiers().len() )?; @@ -55,7 +49,7 @@ impl Observer for Callback<'_> { return Err(io::Error::other("injected attribute observer failure")); } if self.op["read"].as_bool().unwrap() { - writeln!(self.out, "observed {:016x}", bits(a.value()))?; + writeln!(self.out, "observed {:016x}", f64_bits(a.value()))?; } Ok(()) } @@ -64,9 +58,9 @@ fn state(out: &mut dyn Write, id: usize, a: &Instance, pool: &[Modifier]) -> io: writeln!( out, "state {id} {:016x} {} {:016x}", - bits(a.base_value()), + f64_bits(a.base_value()), a.is_dirty(), - bits(a.cached_value()) + f64_bits(a.cached_value()) )?; writeln!(out, "all {}", refs(a.modifiers(), pool))?; writeln!(out, "permanent {}", refs(a.permanent_modifiers(), pool))?; @@ -80,8 +74,8 @@ fn state(out: &mut dyn Write, id: usize, a: &Instance, pool: &[Modifier]) -> io: } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -165,7 +159,7 @@ fn main() -> Result<(), Box> { writeln!( cb.out, "packed {:016x} {}", - bits(p.base), + f64_bits(p.base), refs(&p.modifiers, &pool) )?; packed = Some(p); @@ -181,7 +175,7 @@ fn main() -> Result<(), Box> { ), "many" => instances[target].add_permanent_many(mods(), &mut cb), "value" => { - writeln!(cb.out, "value {:016x}", bits(instances[target].value()))?; + writeln!(cb.out, "value {:016x}", f64_bits(instances[target].value()))?; Ok(()) } _ => panic!("fixture mode"), diff --git a/crates/horizon-world/examples/attribute_health_fixture.rs b/crates/horizon-world/examples/probe/attribute_health_fixture.rs similarity index 94% rename from crates/horizon-world/examples/attribute_health_fixture.rs rename to crates/horizon-world/examples/probe/attribute_health_fixture.rs index 3bf0d8d75..05e779aac 100644 --- a/crates/horizon-world/examples/attribute_health_fixture.rs +++ b/crates/horizon-world/examples/probe/attribute_health_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::{ attribute_health::{AttributeHealth, HealthAttributes, HealthError, HealthObserver}, attributes::{ @@ -21,13 +22,6 @@ fn single(v: &Value) -> f32 { fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn double_bits(v: f64) -> u64 { if v.is_nan() { f64::NAN.to_bits() @@ -55,7 +49,7 @@ impl Observer<'_> { impl HealthObserver for Observer<'_> { type Error = io::Error; fn updated(&mut self, h: &mut SyncedFloat) -> io::Result<()> { - self.effect(&format!("updated {:08x}", bits(h.value()))) + self.effect(&format!("updated {:08x}", f32_bits(h.value()))) } } // This fixture observes health/food values, not cross-attribute hash order. @@ -168,7 +162,7 @@ impl FoodWorld for World<'_, A> { } fn hurt_starvation(&mut self, _: (), _: &mut FoodData, v: f32) -> Result<(), Self::Error> { self.observer - .effect(&format!("starve {:08x}", bits(v))) + .effect(&format!("starve {:08x}", f32_bits(v))) .map_err(HealthError::Observer) } } @@ -261,7 +255,7 @@ fn run(dir: &Path, output: &str) -> Result<(), Box(dir: &Path, output: &str) -> Result<(), Box(dir: &Path, output: &str) -> Result<(), Box Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); - if std::env::args().nth(2).as_deref() == Some("live") { + if crate::args().nth(2).as_deref() == Some("live") { run::(dir, "rust-live.txt") } else { run::(dir, "rust.txt") diff --git a/crates/horizon-world/examples/attribute_map_queries_fixture.rs b/crates/horizon-world/examples/probe/attribute_map_queries_fixture.rs similarity index 98% rename from crates/horizon-world/examples/attribute_map_queries_fixture.rs rename to crates/horizon-world/examples/probe/attribute_map_queries_fixture.rs index 28ee0c73a..8b7bf110a 100644 --- a/crates/horizon-world/examples/attribute_map_queries_fixture.rs +++ b/crates/horizon-world/examples/probe/attribute_map_queries_fixture.rs @@ -244,9 +244,9 @@ mod integration { }; let prefix = format!( "prototype {id} {} {} {}", - bits(a.base_value()), + f64_hex(a.base_value()), a.is_dirty(), - bits(a.cached_value()) + f64_hex(a.cached_value()) ); let all = a.modifiers().to_vec(); let permanent = a.permanent_modifiers().to_vec(); @@ -271,7 +271,7 @@ mod integration { } } pub fn run() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); + let args: Vec<_> = crate::args().collect(); let dir = Path::new(&args[1]); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{}.txt", args[2])))?); @@ -377,14 +377,14 @@ mod integration { } else { ValueKind::Base }; - map.value(world.key(op), kind, &mut world).map(bits) + map.value(world.key(op), kind, &mut world).map(f64_hex) } "modifier-value" => { let id = world.templates[op["template"].as_u64().unwrap() as usize] .id() .to_owned(); map.modifier_value(world.key(op), &id, &mut world) - .map(bits) + .map(f64_hex) .map_err(|e| match e { ModifierValueError::World(e) => e, ModifierValueError::MissingInstanceModifier => Stop::Null, @@ -475,7 +475,7 @@ mod integration { "value" => world .handle(op["instance"].as_i64().unwrap()) .and_then(|h| h.ok_or(Stop::Null)) - .map(|h| bits(world.instances[h.id].value.as_mut().unwrap().value())), + .map(|h| f64_hex(world.instances[h.id].value.as_mut().unwrap().value())), _ => world.raw(&mut map, op).map(|()| "ok".into()), }; world.logs.push(format!( @@ -499,6 +499,6 @@ mod integration { Ok(()) } } -fn main() -> Result<(), Box> { +pub fn main() -> Result<(), Box> { integration::run() } diff --git a/crates/horizon-world/examples/attribute_updates_fixture.rs b/crates/horizon-world/examples/probe/attribute_updates_fixture.rs similarity index 99% rename from crates/horizon-world/examples/attribute_updates_fixture.rs rename to crates/horizon-world/examples/probe/attribute_updates_fixture.rs index 461a552b8..6bf9d815e 100644 --- a/crates/horizon-world/examples/attribute_updates_fixture.rs +++ b/crates/horizon-world/examples/probe/attribute_updates_fixture.rs @@ -625,9 +625,9 @@ fn run(f: Value, out: &mut dyn Write) { w.all(&s); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); - let side = std::env::args().nth(2).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); + let side = crate::args().nth(2).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{side}.txt")))?); for line in fs::read_to_string(dir.join(format!("inputs-{side}.txt")))?.lines() { diff --git a/crates/horizon-world/examples/basic_feature_fixture.rs b/crates/horizon-world/examples/probe/basic_feature_fixture.rs similarity index 97% rename from crates/horizon-world/examples/basic_feature_fixture.rs rename to crates/horizon-world/examples/probe/basic_feature_fixture.rs index f8ec7f53c..2e6bf9d73 100644 --- a/crates/horizon-world/examples/basic_feature_fixture.rs +++ b/crates/horizon-world/examples/probe/basic_feature_fixture.rs @@ -156,8 +156,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let ids: [u32; 5] = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let blocks = ids.map(BlockStateId); diff --git a/crates/horizon-world/examples/biome_chunk_fixture.rs b/crates/horizon-world/examples/probe/biome_chunk_fixture.rs similarity index 96% rename from crates/horizon-world/examples/biome_chunk_fixture.rs rename to crates/horizon-world/examples/probe/biome_chunk_fixture.rs index 69f7c897d..e0c7f1686 100644 --- a/crates/horizon-world/examples/biome_chunk_fixture.rs +++ b/crates/horizon-world/examples/probe/biome_chunk_fixture.rs @@ -20,8 +20,8 @@ fn biome_key(id: &i32) -> Option<&str> { _ => Some("horizon:other"), } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/biome_generation_fixture.rs b/crates/horizon-world/examples/probe/biome_generation_fixture.rs similarity index 97% rename from crates/horizon-world/examples/biome_generation_fixture.rs rename to crates/horizon-world/examples/probe/biome_generation_fixture.rs index 2377747f9..f5a609a5c 100644 --- a/crates/horizon-world/examples/biome_generation_fixture.rs +++ b/crates/horizon-world/examples/probe/biome_generation_fixture.rs @@ -20,8 +20,8 @@ use std::{ fn n(v: &Value) -> i32 { v.as_i64().unwrap() as i32 } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let bundle: Value = serde_json::from_str(&fs::read_to_string(dir.join("registries.json"))?)?; let noises: BTreeMap = serde_json::from_value(bundle["noises"].clone())?; diff --git a/crates/horizon-world/examples/biome_placement_fixture.rs b/crates/horizon-world/examples/probe/biome_placement_fixture.rs similarity index 97% rename from crates/horizon-world/examples/biome_placement_fixture.rs rename to crates/horizon-world/examples/probe/biome_placement_fixture.rs index a412b9924..36a8cb7e6 100644 --- a/crates/horizon-world/examples/biome_placement_fixture.rs +++ b/crates/horizon-world/examples/probe/biome_placement_fixture.rs @@ -150,8 +150,8 @@ fn fixture( writeln!(world.out, "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/biome_source_codec_fixture.rs b/crates/horizon-world/examples/probe/biome_source_codec_fixture.rs similarity index 95% rename from crates/horizon-world/examples/biome_source_codec_fixture.rs rename to crates/horizon-world/examples/probe/biome_source_codec_fixture.rs index d45dcdd3a..70347bbc6 100644 --- a/crates/horizon-world/examples/biome_source_codec_fixture.rs +++ b/crates/horizon-world/examples/probe/biome_source_codec_fixture.rs @@ -26,8 +26,8 @@ fn normalized(value: Value) -> Value { value => value, } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name: &str| -> Result, Box> { Ok(serde_json::from_str(&fs::read_to_string( diff --git a/crates/horizon-world/examples/biome_source_fixture.rs b/crates/horizon-world/examples/probe/biome_source_fixture.rs similarity index 95% rename from crates/horizon-world/examples/biome_source_fixture.rs rename to crates/horizon-world/examples/probe/biome_source_fixture.rs index cbf262a7c..021e67a0f 100644 --- a/crates/horizon-world/examples/biome_source_fixture.rs +++ b/crates/horizon-world/examples/probe/biome_source_fixture.rs @@ -29,8 +29,8 @@ impl DensitySampler for Erosion { } } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/biome_temperature_fixture.rs b/crates/horizon-world/examples/probe/biome_temperature_fixture.rs similarity index 97% rename from crates/horizon-world/examples/biome_temperature_fixture.rs rename to crates/horizon-world/examples/probe/biome_temperature_fixture.rs index 86b1393ce..e5b367947 100644 --- a/crates/horizon-world/examples/biome_temperature_fixture.rs +++ b/crates/horizon-world/examples/probe/biome_temperature_fixture.rs @@ -68,8 +68,8 @@ fn operations(worker: &mut BiomeTemperature, ops: &Value, out: &mut impl Write) } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/block_collision_scan_fixture.rs b/crates/horizon-world/examples/probe/block_collision_scan_fixture.rs similarity index 78% rename from crates/horizon-world/examples/block_collision_scan_fixture.rs rename to crates/horizon-world/examples/probe/block_collision_scan_fixture.rs index 4c4764c5f..e39fe2b8d 100644 --- a/crates/horizon-world/examples/block_collision_scan_fixture.rs +++ b/crates/horizon-world/examples/probe/block_collision_scan_fixture.rs @@ -1,5 +1,6 @@ +use crate::support::shapes::emit; use horizon_core::{ - geometry::{Aabb, Axis, ShapeOp, Vec3, VoxelShape}, + geometry::{Aabb, ShapeOp, Vec3, VoxelShape}, position::{BlockPos, ChunkPos}, }; use horizon_world::{ @@ -20,70 +21,6 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn values( - out: &mut impl Write, - label: &str, - values: impl IntoIterator, -) -> io::Result<()> { - write!(out, "{label}")?; - for v in values { - let bits = if v.is_nan() { - 0x7ff8_0000_0000_0000 - } else { - v.to_bits() - }; - write!(out, " {bits:016x}")?; - } - writeln!(out) -} -fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { - values( - out, - label, - [ - b.min(Axis::X), - b.min(Axis::Y), - b.min(Axis::Z), - b.max(Axis::X), - b.max(Axis::Y), - b.max(Axis::Z), - ], - ) -} -fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { - writeln!( - out, - "shape {} {} {}", - shape.is_empty(), - shape.boxes().len(), - shape.is_cube() - )?; - for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { - values(out, name, shape.coordinates(axis).iter().copied())?; - } - let axes = shape.cube_coordinate_axes(); - writeln!( - out, - "axes {}", - u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) - )?; - values( - out, - "extrema", - Axis::ALL - .map(|a| shape.min(a)) - .into_iter() - .chain(Axis::ALL.map(|a| shape.max(a))), - )?; - match shape.bounds() { - Some(b) => box_values(out, "bounds", b)?, - None => writeln!(out, "bounds none")?, - } - for b in shape.boxes() { - box_values(out, "box", *b)?; - } - Ok(()) -} fn shape(index: u64) -> VoxelShape { let cuboid = |min, max| VoxelShape::from_box(Aabb::new(min, max)).unwrap(); @@ -174,8 +111,8 @@ impl BlockCollisionWorld for World { Ok(self.palette[block.state.0 as usize].shape.clone()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let out = Rc::new(RefCell::new(io::BufWriter::new(fs::File::create( dir.join("rust.txt"), diff --git a/crates/horizon-world/examples/block_entity_storage_fixture.rs b/crates/horizon-world/examples/probe/block_entity_storage_fixture.rs similarity index 98% rename from crates/horizon-world/examples/block_entity_storage_fixture.rs rename to crates/horizon-world/examples/probe/block_entity_storage_fixture.rs index e321f23fe..687eed790 100644 --- a/crates/horizon-world/examples/block_entity_storage_fixture.rs +++ b/crates/horizon-world/examples/probe/block_entity_storage_fixture.rs @@ -72,8 +72,8 @@ fn pending(tag: Option<&Tag>) -> String { } } } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let mut out = io::BufWriter::new(fs::File::create(&args[2])?); let mut position = ChunkPos::default(); let mut chunk = ProtoBlockEntities::::new(position); diff --git a/crates/horizon-world/examples/block_landing_fixture.rs b/crates/horizon-world/examples/probe/block_landing_fixture.rs similarity index 93% rename from crates/horizon-world/examples/block_landing_fixture.rs rename to crates/horizon-world/examples/probe/block_landing_fixture.rs index 9e20d5a1b..a6ab6ac33 100644 --- a/crates/horizon-world/examples/block_landing_fixture.rs +++ b/crates/horizon-world/examples/probe/block_landing_fixture.rs @@ -1,5 +1,7 @@ +use crate::support::common::f64_bits; +use crate::support::shapes::bounds; use horizon_core::{ - geometry::{Aabb, Axis, Vec3, VoxelShape}, + geometry::{Aabb, Vec3, VoxelShape}, position::BlockPos, }; use horizon_world::{ @@ -24,13 +26,6 @@ fn number(v: &Value) -> f64 { fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn fbits(v: f32) -> u32 { if v.is_nan() { 0x7fc00000 } else { v.to_bits() } } @@ -43,17 +38,6 @@ fn bbox(v: &Value) -> Aabb { Vec3::new(number(&v[3]), number(&v[4]), number(&v[5])), ) } -fn bounds(label: &str, b: Aabb) -> String { - format!( - "{label} {:016x} {:016x} {:016x} {:016x} {:016x} {:016x}", - bits(b.min(Axis::X)), - bits(b.min(Axis::Y)), - bits(b.min(Axis::Z)), - bits(b.max(Axis::X)), - bits(b.max(Axis::Y)), - bits(b.max(Axis::Z)) - ) -} struct World<'a, 'r> { f: &'a Value, out: &'a mut dyn Write, @@ -100,9 +84,9 @@ impl BlockPushWorld for World<'_, '_> { self.query(format!( "teleport {} {:016x} {:016x} {:016x}", e.0, - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) ))?; let i = e.0 as usize; self.entities[i] = self.entities[i].move_by(v); @@ -169,7 +153,7 @@ impl BlockLandingWorld for World<'_, '_> { Ok(k) } fn cause_fall_damage(&mut self, d: f64, m: f32, s: Self::DamageSource) -> io::Result { - self.query(format!("damage {:016x} {:08x} {s}", bits(d), fbits(m)))?; + self.query(format!("damage {:016x} {:08x} {s}", f64_bits(d), fbits(m)))?; Ok(self.flag("damage")) } fn known_sound(&self, s: LandingSound) -> Self::Sound { @@ -237,8 +221,8 @@ impl BlockLandingWorld for World<'_, '_> { self.query(format!("level-event {e} {} {d}", pos(p))) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); let read = |name: &str| -> Result> { diff --git a/crates/horizon-world/examples/block_properties_fixture.rs b/crates/horizon-world/examples/probe/block_properties_fixture.rs similarity index 97% rename from crates/horizon-world/examples/block_properties_fixture.rs rename to crates/horizon-world/examples/probe/block_properties_fixture.rs index 3404b1fa1..6169041a2 100644 --- a/crates/horizon-world/examples/block_properties_fixture.rs +++ b/crates/horizon-world/examples/probe/block_properties_fixture.rs @@ -20,8 +20,8 @@ fn bbox(v: &Value) -> Aabb { .collect::>(); Aabb::new(Vec3::new(v[0], v[1], v[2]), Vec3::new(v[3], v[4], v[5])) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name: &str| -> Result> { Ok( diff --git a/crates/horizon-world/examples/block_push_fixture.rs b/crates/horizon-world/examples/probe/block_push_fixture.rs similarity index 83% rename from crates/horizon-world/examples/block_push_fixture.rs rename to crates/horizon-world/examples/probe/block_push_fixture.rs index 8871b1070..678e0fa24 100644 --- a/crates/horizon-world/examples/block_push_fixture.rs +++ b/crates/horizon-world/examples/probe/block_push_fixture.rs @@ -1,5 +1,7 @@ +use crate::support::common::f64_bits; +use crate::support::shapes::bounds; use horizon_core::{ - geometry::{Aabb, Axis, ShapeOp, Vec3, VoxelShape}, + geometry::{Aabb, ShapeOp, Vec3, VoxelShape}, position::BlockPos, }; use horizon_world::{ @@ -16,30 +18,12 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn bbox(v: &Value) -> Aabb { Aabb::new( Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])), Vec3::new(number(&v[3]), number(&v[4]), number(&v[5])), ) } -fn bounds(label: &str, b: Aabb) -> String { - format!( - "{label} {:016x} {:016x} {:016x} {:016x} {:016x} {:016x}", - bits(b.min(Axis::X)), - bits(b.min(Axis::Y)), - bits(b.min(Axis::Z)), - bits(b.max(Axis::X)), - bits(b.max(Axis::Y)), - bits(b.max(Axis::Z)) - ) -} fn shape(v: &Value) -> Result> { let mut s = VoxelShape::empty(); for b in v.as_array().unwrap() { @@ -85,9 +69,9 @@ impl BlockPushWorld for World<'_> { self.query(format!( "teleport {} {:016x} {:016x} {:016x}", e.0, - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) ))?; let index = e.0 as usize; self.entities[index] = self.entities[index].move_by(v); @@ -97,8 +81,8 @@ impl BlockPushWorld for World<'_> { Ok(()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/block_state_codec_fixture.rs b/crates/horizon-world/examples/probe/block_state_codec_fixture.rs similarity index 76% rename from crates/horizon-world/examples/block_state_codec_fixture.rs rename to crates/horizon-world/examples/probe/block_state_codec_fixture.rs index d0632ae86..40d51d4c2 100644 --- a/crates/horizon-world/examples/block_state_codec_fixture.rs +++ b/crates/horizon-world/examples/probe/block_state_codec_fixture.rs @@ -1,4 +1,5 @@ //! Original JSON block-state codec comparison transport. +use crate::support::common::tag; use horizon_world::{ DATA_VERSION, nbt::Tag, @@ -11,19 +12,8 @@ use std::{ io::{self, Write}, path::Path, }; -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(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - _ => panic!("invalid registry metadata"), - } -} -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let registry = BlockRegistry::from_nbt(&Tag::compound([ diff --git a/crates/horizon-world/examples/block_support_fixture.rs b/crates/horizon-world/examples/probe/block_support_fixture.rs similarity index 94% rename from crates/horizon-world/examples/block_support_fixture.rs rename to crates/horizon-world/examples/probe/block_support_fixture.rs index 9c43d5798..5d58fe159 100644 --- a/crates/horizon-world/examples/block_support_fixture.rs +++ b/crates/horizon-world/examples/probe/block_support_fixture.rs @@ -9,8 +9,8 @@ use std::{ io::{self, Write}, path::Path, }; -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name: &str| -> Result> { Ok( diff --git a/crates/horizon-world/examples/block_survival_fixture.rs b/crates/horizon-world/examples/probe/block_survival_fixture.rs similarity index 98% rename from crates/horizon-world/examples/block_survival_fixture.rs rename to crates/horizon-world/examples/probe/block_survival_fixture.rs index e062eb8da..b357d1577 100644 --- a/crates/horizon-world/examples/block_survival_fixture.rs +++ b/crates/horizon-world/examples/probe/block_survival_fixture.rs @@ -103,8 +103,8 @@ impl SurvivalWorld for World<'_, W> { Ok(self.neighbors[old as usize % self.neighbors.len()]) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name: &str| -> Result> { Ok( diff --git a/crates/horizon-world/examples/block_update_fixture.rs b/crates/horizon-world/examples/probe/block_update_fixture.rs similarity index 99% rename from crates/horizon-world/examples/block_update_fixture.rs rename to crates/horizon-world/examples/probe/block_update_fixture.rs index bc90232cb..5be9be731 100644 --- a/crates/horizon-world/examples/block_update_fixture.rs +++ b/crates/horizon-world/examples/probe/block_update_fixture.rs @@ -191,8 +191,8 @@ fn summary(level: &Cells, before: &HashMap, out: &mut St } } -fn main() -> Result<(), Box> { - let mut args = std::env::args().skip(1); +pub fn main() -> Result<(), Box> { + let mut args = crate::args().skip(1); let resources = args.next().expect("resource directory"); let cases = args.next().expect("case file"); let output = args.next().expect("output file"); diff --git a/crates/horizon-world/examples/blocking_item_damage_fixture.rs b/crates/horizon-world/examples/probe/blocking_item_damage_fixture.rs similarity index 97% rename from crates/horizon-world/examples/blocking_item_damage_fixture.rs rename to crates/horizon-world/examples/probe/blocking_item_damage_fixture.rs index 2fd39bea0..eb2a6de60 100644 --- a/crates/horizon-world/examples/blocking_item_damage_fixture.rs +++ b/crates/horizon-world/examples/probe/blocking_item_damage_fixture.rs @@ -117,8 +117,8 @@ impl BlockingItemDamageWorld for World<'_> { Ok(self.flag("server")) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/blocking_rules_fixture.rs b/crates/horizon-world/examples/probe/blocking_rules_fixture.rs similarity index 93% rename from crates/horizon-world/examples/blocking_rules_fixture.rs rename to crates/horizon-world/examples/probe/blocking_rules_fixture.rs index c0e19d541..19d3bb8d5 100644 --- a/crates/horizon-world/examples/blocking_rules_fixture.rs +++ b/crates/horizon-world/examples/probe/blocking_rules_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::blocking_rules::{ BlockingRules, DamageReduction, ItemDamageFunction, TypeMatchWorld, }; @@ -13,13 +14,6 @@ fn single(v: &Value) -> f32 { fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} struct World<'a> { f: &'a Value, out: &'a mut dyn Write, @@ -51,8 +45,8 @@ impl TypeMatchWorld for World<'_> { }) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -96,7 +90,7 @@ fn main() -> Result<(), Box> { )?; writeln!(w.out, "item {}", rules.item_damage.apply(damage))?; match rules.resolve(&mut w, damage, number(&f["angle"])) { - Ok(v) => writeln!(w.out, "blocked {:08x}\nresult ok", bits(v))?, + Ok(v) => writeln!(w.out, "blocked {:08x}\nresult ok", f32_bits(v))?, Err(_) => writeln!(w.out, "result error")?, }; writeln!(w.out, "queries {} {}", w.calls, w.changed)?; diff --git a/crates/horizon-world/examples/bulk_section_fixture.rs b/crates/horizon-world/examples/probe/bulk_section_fixture.rs similarity index 92% rename from crates/horizon-world/examples/bulk_section_fixture.rs rename to crates/horizon-world/examples/probe/bulk_section_fixture.rs index b9be692a7..a7bcc834a 100644 --- a/crates/horizon-world/examples/bulk_section_fixture.rs +++ b/crates/horizon-world/examples/probe/bulk_section_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::tag; use horizon_world::worldgen::{ anchor::WorldGenerationContext, bulk_section::TerrainBulkAccess, feature_region::TerrainRegion, }; @@ -55,17 +56,6 @@ impl TerrainBlockStates for Properties<'_> { fn n(v: &Value) -> i32 { v.as_i64().unwrap() as i32 } -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(i) => Tag::Int(i.as_i64().unwrap() as i32), - Value::Object(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - _ => panic!("unsupported registry fixture value"), - } -} fn fixture( f: &Value, registry: &BlockRegistry, @@ -151,8 +141,8 @@ fn fixture( } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let bundle: Value = serde_json::from_str(&fs::read_to_string(dir.join("tags.json"))?)?; diff --git a/crates/horizon-world/examples/bundle_weight_fixture.rs b/crates/horizon-world/examples/probe/bundle_weight_fixture.rs similarity index 98% rename from crates/horizon-world/examples/bundle_weight_fixture.rs rename to crates/horizon-world/examples/probe/bundle_weight_fixture.rs index 2a47cdc37..8e077b807 100644 --- a/crates/horizon-world/examples/bundle_weight_fixture.rs +++ b/crates/horizon-world/examples/probe/bundle_weight_fixture.rs @@ -69,8 +69,8 @@ fn maximum(v: &Value) -> Option { fn fraction(f: Fraction) -> String { format!("{}/{}", f.numerator(), f.denominator()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/canyon_carver_fixture.rs b/crates/horizon-world/examples/probe/canyon_carver_fixture.rs similarity index 96% rename from crates/horizon-world/examples/canyon_carver_fixture.rs rename to crates/horizon-world/examples/probe/canyon_carver_fixture.rs index 023ffa356..76eaad452 100644 --- a/crates/horizon-world/examples/canyon_carver_fixture.rs +++ b/crates/horizon-world/examples/probe/canyon_carver_fixture.rs @@ -82,8 +82,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/carving_geometry_fixture.rs b/crates/horizon-world/examples/probe/carving_geometry_fixture.rs similarity index 91% rename from crates/horizon-world/examples/carving_geometry_fixture.rs rename to crates/horizon-world/examples/probe/carving_geometry_fixture.rs index 1f0ce0ea2..52582b45b 100644 --- a/crates/horizon-world/examples/carving_geometry_fixture.rs +++ b/crates/horizon-world/examples/probe/carving_geometry_fixture.rs @@ -1,4 +1,5 @@ //! Transport for shared cave/canyon geometry and ordered output failures. +use crate::support::common::f64_bits; use horizon_core::{ carving::{CarverOutput, CarvingMask, can_reach, carve_ellipsoid}, position::ChunkPos, @@ -15,13 +16,6 @@ fn n(v: &Value) -> i32 { fn d(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} struct Output<'a> { mask: &'a mut CarvingMask, trace: &'a std::cell::RefCell>, @@ -47,8 +41,8 @@ impl CarverOutput for Output<'_> { Ok(()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -78,9 +72,9 @@ fn main() -> Result<(), Box> { }; trace.borrow_mut().push(format!( "skip {:x} {:x} {:x} {by} {skip}", - bits(x), - bits(y), - bits(z) + f64_bits(x), + f64_bits(y), + f64_bits(z) )); skip }, diff --git a/crates/horizon-world/examples/carving_mask_fixture.rs b/crates/horizon-world/examples/probe/carving_mask_fixture.rs similarity index 95% rename from crates/horizon-world/examples/carving_mask_fixture.rs rename to crates/horizon-world/examples/probe/carving_mask_fixture.rs index c7675ce47..17c82fd3c 100644 --- a/crates/horizon-world/examples/carving_mask_fixture.rs +++ b/crates/horizon-world/examples/probe/carving_mask_fixture.rs @@ -9,8 +9,8 @@ use std::{ fn n(v: &Value) -> i32 { v.as_i64().unwrap() as i32 } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/cave_carver_fixture.rs b/crates/horizon-world/examples/probe/cave_carver_fixture.rs similarity index 96% rename from crates/horizon-world/examples/cave_carver_fixture.rs rename to crates/horizon-world/examples/probe/cave_carver_fixture.rs index ad0d37612..79917c336 100644 --- a/crates/horizon-world/examples/cave_carver_fixture.rs +++ b/crates/horizon-world/examples/probe/cave_carver_fixture.rs @@ -82,8 +82,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/chunk_dump.rs b/crates/horizon-world/examples/probe/chunk_dump.rs similarity index 96% rename from crates/horizon-world/examples/chunk_dump.rs rename to crates/horizon-world/examples/probe/chunk_dump.rs index 125509d99..d36944989 100644 --- a/crates/horizon-world/examples/chunk_dump.rs +++ b/crates/horizon-world/examples/probe/chunk_dump.rs @@ -11,6 +11,7 @@ //! quart layer (16 columns, z-major), one `y Y ID...` line per block row and //! one `be X Y Z CANONICAL_NBT` line per block entity and one `t block|fluid //! NAME X Y Z PRIORITY` line per scheduled tick. +use crate::support::common::tag; use horizon_core::position::ChunkPos; use horizon_world::{ DATA_VERSION, @@ -23,17 +24,6 @@ use std::{collections::HashMap, fmt::Write as _, fs, io::Write as _, path::Path} 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 states = facts["states"].as_array().ok_or("facts states")?; @@ -106,8 +96,8 @@ fn canonical(tag: &Tag, out: &mut String) { } } -fn main() -> Result<(), Error> { - let mut args = std::env::args().skip(1); +pub fn main() -> Result<(), Error> { + let mut args = crate::args().skip(1); let resources = std::path::PathBuf::from(args.next().ok_or("client resource directory")?); let seed: i64 = args.next().ok_or("seed")?.parse()?; let dimension = format!("minecraft:{}", args.next().ok_or("dimension")?); diff --git a/crates/horizon-world/examples/chunk_stage_fixture.rs b/crates/horizon-world/examples/probe/chunk_stage_fixture.rs similarity index 94% rename from crates/horizon-world/examples/chunk_stage_fixture.rs rename to crates/horizon-world/examples/probe/chunk_stage_fixture.rs index ee57f8930..2929de2f1 100644 --- a/crates/horizon-world/examples/chunk_stage_fixture.rs +++ b/crates/horizon-world/examples/probe/chunk_stage_fixture.rs @@ -1,4 +1,5 @@ //! Test transport for pre-light ProtoChunk writes and stage heightmap transitions. +use crate::support::common::tag; use horizon_core::position::ChunkPos; use horizon_world::{ DATA_VERSION, @@ -54,17 +55,6 @@ impl TerrainBlockStates for Properties<'_> { fn n(v: &Value) -> i32 { v.as_i64().unwrap() as i32 } -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(i) => Tag::Int(i.as_i64().unwrap() as i32), - Value::Object(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - _ => panic!("unsupported registry fixture value"), - } -} fn fixture( f: &Value, registry: &BlockRegistry, @@ -223,8 +213,8 @@ fn fixture( } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let bundle: Value = serde_json::from_str(&fs::read_to_string(dir.join("tags.json"))?)?; diff --git a/crates/horizon-world/examples/chunk_status_fixture.rs b/crates/horizon-world/examples/probe/chunk_status_fixture.rs similarity index 95% rename from crates/horizon-world/examples/chunk_status_fixture.rs rename to crates/horizon-world/examples/probe/chunk_status_fixture.rs index 92c5fe7bd..e124517fa 100644 --- a/crates/horizon-world/examples/chunk_status_fixture.rs +++ b/crates/horizon-world/examples/probe/chunk_status_fixture.rs @@ -4,8 +4,8 @@ use std::{ fs, io::{self, Write}, }; -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let mut out = io::BufWriter::new(fs::File::create(&args[2])?); writeln!( out, diff --git a/crates/horizon-world/examples/climbing_fixture.rs b/crates/horizon-world/examples/probe/climbing_fixture.rs similarity index 98% rename from crates/horizon-world/examples/climbing_fixture.rs rename to crates/horizon-world/examples/probe/climbing_fixture.rs index 19badd19b..48a28b8d3 100644 --- a/crates/horizon-world/examples/climbing_fixture.rs +++ b/crates/horizon-world/examples/probe/climbing_fixture.rs @@ -69,8 +69,8 @@ impl ClimbingWorld for World<'_> { self.last = Some(p); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let registry = BlockRegistry::from_nbt( &nbt::read_named( diff --git a/crates/horizon-world/examples/collision_context_fixture.rs b/crates/horizon-world/examples/probe/collision_context_fixture.rs similarity index 90% rename from crates/horizon-world/examples/collision_context_fixture.rs rename to crates/horizon-world/examples/probe/collision_context_fixture.rs index e99673e11..f26137fef 100644 --- a/crates/horizon-world/examples/collision_context_fixture.rs +++ b/crates/horizon-world/examples/probe/collision_context_fixture.rs @@ -1,5 +1,6 @@ +use crate::support::shapes::emit; use horizon_core::{ - geometry::{Aabb, Axis, ShapeOp, Vec3, VoxelShape}, + geometry::{Aabb, ShapeOp, Vec3, VoxelShape}, position::BlockPos, }; use horizon_world::{ @@ -31,70 +32,6 @@ const ITEMS: [&str; 5] = [ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn values( - out: &mut impl Write, - label: &str, - values: impl IntoIterator, -) -> io::Result<()> { - write!(out, "{label}")?; - for v in values { - let bits = if v.is_nan() { - 0x7ff8_0000_0000_0000 - } else { - v.to_bits() - }; - write!(out, " {bits:016x}")?; - } - writeln!(out) -} -fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { - values( - out, - label, - [ - b.min(Axis::X), - b.min(Axis::Y), - b.min(Axis::Z), - b.max(Axis::X), - b.max(Axis::Y), - b.max(Axis::Z), - ], - ) -} -fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { - writeln!( - out, - "shape {} {} {}", - shape.is_empty(), - shape.boxes().len(), - shape.is_cube() - )?; - for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { - values(out, name, shape.coordinates(axis).iter().copied())?; - } - let axes = shape.cube_coordinate_axes(); - writeln!( - out, - "axes {}", - u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) - )?; - values( - out, - "extrema", - Axis::ALL - .map(|a| shape.min(a)) - .into_iter() - .chain(Axis::ALL.map(|a| shape.max(a))), - )?; - match shape.bounds() { - Some(b) => box_values(out, "bounds", b)?, - None => writeln!(out, "bounds none")?, - } - for b in shape.boxes() { - box_values(out, "box", *b)?; - } - Ok(()) -} struct LiquidWorld<'a, W> { out: &'a mut W, calls: i32, @@ -244,8 +181,8 @@ impl PowderSnowWorld for RegistryWorld<'_, W> { Ok(self.feet.is_item("minecraft:leather_boots")) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let registry = if dir.join("block-registry.nbt").exists() { Some(BlockRegistry::from_nbt( diff --git a/crates/horizon-world/examples/collision_fixture.rs b/crates/horizon-world/examples/probe/collision_fixture.rs similarity index 97% rename from crates/horizon-world/examples/collision_fixture.rs rename to crates/horizon-world/examples/probe/collision_fixture.rs index f8f2651c9..b2601f137 100644 --- a/crates/horizon-world/examples/collision_fixture.rs +++ b/crates/horizon-world/examples/probe/collision_fixture.rs @@ -56,12 +56,8 @@ impl Input<'_> { Vec3::new(self.number(), self.number(), self.number()) } } -fn main() -> Result<(), Box> { - let base = PathBuf::from( - std::env::args() - .nth(1) - .ok_or("fixture directory required")?, - ); +pub fn main() -> Result<(), Box> { + let base = PathBuf::from(crate::args().nth(1).ok_or("fixture directory required")?); let (registry_root, _) = nbt::read_named( &fs::read(base.join("block-registry.nbt"))?, Limits::default(), diff --git a/crates/horizon-world/examples/combat_rules_fixture.rs b/crates/horizon-world/examples/probe/combat_rules_fixture.rs similarity index 88% rename from crates/horizon-world/examples/combat_rules_fixture.rs rename to crates/horizon-world/examples/probe/combat_rules_fixture.rs index 42d01285d..9e523a30d 100644 --- a/crates/horizon-world/examples/combat_rules_fixture.rs +++ b/crates/horizon-world/examples/probe/combat_rules_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::combat_rules::{self, ArmorWorld}; use serde_json::Value; use std::{ @@ -8,13 +9,6 @@ use std::{ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} struct World<'a> { f: &'a Value, out: &'a mut dyn Write, @@ -56,8 +50,8 @@ impl ArmorWorld for World<'_> { Ok(v) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -77,7 +71,7 @@ fn main() -> Result<(), Box> { }; match result { Ok(v) => { - writeln!(w.out, "value {:08x}\nresult ok", bits(v))?; + writeln!(w.out, "value {:08x}\nresult ok", f32_bits(v))?; } Err(_) => writeln!(w.out, "result error")?, } diff --git a/crates/horizon-world/examples/component_durability_fixture.rs b/crates/horizon-world/examples/probe/component_durability_fixture.rs similarity index 98% rename from crates/horizon-world/examples/component_durability_fixture.rs rename to crates/horizon-world/examples/probe/component_durability_fixture.rs index 99f6c2389..7c5d89111 100644 --- a/crates/horizon-world/examples/component_durability_fixture.rs +++ b/crates/horizon-world/examples/probe/component_durability_fixture.rs @@ -135,8 +135,8 @@ impl DurabilityWorld for World<'_> { writeln!(self.out, "copy-after {}", snapshot(©)) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/component_patch_fixture.rs b/crates/horizon-world/examples/probe/component_patch_fixture.rs similarity index 97% rename from crates/horizon-world/examples/component_patch_fixture.rs rename to crates/horizon-world/examples/probe/component_patch_fixture.rs index 29b345c8d..9bd740061 100644 --- a/crates/horizon-world/examples/component_patch_fixture.rs +++ b/crates/horizon-world/examples/probe/component_patch_fixture.rs @@ -88,8 +88,8 @@ fn snapshot( maps[1] == maps[2] ) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/consumable_emission_fixture.rs b/crates/horizon-world/examples/probe/consumable_emission_fixture.rs similarity index 95% rename from crates/horizon-world/examples/consumable_emission_fixture.rs rename to crates/horizon-world/examples/probe/consumable_emission_fixture.rs index 966cec1d6..6bff122e1 100644 --- a/crates/horizon-world/examples/consumable_emission_fixture.rs +++ b/crates/horizon-world/examples/probe/consumable_emission_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{ geometry::Vec3, random::{LegacyRandom, RandomSource, XoroshiroRandom}, @@ -23,13 +24,6 @@ fn n(v: &Value, k: &str) -> i32 { fn fl(v: &Value, k: &str) -> f32 { f32::from_bits(v[k].as_u64().unwrap() as u32) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn opt(v: Option<&i32>) -> String { v.map_or("none".into(), i32::to_string) } @@ -142,12 +136,12 @@ impl ItemParticleWorld for World<'_, R> { "particle {level} {} {} {damage} {same} {} {} {} {} {} {}", t.item(), t.count(), - bits(p.x), - bits(p.y), - bits(p.z), - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z), + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) )) } } @@ -237,8 +231,8 @@ fn run(f: Value, out: &mut dyn Write, make: fn(i64) -> R) { writeln!(w.out, "random {i} {} {}", r.next_long(), r.next_long()).unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/consumable_fixture.rs b/crates/horizon-world/examples/probe/consumable_fixture.rs similarity index 96% rename from crates/horizon-world/examples/consumable_fixture.rs rename to crates/horizon-world/examples/probe/consumable_fixture.rs index bfb1ad786..fccf46129 100644 --- a/crates/horizon-world/examples/consumable_fixture.rs +++ b/crates/horizon-world/examples/probe/consumable_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{ geometry::Vec3, random::{LegacyRandom, RandomSource, XoroshiroRandom}, @@ -33,13 +34,6 @@ fn n(v: &Value, k: &str) -> i32 { fn fl(v: &Value, k: &str) -> f32 { f32::from_bits(v[k].as_u64().unwrap() as u32) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn opt(v: Option<&Component>) -> String { match v { None => "none".into(), @@ -189,12 +183,12 @@ impl ItemParticleWorld for World<'_, R> { "particle {level} {} {} {damage} {same} {} {} {} {} {} {}", t.item(), t.count(), - bits(p.x), - bits(p.y), - bits(p.z), - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z), + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) )) } } @@ -263,9 +257,9 @@ impl FoodConsumptionWorld for World<'_, R> { "food-sound {} {} {category} {} {} {} {} {}", s.level, s.sound, - bits(s.position.x), - bits(s.position.y), - bits(s.position.z), + f64_bits(s.position.x), + f64_bits(s.position.y), + f64_bits(s.position.z), fbits(s.volume), fbits(s.pitch) )) @@ -403,8 +397,8 @@ fn run(f: Value, out: &mut dyn Write, make: fn(i64) -> R) { writeln!(w.out, "random {i} {} {}", r.next_long(), r.next_long()).unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/consume_effect_fixture.rs b/crates/horizon-world/examples/probe/consume_effect_fixture.rs similarity index 98% rename from crates/horizon-world/examples/consume_effect_fixture.rs rename to crates/horizon-world/examples/probe/consume_effect_fixture.rs index 5e4b878b5..85c3b530b 100644 --- a/crates/horizon-world/examples/consume_effect_fixture.rs +++ b/crates/horizon-world/examples/probe/consume_effect_fixture.rs @@ -206,8 +206,8 @@ fn run(f: Value, out: &mut dyn Write, make: fn(i64) -> R) { writeln!(w.out, "random {i} {} {}", r.next_long(), r.next_long()).unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/damage_immunity_fixture.rs b/crates/horizon-world/examples/probe/damage_immunity_fixture.rs similarity index 97% rename from crates/horizon-world/examples/damage_immunity_fixture.rs rename to crates/horizon-world/examples/probe/damage_immunity_fixture.rs index b404b27b2..f477c08de 100644 --- a/crates/horizon-world/examples/damage_immunity_fixture.rs +++ b/crates/horizon-world/examples/probe/damage_immunity_fixture.rs @@ -91,8 +91,8 @@ impl ImmunityWorld for Env<'_> { self.query("loaded", "loaded") } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let slots: Value = serde_json::from_str(&fs::read_to_string(dir.join("slots.json"))?)?; let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); diff --git a/crates/horizon-world/examples/damage_reduction_fixture.rs b/crates/horizon-world/examples/probe/damage_reduction_fixture.rs similarity index 93% rename from crates/horizon-world/examples/damage_reduction_fixture.rs rename to crates/horizon-world/examples/probe/damage_reduction_fixture.rs index 16d37af2f..7310ca43e 100644 --- a/crates/horizon-world/examples/damage_reduction_fixture.rs +++ b/crates/horizon-world/examples/probe/damage_reduction_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::{ combat_rules::ArmorWorld, damage_reduction::{self, Bypass, DamageReductionWorld}, @@ -14,13 +15,6 @@ fn single(v: &Value) -> f32 { fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} struct World<'a> { f: &'a Value, out: &'a mut dyn Write, @@ -73,7 +67,7 @@ impl DamageReductionWorld for World<'_> { Ok(self.state()[format!("bypass_{n}")].as_bool().unwrap()) } fn hurt_armor(&mut self, v: f32) -> io::Result<()> { - self.query(&format!("hurt-armor {:08x}", bits(v))) + self.query(&format!("hurt-armor {:08x}", f32_bits(v))) } fn armor_value(&mut self) -> io::Result { self.query("armor")?; @@ -115,8 +109,8 @@ impl DamageReductionWorld for World<'_> { Ok(0.0) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let slots: Value = serde_json::from_str(&fs::read_to_string(dir.join("slots.json"))?)?; let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); @@ -139,7 +133,7 @@ fn main() -> Result<(), Box> { } else { damage_reduction::after_magic(&mut w, d) }; - r.and_then(|v| writeln!(w.out, "float {:08x}", bits(v))) + r.and_then(|v| writeln!(w.out, "float {:08x}", f32_bits(v))) }; writeln!( w.out, diff --git a/crates/horizon-world/examples/damage_source_fixture.rs b/crates/horizon-world/examples/probe/damage_source_fixture.rs similarity index 94% rename from crates/horizon-world/examples/damage_source_fixture.rs rename to crates/horizon-world/examples/probe/damage_source_fixture.rs index 7e8bfdaee..8599e3cac 100644 --- a/crates/horizon-world/examples/damage_source_fixture.rs +++ b/crates/horizon-world/examples/probe/damage_source_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_world::damage_source::{Catalog, EntityKind, SourceWorld}; use serde_json::Value; use std::{ @@ -11,21 +12,14 @@ fn number(v: &Value) -> f64 { fn position(v: &Value) -> [f64; 3] { std::array::from_fn(|i| number(&v[i])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } -} fn vec(v: Option<[f64; 3]>) -> String { match v { None => "none".into(), Some(v) => format!( "{:016x} {:016x} {:016x}", - bits(v[0]), - bits(v[1]), - bits(v[2]) + f64_bits(v[0]), + f64_bits(v[1]), + f64_bits(v[2]) ), } } @@ -85,8 +79,8 @@ impl SourceWorld for World<'_> { Ok(self.state()["creative"][id].as_bool().unwrap()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let catalog = Catalog::from_json( &serde_json::from_str(&fs::read_to_string(dir.join("catalog.json"))?)?, diff --git a/crates/horizon-world/examples/datafix_world.rs b/crates/horizon-world/examples/probe/datafix_world.rs similarity index 92% rename from crates/horizon-world/examples/datafix_world.rs rename to crates/horizon-world/examples/probe/datafix_world.rs index d3e189d85..f2e119d42 100644 --- a/crates/horizon-world/examples/datafix_world.rs +++ b/crates/horizon-world/examples/probe/datafix_world.rs @@ -4,7 +4,7 @@ //! With a TARGET DataVersion only the data fixes up to it run, on a world in the //! layout of before 1.16. use horizon_world::datafix::files; -use std::{env, fs, io, path::Path, process::ExitCode}; +use std::{fs, io, path::Path, process::ExitCode}; fn copy(from: &Path, to: &Path) -> io::Result<()> { fs::create_dir_all(to)?; @@ -20,8 +20,8 @@ fn copy(from: &Path, to: &Path) -> io::Result<()> { Ok(()) } -fn main() -> ExitCode { - let args: Vec = env::args().skip(1).collect(); +pub fn main() -> ExitCode { + let args: Vec = crate::args().skip(1).collect(); let (input, output, target) = match args.as_slice() { [input, output] => (input, output, None), [input, output, target] => (input, output, target.parse::().ok()), diff --git a/crates/horizon-world/examples/decoration_fixture.rs b/crates/horizon-world/examples/probe/decoration_fixture.rs similarity index 98% rename from crates/horizon-world/examples/decoration_fixture.rs rename to crates/horizon-world/examples/probe/decoration_fixture.rs index 57c33d24b..1d8e53561 100644 --- a/crates/horizon-world/examples/decoration_fixture.rs +++ b/crates/horizon-world/examples/probe/decoration_fixture.rs @@ -102,8 +102,8 @@ impl PlacementContext for World<'_, W> { .is_some_and(|steps| steps.iter().flatten().any(|id| *id == feature))) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/decoration_region_fixture.rs b/crates/horizon-world/examples/probe/decoration_region_fixture.rs similarity index 98% rename from crates/horizon-world/examples/decoration_region_fixture.rs rename to crates/horizon-world/examples/probe/decoration_region_fixture.rs index db1fb4206..bad115a50 100644 --- a/crates/horizon-world/examples/decoration_region_fixture.rs +++ b/crates/horizon-world/examples/probe/decoration_region_fixture.rs @@ -1,5 +1,4 @@ -#[path = "support/decoration_storage.rs"] -mod storage; +use crate::support::decoration_storage as storage; use horizon_core::{ biome::obfuscate_seed, position::{BlockPos, ChunkPos}, @@ -292,8 +291,8 @@ fn fixture( } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let (registry, states) = storage::load(dir)?; let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); diff --git a/crates/horizon-world/examples/probe/dispatch.rs b/crates/horizon-world/examples/probe/dispatch.rs new file mode 100644 index 000000000..0b396edab --- /dev/null +++ b/crates/horizon-world/examples/probe/dispatch.rs @@ -0,0 +1,40 @@ +//! How the probe binary runs a probe. main.rs lists the probes and nothing else (tools/parity.py leaves it out of +//! the harnesses' dependencies); code every probe relies on goes here. +use std::process::ExitCode; + +/// `probes! { a, b, }` declares the binary's `main`, which runs the probe module named by its first argument. +macro_rules! probes { + ($($name:ident,)*) => { + fn run(name: &str) -> Option { + use std::process::Termination; + Some(match name { + $(stringify!($name) => $name::main().report(),)* + _ => return None, + }) + } + + fn main() -> std::process::ExitCode { + dispatch::main(&[$(stringify!($name)),*], run) + } + }; +} + +/// The probe's command line as its own example saw it: the program, then the arguments after the probe's name. +pub fn args() -> std::vec::IntoIter { + let mut args: Vec = std::env::args().collect(); + if args.len() > 1 { + args.remove(1); + } + args.into_iter() +} + +pub fn main(names: &[&str], run: fn(&str) -> Option) -> ExitCode { + let name = std::env::args().nth(1).unwrap_or_default(); + run(&name).unwrap_or_else(|| { + eprintln!( + "usage: probe [arguments...]\nprobes: {}", + names.join(" ") + ); + ExitCode::from(2) + }) +} diff --git a/crates/horizon-world/examples/dynamic_support_fixture.rs b/crates/horizon-world/examples/probe/dynamic_support_fixture.rs similarity index 79% rename from crates/horizon-world/examples/dynamic_support_fixture.rs rename to crates/horizon-world/examples/probe/dynamic_support_fixture.rs index a321f97d0..84a176ea4 100644 --- a/crates/horizon-world/examples/dynamic_support_fixture.rs +++ b/crates/horizon-world/examples/probe/dynamic_support_fixture.rs @@ -1,4 +1,5 @@ -use horizon_core::geometry::{Aabb, Axis, Direction, VoxelShape}; +use crate::support::shapes::{emit, values}; +use horizon_core::geometry::{Direction, VoxelShape}; use horizon_world::{ block_collision::{DynamicCollisionWorld, ShulkerCollisionState}, block_support::SupportType, @@ -15,70 +16,6 @@ use std::{ io::{self, Write}, path::Path, }; -fn values( - out: &mut impl Write, - label: &str, - values: impl IntoIterator, -) -> io::Result<()> { - write!(out, "{label}")?; - for v in values { - let bits = if v.is_nan() { - 0x7ff8_0000_0000_0000 - } else { - v.to_bits() - }; - write!(out, " {bits:016x}")?; - } - writeln!(out) -} -fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { - values( - out, - label, - [ - b.min(Axis::X), - b.min(Axis::Y), - b.min(Axis::Z), - b.max(Axis::X), - b.max(Axis::Y), - b.max(Axis::Z), - ], - ) -} -fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { - writeln!( - out, - "shape {} {} {}", - shape.is_empty(), - shape.boxes().len(), - shape.is_cube() - )?; - for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { - values(out, name, shape.coordinates(axis).iter().copied())?; - } - let axes = shape.cube_coordinate_axes(); - writeln!( - out, - "axes {}", - u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) - )?; - values( - out, - "extrema", - Axis::ALL - .map(|a| shape.min(a)) - .into_iter() - .chain(Axis::ALL.map(|a| shape.max(a))), - )?; - match shape.bounds() { - Some(b) => box_values(out, "bounds", b)?, - None => writeln!(out, "bounds none")?, - } - for b in shape.boxes() { - box_values(out, "box", *b)?; - } - Ok(()) -} struct World<'a, W> { collisions: &'a CachedCollisionRegistry<'a>, pistons: &'a PistonBlockBindings<'a>, @@ -152,8 +89,8 @@ impl PistonCollisionWorld for World<'_, W> { .map_err(io::Error::other) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts.json"))?)?; let states = facts["states"] diff --git a/crates/horizon-world/examples/edge_backoff_fixture.rs b/crates/horizon-world/examples/probe/edge_backoff_fixture.rs similarity index 85% rename from crates/horizon-world/examples/edge_backoff_fixture.rs rename to crates/horizon-world/examples/probe/edge_backoff_fixture.rs index f12ce4431..a805cbb1e 100644 --- a/crates/horizon-world/examples/edge_backoff_fixture.rs +++ b/crates/horizon-world/examples/probe/edge_backoff_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::geometry::{Aabb, Axis, Vec3}; use horizon_world::edge_backoff::{EdgeBackoffInput, EdgeBackoffWorld, back_off_from_edge}; use serde_json::Value; @@ -12,13 +13,6 @@ fn number(v: &Value) -> f64 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} struct World<'a> { input: &'a Value, out: &'a mut dyn Write, @@ -56,12 +50,12 @@ impl EdgeBackoffWorld for World<'_> { fn no_collision(&mut self, b: Aabb) -> io::Result { self.query(format!( "clear {:016x} {:016x} {:016x} {:016x} {:016x} {:016x}", - bits(b.min(Axis::X)), - bits(b.min(Axis::Y)), - bits(b.min(Axis::Z)), - bits(b.max(Axis::X)), - bits(b.max(Axis::Y)), - bits(b.max(Axis::Z)) + f64_bits(b.min(Axis::X)), + f64_bits(b.min(Axis::Y)), + f64_bits(b.min(Axis::Z)), + f64_bits(b.max(Axis::X)), + f64_bits(b.max(Axis::Y)), + f64_bits(b.max(Axis::Z)) ))?; let p = self.probes; self.probes += 1; @@ -73,8 +67,8 @@ impl EdgeBackoffWorld for World<'_> { .unwrap_or(false)) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -105,9 +99,9 @@ fn main() -> Result<(), Box> { Ok(v) => writeln!( world.out, "movement {:016x} {:016x} {:016x}", - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) )?, Err(_) => writeln!(world.out, "error")?, }; diff --git a/crates/horizon-world/examples/effect_attribute_modifiers_fixture.rs b/crates/horizon-world/examples/probe/effect_attribute_modifiers_fixture.rs similarity index 93% rename from crates/horizon-world/examples/effect_attribute_modifiers_fixture.rs rename to crates/horizon-world/examples/probe/effect_attribute_modifiers_fixture.rs index 8616303de..160dcdc28 100644 --- a/crates/horizon-world/examples/effect_attribute_modifiers_fixture.rs +++ b/crates/horizon-world/examples/probe/effect_attribute_modifiers_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_hex; use horizon_world::{ attributes::{AttributeError, Definition, Instance, Modifier, Observer, Operation}, effect_attribute_modifiers::{self as effects, Definitions, Error, ModifierWorld, Template}, @@ -24,21 +25,11 @@ enum Stop { Callback, Duplicate, } -fn bits(v: f64) -> String { - format!( - "{:016x}", - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } - ) -} fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } fn desc(m: &Modifier) -> String { - format!("{}:{}:{}", m.id(), bits(m.amount()), m.operation() as u8) + format!("{}:{}:{}", m.id(), f64_hex(m.amount()), m.operation() as u8) } fn key_desc(k: Option<&Key>) -> String { k.map_or("null".into(), |k| k.id.to_string()) @@ -66,7 +57,7 @@ impl Shared { .iter() .map(|(k, v)| { let v = v.as_ref().map_or("null".into(), |t| { - format!("{}:{}:{}", t.id(), bits(t.amount()), t.operation() as u8) + format!("{}:{}:{}", t.id(), f64_hex(t.amount()), t.operation() as u8) }); format!("{}={v}", key_desc(k.as_ref())) }) @@ -126,9 +117,9 @@ impl Shared { fn state(&mut self, id: usize, a: &Instance) { self.logs.push(format!( "instance {id} {} {} {} | {} | {}", - bits(a.base_value()), + f64_hex(a.base_value()), a.is_dirty(), - bits(a.cached_value()), + f64_hex(a.cached_value()), self.refs(a.modifiers()), self.refs(a.permanent_modifiers()) )); @@ -153,7 +144,7 @@ impl Observer for Dirty<'_> { if self.shared.op["read"].as_bool().unwrap() { self.shared .logs - .push(format!("observed {}", bits(a.value()))); + .push(format!("observed {}", f64_hex(a.value()))); } Ok(()) } @@ -228,8 +219,8 @@ fn error(e: Error) -> &'static str { Error::World(Stop::Duplicate) => "duplicate", } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -316,10 +307,10 @@ fn main() -> Result<(), Box> { } "value" => { let id = op["target"].as_u64().unwrap() as usize; - world - .shared - .logs - .push(format!("value {id} {}", bits(world.instances[id].value()))); + world.shared.logs.push(format!( + "value {id} {}", + f64_hex(world.instances[id].value()) + )); Ok(()) } _ => { diff --git a/crates/horizon-world/examples/effect_notifications_fixture.rs b/crates/horizon-world/examples/probe/effect_notifications_fixture.rs similarity index 99% rename from crates/horizon-world/examples/effect_notifications_fixture.rs rename to crates/horizon-world/examples/probe/effect_notifications_fixture.rs index 248c77a97..195fa9b4b 100644 --- a/crates/horizon-world/examples/effect_notifications_fixture.rs +++ b/crates/horizon-world/examples/probe/effect_notifications_fixture.rs @@ -494,9 +494,9 @@ fn run(f: Value, out: &mut dyn Write) { w.all(&s); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); - let side = std::env::args().nth(2).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); + let side = crate::args().nth(2).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{side}.txt")))?); for line in fs::read_to_string(dir.join(format!("inputs-{side}.txt")))?.lines() { diff --git a/crates/horizon-world/examples/effect_sync_fixture.rs b/crates/horizon-world/examples/probe/effect_sync_fixture.rs similarity index 99% rename from crates/horizon-world/examples/effect_sync_fixture.rs rename to crates/horizon-world/examples/probe/effect_sync_fixture.rs index 6c7b5f3ae..9c8a2aa09 100644 --- a/crates/horizon-world/examples/effect_sync_fixture.rs +++ b/crates/horizon-world/examples/probe/effect_sync_fixture.rs @@ -330,8 +330,8 @@ impl EffectSyncWorld for World<'_> { sync::update_invisibility(s, self) } } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let dir = Path::new(&args[1]); let metadata: Value = serde_json::from_str(&fs::read_to_string(dir.join("catalog.json"))?)?; let catalog = Catalog::from_json(&metadata)?; diff --git a/crates/horizon-world/examples/entity_attribute_fixture.rs b/crates/horizon-world/examples/probe/entity_attribute_fixture.rs similarity index 92% rename from crates/horizon-world/examples/entity_attribute_fixture.rs rename to crates/horizon-world/examples/probe/entity_attribute_fixture.rs index eb1bc8358..e5fe13b98 100644 --- a/crates/horizon-world/examples/entity_attribute_fixture.rs +++ b/crates/horizon-world/examples/probe/entity_attribute_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_world::attributes::{ AttributeError, Modifier, Operation, entity::{Catalog, LookupError}, @@ -12,17 +13,10 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } -} fn lookup(out: &mut dyn Write, label: &str, result: Result) -> io::Result<()> { match result { Ok(v) => { - writeln!(out, "{label} {:016x}", bits(v))?; + writeln!(out, "{label} {:016x}", f64_bits(v))?; writeln!(out, "ok") } Err(e) => writeln!( @@ -36,8 +30,8 @@ fn lookup(out: &mut dyn Write, label: &str, result: Result) -> ), } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let catalog = Arc::new(Catalog::from_json(&serde_json::from_str( &fs::read_to_string(dir.join("catalog.json"))?, @@ -114,9 +108,9 @@ fn main() -> Result<(), Box> { writeln!( out, "state {i} {:016x} {} {:016x} {} {} {} {}", - bits(a.base_value()), + f64_bits(a.base_value()), a.is_dirty(), - bits(a.cached_value()), + f64_bits(a.cached_value()), map.needs_update(id), map.needs_sync(id), a.modifiers().len(), diff --git a/crates/horizon-world/examples/entity_collision_fixture.rs b/crates/horizon-world/examples/probe/entity_collision_fixture.rs similarity index 69% rename from crates/horizon-world/examples/entity_collision_fixture.rs rename to crates/horizon-world/examples/probe/entity_collision_fixture.rs index edf258069..d801e7d34 100644 --- a/crates/horizon-world/examples/entity_collision_fixture.rs +++ b/crates/horizon-world/examples/probe/entity_collision_fixture.rs @@ -1,4 +1,5 @@ -use horizon_core::geometry::{Aabb, Axis, Vec3, VoxelShape}; +use crate::support::shapes::{box_values, emit}; +use horizon_core::geometry::{Aabb, Vec3}; use horizon_world::{ entity_collision::{CollisionCandidate, EntityCollisionWorld, entity_collision_shapes}, entity_obstruction::EntityIdentity, @@ -12,70 +13,6 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn values( - out: &mut impl Write, - label: &str, - values: impl IntoIterator, -) -> io::Result<()> { - write!(out, "{label}")?; - for v in values { - let bits = if v.is_nan() { - 0x7ff8_0000_0000_0000 - } else { - v.to_bits() - }; - write!(out, " {bits:016x}")?; - } - writeln!(out) -} -fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { - values( - out, - label, - [ - b.min(Axis::X), - b.min(Axis::Y), - b.min(Axis::Z), - b.max(Axis::X), - b.max(Axis::Y), - b.max(Axis::Z), - ], - ) -} -fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { - writeln!( - out, - "shape {} {} {}", - shape.is_empty(), - shape.boxes().len(), - shape.is_cube() - )?; - for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { - values(out, name, shape.coordinates(axis).iter().copied())?; - } - let axes = shape.cube_coordinate_axes(); - writeln!( - out, - "axes {}", - u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) - )?; - values( - out, - "extrema", - Axis::ALL - .map(|a| shape.min(a)) - .into_iter() - .chain(Axis::ALL.map(|a| shape.max(a))), - )?; - match shape.bounds() { - Some(b) => box_values(out, "bounds", b)?, - None => writeln!(out, "bounds none")?, - } - for b in shape.boxes() { - box_values(out, "box", *b)?; - } - Ok(()) -} fn bounds(v: &Value) -> Aabb { Aabb::new( Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])), @@ -142,8 +79,8 @@ impl EntityCollisionWorld for World<'_, W> { && source.is_none_or(|id| self.entities[id.0 as usize - 1].root != entity.root)) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/entity_fluid_fixture.rs b/crates/horizon-world/examples/probe/entity_fluid_fixture.rs similarity index 96% rename from crates/horizon-world/examples/entity_fluid_fixture.rs rename to crates/horizon-world/examples/probe/entity_fluid_fixture.rs index 1178c63bf..d897eea1c 100644 --- a/crates/horizon-world/examples/entity_fluid_fixture.rs +++ b/crates/horizon-world/examples/probe/entity_fluid_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::{f64_bits, position}; use horizon_core::{ geometry::{Aabb, Vec3}, position::BlockPos, @@ -28,26 +29,17 @@ fn single(v: &Value) -> f32 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } -} fn show(v: Vec3) -> String { - format!("{:016x} {:016x} {:016x}", bits(v.x), bits(v.y), bits(v.z)) + format!( + "{:016x} {:016x} {:016x}", + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) + ) } fn pos(p: BlockPos) -> String { format!("{} {} {}", p.x, p.y, p.z) } -fn position(v: &Value) -> BlockPos { - BlockPos::new( - v[0].as_i64().unwrap() as i32, - v[1].as_i64().unwrap() as i32, - v[2].as_i64().unwrap() as i32, - ) -} #[derive(Clone, Copy, Default)] struct Tick { touch: bool, @@ -319,8 +311,8 @@ fn limit_checks(template: &Value, states: [FluidState; 5]) { assert!(!interaction.update(&mut world, false, 0).unwrap()); assert!(interaction.trackers().is_empty()); } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); let load = |n: &str| -> Result<_, Box> { @@ -446,7 +438,7 @@ fn main() -> Result<(), Box> { w.out, "tracker {} {:016x} {}", t.fluid as u8, - bits(t.height), + f64_bits(t.height), t.eyes_inside )?; } @@ -455,7 +447,7 @@ fn main() -> Result<(), Box> { w.out, "current {} {:016x} {} {}", tag.0, - bits(c.height), + f64_bits(c.height), show(c.accumulated), c.count )?; @@ -465,7 +457,7 @@ fn main() -> Result<(), Box> { let height = interaction.fluid_height(&w, tag); let inside = interaction.is_in_fluid(&w, tag); let eyes = interaction.is_eye_in_fluid(&w, tag); - writeln!(w.out, "tag {t} {:016x} {inside} {eyes}", bits(height))?; + writeln!(w.out, "tag {t} {:016x} {inside} {eyes}", f64_bits(height))?; } writeln!(w.out, "final {}", show(w.velocity))?; writeln!(w.out, "queries {}", w.calls)?; @@ -476,7 +468,7 @@ fn main() -> Result<(), Box> { "tick {} {} {:016x}", tick.touch, tick.first, - bits(tick.fall) + f64_bits(tick.fall) )?; } } diff --git a/crates/horizon-world/examples/entity_move_fixture.rs b/crates/horizon-world/examples/probe/entity_move_fixture.rs similarity index 94% rename from crates/horizon-world/examples/entity_move_fixture.rs rename to crates/horizon-world/examples/probe/entity_move_fixture.rs index fbcbb8ed1..c31e485a9 100644 --- a/crates/horizon-world/examples/entity_move_fixture.rs +++ b/crates/horizon-world/examples/probe/entity_move_fixture.rs @@ -1,5 +1,7 @@ +use crate::support::common::f64_bits; +use crate::support::shapes::bounds; use horizon_core::{ - geometry::{Aabb, Axis, Vec3, VoxelShape, resolve_shape_movement}, + geometry::{Aabb, Vec3, VoxelShape, resolve_shape_movement}, position::BlockPos, }; use horizon_world::{ @@ -23,30 +25,12 @@ fn single(v: &Value) -> f32 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn vec(label: &str, v: Vec3) -> String { format!( "{label} {:016x} {:016x} {:016x}", - bits(v.x), - bits(v.y), - bits(v.z) - ) -} -fn bounds(label: &str, b: Aabb) -> String { - format!( - "{label} {:016x} {:016x} {:016x} {:016x} {:016x} {:016x}", - bits(b.min(Axis::X)), - bits(b.min(Axis::Y)), - bits(b.min(Axis::Z)), - bits(b.max(Axis::X)), - bits(b.max(Axis::Y)), - bits(b.max(Axis::Z)) + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) ) } fn pos(p: BlockPos) -> String { @@ -213,7 +197,7 @@ impl EntityMoveWorld for World<'_> { _: BlockStateId, p: BlockPos, ) -> io::Result<()> { - self.query(format!("fall {:016x} {ground} {}", bits(dy), pos(p)))?; + self.query(format!("fall {:016x} {ground} {}", f64_bits(dy), pos(p)))?; if self.flag("fall_mutates") { self.fall = 3.0; self.velocity = Vec3::new(17.0, 18.0, 19.0); @@ -327,8 +311,8 @@ impl RestitutionWorld for Bounce<'_, '_> { self.0.set_velocity(v) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -399,7 +383,7 @@ fn main() -> Result<(), Box> { w.flags.minor, w.grounded, w.removed, - bits(w.fall) + f64_bits(w.fall) )?; writeln!(w.out, "history {}", w.history.records().len())?; for r in w.history.records() { diff --git a/crates/horizon-world/examples/entity_obstruction_fixture.rs b/crates/horizon-world/examples/probe/entity_obstruction_fixture.rs similarity index 96% rename from crates/horizon-world/examples/entity_obstruction_fixture.rs rename to crates/horizon-world/examples/probe/entity_obstruction_fixture.rs index ef8f0acc8..0d585170b 100644 --- a/crates/horizon-world/examples/entity_obstruction_fixture.rs +++ b/crates/horizon-world/examples/probe/entity_obstruction_fixture.rs @@ -69,8 +69,8 @@ fn bbox(v: &Value) -> Aabb { Vec3::new(values[3], values[4], values[5]), ) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/extra_items_fixture.rs b/crates/horizon-world/examples/probe/extra_items_fixture.rs similarity index 99% rename from crates/horizon-world/examples/extra_items_fixture.rs rename to crates/horizon-world/examples/probe/extra_items_fixture.rs index 0cbdd98d0..f317e318c 100644 --- a/crates/horizon-world/examples/extra_items_fixture.rs +++ b/crates/horizon-world/examples/probe/extra_items_fixture.rs @@ -392,8 +392,8 @@ impl AfterUseWorld for World { c.apply(self, original) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/face_support_fixture.rs b/crates/horizon-world/examples/probe/face_support_fixture.rs similarity index 60% rename from crates/horizon-world/examples/face_support_fixture.rs rename to crates/horizon-world/examples/probe/face_support_fixture.rs index e6bee0e7a..28e6fa81d 100644 --- a/crates/horizon-world/examples/face_support_fixture.rs +++ b/crates/horizon-world/examples/probe/face_support_fixture.rs @@ -1,4 +1,5 @@ -use horizon_core::geometry::{Aabb, Axis, Direction, ShapeOp, Vec3, VoxelShape}; +use crate::support::shapes::emit; +use horizon_core::geometry::{Aabb, Direction, ShapeOp, Vec3, VoxelShape}; use horizon_world::block_support::SupportType; use serde_json::Value; use std::{ @@ -13,72 +14,8 @@ fn numbers(v: &Value) -> Vec { .map(|v| f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap())) .collect() } -fn values( - out: &mut impl Write, - label: &str, - values: impl IntoIterator, -) -> io::Result<()> { - write!(out, "{label}")?; - for v in values { - let bits = if v.is_nan() { - 0x7ff8_0000_0000_0000 - } else { - v.to_bits() - }; - write!(out, " {bits:016x}")?; - } - writeln!(out) -} -fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { - values( - out, - label, - [ - b.min(Axis::X), - b.min(Axis::Y), - b.min(Axis::Z), - b.max(Axis::X), - b.max(Axis::Y), - b.max(Axis::Z), - ], - ) -} -fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { - writeln!( - out, - "shape {} {} {}", - shape.is_empty(), - shape.boxes().len(), - shape.is_cube() - )?; - for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { - values(out, name, shape.coordinates(axis).iter().copied())?; - } - let axes = shape.cube_coordinate_axes(); - writeln!( - out, - "axes {}", - u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) - )?; - values( - out, - "extrema", - Axis::ALL - .map(|a| shape.min(a)) - .into_iter() - .chain(Axis::ALL.map(|a| shape.max(a))), - )?; - match shape.bounds() { - Some(b) => box_values(out, "bounds", b)?, - None => writeln!(out, "bounds none")?, - } - for b in shape.boxes() { - box_values(out, "box", *b)?; - } - Ok(()) -} -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/face_visibility_fixture.rs b/crates/horizon-world/examples/probe/face_visibility_fixture.rs similarity index 96% rename from crates/horizon-world/examples/face_visibility_fixture.rs rename to crates/horizon-world/examples/probe/face_visibility_fixture.rs index b2ef8716c..3c653f1e1 100644 --- a/crates/horizon-world/examples/face_visibility_fixture.rs +++ b/crates/horizon-world/examples/probe/face_visibility_fixture.rs @@ -12,8 +12,8 @@ use std::{ io::{BufRead, BufReader, BufWriter, Write}, path::Path, }; -fn main() -> Result<(), Box> { - let path = std::env::args().nth(1).ok_or("private fixture directory")?; +pub fn main() -> Result<(), Box> { + let path = crate::args().nth(1).ok_or("private fixture directory")?; let dir = Path::new(&path); let read = |name: &str| -> Result> { Ok( diff --git a/crates/horizon-world/examples/fall_damage_fixture.rs b/crates/horizon-world/examples/probe/fall_damage_fixture.rs similarity index 89% rename from crates/horizon-world/examples/fall_damage_fixture.rs rename to crates/horizon-world/examples/probe/fall_damage_fixture.rs index 092208c95..573b9c1e9 100644 --- a/crates/horizon-world/examples/fall_damage_fixture.rs +++ b/crates/horizon-world/examples/probe/fall_damage_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::fall_damage::{FallDamageWorld, check_fall_damage}; use serde_json::Value; @@ -9,13 +10,6 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn support(v: &Value) -> Option { if v.is_null() { None @@ -66,7 +60,7 @@ impl FallDamageWorld for World<'_> { p.x, p.y, p.z, - bits(distance) + f64_bits(distance) ))?; if self.input["mutate"].as_bool().unwrap() { self.fall = 17.25; @@ -88,9 +82,9 @@ impl FallDamageWorld for World<'_> { fn hit_ground(&mut self, p: Vec3, s: u8) -> io::Result<()> { self.query(format!( "hit-ground {:016x} {:016x} {:016x} {}", - bits(p.x), - bits(p.y), - bits(p.z), + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z), if s == 1 { "queried" } else { "input" } )) } @@ -100,8 +94,8 @@ impl FallDamageWorld for World<'_> { Ok(()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -130,10 +124,10 @@ fn main() -> Result<(), Box> { writeln!( world.out, "final {:016x} {:016x} {:016x} {:016x}", - bits(world.fall), - bits(p.x), - bits(p.y), - bits(p.z) + f64_bits(world.fall), + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z) )?; if let Some(p) = world.support { writeln!(world.out, "support {} {} {}", p.x, p.y, p.z)?; diff --git a/crates/horizon-world/examples/feature_catalog_fixture.rs b/crates/horizon-world/examples/probe/feature_catalog_fixture.rs similarity index 94% rename from crates/horizon-world/examples/feature_catalog_fixture.rs rename to crates/horizon-world/examples/probe/feature_catalog_fixture.rs index c12b9c1a0..bbc69ffd3 100644 --- a/crates/horizon-world/examples/feature_catalog_fixture.rs +++ b/crates/horizon-world/examples/probe/feature_catalog_fixture.rs @@ -1,4 +1,5 @@ //! Feature world transport retaining ordered mutations and partial failures. +use crate::support::common::tag; use horizon_core::random::{LegacyRandom, RandomSource, WorldgenRandom, XoroshiroRandom}; use horizon_world::{ DATA_VERSION, @@ -178,19 +179,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -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(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - _ => panic!("invalid registry metadata"), - } -} -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let resources: Value = serde_json::from_str(&fs::read_to_string(dir.join("catalog.json"))?)?; let definitions = |name: &str| { diff --git a/crates/horizon-world/examples/feature_graph_fixture.rs b/crates/horizon-world/examples/probe/feature_graph_fixture.rs similarity index 97% rename from crates/horizon-world/examples/feature_graph_fixture.rs rename to crates/horizon-world/examples/probe/feature_graph_fixture.rs index fae5b6e2e..381972f44 100644 --- a/crates/horizon-world/examples/feature_graph_fixture.rs +++ b/crates/horizon-world/examples/probe/feature_graph_fixture.rs @@ -161,8 +161,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let ids: [u32; 5] = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let blocks = ids.map(BlockStateId); diff --git a/crates/horizon-world/examples/feature_placement_fixture.rs b/crates/horizon-world/examples/probe/feature_placement_fixture.rs similarity index 94% rename from crates/horizon-world/examples/feature_placement_fixture.rs rename to crates/horizon-world/examples/probe/feature_placement_fixture.rs index c7500fa4f..5310b240f 100644 --- a/crates/horizon-world/examples/feature_placement_fixture.rs +++ b/crates/horizon-world/examples/probe/feature_placement_fixture.rs @@ -1,6 +1,5 @@ //! Transport for native modifier chains and a feature callback sharing the RNG. -#[path = "support/placement_queries.rs"] -mod queries; +use crate::support::placement_queries as queries; use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; use horizon_world::worldgen::{ anchor::WorldGenerationContext, @@ -74,8 +73,8 @@ fn fixture( writeln!(out.borrow_mut(), "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/feature_region_fixture.rs b/crates/horizon-world/examples/probe/feature_region_fixture.rs similarity index 97% rename from crates/horizon-world/examples/feature_region_fixture.rs rename to crates/horizon-world/examples/probe/feature_region_fixture.rs index a6cb08b10..6a244998d 100644 --- a/crates/horizon-world/examples/feature_region_fixture.rs +++ b/crates/horizon-world/examples/probe/feature_region_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::tag; use horizon_core::random::{LegacyRandom, RandomSource, WorldgenRandom, XoroshiroRandom}; use horizon_world::worldgen::{ anchor::WorldGenerationContext, @@ -66,17 +67,6 @@ impl TerrainBlockStates for Properties<'_> { fn n(v: &Value) -> i32 { v.as_i64().unwrap() as i32 } -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(i) => Tag::Int(i.as_i64().unwrap() as i32), - Value::Object(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - _ => panic!("unsupported registry fixture value"), - } -} fn fixture( f: &Value, registry: &BlockRegistry, @@ -496,8 +486,8 @@ fn query_state( } writeln!(out, "tags {bits}") } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let bundle: Value = serde_json::from_str(&fs::read_to_string(dir.join("tags.json"))?)?; diff --git a/crates/horizon-world/examples/feature_sort_fixture.rs b/crates/horizon-world/examples/probe/feature_sort_fixture.rs similarity index 93% rename from crates/horizon-world/examples/feature_sort_fixture.rs rename to crates/horizon-world/examples/probe/feature_sort_fixture.rs index 6e645601c..370a16325 100644 --- a/crates/horizon-world/examples/feature_sort_fixture.rs +++ b/crates/horizon-world/examples/probe/feature_sort_fixture.rs @@ -7,8 +7,8 @@ use std::{ io::{self, Write}, path::Path, }; -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/fill_layer_fixture.rs b/crates/horizon-world/examples/probe/fill_layer_fixture.rs similarity index 91% rename from crates/horizon-world/examples/fill_layer_fixture.rs rename to crates/horizon-world/examples/probe/fill_layer_fixture.rs index d10cd2b72..e107a6383 100644 --- a/crates/horizon-world/examples/fill_layer_fixture.rs +++ b/crates/horizon-world/examples/probe/fill_layer_fixture.rs @@ -1,4 +1,5 @@ //! Feature world transport retaining ordered mutations and partial failures. +use crate::support::common::tag; use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; use horizon_world::{ DATA_VERSION, @@ -134,19 +135,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -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(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - _ => panic!("invalid registry metadata"), - } -} -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let registry = BlockRegistry::from_nbt(&Tag::compound([ diff --git a/crates/horizon-world/examples/fluid_box_fixture.rs b/crates/horizon-world/examples/probe/fluid_box_fixture.rs similarity index 96% rename from crates/horizon-world/examples/fluid_box_fixture.rs rename to crates/horizon-world/examples/probe/fluid_box_fixture.rs index 50e5b7caf..0b348d7bb 100644 --- a/crates/horizon-world/examples/fluid_box_fixture.rs +++ b/crates/horizon-world/examples/probe/fluid_box_fixture.rs @@ -91,8 +91,8 @@ impl BoatFluidBoxWorld for World<'_> { self.boat } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/fluid_fixture.rs b/crates/horizon-world/examples/probe/fluid_fixture.rs similarity index 88% rename from crates/horizon-world/examples/fluid_fixture.rs rename to crates/horizon-world/examples/probe/fluid_fixture.rs index 466b85230..1c5ed4a85 100644 --- a/crates/horizon-world/examples/fluid_fixture.rs +++ b/crates/horizon-world/examples/probe/fluid_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::tag; use horizon_world::{ DATA_VERSION, fluid::{FluidBlockBindings, FluidHeightWorld, FluidKind, FluidState, FluidStateTable}, @@ -40,19 +41,8 @@ impl FluidHeightWorld for World<'_, W> { Ok(self.sturdy) } } -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(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - _ => panic!("invalid registry metadata"), - } -} -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let registry = BlockRegistry::from_nbt(&Tag::compound([ diff --git a/crates/horizon-world/examples/fluid_flow_fixture.rs b/crates/horizon-world/examples/probe/fluid_flow_fixture.rs similarity index 96% rename from crates/horizon-world/examples/fluid_flow_fixture.rs rename to crates/horizon-world/examples/probe/fluid_flow_fixture.rs index 4da9f6a07..ec7810509 100644 --- a/crates/horizon-world/examples/fluid_flow_fixture.rs +++ b/crates/horizon-world/examples/probe/fluid_flow_fixture.rs @@ -60,8 +60,8 @@ impl FluidFlowWorld for World<'_> { Ok(self.f["states"][s]["faces"].as_u64().unwrap() & (1 << (d as u8)) != 0) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/fluid_occupancy_fixture.rs b/crates/horizon-world/examples/probe/fluid_occupancy_fixture.rs similarity index 98% rename from crates/horizon-world/examples/fluid_occupancy_fixture.rs rename to crates/horizon-world/examples/probe/fluid_occupancy_fixture.rs index bb178e300..7fc884f49 100644 --- a/crates/horizon-world/examples/fluid_occupancy_fixture.rs +++ b/crates/horizon-world/examples/probe/fluid_occupancy_fixture.rs @@ -67,8 +67,8 @@ impl FluidOccupancyWorld for World<'_, '_> { Ok(self.min + self.height - 1) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let registry = BlockRegistry::from_nbt( &nbt::read_named( diff --git a/crates/horizon-world/examples/fluid_shape_fixture.rs b/crates/horizon-world/examples/probe/fluid_shape_fixture.rs similarity index 96% rename from crates/horizon-world/examples/fluid_shape_fixture.rs rename to crates/horizon-world/examples/probe/fluid_shape_fixture.rs index 7e42203ec..9c14d5849 100644 --- a/crates/horizon-world/examples/fluid_shape_fixture.rs +++ b/crates/horizon-world/examples/probe/fluid_shape_fixture.rs @@ -34,8 +34,8 @@ impl FluidHeightWorld for World<'_> { panic!("ray shape does not use camera immersion support") } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/food_fixture.rs b/crates/horizon-world/examples/probe/food_fixture.rs similarity index 90% rename from crates/horizon-world/examples/food_fixture.rs rename to crates/horizon-world/examples/probe/food_fixture.rs index d0645ea44..c12106dfb 100644 --- a/crates/horizon-world/examples/food_fixture.rs +++ b/crates/horizon-world/examples/probe/food_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::food::{Difficulty, FoodData, FoodWorld}; use serde_json::Value; use std::{ @@ -8,13 +9,6 @@ use std::{ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn state(v: &Value) -> FoodData { FoodData { food: v["food"].as_i64().unwrap() as i32, @@ -72,7 +66,7 @@ impl FoodWorld for World<'_> { Ok(self.world()["hurt"].as_bool().unwrap()) } fn heal(&mut self, f: &mut FoodData, v: f32) -> io::Result<()> { - self.query(f, &format!("heal {:08x}", bits(v))) + self.query(f, &format!("heal {:08x}", f32_bits(v))) } fn health(&mut self, f: &mut FoodData) -> io::Result { self.query(f, "health")?; @@ -81,11 +75,11 @@ impl FoodWorld for World<'_> { fn hurt_starvation(&mut self, _: (), f: &mut FoodData, v: f32) -> io::Result<()> { self.query(f, "damage-sources")?; self.query(f, "starve-source")?; - self.query(f, &format!("hurt {:08x}", bits(v))) + self.query(f, &format!("hurt {:08x}", f32_bits(v))) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -123,8 +117,8 @@ fn main() -> Result<(), Box> { w.out, "state {} {:08x} {:08x} {} {} {}", food.food, - bits(food.saturation), - bits(food.exhaustion), + f32_bits(food.saturation), + f32_bits(food.exhaustion), food.timer, food.has_enough_food(), food.needs_food() @@ -135,8 +129,8 @@ fn main() -> Result<(), Box> { w.out, "final {} {:08x} {:08x} {}", food.food, - bits(food.saturation), - bits(food.exhaustion), + f32_bits(food.saturation), + f32_bits(food.exhaustion), food.timer )?; writeln!(w.out, "queries {}", w.calls)?; diff --git a/crates/horizon-world/examples/food_properties_fixture.rs b/crates/horizon-world/examples/probe/food_properties_fixture.rs similarity index 98% rename from crates/horizon-world/examples/food_properties_fixture.rs rename to crates/horizon-world/examples/probe/food_properties_fixture.rs index 59524b0dc..50b88bccc 100644 --- a/crates/horizon-world/examples/food_properties_fixture.rs +++ b/crates/horizon-world/examples/probe/food_properties_fixture.rs @@ -160,8 +160,8 @@ fn run(f: Value, out: &mut dyn Write, make: fn(i64) -> R) { writeln!(w.out, "random {i} {} {}", r.next_long(), r.next_long()).unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/food_storage_fixture.rs b/crates/horizon-world/examples/probe/food_storage_fixture.rs similarity index 87% rename from crates/horizon-world/examples/food_storage_fixture.rs rename to crates/horizon-world/examples/probe/food_storage_fixture.rs index 4aafe920e..13e9a52dc 100644 --- a/crates/horizon-world/examples/food_storage_fixture.rs +++ b/crates/horizon-world/examples/probe/food_storage_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::{ food::FoodData, nbt::{Compound, Tag}, @@ -17,13 +18,6 @@ const KEYS: [&str; 4] = [ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn tag(v: &Value) -> Option { let value = &v["value"]; Some(match v["type"].as_i64().unwrap() { @@ -49,8 +43,8 @@ fn tag(v: &Value) -> Option { _ => panic!("tag type"), }) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -82,8 +76,8 @@ fn main() -> Result<(), Box> { "state {} {} {:08x} {:08x}", food.food, food.timer, - bits(food.saturation), - bits(food.exhaustion) + f32_bits(food.saturation), + f32_bits(food.exhaustion) )?; let mut saved = Compound::new(); saved.insert("unrelated".into(), Tag::Int(42)); @@ -96,7 +90,7 @@ fn main() -> Result<(), Box> { for key in KEYS { match saved[&key.into()] { Tag::Int(v) => writeln!(out, "tag 3 {v}")?, - Tag::Float(v) => writeln!(out, "tag 5 {:08x}", bits(f32::from_bits(v)))?, + Tag::Float(v) => writeln!(out, "tag 5 {:08x}", f32_bits(f32::from_bits(v)))?, _ => panic!("saved type"), } } @@ -106,8 +100,8 @@ fn main() -> Result<(), Box> { "roundtrip {} {} {:08x} {:08x}", food.food, food.timer, - bits(food.saturation), - bits(food.exhaustion) + f32_bits(food.saturation), + f32_bits(food.exhaustion) )?; } Ok(()) diff --git a/crates/horizon-world/examples/ground_state_fixture.rs b/crates/horizon-world/examples/probe/ground_state_fixture.rs similarity index 87% rename from crates/horizon-world/examples/ground_state_fixture.rs rename to crates/horizon-world/examples/probe/ground_state_fixture.rs index 7b41515b3..47611587f 100644 --- a/crates/horizon-world/examples/ground_state_fixture.rs +++ b/crates/horizon-world/examples/probe/ground_state_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{ geometry::{Aabb, Axis, Vec3}, position::BlockPos, @@ -15,13 +16,6 @@ fn number(v: &Value) -> f64 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn position(v: &Value) -> Option { if v.is_null() { None @@ -33,8 +27,8 @@ fn position(v: &Value) -> Option { )) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -62,12 +56,12 @@ fn main() -> Result<(), Box> { writeln!( out, "find {:016x} {:016x} {:016x} {:016x} {:016x} {:016x}", - bits(b.min(Axis::X)), - bits(b.min(Axis::Y)), - bits(b.min(Axis::Z)), - bits(b.max(Axis::X)), - bits(b.max(Axis::Y)), - bits(b.max(Axis::Z)) + f64_bits(b.min(Axis::X)), + f64_bits(b.min(Axis::Y)), + f64_bits(b.min(Axis::Z)), + f64_bits(b.max(Axis::X)), + f64_bits(b.max(Axis::Y)), + f64_bits(b.max(Axis::Z)) )?; let call = calls; calls += 1; diff --git a/crates/horizon-world/examples/height_provider_fixture.rs b/crates/horizon-world/examples/probe/height_provider_fixture.rs similarity index 93% rename from crates/horizon-world/examples/height_provider_fixture.rs rename to crates/horizon-world/examples/probe/height_provider_fixture.rs index 7ada87a18..94b2524f7 100644 --- a/crates/horizon-world/examples/height_provider_fixture.rs +++ b/crates/horizon-world/examples/probe/height_provider_fixture.rs @@ -33,8 +33,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/heightmap_fixture.rs b/crates/horizon-world/examples/probe/heightmap_fixture.rs similarity index 98% rename from crates/horizon-world/examples/heightmap_fixture.rs rename to crates/horizon-world/examples/probe/heightmap_fixture.rs index 35d7bc5c2..14cebbc59 100644 --- a/crates/horizon-world/examples/heightmap_fixture.rs +++ b/crates/horizon-world/examples/probe/heightmap_fixture.rs @@ -187,8 +187,8 @@ fn fixture( } Ok(()) } -fn main() -> Result<(), Box> { - let directory = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let directory = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&directory); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let tags: Value = serde_json::from_str(&fs::read_to_string(dir.join("tags.json"))?)?; diff --git a/crates/horizon-world/examples/interaction_shape_fixture.rs b/crates/horizon-world/examples/probe/interaction_shape_fixture.rs similarity index 90% rename from crates/horizon-world/examples/interaction_shape_fixture.rs rename to crates/horizon-world/examples/probe/interaction_shape_fixture.rs index 60b9742b8..c1ca5700b 100644 --- a/crates/horizon-world/examples/interaction_shape_fixture.rs +++ b/crates/horizon-world/examples/probe/interaction_shape_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{ geometry::{Aabb, Axis, ShapeOp, Vec3, VoxelShape}, position::BlockPos, @@ -20,13 +21,6 @@ fn number(v: &Value) -> f64 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn shape(v: &Value) -> Result> { let mut result = VoxelShape::empty(); for b in v.as_array().unwrap() { @@ -77,8 +71,8 @@ impl RayWorld for World<'_, '_> { panic!("direct interaction clip") } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); let read = |n: &str| -> Result> { @@ -131,12 +125,12 @@ fn main() -> Result<(), Box> { writeln!( out, "box {:016x} {:016x} {:016x} {:016x} {:016x} {:016x}", - bits(b.min(Axis::X)), - bits(b.min(Axis::Y)), - bits(b.min(Axis::Z)), - bits(b.max(Axis::X)), - bits(b.max(Axis::Y)), - bits(b.max(Axis::Z)) + f64_bits(b.min(Axis::X)), + f64_bits(b.min(Axis::Y)), + f64_bits(b.min(Axis::Z)), + f64_bits(b.max(Axis::X)), + f64_bits(b.max(Axis::Y)), + f64_bits(b.max(Axis::Z)) )?; } } @@ -160,9 +154,9 @@ fn main() -> Result<(), Box> { Some(h) => writeln!( out, "hit {:016x} {:016x} {:016x} {} {} {} {} {}", - bits(h.location.x), - bits(h.location.y), - bits(h.location.z), + f64_bits(h.location.x), + f64_bits(h.location.y), + f64_bits(h.location.z), format!("{:?}", h.direction).to_lowercase(), h.block.x, h.block.y, diff --git a/crates/horizon-world/examples/inventory_pickup_fixture.rs b/crates/horizon-world/examples/probe/inventory_pickup_fixture.rs similarity index 99% rename from crates/horizon-world/examples/inventory_pickup_fixture.rs rename to crates/horizon-world/examples/probe/inventory_pickup_fixture.rs index b3f742aa0..58170e871 100644 --- a/crates/horizon-world/examples/inventory_pickup_fixture.rs +++ b/crates/horizon-world/examples/probe/inventory_pickup_fixture.rs @@ -218,8 +218,8 @@ impl horizon_world::inventory_pickup::PickupHooks for World { Ok(self.op["infinite"].as_bool().unwrap()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/inventory_tick_fixture.rs b/crates/horizon-world/examples/probe/inventory_tick_fixture.rs similarity index 98% rename from crates/horizon-world/examples/inventory_tick_fixture.rs rename to crates/horizon-world/examples/probe/inventory_tick_fixture.rs index 974ed6760..1dfb9655e 100644 --- a/crates/horizon-world/examples/inventory_tick_fixture.rs +++ b/crates/horizon-world/examples/probe/inventory_tick_fixture.rs @@ -149,8 +149,8 @@ impl InventoryTickWorld for World { Ok(()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/inventory_use_fixture.rs b/crates/horizon-world/examples/probe/inventory_use_fixture.rs similarity index 99% rename from crates/horizon-world/examples/inventory_use_fixture.rs rename to crates/horizon-world/examples/probe/inventory_use_fixture.rs index 2f5ed557b..f00d97c9f 100644 --- a/crates/horizon-world/examples/inventory_use_fixture.rs +++ b/crates/horizon-world/examples/probe/inventory_use_fixture.rs @@ -230,8 +230,8 @@ impl UseServices for Services { self.event(view, state, &format!("synced {id}")) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/inventory_use_start_fixture.rs b/crates/horizon-world/examples/probe/inventory_use_start_fixture.rs similarity index 99% rename from crates/horizon-world/examples/inventory_use_start_fixture.rs rename to crates/horizon-world/examples/probe/inventory_use_start_fixture.rs index f887e5688..fc46a58b7 100644 --- a/crates/horizon-world/examples/inventory_use_start_fixture.rs +++ b/crates/horizon-world/examples/probe/inventory_use_start_fixture.rs @@ -295,8 +295,8 @@ impl StartServices for Services { self.kinetic_count = 0; } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/item_after_use_fixture.rs b/crates/horizon-world/examples/probe/item_after_use_fixture.rs similarity index 99% rename from crates/horizon-world/examples/item_after_use_fixture.rs rename to crates/horizon-world/examples/probe/item_after_use_fixture.rs index 3daf5dfce..30c35b871 100644 --- a/crates/horizon-world/examples/item_after_use_fixture.rs +++ b/crates/horizon-world/examples/probe/item_after_use_fixture.rs @@ -277,8 +277,8 @@ impl AfterUseWorld for World { c.apply(self, original) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/item_blocking_fixture.rs b/crates/horizon-world/examples/probe/item_blocking_fixture.rs similarity index 95% rename from crates/horizon-world/examples/item_blocking_fixture.rs rename to crates/horizon-world/examples/probe/item_blocking_fixture.rs index c4889925a..e3f622a6d 100644 --- a/crates/horizon-world/examples/item_blocking_fixture.rs +++ b/crates/horizon-world/examples/probe/item_blocking_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_core::geometry::Vec3; use horizon_world::{ blocking_rules::{BlockingRules, DamageReduction, ItemDamageFunction, TypeMatchWorld}, @@ -19,13 +20,6 @@ fn number(v: &Value) -> f64 { fn vec(v: &Value) -> Option { (!v.is_null()).then(|| Vec3::new(number(&v[0]), number(&v[1]), number(&v[2]))) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} struct Component { present: bool, bypass: Option, @@ -154,11 +148,11 @@ impl ItemBlockingWorld for World<'_> { e == 1 } fn block_using_item(&mut self, _: u64, damage: f32, fully: bool) -> io::Result<()> { - self.event(&format!("block-using 0 {:08x} {fully}", bits(damage))) + self.event(&format!("block-using 0 {:08x} {fully}", f32_bits(damage))) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -207,7 +201,7 @@ fn main() -> Result<(), Box> { changed: false, }; match item_blocking::apply(&mut w, single(&f["damage"])) { - Ok(v) => writeln!(w.out, "blocked {:08x}\nresult ok", bits(v))?, + Ok(v) => writeln!(w.out, "blocked {:08x}\nresult ok", f32_bits(v))?, Err(_) => writeln!(w.out, "result error")?, }; writeln!(w.out, "queries {} {}", w.calls, w.changed)?; diff --git a/crates/horizon-world/examples/item_cooldowns_fixture.rs b/crates/horizon-world/examples/probe/item_cooldowns_fixture.rs similarity index 98% rename from crates/horizon-world/examples/item_cooldowns_fixture.rs rename to crates/horizon-world/examples/probe/item_cooldowns_fixture.rs index fb92d462f..e43f1c6bb 100644 --- a/crates/horizon-world/examples/item_cooldowns_fixture.rs +++ b/crates/horizon-world/examples/probe/item_cooldowns_fixture.rs @@ -130,8 +130,8 @@ impl CooldownUser for User<'_> { self.book.add(group(&stack), ticks, self.events) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/item_durability_fixture.rs b/crates/horizon-world/examples/probe/item_durability_fixture.rs similarity index 97% rename from crates/horizon-world/examples/item_durability_fixture.rs rename to crates/horizon-world/examples/probe/item_durability_fixture.rs index f051bb91c..de0af24c3 100644 --- a/crates/horizon-world/examples/item_durability_fixture.rs +++ b/crates/horizon-world/examples/probe/item_durability_fixture.rs @@ -82,8 +82,8 @@ impl DurabilityWorld for World<'_> { self.event(s, "break") } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/item_particles_fixture.rs b/crates/horizon-world/examples/probe/item_particles_fixture.rs similarity index 93% rename from crates/horizon-world/examples/item_particles_fixture.rs rename to crates/horizon-world/examples/probe/item_particles_fixture.rs index 9eead88ca..3b7375e17 100644 --- a/crates/horizon-world/examples/item_particles_fixture.rs +++ b/crates/horizon-world/examples/probe/item_particles_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{ geometry::Vec3, random::{LegacyRandom, RandomSource, XoroshiroRandom}, @@ -22,13 +23,6 @@ fn n(v: &Value, k: &str) -> i32 { fn fl(v: &Value, k: &str) -> f32 { f32::from_bits(v[k].as_u64().unwrap() as u32) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn opt(v: Option<&i32>) -> String { v.map_or("none".into(), i32::to_string) } @@ -141,12 +135,12 @@ impl ItemParticleWorld for World<'_, R> { "particle {level} {} {} {damage} {same} {} {} {} {} {} {}", t.item(), t.count(), - bits(p.x), - bits(p.y), - bits(p.z), - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z), + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) )) } } @@ -178,8 +172,8 @@ fn run(f: Value, out: &mut dyn Write, make: fn(i64) -> R) { writeln!(w.out, "random {i} {} {}", r.next_long(), r.next_long()).unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/item_stack_storage_fixture.rs b/crates/horizon-world/examples/probe/item_stack_storage_fixture.rs similarity index 98% rename from crates/horizon-world/examples/item_stack_storage_fixture.rs rename to crates/horizon-world/examples/probe/item_stack_storage_fixture.rs index bceb9f797..31c741b3e 100644 --- a/crates/horizon-world/examples/item_stack_storage_fixture.rs +++ b/crates/horizon-world/examples/probe/item_stack_storage_fixture.rs @@ -86,8 +86,8 @@ fn append(arena: &mut Vec, copy: CopyResult) -> usize { } } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/item_template_fixture.rs b/crates/horizon-world/examples/probe/item_template_fixture.rs similarity index 98% rename from crates/horizon-world/examples/item_template_fixture.rs rename to crates/horizon-world/examples/probe/item_template_fixture.rs index 6a8df6cc0..b6a538b04 100644 --- a/crates/horizon-world/examples/item_template_fixture.rs +++ b/crates/horizon-world/examples/probe/item_template_fixture.rs @@ -115,8 +115,8 @@ fn all( } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/item_use_catalog_fixture.rs b/crates/horizon-world/examples/probe/item_use_catalog_fixture.rs similarity index 96% rename from crates/horizon-world/examples/item_use_catalog_fixture.rs rename to crates/horizon-world/examples/probe/item_use_catalog_fixture.rs index 406ba521d..7d7871720 100644 --- a/crates/horizon-world/examples/item_use_catalog_fixture.rs +++ b/crates/horizon-world/examples/probe/item_use_catalog_fixture.rs @@ -33,8 +33,8 @@ fn snapshot(out: &mut dyn Write, s: &ItemUseStack<'_>) -> io::Result<()> { s.use_on_release() ) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let catalog = ItemUseCatalog::from_json(&serde_json::from_str(&fs::read_to_string( dir.join("catalog.json"), diff --git a/crates/horizon-world/examples/item_use_fixture.rs b/crates/horizon-world/examples/probe/item_use_fixture.rs similarity index 93% rename from crates/horizon-world/examples/item_use_fixture.rs rename to crates/horizon-world/examples/probe/item_use_fixture.rs index 74436d1f3..8d88aae7a 100644 --- a/crates/horizon-world/examples/item_use_fixture.rs +++ b/crates/horizon-world/examples/probe/item_use_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::{ blocking_rules::{BlockingRules, ItemDamageFunction}, item_use::{self, ItemUseWorld}, @@ -11,13 +12,6 @@ use std::{ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} struct World<'a> { f: &'a Value, out: &'a mut dyn Write, @@ -85,8 +79,8 @@ impl ItemUseWorld for World<'_> { Ok(self.state()["virtual_remaining"].as_i64().unwrap() as i32) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -127,7 +121,7 @@ fn main() -> Result<(), Box> { item_use::ticks_using_item(&mut w).and_then(|v| writeln!(w.out, "ticks {v}")) } "partial" => item_use::ticks_using_item_partial(&mut w, single(&f["partial"])) - .and_then(|v| writeln!(w.out, "float {:08x}", bits(v))), + .and_then(|v| writeln!(w.out, "float {:08x}", f32_bits(v))), _ => panic!("mode"), }; writeln!( diff --git a/crates/horizon-world/examples/item_use_lifecycle_fixture.rs b/crates/horizon-world/examples/probe/item_use_lifecycle_fixture.rs similarity index 98% rename from crates/horizon-world/examples/item_use_lifecycle_fixture.rs rename to crates/horizon-world/examples/probe/item_use_lifecycle_fixture.rs index 404f6ba17..f7d3df48a 100644 --- a/crates/horizon-world/examples/item_use_lifecycle_fixture.rs +++ b/crates/horizon-world/examples/probe/item_use_lifecycle_fixture.rs @@ -166,8 +166,8 @@ impl UseLifecycleWorld for World<'_> { Ok(()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/item_use_start_fixture.rs b/crates/horizon-world/examples/probe/item_use_start_fixture.rs similarity index 98% rename from crates/horizon-world/examples/item_use_start_fixture.rs rename to crates/horizon-world/examples/probe/item_use_start_fixture.rs index 19cb859f8..be927e42e 100644 --- a/crates/horizon-world/examples/item_use_start_fixture.rs +++ b/crates/horizon-world/examples/probe/item_use_start_fixture.rs @@ -199,8 +199,8 @@ impl StartUseWorld for World<'_> { self.kinetic_count = 0; } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/java_hash_map_fixture.rs b/crates/horizon-world/examples/probe/java_hash_map_fixture.rs similarity index 97% rename from crates/horizon-world/examples/java_hash_map_fixture.rs rename to crates/horizon-world/examples/probe/java_hash_map_fixture.rs index cc2f6860d..de441a488 100644 --- a/crates/horizon-world/examples/java_hash_map_fixture.rs +++ b/crates/horizon-world/examples/probe/java_hash_map_fixture.rs @@ -35,8 +35,8 @@ impl JavaKey for Key { fn opt(v: Option) -> String { v.map_or("none".into(), |v| v.to_string()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/java_identity_map_fixture.rs b/crates/horizon-world/examples/probe/java_identity_map_fixture.rs similarity index 97% rename from crates/horizon-world/examples/java_identity_map_fixture.rs rename to crates/horizon-world/examples/probe/java_identity_map_fixture.rs index c73d20f7d..700b5b329 100644 --- a/crates/horizon-world/examples/java_identity_map_fixture.rs +++ b/crates/horizon-world/examples/probe/java_identity_map_fixture.rs @@ -48,10 +48,10 @@ impl JavaKey for Key { fn opt(v: Option) -> String { v.map_or("none".into(), |v| v.to_string()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); - let side = std::env::args().nth(2).unwrap(); + let side = crate::args().nth(2).unwrap(); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{side}.txt")))?); for line in fs::read_to_string(dir.join(format!("inputs-{side}.txt")))?.lines() { let f: Value = serde_json::from_str(line)?; diff --git a/crates/horizon-world/examples/level_place_fixture.rs b/crates/horizon-world/examples/probe/level_place_fixture.rs similarity index 97% rename from crates/horizon-world/examples/level_place_fixture.rs rename to crates/horizon-world/examples/probe/level_place_fixture.rs index 13595726d..0b9b4f883 100644 --- a/crates/horizon-world/examples/level_place_fixture.rs +++ b/crates/horizon-world/examples/probe/level_place_fixture.rs @@ -43,8 +43,8 @@ impl LevelAccess for Cells { } } -fn main() -> Result<(), Box> { - let mut args = std::env::args().skip(1); +pub fn main() -> Result<(), Box> { + let mut args = crate::args().skip(1); let resources = args.next().expect("resource directory"); let cases = args.next().expect("case file"); let output = args.next().expect("output file"); diff --git a/crates/horizon-world/examples/level_shape_fixture.rs b/crates/horizon-world/examples/probe/level_shape_fixture.rs similarity index 98% rename from crates/horizon-world/examples/level_shape_fixture.rs rename to crates/horizon-world/examples/probe/level_shape_fixture.rs index 1e4909928..696ac62ab 100644 --- a/crates/horizon-world/examples/level_shape_fixture.rs +++ b/crates/horizon-world/examples/probe/level_shape_fixture.rs @@ -43,8 +43,8 @@ impl LevelAccess for Cells { } } -fn main() -> Result<(), Box> { - let mut args = std::env::args().skip(1); +pub fn main() -> Result<(), Box> { + let mut args = crate::args().skip(1); let resources = args.next().expect("resource directory"); let cases = args.next().expect("case file"); let output = args.next().expect("output file"); diff --git a/crates/horizon-world/examples/live_attribute_updates_fixture.rs b/crates/horizon-world/examples/probe/live_attribute_updates_fixture.rs similarity index 98% rename from crates/horizon-world/examples/live_attribute_updates_fixture.rs rename to crates/horizon-world/examples/probe/live_attribute_updates_fixture.rs index 9f73a07e3..b053c2c82 100644 --- a/crates/horizon-world/examples/live_attribute_updates_fixture.rs +++ b/crates/horizon-world/examples/probe/live_attribute_updates_fixture.rs @@ -252,9 +252,9 @@ mod integration { "instance {} {} {} {} {} | {} | {}", h.index(), key.name(), - bits(a.base_value()), + f64_hex(a.base_value()), a.is_dirty(), - bits(a.cached_value()), + f64_hex(a.cached_value()), refs(a.modifiers(), &mut self.pools[i]), refs(a.permanent_modifiers(), &mut self.pools[i]) ) @@ -474,7 +474,7 @@ mod integration { } } pub fn run() -> std::result::Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); + let args: Vec<_> = crate::args().collect(); let dir = Path::new(&args[1]); let catalog = Arc::new(Catalog::from_json(&serde_json::from_str( &fs::read_to_string(dir.join("catalog.json"))?, @@ -541,8 +541,8 @@ mod integration { None, ); let result = match op["mode"].as_str().unwrap() { - "value" => w.attribute_value(key).map(bits), - "base" => live_updates::value(&mut w, key, ValueKind::Base).map(bits), + "value" => w.attribute_value(key).map(f64_hex), + "base" => live_updates::value(&mut w, key, ValueKind::Base).map(f64_hex), "set-health" => w .dispatch_set_health(single(&op["value"])) .map(|()| "ok".into()), @@ -593,6 +593,6 @@ mod integration { Ok(()) } } -fn main() -> Result<(), Box> { +pub fn main() -> Result<(), Box> { integration::run() } diff --git a/crates/horizon-world/examples/live_attributes_fixture.rs b/crates/horizon-world/examples/probe/live_attributes_fixture.rs similarity index 94% rename from crates/horizon-world/examples/live_attributes_fixture.rs rename to crates/horizon-world/examples/probe/live_attributes_fixture.rs index e90d8cb4f..1c4a868f5 100644 --- a/crates/horizon-world/examples/live_attributes_fixture.rs +++ b/crates/horizon-world/examples/probe/live_attributes_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_hex; use horizon_world::{ attribute_map::ValueKind, attributes::{ @@ -17,16 +18,6 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> String { - format!( - "{:016x}", - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } - ) -} fn error(e: Error) -> &'static str { match e { Error::NullAttribute | Error::MissingInstanceModifier => "null", @@ -52,7 +43,7 @@ fn refs(mods: &[Modifier], pool: &mut Vec) -> String { format!( "{id}:{}:{}:{}", m.id(), - bits(m.amount()), + f64_hex(m.amount()), m.operation() as u8 ) }) @@ -65,8 +56,8 @@ fn effect_error(e: effects::Error) -> Error { _ => panic!("fixture definitions unexpectedly invalid"), } } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let dir = Path::new(&args[1]); let catalog = Arc::new(Catalog::from_json(&serde_json::from_str( &fs::read_to_string(dir.join("catalog.json"))?, @@ -104,11 +95,11 @@ fn main() -> Result<(), Box> { )?; let mode = op["mode"].as_str().unwrap(); let result: Result = match mode { - "value" => attrs.value(key, ValueKind::Computed).map(bits), - "base" => attrs.value(key, ValueKind::Base).map(bits), + "value" => attrs.value(key, ValueKind::Computed).map(f64_hex), + "base" => attrs.value(key, ValueKind::Base).map(f64_hex), "has" => attrs.has_attribute(key).map(|v| v.to_string()), "has_modifier" => attrs.has_modifier(key, m.id()).map(|v| v.to_string()), - "modifier" => attrs.modifier_value(key, m.id()).map(bits), + "modifier" => attrs.modifier_value(key, m.id()).map(f64_hex), "ensure" => attrs.get_instance(key).map(|h| handle(h.as_ref())), "reset" => attrs.reset_base(key).map(|v| v.to_string()), "ack_update" => { @@ -208,9 +199,9 @@ fn main() -> Result<(), Box> { "instance {} {} {} {} {} | {} | {}", h.index(), key.name(), - bits(a.base_value()), + f64_hex(a.base_value()), a.is_dirty(), - bits(a.cached_value()), + f64_hex(a.cached_value()), refs(a.modifiers(), &mut pool), refs(a.permanent_modifiers(), &mut pool) )?; diff --git a/crates/horizon-world/examples/living_air_fixture.rs b/crates/horizon-world/examples/probe/living_air_fixture.rs similarity index 94% rename from crates/horizon-world/examples/living_air_fixture.rs rename to crates/horizon-world/examples/probe/living_air_fixture.rs index fe581f54f..882c5a8f3 100644 --- a/crates/horizon-world/examples/living_air_fixture.rs +++ b/crates/horizon-world/examples/probe/living_air_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::living_air::*; use serde_json::Value; @@ -15,18 +16,16 @@ fn single(v: &Value) -> f32 { fn vec(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn fbits(v: f32) -> u32 { if v.is_nan() { 0x7fc00000 } else { v.to_bits() } } fn vector(v: Vec3) -> String { - format!("{:016x} {:016x} {:016x}", bits(v.x), bits(v.y), bits(v.z)) + format!( + "{:016x} {:016x} {:016x}", + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) + ) } struct World<'a> { f: &'a Value, @@ -193,8 +192,8 @@ impl LivingAirWorld for World<'_> { Ok(self.flag("omni")) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -239,7 +238,12 @@ fn main() -> Result<(), Box> { "result {}", if result.is_ok() { "ok" } else { "error" } )?; - writeln!(w.out, "final {} {:016x}", vector(w.velocity), bits(w.fall))?; + writeln!( + w.out, + "final {} {:016x}", + vector(w.velocity), + f64_bits(w.fall) + )?; writeln!(w.out, "queries {}", w.calls)?; } Ok(()) diff --git a/crates/horizon-world/examples/living_damage_fixture.rs b/crates/horizon-world/examples/probe/living_damage_fixture.rs similarity index 88% rename from crates/horizon-world/examples/living_damage_fixture.rs rename to crates/horizon-world/examples/probe/living_damage_fixture.rs index b77048866..d8097bde9 100644 --- a/crates/horizon-world/examples/living_damage_fixture.rs +++ b/crates/horizon-world/examples/probe/living_damage_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::{ living_damage::{self, DamageStat, DamageWorld}, living_health::{self, HealthWorld}, @@ -14,13 +15,6 @@ fn single(v: &Value) -> f32 { fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn stat(s: DamageStat) -> &'static str { match s { DamageStat::Absorbed => "absorbed", @@ -69,11 +63,11 @@ impl DamageWorld for World<'_> { Ok(self.state()["invulnerable"].as_bool().unwrap()) } fn after_armor(&mut self, v: f32) -> io::Result { - self.query(&format!("armor {:08x}", bits(v)))?; + self.query(&format!("armor {:08x}", f32_bits(v)))?; Ok(single(&self.state()["armor"])) } fn after_magic(&mut self, v: f32) -> io::Result { - self.query(&format!("magic {:08x}", bits(v)))?; + self.query(&format!("magic {:08x}", f32_bits(v)))?; Ok(single(&self.state()["magic"])) } fn absorption(&mut self) -> io::Result { @@ -98,13 +92,13 @@ impl DamageWorld for World<'_> { Ok(single(&self.state()["food_exhaustion"])) } fn cause_food_exhaustion(&mut self, v: f32) -> io::Result<()> { - self.query(&format!("exhaust {:08x}", bits(v)))?; + self.query(&format!("exhaust {:08x}", f32_bits(v)))?; self.exhaustion += v; Ok(()) } fn record_damage(&mut self, v: f32) -> io::Result<()> { self.query("tracker")?; - self.query(&format!("record {:08x}", bits(v)))?; + self.query(&format!("record {:08x}", f32_bits(v)))?; self.recorded = v; Ok(()) } @@ -113,7 +107,7 @@ impl DamageWorld for World<'_> { Ok(self.health) } fn set_health(&mut self, v: f32) -> io::Result<()> { - self.query(&format!("set-health {:08x}", bits(v)))?; + self.query(&format!("set-health {:08x}", f32_bits(v)))?; self.health = v; Ok(()) } @@ -140,7 +134,7 @@ impl HealthWorld for World<'_> { DamageWorld::set_health(self, v) } fn store_absorption(&mut self, v: f32) -> io::Result<()> { - self.query(&format!("set-absorption {:08x}", bits(v)))?; + self.query(&format!("set-absorption {:08x}", f32_bits(v)))?; self.absorption = v; Ok(()) } @@ -151,8 +145,8 @@ impl HealthWorld for World<'_> { DamageWorld::set_health(self, v) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -181,10 +175,10 @@ fn main() -> Result<(), Box> { writeln!( w.out, "final {:08x} {:08x} {:08x} {:08x}", - bits(w.health), - bits(w.absorption), - bits(w.exhaustion), - bits(w.recorded) + f32_bits(w.health), + f32_bits(w.absorption), + f32_bits(w.exhaustion), + f32_bits(w.recorded) )?; writeln!(w.out, "queries {}", w.calls)?; } diff --git a/crates/horizon-world/examples/living_fall_fixture.rs b/crates/horizon-world/examples/probe/living_fall_fixture.rs similarity index 94% rename from crates/horizon-world/examples/living_fall_fixture.rs rename to crates/horizon-world/examples/probe/living_fall_fixture.rs index 64dc1f2df..2d65929ff 100644 --- a/crates/horizon-world/examples/living_fall_fixture.rs +++ b/crates/horizon-world/examples/probe/living_fall_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::geometry::Vec3; use horizon_world::living_fall::{ ImpulseContext, LivingFallWorld, calculate_fall_damage, cause_living_fall_damage, @@ -14,13 +15,6 @@ fn number(v: &Value) -> f64 { fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn vector(v: &Value) -> Option { if v.is_null() { None @@ -60,9 +54,9 @@ impl World<'_> { writeln!( self.out, "impact {:016x} {:016x} {:016x}", - bits(p.x), - bits(p.y), - bits(p.z) + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z) ) } else { writeln!(self.out, "impact none") @@ -100,7 +94,7 @@ impl LivingFallWorld for World<'_> { fn propagate_fall_to_passengers(&mut self, d: f64, m: f32) -> io::Result<()> { self.query(format!( "passengers {:016x} {:08x}", - bits(d), + f64_bits(d), if m.is_nan() { 0x7fc00000 } else { m.to_bits() } ))?; if self.f["mutate"].as_bool().unwrap() { @@ -169,8 +163,8 @@ fn run(world: &mut World<'_>) -> io::Result<()> { }; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/living_fluid_fixture.rs b/crates/horizon-world/examples/probe/living_fluid_fixture.rs similarity index 96% rename from crates/horizon-world/examples/living_fluid_fixture.rs rename to crates/horizon-world/examples/probe/living_fluid_fixture.rs index 55ccdd8f5..bd3704965 100644 --- a/crates/horizon-world/examples/living_fluid_fixture.rs +++ b/crates/horizon-world/examples/probe/living_fluid_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::living_air::*; use horizon_world::living_fluid::*; @@ -16,18 +17,16 @@ fn single(v: &Value) -> f32 { fn vec(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn fbits(v: f32) -> u32 { if v.is_nan() { 0x7fc00000 } else { v.to_bits() } } fn vector(v: Vec3) -> String { - format!("{:016x} {:016x} {:016x}", bits(v.x), bits(v.y), bits(v.z)) + format!( + "{:016x} {:016x} {:016x}", + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) + ) } struct World<'a> { f: &'a Value, @@ -248,8 +247,8 @@ impl LivingFluidWorld for World<'_> { Ok(self.flag("float_tag")) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -320,7 +319,12 @@ fn main() -> Result<(), Box> { "result {}", if result.is_ok() { "ok" } else { "error" } )?; - writeln!(w.out, "final {} {:016x}", vector(w.velocity), bits(w.fall))?; + writeln!( + w.out, + "final {} {:016x}", + vector(w.velocity), + f64_bits(w.fall) + )?; writeln!(w.out, "queries {}", w.calls)?; } Ok(()) diff --git a/crates/horizon-world/examples/living_health_fixture.rs b/crates/horizon-world/examples/probe/living_health_fixture.rs similarity index 90% rename from crates/horizon-world/examples/living_health_fixture.rs rename to crates/horizon-world/examples/probe/living_health_fixture.rs index 958d43b7d..53d00b076 100644 --- a/crates/horizon-world/examples/living_health_fixture.rs +++ b/crates/horizon-world/examples/probe/living_health_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::living_health::{self, HealthWorld, SyncedFloat}; use serde_json::Value; use std::{ @@ -11,13 +12,6 @@ fn single(v: &Value) -> f32 { fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} struct Context<'a> { f: &'a Value, out: &'a mut dyn Write, @@ -70,7 +64,7 @@ impl HealthWorld for World<'_> { self.stores[data].set(v, false, |_| self.ctx.query("updated")) } fn store_absorption(&mut self, v: f32) -> io::Result<()> { - self.ctx.query(&format!("absorption {:08x}", bits(v)))?; + self.ctx.query(&format!("absorption {:08x}", f32_bits(v)))?; self.absorption = v; Ok(()) } @@ -78,12 +72,12 @@ impl HealthWorld for World<'_> { self.ctx.world()["dead"].as_bool().unwrap() } fn dispatch_set_health(&mut self, v: f32) -> io::Result<()> { - self.ctx.query(&format!("set {:08x}", bits(v)))?; + self.ctx.query(&format!("set {:08x}", f32_bits(v)))?; living_health::set_health(self, v) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -123,7 +117,7 @@ fn main() -> Result<(), Box> { "packed {}", w.stores[w.ctx.active] .take_dirty() - .map(|v| format!("{:08x}", bits(v))) + .map(|v| format!("{:08x}", f32_bits(v))) .unwrap_or_else(|| "none".into()) ) } @@ -138,7 +132,7 @@ fn main() -> Result<(), Box> { writeln!( w.ctx.out, "data {i} {:08x} {} {} {}", - bits(s.value()), + f32_bits(s.value()), s.is_dirty(), s.item_dirty(), s.is_default() @@ -149,7 +143,7 @@ fn main() -> Result<(), Box> { w.ctx.out, "state {} {:08x} {dead} {}", w.ctx.active, - bits(w.absorption), + f32_bits(w.absorption), w.ctx.calls )?; } diff --git a/crates/horizon-world/examples/living_hurt_fixture.rs b/crates/horizon-world/examples/probe/living_hurt_fixture.rs similarity index 92% rename from crates/horizon-world/examples/living_hurt_fixture.rs rename to crates/horizon-world/examples/probe/living_hurt_fixture.rs index e9addb406..b5ab3e890 100644 --- a/crates/horizon-world/examples/living_hurt_fixture.rs +++ b/crates/horizon-world/examples/probe/living_hurt_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::living_hurt::{HurtState, HurtTag, HurtWorld, hurt_server}; use serde_json::Value; use std::{ @@ -8,19 +9,12 @@ use std::{ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn state(s: &HurtState<()>) -> String { format!( "{} {} {:08x} {} {} {} {}", s.no_action_time, s.cooldown, - bits(s.last_hurt), + f32_bits(s.last_hurt), s.hurt_duration, s.hurt_time, s.last_source.is_some(), @@ -126,7 +120,7 @@ impl HurtWorld for Env<'_> { Ok(self.flag("component")) } fn apply_blocking(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result { - self.event(&format!("blocking {:08x}", bits(v)))?; + self.event(&format!("blocking {:08x}", f32_bits(v)))?; Ok(single(&self.op["blocked"])) } fn helmet_empty(&mut self, _: &mut HurtState<()>) -> io::Result { @@ -134,10 +128,10 @@ impl HurtWorld for Env<'_> { Ok(!self.flag("helmet")) } fn hurt_helmet(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result<()> { - self.event(&format!("hurt-helmet {:08x}", bits(v))) + self.event(&format!("hurt-helmet {:08x}", f32_bits(v))) } fn actually_hurt(&mut self, s: &mut HurtState<()>, v: f32) -> io::Result<()> { - self.event(&format!("hurt {:08x} {}", bits(v), state(s)))?; + self.event(&format!("hurt {:08x} {}", f32_bits(v), state(s)))?; self.hit = true; self.recorded = v; if self.flag("mutate_hit") { @@ -155,7 +149,7 @@ impl HurtWorld for Env<'_> { Ok(()) } fn knockback(&mut self, _: &mut HurtState<()>, v: f32, b: bool) -> io::Result<()> { - self.event(&format!("knockback {:08x} {b}", bits(v))) + self.event(&format!("knockback {:08x} {b}", f32_bits(v))) } fn death_protection(&mut self, _: &mut HurtState<()>) -> io::Result { self.event("tag bypasses_invulnerability")?; @@ -179,7 +173,7 @@ impl HurtWorld for Env<'_> { fn effects_on_hurt(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result<()> { self.event("effects")?; for i in 0..self.op["effects"].as_u64().unwrap() { - self.event(&format!("effect {i} {:08x}", bits(v)))?; + self.event(&format!("effect {i} {:08x}", f32_bits(v)))?; } Ok(()) } @@ -205,8 +199,8 @@ impl HurtWorld for Env<'_> { self.event("attacker") } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -239,7 +233,7 @@ fn main() -> Result<(), Box> { e.out, "state {} {:08x} {} {}", state(&s), - bits(recorded), + f32_bits(recorded), e.hit, e.calls )?; diff --git a/crates/horizon-world/examples/living_landing_fixture.rs b/crates/horizon-world/examples/probe/living_landing_fixture.rs similarity index 92% rename from crates/horizon-world/examples/living_landing_fixture.rs rename to crates/horizon-world/examples/probe/living_landing_fixture.rs index 156f8a2bd..3c3e333d7 100644 --- a/crates/horizon-world/examples/living_landing_fixture.rs +++ b/crates/horizon-world/examples/probe/living_landing_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::fall_damage::FallDamageWorld; use horizon_world::living_landing::{LivingLandingWorld, check_living_fall_damage}; @@ -10,13 +11,6 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn support(v: &Value) -> Option { if v.is_null() { None @@ -69,7 +63,7 @@ impl FallDamageWorld for World<'_> { p.x, p.y, p.z, - bits(distance) + f64_bits(distance) ))?; if self.input["mutate"].as_bool().unwrap() { self.fall = 17.25; @@ -91,9 +85,9 @@ impl FallDamageWorld for World<'_> { fn hit_ground(&mut self, p: Vec3, s: u8) -> io::Result<()> { self.query(format!( "hit-ground {:016x} {:016x} {:016x} {}", - bits(p.x), - bits(p.y), - bits(p.z), + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z), if s == 1 { "queried" } else { "input" } )) } @@ -142,11 +136,11 @@ impl LivingLandingWorld for World<'_> { assert_eq!(s, 0); self.query(format!( "particles {:016x} {:016x} {:016x} {} {:016x}", - bits(p.x), - bits(p.y), - bits(p.z), + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z), count, - bits(speed) + f64_bits(speed) ))?; if self.input["particle_mutate"].as_bool().unwrap() { self.fall = number(&self.input["after_fall"]); @@ -158,8 +152,8 @@ impl LivingLandingWorld for World<'_> { self.climbable = false; } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -194,10 +188,10 @@ fn main() -> Result<(), Box> { writeln!( world.out, "final {:016x} {:016x} {:016x} {:016x}", - bits(world.fall), - bits(p.x), - bits(p.y), - bits(p.z) + f64_bits(world.fall), + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z) )?; if let Some(p) = world.support { writeln!(world.out, "support {} {} {}", p.x, p.y, p.z)?; diff --git a/crates/horizon-world/examples/living_motion_fixture.rs b/crates/horizon-world/examples/probe/living_motion_fixture.rs similarity index 90% rename from crates/horizon-world/examples/living_motion_fixture.rs rename to crates/horizon-world/examples/probe/living_motion_fixture.rs index 92b4db938..96c0792ac 100644 --- a/crates/horizon-world/examples/living_motion_fixture.rs +++ b/crates/horizon-world/examples/probe/living_motion_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::geometry::Vec3; use horizon_world::living_motion::*; use serde_json::Value; @@ -15,18 +16,16 @@ fn single(v: &Value) -> f32 { fn vec(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn fbits(v: f32) -> u32 { if v.is_nan() { 0x7fc00000 } else { v.to_bits() } } fn vector(v: Vec3) -> String { - format!("{:016x} {:016x} {:016x}", bits(v.x), bits(v.y), bits(v.z)) + format!( + "{:016x} {:016x} {:016x}", + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) + ) } struct World<'a> { f: &'a Value, @@ -118,8 +117,8 @@ impl LivingMotionWorld for World<'_> { Ok(number(&self.f["drag_modifier"])) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -138,10 +137,11 @@ fn main() -> Result<(), Box> { "power" => jump_power(&mut w, single(&f["scale"])) .and_then(|v| writeln!(w.out, "float {:08x}", fbits(v))), "jump" => jump_from_ground(&mut w), - "gravity" => gravity(&mut w).and_then(|v| writeln!(w.out, "double {:016x}", bits(v))), - "effective" => { - effective_gravity(&mut w).and_then(|v| writeln!(w.out, "double {:016x}", bits(v))) + "gravity" => { + gravity(&mut w).and_then(|v| writeln!(w.out, "double {:016x}", f64_bits(v))) } + "effective" => effective_gravity(&mut w) + .and_then(|v| writeln!(w.out, "double {:016x}", f64_bits(v))), "apply" => apply_gravity(&mut w), "up" => swim_vertical(&mut w, true), "down" => swim_vertical(&mut w, false), diff --git a/crates/horizon-world/examples/probe/main.rs b/crates/horizon-world/examples/probe/main.rs new file mode 100644 index 000000000..f3b9b6ef5 --- /dev/null +++ b/crates/horizon-world/examples/probe/main.rs @@ -0,0 +1,358 @@ +//! Every horizon-world parity probe in one binary: `probe [arguments]` runs `.rs` as its own +//! example did (tools/test_*_parity.py). Linking ~170 examples, each instantiating the crate's generics again, +//! was most of the parity job's probe build; one binary builds them once. +//! +//! This file only lists the probes, so that adding one reruns no harness: tools/parity.py leaves it out of +//! their dependencies. How a probe runs is in dispatch.rs. +#[macro_use] +mod dispatch; + +use dispatch::args; + +/// Code shared by several probes. +mod support { + pub mod common; + pub mod decoration_storage; + pub mod placement_queries; + pub mod shapes; +} + +mod active_effect_tick_fixture; +mod active_effects_fixture; +mod anchor_fixture; +mod attribute_fixture; +mod attribute_health_fixture; +mod attribute_map_queries_fixture; +mod attribute_updates_fixture; +mod basic_feature_fixture; +mod biome_chunk_fixture; +mod biome_generation_fixture; +mod biome_placement_fixture; +mod biome_source_codec_fixture; +mod biome_source_fixture; +mod biome_temperature_fixture; +mod block_collision_scan_fixture; +mod block_entity_storage_fixture; +mod block_landing_fixture; +mod block_properties_fixture; +mod block_push_fixture; +mod block_state_codec_fixture; +mod block_support_fixture; +mod block_survival_fixture; +mod block_update_fixture; +mod blocking_item_damage_fixture; +mod blocking_rules_fixture; +mod bulk_section_fixture; +mod bundle_weight_fixture; +mod canyon_carver_fixture; +mod carving_geometry_fixture; +mod carving_mask_fixture; +mod cave_carver_fixture; +mod chunk_dump; +mod chunk_stage_fixture; +mod chunk_status_fixture; +mod climbing_fixture; +mod collision_context_fixture; +mod collision_fixture; +mod combat_rules_fixture; +mod component_durability_fixture; +mod component_patch_fixture; +mod consumable_emission_fixture; +mod consumable_fixture; +mod consume_effect_fixture; +mod damage_immunity_fixture; +mod damage_reduction_fixture; +mod damage_source_fixture; +mod datafix_world; +mod decoration_fixture; +mod decoration_region_fixture; +mod dynamic_support_fixture; +mod edge_backoff_fixture; +mod effect_attribute_modifiers_fixture; +mod effect_notifications_fixture; +mod effect_sync_fixture; +mod entity_attribute_fixture; +mod entity_collision_fixture; +mod entity_fluid_fixture; +mod entity_move_fixture; +mod entity_obstruction_fixture; +mod extra_items_fixture; +mod face_support_fixture; +mod face_visibility_fixture; +mod fall_damage_fixture; +mod feature_catalog_fixture; +mod feature_graph_fixture; +mod feature_placement_fixture; +mod feature_region_fixture; +mod feature_sort_fixture; +mod fill_layer_fixture; +mod fluid_box_fixture; +mod fluid_fixture; +mod fluid_flow_fixture; +mod fluid_occupancy_fixture; +mod fluid_shape_fixture; +mod food_fixture; +mod food_properties_fixture; +mod food_storage_fixture; +mod ground_state_fixture; +mod height_provider_fixture; +mod heightmap_fixture; +mod interaction_shape_fixture; +mod inventory_pickup_fixture; +mod inventory_tick_fixture; +mod inventory_use_fixture; +mod inventory_use_start_fixture; +mod item_after_use_fixture; +mod item_blocking_fixture; +mod item_cooldowns_fixture; +mod item_durability_fixture; +mod item_particles_fixture; +mod item_stack_storage_fixture; +mod item_template_fixture; +mod item_use_catalog_fixture; +mod item_use_fixture; +mod item_use_lifecycle_fixture; +mod item_use_start_fixture; +mod java_hash_map_fixture; +mod java_identity_map_fixture; +mod level_place_fixture; +mod level_shape_fixture; +mod live_attribute_updates_fixture; +mod live_attributes_fixture; +mod living_air_fixture; +mod living_damage_fixture; +mod living_fall_fixture; +mod living_fluid_fixture; +mod living_health_fixture; +mod living_hurt_fixture; +mod living_landing_fixture; +mod living_motion_fixture; +mod material_condition_fixture; +mod material_extension_fixture; +mod material_stage_fixture; +mod material_surface_fixture; +mod movement_emission_fixture; +mod movement_registry_fixture; +mod movement_support_fixture; +mod object_open_map_fixture; +mod object_open_set_fixture; +mod piston_movement_fixture; +mod piston_shape_fixture; +mod placement_fixture; +mod player_equipment_fixture; +mod player_food_fixture; +mod player_health_fixture; +mod player_hurt_fixture; +mod player_inventory_fixture; +mod player_travel_fixture; +mod portal_travel_fixture; +mod registered_player_combat_fixture; +mod registry_collision_scan_fixture; +mod registry_fall_ray_fixture; +mod registry_fluid_fixture; +mod replace_block_fixture; +mod restitution_fixture; +mod retrogen_data_fixture; +mod rule_test_fixture; +mod scattered_ore_fixture; +mod server_player_combat_fixture; +mod server_player_damage_fixture; +mod simple_block_fixture; +mod simple_container_fixture; +mod spawn_origin; +mod state_provider_fixture; +mod status_effect_fixture; +mod status_tick_fixture; +mod stepped_interpolation_fixture; +mod stored_consume_fixture; +mod stored_effect_attributes_fixture; +mod stored_effect_notifications_fixture; +mod structure_density_fixture; +mod suffocation_fixture; +mod swimming_fixture; +mod synced_bytes_fixture; +mod synced_floats_fixture; +mod teleport_consume_fixture; +mod terrain_fixture; +mod tick_fixture; +mod tree_feature_fixture; +mod use_flag_reaction_fixture; +mod use_remainder_fixture; +mod value_provider_fixture; +mod view_direction_fixture; +mod water_splash_fixture; +mod world_border_fixture; +mod world_fixture; +mod world_ray_fixture; +mod worldgen_random_fixture; + +probes! { + active_effect_tick_fixture, + active_effects_fixture, + anchor_fixture, + attribute_fixture, + attribute_health_fixture, + attribute_map_queries_fixture, + attribute_updates_fixture, + basic_feature_fixture, + biome_chunk_fixture, + biome_generation_fixture, + biome_placement_fixture, + biome_source_codec_fixture, + biome_source_fixture, + biome_temperature_fixture, + block_collision_scan_fixture, + block_entity_storage_fixture, + block_landing_fixture, + block_properties_fixture, + block_push_fixture, + block_state_codec_fixture, + block_support_fixture, + block_survival_fixture, + block_update_fixture, + blocking_item_damage_fixture, + blocking_rules_fixture, + bulk_section_fixture, + bundle_weight_fixture, + canyon_carver_fixture, + carving_geometry_fixture, + carving_mask_fixture, + cave_carver_fixture, + chunk_dump, + chunk_stage_fixture, + chunk_status_fixture, + climbing_fixture, + collision_context_fixture, + collision_fixture, + combat_rules_fixture, + component_durability_fixture, + component_patch_fixture, + consumable_emission_fixture, + consumable_fixture, + consume_effect_fixture, + damage_immunity_fixture, + damage_reduction_fixture, + damage_source_fixture, + datafix_world, + decoration_fixture, + decoration_region_fixture, + dynamic_support_fixture, + edge_backoff_fixture, + effect_attribute_modifiers_fixture, + effect_notifications_fixture, + effect_sync_fixture, + entity_attribute_fixture, + entity_collision_fixture, + entity_fluid_fixture, + entity_move_fixture, + entity_obstruction_fixture, + extra_items_fixture, + face_support_fixture, + face_visibility_fixture, + fall_damage_fixture, + feature_catalog_fixture, + feature_graph_fixture, + feature_placement_fixture, + feature_region_fixture, + feature_sort_fixture, + fill_layer_fixture, + fluid_box_fixture, + fluid_fixture, + fluid_flow_fixture, + fluid_occupancy_fixture, + fluid_shape_fixture, + food_fixture, + food_properties_fixture, + food_storage_fixture, + ground_state_fixture, + height_provider_fixture, + heightmap_fixture, + interaction_shape_fixture, + inventory_pickup_fixture, + inventory_tick_fixture, + inventory_use_fixture, + inventory_use_start_fixture, + item_after_use_fixture, + item_blocking_fixture, + item_cooldowns_fixture, + item_durability_fixture, + item_particles_fixture, + item_stack_storage_fixture, + item_template_fixture, + item_use_catalog_fixture, + item_use_fixture, + item_use_lifecycle_fixture, + item_use_start_fixture, + java_hash_map_fixture, + java_identity_map_fixture, + level_place_fixture, + level_shape_fixture, + live_attribute_updates_fixture, + live_attributes_fixture, + living_air_fixture, + living_damage_fixture, + living_fall_fixture, + living_fluid_fixture, + living_health_fixture, + living_hurt_fixture, + living_landing_fixture, + living_motion_fixture, + material_condition_fixture, + material_extension_fixture, + material_stage_fixture, + material_surface_fixture, + movement_emission_fixture, + movement_registry_fixture, + movement_support_fixture, + object_open_map_fixture, + object_open_set_fixture, + piston_movement_fixture, + piston_shape_fixture, + placement_fixture, + player_equipment_fixture, + player_food_fixture, + player_health_fixture, + player_hurt_fixture, + player_inventory_fixture, + player_travel_fixture, + portal_travel_fixture, + registered_player_combat_fixture, + registry_collision_scan_fixture, + registry_fall_ray_fixture, + registry_fluid_fixture, + replace_block_fixture, + restitution_fixture, + retrogen_data_fixture, + rule_test_fixture, + scattered_ore_fixture, + server_player_combat_fixture, + server_player_damage_fixture, + simple_block_fixture, + simple_container_fixture, + spawn_origin, + state_provider_fixture, + status_effect_fixture, + status_tick_fixture, + stepped_interpolation_fixture, + stored_consume_fixture, + stored_effect_attributes_fixture, + stored_effect_notifications_fixture, + structure_density_fixture, + suffocation_fixture, + swimming_fixture, + synced_bytes_fixture, + synced_floats_fixture, + teleport_consume_fixture, + terrain_fixture, + tick_fixture, + tree_feature_fixture, + use_flag_reaction_fixture, + use_remainder_fixture, + value_provider_fixture, + view_direction_fixture, + water_splash_fixture, + world_border_fixture, + world_fixture, + world_ray_fixture, + worldgen_random_fixture, +} diff --git a/crates/horizon-world/examples/material_condition_fixture.rs b/crates/horizon-world/examples/probe/material_condition_fixture.rs similarity index 99% rename from crates/horizon-world/examples/material_condition_fixture.rs rename to crates/horizon-world/examples/probe/material_condition_fixture.rs index 0cbb03168..86017d1eb 100644 --- a/crates/horizon-world/examples/material_condition_fixture.rs +++ b/crates/horizon-world/examples/probe/material_condition_fixture.rs @@ -646,8 +646,8 @@ where } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); let definitions = serde_json::from_str(&fs::read_to_string(dir.join("conditions.json"))?)?; diff --git a/crates/horizon-world/examples/material_extension_fixture.rs b/crates/horizon-world/examples/probe/material_extension_fixture.rs similarity index 98% rename from crates/horizon-world/examples/material_extension_fixture.rs rename to crates/horizon-world/examples/probe/material_extension_fixture.rs index a48943723..1d7170b6d 100644 --- a/crates/horizon-world/examples/material_extension_fixture.rs +++ b/crates/horizon-world/examples/probe/material_extension_fixture.rs @@ -189,8 +189,8 @@ where } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let noises = serde_json::from_str(&fs::read_to_string(dir.join("noises.json"))?)?; let biomes = serde_json::from_str(&fs::read_to_string(dir.join("biomes.json"))?)?; diff --git a/crates/horizon-world/examples/material_stage_fixture.rs b/crates/horizon-world/examples/probe/material_stage_fixture.rs similarity index 98% rename from crates/horizon-world/examples/material_stage_fixture.rs rename to crates/horizon-world/examples/probe/material_stage_fixture.rs index 6682b04b7..31a563f7c 100644 --- a/crates/horizon-world/examples/material_stage_fixture.rs +++ b/crates/horizon-world/examples/probe/material_stage_fixture.rs @@ -1,4 +1,5 @@ //! Original transport for complete surface-stage chunk comparison. +use crate::support::common::tag; use horizon_core::{ biome::{BiomeZoom, obfuscate_seed}, carving::CarvingMask, @@ -78,17 +79,6 @@ impl TerrainBlockStates for Properties<'_> { self.0[id.0 as usize] } } -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 n(v: &Value) -> i32 { v.as_i64().unwrap() as i32 } @@ -705,8 +695,8 @@ fn dump( } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name: &str| -> Result, Box> { Ok(serde_json::from_str(&fs::read_to_string( diff --git a/crates/horizon-world/examples/material_surface_fixture.rs b/crates/horizon-world/examples/probe/material_surface_fixture.rs similarity index 97% rename from crates/horizon-world/examples/material_surface_fixture.rs rename to crates/horizon-world/examples/probe/material_surface_fixture.rs index c7cb93bbd..3b3373f86 100644 --- a/crates/horizon-world/examples/material_surface_fixture.rs +++ b/crates/horizon-world/examples/probe/material_surface_fixture.rs @@ -105,8 +105,8 @@ fn fixture( } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private directory"); let dir = Path::new(&arg); let noises: BTreeMap = serde_json::from_str(&fs::read_to_string(dir.join("noises.json"))?)?; diff --git a/crates/horizon-world/examples/movement_emission_fixture.rs b/crates/horizon-world/examples/probe/movement_emission_fixture.rs similarity index 92% rename from crates/horizon-world/examples/movement_emission_fixture.rs rename to crates/horizon-world/examples/probe/movement_emission_fixture.rs index 36439e118..70ef1b32b 100644 --- a/crates/horizon-world/examples/movement_emission_fixture.rs +++ b/crates/horizon-world/examples/probe/movement_emission_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::{f64_bits, position}; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::movement_emission::*; use serde_json::Value; @@ -15,23 +16,9 @@ fn single(v: &Value) -> f32 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn position(v: &Value) -> BlockPos { - BlockPos::new( - v[0].as_i64().unwrap() as i32, - v[1].as_i64().unwrap() as i32, - v[2].as_i64().unwrap() as i32, - ) -} fn pos(p: BlockPos) -> String { format!("{} {} {}", p.x, p.y, p.z) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn fbits(v: f32) -> u32 { if v.is_nan() { 0x7fc00000 } else { v.to_bits() } } @@ -137,9 +124,9 @@ impl MovementEmissionWorld for World<'_> { let p = vector(&self.f["position"]); self.query(format!( "step {s} {:016x} {:016x} {:016x}", - bits(p.x), - bits(p.y), - bits(p.z) + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z) ))?; self.mutate(); Ok(()) @@ -178,8 +165,8 @@ impl MovementEmissionWorld for World<'_> { Ok(emission(&self.f["flap_emission"])) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/movement_registry_fixture.rs b/crates/horizon-world/examples/probe/movement_registry_fixture.rs similarity index 95% rename from crates/horizon-world/examples/movement_registry_fixture.rs rename to crates/horizon-world/examples/probe/movement_registry_fixture.rs index a04f5c124..28a934ee5 100644 --- a/crates/horizon-world/examples/movement_registry_fixture.rs +++ b/crates/horizon-world/examples/probe/movement_registry_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::position; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::movement_support::{self as support, MovementLocation}; use horizon_world::{ @@ -21,13 +22,6 @@ fn number(v: &Value) -> f64 { fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn position(v: &Value) -> BlockPos { - BlockPos::new( - v[0].as_i64().unwrap() as i32, - v[1].as_i64().unwrap() as i32, - v[2].as_i64().unwrap() as i32, - ) -} struct World<'a> { input: &'a Value, out: &'a mut dyn Write, @@ -48,8 +42,8 @@ impl MovementBlockProvider for World<'_> { )) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); let read = |name: &str| -> Result> { diff --git a/crates/horizon-world/examples/movement_support_fixture.rs b/crates/horizon-world/examples/probe/movement_support_fixture.rs similarity index 93% rename from crates/horizon-world/examples/movement_support_fixture.rs rename to crates/horizon-world/examples/probe/movement_support_fixture.rs index 096559250..1206aa0dc 100644 --- a/crates/horizon-world/examples/movement_support_fixture.rs +++ b/crates/horizon-world/examples/probe/movement_support_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::position; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::movement_support::{self as support, MovementBlockWorld, MovementLocation}; use serde_json::Value; @@ -12,13 +13,6 @@ fn number(v: &Value) -> f64 { fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn position(v: &Value) -> BlockPos { - BlockPos::new( - v[0].as_i64().unwrap() as i32, - v[1].as_i64().unwrap() as i32, - v[2].as_i64().unwrap() as i32, - ) -} struct World<'a> { input: &'a Value, out: &'a mut dyn Write, @@ -84,8 +78,8 @@ impl MovementBlockWorld for World<'_> { self.factor(id, "speed") } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/object_open_map_fixture.rs b/crates/horizon-world/examples/probe/object_open_map_fixture.rs similarity index 98% rename from crates/horizon-world/examples/object_open_map_fixture.rs rename to crates/horizon-world/examples/probe/object_open_map_fixture.rs index 63073aa8d..ae03169dd 100644 --- a/crates/horizon-world/examples/object_open_map_fixture.rs +++ b/crates/horizon-world/examples/probe/object_open_map_fixture.rs @@ -74,8 +74,8 @@ fn mutation(map: &mut ObjectOpenMap, keys: &[Key], op: &Value) -> Stri _ => panic!("mutation"), } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/object_open_set_fixture.rs b/crates/horizon-world/examples/probe/object_open_set_fixture.rs similarity index 96% rename from crates/horizon-world/examples/object_open_set_fixture.rs rename to crates/horizon-world/examples/probe/object_open_set_fixture.rs index d4c06f39d..c624d336d 100644 --- a/crates/horizon-world/examples/object_open_set_fixture.rs +++ b/crates/horizon-world/examples/probe/object_open_set_fixture.rs @@ -25,8 +25,8 @@ impl ObjectKey for Key { fn desc(key: Option<&Key>) -> String { key.map_or("null".into(), |k| format!("{}:{}", k.id, k.object)) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/piston_movement_fixture.rs b/crates/horizon-world/examples/probe/piston_movement_fixture.rs similarity index 79% rename from crates/horizon-world/examples/piston_movement_fixture.rs rename to crates/horizon-world/examples/probe/piston_movement_fixture.rs index 3c324aa00..804ccec2e 100644 --- a/crates/horizon-world/examples/piston_movement_fixture.rs +++ b/crates/horizon-world/examples/probe/piston_movement_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::geometry::Vec3; use horizon_world::piston_movement::PistonMovement; use serde_json::Value; @@ -12,15 +13,8 @@ fn number(v: &Value) -> f64 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -45,18 +39,18 @@ fn main() -> Result<(), Box> { Ok(v) => writeln!( out, "movement {:016x} {:016x} {:016x}", - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) )?, Err(_) => writeln!(out, "error")?, } writeln!( out, "deltas {:016x} {:016x} {:016x}", - bits(state.deltas[0]), - bits(state.deltas[1]), - bits(state.deltas[2]) + f64_bits(state.deltas[0]), + f64_bits(state.deltas[1]), + f64_bits(state.deltas[2]) )?; writeln!(out, "tick {}", state.game_time)?; writeln!(out, "queries {calls}")?; diff --git a/crates/horizon-world/examples/piston_shape_fixture.rs b/crates/horizon-world/examples/probe/piston_shape_fixture.rs similarity index 71% rename from crates/horizon-world/examples/piston_shape_fixture.rs rename to crates/horizon-world/examples/probe/piston_shape_fixture.rs index 06c62803b..ec75a9502 100644 --- a/crates/horizon-world/examples/piston_shape_fixture.rs +++ b/crates/horizon-world/examples/probe/piston_shape_fixture.rs @@ -1,4 +1,5 @@ -use horizon_core::geometry::{Aabb, Axis, Direction, VoxelShape}; +use crate::support::shapes::emit; +use horizon_core::geometry::{Direction, VoxelShape}; use horizon_world::{ collision::CachedCollisionRegistry, dynamic_support::{DynamicSupport, DynamicSupportWorld}, @@ -12,70 +13,6 @@ use std::{ io::{self, Write}, path::Path, }; -fn values( - out: &mut impl Write, - label: &str, - values: impl IntoIterator, -) -> io::Result<()> { - write!(out, "{label}")?; - for v in values { - let bits = if v.is_nan() { - 0x7ff8_0000_0000_0000 - } else { - v.to_bits() - }; - write!(out, " {bits:016x}")?; - } - writeln!(out) -} -fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { - values( - out, - label, - [ - b.min(Axis::X), - b.min(Axis::Y), - b.min(Axis::Z), - b.max(Axis::X), - b.max(Axis::Y), - b.max(Axis::Z), - ], - ) -} -fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { - writeln!( - out, - "shape {} {} {}", - shape.is_empty(), - shape.boxes().len(), - shape.is_cube() - )?; - for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { - values(out, name, shape.coordinates(axis).iter().copied())?; - } - let axes = shape.cube_coordinate_axes(); - writeln!( - out, - "axes {}", - u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) - )?; - values( - out, - "extrema", - Axis::ALL - .map(|a| shape.min(a)) - .into_iter() - .chain(Axis::ALL.map(|a| shape.max(a))), - )?; - match shape.bounds() { - Some(b) => box_values(out, "bounds", b)?, - None => writeln!(out, "bounds none")?, - } - for b in shape.boxes() { - box_values(out, "box", *b)?; - } - Ok(()) -} struct World<'a, 'r, W> { collisions: &'a CachedCollisionRegistry<'r>, dynamic: &'a [Option], @@ -125,8 +62,8 @@ fn number(v: &Value) -> f32 { fn float_bits(v: f32) -> u32 { if v.is_nan() { 0x7fc0_0000 } else { v.to_bits() } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name: &str| -> Result> { Ok( diff --git a/crates/horizon-world/examples/placement_fixture.rs b/crates/horizon-world/examples/probe/placement_fixture.rs similarity index 94% rename from crates/horizon-world/examples/placement_fixture.rs rename to crates/horizon-world/examples/probe/placement_fixture.rs index b3e6c4747..6214e630e 100644 --- a/crates/horizon-world/examples/placement_fixture.rs +++ b/crates/horizon-world/examples/probe/placement_fixture.rs @@ -1,6 +1,5 @@ //! Transport for placement decoding, emissions, failures and random state. -#[path = "support/placement_queries.rs"] -mod queries; +use crate::support::placement_queries as queries; use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; use horizon_world::worldgen::{anchor::WorldGenerationContext, placement::PlacementModifier}; use serde_json::Value; @@ -67,8 +66,8 @@ fn fixture( writeln!(out.borrow_mut(), "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/player_equipment_fixture.rs b/crates/horizon-world/examples/probe/player_equipment_fixture.rs similarity index 98% rename from crates/horizon-world/examples/player_equipment_fixture.rs rename to crates/horizon-world/examples/probe/player_equipment_fixture.rs index a7349b78c..0a356e31d 100644 --- a/crates/horizon-world/examples/player_equipment_fixture.rs +++ b/crates/horizon-world/examples/probe/player_equipment_fixture.rs @@ -131,8 +131,8 @@ impl EquipWorld for World { } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/player_food_fixture.rs b/crates/horizon-world/examples/probe/player_food_fixture.rs similarity index 93% rename from crates/horizon-world/examples/player_food_fixture.rs rename to crates/horizon-world/examples/probe/player_food_fixture.rs index 7478be35f..186ec6332 100644 --- a/crates/horizon-world/examples/player_food_fixture.rs +++ b/crates/horizon-world/examples/probe/player_food_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::{ food::FoodData, player_food::{self, PlayerFoodWorld, StoredPlayerFood}, @@ -11,13 +12,6 @@ use std::{ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} struct World<'a> { f: &'a Value, out: &'a mut dyn Write, @@ -68,7 +62,7 @@ impl PlayerFoodWorld for World<'_> { } fn add_exhaustion_direct(&mut self, v: f32) -> io::Result<()> { let i = self.index("direct"); - self.query(&format!("exhaust {i} {:08x}", bits(v)))?; + self.query(&format!("exhaust {i} {:08x}", f32_bits(v)))?; self.foods[i].add_exhaustion(v); Ok(()) } @@ -96,8 +90,8 @@ fn run(w: &mut W, f: &Value) -> Result, W::Erro _ => panic!("mode"), } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -136,7 +130,7 @@ fn main() -> Result<(), Box> { w.out, "food {i} {} {:08x}", food.food, - bits(food.exhaustion) + f32_bits(food.exhaustion) )?; } writeln!(w.out, "queries {}", w.calls)?; diff --git a/crates/horizon-world/examples/player_health_fixture.rs b/crates/horizon-world/examples/probe/player_health_fixture.rs similarity index 94% rename from crates/horizon-world/examples/player_health_fixture.rs rename to crates/horizon-world/examples/probe/player_health_fixture.rs index f7b687f65..24163bb75 100644 --- a/crates/horizon-world/examples/player_health_fixture.rs +++ b/crates/horizon-world/examples/probe/player_health_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::{ attributes::{ Modifier, Operation, @@ -19,20 +20,13 @@ fn single(v: &Value) -> f32 { fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn values(v: Option<&[FloatValue]>) -> String { match v { None => "none".into(), Some([]) => "empty".into(), Some(v) => v .iter() - .map(|v| format!("{}:{:08x}", v.id, bits(v.value))) + .map(|v| format!("{}:{:08x}", v.id, f32_bits(v.value))) .collect::>() .join(","), } @@ -59,7 +53,7 @@ impl Observer for Callback<'_> { fn updated(&mut self, data: &mut SyncedFloats, id: u8) -> io::Result<()> { self.event(&format!( "updated {id} {:08x} {}", - bits(data.get(id).unwrap()), + f32_bits(data.get(id).unwrap()), data.is_dirty() ))?; if self.op["pack_callback"].as_bool().unwrap() { @@ -96,8 +90,8 @@ impl State { .unwrap() } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let ids: Value = serde_json::from_str(&fs::read_to_string(dir.join("ids.json"))?)?; let ids = PlayerFloatIds { @@ -145,7 +139,7 @@ fn main() -> Result<(), Box> { .bind(&mut cb) .absorption() .map_err(|_| ()) - .and_then(|v| writeln!(cb.out, "float {:08x}", bits(v)).map_err(|_| ())), + .and_then(|v| writeln!(cb.out, "float {:08x}", f32_bits(v)).map_err(|_| ())), "hurt" => state .bind(&mut cb) .is_hurt() @@ -227,8 +221,8 @@ fn main() -> Result<(), Box> { writeln!( cb.out, "state {:08x} {:08x} {} {} {} {} {} {}", - bits(state.data.get(ids.health).unwrap()), - bits(state.data.get(ids.absorption).unwrap()), + f32_bits(state.data.get(ids.health).unwrap()), + f32_bits(state.data.get(ids.absorption).unwrap()), state.data.is_dirty(), state.data.item_dirty(ids.health).unwrap(), state.data.item_dirty(ids.absorption).unwrap(), diff --git a/crates/horizon-world/examples/player_hurt_fixture.rs b/crates/horizon-world/examples/probe/player_hurt_fixture.rs similarity index 94% rename from crates/horizon-world/examples/player_hurt_fixture.rs rename to crates/horizon-world/examples/probe/player_hurt_fixture.rs index 54a5ed5e4..6e77abf71 100644 --- a/crates/horizon-world/examples/player_hurt_fixture.rs +++ b/crates/horizon-world/examples/probe/player_hurt_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::living_hurt::{HurtState, HurtTag, HurtWorld}; use horizon_world::{ food::Difficulty, @@ -15,19 +16,12 @@ use std::{ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn state(s: &HurtState<()>) -> String { format!( "{} {} {:08x} {} {} {} {}", s.no_action_time, s.cooldown, - bits(s.last_hurt), + f32_bits(s.last_hurt), s.hurt_duration, s.hurt_time, s.last_source.is_some(), @@ -134,7 +128,7 @@ impl HurtWorld for Env<'_> { Ok(self.flag("component")) } fn apply_blocking(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result { - self.event(&format!("blocking {:08x}", bits(v)))?; + self.event(&format!("blocking {:08x}", f32_bits(v)))?; Ok(single(&self.op["blocked"])) } fn helmet_empty(&mut self, _: &mut HurtState<()>) -> io::Result { @@ -142,10 +136,10 @@ impl HurtWorld for Env<'_> { Ok(!self.flag("helmet")) } fn hurt_helmet(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result<()> { - self.event(&format!("hurt-helmet {:08x}", bits(v))) + self.event(&format!("hurt-helmet {:08x}", f32_bits(v))) } fn actually_hurt(&mut self, s: &mut HurtState<()>, v: f32) -> io::Result<()> { - self.event(&format!("hurt {:08x} {}", bits(v), state(s)))?; + self.event(&format!("hurt {:08x} {}", f32_bits(v), state(s)))?; self.hit = true; self.recorded = v; if self.flag("mutate_hit") { @@ -163,7 +157,7 @@ impl HurtWorld for Env<'_> { Ok(()) } fn knockback(&mut self, _: &mut HurtState<()>, v: f32, b: bool) -> io::Result<()> { - self.event(&format!("knockback {:08x} {b}", bits(v))) + self.event(&format!("knockback {:08x} {b}", f32_bits(v))) } fn death_protection(&mut self, _: &mut HurtState<()>) -> io::Result { self.event("tag bypasses_invulnerability")?; @@ -187,7 +181,7 @@ impl HurtWorld for Env<'_> { fn effects_on_hurt(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result<()> { self.event("effects")?; for i in 0..self.op["effects"].as_u64().unwrap() { - self.event(&format!("effect {i} {:08x}", bits(v)))?; + self.event(&format!("effect {i} {:08x}", f32_bits(v)))?; } Ok(()) } @@ -263,8 +257,8 @@ impl ServerPlayerHurtWorld for Env<'_> { Ok(self.flag("can_harm")) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -303,7 +297,7 @@ fn main() -> Result<(), Box> { e.out, "state {} {:08x} {} {}", state(&s), - bits(recorded), + f32_bits(recorded), e.hit, e.calls )?; diff --git a/crates/horizon-world/examples/player_inventory_fixture.rs b/crates/horizon-world/examples/probe/player_inventory_fixture.rs similarity index 99% rename from crates/horizon-world/examples/player_inventory_fixture.rs rename to crates/horizon-world/examples/probe/player_inventory_fixture.rs index a3e2625e2..418fb9a3e 100644 --- a/crates/horizon-world/examples/player_inventory_fixture.rs +++ b/crates/horizon-world/examples/probe/player_inventory_fixture.rs @@ -142,8 +142,8 @@ impl Output { writeln!(self.out, "empty {e}").unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/player_travel_fixture.rs b/crates/horizon-world/examples/probe/player_travel_fixture.rs similarity index 94% rename from crates/horizon-world/examples/player_travel_fixture.rs rename to crates/horizon-world/examples/probe/player_travel_fixture.rs index 47adeaeb7..e4d493662 100644 --- a/crates/horizon-world/examples/player_travel_fixture.rs +++ b/crates/horizon-world/examples/probe/player_travel_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::player_travel::*; use serde_json::Value; @@ -15,18 +16,16 @@ fn single(v: &Value) -> f32 { fn vec(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn fbits(v: f32) -> u32 { if v.is_nan() { 0x7fc00000 } else { v.to_bits() } } fn vector(v: Vec3) -> String { - format!("{:016x} {:016x} {:016x}", bits(v.x), bits(v.y), bits(v.z)) + format!( + "{:016x} {:016x} {:016x}", + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) + ) } struct World<'a> { f: &'a Value, @@ -115,8 +114,8 @@ impl PlayerTravelWorld for World<'_> { Ok(()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/portal_travel_fixture.rs b/crates/horizon-world/examples/probe/portal_travel_fixture.rs similarity index 98% rename from crates/horizon-world/examples/portal_travel_fixture.rs rename to crates/horizon-world/examples/probe/portal_travel_fixture.rs index b0843e411..cda3ae248 100644 --- a/crates/horizon-world/examples/portal_travel_fixture.rs +++ b/crates/horizon-world/examples/probe/portal_travel_fixture.rs @@ -246,8 +246,8 @@ fn run(case: &Value, b: &Behaviours, air: BlockStateId, out: &mut Vec) { )); } -fn main() -> Result<(), Box> { - let mut args = std::env::args().skip(1); +pub fn main() -> Result<(), Box> { + let mut args = crate::args().skip(1); let resources = args.next().expect("resource directory"); let cases = args.next().expect("case file"); let output = args.next().expect("output file"); diff --git a/crates/horizon-world/examples/registered_player_combat_fixture.rs b/crates/horizon-world/examples/probe/registered_player_combat_fixture.rs similarity index 95% rename from crates/horizon-world/examples/registered_player_combat_fixture.rs rename to crates/horizon-world/examples/probe/registered_player_combat_fixture.rs index 01afec289..c70881165 100644 --- a/crates/horizon-world/examples/registered_player_combat_fixture.rs +++ b/crates/horizon-world/examples/probe/registered_player_combat_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::damage_immunity::{DamageRule, ImmunityTag, ImmunityWorld}; use horizon_world::damage_source::{ Catalog as DamageCatalog, DamageSource, EntityKind, SourceWorld, @@ -31,19 +32,12 @@ use std::{ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn state(s: &HurtState<()>) -> String { format!( "{} {} {:08x} {} {} {} {}", s.no_action_time, s.cooldown, - bits(s.last_hurt), + f32_bits(s.last_hurt), s.hurt_duration, s.hurt_time, s.last_source.is_some(), @@ -151,7 +145,7 @@ impl HurtWorld for Env<'_> { Ok(self.flag("component")) } fn apply_blocking(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result { - self.event(&format!("blocking {:08x}", bits(v)))?; + self.event(&format!("blocking {:08x}", f32_bits(v)))?; Ok(single(&self.op["blocked"])) } fn helmet_empty(&mut self, _: &mut HurtState<()>) -> io::Result { @@ -159,7 +153,7 @@ impl HurtWorld for Env<'_> { Ok(!self.flag("helmet")) } fn hurt_helmet(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result<()> { - self.event(&format!("hurt-helmet {:08x}", bits(v))) + self.event(&format!("hurt-helmet {:08x}", f32_bits(v))) } fn actually_hurt(&mut self, _s: &mut HurtState<()>, _v: f32) -> io::Result<()> { panic!("combat binding supplies actual inner damage") @@ -171,7 +165,7 @@ impl HurtWorld for Env<'_> { Ok(()) } fn knockback(&mut self, _: &mut HurtState<()>, v: f32, b: bool) -> io::Result<()> { - self.event(&format!("knockback {:08x} {b}", bits(v))) + self.event(&format!("knockback {:08x} {b}", f32_bits(v))) } fn death_protection(&mut self, _: &mut HurtState<()>) -> io::Result { if !self @@ -197,7 +191,7 @@ impl HurtWorld for Env<'_> { fn effects_on_hurt(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result<()> { self.event("effects")?; for i in 0..self.op["effects"].as_u64().unwrap() { - self.event(&format!("effect {i} {:08x}", bits(v)))?; + self.event(&format!("effect {i} {:08x}", f32_bits(v)))?; } Ok(()) } @@ -280,7 +274,7 @@ fn values(v: Option<&[FloatValue]>) -> String { Some([]) => "empty".into(), Some(v) => v .iter() - .map(|v| format!("{}:{:08x}", v.id, bits(v.value))) + .map(|v| format!("{}:{:08x}", v.id, f32_bits(v.value))) .collect::>() .join(","), } @@ -290,7 +284,7 @@ impl Observer for Env<'_> { fn updated(&mut self, data: &mut SyncedFloats, id: u8) -> io::Result<()> { self.event(&format!( "updated {id} {:08x} {}", - bits(data.get(id).unwrap()), + f32_bits(data.get(id).unwrap()), data.is_dirty() ))?; if self.flag("pack_callback") { @@ -329,7 +323,7 @@ impl ServerDamageEnvironment for Env<'_> { Ok(self.source.bypasses(b)) } fn hurt_armor(&mut self, a: &mut EntityAttributes, v: f32) -> io::Result<()> { - self.event(&format!("hurt-armor {:08x}", bits(v)))?; + self.event(&format!("hurt-armor {:08x}", f32_bits(v)))?; if self.flag("break_armor") { let id = a.catalog().id("minecraft:armor").unwrap(); a.edit(id, |a, o| { @@ -387,7 +381,7 @@ impl ServerDamageEnvironment for Env<'_> { } fn record_damage(&mut self, v: f32) -> io::Result<()> { self.event("tracker")?; - self.event(&format!("record {:08x}", bits(v)))?; + self.event(&format!("record {:08x}", f32_bits(v)))?; self.recorded = v; self.hit = true; Ok(()) @@ -401,8 +395,8 @@ impl CombatEnvironment for Env<'_> { self.dead } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let damage_catalog = DamageCatalog::from_json( &serde_json::from_str(&fs::read_to_string(dir.join("damage/catalog.json"))?)?, @@ -513,16 +507,16 @@ fn main() -> Result<(), Box> { e.out, "state {} {:08x} {} {}", state(&s), - bits(recorded), + f32_bits(recorded), e.hit, e.calls )?; writeln!( e.out, "storage {:08x} {:08x} {:08x} {} {} {} {}", - bits(data.get(ids.health).unwrap()), - bits(data.get(ids.absorption).unwrap()), - bits(food.exhaustion), + f32_bits(data.get(ids.health).unwrap()), + f32_bits(data.get(ids.absorption).unwrap()), + f32_bits(food.exhaustion), data.is_dirty(), data.item_dirty(ids.health).unwrap(), data.item_dirty(ids.absorption).unwrap(), diff --git a/crates/horizon-world/examples/registry_collision_scan_fixture.rs b/crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs similarity index 92% rename from crates/horizon-world/examples/registry_collision_scan_fixture.rs rename to crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs index 9e3a19914..b66812142 100644 --- a/crates/horizon-world/examples/registry_collision_scan_fixture.rs +++ b/crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs @@ -1,4 +1,5 @@ //! Integrated registry/cursor differential transport using resident TerrainChunk storage. +use crate::support::shapes::{emit, values}; use horizon_core::{ geometry::{Aabb, Axis, Vec3, VoxelShape}, position::{BlockPos, ChunkPos}, @@ -43,70 +44,6 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn values( - out: &mut impl Write, - label: &str, - values: impl IntoIterator, -) -> io::Result<()> { - write!(out, "{label}")?; - for v in values { - let bits = if v.is_nan() { - 0x7ff8_0000_0000_0000 - } else { - v.to_bits() - }; - write!(out, " {bits:016x}")?; - } - writeln!(out) -} -fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { - values( - out, - label, - [ - b.min(Axis::X), - b.min(Axis::Y), - b.min(Axis::Z), - b.max(Axis::X), - b.max(Axis::Y), - b.max(Axis::Z), - ], - ) -} -fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { - writeln!( - out, - "shape {} {} {}", - shape.is_empty(), - shape.boxes().len(), - shape.is_cube() - )?; - for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { - values(out, name, shape.coordinates(axis).iter().copied())?; - } - let axes = shape.cube_coordinate_axes(); - writeln!( - out, - "axes {}", - u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) - )?; - values( - out, - "extrema", - Axis::ALL - .map(|a| shape.min(a)) - .into_iter() - .chain(Axis::ALL.map(|a| shape.max(a))), - )?; - match shape.bounds() { - Some(b) => box_values(out, "bounds", b)?, - None => writeln!(out, "bounds none")?, - } - for b in shape.boxes() { - box_values(out, "box", *b)?; - } - Ok(()) -} struct Trace { out: io::BufWriter, calls: i32, @@ -382,8 +319,8 @@ impl CollisionChunks for World<'_> { &mut self.chunks.get_mut(&(p.x, p.z)).unwrap().1 } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name| -> Result<_, Box> { Ok( diff --git a/crates/horizon-world/examples/registry_fall_ray_fixture.rs b/crates/horizon-world/examples/probe/registry_fall_ray_fixture.rs similarity index 94% rename from crates/horizon-world/examples/registry_fall_ray_fixture.rs rename to crates/horizon-world/examples/probe/registry_fall_ray_fixture.rs index 3f2ebce75..c4f61644c 100644 --- a/crates/horizon-world/examples/registry_fall_ray_fixture.rs +++ b/crates/horizon-world/examples/probe/registry_fall_ray_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::{ entity_obstruction::EntityIdentity, @@ -21,13 +22,6 @@ fn number(v: &Value) -> f64 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn pos(p: BlockPos) -> String { format!("{} {} {}", p.x, p.y, p.z) } @@ -86,8 +80,8 @@ impl FallRayWorld for World<'_, '_, '_> { Ok(self.f["delay"].as_i64().unwrap() as i32) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); let read = |n: &str| -> Result> { @@ -181,9 +175,9 @@ fn main() -> Result<(), Box> { w.out, "hit {} {:016x} {:016x} {:016x} {} {} {}", r.miss, - bits(h.location.x), - bits(h.location.y), - bits(h.location.z), + f64_bits(h.location.x), + f64_bits(h.location.y), + f64_bits(h.location.z), format!("{:?}", h.direction).to_lowercase(), pos(h.block), h.inside diff --git a/crates/horizon-world/examples/registry_fluid_fixture.rs b/crates/horizon-world/examples/probe/registry_fluid_fixture.rs similarity index 97% rename from crates/horizon-world/examples/registry_fluid_fixture.rs rename to crates/horizon-world/examples/probe/registry_fluid_fixture.rs index de6e111a6..45cd272b0 100644 --- a/crates/horizon-world/examples/registry_fluid_fixture.rs +++ b/crates/horizon-world/examples/probe/registry_fluid_fixture.rs @@ -67,8 +67,8 @@ impl DynamicSupportWorld for World<'_> { Ok(None) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); let load = |n: &str| -> Result<_, Box> { diff --git a/crates/horizon-world/examples/replace_block_fixture.rs b/crates/horizon-world/examples/probe/replace_block_fixture.rs similarity index 92% rename from crates/horizon-world/examples/replace_block_fixture.rs rename to crates/horizon-world/examples/probe/replace_block_fixture.rs index 7a8d00363..d0a742f99 100644 --- a/crates/horizon-world/examples/replace_block_fixture.rs +++ b/crates/horizon-world/examples/probe/replace_block_fixture.rs @@ -1,4 +1,5 @@ //! Feature world transport retaining ordered mutations and partial failures. +use crate::support::common::tag; use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; use horizon_world::{ DATA_VERSION, @@ -135,19 +136,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -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(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - _ => panic!("invalid registry metadata"), - } -} -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let registry = BlockRegistry::from_nbt(&Tag::compound([ diff --git a/crates/horizon-world/examples/restitution_fixture.rs b/crates/horizon-world/examples/probe/restitution_fixture.rs similarity index 93% rename from crates/horizon-world/examples/restitution_fixture.rs rename to crates/horizon-world/examples/probe/restitution_fixture.rs index d32532a82..0d630274e 100644 --- a/crates/horizon-world/examples/restitution_fixture.rs +++ b/crates/horizon-world/examples/probe/restitution_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::{ movement_restitution::{RestitutionInput, RestitutionWorld, restitute_movement}, @@ -18,19 +19,12 @@ fn single(v: &Value) -> f32 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn vector_text(prefix: &str, v: Vec3) -> String { format!( "{prefix} {:016x} {:016x} {:016x}", - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) ) } struct World<'a, W> { @@ -102,7 +96,7 @@ impl RestitutionWorld for World<'_, W> { p.x, p.y, p.z, - bits(fall) + f64_bits(fall) ))?; if self.f["mutate"].as_bool().unwrap() { self.velocity = Vec3::new(17.0, 18.0, 19.0); @@ -121,8 +115,8 @@ impl RestitutionWorld for World<'_, W> { Ok(()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/retrogen_data_fixture.rs b/crates/horizon-world/examples/probe/retrogen_data_fixture.rs similarity index 97% rename from crates/horizon-world/examples/retrogen_data_fixture.rs rename to crates/horizon-world/examples/probe/retrogen_data_fixture.rs index 1f35cb363..3980d1234 100644 --- a/crates/horizon-world/examples/retrogen_data_fixture.rs +++ b/crates/horizon-world/examples/probe/retrogen_data_fixture.rs @@ -51,8 +51,8 @@ fn tag(row: &Value) -> Tag { _ => panic!("unknown tag"), } } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let mut out = io::BufWriter::new(fs::File::create(&args[2])?); for (index, line) in fs::read_to_string(&args[1])?.lines().enumerate() { writeln!(out, "case {index}")?; diff --git a/crates/horizon-world/examples/rule_test_fixture.rs b/crates/horizon-world/examples/probe/rule_test_fixture.rs similarity index 85% rename from crates/horizon-world/examples/rule_test_fixture.rs rename to crates/horizon-world/examples/probe/rule_test_fixture.rs index 31fa4c436..42a25532c 100644 --- a/crates/horizon-world/examples/rule_test_fixture.rs +++ b/crates/horizon-world/examples/probe/rule_test_fixture.rs @@ -1,4 +1,5 @@ //! Differential transport for replacement rules over pinned block identities. +use crate::support::common::tag; use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; use horizon_world::{ DATA_VERSION, @@ -41,19 +42,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -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(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - _ => panic!("invalid registry metadata"), - } -} -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let registry = BlockRegistry::from_nbt(&Tag::compound([ diff --git a/crates/horizon-world/examples/scattered_ore_fixture.rs b/crates/horizon-world/examples/probe/scattered_ore_fixture.rs similarity index 93% rename from crates/horizon-world/examples/scattered_ore_fixture.rs rename to crates/horizon-world/examples/probe/scattered_ore_fixture.rs index bc9dd9200..91b6821b7 100644 --- a/crates/horizon-world/examples/scattered_ore_fixture.rs +++ b/crates/horizon-world/examples/probe/scattered_ore_fixture.rs @@ -1,4 +1,5 @@ //! Feature world transport retaining ordered mutations and partial failures. +use crate::support::common::tag; use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; use horizon_world::{ DATA_VERSION, @@ -159,19 +160,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -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(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - _ => panic!("invalid registry metadata"), - } -} -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let registry = BlockRegistry::from_nbt(&Tag::compound([ diff --git a/crates/horizon-world/examples/server_player_combat_fixture.rs b/crates/horizon-world/examples/probe/server_player_combat_fixture.rs similarity index 95% rename from crates/horizon-world/examples/server_player_combat_fixture.rs rename to crates/horizon-world/examples/probe/server_player_combat_fixture.rs index ac911a7c8..9607dcec2 100644 --- a/crates/horizon-world/examples/server_player_combat_fixture.rs +++ b/crates/horizon-world/examples/probe/server_player_combat_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::damage_immunity::{DamageRule, ImmunityTag, ImmunityWorld}; use horizon_world::living_hurt::{HurtState, HurtTag, HurtWorld}; use horizon_world::{ @@ -84,19 +85,12 @@ impl FixtureAttributes for Live { fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn state(s: &HurtState<()>) -> String { format!( "{} {} {:08x} {} {} {} {}", s.no_action_time, s.cooldown, - bits(s.last_hurt), + f32_bits(s.last_hurt), s.hurt_duration, s.hurt_time, s.last_source.is_some(), @@ -208,7 +202,7 @@ impl HurtWorld for Env<'_> { Ok(self.flag("component")) } fn apply_blocking(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result { - self.event(&format!("blocking {:08x}", bits(v)))?; + self.event(&format!("blocking {:08x}", f32_bits(v)))?; Ok(single(&self.op["blocked"])) } fn helmet_empty(&mut self, _: &mut HurtState<()>) -> io::Result { @@ -216,7 +210,7 @@ impl HurtWorld for Env<'_> { Ok(!self.flag("helmet")) } fn hurt_helmet(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result<()> { - self.event(&format!("hurt-helmet {:08x}", bits(v))) + self.event(&format!("hurt-helmet {:08x}", f32_bits(v))) } fn actually_hurt(&mut self, _s: &mut HurtState<()>, _v: f32) -> io::Result<()> { panic!("combat binding supplies actual inner damage") @@ -228,7 +222,7 @@ impl HurtWorld for Env<'_> { Ok(()) } fn knockback(&mut self, _: &mut HurtState<()>, v: f32, b: bool) -> io::Result<()> { - self.event(&format!("knockback {:08x} {b}", bits(v))) + self.event(&format!("knockback {:08x} {b}", f32_bits(v))) } fn death_protection(&mut self, _: &mut HurtState<()>) -> io::Result { self.event("tag bypasses_invulnerability")?; @@ -252,7 +246,7 @@ impl HurtWorld for Env<'_> { fn effects_on_hurt(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result<()> { self.event("effects")?; for i in 0..self.op["effects"].as_u64().unwrap() { - self.event(&format!("effect {i} {:08x}", bits(v)))?; + self.event(&format!("effect {i} {:08x}", f32_bits(v)))?; } Ok(()) } @@ -337,7 +331,7 @@ fn values(v: Option<&[FloatValue]>) -> String { Some([]) => "empty".into(), Some(v) => v .iter() - .map(|v| format!("{}:{:08x}", v.id, bits(v.value))) + .map(|v| format!("{}:{:08x}", v.id, f32_bits(v.value))) .collect::>() .join(","), } @@ -347,7 +341,7 @@ impl Observer for Env<'_> { fn updated(&mut self, data: &mut SyncedFloats, id: u8) -> io::Result<()> { self.event(&format!( "updated {id} {:08x} {}", - bits(data.get(id).unwrap()), + f32_bits(data.get(id).unwrap()), data.is_dirty() ))?; if self.flag("pack_callback") { @@ -393,7 +387,7 @@ impl ServerDamageEnvironment for Env<'_> { Ok(self.flag(&format!("bypass_{n}"))) } fn hurt_armor(&mut self, a: &mut A, v: f32) -> io::Result<()> { - self.event(&format!("hurt-armor {:08x}", bits(v)))?; + self.event(&format!("hurt-armor {:08x}", f32_bits(v)))?; if self.flag("break_armor") { a.configure("minecraft:armor", number(&self.op["armor_after"]), None); } @@ -447,7 +441,7 @@ impl ServerDamageEnvironment for Env<'_> { } fn record_damage(&mut self, v: f32) -> io::Result<()> { self.event("tracker")?; - self.event(&format!("record {:08x}", bits(v)))?; + self.event(&format!("record {:08x}", f32_bits(v)))?; self.recorded = v; self.hit = true; Ok(()) @@ -461,10 +455,10 @@ impl CombatEnvironment for Env<'_> { self.dead } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); - if std::env::args().nth(2).as_deref() == Some("--live") { + if crate::args().nth(2).as_deref() == Some("--live") { run::(dir, "rust-live.txt") } else { run::(dir, "rust.txt") @@ -554,16 +548,16 @@ fn run(dir: &Path, output: &str) -> Result<(), Box f32 { fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn values(v: Option<&[FloatValue]>) -> String { match v { None => "none".into(), Some([]) => "empty".into(), Some(v) => v .iter() - .map(|v| format!("{}:{:08x}", v.id, bits(v.value))) + .map(|v| format!("{}:{:08x}", v.id, f32_bits(v.value))) .collect::>() .join(","), } @@ -69,7 +63,7 @@ impl Observer for Env<'_> { fn updated(&mut self, data: &mut SyncedFloats, id: u8) -> io::Result<()> { self.event(&format!( "updated {id} {:08x} {}", - bits(data.get(id).unwrap()), + f32_bits(data.get(id).unwrap()), data.is_dirty() ))?; if self.flag("pack_callback") { @@ -115,7 +109,7 @@ impl ServerDamageEnvironment for Env<'_> { Ok(self.flag(&format!("bypass_{n}"))) } fn hurt_armor(&mut self, a: &mut EntityAttributes, v: f32) -> io::Result<()> { - self.event(&format!("hurt-armor {:08x}", bits(v)))?; + self.event(&format!("hurt-armor {:08x}", f32_bits(v)))?; if self.flag("break_armor") { let id = a.catalog().id("minecraft:armor").unwrap(); a.edit(id, |a, o| { @@ -174,7 +168,7 @@ impl ServerDamageEnvironment for Env<'_> { } fn record_damage(&mut self, v: f32) -> io::Result<()> { self.event("tracker")?; - self.event(&format!("record {:08x}", bits(v)))?; + self.event(&format!("record {:08x}", f32_bits(v)))?; self.recorded = v; Ok(()) } @@ -182,8 +176,8 @@ impl ServerDamageEnvironment for Env<'_> { self.event("damage-event") } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let ids: Value = serde_json::from_str(&fs::read_to_string(dir.join("ids.json"))?)?; let ids = PlayerFloatIds { @@ -255,10 +249,10 @@ fn main() -> Result<(), Box> { writeln!( env.out, "state {:08x} {:08x} {:08x} {:08x} {} {} {} {}", - bits(data.get(ids.health).unwrap()), - bits(data.get(ids.absorption).unwrap()), - bits(food.exhaustion), - bits(recorded), + f32_bits(data.get(ids.health).unwrap()), + f32_bits(data.get(ids.absorption).unwrap()), + f32_bits(food.exhaustion), + f32_bits(recorded), data.is_dirty(), data.item_dirty(ids.health).unwrap(), data.item_dirty(ids.absorption).unwrap(), diff --git a/crates/horizon-world/examples/simple_block_fixture.rs b/crates/horizon-world/examples/probe/simple_block_fixture.rs similarity index 99% rename from crates/horizon-world/examples/simple_block_fixture.rs rename to crates/horizon-world/examples/probe/simple_block_fixture.rs index 742f3b39f..232e56f94 100644 --- a/crates/horizon-world/examples/simple_block_fixture.rs +++ b/crates/horizon-world/examples/probe/simple_block_fixture.rs @@ -553,8 +553,8 @@ fn fixture( )?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name: &str| -> Result> { Ok( diff --git a/crates/horizon-world/examples/simple_container_fixture.rs b/crates/horizon-world/examples/probe/simple_container_fixture.rs similarity index 98% rename from crates/horizon-world/examples/simple_container_fixture.rs rename to crates/horizon-world/examples/probe/simple_container_fixture.rs index 44f9a382a..c6aef9c2a 100644 --- a/crates/horizon-world/examples/simple_container_fixture.rs +++ b/crates/horizon-world/examples/probe/simple_container_fixture.rs @@ -120,8 +120,8 @@ impl ContainerHooks for World { self.event(c, "changed") } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/spawn_origin.rs b/crates/horizon-world/examples/probe/spawn_origin.rs similarity index 76% rename from crates/horizon-world/examples/spawn_origin.rs rename to crates/horizon-world/examples/probe/spawn_origin.rs index 727b25a91..7162a00a8 100644 --- a/crates/horizon-world/examples/spawn_origin.rs +++ b/crates/horizon-world/examples/probe/spawn_origin.rs @@ -3,6 +3,7 @@ //! (NoiseBasedChunkGenerator.getOrigin), as `seed x z chunk_x chunk_z` lines. //! //! usage: spawn_origin ... +use crate::support::common::tag; use horizon_world::{ DATA_VERSION, nbt::Tag, @@ -14,17 +15,6 @@ use std::{fs, path::Path}; 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 states = facts["states"].as_array().ok_or("facts states")?; @@ -39,8 +29,8 @@ fn registry(resources: &Path) -> Result<&'static BlockRegistry, Error> { Ok(Box::leak(Box::new(registry))) } -fn main() -> Result<(), Error> { - let mut args = std::env::args().skip(1); +pub fn main() -> Result<(), Error> { + let mut args = crate::args().skip(1); let resources = std::path::PathBuf::from(args.next().ok_or("client resource directory")?); let data = GeneratorData::load(&resources.join("worldgen"), registry(&resources)?)?; for seed in args { diff --git a/crates/horizon-world/examples/state_provider_fixture.rs b/crates/horizon-world/examples/probe/state_provider_fixture.rs similarity index 97% rename from crates/horizon-world/examples/state_provider_fixture.rs rename to crates/horizon-world/examples/probe/state_provider_fixture.rs index e8a8f9f5a..6164e5d6c 100644 --- a/crates/horizon-world/examples/state_provider_fixture.rs +++ b/crates/horizon-world/examples/probe/state_provider_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::tag; use horizon_core::random::{LegacyRandom, RandomSource, WorldgenRandom, XoroshiroRandom}; use horizon_world::{ DATA_VERSION, @@ -288,19 +289,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -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(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - _ => panic!("invalid registry metadata"), - } -} -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let registry = BlockRegistry::from_nbt(&Tag::compound([ diff --git a/crates/horizon-world/examples/status_effect_fixture.rs b/crates/horizon-world/examples/probe/status_effect_fixture.rs similarity index 97% rename from crates/horizon-world/examples/status_effect_fixture.rs rename to crates/horizon-world/examples/probe/status_effect_fixture.rs index 759aad818..c1307dd3a 100644 --- a/crates/horizon-world/examples/status_effect_fixture.rs +++ b/crates/horizon-world/examples/probe/status_effect_fixture.rs @@ -138,8 +138,8 @@ fn run(f: Value, out: &mut dyn Write) { dump(out, &slots, &mut ids); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/status_tick_fixture.rs b/crates/horizon-world/examples/probe/status_tick_fixture.rs similarity index 98% rename from crates/horizon-world/examples/status_tick_fixture.rs rename to crates/horizon-world/examples/probe/status_tick_fixture.rs index 22aa0d412..23492971c 100644 --- a/crates/horizon-world/examples/status_tick_fixture.rs +++ b/crates/horizon-world/examples/probe/status_tick_fixture.rs @@ -210,8 +210,8 @@ fn run(f: Value, out: &mut dyn Write) { w.all(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/stepped_interpolation_fixture.rs b/crates/horizon-world/examples/probe/stepped_interpolation_fixture.rs similarity index 98% rename from crates/horizon-world/examples/stepped_interpolation_fixture.rs rename to crates/horizon-world/examples/probe/stepped_interpolation_fixture.rs index d2228d8b5..568e5ded8 100644 --- a/crates/horizon-world/examples/stepped_interpolation_fixture.rs +++ b/crates/horizon-world/examples/probe/stepped_interpolation_fixture.rs @@ -10,8 +10,8 @@ fn set_rot(entity: &mut PosRot, yaw: f32, pitch: f32) { entity.pitch = (pitch % 360.0 % 360.0).clamp(-90.0, 90.0); } -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let input = std::fs::read_to_string(&args[1]).expect("input"); let mut out = String::new(); let mut handler = SteppedInterpolation::new(0); diff --git a/crates/horizon-world/examples/stored_consume_fixture.rs b/crates/horizon-world/examples/probe/stored_consume_fixture.rs similarity index 98% rename from crates/horizon-world/examples/stored_consume_fixture.rs rename to crates/horizon-world/examples/probe/stored_consume_fixture.rs index 7fd9abc91..8f8f6046a 100644 --- a/crates/horizon-world/examples/stored_consume_fixture.rs +++ b/crates/horizon-world/examples/probe/stored_consume_fixture.rs @@ -390,9 +390,9 @@ fn run(f: Value, out: &mut dyn Write, make: fn(i64) -> R) { writeln!(w.out, "random {i} {} {}", r.next_long(), r.next_long()).unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); - let side = std::env::args().nth(2).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); + let side = crate::args().nth(2).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{side}.txt")))?); for line in fs::read_to_string(dir.join(format!("inputs-{side}.txt")))?.lines() { diff --git a/crates/horizon-world/examples/stored_effect_attributes_fixture.rs b/crates/horizon-world/examples/probe/stored_effect_attributes_fixture.rs similarity index 96% rename from crates/horizon-world/examples/stored_effect_attributes_fixture.rs rename to crates/horizon-world/examples/probe/stored_effect_attributes_fixture.rs index 6abc4f79f..10ae7bf63 100644 --- a/crates/horizon-world/examples/stored_effect_attributes_fixture.rs +++ b/crates/horizon-world/examples/probe/stored_effect_attributes_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_hex; use horizon_world::{ attribute_map::AttributeMap, attributes::{AttributeError, Definition, Instance, Modifier, Observer, Operation}, @@ -38,16 +39,6 @@ enum Stop { Null, Bounds, } -fn bits(v: f64) -> String { - format!( - "{:016x}", - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } - ) -} fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } @@ -118,7 +109,7 @@ impl World { format!( "{id}:{}:{}:{}", m.id(), - bits(m.amount()), + f64_hex(m.amount()), m.operation() as u8 ) }) @@ -162,9 +153,9 @@ impl World { let prefix = format!( "instance {id} {} {} {} {}", n.key.id, - bits(a.base_value()), + f64_hex(a.base_value()), a.is_dirty(), - bits(a.cached_value()) + f64_hex(a.cached_value()) ); let all = a.modifiers().to_vec(); let permanent = a.permanent_modifiers().to_vec(); @@ -348,8 +339,8 @@ fn effect_error(e: effects::Error) -> Stop { effects::Error::MissingTemplate | effects::Error::Cursor(_) => Stop::Null, } } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let dir = Path::new(&args[1]); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{}.txt", args[2])))?); for line in fs::read_to_string(dir.join(format!("inputs-{}.txt", args[2])))?.lines() { @@ -469,7 +460,7 @@ fn main() -> Result<(), Box> { "value" => world .handle(op["instance"].as_i64().unwrap()) .and_then(|h| h.ok_or(Stop::Null)) - .map(|h| bits(world.instances[h.id].value.as_mut().unwrap().value())), + .map(|h| f64_hex(world.instances[h.id].value.as_mut().unwrap().value())), _ => world.raw(&mut map, op).map(|()| "ok".into()), }; world.logs.push(format!( diff --git a/crates/horizon-world/examples/stored_effect_notifications_fixture.rs b/crates/horizon-world/examples/probe/stored_effect_notifications_fixture.rs similarity index 98% rename from crates/horizon-world/examples/stored_effect_notifications_fixture.rs rename to crates/horizon-world/examples/probe/stored_effect_notifications_fixture.rs index 96c089857..9dccc7cf8 100644 --- a/crates/horizon-world/examples/stored_effect_notifications_fixture.rs +++ b/crates/horizon-world/examples/probe/stored_effect_notifications_fixture.rs @@ -169,7 +169,7 @@ mod integration { } } pub fn run() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); + let args: Vec<_> = crate::args().collect(); let dir = Path::new(&args[1]); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{}.txt", args[2])))?); @@ -329,7 +329,7 @@ mod integration { "value" => world .handle(op["instance"].as_i64().unwrap()) .and_then(|h| h.ok_or(Stop::Null)) - .map(|h| bits(world.instances[h.id].value.as_mut().unwrap().value())), + .map(|h| f64_hex(world.instances[h.id].value.as_mut().unwrap().value())), _ => world.raw(&mut map, op).map(|()| "ok".into()), }; world.logs.push(format!( @@ -352,6 +352,6 @@ mod integration { Ok(()) } } -fn main() -> Result<(), Box> { +pub fn main() -> Result<(), Box> { integration::run() } diff --git a/crates/horizon-world/examples/structure_density_fixture.rs b/crates/horizon-world/examples/probe/structure_density_fixture.rs similarity index 96% rename from crates/horizon-world/examples/structure_density_fixture.rs rename to crates/horizon-world/examples/probe/structure_density_fixture.rs index 55ef66f83..2159bc566 100644 --- a/crates/horizon-world/examples/structure_density_fixture.rs +++ b/crates/horizon-world/examples/probe/structure_density_fixture.rs @@ -31,8 +31,8 @@ fn bits(value: f32) -> u32 { value.to_bits() } } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let mut out = io::BufWriter::new(fs::File::create(&args[2])?); for line in fs::read_to_string(&args[1])?.lines() { let f: Value = serde_json::from_str(line)?; diff --git a/crates/horizon-world/examples/suffocation_fixture.rs b/crates/horizon-world/examples/probe/suffocation_fixture.rs similarity index 97% rename from crates/horizon-world/examples/suffocation_fixture.rs rename to crates/horizon-world/examples/probe/suffocation_fixture.rs index 79a3ccfa0..3e1683394 100644 --- a/crates/horizon-world/examples/suffocation_fixture.rs +++ b/crates/horizon-world/examples/probe/suffocation_fixture.rs @@ -58,8 +58,8 @@ impl DynamicCollisionWorld for World<'_, W> { Ok(None) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name| -> Result<_, Box> { Ok( diff --git a/crates/horizon-world/examples/probe/support/common.rs b/crates/horizon-world/examples/probe/support/common.rs new file mode 100644 index 000000000..17c453363 --- /dev/null +++ b/crates/horizon-world/examples/probe/support/common.rs @@ -0,0 +1,49 @@ +//! Number formats and JSON readers several probes share. +use horizon_core::position::BlockPos; +use horizon_world::nbt::Tag; +use serde_json::Value; + +/// An f64's bits, every NaN as Java's canonical one (Double.doubleToLongBits). +pub fn f64_bits(v: f64) -> u64 { + if v.is_nan() { + f64::NAN.to_bits() + } else { + v.to_bits() + } +} + +/// An f32's bits, every NaN as Java's canonical one (Float.floatToIntBits). +pub fn f32_bits(v: f32) -> u32 { + if v.is_nan() { + f32::NAN.to_bits() + } else { + v.to_bits() + } +} + +/// f64_bits as 16 hex digits. +pub fn f64_hex(v: f64) -> String { + format!("{:016x}", f64_bits(v)) +} + +/// Registry metadata from the oracle's JSON as NBT: strings, ints, lists and compounds. +pub 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(m) => { + Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) + } + _ => panic!("invalid registry metadata"), + } +} + +/// A block position from a JSON `[x, y, z]`. +pub fn position(v: &Value) -> BlockPos { + BlockPos::new( + v[0].as_i64().unwrap() as i32, + v[1].as_i64().unwrap() as i32, + v[2].as_i64().unwrap() as i32, + ) +} diff --git a/crates/horizon-world/examples/support/decoration_storage.rs b/crates/horizon-world/examples/probe/support/decoration_storage.rs similarity index 100% rename from crates/horizon-world/examples/support/decoration_storage.rs rename to crates/horizon-world/examples/probe/support/decoration_storage.rs diff --git a/crates/horizon-world/examples/support/placement_queries.rs b/crates/horizon-world/examples/probe/support/placement_queries.rs similarity index 100% rename from crates/horizon-world/examples/support/placement_queries.rs rename to crates/horizon-world/examples/probe/support/placement_queries.rs diff --git a/crates/horizon-world/examples/probe/support/shapes.rs b/crates/horizon-world/examples/probe/support/shapes.rs new file mode 100644 index 000000000..eed5f436d --- /dev/null +++ b/crates/horizon-world/examples/probe/support/shapes.rs @@ -0,0 +1,85 @@ +//! Shapes and boxes printed the same way by the collision probes. +use super::common::f64_bits; +use horizon_core::geometry::{Aabb, Axis, VoxelShape}; +use std::io::{self, Write}; + +pub fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { + writeln!( + out, + "shape {} {} {}", + shape.is_empty(), + shape.boxes().len(), + shape.is_cube() + )?; + for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { + values(out, name, shape.coordinates(axis).iter().copied())?; + } + let axes = shape.cube_coordinate_axes(); + writeln!( + out, + "axes {}", + u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) + )?; + values( + out, + "extrema", + Axis::ALL + .map(|a| shape.min(a)) + .into_iter() + .chain(Axis::ALL.map(|a| shape.max(a))), + )?; + match shape.bounds() { + Some(b) => box_values(out, "bounds", b)?, + None => writeln!(out, "bounds none")?, + } + for b in shape.boxes() { + box_values(out, "box", *b)?; + } + Ok(()) +} + +/// `label` and each value's bits in hex, NaN as Java's canonical one. +pub fn values( + out: &mut impl Write, + label: &str, + values: impl IntoIterator, +) -> io::Result<()> { + write!(out, "{label}")?; + for v in values { + let bits = if v.is_nan() { + 0x7ff8_0000_0000_0000 + } else { + v.to_bits() + }; + write!(out, " {bits:016x}")?; + } + writeln!(out) +} + +pub fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { + values( + out, + label, + [ + b.min(Axis::X), + b.min(Axis::Y), + b.min(Axis::Z), + b.max(Axis::X), + b.max(Axis::Y), + b.max(Axis::Z), + ], + ) +} + +/// `label` and the box's six bounds' bits in hex. +pub fn bounds(label: &str, b: Aabb) -> String { + format!( + "{label} {:016x} {:016x} {:016x} {:016x} {:016x} {:016x}", + f64_bits(b.min(Axis::X)), + f64_bits(b.min(Axis::Y)), + f64_bits(b.min(Axis::Z)), + f64_bits(b.max(Axis::X)), + f64_bits(b.max(Axis::Y)), + f64_bits(b.max(Axis::Z)) + ) +} diff --git a/crates/horizon-world/examples/swimming_fixture.rs b/crates/horizon-world/examples/probe/swimming_fixture.rs similarity index 96% rename from crates/horizon-world/examples/swimming_fixture.rs rename to crates/horizon-world/examples/probe/swimming_fixture.rs index ebf58cf8b..b31c3a109 100644 --- a/crates/horizon-world/examples/swimming_fixture.rs +++ b/crates/horizon-world/examples/probe/swimming_fixture.rs @@ -79,8 +79,8 @@ impl PlayerSwimmingWorld for World<'_> { self.f["flying"].as_bool().unwrap() } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/synced_bytes_fixture.rs b/crates/horizon-world/examples/probe/synced_bytes_fixture.rs similarity index 98% rename from crates/horizon-world/examples/synced_bytes_fixture.rs rename to crates/horizon-world/examples/probe/synced_bytes_fixture.rs index 288e5fa7c..b6932a4fe 100644 --- a/crates/horizon-world/examples/synced_bytes_fixture.rs +++ b/crates/horizon-world/examples/probe/synced_bytes_fixture.rs @@ -114,8 +114,8 @@ impl Observer for Callback<'_> { self.event(&format!("assigned {}", values(Some(v)))) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/synced_floats_fixture.rs b/crates/horizon-world/examples/probe/synced_floats_fixture.rs similarity index 91% rename from crates/horizon-world/examples/synced_floats_fixture.rs rename to crates/horizon-world/examples/probe/synced_floats_fixture.rs index 4eb2e8046..7f649c18b 100644 --- a/crates/horizon-world/examples/synced_floats_fixture.rs +++ b/crates/horizon-world/examples/probe/synced_floats_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::synced_floats::{DataError, FloatValue, Observer, SyncedFloats}; use serde_json::Value; use std::{ @@ -8,13 +9,6 @@ use std::{ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn parse(v: &Value) -> Vec { v.as_array() .unwrap() @@ -31,7 +25,7 @@ fn values(v: Option<&[FloatValue]>) -> String { Some([]) => "empty".into(), Some(v) => v .iter() - .map(|v| format!("{}:{:08x}", v.id, bits(v.value))) + .map(|v| format!("{}:{:08x}", v.id, f32_bits(v.value))) .collect::>() .join(","), } @@ -59,7 +53,7 @@ impl Observer for Callback<'_> { fn updated(&mut self, data: &mut SyncedFloats, id: u8) -> io::Result<()> { self.event(&format!( "updated {id} {:08x} {} {}", - bits(data.get(id).unwrap()), + f32_bits(data.get(id).unwrap()), data.is_dirty(), data.item_dirty(id).unwrap() ))?; @@ -102,8 +96,8 @@ impl Observer for Callback<'_> { self.event(&format!("assigned {}", values(Some(v)))) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -129,7 +123,7 @@ fn main() -> Result<(), Box> { ), "assign" => data.assign(&parse(&op["values"]), &mut cb), "get" => data.get(id).map_err(DataError::UnknownId).and_then(|v| { - writeln!(cb.out, "get {:08x}", bits(v)).map_err(DataError::Observer) + writeln!(cb.out, "get {:08x}", f32_bits(v)).map_err(DataError::Observer) }), "pack" => writeln!(cb.out, "packed {}", values(data.take_dirty().as_deref())) .map_err(DataError::Observer), @@ -149,7 +143,7 @@ fn main() -> Result<(), Box> { writeln!( cb.out, "state {id} {:08x} {} {}", - bits(data.get(*id).unwrap()), + f32_bits(data.get(*id).unwrap()), data.item_dirty(*id).unwrap(), data.is_default(*id).unwrap() )?; diff --git a/crates/horizon-world/examples/teleport_consume_fixture.rs b/crates/horizon-world/examples/probe/teleport_consume_fixture.rs similarity index 92% rename from crates/horizon-world/examples/teleport_consume_fixture.rs rename to crates/horizon-world/examples/probe/teleport_consume_fixture.rs index 0c21b359c..595fa3855 100644 --- a/crates/horizon-world/examples/teleport_consume_fixture.rs +++ b/crates/horizon-world/examples/probe/teleport_consume_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{ geometry::Vec3, position::BlockPos, @@ -13,13 +14,6 @@ use std::{ fn n(v: &Value, k: &str) -> i32 { v[k].as_i64().unwrap() as i32 } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} struct World<'a, R> { f: Value, out: &'a mut dyn Write, @@ -63,10 +57,10 @@ impl World<'_, R> { self.attempts, self.changed, self.riding, - bits(self.pos.x), - bits(self.pos.y), - bits(self.pos.z), - bits(self.fall), + f64_bits(self.pos.x), + f64_bits(self.pos.y), + f64_bits(self.pos.z), + f64_bits(self.fall), self.grace, self.impact ) @@ -128,9 +122,9 @@ impl TeleportConsumeWorld for World<'_, R> { self.attempts += 1; self.event(format!( "teleport {} {} {}", - bits(p.x), - bits(p.y), - bits(p.z) + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z) ))?; let at = n(self.config(), "success_at"); let success = at >= 0 && i >= at; @@ -142,9 +136,9 @@ impl TeleportConsumeWorld for World<'_, R> { fn teleport_event(&mut self, l: i32, p: Vec3) -> Result<(), Self::Error> { self.event(format!( "game-event {l} {} {} {}", - bits(p.x), - bits(p.y), - bits(p.z) + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z) )) } fn is_fox(&self) -> bool { @@ -153,9 +147,9 @@ impl TeleportConsumeWorld for World<'_, R> { fn teleport_sound(&mut self, l: i32, p: Vec3, fox: bool) -> Result<(), Self::Error> { self.event(format!( "sound {l} {fox} {} {} {}", - bits(p.x), - bits(p.y), - bits(p.z) + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z) )) } fn block_position(&mut self) -> Result { @@ -220,8 +214,8 @@ fn run(f: Value, out: &mut dyn Write, make: fn(i64) -> R) { writeln!(w.out, "random {i} {} {}", r.next_long(), r.next_long()).unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/terrain_fixture.rs b/crates/horizon-world/examples/probe/terrain_fixture.rs similarity index 94% rename from crates/horizon-world/examples/terrain_fixture.rs rename to crates/horizon-world/examples/probe/terrain_fixture.rs index 09868a340..506273a10 100644 --- a/crates/horizon-world/examples/terrain_fixture.rs +++ b/crates/horizon-world/examples/probe/terrain_fixture.rs @@ -1,4 +1,5 @@ //! Test transport for registry-backed noise-stage filling against vanilla doFill. +use crate::support::common::tag; use horizon_core::{ density::{ Beardifier, JigsawJunction, RigidPiece, SamplerContext, StructureBounds, TerrainAdjustment, @@ -67,17 +68,6 @@ impl TerrainBlockStates for Properties<'_> { fn n(v: &Value) -> i32 { v.as_i64().unwrap() as i32 } -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(i) => Tag::Int(i.as_i64().unwrap() as i32), - Value::Object(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - _ => panic!("unsupported registry fixture value"), - } -} fn structure(v: &Value) -> Beardifier { let bounds = |v: &Value| { StructureBounds::new( @@ -239,8 +229,8 @@ fn fixture( } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let bundle: Value = serde_json::from_str(&fs::read_to_string(dir.join("registries.json"))?)?; diff --git a/crates/horizon-world/examples/tick_fixture.rs b/crates/horizon-world/examples/probe/tick_fixture.rs similarity index 93% rename from crates/horizon-world/examples/tick_fixture.rs rename to crates/horizon-world/examples/probe/tick_fixture.rs index 7b5bfa8ed..9e31fa5b6 100644 --- a/crates/horizon-world/examples/tick_fixture.rs +++ b/crates/horizon-world/examples/probe/tick_fixture.rs @@ -11,12 +11,8 @@ use horizon_world::{ tick_data::TickKind, }; use std::{collections::BTreeMap, error::Error, fs, path::PathBuf}; -fn main() -> Result<(), Box> { - let base = PathBuf::from( - std::env::args() - .nth(1) - .ok_or("expected fixture directory")?, - ); +pub fn main() -> Result<(), Box> { + let base = PathBuf::from(crate::args().nth(1).ok_or("expected fixture directory")?); let bytes = fs::read(base.join("ticks-input.nbt"))?; let (root, used) = nbt::read_named(&bytes, Limits::default())?; assert_eq!(used, bytes.len()); diff --git a/crates/horizon-world/examples/tree_feature_fixture.rs b/crates/horizon-world/examples/probe/tree_feature_fixture.rs similarity index 99% rename from crates/horizon-world/examples/tree_feature_fixture.rs rename to crates/horizon-world/examples/probe/tree_feature_fixture.rs index 0de4fd562..3222254bd 100644 --- a/crates/horizon-world/examples/tree_feature_fixture.rs +++ b/crates/horizon-world/examples/probe/tree_feature_fixture.rs @@ -486,8 +486,8 @@ fn survival_rule(rule: &str) -> SurvivalRule { _ => panic!("unknown rule {rule}"), } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name: &str| -> Result> { Ok( diff --git a/crates/horizon-world/examples/use_flag_reaction_fixture.rs b/crates/horizon-world/examples/probe/use_flag_reaction_fixture.rs similarity index 99% rename from crates/horizon-world/examples/use_flag_reaction_fixture.rs rename to crates/horizon-world/examples/probe/use_flag_reaction_fixture.rs index 038b529fc..6c7c7fb97 100644 --- a/crates/horizon-world/examples/use_flag_reaction_fixture.rs +++ b/crates/horizon-world/examples/probe/use_flag_reaction_fixture.rs @@ -243,8 +243,8 @@ impl DurationServices for Services { Ok(self.config()["durations"][kind].as_i64().unwrap() as i32) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/use_remainder_fixture.rs b/crates/horizon-world/examples/probe/use_remainder_fixture.rs similarity index 99% rename from crates/horizon-world/examples/use_remainder_fixture.rs rename to crates/horizon-world/examples/probe/use_remainder_fixture.rs index b572b3ce9..534abb167 100644 --- a/crates/horizon-world/examples/use_remainder_fixture.rs +++ b/crates/horizon-world/examples/probe/use_remainder_fixture.rs @@ -115,8 +115,8 @@ fn all( } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/value_provider_fixture.rs b/crates/horizon-world/examples/probe/value_provider_fixture.rs similarity index 94% rename from crates/horizon-world/examples/value_provider_fixture.rs rename to crates/horizon-world/examples/probe/value_provider_fixture.rs index be7bf8afe..9cb895e1c 100644 --- a/crates/horizon-world/examples/value_provider_fixture.rs +++ b/crates/horizon-world/examples/probe/value_provider_fixture.rs @@ -51,8 +51,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/view_direction_fixture.rs b/crates/horizon-world/examples/probe/view_direction_fixture.rs similarity index 75% rename from crates/horizon-world/examples/view_direction_fixture.rs rename to crates/horizon-world/examples/probe/view_direction_fixture.rs index 6fa6ccd55..0c5f483df 100644 --- a/crates/horizon-world/examples/view_direction_fixture.rs +++ b/crates/horizon-world/examples/probe/view_direction_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::geometry::Vec3; use horizon_world::view_direction; use serde_json::Value; @@ -15,15 +16,8 @@ fn number(v: &Value) -> f64 { fn vec(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } -} -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -32,22 +26,22 @@ fn main() -> Result<(), Box> { "acos" => writeln!( out, "angle {:016x}", - bits(view_direction::acos(number(&f["value"]))) + f64_bits(view_direction::acos(number(&f["value"]))) )?, "view" => { let v = view_direction::view_vector(single(&f["pitch"]), single(&f["yaw"])); writeln!( out, "view {:016x} {:016x} {:016x}", - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) )?; } "blocking" => writeln!( out, "angle {:016x}", - bits(view_direction::blocking_angle( + f64_bits(view_direction::blocking_angle( vec(&f["source"]), vec(&f["position"]), single(&f["yaw"]) @@ -56,7 +50,7 @@ fn main() -> Result<(), Box> { "fallback" => writeln!( out, "angle {:016x}", - bits(view_direction::BLOCKING_FALLBACK_ANGLE) + f64_bits(view_direction::BLOCKING_FALLBACK_ANGLE) )?, _ => panic!("mode"), } diff --git a/crates/horizon-world/examples/water_splash_fixture.rs b/crates/horizon-world/examples/probe/water_splash_fixture.rs similarity index 94% rename from crates/horizon-world/examples/water_splash_fixture.rs rename to crates/horizon-world/examples/probe/water_splash_fixture.rs index dd8c71080..8d6eabc79 100644 --- a/crates/horizon-world/examples/water_splash_fixture.rs +++ b/crates/horizon-world/examples/probe/water_splash_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{ geometry::Vec3, random::{LegacyRandom, RandomSource, XoroshiroRandom}, @@ -18,13 +19,6 @@ fn single(v: &Value) -> f32 { fn vec(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } -} fn float_bits(v: f32) -> u32 { if v.is_nan() { f32::NAN.to_bits() @@ -33,7 +27,12 @@ fn float_bits(v: f32) -> u32 { } } fn vector(v: Vec3) -> String { - format!("{:016x} {:016x} {:016x}", bits(v.x), bits(v.y), bits(v.z)) + format!( + "{:016x} {:016x} {:016x}", + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) + ) } struct World<'a, R> { f: &'a Value, @@ -154,8 +153,8 @@ fn run(f: &Value, out: &mut dyn Write, rng: R) -> io::Result<() writeln!(w.out, "next {}", w.rng.next_long())?; writeln!(w.out, "queries {}", w.calls) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); let input = fs::read_to_string(dir.join("inputs.txt"))?; diff --git a/crates/horizon-world/examples/world_border_fixture.rs b/crates/horizon-world/examples/probe/world_border_fixture.rs similarity index 64% rename from crates/horizon-world/examples/world_border_fixture.rs rename to crates/horizon-world/examples/probe/world_border_fixture.rs index 60cabdd3d..ab0b8795b 100644 --- a/crates/horizon-world/examples/world_border_fixture.rs +++ b/crates/horizon-world/examples/probe/world_border_fixture.rs @@ -1,5 +1,6 @@ +use crate::support::shapes::{emit, values}; use horizon_core::geometry::{ - Aabb, Axis, Vec3, VoxelShape, + Aabb, Vec3, border::{BorderGeometry, BorderStatus}, }; use serde_json::Value; @@ -11,72 +12,8 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn values( - out: &mut impl Write, - label: &str, - values: impl IntoIterator, -) -> io::Result<()> { - write!(out, "{label}")?; - for v in values { - let bits = if v.is_nan() { - 0x7ff8_0000_0000_0000 - } else { - v.to_bits() - }; - write!(out, " {bits:016x}")?; - } - writeln!(out) -} -fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { - values( - out, - label, - [ - b.min(Axis::X), - b.min(Axis::Y), - b.min(Axis::Z), - b.max(Axis::X), - b.max(Axis::Y), - b.max(Axis::Z), - ], - ) -} -fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { - writeln!( - out, - "shape {} {} {}", - shape.is_empty(), - shape.boxes().len(), - shape.is_cube() - )?; - for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { - values(out, name, shape.coordinates(axis).iter().copied())?; - } - let axes = shape.cube_coordinate_axes(); - writeln!( - out, - "axes {}", - u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) - )?; - values( - out, - "extrema", - Axis::ALL - .map(|a| shape.min(a)) - .into_iter() - .chain(Axis::ALL.map(|a| shape.max(a))), - )?; - match shape.bounds() { - Some(b) => box_values(out, "bounds", b)?, - None => writeln!(out, "bounds none")?, - } - for b in shape.boxes() { - box_values(out, "box", *b)?; - } - Ok(()) -} -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/world_fixture.rs b/crates/horizon-world/examples/probe/world_fixture.rs similarity index 96% rename from crates/horizon-world/examples/world_fixture.rs rename to crates/horizon-world/examples/probe/world_fixture.rs index d972643cc..fd89e767b 100644 --- a/crates/horizon-world/examples/world_fixture.rs +++ b/crates/horizon-world/examples/probe/world_fixture.rs @@ -6,12 +6,8 @@ use horizon_world::{ }; use std::{error::Error, fs, path::PathBuf}; -fn main() -> Result<(), Box> { - let base = PathBuf::from( - std::env::args() - .nth(1) - .ok_or("expected fixture directory")?, - ); +pub fn main() -> Result<(), Box> { + let base = PathBuf::from(crate::args().nth(1).ok_or("expected fixture directory")?); let output = base.join("rust/palettes"); fs::create_dir_all(&output)?; for entry in fs::read_dir(base.join("palettes"))? { diff --git a/crates/horizon-world/examples/world_ray_fixture.rs b/crates/horizon-world/examples/probe/world_ray_fixture.rs similarity index 94% rename from crates/horizon-world/examples/world_ray_fixture.rs rename to crates/horizon-world/examples/probe/world_ray_fixture.rs index b418785b0..ded8645c7 100644 --- a/crates/horizon-world/examples/world_ray_fixture.rs +++ b/crates/horizon-world/examples/probe/world_ray_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{ geometry::{Aabb, ShapeOp, Vec3, VoxelShape}, position::BlockPos, @@ -15,13 +16,6 @@ fn number(v: &Value) -> f64 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn pos(p: BlockPos) -> String { format!("{} {} {}", p.x, p.y, p.z) } @@ -137,8 +131,8 @@ impl RayWorld for World<'_> { Ok(self.shapes[s][4].clone()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -185,9 +179,9 @@ fn main() -> Result<(), Box> { w.out, "hit {} {:016x} {:016x} {:016x} {} {} {}", r.miss, - bits(h.location.x), - bits(h.location.y), - bits(h.location.z), + f64_bits(h.location.x), + f64_bits(h.location.y), + f64_bits(h.location.z), format!("{:?}", h.direction).to_lowercase(), pos(h.block), h.inside diff --git a/crates/horizon-world/examples/worldgen_random_fixture.rs b/crates/horizon-world/examples/probe/worldgen_random_fixture.rs similarity index 97% rename from crates/horizon-world/examples/worldgen_random_fixture.rs rename to crates/horizon-world/examples/probe/worldgen_random_fixture.rs index 1cf37b1f9..1db24cf8a 100644 --- a/crates/horizon-world/examples/worldgen_random_fixture.rs +++ b/crates/horizon-world/examples/probe/worldgen_random_fixture.rs @@ -118,8 +118,8 @@ fn layers(f: &Value, mut source: impl WorldgenSource, out: &mut impl Write) -> i _ => panic!("unsupported layer count"), } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { 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(()) -} diff --git a/crates/horizon-world/src/block_entities.rs b/crates/horizon-world/src/block_entities.rs index 22a2bc959..1ee8a90e0 100644 --- a/crates/horizon-world/src/block_entities.rs +++ b/crates/horizon-world/src/block_entities.rs @@ -62,9 +62,6 @@ impl ProtoBlockEntities { pub fn active(&self, position: BlockPos) -> Option<&E> { self.active.get(&position) } - pub fn active_mut(&mut self, position: BlockPos) -> Option<&mut E> { - self.active.get_mut(&position) - } pub fn pending(&self, position: BlockPos) -> Option<&Tag> { self.pending.get(&position) } diff --git a/crates/horizon-world/src/block_render.rs b/crates/horizon-world/src/block_render.rs index 1ed9c51af..aa10d361c 100644 --- a/crates/horizon-world/src/block_render.rs +++ b/crates/horizon-world/src/block_render.rs @@ -157,12 +157,6 @@ impl FaceVisibility { } } } - /// Whether the state's occlusion face toward `direction` is the full square. - pub fn full_face(&self, state: BlockStateId, direction: Direction) -> bool { - self.states - .get(state.0 as usize) - .is_some_and(|s| s.faces[direction as usize] == 1) - } /// The state's occlusion face toward `direction` (`getFaceOcclusionShape`) and /// its shared ID: 0 is the empty singleton, 1 the full-block singleton. pub fn occlusion_face( @@ -173,12 +167,6 @@ impl FaceVisibility { let id = self.states.get(state.0 as usize)?.faces[direction as usize]; Some((id, &self.faces[id as usize])) } - /// Whether the state's occlusion face toward `direction` is empty. - pub fn empty_face(&self, state: BlockStateId, direction: Direction) -> bool { - self.states - .get(state.0 as usize) - .is_none_or(|s| s.faces[direction as usize] == 0) - } pub fn skip_rendering( &self, state: BlockStateId, diff --git a/crates/horizon-world/src/block_support.rs b/crates/horizon-world/src/block_support.rs index 295999d18..d3ac386cd 100644 --- a/crates/horizon-world/src/block_support.rs +++ b/crates/horizon-world/src/block_support.rs @@ -186,25 +186,6 @@ impl<'r> BlockSupportRegistry<'r> { pub fn registry(&self) -> &'r BlockRegistry { self.cached.registry() } - pub fn support_shape( - &self, - world: &mut W, - state: BlockStateId, - position: [i32; 3], - ) -> Result> { - if let Some(shape) = self - .cached - .cached_shape(state) - .map_err(SupportQueryError::Data)? - { - return Ok(shape.clone()); - } - self.dynamic - .get(&state) - .ok_or(SupportQueryError::Unsupported(state))? - .shape(world, position) - .map_err(SupportQueryError::Dynamic) - } pub fn is_face_sturdy( &self, world: &mut W, diff --git a/crates/horizon-world/src/block_survival.rs b/crates/horizon-world/src/block_survival.rs index bb21f46df..ae53451ba 100644 --- a/crates/horizon-world/src/block_survival.rs +++ b/crates/horizon-world/src/block_survival.rs @@ -524,14 +524,6 @@ impl<'r> BlockSurvivalRegistry<'r> { bubble_down: tag_states("minecraft:enables_bubble_column_drag_down")?, }) } - pub fn supported_states(&self) -> usize { - self.rules.iter().filter(|r| r.is_some()).count() - } - pub fn supports_state(&self, state: BlockStateId) -> bool { - self.rules - .get(state.0 as usize) - .is_some_and(Option::is_some) - } fn read( &self, world: &mut W, diff --git a/crates/horizon-world/src/component_durability.rs b/crates/horizon-world/src/component_durability.rs index 15237133b..5bf576c08 100644 --- a/crates/horizon-world/src/component_durability.rs +++ b/crates/horizon-world/src/component_durability.rs @@ -3,7 +3,6 @@ use crate::{ component_patch::{ComponentMap, MissingPrototype, Patch, Prototype}, item_durability::DurabilityStorage, - item_use_catalog::UseComponents, }; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Key { @@ -52,13 +51,6 @@ impl DurabilityPrototype { } Self(Prototype::new(entries)) } - pub fn from_defaults(defaults: &UseComponents) -> Self { - Self::new([ - Change::MaxDamage(defaults.max_damage), - Change::Damage(defaults.damage), - Change::Unbreakable(defaults.unbreakable), - ]) - } } #[derive(Clone, Debug)] pub struct DurabilityPatch(Patch); diff --git a/crates/horizon-world/src/datafix/dynamic.rs b/crates/horizon-world/src/datafix/dynamic.rs index 44336729c..69cca1453 100644 --- a/crates/horizon-world/src/datafix/dynamic.rs +++ b/crates/horizon-world/src/datafix/dynamic.rs @@ -157,12 +157,6 @@ pub fn map(tag: &Tag) -> Option<&Compound> { _ => None, } } -pub fn map_mut(tag: &mut Tag) -> Option<&mut Compound> { - match tag { - Tag::Compound(c) => Some(c), - _ => None, - } -} /// `Dynamic.set`: only maps change. pub fn set(tag: &mut Tag, field: &str, value: Tag) { if let Tag::End = tag { @@ -193,12 +187,6 @@ pub fn update(tag: &mut Tag, field: &str, f: impl FnOnce(Tag) -> Tag) { set(tag, field, f(v)); } } -/// `Dynamic.update` in place. -pub fn update_mut(tag: &mut Tag, field: &str, f: impl FnOnce(&mut Tag)) { - if let Some(v) = tag.get_mut(field) { - f(v); - } -} /// `Dynamic.renameAndFixField`: the fixed value under the new name, removed when /// the fix gives nothing. pub fn rename_and_fix(tag: &mut Tag, from: &str, to: &str, f: impl FnOnce(Tag) -> Option) { @@ -223,15 +211,6 @@ pub fn is_empty_map(tag: &Tag) -> bool { pub fn or_empty_map(tag: Option<&Tag>) -> Tag { tag.cloned().unwrap_or_else(empty_map) } -/// Apply `f` to every element of a list field (`Dynamic.createList(asStream().map(f))`). -pub fn map_list(tag: &mut Tag, field: &str, mut f: impl FnMut(Tag) -> Tag) { - if let Some(v) = tag.get(field) - && is_list(Some(v)) - { - let list = stream(Some(v)).into_iter().map(&mut f).collect(); - set(tag, field, Tag::List(list)); - } -} /// `NamespacedSchema.ensureNamespaced`. pub fn namespaced(id: &str) -> String { match crate::datafix::identifier(id) { diff --git a/crates/horizon-world/src/entity_move.rs b/crates/horizon-world/src/entity_move.rs index b3b189df0..25d7aef14 100644 --- a/crates/horizon-world/src/entity_move.rs +++ b/crates/horizon-world/src/entity_move.rs @@ -44,9 +44,6 @@ impl MovementHistory { } self.records.push_back(record); } - pub fn remove_latest(&mut self) { - self.records.pop_back(); - } pub fn clear(&mut self) { self.records.clear(); } diff --git a/crates/horizon-world/src/entity_obstruction.rs b/crates/horizon-world/src/entity_obstruction.rs index 89f7f586b..aac2306b6 100644 --- a/crates/horizon-world/src/entity_obstruction.rs +++ b/crates/horizon-world/src/entity_obstruction.rs @@ -73,17 +73,3 @@ pub fn is_unobstructed( } Ok(true) } - -/// Entity obstruction for the unit cube used by the vanilla block predicate. -/// Translate the voxel shape in floating point: integer MAX + 1 must not wrap. -pub fn is_block_unobstructed( - world: &mut W, - position: [i32; 3], -) -> Result> { - let shape = VoxelShape::block().moved(horizon_core::geometry::Vec3::new( - f64::from(position[0]), - f64::from(position[1]), - f64::from(position[2]), - )); - is_unobstructed(world, None, &shape) -} diff --git a/crates/horizon-world/src/fluid.rs b/crates/horizon-world/src/fluid.rs index 4a89764a8..ab03d6a52 100644 --- a/crates/horizon-world/src/fluid.rs +++ b/crates/horizon-world/src/fluid.rs @@ -272,13 +272,6 @@ impl FluidStateTable { pub fn get(&self, state: BlockStateId) -> Option { self.0.get(state.0 as usize).copied() } - pub fn matching_states(&self, mask: u8) -> impl Iterator + '_ { - self.0 - .iter() - .enumerate() - .filter(move |(_, state)| state.kind.mask() & mask != 0) - .map(|(i, _)| BlockStateId(i as u32)) - } } /// Bound identities for converting fluid states into their legacy liquid blocks. diff --git a/crates/horizon-world/src/level/classes.rs b/crates/horizon-world/src/level/classes.rs index 9540a5a47..2d0193de5 100644 --- a/crates/horizon-world/src/level/classes.rs +++ b/crates/horizon-world/src/level/classes.rs @@ -15,9 +15,6 @@ macro_rules! classes { pub fn from_java(name: &str) -> Option { match name { $($java => Some(Class::$name),)* _ => None } } - pub const fn java_name(self) -> &'static str { - match self { $(Class::$name => $java,)* } - } } }; } diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index e343e06a7..696777386 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -148,7 +148,6 @@ pub mod flags { pub const UPDATE_NEIGHBORS: i32 = 1; pub const UPDATE_CLIENTS: i32 = 2; pub const UPDATE_INVISIBLE: i32 = 4; - pub const UPDATE_IMMEDIATE: i32 = 8; pub const UPDATE_KNOWN_SHAPE: i32 = 16; pub const UPDATE_SUPPRESS_DROPS: i32 = 32; pub const UPDATE_MOVE_BY_PISTON: i32 = 64; diff --git a/crates/horizon-world/src/level/states.rs b/crates/horizon-world/src/level/states.rs index c7fe012dc..8d2544953 100644 --- a/crates/horizon-world/src/level/states.rs +++ b/crates/horizon-world/src/level/states.rs @@ -348,10 +348,4 @@ impl StateTable { } result } - pub fn property_names(&self, block: BlockId) -> impl Iterator { - self.info(block) - .slots - .iter() - .map(|slot| self.key_names[slot.key.0 as usize].as_str()) - } } diff --git a/crates/horizon-world/src/level/ticks.rs b/crates/horizon-world/src/level/ticks.rs index fbad6c28d..c8d715623 100644 --- a/crates/horizon-world/src/level/ticks.rs +++ b/crates/horizon-world/src/level/ticks.rs @@ -149,9 +149,6 @@ impl Ticks { self.blocks .has_scheduled(pos, TickTypeId(u32::from(block.0))) } - pub fn has_fluid_tick(&self, pos: BlockPos, fluid: FluidKind) -> bool { - self.fluids.has_scheduled(pos, TickTypeId(fluid as u32)) - } pub fn will_block_tick_this_tick(&mut self, pos: BlockPos, block: BlockId) -> bool { self.blocks .will_tick_this_tick(pos, TickTypeId(u32::from(block.0))) diff --git a/crates/horizon-world/src/registry_fluid.rs b/crates/horizon-world/src/registry_fluid.rs index eb0f4ffe0..a122a8978 100644 --- a/crates/horizon-world/src/registry_fluid.rs +++ b/crates/horizon-world/src/registry_fluid.rs @@ -62,9 +62,6 @@ impl<'r> FluidRegistry<'r> { pub fn blocks_flow(&self, id: BlockStateId) -> io::Result { Ok(self.state(id)?.blocks_flow) } - pub fn is_ice(&self, id: BlockStateId) -> io::Result { - Ok(self.state(id)?.ice) - } } /// Both queries return state IDs from the same registry. Separate entry points /// preserve native world dispatch when reading a block versus its fluid cell. diff --git a/crates/horizon-world/src/retrogen.rs b/crates/horizon-world/src/retrogen.rs index fc9f450bf..2f048f48e 100644 --- a/crates/horizon-world/src/retrogen.rs +++ b/crates/horizon-world/src/retrogen.rs @@ -33,9 +33,6 @@ impl BelowZeroRetrogen { .get(index / 64) .is_some_and(|word| word & (1_u64 << (index % 64)) != 0) } - pub fn missing_bedrock_words(&self) -> &[u64] { - &self.missing_bedrock - } pub fn from_nbt(tag: &Tag) -> io::Result { if !matches!(tag, Tag::Compound(_)) { return Err(invalid("retrogen is not a compound")); diff --git a/crates/horizon-world/src/worldgen/aquifer.rs b/crates/horizon-world/src/worldgen/aquifer.rs index 2b4f6e7c3..44500313b 100644 --- a/crates/horizon-world/src/worldgen/aquifer.rs +++ b/crates/horizon-world/src/worldgen/aquifer.rs @@ -50,11 +50,6 @@ impl GlobalFluidPicker { disabled: false, } } - /// Matches the vanilla developer flag. Regular gameplay keeps this false. - pub const fn with_disabled(mut self, disabled: bool) -> Self { - self.disabled = disabled; - self - } } impl FluidPicker for GlobalFluidPicker { fn compute(&self, [_, y, _]: [i32; 3]) -> FluidStatus { diff --git a/crates/horizon-world/src/worldgen/feature_region.rs b/crates/horizon-world/src/worldgen/feature_region.rs index b4e8c07b0..e1d80e8bc 100644 --- a/crates/horizon-world/src/worldgen/feature_region.rs +++ b/crates/horizon-world/src/worldgen/feature_region.rs @@ -212,9 +212,6 @@ impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { pub fn tick_clock(&self) -> (i64, i64) { (self.game_time, self.next_tick_order) } - pub fn set_game_time(&mut self, game_time: i64) { - self.game_time = game_time; - } /// Raw tick identities are default block-state IDs for block ticks and /// `FluidKind` discriminants for fluid ticks, in separate namespaces. pub fn schedule_tick( @@ -224,15 +221,6 @@ impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { ) -> Result { WorldGenTickAccess::new(RegionTickContainers { region: self, kind }).schedule(tick) } - pub fn has_scheduled_tick( - &mut self, - kind: TickKind, - position: BlockPos, - tick_type: TickTypeId, - ) -> Result { - WorldGenTickAccess::new(RegionTickContainers { region: self, kind }) - .has_scheduled(position, tick_type) - } fn request_tick( &mut self, kind: TickKind, @@ -251,11 +239,6 @@ impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { self.schedule_tick(kind, tick)?; Ok(()) } - /// Override world sea level without changing generator placement anchors. - pub fn with_world_sea_level(mut self, sea_level: i32) -> Self { - self.sea_level = sea_level; - self - } /// Release the resident chunks, ordered by X then Z; match them by position. pub fn into_chunks(self) -> Vec> { self.chunks diff --git a/crates/horizon-world/src/worldgen/material_condition/codec.rs b/crates/horizon-world/src/worldgen/material_condition/codec.rs index ec646697e..aa159bd1e 100644 --- a/crates/horizon-world/src/worldgen/material_condition/codec.rs +++ b/crates/horizon-world/src/worldgen/material_condition/codec.rs @@ -65,12 +65,6 @@ impl MaterialConditionRegistry { pub fn from_json(definitions: &BTreeMap) -> Result { Self::load(definitions, None) } - pub fn from_json_with_biomes( - definitions: &BTreeMap, - biomes: &BTreeSet, - ) -> Result { - Self::from_json_with_biome_tags(definitions, biomes, &BTreeMap::new()) - } /// Bind resolved biome tags, such as `TagDefinitions::build().tags`. /// Names and memberships remain immutable for the lifetime of this registry. pub fn from_json_with_biome_tags( diff --git a/crates/horizon-world/src/worldgen/state_provider.rs b/crates/horizon-world/src/worldgen/state_provider.rs index 098decdf1..da39cd246 100644 --- a/crates/horizon-world/src/worldgen/state_provider.rs +++ b/crates/horizon-world/src/worldgen/state_provider.rs @@ -344,12 +344,6 @@ impl BlockStateProvider { _ => Err(DecodeError::Field("exclusive state or provider")), } } - pub fn from_typed_json( - json: &str, - bindings: &StateProviderBindings<'_>, - ) -> Result { - Self::decode_typed(json, bindings, 0, &mut 65536, None) - } fn decode_typed( json: &str, bindings: &StateProviderBindings<'_>, diff --git a/crates/horizon-world/src/worldgen/terrain.rs b/crates/horizon-world/src/worldgen/terrain.rs index 8ea3b01be..5ecc48045 100644 --- a/crates/horizon-world/src/worldgen/terrain.rs +++ b/crates/horizon-world/src/worldgen/terrain.rs @@ -432,18 +432,6 @@ impl<'r, B: TerrainBlockStates> TerrainChunk<'r, B> { )?; Ok(()) } - pub fn set_heightmap_raw( - &mut self, - kind: HeightmapType, - words: &[u64], - ) -> Result<(), TerrainError> { - self.ensure_heightmap(kind); - self.heightmaps[kind as usize] - .as_mut() - .unwrap() - .set_raw_data(&self.blocks, words)?; - Ok(()) - } /// Before replaying a saved chunk's `PostProcessing` lists. pub fn clear_postprocessing(&mut self) { self.postprocessing.iter_mut().for_each(Vec::clear); diff --git a/docs/parity-workflow.md b/docs/parity-workflow.md index dde4b5d41..a2cd10584 100644 --- a/docs/parity-workflow.md +++ b/docs/parity-workflow.md @@ -26,6 +26,8 @@ Vanilla oracle runs are reused as well. `tools/parity_shim.py` stands in for `ja Probes build into `.local/parity-target/` with release optimisation but no LTO and 16 codegen units. On ludodesktop that rebuilds every `horizon-world` probe in 3 seconds after a one-line change, against 122 seconds with the release profile. Rust gives these settings identical results (no fast-math; overflow checks as in release), and the full harness suite passes under them. Probes that harnesses build in the dev profile get `opt-level = 3` too, keeping their overflow checks and debug assertions. Harnesses must locate binaries through `cargo metadata` or `lab.cargo_target()`, never a hard-coded `target/`. +The probes of `horizon-world` and of `horizon-client` are one binary per crate, `cargo build --release -p --example probe`: a harness runs `probe [arguments]`, and `` is a module in `crates//examples/probe/` (add it to the `mod` list and the `probes!` list in its `main.rs`; read arguments with `crate::args()` or `crate::args_os()`, which drop the name). Code several probes share goes in `examples/probe/support/` or a module of its own. Linking one binary instead of ~250 examples is most of what a probe build used to cost. The runner counts only the probes a harness ran, the probes and support modules they name, their own subdirectories and `dispatch.rs` as its dependencies, not `main.rs`, which only lists the probes: editing one probe reruns only its harnesses, and adding one reruns none. + Passes are shared between worktrees. A harness's key depends only on the content of its dependencies, not on where they are, so every pass is also written to `parity-shared/` beside the shared vanilla data (`PARITY_SHARED` overrides it). A worktree whose files match those a harness passed with, in any worktree, counts that pass without running the harness: after merging the integration branch, an agent's gate only runs the harnesses its own changes affect. Every runner on the machine shares `PARITY_MACHINE_JOBS` slots (default: half the CPU threads), so several agents' runs together can't overload it. Parallel harnesses are also admitted by memory: each harness's recorded peak is reserved, within three quarters of the memory available at the start, and a harness starts only if the memory free at that moment still leaves 2 GB. `-j` caps the count here (default: `PARITY_LOCAL_JOBS`, else 3 while other machines help or a third of the CPU threads alone, within `$FLEET_LOAD_JOBS`). diff --git a/docs/parity/meshing.md b/docs/parity/meshing.md index 5b746e76c..bcd1cbc6a 100644 --- a/docs/parity/meshing.md +++ b/docs/parity/meshing.md @@ -20,7 +20,7 @@ emit for the same scenes. `FluidRenderer.tesselate`, then `RenderShape.MODEL` blocks through `ModelBlockRenderer.tesselateBlock` with smooth lighting on, culling on, cutout leaves, `BlockColors.createDefault()` and `state.getSeed(pos)`. -- **Horizon side**: `crates/horizon-client/examples/section_mesh_fixture.rs` +- **Horizon side**: `crates/horizon-client/examples/probe/section_mesh_fixture.rs` loads the prepared resources (`Assets`, `BlockFacts`, `Biomes`, `load_visibility`, `MeshTables`), builds the same blocks and light in real client `Chunk`s (a 3x3 chunk region), sets every biome's colours to the diff --git a/docs/rust-parity.md b/docs/rust-parity.md index fee801463..98bff8f82 100644 --- a/docs/rust-parity.md +++ b/docs/rust-parity.md @@ -1471,7 +1471,7 @@ the `hp` text when they no longer fit; and the header and footer wrapped by the list in single player unless a `list` objective is set. `tools/test_tab_list_parity.py` runs vanilla's own `extractRenderState` frame after frame (`VanillaTabListOracle`: stand-in connection, level and options, -real `Scoreboard`) against `examples/tab_list_fixture` and compares every fill, +real `Scoreboard`) against `examples/probe/tab_list_fixture.rs` and compares every fill, styled text run, sprite and face blit (as `hud_layout::GuiDraw` calls, painted like the rest of the HUD): **1,000 cases, 3,476 frames and 844,758 calls match**. The game draws the same layout while the player-list key is @@ -1492,7 +1492,7 @@ nearest first. `WorldBorder::warning_strength` feeds `hud_overlays::vignette` the border's warning strength at the camera. `tools/test_world_border_render_parity.py` drives vanilla's border, renderer and vignette (`VanillaWorldBorderRenderOracle`, with a stand-in GPU device, dynamic-uniform writer and render pass) against -`examples/world_border_render_fixture`: **1,500 cases and 16,859 frames match +`examples/probe/world_border_render_fixture.rs`: **1,500 cases and 16,859 frames match bit for bit** (8,513 with the wall drawn). The game draws the wall with `RenderPipelines.WORLD_BORDER`'s overlay blend and the mipmapped forcefield texture, and follows the server's border packets. One border is kept for all diff --git a/docs/world-generation.md b/docs/world-generation.md index 42cc07cff..f55cbdcb2 100644 --- a/docs/world-generation.md +++ b/docs/world-generation.md @@ -195,7 +195,7 @@ above remains a record of its narrower tested source snapshot. `tools/test_chunk_generation_parity.py` generates chunks in actual vanilla classes (`VanillaChunkGenerationOracle`: structure starts and references, biomes, noise, surface, carvers, then biome decoration and structure pieces through real `WorldGenRegion`s) and with -`crates/horizon-world/examples/chunk_dump.rs`, and compares every block state, quart biome and block entity (canonical NBT) of each target +`crates/horizon-world/examples/probe/chunk_dump.rs`, and compares every block state, quart biome and block entity (canonical NBT) of each target chunk, and the scheduled block and fluid ticks each proto chunk carries into the live world. Cases are terrain sites for several seeds across the overworld, Nether and End, plus rectangles around every structure kind found by scanning the seed. `--phase structures` isolates terrain plus structure pieces, `--phase terrain` stops before features. `HORIZON_ORDER` (a file of `x z` lines) makes both sides diff --git a/tests/test_parity_runner.py b/tests/test_parity_runner.py index ffec8d3d5..633163bf5 100644 --- a/tests/test_parity_runner.py +++ b/tests/test_parity_runner.py @@ -16,10 +16,56 @@ class ParityRunnerTests(unittest.TestCase): def test_artifacts_follow_profile_and_stop_at_program_arguments(self): self.assertEqual(parity.artifacts_of(["cargo", "build", "--release", "--example", "a", "--bin", "b"]), - [["example", "a", "release"], ["bin", "b", "release"]]) + [["example", "a", "release", [], True], ["bin", "b", "release", [], True]]) self.assertEqual(parity.artifacts_of(["cargo", "run", "--profile", "fast", "--example", "c", "--", "--example", "x"]), - [["example", "c", "fast"]]) - self.assertEqual(parity.artifacts_of(["cargo", "build", "--example", "d"]), [["example", "d", "dev"]]) + [["example", "c", "fast", [], True]]) + self.assertEqual(parity.artifacts_of(["cargo", "build", "--example", "d"]), [["example", "d", "dev", [], True]]) + + def test_artifacts_keep_the_package_and_feature_selection(self): + self.assertEqual(parity.artifacts_of(["cargo", "build", "--locked", "--profile=fast", "-j", "4", "--package", + "horizon-client", "--bins", "-F", "x"]), + [["bins", "", "fast", ["-p", "horizon-client", "--features", "x"], False]]) + self.assertEqual(parity.artifacts_of(["cargo", "build", "--release", "-p", "horizon-world", "--bin=horizon-world"]), + [["bin", "horizon-world", "release", ["-p", "horizon-world"], False]]) + + def test_prebuild_repeats_each_harness_selection(self): + artifacts = [ + *parity.artifacts_of(["cargo", "build", "--release", "-p", "horizon-world", "--example", "a"]), + *parity.artifacts_of(["cargo", "build", "--release", "-p", "horizon-world", "--example", "b"]), + *parity.artifacts_of(["cargo", "build", "--release", "-p", "horizon-world", "--bin", "horizon-world"]), + *parity.artifacts_of(["cargo", "build", "--release", "--bin", "horizon-world"]), + *parity.artifacts_of(["cargo", "run", "--profile", "fast", "-p", "horizon-client", "--example", "c"]), + *parity.artifacts_of(["cargo", "build", "--release", "-p", "horizon-world", "--example", "renamed"]), + ["example", "old", "release"], # recorded before selections were kept: its own crate's -p + ["example", "unknown", "release"], # no longer in the workspace: left to its harness + ] + packages = {("example", "a"): "horizon-world", ("example", "b"): "horizon-world", ("example", "c"): "horizon-client", + ("bin", "horizon-world"): "horizon-world", ("example", "old"): "horizon-world"} + self.assertEqual(parity.prebuild_commands(artifacts, packages), [ + ["cargo", "build", "--locked", "--profile", "fast", "-p", "horizon-client", "--example", "c"], + ["cargo", "build", "--locked", "--profile", "release", "--bin", "horizon-world"], + ["cargo", "build", "--locked", "--profile", "release", "-p", "horizon-world", "--bin", "horizon-world"], + ["cargo", "build", "--locked", "--profile", "release", "-p", "horizon-world", "--example", "a", "--example", "b", + "--example", "old"], + ]) + + def test_a_probe_binary_depends_only_on_the_probes_it_ran(self): + commands = [["/t/release/examples/probe", "a_fixture", "/dir"], ["cargo", "run", "--example", "probe", "--", "b_fixture"]] + self.assertEqual(parity.probes_run(commands), {"a_fixture", "b_fixture"}) + with tempfile.TemporaryDirectory() as temp, mock.patch.object(parity, "ROOT", Path(temp)): + probe = Path(temp, "crates/w/examples/probe") + (probe / "support").mkdir(parents=True) + (probe / "a_fixture.rs").write_text('mod integration { include!("d_fixture.rs"); }') + (probe / "d_fixture.rs").write_text("use crate::support::shared as s;") + (probe / "b_fixture.rs").write_text("use crate::e_fixture;") + for name in ("c_fixture.rs", "dispatch.rs", "e_fixture.rs", "main.rs", "support/shared.rs", "support/other.rs"): + (probe / name).write_text("") + paths = [f"crates/w/examples/probe/{name}" for name in ("a_fixture.rs", "b_fixture.rs", "c_fixture.rs", + "d_fixture.rs", "dispatch.rs", "e_fixture.rs", "main.rs", + "support/other.rs", "support/shared.rs")] + self.assertEqual(parity.only_probes_run(["crates/w/src/lib.rs", *paths], {"a_fixture", "b_fixture"}), + ["crates/w/src/lib.rs", *paths[:2], *paths[3:6], paths[8]]) + self.assertEqual(parity.only_probes_run(paths, set()), paths) def test_java_sources_include_classes_pulled_from_the_sourcepath(self): with tempfile.TemporaryDirectory() as temp: diff --git a/tools/audio_harness.py b/tools/audio_harness.py index 6a26f2d44..1d5908fe0 100644 --- a/tools/audio_harness.py +++ b/tools/audio_harness.py @@ -37,7 +37,7 @@ def require_sounds(): def run_harness(name, oracle, example, inputs_text, extra_sources=(), java_args=(), rust_args=(), scope='', timeout=1800): - """Run oracle and example on inputs; returns the number of matched lines.""" + """Run oracle and the client probe `example` on inputs; returns the number of matched lines.""" require_sounds() lock, jars, _ = base.verify_artifacts() libraries = baking.client_libraries() @@ -46,7 +46,7 @@ def run_harness(name, oracle, example, inputs_text, extra_sources=(), java_args= report = build / 'report.json' report.unlink(missing_ok=True) oracle_path = lab.ROOT / f'mods/horizon/src/test/java/dev/horizonlab/parity/{oracle}.java' - example_path = lab.ROOT / f'crates/horizon-client/examples/{example}.rs' + example_path = lab.ROOT / f'crates/horizon-client/examples/probe/{example}.rs' sources = [*COMMON_SOURCES, oracle_path, example_path, *[Path(s) for s in extra_sources]] tested = base.source_hashes(sources) inputs = build / 'inputs.txt' @@ -65,10 +65,10 @@ def run_harness(name, oracle, example, inputs_text, extra_sources=(), java_args= dependencies = os.pathsep.join(map(str, [jars['client'], *libraries])) run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle_path], 'compile-java') - run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', example], 'compile-rust') + run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory']) / 'debug/examples' / (example + ('.exe' if os.name == 'nt' else '')) - run([binary, *rust_args, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'debug/examples' / ('probe.exe' if os.name == 'nt' else 'probe') + run([binary, example, *rust_args, inputs, build / 'rust.txt'], 'rust') env = dict(os.environ, ALSOFT_DRIVERS='null') run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, f'dev.horizonlab.parity.{oracle}', *java_args, inputs, build / 'client.txt'], 'client', env=env) diff --git a/tools/block_update_harness.py b/tools/block_update_harness.py index 24483f5ed..852c013d5 100644 --- a/tools/block_update_harness.py +++ b/tools/block_update_harness.py @@ -133,8 +133,8 @@ def execute(name, cases, args, facts, origin_of=None): '-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaBlockUpdateOracle.java')]) run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaBlockUpdateOracle', str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')]) - run(['cargo', 'run', '-q', '--release', '-p', 'horizon-world', '--example', 'block_update_fixture', '--', - str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], cwd=lab.ROOT, env={**os.environ, 'CARGO_BUILD_JOBS': '3'}) + run(['cargo', 'run', '-q', '--release', '-p', 'horizon-world', '--example', 'probe', '--', + 'block_update_fixture', str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], cwd=lab.ROOT, env={**os.environ, 'CARGO_BUILD_JOBS': '3'}) ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) native = split_cases((work / 'native.txt').read_text(), ignore) rust = split_cases((work / 'rust.txt').read_text(), ignore) diff --git a/tools/datafix_scene_12.py b/tools/datafix_scene_12.py index 3d4a6366f..a73b16c28 100644 --- a/tools/datafix_scene_12.py +++ b/tools/datafix_scene_12.py @@ -23,6 +23,8 @@ import threading import time from pathlib import Path +import lab + BX, BZ, SIZE = 144, 144, 96 # south-west corner and size of the platforms (inside the spawn chunks) LAYERS = list(range(100, 245, 16)) # platform y levels: one chunk section each, the last one reaches y = 255 UUID_HI = 0x6000 @@ -1743,7 +1745,7 @@ LAST = {} def populate(server, Bot, port, protocol, name, problems): """Build the whole 1.12.2 scene, save it for good and return the (still joined) bot.""" harness = sys.modules[Bot.__module__] - Player = make_player(Bot, harness.varint, harness.parse_varint, harness.mcstring) + Player = make_player(Bot, lab.varint, lab.parse_varint, harness.mcstring) set_protocol(protocol) say = lambda cmds, **kw: batch(server, cmds, problems, **kw) if ERA < 12: @@ -1874,7 +1876,7 @@ def build_flat(h, force=False): return [] work = h.LOCAL / 'gen' / (version + '-flat') shutil.rmtree(work, ignore_errors=True) - port = h.free_port() + port = lab.free_port() class FlatServer(h.Server): def __init__(self, directory): # as Server.__init__, with a flat world @@ -1900,7 +1902,7 @@ def build_flat(h, force=False): # A flat world's spawn is found far away; make it (64, 64), and let a bot visit the scene's area so that its chunks # are loaded (they stay loaded, being within the spawn radius). batch(server, ['setworldspawn 64 4 64'], problems) - Player = make_player(h.Bot, h.varint, h.parse_varint, h.mcstring) + Player = make_player(h.Bot, lab.varint, lab.parse_varint, h.mcstring) visitor = Player(port, protocol, h.BOT) time.sleep(2) for x, z in ((24, 24), (24, 72), (24, 104), (72, 24), (72, 72), (72, 104), (104, 24), (104, 72), (104, 104), (72, 123), (-8, 63), (32, 103)): diff --git a/tools/datafix_worlds.py b/tools/datafix_worlds.py index de32e4c09..8411afbc2 100644 --- a/tools/datafix_worlds.py +++ b/tools/datafix_worlds.py @@ -23,7 +23,6 @@ import sys import threading import time import urllib.request -import uuid import zipfile import zlib from pathlib import Path @@ -31,6 +30,7 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) import datafix_scene as scene # noqa: E402 import datafix_scene_12 as scene12 # noqa: E402 +import lab # noqa: E402 ROOT = Path(__file__).resolve().parent.parent LOCAL = ROOT / '.local' / 'datafix' @@ -159,12 +159,6 @@ def install_runtime(pin, home): target.symlink_to(to) -def free_port(): - with socket.socket() as s: - s.bind(('127.0.0.1', 0)) - return s.getsockname()[1] - - class Server: def __init__(self, directory, jar, port, packs=(), java='java', props_override=None): directory.mkdir(parents=True, exist_ok=True) @@ -230,38 +224,9 @@ def failed(lines): # ------------------------------------------------------------------ minimal bot -def varint(v): - out = b'' - v &= 0xFFFFFFFF - while True: - b = v & 0x7F - v >>= 7 - out += bytes([b | (0x80 if v else 0)]) - if not v: - return out - - def mcstring(s): data = s.encode() - return varint(len(data)) + data - - -def parse_varint(data, pos): - value = shift = 0 - while True: - b = data[pos] - pos += 1 - value |= (b & 0x7F) << shift - shift += 7 - if not b & 0x80: - return pos, value - - -def offline_uuid(name): - digest = bytearray(hashlib.md5(('OfflinePlayer:' + name).encode()).digest()) - digest[6] = (digest[6] & 0x0F) | 0x30 - digest[8] = (digest[8] & 0x3F) | 0x80 - return uuid.UUID(bytes=bytes(digest)) + return lab.varint(len(data)) + data class Bot: @@ -273,21 +238,21 @@ class Bot: self.buffer = b'' self.protocol = protocol self.stop = threading.Event() - self.send(0, varint(protocol) + mcstring('127.0.0.1') + struct.pack('>H', port) + varint(2)) + self.send(0, lab.varint(protocol) + mcstring('127.0.0.1') + struct.pack('>H', port) + lab.varint(2)) if protocol <= 758: # 1.18.2: the name only self.send(0, mcstring(name)) elif protocol == 759: # 1.19: no signature data self.send(0, mcstring(name) + b'\x00') elif protocol == 760: # 1.19.2: no signature data, optional UUID - self.send(0, mcstring(name) + b'\x00' + b'\x01' + offline_uuid(name).bytes) + self.send(0, mcstring(name) + b'\x00' + b'\x01' + lab.offline_uuid(name).bytes) elif protocol <= 763: # 1.19.3 - 1.20.1: optional UUID - self.send(0, mcstring(name) + b'\x01' + offline_uuid(name).bytes) + self.send(0, mcstring(name) + b'\x01' + lab.offline_uuid(name).bytes) else: - self.send(0, mcstring(name) + offline_uuid(name).bytes) + self.send(0, mcstring(name) + lab.offline_uuid(name).bytes) while True: pid, data = self.receive() if pid == 3: - self.threshold = parse_varint(data, 0)[1] + self.threshold = lab.parse_varint(data, 0)[1] elif pid == 2: break elif pid == 0: @@ -312,15 +277,15 @@ class Bot: elif pid == disconnect: raise RuntimeError(f'disconnected during configuration: {data!r}') elif not old and self.known_packs(data): - self.send(7, varint(0)) # claim no packs: the server sends full registries + self.send(7, lab.varint(0)) # claim no packs: the server sends full registries @staticmethod def known_packs(data): try: - pos, count = parse_varint(data, 0) + pos, count = lab.parse_varint(data, 0) if count < 1: return False - pos, n = parse_varint(data, pos) + pos, n = lab.parse_varint(data, pos) return data[pos:pos + n] == b'minecraft' except IndexError: return False @@ -359,18 +324,18 @@ class Bot: return value def send(self, packet_id, payload=b''): - body = varint(packet_id) + payload + body = lab.varint(packet_id) + payload if self.threshold >= 0: - body = varint(len(body)) + zlib.compress(body) if len(body) >= self.threshold else varint(0) + body - self.sock.sendall(varint(len(body)) + body) + body = lab.varint(len(body)) + zlib.compress(body) if len(body) >= self.threshold else lab.varint(0) + body + self.sock.sendall(lab.varint(len(body)) + body) def receive(self): length = self.read_varint() body = self.read_exact(length) if self.threshold >= 0: - pos, size = parse_varint(body, 0) + pos, size = lab.parse_varint(body, 0) body = zlib.decompress(body[pos:]) if size else body[pos:] - pos, packet_id = parse_varint(body, 0) + pos, packet_id = lab.parse_varint(body, 0) return packet_id, body[pos:] @@ -428,7 +393,7 @@ def build(name, force=False): era = scene.era(data_version) work = LOCAL / 'gen' / name shutil.rmtree(work, ignore_errors=True) - port = free_port() + port = lab.free_port() server = Server(work, jar, port, scene.experiments(data_version), java(version), props) problems = [] diff --git a/tools/interaction_lab.py b/tools/interaction_lab.py index 0851b6d06..bc574b73d 100644 --- a/tools/interaction_lab.py +++ b/tools/interaction_lab.py @@ -50,7 +50,7 @@ def cargo_example(package, example, *args, profile=None): command = ['cargo', 'run', '-q', '-j3'] if profile: command += ['--profile', profile] - command += ['-p', package, '--example', example, '--', *map(str, args)] + command += ['-p', package, '--example', 'probe', '--', example, *map(str, args)] subprocess.run(command, check=True, cwd=lab.ROOT) diff --git a/tools/lab.py b/tools/lab.py index 87713276d..a62a38f59 100644 --- a/tools/lab.py +++ b/tools/lab.py @@ -1,7 +1,8 @@ #!/usr/bin/env python3 """Pinned Java Edition import/decompilation. Game files come from the user's own copy (their official launcher install and the server jar they downloaded); all -generated files stay in .local/.""" +generated files stay in .local/. Also the small helpers the harnesses share +(free ports, offline UUIDs, VarInts, float bits).""" import argparse from collections import Counter @@ -12,11 +13,13 @@ import platform from pathlib import Path, PurePosixPath import re import shutil +import socket import struct import subprocess import sys import tempfile import urllib.request +import uuid import zipfile ROOT = Path(__file__).resolve().parents[1] @@ -61,6 +64,66 @@ def digest(path, algorithm): return hashlib.file_digest(stream, algorithm).hexdigest() +def free_port(): + """A free local TCP port, for a server a harness starts.""" + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def offline_uuid(name): + """UUIDUtil.createOfflinePlayerUUID: the UUID an offline-mode server gives a player name.""" + digest = bytearray(hashlib.md5(("OfflinePlayer:" + name).encode()).digest()) + digest[6] = (digest[6] & 0x0F) | 0x30 + digest[8] = (digest[8] & 0x3F) | 0x80 + return uuid.UUID(bytes=bytes(digest)) + + +def varint(value): + """FriendlyByteBuf.writeVarInt: the int's 32 bits, 7 at a time.""" + out = b"" + value &= 0xFFFFFFFF + while True: + b = value & 0x7F + value >>= 7 + out += bytes([b | (0x80 if value else 0)]) + if not value: + return out + + +def parse_varint(data, pos): + """The VarInt at data[pos]: (the position after it, its unsigned value).""" + value = shift = 0 + while True: + b = data[pos] + pos += 1 + value |= (b & 0x7F) << shift + shift += 7 + if not b & 0x80: + return pos, value + + +def fbits(value): + """A float's IEEE 754 bits in hex, as the Java oracles print them.""" + return struct.pack(">f", value).hex() + + +def dbits(value): + """A double's IEEE 754 bits in hex, as the Java oracles print them.""" + return struct.pack(">d", value).hex() + + +def settled(lines): + """One player's lines of one step, in order, with the waypoint packets reduced to the last for each waypoint: + what the locator bar shows once the step is over. Arriving in a level, vanilla sends the same waypoint more + than once on the way there; the packet by packet order is test_locator_bar_parity's.""" + def waypoint(line): + parts = line.split(" ") + return parts[3] if len(parts) > 3 and parts[2] in ("track", "untrack", "update") else None + last = {waypoint(l): i for i, l in enumerate(lines) if waypoint(l)} + return [l for i, l in enumerate(lines) if not waypoint(l) or last[waypoint(l)] == i] + + def download(url, destination, checksum, algorithm="sha1"): """Never promote an unverified or partial download into the artifact cache.""" destination.parent.mkdir(parents=True, exist_ok=True) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index b3dae9ef4..4551ed82e 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -107,6 +107,11 @@ address. The script then checks, from both sides, what a guest's game used to ge guest as the host has them (kind, place, rotation, what they hold or wear, the variant). - projectiles: primed TNT (one falling), an end crystal and an arrow that lands reach the guest where the host has them; a falling block lands on both sides. +- thrown: a splash potion and an eye of ender the host and the guest each throw fly on both + sides (#1363, #1391); +- sparks: level events' particles on both sides: the host's and the guest's bone meal on wheat + (growth sparks), honeycomb on copper and an axe taking the wax off, and a spawner's + burst when it spawns (#1395, #1401, #1402); - fireball: a fire charge a dispenser shoots onto stone lights a fire both sides see, and the fire goes out on its own within a minute (it ticks: FireBlock.tick on a floor that doesn't burn) @@ -173,6 +178,9 @@ address. The script then checks, from both sides, what a guest's game used to ge - light: the guest's light matches the host's: around a torch placed near it, under a roof and once a block of the roof is removed under the sky, and in the last chunk it tracks next to glowstone in a chunk it doesn't (only the server's light updates bring that one). +- totem: the host and the guest each take a lethal hit holding a totem of undying in the off + hand, then the main hand: the server uses it up and keeps them alive at 1 health with its + effects, and each side hears the totem once (entity event 35) (#1292). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -208,7 +216,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'sidebar', 'border', 'particles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] class Game: @@ -2612,6 +2620,291 @@ def check_projectiles(host, guest, out): return f'{len(theirs)} identical, fuses (host, guest) {fuses}' +def check_thrown(host, guest, out): + spots = apart(host, guest) + result = {} + for label, player, other in (('host', host, guest), ('guest', guest, host)): + x, y, z = spots[label] + player('command', command='gamemode survival') + for item, kind in (('splash_potion', 'minecraft:splash_potion'), ('ender_eye', 'minecraft:eye_of_ender')): + player('command', command=f'item replace entity @s weapon.mainhand with minecraft:{item}') + player.wait(10) + # Up at 45 degrees, into open sky. + player.raw('look-at', f'{x + 0.5:.2f}', f'{y + 11.6:.2f}', f'{z + 10.5:.2f}') + player.raw('use-item') + seen = {'own': 0, 'other': 0} + for _ in range(10): + player.wait(2) + for side, game in (('own', player), ('other', other)): + if any(p['kind'] == kind for p in game('status')['projectiles']): + seen[side] += 1 + if all(seen.values()): + break + player.shot(out, f'thrown-{label}-{item}') + other.shot(out, f'thrown-{label}-{item}-seen') + player.wait(100) # it lands or drops + result[f'{label} {item}'] = seen + for name, seen in result.items(): + assert all(seen.values()), f'{name}: seen in flight (samples) {result}' + return result + + +def made(game, kind): + """How many `kind` particles `game` has made so far.""" + return game('status').get('particles', {}).get(kind, 0) + + +def sparked(player, other, kinds, act, ticks=20): + """The `kinds` particles each side makes while `act` runs and for up to `ticks` after.""" + before = {(side, k): made(g, k) for side, g in (('own', player), ('other', other)) for k in kinds} + act() + seen = {} + for _ in range(ticks // 2): + player.wait(2) + seen = {f'{side} {k}': made(g, k) - before[(side, k)] + for side, g in (('own', player), ('other', other)) for k in kinds} + if all(seen.values()): + break + return seen + + +def check_sparks(host, guest, out): + spots = apart(host, guest) + result = {} + for label, player, other in (('host', host, guest), ('guest', guest, host)): + x, y, z = spots[label] + at = (x, y, z + 2) + player('command', command='gamemode survival') + try: + player('command', command=f'setblock {at[0]} {at[1] - 1} {at[2]} minecraft:farmland') + player('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:wheat') + player('command', command='item replace entity @s weapon.mainhand with minecraft:bone_meal 8') + player.wait(10) + + def click(height): + player.raw('look-at', f'{at[0] + 0.5:.2f}', f'{at[1] + height:.2f}', f'{at[2] + 0.5:.2f}') + player.raw('mouse', 'right', 'click') + result[f'{label} bone meal'] = sparked(player, other, ['happy_villager'], lambda: click(0.1)) + player('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:copper_block') + player('command', command='item replace entity @s weapon.mainhand with minecraft:honeycomb') + player.wait(10) + result[f'{label} wax'] = sparked(player, other, ['wax_on'], lambda: click(0.5)) + player('command', command='item replace entity @s weapon.mainhand with minecraft:iron_axe') + player.wait(10) + result[f'{label} wax off'] = sparked(player, other, ['wax_off'], lambda: click(0.5)) + block = player.raw('block', *at).get('block', '') + result[f'{label} copper'] = block + finally: + player('command', command=f'fill {at[0]} {at[1] - 1} {at[2]} {at[0]} {at[1]} {at[2]} minecraft:air') + player('command', command=f'setblock {at[0]} {at[1] - 1} {at[2]} minecraft:stone') + player('command', command='clear @s') + # A spawner beside the host, at night: its burst when the zombie comes. + x, y, z = spots['host'] + host('command', command='time set midnight') + try: + host('command', command=f'setblock {x} {y} {z + 3} minecraft:spawner{{Delay:20s,SpawnCount:1s,' + 'SpawnData:{entity:{id:"minecraft:zombie",NoAI:1b}}}') + result['spawner'] = sparked(host, guest, ['flame', 'smoke'], lambda: None, ticks=200) + finally: + host('command', command=f'setblock {x} {y} {z + 3} minecraft:air') + host('command', command=f'kill @e[type=minecraft:zombie,x={x},y={y},z={z},distance=..12]') + host('command', command='time set day') + wrong = {k: v for k, v in result.items() if isinstance(v, dict) and not all(n > 0 for n in v.values())} + assert not wrong, f'no particles: {wrong}\n{result}' + return result + + +def hearts(game): + """The player's maximum and current health as its own client holds them.""" + p = game('status')['player'] + return p.get('max_health'), round(p['health'], 1) + + +def check_hud(host, guest, out): + result = {} + for label, player in (('host', host), ('guest', guest)): + player('command', command='gamemode survival') + try: + for maximum in (40, 10): + player('command', command=f'attribute @s minecraft:max_health base set {maximum}') + player.wait(10) + player('command', command='effect give @s minecraft:instant_health 1 10') + seen = None + for _ in range(15): + player.wait(2) + seen = hearts(player) + if seen == (maximum, maximum): + break + result[f'{label} {maximum}'] = seen + player.shot(out, f'hearts-{label}-{maximum}') + finally: + player('command', command='attribute @s minecraft:max_health base reset') + player('command', command='effect give @s minecraft:instant_health 1 10') + # BossBarCommands' new bar starts visible (ServerBossEvent's constructor). + host('command', command='bossbar add lan_e2e:bar "LAN bar"') + try: + host('command', command='bossbar get lan_e2e:bar visible') + host.wait(5) + result['bar'] = [line for line in host.raw('messages', 5)['chat'] if 'lan_e2e:bar' in line or 'LAN bar' in line] + finally: + host('command', command='bossbar remove lan_e2e:bar') + wrong = {k: v for k, v in result.items() if k != 'bar' and v != (int(k.split()[1]),) * 2} + assert not wrong, f'hearts: {wrong}\n{result}' + assert any('currently visible' in line for line in result['bar']), f'bar: {result["bar"]}' + return result + + +def sidebars(host, guest, want, ticks=40): + """Each side's sidebar (objective and scores) once both show `want` (host, guest), or after `ticks`.""" + seen = None + for _ in range(ticks // 2): + host.wait(2) + seen = tuple(g('status').get('sidebar') for g in (host, guest)) + got = tuple(s and (s['objective'], s['scores']) for s in seen) + if got == want: + break + return seen + + +def check_sidebar(host, guest, out): + result = {} + run = lambda *cmds: [host('command', command=c) for c in cmds] + try: + run('scoreboard objectives add audit dummy {"text":"Audit board","color":"aqua"}', + 'scoreboard players set Alpha audit 7', 'scoreboard players set Beta audit 3', + 'scoreboard objectives setdisplay sidebar audit') + both = ('audit', {'Alpha': 7, 'Beta': 3}) + result['shown'] = sidebars(host, guest, (both, both)) + host.shot(out, 'sidebar') + guest.shot(out, 'sidebar') + run('scoreboard players set Alpha audit 12', 'scoreboard players reset Beta audit') + both = ('audit', {'Alpha': 12}) + result['changed'] = sidebars(host, guest, (both, both)) + # The guest's team's sidebar replaces the sidebar for the guest only. + run('team add red', 'team modify red color red', f'team join red {GUEST_NAME}', + 'scoreboard objectives add reds dummy', f'scoreboard players set {GUEST_NAME} reds 5', + 'scoreboard objectives setdisplay sidebar.team.red reds') + result['team'] = sidebars(host, guest, (both, ('reds', {GUEST_NAME: 5}))) + run('scoreboard objectives remove reds', 'scoreboard objectives setdisplay sidebar') + result['cleared'] = sidebars(host, guest, (None, None)) + finally: + run('scoreboard objectives remove audit', 'scoreboard objectives remove reds', 'team remove red') + want = {'shown': (('audit', {'Alpha': 7, 'Beta': 3}),) * 2, 'changed': (('audit', {'Alpha': 12}),) * 2, + 'team': (('audit', {'Alpha': 12}), ('reds', {GUEST_NAME: 5})), 'cleared': (None, None)} + got = {k: tuple(s and (s['objective'], s['scores']) for s in v) for k, v in result.items()} + wrong = {k: v for k, v in got.items() if v != want[k]} + assert not wrong, f'sidebars: {wrong}\n{result}' + return result + + +def check_border(host, guest, out): + spots = apart(host, guest) + result = {} + try: + for label, player, other in (('host', host, guest), ('guest', guest, host)): + x, y, z = spots[label] + # A whole-block centre: the wall's collision box is the border's, rounded out to blocks. + cx, cz = float(x), float(z) + # The other player keeps out of harm outside the border meanwhile. + other('command', command='gamemode creative') + host('command', command=f'fill {x - 3} {y - 1} {z} {x + 4} {y - 1} {z + 10} minecraft:stone') + host('command', command=f'fill {x - 3} {y} {z} {x + 4} {y + 3} {z + 10} minecraft:air') + # A border 10 wide around the player, its wall 5 blocks ahead: both sides know it. + host('command', command=f'worldborder center {cx} {cz}') + host('command', command='worldborder set 10') + seen = None + for _ in range(10): + player.wait(2) + seen = [g('status').get('border') for g in (player, other)] + if all(b and b['size'] == 10 and b['center'] == [cx, cz] for b in seen): + break + result[f'{label} border'] = seen + # Sprint-jumping into the wall: it stops the player at the border. + player('command', command=f'tp @s {cx} {y} {cz} 0 0') + player.wait(10) + player.raw('look-at', f'{cx:.2f}', f'{y + 1.6:.2f}', f'{cz + 20:.2f}') + for k in ('w', 'ctrl', 'space'): + player.raw('key', k, 'down') + player.wait(40) + for k in ('space', 'ctrl', 'w'): + player.raw('key', k, 'up') + player.wait(10) + result[f'{label} reached'] = round(pos_of(player)[2] - cz, 2) + player.shot(out, f'border-{label}') + # Two blocks outside, with no safe zone: the border hurts. + host('command', command='worldborder damage buffer 0') + host('command', command='worldborder damage amount 1') + player('command', command='effect give @s minecraft:instant_health 1 5') + player.wait(20) + player('command', command=f'tp @s {cx} {y} {cz + 7}') + player.wait(5) + before = player('status')['player']['health'] + player.wait(40) + result[f'{label} hurt'] = [before, player('status')['player']['health']] + player('command', command=f'tp @s {cx} {y} {cz}') + player('command', command='effect give @s minecraft:instant_health 1 5') + host('command', command='worldborder damage amount 0.2') + host('command', command='worldborder damage buffer 5') + other('command', command='gamemode survival') + finally: + guest('command', command='gamemode survival') + host('command', command='gamemode survival') + host('command', command='worldborder damage amount 0.2') + host('command', command='worldborder damage buffer 5') + host('command', command='worldborder center 0 0') + host('command', command='worldborder set 59999968') + wrong = {} + for label in ('host', 'guest'): + x, y, z = spots[label] + known = result[f'{label} border'] + if not all(b and b['size'] == 10 and b['center'] == [x, z] for b in known): + wrong[f'{label} border'] = known + if not 4.0 < result[f'{label} reached'] <= 4.71: + wrong[f'{label} reached'] = result[f'{label} reached'] + before, after = result[f'{label} hurt'] + if not after < before: + wrong[f'{label} hurt'] = result[f'{label} hurt'] + assert not wrong, f'border: {wrong}\n{result}' + return result + + +def check_particles(host, guest, out): + spots = apart(host, guest) + result = {} + for label, player, other in (('host', host, guest), ('guest', guest, host)): + # For the player alone (`@s`), then for every player near. + before = {side: made(g, 'flame') for side, g in (('own', player), ('other', other))} + player('command', command='particle minecraft:flame ~ ~1 ~3 .2 .2 .2 0 60 force @s') + player.wait(10) + result[f'{label} @s'] = {side: made(g, 'flame') - before[side] for side, g in (('own', player), ('other', other))} + player.shot(out, f'flame-{label}') + # No spread: one point, wherever the player stands. + player('command', command='particle minecraft:flame ~ ~1 ~3 0 0 0 0 200 force @s') + player.wait(3) + player.shot(out, f'zero-spread-{label}') + result[f'{label} all'] = sparked(player, other, ['dust'], lambda: player( + 'command', command='particle minecraft:dust{color:[1,0,0],scale:2} ~ ~1 ~3 0 0 0 0 10')) + # A TNT's blast between the players: its burst on both sides. + x, y, z = spots['host'] + host('command', command='gamemode creative') + guest('command', command='gamemode creative') + try: + result['blast'] = sparked(host, guest, ['explosion_emitter'], lambda: host( + 'command', command=f'summon minecraft:tnt {x + 6.5} {y} {z + 4.5} {{fuse:10s}}'), ticks=40) + host.shot(out, 'blast') + finally: + host('command', command='gamemode survival') + guest('command', command='gamemode survival') + host('command', command=f'fill {x - 3} {y - 1} {z - 3} {x + 16} {y - 1} {z + 8} minecraft:stone') + # Without the server thread a guest's command reaches no host player (as `@a` doesn't). + if not SERVER_THREAD: + result['guest all'].pop('other dust') + wrong = {k: v for k, v in result.items() if not k.endswith('@s') and not all(n > 0 for n in v.values())} + wrong.update({k: v for k, v in result.items() if k.endswith('@s') and not (v['own'] >= 30 and v['other'] == 0)}) + assert not wrong, f'particles: {wrong}\n{result}' + return result + + def check_blast(host, guest, out): guest('command', command='gamemode survival') guest('command', command='clear @s') @@ -3945,7 +4238,13 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'lava': check_lava, 'levels': check_levels, 'drops': check_drops, 'underwater': check_underwater, 'looks': check_looks, - 'leads': check_leads} + 'leads': check_leads, + 'thrown': check_thrown, + 'sparks': check_sparks, + 'hud': check_hud, + 'sidebar': check_sidebar, + 'border': check_border, + 'particles': check_particles} def run(ctl, out, resources, checks): @@ -4019,5 +4318,55 @@ def main(): sys.exit(0 if results and all(r['pass'] for r in results.values()) else 1) + +# Checks added after the list above (kept apart so open branches that extend it don't conflict). + + +def heard(game, sound): + return game('status')['heard'].get(sound, 0) + + +def check_totem(host, guest, out): + """LivingEntity.checkTotemDeathProtection on the server for each player: 100 damage holding a + totem in the off hand, then in the main hand, uses the totem up, leaves 1 health with + Regeneration II, Absorption II and Fire Resistance, and broadcasts entity event 35, which both + clients play once (#1292).""" + sound = 'minecraft:item.totem.use' + seen = {} + for game in (host, guest): + for hand in ('offhand', 'mainhand'): + game('command', command='gamemode survival') + game('command', command='clear @s') + game('command', command='effect clear @s') + game('command', command='effect give @s minecraft:instant_health 1 5 true') + game('command', command=f'item replace entity @s weapon.{hand} with minecraft:totem_of_undying') + game.wait(10) + before = {g.name: heard(g, sound) for g in (host, guest)} + game('command', command='damage @s 100 minecraft:generic') + game.wait(10) + me = own(game) + case = f'{game.name}-{hand}' + seen[case] = { + 'screen': game('state').get('screen'), + 'health': me['health'], + 'server_health': server_player(host, game)['health'], + 'effects': sorted(effect_ids(game)), + 'totems': server_count(game, 'totem_of_undying'), + 'heard': {g.name: heard(g, sound) - before[g.name] for g in (host, guest)}, + } + game.shot(out, f'totem-{hand}') + game('command', command='effect clear @s') + for case, s in seen.items(): + # 1 health, and what Regeneration II and the full food bar gave back since. + assert s['screen'] == 'playing' and 0 < s['health'] < 5 and 0 < s['server_health'] < 5, f'{case}: {seen}' + assert s['effects'] == ['absorption', 'fire_resistance', 'regeneration'], f'{case}: {seen}' + assert s['totems'] == 0 and s['heard'] == {'host': 1, 'guest': 1}, f'{case}: {seen}' + return seen + + +CHECKS += ['totem'] +CHECK_FNS.update(totem=check_totem) + + if __name__ == '__main__': main() diff --git a/tools/oracle_harness.py b/tools/oracle_harness.py index a19b5ba94..c6f45553f 100644 --- a/tools/oracle_harness.py +++ b/tools/oracle_harness.py @@ -31,12 +31,13 @@ def compile_oracle(build, oracle_name, jars, libraries, java_major): def build_probe(build, example): - run_logged(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', example], + """Build the horizon-client probe binary; returns the command that runs probe `example`.""" + run_logged(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'probe'], build, 'compile-rust-' + example, env=dict(os.environ, CARGO_BUILD_JOBS='3')) import json metadata = json.loads(subprocess.check_output( ['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - return Path(metadata['target_directory']) / 'debug/examples' / example + return [Path(metadata['target_directory']) / 'debug/examples/probe', example] def java_run(build, classes, dependencies, main_class, args, name, jvm=()): @@ -64,13 +65,13 @@ def differential(name, oracle, probe, make_input, scope, sources=(), expected_li all_sources = [Path(__file__).resolve(), lab.ROOT / 'tools/oracle_harness.py', lab.ROOT / 'tools/test_rust_parity.py', lab.ROOT / 'tools/lab.py', oracle_path, lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock', lab.ROOT / 'crates/horizon-client/Cargo.toml', lab.ROOT / 'crates/horizon-client/src/lib.rs', - lab.ROOT / f'crates/horizon-client/examples/{probe}.rs', *map(Path, sources)] + lab.ROOT / f'crates/horizon-client/examples/probe/{probe}.rs', *map(Path, sources)] tested = base.source_hashes(all_sources) input_path, units = make_input(build) input_hash = lab.digest(input_path, 'sha256') if input_path.is_file() else None classes, dependencies, _ = compile_oracle(build, oracle, jars, libraries, lock['minecraft']['java_major']) - binary = build_probe(build, probe) - run_logged([binary, input_path, build / 'rust.txt'], build, 'rust') + command = build_probe(build, probe) + run_logged([*command, input_path, build / 'rust.txt'], build, 'rust') java_run(build, classes, dependencies, oracle, [input_path, build / 'client.txt'], 'client') try: matched = base.compare(build / 'client.txt', build / 'rust.txt') diff --git a/tools/parity.py b/tools/parity.py index 6ba4c0d90..68ff16e73 100644 --- a/tools/parity.py +++ b/tools/parity.py @@ -27,9 +27,10 @@ Harness probes build into .local/parity-target with release optimisations but without LTO and with 16 codegen units (`PROFILE` below), which builds in seconds instead of minutes. Rust does not let those settings change results: there is no fast-math, and overflow checks stay as in release. Probes built in -the dev profile are optimised too, keeping their overflow checks. Probes the -recorded harnesses need are built in one Cargo run before the harnesses start, -so parallel harnesses don't queue on Cargo's lock. +the dev profile are optimised too, keeping their overflow checks. The probes the +selected harnesses built last time are built before they start, so parallel +harnesses don't queue on Cargo's lock, with each harness's own package and +feature flags so that its Cargo run then finds them fresh. """ import argparse @@ -210,18 +211,42 @@ def artifact_path(kind, name, profile): return TARGET / directory / ("examples" if kind == "example" else "") / name +SELECTION_FLAGS = {"-p", "--package", "-F", "--features"} # followed by a value +SELECTION_SWITCHES = {"--workspace", "--all", "--all-features", "--no-default-features"} + + def artifacts_of(arguments): - """The [kind, name, profile] targets a cargo build/run command line names.""" + """The [kind, name, profile, selection, examples] targets a cargo build/run command line names. + + kind is example, bin, or examples/bins (every one, name ""). selection is the command's package and feature + flags, and examples whether the command builds any example (which turns on dev-dependencies): together they + decide how Cargo unifies features, so the probe prebuild must repeat them exactly. A `--workspace` build of + the same example gives its dependencies other features, and the harness's own `-p` build then compiles + everything again.""" arguments = arguments[:arguments.index("--")] if "--" in arguments else arguments profile = "release" if "--release" in arguments else "dev" - if "--profile" in arguments: - profile = arguments[arguments.index("--profile") + 1] + selection = [] found = [] - for flag, kind in (("--example", "example"), ("--bin", "bin")): - for index, argument in enumerate(arguments[:-1]): - if argument == flag: - found.append([kind, arguments[index + 1], profile]) - return found + index = 1 + while index < len(arguments): + argument = arguments[index] + flag, _, value = argument.partition("=") + if flag in SELECTION_FLAGS | {"--profile", "--example", "--bin"} and not value and index + 1 < len(arguments): + value = arguments[index + 1] + index += 1 + if flag == "--profile": + profile = value + elif flag in SELECTION_FLAGS: + selection += ["-p" if flag == "--package" else "--features" if flag == "-F" else flag, value] + elif flag in SELECTION_SWITCHES: + selection.append("--workspace" if flag == "--all" else flag) + elif flag in ("--example", "--bin"): + found.append([flag[2:], value]) + elif flag in ("--examples", "--bins"): + found.append([flag[2:], ""]) + index += 1 + examples = any(kind in ("example", "examples") for kind, _ in found) + return [[kind, name, profile, selection, examples] for kind, name in found] RUST_PATH = re.compile(r"(? ...`, or + `cargo run --example probe -- ...`.""" + names = set() + for arguments in commands: + program = Path(arguments[0]).name if arguments else "" + if program in ("probe", "probe.exe") and len(arguments) > 1: + names.add(arguments[1]) + elif program == "cargo" and "--" in arguments and "probe" in arguments[:arguments.index("--")] \ + and len(arguments) > arguments.index("--") + 1: + names.add(arguments[arguments.index("--") + 1]) + return names + + +def only_probes_run(paths, names): + """A probe binary's dep-info lists every probe in it. Keep those the harness ran, the probes they include! or + name (crate::) and the shared support modules they name (support::), so that editing one probe + reruns only its own harnesses. Files in a probe's own subdirectory and dispatch.rs, which runs them, are always + kept; main.rs, which only lists them, is left out, so adding a probe reruns nothing.""" + if not names: + return paths + names, used = {*names, "dispatch"}, "" + while True: + ran = [path for path in paths if (match := PROBE_SOURCE.search(path)) and not match.group(1) and match.group(2) in names] + used = "".join((ROOT / path).read_text(encoding="utf-8", errors="replace") for path in ran) + included = {*re.findall(r'include!\("(\w+)\.rs"\)', used), *re.findall(r"\bcrate::(\w+)", used)} - names + if not included: + break + names |= included + return [path for path in paths if not (match := PROBE_SOURCE.search(path)) + or (f"support::{match.group(2)}" in used if match.group(1) else match.group(2) in names)] + + def dependencies(trace, scope=None): """Repository files a traced harness depended on, relative to ROOT, and the probes it built. @@ -457,8 +518,9 @@ def dependencies(trace, scope=None): for argument in arguments[1:]: if isinstance(argument, str) and os.path.isfile(argument): found.add(argument) - for kind, name, profile in artifacts: - found.update(dep_info(artifact_path(kind, name, profile))) + for kind, name, profile, *_ in artifacts: + if name: + found.update(dep_info(artifact_path(kind, name, profile))) kept = set() for path in found: path = Path(path) if os.path.isabs(path) else ROOT / path @@ -469,7 +531,8 @@ def dependencies(trace, scope=None): for artifact in artifacts: if artifact not in unique: unique.append(artifact) - kept, note = narrow_rust_sources(sorted(kept), scope) if scope else (sorted(kept), None) + kept = only_probes_run(sorted(kept), probes_run(trace["commands"])) + kept, note = narrow_rust_sources(kept, scope) if scope else (kept, None) if note: print(f"note: PARITY_RUST_SCOPE not applied: {note}", flush=True) return kept, unique @@ -515,15 +578,49 @@ def default_build_jobs(): return jobs +def target_packages(): + """{(kind, name): package} for the workspace's examples and binaries.""" + result = subprocess.run(["cargo", "metadata", "--no-deps", "--format-version", "1"], cwd=ROOT, capture_output=True, + text=True) + if result.returncode: + return {} + return {(kind, target["name"]): package["name"] for package in json.loads(result.stdout)["packages"] + for target in package["targets"] for kind in target["kind"] if kind in ("example", "bin")} + + +def prebuild_commands(artifacts, packages=None): + """The Cargo runs that build the recorded probes exactly as their harnesses do: one per profile, package and + feature selection, and whether examples are among the command's targets (see artifacts_of). + + packages: target_packages(). Records of targets that no longer exist (a probe renamed or deleted since a harness + ran it) are left out, since one unknown target fails its whole Cargo run. A [kind, name, profile] record from + before selections were kept is taken as built with `-p` and its own crate, as nearly every harness does; the + harness's next run records the real one.""" + groups = {} + for artifact in artifacts: + if packages and artifact[1] and tuple(artifact[:2]) not in packages: + continue + if len(artifact) == 3 and (packages or {}).get(tuple(artifact[:2])): + kind, name, profile = artifact + artifact = [kind, name, profile, ["-p", packages[(kind, name)]], kind == "example"] + if len(artifact) < 5: + continue + kind, name, profile, selection, examples = artifact + targets = groups.setdefault((profile, tuple(selection), examples), []) + target = [f"--{kind}", name] if name else [f"--{kind}"] + if target not in targets: + targets.append(target) + return [["cargo", "build", "--locked", "--profile", profile, *selection, *(part for target in targets for part in target)] + for (profile, selection, _), targets in sorted(groups.items())] + + def prebuild(artifacts, jobs): - """Build every recorded probe in one Cargo run so harnesses don't serialise on its lock.""" + """Build the recorded probes before the harnesses start, so they don't serialise on Cargo's lock.""" environment = run_environment() environment["CARGO_BUILD_JOBS"] = str(jobs) errors = "" - for profile in sorted({profile for _, _, profile in artifacts}): - command = ["cargo", "build", "--locked", "--workspace", "--profile", profile] - for kind, name, _ in (artifact for artifact in artifacts if artifact[2] == profile): - command += ["--examples", "--bins"] if kind == "all" else [f"--{kind}", name] + packages = target_packages() + for command in prebuild_commands(artifacts, packages): result = subprocess.run(command, cwd=ROOT, env=environment, capture_output=True, text=True) if result.returncode: errors += result.stderr @@ -1217,10 +1314,15 @@ def main(): finished_run([]) return 0 - # Harnesses that never ran here have no recorded probes: build them all. - artifacts = [["all", "", "release"]] if any("artifacts" not in records.get(name, {}) for name in selected) else [] + # The probes the selected harnesses built last time, here or (for those that never ran here) in another + # worktree. A harness with no record builds its own: building every probe for it would be ~275 binaries. + artifacts = [] for name in selected: - for artifact in records.get(name, {}).get("artifacts", []): + record = records.get(name) + if not record or "artifacts" not in record: + template = SHARED / "dependencies" / f"{name}.json" + record = json.loads(template.read_text(encoding="utf-8")) if template.exists() else {} + for artifact in record.get("artifacts", []): if artifact not in artifacts: artifacts.append(artifact) config = host_config() diff --git a/tools/parity_shard.py b/tools/parity_shard.py new file mode 100644 index 000000000..249235ffb --- /dev/null +++ b/tools/parity_shard.py @@ -0,0 +1,21 @@ +"""A sharded harness's share of its cases. + +A harness that declares PARITY_SHARDS = n runs as n entries in tools/parity.py, which sets PARITY_SHARD=i/n for +each. Outside the runner PARITY_SHARD is unset and a harness runs everything. Kept out of lab.py: every harness +imports lab.py, so a change there reruns them all. +""" +import os + + +def shard(items): + """Every n-th item from the i-th, or all of them outside the runner.""" + spec = os.environ.get("PARITY_SHARD") + if not spec: + return items + index, count = map(int, spec.split("/")) + return items[index - 1::count] + + +def label(): + """A directory name for this share ("2-4", or "all"): shards run at once and must not share outputs.""" + return os.environ.get("PARITY_SHARD", "all").replace("/", "-") diff --git a/tools/port_regen.py b/tools/port_regen.py index be2d31843..c47e7cc35 100644 --- a/tools/port_regen.py +++ b/tools/port_regen.py @@ -229,10 +229,10 @@ def gen_vanilla_order(root, version, store, build): "dev.horizonlab.parity.VanillaCommandParseOracle", "tree", build], build) env = dict(os.environ, CARGO_TARGET_DIR=str(root / ".local" / "port-target")) jobs = os.environ.get("FLEET_LOAD_JOBS") - run(["cargo", "build", "-p", "horizon-client", "--example", "command_parse_fixture", + run(["cargo", "build", "-p", "horizon-client", "--example", "probe", *(["-j", jobs] if jobs else [])], root, env=env) - fixture = root / ".local/port-target/debug/examples/command_parse_fixture" - run([fixture, "tree", build / "rust_tree.json"], root) + fixture = root / ".local/port-target/debug/examples/probe" + run([fixture, "command_parse_fixture", "tree", build / "rust_tree.json"], root) return [python(), "tools/generate_command_order.py", build / "tree.json", build / "rust_tree.json"] diff --git a/tools/server_bench.py b/tools/server_bench.py index ebd2a1a99..a9a494efd 100755 --- a/tools/server_bench.py +++ b/tools/server_bench.py @@ -45,7 +45,6 @@ from pathlib import Path import platform import re import shutil -import socket import statistics import subprocess import sys @@ -81,12 +80,6 @@ PROPERTIES = { } -def free_port(): - with socket.socket() as s: - s.bind(('127.0.0.1', 0)) - return s.getsockname()[1] - - def cpu_seconds(text): """ps's cumulative CPU time: [[DD-]HH:]MM:SS[.ss].""" days, _, rest = text.rpartition('-') @@ -282,7 +275,7 @@ def run_once(kind, bots, behaviour, args, out): directory = out / name shutil.rmtree(directory, ignore_errors=True) directory.mkdir(parents=True) - port = free_port() + port = lab.free_port() props = dict(PROPERTIES, **{'server-port': str(port), 'level-seed': str(args.seed)}) (directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items())) (directory / 'eula.txt').write_text('eula=true\n') diff --git a/tools/test_active_effect_tick_parity.py b/tools/test_active_effect_tick_parity.py index 61207ca45..dcb34ae21 100644 --- a/tools/test_active_effect_tick_parity.py +++ b/tools/test_active_effect_tick_parity.py @@ -61,7 +61,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaActiveEffectTickOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/active_effect_tick_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/active_effect_tick_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -72,14 +72,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaActiveEffectTickOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','active_effect_tick_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('active_effect_tick_fixture.exe' if os.name=='nt' else 'active_effect_tick_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';enriched_hash=base.source_hashes([enriched]) - run([binary,build,side],'rust-'+side) + run([binary,'active_effect_tick_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';rust_output=build/f'rust-{side}.txt';matched=base.compare(reference,rust_output) base.ensure_sources_unchanged([enriched],enriched_hash) tested_fixtures.update(enriched_hash);fixture_paths.append(enriched) diff --git a/tools/test_active_effects_parity.py b/tools/test_active_effects_parity.py index 16338b15f..926c2ecf8 100644 --- a/tools/test_active_effects_parity.py +++ b/tools/test_active_effects_parity.py @@ -50,7 +50,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaActiveEffectsOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/active_effects_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/active_effects_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -61,14 +61,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaActiveEffectsOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','active_effects_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('active_effects_fixture.exe' if os.name=='nt' else 'active_effects_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';enriched_hash=base.source_hashes([enriched]) - run([binary,build,side],'rust-'+side) + run([binary,'active_effects_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';rust_output=build/f'rust-{side}.txt';matched=base.compare(reference,rust_output) base.ensure_sources_unchanged([enriched],enriched_hash) tested_fixtures.update(enriched_hash);fixture_paths.append(enriched) diff --git a/tools/test_ambient_sound_parity.py b/tools/test_ambient_sound_parity.py index 8906d2d7a..7e272fa94 100644 --- a/tools/test_ambient_sound_parity.py +++ b/tools/test_ambient_sound_parity.py @@ -17,16 +17,12 @@ playing instance and the subtitle notifications. Horizon's `Ambience` and """ import json import random -import struct try: - from . import audio_harness as h + from . import audio_harness as h, lab except ImportError: import audio_harness as h - - -def dbits(v): - return struct.pack('>d', v).hex() + import lab def settings(): @@ -54,11 +50,11 @@ class Script: self.lines.append(' '.join(map(str, parts))) def sounds(self, value): - mood = '-' if value['mood'] is None else '{},{},{},{}'.format(value['mood'][0], value['mood'][1], value['mood'][2], dbits(value['mood'][3])) - self.add('sounds', value['loop'] or '-', mood, *[f'{s},{dbits(c)}' for s, c in value['additions']]) + mood = '-' if value['mood'] is None else '{},{},{},{}'.format(value['mood'][0], value['mood'][1], value['mood'][2], lab.dbits(value['mood'][3])) + self.add('sounds', value['loop'] or '-', mood, *[f'{s},{lab.dbits(c)}' for s, c in value['additions']]) def player(self, at=(0.5, 64.0, 0.5), eye=1.62, water=0, spectator=0, removed=0, mode=0, height=1.8, columns=()): - self.add('player', *map(dbits, at), h.bits(eye), water, spectator, removed, mode, h.bits(height), + self.add('player', *map(lab.dbits, at), h.bits(eye), water, spectator, removed, mode, h.bits(height), *[f'{x},{y},{z},{d}' for x, y, z, d in columns]) def tick(self, n=1): @@ -181,7 +177,7 @@ def main(): 'ambient', 'VanillaAmbientOracle', 'ambient_fixture', ''.join(l + '\n' for l in lines), extra_sources=[h.lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundRig.java', h.lab.ROOT / 'crates/horizon-client/src/ambience.rs', - h.lab.ROOT / 'crates/horizon-client/examples/audio_common/mod.rs'], + h.lab.ROOT / 'crates/horizon-client/examples/probe/audio_common/mod.rs'], java_args=[h.RESOURCES], rust_args=[h.RESOURCES], scope='Real LocalPlayer.updateIsUnderwater, UnderwaterAmbientSoundHandler and BiomeAmbientSoundsHandler (loop cross-fades, additions, ' 'cave mood sampling, moodiness and the mood sound position) with UnderLiquidAmbientSoundInstance/UnderLiquidSubSound/LoopSoundInstance ' diff --git a/tools/test_anchor_parity.py b/tools/test_anchor_parity.py index fbff1d7e6..19b8f6e4b 100644 --- a/tools/test_anchor_parity.py +++ b/tools/test_anchor_parity.py @@ -45,7 +45,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAnchorOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/anchor_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/anchor_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -53,10 +53,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","anchor_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("anchor_fixture.exe" if os.name=="nt" else "anchor_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"anchor_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_arrow_parity.py b/tools/test_arrow_parity.py index 0daa2e311..72692eb55 100644 --- a/tools/test_arrow_parity.py +++ b/tools/test_arrow_parity.py @@ -3,7 +3,7 @@ Real vanilla `Arrow` entities tick in an independently built copy of the scene (`VanillaArrowOracle`, client and server jars); Horizon's -`arrows::tick` runs over the scene itself (`examples/arrow_probe.rs`). Every +`arrows::tick` runs over the scene itself (`examples/probe/arrow_probe.rs`). Every operation prints the arrow's position, motion, rotation, ground state, life, shake, stuck block, fire ticks, water flags, fluid heights, removal, crit flag, fall distance and old position (what rendering interpolates from) by exact @@ -224,7 +224,7 @@ def main(): 'VanillaHeightmapOracle', 'VanillaCollisionOracle', 'VanillaBlockStateCodecOracle', 'VanillaSuffocationOracle', 'VanillaFaceSupportOracle', 'VanillaEntityAttributeOracle', 'VanillaBlockLandingOracle', 'VanillaMovementRegistryOracle', 'VanillaDamageSourceOracle']] sources = [Path(__file__), lab.ROOT / 'tools/test_native_client.py', lab.ROOT / 'tools/test_rust_parity.py', lab.ROOT / 'tools/lab.py', - oracle, *helpers, lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock', lab.ROOT / 'crates/horizon-client/examples/arrow_probe.rs'] + oracle, *helpers, lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock', lab.ROOT / 'crates/horizon-client/examples/probe/arrow_probe.rs'] for crate in ['horizon-core', 'horizon-world', 'horizon-assets', 'horizon-client']: sources += [lab.ROOT / 'crates' / crate / 'Cargo.toml', *sorted((lab.ROOT / 'crates' / crate / 'src').rglob('*.rs'))] tested = base.source_hashes(sources) @@ -241,15 +241,15 @@ def main(): expected = 3 * operations + len(fixtures) (build / 'inputs.txt').write_text(''.join(json.dumps(f, separators=(',', ':')) + '\n' for f in fixtures)) input_hash = lab.digest(build / 'inputs.txt', 'sha256') - run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'arrow_probe'], 'compile-rust') + run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory']) / 'debug/examples' / ('arrow_probe.exe' if os.name == 'nt' else 'arrow_probe') - run([binary, resources, build, '--describe'], 'describe') + binary = Path(metadata['target_directory']) / 'debug/examples' / ('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'arrow_probe',resources, build, '--describe'], 'describe') references = [] for side, jar in jars.items(): run(['java', '-Xmx768M', '-cp', os.pathsep.join([str(classes), str(jar), dependencies]), 'dev.horizonlab.parity.VanillaArrowOracle', side, build, resources], side) - run([binary, resources, build, side], 'rust-' + side) + run([binary, 'arrow_probe',resources, build, side], 'rust-' + side) matched = base.compare(build / (side + '.txt'), build / ('rust-' + side + '.txt')) if matched != expected: raise AssertionError('Incomplete arrow output') diff --git a/tools/test_attribute_health_parity.py b/tools/test_attribute_health_parity.py index e243b60ea..eaf06d857 100644 --- a/tools/test_attribute_health_parity.py +++ b/tools/test_attribute_health_parity.py @@ -48,7 +48,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAttributeHealthOracle.java' helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAttributeOracle.java' - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/attribute_health_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/attribute_health_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaAttributeHealthOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'catalog.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','attribute_health_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('attribute_health_fixture.exe' if os.name=='nt' else 'attribute_health_fixture') - run([binary,build],'rust');run([binary,build,'live'],'rust-live');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'attribute_health_fixture',build],'rust');run([binary,'attribute_health_fixture',build,'live'],'rust-live');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') live_matched=base.compare(reference,build/'rust-live.txt') diff --git a/tools/test_attribute_map_queries_parity.py b/tools/test_attribute_map_queries_parity.py index 24c1b134e..ca222a07c 100644 --- a/tools/test_attribute_map_queries_parity.py +++ b/tools/test_attribute_map_queries_parity.py @@ -69,9 +69,9 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAttributeMapQueriesOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/attribute_map_queries_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/attribute_map_queries_fixture.rs'] helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStoredEffectAttributesOracle.java' - sources.extend([helper,lab.ROOT/'crates/horizon-world/examples/stored_effect_attributes_fixture.rs',lab.ROOT/'tools/test_stored_effect_attributes_parity.py',lab.ROOT/'tools/test_stored_effect_notifications_parity.py']) + sources.extend([helper,lab.ROOT/'crates/horizon-world/examples/probe/stored_effect_attributes_fixture.rs',lab.ROOT/'tools/test_stored_effect_attributes_parity.py',lab.ROOT/'tools/test_stored_effect_notifications_parity.py']) tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -82,14 +82,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaAttributeMapQueriesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','attribute_map_queries_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('attribute_map_queries_fixture.exe' if os.name=='nt' else 'attribute_map_queries_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';fixture_paths.append(enriched);tested_fixtures.update(base.source_hashes([enriched])) - run([binary,build,side],'rust-'+side) + run([binary,'attribute_map_queries_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';candidate=build/f'rust-{side}.txt';matched=base.compare(reference,candidate) references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched,'rust_output_sha256':lab.digest(candidate,'sha256')}) print(f'{side}: {matched:,} attribute map query output lines match Rust',flush=True) diff --git a/tools/test_attribute_parity.py b/tools/test_attribute_parity.py index c5bd95210..02051188d 100644 --- a/tools/test_attribute_parity.py +++ b/tools/test_attribute_parity.py @@ -78,7 +78,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAttributeOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/attribute_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/attribute_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -89,10 +89,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaAttributeOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'attributes.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'attributes.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','attribute_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('attribute_fixture.exe' if os.name=='nt' else 'attribute_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'attribute_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_attribute_updates_parity.py b/tools/test_attribute_updates_parity.py index f4959be0a..cc4f70d1a 100644 --- a/tools/test_attribute_updates_parity.py +++ b/tools/test_attribute_updates_parity.py @@ -59,7 +59,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAttributeUpdatesOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/"tools/test_effect_notifications_parity.py",lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/attribute_updates_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/"tools/test_effect_notifications_parity.py",lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/attribute_updates_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -70,14 +70,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaAttributeUpdatesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','attribute_updates_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('attribute_updates_fixture.exe' if os.name=='nt' else 'attribute_updates_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';enriched_hash=base.source_hashes([enriched]) - run([binary,build,side],'rust-'+side) + run([binary,'attribute_updates_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';rust_output=build/f'rust-{side}.txt';matched=base.compare(reference,rust_output) base.ensure_sources_unchanged([enriched],enriched_hash) tested_fixtures.update(enriched_hash);fixture_paths.append(enriched) diff --git a/tools/test_auto_jump_parity.py b/tools/test_auto_jump_parity.py index da0c16b7b..348bbdbc8 100644 --- a/tools/test_auto_jump_parity.py +++ b/tools/test_auto_jump_parity.py @@ -8,11 +8,9 @@ overhangs approached from every angle with varied speeds, input vectors, sizes, jump boost and the canAutoJump preconditions.""" import json import math -import os from pathlib import Path import platform import random -import struct import subprocess try: @@ -23,14 +21,6 @@ except ImportError: import test_native_client as client -def fbits(v): - return struct.pack('>f', v).hex() - - -def dbits(v): - return struct.pack('>d', v).hex() - - BLOCKS = [ ('stone', {}), ('stone', {}), ('stone', {}), ('stone_slab', {'type': 'bottom'}), ('stone_slab', {'type': 'top'}), ('stone_slab', {'type': 'double'}), @@ -64,12 +54,12 @@ DIMS = [(0.6, 1.8), (0.6, 1.8), (0.6, 1.5), (0.6, 0.6), (0.3, 0.9), (1.2, 3.6), def player(rng, x, y, z, yaw): w, h = rng.choice(DIMS) - return dict(pos=[dbits(x), dbits(y), dbits(z)], ground=rng.random() < 0.9, shift=rng.random() < 0.08, - yr=fbits(yaw), xr=fbits(rng.choice([0.0, 30.0, -45.0, 90.0, rng.uniform(-90, 90)])), - speed=fbits(rng.choice([0.1, 0.13000001, 0.03, 0.0, 0.2, rng.uniform(0, 0.3)])), - move=[fbits(v) for v in rng.choice([(0.0, 1.0), (0.0, 1.0), (1.0, 0.0), (-1.0, 0.0), (0.70710677, 0.70710677), + return dict(pos=[lab.dbits(x), lab.dbits(y), lab.dbits(z)], ground=rng.random() < 0.9, shift=rng.random() < 0.08, + yr=lab.fbits(yaw), xr=lab.fbits(rng.choice([0.0, 30.0, -45.0, 90.0, rng.uniform(-90, 90)])), + speed=lab.fbits(rng.choice([0.1, 0.13000001, 0.03, 0.0, 0.2, rng.uniform(0, 0.3)])), + move=[lab.fbits(v) for v in rng.choice([(0.0, 1.0), (0.0, 1.0), (1.0, 0.0), (-1.0, 0.0), (0.70710677, 0.70710677), (0.0, -1.0), (0.0, 0.0), (0.3, 0.3)])], - width=fbits(w), height=fbits(h), boost=rng.choice([None] * 6 + [0, 1, 4, 255]), + width=lab.fbits(w), height=lab.fbits(h), boost=rng.choice([None] * 6 + [0, 1, 4, 255]), enabled=rng.random() < 0.93, time=rng.choice([0] * 12 + [1, -3, 2])) @@ -86,18 +76,18 @@ def cases(rng): x = ox + 0.5 - dx * 1.1 z = oz + 0.5 - dz * 1.1 p = player(rng, x, float(oy), z, yaw) - p.update(ground=True, shift=False, enabled=True, time=0, boost=None, move=[fbits(0.0), fbits(1.0)], - width=fbits(0.6), height=fbits(1.8), xr=fbits(0.0)) - yield dict(blocks=blocks, player=p, xa=fbits(dx * step), za=fbits(dz * step)) + p.update(ground=True, shift=False, enabled=True, time=0, boost=None, move=[lab.fbits(0.0), lab.fbits(1.0)], + width=lab.fbits(0.6), height=lab.fbits(1.8), xr=lab.fbits(0.0)) + yield dict(blocks=blocks, player=p, xa=lab.fbits(dx * step), za=lab.fbits(dz * step)) # Ceilings above the player and above the step. for ceiling in range(2, 6): for step_height in (0, 1): blocks = [[ox, oy + step_height, oz, 'minecraft:stone', {}], [ox - 1, oy + ceiling, oz, 'minecraft:stone', {}], [ox, oy + ceiling + step_height, oz, 'minecraft:stone_slab', {'type': 'top'}]] p = player(rng, ox - 0.5, float(oy), oz + 0.5, -90.0) - p.update(ground=True, shift=False, enabled=True, time=0, boost=None, move=[fbits(0.0), fbits(1.0)], - width=fbits(0.6), height=fbits(1.8)) - yield dict(blocks=blocks, player=p, xa=fbits(0.2), za=fbits(0.0)) + p.update(ground=True, shift=False, enabled=True, time=0, boost=None, move=[lab.fbits(0.0), lab.fbits(1.0)], + width=lab.fbits(0.6), height=lab.fbits(1.8)) + yield dict(blocks=blocks, player=p, xa=lab.fbits(0.2), za=lab.fbits(0.0)) for _ in range(9000): blocks = placed(rng, rng.choice([1, 2, 4, 8, 16, 30])) x = ox + rng.uniform(-2, 3) @@ -108,7 +98,7 @@ def cases(rng): move = rng.choice([0.0, 0.0, 0.01, 0.1, 0.215, 0.3, rng.uniform(0, 0.4)]) angle = rng.uniform(0, 6.283) - yield dict(blocks=blocks, player=p, xa=fbits(math.cos(angle) * move), za=fbits(math.sin(angle) * move)) + yield dict(blocks=blocks, player=p, xa=lab.fbits(math.cos(angle) * move), za=lab.fbits(math.sin(angle) * move)) def main(): @@ -125,7 +115,7 @@ def main(): sources = [Path(__file__).resolve(), lab.ROOT / 'tools/oracle_harness.py', lab.ROOT / 'tools/lab.py', parity / (oracle + '.java'), parity / 'VanillaSceneCollisionOracle.java', parity / 'VanillaRegistryCollisionScanOracle.java', lab.ROOT / 'Cargo.lock', - lab.ROOT / 'crates/horizon-client/examples/auto_jump_probe.rs', + lab.ROOT / 'crates/horizon-client/examples/probe/auto_jump_probe.rs', lab.ROOT / 'crates/horizon-client/src/auto_jump.rs', lab.ROOT / 'crates/horizon-client/src/motion.rs'] tested = base.source_hashes(sources) fixtures = list(cases(random.Random(0x4155544f))) @@ -133,8 +123,8 @@ def main(): inputs.write_text(''.join(json.dumps(f, separators=(',', ':')) + '\n' for f in fixtures)) input_hash = lab.digest(inputs, 'sha256') classes, dependencies, _ = harness.compile_oracle(build, oracle, jars, libraries, lock['minecraft']['java_major']) - binary = harness.build_probe(build, 'auto_jump_probe') - harness.run_logged([binary, resources, inputs, build / 'rust.txt', build / 'scene.json'], build, 'rust', timeout=3600) + command = harness.build_probe(build, 'auto_jump_probe') + harness.run_logged([*command, resources, inputs, build / 'rust.txt', build / 'scene.json'], build, 'rust', timeout=3600) harness.java_run(build, classes, dependencies, oracle, [inputs, build / 'client.txt', resources, build / 'scene.json'], 'client') matched = harness.compare(build / 'client.txt', build / 'rust.txt', 2 * len(fixtures)) base.ensure_sources_unchanged(sources, tested) diff --git a/tools/test_basic_feature_parity.py b/tools/test_basic_feature_parity.py index 001397965..2de93cd1a 100644 --- a/tools/test_basic_feature_parity.py +++ b/tools/test_basic_feature_parity.py @@ -57,7 +57,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBasicFeatureOracle.java" helper=oracle.with_name("VanillaPlacementOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/basic_feature_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/basic_feature_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -71,10 +71,10 @@ def main(): fixture_paths.append(path) if json.loads((build/"facts-client.json").read_text())!=json.loads((build/"facts-server.json").read_text()):raise ValueError("reference feature block states differ") tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","basic_feature_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("basic_feature_fixture.exe" if os.name=="nt" else "basic_feature_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"basic_feature_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_biome_chunk_parity.py b/tools/test_biome_chunk_parity.py index f484c1c5f..f24370455 100644 --- a/tools/test_biome_chunk_parity.py +++ b/tools/test_biome_chunk_parity.py @@ -49,7 +49,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeChunkOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/biome_chunk_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/biome_chunk_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -57,10 +57,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=3600,stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","biome_chunk_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("biome_chunk_fixture.exe" if os.name=="nt" else "biome_chunk_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"biome_chunk_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_biome_generation_parity.py b/tools/test_biome_generation_parity.py index 4c38070d7..67c642585 100644 --- a/tools/test_biome_generation_parity.py +++ b/tools/test_biome_generation_parity.py @@ -53,7 +53,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeGenerationOracle.java" exporter=oracle.with_name("VanillaBiomeExport.java") sources=[oracle,exporter,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/biome_generation_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/biome_generation_fixture.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -76,10 +76,10 @@ def main(): registries=build/'registries.json';registries.write_text(json.dumps(bundle,separators=(',',':')),encoding='utf-8') fixtures=list(corpus(bundle));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') fixture_paths=[inputs,registries,*exports];tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","biome_generation_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("biome_generation_fixture.exe" if os.name=="nt" else "biome_generation_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"biome_generation_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_biome_placement_parity.py b/tools/test_biome_placement_parity.py index 21408e20f..caf99b7c9 100644 --- a/tools/test_biome_placement_parity.py +++ b/tools/test_biome_placement_parity.py @@ -44,7 +44,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomePlacementOracle.java' helper=oracle.with_name("VanillaPlacementOracle.java") - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/biome_placement_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/biome_placement_fixture.rs'] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) @@ -53,10 +53,10 @@ def main(): with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle,helper],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','biome_placement_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('biome_placement_fixture.exe' if os.name=='nt' else 'biome_placement_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'biome_placement_fixture',build],'rust');references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependency_path]),'dev.horizonlab.parity.VanillaBiomePlacementOracle',side,build],side) reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_biome_source_codec_parity.py b/tools/test_biome_source_codec_parity.py index 58989d884..9363378af 100644 --- a/tools/test_biome_source_codec_parity.py +++ b/tools/test_biome_source_codec_parity.py @@ -72,7 +72,7 @@ def main(): exporter=oracle.with_name("VanillaBiomeExport.java") helpers=[oracle.with_name(name+".java") for name in ["VanillaMaterialConditionOracle","VanillaAnchorOracle","VanillaBiomeTemperatureOracle"]] sources=[oracle,exporter,*helpers,lab.ROOT/"tools/test_biome_temperature_parity.py",lab.ROOT/"tools/test_material_condition_parity.py",Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/biome_source_codec_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/biome_source_codec_fixture.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -95,10 +95,10 @@ def main(): fixtures=list(corpus(bundle));inputs=build/'inputs.txt';inputs.write_text('\n'.join(fixtures)+'\n',encoding='utf-8') (build/'positions.json').write_text(json.dumps(positions(),separators=(',',':')),encoding='utf-8') fixture_paths=[inputs,*exports,build/'positions.json',*[build/(name+'.json') for name in bundle]];tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","biome_source_codec_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("biome_source_codec_fixture.exe" if os.name=="nt" else "biome_source_codec_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"biome_source_codec_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_biome_source_parity.py b/tools/test_biome_source_parity.py index 093c92427..7616f7545 100644 --- a/tools/test_biome_source_parity.py +++ b/tools/test_biome_source_parity.py @@ -36,7 +36,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeSourceOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/biome_source_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/biome_source_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -44,10 +44,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","biome_source_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("biome_source_fixture.exe" if os.name=="nt" else "biome_source_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"biome_source_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_biome_temperature_parity.py b/tools/test_biome_temperature_parity.py index 1edec516e..af8d75976 100644 --- a/tools/test_biome_temperature_parity.py +++ b/tools/test_biome_temperature_parity.py @@ -74,7 +74,7 @@ def main(): (build/'biomes.json').write_text(json.dumps(biomes,separators=(',',':')),encoding='utf-8') oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeTemperatureOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/biome_temperature_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/biome_temperature_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=[*corpus(),*codec_corpus(biomes)];inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs,build/"biomes.json"];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -82,10 +82,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","biome_temperature_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("biome_temperature_fixture.exe" if os.name=="nt" else "biome_temperature_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"biome_temperature_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_block_collision_scan_parity.py b/tools/test_block_collision_scan_parity.py index 97c6e12b7..a59bfd8f9 100644 --- a/tools/test_block_collision_scan_parity.py +++ b/tools/test_block_collision_scan_parity.py @@ -57,7 +57,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockCollisionScanOracle.java' helpers=[oracle.with_name('VanillaFaceSupportOracle.java')] - sources=[oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/block_collision_scan_fixture.rs'] + sources=[oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/block_collision_scan_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -68,10 +68,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBlockCollisionScanOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','block_collision_scan_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('block_collision_scan_fixture.exe' if os.name=='nt' else 'block_collision_scan_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'block_collision_scan_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_block_entity_anim_parity.py b/tools/test_block_entity_anim_parity.py index 8935afef4..b0c462aee 100755 --- a/tools/test_block_entity_anim_parity.py +++ b/tools/test_block_entity_anim_parity.py @@ -9,7 +9,7 @@ on a stand-in client level, then per scripted step applies the block event (triggerEvent), runs the entity's own client ticker and the renderer's extractRenderState, printing the fields, the level calls the tick made (neighbour updates, entity pushes/queries, sounds, particles) and the render -state. `examples/block_entity_anim_fixture` replays the steps through +state. `examples/probe/block_entity_anim_fixture` replays the steps through `horizon_client::block_entity_anim` and derives the render state from the `BlockAnim` Horizon's renderer reads. Lines must match exactly (floats as bits). @@ -279,8 +279,8 @@ def main(): *(PARITY / f'{n}.java' for n in ('ParityData', 'VanillaBlockEntityAnimOracle'))], 'compile-java') run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaBlockEntityAnimOracle', inputs, build / 'vanilla.txt'], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'block_entity_anim_fixture', '--', - resources, inputs, build / 'rust.txt'], 'rust') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'block_entity_anim_fixture', resources, inputs, build / 'rust.txt'], 'rust') def split(path): result, current = {}, None diff --git a/tools/test_block_entity_render_parity.py b/tools/test_block_entity_render_parity.py index 3c096bdcc..901f4300f 100644 --- a/tools/test_block_entity_render_parity.py +++ b/tools/test_block_entity_render_parity.py @@ -5,7 +5,7 @@ The Java oracle (VanillaBlockEntityRenderOracle) builds each case's vanilla block entity, sets its animation fields, runs the real BlockEntityRenderer's extractRenderState and submit, and captures what it submits: model vertices after setupAnim and the pose stack (sprite-local UVs, tint, normal, light), -text calls and items. `examples/block_entity_render_fixture` replays the case +text calls and items. `examples/probe/block_entity_render_fixture` replays the case through Horizon's BlockEntityRenderer. Quads are matched by texture and position; colours compare vanilla's tint times the entity shader's `minecraft_mix_light` for the vanilla normal with Horizon's baked colour. @@ -303,8 +303,8 @@ def main(): vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] textures = sorted({s['texture'] for v in vanilla for s in v.get('submits', []) if 'texture' in s}) (build / 'textures.txt').write_text(''.join(t + '\n' for t in textures)) - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'block_entity_render_fixture', '--', - resources, inputs, build / 'textures.txt', build / 'rust.jsonl'], 'rust') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'block_entity_render_fixture', resources, inputs, build / 'textures.txt', build / 'rust.jsonl'], 'rust') rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] assert len(vanilla) == len(rust), (len(vanilla), len(rust)) groups, errors, skipped, passed = {}, {}, {}, 0 diff --git a/tools/test_block_entity_storage_parity.py b/tools/test_block_entity_storage_parity.py index 7e90ac530..a1f378f31 100644 --- a/tools/test_block_entity_storage_parity.py +++ b/tools/test_block_entity_storage_parity.py @@ -67,7 +67,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityStorageOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/block_entity_storage_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/block_entity_storage_fixture.rs'] tested_sources=base.source_hashes(sources) commands=list(corpus());inputs=build/'inputs.txt';inputs.write_text('\n'.join(commands)+'\n') tested_fixtures=base.source_hashes([inputs]);classes=build/'classes';classes.mkdir(exist_ok=True) @@ -75,10 +75,10 @@ def main(): with (build/(name+'.log')).open('w') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=3600,stdout=log,stderr=subprocess.STDOUT) dependencies=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependencies,'-d',classes,oracle],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','block_entity_storage_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('block_entity_storage_fixture.exe' if os.name=='nt' else 'block_entity_storage_fixture') - run([binary,inputs,build/'rust.txt'],'rust') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'block_entity_storage_fixture',inputs,build/'rust.txt'],'rust') references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependencies]),'dev.horizonlab.parity.VanillaBlockEntityStorageOracle',inputs,build/(side+'.txt')],side) diff --git a/tools/test_block_entity_tickers_parity.py b/tools/test_block_entity_tickers_parity.py index 459e7a926..66a84cf48 100644 --- a/tools/test_block_entity_tickers_parity.py +++ b/tools/test_block_entity_tickers_parity.py @@ -6,7 +6,7 @@ one chunk to make its block entity map grow), place, replace and remove block entities, give jukeboxes a record and take it, and unload chunks, with ticks in between. `VanillaBlockEntityTickerOracle` runs them on real `LevelChunk`s of a server level and prints, after each tick, the positions of the live -tickers in list order; `examples/block_entity_tickers_fixture` runs the same +tickers in list order; `examples/probe/block_entity_tickers_fixture` runs the same on `horizon_client::block_entities::BlockEntities`. The block entities are the kinds the game ticks in that list (hoppers, furnaces, beacons, spawners, trial spawners, vaults, hives, crafters, brewing stands, jukebox), with chests and barrels, @@ -120,7 +120,7 @@ def main(): run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaBlockEntityTickerOracle', inputs, build / 'vanilla.txt'], 'vanilla') run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', - 'block_entity_tickers_fixture', '--', inputs, build / 'rust.txt'], 'rust') + 'probe', '--', 'block_entity_tickers_fixture', inputs, build / 'rust.txt'], 'rust') matched = base.compare(build / 'vanilla.txt', build / 'rust.txt') ticks = sum(1 for line in lines if line == 'tick') listed = sum(len(line.split()) - 1 for line in (build / 'vanilla.txt').read_text().splitlines()) diff --git a/tools/test_block_landing_parity.py b/tools/test_block_landing_parity.py index 0b2792d82..822ff1614 100644 --- a/tools/test_block_landing_parity.py +++ b/tools/test_block_landing_parity.py @@ -56,7 +56,7 @@ def main(): lock,jars,libraries=base.verify_artifacts();build=lab.LOCAL/'rust-block-landing-parity';build.mkdir(exist_ok=True);report_path=build/'report.json';report_path.unlink(missing_ok=True) root=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity' oracles=[root/(n+'.java') for n in ['VanillaBlockLandingOracle','VanillaMovementRegistryOracle','VanillaHeightmapOracle','VanillaCollisionOracle']] - sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/block_landing_fixture.rs'] + sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/probe/block_landing_fixture.rs'] for crate in ['horizon-core','horizon-world']:sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] tested=base.source_hashes(sources);classes=build/'classes';classes.mkdir(exist_ok=True);dependencies=os.pathsep.join(map(str,libraries)) def run(command,name): @@ -69,9 +69,9 @@ def main(): with (build/'inputs.txt').open('w') as output: for f in corpus(states,definitions):output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 fixture_paths=[build/n for n in ['inputs.txt','landing-states.json','landing-definitions.json','movement-properties.nbt','block-registry.nbt','cached-collision.nbt']];fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','block_landing_fixture'],'compile-rust') - metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('block_landing_fixture.exe' if os.name=='nt' else 'block_landing_fixture') - run([binary,build],'rust');references=[] + run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'block_landing_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side);matched=base.compare(build/(side+'.txt'),build/'rust.txt');references.append(dict(side=side,jar_sha256=lab.digest(jar,'sha256'),output_sha256=lab.digest(build/(side+'.txt'),'sha256'),matched_output_lines=matched));print(f'{side}: {matched:,} registered block landing lines match',flush=True) base.ensure_sources_unchanged(sources,tested);base.ensure_sources_unchanged(fixture_paths,fixtures) diff --git a/tools/test_block_particles_parity.py b/tools/test_block_particles_parity.py index 3f0f0f99c..7e08e98f8 100644 --- a/tools/test_block_particles_parity.py +++ b/tools/test_block_particles_parity.py @@ -13,7 +13,7 @@ def main(): resources = lab.RESOURCES build = lab.LOCAL / "block-particles-parity" build.mkdir(exist_ok=True) - paths = [lab.ROOT / p for p in ["tools/test_block_particles_parity.py", "tools/test_breaking_model_parity.py", "tools/oracle_harness.py", "tools/lab.py", "crates/horizon-client/src/particles.rs", "crates/horizon-client/src/game.rs", "crates/horizon-client/src/blocks.rs", "crates/horizon-client/src/mesher.rs", "crates/horizon-client/examples/block_particles_fixture.rs", "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockParticlesOracle.java", "crates/horizon-core/src/random.rs", "Cargo.lock", "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameplayFactsExporter.java"]] + paths = [lab.ROOT / p for p in ["tools/test_block_particles_parity.py", "tools/test_breaking_model_parity.py", "tools/oracle_harness.py", "tools/lab.py", "crates/horizon-client/src/particles.rs", "crates/horizon-client/src/game.rs", "crates/horizon-client/src/blocks.rs", "crates/horizon-client/src/mesher.rs", "crates/horizon-client/examples/probe/block_particles_fixture.rs", "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockParticlesOracle.java", "crates/horizon-core/src/random.rs", "Cargo.lock", "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameplayFactsExporter.java"]] tested = base.source_hashes(paths) rows = [dict(case=i, seed=(-1 if i % 2 else 1) * i * 987654321, **row) for i, row in enumerate(breaking.cases(resources))] rows[0]["seed"] = -(2**63) @@ -21,8 +21,8 @@ def main(): inputs = build / "inputs.jsonl" inputs.write_text("".join(json.dumps(row)+"\n" for row in rows)) classes, dependencies, _ = harness.compile_oracle(build, "VanillaBlockParticlesOracle", jars, baking.client_libraries(), lock["minecraft"]["java_major"]) - binary = harness.build_probe(build, "block_particles_fixture") - harness.run_logged([binary, resources, inputs, build / "rust.jsonl"], build, "rust") + command = harness.build_probe(build, "block_particles_fixture") + harness.run_logged([*command, resources, inputs, build / "rust.jsonl"], build, "rust") harness.java_run(build, classes, dependencies, "VanillaBlockParticlesOracle", [inputs, build / "client.jsonl"], "client") count = hits = burst = 0 max_error = 0.0 diff --git a/tools/test_block_properties_parity.py b/tools/test_block_properties_parity.py index da2f9dd11..28cd2832c 100644 --- a/tools/test_block_properties_parity.py +++ b/tools/test_block_properties_parity.py @@ -45,7 +45,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockPropertiesOracle.java' helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionOracle.java' - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/block_properties_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/block_properties_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): java('server','export',build) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'block-registry.nbt',build/'cached-collision.nbt',build/'block-properties.nbt'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','block_properties_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('block_properties_fixture.exe' if os.name=='nt' else 'block_properties_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'block_properties_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_block_push_parity.py b/tools/test_block_push_parity.py index 273f9e8de..986a3b1c9 100644 --- a/tools/test_block_push_parity.py +++ b/tools/test_block_push_parity.py @@ -42,7 +42,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockPushOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/block_push_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/block_push_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -53,10 +53,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBlockPushOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','block_push_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('block_push_fixture.exe' if os.name=='nt' else 'block_push_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'block_push_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_block_state_codec_parity.py b/tools/test_block_state_codec_parity.py index 1eb3ebe4a..e6db50860 100644 --- a/tools/test_block_state_codec_parity.py +++ b/tools/test_block_state_codec_parity.py @@ -45,7 +45,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockStateCodecOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/block_state_codec_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/block_state_codec_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -60,10 +60,10 @@ def main(): if len(facts['states'])!=35723:raise ValueError('incomplete pinned state registry') fixtures=list(corpus(facts));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'facts-client.json',build/'facts-server.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','block_state_codec_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('block_state_codec_fixture.exe' if os.name=='nt' else 'block_state_codec_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'block_state_codec_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_block_support_parity.py b/tools/test_block_support_parity.py index 2d7cb8b9c..928f099d1 100644 --- a/tools/test_block_support_parity.py +++ b/tools/test_block_support_parity.py @@ -24,7 +24,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockSupportOracle.java' helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionOracle.java' - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/block_support_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/block_support_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -35,10 +35,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBlockSupportOracle',mode,path],side+'-'+mode) java('server','export',build) fixture_paths=[build/'block-registry.nbt',build/'cached-support.nbt'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','block_support_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('block_support_fixture.exe' if os.name=='nt' else 'block_support_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'block_support_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_block_survival_parity.py b/tools/test_block_survival_parity.py index fac8f64b1..2d99db9e2 100644 --- a/tools/test_block_survival_parity.py +++ b/tools/test_block_survival_parity.py @@ -205,7 +205,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockSurvivalOracle.java' helpers=[oracle.with_name(name+'.java') for name in ['VanillaBlockPropertiesOracle','VanillaBlockSupportOracle','VanillaBlockStateCodecOracle','VanillaCollisionOracle','VanillaHeightmapOracle']] - sources=[oracle,*helpers,lab.ROOT/'tools/test_worldgen_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/block_survival_fixture.rs'] + sources=[oracle,*helpers,lab.ROOT/'tools/test_worldgen_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/block_survival_fixture.rs'] tested_sources=base.source_hashes(sources) environment={'minecraft':lock['minecraft']['version'],'manifest_sha1':lock['minecraft']['manifest_sha1'],'platform':platform.platform(),'java':subprocess.check_output(['java','--version'],text=True).splitlines()[0],'rustc':subprocess.check_output(['rustc','--version'],text=True).strip(),'dependencies':{str(path):lab.digest(path,'sha256') for path in [*jars.values(),*libraries]}} checkpoint=load_checkpoint(checkpoint_path,tested_sources,environment) if args.resume else None @@ -236,9 +236,9 @@ def main(): output.write(json.dumps(fixture,separators=(',',':'))+'\n');fixture_count+=1 fixture_paths=[inputs,build/'survival-extra-definitions.json',build/'fluid-tags.json',build/'survival-placement-classes.json',build/'survival-support-tags.json',build/'facts.json',build/'survival-classes.json',build/'survival-rules.json',build/'tags.json',build/'block-registry.nbt',build/'cached-collision.nbt',build/'block-properties.nbt',build/'cached-support.nbt'] tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','block_survival_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('block_survival_fixture.exe' if os.name=='nt' else 'block_survival_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') base.ensure_sources_unchanged(sources,tested_sources) checkpoint={'schema':1,'environment':environment,'sources_sha256':tested_sources,'fixtures_sha256':{str(lab.ROOT/name):digest for name,digest in tested_fixtures.items()},'artifacts_sha256':{str(path):lab.digest(path,'sha256') for path in [binary,*sorted(classes.rglob('*.class'))]},'binary':str(binary),'counts':{'supported_blocks':len(definitions),'supported_states':sum(state['id'] in definitions for state in facts['states']),'survival_rules':len(set(definitions.values())),'survival_rule_kinds':len({rule.split(':',1)[0] for rule in definitions.values()}),'fluid_tag_files':len(fluid_tags),'fixtures':fixture_count},'outputs':{}} save_checkpoint(checkpoint_path,checkpoint) @@ -251,7 +251,7 @@ def main(): checkpoint['outputs'][name]=lab.digest(output,'sha256') save_checkpoint(checkpoint_path,checkpoint) print(f'{name}: completed output checkpointed',flush=True) - stage('rust',lambda:run([checkpoint['binary'],build],'rust')) + stage('rust',lambda:run([checkpoint['binary'],'block_survival_fixture',build],'rust')) references=[] for side,jar in jars.items(): stage(side,lambda:java(side,side,build)) diff --git a/tools/test_blocking_item_damage_parity.py b/tools/test_blocking_item_damage_parity.py index d9a8c9669..b8b3ea251 100644 --- a/tools/test_blocking_item_damage_parity.py +++ b/tools/test_blocking_item_damage_parity.py @@ -49,7 +49,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockingItemDamageOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/blocking_item_damage_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/blocking_item_damage_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -60,10 +60,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBlockingItemDamageOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','blocking_item_damage_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('blocking_item_damage_fixture.exe' if os.name=='nt' else 'blocking_item_damage_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'blocking_item_damage_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_blocking_rules_parity.py b/tools/test_blocking_rules_parity.py index 5afc38333..2ff5763d6 100644 --- a/tools/test_blocking_rules_parity.py +++ b/tools/test_blocking_rules_parity.py @@ -49,7 +49,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockingRulesOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/blocking_rules_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/blocking_rules_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -60,10 +60,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBlockingRulesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','blocking_rules_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('blocking_rules_fixture.exe' if os.name=='nt' else 'blocking_rules_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'blocking_rules_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_breaking_model_parity.py b/tools/test_breaking_model_parity.py index 92b74d582..272e57dea 100644 --- a/tools/test_breaking_model_parity.py +++ b/tools/test_breaking_model_parity.py @@ -29,13 +29,13 @@ def canonical(quads): def main(): lock,jars,_=base.verify_artifacts();libraries=baking.client_libraries() resources=lab.RESOURCES;build=lab.LOCAL/"breaking-model-parity";build.mkdir(exist_ok=True) - paths=[lab.ROOT/"tools/test_breaking_model_parity.py",lab.ROOT/"crates/horizon-client/src/breaking.rs",lab.ROOT/"crates/horizon-client/src/game.rs",lab.ROOT/"crates/horizon-client/src/gfx.rs",lab.ROOT/"crates/horizon-client/src/entity.wgsl",lab.ROOT/"crates/horizon-client/src/models/catalog.rs",lab.ROOT/"crates/horizon-client/src/mesher.rs",lab.ROOT/"crates/horizon-client/src/camera.rs",lab.ROOT/"crates/horizon-client/examples/breaking_fixture.rs",lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBreakingModelOracle.java",lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSectionMeshOracle.java",lab.ROOT/"Cargo.lock"] + paths=[lab.ROOT/"tools/test_breaking_model_parity.py",lab.ROOT/"crates/horizon-client/src/breaking.rs",lab.ROOT/"crates/horizon-client/src/game.rs",lab.ROOT/"crates/horizon-client/src/gfx.rs",lab.ROOT/"crates/horizon-client/src/entity.wgsl",lab.ROOT/"crates/horizon-client/src/models/catalog.rs",lab.ROOT/"crates/horizon-client/src/mesher.rs",lab.ROOT/"crates/horizon-client/src/camera.rs",lab.ROOT/"crates/horizon-client/examples/probe/breaking_fixture.rs",lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBreakingModelOracle.java",lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSectionMeshOracle.java",lab.ROOT/"Cargo.lock"] tested=base.source_hashes(paths) rows=[dict(case=i,**row) for i,row in enumerate(cases(resources))] inputs=build/"inputs.jsonl";inputs.write_text("".join(json.dumps(row)+"\n" for row in rows)) classes,dependencies,_=harness.compile_oracle(build,"VanillaBreakingModelOracle",jars,libraries,lock["minecraft"]["java_major"]) - binary=harness.build_probe(build,"breaking_fixture") - harness.run_logged([binary,resources,inputs,build/"rust.jsonl"],build,"rust") + command=harness.build_probe(build,"breaking_fixture") + harness.run_logged([*command,resources,inputs,build/"rust.jsonl"],build,"rust") harness.java_run(build,classes,dependencies,"VanillaBreakingModelOracle",[inputs,build/"client.jsonl"],"client") count=vertices=0;max_error=0.0 with (build/"client.jsonl").open() as native, (build/"rust.jsonl").open() as rust: diff --git a/tools/test_bulk_section_parity.py b/tools/test_bulk_section_parity.py index 414613067..b9a9ae3a8 100644 --- a/tools/test_bulk_section_parity.py +++ b/tools/test_bulk_section_parity.py @@ -52,7 +52,7 @@ def main(): helper=oracle.with_name("VanillaHeightmapOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock", lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/bulk_section_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/bulk_section_fixture.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -70,10 +70,10 @@ def main(): (build/"tags.json").write_text(json.dumps(tags,separators=(",",":")),encoding="utf-8") fixture_paths=[inputs,build/"tags.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","bulk_section_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("bulk_section_fixture.exe" if os.name=="nt" else "bulk_section_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"bulk_section_fixture",build],"rust") references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_bundle_weight_parity.py b/tools/test_bundle_weight_parity.py index 0d42a2ded..c509e08a1 100644 --- a/tools/test_bundle_weight_parity.py +++ b/tools/test_bundle_weight_parity.py @@ -53,7 +53,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBundleWeightOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/bundle_weight_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/bundle_weight_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -64,10 +64,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBundleWeightOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','bundle_weight_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('bundle_weight_fixture.exe' if os.name=='nt' else 'bundle_weight_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'bundle_weight_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_camera_parity.py b/tools/test_camera_parity.py index 3cd0e403d..bde9ea897 100644 --- a/tools/test_camera_parity.py +++ b/tools/test_camera_parity.py @@ -20,14 +20,6 @@ except ImportError: import lab, oracle_harness as harness -def fbits(v): - return struct.pack('>f', v).hex() - - -def dbits(v): - return struct.pack('>d', v).hex() - - def f32(v): return struct.unpack('>f', struct.pack('>f', v))[0] @@ -39,8 +31,8 @@ TICKS = [0, 1, 5, 10, 19, 20, 21, 72000, -5, 3] def fov_fields(rng): use = rng.choice([None, None, ['bow', rng.choice(TICKS)], ['spyglass', rng.choice(TICKS)], ['other', rng.choice(TICKS)]]) - return dict(flying=rng.random() < 0.3, ws=fbits(rng.choice(WALK + [rng.uniform(-0.3, 0.3)])), - speed=dbits(rng.choice(SPEED + [rng.uniform(0, 2)])), use=use) + return dict(flying=rng.random() < 0.3, ws=lab.fbits(rng.choice(WALK + [rng.uniform(-0.3, 0.3)])), + speed=lab.dbits(rng.choice(SPEED + [rng.uniform(0, 2)])), use=use) def fov_cases(rng): @@ -50,9 +42,9 @@ def fov_cases(rng): for use in [None, ['bow', 0], ['bow', 7], ['bow', 20], ['bow', 40], ['spyglass', 2], ['other', 5]]: for fp in (False, True): for scale in (0.0, 0.5, 1.0): - yield dict(t='fov', flying=flying, ws=fbits(ws), speed=dbits(speed), use=use, fp=fp, scale=fbits(scale)) + yield dict(t='fov', flying=flying, ws=lab.fbits(ws), speed=lab.dbits(speed), use=use, fp=fp, scale=lab.fbits(scale)) for _ in range(3000): - yield dict(t='fov', **fov_fields(rng), fp=rng.random() < 0.6, scale=fbits(rng.choice([0.0, 1.0, rng.random()]))) + yield dict(t='fov', **fov_fields(rng), fp=rng.random() < 0.6, scale=lab.fbits(rng.choice([0.0, 1.0, rng.random()]))) FULL = [[0, 0, 0, 1, 1, 1]] @@ -65,7 +57,7 @@ def world(rng, center): cx, cy, cz = center for _ in range(rng.choice([0, 3, 10, 40, 120])): p = (cx + rng.randint(-6, 6), cy + rng.randint(-3, 5), cz + rng.randint(-6, 6)) - cells[f'{p[0]} {p[1]} {p[2]}'] = [[dbits(v) for v in box] for box in rng.choice(SHAPES)] + cells[f'{p[0]} {p[1]} {p[2]}'] = [[lab.dbits(v) for v in box] for box in rng.choice(SHAPES)] return cells @@ -81,22 +73,22 @@ def entity_state(rng, center): prev = [p - rng.choice([0, 0, 0.1, 0.3, 1.0, rng.uniform(-1, 1)]) for p in pos] kind = 'player' if rng.random() < 0.85 else 'marker' xr, yr = angle(rng), angle(rng) - s = dict(kind=kind, pos=[dbits(v) for v in pos], prev=[dbits(v) for v in prev], xr=fbits(xr), yr=fbits(yr), - xro=fbits(rng.choice([xr, xr - 5, angle(rng)])), yro=fbits(rng.choice([yr, yr + 10, angle(rng)])), - eye=fbits(rng.choice([1.62, 1.27, 0.4, 0.2, 0.81, 3.24, rng.uniform(0, 4)]))) + s = dict(kind=kind, pos=[lab.dbits(v) for v in pos], prev=[lab.dbits(v) for v in prev], xr=lab.fbits(xr), yr=lab.fbits(yr), + xro=lab.fbits(rng.choice([xr, xr - 5, angle(rng)])), yro=lab.fbits(rng.choice([yr, yr + 10, angle(rng)])), + eye=lab.fbits(rng.choice([1.62, 1.27, 0.4, 0.2, 0.81, 3.24, rng.uniform(0, 4)]))) s.update(fov_fields(rng)) - s.update(scale_attr=dbits(rng.choice([1.0, 1.0, 0.5, 2.0, 0.0625, 16.0, rng.uniform(0.0625, 3)])), - dist=dbits(rng.choice([4.0, 4.0, 0.0, 1.0, 10.0, 32.0, rng.uniform(0, 32)])), + s.update(scale_attr=lab.dbits(rng.choice([1.0, 1.0, 0.5, 2.0, 0.0625, 16.0, rng.uniform(0.0625, 3)])), + dist=lab.dbits(rng.choice([4.0, 4.0, 0.0, 1.0, 10.0, 32.0, rng.uniform(0, 32)])), sleeping=rng.choice([None] * 6 + [[None], [0], [1], [2], [3]]), dead=rng.choice([None] * 6 + [0, 1, 5, 19, 20, 25]), - mount=rng.choice([None] * 4 + [[dbits(rng.choice([1.0, 2.0, 0.5])), dbits(rng.choice([4.0, 8.0, 1.0]))]])) + mount=rng.choice([None] * 4 + [[lab.dbits(rng.choice([1.0, 2.0, 0.5])), lab.dbits(rng.choice([4.0, 8.0, 1.0]))]])) return s def window(rng): """Window size and Camera.depthFar for the world and hand projections.""" w, h = rng.choice([(1600, 1000), (854, 480), (1920, 1080), (800, 1200), (1, 1), (rng.randint(1, 4000), rng.randint(1, 3000))]) - return [fbits(w), fbits(h), fbits(rng.choice([768.0, 128.0, 2048.0, 4096.0, rng.uniform(32, 4096)]))] + return [lab.fbits(w), lab.fbits(h), lab.fbits(rng.choice([768.0, 128.0, 2048.0, 4096.0, rng.uniform(32, 4096)]))] def camera_cases(rng): @@ -113,11 +105,11 @@ def camera_cases(rng): ops.append(['tick']) elif kind == 'frame': pt = rng.choice([0.0, 1.0, 0.5, 0.25, 0.999, rng.random()]) - ops.append(['frame', fbits(pt), rng.choice([0, 0, 0, 1, 2, 3]), rng.random() < 0.05] + window(rng)) + ops.append(['frame', lab.fbits(pt), rng.choice([0, 0, 0, 1, 2, 3]), rng.random() < 0.05] + window(rng)) else: ops.append(['type', rng.randrange(3)]) yield dict(t='camera', fov=rng.choice([70, 30, 110, 90, rng.randint(30, 110)]), - effect=dbits(rng.choice([1.0, 0.0, 0.5, rng.random()])), type=rng.choice([0, 1, 1, 2]), + effect=lab.dbits(rng.choice([1.0, 0.0, 0.5, rng.random()])), type=rng.choice([0, 1, 1, 2]), cells=world(rng, center), ops=ops) # The hand's projection at FOV 30, 70 and 110 while walking, sprinting, under # speed, drawing a bow, dying and in fluids: GameRenderer.render3dHud uses @@ -127,13 +119,13 @@ def camera_cases(rng): for use in (None, ['bow', 10]): for dead in (None, 5): for fluid in (0, 1, 2): - s = dict(kind='player', pos=[dbits(0.5), dbits(64.0), dbits(0.5)], prev=[dbits(0.5), dbits(64.0), dbits(0.5)], - xr=fbits(0.0), yr=fbits(0.0), xro=fbits(0.0), yro=fbits(0.0), eye=fbits(1.62), flying=False, - ws=fbits(0.1), speed=dbits(speed), use=use, scale_attr=dbits(1.0), dist=dbits(4.0), + s = dict(kind='player', pos=[lab.dbits(0.5), lab.dbits(64.0), lab.dbits(0.5)], prev=[lab.dbits(0.5), lab.dbits(64.0), lab.dbits(0.5)], + xr=lab.fbits(0.0), yr=lab.fbits(0.0), xro=lab.fbits(0.0), yro=lab.fbits(0.0), eye=lab.fbits(1.62), flying=False, + ws=lab.fbits(0.1), speed=lab.dbits(speed), use=use, scale_attr=lab.dbits(1.0), dist=lab.dbits(4.0), sleeping=None, dead=dead, mount=None) - ops = [['entity', s]] + [['tick']] * 8 + [['frame', fbits(pt), fluid, False, fbits(1600.0), fbits(1000.0), fbits(768.0)] + ops = [['entity', s]] + [['tick']] * 8 + [['frame', lab.fbits(pt), fluid, False, lab.fbits(1600.0), lab.fbits(1000.0), lab.fbits(768.0)] for pt in (0.0, 0.5, 1.0)] - yield dict(t='camera', fov=fov, effect=dbits(1.0), type=0, cells={}, ops=ops) + yield dict(t='camera', fov=fov, effect=lab.dbits(1.0), type=0, cells={}, ops=ops) # A walled-in third-person camera stepping through every distance bound. for dist in [0.0, 0.5, 1.0, 2.0, 4.0, 8.0, 32.0]: for wall in range(0, 6): @@ -141,28 +133,28 @@ def camera_cases(rng): cells = {} for dx in range(-6, 7): for dy in range(62, 68): - cells[f'{dx} {dy} {-wall - 1}'] = [[dbits(v) for v in box] for box in FULL] - cells[f'{dx} {dy} {wall + 1}'] = [[dbits(v) for v in box] for box in FULL] - s = dict(kind='player', pos=[dbits(0.5), dbits(64.0), dbits(0.5)], prev=[dbits(0.5), dbits(64.0), dbits(0.5)], - xr=fbits(15.0), yr=fbits(yaw), xro=fbits(15.0), yro=fbits(yaw), eye=fbits(1.62), flying=False, - ws=fbits(0.1), speed=dbits(f32(0.1)), use=None, scale_attr=dbits(1.0), dist=dbits(dist), + cells[f'{dx} {dy} {-wall - 1}'] = [[lab.dbits(v) for v in box] for box in FULL] + cells[f'{dx} {dy} {wall + 1}'] = [[lab.dbits(v) for v in box] for box in FULL] + s = dict(kind='player', pos=[lab.dbits(0.5), lab.dbits(64.0), lab.dbits(0.5)], prev=[lab.dbits(0.5), lab.dbits(64.0), lab.dbits(0.5)], + xr=lab.fbits(15.0), yr=lab.fbits(yaw), xro=lab.fbits(15.0), yro=lab.fbits(yaw), eye=lab.fbits(1.62), flying=False, + ws=lab.fbits(0.1), speed=lab.dbits(f32(0.1)), use=None, scale_attr=lab.dbits(1.0), dist=lab.dbits(dist), sleeping=None, dead=None, mount=None) - ops = [['entity', s]] + [['tick']] * 6 + [['frame', fbits(pt), 0, False] + window(rng) for pt in (0.0, 0.5, 1.0)] - yield dict(t='camera', fov=70, effect=dbits(1.0), type=1 + (wall % 2), cells=cells, ops=ops) + ops = [['entity', s]] + [['tick']] * 6 + [['frame', lab.fbits(pt), 0, False] + window(rng) for pt in (0.0, 0.5, 1.0)] + yield dict(t='camera', fov=70, effect=lab.dbits(1.0), type=1 + (wall % 2), cells=cells, ops=ops) def bob_cases(rng): for n in range(6000): living = None if rng.random() < 0.8: - living = dict(hurt=fbits(rng.choice([-1.0, -0.5, 0.0, 10.0, 9.5, 5.25, 1.0, rng.uniform(-2, 11)])), - duration=rng.choice([10, 10, 0, 5, 20]), dir=fbits(rng.choice([0.0, 90.0, -45.0, 180.0, rng.uniform(-360, 360)])), - death=rng.choice([None, None, None, fbits(rng.choice([0.0, 0.5, 19.5, 20.0, 25.0, rng.uniform(0, 30)]))])) + living = dict(hurt=lab.fbits(rng.choice([-1.0, -0.5, 0.0, 10.0, 9.5, 5.25, 1.0, rng.uniform(-2, 11)])), + duration=rng.choice([10, 10, 0, 5, 20]), dir=lab.fbits(rng.choice([0.0, 90.0, -45.0, 180.0, rng.uniform(-360, 360)])), + death=rng.choice([None, None, None, lab.fbits(rng.choice([0.0, 0.5, 19.5, 20.0, 25.0, rng.uniform(0, 30)]))])) player = None if rng.random() < 0.8: - player = [fbits(rng.choice([0.0, -0.3, -1.7, -100.25, rng.uniform(-1000, 0)])), - fbits(rng.choice([0.0, 0.1, 0.05, 0.0999, rng.uniform(0, 0.1)]))] - yield dict(t='bob', living=living, player=player, tilt=dbits(rng.choice([1.0, 0.0, 0.5, rng.random()])), + player = [lab.fbits(rng.choice([0.0, -0.3, -1.7, -100.25, rng.uniform(-1000, 0)])), + lab.fbits(rng.choice([0.0, 0.1, 0.05, 0.0999, rng.uniform(0, 0.1)]))] + yield dict(t='bob', living=living, player=player, tilt=lab.dbits(rng.choice([1.0, 0.0, 0.5, rng.random()])), view=rng.random() < 0.8) @@ -174,12 +166,12 @@ def avatar_cases(rng): if kind == 'tick': ops.append(['tick']) elif kind == 'move': - ops.append(['move', fbits(rng.choice([0.0, 0.2158, -0.1, rng.uniform(-1, 1)])), fbits(rng.choice([0.0, 0.2806, rng.uniform(-1, 1)]))]) + ops.append(['move', lab.fbits(rng.choice([0.0, 0.2158, -0.1, rng.uniform(-1, 1)])), lab.fbits(rng.choice([0.0, 0.2806, rng.uniform(-1, 1)]))]) elif kind == 'bob': v = [rng.choice([0.0, 0.05, -0.2, rng.uniform(-0.5, 0.5)]), rng.uniform(-1, 1), rng.choice([0.0, 0.08, rng.uniform(-0.5, 0.5)])] - ops.append(['bob', rng.random() < 0.7, rng.random() < 0.1, rng.random() < 0.1, [dbits(x) for x in v]]) + ops.append(['bob', rng.random() < 0.7, rng.random() < 0.1, rng.random() < 0.1, [lab.dbits(x) for x in v]]) elif kind == 'frame': - ops.append(['frame', fbits(rng.choice([0.0, 1.0, 0.5, rng.random()]))]) + ops.append(['frame', lab.fbits(rng.choice([0.0, 1.0, 0.5, rng.random()]))]) else: ops.append(['reset']) yield dict(t='avatar', ops=ops) diff --git a/tools/test_canyon_carver_parity.py b/tools/test_canyon_carver_parity.py index 81d281a4c..25fbc30de 100644 --- a/tools/test_canyon_carver_parity.py +++ b/tools/test_canyon_carver_parity.py @@ -54,7 +54,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCanyonCarverOracle.java" helper=oracle.with_name("VanillaAnchorOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/canyon_carver_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/canyon_carver_fixture.rs"] tested_sources=base.source_hashes(sources) resources=worldgen.registry_resources(jars['server'],'carver') if not resources or resources!=worldgen.registry_resources(jars['client'],'carver'):raise ValueError('reference carver resources differ') @@ -65,10 +65,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,helper],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","canyon_carver_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("canyon_carver_fixture.exe" if os.name=="nt" else "canyon_carver_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"canyon_carver_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_carving_geometry_parity.py b/tools/test_carving_geometry_parity.py index 0ad9e6da0..e69331bbe 100644 --- a/tools/test_carving_geometry_parity.py +++ b/tools/test_carving_geometry_parity.py @@ -63,7 +63,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCarvingGeometryOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/carving_geometry_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/carving_geometry_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") reach=list(reach_corpus());reach_path=build/'reach.txt';reach_path.write_text(''.join(json.dumps(q,separators=(',',':'))+'\n' for q in reach),encoding='utf-8') @@ -72,10 +72,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","carving_geometry_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("carving_geometry_fixture.exe" if os.name=="nt" else "carving_geometry_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"carving_geometry_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_carving_mask_parity.py b/tools/test_carving_mask_parity.py index a3d4e375c..15dacf52e 100644 --- a/tools/test_carving_mask_parity.py +++ b/tools/test_carving_mask_parity.py @@ -57,7 +57,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCarvingMaskOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/carving_mask_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/carving_mask_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -65,10 +65,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","carving_mask_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("carving_mask_fixture.exe" if os.name=="nt" else "carving_mask_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"carving_mask_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_cave_carver_parity.py b/tools/test_cave_carver_parity.py index 863dd15d4..d79914762 100644 --- a/tools/test_cave_carver_parity.py +++ b/tools/test_cave_carver_parity.py @@ -49,7 +49,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCaveCarverOracle.java" helper=oracle.with_name("VanillaAnchorOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/cave_carver_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/cave_carver_fixture.rs"] tested_sources=base.source_hashes(sources) resources=worldgen.registry_resources(jars['server'],'carver') if not resources or resources!=worldgen.registry_resources(jars['client'],'carver'):raise ValueError('reference carver resources differ') @@ -60,10 +60,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,helper],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","cave_carver_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("cave_carver_fixture.exe" if os.name=="nt" else "cave_carver_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"cave_carver_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_chat_screen_parity.py b/tools/test_chat_screen_parity.py index 1447ebaa6..fead1b5cb 100644 --- a/tools/test_chat_screen_parity.py +++ b/tools/test_chat_screen_parity.py @@ -8,7 +8,7 @@ all, history up and down, Tab and Shift+Tab through suggestions, Escape) and clicks (on the suggestion list, on the input). The Java oracle (VanillaChatScreenOracle) drives a real ChatScreen, whose CommandSuggestions parse with vanilla's client command tree and ask the server's dispatcher -for the suggestions a node leaves to it; examples/chat_screen_fixture runs +for the suggestions a node leaves to it; examples/probe/chat_screen_fixture runs horizon_client::chat::ChatScreen on Horizon's dispatcher. After the actions the input's value, cursor, selection and scroll and the screen's GUI calls (the input background, the EditBox with its argument colouring, cursor, diff --git a/tools/test_chunk_generation_parity.py b/tools/test_chunk_generation_parity.py index 13262dc3b..6951e4355 100644 --- a/tools/test_chunk_generation_parity.py +++ b/tools/test_chunk_generation_parity.py @@ -4,7 +4,7 @@ Vanilla side: VanillaChunkGenerationOracle drives the actual ChunkGenerator stages (structure starts and references, biomes, terrain with surface and carvers, then biome decoration with every placed feature and structure piece) -through real WorldGenRegion instances. Horizon side: the chunk_dump example +through real WorldGenRegion instances. Horizon side: the chunk_dump probe runs the same stages in the same order. Every block state, quart biome and block entity (canonical NBT) of each target chunk is compared. @@ -71,9 +71,9 @@ class Oracle: def rust_binary(): - subprocess.run(['cargo', 'build', '--release', '-q', '-p', 'horizon-world', '--example', 'chunk_dump'], check=True, cwd=lab.ROOT) + subprocess.run(['cargo', 'build', '--release', '-q', '-p', 'horizon-world', '--example', 'probe'], check=True, cwd=lab.ROOT) metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - return Path(metadata['target_directory']) / 'release/examples/chunk_dump' + return Path(metadata['target_directory']) / 'release/examples/probe' def run_rust(binary, out, seed, dimension, rects, scan=False): @@ -81,7 +81,7 @@ def run_rust(binary, out, seed, dimension, rects, scan=False): if scan: env['HORIZON_SCAN'] = '1' with open(out, 'w') as handle: - result = subprocess.run([str(binary), str(RESOURCES), str(seed), dimension, *rects], stdout=handle, stderr=subprocess.PIPE, text=True, env=env, cwd=lab.ROOT) + result = subprocess.run([str(binary), 'chunk_dump', str(RESOURCES), str(seed), dimension, *rects], stdout=handle, stderr=subprocess.PIPE, text=True, env=env, cwd=lab.ROOT) if result.returncode: raise SystemExit('chunk_dump failed: ' + result.stderr[-2000:]) return result.stderr diff --git a/tools/test_chunk_stage_parity.py b/tools/test_chunk_stage_parity.py index 6e055f631..b8aaa6153 100644 --- a/tools/test_chunk_stage_parity.py +++ b/tools/test_chunk_stage_parity.py @@ -55,7 +55,7 @@ def main(): helper=oracle.with_name("VanillaHeightmapOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock", lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/chunk_stage_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/chunk_stage_fixture.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -73,10 +73,10 @@ def main(): (build/"tags.json").write_text(json.dumps(tags,separators=(",",":")),encoding="utf-8") fixture_paths=[inputs,build/"tags.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","chunk_stage_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("chunk_stage_fixture.exe" if os.name=="nt" else "chunk_stage_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"chunk_stage_fixture",build],"rust") references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_chunk_status_parity.py b/tools/test_chunk_status_parity.py index cd6c7a2d6..17c3d65ed 100644 --- a/tools/test_chunk_status_parity.py +++ b/tools/test_chunk_status_parity.py @@ -34,7 +34,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkStatusOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/chunk_status_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/chunk_status_fixture.rs'] tested_sources=base.source_hashes(sources) commands=list(corpus());inputs=build/'inputs.txt';inputs.write_text('\n'.join(json.dumps(command) for command in commands)+'\n') tested_fixtures=base.source_hashes([inputs]);classes=build/'classes';classes.mkdir(exist_ok=True) @@ -42,10 +42,10 @@ def main(): with (build/(name+'.log')).open('w') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=3600,stdout=log,stderr=subprocess.STDOUT) dependencies=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependencies,'-d',classes,oracle],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','chunk_status_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('chunk_status_fixture.exe' if os.name=='nt' else 'chunk_status_fixture') - run([binary,inputs,build/'rust.txt'],'rust') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'chunk_status_fixture',inputs,build/'rust.txt'],'rust') references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependencies]),'dev.horizonlab.parity.VanillaChunkStatusOracle',inputs,build/(side+'.txt')],side) diff --git a/tools/test_climbing_parity.py b/tools/test_climbing_parity.py index 9c5a57260..7b54fc4fb 100644 --- a/tools/test_climbing_parity.py +++ b/tools/test_climbing_parity.py @@ -40,7 +40,7 @@ def corpus(info): def main(): lock,jars,libraries=base.verify_artifacts();build=lab.LOCAL/'rust-climbing-parity';build.mkdir(exist_ok=True);report_path=build/'report.json';report_path.unlink(missing_ok=True) root=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity';oracles=[root/(n+'.java') for n in ['VanillaClimbingOracle','VanillaHeightmapOracle']] - sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/climbing_fixture.rs'] + sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/probe/climbing_fixture.rs'] for crate in ['horizon-core','horizon-world']:sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] tested=base.source_hashes(sources);tags=worldgen.tag_resources(jars['server']) if tags!=worldgen.tag_resources(jars['client']):raise AssertionError('Native tags differ between artifacts') @@ -54,7 +54,7 @@ def main(): with (build/'inputs.txt').open('w') as output: for f in corpus(info):output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 fixture_paths=[build/n for n in ['inputs.txt','info.json','block-registry.nbt','tags.json']];fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','climbing_fixture'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('climbing_fixture.exe' if os.name=='nt' else 'climbing_fixture');run([binary,build],'rust');references=[] + run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'climbing_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side);matched=base.compare(build/(side+'.txt'),build/'rust.txt');references.append(dict(side=side,jar_sha256=lab.digest(jar,'sha256'),output_sha256=lab.digest(build/(side+'.txt'),'sha256'),matched_output_lines=matched));print(f'{side}: {matched:,} climbing output lines match Rust',flush=True) base.ensure_sources_unchanged(sources,tested);base.ensure_sources_unchanged(fixture_paths,fixtures) diff --git a/tools/test_collision_context_parity.py b/tools/test_collision_context_parity.py index 212e0d28e..da1f382db 100644 --- a/tools/test_collision_context_parity.py +++ b/tools/test_collision_context_parity.py @@ -48,7 +48,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionContextOracle.java' helpers=[oracle.with_name('VanillaFaceSupportOracle.java')] - sources=[oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/collision_context_fixture.rs'] + sources=[oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/collision_context_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaCollisionContextOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','collision_context_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('collision_context_fixture.exe' if os.name=='nt' else 'collision_context_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'collision_context_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_collision_parity.py b/tools/test_collision_parity.py index b4d2904a8..3031e47b2 100644 --- a/tools/test_collision_parity.py +++ b/tools/test_collision_parity.py @@ -39,7 +39,7 @@ def main(): lock, jars, libraries = test_rust_parity.verify_artifacts() base = Path(tempfile.mkdtemp(prefix="run-", dir=directory)) oracle = lab.ROOT / "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionOracle.java" - sources = [oracle, Path(__file__).resolve(), lab.ROOT / "tools/test_rust_parity.py", lab.ROOT / "Cargo.toml", lab.ROOT / "Cargo.lock", lab.ROOT / "crates/horizon-core/Cargo.toml", lab.ROOT / "crates/horizon-world/Cargo.toml", *sorted((lab.ROOT / "crates/horizon-core/src").rglob("*.rs")), *sorted((lab.ROOT / "crates/horizon-world/src").rglob("*.rs")), lab.ROOT / "crates/horizon-world/examples/collision_fixture.rs"] + sources = [oracle, Path(__file__).resolve(), lab.ROOT / "tools/test_rust_parity.py", lab.ROOT / "Cargo.toml", lab.ROOT / "Cargo.lock", lab.ROOT / "crates/horizon-core/Cargo.toml", lab.ROOT / "crates/horizon-world/Cargo.toml", *sorted((lab.ROOT / "crates/horizon-core/src").rglob("*.rs")), *sorted((lab.ROOT / "crates/horizon-world/src").rglob("*.rs")), lab.ROOT / "crates/horizon-world/examples/probe/collision_fixture.rs"] tested_sources = test_rust_parity.source_hashes(sources) classes = base / "classes" classes.mkdir() @@ -51,10 +51,10 @@ def main(): result.check_returncode() return result.stdout expected = counts(java("server", "generate")) - test_rust_parity.run(["cargo", "build", "--release", "-p", "horizon-world", "--example", "collision_fixture"]) + test_rust_parity.run(["cargo", "build", "--release", "-p", "horizon-world", "--example", "probe"]) metadata = json.loads(subprocess.check_output(["cargo", "metadata", "--no-deps", "--format-version", "1"], cwd=lab.ROOT, text=True)) - binary = Path(metadata["target_directory"]) / "release/examples" / ("collision_fixture.exe" if os.name == "nt" else "collision_fixture") - actual = counts(subprocess.check_output([str(binary), str(base)], cwd=lab.ROOT, text=True)) + binary = Path(metadata["target_directory"]) / "release/examples" / ("probe.exe" if os.name=="nt" else "probe") + actual = counts(subprocess.check_output([str(binary), "collision_fixture", str(base)], cwd=lab.ROOT, text=True)) if actual != expected: raise AssertionError(f"Collision coverage differs: vanilla={expected}, Rust={actual}") canonical = {"empty_states":0,"block_states":0,"other_cached_states":0} diff --git a/tools/test_combat_rules_parity.py b/tools/test_combat_rules_parity.py index e7d2f89ac..642c0603d 100644 --- a/tools/test_combat_rules_parity.py +++ b/tools/test_combat_rules_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCombatRulesOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/combat_rules_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/combat_rules_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaCombatRulesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','combat_rules_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('combat_rules_fixture.exe' if os.name=='nt' else 'combat_rules_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'combat_rules_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_command_parse_parity.py b/tools/test_command_parse_parity.py index 192cc5b9f..c43e66b54 100644 --- a/tools/test_command_parse_parity.py +++ b/tools/test_command_parse_parity.py @@ -64,9 +64,9 @@ def main(): registries = json.loads((build / 'registries.json').read_text()) corpus = corpus_module.corpus(tree, registries) (build / 'corpus.txt').write_text(''.join(line + '\n' for line in corpus), encoding='utf-8') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'command_parse_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('command_parse_fixture.exe' if os.name == 'nt' else 'command_parse_fixture') + binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') resources = lab.RESOURCES total_failures = 0 summary = [] @@ -79,7 +79,7 @@ def main(): if not (stamp.exists() and stamp.read_text() == digest and (level_dir / 'vanilla.jsonl').exists()): java('run', str(level_dir), str(build / 'corpus.txt'), str(permission)) stamp.write_text(digest) - run([binary, resources, build / 'registries.json', build / 'corpus.txt', str(permission), level_dir / 'rust.jsonl'], f'rust{permission}') + run([binary, 'command_parse_fixture',resources, build / 'registries.json', build / 'corpus.txt', str(permission), level_dir / 'rust.jsonl'], f'rust{permission}') failures = compare(level_dir / 'vanilla.jsonl', level_dir / 'rust.jsonl', args.limit) count = sum(1 for _ in (level_dir / 'vanilla.jsonl').open()) print(f'permission {permission}: {count - failures}/{count} commands match', flush=True) diff --git a/tools/test_component_durability_parity.py b/tools/test_component_durability_parity.py index fa97e30d4..e912fa80b 100644 --- a/tools/test_component_durability_parity.py +++ b/tools/test_component_durability_parity.py @@ -60,7 +60,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaComponentDurabilityOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/component_durability_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/component_durability_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -71,10 +71,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaComponentDurabilityOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','component_durability_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('component_durability_fixture.exe' if os.name=='nt' else 'component_durability_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'component_durability_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_component_patch_parity.py b/tools/test_component_patch_parity.py index dcbb1ed27..bae69bb56 100644 --- a/tools/test_component_patch_parity.py +++ b/tools/test_component_patch_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaComponentPatchOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/component_patch_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/component_patch_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaComponentPatchOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','component_patch_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('component_patch_fixture.exe' if os.name=='nt' else 'component_patch_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'component_patch_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_consumable_emission_parity.py b/tools/test_consumable_emission_parity.py index 3919be5bc..7e8085087 100644 --- a/tools/test_consumable_emission_parity.py +++ b/tools/test_consumable_emission_parity.py @@ -44,7 +44,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaConsumableEmissionOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/consumable_emission_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/consumable_emission_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -55,10 +55,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaConsumableEmissionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','consumable_emission_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('consumable_emission_fixture.exe' if os.name=='nt' else 'consumable_emission_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'consumable_emission_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_consumable_parity.py b/tools/test_consumable_parity.py index 36ccf0138..083ff810f 100644 --- a/tools/test_consumable_parity.py +++ b/tools/test_consumable_parity.py @@ -50,7 +50,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaConsumableOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/consumable_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/consumable_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -61,10 +61,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaConsumableOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','consumable_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('consumable_fixture.exe' if os.name=='nt' else 'consumable_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'consumable_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_consume_effect_parity.py b/tools/test_consume_effect_parity.py index bf3a31961..4f4037073 100644 --- a/tools/test_consume_effect_parity.py +++ b/tools/test_consume_effect_parity.py @@ -44,7 +44,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaConsumeEffectOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/consume_effect_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/consume_effect_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -55,10 +55,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaConsumeEffectOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','consume_effect_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('consume_effect_fixture.exe' if os.name=='nt' else 'consume_effect_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'consume_effect_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_contextual_collision_parity.py b/tools/test_contextual_collision_parity.py index 2a2eb9090..bbfe45b02 100644 --- a/tools/test_contextual_collision_parity.py +++ b/tools/test_contextual_collision_parity.py @@ -36,7 +36,7 @@ def main(): oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionContextOracle.java' helpers=[oracle.with_name(name+'.java') for name in ['VanillaFaceSupportOracle','VanillaCollisionOracle','VanillaContextualCollisionAudit']] runner=lab.ROOT/'tools/test_collision_context_parity.py' - sources=[oracle,*helpers,runner,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/collision_context_fixture.rs'] + sources=[oracle,*helpers,runner,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/collision_context_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -48,10 +48,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars['server']),dependency_path]),'dev.horizonlab.parity.VanillaCollisionOracle','generate',build],'export') fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'block-registry.nbt',build/'cached-collision.nbt'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','collision_context_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('collision_context_fixture.exe' if os.name=='nt' else 'collision_context_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'collision_context_fixture',build],'rust');references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependency_path]),'dev.horizonlab.parity.VanillaContextualCollisionAudit',side,build],side+'-audit') audited=base.compare(build/(side+'-audit.txt'),build/'rust-audit.txt') diff --git a/tools/test_creative_parity.py b/tools/test_creative_parity.py index aa23cbbc9..6a96d3c52 100644 --- a/tools/test_creative_parity.py +++ b/tools/test_creative_parity.py @@ -7,7 +7,7 @@ tab built by vanilla's CreativeModeTabs over the vanilla data pack's registries), then what the vanilla client shows: every tab's display items and, for each search query, CreativeModeInventoryScreen.refreshSearchResults' items, searched through the client's own SessionSearchTrees. -examples/creative_search_fixture loads the export into +examples/probe/creative_search_fixture loads the export into horizon_client::creative::Creative. The tabs it shows (id, title, icon, position, every stack with its components), the search tab's stacks and the results of every query must agree. The queries are QUERIES below, then every diff --git a/tools/test_damage_immunity_parity.py b/tools/test_damage_immunity_parity.py index 962634bcc..d68277dd8 100644 --- a/tools/test_damage_immunity_parity.py +++ b/tools/test_damage_immunity_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDamageImmunityOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/damage_immunity_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/damage_immunity_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaDamageImmunityOracle',mode,path],side+'-'+mode) java('server','export',build);fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'slots.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','damage_immunity_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('damage_immunity_fixture.exe' if os.name=='nt' else 'damage_immunity_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'damage_immunity_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_damage_reduction_parity.py b/tools/test_damage_reduction_parity.py index ad53500fb..06c827dcf 100644 --- a/tools/test_damage_reduction_parity.py +++ b/tools/test_damage_reduction_parity.py @@ -53,7 +53,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDamageReductionOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/damage_reduction_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/damage_reduction_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -65,10 +65,10 @@ def main(): java('server','export',build) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'slots.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','damage_reduction_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('damage_reduction_fixture.exe' if os.name=='nt' else 'damage_reduction_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'damage_reduction_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_damage_source_parity.py b/tools/test_damage_source_parity.py index a532e4ff0..75f360822 100644 --- a/tools/test_damage_source_parity.py +++ b/tools/test_damage_source_parity.py @@ -45,7 +45,7 @@ def main(): resources={'minecraft:'+n[len(prefix):-5]:archive.read(n).decode('utf-8') for n in sorted(archive.namelist()) if n.startswith(prefix) and n.endswith('.json')};lab.write_json(build/file,resources) oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDamageSourceOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/damage_source_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/damage_source_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -56,10 +56,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaDamageSourceOracle',mode,path],side+'-'+mode) java('server','export',build);catalog=json.loads((build/'catalog.json').read_text());fixtures=list(corpus(catalog));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json',build/'types.json',build/'tags.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','damage_source_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('damage_source_fixture.exe' if os.name=='nt' else 'damage_source_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'damage_source_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_datafix_parity.py b/tools/test_datafix_parity.py index a2d11009c..dc5a2495b 100644 --- a/tools/test_datafix_parity.py +++ b/tools/test_datafix_parity.py @@ -9,7 +9,7 @@ generated automatically when missing), two upgrades run on a copy: vanilla VanillaDataFixOracle: FileFixerUpper, then DataFixers on level.dat, every chunk, entity chunk and POI chunk, player, saved data, advancements and statistics file, exactly as 26.3 does when it opens the world - horizon the `datafix_world` example of horizon-world, which does the same with + horizon the `datafix_world` probe of horizon-world, which does the same with horizon_world::datafix Then every file is compared: region files chunk by chunk, NBT files and JSON @@ -33,6 +33,7 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) import anvil_dump # noqa: E402 +import parity_shard # noqa: E402 ROOT = Path(__file__).resolve().parent.parent LOCAL = ROOT / '.local' / 'datafix' @@ -63,7 +64,7 @@ def java_classpath(): import test_model_baking_parity as baking lock, jars, _ = base.verify_artifacts() libraries = baking.client_libraries() - build = LOCAL / 'build' / os.environ.get('PARITY_SHARD', 'all').replace('/', '-') # shards compile apart + build = LOCAL / 'build' / parity_shard.label() # shards compile apart build.mkdir(parents=True, exist_ok=True) classes, dependencies, _ = harness.compile_oracle(build, 'VanillaDataFixOracle', jars, libraries, lock['minecraft']['java_major']) @@ -71,20 +72,11 @@ def java_classpath(): def build_rust(): - subprocess.run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'datafix_world'], + subprocess.run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], cwd=ROOT, check=True) meta = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=ROOT)) - return Path(meta['target_directory']) / 'release' / 'examples' / 'datafix_world' - - -def shard(items): - """This run's share of items when tools/parity.py runs the harness in parts (PARITY_SHARD=i/n).""" - spec = os.environ.get('PARITY_SHARD') - if not spec: - return items - index, count = map(int, spec.split('/')) - return items[index - 1::count] + return Path(meta['target_directory']) / 'release' / 'examples' / 'probe' def run_vanilla(classpath, world, out, target=None): @@ -100,7 +92,8 @@ def run_horizon(binary, world, out, target=None): shutil.rmtree(out, ignore_errors=True) log = out.parent / (out.name + '.log') with log.open('w') as f: - subprocess.run([str(binary), str(world), str(out), *([str(target)] if target else [])], check=True, stdout=f, stderr=subprocess.STDOUT) + subprocess.run([str(binary), 'datafix_world', str(world), str(out), *([str(target)] if target else [])], check=True, + stdout=f, stderr=subprocess.STDOUT) # ---------------------------------------------------------------- comparison @@ -209,7 +202,7 @@ def main(): p.add_argument('versions', nargs='*') p.add_argument('--keep', action='store_true') p.add_argument('--vanilla-only', action='store_true', help='only run the oracle') - p.add_argument('--binary', help='a prebuilt datafix_world example') + p.add_argument('--binary', help='a prebuilt horizon-world probe binary') p.add_argument('--band', type=int, metavar='TARGET', help='check the data fixes up to this DataVersion only (not the ' 'file fixes), on the sample worlds saved before it, for developing the fixes of a range of versions') args = p.parse_args() @@ -226,7 +219,7 @@ def main(): band = args.band if band and not args.versions: # worlds in the layout of before 1.16, saved before the target worlds = [w for w in worlds if json.loads((world_path(w) / 'datafix-source.json').read_text())['data_version'] < band] - versions = shard(args.versions or worlds) + versions = parity_shard.shard(args.versions or worlds) classpath = java_classpath() binary = None if args.vanilla_only else Path(args.binary) if args.binary else build_rust() total = 0 diff --git a/tools/test_decorated_region_parity.py b/tools/test_decorated_region_parity.py index 2716a99e0..71ba5b469 100644 --- a/tools/test_decorated_region_parity.py +++ b/tools/test_decorated_region_parity.py @@ -66,7 +66,7 @@ def build_dir(): def vanilla_order(binary, cx, cz, view): - out = subprocess.run([str(binary), str(cg.RESOURCES), '0', 'overworld'], capture_output=True, text=True, check=True, + out = subprocess.run([str(binary), 'chunk_dump', str(cg.RESOURCES), '0', 'overworld'], capture_output=True, text=True, check=True, env=dict(os.environ, HORIZON_LIST_ORDER=f'{cx},{cz},{view}'), cwd=lab.ROOT).stdout return [tuple(map(int, line.split())) for line in out.splitlines()] diff --git a/tools/test_decoration_parity.py b/tools/test_decoration_parity.py index 1b8fa4065..ae8c7ce02 100644 --- a/tools/test_decoration_parity.py +++ b/tools/test_decoration_parity.py @@ -65,7 +65,7 @@ def main(): resources=sort.biome_features(jars['server']) if len(resources)!=67 or resources!=sort.biome_features(jars['client']):raise ValueError('pinned biome feature resources differ') oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDecorationOracle.java';helper=oracle.with_name('VanillaPlacementOracle.java') - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_feature_sort_parity.py',lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/decoration_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_feature_sort_parity.py',lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/decoration_fixture.rs'] tested_sources=base.source_hashes(sources) fixtures=list(corpus(resources));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') resource_path=build/'biome-features.json';resource_path.write_text(json.dumps(resources,separators=(',',':')),encoding='utf-8') @@ -75,10 +75,10 @@ def main(): with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle,helper],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','decoration_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('decoration_fixture.exe' if os.name=='nt' else 'decoration_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'decoration_fixture',build],'rust');references=[] for side,jar in jars.items(): run(['java','-Xmx768M','-cp',os.pathsep.join([str(classes),str(jar),dependency_path]),'dev.horizonlab.parity.VanillaDecorationOracle',side,build],side) reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_decoration_region_parity.py b/tools/test_decoration_region_parity.py index 0b59c4817..c91ab86e8 100644 --- a/tools/test_decoration_region_parity.py +++ b/tools/test_decoration_region_parity.py @@ -55,7 +55,7 @@ def main(): placement_helper=oracle.with_name("VanillaPlacementOracle.java") sources=[oracle,helper,placement_helper,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_feature_region_parity.py",lab.ROOT/"tools/test_decoration_parity.py",lab.ROOT/"tools/test_feature_sort_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock", lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/decoration_region_fixture.rs",lab.ROOT/"crates/horizon-world/examples/support/decoration_storage.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/decoration_region_fixture.rs",lab.ROOT/"crates/horizon-world/examples/probe/support/decoration_storage.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -73,10 +73,10 @@ def main(): (build/"tags.json").write_text(json.dumps(tags,separators=(",",":")),encoding="utf-8") fixture_paths=[inputs,build/"tags.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","decoration_region_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("decoration_region_fixture.exe" if os.name=="nt" else "decoration_region_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"decoration_region_fixture",build],"rust") references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_dedicated_server_parity.py b/tools/test_dedicated_server_parity.py index 22677bf07..07d61f3d5 100644 --- a/tools/test_dedicated_server_parity.py +++ b/tools/test_dedicated_server_parity.py @@ -68,10 +68,12 @@ import zlib try: from . import lab, oracle_harness as oh, test_rust_parity as base + from .lab import free_port # the other server harnesses import it from here except ImportError: import lab import oracle_harness as oh import test_rust_parity as base + from lab import free_port NAME = 'dedicated-server-parity' SEED = 12345 @@ -89,12 +91,6 @@ PROPERTIES = { } -def free_port(): - with socket.socket() as s: - s.bind(('127.0.0.1', 0)) - return s.getsockname()[1] - - def icon_png(): """A 64x64 RGBA PNG (server-icon.png).""" rows = b''.join(b'\0' + b''.join(bytes((x * 4, y * 4, (x ^ y) * 4, 255)) for x in range(64)) for y in range(64)) diff --git a/tools/test_dynamic_support_parity.py b/tools/test_dynamic_support_parity.py index ac876fa5a..76beb65c8 100644 --- a/tools/test_dynamic_support_parity.py +++ b/tools/test_dynamic_support_parity.py @@ -68,7 +68,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDynamicSupportOracle.java' helpers=[oracle.with_name(name+'.java') for name in ['VanillaFaceSupportOracle','VanillaBlockStateCodecOracle','VanillaCollisionOracle']] - sources=[oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/dynamic_support_fixture.rs'] + sources=[oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/dynamic_support_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -82,10 +82,10 @@ def main(): if len(states)!=199:raise ValueError('incomplete uncached support registry') fixtures=list(collision_corpus(facts,states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'facts.json',build/'uncached-states.json',build/'block-registry.nbt',build/'cached-collision.nbt'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','dynamic_support_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('dynamic_support_fixture.exe' if os.name=='nt' else 'dynamic_support_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'dynamic_support_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_edge_backoff_parity.py b/tools/test_edge_backoff_parity.py index 60dd0d66d..58d5ba8dd 100644 --- a/tools/test_edge_backoff_parity.py +++ b/tools/test_edge_backoff_parity.py @@ -45,7 +45,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEdgeBackoffOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/edge_backoff_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/edge_backoff_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -56,10 +56,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEdgeBackoffOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','edge_backoff_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('edge_backoff_fixture.exe' if os.name=='nt' else 'edge_backoff_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'edge_backoff_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_effect_attribute_modifiers_parity.py b/tools/test_effect_attribute_modifiers_parity.py index 0d6a45619..9fd9694aa 100644 --- a/tools/test_effect_attribute_modifiers_parity.py +++ b/tools/test_effect_attribute_modifiers_parity.py @@ -112,7 +112,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEffectAttributeModifiersOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/effect_attribute_modifiers_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/effect_attribute_modifiers_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -123,10 +123,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEffectAttributeModifiersOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','effect_attribute_modifiers_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('effect_attribute_modifiers_fixture.exe' if os.name=='nt' else 'effect_attribute_modifiers_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'effect_attribute_modifiers_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_effect_notifications_parity.py b/tools/test_effect_notifications_parity.py index 58f5b2ca6..e39258a8b 100644 --- a/tools/test_effect_notifications_parity.py +++ b/tools/test_effect_notifications_parity.py @@ -65,7 +65,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEffectNotificationsOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/effect_notifications_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/effect_notifications_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -76,14 +76,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEffectNotificationsOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','effect_notifications_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('effect_notifications_fixture.exe' if os.name=='nt' else 'effect_notifications_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';enriched_hash=base.source_hashes([enriched]) - run([binary,build,side],'rust-'+side) + run([binary,'effect_notifications_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';rust_output=build/f'rust-{side}.txt';matched=base.compare(reference,rust_output) base.ensure_sources_unchanged([enriched],enriched_hash) tested_fixtures.update(enriched_hash);fixture_paths.append(enriched) diff --git a/tools/test_effect_sync_parity.py b/tools/test_effect_sync_parity.py index ecfd8fe68..5aeeae09b 100644 --- a/tools/test_effect_sync_parity.py +++ b/tools/test_effect_sync_parity.py @@ -101,7 +101,7 @@ def main(): lab.ROOT / 'crates/horizon-core/Cargo.toml', lab.ROOT / 'crates/horizon-world/Cargo.toml', *sorted((lab.ROOT / 'crates/horizon-core/src').rglob('*.rs')), *sorted((lab.ROOT / 'crates/horizon-world/src').rglob('*.rs')), - lab.ROOT / 'crates/horizon-world/examples/effect_sync_fixture.rs'] + lab.ROOT / 'crates/horizon-world/examples/probe/effect_sync_fixture.rs'] tested_sources = base.source_hashes(sources) classes = build / 'classes' classes.mkdir(exist_ok=True) @@ -129,16 +129,16 @@ def main(): inputs.write_text(''.join(json.dumps(row, separators=(',', ':')) + '\n' for row in fixtures), encoding='utf-8') fixture_paths = [inputs, build / 'catalog.json', build / 'catalog-client.json', build / 'catalog-server.json'] tested_fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'effect_sync_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('effect_sync_fixture.exe' if os.name == 'nt' else 'effect_sync_fixture') + binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') references = [] for side, jar in jars.items(): java(side, side) enriched = build / f'inputs-{side}.txt' fixture_paths.append(enriched) tested_fixtures.update(base.source_hashes([enriched])) - run([binary, build, side], 'rust-' + side) + run([binary, 'effect_sync_fixture', build, side], 'rust-' + side) reference = build / f'{side}.txt' candidate = build / f'rust-{side}.txt' matched = base.compare(reference, candidate) diff --git a/tools/test_enchanting_parity.py b/tools/test_enchanting_parity.py index 4b5c975d0..9f5f5647f 100644 --- a/tools/test_enchanting_parity.py +++ b/tools/test_enchanting_parity.py @@ -42,7 +42,7 @@ def main(): catalog = json.loads((resources / 'items.json').read_text()) items = sorted(k for k, v in catalog.items() if 'minecraft:enchantable' in v) oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEnchantingOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/enchanting_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/enchanting_fixture.rs', *sorted((lab.ROOT / 'crates/horizon-client/src').glob('*.rs'))] tested = base.source_hashes(sources) inputs = build / 'inputs.txt' @@ -56,10 +56,10 @@ def main(): with (build / (name + '.log')).open('w', encoding='utf-8') as log: base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT) run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'), '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'enchanting_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('enchanting_fixture.exe' if os.name == 'nt' else 'enchanting_fixture') - run([binary, resources, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'enchanting_fixture',resources, inputs, build / 'rust.txt'], 'rust') references = [] for side in ['server']: run(['java', '-Xmx1G', '-cp', os.pathsep.join([str(classes), str(jars[side]), deps]), 'dev.horizonlab.parity.VanillaEnchantingOracle', inputs, build / f'{side}.txt'], side) diff --git a/tools/test_entity_attribute_parity.py b/tools/test_entity_attribute_parity.py index b117694d2..045488ee3 100644 --- a/tools/test_entity_attribute_parity.py +++ b/tools/test_entity_attribute_parity.py @@ -43,7 +43,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAttributeOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/entity_attribute_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/entity_attribute_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -54,10 +54,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEntityAttributeOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'catalog.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','entity_attribute_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('entity_attribute_fixture.exe' if os.name=='nt' else 'entity_attribute_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'entity_attribute_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_entity_collision_parity.py b/tools/test_entity_collision_parity.py index b57afa4b6..6fe12a7aa 100644 --- a/tools/test_entity_collision_parity.py +++ b/tools/test_entity_collision_parity.py @@ -54,7 +54,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityCollisionOracle.java' helper=oracle.with_name('VanillaFaceSupportOracle.java') - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/entity_collision_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/entity_collision_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -65,10 +65,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEntityCollisionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','entity_collision_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('entity_collision_fixture.exe' if os.name=='nt' else 'entity_collision_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'entity_collision_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_entity_death_loot_parity.py b/tools/test_entity_death_loot_parity.py index 000a2ea6f..b0f77cbfd 100644 --- a/tools/test_entity_death_loot_parity.py +++ b/tools/test_entity_death_loot_parity.py @@ -122,7 +122,7 @@ def main(): tables = resources / 'data/minecraft/loot_table/entities' types = sorted('minecraft:' + p.stem for p in tables.glob('*.json') if p.stem not in SKIPPED) oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityDeathLootOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/entity_death_loot_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/entity_death_loot_fixture.rs', lab.ROOT / 'crates/horizon-client/src/mobs/drops.rs', lab.ROOT / 'crates/horizon-world/src/loot.rs'] tested = base.source_hashes(sources) inputs = build / 'inputs.txt' @@ -139,10 +139,10 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx2G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaEntityDeathLootOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'entity_death_loot_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/entity_death_loot_fixture' - run([binary, resources, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples/probe' + run([binary, 'entity_death_loot_fixture', resources, inputs, build / 'rust.txt'], 'rust') errors = [l for l in (build / 'server.txt').read_text().splitlines() if l.startswith('error ')] if errors: raise SystemExit(f'oracle errors ({len(errors)}): {errors[:5]}') diff --git a/tools/test_entity_fluid_parity.py b/tools/test_entity_fluid_parity.py index 609a869de..712db03b5 100644 --- a/tools/test_entity_fluid_parity.py +++ b/tools/test_entity_fluid_parity.py @@ -68,7 +68,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityFluidOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/entity_fluid_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/entity_fluid_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -79,10 +79,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEntityFluidOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','entity_fluid_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('entity_fluid_fixture.exe' if os.name=='nt' else 'entity_fluid_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'entity_fluid_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_entity_fluid_tick_parity.py b/tools/test_entity_fluid_tick_parity.py index f9b4699ce..58380bd03 100644 --- a/tools/test_entity_fluid_tick_parity.py +++ b/tools/test_entity_fluid_tick_parity.py @@ -53,7 +53,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityFluidOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_entity_fluid_parity.py',lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/entity_fluid_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_entity_fluid_parity.py',lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/entity_fluid_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -64,10 +64,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEntityFluidOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','entity_fluid_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('entity_fluid_fixture.exe' if os.name=='nt' else 'entity_fluid_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'entity_fluid_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_entity_model_parity.py b/tools/test_entity_model_parity.py index 37c61b4ac..ba54797fa 100644 --- a/tools/test_entity_model_parity.py +++ b/tools/test_entity_model_parity.py @@ -4,7 +4,7 @@ The Java oracle bakes each vanilla model layer, builds the model's own render state class with the generated walk/age/head/attack inputs (plus per-species state fields), runs the real `setupAnim` and writes every part's pose. -`examples/entity_anim_fixture` replays the same inputs through Horizon's +`examples/probe/entity_anim_fixture` replays the same inputs through Horizon's `mobs::anim::setup` and the loaded model tree; the two must agree on every part pose and on the baked polygon count and vertex sums. @@ -364,8 +364,8 @@ def main(): run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', dependencies, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaEntityAnimOracle', inputs, build / 'vanilla.jsonl', jars['client']], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'entity_anim_fixture', '--', - resources, build / 'vanilla.jsonl', build / 'rust.jsonl'], 'rust') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'entity_anim_fixture', resources, build / 'vanilla.jsonl', build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] assert len(vanilla) == len(rust), (len(vanilla), len(rust)) diff --git a/tools/test_entity_move_parity.py b/tools/test_entity_move_parity.py index 2f5dc0da1..d17bb2444 100644 --- a/tools/test_entity_move_parity.py +++ b/tools/test_entity_move_parity.py @@ -45,7 +45,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityMoveOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/entity_move_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/entity_move_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -56,10 +56,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEntityMoveOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','entity_move_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('entity_move_fixture.exe' if os.name=='nt' else 'entity_move_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'entity_move_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_entity_obstruction_parity.py b/tools/test_entity_obstruction_parity.py index 8dc86453d..210c2080f 100644 --- a/tools/test_entity_obstruction_parity.py +++ b/tools/test_entity_obstruction_parity.py @@ -50,7 +50,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityObstructionOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/entity_obstruction_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/entity_obstruction_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -61,10 +61,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEntityObstructionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','entity_obstruction_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('entity_obstruction_fixture.exe' if os.name=='nt' else 'entity_obstruction_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'entity_obstruction_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_entity_particles_parity.py b/tools/test_entity_particles_parity.py index 2156f97ec..f34528b4c 100644 --- a/tools/test_entity_particles_parity.py +++ b/tools/test_entity_particles_parity.py @@ -74,13 +74,13 @@ def main(): 'tools/test_entity_particles_parity.py', 'tools/oracle_harness.py', 'tools/test_rust_parity.py', 'tools/lab.py', f'mods/horizon/src/test/java/dev/horizonlab/parity/{oracle}.java', 'Cargo.toml', 'Cargo.lock', 'crates/horizon-client/Cargo.toml', 'crates/horizon-client/src/particles.rs', - f'crates/horizon-client/examples/{probe}.rs', 'crates/horizon-core/src/random.rs']] + f'crates/horizon-client/examples/probe/{probe}.rs', 'crates/horizon-core/src/random.rs']] tested = base.source_hashes(sources) cases_path, units = make_cases(build) classes, dependencies, _ = harness.compile_oracle(build, oracle, jars, baking.client_libraries(), lock['minecraft']['java_major']) - binary = harness.build_probe(build, probe) - harness.run_logged([binary, cases_path, build / 'rust.txt'], build, 'rust') + command = harness.build_probe(build, probe) + harness.run_logged([*command, cases_path, build / 'rust.txt'], build, 'rust') harness.java_run(build, classes, dependencies, oracle, [cases_path, build / 'client.txt'], 'client') vanilla = (build / 'client.txt').read_text().splitlines() rust = (build / 'rust.txt').read_text().splitlines() diff --git a/tools/test_environment_render_parity.py b/tools/test_environment_render_parity.py index 2e14bb356..893a1c70d 100755 --- a/tools/test_environment_render_parity.py +++ b/tools/test_environment_render_parity.py @@ -5,7 +5,7 @@ The Java oracle builds vanilla's `EnvironmentAttributeSystem` from the data pack (dimension attributes, one biome's attributes, the dimension timelines and the weather layers) and prints every visual/gameplay attribute for a grid of dimensions, world times, rain/thunder levels and biomes. -`examples/environment_fixture` samples the same cases through Horizon's +`examples/probe/environment_fixture` samples the same cases through Horizon's `Environment::sample` + `apply_weather`; every attribute Horizon computes must agree with vanilla. @@ -66,8 +66,8 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx1G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaEnvironmentOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'environment_fixture', '--', - resources, inputs, build / 'rust.jsonl'], 'rust') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'environment_fixture', resources, inputs, build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] assert len(vanilla) == len(rust), (len(vanilla), len(rust)) diff --git a/tools/test_extra_items_parity.py b/tools/test_extra_items_parity.py index b9b060ee3..83752e515 100644 --- a/tools/test_extra_items_parity.py +++ b/tools/test_extra_items_parity.py @@ -56,7 +56,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaExtraItemsOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/extra_items_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/extra_items_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -67,10 +67,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaExtraItemsOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','extra_items_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('extra_items_fixture.exe' if os.name=='nt' else 'extra_items_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'extra_items_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_face_support_parity.py b/tools/test_face_support_parity.py index c82c23453..ad6db8922 100644 --- a/tools/test_face_support_parity.py +++ b/tools/test_face_support_parity.py @@ -50,7 +50,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFaceSupportOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/face_support_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/face_support_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -61,10 +61,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFaceSupportOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','face_support_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('face_support_fixture.exe' if os.name=='nt' else 'face_support_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'face_support_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_face_visibility_parity.py b/tools/test_face_visibility_parity.py index c505fd03f..fa8c6696a 100644 --- a/tools/test_face_visibility_parity.py +++ b/tools/test_face_visibility_parity.py @@ -49,7 +49,7 @@ def main(): oracle = lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFaceVisibilityOracle.java' helpers = [oracle.with_name(name) for name in ['VanillaCollisionOracle.java','VanillaHeightmapOracle.java']] sources = [oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py', - lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/face_visibility_fixture.rs'] + lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/probe/face_visibility_fixture.rs'] for crate in ['horizon-core','horizon-world']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] tested = base.source_hashes(sources) @@ -71,10 +71,10 @@ def main(): for a,b in pairs(definitions):output.write(f'{a} {b}\n');pair_count+=1 fixture_paths = [build/name for name in ['pairs.txt','block-registry.nbt','occlusion.nbt','definitions.json','tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','face_visibility_fixture'],'compile-rust') + run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata = json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('face_visibility_fixture.exe' if os.name=='nt' else 'face_visibility_fixture') - run([binary,build],'rust');references=[] + binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'face_visibility_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side) matched = base.compare(build/(side+'.txt'),build/'rust.txt') diff --git a/tools/test_fall_damage_parity.py b/tools/test_fall_damage_parity.py index 2f080215d..585084eb4 100644 --- a/tools/test_fall_damage_parity.py +++ b/tools/test_fall_damage_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFallDamageOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/fall_damage_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/fall_damage_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFallDamageOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','fall_damage_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('fall_damage_fixture.exe' if os.name=='nt' else 'fall_damage_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'fall_damage_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_feature_catalog_parity.py b/tools/test_feature_catalog_parity.py index 39a290ed3..52a19a652 100644 --- a/tools/test_feature_catalog_parity.py +++ b/tools/test_feature_catalog_parity.py @@ -85,7 +85,7 @@ def main(): helper=oracle.with_name("VanillaPlacementOracle.java") state_helper=oracle.with_name("VanillaBlockStateCodecOracle.java") sources=[oracle,helper,state_helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/feature_catalog_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/feature_catalog_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") resources=build/"catalog.json";resources.write_text(json.dumps(catalog(),separators=(",",":")),encoding="utf-8") @@ -100,10 +100,10 @@ def main(): fixture_paths.append(path) if json.loads((build/"facts-client.json").read_text())!=json.loads((build/"facts-server.json").read_text()):raise ValueError("reference feature block states differ") tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","feature_catalog_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("feature_catalog_fixture.exe" if os.name=="nt" else "feature_catalog_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"feature_catalog_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_feature_graph_parity.py b/tools/test_feature_graph_parity.py index 876b9bc3c..553baaf09 100644 --- a/tools/test_feature_graph_parity.py +++ b/tools/test_feature_graph_parity.py @@ -69,7 +69,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFeatureGraphOracle.java" helper=oracle.with_name("VanillaPlacementOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/feature_graph_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/feature_graph_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -83,10 +83,10 @@ def main(): fixture_paths.append(path) if json.loads((build/"facts-client.json").read_text())!=json.loads((build/"facts-server.json").read_text()):raise ValueError("reference feature block states differ") tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","feature_graph_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("feature_graph_fixture.exe" if os.name=="nt" else "feature_graph_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"feature_graph_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_feature_placement_parity.py b/tools/test_feature_placement_parity.py index 630b593bf..58dc3167a 100644 --- a/tools/test_feature_placement_parity.py +++ b/tools/test_feature_placement_parity.py @@ -79,7 +79,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFeaturePlacementOracle.java" helper=oracle.with_name("VanillaPlacementOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/feature_placement_fixture.rs",lab.ROOT/"crates/horizon-world/examples/support/placement_queries.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/feature_placement_fixture.rs",lab.ROOT/"crates/horizon-world/examples/probe/support/placement_queries.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -87,10 +87,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,helper],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","feature_placement_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("feature_placement_fixture.exe" if os.name=="nt" else "feature_placement_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"feature_placement_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_feature_region_parity.py b/tools/test_feature_region_parity.py index 901743e1c..2cc8d78a7 100644 --- a/tools/test_feature_region_parity.py +++ b/tools/test_feature_region_parity.py @@ -75,7 +75,7 @@ def main(): placement_helper=oracle.with_name("VanillaPlacementOracle.java") sources=[oracle,helper,placement_helper,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock", lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/feature_region_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/feature_region_fixture.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -107,10 +107,10 @@ def main(): height_inputs=build/'heights.json';height_inputs.write_text(json.dumps(heights,separators=(',',':'))) fixture_paths=[height_inputs,zone_inputs,inputs,build/"tags.json",build/"fluid-tags.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","feature_region_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("feature_region_fixture.exe" if os.name=="nt" else "feature_region_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"feature_region_fixture",build],"rust") references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_feature_sort_parity.py b/tools/test_feature_sort_parity.py index 9da7f17e4..6c0e4a44e 100644 --- a/tools/test_feature_sort_parity.py +++ b/tools/test_feature_sort_parity.py @@ -54,7 +54,7 @@ def main(): resources=biome_features(jars['server']) if len(resources)!=67 or resources!=biome_features(jars['client']):raise ValueError('pinned biome feature resources differ') oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFeatureSortOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/feature_sort_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/feature_sort_fixture.rs'] tested_sources=base.source_hashes(sources) fixtures=list(corpus(resources));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') resource_path=build/'biome-features.json';resource_path.write_text(json.dumps(resources,separators=(',',':')),encoding='utf-8') @@ -64,10 +64,10 @@ def main(): with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','feature_sort_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('feature_sort_fixture.exe' if os.name=='nt' else 'feature_sort_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'feature_sort_fixture',build],'rust');references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependency_path]),'dev.horizonlab.parity.VanillaFeatureSortOracle',side,build],side) reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_fill_layer_parity.py b/tools/test_fill_layer_parity.py index 0adf9f6c1..b23521d02 100644 --- a/tools/test_fill_layer_parity.py +++ b/tools/test_fill_layer_parity.py @@ -42,7 +42,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFillLayerOracle.java" helper=oracle.with_name("VanillaBlockStateCodecOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/fill_layer_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/fill_layer_fixture.rs"] tested_sources=base.source_hashes(sources) fixture_paths=[];classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -60,10 +60,10 @@ def main(): fixtures=list(corpus(facts));inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths.append(inputs) tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","fill_layer_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("fill_layer_fixture.exe" if os.name=="nt" else "fill_layer_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"fill_layer_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_finalize_spawn_parity.py b/tools/test_finalize_spawn_parity.py index 7c995fa83..c3130d380 100644 --- a/tools/test_finalize_spawn_parity.py +++ b/tools/test_finalize_spawn_parity.py @@ -118,7 +118,7 @@ def main(): lock, jars, libraries = base.verify_artifacts() resources = lab.RESOURCES oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFinalizeSpawnOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/finalize_spawn_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/finalize_spawn_fixture.rs', lab.ROOT / 'crates/horizon-client/src/mobs/finalize.rs'] tested = base.source_hashes([s for s in sources if s.exists()]) inputs = build / 'inputs.txt' @@ -148,10 +148,10 @@ def main(): print(f'{len(vanilla)} oracle lines') return halloween = vanilla[0].split()[1] - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'finalize_spawn_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/finalize_spawn_fixture' - run([binary, resources, inputs, build / 'rust.txt', halloween], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples/probe' + run([binary, 'finalize_spawn_fixture', resources, inputs, build / 'rust.txt', halloween], 'rust') rust = (build / 'rust.txt').read_text().splitlines() bad = [(a, b) for a, b in zip(vanilla, rust) if a != b] if bad or len(vanilla) != len(rust): diff --git a/tools/test_firework_tooltip_parity.py b/tools/test_firework_tooltip_parity.py index b3114c01a..14a4138b5 100644 --- a/tools/test_firework_tooltip_parity.py +++ b/tools/test_firework_tooltip_parity.py @@ -4,7 +4,7 @@ Random rockets (flight durations 0 to 3 and higher, up to six explosions, runs of equal ones) and stars, with dye and custom colours, fade colours, trails and twinkles, some without the component (a rocket's default) and some whose tooltip_display hides it. Vanilla prints what `Fireworks.addToTooltip` and `FireworkExplosion.addToTooltip` add -(VanillaFireworkTooltipOracle); Horizon what `item_tooltip::firework_lines` gives (examples/firework_tooltip_fixture). +(VanillaFireworkTooltipOracle); Horizon what `item_tooltip::firework_lines` gives (examples/probe/firework_tooltip_fixture). """ import random try: diff --git a/tools/test_first_person_parity.py b/tools/test_first_person_parity.py index 476d2cc52..fcb1206ec 100644 --- a/tools/test_first_person_parity.py +++ b/tools/test_first_person_parity.py @@ -18,14 +18,6 @@ except ImportError: import lab, oracle_harness as harness -def fbits(v): - return struct.pack('>f', v).hex() - - -def dbits(v): - return struct.pack('>d', v).hex() - - def f32(v): return struct.unpack('>f', struct.pack('>f', v))[0] @@ -52,15 +44,15 @@ def step(hit=('miss',), ac=0, uc=0, ad=False, ud=False, busy=False, using=False, """rot: the player's (xRot, yRot) from this step on (LocalPlayer.applyInput's hand sway).""" return dict(hit=list(hit), ac=ac, uc=uc, ad=ad, ud=ud, busy=busy, using=using, uses=uses or dict(entity='pass', block='pass', item='pass'), shrink=shrink, set=set, - rot=None if rot is None else [fbits(rot[0]), fbits(rot[1])]) + rot=None if rot is None else [lab.fbits(rot[0]), lab.fbits(rot[1])]) def case(steps, creative=False, main=None, off=None, blocks=None, haste=None, fatigue=None): return dict(creative=creative, main=main, off=off, haste=haste, fatigue=fatigue, blocks=[[*p, b] for p, b in (blocks or {}).items()], steps=steps, - rust=dict(blocks={k: [fbits(v[0]), v[1]] for k, v in BLOCKS.items()}, - tools={k: [fbits(v[0]), v[1]] for k, v in TOOLS.items()}, - attack_speed={k: dbits(v) for k, v in SPEEDS.items()})) + rust=dict(blocks={k: [lab.fbits(v[0]), v[1]] for k, v in BLOCKS.items()}, + tools={k: [lab.fbits(v[0]), v[1]] for k, v in TOOLS.items()}, + attack_speed={k: lab.dbits(v) for k, v in SPEEDS.items()})) def block_hit(pos, face=1): diff --git a/tools/test_fluid_box_parity.py b/tools/test_fluid_box_parity.py index 40056ed31..1b4e7743c 100644 --- a/tools/test_fluid_box_parity.py +++ b/tools/test_fluid_box_parity.py @@ -47,7 +47,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFluidBoxOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/fluid_box_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/fluid_box_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -58,10 +58,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFluidBoxOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','fluid_box_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('fluid_box_fixture.exe' if os.name=='nt' else 'fluid_box_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'fluid_box_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_fluid_flow_parity.py b/tools/test_fluid_flow_parity.py index b243fa34b..ef1606d91 100644 --- a/tools/test_fluid_flow_parity.py +++ b/tools/test_fluid_flow_parity.py @@ -56,7 +56,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFluidFlowOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/fluid_flow_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/fluid_flow_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -67,10 +67,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFluidFlowOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'fluid-states.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'fluid-states.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','fluid_flow_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('fluid_flow_fixture.exe' if os.name=='nt' else 'fluid_flow_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'fluid_flow_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_fluid_occupancy_parity.py b/tools/test_fluid_occupancy_parity.py index 50906f32e..90af340d3 100644 --- a/tools/test_fluid_occupancy_parity.py +++ b/tools/test_fluid_occupancy_parity.py @@ -44,7 +44,7 @@ def corpus(info): def main(): lock,jars,libraries=base.verify_artifacts();build=lab.LOCAL/'rust-fluid-occupancy-parity';build.mkdir(exist_ok=True);report_path=build/'report.json';report_path.unlink(missing_ok=True) root=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity';oracles=[root/(n+'.java') for n in ['VanillaFluidOccupancyOracle']] - sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/fluid_occupancy_fixture.rs'] + sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/probe/fluid_occupancy_fixture.rs'] for crate in ['horizon-core','horizon-world']:sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] tested=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True);dependencies=os.pathsep.join(map(str,libraries)) @@ -57,7 +57,7 @@ def main(): with (build/'inputs.txt').open('w') as output: for f in corpus(info):output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 fixture_paths=[build/n for n in ['inputs.txt','info.json','block-registry.nbt']];fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','fluid_occupancy_fixture'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('fluid_occupancy_fixture.exe' if os.name=='nt' else 'fluid_occupancy_fixture');run([binary,build],'rust');references=[] + run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'fluid_occupancy_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side);matched=base.compare(build/(side+'.txt'),build/'rust.txt');references.append(dict(side=side,jar_sha256=lab.digest(jar,'sha256'),output_sha256=lab.digest(build/(side+'.txt'),'sha256'),matched_output_lines=matched));print(f'{side}: {matched:,} fluid-occupancy output lines match Rust',flush=True) base.ensure_sources_unchanged(sources,tested);base.ensure_sources_unchanged(fixture_paths,fixtures) diff --git a/tools/test_fluid_parity.py b/tools/test_fluid_parity.py index f8fb98b4e..3acfc3702 100644 --- a/tools/test_fluid_parity.py +++ b/tools/test_fluid_parity.py @@ -46,7 +46,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFluidOracle.java' helper=oracle.with_name('VanillaBlockStateCodecOracle.java') - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/fluid_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/fluid_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -62,10 +62,10 @@ def main(): fixtures=list(corpus(facts));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') codec_inputs=build/'codec-inputs.txt';codec_fixtures=list(codec_corpus());codec_inputs.write_text(''.join(json.dumps(v,separators=(',',':'))+'\n' for v in codec_fixtures),encoding='utf-8') fixture_paths=[inputs,codec_inputs,build/'facts-client.json',build/'facts-server.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','fluid_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('fluid_fixture.exe' if os.name=='nt' else 'fluid_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'fluid_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_fluid_shape_parity.py b/tools/test_fluid_shape_parity.py index 55d395ffa..1378d33a5 100644 --- a/tools/test_fluid_shape_parity.py +++ b/tools/test_fluid_shape_parity.py @@ -37,7 +37,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFluidShapeOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/fluid_shape_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/fluid_shape_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -48,10 +48,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFluidShapeOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'fluid-states.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'fluid-states.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','fluid_shape_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('fluid_shape_fixture.exe' if os.name=='nt' else 'fluid_shape_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'fluid_shape_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_food_parity.py b/tools/test_food_parity.py index 519be39e6..c2e451fd0 100644 --- a/tools/test_food_parity.py +++ b/tools/test_food_parity.py @@ -57,7 +57,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFoodOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/food_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/food_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -68,10 +68,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFoodOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','food_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('food_fixture.exe' if os.name=='nt' else 'food_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'food_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_food_properties_parity.py b/tools/test_food_properties_parity.py index 195c554ab..950c19ee3 100644 --- a/tools/test_food_properties_parity.py +++ b/tools/test_food_properties_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFoodPropertiesOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/food_properties_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/food_properties_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFoodPropertiesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','food_properties_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('food_properties_fixture.exe' if os.name=='nt' else 'food_properties_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'food_properties_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_food_storage_parity.py b/tools/test_food_storage_parity.py index fc974185c..aeedde587 100644 --- a/tools/test_food_storage_parity.py +++ b/tools/test_food_storage_parity.py @@ -41,7 +41,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFoodStorageOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/food_storage_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/food_storage_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -52,10 +52,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFoodStorageOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','food_storage_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('food_storage_fixture.exe' if os.name=='nt' else 'food_storage_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'food_storage_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_free_space_parity.py b/tools/test_free_space_parity.py index 19e421265..a81fb0fe7 100644 --- a/tools/test_free_space_parity.py +++ b/tools/test_free_space_parity.py @@ -64,7 +64,7 @@ def main(): sources = [oracle, *helpers, Path(__file__), lab.ROOT/'tools/test_rust_parity.py', lab.ROOT/'tools/test_worldgen_parity.py', lab.ROOT/'tools/lab.py', lab.ROOT/'Cargo.toml', lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-world/examples/registry_collision_scan_fixture.rs'] + lab.ROOT/'crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs'] for crate in ['horizon-core', 'horizon-world']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml', *sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] @@ -94,10 +94,10 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'facts.json', 'definitions.json', 'block-registry.nbt', 'cached-collision.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'registry_collision_scan_fixture'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('registry_collision_scan_fixture.exe' if os.name=='nt' else 'registry_collision_scan_fixture') - run([binary, build], 'rust');references = [] + binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'registry_collision_scan_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) matched = base.compare(build/(side+'.txt'), build/'rust.txt') diff --git a/tools/test_friends.py b/tools/test_friends.py index 3daeb28e7..8fa1a4fee 100644 --- a/tools/test_friends.py +++ b/tools/test_friends.py @@ -72,12 +72,6 @@ def wait_for(endpoint, line, predicate, timeout=60, what=None): raise AssertionError(f'timed out waiting for {what or line}: {last}') -def free_port(): - with socket.socket() as s: - s.bind(('127.0.0.1', 0)) - return s.getsockname()[1] - - def health(relay_url): with urllib.request.urlopen(f'http://{relay_url}/health', timeout=5) as r: return json.loads(r.read()) @@ -204,7 +198,7 @@ def leave(host, guest, name): def start_relay(args, work): """A relay on a free local port, as anyone would run their own.""" - port = free_port() + port = lab.free_port() url = f'127.0.0.1:{port}' log = (work / 'relay.log').open('w+') process = subprocess.Popen([str(args.relay.resolve())], env=dict(os.environ, PORT=str(port)), diff --git a/tools/test_game_loop_parity.py b/tools/test_game_loop_parity.py index 101b3f238..f5f5e94a3 100644 --- a/tools/test_game_loop_parity.py +++ b/tools/test_game_loop_parity.py @@ -6,9 +6,7 @@ and absolute motion, sensitivity curve, cinematic smoothing, inversion, scroll accumulation and discrete scrolling), Entity.turn and ToggleKeyMapping, all driven with identical synthetic input and time sequences.""" import json -import math import random -import struct try: from . import lab, oracle_harness as harness @@ -16,14 +14,6 @@ except ImportError: import lab, oracle_harness as harness -def fbits(v): - return struct.pack('>f', v).hex() - - -def dbits(v): - return struct.pack('>d', v).hex() - - def timer_cases(rng): for n in range(700): tps = rng.choice([20.0, 20.0, 10.0, 60.0, 1.0, 144.0]) @@ -38,12 +28,12 @@ def timer_cases(rng): now -= rng.randrange(0, 30) if kind == 'adv': mspt = rng.choice([None, None, None, 50.0, 25.0, 100.0, 500.0, 1000.0, 0.5, 5.0, 0.1]) - ops.append(['adv', now, None if mspt is None else fbits(mspt)]) + ops.append(['adv', now, None if mspt is None else lab.fbits(mspt)]) elif kind == 'real': ops.append(['real', now]) else: ops.append([kind, rng.random() < 0.5]) - yield dict(t='timer', tps=fbits(tps), start=start, ops=ops) + yield dict(t='timer', tps=lab.fbits(tps), start=start, ops=ops) def rate_cases(rng): @@ -55,7 +45,7 @@ def rate_cases(rng): kind = rng.choice(['rate', 'freeze', 'step', 'stopstep', 'sprint', 'check', 'check', 'check', 'end', 'stopsprint', 'tick', 'tick', 'tick']) if kind == 'rate': - ops.append(['rate', fbits(rng.choice(rates))]) + ops.append(['rate', lab.fbits(rng.choice(rates))]) elif kind == 'freeze': ops.append(['freeze', rng.random() < 0.5]) elif kind == 'step': @@ -78,7 +68,7 @@ def scale_cases(rng): for uni in (False, True): sw, sh = rng.choice([(w, h), (max(w // 2, 1), max(h // 2, 1)), (w + 1, h + 3)]) yield dict(t='scale', w=w, h=h, max=maxs, uni=uni, sw=sw, sh=sh, - x=dbits(rng.uniform(0, w)), y=dbits(rng.uniform(0, h))) + x=lab.dbits(rng.uniform(0, w)), y=lab.dbits(rng.uniform(0, h))) def limit_cases(rng): @@ -103,13 +93,13 @@ def mouse_cases(rng): if kind == 'move': x, y = rng.uniform(0, 1920), rng.uniform(0, 1080) big = rng.choice([1, 1, 1, 50, 5000]) - ops.append(['move', dbits(x), dbits(y), dbits(rng.uniform(-30, 30) * big), dbits(rng.uniform(-30, 30) * big)]) + ops.append(['move', lab.dbits(x), lab.dbits(y), lab.dbits(rng.uniform(-30, 30) * big), lab.dbits(rng.uniform(-30, 30) * big)]) elif kind == 'frame': time += rng.choice([0.0, 0.001, 0.0069, 0.016, 0.0167, 0.05, 0.5, 2.0]) - ops.append(['frame', dbits(time)]) + ops.append(['frame', lab.dbits(time)]) else: ops.append(['ignore']) - yield dict(t='mouse', sens=dbits(sens), smooth=rng.random() < 0.4, scoping=rng.random() < 0.3, + yield dict(t='mouse', sens=lab.dbits(sens), smooth=rng.random() < 0.4, scoping=rng.random() < 0.3, ix=rng.random() < 0.3, iy=rng.random() < 0.3, grabbed=rng.random() < 0.85, active=rng.random() < 0.9, ops=ops) @@ -119,14 +109,14 @@ def scroll_cases(rng): for _ in range(rng.randrange(1, 40)): x = rng.choice([0.0, 0.0, 0.0, 1.0, -1.0, 0.25, -0.25, 0.4, 2.0, 5.5, -7.0, rng.uniform(-3, 3)]) y = rng.choice([0.0, 1.0, -1.0, 1.0, -1.0, 0.1, -0.3, 0.5, -0.5, 2.0, -3.0, 120.0, rng.uniform(-3, 3)]) - ops.append([dbits(x), dbits(y)]) - case = dict(t='scroll', discrete=rng.random() < 0.4, sens=dbits(rng.choice([1.0, 0.01, 10.0, 0.5, 2.0, 3.1622776601683795])), + ops.append([lab.dbits(x), lab.dbits(y)]) + case = dict(t='scroll', discrete=rng.random() < 0.4, sens=lab.dbits(rng.choice([1.0, 0.01, 10.0, 0.5, 2.0, 3.1622776601683795])), slot=rng.randrange(9), ops=ops) yield case yield dict(case, spectator=True) # Bounds, recovery from each bound, fractional accumulation, and horizontal-only input. - yield dict(t='scroll', discrete=False, sens=dbits(1.0), slot=4, spectator=True, - ops=[[dbits(x), dbits(y)] for x, y in + yield dict(t='scroll', discrete=False, sens=lab.dbits(1.0), slot=4, spectator=True, + ops=[[lab.dbits(x), lab.dbits(y)] for x, y in [(0, 100), (0, -1), (0, -100), (0, 1), (0, .4), (0, .7), (0, -.4), (0, -.7), (5, 0), (-5, 0)]]) diff --git a/tools/test_ghost_recipe_parity.py b/tools/test_ghost_recipe_parity.py index ad722109b..ac902a68c 100644 --- a/tools/test_ghost_recipe_parity.py +++ b/tools/test_ghost_recipe_parity.py @@ -10,7 +10,7 @@ against the real menu for every display of the recipe and prints the GhostSlots it fills: the menu slot, whether it is the result and the stacks the slot cycles through (PlaceRecipeHelper's centred placement of shaped recipes, the first slots for shapeless ones, every fuel for an empty fuel slot); -examples/ghost_recipe_fixture prints the same from +examples/probe/ghost_recipe_fixture prints the same from horizon_client::recipe_book::Book::ghost, which the game fills its ghost slots from. The lines must agree. """ diff --git a/tools/test_ground_support_parity.py b/tools/test_ground_support_parity.py index 931aaa372..4393daf21 100644 --- a/tools/test_ground_support_parity.py +++ b/tools/test_ground_support_parity.py @@ -65,7 +65,7 @@ def main(): sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_block_collision_scan_parity.py',lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock'] for crate in ['horizon-core','horizon-world']:sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] names=['block_collision_scan_fixture','ground_state_fixture'] - sources += [lab.ROOT/'crates/horizon-world/examples'/(name+'.rs') for name in names] + sources += [lab.ROOT/'crates/horizon-world/examples/probe'/(name+'.rs') for name in names] tested=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True);dependencies=os.pathsep.join(map(str,libraries)) def run(command,name): @@ -78,10 +78,10 @@ def main(): for f in corpus():output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 counts[name]=count;fixture_paths.append(path) fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example',names[0],'--example',names[1]],'compile-rust') + run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT)) for group,name in zip(['selection','state'],names): - binary=Path(metadata['target_directory'])/'release/examples'/(name+'.exe' if os.name=='nt' else name);run([binary,build/group],'rust-'+group) + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,name,build/group],'rust-'+group) references=[] for side,jar in jars.items(): results=[] diff --git a/tools/test_height_provider_parity.py b/tools/test_height_provider_parity.py index a14b7f8ca..4f63c80cd 100644 --- a/tools/test_height_provider_parity.py +++ b/tools/test_height_provider_parity.py @@ -65,7 +65,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightProviderOracle.java" helper=oracle.with_name("VanillaAnchorOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/height_provider_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/height_provider_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -73,10 +73,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,helper],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","height_provider_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("height_provider_fixture.exe" if os.name=="nt" else "height_provider_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"height_provider_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_heightmap_parity.py b/tools/test_heightmap_parity.py index 86368997c..502f165ab 100644 --- a/tools/test_heightmap_parity.py +++ b/tools/test_heightmap_parity.py @@ -82,7 +82,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightmapOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock", lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/heightmap_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/heightmap_fixture.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -100,10 +100,10 @@ def main(): (build/"tags.json").write_text(json.dumps(tags,separators=(",",":")),encoding="utf-8") fixture_paths=[inputs,build/"tags.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","heightmap_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("heightmap_fixture.exe" if os.name=="nt" else "heightmap_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"heightmap_fixture",build],"rust") references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_held_drop_parity.py b/tools/test_held_drop_parity.py index 842ad3d8a..d2f215050 100644 --- a/tools/test_held_drop_parity.py +++ b/tools/test_held_drop_parity.py @@ -35,7 +35,7 @@ def main(): 'dev.horizonlab.parity.VanillaHeldDropOracle', str(build / 'vanilla.txt')], check=True) with (build / 'rust.txt').open('w') as out: subprocess.run(['cargo', 'run', '--quiet', '-p', 'horizon-client', '--example', - 'held_drop_fixture'], cwd=lab.ROOT, stdout=out, check=True) + 'probe', '--', 'held_drop_fixture'], cwd=lab.ROOT, stdout=out, check=True) matched = base.compare(build / 'vanilla.txt', build / 'rust.txt') print(f'Held drop parity passed: {matched} inventory/drop/swing/packet snapshots match vanilla') diff --git a/tools/test_hotbar_parity.py b/tools/test_hotbar_parity.py index 336bda274..b8c83b87c 100644 --- a/tools/test_hotbar_parity.py +++ b/tools/test_hotbar_parity.py @@ -9,7 +9,7 @@ id), rows of the wrong size or type and garbage. The Java oracle (VanillaHotbarOracle) writes the file and loads it with the client's real HotbarManager and DataFixers (DataFixTypes.HOTBAR, so EmptyItemInHotbarFix and every item stack fixer), then Hotbar.load on each row; -examples/hotbar_fixture runs horizon_client::hotbar on the same tag. The nine +examples/probe/hotbar_fixture runs horizon_client::hotbar on the same tag. The nine rows' stacks are compared. """ import argparse diff --git a/tools/test_hud_parity.py b/tools/test_hud_parity.py index a0baa3214..4dcd19a7b 100644 --- a/tools/test_hud_parity.py +++ b/tools/test_hud_parity.py @@ -5,7 +5,7 @@ The Java oracle (VanillaHudOracle) runs vanilla's own code on a stand-in client whose player answers from the case, and records every GuiGraphicsExtractor blit (sprite, texture, position, size, region, colour, pose), fill, text call (string, style runs, position, colour, shadow, pose) -and hotbar item (slot, position, seed, pose). `examples/hud_fixture` lays +and hotbar item (slot, position, seed, pose). `examples/probe/hud_fixture` lays out the same state with `horizon_client::hud_layout`, `hud_overlays` and `chat`; the ordered call lists (and any state read back) must agree. @@ -114,8 +114,8 @@ def main(): *(PARITY / f'{n}.java' for n in ('ParityData', 'ParityFont', 'VanillaHudOracle'))], 'compile-java') run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaHudOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'hud_fixture', '--', - resources, inputs, build / 'rust.jsonl'], 'rust') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'hud_fixture', resources, inputs, build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] assert len(vanilla) == len(rust) diff --git a/tools/test_interaction_shape_parity.py b/tools/test_interaction_shape_parity.py index 6e372fcda..d40ca2c0b 100644 --- a/tools/test_interaction_shape_parity.py +++ b/tools/test_interaction_shape_parity.py @@ -36,7 +36,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaInteractionShapeOracle.java' helper=oracle.with_name('VanillaCollisionOracle.java') - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/interaction_shape_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/interaction_shape_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -47,10 +47,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaInteractionShapeOracle',mode,path],side+'-'+mode) java('server','export',build);info=json.loads((build/'info.json').read_text());fixtures=list(corpus(info));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'info.json',build/'block-registry.nbt',build/'interaction-shapes.nbt'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','interaction_shape_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('interaction_shape_fixture.exe' if os.name=='nt' else 'interaction_shape_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'interaction_shape_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_inventory_pickup_parity.py b/tools/test_inventory_pickup_parity.py index 073b56a50..a3172f472 100644 --- a/tools/test_inventory_pickup_parity.py +++ b/tools/test_inventory_pickup_parity.py @@ -61,7 +61,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaInventoryPickupOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/inventory_pickup_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/inventory_pickup_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -72,10 +72,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaInventoryPickupOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','inventory_pickup_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('inventory_pickup_fixture.exe' if os.name=='nt' else 'inventory_pickup_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'inventory_pickup_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_inventory_tick_parity.py b/tools/test_inventory_tick_parity.py index 02941c7b7..2dd34b76f 100644 --- a/tools/test_inventory_tick_parity.py +++ b/tools/test_inventory_tick_parity.py @@ -49,7 +49,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaInventoryTickOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/inventory_tick_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/inventory_tick_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -60,10 +60,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaInventoryTickOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','inventory_tick_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('inventory_tick_fixture.exe' if os.name=='nt' else 'inventory_tick_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'inventory_tick_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_inventory_use_parity.py b/tools/test_inventory_use_parity.py index f4ba01980..925567c3f 100644 --- a/tools/test_inventory_use_parity.py +++ b/tools/test_inventory_use_parity.py @@ -44,7 +44,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaInventoryUseOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/inventory_use_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/inventory_use_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -55,10 +55,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaInventoryUseOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','inventory_use_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('inventory_use_fixture.exe' if os.name=='nt' else 'inventory_use_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'inventory_use_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_inventory_use_start_parity.py b/tools/test_inventory_use_start_parity.py index 9de828505..67e282c06 100644 --- a/tools/test_inventory_use_start_parity.py +++ b/tools/test_inventory_use_start_parity.py @@ -44,7 +44,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaInventoryUseStartOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/inventory_use_start_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/inventory_use_start_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -55,10 +55,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaInventoryUseStartOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','inventory_use_start_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('inventory_use_start_fixture.exe' if os.name=='nt' else 'inventory_use_start_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'inventory_use_start_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_after_use_parity.py b/tools/test_item_after_use_parity.py index 9073cdee7..4aa5258f9 100644 --- a/tools/test_item_after_use_parity.py +++ b/tools/test_item_after_use_parity.py @@ -43,7 +43,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemAfterUseOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_after_use_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_after_use_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -54,10 +54,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemAfterUseOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_after_use_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_after_use_fixture.exe' if os.name=='nt' else 'item_after_use_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_after_use_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_blocking_parity.py b/tools/test_item_blocking_parity.py index f72fd6977..08d8dce24 100644 --- a/tools/test_item_blocking_parity.py +++ b/tools/test_item_blocking_parity.py @@ -47,7 +47,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemBlockingOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_blocking_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_blocking_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -58,10 +58,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemBlockingOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_blocking_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_blocking_fixture.exe' if os.name=='nt' else 'item_blocking_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_blocking_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_cooldowns_parity.py b/tools/test_item_cooldowns_parity.py index 003394f88..807c576dc 100644 --- a/tools/test_item_cooldowns_parity.py +++ b/tools/test_item_cooldowns_parity.py @@ -53,7 +53,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemCooldownsOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_cooldowns_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_cooldowns_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -64,10 +64,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemCooldownsOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_cooldowns_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_cooldowns_fixture.exe' if os.name=='nt' else 'item_cooldowns_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_cooldowns_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_durability_parity.py b/tools/test_item_durability_parity.py index 92b34c9e6..e3cdebb07 100644 --- a/tools/test_item_durability_parity.py +++ b/tools/test_item_durability_parity.py @@ -50,7 +50,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemDurabilityOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_durability_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_durability_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -61,10 +61,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemDurabilityOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_durability_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_durability_fixture.exe' if os.name=='nt' else 'item_durability_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_durability_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_particles_parity.py b/tools/test_item_particles_parity.py index eb11f85da..0e030a3b3 100644 --- a/tools/test_item_particles_parity.py +++ b/tools/test_item_particles_parity.py @@ -42,7 +42,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemParticlesOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_particles_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_particles_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -53,10 +53,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemParticlesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_particles_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_particles_fixture.exe' if os.name=='nt' else 'item_particles_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_particles_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_stack_storage_parity.py b/tools/test_item_stack_storage_parity.py index 5f41b968e..953dc8300 100644 --- a/tools/test_item_stack_storage_parity.py +++ b/tools/test_item_stack_storage_parity.py @@ -48,7 +48,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemStackStorageOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_stack_storage_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_stack_storage_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemStackStorageOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_stack_storage_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_stack_storage_fixture.exe' if os.name=='nt' else 'item_stack_storage_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_stack_storage_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_template_parity.py b/tools/test_item_template_parity.py index 1e01cef69..837465bb3 100644 --- a/tools/test_item_template_parity.py +++ b/tools/test_item_template_parity.py @@ -47,7 +47,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemTemplateOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_template_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_template_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -58,10 +58,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemTemplateOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_template_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_template_fixture.exe' if os.name=='nt' else 'item_template_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_template_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_use_catalog_parity.py b/tools/test_item_use_catalog_parity.py index ca83e3c26..38664bd03 100644 --- a/tools/test_item_use_catalog_parity.py +++ b/tools/test_item_use_catalog_parity.py @@ -48,7 +48,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemUseCatalogOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_use_catalog_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_use_catalog_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -63,10 +63,10 @@ def main(): if exports[0]!=exports[1]:raise RuntimeError('native item catalogs differ') catalog_path=build/'catalog.json';lab.write_json(catalog_path,exports[0]);fixtures=list(corpus(exports[0]));inputs=build/'inputs.txt' ;inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,catalog_path];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_use_catalog_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_use_catalog_fixture.exe' if os.name=='nt' else 'item_use_catalog_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_use_catalog_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_use_lifecycle_parity.py b/tools/test_item_use_lifecycle_parity.py index f0615c64c..0c3c4ee6e 100644 --- a/tools/test_item_use_lifecycle_parity.py +++ b/tools/test_item_use_lifecycle_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemUseLifecycleOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_use_lifecycle_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_use_lifecycle_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemUseLifecycleOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_use_lifecycle_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_use_lifecycle_fixture.exe' if os.name=='nt' else 'item_use_lifecycle_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_use_lifecycle_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_use_parity.py b/tools/test_item_use_parity.py index 9460ffb83..f69d49e35 100644 --- a/tools/test_item_use_parity.py +++ b/tools/test_item_use_parity.py @@ -55,7 +55,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemUseOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_use_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_use_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -66,10 +66,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemUseOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_use_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_use_fixture.exe' if os.name=='nt' else 'item_use_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_use_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_use_start_parity.py b/tools/test_item_use_start_parity.py index 6325fc5a6..e59945e82 100644 --- a/tools/test_item_use_start_parity.py +++ b/tools/test_item_use_start_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemUseStartOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_use_start_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_use_start_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemUseStartOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_use_start_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_use_start_fixture.exe' if os.name=='nt' else 'item_use_start_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_use_start_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_java_hash_map_parity.py b/tools/test_java_hash_map_parity.py index c51404aa8..5ae1cce41 100644 --- a/tools/test_java_hash_map_parity.py +++ b/tools/test_java_hash_map_parity.py @@ -62,7 +62,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaJavaHashMapOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/java_hash_map_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/java_hash_map_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -73,10 +73,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaJavaHashMapOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','java_hash_map_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('java_hash_map_fixture.exe' if os.name=='nt' else 'java_hash_map_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'java_hash_map_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_java_identity_map_parity.py b/tools/test_java_identity_map_parity.py index c104eafcc..9e9f04c1d 100644 --- a/tools/test_java_identity_map_parity.py +++ b/tools/test_java_identity_map_parity.py @@ -56,7 +56,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaJavaIdentityMapOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/java_identity_map_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/java_identity_map_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -67,14 +67,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaJavaIdentityMapOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','java_identity_map_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('java_identity_map_fixture.exe' if os.name=='nt' else 'java_identity_map_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';enriched_hash=base.source_hashes([enriched]) - run([binary,build,side],'rust-'+side) + run([binary,'java_identity_map_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';rust_output=build/f'rust-{side}.txt';matched=base.compare(reference,rust_output) base.ensure_sources_unchanged([enriched],enriched_hash) tested_fixtures.update(enriched_hash);fixture_paths.append(enriched) diff --git a/tools/test_level_place_parity.py b/tools/test_level_place_parity.py index 23a68800c..18e90e348 100644 --- a/tools/test_level_place_parity.py +++ b/tools/test_level_place_parity.py @@ -105,8 +105,8 @@ def main(): subprocess.run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaBlockPlacementOracle', str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')], check=True) - subprocess.run(['cargo', 'run', '-q', '-j2', '--release', '-p', 'horizon-world', '--example', 'level_place_fixture', '--', - str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], check=True, cwd=lab.ROOT) + subprocess.run(['cargo', 'run', '-q', '-j2', '--release', '-p', 'horizon-world', '--example', 'probe', '--', + 'level_place_fixture', str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], check=True, cwd=lab.ROOT) native = (work / 'native.txt').read_text().splitlines() rust = (work / 'rust.txt').read_text().splitlines() differences = {} diff --git a/tools/test_level_shape_parity.py b/tools/test_level_shape_parity.py index 212284656..c86f51fe6 100644 --- a/tools/test_level_shape_parity.py +++ b/tools/test_level_shape_parity.py @@ -80,8 +80,8 @@ def main(): subprocess.run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaLevelShapeOracle', str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')], check=True) - subprocess.run(['cargo', 'run', '-q', '-j2', '--release', '-p', 'horizon-world', '--example', 'level_shape_fixture', '--', - str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], check=True, cwd=lab.ROOT) + subprocess.run(['cargo', 'run', '-q', '-j2', '--release', '-p', 'horizon-world', '--example', 'probe', '--', + 'level_shape_fixture', str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], check=True, cwd=lab.ROOT) native = (work / 'native.txt').read_text().splitlines() rust = (work / 'rust.txt').read_text().splitlines() differences = {} diff --git a/tools/test_light_parity.py b/tools/test_light_parity.py index ad3945ba8..3ed2351fa 100755 --- a/tools/test_light_parity.py +++ b/tools/test_light_parity.py @@ -4,7 +4,7 @@ Builds a scene of slabs, stairs, snow layers, trapdoors, lanterns, glass, leaves, water and glowstone in a fresh vanilla world, lets the vanilla light engine settle, stops the server so the SkyLight/BlockLight arrays are saved, -then relights every saved chunk with `examples/light_parity` and requires every +then relights every saved chunk with `examples/probe/light_parity` and requires every value to agree. The example also replays block edits through the incremental `light::relight` and checks them against a full relight. @@ -92,7 +92,7 @@ def main(): dimension = run / 'world' for extra in (['--chunks', '0', '0', '2', '3'], ['--incremental', '100']): status = subprocess.run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', - '--example', 'light_parity', '--', str(RESOURCES), str(dimension), *extra], + '--example', 'probe', '--', 'light_parity', str(RESOURCES), str(dimension), *extra], cwd=ROOT).returncode if status: sys.exit('light mismatch against vanilla') diff --git a/tools/test_liquid_collision_parity.py b/tools/test_liquid_collision_parity.py index 9989da2e7..6a4ca638b 100644 --- a/tools/test_liquid_collision_parity.py +++ b/tools/test_liquid_collision_parity.py @@ -59,7 +59,7 @@ def main(): oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionContextOracle.java' helpers=[oracle.with_name('VanillaFaceSupportOracle.java')] runner=lab.ROOT/'tools/test_collision_context_parity.py' - sources=[oracle,*helpers,runner,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/collision_context_fixture.rs'] + sources=[oracle,*helpers,runner,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/collision_context_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -70,10 +70,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaCollisionContextOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','collision_context_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('collision_context_fixture.exe' if os.name=='nt' else 'collision_context_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'collision_context_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_live_attribute_updates_parity.py b/tools/test_live_attribute_updates_parity.py index cd619de72..1e05f4bae 100644 --- a/tools/test_live_attribute_updates_parity.py +++ b/tools/test_live_attribute_updates_parity.py @@ -131,8 +131,8 @@ def main(): lab.ROOT / 'crates/horizon-core/Cargo.toml', lab.ROOT / 'crates/horizon-world/Cargo.toml', *sorted((lab.ROOT / 'crates/horizon-core/src').rglob('*.rs')), *sorted((lab.ROOT / 'crates/horizon-world/src').rglob('*.rs')), - lab.ROOT / 'crates/horizon-world/examples/live_attribute_updates_fixture.rs', - lab.ROOT / 'crates/horizon-world/examples/live_attributes_fixture.rs'] + lab.ROOT / 'crates/horizon-world/examples/probe/live_attribute_updates_fixture.rs', + lab.ROOT / 'crates/horizon-world/examples/probe/live_attributes_fixture.rs'] tested_sources = base.source_hashes(sources) classes = build / 'classes' classes.mkdir(exist_ok=True) @@ -160,16 +160,16 @@ def main(): inputs.write_text(''.join(json.dumps(row, separators=(',', ':')) + '\n' for row in fixtures), encoding='utf-8') fixture_paths = [inputs, build / 'catalog.json', build / 'catalog-client.json', build / 'catalog-server.json'] tested_fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'live_attribute_updates_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('live_attribute_updates_fixture.exe' if os.name == 'nt' else 'live_attribute_updates_fixture') + binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') references = [] for side, jar in jars.items(): java(side, side) enriched = build / f'inputs-{side}.txt' fixture_paths.append(enriched) tested_fixtures.update(base.source_hashes([enriched])) - run([binary, build, side], 'rust-' + side) + run([binary, 'live_attribute_updates_fixture', build, side], 'rust-' + side) reference = build / f'{side}.txt' candidate = build / f'rust-{side}.txt' matched = base.compare(reference, candidate) diff --git a/tools/test_live_attributes_parity.py b/tools/test_live_attributes_parity.py index 74bd083f2..f221fa27e 100644 --- a/tools/test_live_attributes_parity.py +++ b/tools/test_live_attributes_parity.py @@ -104,7 +104,7 @@ def main(): lab.ROOT / 'crates/horizon-core/Cargo.toml', lab.ROOT / 'crates/horizon-world/Cargo.toml', *sorted((lab.ROOT / 'crates/horizon-core/src').rglob('*.rs')), *sorted((lab.ROOT / 'crates/horizon-world/src').rglob('*.rs')), - lab.ROOT / 'crates/horizon-world/examples/live_attributes_fixture.rs'] + lab.ROOT / 'crates/horizon-world/examples/probe/live_attributes_fixture.rs'] tested_sources = base.source_hashes(sources) classes = build / 'classes' classes.mkdir(exist_ok=True) @@ -132,16 +132,16 @@ def main(): inputs.write_text(''.join(json.dumps(row, separators=(',', ':')) + '\n' for row in fixtures), encoding='utf-8') fixture_paths = [inputs, build / 'catalog.json', build / 'catalog-client.json', build / 'catalog-server.json'] tested_fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'live_attributes_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('live_attributes_fixture.exe' if os.name == 'nt' else 'live_attributes_fixture') + binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') references = [] for side, jar in jars.items(): java(side, side) enriched = build / f'inputs-{side}.txt' fixture_paths.append(enriched) tested_fixtures.update(base.source_hashes([enriched])) - run([binary, build, side], 'rust-' + side) + run([binary, 'live_attributes_fixture', build, side], 'rust-' + side) reference = build / f'{side}.txt' candidate = build / f'rust-{side}.txt' matched = base.compare(reference, candidate) diff --git a/tools/test_living_air_parity.py b/tools/test_living_air_parity.py index 85da124e3..4d837f02a 100644 --- a/tools/test_living_air_parity.py +++ b/tools/test_living_air_parity.py @@ -70,7 +70,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLivingAirOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/living_air_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/living_air_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -81,10 +81,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingAirOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','living_air_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('living_air_fixture.exe' if os.name=='nt' else 'living_air_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'living_air_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_living_damage_parity.py b/tools/test_living_damage_parity.py index 43c45c926..ae97c4686 100644 --- a/tools/test_living_damage_parity.py +++ b/tools/test_living_damage_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLivingDamageOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/living_damage_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/living_damage_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingDamageOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','living_damage_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('living_damage_fixture.exe' if os.name=='nt' else 'living_damage_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'living_damage_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_living_fall_parity.py b/tools/test_living_fall_parity.py index db79c440f..db55b5728 100644 --- a/tools/test_living_fall_parity.py +++ b/tools/test_living_fall_parity.py @@ -48,7 +48,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLivingFallOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/living_fall_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/living_fall_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingFallOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','living_fall_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('living_fall_fixture.exe' if os.name=='nt' else 'living_fall_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'living_fall_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_living_fluid_parity.py b/tools/test_living_fluid_parity.py index f50289e04..19748fef2 100644 --- a/tools/test_living_fluid_parity.py +++ b/tools/test_living_fluid_parity.py @@ -66,7 +66,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLivingFluidOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/living_fluid_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/living_fluid_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -77,10 +77,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingFluidOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','living_fluid_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('living_fluid_fixture.exe' if os.name=='nt' else 'living_fluid_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'living_fluid_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_living_health_parity.py b/tools/test_living_health_parity.py index b58f3e357..ab97d0061 100644 --- a/tools/test_living_health_parity.py +++ b/tools/test_living_health_parity.py @@ -48,7 +48,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLivingHealthOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/living_health_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/living_health_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingHealthOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','living_health_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('living_health_fixture.exe' if os.name=='nt' else 'living_health_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'living_health_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_living_hurt_parity.py b/tools/test_living_hurt_parity.py index 4e7d951b8..38ade5720 100644 --- a/tools/test_living_hurt_parity.py +++ b/tools/test_living_hurt_parity.py @@ -50,7 +50,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLivingHurtOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/living_hurt_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/living_hurt_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -61,10 +61,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingHurtOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','living_hurt_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('living_hurt_fixture.exe' if os.name=='nt' else 'living_hurt_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'living_hurt_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_living_landing_parity.py b/tools/test_living_landing_parity.py index 84e6c705d..eb65800da 100644 --- a/tools/test_living_landing_parity.py +++ b/tools/test_living_landing_parity.py @@ -55,7 +55,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLivingLandingOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/living_landing_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/living_landing_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -66,10 +66,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingLandingOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','living_landing_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('living_landing_fixture.exe' if os.name=='nt' else 'living_landing_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'living_landing_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_living_motion_parity.py b/tools/test_living_motion_parity.py index 66190f812..39935303c 100644 --- a/tools/test_living_motion_parity.py +++ b/tools/test_living_motion_parity.py @@ -69,7 +69,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLivingMotionOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/living_motion_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/living_motion_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -80,10 +80,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingMotionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','living_motion_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('living_motion_fixture.exe' if os.name=='nt' else 'living_motion_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'living_motion_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_local_input_parity.py b/tools/test_local_input_parity.py index 2873f11a7..adfea1a4b 100644 --- a/tools/test_local_input_parity.py +++ b/tools/test_local_input_parity.py @@ -35,7 +35,7 @@ def main(): build=lab.LOCAL/'rust-local-input';build.mkdir(exist_ok=True) report=build/'report.json';report.unlink(missing_ok=True) oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLocalInputOracle.java' - sources=[Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_model_baking_parity.py',lab.ROOT/'tools/lab.py',oracle,lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-client/Cargo.toml',lab.ROOT/'crates/horizon-client/src/input.rs',lab.ROOT/'crates/horizon-client/src/lib.rs',lab.ROOT/'crates/horizon-client/examples/input_probe.rs'] + sources=[Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_model_baking_parity.py',lab.ROOT/'tools/lab.py',oracle,lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-client/Cargo.toml',lab.ROOT/'crates/horizon-client/src/input.rs',lab.ROOT/'crates/horizon-client/src/lib.rs',lab.ROOT/'crates/horizon-client/examples/probe/input_probe.rs'] tested=base.source_hashes(sources) def run(command,name): with (build/(name+'.log')).open('w') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=600,stdout=log,stderr=subprocess.STDOUT) @@ -44,10 +44,10 @@ def main(): classes=build/'classes';classes.mkdir(exist_ok=True) dependencies=os.pathsep.join(map(str,[jars['client'],*libraries])) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',dependencies,'-d',classes,oracle],'compile-java') - run(['cargo','build','--locked','-p','horizon-client','--example','input_probe'],'compile-rust') + run(['cargo','build','--locked','-p','horizon-client','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT)) - binary=Path(metadata['target_directory'])/'debug/examples'/('input_probe.exe' if os.name=='nt' else 'input_probe') - run([binary,inputs,build/'rust.txt'],'rust') + binary=Path(metadata['target_directory'])/'debug/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'input_probe',inputs,build/'rust.txt'],'rust') run(['java','-Xmx768M','-cp',str(classes)+os.pathsep+dependencies,'dev.horizonlab.parity.VanillaLocalInputOracle',inputs,build/'client.txt'],'client') matched=base.compare(build/'client.txt',build/'rust.txt') if matched!=len(fixtures):raise AssertionError('Incomplete input output') diff --git a/tools/test_material_condition_parity.py b/tools/test_material_condition_parity.py index 43e0fa48b..adddd336b 100644 --- a/tools/test_material_condition_parity.py +++ b/tools/test_material_condition_parity.py @@ -285,7 +285,7 @@ def main(): anchor_oracle=oracle.with_name("VanillaAnchorOracle.java") biome_oracle=oracle.with_name("VanillaBiomeTemperatureOracle.java") sources=[oracle,anchor_oracle,biome_oracle,lab.ROOT/"tools/test_biome_temperature_parity.py",Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/material_condition_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/material_condition_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=[*corpus(),*codec_corpus(conditions),*rule_corpus(conditions),*noise_corpus(noises),*biome_corpus(biomes),*biome_tag_corpus(biomes,biome_tags),*preliminary_corpus(),*ore_corpus()];inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs,build/"noises.json",build/"conditions.json",build/"biomes.json",build/"biome_tags.json"];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -293,10 +293,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,anchor_oracle,biome_oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","material_condition_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("material_condition_fixture.exe" if os.name=="nt" else "material_condition_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"material_condition_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_material_extension_parity.py b/tools/test_material_extension_parity.py index 7ce03502c..4036ecc37 100644 --- a/tools/test_material_extension_parity.py +++ b/tools/test_material_extension_parity.py @@ -60,15 +60,15 @@ def main(): if not biomes or biomes!=biome.biome_resources(jars['client']):raise ValueError('reference biome resources differ') for name,data in [('noises',noises),('biomes',biomes)]:(build/(name+'.json')).write_text(json.dumps(data,separators=(',',':')),encoding='utf-8') folder=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity';oracles=[folder/(name+'.java') for name in ['VanillaMaterialExtensionOracle','VanillaBiomeTemperatureOracle']] - sources=[*oracles,Path(__file__),*[lab.ROOT/'tools'/name for name in ['test_biome_temperature_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/material_extension_fixture.rs'] + sources=[*oracles,Path(__file__),*[lab.ROOT/'tools'/name for name in ['test_biome_temperature_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/material_extension_fixture.rs'] tested_sources=base.source_hashes(sources);fixtures=list(corpus(biomes));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'noises.json',build/'biomes.json'];tested_fixtures=base.source_hashes(fixture_paths);classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependencies=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependencies,'-d',classes,*oracles],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','material_extension_fixture'],'compile-rust') - metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('material_extension_fixture.exe' if os.name=='nt' else 'material_extension_fixture');run([binary,build],'rust');references=[] + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'material_extension_fixture',build],'rust');references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependencies]),'dev.horizonlab.parity.VanillaMaterialExtensionOracle',side,build],side) reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt');references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched});print(f'{side}: {matched:,} material-extension output lines match Rust',flush=True) diff --git a/tools/test_material_rule_library_parity.py b/tools/test_material_rule_library_parity.py index d2e7023ae..1e9b82357 100644 --- a/tools/test_material_rule_library_parity.py +++ b/tools/test_material_rule_library_parity.py @@ -67,7 +67,7 @@ def main(): for field,value in bundle.items():(build/(field+'.json')).write_text(json.dumps(value,separators=(',',':')),encoding='utf-8') folder=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity' oracles=[folder/(name+'.java') for name in ['VanillaMaterialConditionOracle','VanillaAnchorOracle','VanillaBiomeTemperatureOracle','VanillaBlockStateCodecOracle']] - sources=[*oracles,Path(__file__),*[lab.ROOT/'tools'/name for name in ['test_material_condition_parity.py','test_biome_temperature_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/material_condition_fixture.rs'] + sources=[*oracles,Path(__file__),*[lab.ROOT/'tools'/name for name in ['test_material_condition_parity.py','test_biome_temperature_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/material_condition_fixture.rs'] tested_sources=base.source_hashes(sources);classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) @@ -79,9 +79,9 @@ def main(): if facts!=json.loads((build/'facts-client.json').read_text()):raise ValueError('reference block metadata differs') fixtures=list(corpus(bundle['rules'],bundle['biomes']));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'facts-client.json',build/'facts-server.json',*[build/(field+'.json') for field in bundle]];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','material_condition_fixture'],'compile-rust') - metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('material_condition_fixture.exe' if os.name=='nt' else 'material_condition_fixture') - run([binary,build],'rust');references=[] + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'material_condition_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,'VanillaMaterialConditionOracle',side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched});print(f'{side}: {matched:,} material-rule library output lines match Rust',flush=True) diff --git a/tools/test_material_stage_parity.py b/tools/test_material_stage_parity.py index 29de0d9e0..46bb4649b 100644 --- a/tools/test_material_stage_parity.py +++ b/tools/test_material_stage_parity.py @@ -110,7 +110,7 @@ def main(): counts={key:len(value) for key,value in bundle.items()};bundle['rules'].update(synthetic_rules()) for name,value in bundle.items():(build/(name+'.json')).write_text(json.dumps(value,separators=(',',':')),encoding='utf-8') folder=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity';oracles=[folder/(name+'.java') for name in ['VanillaMaterialStageOracle','VanillaMaterialConditionOracle','VanillaAnchorOracle','VanillaBiomeTemperatureOracle','VanillaHeightmapOracle','VanillaBiomeExport']] - sources=[*oracles,Path(__file__),*[lab.ROOT/'tools'/name for name in ['test_material_condition_parity.py','test_biome_temperature_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/material_stage_fixture.rs'] + sources=[*oracles,Path(__file__),*[lab.ROOT/'tools'/name for name in ['test_material_condition_parity.py','test_biome_temperature_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/material_stage_fixture.rs'] tested_sources=base.source_hashes(sources);classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) @@ -132,7 +132,7 @@ def main(): f['top_queries']=top_queries(f);f['carving']=carving_fixture(f,facts) inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') fixture_paths=[inputs,*preset_exports,build/'facts-client.json',build/'facts-server.json',*[build/(name+'.json') for name in bundle]];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','material_stage_fixture'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('material_stage_fixture.exe' if os.name=='nt' else 'material_stage_fixture');run([binary,build],'rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'material_stage_fixture',build],'rust') with (build/'rust.txt').open() as stream: if any((line.startswith('surface ') or line.startswith('top ') or line.startswith('carving ') or line.startswith('generatedcarving ')) and line.endswith(' error\n') for line in stream):raise AssertionError('valid surface fixture failed; inspect private Rust log') references=[] diff --git a/tools/test_material_surface_parity.py b/tools/test_material_surface_parity.py index 30df0f4da..120decbe7 100644 --- a/tools/test_material_surface_parity.py +++ b/tools/test_material_surface_parity.py @@ -44,7 +44,7 @@ def main(): (build/"noises.json").write_text(json.dumps(noises,separators=(",",":")),encoding="utf-8") oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMaterialSurfaceOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/material_surface_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/material_surface_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs,build/"noises.json"];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -52,10 +52,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","material_surface_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("material_surface_fixture.exe" if os.name=="nt" else "material_surface_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"material_surface_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index 01ed4680f..07f41b2af 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -467,7 +467,7 @@ def main(): 'dev.horizonlab.parity.VanillaMobAiOracle', inputs, build / 'vanilla.txt', world], build, 'vanilla', timeout=3600) if not args.java_only: - command = ['cargo', 'build', '--locked', '--release', '-p', 'horizon-client', '--example', 'mob_ai_probe'] + command = ['cargo', 'build', '--locked', '--release', '-p', 'horizon-client', '--example', 'probe'] target, env = lab.cargo_target(), None if args.trace: target = lab.LOCAL / 'mob-ai-trace-target' @@ -475,8 +475,8 @@ def main(): env = dict(os.environ, CARGO_TARGET_DIR=str(target), CARGO_PROFILE_RELEASE_DEBUG='line-tables-only', CARGO_PROFILE_RELEASE_LTO='false', CARGO_PROFILE_RELEASE_CODEGEN_UNITS='16') oracle_harness.run_logged(command, build, 'compile-rust', env=env) - binary = target / 'release/examples/mob_ai_probe' - oracle_harness.run_logged([binary, lab.RESOURCES, inputs, build / 'horizon.txt'], build, 'horizon') + binary = target / 'release/examples/probe' + oracle_harness.run_logged([binary, 'mob_ai_probe', lab.RESOURCES, inputs, build / 'horizon.txt'], build, 'horizon') if args.java_only: return names = {s[0] for _, s in chosen} diff --git a/tools/test_mob_attributes_parity.py b/tools/test_mob_attributes_parity.py index 1e4057eb7..6cefdc4b8 100755 --- a/tools/test_mob_attributes_parity.py +++ b/tools/test_mob_attributes_parity.py @@ -62,10 +62,10 @@ def main(): subprocess.run(list(map(str, cmd)), cwd=lab.ROOT, check=True, timeout=3600, stdout=log, stderr=subprocess.STDOUT) run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx1G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaMobAttributesOracle', build / 'vanilla.txt'], 'java') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'mob_attributes_fixture'], 'compile-rust') - binary = lab.cargo_target() / 'release/examples/mob_attributes_fixture' + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') + binary = lab.cargo_target() / 'release/examples/probe' resources = lab.RESOURCES - run([binary, resources, build / 'rust.txt'], 'rust') + run([binary, 'mob_attributes_fixture', resources, build / 'rust.txt'], 'rust') vanilla, rust = parse(build / 'vanilla.txt'), parse(build / 'rust.txt') problems = [] living = [i for i, r in vanilla.items() if 'attrs' in r] diff --git a/tools/test_movement_emission_parity.py b/tools/test_movement_emission_parity.py index 14977b45b..7db2c16d0 100644 --- a/tools/test_movement_emission_parity.py +++ b/tools/test_movement_emission_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMovementEmissionOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/movement_emission_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/movement_emission_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaMovementEmissionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','movement_emission_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('movement_emission_fixture.exe' if os.name=='nt' else 'movement_emission_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'movement_emission_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_movement_registry_parity.py b/tools/test_movement_registry_parity.py index ef1542415..190c34d37 100644 --- a/tools/test_movement_registry_parity.py +++ b/tools/test_movement_registry_parity.py @@ -40,7 +40,7 @@ def main(): sources = [oracle, *helpers, Path(__file__), lab.ROOT/'tools/test_rust_parity.py', lab.ROOT/'tools/test_worldgen_parity.py', lab.ROOT/'tools/lab.py', lab.ROOT/'Cargo.toml', lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-world/examples/movement_registry_fixture.rs'] + lab.ROOT/'crates/horizon-world/examples/probe/movement_registry_fixture.rs'] for crate in ['horizon-core', 'horizon-world']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml', *sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] @@ -69,10 +69,10 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'registry-info.json', 'movement-properties.nbt', 'block-registry.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'movement_registry_fixture'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('movement_registry_fixture.exe' if os.name=='nt' else 'movement_registry_fixture') - run([binary, build], 'rust');references = [] + binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'movement_registry_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) matched = base.compare(build/(side+'.txt'), build/'rust.txt') diff --git a/tools/test_movement_support_parity.py b/tools/test_movement_support_parity.py index dbc727c76..793804a9e 100644 --- a/tools/test_movement_support_parity.py +++ b/tools/test_movement_support_parity.py @@ -48,7 +48,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMovementSupportOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/movement_support_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/movement_support_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaMovementSupportOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','movement_support_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('movement_support_fixture.exe' if os.name=='nt' else 'movement_support_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'movement_support_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_music_parity.py b/tools/test_music_parity.py index 7d41be5f1..b56c9ab25 100644 --- a/tools/test_music_parity.py +++ b/tools/test_music_parity.py @@ -154,7 +154,7 @@ def main(): 'music', 'VanillaMusicOracle', 'music_fixture', ''.join(l + '\n' for l in lines), extra_sources=[h.lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundRig.java', h.lab.ROOT / 'crates/horizon-client/src/music.rs', - h.lab.ROOT / 'crates/horizon-client/examples/audio_common/mod.rs'], + h.lab.ROOT / 'crates/horizon-client/examples/probe/audio_common/mod.rs'], java_args=[h.RESOURCES], rust_args=[h.RESOURCES], scope='Real MusicManager.tick/startPlaying/stopPlaying/fadePlaying/setMinutesBetweenSongs/showNowPlayingToastIfNeeded with a seeded ' 'random over the real SoundEngine: track starts and replacements, nextSongDelay draws, the three music frequencies, the loading ' diff --git a/tools/test_native_scene_collision.py b/tools/test_native_scene_collision.py index a70cf48fb..8efc6946b 100644 --- a/tools/test_native_scene_collision.py +++ b/tools/test_native_scene_collision.py @@ -70,7 +70,7 @@ def main(): sources = [Path(__file__), lab.ROOT/'tools/test_native_client.py', lab.ROOT/'tools/test_rust_parity.py', lab.ROOT/'tools/lab.py', lab.ROOT/'tools/prepare_native_client.py', oracle, *helpers, lab.ROOT/'Cargo.toml', lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-client/examples/scene_collision_probe.rs'] + lab.ROOT/'crates/horizon-client/examples/probe/scene_collision_probe.rs'] for crate in ['horizon-core', 'horizon-world', 'horizon-assets', 'horizon-client']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml', *sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] tested = base.source_hashes(sources) @@ -82,16 +82,16 @@ def main(): dependencies = os.pathsep.join(map(str, libraries)) run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', str(jars['server'])+os.pathsep+dependencies, '-d', classes, oracle, *helpers], 'compile-java') - run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'scene_collision_probe'], 'compile-rust') + run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - executable = Path(metadata['target_directory'])/'debug/examples'/('scene_collision_probe.exe' if os.name == 'nt' else 'scene_collision_probe') + executable = Path(metadata['target_directory'])/'debug/examples'/('probe.exe' if os.name=='nt' else 'probe') cases = [] for radius in [1, 2]: build = root/str(radius); build.mkdir(exist_ok=True) fixtures = list(corpus(radius)) (build/'inputs.txt').write_text(''.join(json.dumps(f, separators=(',', ':'))+'\n' for f in fixtures)) input_hash = lab.digest(build/'inputs.txt', 'sha256') - run([executable, resources, build, radius], f'rust-{radius}') + run([executable, 'scene_collision_probe',resources, build, radius], f'rust-{radius}') scene_hash = lab.digest(build/'scene.json', 'sha256') references = [] for side, jar in jars.items(): diff --git a/tools/test_native_scene_motion.py b/tools/test_native_scene_motion.py index 4b8089795..a917d7337 100644 --- a/tools/test_native_scene_motion.py +++ b/tools/test_native_scene_motion.py @@ -789,7 +789,7 @@ def main(): if args.sprint_input:helpers.append(oracle.with_name('VanillaSprintInputOracle.java')) sources=[Path(__file__),lab.ROOT/'tools/test_native_client.py',lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py', lab.ROOT/'tools/prepare_native_client.py',oracle,*helpers,lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-client/examples/scene_motion_probe.rs'] + lab.ROOT/'crates/horizon-client/examples/probe/scene_motion_probe.rs'] for crate in ['horizon-core','horizon-world','horizon-assets','horizon-client']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] if args.sprint_input:sources.append(lab.ROOT/'tools/test_model_baking_parity.py') @@ -807,16 +807,16 @@ def main(): damage_dir=build/'damage';damage_dir.mkdir(exist_ok=True) for target, source in [('types.json','damage-types.json'),('tags.json','damage-tags.json')]: (damage_dir/target).write_bytes((resources/source).read_bytes()) - run(['cargo','build','--locked','-p','horizon-client','--example','scene_motion_probe'],'compile-rust') + run(['cargo','build','--locked','-p','horizon-client','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT)) - binary=Path(metadata['target_directory'])/'debug/examples'/('scene_motion_probe.exe' if os.name=='nt' else 'scene_motion_probe') - run([binary,resources,build,'--describe'],'describe') + binary=Path(metadata['target_directory'])/'debug/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'scene_motion_probe',resources,build,'--describe'],'describe') references=[] for side,jar in jars.items(): run(['java','-Xmx768M','-cp',os.pathsep.join([str(classes),str(jar),dependencies]), 'dev.horizonlab.parity.VanillaSceneMotionOracle',side,build,resources],side) replay_hash=lab.digest(build/('inputs-'+side+'.txt'),'sha256') - run([binary,resources,build,side],'rust-'+side) + run([binary,'scene_motion_probe',resources,build,side],'rust-'+side) if replay_hash!=lab.digest(build/('inputs-'+side+'.txt'),'sha256'):raise AssertionError('Identity replay changed') matched=base.compare(build/(side+'.txt'),build/('rust-'+side+'.txt')) if matched!=expected_lines:raise AssertionError('Incomplete motion output') diff --git a/tools/test_natural_spawn_parity.py b/tools/test_natural_spawn_parity.py index fabdc184b..3c95e6ac2 100644 --- a/tools/test_natural_spawn_parity.py +++ b/tools/test_natural_spawn_parity.py @@ -550,7 +550,7 @@ def main(): lock, jars, libraries = base.verify_artifacts() resources = lab.RESOURCES oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/natural_spawn_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/natural_spawn_fixture.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawn_selection.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawn_rules.rs'] tested = base.source_hashes(sources) @@ -568,10 +568,10 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'natural_spawn_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/natural_spawn_fixture' - run([binary, resources, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples/probe' + run([binary, 'natural_spawn_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] if errors: diff --git a/tools/test_nether_portal_parity.py b/tools/test_nether_portal_parity.py index 08e707e90..71cbf7be8 100644 --- a/tools/test_nether_portal_parity.py +++ b/tools/test_nether_portal_parity.py @@ -145,8 +145,8 @@ def main(): '-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaPortalOracle.java')]) h.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaPortalOracle', str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')]) - h.run(['cargo', 'run', '-q', '--release', '-p', 'horizon-world', '--example', 'portal_travel_fixture', '--', - str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], cwd=lab.ROOT) + h.run(['cargo', 'run', '-q', '--release', '-p', 'horizon-world', '--example', 'probe', '--', + 'portal_travel_fixture', str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], cwd=lab.ROOT) native = h.split_cases((work / 'native.txt').read_text(), ()) rust = h.split_cases((work / 'rust.txt').read_text(), ()) assert len(native) == len(rust) == len(all_cases), (len(native), len(rust), len(all_cases)) diff --git a/tools/test_object_open_map_parity.py b/tools/test_object_open_map_parity.py index 0a4633b3d..72bafc1a4 100644 --- a/tools/test_object_open_map_parity.py +++ b/tools/test_object_open_map_parity.py @@ -117,7 +117,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaObjectOpenMapOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/object_open_map_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/object_open_map_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -128,10 +128,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaObjectOpenMapOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','object_open_map_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('object_open_map_fixture.exe' if os.name=='nt' else 'object_open_map_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'object_open_map_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_object_open_set_parity.py b/tools/test_object_open_set_parity.py index cdbe43a15..3801cdb60 100644 --- a/tools/test_object_open_set_parity.py +++ b/tools/test_object_open_set_parity.py @@ -66,7 +66,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaObjectOpenSetOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/object_open_set_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/object_open_set_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -77,10 +77,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaObjectOpenSetOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','object_open_set_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('object_open_set_fixture.exe' if os.name=='nt' else 'object_open_set_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'object_open_set_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_pack_screen_parity.py b/tools/test_pack_screen_parity.py index a73f734fe..1f3f03ede 100644 --- a/tools/test_pack_screen_parity.py +++ b/tools/test_pack_screen_parity.py @@ -14,7 +14,7 @@ records every GuiGraphicsExtractor call of the screen shown at the end (widgets, list backgrounds, scissor, separators, scroll bars, entries with their incompatibility tint, hover overlay and arrows, the selection outline, the search box, the buttons and their tooltip); -examples/pack_screen_fixture runs horizon_client::pack_screen, which the +examples/probe/pack_screen_fixture runs horizon_client::pack_screen, which the game's pack screen is, through the same actions. The call lists must agree. test_pack_screen_parity.py [--count N] [--detail N] diff --git a/tools/test_pack_selection_parity.py b/tools/test_pack_selection_parity.py index 8610d85f3..9af372d1e 100644 --- a/tools/test_pack_selection_parity.py +++ b/tools/test_pack_selection_parity.py @@ -7,7 +7,7 @@ initial selection as options.txt stores it, and the actions the screen's entries take on a click or key press: select (an incompatible pack only when its confirmation is accepted), unselect, move up, move down. The Java oracle (VanillaPackSelectionOracle) runs vanilla's PackRepository and -PackSelectionModel; examples/pack_selection_fixture runs +PackSelectionModel; examples/probe/pack_selection_fixture runs horizon_client::packs::SelectionModel, which the game's pack screen uses. After every action both lists, in order, with each entry's canSelect, canUnselect, canMoveUp and canMoveDown, and the selection committed at the @@ -71,8 +71,8 @@ def main(): *(PARITY / f'{n}.java' for n in ('ParityData', 'VanillaPackSelectionOracle'))], 'compile-java') run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaPackSelectionOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'pack_selection_fixture', '--', - inputs, build / 'rust.jsonl'], 'rust') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'pack_selection_fixture', inputs, build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] assert len(vanilla) == len(rust) == len(chosen) diff --git a/tools/test_particle_providers_parity.py b/tools/test_particle_providers_parity.py index 2fdd510d9..def7e3bfa 100644 --- a/tools/test_particle_providers_parity.py +++ b/tools/test_particle_providers_parity.py @@ -197,14 +197,14 @@ def main(): 'tools/test_particle_providers_parity.py', 'tools/oracle_harness.py', 'tools/test_rust_parity.py', 'tools/lab.py', f'mods/horizon/src/test/java/dev/horizonlab/parity/{oracle}.java', 'Cargo.toml', 'Cargo.lock', 'crates/horizon-client/Cargo.toml', 'crates/horizon-client/src/particles.rs', - f'crates/horizon-client/examples/{probe}.rs', 'crates/horizon-core/src/random.rs']] + f'crates/horizon-client/examples/probe/{probe}.rs', 'crates/horizon-core/src/random.rs']] tested = base.source_hashes(sources) cases_path, units = make_cases(build) classes, dependencies, _ = harness.compile_oracle(build, oracle, jars, libraries, lock['minecraft']['java_major']) - binary = harness.build_probe(build, probe) + command = harness.build_probe(build, probe) # The oracle runs first: the probe replays the particle seeds it recovered. harness.java_run(build, classes, dependencies, oracle, [cases_path, build / 'client.txt'], 'client') - harness.run_logged([binary, cases_path, build / 'client.txt', build / 'rust.txt'], build, 'rust') + harness.run_logged([*command, cases_path, build / 'client.txt', build / 'rust.txt'], build, 'rust') tolerance = 0 try: matched = base.compare(build / 'client.txt', build / 'rust.txt') diff --git a/tools/test_piston_movement_parity.py b/tools/test_piston_movement_parity.py index 9b580c1ee..82bcd09ca 100644 --- a/tools/test_piston_movement_parity.py +++ b/tools/test_piston_movement_parity.py @@ -49,7 +49,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPistonMovementOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/piston_movement_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/piston_movement_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -60,10 +60,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPistonMovementOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','piston_movement_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('piston_movement_fixture.exe' if os.name=='nt' else 'piston_movement_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'piston_movement_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_piston_shape_parity.py b/tools/test_piston_shape_parity.py index 0816b3f8b..74ae48e39 100644 --- a/tools/test_piston_shape_parity.py +++ b/tools/test_piston_shape_parity.py @@ -49,7 +49,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPistonShapeOracle.java' helpers=[oracle.with_name(name+'.java') for name in ['VanillaFaceSupportOracle','VanillaBlockStateCodecOracle','VanillaCollisionOracle']] - sources=[oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/piston_shape_fixture.rs'] + sources=[oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/piston_shape_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -63,10 +63,10 @@ def main(): if len(facts['states'])!=35723:raise ValueError('incomplete pinned registry') fixtures=list(corpus(facts));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'facts.json',build/'block-registry.nbt',build/'cached-collision.nbt'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','piston_shape_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('piston_shape_fixture.exe' if os.name=='nt' else 'piston_shape_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'piston_shape_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_place_recipe_parity.py b/tools/test_place_recipe_parity.py index 405ad8009..0b4bdf08e 100644 --- a/tools/test_place_recipe_parity.py +++ b/tools/test_place_recipe_parity.py @@ -9,7 +9,7 @@ renamed copies the book must not use, junk, and sometimes a nearly full inventory; the grid is empty, holds the same recipe already (placing again adds one set, or a full stack with shift) or something else. The Java oracle (VanillaPlaceRecipeOracle) runs RecipeBookMenu.handlePlacement as the server's -packet handler does; examples/place_recipe_fixture runs +packet handler does; examples/probe/place_recipe_fixture runs horizon_client::menu's place_recipe. Every menu slot, the whole inventory, the drops and whether the client gets a ghost recipe are compared. diff --git a/tools/test_placement_parity.py b/tools/test_placement_parity.py index 8ac2f9247..d4e84eaf8 100644 --- a/tools/test_placement_parity.py +++ b/tools/test_placement_parity.py @@ -100,7 +100,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlacementOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/placement_fixture.rs",lab.ROOT/"crates/horizon-world/examples/support/placement_queries.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/placement_fixture.rs",lab.ROOT/"crates/horizon-world/examples/probe/support/placement_queries.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -108,10 +108,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","placement_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("placement_fixture.exe" if os.name=="nt" else "placement_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"placement_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_player_equipment_parity.py b/tools/test_player_equipment_parity.py index dd54b4c24..5f2499eab 100644 --- a/tools/test_player_equipment_parity.py +++ b/tools/test_player_equipment_parity.py @@ -51,7 +51,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerEquipmentOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/player_equipment_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/player_equipment_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -62,10 +62,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPlayerEquipmentOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','player_equipment_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('player_equipment_fixture.exe' if os.name=='nt' else 'player_equipment_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'player_equipment_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_player_food_parity.py b/tools/test_player_food_parity.py index 5f8bf6784..ff38abe39 100644 --- a/tools/test_player_food_parity.py +++ b/tools/test_player_food_parity.py @@ -48,7 +48,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerFoodOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/player_food_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/player_food_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPlayerFoodOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','player_food_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('player_food_fixture.exe' if os.name=='nt' else 'player_food_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'player_food_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_player_health_parity.py b/tools/test_player_health_parity.py index 40d6d2e5e..256ffdf46 100644 --- a/tools/test_player_health_parity.py +++ b/tools/test_player_health_parity.py @@ -47,7 +47,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerHealthOracle.java' helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAttributeOracle.java' - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/player_health_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/player_health_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -58,10 +58,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPlayerHealthOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'catalog.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json',build/'ids.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','player_health_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('player_health_fixture.exe' if os.name=='nt' else 'player_health_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'player_health_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_player_hurt_parity.py b/tools/test_player_hurt_parity.py index abc429a0c..34ce6a9dd 100644 --- a/tools/test_player_hurt_parity.py +++ b/tools/test_player_hurt_parity.py @@ -71,7 +71,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerHurtOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/player_hurt_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/player_hurt_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -82,10 +82,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPlayerHurtOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','player_hurt_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('player_hurt_fixture.exe' if os.name=='nt' else 'player_hurt_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'player_hurt_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_player_inventory_parity.py b/tools/test_player_inventory_parity.py index 13d90b9c0..10f6af812 100644 --- a/tools/test_player_inventory_parity.py +++ b/tools/test_player_inventory_parity.py @@ -57,7 +57,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerInventoryOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/player_inventory_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/player_inventory_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -68,10 +68,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPlayerInventoryOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','player_inventory_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('player_inventory_fixture.exe' if os.name=='nt' else 'player_inventory_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'player_inventory_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_player_travel_parity.py b/tools/test_player_travel_parity.py index 2fc9e1b48..9b96ba8e8 100644 --- a/tools/test_player_travel_parity.py +++ b/tools/test_player_travel_parity.py @@ -55,7 +55,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerTravelOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/player_travel_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/player_travel_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -66,10 +66,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPlayerTravelOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','player_travel_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('player_travel_fixture.exe' if os.name=='nt' else 'player_travel_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'player_travel_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_powder_snow_collision_parity.py b/tools/test_powder_snow_collision_parity.py index 737e367be..10c287cc5 100644 --- a/tools/test_powder_snow_collision_parity.py +++ b/tools/test_powder_snow_collision_parity.py @@ -51,7 +51,7 @@ def main(): oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionContextOracle.java' helpers=[oracle.with_name('VanillaFaceSupportOracle.java')] runner=lab.ROOT/'tools/test_collision_context_parity.py' - sources=[oracle,*helpers,runner,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/collision_context_fixture.rs'] + sources=[oracle,*helpers,runner,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/collision_context_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -62,10 +62,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaCollisionContextOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','collision_context_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('collision_context_fixture.exe' if os.name=='nt' else 'collision_context_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'collision_context_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_raid_parity.py b/tools/test_raid_parity.py index 6df5f8fa6..be1ed7e25 100644 --- a/tools/test_raid_parity.py +++ b/tools/test_raid_parity.py @@ -316,7 +316,7 @@ def main(): lock, jars, libraries = base.verify_artifacts() resources = lab.RESOURCES oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRaidOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/raid_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/raid_fixture.rs', lab.ROOT / 'crates/horizon-client/src/raid.rs', lab.ROOT / 'crates/horizon-client/src/patrol.rs'] tested = base.source_hashes(sources) inputs = build / 'inputs.txt' @@ -335,10 +335,10 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaRaidOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'raid_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/raid_fixture' - run([binary, resources, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples/probe' + run([binary, 'raid_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] if errors: diff --git a/tools/test_random_tick_sections_parity.py b/tools/test_random_tick_sections_parity.py index 632808523..0b78afadb 100644 --- a/tools/test_random_tick_sections_parity.py +++ b/tools/test_random_tick_sections_parity.py @@ -7,7 +7,7 @@ Each case loads sections (every block state fills one, alone, so each state's ow ticking and a non-ticking state), ticks, sets and removes randomly ticking blocks (leaving them in the palette), and ticks again. Vanilla runs ServerLevel.tickChunk's section loop on real sections with the real getBlockRandomPos (VanillaRandomTickSectionsOracle); Horizon runs Behaviours::tick_chunk_random with the game's RandomTickSections -(examples/random_tick_sections_probe). Both print every drawn position, whether its block and its fluid tick +(examples/probe/random_tick_sections_probe). Both print every drawn position, whether its block and its fluid tick randomly, and the final randValue. """ import itertools diff --git a/tools/test_recipe_book_parity.py b/tools/test_recipe_book_parity.py index 4aa91686e..c25f180ac 100644 --- a/tools/test_recipe_book_parity.py +++ b/tools/test_recipe_book_parity.py @@ -8,7 +8,7 @@ having seen a highlighted recipe, the open and filter settings of the four book types, and saving and loading the player's recipeBook compound (with unknown ids dropped, and a compound missing a list ignored). The Java oracle (VanillaRecipeBookOracle) drives ServerRecipeBook and its codec; -examples/recipe_book_fixture drives horizon_client::recipe_book. After each +examples/probe/recipe_book_fixture drives horizon_client::recipe_book. After each operation the count, the known and highlighted recipes, the settings and the saved compound are compared. """ diff --git a/tools/test_recipe_book_render_parity.py b/tools/test_recipe_book_render_parity.py index 78d911d72..f60ac83fb 100644 --- a/tools/test_recipe_book_render_parity.py +++ b/tools/test_recipe_book_render_parity.py @@ -11,7 +11,7 @@ the mouse. The Java oracle (VanillaRecipeBookScreenOracle) builds vanilla's widgets for that state as RecipeBookComponent.initVisuals and RecipeBookPage.init do and records every GuiGraphicsExtractor call of their extractRenderState, the tooltips and GhostSlots.extractRenderState, with its -pose; examples/recipe_book_render_fixture lays out the same state with +pose; examples/probe/recipe_book_render_fixture lays out the same state with horizon_client::recipe_book_screen, which the game paints. The call lists must agree. """ diff --git a/tools/test_recipe_book_view_parity.py b/tools/test_recipe_book_view_parity.py index a38d04eca..dcdc88a88 100644 --- a/tools/test_recipe_book_view_parity.py +++ b/tools/test_recipe_book_view_parity.py @@ -8,7 +8,7 @@ grid, the furnace, blast furnace or smoker) with random inventory and menu contents and the craftable filter on or off. The Java oracle (VanillaRecipeBookViewOracle, on the client jar) runs ClientRecipeBook, RecipeCollection.selectRecipes and the tab and page logic of -RecipeBookComponent; examples/recipe_book_view_fixture runs +RecipeBookComponent; examples/probe/recipe_book_view_fixture runs horizon_client::recipe_book::ClientBook. Per tab: visibility, pages and every button's displays with their selected and craftable flags, in order (the client's HashMap of display ids decides it). Most cases also carry a diff --git a/tools/test_registered_entity_fluid_parity.py b/tools/test_registered_entity_fluid_parity.py index c994c392a..ff7a83eb6 100644 --- a/tools/test_registered_entity_fluid_parity.py +++ b/tools/test_registered_entity_fluid_parity.py @@ -53,7 +53,7 @@ def corpus(info): def main(): lock,jars,libraries=base.verify_artifacts();build=lab.LOCAL/'rust-registered-entity-fluid-parity';build.mkdir(exist_ok=True);report_path=build/'report.json';report_path.unlink(missing_ok=True) root=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity';oracles=[root/(n+'.java') for n in ['VanillaRegisteredEntityFluidOracle','VanillaEntityFluidOracle','VanillaRegistryFluidOracle','VanillaHeightmapOracle','VanillaBlockSupportOracle','VanillaCollisionOracle','VanillaBlockStateCodecOracle']] - sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_entity_fluid_parity.py',lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/entity_fluid_fixture.rs'] + sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_entity_fluid_parity.py',lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/probe/entity_fluid_fixture.rs'] for crate in ['horizon-core','horizon-world']:sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] tested=base.source_hashes(sources);tags=worldgen.tag_resources(jars['server']) if tags!=worldgen.tag_resources(jars['client']):raise AssertionError('Native tags differ between artifacts') @@ -67,7 +67,7 @@ def main(): with (build/'inputs.txt').open('w') as output: for f in corpus(info):output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 fixture_paths=[build/n for n in ['inputs.txt','facts.json','fluid-info.json','block-registry.nbt','cached-support.nbt','tags.json']];fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','entity_fluid_fixture'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('entity_fluid_fixture.exe' if os.name=='nt' else 'entity_fluid_fixture');run([binary,build],'rust');references=[] + run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'entity_fluid_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side);matched=base.compare(build/(side+'.txt'),build/'rust.txt');references.append(dict(side=side,jar_sha256=lab.digest(jar,'sha256'),output_sha256=lab.digest(build/(side+'.txt'),'sha256'),matched_output_lines=matched));print(f'{side}: {matched:,} registered entity fluid output lines match Rust',flush=True) base.ensure_sources_unchanged(sources,tested);base.ensure_sources_unchanged(fixture_paths,fixtures) diff --git a/tools/test_registered_player_combat_parity.py b/tools/test_registered_player_combat_parity.py index 219d75e52..eecb6e6cf 100644 --- a/tools/test_registered_player_combat_parity.py +++ b/tools/test_registered_player_combat_parity.py @@ -48,7 +48,7 @@ def main(): helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAttributeOracle.java' health_helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerHealthOracle.java' damage_helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDamageSourceOracle.java' - sources=[oracle,helper,health_helper,damage_helper,lab.ROOT/'tools/test_server_player_combat_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_player_hurt_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/registered_player_combat_fixture.rs'] + sources=[oracle,helper,health_helper,damage_helper,lab.ROOT/'tools/test_server_player_combat_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_player_hurt_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/registered_player_combat_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaRegisteredPlayerCombatOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'catalog.json').read_text());damage=json.loads((damage_dir/'catalog.json').read_text());fixtures=list(corpus(states,damage));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json',build/'ids.json',build/'slots.json',build/'head.json',damage_dir/'catalog.json',damage_dir/'types.json',damage_dir/'tags.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','registered_player_combat_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('registered_player_combat_fixture.exe' if os.name=='nt' else 'registered_player_combat_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'registered_player_combat_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_registry_collision_scan_parity.py b/tools/test_registry_collision_scan_parity.py index e183875ca..5b40d7285 100644 --- a/tools/test_registry_collision_scan_parity.py +++ b/tools/test_registry_collision_scan_parity.py @@ -66,7 +66,7 @@ def main(): sources = [oracle, *helpers, Path(__file__), lab.ROOT/'tools/test_rust_parity.py', lab.ROOT/'tools/test_worldgen_parity.py', lab.ROOT/'tools/lab.py', lab.ROOT/'Cargo.toml', lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-world/examples/registry_collision_scan_fixture.rs'] + lab.ROOT/'crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs'] for crate in ['horizon-core', 'horizon-world']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml', *sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] @@ -96,10 +96,10 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'facts.json', 'definitions.json', 'block-registry.nbt', 'cached-collision.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'registry_collision_scan_fixture'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('registry_collision_scan_fixture.exe' if os.name=='nt' else 'registry_collision_scan_fixture') - run([binary, build], 'rust');references = [] + binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'registry_collision_scan_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) matched = base.compare(build/(side+'.txt'), build/'rust.txt') diff --git a/tools/test_registry_fall_ray_parity.py b/tools/test_registry_fall_ray_parity.py index b343663e3..a7639c3ab 100644 --- a/tools/test_registry_fall_ray_parity.py +++ b/tools/test_registry_fall_ray_parity.py @@ -47,7 +47,7 @@ def corpus(info): def main(): lock,jars,libraries=base.verify_artifacts();build=lab.LOCAL/'rust-registry-fall-ray-parity';build.mkdir(exist_ok=True);report_path=build/'report.json';report_path.unlink(missing_ok=True) root=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity';oracles=[root/(n+'.java') for n in ['VanillaRegistryFallRayOracle','VanillaInteractionShapeOracle','VanillaCollisionOracle','VanillaHeightmapOracle']] - sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/registry_fall_ray_fixture.rs'] + sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/probe/registry_fall_ray_fixture.rs'] for crate in ['horizon-core','horizon-world']:sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] tested=base.source_hashes(sources);tags=worldgen.tag_resources(jars['server']);fluids=fluid_tags(jars['server']) if tags!=worldgen.tag_resources(jars['client']) or fluids!=fluid_tags(jars['client']):raise AssertionError('Native tags differ between artifacts') @@ -61,7 +61,7 @@ def main(): with (build/'inputs.txt').open('w') as output: for f in corpus(info):output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 fixture_paths=[build/n for n in ['inputs.txt','info.json','block-registry.nbt','interaction-shapes.nbt','tags.json','fluid-tags.json','bound-tags.json']];fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','registry_fall_ray_fixture'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('registry_fall_ray_fixture.exe' if os.name=='nt' else 'registry_fall_ray_fixture');run([binary,build],'rust');references=[] + run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'registry_fall_ray_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side);matched=base.compare(build/(side+'.txt'),build/'rust.txt');references.append(dict(side=side,jar_sha256=lab.digest(jar,'sha256'),output_sha256=lab.digest(build/(side+'.txt'),'sha256'),matched_output_lines=matched));print(f'{side}: {matched:,} registered fall-ray output lines match Rust',flush=True) base.ensure_sources_unchanged(sources,tested);base.ensure_sources_unchanged(fixture_paths,fixtures) diff --git a/tools/test_registry_fluid_parity.py b/tools/test_registry_fluid_parity.py index 2ae0486fe..fd0fb106b 100644 --- a/tools/test_registry_fluid_parity.py +++ b/tools/test_registry_fluid_parity.py @@ -48,7 +48,7 @@ def corpus(info): def main(): lock,jars,libraries=base.verify_artifacts();build=lab.LOCAL/'rust-registry_fluid-parity';build.mkdir(exist_ok=True);report_path=build/'report.json';report_path.unlink(missing_ok=True) root=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity';oracles=[root/(n+'.java') for n in ['VanillaRegistryFluidOracle','VanillaHeightmapOracle','VanillaBlockSupportOracle','VanillaCollisionOracle','VanillaBlockStateCodecOracle']] - sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/registry_fluid_fixture.rs'] + sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/probe/registry_fluid_fixture.rs'] for crate in ['horizon-core','horizon-world']:sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] tested=base.source_hashes(sources);tags=worldgen.tag_resources(jars['server']) if tags!=worldgen.tag_resources(jars['client']):raise AssertionError('Native tags differ between artifacts') @@ -62,7 +62,7 @@ def main(): with (build/'inputs.txt').open('w') as output: for f in corpus(info):output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 fixture_paths=[build/n for n in ['inputs.txt','facts.json','fluid-info.json','block-registry.nbt','cached-support.nbt','tags.json']];fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','registry_fluid_fixture'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('registry_fluid_fixture.exe' if os.name=='nt' else 'registry_fluid_fixture');run([binary,build],'rust');references=[] + run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'registry_fluid_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side);matched=base.compare(build/(side+'.txt'),build/'rust.txt');references.append(dict(side=side,jar_sha256=lab.digest(jar,'sha256'),output_sha256=lab.digest(build/(side+'.txt'),'sha256'),matched_output_lines=matched));print(f'{side}: {matched:,} registry_fluid output lines match Rust',flush=True) base.ensure_sources_unchanged(sources,tested);base.ensure_sources_unchanged(fixture_paths,fixtures) diff --git a/tools/test_replace_block_parity.py b/tools/test_replace_block_parity.py index 8ca916b07..e96bf4c72 100644 --- a/tools/test_replace_block_parity.py +++ b/tools/test_replace_block_parity.py @@ -51,7 +51,7 @@ def main(): if not tags or tags!=worldgen.tag_resources(jars['client']):raise ValueError('client/server tags differ') (build/'tags.json').write_text(json.dumps(tags,separators=(',',':')),encoding='utf-8') sources=[oracle,helper,tag_helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/replace_block_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/replace_block_fixture.rs"] tested_sources=base.source_hashes(sources) fixture_paths=[build/"tags.json"];classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -68,10 +68,10 @@ def main(): fixtures=list(corpus(facts));inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths.append(inputs) tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","replace_block_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("replace_block_fixture.exe" if os.name=="nt" else "replace_block_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"replace_block_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_resource_pack_parity.py b/tools/test_resource_pack_parity.py index 6169542c5..2d9ae2a85 100644 --- a/tools/test_resource_pack_parity.py +++ b/tools/test_resource_pack_parity.py @@ -9,7 +9,7 @@ sources) and selects them over the prepared vanilla resources. The Java oracle and MultiPackResourceManager and asks what each reload listener reads: which pack a file comes from, translations (ClientLanguage), sound events (SoundManager.prepare), font providers (FontManager) and atlas sources -(SpriteSourceList). examples/pack_resources_fixture builds Horizon's resource +(SpriteSourceList). examples/probe/pack_resources_fixture builds Horizon's resource root for the same selection (packs::build_overlay) and reads it with Horizon's loaders. Every answer must agree. """ diff --git a/tools/test_restitution_parity.py b/tools/test_restitution_parity.py index bbb2d95ba..ada050a13 100644 --- a/tools/test_restitution_parity.py +++ b/tools/test_restitution_parity.py @@ -51,7 +51,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRestitutionOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/restitution_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/restitution_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -62,10 +62,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaRestitutionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','restitution_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('restitution_fixture.exe' if os.name=='nt' else 'restitution_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'restitution_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_retrogen_chunk_parity.py b/tools/test_retrogen_chunk_parity.py index 2fe4be7ef..9a13e1303 100644 --- a/tools/test_retrogen_chunk_parity.py +++ b/tools/test_retrogen_chunk_parity.py @@ -56,7 +56,7 @@ def main(): helper=oracle.with_name("VanillaHeightmapOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock", lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/chunk_stage_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/chunk_stage_fixture.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -74,10 +74,10 @@ def main(): (build/"tags.json").write_text(json.dumps(tags,separators=(",",":")),encoding="utf-8") fixture_paths=[inputs,build/"tags.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","chunk_stage_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("chunk_stage_fixture.exe" if os.name=="nt" else "chunk_stage_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"chunk_stage_fixture",build],"rust") references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_retrogen_data_parity.py b/tools/test_retrogen_data_parity.py index 5904cbe93..242f3b5d3 100644 --- a/tools/test_retrogen_data_parity.py +++ b/tools/test_retrogen_data_parity.py @@ -38,7 +38,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRetrogenDataOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/retrogen_data_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/retrogen_data_fixture.rs'] tested_sources=base.source_hashes(sources) commands=list(corpus());inputs=build/'inputs.txt';inputs.write_text('\n'.join(json.dumps(command) for command in commands)+'\n') tested_fixtures=base.source_hashes([inputs]);classes=build/'classes';classes.mkdir(exist_ok=True) @@ -46,10 +46,10 @@ def main(): with (build/(name+'.log')).open('w') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=3600,stdout=log,stderr=subprocess.STDOUT) dependencies=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependencies,'-d',classes,oracle],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','retrogen_data_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('retrogen_data_fixture.exe' if os.name=='nt' else 'retrogen_data_fixture') - run([binary,inputs,build/'rust.txt'],'rust') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'retrogen_data_fixture',inputs,build/'rust.txt'],'rust') references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependencies]),'dev.horizonlab.parity.VanillaRetrogenDataOracle',inputs,build/(side+'.txt')],side) diff --git a/tools/test_rule_test_parity.py b/tools/test_rule_test_parity.py index f87283982..8fef86b95 100644 --- a/tools/test_rule_test_parity.py +++ b/tools/test_rule_test_parity.py @@ -58,7 +58,7 @@ def main(): tags=worldgen.tag_resources(jars['server']) if not tags or tags!=worldgen.tag_resources(jars['client']):raise ValueError('client/server tags differ') (build/'tags.json').write_text(json.dumps(tags,separators=(',',':')),encoding='utf-8') - sources=[oracle,*helpers,lab.ROOT/'tools/test_worldgen_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/rule_test_fixture.rs'] + sources=[oracle,*helpers,lab.ROOT/'tools/test_worldgen_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/rule_test_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -73,10 +73,10 @@ def main(): if len(facts['states'])!=35723:raise ValueError('incomplete pinned state registry') fixtures=list(corpus(facts,tags));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'tags.json',build/'facts-client.json',build/'facts-server.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','rule_test_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('rule_test_fixture.exe' if os.name=='nt' else 'rule_test_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'rule_test_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_save_roundtrip_parity.py b/tools/test_save_roundtrip_parity.py index 72bea8845..bd8b07a29 100644 --- a/tools/test_save_roundtrip_parity.py +++ b/tools/test_save_roundtrip_parity.py @@ -109,15 +109,9 @@ BENIGN = re.compile(r'(Unpacking |OFFLINE/INSECURE|online-mode|authenticate user # ---------------------------------------------------------------- vanilla server -def free_port(): - with socket.socket() as s: - s.bind(('127.0.0.1', 0)) - return s.getsockname()[1] - - class Vanilla: def __init__(self, directory, port=None, world='world', extra=None): - port = port or free_port() + port = port or lab.free_port() directory.mkdir(parents=True, exist_ok=True) (directory / 'eula.txt').write_text('eula=true\n') props = { diff --git a/tools/test_scaffolding_collision_parity.py b/tools/test_scaffolding_collision_parity.py index 3e60f229a..bebd63087 100644 --- a/tools/test_scaffolding_collision_parity.py +++ b/tools/test_scaffolding_collision_parity.py @@ -44,7 +44,7 @@ def main(): oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionContextOracle.java' helpers=[oracle.with_name('VanillaFaceSupportOracle.java')] runner=lab.ROOT/'tools/test_collision_context_parity.py' - sources=[oracle,*helpers,runner,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/collision_context_fixture.rs'] + sources=[oracle,*helpers,runner,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/collision_context_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -55,10 +55,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaCollisionContextOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','collision_context_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('collision_context_fixture.exe' if os.name=='nt' else 'collision_context_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'collision_context_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_scattered_ore_parity.py b/tools/test_scattered_ore_parity.py index b6bbd5aa7..0cbb6fcac 100644 --- a/tools/test_scattered_ore_parity.py +++ b/tools/test_scattered_ore_parity.py @@ -52,7 +52,7 @@ def main(): if not tags or tags!=worldgen.tag_resources(jars['client']):raise ValueError('client/server tags differ') (build/'tags.json').write_text(json.dumps(tags,separators=(',',':')),encoding='utf-8') sources=[oracle,helper,tag_helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/scattered_ore_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/scattered_ore_fixture.rs"] tested_sources=base.source_hashes(sources) fixture_paths=[build/"tags.json"];classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -69,10 +69,10 @@ def main(): fixtures=list(corpus(facts));inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths.append(inputs) tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","scattered_ore_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("scattered_ore_fixture.exe" if os.name=="nt" else "scattered_ore_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"scattered_ore_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_scoreboard_parity.py b/tools/test_scoreboard_parity.py index 8a035eb17..db308d861 100644 --- a/tools/test_scoreboard_parity.py +++ b/tools/test_scoreboard_parity.py @@ -13,7 +13,7 @@ of each collection in vanilla's iteration order (objectivesByName and playerScores as fastutil open hash maps, teamsByName, each team's HashSet of players), and the ScoreboardSaveData.Packed codec output that data/minecraft/scoreboard.dat holds, before and after loading it back. -`examples/scoreboard_fixture` runs the same cases on +`examples/probe/scoreboard_fixture` runs the same cases on `horizon_client::scoreboard`, reloads vanilla's NBT, and vanilla reloads Horizon's NBT; all must agree. The one order vanilla leaves to identity hash codes (each holder's scores within PlayerScores) is compared as a set. @@ -250,10 +250,10 @@ def main(): inputs = build / 'inputs.jsonl' inputs.write_text(''.join(json.dumps(c, ensure_ascii=False) + '\n' for c in chosen), encoding='utf-8') run([*oracle, 'run', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'scoreboard_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('scoreboard_fixture.exe' if os.name == 'nt' else 'scoreboard_fixture') - run([binary, build / 'registries.json', inputs, build / 'rust.jsonl', build / 'vanilla.jsonl'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'scoreboard_fixture',build / 'registries.json', inputs, build / 'rust.jsonl', build / 'vanilla.jsonl'], 'rust') read = lambda p: [json.loads(l) for l in p.read_text(encoding='utf-8').splitlines()] vanilla, rust = read(build / 'vanilla.jsonl'), read(build / 'rust.jsonl') assert len(vanilla) == len(rust) diff --git a/tools/test_screen_layout_parity.py b/tools/test_screen_layout_parity.py index d488716f6..c9e791afb 100644 --- a/tools/test_screen_layout_parity.py +++ b/tools/test_screen_layout_parity.py @@ -6,7 +6,7 @@ a loom screen and menu whose state comes from the case (inputs present, the selectable patterns, the selected one, the scroller, the result banner or the six-layer error, the mouse over a pattern button) and CrafterScreen's background, disabled slots and redstone arrow, recording every -GuiGraphicsExtractor call; examples/screen_layout_fixture lays out the same +GuiGraphicsExtractor call; examples/probe/screen_layout_fixture lays out the same state with horizon_client::screen_layout, which the game paints. The ordered call lists must agree. """ diff --git a/tools/test_section_mesh_parity.py b/tools/test_section_mesh_parity.py index 78c0d68e9..65878bc97 100644 --- a/tools/test_section_mesh_parity.py +++ b/tools/test_section_mesh_parity.py @@ -481,7 +481,7 @@ def main(): oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSectionMeshOracle.java' helpers = [oracle.with_name(n + '.java') for n in ['VanillaCuboidModelOracle', 'VanillaHeightmapOracle']] sources = [Path(__file__), lab.ROOT / 'tools/lab.py', lab.ROOT / 'tools/test_rust_parity.py', oracle, *helpers, - lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock', lab.ROOT / 'crates/horizon-client/examples/section_mesh_fixture.rs'] + lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock', lab.ROOT / 'crates/horizon-client/examples/probe/section_mesh_fixture.rs'] for crate in ['horizon-core', 'horizon-world', 'horizon-assets', 'horizon-client']: sources += [lab.ROOT / 'crates' / crate / 'Cargo.toml', *sorted((lab.ROOT / 'crates' / crate / 'src').rglob('*.rs'))] tested = base.source_hashes(sources) @@ -502,14 +502,14 @@ def main(): dependencies = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()])) run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'), '-cp', dependencies, '-d', classes, oracle, *helpers], 'compile-java') env_jobs = os.environ.get('CARGO_BUILD_JOBS', '3') - run(['cargo', 'build', '--locked', '--profile', 'fast', '-j', env_jobs, '-p', 'horizon-client', '--example', 'section_mesh_fixture'], 'compile-rust') + run(['cargo', 'build', '--locked', '--profile', 'fast', '-j', env_jobs, '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory']) / 'fast/examples' / ('section_mesh_fixture.exe' if os.name == 'nt' else 'section_mesh_fixture') + binary = Path(metadata['target_directory']) / 'fast/examples' / ('probe.exe' if os.name=='nt' else 'probe') java = ['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaSectionMeshOracle'] - run([binary, resources, inputs, BUILD / 'rust.jsonl'], 'rust') + run([binary, 'section_mesh_fixture',resources, inputs, BUILD / 'rust.jsonl'], 'rust') run([*java, inputs, BUILD / 'client.jsonl', resources], 'client') run([*java, 'facts', BUILD / 'client-facts.jsonl', resources], 'client-facts') - run([binary, resources, 'facts', BUILD / 'rust-facts.jsonl'], 'rust-facts') + run([binary, 'section_mesh_fixture',resources, 'facts', BUILD / 'rust-facts.jsonl'], 'rust-facts') report = {'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'scenes': len(rows), 'client_quads': 0, 'rust_quads': 0, 'matched_quads': 0, 'identical_quads': 0, 'categories': {}, 'examples': {}, 'per_scene': {}, 'facts': {}} diff --git a/tools/test_secure_chat_parity.py b/tools/test_secure_chat_parity.py index ed408efa3..c6c76a892 100644 --- a/tools/test_secure_chat_parity.py +++ b/tools/test_secure_chat_parity.py @@ -41,12 +41,12 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer try: from . import lab, oracle_harness as oh, test_rust_parity as base - from .test_dedicated_server_parity import Server, free_port + from .test_dedicated_server_parity import Server except ImportError: import lab import oracle_harness as oh import test_rust_parity as base - from test_dedicated_server_parity import Server, free_port + from test_dedicated_server_parity import Server NAME = 'secure-chat-parity' SCENARIOS = { @@ -153,20 +153,10 @@ def dashed(u): return f'{u[:8]}-{u[8:12]}-{u[12:16]}-{u[16:20]}-{u[20:]}' -def varint(n): - out = b'' - while True: - b = n & 0x7F - n >>= 7 - out += bytes([b | (0x80 if n else 0)]) - if not n: - return out - - def status(port): """The status response's JSON (ServerStatus).""" def packet(body): - return varint(len(body)) + body + return lab.varint(len(body)) + body def read_varint(s): value = 0 @@ -177,7 +167,7 @@ def status(port): return value with socket.create_connection(('127.0.0.1', port), timeout=10) as s: host = b'127.0.0.1' - s.sendall(packet(b'\x00' + varint(777) + varint(len(host)) + host + port.to_bytes(2, 'big') + b'\x01')) + s.sendall(packet(b'\x00' + lab.varint(777) + lab.varint(len(host)) + host + port.to_bytes(2, 'big') + b'\x01')) s.sendall(packet(b'\x00')) length = read_varint(s) data = b'' @@ -212,7 +202,7 @@ def chat_lines(lines): def run_side(label, scenario, command, directory, client): - port = free_port() + port = lab.free_port() shutil.rmtree(directory, ignore_errors=True) directory.mkdir(parents=True) props = dict(PROPERTIES, **SCENARIOS[scenario], **{'server-port': str(port)}) diff --git a/tools/test_server_dimension_players_parity.py b/tools/test_server_dimension_players_parity.py index 8453d14af..b1efc4378 100644 --- a/tools/test_server_dimension_players_parity.py +++ b/tools/test_server_dimension_players_parity.py @@ -96,17 +96,6 @@ def run_side(label, server_command, client_command, build, world): SHOWN = ('add', 'remove', 'respawn', 'track', 'untrack', 'update') -def settled(lines): - """One player's lines of one step, in order, with the waypoint packets reduced to the last for each waypoint: - what the locator bar shows once the step is over. Arriving in a level, vanilla sends the same waypoint more - than once on the way there; the packet by packet order is test_locator_bar_parity's.""" - def waypoint(line): - parts = line.split(' ') - return parts[3] if len(parts) > 3 and parts[2] in ('track', 'untrack', 'update') else None - last = {waypoint(l): i for i, l in enumerate(lines) if waypoint(l)} - return [l for i, l in enumerate(lines) if not waypoint(l) or last[waypoint(l)] == i] - - def shown(lines): """Each player's adds, removes, respawns and waypoints (as the step leaves them), step by step; sorted within a step (the packets of one step may leave in another order within the tick).""" @@ -115,7 +104,7 @@ def shown(lines): parts = line.split(' ', 2) if len(parts) == 3 and parts[2].split(' ')[0] in SHOWN: steps.setdefault((parts[0], parts[1]), []).append(line) - return [l for key in steps for l in sorted(settled(steps[key]))] + return [l for key in steps for l in sorted(lab.settled(steps[key]))] def main(): diff --git a/tools/test_server_files_parity.py b/tools/test_server_files_parity.py index 735bca302..82c0eaa8a 100644 --- a/tools/test_server_files_parity.py +++ b/tools/test_server_files_parity.py @@ -194,7 +194,7 @@ def main(): oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaServerFilesOracle.java' sources = [Path(__file__).resolve(), oracle, lab.ROOT / 'tools/oracle_harness.py', lab.ROOT / 'tools/lab.py', lab.ROOT / 'tools/test_rust_parity.py', lab.ROOT / 'Cargo.lock', - lab.ROOT / 'crates/horizon-client/examples/server_files_probe.rs', + lab.ROOT / 'crates/horizon-client/examples/probe/server_files_probe.rs', *sorted((lab.ROOT / 'crates/horizon-client/src/server').glob('*.rs'))] tested = base.source_hashes(sources) cases, count = make_cases(build) @@ -204,8 +204,8 @@ def main(): oh.run_logged(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], build, 'compile-java') - binary = oh.build_probe(build, 'server_files_probe') - oh.run_logged([binary, cases, build / 'rust.txt'], build, 'rust') + command = oh.build_probe(build, 'server_files_probe') + oh.run_logged([*command, cases, build / 'rust.txt'], build, 'rust') oh.run_logged(['java', '-Xmx1g', '-Duser.timezone=UTC', '-Djava.awt.headless=true', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaServerFilesOracle', cases, build / 'server.txt'], build, 'server') diff --git a/tools/test_server_player_combat_parity.py b/tools/test_server_player_combat_parity.py index 7192e7109..161c4cbcf 100644 --- a/tools/test_server_player_combat_parity.py +++ b/tools/test_server_player_combat_parity.py @@ -66,7 +66,7 @@ def main(): oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaServerPlayerCombatOracle.java' helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAttributeOracle.java' health_helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerHealthOracle.java' - sources=[oracle,helper,health_helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_player_hurt_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/server_player_combat_fixture.rs'] + sources=[oracle,helper,health_helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_player_hurt_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/server_player_combat_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -77,11 +77,11 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaServerPlayerCombatOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'catalog.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json',build/'ids.json',build/'slots.json',build/'head.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','server_player_combat_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('server_player_combat_fixture.exe' if os.name=='nt' else 'server_player_combat_fixture') - run([binary,build],'rust') - run([binary,build,'--live'],'rust-live') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'server_player_combat_fixture',build],'rust') + run([binary,'server_player_combat_fixture',build,'--live'],'rust-live') base.compare(build/'rust.txt',build/'rust-live.txt');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_server_player_damage_parity.py b/tools/test_server_player_damage_parity.py index 4a0e0b9c7..8e1418f4e 100644 --- a/tools/test_server_player_damage_parity.py +++ b/tools/test_server_player_damage_parity.py @@ -51,7 +51,7 @@ def main(): oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaServerPlayerDamageOracle.java' helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAttributeOracle.java' health_helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerHealthOracle.java' - sources=[oracle,helper,health_helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/server_player_damage_fixture.rs'] + sources=[oracle,helper,health_helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/server_player_damage_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -62,10 +62,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaServerPlayerDamageOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'catalog.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json',build/'ids.json',build/'slots.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','server_player_damage_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('server_player_damage_fixture.exe' if os.name=='nt' else 'server_player_damage_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'server_player_damage_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_server_player_targets_parity.py b/tools/test_server_player_targets_parity.py index 71416223b..cad8782cc 100644 --- a/tools/test_server_player_targets_parity.py +++ b/tools/test_server_player_targets_parity.py @@ -15,7 +15,6 @@ in sorted order (the packets of one step may leave in another order within the t waypoints as each step leaves them (one manager per level: a player in another level is untracked). What a death does besides its messages is left to its own harness. """ -import hashlib import os from pathlib import Path import platform @@ -23,7 +22,6 @@ import shutil import subprocess import sys import time -import uuid as uuidlib try: from . import lab, test_rust_parity as base @@ -39,20 +37,12 @@ NAME = 'server-player-targets-parity' NETHER, OVERWORLD = 'minecraft:the_nether', 'minecraft:overworld' -def offline_uuid(name): - """UUIDUtil.createOfflinePlayerUUID.""" - digest = bytearray(hashlib.md5(f'OfflinePlayer:{name}'.encode()).digest()) - digest[6] = (digest[6] & 0x0F) | 0x30 - digest[8] = (digest[8] & 0x3F) | 0x80 - return str(uuidlib.UUID(bytes=bytes(digest))) - - # (label, what the console does, what the players do). SCRIPT = [ ('console-give', ['give Bob minecraft:diamond 3'], []), ('console-give-all', ['give @a minecraft:apple'], []), ('alice-give-bob', [], ['cmd Alice give Bob minecraft:stick 2']), - ('console-give-uuid', [f'give {offline_uuid("Bob")} minecraft:iron_ingot'], []), + ('console-give-uuid', [f'give {lab.offline_uuid("Bob")} minecraft:iron_ingot'], []), ('console-give-nearest', ['give @p minecraft:emerald'], []), ('alice-give-random', [], ['cmd Alice give @r[name=Bob] minecraft:gold_ingot']), ('console-gamemode', ['gamemode survival Bob'], []), @@ -83,17 +73,6 @@ DEATH_STEP = 'step=console-kill' STEP_SECONDS = 2.5 -def settled(lines): - """One player's lines of one step, in order, with the waypoint packets reduced to the last for each waypoint: - what the locator bar shows once the step is over. Arriving in a level, vanilla sends the same waypoint more - than once on the way there; the packet by packet order is test_locator_bar_parity's.""" - def waypoint(line): - parts = line.split(' ') - return parts[3] if len(parts) > 3 and parts[2] in ('track', 'untrack', 'update') else None - last = {waypoint(l): i for i, l in enumerate(lines) if waypoint(l)} - return [l for i, l in enumerate(lines) if not waypoint(l) or last[waypoint(l)] == i] - - def run_side(label, server_command, client_command, build, world): directory = build / label port = server_dir(directory, world) @@ -151,7 +130,7 @@ def run_side(label, server_command, client_command, build, world): steps.setdefault((who, step), []).append(line) order = {f'step={s}': i for i, (s, _, _) in enumerate(SCRIPT)} keys = sorted(steps, key=lambda k: (k[0], order.get(k[1], -1))) - return [l for k in keys for l in sorted(settled(steps[k]))], errors + return [l for k in keys for l in sorted(lab.settled(steps[k]))], errors def main(): diff --git a/tools/test_simple_block_parity.py b/tools/test_simple_block_parity.py index f68f3c92e..3af85a241 100644 --- a/tools/test_simple_block_parity.py +++ b/tools/test_simple_block_parity.py @@ -93,7 +93,7 @@ def run(corpus, build_name, source_file, scope): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts();oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSimpleBlockOracle.java' helpers=[oracle.with_name(name+'.java') for name in ['VanillaPlacementOracle','VanillaBlockSurvivalOracle','VanillaBlockPropertiesOracle','VanillaBlockSupportOracle','VanillaBlockStateCodecOracle','VanillaCollisionOracle','VanillaHeightmapOracle']] - sources=[oracle,*helpers,Path(__file__),Path(source_file),*[lab.ROOT/'tools'/name for name in ['test_block_survival_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/simple_block_fixture.rs'] + sources=[oracle,*helpers,Path(__file__),Path(source_file),*[lab.ROOT/'tools'/name for name in ['test_block_survival_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/simple_block_fixture.rs'] tested_sources=base.source_hashes(sources);classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): with (build/(name+'.log')).open('w',encoding='utf-8') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=3600,stdout=log,stderr=subprocess.STDOUT) @@ -116,9 +116,9 @@ def run(corpus, build_name, source_file, scope): with inputs.open('w',encoding='utf-8') as output: for fixture in corpus(facts,placement):output.write(json.dumps(fixture,separators=(',',':'))+'\n');fixture_count+=1 fixtures=[inputs,*sorted(build.glob('*.nbt')),*[p for p in sorted(build.glob('*.json')) if p.name!='report.json']];tested_fixtures=base.source_hashes(fixtures);print(f'Prepared {fixture_count:,} placement fixtures',flush=True) - run(['cargo','build','--release','-p','horizon-world','--example','simple_block_fixture'],'compile-rust') - metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('simple_block_fixture.exe' if os.name=='nt' else 'simple_block_fixture') - run([binary,build],'rust');references=[] + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'simple_block_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);matched=base.compare(build/(side+'.txt'),build/'rust.txt');print(f'{side}: {matched:,} {label} output lines match Rust',flush=True) references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(build/(side+'.txt'),'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_simple_container_parity.py b/tools/test_simple_container_parity.py index 8365276dd..0af91292a 100644 --- a/tools/test_simple_container_parity.py +++ b/tools/test_simple_container_parity.py @@ -59,7 +59,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSimpleContainerOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/simple_container_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/simple_container_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -70,10 +70,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaSimpleContainerOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','simple_container_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('simple_container_fixture.exe' if os.name=='nt' else 'simple_container_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'simple_container_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_sound_engine_parity.py b/tools/test_sound_engine_parity.py index 36095542c..8eb02a7fe 100644 --- a/tools/test_sound_engine_parity.py +++ b/tools/test_sound_engine_parity.py @@ -18,14 +18,10 @@ import math import random try: - from . import audio_harness as h + from . import audio_harness as h, lab except ImportError: import audio_harness as h - - -def dbits(v): - import struct - return struct.pack('>d', v).hex() + import lab class Script: @@ -37,11 +33,11 @@ class Script: self.lines.append(' '.join(map(str, parts))) def play(self, name, event, source=4, volume=1.0, pitch=1.0, at=(0.0, 0.0, 0.0), looping=0, delay=0, linear=True, relative=0, seed=0, kind='simple'): - self.add('play', name, kind, event, source, h.bits(volume), h.bits(pitch), *map(dbits, at), looping, delay, + self.add('play', name, kind, event, source, h.bits(volume), h.bits(pitch), *map(lab.dbits, at), looping, delay, 'linear' if linear else 'none', relative, seed) def cart(self, name, at, delta, removed=0): - self.add('cart', name, *map(dbits, at), *map(dbits, delta), removed) + self.add('cart', name, *map(lab.dbits, at), *map(lab.dbits, delta), removed) def tick(self, n=1, paused=0): for _ in range(n): diff --git a/tools/test_spawn_rules_parity.py b/tools/test_spawn_rules_parity.py index e71a032b5..19bd8db46 100644 --- a/tools/test_spawn_rules_parity.py +++ b/tools/test_spawn_rules_parity.py @@ -138,7 +138,7 @@ def main(): entity_types = json.loads((resources / 'entity-types.json').read_text()) types = sorted(t for t, v in entity_types.items() if 'attributes' in v and t.split(':')[1] not in SKIPPED) oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSpawnRulesOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/spawn_rules_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/spawn_rules_fixture.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawn_rules.rs'] tested = base.source_hashes(sources) inputs = build / 'inputs.txt' @@ -155,10 +155,10 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx2G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaSpawnRulesOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'spawn_rules_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/spawn_rules_fixture' - run([binary, resources, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples/probe' + run([binary, 'spawn_rules_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] if errors: diff --git a/tools/test_spawner_parity.py b/tools/test_spawner_parity.py index b1637cf4e..5aa9029e3 100644 --- a/tools/test_spawner_parity.py +++ b/tools/test_spawner_parity.py @@ -230,7 +230,7 @@ def main(): lock, jars, libraries = base.verify_artifacts() resources = lab.RESOURCES oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/natural_spawn_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/natural_spawn_fixture.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawner.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawn_selection.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawn_rules.rs'] @@ -249,10 +249,10 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'natural_spawn_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/natural_spawn_fixture' - run([binary, resources, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples/probe' + run([binary, 'natural_spawn_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] if errors: diff --git a/tools/test_sprint_input_parity.py b/tools/test_sprint_input_parity.py index 0fe9eecec..0ac515e44 100644 --- a/tools/test_sprint_input_parity.py +++ b/tools/test_sprint_input_parity.py @@ -40,7 +40,7 @@ def main(): build=lab.LOCAL/'rust-sprint-input';build.mkdir(exist_ok=True) report=build/'report.json';report.unlink(missing_ok=True) oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSprintInputOracle.java' - sources=[Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_model_baking_parity.py',lab.ROOT/'tools/lab.py',oracle,lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-client/Cargo.toml',lab.ROOT/'crates/horizon-client/src/input.rs',lab.ROOT/'crates/horizon-client/src/sprint.rs',lab.ROOT/'crates/horizon-client/src/lib.rs',lab.ROOT/'crates/horizon-client/examples/sprint_probe.rs'] + sources=[Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_model_baking_parity.py',lab.ROOT/'tools/lab.py',oracle,lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-client/Cargo.toml',lab.ROOT/'crates/horizon-client/src/input.rs',lab.ROOT/'crates/horizon-client/src/sprint.rs',lab.ROOT/'crates/horizon-client/src/lib.rs',lab.ROOT/'crates/horizon-client/examples/probe/sprint_probe.rs'] tested=base.source_hashes(sources) def run(command,name): with (build/(name+'.log')).open('w') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=600,stdout=log,stderr=subprocess.STDOUT) @@ -49,10 +49,10 @@ def main(): classes=build/'classes';classes.mkdir(exist_ok=True) dependencies=os.pathsep.join(map(str,[jars['client'],*libraries])) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',dependencies,'-d',classes,oracle],'compile-java') - run(['cargo','build','--locked','-p','horizon-client','--example','sprint_probe'],'compile-rust') + run(['cargo','build','--locked','-p','horizon-client','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT)) - binary=Path(metadata['target_directory'])/'debug/examples'/('sprint_probe.exe' if os.name=='nt' else 'sprint_probe') - run([binary,inputs,build/'rust.txt'],'rust') + binary=Path(metadata['target_directory'])/'debug/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'sprint_probe',inputs,build/'rust.txt'],'rust') run(['java','-Xmx768M','-cp',str(classes)+os.pathsep+dependencies,'dev.horizonlab.parity.VanillaSprintInputOracle',inputs,build/'client.txt'],'client') matched=base.compare(build/'client.txt',build/'rust.txt') if matched!=operations+len(fixtures):raise AssertionError('Incomplete input output') diff --git a/tools/test_state_provider_parity.py b/tools/test_state_provider_parity.py index 1cc74b2b3..9f7523273 100644 --- a/tools/test_state_provider_parity.py +++ b/tools/test_state_provider_parity.py @@ -309,7 +309,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStateProviderOracle.java' helpers=[oracle.with_name(name+'.java') for name in ['VanillaBlockStateCodecOracle','VanillaHeightmapOracle','VanillaMaterialConditionOracle','VanillaBiomeTemperatureOracle','VanillaAnchorOracle','VanillaBlockPropertiesOracle','VanillaBlockSupportOracle','VanillaBlockSurvivalOracle','VanillaCollisionOracle']] - sources=[oracle,*helpers,lab.ROOT/'tools/test_block_survival_parity.py',lab.ROOT/'tools/test_biome_temperature_parity.py',lab.ROOT/'tools/test_material_condition_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/state_provider_fixture.rs'] + sources=[oracle,*helpers,lab.ROOT/'tools/test_block_survival_parity.py',lab.ROOT/'tools/test_biome_temperature_parity.py',lab.ROOT/'tools/test_material_condition_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/state_provider_fixture.rs'] tested_sources=base.source_hashes(sources) environment={'minecraft':lock['minecraft']['version'],'manifest_sha1':lock['minecraft']['manifest_sha1'],'platform':platform.platform(),'java':subprocess.check_output(['java','--version'],text=True).splitlines()[0],'rustc':subprocess.check_output(['rustc','--version'],text=True).strip(),'dependencies':{str(path):lab.digest(path,'sha256') for path in [*jars.values(),*libraries]}} checkpoint=survival.load_checkpoint(checkpoint_path,tested_sources,environment) if args.resume else None @@ -371,9 +371,9 @@ def main(): output.write(json.dumps(fixture,separators=(',',':'))+'\n') fixture_count+=1;requested_samples+=len(fixture['states'])*fixture['repeats']*2 fixture_paths=[inputs,build/'survival-extra-definitions.json',build/'survival-placement-classes.json',build/'survival-support-tags.json',build/'survival-classes.json',build/'survival-rules.json',build/'cached-support.nbt',build/'support-cached-states.json',build/'block-properties.nbt',build/'cached-collision.nbt',build/'biomes.json',build/'biome_tags.json',build/'fluid-tags.json',build/'catalog.json',build/'providers.json',build/'tags.json',build/'facts-client.json',build/'facts-server.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','state_provider_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('state_provider_fixture.exe' if os.name=='nt' else 'state_provider_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') counts={'block_states':len(facts['states']),'blocks':len(facts['defaults']),'integer_properties':len(facts['integers']),'codec_inputs':fixture_count,'provider_types':10,'named_providers':len(catalog_resources),'rule_predicate_types':16,'survival_supported_blocks':len(survival_rules),'survival_supported_states':sum(s['id'] in survival_rules for s in facts['states']),'support_cached_states':len(support_states),'support_dynamic_states':len(facts['states'])-len(support_states),'biomes':len(biomes),'biome_tag_files':len(biome_tags),'fluid_tag_files':len(fluid_tags),'bundled_provider_definitions':len(provider_resources),'block_tag_files':len(tags),'requested_samples':requested_samples} base.ensure_sources_unchanged(sources,tested_sources) checkpoint={'schema':1,'environment':environment,'sources_sha256':tested_sources,'fixtures_sha256':{str(lab.ROOT/name):digest for name,digest in tested_fixtures.items()},'artifacts_sha256':{str(path):lab.digest(path,'sha256') for path in [binary,*sorted(classes.rglob('*.class'))]},'binary':str(binary),'counts':counts,'outputs':{}} @@ -386,7 +386,7 @@ def main(): checkpoint['outputs'][name]=lab.digest(output,'sha256') survival.save_checkpoint(checkpoint_path,checkpoint) print(f'{name}: completed output checkpointed',flush=True) - stage('rust',lambda:run([checkpoint['binary'],build],'rust'));references=[] + stage('rust',lambda:run([checkpoint['binary'],'state_provider_fixture',build],'rust'));references=[] for side,jar in jars.items(): stage(side,lambda:java(side,side,build));reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_status_effect_parity.py b/tools/test_status_effect_parity.py index 5c94af434..6f369c683 100644 --- a/tools/test_status_effect_parity.py +++ b/tools/test_status_effect_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStatusEffectOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/status_effect_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/status_effect_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaStatusEffectOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','status_effect_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('status_effect_fixture.exe' if os.name=='nt' else 'status_effect_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'status_effect_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_status_tick_parity.py b/tools/test_status_tick_parity.py index c14f72bf9..40786fe3c 100644 --- a/tools/test_status_tick_parity.py +++ b/tools/test_status_tick_parity.py @@ -47,7 +47,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStatusTickOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/status_tick_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/status_tick_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -58,10 +58,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaStatusTickOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','status_tick_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('status_tick_fixture.exe' if os.name=='nt' else 'status_tick_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'status_tick_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_stepped_interpolation_parity.py b/tools/test_stepped_interpolation_parity.py index 998d5a4ba..e5586c981 100644 --- a/tools/test_stepped_interpolation_parity.py +++ b/tools/test_stepped_interpolation_parity.py @@ -94,7 +94,7 @@ def main(): 'dev.horizonlab.parity.VanillaSteppedInterpolationOracle', str(events), str(build / 'vanilla.txt')], check=True) subprocess.run(['cargo', 'run', '--quiet', '--release', '-p', 'horizon-world', '--example', - 'stepped_interpolation_fixture', '--', str(events), str(build / 'rust.txt')], cwd=lab.ROOT, check=True) + 'probe', '--', 'stepped_interpolation_fixture', str(events), str(build / 'rust.txt')], cwd=lab.ROOT, check=True) matched = base.compare(build / 'vanilla.txt', build / 'rust.txt') print(f'Stepped interpolation parity passed: {matched} entity positions and rotations match vanilla') diff --git a/tools/test_stored_consume_parity.py b/tools/test_stored_consume_parity.py index e10a020ca..3ddfed86a 100644 --- a/tools/test_stored_consume_parity.py +++ b/tools/test_stored_consume_parity.py @@ -55,7 +55,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStoredConsumeOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/stored_consume_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/stored_consume_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -66,14 +66,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaStoredConsumeOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','stored_consume_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('stored_consume_fixture.exe' if os.name=='nt' else 'stored_consume_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';enriched_hash=base.source_hashes([enriched]) - run([binary,build,side],'rust-'+side) + run([binary,'stored_consume_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';rust_output=build/f'rust-{side}.txt';matched=base.compare(reference,rust_output) base.ensure_sources_unchanged([enriched],enriched_hash) tested_fixtures.update(enriched_hash);fixture_paths.append(enriched) diff --git a/tools/test_stored_effect_attributes_parity.py b/tools/test_stored_effect_attributes_parity.py index 3d3d0a543..2a8fe799d 100644 --- a/tools/test_stored_effect_attributes_parity.py +++ b/tools/test_stored_effect_attributes_parity.py @@ -83,7 +83,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStoredEffectAttributesOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/stored_effect_attributes_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/stored_effect_attributes_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -94,14 +94,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaStoredEffectAttributesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','stored_effect_attributes_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('stored_effect_attributes_fixture.exe' if os.name=='nt' else 'stored_effect_attributes_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';fixture_paths.append(enriched);tested_fixtures.update(base.source_hashes([enriched])) - run([binary,build,side],'rust-'+side) + run([binary,'stored_effect_attributes_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';candidate=build/f'rust-{side}.txt';matched=base.compare(reference,candidate) references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched,'rust_output_sha256':lab.digest(candidate,'sha256')}) print(f'{side}: {matched:,} stored effect attribute output lines match Rust',flush=True) diff --git a/tools/test_stored_effect_notifications_parity.py b/tools/test_stored_effect_notifications_parity.py index 82bcb65ad..6a0cee403 100644 --- a/tools/test_stored_effect_notifications_parity.py +++ b/tools/test_stored_effect_notifications_parity.py @@ -60,9 +60,9 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStoredEffectNotificationsOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/stored_effect_notifications_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/stored_effect_notifications_fixture.rs'] helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStoredEffectAttributesOracle.java' - sources.extend([helper,lab.ROOT/'crates/horizon-world/examples/stored_effect_attributes_fixture.rs',lab.ROOT/'tools/test_stored_effect_attributes_parity.py']) + sources.extend([helper,lab.ROOT/'crates/horizon-world/examples/probe/stored_effect_attributes_fixture.rs',lab.ROOT/'tools/test_stored_effect_attributes_parity.py']) tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -73,14 +73,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaStoredEffectNotificationsOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','stored_effect_notifications_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('stored_effect_notifications_fixture.exe' if os.name=='nt' else 'stored_effect_notifications_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';fixture_paths.append(enriched);tested_fixtures.update(base.source_hashes([enriched])) - run([binary,build,side],'rust-'+side) + run([binary,'stored_effect_notifications_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';candidate=build/f'rust-{side}.txt';matched=base.compare(reference,candidate) references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched,'rust_output_sha256':lab.digest(candidate,'sha256')}) print(f'{side}: {matched:,} stored effect notification output lines match Rust',flush=True) diff --git a/tools/test_structure_density_parity.py b/tools/test_structure_density_parity.py index 75094c3e6..ad15790e0 100644 --- a/tools/test_structure_density_parity.py +++ b/tools/test_structure_density_parity.py @@ -60,7 +60,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureDensityOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/structure_density_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/structure_density_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") tested_fixtures=base.source_hashes([inputs]);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -68,10 +68,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","structure_density_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("structure_density_fixture.exe" if os.name=="nt" else "structure_density_fixture") - run([binary,inputs,build/"rust.txt"],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"structure_density_fixture",inputs,build/"rust.txt"],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_subtitle_parity.py b/tools/test_subtitle_parity.py index 21b4c7175..1444bb5bd 100644 --- a/tools/test_subtitle_parity.py +++ b/tools/test_subtitle_parity.py @@ -11,7 +11,7 @@ it renders), the notification display time, the text background opacity and its "chat only" setting, and a GUI size. Each frame records the fills and texts in order with the pose: which subtitles show, their order, merging of repeats, expiry, the fade by age (looping sounds stay bright longer), the direction -arrows and the box width. `examples/subtitle_fixture` replays the cases through +arrows and the box width. `examples/probe/subtitle_fixture` replays the cases through `horizon_client::subtitles`; the frames must agree exactly. test_subtitle_parity.py [--count N] [--detail N] @@ -133,10 +133,10 @@ def main(): *(PARITY / f'{n}.java' for n in ('ParityFont', 'VanillaSubtitleOracle'))], 'compile-java') run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaSubtitleOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'subtitle_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('subtitle_fixture.exe' if os.name == 'nt' else 'subtitle_fixture') - run([binary, resources, inputs, build / 'rust.jsonl'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'subtitle_fixture',resources, inputs, build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text(encoding='utf-8').splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text(encoding='utf-8').splitlines()] assert len(vanilla) == len(rust) == len(chosen) diff --git a/tools/test_suffocation_parity.py b/tools/test_suffocation_parity.py index c9d8d37ec..ffe80b31f 100644 --- a/tools/test_suffocation_parity.py +++ b/tools/test_suffocation_parity.py @@ -42,7 +42,7 @@ def main(): sources = [oracle, *helpers, Path(__file__), lab.ROOT/'tools/test_rust_parity.py', lab.ROOT/'tools/test_worldgen_parity.py', lab.ROOT/'tools/lab.py', lab.ROOT/'Cargo.toml', lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-world/examples/suffocation_fixture.rs'] + lab.ROOT/'crates/horizon-world/examples/probe/suffocation_fixture.rs'] for crate in ['horizon-core', 'horizon-world']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml', *sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] @@ -72,10 +72,10 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'facts.json', 'definitions.json', 'block-registry.nbt', 'cached-collision.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'suffocation_fixture'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('suffocation_fixture.exe' if os.name=='nt' else 'suffocation_fixture') - run([binary, build], 'rust');references = [] + binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'suffocation_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) matched = base.compare(build/(side+'.txt'), build/'rust.txt') diff --git a/tools/test_swimming_parity.py b/tools/test_swimming_parity.py index d63ce66e1..574b72e5b 100644 --- a/tools/test_swimming_parity.py +++ b/tools/test_swimming_parity.py @@ -40,7 +40,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSwimmingOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/swimming_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/swimming_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -51,10 +51,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaSwimmingOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','swimming_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('swimming_fixture.exe' if os.name=='nt' else 'swimming_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'swimming_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_synced_bytes_parity.py b/tools/test_synced_bytes_parity.py index cc0024a1c..a6659bf21 100644 --- a/tools/test_synced_bytes_parity.py +++ b/tools/test_synced_bytes_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSyncedBytesOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/synced_bytes_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/synced_bytes_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaSyncedBytesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','synced_bytes_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('synced_bytes_fixture.exe' if os.name=='nt' else 'synced_bytes_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'synced_bytes_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_synced_floats_parity.py b/tools/test_synced_floats_parity.py index 768192ea2..fa7ca7132 100644 --- a/tools/test_synced_floats_parity.py +++ b/tools/test_synced_floats_parity.py @@ -50,7 +50,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSyncedFloatsOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/synced_floats_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/synced_floats_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -61,10 +61,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaSyncedFloatsOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','synced_floats_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('synced_floats_fixture.exe' if os.name=='nt' else 'synced_floats_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'synced_floats_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_tab_list_parity.py b/tools/test_tab_list_parity.py index cdf32df65..9b3c65605 100644 --- a/tools/test_tab_list_parity.py +++ b/tools/test_tab_list_parity.py @@ -10,12 +10,12 @@ them (upside-down Dinnerbone and Grumm) and whose real Scoreboard has the case's teams (colour, prefix, suffix), `list` objective (integer or hearts, number formats) and scores, with the header, footer, row background option and Hud ticks. It records every fill, text (as styled runs), sprite and -face blit. `examples/tab_list_fixture` lays out the same frames with +face blit. `examples/probe/tab_list_fixture` lays out the same frames with `horizon_client::tab_list`; the ordered call lists must agree. Downloaded skin images are compared too: VanillaSkinImageOracle decodes PNGs as NativeImage does and runs SkinTextureDownloader.processLegacySkin; -`examples/skin_image_fixture` runs `horizon_client::skins`. Pixels must agree. +`examples/probe/skin_image_fixture` runs `horizon_client::skins`. Pixels must agree. test_tab_list_parity.py [--count N] [--detail N] """ @@ -241,13 +241,13 @@ def main(): *(PARITY / f'{n}.java' for n in ('ParityData', 'ParityFont', 'VanillaTabListOracle', 'VanillaSkinImageOracle'))], 'compile-java') run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaTabListOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'tab_list_fixture', '--', - resources, inputs, build / 'rust.jsonl'], 'rust') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'tab_list_fixture', resources, inputs, build / 'rust.jsonl'], 'rust') images = build / 'skins.txt'; images.write_text(''.join(i + '\n' for i in skin_images(args.images))) run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaSkinImageOracle', images, build / 'vanilla-skins.txt'], 'vanilla-skins') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'skin_image_fixture', '--', - images, build / 'rust-skins.txt'], 'rust-skins') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'skin_image_fixture', images, build / 'rust-skins.txt'], 'rust-skins') vanilla_skins = (build / 'vanilla-skins.txt').read_text().splitlines() rust_skins = (build / 'rust-skins.txt').read_text().splitlines() assert len(vanilla_skins) == len(rust_skins) == args.images diff --git a/tools/test_team_rules_parity.py b/tools/test_team_rules_parity.py index af73aad10..5eb0c7d9d 100644 --- a/tools/test_team_rules_parity.py +++ b/tools/test_team_rules_parity.py @@ -9,7 +9,7 @@ EntitySelector.pushableBy predicate (collision rules), Entity.isInvisibleTo (name tag visibility, with a stand-in client for the viewer, camera and F1) on stand-in entities, for every combination of two teams' options, the three entities' teams (none, either team) and the flags involved. -`examples/team_rules_fixture` answers from `horizon_client::scoreboard`. +`examples/probe/team_rules_fixture` answers from `horizon_client::scoreboard`. test_team_rules_parity.py [--count N] """ @@ -84,10 +84,10 @@ def main(): PARITY / 'VanillaTeamRulesOracle.java'], 'compile-java') run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaTeamRulesOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'team_rules_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('team_rules_fixture.exe' if os.name == 'nt' else 'team_rules_fixture') - run([binary, inputs, build / 'rust.jsonl'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'team_rules_fixture',inputs, build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] assert len(vanilla) == len(rust) == len(chosen) diff --git a/tools/test_teleport_consume_parity.py b/tools/test_teleport_consume_parity.py index c24dda3a1..8f51361f8 100644 --- a/tools/test_teleport_consume_parity.py +++ b/tools/test_teleport_consume_parity.py @@ -43,7 +43,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTeleportConsumeOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/teleport_consume_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/teleport_consume_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -54,10 +54,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaTeleportConsumeOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','teleport_consume_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('teleport_consume_fixture.exe' if os.name=='nt' else 'teleport_consume_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'teleport_consume_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_terrain_parity.py b/tools/test_terrain_parity.py index 3bd4dbcc6..a818dcabb 100644 --- a/tools/test_terrain_parity.py +++ b/tools/test_terrain_parity.py @@ -75,7 +75,7 @@ def main(): exporter=oracle.with_name("VanillaHeightmapOracle.java") sources=[oracle,exporter,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock", lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/terrain_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/terrain_fixture.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -99,10 +99,10 @@ def main(): (build/"registries.json").write_text(json.dumps(bundle,separators=(",",":")),encoding="utf-8") fixture_paths=[inputs,build/"registries.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","terrain_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("terrain_fixture.exe" if os.name=="nt" else "terrain_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"terrain_fixture",build],"rust") references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_tick_parity.py b/tools/test_tick_parity.py index 4efcc93e9..47dd842d0 100644 --- a/tools/test_tick_parity.py +++ b/tools/test_tick_parity.py @@ -145,7 +145,7 @@ def main(): inputs.write_text("\n".join(commands) + "\n", encoding="utf-8") oracle = lab.ROOT / "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTickOracle.java" data_oracle = oracle.with_name("VanillaTickDataOracle.java") - sources = [oracle, data_oracle, Path(__file__).resolve(), lab.ROOT / "tools/test_rust_parity.py", lab.ROOT / "Cargo.toml", lab.ROOT / "Cargo.lock", lab.ROOT / "crates/horizon-core/Cargo.toml", lab.ROOT / "crates/horizon-world/Cargo.toml", *sorted((lab.ROOT / "crates/horizon-core/src").rglob("*.rs")), *sorted((lab.ROOT / "crates/horizon-world/src").rglob("*.rs")), lab.ROOT / "crates/horizon-world/examples/tick_fixture.rs"] + sources = [oracle, data_oracle, Path(__file__).resolve(), lab.ROOT / "tools/test_rust_parity.py", lab.ROOT / "Cargo.toml", lab.ROOT / "Cargo.lock", lab.ROOT / "crates/horizon-core/Cargo.toml", lab.ROOT / "crates/horizon-world/Cargo.toml", *sorted((lab.ROOT / "crates/horizon-core/src").rglob("*.rs")), *sorted((lab.ROOT / "crates/horizon-world/src").rglob("*.rs")), lab.ROOT / "crates/horizon-world/examples/probe/tick_fixture.rs"] tested_sources = test_rust_parity.source_hashes(sources) classes = base / "classes" classes.mkdir() @@ -163,9 +163,9 @@ def main(): completed.check_returncode() return completed.stdout data_java("server", "generate") - test_rust_parity.run(["cargo", "build", "--release", "-p", "horizon-world", "--example", "tick_fixture"]) - fixture = Path(metadata["target_directory"]) / "release/examples" / ("tick_fixture.exe" if os.name == "nt" else "tick_fixture") - test_rust_parity.run([str(fixture), str(base)]) + test_rust_parity.run(["cargo", "build", "--release", "-p", "horizon-world", "--example", "probe"]) + fixture = Path(metadata["target_directory"]) / "release/examples" / ("probe.exe" if os.name=="nt" else "probe") + test_rust_parity.run([str(fixture), "tick_fixture", str(base)]) references = [] for side, jar in jars.items(): reference = base / f"vanilla-{side}.txt" diff --git a/tools/test_trading_parity.py b/tools/test_trading_parity.py index 13ef60880..c26c449fb 100644 --- a/tools/test_trading_parity.py +++ b/tools/test_trading_parity.py @@ -184,7 +184,7 @@ def main(): lock, jars, libraries = base.verify_artifacts() resources = lab.RESOURCES oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTradingOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/trading_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/trading_fixture.rs', lab.ROOT / 'crates/horizon-client/src/merchant.rs', lab.ROOT / 'crates/horizon-client/src/menu.rs'] tested = base.source_hashes([s for s in sources if s.exists()]) inputs = build / 'inputs.txt' @@ -219,9 +219,9 @@ def main(): if args.java_only: print(f'{len(vanilla)} oracle lines') return - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'trading_fixture'], 'compile-rust') - binary = lab.cargo_target() / 'release/examples/trading_fixture' - run([binary, resources, inputs, build / 'server.txt', build / 'rust.txt'], 'rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') + binary = lab.cargo_target() / 'release/examples/probe' + run([binary, 'trading_fixture', resources, inputs, build / 'server.txt', build / 'rust.txt'], 'rust') rust = (build / 'rust.txt').read_text().splitlines() bad = [(a, b) for a, b in zip(vanilla, rust) if a != b] if bad or len(vanilla) != len(rust): diff --git a/tools/test_translucency_parity.py b/tools/test_translucency_parity.py index fcf8d3842..fff0390eb 100644 --- a/tools/test_translucency_parity.py +++ b/tools/test_translucency_parity.py @@ -52,7 +52,7 @@ def main(): lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTranslucencyOracle.java'], 'compile-java') vanilla, rust = build / 'vanilla.jsonl', build / 'rust.jsonl' run(['java', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaTranslucencyOracle', inputs, vanilla], 'vanilla') - run(['cargo', 'run', '--quiet', '--locked', '--profile', args.profile, '-p', 'horizon-client', '--example', 'translucency_fixture', '--', inputs, rust], 'rust') + run(['cargo', 'run', '--quiet', '--locked', '--profile', args.profile, '-p', 'horizon-client', '--example', 'probe', '--', 'translucency_fixture', inputs, rust], 'rust') expected = [json.loads(line) for line in vanilla.read_text().splitlines()] actual = [json.loads(line) for line in rust.read_text().splitlines()] assert len(expected) == len(actual), 'case count differs' diff --git a/tools/test_tree_feature_parity.py b/tools/test_tree_feature_parity.py index 66f7a6eb7..b3f9ace68 100644 --- a/tools/test_tree_feature_parity.py +++ b/tools/test_tree_feature_parity.py @@ -109,7 +109,7 @@ def main(): oracle=parity/'VanillaTreeFeatureOracle.java';exporter=parity/'VanillaSimpleBlockOracle.java' helpers=[parity/(name+'.java') for name in ['VanillaPlacementOracle','VanillaBlockSurvivalOracle','VanillaBlockPropertiesOracle','VanillaBlockSupportOracle','VanillaBlockStateCodecOracle','VanillaCollisionOracle','VanillaHeightmapOracle']] sources=[oracle,exporter,*helpers,Path(__file__),*[lab.ROOT/'tools'/name for name in ['test_block_survival_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock', - *sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/tree_feature_fixture.rs'] + *sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/tree_feature_fixture.rs'] tested_sources=base.source_hashes(sources);classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): with (build/(name+'.log')).open('w',encoding='utf-8') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=7200,stdout=log,stderr=subprocess.STDOUT) @@ -135,10 +135,10 @@ def main(): output.write(json.dumps(fixture,separators=(',',':'))+'\n');count+=1 fixtures=[inputs,*sorted(build.glob('*.nbt')),*[p for p in sorted(build.glob('*.json')) if p.name!='report.json']];tested_fixtures=fixture_hashes(fixtures) print(f'Prepared {count:,} feature fixtures',flush=True) - run(['cargo','build','--release','-p','horizon-world','--example','tree_feature_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('tree_feature_fixture.exe' if os.name=='nt' else 'tree_feature_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'tree_feature_fixture',build],'rust');references=[] for side,jar in jars.items(): java('VanillaTreeFeatureOracle',side,side,build);matched=base.compare(build/(side+'.txt'),build/'rust.txt');print(f'{side}: {matched:,} tree/ore output lines match Rust',flush=True) references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(build/(side+'.txt'),'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_trial_spawner_parity.py b/tools/test_trial_spawner_parity.py index 6fb79d9e1..bd6d69ac2 100644 --- a/tools/test_trial_spawner_parity.py +++ b/tools/test_trial_spawner_parity.py @@ -194,7 +194,7 @@ def main(): lock, jars, libraries = base.verify_artifacts() resources = lab.RESOURCES oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/natural_spawn_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/natural_spawn_fixture.rs', lab.ROOT / 'crates/horizon-client/src/mobs/trial_spawner.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawner.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawn_selection.rs', @@ -214,10 +214,10 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'natural_spawn_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/natural_spawn_fixture' - run([binary, resources, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples/probe' + run([binary, 'natural_spawn_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] if errors: diff --git a/tools/test_use_flag_reaction_parity.py b/tools/test_use_flag_reaction_parity.py index b52f0b868..de3b5fa20 100644 --- a/tools/test_use_flag_reaction_parity.py +++ b/tools/test_use_flag_reaction_parity.py @@ -49,7 +49,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaUseFlagReactionOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/use_flag_reaction_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/use_flag_reaction_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -60,10 +60,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaUseFlagReactionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','use_flag_reaction_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('use_flag_reaction_fixture.exe' if os.name=='nt' else 'use_flag_reaction_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'use_flag_reaction_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_use_remainder_parity.py b/tools/test_use_remainder_parity.py index 05b964325..853d12acb 100644 --- a/tools/test_use_remainder_parity.py +++ b/tools/test_use_remainder_parity.py @@ -48,7 +48,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaUseRemainderOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/use_remainder_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/use_remainder_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaUseRemainderOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','use_remainder_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('use_remainder_fixture.exe' if os.name=='nt' else 'use_remainder_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'use_remainder_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_value_provider_parity.py b/tools/test_value_provider_parity.py index f276e4f31..589a97632 100644 --- a/tools/test_value_provider_parity.py +++ b/tools/test_value_provider_parity.py @@ -66,7 +66,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaValueProviderOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/value_provider_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/value_provider_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -74,10 +74,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","value_provider_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("value_provider_fixture.exe" if os.name=="nt" else "value_provider_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"value_provider_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_vault_parity.py b/tools/test_vault_parity.py index 7eeace526..73c41e197 100644 --- a/tools/test_vault_parity.py +++ b/tools/test_vault_parity.py @@ -173,7 +173,7 @@ def main(): lock, jars, libraries = base.verify_artifacts() resources = lab.LOCAL / 'horizon-client/26.3' oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/natural_spawn_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/natural_spawn_fixture.rs', lab.ROOT / 'crates/horizon-client/src/vault.rs'] tested = base.source_hashes(sources) inputs = build / 'inputs.txt' @@ -190,10 +190,10 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'natural_spawn_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/natural_spawn_fixture' - run([binary, resources, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples/probe' + run([binary, 'natural_spawn_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] if errors: diff --git a/tools/test_view_direction_parity.py b/tools/test_view_direction_parity.py index 9dbb47de5..f2738dcff 100644 --- a/tools/test_view_direction_parity.py +++ b/tools/test_view_direction_parity.py @@ -47,7 +47,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaViewDirectionOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/view_direction_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/view_direction_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -58,10 +58,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaViewDirectionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','view_direction_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('view_direction_fixture.exe' if os.name=='nt' else 'view_direction_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'view_direction_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_water_splash_parity.py b/tools/test_water_splash_parity.py index b746b31c0..84f89d360 100644 --- a/tools/test_water_splash_parity.py +++ b/tools/test_water_splash_parity.py @@ -48,7 +48,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWaterSplashOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/water_splash_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/water_splash_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaWaterSplashOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','water_splash_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('water_splash_fixture.exe' if os.name=='nt' else 'water_splash_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'water_splash_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_world_border_parity.py b/tools/test_world_border_parity.py index 62aa58ddf..618194978 100644 --- a/tools/test_world_border_parity.py +++ b/tools/test_world_border_parity.py @@ -59,7 +59,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldBorderOracle.java' helper=oracle.with_name('VanillaFaceSupportOracle.java') - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/world_border_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/world_border_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -70,10 +70,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaWorldBorderOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','world_border_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('world_border_fixture.exe' if os.name=='nt' else 'world_border_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'world_border_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_world_border_render_parity.py b/tools/test_world_border_render_parity.py index 1a04a0de4..f8c88b6a6 100644 --- a/tools/test_world_border_render_parity.py +++ b/tools/test_world_border_render_parity.py @@ -103,8 +103,8 @@ def main(): PARITY / 'VanillaWorldBorderRenderOracle.java'], 'compile-java') run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaWorldBorderRenderOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'world_border_render_fixture', '--', - inputs, build / 'rust.jsonl'], 'rust') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'world_border_render_fixture', inputs, build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] assert len(vanilla) == len(rust) diff --git a/tools/test_world_collision_check_parity.py b/tools/test_world_collision_check_parity.py index d6f7e0bfb..3dae747d5 100644 --- a/tools/test_world_collision_check_parity.py +++ b/tools/test_world_collision_check_parity.py @@ -50,7 +50,7 @@ def main(): sources = [oracle, *helpers, Path(__file__), lab.ROOT/'tools/test_rust_parity.py', lab.ROOT/'tools/test_worldgen_parity.py', lab.ROOT/'tools/lab.py', lab.ROOT/'Cargo.toml', lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-world/examples/registry_collision_scan_fixture.rs'] + lab.ROOT/'crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs'] for crate in ['horizon-core', 'horizon-world']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml', *sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] @@ -80,10 +80,10 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'facts.json', 'definitions.json', 'block-registry.nbt', 'cached-collision.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'registry_collision_scan_fixture'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('registry_collision_scan_fixture.exe' if os.name=='nt' else 'registry_collision_scan_fixture') - run([binary, build], 'rust');references = [] + binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'registry_collision_scan_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) matched = base.compare(build/(side+'.txt'), build/'rust.txt') diff --git a/tools/test_world_edge_backoff_parity.py b/tools/test_world_edge_backoff_parity.py index bf4c39c70..10cf1316f 100644 --- a/tools/test_world_edge_backoff_parity.py +++ b/tools/test_world_edge_backoff_parity.py @@ -51,7 +51,7 @@ def main(): sources = [oracle, *helpers, Path(__file__), lab.ROOT/'tools/test_rust_parity.py', lab.ROOT/'tools/test_worldgen_parity.py', lab.ROOT/'tools/lab.py', lab.ROOT/'Cargo.toml', lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-world/examples/registry_collision_scan_fixture.rs'] + lab.ROOT/'crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs'] for crate in ['horizon-core', 'horizon-world']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml', *sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] @@ -81,10 +81,10 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'facts.json', 'definitions.json', 'block-registry.nbt', 'cached-collision.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'registry_collision_scan_fixture'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('registry_collision_scan_fixture.exe' if os.name=='nt' else 'registry_collision_scan_fixture') - run([binary, build], 'rust');references = [] + binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'registry_collision_scan_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) matched = base.compare(build/(side+'.txt'), build/'rust.txt') diff --git a/tools/test_world_movement_parity.py b/tools/test_world_movement_parity.py index e01a989f5..5a583ecb7 100644 --- a/tools/test_world_movement_parity.py +++ b/tools/test_world_movement_parity.py @@ -76,7 +76,7 @@ def main(): sources = [oracle, *helpers, Path(__file__), lab.ROOT/'tools/test_rust_parity.py', lab.ROOT/'tools/test_worldgen_parity.py', lab.ROOT/'tools/lab.py', lab.ROOT/'Cargo.toml', lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-world/examples/registry_collision_scan_fixture.rs'] + lab.ROOT/'crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs'] for crate in ['horizon-core', 'horizon-world']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml', *sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] @@ -106,10 +106,10 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'facts.json', 'definitions.json', 'block-registry.nbt', 'cached-collision.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'registry_collision_scan_fixture'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('registry_collision_scan_fixture.exe' if os.name=='nt' else 'registry_collision_scan_fixture') - run([binary, build], 'rust');references = [] + binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'registry_collision_scan_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) matched = base.compare(build/(side+'.txt'), build/'rust.txt') diff --git a/tools/test_world_parity.py b/tools/test_world_parity.py index 802dc3884..e2781866e 100644 --- a/tools/test_world_parity.py +++ b/tools/test_world_parity.py @@ -51,12 +51,12 @@ def main(): print("Generating vanilla world-data fixtures...", flush=True) print(java("server", "generate").split("HORIZON_WORLD_GENERATED")[-1].strip(), flush=True) - run(["cargo", "build", "--release", "-p", "horizon-world", "--bin", "horizon-world", "--example", "world_fixture"], base / "compile-rust.log") + run(["cargo", "build", "--release", "-p", "horizon-world", "--bin", "horizon-world", "--example", "probe"], base / "compile-rust.log") metadata = json.loads(run(["cargo", "metadata", "--no-deps", "--format-version", "1"])) target = Path(metadata["target_directory"]) / "release" suffix = ".exe" if os.name == "nt" else "" binary = target / ("horizon-world" + suffix) - run([target / "examples" / ("world_fixture" + suffix), base], base / "rust-fixture.log") + run([target / "examples" / ("probe" + suffix), "world_fixture", base], base / "rust-fixture.log") for network in [False, True]: kind = "network" if network else "nbt" output = base / "rust" / kind diff --git a/tools/test_world_ray_parity.py b/tools/test_world_ray_parity.py index 93f2dfcef..87189d611 100644 --- a/tools/test_world_ray_parity.py +++ b/tools/test_world_ray_parity.py @@ -49,7 +49,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldRayOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/world_ray_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/world_ray_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -60,10 +60,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaWorldRayOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','world_ray_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('world_ray_fixture.exe' if os.name=='nt' else 'world_ray_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'world_ray_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_world_spawn_parity.py b/tools/test_world_spawn_parity.py index 9b495c3dc..f73da3a8c 100644 --- a/tools/test_world_spawn_parity.py +++ b/tools/test_world_spawn_parity.py @@ -29,6 +29,10 @@ Seeds: the player report's seed (1891623539983467248: Horizon spawned at -48 -48, vanilla at 152 145), the chunk generation harness's seeds and --random seeds from a fixed generator. +tools/parity.py runs it in PARITY_SHARDS parts, each creating the worlds of +every PARITY_SHARDS-th seed: each seed is a vanilla and a Horizon server start, +~15 s, and 60 seeds in one run were the longest harness (~25 min). + usage: test_world_spawn_parity.py [--random N] [--jobs N] [--origins-only] """ import argparse @@ -43,16 +47,18 @@ from concurrent.futures import ThreadPoolExecutor from pathlib import Path try: - from . import anvil_dump, lab, oracle_harness as oh, test_rust_parity as base + from . import anvil_dump, lab, oracle_harness as oh, parity_shard, test_rust_parity as base from .test_dedicated_server_parity import Server, free_port except ImportError: import anvil_dump import lab import oracle_harness as oh + import parity_shard import test_rust_parity as base from test_dedicated_server_parity import Server, free_port NAME = 'world-spawn-parity' +PARITY_SHARDS = 4 REPORT = 1891623539983467248 SEEDS = [REPORT, 12345, -7046029254386353131, 987654321987, 4242, -1, 0x5DEECE66D, 20260607, 777, 0] RESOURCES = lab.RESOURCES @@ -73,7 +79,7 @@ def origins(build, classes, dependencies, all_seeds): vanilla_out = build / 'origins-vanilla.txt' oh.run_logged(['java', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaWorldSpawnOracle', vanilla_out, *all_seeds], build, 'origins-vanilla') - rust = subprocess.run([target_dir() / 'examples/spawn_origin', RESOURCES, *map(str, all_seeds)], + rust = subprocess.run([target_dir() / 'examples/probe', 'spawn_origin', RESOURCES, *map(str, all_seeds)], capture_output=True, text=True, check=True, cwd=lab.ROOT).stdout vanilla = vanilla_out.read_text() parse = lambda text: {int(l.split()[0]): tuple(map(int, l.split()[1:])) for l in text.splitlines() if l} @@ -107,7 +113,7 @@ def main(): parser.add_argument('--seed', type=int, action='append', help='only these seeds (repeatable)') args = parser.parse_args() lock, jars, libraries = base.verify_artifacts() - build = lab.LOCAL / NAME + build = lab.LOCAL / NAME / parity_shard.label() # shards run at once build.mkdir(parents=True, exist_ok=True) dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) classes = build / 'classes' @@ -115,8 +121,8 @@ def main(): oh.run_logged(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-cp', dependencies, '-d', classes, lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldSpawnOracle.java'], build, 'compile-java') - oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'spawn_origin'], build, 'compile-probe') - all_seeds = args.seed or seeds(args.random) + oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'probe'], build, 'compile-probe') + all_seeds = parity_shard.shard(args.seed or seeds(args.random)) started = time.time() vanilla, rust = origins(build, classes, dependencies, all_seeds) diff --git a/tools/test_worldgen_random_parity.py b/tools/test_worldgen_random_parity.py index 7b2d37a6f..29eedfa49 100644 --- a/tools/test_worldgen_random_parity.py +++ b/tools/test_worldgen_random_parity.py @@ -44,7 +44,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldgenRandomOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/worldgen_random_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/worldgen_random_fixture.rs'] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) @@ -53,10 +53,10 @@ def main(): with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','worldgen_random_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('worldgen_random_fixture.exe' if os.name=='nt' else 'worldgen_random_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'worldgen_random_fixture',build],'rust');references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependency_path]),'dev.horizonlab.parity.VanillaWorldgenRandomOracle',side,build],side) reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/upgrade_world.py b/tools/upgrade_world.py index 9db5e4517..5f42988f1 100755 --- a/tools/upgrade_world.py +++ b/tools/upgrade_world.py @@ -9,7 +9,6 @@ level.dat, player and data/*.dat files) is applied exactly. The original is kept upgrade_world.py SOURCE_WORLD DEST_WORLD """ import shutil -import socket import subprocess import sys import tempfile @@ -24,12 +23,6 @@ ROOT = Path(__file__).resolve().parent.parent SERVER = lab.GAME / 'jars' / 'server.jar' -def free_port(): - with socket.socket() as s: - s.bind(('127.0.0.1', 0)) - return s.getsockname()[1] - - def main(): if len(sys.argv) != 3: sys.exit(__doc__) @@ -42,7 +35,7 @@ def main(): scratch = Path(scratch) (scratch / 'eula.txt').write_text('eula=true\n') (scratch / 'server.properties').write_text( - f'level-name=world\nonline-mode=false\nserver-port={free_port()}\n') + f'level-name=world\nonline-mode=false\nserver-port={lab.free_port()}\n') shutil.copytree(source, scratch / 'world') # The server upgrades at startup, then keeps running as a normal server: stop it # once it reports "Done". diff --git a/tools/vanilla_client.py b/tools/vanilla_client.py index 64eb82691..2cdfeec21 100644 --- a/tools/vanilla_client.py +++ b/tools/vanilla_client.py @@ -14,12 +14,10 @@ that skips the first-run screens, keeps the game running unfocused and renders few chunks, so a harness can drive it with vscreen keys. """ import argparse -import hashlib import json import os import subprocess import sys -import uuid import zipfile from pathlib import Path @@ -56,13 +54,6 @@ if sys.platform == "darwin": OPTIONS["enableVsync"] = "false" -def offline_uuid(name): - digest = bytearray(hashlib.md5(("OfflinePlayer:" + name).encode()).digest()) - digest[6] = (digest[6] & 0x0F) | 0x30 - digest[8] = (digest[8] & 0x3F) | 0x80 - return uuid.UUID(bytes=bytes(digest)) - - def host_library(path): name = Path(path).name if "natives-" in name: @@ -127,7 +118,7 @@ def command(args): f"-Djava.library.path={natives}", f"-Dorg.lwjgl.system.SharedLibraryExtractPath={natives}", f"-Dio.netty.native.workdir={natives}", "-cp", os.pathsep.join(map(str, jars)), "net.minecraft.client.main.Main", - "--username", args.name, "--uuid", offline_uuid(args.name).hex, + "--username", args.name, "--uuid", lab.offline_uuid(args.name).hex, "--accessToken", "0", "--offlineDeveloperMode", "--version", lab.VERSION, "--gameDir", str(args.game_dir), "--assetsDir", str(assets), "--assetIndex", json.loads((GAME / "manifest.json").read_text())["assetIndex"]["id"], diff --git a/tools/vanilla_login.py b/tools/vanilla_login.py index fa2664c9d..ecc9715b4 100644 --- a/tools/vanilla_login.py +++ b/tools/vanilla_login.py @@ -11,12 +11,10 @@ its log reports the position it read, and console commands such as `data get entity NAME` can inspect the loaded player meanwhile. """ import argparse -import hashlib import socket import struct import sys import time -import uuid import zlib try: @@ -25,27 +23,9 @@ except ImportError: import lab -def offline_uuid(name): - digest = bytearray(hashlib.md5(('OfflinePlayer:' + name).encode()).digest()) - digest[6] = (digest[6] & 0x0F) | 0x30 - digest[8] = (digest[8] & 0x3F) | 0x80 - return uuid.UUID(bytes=bytes(digest)) - - -def varint(v): - out = b'' - v &= 0xFFFFFFFF - while True: - b = v & 0x7F - v >>= 7 - out += bytes([b | (0x80 if v else 0)]) - if not v: - return out - - def string(s): data = s.encode() - return varint(len(data)) + data + return lab.varint(len(data)) + data class Connection: @@ -73,44 +53,33 @@ class Connection: return value def send(self, packet_id, payload=b''): - body = varint(packet_id) + payload + body = lab.varint(packet_id) + payload if self.threshold >= 0: if len(body) >= self.threshold: - body = varint(len(body)) + zlib.compress(body) + body = lab.varint(len(body)) + zlib.compress(body) else: - body = varint(0) + body - self.sock.sendall(varint(len(body)) + body) + body = lab.varint(0) + body + self.sock.sendall(lab.varint(len(body)) + body) def receive(self): length = self.read_varint() body = self.read_exact(length) if self.threshold >= 0: - pos, size = parse_varint(body, 0) + pos, size = lab.parse_varint(body, 0) body = zlib.decompress(body[pos:]) if size else body[pos:] - pos, packet_id = parse_varint(body, 0) + pos, packet_id = lab.parse_varint(body, 0) return packet_id, body[pos:] -def parse_varint(data, pos): - value = shift = 0 - while True: - b = data[pos] - pos += 1 - value |= (b & 0x7F) << shift - shift += 7 - if not b & 0x80: - return pos, value - - def join(host, port, name, seconds): c = Connection(host, port) - c.send(0, varint(lab.version_info()['protocol_version']) + string(host) + struct.pack('>H', port) + varint(2)) - c.send(0, string(name) + offline_uuid(name).bytes) + c.send(0, lab.varint(lab.version_info()['protocol_version']) + string(host) + struct.pack('>H', port) + lab.varint(2)) + c.send(0, string(name) + lab.offline_uuid(name).bytes) # Login: compression, then login finished. while True: pid, data = c.receive() if pid == 3: - c.threshold = parse_varint(data, 0)[1] + c.threshold = lab.parse_varint(data, 0)[1] elif pid == 2: break elif pid == 0: @@ -119,7 +88,7 @@ def join(host, port, name, seconds): while True: pid, data = c.receive() if pid == 15: # select known packs: claim none, receive full registries - c.send(7, varint(0)) + c.send(7, lab.varint(0)) elif pid == 4: # keep alive c.send(4, data) elif pid == 5: # ping @@ -153,7 +122,7 @@ def main(): p.add_argument('--uuid', action='store_true') args = p.parse_args() if args.uuid: - print(offline_uuid(args.name)) + print(lab.offline_uuid(args.name)) return 0 join(args.host, args.port, args.name, args.seconds) return 0 diff --git a/tools/vanilla_world_check.py b/tools/vanilla_world_check.py index 1bbc64004..317b7e998 100644 --- a/tools/vanilla_world_check.py +++ b/tools/vanilla_world_check.py @@ -17,12 +17,16 @@ load failures. import argparse import os import re -import socket import subprocess import sys import threading import time +try: + from . import lab +except ImportError: + import lab + SUSPICIOUS = re.compile( r'(ERROR|login failed|Exception|Couldn\'t load|Failed to|Skipping|Invalid|Unknown|corrupt|' r'Recreating|upgrad|DataFix|out of bounds|missing|Mismatch)', re.IGNORECASE) @@ -31,12 +35,6 @@ BENIGN = re.compile(r'(Unpacking |OFFLINE/INSECURE|online-mode|authenticate user r'Failed to load properties|Failed to load eula)') -def free_port(): - with socket.socket() as s: - s.bind(('127.0.0.1', 0)) - return s.getsockname()[1] - - def main(): p = argparse.ArgumentParser() p.add_argument('--jar', required=True) @@ -48,7 +46,7 @@ def main(): p.add_argument('--wait-after', type=float, default=1.0) p.add_argument('--timeout', type=float, default=240) args = p.parse_args() - port = args.port or free_port() + port = args.port or lab.free_port() os.makedirs(args.dir, exist_ok=True) with open(os.path.join(args.dir, 'eula.txt'), 'w') as f: f.write('eula=true\n')