Merge pull request #1453 from ludovic111/feat/world-probe-binary

🤖 Agent: merged after verify passed, with local proof: all 217 world harnesses ran on main and on the branch and their transcripts were diffed (203 byte-identical, the rest only timings or known run-to-run counts). 168 world examples become one probe binary, with 1,097 duplicated helper lines and 11 dead examples gone.
This commit is contained in:
Ludovic Marie
2026-10-23 22:15:44 +02:00
committed by GitHub
370 changed files with 2044 additions and 4670 deletions
@@ -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<T> = horizon_client::Result<T>;
fn tag(value: &Value) -> Result<Tag> {
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::<Result<_>>()?),
Value::Object(o) => Tag::Compound(
o.iter()
.map(|(k, v)| Ok((k.as_str().into(), tag(v)?)))
.collect::<Result<_>>()?,
),
_ => return Err("registry value".into()),
})
}
fn registry(root: &Path) -> Result<BlockRegistry> {
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::<Result<_>>()?,
),
),
("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, &registry)?;
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<f64> {
let start = Instant::now();
let facts = black_box(BlockFacts::load(black_box(root), black_box(&registry))?);
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::<Result<Vec<_>>>()?;
println!("samples_ms={times:.3?}");
times.sort_by(f64::total_cmp);
println!("median_ms={:.3}", times[times.len() / 2]);
}
Ok(())
}
@@ -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 <client resource dir> [--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<T> = std::result::Result<T, Box<dyn std::error::Error>>;
fn main() -> Result<()> {
let args: Vec<String> = 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<Option<Proto>> = (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<Chunk> = 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<Arc<Chunk>> = 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<Arc<Chunk>>; 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(&region);
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<Chunk> = 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<Arc<Chunk>> = 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<Arc<Chunk>>; 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(&region);
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(())
}
@@ -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<Vertex>) {
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::<Vertex, u8>(&retained),
bytemuck::cast_slice::<Vertex, u8>(&fresh)
);
assert_eq!(
(retained.as_ptr(), retained.capacity()),
(pointer, capacity)
);
}
assert_eq!(
bytemuck::cast_slice::<Vertex, u8>(&retained),
bytemuck::cast_slice::<Vertex, u8>(&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::<Vertex>(),
fresh[5],
reused[5],
fresh[5] / reused[5],
paired_speedups[5],
paired_speedups[0],
paired_speedups[10]
);
}
}
@@ -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<T> = horizon_client::Result<T>;
#[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<String, Value>);
reader!(catalog_facts, BTreeMap<String, Value>);
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Result<Self> {
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<T: PartialEq + Debug>(
label: &str,
path: &Path,
repetitions: usize,
read: impl Fn(&Path, Reader) -> Result<T>,
) -> 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<f64>; 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::<BTreeMap<_, _>>(),
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::<serde_json::Error>().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::<std::io::Error>().unwrap().kind(),
std::io::ErrorKind::NotFound
);
}
Ok(())
}
}
-144
View File
@@ -1,144 +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<dyn std::error::Error>> {
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<String> = 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,
border: &horizon_client::worldborder::WorldBorder::default(),
};
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));
}
}
@@ -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<T> = std::result::Result<T, Box<dyn std::error::Error>>;
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<String> = 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<usize> {
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::<std::io::Result<_>>()?;
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::<usize>()})
);
// 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(())
}
@@ -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<T> = std::result::Result<T, Box<dyn std::error::Error>>;
fn main() -> Result<()> {
let args: Vec<String> = 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<ChunkRecord> = tags
.iter()
.map(|tag| ChunkRecord::from_nbt(tag, Compression::Zlib, 0, Limits::default()))
.collect::<std::io::Result<_>>()?;
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::<usize>() / 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(())
}
@@ -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<i64, Vec<String>> {
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<String> = 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<i64, Vec<u8>> {
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<i64, Vec<u8>>,
sy: i64,
i: usize,
sky: bool,
empty: bool,
top: i64,
) -> u8 {
let nibble = |a: &Vec<u8>, 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<String> = 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<ChunkPos> = 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(&region, &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<Tag> {
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)
}
@@ -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<T> = std::result::Result<T, Box<dyn std::error::Error>>;
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::<Vec<_>>();
Some((fields[11].parse::<f64>().ok()? + fields[12].parse::<f64>().ok()?) / 100.0)
})
.unwrap_or(0.0)
}
#[derive(Default)]
struct Phase {
updates: Vec<f64>,
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<String> = 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(())
}
@@ -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<Key>,
}
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]
);
}
}
@@ -512,9 +512,9 @@ fn run<R: RandomSource>(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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
let side = std::env::args().nth(2).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -304,9 +304,9 @@ fn run(f: Value, out: &mut dyn Write) {
w.all(&s);
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
let side = std::env::args().nth(2).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -18,8 +18,8 @@ fn anchor(
a.to_json().unwrap_or_else(|_| "error".to_owned())
)
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -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<Item = &'a Modifier>, 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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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<dyn std::error::Error>> {
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<dyn std::error::Error>> {
),
"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"),
@@ -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<A: TestAttributes> 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<A: TestAttributes>(dir: &Path, output: &str) -> Result<(), Box<dyn std::e
"packed {}",
w.health
.take_dirty()
.map(|v| format!("{:08x}", bits(v)))
.map(|v| format!("{:08x}", f32_bits(v)))
.unwrap_or_else(|| "none".into())
)
.map_err(HealthError::Observer),
@@ -275,13 +269,13 @@ fn run<A: TestAttributes>(dir: &Path, output: &str) -> Result<(), Box<dyn std::e
writeln!(
w.observer.out,
"state {:08x} {} {} {:08x} {} {:08x} {:08x} {} {}",
bits(w.health.value()),
f32_bits(w.health.value()),
w.health.is_dirty(),
w.health.is_default(),
bits(w.absorption),
f32_bits(w.absorption),
food.food,
bits(food.saturation),
bits(food.exhaustion),
f32_bits(food.saturation),
f32_bits(food.exhaustion),
food.timer,
w.observer.calls
)?;
@@ -304,10 +298,10 @@ fn run<A: TestAttributes>(dir: &Path, output: &str) -> Result<(), Box<dyn std::e
Ok(())
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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::<Live>(dir, "rust-live.txt")
} else {
run::<EntityAttributes>(dir, "rust.txt")
@@ -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<dyn std::error::Error>> {
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<dyn std::error::Error>> {
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
integration::run()
}
@@ -625,9 +625,9 @@ fn run(f: Value, out: &mut dyn Write) {
w.all(&s);
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
let side = std::env::args().nth(2).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -156,8 +156,8 @@ fn fixture(
writeln!(out, "tail {}", random.next_long())?;
Ok(())
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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);
@@ -20,8 +20,8 @@ fn biome_key(id: &i32) -> Option<&str> {
_ => Some("horizon:other"),
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -20,8 +20,8 @@ use std::{
fn n(v: &Value) -> i32 {
v.as_i64().unwrap() as i32
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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<String, String> = serde_json::from_value(bundle["noises"].clone())?;
@@ -150,8 +150,8 @@ fn fixture(
writeln!(world.out, "tail {}", random.next_long())?;
Ok(())
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -26,8 +26,8 @@ fn normalized(value: Value) -> Value {
value => value,
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = crate::args().nth(1).expect("private fixture directory");
let dir = Path::new(&arg);
let read = |name: &str| -> Result<BTreeMap<String, String>, Box<dyn std::error::Error>> {
Ok(serde_json::from_str(&fs::read_to_string(
@@ -29,8 +29,8 @@ impl DensitySampler for Erosion {
}
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -68,8 +68,8 @@ fn operations(worker: &mut BiomeTemperature, ops: &Value, out: &mut impl Write)
}
Ok(())
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -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<Item = f64>,
) -> 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<W: Write> BlockCollisionWorld for World<W> {
Ok(self.palette[block.state.0 as usize].shape.clone())
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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"),
@@ -72,8 +72,8 @@ fn pending(tag: Option<&Tag>) -> String {
}
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = std::env::args().collect();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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::<i64>::new(position);
@@ -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<bool> {
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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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<Tag, Box<dyn std::error::Error>> {
@@ -20,8 +20,8 @@ fn bbox(v: &Value) -> Aabb {
.collect::<Vec<_>>();
Aabb::new(Vec3::new(v[0], v[1], v[2]), Vec3::new(v[3], v[4], v[5]))
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = crate::args().nth(1).expect("private fixture directory");
let dir = Path::new(&arg);
let read = |name: &str| -> Result<Tag, Box<dyn std::error::Error>> {
Ok(
@@ -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<VoxelShape, Box<dyn std::error::Error>> {
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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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([
@@ -9,8 +9,8 @@ use std::{
io::{self, Write},
path::Path,
};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = crate::args().nth(1).expect("private fixture directory");
let dir = Path::new(&arg);
let read = |name: &str| -> Result<Tag, Box<dyn std::error::Error>> {
Ok(
@@ -103,8 +103,8 @@ impl<W: Write> SurvivalWorld for World<'_, W> {
Ok(self.neighbors[old as usize % self.neighbors.len()])
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = crate::args().nth(1).expect("private fixture directory");
let dir = Path::new(&arg);
let read = |name: &str| -> Result<Tag, Box<dyn std::error::Error>> {
Ok(
@@ -191,8 +191,8 @@ fn summary(level: &Cells, before: &HashMap<BlockPos, BlockStateId>, out: &mut St
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut args = std::env::args().skip(1);
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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");
@@ -117,8 +117,8 @@ impl BlockingItemDamageWorld for World<'_> {
Ok(self.flag("server"))
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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<dyn std::error::Error>> {
)?;
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)?;
@@ -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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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"))?)?;
@@ -69,8 +69,8 @@ fn maximum(v: &Value) -> Option<i32> {
fn fraction(f: Fraction) -> String {
format!("{}/{}", f.numerator(), f.denominator())
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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 +82,8 @@ fn fixture(
writeln!(out, "tail {}", random.next_long())?;
Ok(())
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -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<Vec<String>>,
@@ -47,8 +41,8 @@ impl CarverOutput for Output<'_> {
Ok(())
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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<dyn std::error::Error>> {
};
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
},
@@ -9,8 +9,8 @@ use std::{
fn n(v: &Value) -> i32 {
v.as_i64().unwrap() as i32
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -82,8 +82,8 @@ fn fixture(
writeln!(out, "tail {}", random.next_long())?;
Ok(())
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -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<dyn std::error::Error + Send + Sync>;
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")?);
@@ -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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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"))?)?;
@@ -4,8 +4,8 @@ use std::{
fs,
io::{self, Write},
};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = std::env::args().collect();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = crate::args().collect();
let mut out = io::BufWriter::new(fs::File::create(&args[2])?);
writeln!(
out,
@@ -69,8 +69,8 @@ impl ClimbingWorld for World<'_> {
self.last = Some(p);
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = crate::args().nth(1).unwrap();
let dir = Path::new(&arg);
let registry = BlockRegistry::from_nbt(
&nbt::read_named(
@@ -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<Item = f64>,
) -> 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<W: Write> PowderSnowWorld for RegistryWorld<'_, W> {
Ok(self.feet.is_item("minecraft:leather_boots"))
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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(
@@ -56,12 +56,8 @@ impl Input<'_> {
Vec3::new(self.number(), self.number(), self.number())
}
}
fn main() -> Result<(), Box<dyn Error>> {
let base = PathBuf::from(
std::env::args()
.nth(1)
.ok_or("fixture directory required")?,
);
pub fn main() -> Result<(), Box<dyn Error>> {
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(),
@@ -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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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<dyn std::error::Error>> {
};
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")?,
}
@@ -135,8 +135,8 @@ impl DurabilityWorld for World<'_> {
writeln!(self.out, "copy-after {}", snapshot(&copy))
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -88,8 +88,8 @@ fn snapshot(
maps[1] == maps[2]
)
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -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<R: RandomSource> ItemParticleWorld<u8, u8, i32> 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<R: RandomSource>(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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -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<R: RandomSource> ItemParticleWorld<u8, u8, Component> 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<R: RandomSource> 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<R: RandomSource>(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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -206,8 +206,8 @@ fn run<R: RandomSource>(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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -91,8 +91,8 @@ impl ImmunityWorld for Env<'_> {
self.query("loaded", "loaded")
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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"))?);
@@ -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<i32> {
self.query("armor")?;
@@ -115,8 +109,8 @@ impl DamageReductionWorld for World<'_> {
Ok(0.0)
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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<dyn std::error::Error>> {
} 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,
@@ -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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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"))?)?,
@@ -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<String> = env::args().skip(1).collect();
pub fn main() -> ExitCode {
let args: Vec<String> = 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::<i32>().ok()),
@@ -102,8 +102,8 @@ impl<W: Write> PlacementContext for World<'_, W> {
.is_some_and(|steps| steps.iter().flatten().any(|id| *id == feature)))
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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"))?);
@@ -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<std::process::ExitCode> {
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<String> {
let mut args: Vec<String> = std::env::args().collect();
if args.len() > 1 {
args.remove(1);
}
args.into_iter()
}
pub fn main(names: &[&str], run: fn(&str) -> Option<ExitCode>) -> ExitCode {
let name = std::env::args().nth(1).unwrap_or_default();
run(&name).unwrap_or_else(|| {
eprintln!(
"usage: probe <name> [arguments...]\nprobes: {}",
names.join(" ")
);
ExitCode::from(2)
})
}
@@ -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<Item = f64>,
) -> 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<W: Write> PistonCollisionWorld for World<'_, W> {
.map_err(io::Error::other)
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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"]
@@ -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<bool> {
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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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<dyn std::error::Error>> {
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")?,
};
@@ -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<Stop>) -> &'static str {
Error::World(Stop::Duplicate) => "duplicate",
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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<dyn std::error::Error>> {
}
"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(())
}
_ => {
@@ -494,9 +494,9 @@ fn run(f: Value, out: &mut dyn Write) {
w.all(&s);
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
let side = std::env::args().nth(2).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -330,8 +330,8 @@ impl EffectSyncWorld<Key> for World<'_> {
sync::update_invisibility(s, self)
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = std::env::args().collect();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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)?;
@@ -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<f64, LookupError>) -> 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<f64, LookupError>) ->
),
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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<dyn std::error::Error>> {
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(),
@@ -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<Item = f64>,
) -> 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<W: Write> EntityCollisionWorld for World<'_, W> {
&& source.is_none_or(|id| self.entities[id.0 as usize - 1].root != entity.root))
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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<dyn std::error::Error>> {
@@ -446,7 +438,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
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<dyn std::error::Error>> {
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<dyn std::error::Error>> {
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<dyn std::error::Error>> {
"tick {} {} {:016x}",
tick.touch,
tick.first,
bits(tick.fall)
f64_bits(tick.fall)
)?;
}
}
@@ -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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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<dyn std::error::Error>> {
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() {
@@ -69,8 +69,8 @@ fn bbox(v: &Value) -> Aabb {
Vec3::new(values[3], values[4], values[5]),
)
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -392,8 +392,8 @@ impl AfterUseWorld<usize, u8, Component> for World {
c.apply(self, original)
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -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<f64> {
.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<Item = f64>,
) -> 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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -12,8 +12,8 @@ use std::{
io::{BufRead, BufReader, BufWriter, Write},
path::Path,
};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let path = std::env::args().nth(1).ok_or("private fixture directory")?;
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
let path = crate::args().nth(1).ok_or("private fixture directory")?;
let dir = Path::new(&path);
let read = |name: &str| -> Result<Tag, Box<dyn std::error::Error>> {
Ok(
@@ -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<BlockPos> {
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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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<dyn std::error::Error>> {
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)?;
@@ -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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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| {
@@ -161,8 +161,8 @@ fn fixture(
writeln!(out, "tail {}", random.next_long())?;
Ok(())
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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);
@@ -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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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"))?)?;
@@ -7,8 +7,8 @@ use std::{
io::{self, Write},
path::Path,
};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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([
@@ -91,8 +91,8 @@ impl BoatFluidBoxWorld for World<'_> {
self.boat
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -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<W: Write> 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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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([
@@ -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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -67,8 +67,8 @@ impl FluidOccupancyWorld for World<'_, '_> {
Ok(self.min + self.height - 1)
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = crate::args().nth(1).unwrap();
let dir = Path::new(&arg);
let registry = BlockRegistry::from_nbt(
&nbt::read_named(
@@ -34,8 +34,8 @@ impl FluidHeightWorld for World<'_> {
panic!("ray shape does not use camera immersion support")
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -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<f32> {
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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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<dyn std::error::Error>> {
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<dyn std::error::Error>> {
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)?;
@@ -160,8 +160,8 @@ fn run<R: RandomSource>(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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -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<Tag> {
let value = &v["value"];
Some(match v["type"].as_i64().unwrap() {
@@ -49,8 +43,8 @@ fn tag(v: &Value) -> Option<Tag> {
_ => panic!("tag type"),
})
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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<dyn std::error::Error>> {
"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<dyn std::error::Error>> {
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<dyn std::error::Error>> {
"roundtrip {} {} {:08x} {:08x}",
food.food,
food.timer,
bits(food.saturation),
bits(food.exhaustion)
f32_bits(food.saturation),
f32_bits(food.exhaustion)
)?;
}
Ok(())
@@ -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<BlockPos> {
if v.is_null() {
None
@@ -33,8 +27,8 @@ fn position(v: &Value) -> Option<BlockPos> {
))
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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<dyn std::error::Error>> {
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;
@@ -33,8 +33,8 @@ fn fixture(
writeln!(out, "tail {}", random.next_long())?;
Ok(())
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -187,8 +187,8 @@ fn fixture(
}
Ok(())
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let directory = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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"))?)?;
@@ -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<VoxelShape, Box<dyn std::error::Error>> {
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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).expect("private fixture directory");
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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<Tag, Box<dyn std::error::Error>> {
@@ -131,12 +125,12 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
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<dyn std::error::Error>> {
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,
@@ -218,8 +218,8 @@ impl horizon_world::inventory_pickup::PickupHooks<u8, usize, i32> for World {
Ok(self.op["infinite"].as_bool().unwrap())
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -149,8 +149,8 @@ impl InventoryTickWorld<u8, u8, i32> for World {
Ok(())
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -230,8 +230,8 @@ impl UseServices<usize, u8, bool> for Services {
self.event(view, state, &format!("synced {id}"))
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -295,8 +295,8 @@ impl StartServices<usize, u8, bool> for Services {
self.kinetic_count = 0;
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -277,8 +277,8 @@ impl AfterUseWorld<usize, u8, Component> for World {
c.apply(self, original)
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {
@@ -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<Vec3> {
(!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<u64>,
@@ -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<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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<dyn std::error::Error>> {
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)?;
@@ -130,8 +130,8 @@ impl CooldownUser for User<'_> {
self.book.add(group(&stack), ticks, self.events)
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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 +82,8 @@ impl DurabilityWorld for World<'_> {
self.event(s, "break")
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
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() {

Some files were not shown because too many files have changed in this diff Show More