From 60fc787288ab5d5ebf89cacb61b72b3c4151094b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 20:24:55 +0200 Subject: [PATCH 001/408] Java shader packs: Photon, Chocapic13' and MakeUp Ultra Fast load The translator now legalises what these packs write and naga refuses: lookups without a level outside fragment shaders become textureLod at level 0; struct varyings travel as one varying per field; textureGather is emulated with texelFetch; a bool given to a numeric constructor becomes cond ? 1 : 0; `const in` parameters lose the const; array fields of private structs get their natural stride (naga lays every struct out as std140); modf into a vector component assigns it instead of passing a pointer. shaders.properties keeps the empty lines the preprocessor leaves, so Photon's `) \` before `#else` ends its value. real_packs_load now also parses every translated program again as WGSL, which is what wgpu is given. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/java_pack.rs | 22 ++ crates/horizon-shaderpack/src/properties.rs | 26 +- crates/horizon-shaderpack/src/translate.rs | 339 ++++++++++++++++++- crates/horizon-shaderpack/tests/translate.rs | 72 ++++ docs/shader-packs.md | 15 +- 5 files changed, 468 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/java_pack.rs b/crates/horizon-client/src/java_pack.rs index a5bc2904e..e6bd28c7f 100644 --- a/crates/horizon-client/src/java_pack.rs +++ b/crates/horizon-client/src/java_pack.rs @@ -180,6 +180,24 @@ mod tests { assert_eq!(vendor_name(0, "Apple M4 Pro"), "Apple"); } + /// wgpu is given the WGSL text: it must parse again. + fn reparse_error(pack: &JavaPasses) -> Option { + let passes = pack + .folders + .iter() + .flat_map(|f| f.passes.iter().chain(&f.final_pass)); + passes + .flat_map(|p| [(p, &p.vertex, "vsh"), (p, &p.fragment, "fsh")]) + .find_map(|(p, t, ext)| { + let e = naga::front::wgsl::parse_str(&t.wgsl).err()?; + Some(format!( + "{}.{ext}: {}", + p.pass.program, + e.emit_to_string(&t.wgsl) + )) + }) + } + /// The packs in `HORIZON_TEST_SHADERPACKS` (folders or zips) load as the /// game loads them, with their default options: the compatibility table /// of docs/shader-packs.md. Skipped when the variable isn't set. @@ -199,6 +217,10 @@ mod tests { for path in entries { let name = path.file_name().unwrap().to_string_lossy().into_owned(); match load(&path, &BTreeMap::new(), "Apple", "Apple M4 Pro") { + Ok(pack) if let Some(e) = reparse_error(&pack) => { + println!("{name}: {e}"); + failures.push(name); + } Ok(pack) => { let folders: Vec = pack .folders diff --git a/crates/horizon-shaderpack/src/properties.rs b/crates/horizon-shaderpack/src/properties.rs index 3c6ee251c..703d696cf 100644 --- a/crates/horizon-shaderpack/src/properties.rs +++ b/crates/horizon-shaderpack/src/properties.rs @@ -199,8 +199,11 @@ pub fn preprocess( let (start, end) = (token.location.start, token.location.end); let at = line_of(start); if at > line { + // Lines the preprocessor left empty stay empty lines, so a value + // continued with `\` before an `#else` (Photon's + // `moon_phase_brightness`) ends there, as in Iris. if line > 0 { - out.push('\n'); + out.extend(std::iter::repeat_n('\n', at - line)); } line = at; } else if last_end != Some(start) { @@ -747,7 +750,26 @@ b = 1 }; let values = OptionValues::default(); let out = preprocess(text, &env, &set, &values).unwrap(); - assert_eq!(out, "a = 0.75\nb = 1\n"); + let lines: Vec<&str> = out.lines().filter(|l| !l.is_empty()).collect(); + assert_eq!(lines, ["a = 0.75", "b = 1"]); + // Photon ends an `#if`'d value with `) \` before `#else`: the value + // stops at the empty line the directive leaves. + let text = "\ +#if FOG == 0 +a = if( \\ + moonPhase == 0, 1.0, \\ + 2.0 \\ +) \\ +#else +a = 1.0 +#endif + +b = 2 +"; + let out = preprocess(text, &env, &set, &values).unwrap(); + let parsed = Properties::parse(&out); + assert_eq!(parsed.get("a"), Some("if( moonPhase == 0, 1.0, 2.0 ) ")); + assert_eq!(parsed.get("b"), Some("2")); assert_eq!( jcpp_condition("#elif FOG == 0.75 && X > 2.5", &set, &values), "#elif 0 == 0 && X > 2" diff --git a/crates/horizon-shaderpack/src/translate.rs b/crates/horizon-shaderpack/src/translate.rs index 8a32795af..184185cdb 100644 --- a/crates/horizon-shaderpack/src/translate.rs +++ b/crates/horizon-shaderpack/src/translate.rs @@ -364,9 +364,10 @@ pub fn translate( stage: naga_stage, defines: Default::default(), }; - let module = naga::front::glsl::Frontend::default() + let mut module = naga::front::glsl::Frontend::default() .parse(&options, &glsl) .map_err(|e| first_lines(&e.emit_to_string(&glsl)))?; + unpad_private_arrays(&mut module); let info = naga::valid::Validator::new( naga::valid::ValidationFlags::all(), naga::valid::Capabilities::all(), @@ -491,6 +492,79 @@ fn negative_constant(e: &ast::Expr) -> bool { } } +/// naga's GLSL front end lays every struct out as std140, so an array field +/// of a struct that never reaches a buffer (Photon's ACES spline parameters, +/// `float[6]`) gets a stride of 16, and constructing it from a `float[6](..)` +/// (stride 4) fails validation. Give such fields their natural stride. +fn unpad_private_arrays(module: &mut naga::Module) { + use naga::TypeInner as T; + let mut shared = HashSet::new(); + let mut stack: Vec<_> = module + .global_variables + .iter() + .filter(|(_, v)| { + matches!( + v.space, + naga::AddressSpace::Uniform + | naga::AddressSpace::Storage { .. } + | naga::AddressSpace::Immediate + ) + }) + .map(|(_, v)| v.ty) + .collect(); + while let Some(ty) = stack.pop() { + if !shared.insert(ty) { + continue; + } + match &module.types[ty].inner { + T::Struct { members, .. } => stack.extend(members.iter().map(|m| m.ty)), + T::Array { base, .. } | T::BindingArray { base, .. } => stack.push(*base), + _ => {} + } + } + let mut layouter = naga::proc::Layouter::default(); + if layouter.update(module.to_ctx()).is_err() { + return; + } + let structs: Vec<_> = module + .types + .iter() + .filter(|(h, t)| !shared.contains(h) && matches!(t.inner, T::Struct { .. })) + .map(|(h, _)| h) + .collect(); + for ty in structs { + let mut new = module.types[ty].clone(); + let T::Struct { members, .. } = &mut new.inner else { + continue; + }; + let mut changed = false; + for m in members.iter_mut() { + let T::Array { base, size, stride } = module.types[m.ty].inner else { + continue; + }; + let natural = layouter[base].to_stride(); + if stride != natural { + let span = module.types.get_span(m.ty); + m.ty = module.types.insert( + naga::Type { + name: None, + inner: T::Array { + base, + size, + stride: natural, + }, + }, + span, + ); + changed = true; + } + } + if changed { + module.types.replace(ty, new); + } + } +} + fn first_lines(s: &str) -> String { s.lines().take(8).collect::>().join("\n") } @@ -506,6 +580,8 @@ enum Local { struct Legaliser<'a> { stage: Stage, link: &'a mut Link, + /// Struct types declared so far: their fields (type, name, array). + structs: HashMap>, interface: Interface, /// Global samplers: name → combined type. /// Sampler uniforms: their combined type and sampler variable. @@ -532,6 +608,8 @@ struct Legaliser<'a> { /// helpers go in. modulo: bool, nan: bool, + /// `textureGather` was used: [`GATHER`] is added. + gather: bool, /// Constants turned into globals ([`needs_runtime`]). runtime_constants: HashSet, } @@ -548,6 +626,94 @@ fn call(name: &str, args: Vec) -> ast::Expr { .into_node() } +/// `textureGather(sampler2D, uv, comp)`: component `comp` of the four texels +/// bilinear filtering at `uv` would blend, in GL's order, read with +/// `texelFetch` (edges clamped). +const GATHER: &str = "\ +vec4 iris_gather(texture2D t, sampler s, vec2 uv, int c) { + ivec2 hi = textureSize(sampler2D(t, s), 0) - 1; + ivec2 i = ivec2(floor(uv * vec2(hi + 1) - 0.5)); + vec4 a = texelFetch(sampler2D(t, s), clamp(i + ivec2(0, 1), ivec2(0), hi), 0); + vec4 b = texelFetch(sampler2D(t, s), clamp(i + ivec2(1, 1), ivec2(0), hi), 0); + vec4 d = texelFetch(sampler2D(t, s), clamp(i + ivec2(1, 0), ivec2(0), hi), 0); + vec4 e = texelFetch(sampler2D(t, s), clamp(i, ivec2(0), hi), 0); + return vec4(a[c], b[c], d[c], e[c]); +} +"; + +/// GL converts a `bool` given to a numeric constructor (`vec3(r < radius)`, +/// Photon's sun disc); naga refuses. A comparison or logical expression +/// passed to one becomes `(cond ? 1.0 : 0.0)` (or `1`/`1u`). +fn bool_to_number(e: &mut ast::Expr) { + use ast::BinaryOpData as B; + let ast::ExprData::FunCall(f, args) = &mut e.content else { + return; + }; + let Some(name) = callee(f) else { return }; + let base = name.trim_start_matches('d'); + let (one, zero) = if base.starts_with("ivec") || name == "int" { + (ast::ExprData::IntConst(1), ast::ExprData::IntConst(0)) + } else if base.starts_with("uvec") || name == "uint" { + (ast::ExprData::UIntConst(1), ast::ExprData::UIntConst(0)) + } else if base.starts_with("vec") || base.starts_with("mat") || name == "float" { + ( + ast::ExprData::FloatConst(1.0), + ast::ExprData::FloatConst(0.0), + ) + } else { + return; + }; + for a in args.iter_mut() { + let boolean = match &a.content { + ast::ExprData::Binary(op, ..) => matches!( + op.content, + B::Or | B::Xor | B::And | B::Equal | B::NonEqual | B::Lt | B::Gt | B::Lte | B::Gte + ), + ast::ExprData::Unary(op, _) => op.content == ast::UnaryOpData::Not, + _ => false, + }; + if boolean { + let cond = std::mem::replace(a, var("_")); + *a = ast::ExprData::Ternary( + Box::new(cond), + Box::new(one.clone().into_node()), + Box::new(zero.clone().into_node()), + ) + .into_node(); + } + } +} + +/// Outside fragment shaders there are no derivatives, so GL samples level 0 +/// where `texture` and its kin would pick one; naga refuses them there (the +/// vertex programs of Chocapic13', MakeUp and Bliss). Turn them into their +/// `Lod` forms at level 0 (a bias is dropped), also inside `vec4(..)` as +/// legacy shadow lookups are wrapped. +fn explicit_lod(e: &mut ast::Expr) { + let ast::ExprData::FunCall(f, args) = &mut e.content else { + return; + }; + let Some(name) = callee(f) else { return }; + if name == "vec4" && args.len() == 1 { + return explicit_lod(&mut args[0]); + } + // (implicit, explicit, where the level goes, how many arguments without a bias) + let (lod, at, plain) = match name.as_str() { + "texture" => ("textureLod", 2, 2), + "textureProj" => ("textureProjLod", 2, 2), + "textureOffset" => ("textureLodOffset", 2, 3), + "textureProjOffset" => ("textureProjLodOffset", 2, 3), + _ => return, + }; + if args.len() < plain { + return; + } + args.truncate(plain); + let zero = ast::ExprData::FloatConst(0.0).into_node(); + args.insert(at, zero); + *f = ast::FunIdentifierData::Expr(Box::new(var(lod))).into_node(); +} + /// The name a call is made by: a function, or a constructor's type. fn callee(f: &ast::FunIdentifier) -> Option { match &f.content { @@ -713,6 +879,7 @@ impl<'a> Legaliser<'a> { Self { stage, link, + structs: HashMap::new(), interface: Interface::default(), samplers: HashMap::new(), sampler_vars: HashSet::new(), @@ -728,6 +895,7 @@ impl<'a> Legaliser<'a> { constant: false, modulo: false, nan: false, + gather: false, runtime_constants: HashSet::new(), } } @@ -812,6 +980,25 @@ impl<'a> Legaliser<'a> { } fn global_list(&mut self, list: &mut ast::InitDeclaratorList) -> Result { + if let ast::TypeSpecifierNonArrayData::Struct(st) = &list.head.ty.ty.ty.content + && let Some(name) = &st.name + { + let fields = st + .fields + .iter() + .flat_map(|f| { + let ty = type_text(&f.ty); + f.identifiers.iter().map(move |i| { + ( + ty.clone(), + i.ident.as_str().to_owned(), + array_text(&i.array_spec), + ) + }) + }) + .collect(); + self.structs.insert(name.as_str().to_owned(), fields); + } let qualifier = list.head.ty.qualifier.clone(); let storage = storage(&qualifier); let has = |s: ast::StorageQualifierData| storage.contains(&s); @@ -934,6 +1121,24 @@ impl<'a> Legaliser<'a> { "out" }; let interp = interpolation(&qualifier); + if varying + && ty_array.is_empty() + && let Some(fields) = self.structs.get(&ty).cloned() + { + // The struct global stays where it is declared (after its + // type), without its qualifiers; its fields travel. + for (name, array) in &names { + if array.is_empty() { + self.struct_varying(dir, &interp, &ty, name, fields.clone()); + } else { + self.errors.push(format!( + "varying {name}: arrays of structs are not supported" + )); + } + } + list.head.ty.qualifier = None; + return Ok(true); + } let explicit = layout_ids(&qualifier) .into_iter() .find(|(k, _)| k == "location") @@ -1061,6 +1266,73 @@ impl<'a> Legaliser<'a> { } } + /// A struct varying (Photon's `CloudsParameters`): a varying per field, + /// matrix column or array element, copied from or into a private global + /// of the struct type. + fn struct_varying( + &mut self, + dir: &str, + interp: &str, + ty: &str, + name: &str, + fields: Vec<(String, String, String)>, + ) { + let _ = ty; + for (field_ty, field, array) in fields { + let count: Option = array + .strip_prefix('[') + .and_then(|a| a.strip_suffix(']')) + .and_then(|n| n.parse().ok()); + let element = format!("{name}.{field}"); + let parts: Vec<(String, String, String)> = match (matrix_columns(&field_ty), count) { + (None, None) if !self.structs.contains_key(&field_ty) => { + vec![(format!("{name}#{field}"), field_ty.clone(), element)] + } + (Some((cols, column)), None) => (0..cols) + .map(|c| { + ( + format!("{name}#{field}#{c}"), + column.clone(), + format!("{element}[{c}]"), + ) + }) + .collect(), + (None, Some(n)) if matrix_columns(&field_ty).is_none() => (0..n) + .map(|e| { + ( + format!("{name}#{field}#{e}"), + field_ty.clone(), + format!("{element}[{e}]"), + ) + }) + .collect(), + _ => { + self.errors.push(format!( + "varying {name}: field {field} ({field_ty}{array}) is not supported" + )); + return; + } + }; + for (key, part_ty, element) in parts { + let at = Link::location(&mut self.link.varyings, &key); + let part = key.replace('#', "_iris_"); + let flat = if is_integer(&part_ty) && !interp.contains("flat") { + "flat " + } else { + "" + }; + self.header.push(format!( + "layout(location = {at}) {flat}{interp}{dir} {part_ty} {part};" + )); + if dir == "out" { + self.epilogue.push(format!("{part} = {element};")); + } else { + self.prologue.push(format!("{element} = {part};")); + } + } + } + } + fn sized(&mut self, list: &mut ast::InitDeclaratorList) { let head_ty = list.head.ty.ty.clone(); let head = &mut list.head.content; @@ -1117,7 +1389,23 @@ impl<'a> Legaliser<'a> { } let mut locals = Vec::new(); let mut params = Vec::with_capacity(p.parameters.len()); - for param in std::mem::take(&mut p.parameters) { + for mut param in std::mem::take(&mut p.parameters) { + // `const in float x` (Bliss): naga's front end takes no `const` + // on parameters, and it changes nothing for the caller. + match &mut param.content { + ast::FunctionParameterDeclarationData::Named(q, _) + | ast::FunctionParameterDeclarationData::Unnamed(q, _) => { + if let Some(list) = q { + list.qualifiers.retain(|q| { + !matches!(&q.content, ast::TypeQualifierSpecData::Storage(s) + if s.content == ast::StorageQualifierData::Const) + }); + if list.qualifiers.is_empty() { + *q = None; + } + } + } + } let (ty, name) = match ¶m.content { ast::FunctionParameterDeclarationData::Named(_, d) => { (type_text(&d.ty), Some(d.ident.ident.as_str().to_owned())) @@ -1544,12 +1832,56 @@ impl<'a> Legaliser<'a> { self.nan = true; return; } + if name == "textureGather" + && (2..=3).contains(&args.len()) + && let ast::ExprData::FunCall(g, inner) = &args[0].content + && inner.len() == 2 + && callee(g).as_deref() == Some("sampler2D") + { + // naga's GLSL front end has no `textureGather`. + let mut call_args = inner.clone(); + call_args.push(args[1].clone()); + call_args.push( + args.get(2) + .cloned() + .unwrap_or_else(|| ast::ExprData::IntConst(0).into_node()), + ); + *e = call("iris_gather", call_args); + self.gather = true; + return; + } + if name == "modf" + && args.len() == 2 + && !matches!(args[1].content, ast::ExprData::Variable(_)) + { + // `modf(x, v.y)` (Photon): WGSL can't point at a vector + // component, so no `out` parameter: `(v.y = trunc(x), x - trunc(x))`. + let (x, whole) = (args[0].clone(), args[1].clone()); + let assign = ast::ExprData::Assignment( + Box::new(whole), + ast::AssignmentOpData::Equal.into_node(), + Box::new(call("trunc", vec![x.clone()])), + ) + .into_node(); + let fraction = ast::ExprData::Binary( + ast::BinaryOpData::Sub.into_node(), + Box::new(x.clone()), + Box::new(call("trunc", vec![x])), + ) + .into_node(); + *e = ast::ExprData::Comma(Box::new(assign), Box::new(fraction)).into_node(); + return; + } if let Some((_, new)) = LEGACY_CALLS.iter().find(|(old, _)| *old == name) { *f = ast::FunIdentifierData::Expr(Box::new(var(new))).into_node(); } else if let Some((_, new)) = SHADOW_CALLS.iter().find(|(old, _)| *old == name) { let args = std::mem::take(args); *e = call("vec4", vec![call(new, args)]); } + if self.stage != Stage::Fragment { + explicit_lod(e); + } + bool_to_number(e); } /// The legalised source: header, the rewritten program, then a `main` @@ -1586,6 +1918,9 @@ impl<'a> Legaliser<'a> { if self.modulo { out.push_str(&modulo_helpers()); } + if self.gather { + out.push_str(GATHER); + } if self.nan { out.push_str("float iris_sqrt(float x) { return sqrt(x); }\n"); } diff --git a/crates/horizon-shaderpack/tests/translate.rs b/crates/horizon-shaderpack/tests/translate.rs index 3c71d8546..f34c90520 100644 --- a/crates/horizon-shaderpack/tests/translate.rs +++ b/crates/horizon-shaderpack/tests/translate.rs @@ -331,6 +331,78 @@ void main() { reparse(&fs.wgsl).unwrap(); } +/// What Photon, Chocapic13', MakeUp Ultra Fast and Bliss write and GL takes: +/// lookups without a level in a vertex shader, a struct passed between +/// stages, `textureGather`, a `bool` given to `vec3(..)`, `const in` +/// parameters and an array field in a struct built by its constructor. +#[test] +fn legalises_what_photon_and_chocapic_write() { + let mut link = Link::default(); + let header = "uniform sampler2D colortex0; +uniform sampler2DShadow shadowtex0; +struct Clouds { float coverage; vec2 wind; mat3 turn; int layers; }; +"; + let vs = run( + Stage::Vertex, + &format!( + "{header}flat varying Clouds clouds; +void main() {{ + clouds.coverage = texture2D(colortex0, vec2(0.5)).r + shadow2D(shadowtex0, vec3(0.5)).r; + clouds.wind = textureOffset(colortex0, vec2(0.5), ivec2(1, 0), 2.0).rg; + clouds.turn = mat3(1.0); + clouds.layers = 2; + gl_Position = ftransform(); +}} +" + ), + &mut link, + ) + .unwrap(); + for wanted in [ + "textureLod(sampler2D(colortex0_t", + "vec2(0.5), 0.)", + "textureLodOffset(sampler2D(colortex0_t", + "clouds_iris_coverage = clouds.coverage;", + "clouds_iris_turn_iris_1 = clouds.turn[1];", + ] { + assert!(vs.glsl.contains(wanted), "{wanted}\n{}", vs.glsl); + } + reparse(&vs.wgsl).unwrap(); + let fs = run( + Stage::Fragment, + &format!( + "{header}flat varying Clouds clouds; +struct Spline {{ float slope; float[3] coeffs; }}; +float edge(const in float x, const float r) {{ return float(x < r); }} +void main() {{ + const Spline spline = Spline(0.0, float[3](1.0, 2.0, 3.0)); + vec4 four = textureGather(colortex0, vec2(0.5), 1); + vec3 disc = vec3(clouds.coverage < 0.5); + vec2 cell = vec2(0.0); + float part = modf(clouds.coverage * 4.0, cell.y); + gl_FragColor = vec4(disc * edge(four.x, spline.coeffs[1]), clouds.wind.x + float(clouds.layers) + part + cell.y); +}} +" + ), + &mut link, + ) + .unwrap(); + for wanted in [ + "iris_gather(colortex0_t", + "clouds.coverage = clouds_iris_coverage;", + "float edge(in float x, float r)", + "cell.y = trunc(", + ] { + assert!(fs.glsl.contains(wanted), "{wanted}\n{}", fs.glsl); + } + reparse(&fs.wgsl).unwrap(); + // The vertex program's outputs are the fragment program's inputs. + assert_eq!( + io(&vs, true).get("clouds_iris_wind"), + io(&fs, false).get("clouds_iris_wind") + ); +} + /// A fragment output narrower than its four-channel target (Steadfast's /// `final` writes `out vec3 color`) is written through a `vec4` with alpha 1: /// GL fills the missing channels, wgpu refuses the pipeline. diff --git a/docs/shader-packs.md b/docs/shader-packs.md index 2e8d231aa..3b3a47189 100644 --- a/docs/shader-packs.md +++ b/docs/shader-packs.md @@ -397,10 +397,12 @@ and screenshotted. Only full-screen passes run (above), so no pack has its own t | Complementary Unbound | r5.8 | loads: 27 passes | | | Sildur's Vibrant Extreme | 2.02 | drawn: 18 passes, only its sky (above) | | | Steadfast | 0.8.0 | drawn: 3 passes | | -| Bliss | 2.1.2 | fails | `world0/deferred.vsh`: an operation naga forbids in a vertex shader | +| Chocapic13' | V9 High | drawn: 16 passes, its grade and fog over Horizon's world | | +| MakeUp Ultra Fast | 9.6 | drawn: 6 passes; its fog covers everything without its `gbuffers_*` | | +| Photon | v1.4 | loads: 27 passes; draws black: it lights the scene from the G-buffer its `gbuffers_*` write | | +| Bliss | 2.1.2 | fails | `world0/composite1.fsh`: a vector component passed to an `inout` parameter (WGSL can't point at one) | | Bloop | 1.8.0-Alpha-3 | fails | `world0/prepare1.fsh`: `mat2(vec4)` and other constructors naga's GLSL front end refuses | | Noble | v1.9.9 | fails (Apple and NVIDIA) | `world0/deferred4.vsh`: a `vec3[9][9]` varying (nested arrays between stages) | -| Photon | v1.4 | fails | `world0/prepare.vsh`: a struct varying (`CloudsParameters`) | | Rethinking Voxels | r0.1-beta9 | fails | `world0/prepare.fsh`: `1 << 31` overflows naga's constant folding; it also needs images | What the translator does for these packs, as Iris (JCPP and its GLSL transformer) does: @@ -418,6 +420,15 @@ What the translator does for these packs, as Iris (JCPP and its GLSL transformer (`mix`, `?:`, `smoothstep`) becomes a global set at the start of `main`, `sqrt` of a negative constant is evaluated at run time, and a fragment output narrower than four channels (`out vec3`, Steadfast's `final`) is written through a `vec4` with alpha 1 as OpenGL fills it. +- **What GL takes and naga doesn't** (Photon, Chocapic13', MakeUp Ultra Fast, Bliss): `texture2D` and its kin without a + level outside fragment shaders sample level 0 (`textureLod`); a struct passed between stages travels as one varying + per field (matrices by column, arrays by element); `textureGather` reads the four texels with `texelFetch`; a + `bool` given to `vec3(..)` and other numeric constructors becomes `cond ? 1.0 : 0.0`; `const in` parameters lose + the `const`; an array field of a struct that never reaches a buffer gets its natural stride (naga lays every struct + out as std140, so `Spline(.., float[6](..))` didn't match); `modf` into a vector component assigns it instead of + passing a pointer. +- **Every translated program parses again as WGSL** in `real_packs_load`: wgpu is given the text, and naga's WGSL + writer can emit what its WGSL parser refuses (`&v.y`). ### Order to implement From 91d89b4abfdac7a1664854aa008efdc9c19e2c3a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 20:56:08 +0200 Subject: [PATCH 002/408] Java shader packs: modf into a vector component works in an initialiser The comma form of modf (`v.y = trunc(x), x - trunc(x)`) printed without brackets in a declaration's initialiser, which naga's GLSL front end then read as a second declarator. A unary + around it has glsl-lang print the brackets. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-shaderpack/src/translate.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/horizon-shaderpack/src/translate.rs b/crates/horizon-shaderpack/src/translate.rs index 184185cdb..e53b4895b 100644 --- a/crates/horizon-shaderpack/src/translate.rs +++ b/crates/horizon-shaderpack/src/translate.rs @@ -1855,7 +1855,9 @@ impl<'a> Legaliser<'a> { && !matches!(args[1].content, ast::ExprData::Variable(_)) { // `modf(x, v.y)` (Photon): WGSL can't point at a vector - // component, so no `out` parameter: `(v.y = trunc(x), x - trunc(x))`. + // component, so no `out` parameter: `+(v.y = trunc(x), x - trunc(x))` + // (the unary `+` has the comma printed in brackets, also in an + // initialiser). let (x, whole) = (args[0].clone(), args[1].clone()); let assign = ast::ExprData::Assignment( Box::new(whole), @@ -1869,7 +1871,9 @@ impl<'a> Legaliser<'a> { Box::new(call("trunc", vec![x])), ) .into_node(); - *e = ast::ExprData::Comma(Box::new(assign), Box::new(fraction)).into_node(); + let comma = ast::ExprData::Comma(Box::new(assign), Box::new(fraction)).into_node(); + *e = ast::ExprData::Unary(ast::UnaryOpData::Add.into_node(), Box::new(comma)) + .into_node(); return; } if let Some((_, new)) = LEGACY_CALLS.iter().find(|(old, _)| *old == name) { From 6a58fc20dadaeed3e0e0af151c5b8ad59ca84c60 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 21:50:37 +0200 Subject: [PATCH 003/408] Java shader packs: the pack's gbuffers_terrain and gbuffers_water draw the terrain When a Java pack has a terrain program (gbuffers_terrain, or the program Iris falls back to), Horizon's world pass skips its own terrain and the pack's program draws every visible section into its render targets, tested against the depth of the rest of the world; gbuffers_water draws the translucent layer before the first composite with the pack's blend modes. depthtex0/depthtex1 get the depth before and after water. - translate: a geometry mode (group 2, attributes as globals a glue function fills before main, alpha test) and a pass that ends switch cases which return, which naga's WGSL writer otherwise rejects (Photon). - java_terrain: the glue decoding Horizon's terrain vertices from the arena pages into Iris's attributes, the block.properties id table by sprite name, and a 2D atlas built from the sprite arrays (animated sprites copied in). - RGBA16/RG16/R16 targets are 16-bit unorm where the GPU renders them: Chocapic13' packs its G-buffer into them. MakeUp Ultra Fast, Chocapic13' and BSL draw their own terrain and water on the M4 Pro; Photon still draws black (compute and .dat textures). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/Cargo.toml | 2 +- .../horizon-client/src/game/shader_packs.rs | 7 +- crates/horizon-client/src/gfx.rs | 213 ++++- crates/horizon-client/src/gfx/arena.rs | 9 +- crates/horizon-client/src/gfx/flat.rs | 10 + crates/horizon-client/src/gfx/java_stages.rs | 818 ++++++++++++++++-- crates/horizon-client/src/gfx/java_terrain.rs | 645 ++++++++++++++ crates/horizon-client/src/java_pack.rs | 162 +++- crates/horizon-shaderpack/src/lib.rs | 16 + crates/horizon-shaderpack/src/pipeline.rs | 107 ++- crates/horizon-shaderpack/src/properties.rs | 88 ++ crates/horizon-shaderpack/src/translate.rs | 157 +++- crates/horizon-shaderpack/tests/translate.rs | 91 +- docs/shader-packs.md | 48 +- 14 files changed, 2245 insertions(+), 128 deletions(-) create mode 100644 crates/horizon-client/src/gfx/java_terrain.rs diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 48e2e57d4..33e383907 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -84,4 +84,4 @@ workspace = true [dev-dependencies] # Every WGSL shader translated as wgpu's DirectX 12 backend does (gfx.rs tests). -naga = { version = "30.0.1", features = ["wgsl-in", "hlsl-out"] } +naga = { version = "30.0.1", features = ["wgsl-in", "hlsl-out", "msl-out", "spv-out"] } diff --git a/crates/horizon-client/src/game/shader_packs.rs b/crates/horizon-client/src/game/shader_packs.rs index 7d628ef44..851a92e44 100644 --- a/crates/horizon-client/src/game/shader_packs.rs +++ b/crates/horizon-client/src/game/shader_packs.rs @@ -69,7 +69,7 @@ impl Game<'_> { } }; if let Some(r) = self.renderer.as_mut() - && let Err(e) = r.set_shader_pack(pack.as_ref()) + && let Err(e) = r.set_shader_pack(pack.as_ref(), &self.pack.render.sprite_layers) { return self.shader_pack_error(&id, &e.to_string()); } @@ -79,7 +79,10 @@ impl Game<'_> { /// Give the loaded pack to the renderer (also after it is rebuilt). pub(super) fn apply_shader_pack(&mut self) -> horizon_client::Result<()> { match self.renderer.as_mut() { - Some(r) => r.set_shader_pack(self.shader_packs.pack.as_ref()), + Some(r) => r.set_shader_pack( + self.shader_packs.pack.as_ref(), + &self.pack.render.sprite_layers, + ), None => Ok(()), } } diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 14c040c5c..bc49052f1 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -62,7 +62,8 @@ pub fn outline_vertices(edges: &[[f64; 6]], camera: glam::DVec3) -> Vec<[f32; 6] mod arena; mod cull; mod flat; -mod java_stages; +pub(crate) mod java_stages; +pub(crate) mod java_terrain; mod lod; mod occlusion; mod pack_stages; @@ -436,6 +437,15 @@ pub struct Renderer { world_post: world_post::Post, /// The selected shader pack's stages (Horizon setting; none by default). pack: Option, + /// A Java pack's terrain programs (`gfx/java_terrain.rs`): their page + /// groups' layout, the glue's table, each arena page's group. + java_page_layout: wgpu::BindGroupLayout, + /// The device renders to and filters 16-bit normalized formats. + java_norm16: bool, + java_table: Option, + java_pages: Vec>, + /// The sprite layers and mip levels `animate` wrote this frame. + animated: Vec<(u32, u32)>, pub hud: HudRenderer, /// The menus' backdrop blur, made on first use. post: Option, @@ -784,7 +794,10 @@ async fn open_device( | cull::Cull::features(&adapter) | (adapter.features() & (wgpu::Features::INDIRECT_FIRST_INSTANCE - | wgpu::Features::MAPPABLE_PRIMARY_BUFFERS)); + | wgpu::Features::MAPPABLE_PRIMARY_BUFFERS + // Java shader packs' 16-bit colour targets. + | wgpu::Features::TEXTURE_FORMAT_16BIT_NORM + | wgpu::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES)); let driver = format!("{} {}", info.driver, info.driver_info); startup_step(format_args!( "requesting the device (driver {}) with features [{features}] and the adapter's \ @@ -1274,7 +1287,10 @@ impl Renderer { sample_count: 1, dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::Rgba8Unorm, - usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + // COPY_SRC: animated sprites into a Java pack's atlas. + usage: wgpu::TextureUsages::TEXTURE_BINDING + | wgpu::TextureUsages::COPY_DST + | wgpu::TextureUsages::COPY_SRC, view_formats: &[], }, wgpu::util::TextureDataOrder::LayerMajor, @@ -2001,6 +2017,8 @@ impl Renderer { std::mem::size_of::() as u64, 1 << 20, ); + let java_page_layout = java_terrain::page_layout(&device); + let java_norm16 = java_terrain::norm16_targets(&adapter, &device); // Sections as one index list per frame where multi-draw is emulated. let flat = flat::wanted(&adapter, &device).then(|| { let buffers = [Some(wgpu::VertexBufferLayout { @@ -2180,6 +2198,11 @@ impl Renderer { occlusion: occlusion::Occlusion::new(crate::chunk::MIN_Y, crate::chunk::HEIGHT / 16), world_post, pack: None, + java_page_layout, + java_norm16, + java_table: None, + java_pages: Vec::new(), + animated: Vec::new(), hud, post: None, menu_blur: None, @@ -2483,6 +2506,18 @@ impl Renderer { base: u32, first: u32, count: u32, + ) { + self.draw_sections_with(pass, indirect, base, first, count, |_, _| {}); + } + /// [`Self::draw_sections`]; `page` binds what else a page's draws need. + fn draw_sections_with( + &self, + pass: &mut wgpu::RenderPass<'_>, + indirect: &wgpu::Buffer, + base: u32, + first: u32, + count: u32, + page_group: impl Fn(&mut wgpu::RenderPass<'_>, u32), ) { let (mut i, end) = (first as usize, (first + count) as usize); while i < end { @@ -2492,6 +2527,7 @@ impl Renderer { .take_while(|&&p| p == (page, index_page)) .count(); pass.set_vertex_buffer(0, self.arena.buffer(page).slice(..)); + page_group(pass, page); let indices = index_page.map_or(&self.indices, |p| self.sorted_indices.buffer(p)); pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32); if self.multi_draw { @@ -2505,6 +2541,88 @@ impl Renderer { i += run; } } + /// Horizon's terrain, solid or `translucent`, with a Java pack's + /// geometry pipelines (`java_terrain::DrawTerrain`): the frame's flat + /// draws or its section draws, each page with its group 3. + fn draw_java_terrain( + &self, + pass: &mut wgpu::RenderPass<'_>, + translucent: bool, + pipelines: &java_terrain::TerrainPipelines, + flat_frame: bool, + draws: [u32; 2], + ) { + let page = |pass: &mut wgpu::RenderPass<'_>, page: u32| { + if let Some(Some((_, group))) = self.java_pages.get(page as usize) { + pass.set_bind_group(3, group, &[]); + } + }; + pass.set_bind_group(2, pipelines.group, &[]); + match (self.flat.as_ref().filter(|_| flat_frame), pipelines.flat) { + (Some(flat), Some(pipeline)) => { + pass.set_pipeline(pipeline); + let calls = if translucent { + &flat.calls[flat.solid_calls..] + } else { + &flat.calls[..flat.solid_calls] + }; + flat.draw(pass, calls, |p| self.arena.buffer(p), page); + } + (Some(_), None) => {} + (None, _) => { + pass.set_pipeline(pipelines.instanced); + pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); + pass.set_vertex_buffer(1, self.instances.slice(..)); + let [solid, translucent_draws] = draws; + let (first, count) = if translucent { + (solid, translucent_draws) + } else { + (0, solid) + }; + self.draw_sections_with(pass, &self.indirect, 0, first, count, page); + } + } + } + /// Each arena page's group for a Java pack's terrain programs: its + /// vertices and the glue's table. + fn prepare_java_pages(&mut self) { + let Some(table) = &self.java_table else { + return; + }; + let count = self.arena.page_count() as usize; + self.java_pages.resize_with(count, || None); + let limit = self.device.limits().max_storage_buffer_binding_size; + for page in 0..count { + if !self.arena.has_page(page as u32) { + self.java_pages[page] = None; + continue; + } + let buffer = self.arena.buffer(page as u32); + if matches!(&self.java_pages[page], Some((b, _)) if b == buffer) { + continue; + } + let size = buffer.size().min(limit / 4 * 4); + let group = self.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Java shader pack terrain page"), + layout: &self.java_page_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer, + offset: 0, + size: std::num::NonZeroU64::new(size), + }), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: table.as_entire_binding(), + }, + ], + }); + self.java_pages[page] = Some((buffer.clone(), group)); + } + } fn release_section(&mut self, key: SectionKey) { if let Some(s) = self.sections.remove(key) { self.release_mesh(s); @@ -2588,9 +2706,29 @@ impl Renderer { } } /// Run `pack`'s stages over the world from now on (`None`: no pack, the - /// vanilla frame). On error the previous pack stays. - pub fn set_shader_pack(&mut self, pack: Option<&crate::shader_pack::ShaderPack>) -> Result<()> { + /// vanilla frame). On error the previous pack stays. `sprite_layers` + /// names the block sprites, for a Java pack's `block.properties`. + pub fn set_shader_pack( + &mut self, + pack: Option<&crate::shader_pack::ShaderPack>, + sprite_layers: &std::collections::BTreeMap, + ) -> Result<()> { let format = self.config.format.remove_srgb_suffix(); + let layouts = java_stages::GeometryLayouts { + flat: self.flat.as_ref().map(|f| f.draw_layout()), + page: &self.java_page_layout, + }; + let table = pack.and_then(|p| p.java.as_ref()).map(|java| { + let table = java_terrain::table(sprite_layers, &java.block_ids); + wgpu::util::DeviceExt::create_buffer_init( + &self.device, + &wgpu::util::BufferInitDescriptor { + label: Some("Java shader pack terrain table"), + contents: bytemuck::cast_slice(&table), + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, + }, + ) + }); self.pack = match pack { Some(pack) => Some(match &pack.java { Some(java) => Pack::Java(java_stages::JavaStages::new( @@ -2599,11 +2737,15 @@ impl Renderer { format, &pack.id, java, + &layouts, + self.java_norm16, )?), None => Pack::Horizon(pack_stages::PackStages::new(&self.device, format, pack)?), }), None => None, }; + self.java_table = table; + self.java_pages.clear(); Ok(()) } /// The folder name of the pack `set_shader_pack` gave. @@ -2733,11 +2875,13 @@ impl Renderer { self.lightmap_uploaded = true; } fn animate(&mut self, encoder: &mut wgpu::CommandEncoder, tick: u64) { + self.animated.clear(); animate_sprites( &mut self.animations, tick, self.mip_levels, |layer, level, size, pixels| { + self.animated.push((layer, level)); self.uploads.texture( encoder, wgpu::TexelCopyTextureInfo { @@ -3040,6 +3184,12 @@ impl Renderer { let eye = (frame.bob * crate::camera::view_matrix(frame.yaw, frame.pitch)) .inverse() .transform_point3(Vec3::ZERO); + // A Java pack that draws the terrain (`gfx/java_terrain.rs`): the + // world pass leaves it out, and occlusion culling (which tests + // against its depth) is off. + let java_terrain = !frame.title + && self.java_table.is_some() + && matches!(&self.pack, Some(Pack::Java(j)) if j.draws_terrain(frame.shader.dimension)); // Occlusion culling leaves the sections its last result did not see // to phase 2, after the others, with instance counts of 0. let mut cull = self @@ -3050,6 +3200,7 @@ impl Renderer { && !frame.title && self.multi_draw && !(self.flat_on && self.flat.is_some()) + && !java_terrain }) .and_then(|cull| cull.begin(&self.device).then_some(cull)); self.phase2_draws.clear(); @@ -3439,6 +3590,14 @@ impl Renderer { ); } } + if java_terrain { + self.prepare_java_pages(); + if let Some(table) = &self.java_table { + let nether = i32::from(frame.shader.dimension == -1); + self.queue + .write_buffer(table, 4, bytemuck::bytes_of(&nether)); + } + } let view_target = target_texture.create_view(&wgpu::TextureViewDescriptor { format: Some(self.config.format.remove_srgb_suffix()), ..Default::default() @@ -3528,11 +3687,15 @@ impl Renderer { } } match self.flat.as_ref().filter(|_| flat_frame) { + _ if java_terrain => {} Some(flat) => { pass.set_pipeline(&flat.solid); - flat.draw(&mut pass, &flat.calls[..flat.solid_calls], |p| { - self.arena.buffer(p) - }); + flat.draw( + &mut pass, + &flat.calls[..flat.solid_calls], + |p| self.arena.buffer(p), + |_, _| {}, + ); pass.set_bind_group(0, &self.group, &[]); pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); } @@ -3645,11 +3808,15 @@ impl Renderer { pass.draw(0..4, debug_depth..debug_depth + debug_top); } match self.flat.as_ref().filter(|_| flat_frame) { + _ if java_terrain => {} Some(flat) => { pass.set_pipeline(&flat.translucent); - flat.draw(&mut pass, &flat.calls[flat.solid_calls..], |p| { - self.arena.buffer(p) - }); + flat.draw( + &mut pass, + &flat.calls[flat.solid_calls..], + |p| self.arena.buffer(p), + |_, _| {}, + ); pass.set_bind_group(0, &self.group, &[]); pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); } @@ -3715,10 +3882,26 @@ impl Renderer { ); } } - if let (true, Some((color, depth)), Some(size), Some(stages)) = - (pack, &scaled, self.world_post.size(), self.pack.as_mut()) + if pack + && let (Some((color, depth)), Some(size)) = (&scaled, self.world_post.size()) + && let Some(mut stages) = self.pack.take() { - let output = match stages { + // The pack's terrain programs draw with the frame's draws. + let draws = [solid_draws, translucent_draws]; + let draw = |render: &mut wgpu::RenderPass<'_>, + translucent: bool, + pipelines: &java_terrain::TerrainPipelines| { + self.draw_java_terrain(render, translucent, pipelines, flat_frame, draws); + }; + let world = java_terrain::JavaWorld { + sprites: &self.sprite_textures, + split: self.sprite_split, + levels: self.mipmaps, + animated: &self.animated, + lightmap: &self.lightmap_view, + draw: &draw, + }; + let output = match &mut stages { Pack::Horizon(stages) => stages.run( &self.device, &self.queue, @@ -3743,10 +3926,12 @@ impl Renderer { sun_angle: frame.sky.sun_angle, moon_angle: frame.sky.moon_angle, }, + java_terrain.then_some(&world), ), }; self.world_post .finish_with(&mut encoder, &view_target, output); + self.pack = Some(stages); } else if scaled.is_some() { self.world_post.finish(&mut encoder, &view_target); } diff --git a/crates/horizon-client/src/gfx/arena.rs b/crates/horizon-client/src/gfx/arena.rs index 8da835aa2..14a264cd2 100644 --- a/crates/horizon-client/src/gfx/arena.rs +++ b/crates/horizon-client/src/gfx/arena.rs @@ -65,8 +65,11 @@ pub struct Arena { } impl Arena { + /// Vertices; also storage, which a Java shader pack's terrain programs + /// read a quad's corners from (`gfx/java_terrain.rs`). pub fn new(device: &wgpu::Device, stride: u64, capacity: u64) -> Self { - Self::with_usage(device, stride, capacity, wgpu::BufferUsages::VERTEX) + let usage = wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::STORAGE; + Self::with_usage(device, stride, capacity, usage) } /// Sorted translucent indices; `storage` when compute passes read them. pub fn indices(device: &wgpu::Device, capacity: u64, storage: bool) -> Self { @@ -145,6 +148,10 @@ impl Arena { pub fn page_vertices(&self) -> u64 { self.page_limit } + /// One past the last page index. + pub fn page_count(&self) -> u32 { + self.pages.len() as u32 + } pub fn has_page(&self, page: u32) -> bool { self.pages.get(page as usize).is_some_and(Option::is_some) } diff --git a/crates/horizon-client/src/gfx/flat.rs b/crates/horizon-client/src/gfx/flat.rs index a1ae20d09..8da19d7c5 100644 --- a/crates/horizon-client/src/gfx/flat.rs +++ b/crates/horizon-client/src/gfx/flat.rs @@ -466,11 +466,20 @@ impl Flat { } /// Draws `calls` with a flat pipeline set and `vertices` giving each /// page's vertex buffer. + /// The bind group layout of the draws' group 1 (block slots, slot + /// origins). + pub fn draw_layout(&self) -> &wgpu::BindGroupLayout { + &self.draw_layout + } + + /// Draw `calls`; `page` binds what else a page's draws need (a Java + /// pack's terrain reads the page's vertices). pub fn draw<'a>( &self, pass: &mut wgpu::RenderPass<'_>, calls: &[Call], vertices: impl Fn(u32) -> &'a wgpu::Buffer, + page: impl Fn(&mut wgpu::RenderPass<'_>, u32), ) { pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); for call in calls { @@ -480,6 +489,7 @@ impl Flat { .expect("prepared page"); pass.set_vertex_buffer(0, vertices(call.page).slice(..)); pass.set_bind_group(1, table, &[]); + page(pass, call.page); pass.draw_indexed(call.first..call.first + call.count, 0, 0..1); } } diff --git a/crates/horizon-client/src/gfx/java_stages.rs b/crates/horizon-client/src/gfx/java_stages.rs index e9f8ddbb1..19e2109e0 100644 --- a/crates/horizon-client/src/gfx/java_stages.rs +++ b/crates/horizon-client/src/gfx/java_stages.rs @@ -7,9 +7,17 @@ //! drawn, and the last picture goes to `world_post`. The targets keep GL's //! layout (row 0 at the bottom, which the translated vertex programs //! produce), so the world is flipped going in and the picture coming out. +//! +//! When the pack has terrain programs (`gfx/java_terrain.rs`), Horizon's +//! world comes without its terrain: the pack's `gbuffers_terrain` draws it +//! into the pack's targets right after, against the world's depth, and its +//! `gbuffers_water` draws the translucent terrain after `deferred`, as in +//! Iris. `depthtex1` and `depthtex2` then hold the depth before it. +use super::java_terrain::{Atlas, JavaWorld, TerrainPipelines}; use super::pack_stages::FrameUniform; use crate::java_pack::{JavaFolder, JavaPasses}; use glam::{Mat3, Mat4, Vec3, Vec4}; +use horizon_shaderpack::pipeline::GeometryProgram; use horizon_shaderpack::pipeline::TargetSettings; use horizon_shaderpack::pipeline::{Directives, Program, target_index}; use horizon_shaderpack::uniforms::{CustomUniforms, SmoothFloat, UniformState}; @@ -32,7 +40,7 @@ const NOISE_SIZE: u32 = 256; /// The vertex buffers a pass may read (wgpu's default limit). const MAX_ATTRIBUTES: usize = 8; -const BLIT: &str = r#" +pub(super) const BLIT: &str = r#" @group(0) @binding(0) var color: texture_2d; @group(0) @binding(1) var depth: texture_depth_2d; @@ -49,13 +57,49 @@ struct World { // The world's colour and depth, upside down into GL's layout; Horizon's // reversed depth (near 1) as GL's (near 0). -@fragment -fn world_in(@builtin(position) p: vec4f) -> World { +fn world_texel(p: vec4f) -> World { let size = textureDimensions(depth); let xy = vec2u(u32(p.x), size.y - 1u - u32(p.y)); return World(textureLoad(color, xy, 0), vec4f(1.0 - textureLoad(depth, xy, 0))); } +@fragment +fn world_in(@builtin(position) p: vec4f) -> World { + return world_texel(p); +} + +struct WorldDepth { + @location(0) color: vec4f, + @location(1) depth: vec4f, + @builtin(frag_depth) test: f32, +} + +// The same, and the depth into the depth buffer the pack's geometry +// programs test against. +@fragment +fn world_in_depth(@builtin(position) p: vec4f) -> WorldDepth { + let world = world_texel(p); + return WorldDepth(world.color, world.depth, world.depth.x); +} + +struct Depths { + @location(0) all: vec4f, + @location(1) solid: vec4f, +} + +// The depth buffer after the pack's geometry into `depthtex0` (and +// `depthtex1`, after solid terrain), both in GL's layout already. +@fragment +fn depth_out_both(@builtin(position) p: vec4f) -> Depths { + let d = vec4f(textureLoad(depth, vec2u(p.xy), 0)); + return Depths(d, d); +} + +@fragment +fn depth_out(@builtin(position) p: vec4f) -> @location(0) vec4f { + return vec4f(textureLoad(depth, vec2u(p.xy), 0)); +} + // A target, upside down back into wgpu's layout. @fragment fn present(@builtin(position) p: vec4f) -> @location(0) vec4f { @@ -67,7 +111,10 @@ fn present(@builtin(position) p: vec4f) -> @location(0) vec4f { /// A wgpu format for each of Iris's (`InternalTextureFormat`), renderable /// everywhere: 8-bit unsigned normalized formats stay, signed normalized, /// 16-bit and packed float ones become half floats, integer ones 32-bit. -fn target_format(iris: &str) -> wgpu::TextureFormat { +/// `norm16`: the device has 16-bit normalized formats, which keep packed +/// G-buffers (Chocapic13' packs two 8-bit values per `RGBA16` channel) +/// exact where a half float rounds them. +fn target_format(iris: &str, norm16: bool) -> wgpu::TextureFormat { use wgpu::TextureFormat as F; let channels = if iris.starts_with("RGB") || iris.contains("_B") { 4 @@ -84,6 +131,12 @@ fn target_format(iris: &str) -> wgpu::TextureFormat { match iris { "R8" | "RG8" | "RGB8" | "RGBA8" | "RGBA" | "RGBA2" | "RGBA4" | "R3_G3_B2" | "RGB5_A1" | "RGB565" => pick(F::R8Unorm, F::Rg8Unorm, F::Rgba8Unorm), + "R16" | "RG16" | "RGB16" | "RGBA16" if norm16 => { + pick(F::R16Unorm, F::Rg16Unorm, F::Rgba16Unorm) + } + "R16_SNORM" | "RG16_SNORM" | "RGB16_SNORM" | "RGBA16_SNORM" if norm16 => { + pick(F::R16Snorm, F::Rg16Snorm, F::Rgba16Snorm) + } "RGB10_A2" => F::Rgb10a2Unorm, "RGB10_A2UI" => F::Rgb10a2Uint, f if f.ends_with("32F") => pick(F::R32Float, F::Rg32Float, F::Rgba32Float), @@ -109,6 +162,14 @@ fn sample_type(format: wgpu::TextureFormat) -> wgpu::TextureSampleType { } } +/// The textures besides the targets a pass may read. +struct Views<'a> { + depth: &'a wgpu::TextureView, + depth_solid: &'a wgpu::TextureView, + atlas: Option<&'a wgpu::TextureView>, + lightmap: Option<&'a wgpu::TextureView>, +} + /// A colour target's two sides. struct Target { format: wgpu::TextureFormat, @@ -123,19 +184,33 @@ struct Target { #[derive(Clone, Copy, Debug, PartialEq)] enum Source { Target(u32), - /// `depthtex0..2`: the world's depth. + /// `depthtex0`: the world's depth. Depth, + /// `depthtex1` and `depthtex2`: the depth before translucent terrain + /// (the world's depth when the pack doesn't draw the terrain). + DepthSolid, Noise, /// `shadowtex*`: no shadow map yet, so a far depth (nothing in shadow); /// also Distant Horizons' and Voxy's depth, as without those mods. Shadow, /// Anything else (`shadowcolor*`, custom textures): white or black. Blank(bool), + /// In geometry programs: the block atlas (`gtexture`), the lightmap, + /// and a flat normal map for `normals` (sprites have no LabPBR maps). + Atlas, + Lightmap, + FlatNormal, } -fn source(name: &str) -> Source { +/// What sampler `name` reads, in a geometry program or a full-screen one. +fn source(name: &str, geometry: bool) -> Source { match name { - "depthtex0" | "depthtex1" | "depthtex2" | "gdepthtex" => Source::Depth, + "texture" | "gtexture" | "tex" if geometry => Source::Atlas, + "lightmap" if geometry => Source::Lightmap, + "normals" if geometry => Source::FlatNormal, + "specular" if geometry => Source::Blank(false), + "depthtex0" | "gdepthtex" => Source::Depth, + "depthtex1" | "depthtex2" => Source::DepthSolid, "noisetex" => Source::Noise, "shadowtex0" | "shadowtex1" | "shadow" | "watershadow" => Source::Shadow, n if n.starts_with("dhDepthTex") || n.starts_with("vxDepthTex") => Source::Shadow, @@ -174,11 +249,48 @@ struct PassGpu { draw_buffers: Vec, reads_alt: BTreeSet, scale: f32, + /// Geometry programs: the flat draws' pipeline (where the renderer has + /// them), and the targets written on their alternate side. + flat_pipeline: Option, + geometry: Option>, +} + +/// What a pass draws into. +enum Output<'a> { + /// A full-screen pass: its targets, or for `final` the screen's format. + Screen(Option), + /// A geometry program over Horizon's terrain. + Geometry(GeometrySetup<'a>), +} + +struct GeometrySetup<'a> { + /// The vertex program for flat draws. + flat_vertex: &'a horizon_shaderpack::translate::Translated, + /// Each draw buffer's blending. + blends: &'a [Option], + layouts: &'a GeometryLayouts<'a>, +} + +/// The renderer's bind group layouts a geometry program's pipelines use: +/// the flat draws' group 1 (`gfx/flat.rs`, when it has them) and the page +/// group 3 ([`super::java_terrain::page_layout`]). +pub struct GeometryLayouts<'a> { + pub flat: Option<&'a wgpu::BindGroupLayout>, + pub page: &'a wgpu::BindGroupLayout, +} + +/// A folder's terrain and water programs. +struct FolderGeometry { + terrain: PassGpu, + water: Option, + translucent_at: usize, } /// What every pass of the pack shares. struct Common { linear: wgpu::Sampler, + /// The block atlas's, as vanilla's: nearest, mipmapped. + atlas: wgpu::Sampler, nearest: wgpu::Sampler, repeat: wgpu::Sampler, compare: wgpu::Sampler, @@ -187,6 +299,8 @@ struct Common { vertices: [wgpu::Buffer; 4], world_layout: wgpu::BindGroupLayout, present_layout: wgpu::BindGroupLayout, + /// The geometry's depth buffer, read into `depthtex0` and `depthtex1`. + depth_layout: wgpu::BindGroupLayout, blit: wgpu::ShaderModule, } @@ -196,8 +310,11 @@ struct Bound { size: [u32; 2], targets: BTreeMap, depth: wgpu::TextureView, + /// `depthtex1`: `depth` before translucent terrain, or `depth` itself. + depth_solid: wgpu::TextureView, /// Per pass, then `final`. groups: Vec, + geometry: Option, world_in: (wgpu::RenderPipeline, wgpu::BindGroup), /// The world goes to colortex0's alternate side. world_alt: bool, @@ -209,6 +326,21 @@ struct Bound { _blank: Vec, } +/// What a folder's geometry programs draw with at one size. +struct BoundGeometry { + /// The depth buffer the geometry tests against: the world's, then the + /// terrain's. + test: wgpu::TextureView, + terrain: wgpu::BindGroup, + water: Option, + /// `world_in` that also fills `test`. + world_in: wgpu::RenderPipeline, + /// `test` into `depthtex0` and `depthtex1`, and into `depthtex0` alone. + out_both: wgpu::RenderPipeline, + out: wgpu::RenderPipeline, + out_group: wgpu::BindGroup, +} + struct Folder { targets: Vec, world_at: usize, @@ -217,6 +349,7 @@ struct Folder { passes: Vec, final_pass: Option, directives: Directives, + geometry: Option, } pub struct JavaStages { @@ -234,16 +367,24 @@ pub struct JavaStages { uniform_state: UniformState, /// `eyeBrightnessSmooth`, block then sky. eye_smooth: [SmoothFloat; 2], + /// The block atlas of the geometry programs. + atlas: Option, + /// The device has 16-bit normalized formats ([`target_format`]). + norm16: bool, } impl JavaStages { - /// The pipelines of a loaded Java pack, or wgpu's error. + /// The pipelines of a loaded Java pack, or wgpu's error. `norm16`: the + /// device has 16-bit normalized targets ([`target_format`]). + #[allow(clippy::too_many_arguments)] pub fn new( device: &wgpu::Device, queue: &wgpu::Queue, format: wgpu::TextureFormat, id: &str, pack: &JavaPasses, + layouts: &GeometryLayouts, + norm16: bool, ) -> Result { let common = Common::new(device, queue); let folder_for = [-1, 0, 1].map(|d| pack.folder_for(d)); @@ -255,17 +396,17 @@ impl JavaStages { let formats: Vec = plan .targets .iter() - .map(|t| target_format(&t.format)) + .map(|t| target_format(&t.format, norm16)) .collect(); let passes = plan .passes .iter() - .map(|p| PassGpu::new(device, p, &formats, None)) + .map(|p| PassGpu::new(device, p, &formats, Output::Screen(None))) .collect::, _>>()?; let final_pass = plan .final_pass .as_ref() - .map(|p| PassGpu::new(device, p, &formats, Some(format))) + .map(|p| PassGpu::new(device, p, &formats, Output::Screen(Some(format)))) .transpose()?; Ok::<_, String>(Folder { targets: plan.targets.clone(), @@ -275,6 +416,7 @@ impl JavaStages { passes, final_pass, directives: plan.directives, + geometry: folder_geometry(device, plan, &formats, layouts), }) }) .collect::, _>>()?; @@ -295,11 +437,26 @@ impl JavaStages { uniforms: pack.uniforms.clone(), uniform_state: UniformState::default(), eye_smooth: [SmoothFloat::default(); 2], + atlas: None, + norm16, }) } + /// Whether the pack draws the terrain in `dimension` (0 overworld, -1 + /// the Nether, 1 the End): the renderer then leaves it out of the world + /// and gives `run` a [`JavaWorld`]. + pub fn draws_terrain(&self, dimension: i8) -> bool { + let d = i32::from(dimension).clamp(-1, 1); + let folder = self.folder_for[(d + 1) as usize].unwrap_or(0); + self.folders + .get(folder) + .is_some_and(|f| f.geometry.is_some()) + } + /// Run the passes of the world's dimension over its `color` and `depth` - /// (`size`) and return `post`'s bindings of the picture. + /// (`size`) and return `post`'s bindings of the picture. `world` is given + /// when the world was drawn without its terrain ([`Self::draws_terrain`]): + /// the pack's geometry programs draw it. #[allow(clippy::too_many_arguments)] pub fn run( &mut self, @@ -312,15 +469,21 @@ impl JavaStages { post: &super::world_post::Post, frame: FrameUniform, world: JavaFrame, + terrain: Option<&JavaWorld>, ) -> &wgpu::BindGroup { let dimension = (frame.dimension[0] as i32).clamp(-1, 1); let folder = self.folder_for[(dimension + 1) as usize].unwrap_or(0); - if self - .bound - .as_ref() - .is_none_or(|b| b.folder != folder || b.size != size) + let terrain = terrain.filter(|_| self.folders[folder].geometry.is_some()); + if let Some(w) = terrain + && self.atlas.as_ref().is_none_or(|a| !a.fits(w)) { - self.bound = Some(self.bind(device, queue, folder, color, depth, size, post)); + self.atlas = Atlas::new(device, queue, w); + self.bound = None; + } + if self.bound.as_ref().is_none_or(|b| { + b.folder != folder || b.size != size || b.geometry.is_some() != terrain.is_some() + }) { + self.bound = Some(self.bind(device, queue, folder, color, depth, size, post, terrain)); } let now = std::time::Instant::now(); let frame_time = self.last.map_or(0.0, |t| (now - t).as_secs_f32()); @@ -335,6 +498,9 @@ impl JavaStages { self.previous, ); inputs.set_world(&world, directives.sun_path_rotation); + if let Some(atlas) = &self.atlas { + inputs.atlas_size = atlas.size().map(|v| v as f32); + } let half_life = directives.eye_brightness_half_life; for (i, smooth) in self.eye_smooth.iter_mut().enumerate() { inputs.eye_smooth[i] = smooth.update(inputs.eye[i], half_life, half_life, frame_time); @@ -357,15 +523,40 @@ impl JavaStages { } } } - let world_at = folder.world_at; - for (i, (pass, group)) in folder.passes.iter().zip(&bound.groups).enumerate() { + if let (Some(w), Some(atlas)) = (terrain, &mut self.atlas) { + atlas.update(device, encoder, w); + } + // The world after `prepare`, the terrain with it; translucent + // terrain after `deferred`. + let world_at = folder.world_at.min(folder.passes.len()); + let geometry = folder + .geometry + .as_ref() + .zip(bound.geometry.as_ref()) + .zip(terrain); + let translucent_at = geometry.map_or(usize::MAX, |((g, _), _)| { + g.translucent_at.min(folder.passes.len()) + }); + for i in 0..=folder.passes.len() { if i == world_at { world_in(encoder, bound); + if let Some(((g, b), w)) = geometry { + g.terrain.draw_geometry( + queue, encoder, bound, &b.terrain, &b.test, &inputs, w, false, + ); + depth_out(encoder, bound, true); + } + } + if i == translucent_at + && let Some(((g, b), w)) = geometry + && let (Some(water), Some(group)) = (&g.water, &b.water) + { + water.draw_geometry(queue, encoder, bound, group, &b.test, &inputs, w, true); + depth_out(encoder, bound, false); + } + if let (Some(pass), Some(group)) = (folder.passes.get(i), bound.groups.get(i)) { + pass.draw(queue, encoder, bound, group, &self.common, &inputs); } - pass.draw(queue, encoder, bound, group, &self.common, &inputs); - } - if folder.passes.len() <= world_at { - world_in(encoder, bound); } if let (Some(pass), Some(view)) = (&folder.final_pass, &bound.final_target) { let group = bound.groups.last().expect("final's group"); @@ -413,13 +604,18 @@ impl JavaStages { world_depth: &wgpu::TextureView, size: [u32; 2], post: &super::world_post::Post, + world: Option<&JavaWorld>, ) -> Bound { let folder = &self.folders[folder_index]; let plan = folder; let all = folder.passes.iter().chain(&folder.final_pass); + let geometry = folder.geometry.as_ref().filter(|_| world.is_some()); + let geometry_passes = geometry + .into_iter() + .flat_map(|g| std::iter::once(&g.terrain).chain(&g.water)); // Every target a pass reads or writes, and colortex0 (the world). let mut used: BTreeSet = [0].into(); - for pass in all.clone() { + for pass in all.clone().chain(geometry_passes) { used.extend(pass.draw_buffers.iter().copied()); used.extend(pass.samplers.iter().filter_map(|s| match s.source { Source::Target(i) => Some(i), @@ -450,7 +646,7 @@ impl JavaStages { .iter() .filter_map(|&i| { let settings = plan.targets.get(i as usize)?; - let format = target_format(&settings.format); + let format = target_format(&settings.format, self.norm16); let target_size = match settings.size { Some(horizon_shaderpack::pipeline::TargetSize::Relative(w, h)) if i != 0 => [ (size[0] as f32 * w).round() as u32, @@ -496,11 +692,78 @@ impl JavaStages { size, ) .create_view(&Default::default()); + let depth_solid = match geometry { + Some(_) => texture( + "Java shader pack depth before translucent terrain", + wgpu::TextureFormat::R32Float, + wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, + size, + ) + .create_view(&Default::default()), + None => depth.clone(), + }; + let views = Views { + depth: &depth, + depth_solid: &depth_solid, + atlas: self.atlas.as_ref().map(|a| &a.view), + lightmap: world.map(|w| w.lightmap), + }; let mut blank = Vec::new(); let groups = all .clone() - .map(|pass| pass.bind(device, queue, &targets, &depth, &self.common, &mut blank)) + .map(|pass| pass.bind(device, queue, &targets, &views, &self.common, &mut blank)) .collect(); + let geometry = geometry.map(|g| { + let test = texture( + "Java shader pack geometry depth", + wgpu::TextureFormat::Depth32Float, + wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, + size, + ) + .create_view(&Default::default()); + let r32 = wgpu::TextureFormat::R32Float; + let out_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Java shader pack geometry depth"), + layout: &self.common.depth_layout, + entries: &[wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(&test), + }], + }); + let mut bind = |pass: &PassGpu| { + pass.bind(device, queue, &targets, &views, &self.common, &mut blank) + }; + BoundGeometry { + terrain: bind(&g.terrain), + water: g.water.as_ref().map(&mut bind), + world_in: blit_pipeline( + device, + &self.common, + &self.common.world_layout, + "world_in_depth", + &[targets[&0].format, r32], + true, + ), + out_both: blit_pipeline( + device, + &self.common, + &self.common.depth_layout, + "depth_out_both", + &[r32, r32], + false, + ), + out: blit_pipeline( + device, + &self.common, + &self.common.depth_layout, + "depth_out", + &[r32], + false, + ), + out_group, + test, + } + }); // The world goes into colortex0's side the gbuffers would write. let colortex0 = &targets[&0]; @@ -510,6 +773,7 @@ impl JavaStages { &self.common.world_layout, "world_in", &[colortex0.format, wgpu::TextureFormat::R32Float], + false, ); let world_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("Java shader pack world"), @@ -549,6 +813,7 @@ impl JavaStages { &self.common.present_layout, "present", &[self.format], + false, ); let present_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("Java shader pack picture"), @@ -571,7 +836,9 @@ impl JavaStages { size, targets, depth, + depth_solid, groups, + geometry, world_in: (world_pipeline, world_group), world_alt: plan.flipped_after_prepare.contains(&0), final_target, @@ -583,6 +850,54 @@ impl JavaStages { } } +/// A folder's terrain and water programs on the GPU, or `None` (with a +/// warning: the terrain is then Horizon's) when wgpu refuses them. +fn folder_geometry( + device: &wgpu::Device, + plan: &JavaFolder, + formats: &[wgpu::TextureFormat], + layouts: &GeometryLayouts, +) -> Option { + let terrain = plan.terrain.as_ref()?; + let scope = device.push_error_scope(wgpu::ErrorFilter::Validation); + let gpu = |g: &GeometryProgram, blends: &[Option]| { + PassGpu::new( + device, + &g.program, + formats, + Output::Geometry(GeometrySetup { + flat_vertex: g.variants.first().unwrap_or(&g.program.vertex), + blends, + layouts, + }), + ) + }; + let made = gpu(terrain, &plan.terrain_blends).and_then(|terrain| { + let water = plan + .water + .as_ref() + .map(|w| gpu(w, &plan.water_blends)) + .transpose()?; + Ok(FolderGeometry { + terrain, + water, + translucent_at: plan.translucent_at, + }) + }); + let error = pollster::block_on(scope.pop()); + match (made, error) { + (Ok(geometry), None) => Some(geometry), + (Err(e), _) => { + log::warn!("Horizon: shader pack {}: {e}", terrain.program.pass.program); + None + } + (_, Some(e)) => { + log::warn!("Horizon: shader pack {}: {e}", terrain.program.pass.program); + None + } + } +} + fn world_in(encoder: &mut wgpu::CommandEncoder, bound: &Bound) { let colortex0 = &bound.targets[&0]; let side = if bound.world_alt { @@ -597,13 +912,46 @@ fn world_in(encoder: &mut wgpu::CommandEncoder, bound: &Bound) { let mut render = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("Java shader pack world"), color_attachments: &attachments, + depth_stencil_attachment: bound.geometry.as_ref().map(|g| { + wgpu::RenderPassDepthStencilAttachment { + view: &g.test, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(1.0), + store: wgpu::StoreOp::Store, + }), + stencil_ops: None, + } + }), ..Default::default() }); - render.set_pipeline(&bound.world_in.0); + match &bound.geometry { + Some(g) => render.set_pipeline(&g.world_in), + None => render.set_pipeline(&bound.world_in.0), + } render.set_bind_group(0, &bound.world_in.1, &[]); render.draw(0..3, 0..1); } +/// The geometry's depth buffer into `depthtex0`, and `depthtex1` too after +/// solid terrain. +fn depth_out(encoder: &mut wgpu::CommandEncoder, bound: &Bound, solid: bool) { + let Some(g) = &bound.geometry else { + return; + }; + let mut attachments = vec![Some(color_attachment(&bound.depth, None))]; + if solid { + attachments.push(Some(color_attachment(&bound.depth_solid, None))); + } + let mut render = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Java shader pack geometry depth"), + color_attachments: &attachments, + ..Default::default() + }); + render.set_pipeline(if solid { &g.out_both } else { &g.out }); + render.set_bind_group(0, &g.out_group, &[]); + render.draw(0..3, 0..1); +} + fn color_attachment( view: &wgpu::TextureView, clear: Option, @@ -628,12 +976,15 @@ fn clear_view(encoder: &mut wgpu::CommandEncoder, view: &wgpu::TextureView, colo }); } +/// A full-screen pipeline of `BLIT`'s `entry`; `depth`: it writes the +/// geometry's depth buffer. fn blit_pipeline( device: &wgpu::Device, common: &Common, layout: &wgpu::BindGroupLayout, entry: &str, formats: &[wgpu::TextureFormat], + depth: bool, ) -> wgpu::RenderPipeline { let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("Java shader pack blit"), @@ -652,7 +1003,13 @@ fn blit_pipeline( buffers: &[], }, primitive: Default::default(), - depth_stencil: None, + depth_stencil: depth.then_some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(true), + depth_compare: Some(wgpu::CompareFunction::Always), + stencil: Default::default(), + bias: Default::default(), + }), multisample: Default::default(), fragment: Some(wgpu::FragmentState { module: &common.blit, @@ -750,6 +1107,13 @@ impl Common { let unfilterable = wgpu::TextureSampleType::Float { filterable: false }; Self { linear: sampler(Linear, ClampToEdge, None), + atlas: device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("Java shader pack block atlas"), + mag_filter: Nearest, + min_filter: Nearest, + mipmap_filter: wgpu::MipmapFilterMode::Nearest, + ..Default::default() + }), nearest: sampler(Nearest, ClampToEdge, None), repeat: sampler(Linear, Repeat, None), compare: sampler(Linear, ClampToEdge, Some(wgpu::CompareFunction::LessEqual)), @@ -766,6 +1130,10 @@ impl Common { label: Some("Java shader pack picture"), entries: &[texture_entry(0, unfilterable)], }), + depth_layout: device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Java shader pack geometry depth"), + entries: &[texture_entry(1, wgpu::TextureSampleType::Depth)], + }), blit: device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("Java shader pack blit"), source: wgpu::ShaderSource::Wgsl(BLIT.into()), @@ -808,8 +1176,12 @@ impl PassGpu { device: &wgpu::Device, program: &Program, formats: &[wgpu::TextureFormat], - screen: Option, + output: Output, ) -> Result { + let (screen, setup) = match output { + Output::Screen(screen) => (screen, None), + Output::Geometry(setup) => (None, Some(setup)), + }; let name = program.pass.program.clone(); let link = &program.link; let mut samplers = Vec::new(); @@ -841,7 +1213,7 @@ impl PassGpu { .cloned() .unwrap_or_else(|| format!("{sampler}_s")); samplers.push(SamplerBinding { - source: source(sampler), + source: source(sampler, setup.is_some()), dimension, signed, texture: binding(&format!("{sampler}_t"))?, @@ -885,7 +1257,7 @@ impl PassGpu { )), ) } - (false, Source::Depth | Source::Shadow) => ( + (false, Source::Depth | Source::DepthSolid | Source::Shadow) => ( wgpu::TextureSampleType::Float { filterable: false }, Some(false), ), @@ -934,6 +1306,9 @@ impl PassGpu { label: Some(&name), entries: &entries, }); + if let Some(setup) = setup { + return Self::geometry(device, program, formats, setup, layout, samplers, block); + } let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some(&name), bind_group_layouts: &[Some(&layout)], @@ -1064,19 +1439,164 @@ impl PassGpu { }, reads_alt: program.pass.reads_alt.clone(), scale: program.pass.scale.clamp(0.0, 1.0), + flat_pipeline: None, + geometry: None, }) } - /// The pass's bind group over `targets`. + /// A geometry program's pipelines over Horizon's terrain vertices + /// (instanced and flat draws), into its draw buffers on the side the + /// next passes read, tested against the world's depth. + #[allow(clippy::too_many_arguments)] + fn geometry( + device: &wgpu::Device, + program: &Program, + formats: &[wgpu::TextureFormat], + setup: GeometrySetup, + layout: wgpu::BindGroupLayout, + samplers: Vec, + block: Option<(u32, Vec<(String, Vec)>)>, + ) -> Result { + let name = program.pass.program.clone(); + let outputs = &program.fragment.interface.outputs; + let targets: Vec> = program + .draw_buffers + .iter() + .enumerate() + .map(|(l, &i)| { + let format = formats + .get(i as usize) + .copied() + .unwrap_or(wgpu::TextureFormat::Rgba8Unorm); + let blendable = matches!( + sample_type(format), + wgpu::TextureSampleType::Float { filterable: true } + ); + Some(wgpu::ColorTargetState { + format, + blend: setup.blends.get(l).copied().flatten().filter(|_| blendable), + write_mask: if outputs.contains_key(&(l as u32)) { + wgpu::ColorWrites::ALL + } else { + wgpu::ColorWrites::empty() + }, + }) + }) + .collect(); + let vertex = wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &super::TERRAIN_ATTRIBUTES, + }; + let instance_attributes = wgpu::vertex_attr_array![5 => Float32x4]; + let instance = wgpu::VertexBufferLayout { + array_stride: 16, + step_mode: wgpu::VertexStepMode::Instance, + attributes: &instance_attributes, + }; + let fragment_module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some(&format!("{name}.fsh")), + source: wgpu::ShaderSource::Wgsl(program.fragment.wgsl.as_str().into()), + }); + let pipeline = |vertex_program: &horizon_shaderpack::translate::Translated, + flat: Option<&wgpu::BindGroupLayout>| { + let vertex_module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some(&format!("{name}.vsh")), + source: wgpu::ShaderSource::Wgsl(vertex_program.wgsl.as_str().into()), + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some(&name), + bind_group_layouts: &[None, flat, Some(&layout), Some(setup.layouts.page)], + ..Default::default() + }); + let buffers = if flat.is_some() { + vec![Some(vertex.clone())] + } else { + vec![Some(vertex.clone()), Some(instance.clone())] + }; + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(&name), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &vertex_module, + entry_point: Some("main"), + compilation_options: Default::default(), + buffers: &buffers, + }, + // The y flip into GL's layout turns the faces around. + primitive: wgpu::PrimitiveState { + cull_mode: Some(wgpu::Face::Back), + front_face: wgpu::FrontFace::Cw, + ..Default::default() + }, + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(true), + depth_compare: Some(wgpu::CompareFunction::LessEqual), + stencil: Default::default(), + bias: Default::default(), + }), + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &fragment_module, + entry_point: Some("main"), + compilation_options: Default::default(), + targets: &targets, + }), + multiview_mask: None, + cache: None, + }) + }; + let instanced = pipeline(&program.vertex, None); + let flat_pipeline = setup + .layouts + .flat + .map(|flat| pipeline(setup.flat_vertex, Some(flat))); + let uniform = block.as_ref().map(|(size, _)| { + ( + *size, + device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Java shader pack uniforms"), + size: u64::from(*size).max(16), + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }), + ) + }); + // It reads the side the next passes read, but the other side of the + // targets it writes: wgpu can't read and write a texture at once. + let flipped = program.pass.reads_alt.clone(); + let written: BTreeSet = program.draw_buffers.iter().copied().collect(); + let reads_alt = (0..horizon_shaderpack::pipeline::MAX_COLOR_BUFFERS) + .filter(|i| flipped.contains(i) != written.contains(i)) + .collect(); + Ok(Self { + program: name, + pipeline: instanced, + layout, + samplers, + uniforms: block.map(|(_, members)| members).unwrap_or_default(), + uniform, + attributes: Vec::new(), + draw_buffers: program.draw_buffers.clone(), + reads_alt, + scale: 1.0, + flat_pipeline, + geometry: Some(flipped), + }) + } + + /// The pass's bind group over `targets` and `views`. fn bind( &self, device: &wgpu::Device, queue: &wgpu::Queue, targets: &BTreeMap, - depth: &wgpu::TextureView, + textures: &Views, common: &Common, blank: &mut Vec, ) -> wgpu::BindGroup { + let depth = textures.depth; let mut views = Vec::new(); for s in &self.samplers { let view = match (s.compare, s.source) { @@ -1091,6 +1611,24 @@ impl PassGpu { (false, Source::Depth) if s.dimension == wgpu::TextureViewDimension::D2 => { depth.clone() } + (false, Source::DepthSolid) if s.dimension == wgpu::TextureViewDimension::D2 => { + textures.depth_solid.clone() + } + (false, Source::Atlas) if s.dimension == wgpu::TextureViewDimension::D2 => { + match textures.atlas { + Some(v) => v.clone(), + None => blank_view(device, queue, blank, s, BlankKind::Color(true)), + } + } + (false, Source::Lightmap) if s.dimension == wgpu::TextureViewDimension::D2 => { + match textures.lightmap { + Some(v) => v.clone(), + None => blank_view(device, queue, blank, s, BlankKind::Color(true)), + } + } + (false, Source::FlatNormal) => { + blank_view(device, queue, blank, s, BlankKind::FlatNormal) + } (false, Source::Shadow) => blank_view(device, queue, blank, s, BlankKind::Far), (false, Source::Noise) if s.dimension == wgpu::TextureViewDimension::D2 => { common.noise.clone() @@ -1110,7 +1648,8 @@ impl PassGpu { (true, _) => &common.compare, _ if s.signed.is_some() => &common.nearest, (false, Source::Noise) => &common.repeat, - (false, Source::Depth | Source::Shadow) => &common.nearest, + (false, Source::Depth | Source::DepthSolid | Source::Shadow) => &common.nearest, + (false, Source::Atlas) => &common.atlas, (false, Source::Target(i)) => { match targets.get(&i).map(|t| sample_type(t.format)) { Some(wgpu::TextureSampleType::Float { filterable: true }) | None => { @@ -1151,6 +1690,88 @@ impl PassGpu { }) } + /// This frame's values of its uniforms. + fn write_uniforms(&self, queue: &wgpu::Queue, inputs: &Inputs) { + let Some((block_size, buffer)) = &self.uniform else { + return; + }; + let mut bytes = vec![0u8; *block_size as usize]; + for (name, slots) in &self.uniforms { + if let Some(values) = inputs.value(name, self.geometry.is_some()) { + for (&(offset, int), value) in slots.iter().zip(values) { + let at = offset as usize..offset as usize + 4; + bytes[at].copy_from_slice(&if int { + (value as i32).to_ne_bytes() + } else { + value.to_ne_bytes() + }); + } + } + } + queue.write_buffer(buffer, 0, &bytes); + } + + /// A geometry program: Horizon's terrain (solid or `translucent`) into + /// its draw buffers on the side the next passes read, against `depth`. + #[allow(clippy::too_many_arguments)] + fn draw_geometry( + &self, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + bound: &Bound, + group: &wgpu::BindGroup, + depth: &wgpu::TextureView, + inputs: &Inputs, + world: &JavaWorld, + translucent: bool, + ) { + let Some(flipped) = &self.geometry else { + return; + }; + self.write_uniforms(queue, inputs); + // Targets of another size than the world's can't be drawn with it. + let size = wgpu::Extent3d { + width: bound.size[0].max(1), + height: bound.size[1].max(1), + depth_or_array_layers: 1, + }; + let attachments: Vec> = self + .draw_buffers + .iter() + .map(|i| { + let t = bound.targets.get(i).filter(|t| t.main.size() == size)?; + let side = if flipped.contains(i) { + &t.alt_view + } else { + &t.main_view + }; + Some(color_attachment(side, None)) + }) + .collect(); + let mut render = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some(&self.program), + color_attachments: &attachments, + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: depth, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Load, + store: wgpu::StoreOp::Store, + }), + stencil_ops: None, + }), + ..Default::default() + }); + (world.draw)( + &mut render, + translucent, + &TerrainPipelines { + instanced: &self.pipeline, + flat: self.flat_pipeline.as_ref(), + group, + }, + ); + } + /// Draw into the targets of `draw_buffers`, on the side it doesn't read. fn draw( &self, @@ -1196,22 +1817,7 @@ impl PassGpu { common: &Common, inputs: &Inputs, ) { - if let Some((block_size, buffer)) = &self.uniform { - let mut bytes = vec![0u8; *block_size as usize]; - for (name, slots) in &self.uniforms { - if let Some(values) = inputs.value(name) { - for (&(offset, int), value) in slots.iter().zip(values) { - let at = offset as usize..offset as usize + 4; - bytes[at].copy_from_slice(&if int { - (value as i32).to_ne_bytes() - } else { - value.to_ne_bytes() - }); - } - } - } - queue.write_buffer(buffer, 0, &bytes); - } + self.write_uniforms(queue, inputs); let attachments: Vec> = views .iter() .map(|v| v.map(|v| color_attachment(v, None))) @@ -1234,6 +1840,8 @@ impl PassGpu { enum BlankKind { Color(bool), + /// A normal map's flat normal, (0.5, 0.5, 1). + FlatNormal, /// An `R32Float` 1.0: the far plane. Far, /// A depth texture at the far plane, for comparison samplers. @@ -1256,6 +1864,7 @@ fn blank_view( wgpu::TextureFormat::Rgba8Unorm, vec![if white { 255 } else { 0 }; 4], ), + (BlankKind::FlatNormal, _) => (wgpu::TextureFormat::Rgba8Unorm, vec![128, 128, 255, 255]), (BlankKind::Far, _) => (wgpu::TextureFormat::R32Float, 1.0f32.to_ne_bytes().to_vec()), (BlankKind::FarDepth, _) => (wgpu::TextureFormat::Depth32Float, Vec::new()), }; @@ -1452,6 +2061,8 @@ struct Inputs { is_day: bool, /// The pack's custom uniforms this frame. custom: HashMap>, + /// `atlasSize`, in geometry programs. + atlas_size: [f32; 2], } /// `CelestialUniforms.getSunAngle`: the body's angle plus 90, in 0..360 @@ -1506,6 +2117,7 @@ impl Inputs { shadow_angle: 0.0, is_day: true, custom: HashMap::new(), + atlas_size: [0.0; 2], }; out.set_world(&JavaFrame::default(), 0.0); out @@ -1541,16 +2153,55 @@ impl Inputs { /// The value of uniform `name`, as its scalars in order: Iris's own, /// else the pack's custom uniform; `None` for one Horizon doesn't /// provide (it stays zero). - fn value(&self, name: &str) -> Option> { - self.builtin(name) + fn value(&self, name: &str, geometry: bool) -> Option> { + geometry + .then(|| self.geometry(name)) + .flatten() + .or_else(|| self.builtin(name)) .or_else(|| self.custom.get(name).cloned()) } + /// The uniforms whose value differs in geometry programs: the + /// camera's matrices (camera-relative positions, as Iris's terrain), + /// the lightmap's texture matrix, the atlas's size. + fn geometry(&self, name: &str) -> Option> { + let mat = |m: Mat4| m.to_cols_array().to_vec(); + Some(match name { + "iris_ModelViewMatrix" | "modelViewMatrix" => mat(self.view), + "iris_ModelViewMatrixInverse" | "modelViewMatrixInverse" => mat(self.view.inverse()), + "iris_ProjectionMatrix" | "projectionMatrix" => mat(self.projection), + "iris_ProjectionMatrixInverse" | "projectionMatrixInverse" => { + mat(self.projection.inverse()) + } + "iris_ModelViewProjectionMatrix" => mat(self.projection * self.view), + "iris_NormalMatrix" | "normalMatrix" => Mat3::from_mat4(self.view) + .inverse() + .transpose() + .to_cols_array() + .to_vec(), + // Unit 1, the lightmap: 0..240 to texel centres (Iris's + // `LIGHTMAP_TEXTURE_MATRIX`). + "iris_TextureMatrix" => { + let lightmap = Mat4::from_scale(Vec3::splat(1.0 / 256.0)) + * Mat4::from_translation(Vec3::splat(8.0)); + (0..8) + .flat_map(|i| mat(if i == 1 { lightmap } else { Mat4::IDENTITY })) + .collect() + } + "textureMatrix" => mat(Mat4::IDENTITY), + "chunkOffset" => vec![0.0; 3], + "alphaTestRef" => vec![0.1], + "atlasSize" => self.atlas_size.to_vec(), + "entityId" | "blockEntityId" | "currentRenderedItemId" => vec![-1.0], + _ => return None, + }) + } + /// The value of Iris uniform `name`; `None` for one Horizon doesn't /// provide. fn builtin(&self, name: &str) -> Option> { if let Some(flag) = name.strip_prefix("iris_bool_") { - return self.value(flag); + return self.value(flag, false); } let f = &self.frame; let mat = |m: Mat4| m.to_cols_array().to_vec(); @@ -1638,8 +2289,11 @@ mod tests { ("R32UI", F::R32Uint), ("RGBA16I", F::Rgba32Sint), ] { - assert_eq!(target_format(iris), wgpu, "{iris}"); + assert_eq!(target_format(iris, false), wgpu, "{iris}"); } + assert_eq!(target_format("RGBA16", true), F::Rgba16Unorm); + assert_eq!(target_format("RG16_SNORM", true), F::Rg16Snorm); + assert_eq!(target_format("RGBA16F", true), F::Rgba16Float); assert_eq!( sample_type(F::R32Float), wgpu::TextureSampleType::Float { filterable: false } @@ -1648,13 +2302,20 @@ mod tests { #[test] fn samplers_read_what_iris_binds() { - assert_eq!(source("colortex4"), Source::Target(4)); - assert_eq!(source("gaux1"), Source::Target(4)); - assert_eq!(source("gdepthtex"), Source::Depth); - assert_eq!(source("shadowtex1"), Source::Shadow); - assert_eq!(source("dhDepthTex0"), Source::Shadow); - assert_eq!(source("shadowcolor0"), Source::Blank(true)); - assert_eq!(source("cloudTexture"), Source::Blank(false)); + assert_eq!(source("colortex4", false), Source::Target(4)); + assert_eq!(source("gaux1", false), Source::Target(4)); + assert_eq!(source("gdepthtex", false), Source::Depth); + assert_eq!(source("shadowtex1", false), Source::Shadow); + assert_eq!(source("dhDepthTex0", false), Source::Shadow); + assert_eq!(source("shadowcolor0", false), Source::Blank(true)); + assert_eq!(source("cloudTexture", false), Source::Blank(false)); + // Before translucent terrain; geometry programs' own textures. + assert_eq!(source("depthtex1", false), Source::DepthSolid); + assert_eq!(source("gtexture", true), Source::Atlas); + assert_eq!(source("texture", true), Source::Atlas); + assert_eq!(source("lightmap", true), Source::Lightmap); + assert_eq!(source("normals", true), Source::FlatNormal); + assert_eq!(source("colortex1", true), Source::Target(1)); let (d, signed, shadow) = sampler_kind("usampler2D").unwrap(); assert_eq!( (d, signed, shadow), @@ -1688,21 +2349,24 @@ mod tests { moon_angle: sun_angle + 180.0, }; inputs.set_world(&world(-90.0), 0.0); - close(inputs.value("sunPosition"), [100.0, 0.0, 0.0]); - close(inputs.value("moonPosition"), [-100.0, 0.0, 0.0]); - close(inputs.value("upPosition"), [0.0, 100.0, 0.0]); - assert_eq!(inputs.value("sunAngle"), Some(vec![0.0])); - assert_eq!(inputs.value("eyeBrightness"), Some(vec![48.0, 240.0])); + close(inputs.value("sunPosition", false), [100.0, 0.0, 0.0]); + close(inputs.value("moonPosition", false), [-100.0, 0.0, 0.0]); + close(inputs.value("upPosition", false), [0.0, 100.0, 0.0]); + assert_eq!(inputs.value("sunAngle", false), Some(vec![0.0])); + assert_eq!( + inputs.value("eyeBrightness", false), + Some(vec![48.0, 240.0]) + ); // Complementary Unbound's sunPathRotation of -40 at noon: the sun // where its GetSunVector puts it, (0, cos 40, sin 40). let tilt = (-40f32).to_radians(); inputs.set_world(&world(0.0), -40.0); close( - inputs.value("sunPosition"), + inputs.value("sunPosition", false), [0.0, 100.0 * tilt.cos(), -100.0 * tilt.sin()], ); - assert_eq!(inputs.value("sunAngle"), Some(vec![0.25])); - close(inputs.value("shadowLightPosition"), { + assert_eq!(inputs.value("sunAngle", false), Some(vec![0.25])); + close(inputs.value("shadowLightPosition", false), { let s = inputs.sun_position; [s.x, s.y, s.z] }); @@ -1710,15 +2374,15 @@ mod tests { inputs.set_world(&world(150.0), 0.0); assert!(!inputs.is_day); assert_eq!( - inputs.value("shadowLightPosition"), - inputs.value("moonPosition") + inputs.value("shadowLightPosition", false), + inputs.value("moonPosition", false) ); - assert!((inputs.value("shadowAngle").unwrap()[0] - 60.0 / 360.0).abs() < 1e-6); + assert!((inputs.value("shadowAngle", false).unwrap()[0] - 60.0 / 360.0).abs() < 1e-6); // Custom uniforms come after Iris's own. inputs.custom.insert("eyeBrightnessM".into(), vec![0.5]); inputs.custom.insert("sunAngle".into(), vec![9.0]); - assert_eq!(inputs.value("eyeBrightnessM"), Some(vec![0.5])); - assert_ne!(inputs.value("sunAngle"), Some(vec![9.0])); + assert_eq!(inputs.value("eyeBrightnessM", false), Some(vec![0.5])); + assert_ne!(inputs.value("sunAngle", false), Some(vec![9.0])); } #[test] @@ -1737,10 +2401,10 @@ mod tests { }; assert!((depth(near) + 1.0).abs() < 1e-4, "{}", depth(near)); assert!((depth(far) - 1.0).abs() < 1e-3, "{}", depth(far)); - assert_eq!(inputs.value("viewWidth"), Some(vec![300.0])); + assert_eq!(inputs.value("viewWidth", false), Some(vec![300.0])); assert_eq!( - inputs.value("iris_bool_hasSkylight"), - inputs.value("hasSkylight") + inputs.value("iris_bool_hasSkylight", false), + inputs.value("hasSkylight", false) ); } } diff --git a/crates/horizon-client/src/gfx/java_terrain.rs b/crates/horizon-client/src/gfx/java_terrain.rs new file mode 100644 index 000000000..6411efda1 --- /dev/null +++ b/crates/horizon-client/src/gfx/java_terrain.rs @@ -0,0 +1,645 @@ +//! Horizon's terrain drawn with a Java pack's `gbuffers_terrain` and +//! `gbuffers_water` (docs/shader-packs.md). The pack's vertex program runs +//! after a glue that rebuilds what Iris would feed it from Horizon's +//! `TerrainVertex`: the camera-relative position, the quad's normal and +//! tangent (from its four corners, read from the arena page as storage), +//! the colour without vanilla's directional shade, the lightmap +//! coordinates, the sprite's place in a block atlas laid out from Horizon's +//! sprite arrays, and `mc_Entity` from the pack's `block.properties`, by +//! sprite name. +use horizon_shaderpack::translate::Geometry; +use std::collections::BTreeMap; + +/// `TerrainVertex` in 32-bit words. +const VERTEX_WORDS: u32 = 6; + +/// The glue's declarations and `hz_vertex`; `HZ_ORIGIN_DECL` and +/// `HZ_ORIGIN` are the variant's (instanced or flat draws). +const GLUE: &str = r#" +layout(location = 0) in vec3 hz_position; +layout(location = 1) in uvec2 hz_uv; +layout(location = 2) in uint hz_layer; +layout(location = 3) in vec4 hz_color; +layout(location = 4) in uvec2 hz_light; +HZ_ORIGIN_DECL +layout(std430, set = 3, binding = 0) readonly buffer HzVertices { uint hz_vertices[]; }; +// [0]: atlas columns, [1]: 1 in the Nether, then each sprite layer's block id. +layout(std430, set = 3, binding = 1) readonly buffer HzTable { int hz_table[]; }; +vec4 hz_pos; +vec3 hz_normal; +vec4 hz_tangent; +vec4 hz_tint; +vec2 hz_atlas; +vec2 hz_mid; +vec2 hz_lightmap; +float hz_block; +vec3 hz_mid_block; +vec3 hz_corner(uint v) { + uint b = v * HZ_WORDSu; + return vec3(uintBitsToFloat(hz_vertices[b]), uintBitsToFloat(hz_vertices[b + 1u]), + uintBitsToFloat(hz_vertices[b + 2u])); +} +vec2 hz_corner_uv(uint v) { + uint w = hz_vertices[v * HZ_WORDSu + 3u]; + return vec2(float(w & 65535u), float(w >> 16u)); +} +void hz_vertex() { + vec4 origin = HZ_ORIGIN; + hz_pos = vec4(hz_position + origin.xyz, 1.0); + // The quad's corners: quads are four vertices from a multiple of four. + uint q = uint(gl_VertexIndex) & 4294967292u; + vec3 p0 = hz_corner(q); + vec3 e1 = hz_corner(q + 1u) - p0; + vec3 e2 = hz_corner(q + 2u) - p0; + vec3 n = cross(e1, e2); + if (dot(n, n) < 1e-12) { + n = cross(e2, hz_corner(q + 3u) - p0); + } + hz_normal = dot(n, n) > 0.0 ? normalize(n) : vec3(0.0, 1.0, 0.0); + vec2 t0 = hz_corner_uv(q); + vec2 d1 = hz_corner_uv(q + 1u) - t0; + vec2 d2 = hz_corner_uv(q + 2u) - t0; + float s = d1.x * d2.y - d2.x * d1.y < 0.0 ? -1.0 : 1.0; + vec3 t = (e1 * d2.y - e2 * d1.y) * s; + vec3 b = (e2 * d1.x - e1 * d2.x) * s; + t = t - hz_normal * dot(hz_normal, t); + t = dot(t, t) > 0.0 ? normalize(t) : vec3(1.0, 0.0, 0.0); + hz_tangent = vec4(t, dot(cross(hz_normal, t), b) < 0.0 ? -1.0 : 1.0); + // Iris turns vanilla's directional shade off: undo it on axis faces. + vec3 a = abs(hz_normal); + bool nether = hz_table[1] != 0; + float shade = 1.0; + if (a.y > 0.999) { + shade = nether ? 0.9 : (hz_normal.y > 0.0 ? 1.0 : 0.5); + } else if (a.z > 0.999) { + shade = 0.8; + } else if (a.x > 0.999) { + shade = 0.6; + } + hz_tint = vec4(min(hz_color.rgb / shade, vec3(1.0)), hz_color.a); + // The sprite's cell in the atlas, columns of square cells. + int layer = int(hz_layer & 16383u); + int cols = max(hz_table[0], 1); + vec2 cell = vec2(float(layer % cols), float(layer / cols)); + vec2 uv = clamp(vec2(hz_uv) * origin.w, 0.0, 1.0); + hz_atlas = (cell + uv) / float(cols); + hz_mid = (cell + 0.5) / float(cols); + // Vanilla's UV2: block light, then sky light, 0..240. + hz_lightmap = vec2(float(hz_light.y), float(hz_light.x)); + hz_block = float(hz_table[2 + layer]); + hz_mid_block = (floor(hz_position - hz_normal * 0.01) + 0.5 - hz_position) * 64.0; +} +"#; + +/// The glue of one draw path: instanced section draws (the origin is an +/// instance attribute) or flat ones (`gfx/flat.rs`: from the block's slot). +pub fn glue(flat: bool, alpha_test: Option) -> Geometry { + let (decl, origin) = if flat { + ( + "layout(std430, set = 1, binding = 0) readonly buffer HzBlockSlots { uint hz_block_slots[]; };\n\ + layout(std430, set = 1, binding = 1) readonly buffer HzSlotOrigins { vec4 hz_slot_origins[]; };", + "hz_slot_origins[hz_block_slots[uint(gl_VertexIndex) >> 8u]]", + ) + } else { + ("layout(location = 5) in vec4 hz_origin;", "hz_origin") + }; + let vertex_glue = GLUE + .replace("HZ_ORIGIN_DECL", decl) + .replace("HZ_ORIGIN", origin) + .replace("HZ_WORDS", &VERTEX_WORDS.to_string()); + let lightmap = "vec4(hz_lightmap, 0.0, 1.0)"; + let attributes: BTreeMap = [ + ("iris_Vertex", "hz_pos"), + ("vaPosition", "hz_pos"), + ("iris_Normal", "vec4(hz_normal, 0.0)"), + ("vaNormal", "vec4(hz_normal, 0.0)"), + ("iris_Color", "hz_tint"), + ("vaColor", "hz_tint"), + ("iris_MultiTexCoord0", "vec4(hz_atlas, 0.0, 1.0)"), + ("vaUV0", "vec4(hz_atlas, 0.0, 1.0)"), + ("iris_MultiTexCoord1", lightmap), + ("iris_MultiTexCoord2", lightmap), + ("vaUV2", lightmap), + // OverlayTexture.NO_OVERLAY. + ("vaUV1", "vec4(0.0, 10.0, 0.0, 0.0)"), + ("mc_Entity", "vec4(hz_block, -1.0, 0.0, 0.0)"), + ("mc_midTexCoord", "vec4(hz_mid, 0.0, 1.0)"), + ("at_tangent", "hz_tangent"), + ("at_midBlock", "vec4(hz_mid_block, 0.0)"), + ] + .into_iter() + .map(|(k, v)| (k.to_owned(), v.to_owned())) + .collect(); + Geometry { + vertex_glue, + attributes, + alpha_test, + } +} + +/// The glue's table: atlas columns, the Nether flag, then each sprite +/// layer's block id from `block.properties` (-1 for blocks it doesn't +/// list, as Iris). +pub fn table(sprite_layers: &BTreeMap, block_ids: &BTreeMap) -> Vec { + let layers = sprite_layers.values().max().map_or(0, |&m| m as usize + 1); + let mut out = vec![-1; layers + 2]; + out[0] = atlas_columns(layers as u32) as i32; + out[1] = 0; + for (name, &layer) in sprite_layers { + if let Some(id) = horizon_shaderpack::properties::sprite_block_id(name, block_ids) { + out[layer as usize + 2] = id; + } + } + out +} + +/// The atlas's columns (and rows) of sprite cells for `layers` sprites. +pub fn atlas_columns(layers: u32) -> u32 { + (f64::from(layers.max(1)).sqrt().ceil() as u32).max(1) +} + +/// Whether `device` renders to and filters the 16-bit normalized formats +/// a Java pack's `RGBA16` targets become (`java_stages::target_format`). +pub fn norm16_targets(adapter: &wgpu::Adapter, device: &wgpu::Device) -> bool { + use wgpu::TextureFormat as F; + let wanted = wgpu::Features::TEXTURE_FORMAT_16BIT_NORM + | wgpu::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES; + device.features().contains(wanted) + && [ + F::R16Unorm, + F::Rg16Unorm, + F::Rgba16Unorm, + F::R16Snorm, + F::Rg16Snorm, + F::Rgba16Snorm, + ] + .into_iter() + .all(|f| { + let features = adapter.get_texture_format_features(f); + features + .allowed_usages + .contains(wgpu::TextureUsages::RENDER_ATTACHMENT) + && features + .flags + .contains(wgpu::TextureFormatFeatureFlags::FILTERABLE) + }) +} + +/// The bind group layout of a page group: the page's vertices and the glue's +/// table, read by the vertex stage. +pub fn page_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout { + let storage = |binding| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: true }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }; + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Java shader pack terrain page"), + entries: &[storage(0), storage(1)], + }) +} + +/// Draws Horizon's terrain with a pack's pipelines: the solid layer or the +/// translucent one. Set by the renderer, which owns the sections. +pub type DrawTerrain<'a> = dyn Fn(&mut wgpu::RenderPass<'_>, bool, &TerrainPipelines<'_>) + 'a; + +/// What the renderer binds to draw with a pack's geometry program: the +/// pipeline of its draw path and the pack's group (group 2). Group 1 is the +/// flat path's, group 3 the page's ([`page_layout`]). `flat` is `None` when +/// the renderer has no flat draws. +pub struct TerrainPipelines<'a> { + pub instanced: &'a wgpu::RenderPipeline, + pub flat: Option<&'a wgpu::RenderPipeline>, + pub group: &'a wgpu::BindGroup, +} + +/// What a Java pack's geometry reads from the renderer each frame. +pub struct JavaWorld<'a> { + /// The block sprite arrays, [`super::SPRITE_SPLIT`]-layer each. + pub sprites: &'a [wgpu::Texture], + pub split: u32, + /// Mipmap levels the terrain samples. + pub levels: u32, + /// The sprite layers and mip levels animation rewrote this frame. + pub animated: &'a [(u32, u32)], + pub lightmap: &'a wgpu::TextureView, + pub draw: &'a DrawTerrain<'a>, +} + +const ATLAS: &str = r#" +struct Atlas { cols: u32, layers: u32, split: u32, pad: u32 } +@group(0) @binding(0) var atlas: Atlas; +@group(0) @binding(1) var s0: texture_2d_array; +@group(0) @binding(2) var s1: texture_2d_array; +@group(0) @binding(3) var s2: texture_2d_array; +@group(0) @binding(4) var s3: texture_2d_array; +@group(0) @binding(5) var s4: texture_2d_array; +@group(0) @binding(6) var s5: texture_2d_array; +@group(0) @binding(7) var s6: texture_2d_array; +@group(0) @binding(8) var s7: texture_2d_array; + +struct Out { + @builtin(position) p: vec4f, + @location(0) @interpolate(flat) mip: u32, +} + +@vertex +fn vs(@builtin(vertex_index) i: u32, @builtin(instance_index) mip: u32) -> Out { + let uv = vec2f(f32((i << 1u) & 2u), f32(i & 2u)); + return Out(vec4f(uv * 2.0 - 1.0, 0.0, 1.0), mip); +} + +// Each sprite layer into its cell, at mip level `mip`. +@fragment +fn fs(in: Out) -> @location(0) vec4f { + let cell = max(textureDimensions(s0, in.mip).x, 1u); + let px = vec2u(in.p.xy); + let c = px / cell; + let layer = c.y * atlas.cols + c.x; + if c.x >= atlas.cols || layer >= atlas.layers { + return vec4f(0.0); + } + let at = px % cell; + let l = i32(layer % atlas.split); + let m = i32(in.mip); + switch layer / atlas.split { + case 0u: { return textureLoad(s0, at, l, m); } + case 1u: { return textureLoad(s1, at, l, m); } + case 2u: { return textureLoad(s2, at, l, m); } + case 3u: { return textureLoad(s3, at, l, m); } + case 4u: { return textureLoad(s4, at, l, m); } + case 5u: { return textureLoad(s5, at, l, m); } + case 6u: { return textureLoad(s6, at, l, m); } + default: { return textureLoad(s7, at, l, m); } + } +} +"#; + +/// Horizon's block sprites as one 2D atlas, as Iris binds `gtexture`: +/// square cells, [`atlas_columns`] to a row. Drawn from the sprite arrays +/// once, then animated sprites are copied in as they change. +pub struct Atlas { + texture: wgpu::Texture, + pub view: wgpu::TextureView, + mips: Vec, + pipeline: wgpu::RenderPipeline, + layout: wgpu::BindGroupLayout, + uniform: wgpu::Buffer, + /// Layers, sprite size, mip levels it was made for. + key: (u32, u32, u32), + /// The first sprite array it was drawn from (resource reloads make + /// new ones). + source: wgpu::Texture, + drawn: bool, +} + +impl Atlas { + /// The atlas for `world`'s sprites; `None` without any. + pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, world: &JavaWorld) -> Option { + let key = Self::key(world)?; + let (layers, size, levels) = key; + let cols = atlas_columns(layers); + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("Java shader pack block atlas"), + size: wgpu::Extent3d { + width: cols * size, + height: cols * size, + depth_or_array_layers: 1, + }, + mip_level_count: levels, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT + | wgpu::TextureUsages::TEXTURE_BINDING + | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + let mips = (0..levels) + .map(|level| { + texture.create_view(&wgpu::TextureViewDescriptor { + base_mip_level: level, + mip_level_count: Some(1), + ..Default::default() + }) + }) + .collect(); + let mut entries = vec![wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }]; + entries.extend((1..=8).map(|binding| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2Array, + multisampled: false, + }, + count: None, + })); + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Java shader pack block atlas"), + entries: &entries, + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Java shader pack block atlas"), + source: wgpu::ShaderSource::Wgsl(ATLAS.into()), + }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Java shader pack block atlas"), + layout: Some( + &device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Java shader pack block atlas"), + bind_group_layouts: &[Some(&layout)], + ..Default::default() + }), + ), + vertex: wgpu::VertexState { + module: &module, + entry_point: Some("vs"), + compilation_options: Default::default(), + buffers: &[], + }, + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some("fs"), + compilation_options: Default::default(), + targets: &[Some(wgpu::TextureFormat::Rgba8Unorm.into())], + }), + multiview_mask: None, + cache: None, + }); + let uniform = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Java shader pack block atlas"), + size: 16, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + queue.write_buffer( + &uniform, + 0, + bytemuck::cast_slice(&[cols, layers, world.split.max(1), 0]), + ); + Some(Self { + view: texture.create_view(&Default::default()), + texture, + mips, + pipeline, + layout, + uniform, + key, + source: world.sprites[0].clone(), + drawn: false, + }) + } + + fn key(world: &JavaWorld) -> Option<(u32, u32, u32)> { + let first = world.sprites.first()?; + let layers = world + .sprites + .iter() + .map(|t| t.depth_or_array_layers()) + .sum(); + let levels = (world.levels + 1).min(first.mip_level_count()).max(1); + Some((layers, first.width(), levels)) + } + + /// Whether it was made for `world`'s sprites. + pub fn fits(&self, world: &JavaWorld) -> bool { + Self::key(world) == Some(self.key) && world.sprites.first() == Some(&self.source) + } + + /// Bring it up to date: drawn the first time, then the sprites + /// animation rewrote copied into their cells. + pub fn update( + &mut self, + device: &wgpu::Device, + encoder: &mut wgpu::CommandEncoder, + world: &JavaWorld, + ) { + if !self.drawn { + self.draw(device, encoder, world); + self.drawn = true; + return; + } + let (layers, size, levels) = self.key; + let cols = atlas_columns(layers); + let split = world.split.max(1); + for &(layer, level) in world.animated { + let Some(array) = world.sprites.get((layer / split) as usize) else { + continue; + }; + if level >= levels || layer >= layers { + continue; + } + let edge = (size >> level).max(1); + encoder.copy_texture_to_texture( + wgpu::TexelCopyTextureInfo { + texture: array, + mip_level: level, + origin: wgpu::Origin3d { + x: 0, + y: 0, + z: layer % split, + }, + aspect: wgpu::TextureAspect::All, + }, + wgpu::TexelCopyTextureInfo { + texture: &self.texture, + mip_level: level, + origin: wgpu::Origin3d { + x: (layer % cols) * edge, + y: (layer / cols) * edge, + z: 0, + }, + aspect: wgpu::TextureAspect::All, + }, + wgpu::Extent3d { + width: edge, + height: edge, + depth_or_array_layers: 1, + }, + ); + } + } + + /// The atlas's size in pixels (`atlasSize`). + pub fn size(&self) -> [u32; 2] { + [self.texture.width(), self.texture.height()] + } + + /// Draw the sprites into the atlas, every mip level. + fn draw(&self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, world: &JavaWorld) { + let views: Vec = (0..8) + .map(|i| { + let t = world.sprites.get(i).unwrap_or(&world.sprites[0]); + t.create_view(&wgpu::TextureViewDescriptor { + dimension: Some(wgpu::TextureViewDimension::D2Array), + mip_level_count: Some(self.key.2), + ..Default::default() + }) + }) + .collect(); + let mut entries = vec![wgpu::BindGroupEntry { + binding: 0, + resource: self.uniform.as_entire_binding(), + }]; + entries.extend(views.iter().enumerate().map(|(i, v)| wgpu::BindGroupEntry { + binding: i as u32 + 1, + resource: wgpu::BindingResource::TextureView(v), + })); + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Java shader pack block atlas"), + layout: &self.layout, + entries: &entries, + }); + for (mip, view) in self.mips.iter().enumerate() { + let attachments = [Some(wgpu::RenderPassColorAttachment { + view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), + store: wgpu::StoreOp::Store, + }, + })]; + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Java shader pack block atlas"), + color_attachments: &attachments, + ..Default::default() + }); + pass.set_pipeline(&self.pipeline); + pass.set_bind_group(0, &group, &[]); + pass.draw(0..3, mip as u32..mip as u32 + 1); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// `module` validates and translates for Metal, Vulkan and DirectX 12. + fn backends(module: &naga::Module, label: &str) { + let info = naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::all(), + ) + .validate(module) + .unwrap_or_else(|e| panic!("{label}: {e:?}")); + naga::back::msl::write_string( + module, + &info, + // wgpu's Metal backend asks for MSL 2.x. + &naga::back::msl::Options { + lang_version: (2, 4), + ..Default::default() + }, + &naga::back::msl::PipelineOptions::default(), + ) + .unwrap_or_else(|e| panic!("{label} (MSL): {e}")); + naga::back::spv::write_vec(module, &info, &Default::default(), None) + .unwrap_or_else(|e| panic!("{label} (SPIR-V): {e}")); + for entry in &module.entry_points { + let mut hlsl = String::new(); + naga::back::hlsl::Writer::new( + &mut hlsl, + &naga::back::hlsl::Options::default(), + &naga::back::hlsl::PipelineOptions { + entry_point: Some((entry.stage, entry.name.clone())), + }, + ) + .write(module, &info, None) + .unwrap_or_else(|e| panic!("{label} {} (HLSL): {e}", entry.name)); + } + } + + /// A terrain program reading every attribute the glue fills, run after + /// each draw path's glue, and the atlas shader, on every backend. + #[test] + fn the_glue_feeds_a_terrain_program_on_every_backend() { + let program = "#version 120 +attribute vec4 mc_Entity; +attribute vec4 mc_midTexCoord; +attribute vec4 at_tangent; +attribute vec3 at_midBlock; +varying vec4 color; +varying vec2 uv; +varying vec2 lm; +varying vec3 normal; +varying float id; +void main() { + vec4 p = gl_ModelViewMatrix * gl_Vertex; + p.xyz += at_midBlock / 64.0 * 0.0 + at_tangent.xyz * 0.0; + gl_Position = gl_ProjectionMatrix * p; + color = gl_Color; + uv = (gl_TextureMatrix[0] * gl_MultiTexCoord0).xy + mc_midTexCoord.xy * 0.0; + lm = (gl_TextureMatrix[1] * gl_MultiTexCoord1).xy; + normal = gl_NormalMatrix * gl_Normal; + id = mc_Entity.x; +} +"; + for flat in [false, true] { + let mut link = horizon_shaderpack::translate::Link { + set: 2, + geometry: Some(glue(flat, Some(0.1))), + ..Default::default() + }; + let t = horizon_shaderpack::translate::translate( + horizon_shaderpack::Stage::Vertex, + program, + &mut link, + &|l| format!("line {l}"), + ) + .unwrap_or_else(|e| panic!("flat {flat}: {e}")); + for wanted in ["hz_vertex();", "mc_Entity = vec4(vec4(hz_block"] { + assert!(t.glsl.contains(wanted), "{wanted}\n{}", t.glsl); + } + // The glue's inputs are Horizon's vertex layout. + let inputs = t.module.entry_points[0].function.arguments.len(); + assert_eq!(inputs, if flat { 6 } else { 7 }, "{}", t.wgsl); + let reparsed = naga::front::wgsl::parse_str(&t.wgsl).unwrap(); + backends(&reparsed, &format!("terrain glue (flat {flat})")); + } + backends(&naga::front::wgsl::parse_str(ATLAS).unwrap(), "atlas"); + backends( + &naga::front::wgsl::parse_str(super::super::java_stages::BLIT).unwrap(), + "Java shader pack blits", + ); + } + + #[test] + fn sprites_take_their_blocks_ids() { + let layers: BTreeMap = [ + ("minecraft:block/oak_leaves", 0), + ("minecraft:block/water_still", 1), + ("minecraft:block/stone", 2), + ("minecraft:block/oak_log_top", 3), + ] + .into_iter() + .map(|(n, l)| (n.to_owned(), l)) + .collect(); + let ids: BTreeMap = [("oak_leaves", 10003), ("water", 8), ("oak_log", 7)] + .into_iter() + .map(|(n, i)| (n.to_owned(), i)) + .collect(); + assert_eq!(table(&layers, &ids), [2, 0, 10003, 8, -1, 7]); + assert_eq!(atlas_columns(5), 3); + assert_eq!(atlas_columns(0), 1); + } +} diff --git a/crates/horizon-client/src/java_pack.rs b/crates/horizon-client/src/java_pack.rs index e6bd28c7f..f0a1b85f0 100644 --- a/crates/horizon-client/src/java_pack.rs +++ b/crates/horizon-client/src/java_pack.rs @@ -2,11 +2,12 @@ //! a folder holding `shaders/`, or a `.zip`. `horizon-shaderpack` translates //! their full-screen programs (`begin`, `prepare`, `deferred`, `composite`, //! `final`) to WGSL, and `gfx/java_stages.rs` runs them over Horizon's world -//! as Iris runs them over its own. Geometry programs (`gbuffers_*`, -//! `shadow`) don't run yet: the world is drawn by Horizon. +//! as Iris runs them over its own. Of the geometry programs, the terrain's +//! (`gbuffers_terrain`, `gbuffers_water` and their fallbacks) draw Horizon's +//! terrain (`gfx/java_terrain.rs`); the rest of the world is Horizon's. use horizon_shaderpack::{ JavaPack, - pipeline::{Directives, Program, TargetSettings}, + pipeline::{Directives, GeometryProgram, Program, TargetSettings}, preprocess::Environment, properties::SkyDirectives, uniforms::CustomUniforms, @@ -32,6 +33,17 @@ pub struct JavaFolder { pub flipped_at_end: BTreeSet, /// `sunPathRotation` and `eyeBrightnessHalflife`. pub directives: Directives, + /// The programs Horizon's solid and translucent terrain are drawn with, + /// each translated for instanced and flat draws (`variants[0]`). + pub terrain: Option, + pub water: Option, + /// How many of `passes` run before translucent terrain (`begin*`, + /// `prepare*`, `deferred*`). + pub translucent_at: usize, + pub flipped_after_translucent: BTreeSet, + /// Each draw buffer's blending in `terrain` and `water`. + pub terrain_blends: Vec>, + pub water_blends: Vec>, } /// A loaded Java pack. @@ -41,6 +53,8 @@ pub struct JavaPasses { pub uniforms: CustomUniforms, /// What the pack keeps of the vanilla sky (`clouds`, `sun`, `moon`). pub sky: SkyDirectives, + /// `block.properties`: block name → `mc_Entity` id. + pub block_ids: BTreeMap, } impl JavaPasses { @@ -122,6 +136,50 @@ pub fn load( if passes.is_empty() && final_pass.is_none() { continue; } + // A geometry program that doesn't translate leaves that terrain to + // Horizon, with a warning. + let geometry = |pass: &Option, alpha_test| { + let pass = pass.as_ref()?; + let glues = [false, true].map(|flat| crate::gfx::java_terrain::glue(flat, alpha_test)); + match pack.compile_geometry(pass, &plan.targets, &values, &env, &properties, &glues) { + Ok(program) => Some(program), + Err(e) => { + log::warn!("Horizon: shader pack {}: {e}", pass.program); + None + } + } + }; + // Iris's alpha test of cutout terrain (`AlphaTests.ONE_TENTH_ALPHA`). + let terrain = geometry(&plan.terrain, Some(0.1)); + let water = terrain.as_ref().and_then(|_| geometry(&plan.water, None)); + let translucent_at = early.clone().count() + plan.deferred.len(); + let blends = |g: &Option, default| { + g.as_ref().map_or_else(Vec::new, |g| { + geometry_blends( + &properties, + &g.program.pass.program, + &g.program.draw_buffers, + default, + ) + }) + }; + let terrain_blends = blends(&terrain, None); + // Vanilla's translucent blending (`BlendFunction.TRANSLUCENT`). + let water_blends = blends( + &water, + Some(wgpu::BlendState { + color: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::SrcAlpha, + dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, + operation: wgpu::BlendOperation::Add, + }, + alpha: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::One, + dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, + operation: wgpu::BlendOperation::Add, + }, + }), + ); folders.push(JavaFolder { folder: name.to_owned(), targets: plan.targets, @@ -131,6 +189,12 @@ pub fn load( final_pass, flipped_at_end: plan.flipped_at_end, directives: plan.directives, + terrain, + water, + translucent_at, + flipped_after_translucent: plan.flipped_after_translucent, + terrain_blends, + water_blends, }); } if folders.is_empty() { @@ -140,10 +204,84 @@ pub fn load( for problem in &uniforms.problems { log::warn!("Horizon: shader pack custom uniform {problem}"); } + let block_ids = pack.block_ids(&values, &env).unwrap_or_else(|e| { + log::warn!("Horizon: shader pack {e}"); + BTreeMap::new() + }); Ok(JavaPasses { folders, uniforms, sky: properties.sky(), + block_ids, + }) +} + +/// A geometry program's blending per draw buffer: `default`, or the +/// pack's `blend.` and `blend..` (Iris's +/// `BlendModeOverride`; the folder isn't part of the name). +fn geometry_blends( + properties: &horizon_shaderpack::properties::ShaderProperties, + program: &str, + draw_buffers: &[u32], + default: Option, +) -> Vec> { + use horizon_shaderpack::properties::Blend; + let name = program.rsplit('/').next().unwrap_or(program); + let state = |blend: &Result| match blend { + Ok(Blend::Off) => Some(None), + Ok(Blend::Factors(f)) => { + let [a, b, c, d] = f.each_ref().map(|f| blend_factor(f)); + Some(Some(wgpu::BlendState { + color: wgpu::BlendComponent { + src_factor: a?, + dst_factor: b?, + operation: wgpu::BlendOperation::Add, + }, + alpha: wgpu::BlendComponent { + src_factor: c?, + dst_factor: d?, + operation: wgpu::BlendOperation::Add, + }, + })) + } + Err(e) => { + log::warn!("Horizon: shader pack blend.{name}: {e}"); + None + } + }; + let all = properties + .blend(name) + .and_then(|b| state(&b)) + .unwrap_or(default); + let buffers = properties.buffer_blends(name); + draw_buffers + .iter() + .map(|i| { + buffers + .iter() + .find(|(b, _)| b == i) + .and_then(|(_, b)| state(b)) + .unwrap_or(all) + }) + .collect() +} + +/// A GL blend factor's wgpu one. +fn blend_factor(name: &str) -> Option { + use wgpu::BlendFactor as F; + Some(match name { + "ZERO" => F::Zero, + "ONE" => F::One, + "SRC_COLOR" => F::Src, + "ONE_MINUS_SRC_COLOR" => F::OneMinusSrc, + "DST_COLOR" => F::Dst, + "ONE_MINUS_DST_COLOR" => F::OneMinusDst, + "SRC_ALPHA" => F::SrcAlpha, + "ONE_MINUS_SRC_ALPHA" => F::OneMinusSrcAlpha, + "DST_ALPHA" => F::DstAlpha, + "ONE_MINUS_DST_ALPHA" => F::OneMinusDstAlpha, + "SRC_ALPHA_SATURATE" => F::SrcAlphaSaturated, + _ => return None, }) } @@ -186,8 +324,18 @@ mod tests { .folders .iter() .flat_map(|f| f.passes.iter().chain(&f.final_pass)); + let geometry = pack + .folders + .iter() + .flat_map(|f| f.terrain.iter().chain(&f.water)); passes .flat_map(|p| [(p, &p.vertex, "vsh"), (p, &p.fragment, "fsh")]) + .chain(geometry.flat_map(|g| { + let p = &g.program; + [(p, &p.vertex, "vsh"), (p, &p.fragment, "fsh")] + .into_iter() + .chain(g.variants.iter().map(move |v| (p, v, "vsh (flat)"))) + })) .find_map(|(p, t, ext)| { let e = naga::front::wgsl::parse_str(&t.wgsl).err()?; Some(format!( @@ -227,7 +375,13 @@ mod tests { .iter() .map(|f| { let n = f.passes.len() + usize::from(f.final_pass.is_some()); - format!("{} {n} passes", f.folder) + let geometry: Vec<&str> = f + .terrain + .iter() + .chain(&f.water) + .map(|g| g.program.pass.program.as_str()) + .collect(); + format!("{} {n} passes, terrain {geometry:?}", f.folder) }) .collect(); println!("{name}: loads ({})", folders.join(", ")); diff --git a/crates/horizon-shaderpack/src/lib.rs b/crates/horizon-shaderpack/src/lib.rs index 71b6abbd3..981cbc654 100644 --- a/crates/horizon-shaderpack/src/lib.rs +++ b/crates/horizon-shaderpack/src/lib.rs @@ -156,6 +156,22 @@ impl JavaPack { } } +impl JavaPack { + /// The block ids of the pack's `block.properties` (empty without one), + /// [`properties::block_ids`]. + pub fn block_ids( + &self, + values: &OptionValues, + env: &Environment, + ) -> Result, String> { + match self.files.read("block.properties") { + Some(text) => properties::block_ids(&text, env, &self.options, values) + .map_err(|e| format!("block.properties: {e}")), + None => Ok(BTreeMap::new()), + } + } +} + /// A program's name in `shaders.properties` (`world-1/composite1.fsh` is /// `world-1/composite1`). pub fn program_name(program: &str) -> &str { diff --git a/crates/horizon-shaderpack/src/pipeline.rs b/crates/horizon-shaderpack/src/pipeline.rs index 7ebb35442..bcc1f310d 100644 --- a/crates/horizon-shaderpack/src/pipeline.rs +++ b/crates/horizon-shaderpack/src/pipeline.rs @@ -12,7 +12,7 @@ use crate::{ options::OptionValues, preprocess::Environment, properties::{LEGACY_TARGETS, ShaderProperties}, - translate::{Link, Translated}, + translate::{Geometry, Link, Translated}, }; use std::collections::{BTreeMap, BTreeSet}; @@ -319,8 +319,33 @@ pub struct Passes { /// next frame starts unflipped. pub flipped_at_end: BTreeSet, pub directives: Directives, + /// The program Horizon's solid terrain is drawn with + /// ([`TERRAIN_PROGRAMS`]), before `deferred`. + pub terrain: Option, + /// The program its translucent terrain is drawn with + /// ([`WATER_PROGRAMS`]), after `deferred`. + pub water: Option, } +/// The programs Iris draws solid terrain with, the first the pack has +/// (`ProgramId.Terrain`'s fallbacks). +pub const TERRAIN_PROGRAMS: &[&str] = &[ + "gbuffers_terrain", + "gbuffers_textured_lit", + "gbuffers_textured", + "gbuffers_basic", +]; + +/// The programs Iris draws translucent terrain with (`ProgramId.Water`'s +/// fallbacks). +pub const WATER_PROGRAMS: &[&str] = &[ + "gbuffers_water", + "gbuffers_terrain", + "gbuffers_textured_lit", + "gbuffers_textured", + "gbuffers_basic", +]; + /// The `const` directives of a program folder that aren't about targets /// (`PackDirectives`), read from the same programs in the same order. #[derive(Clone, Copy, Debug, PartialEq)] @@ -510,6 +535,22 @@ impl JavaPack { out.flipped_after_translucent = flipped.clone(); out.composite = run(&groups[3], "composite_pre", &mut flipped)?; out.flipped_at_end = flipped; + // Geometry writes the side the next passes read. + let geometry = |chain: &[&str], flipped: &BTreeSet| { + let Some(name) = chain.iter().find(|n| exists(n)) else { + return Ok::<_, String>(None); + }; + let text = fragment(name)?; + Ok(Some(Pass { + program: path(name), + draw_buffers: draw_buffers(&text).map_err(|e| format!("{}: {e}", path(name)))?, + reads_alt: flipped.clone(), + mipmapped: BTreeSet::new(), + scale: 1.0, + })) + }; + out.terrain = geometry(TERRAIN_PROGRAMS, &out.flipped_after_prepare)?; + out.water = geometry(WATER_PROGRAMS, &out.flipped_after_translucent)?; if exists("final") { out.final_pass = Some(Pass { program: path("final"), @@ -566,6 +607,70 @@ impl JavaPack { } } +/// A geometry program translated: the program (its vertex with the first +/// glue), and its vertex with each other glue. +pub struct GeometryProgram { + pub program: Program, + pub variants: Vec, +} + +impl JavaPack { + /// Translate geometry program `pass` (`gbuffers_*`) to run over + /// Horizon's geometry: its bindings in group 2, its attributes from + /// each of `glues` (the vertex program is translated once per glue). + #[allow(clippy::too_many_arguments)] + pub fn compile_geometry( + &self, + pass: &Pass, + targets: &[TargetSettings], + values: &OptionValues, + env: &Environment, + properties: &ShaderProperties, + glues: &[Geometry], + ) -> Result { + let (first, rest) = glues + .split_first() + .ok_or("a geometry program needs a glue")?; + let mut link = Link { + image_formats: properties.image_formats(), + shared_samplers: shared_samplers(targets), + set: 2, + geometry: Some(first.clone()), + ..Link::default() + }; + let vertex = self.translate(&format!("{}.vsh", pass.program), values, env, &mut link)?; + let fragment = self.translate(&format!("{}.fsh", pass.program), values, env, &mut link)?; + let mut variants = Vec::new(); + for glue in rest { + let mut other = link.clone(); + other.geometry = Some(glue.clone()); + variants.push(self.translate( + &format!("{}.vsh", pass.program), + values, + env, + &mut other, + )?); + if other.uniforms != link.uniforms || other.bindings != link.bindings { + return Err(format!("{}: its variants bind differently", pass.program)); + } + } + let draw_buffers = match &pass.draw_buffers { + Some(buffers) => buffers.clone(), + None => (0..fragment.interface.outputs.keys().max().map_or(1, |m| m + 1)).collect(), + }; + Ok(GeometryProgram { + program: Program { + pass: pass.clone(), + vertex, + fragment, + draw_buffers, + link, + }, + variants, + }) + } +} + /// Iris's sampler states for the textures it binds: colour targets /// linear (nearest for integer formats, and for 32-bit floats, which wgpu /// can't filter everywhere), depth nearest, noise repeating. For diff --git a/crates/horizon-shaderpack/src/properties.rs b/crates/horizon-shaderpack/src/properties.rs index 703d696cf..548fee50f 100644 --- a/crates/horizon-shaderpack/src/properties.rs +++ b/crates/horizon-shaderpack/src/properties.rs @@ -587,6 +587,58 @@ impl ShaderProperties { } } +/// `block.properties` (`block.=`), preprocessed as +/// `shaders.properties` is: each block's id by its name without namespace +/// (`oak_leaves`). A block listed with a state (`grass_block:snowy=true`) +/// takes that id only when no entry names it without one; numeric ids +/// (before 1.13) are skipped. +pub fn block_ids( + text: &str, + env: &Environment, + options: &OptionSet, + values: &OptionValues, +) -> Result, String> { + let properties = Properties::parse(&preprocess(text, env, options, values)?); + let mut plain = BTreeMap::new(); + let mut with_state = BTreeMap::new(); + for (key, value) in properties.iter() { + let Some(Ok(id)) = key.strip_prefix("block.").map(str::parse::) else { + continue; + }; + for entry in value.split_whitespace() { + let entry = entry.strip_prefix("minecraft:").unwrap_or(entry); + if entry.contains(':') && entry.split(':').nth(1).is_some_and(|s| s.contains('=')) { + let name = entry.split(':').next().unwrap_or(entry); + with_state.entry(name.to_owned()).or_insert(id); + } else if !entry.chars().all(|c| c.is_ascii_digit()) && !entry.contains('=') { + plain.insert(entry.to_owned(), id); + } + } + } + for (name, id) in with_state { + plain.entry(name).or_insert(id); + } + Ok(plain) +} + +/// The block a block sprite (`minecraft:block/oak_log_top`) belongs to in +/// `ids` ([`block_ids`]): the block named like it, else the longest one its +/// name starts with followed by `_` (`oak_log`, `water` for `water_still`). +pub fn sprite_block_id(sprite: &str, ids: &BTreeMap) -> Option { + let name = sprite.rsplit(['/', ':']).next()?; + if let Some(&id) = ids.get(name) { + return Some(id); + } + let mut end = name.len(); + while let Some(cut) = name[..end].rfind('_') { + if let Some(&id) = ids.get(&name[..cut]) { + return Some(id); + } + end = cut; + } + None +} + /// Iris's `BooleanParser`: options joined by `!`, `&&`, `||` and brackets, /// `&&` binding tighter. `true`/`1` and `false`/`0` are literals; a name that /// isn't a boolean option is true; a malformed expression is true. @@ -705,6 +757,42 @@ mod tests { set } + /// `block.properties` as Chocapic13' writes it, and sprites matched to + /// its blocks. + #[test] + fn block_ids_and_the_sprites_of_their_blocks() { + let text = "\ +#if MC_VERSION >= 11300 +block.10001= minecraft:wheat minecraft:short_grass +block.10003 = minecraft:oak_leaves \\ + minecraft:vine +block.10006 = minecraft:grass_block:snowy=true minecraft:snow +block.8 = minecraft:water +block.2 = minecraft:grass_block +#else +block.10001= 6 31 +#endif +layer.translucent=minecraft:glass +"; + let env = Environment { + defines: vec![("MC_VERSION".into(), "260300".into())], + }; + let ids = block_ids(text, &env, &OptionSet::default(), &OptionValues::default()).unwrap(); + assert_eq!(ids.get("vine"), Some(&10003)); + // The stateless entry wins over the snowy one. + assert_eq!(ids.get("grass_block"), Some(&2)); + assert!(!ids.contains_key("6") && !ids.contains_key("glass")); + for (sprite, id) in [ + ("minecraft:block/oak_leaves", Some(10003)), + ("minecraft:block/water_still", Some(8)), + ("minecraft:block/grass_block_top", Some(2)), + ("minecraft:block/wheat_stage7", Some(10001)), + ("minecraft:block/stone", None), + ] { + assert_eq!(sprite_block_id(sprite, &ids), id, "{sprite}"); + } + } + #[test] fn java_properties_syntax() { let p = Properties::parse( diff --git a/crates/horizon-shaderpack/src/translate.rs b/crates/horizon-shaderpack/src/translate.rs index e53b4895b..208fe84b5 100644 --- a/crates/horizon-shaderpack/src/translate.rs +++ b/crates/horizon-shaderpack/src/translate.rs @@ -40,7 +40,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; /// Locations, bindings and uniforms shared by the programs of one pass: a /// pass's vertex program is translated first, its fragment program second. -#[derive(Default, Debug)] +#[derive(Clone, Default, Debug)] pub struct Link { /// Varying name → location (split matrices and arrays as `name#i`). pub varyings: BTreeMap, @@ -59,6 +59,27 @@ pub struct Link { /// 16). Once any is named, comparison samplers share `iris_compare` and /// integer ones `iris_nearest`; textures not named keep `{name}_s`. pub shared_samplers: BTreeMap, + /// The bind group of the pack's bindings (0; 2 for geometry programs, + /// whose first groups are Horizon's). + pub set: u32, + /// Set for `gbuffers_*` programs drawn over Horizon's own geometry. + pub geometry: Option, +} + +/// How a `gbuffers_*` program runs over Horizon's geometry: its vertex +/// attributes aren't inputs but globals the glue fills from Horizon's +/// vertices before the program's `main`. +#[derive(Clone, Debug, Default)] +pub struct Geometry { + /// GLSL put before the vertex program: Horizon's vertex inputs and + /// buffers, and a `void hz_vertex()` run first in `main`. + pub vertex_glue: String, + /// Each attribute's value as a `vec4` expression of the glue + /// (`iris_Vertex`, `mc_Entity`, `vaUV0`...). Others are zero. + pub attributes: BTreeMap, + /// Iris's alpha test: the fragment is discarded unless output 0's + /// alpha is above it. + pub alpha_test: Option, } impl Link { @@ -368,6 +389,7 @@ pub fn translate( .parse(&options, &glsl) .map_err(|e| first_lines(&e.emit_to_string(&glsl)))?; unpad_private_arrays(&mut module); + end_returning_cases(&mut module); let info = naga::valid::Validator::new( naga::valid::ValidationFlags::all(), naga::valid::Capabilities::all(), @@ -387,6 +409,49 @@ pub fn translate( }) } +/// A `case` that ends with `return` or `discard` rather than `break` +/// (Photon's displacement) is a fall-through one to naga's GLSL front end, +/// which its WGSL writer refuses: nothing falls through it. +fn end_returning_cases(module: &mut naga::Module) { + fn block(b: &mut naga::Block) { + for s in b.iter_mut() { + match s { + naga::Statement::Block(inner) => block(inner), + naga::Statement::If { accept, reject, .. } => { + block(accept); + block(reject); + } + naga::Statement::Loop { + body, continuing, .. + } => { + block(body); + block(continuing); + } + naga::Statement::Switch { cases, .. } => { + for case in cases { + block(&mut case.body); + if case.fall_through + && matches!( + case.body.last(), + Some(naga::Statement::Return { .. } | naga::Statement::Kill) + ) + { + case.fall_through = false; + } + } + } + _ => {} + } + } + } + for (_, f) in module.functions.iter_mut() { + block(&mut f.body); + } + for e in &mut module.entry_points { + block(&mut e.function.body); + } +} + /// The GLSL built-ins naga's constant evaluator folds (`MathFunction`s it /// implements), besides type constructors. const FOLDABLE: &[&str] = &[ @@ -612,6 +677,8 @@ struct Legaliser<'a> { gather: bool, /// Constants turned into globals ([`needs_runtime`]). runtime_constants: HashSet, + /// Geometry programs: each attribute's type, for the glue. + attribute_types: BTreeMap, } fn var(name: &str) -> ast::Expr { @@ -897,6 +964,7 @@ impl<'a> Legaliser<'a> { nan: false, gather: false, runtime_constants: HashSet::new(), + attribute_types: BTreeMap::new(), } } @@ -969,7 +1037,8 @@ impl<'a> Legaliser<'a> { show_declaration(&mut text, d, &mut FormattingState::default()) .map_err(|e| e.to_string())?; self.header.push(format!( - "layout({kind}, set = 0, binding = {binding}) {}", + "layout({kind}, set = {}, binding = {binding}) {}", + self.link.set, text.trim() )); Ok(false) @@ -1028,7 +1097,8 @@ impl<'a> Legaliser<'a> { for (name, _) in &names { let t = self.link.binding(&format!("{name}_t")); self.header.push(format!( - "layout(set = 0, binding = {t}) uniform {texture} {name}_t;" + "layout(set = {}, binding = {t}) uniform {texture} {name}_t;", + self.link.set )); let shared = &self.link.shared_samplers; let var = if shared.is_empty() { @@ -1046,7 +1116,8 @@ impl<'a> Legaliser<'a> { if self.sampler_vars.insert(var.clone()) { let s = self.link.binding(&var); self.header.push(format!( - "layout(set = 0, binding = {s}) uniform {sampler} {var};" + "layout(set = {}, binding = {s}) uniform {sampler} {var};", + self.link.set )); } self.interface @@ -1085,7 +1156,8 @@ impl<'a> Legaliser<'a> { .unwrap_or_else(|| "rgba8".to_owned()); let binding = self.link.binding(name); layout.push(format!( - "layout({f}, set = 0, binding = {binding}) {memory}uniform {ty} {name};" + "layout({f}, set = {}, binding = {binding}) {memory}uniform {ty} {name};", + self.link.set )); self.interface.images.push((name.clone(), f)); } @@ -1146,9 +1218,8 @@ impl<'a> Legaliser<'a> { for (i, (name, array)) in names.iter().enumerate() { let full = format!("{ty}{ty_array}"); if input { - let at = Link::location(&mut self.link.attributes, name); - self.header - .push(format!("layout(location = {at}) in {full} {name}{array};")); + let decl = self.attribute(&full, name, array); + self.header.push(decl); self.interface.attributes.insert(name.clone()); } else if !varying { let at = explicit @@ -1640,9 +1711,8 @@ impl<'a> Legaliser<'a> { let ty = LEGACY_ATTRIBUTES.iter().find(|(a, _)| *a == n).unwrap().1; let renamed = n.replacen("gl_", "iris_", 1); if self.interface.attributes.insert(renamed.clone()) { - let at = Link::location(&mut self.link.attributes, &renamed); - self.header - .push(format!("layout(location = {at}) in {ty} {renamed};")); + let decl = self.attribute(ty, &renamed, ""); + self.header.push(decl); } renamed } @@ -1664,6 +1734,21 @@ impl<'a> Legaliser<'a> { } } + /// A vertex attribute's declaration: an input, or for geometry programs + /// a global the glue fills ([`Geometry`]). + fn attribute(&mut self, ty: &str, name: &str, array: &str) -> String { + match &self.link.geometry { + Some(_) => { + self.attribute_types.insert(name.to_owned(), ty.to_owned()); + format!("{ty} {name}{array};") + } + None => { + let at = Link::location(&mut self.link.attributes, name); + format!("layout(location = {at}) in {ty} {name}{array};") + } + } + } + fn frag_data(&mut self, n: u32) -> ast::Expr { let name = format!("iris_FragData{n}"); if self.interface.outputs.insert(n, name.clone()).is_none() { @@ -1896,9 +1981,8 @@ impl<'a> Legaliser<'a> { continue; } if attribute && self.stage == Stage::Vertex { - let at = Link::location(&mut self.link.attributes, name); - self.header - .push(format!("layout(location = {at}) in {ty} {name};")); + let decl = self.attribute(ty, name, ""); + self.header.push(decl); self.interface.attributes.insert(name.to_owned()); } else if !attribute { self.link.uniform(name, format!("{ty} {name}"))?; @@ -1908,6 +1992,42 @@ impl<'a> Legaliser<'a> { if !self.errors.is_empty() { return Err(self.errors.join("\n")); } + if let Some(geometry) = &self.link.geometry { + match self.stage { + Stage::Vertex => { + // The glue first, then the attributes from it, before + // the global initialisers (which may read them). + let mut first = vec!["hz_vertex();".to_owned()]; + for (name, ty) in &self.attribute_types { + first.push(match geometry.attributes.get(name) { + Some(value) => format!("{name} = {ty}({value});"), + None => format!("{name} = {ty}(0);"), + }); + } + self.prologue.splice(0..0, first); + } + Stage::Fragment => { + if let (Some(reference), Some(name)) = + (geometry.alpha_test, self.interface.outputs.get(&0)) + { + let written = format!("iris_out_{name}"); + let name = if self.declared.contains(&written) + || self + .header + .iter() + .any(|h| h.ends_with(&format!(" {written};"))) + { + written + } else { + name.clone() + }; + self.epilogue + .push(format!("if (!({name}.a > {reference:?})) discard;")); + } + } + _ => {} + } + } if self.stage == Stage::Vertex { // GL's clip space to wgpu's: y flipped, so texture row 0 stays // the bottom of the picture as in GL (texture coordinates and @@ -1919,6 +2039,10 @@ impl<'a> Legaliser<'a> { } let mut out = String::from("#version 450 core\n"); out.push_str(HELPERS); + if let (Some(geometry), Stage::Vertex) = (&self.link.geometry, self.stage) { + out.push_str(&geometry.vertex_glue); + out.push('\n'); + } if self.modulo { out.push_str(&modulo_helpers()); } @@ -1929,7 +2053,10 @@ impl<'a> Legaliser<'a> { out.push_str("float iris_sqrt(float x) { return sqrt(x); }\n"); } if !self.link.uniforms.is_empty() { - out.push_str("layout(std140, set = 0, binding = 0) uniform IrisUniforms {\n"); + out.push_str(&format!( + "layout(std140, set = {}, binding = 0) uniform IrisUniforms {{\n", + self.link.set + )); for (_, decl) in &self.link.uniforms { out.push_str(&format!(" {decl};\n")); } diff --git a/crates/horizon-shaderpack/tests/translate.rs b/crates/horizon-shaderpack/tests/translate.rs index f34c90520..e6068aaea 100644 --- a/crates/horizon-shaderpack/tests/translate.rs +++ b/crates/horizon-shaderpack/tests/translate.rs @@ -7,7 +7,7 @@ use horizon_shaderpack::{ include::Inlined, preprocess::{Environment, preprocess}, program_name, - translate::{Link, Translated, translate}, + translate::{Geometry, Link, Translated, translate}, }; use std::collections::{BTreeMap, BTreeSet}; @@ -403,6 +403,95 @@ void main() {{ ); } +/// A `gbuffers_*` program over Horizon's geometry: its attributes are +/// globals the glue fills before `main`, its bindings in group 2, and its +/// fragment discards below Iris's alpha test. A `case` ending in `return` +/// (Photon's displacement) isn't a fall-through for naga. +#[test] +fn geometry_programs_take_their_attributes_from_the_glue() { + let glue = Geometry { + vertex_glue: "layout(location = 0) in vec3 hz_position; +layout(std430, set = 3, binding = 0) readonly buffer HzTable { int hz_table[]; }; +vec4 hz_pos; +void hz_vertex() { hz_pos = vec4(hz_position, 1.0) + float(hz_table[0]); }" + .into(), + attributes: [ + ("iris_Vertex".to_owned(), "hz_pos".to_owned()), + ( + "mc_Entity".to_owned(), + "vec4(8.0, -1.0, 0.0, 0.0)".to_owned(), + ), + ] + .into(), + alpha_test: Some(0.1), + }; + let mut link = Link { + set: 2, + geometry: Some(glue), + ..Link::default() + }; + let vs = run( + Stage::Vertex, + "uniform sampler2D noisetex; +attribute vec4 mc_Entity; +attribute vec2 mc_midTexCoord; +varying vec2 uv; +vec3 sway(vec3 p, int id) { + switch (id) { + case 8: + return p + 1.0; + case 9: + case 10: + return p - 1.0; + default: + return p; + } +} +void main() { + uv = gl_MultiTexCoord0.xy + mc_midTexCoord; + gl_Position = gl_ModelViewProjectionMatrix * vec4(sway(gl_Vertex.xyz, int(mc_Entity.x)), 1.0); +} +", + &mut link, + ) + .unwrap(); + for wanted in [ + "hz_vertex();", + "mc_Entity = vec4(vec4(8.0, -1.0, 0.0, 0.0));", + "iris_Vertex = vec4(hz_pos);", + "mc_midTexCoord = vec2(0);", + "set = 2, binding = 0) uniform IrisUniforms", + ] { + assert!(vs.glsl.contains(wanted), "{wanted}\n{}", vs.glsl); + } + // Horizon's vertex input is the only one. + assert_eq!( + io(&vs, false).into_keys().collect::>(), + ["hz_position"] + ); + reparse(&vs.wgsl).unwrap(); + let fs = run( + Stage::Fragment, + "uniform sampler2D gtexture; +varying vec2 uv; +void main() { + /* DRAWBUFFERS:02 */ + gl_FragData[0] = texture2D(gtexture, uv); + gl_FragData[1] = vec4(1.0); +} +", + &mut link, + ) + .unwrap(); + assert!( + fs.glsl.contains("if (!(iris_FragData0.a > 0.1)) discard;"), + "{}", + fs.glsl + ); + assert!(fs.glsl.contains("set = 2, binding = "), "{}", fs.glsl); + reparse(&fs.wgsl).unwrap(); +} + /// A fragment output narrower than its four-channel target (Steadfast's /// `final` writes `out vec3 color`) is written through a `vec4` with alpha 1: /// GL fills the missing channels, wgpu refuses the pipeline. diff --git a/docs/shader-packs.md b/docs/shader-packs.md index 3b3a47189..3d32e37f6 100644 --- a/docs/shader-packs.md +++ b/docs/shader-packs.md @@ -22,7 +22,8 @@ Both are off by default. With no pack selected the renderer draws exactly what i | Java shader packs: full-screen pass plan (`horizon_shaderpack::pipeline`: `DRAWBUFFERS`/`RENDERTARGETS`, `colortexN` formats and clearing, buffer flips) | done: planned for the three test packs | | Java shader packs: full-screen passes drawn (`java_pack.rs`, `gfx/java_stages.rs`: `begin`, `prepare`, `deferred*`, `composite*`, `final` over Horizon's world) | first slice: BSL and Complementary run (below) | | Java shader packs: custom uniforms (`horizon_shaderpack::uniforms`), `sunPathRotation`, `clouds`/`sun`/`moon`, eye light | done for the full-screen passes (below) | -| Java shader packs: `gbuffers_*`, `shadow`, custom textures, images, compute, option screen | planned | +| Java shader packs: `gbuffers_terrain`, `gbuffers_water` (`gfx/java_terrain.rs`: Horizon's terrain fed to the pack's programs) | first slice: MakeUp Ultra Fast, Chocapic13' and BSL draw their own terrain and water (below) | +| Java shader packs: other `gbuffers_*`, `shadow`, custom textures, images, compute, option screen | planned | ## How the renderer draws a frame today @@ -347,6 +348,25 @@ Picking one translates every planned pass of each dimension folder (`java_pack.r 4. `final` draws into a target that replaces the world's picture, where Horizon packs' `composite` output goes: the hand, menus and HUD are drawn over it. +When the pack has a `gbuffers_terrain` (or `textured_lit`, `textured`, `basic`, the program Iris falls back to), the +pack draws the terrain itself (`gfx/java_terrain.rs`): Horizon's world pass skips its own solid and translucent +terrain, then + +- at step 2, after Horizon's sky, entities and the rest enter `colortex0` and depth, the pack's terrain program draws + every visible section into its `RENDERTARGETS` (the side the next pass reads), tested against that depth; the + depth is then copied into `depthtex0` and `depthtex1`; +- before the first `composite`, as Iris does, `gbuffers_water` (or the terrain program) draws the translucent + layer with the pack's `blend.*` or vanilla's blending; the depth goes into `depthtex0` only. + +The pack's vertex program reads Horizon's own terrain vertices (the arena pages, instanced or flat draws): a glue +function written before `main` decodes them into Iris's attributes (`vaPosition`/`gl_Vertex` relative to the camera, +`gl_Color` with vanilla's face shading undone, `gl_MultiTexCoord0/1`, the normal and `at_tangent` from the quad's +four corners, `mc_midTexCoord`, `at_midBlock`), and `mc_Entity.x` is the block's id from the pack's +`block.properties`, matched to the sprite's block by name. `gtexture`/`texture` is a 2D atlas built from Horizon's +sprite arrays (animated sprites copied in each frame), `lightmap` is Horizon's lightmap with Iris's texture matrix, +and fragments under alpha 0.1 are discarded (`alphaTestRef`). `RGBA16` targets are 16-bit unorm where the GPU can +render them (Chocapic13' packs its G-buffer into them; half floats broke it). + What makes Horizon look like OpenGL to the pack: - **Layout.** The translator ends every vertex shader by flipping `gl_Position.y` and moving depth from `[-w, w]` to @@ -377,10 +397,13 @@ What makes Horizon look like OpenGL to the pack: Measured on the Mac mini (M4 Pro) with the packs' default options: BSL v10.1.8 and Complementary Reimagined r5.9.3 grade and light Horizon's world as their post-processing would. Sildur's Vibrant v2.02 draws only its sky: its -`deferred` reads the albedo `gbuffers_*` write to `colortex4`. Without `gbuffers_*` and `shadow`, no pack has its -shadows, water or sky look yet; Distant Horizons' and Voxy's depth read as far. Not supported yet: images and +`deferred` reads the albedo `gbuffers_*` write to `colortex4` (not checked again since the terrain programs run). +Without the other `gbuffers_*` and `shadow`, no pack has its shadows or sky look yet; Distant Horizons' and Voxy's depth read as far. Not supported yet: images and compute (`.csh`; a pack that needs them doesn't load), mipmapped targets (`colortexNMipmapEnabled` is read but -ignored), custom textures, the option screen; shadow matrices are identity. +ignored), custom textures, the option screen; shadow matrices are identity. With the pack's terrain: entities, the +sky, the hand, weather and clouds are still Horizon's (in `colortex0` only), GPU occlusion culling is off, block ids +come from sprite names rather than block states, distant (LOD) terrain doesn't repeat its textures, and only the +overworld has been checked. ### Compatibility @@ -388,18 +411,19 @@ Tested on 2026-10-22 on the Mac mini (M4 Pro, Metal) with each pack's default op the authors' pages (dev-only test inputs, kept outside the repository). "Loads" means every pass the pack enables for the overworld, Nether and End is preprocessed, translated and validated, as the game does when the pack is picked (`java_pack::tests::real_packs_load` with `HORIZON_TEST_SHADERPACKS`); "drawn" means it was also picked in the game -and screenshotted. Only full-screen passes run (above), so no pack has its own terrain, water, shadows or sky yet. +and screenshotted. Full-screen passes, `gbuffers_terrain` and `gbuffers_water` run (above); no pack has its own +shadows, entities or sky yet. | Pack | Version | Result | First thing that stops it | | --- | --- | --- | --- | -| BSL | v10.1.8 | drawn: 26 passes | | +| BSL | v10.1.8 | drawn: 26 passes and its terrain and water programs | | | Complementary Reimagined | r5.9.3 | drawn: 27 passes | | | Complementary Unbound | r5.8 | loads: 27 passes | | | Sildur's Vibrant Extreme | 2.02 | drawn: 18 passes, only its sky (above) | | | Steadfast | 0.8.0 | drawn: 3 passes | | -| Chocapic13' | V9 High | drawn: 16 passes, its grade and fog over Horizon's world | | -| MakeUp Ultra Fast | 9.6 | drawn: 6 passes; its fog covers everything without its `gbuffers_*` | | -| Photon | v1.4 | loads: 27 passes; draws black: it lights the scene from the G-buffer its `gbuffers_*` write | | +| Chocapic13' | V9 High | drawn: 16 passes and its terrain and water programs | | +| MakeUp Ultra Fast | 9.6 | drawn: 6 passes and its terrain and water programs | | +| Photon | v1.4 | loads: 27 passes and its terrain and water programs; draws black | its sky and light come from a compute pass and `.dat` look-up tables, not loaded yet | | Bliss | 2.1.2 | fails | `world0/composite1.fsh`: a vector component passed to an `inout` parameter (WGSL can't point at one) | | Bloop | 1.8.0-Alpha-3 | fails | `world0/prepare1.fsh`: `mat2(vec4)` and other constructors naga's GLSL front end refuses | | Noble | v1.9.9 | fails (Apple and NVIDIA) | `world0/deferred4.vsh`: a `vec3[9][9]` varying (nested arrays between stages) | @@ -440,9 +464,9 @@ What the translator does for these packs, as Iris (JCPP and its GLSL transformer 3. **Full-screen programs**: `deferred*`, `composite*`, `final` with `colortex0..15` (formats from the pack), `depthtex0..2`, `noisetex` and the uniforms (most are already computed for the world shaders). This alone runs Sildur's and BSL post-processing over Horizon's own world. -4. **`gbuffers_terrain`, `gbuffers_water`, `gbuffers_sky*`**: Horizon's terrain vertices extended with Iris's - attributes (`mc_Entity` from `block.properties`, `mc_midTexCoord`, `at_tangent`, lightmap), a second set of - terrain pipelines writing the pack's render targets. +4. **`gbuffers_terrain`, `gbuffers_water`** (done, above), **`gbuffers_sky*`**: Horizon's terrain vertices decoded + into Iris's attributes (`mc_Entity` from `block.properties`, `mc_midTexCoord`, `at_tangent`, lightmap), a second + set of terrain pipelines writing the pack's render targets. 5. **Entities, block entities, hand, weather, clouds, particles** `gbuffers_*`. 6. **Shadow pass**: terrain and entities from the sun into `shadowtex0/1` and `shadowcolor0/1`, culled from the light's view, with the pack's distortion. From c344a26e80c4b85c39775d54e7727d7babdae9d5 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:05:26 +0200 Subject: [PATCH 004/408] Java shader packs: occlusion culling while the pack draws the terrain The pack's terrain program draws the solid sections the last test saw, the boxes of the others are tested against the pack's depth in a pass of their own (OpenGL's layout: y flipped, depth 0 near, so a second depth-only culling pipeline), and the program then draws the sections in sight from the culling's phase 2 draws. The flat path, which has no occlusion culling, is unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/gfx.rs | 57 ++++++--- crates/horizon-client/src/gfx/cull.rs | 120 +++++++++++++----- crates/horizon-client/src/gfx/cull.wgsl | 38 +++++- crates/horizon-client/src/gfx/java_stages.rs | 54 ++++---- crates/horizon-client/src/gfx/java_terrain.rs | 24 +++- docs/shader-packs.md | 6 +- 6 files changed, 213 insertions(+), 86 deletions(-) diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index bc49052f1..1d924e229 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -2541,17 +2541,22 @@ impl Renderer { i += run; } } - /// Horizon's terrain, solid or `translucent`, with a Java pack's - /// geometry pipelines (`java_terrain::DrawTerrain`): the frame's flat - /// draws or its section draws, each page with its group 3. + /// One `layer` of Horizon's terrain with a Java pack's geometry + /// pipelines (`java_terrain::DrawTerrain`): the frame's flat draws or its + /// section draws, each page with its group 3. `draws` are the frame's + /// phase 1 solid draws, all its solid draws and its translucent ones; + /// `culling` tells whether phase 2's come from occlusion culling. fn draw_java_terrain( &self, pass: &mut wgpu::RenderPass<'_>, - translucent: bool, + layer: java_terrain::Layer, pipelines: &java_terrain::TerrainPipelines, flat_frame: bool, - draws: [u32; 2], + draws: [u32; 3], + culling: bool, ) { + use java_terrain::Layer; + let translucent = layer == Layer::Translucent; let page = |pass: &mut wgpu::RenderPass<'_>, page: u32| { if let Some(Some((_, group))) = self.java_pages.get(page as usize) { pass.set_bind_group(3, group, &[]); @@ -2559,6 +2564,8 @@ impl Renderer { }; pass.set_bind_group(2, pipelines.group, &[]); match (self.flat.as_ref().filter(|_| flat_frame), pipelines.flat) { + // The flat path doesn't cull by occlusion: phase 1 is everything. + (Some(_), Some(_)) if layer == Layer::Revealed => {} (Some(flat), Some(pipeline)) => { pass.set_pipeline(pipeline); let calls = if translucent { @@ -2570,16 +2577,22 @@ impl Renderer { } (Some(_), None) => {} (None, _) => { + let [phase1, solid, translucent_draws] = draws; + let cull = self.cull.as_ref().filter(|_| culling); + let (indirect, base, first, count) = match (layer, cull) { + (Layer::Solid, Some(_)) => (&self.indirect, 0, 0, phase1), + (Layer::Solid, None) => (&self.indirect, 0, 0, solid), + (Layer::Revealed, Some(c)) => (&c.phase2, phase1, phase1, solid - phase1), + (Layer::Revealed, None) => return, + (Layer::Translucent, _) => (&self.indirect, 0, solid, translucent_draws), + }; + if count == 0 { + return; + } pass.set_pipeline(pipelines.instanced); pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); pass.set_vertex_buffer(1, self.instances.slice(..)); - let [solid, translucent_draws] = draws; - let (first, count) = if translucent { - (solid, translucent_draws) - } else { - (0, solid) - }; - self.draw_sections_with(pass, &self.indirect, 0, first, count, page); + self.draw_sections_with(pass, indirect, base, first, count, page); } } } @@ -3185,8 +3198,8 @@ impl Renderer { .inverse() .transform_point3(Vec3::ZERO); // A Java pack that draws the terrain (`gfx/java_terrain.rs`): the - // world pass leaves it out, and occlusion culling (which tests - // against its depth) is off. + // world pass leaves it out, and occlusion culling tests against the + // pack's depth (`Cull::test_gl`). let java_terrain = !frame.title && self.java_table.is_some() && matches!(&self.pack, Some(Pack::Java(j)) if j.draws_terrain(frame.shader.dimension)); @@ -3200,7 +3213,6 @@ impl Renderer { && !frame.title && self.multi_draw && !(self.flat_on && self.flat.is_some()) - && !java_terrain }) .and_then(|cull| cull.begin(&self.device).then_some(cull)); self.phase2_draws.clear(); @@ -3887,11 +3899,17 @@ impl Renderer { && let Some(mut stages) = self.pack.take() { // The pack's terrain programs draw with the frame's draws. - let draws = [solid_draws, translucent_draws]; + let draws = [phase1_draws, solid_draws, translucent_draws]; let draw = |render: &mut wgpu::RenderPass<'_>, - translucent: bool, + layer: java_terrain::Layer, pipelines: &java_terrain::TerrainPipelines| { - self.draw_java_terrain(render, translucent, pipelines, flat_frame, draws); + self.draw_java_terrain(render, layer, pipelines, flat_frame, draws, culling); + }; + let cull = self.cull.as_ref().filter(|_| culling && solid_draws > 0); + let occlusion = |encoder: &mut wgpu::CommandEncoder, depth: &wgpu::TextureView| { + if let Some(cull) = cull { + cull.test_gl(encoder, depth); + } }; let world = java_terrain::JavaWorld { sprites: &self.sprite_textures, @@ -3900,6 +3918,9 @@ impl Renderer { animated: &self.animated, lightmap: &self.lightmap_view, draw: &draw, + occlusion: cull + .is_some() + .then_some(&occlusion as &java_terrain::OcclusionTest), }; let output = match &mut stages { Pack::Horizon(stages) => stages.run( diff --git a/crates/horizon-client/src/gfx/cull.rs b/crates/horizon-client/src/gfx/cull.rs index bcb738de3..57acec5f5 100644 --- a/crates/horizon-client/src/gfx/cull.rs +++ b/crates/horizon-client/src/gfx/cull.rs @@ -76,6 +76,8 @@ struct Group { pub struct Cull { pipeline: wgpu::RenderPipeline, + /// [`Self::test_gl`]'s: a depth-only pass in OpenGL's layout. + gl_pipeline: wgpu::RenderPipeline, layout: wgpu::BindGroupLayout, group: Option, params: wgpu::Buffer, @@ -187,43 +189,63 @@ impl Cull { bind_group_layouts: &[Some(&layout)], ..Default::default() }); - let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some("Section culling"), - layout: Some(&pipeline_layout), - vertex: wgpu::VertexState { - module: &module, - entry_point: Some("vs_box"), - compilation_options: Default::default(), - buffers: &[], - }, - primitive: wgpu::PrimitiveState { - cull_mode: Some(wgpu::Face::Back), - ..Default::default() - }, - // The world pass's reversed depth test, without writes. - depth_stencil: Some(wgpu::DepthStencilState { - format: wgpu::TextureFormat::Depth32Float, - depth_write_enabled: Some(false), - depth_compare: Some(wgpu::CompareFunction::GreaterEqual), - stencil: Default::default(), - bias: Default::default(), - }), - multisample: Default::default(), - fragment: Some(wgpu::FragmentState { - module: &module, - entry_point: Some("fs_box"), - compilation_options: Default::default(), - targets: &[Some(wgpu::ColorTargetState { - format: color, - blend: None, - write_mask: wgpu::ColorWrites::empty(), - })], - }), - multiview_mask: None, - cache: None, - }); + let pipeline = |label, gl: bool, targets: &[Option]| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(label), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &module, + entry_point: Some(if gl { "vs_box_gl" } else { "vs_box" }), + compilation_options: Default::default(), + buffers: &[], + }, + // OpenGL's layout flips y, and with it the faces' winding. + primitive: wgpu::PrimitiveState { + cull_mode: Some(wgpu::Face::Back), + front_face: if gl { + wgpu::FrontFace::Cw + } else { + wgpu::FrontFace::Ccw + }, + ..Default::default() + }, + // The pass's depth test (reversed in the world pass, OpenGL's + // in a Java pack's), without writes. + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(false), + depth_compare: Some(if gl { + wgpu::CompareFunction::LessEqual + } else { + wgpu::CompareFunction::GreaterEqual + }), + stencil: Default::default(), + bias: Default::default(), + }), + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some(if gl { "fs_box_depth" } else { "fs_box" }), + compilation_options: Default::default(), + targets, + }), + multiview_mask: None, + cache: None, + }) + }; + let gl_pipeline = pipeline("Section culling, OpenGL layout", true, &[]); + let pipeline = pipeline( + "Section culling", + false, + &[Some(wgpu::ColorTargetState { + format: color, + blend: None, + write_mask: wgpu::ColorWrites::empty(), + })], + ); Self { pipeline, + gl_pipeline, layout, group: None, params: buffer( @@ -413,6 +435,34 @@ impl Cull { pass.draw(0..36, 0..self.test_data.len() as u32); } + /// [`Self::test`] for a Java shader pack that draws the terrain + /// (`gfx/java_stages.rs`): in a pass of its own against `depth`, the + /// pack's depth after phase 1 in OpenGL's layout (y up, 0 near). + pub fn test_gl(&self, encoder: &mut wgpu::CommandEncoder, depth: &wgpu::TextureView) { + let Some(Group { group, .. }) = &self.group else { + return; + }; + if self.test_data.is_empty() { + return; + } + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Section culling, Java shader pack"), + color_attachments: &[], + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: depth, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Load, + store: wgpu::StoreOp::Store, + }), + stencil_ops: None, + }), + ..Default::default() + }); + pass.set_pipeline(&self.gl_pipeline); + pass.set_bind_group(0, group, &[]); + pass.draw(0..36, 0..self.test_data.len() as u32); + } + /// After the world passes: copy the results for reading back, when a /// readback buffer is free. pub fn end(&mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder) { diff --git a/crates/horizon-client/src/gfx/cull.wgsl b/crates/horizon-client/src/gfx/cull.wgsl index faa495caf..8345c15ae 100644 --- a/crates/horizon-client/src/gfx/cull.wgsl +++ b/crates/horizon-client/src/gfx/cull.wgsl @@ -52,6 +52,10 @@ fn corner(origin: vec3, c: u32) -> vec3 { // section fail the depth test against the final depth, which is only nearer. @vertex fn vs_box(@builtin(vertex_index) v: u32, @builtin(instance_index) t: u32) -> Box { + return box_vertex(v, t); +} + +fn box_vertex(v: u32, t: u32) -> Box { let origin = origins[tests[t].x].xyz; var out: Box; out.test = t; @@ -86,16 +90,36 @@ fn vs_box(@builtin(vertex_index) v: u32, @builtin(instance_index) t: u32) -> Box return out; } -// Runs only for fragments that pass the depth test (forced early). -@fragment -@early_depth_test(force) -fn fs_box(in: Box) -> @location(0) vec4 { - if results[in.test] != params.stamp { - results[in.test] = params.stamp; - let test = tests[in.test]; +// The same box in OpenGL's layout, for a Java shader pack's terrain depth +// (gfx/java_stages.rs): y flipped, depth from 0 near to 1 far. +@vertex +fn vs_box_gl(@builtin(vertex_index) v: u32, @builtin(instance_index) t: u32) -> Box { + var out = box_vertex(v, t); + out.position = vec4(out.position.x, -out.position.y, out.position.w - out.position.z, out.position.w); + return out; +} + +fn seen(index: u32) { + if results[index] != params.stamp { + results[index] = params.stamp; + let test = tests[index]; for (var k = 0u; k < test.z; k++) { phase2[(test.y + k) * 5u + 1u] = 1u; } } +} + +// Runs only for fragments that pass the depth test (forced early). +@fragment +@early_depth_test(force) +fn fs_box(in: Box) -> @location(0) vec4 { + seen(in.test); return vec4(0.0); } + +// fs_box in a pass without colour targets. +@fragment +@early_depth_test(force) +fn fs_box_depth(in: Box) { + seen(in.test); +} diff --git a/crates/horizon-client/src/gfx/java_stages.rs b/crates/horizon-client/src/gfx/java_stages.rs index 19e2109e0..52bba0893 100644 --- a/crates/horizon-client/src/gfx/java_stages.rs +++ b/crates/horizon-client/src/gfx/java_stages.rs @@ -13,7 +13,7 @@ //! into the pack's targets right after, against the world's depth, and its //! `gbuffers_water` draws the translucent terrain after `deferred`, as in //! Iris. `depthtex1` and `depthtex2` then hold the depth before it. -use super::java_terrain::{Atlas, JavaWorld, TerrainPipelines}; +use super::java_terrain::{Atlas, JavaWorld, Layer, TerrainPipelines}; use super::pack_stages::FrameUniform; use crate::java_pack::{JavaFolder, JavaPasses}; use glam::{Mat3, Mat4, Vec3, Vec4}; @@ -1748,28 +1748,38 @@ impl PassGpu { Some(color_attachment(side, None)) }) .collect(); - let mut render = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { - label: Some(&self.program), - color_attachments: &attachments, - depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { - view: depth, - depth_ops: Some(wgpu::Operations { - load: wgpu::LoadOp::Load, - store: wgpu::StoreOp::Store, + let pipelines = TerrainPipelines { + instanced: &self.pipeline, + flat: self.flat_pipeline.as_ref(), + group, + }; + let draw = |encoder: &mut wgpu::CommandEncoder, layer| { + let mut render = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some(&self.program), + color_attachments: &attachments, + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: depth, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Load, + store: wgpu::StoreOp::Store, + }), + stencil_ops: None, }), - stencil_ops: None, - }), - ..Default::default() - }); - (world.draw)( - &mut render, - translucent, - &TerrainPipelines { - instanced: &self.pipeline, - flat: self.flat_pipeline.as_ref(), - group, - }, - ); + ..Default::default() + }); + (world.draw)(&mut render, layer, &pipelines); + }; + if translucent { + draw(encoder, Layer::Translucent); + return; + } + draw(encoder, Layer::Solid); + // Occlusion culling: the sections left out, tested against what + // phase 1 drew, then the ones in sight. + if let Some(test) = world.occlusion { + test(encoder, depth); + draw(encoder, Layer::Revealed); + } } /// Draw into the targets of `draw_buffers`, on the side it doesn't read. diff --git a/crates/horizon-client/src/gfx/java_terrain.rs b/crates/horizon-client/src/gfx/java_terrain.rs index 6411efda1..dd0416428 100644 --- a/crates/horizon-client/src/gfx/java_terrain.rs +++ b/crates/horizon-client/src/gfx/java_terrain.rs @@ -204,9 +204,25 @@ pub fn page_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout { }) } -/// Draws Horizon's terrain with a pack's pipelines: the solid layer or the -/// translucent one. Set by the renderer, which owns the sections. -pub type DrawTerrain<'a> = dyn Fn(&mut wgpu::RenderPass<'_>, bool, &TerrainPipelines<'_>) + 'a; +/// Which of Horizon's terrain draws a pack's program draws. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Layer { + /// The solid sections: all of them, or with occlusion culling + /// ([`JavaWorld::occlusion`]) the ones the last test saw (phase 1). + Solid, + /// With occlusion culling, the solid sections the test after phase 1 + /// found in sight (phase 2). + Revealed, + Translucent, +} + +/// Draws Horizon's terrain with a pack's pipelines. Set by the renderer, +/// which owns the sections. +pub type DrawTerrain<'a> = dyn Fn(&mut wgpu::RenderPass<'_>, Layer, &TerrainPipelines<'_>) + 'a; + +/// Occlusion culling's test between [`Layer::Solid`] and +/// [`Layer::Revealed`], against the pack's depth (OpenGL's layout). +pub type OcclusionTest<'a> = dyn Fn(&mut wgpu::CommandEncoder, &wgpu::TextureView) + 'a; /// What the renderer binds to draw with a pack's geometry program: the /// pipeline of its draw path and the pack's group (group 2). Group 1 is the @@ -229,6 +245,8 @@ pub struct JavaWorld<'a> { pub animated: &'a [(u32, u32)], pub lightmap: &'a wgpu::TextureView, pub draw: &'a DrawTerrain<'a>, + /// Set when the frame culls solid sections by occlusion. + pub occlusion: Option<&'a OcclusionTest<'a>>, } const ATLAS: &str = r#" diff --git a/docs/shader-packs.md b/docs/shader-packs.md index 3d32e37f6..263372d16 100644 --- a/docs/shader-packs.md +++ b/docs/shader-packs.md @@ -367,6 +367,10 @@ sprite arrays (animated sprites copied in each frame), `lightmap` is Horizon's l and fragments under alpha 0.1 are discarded (`alphaTestRef`). `RGBA16` targets are 16-bit unorm where the GPU can render them (Chocapic13' packs its G-buffer into them; half floats broke it). +Occlusion culling works as in Horizon's world pass where the GPU has it: the pack's terrain program draws the +sections the last test saw, the boxes of the others are tested against that depth (in OpenGL's layout, in a pass of +their own since the pack's targets vary), and the pack's program then draws the ones in sight. + What makes Horizon look like OpenGL to the pack: - **Layout.** The translator ends every vertex shader by flipping `gl_Position.y` and moving depth from `[-w, w]` to @@ -401,7 +405,7 @@ grade and light Horizon's world as their post-processing would. Sildur's Vibrant Without the other `gbuffers_*` and `shadow`, no pack has its shadows or sky look yet; Distant Horizons' and Voxy's depth read as far. Not supported yet: images and compute (`.csh`; a pack that needs them doesn't load), mipmapped targets (`colortexNMipmapEnabled` is read but ignored), custom textures, the option screen; shadow matrices are identity. With the pack's terrain: entities, the -sky, the hand, weather and clouds are still Horizon's (in `colortex0` only), GPU occlusion culling is off, block ids +sky, the hand, weather and clouds are still Horizon's (in `colortex0` only), block ids come from sprite names rather than block states, distant (LOD) terrain doesn't repeat its textures, and only the overworld has been checked. From fe6ae937effdd9a7e5ef89c33c3fea9504f24cae Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:41:18 +0200 Subject: [PATCH 005/408] Java shader packs: the pack's shadow programs draw the shadow map A Java pack's shadow program (shadow_cutout, shadow or shadow_solid for the solid layer, shadow_water or shadow for the translucent one) draws Horizon's terrain from the light after begin, as Iris's ShadowRenderer: - shadowModelView and shadowProjection are Iris's ShadowMatrices, with the pack's shadowMapResolution, shadowDistance, near and far planes, shadowIntervalSize and sunPathRotation; shadow programs get them as their model view and projection. - The renderer picks every resident section inside the light's box (no cave culling, no face culling) and draws it instanced, solid then translucent, with origins after the camera's. - shadowtex0 holds everything, shadowtex1 the depth before translucent terrain, bound as depth textures for comparisons and as float copies for plain reads; shadowcolor0..7 take the pack's formats and clears (white by default). A shadow program that fails to compile leaves the pack without its shadow map, with a warning; its terrain programs still run. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/gfx.rs | 162 ++++- crates/horizon-client/src/gfx/java_stages.rs | 615 +++++++++++++++++- crates/horizon-client/src/gfx/java_terrain.rs | 4 + crates/horizon-client/src/java_pack.rs | 52 +- crates/horizon-shaderpack/src/pipeline.rs | 133 ++++ docs/shader-packs.md | 34 +- 6 files changed, 951 insertions(+), 49 deletions(-) diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 1d924e229..8e7f765a6 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -120,6 +120,18 @@ struct Globals { dynamic_lights: [[f32; 4]; crate::dynamic_light::MAX], } pub type SectionKey = (i32, i32, i32); +/// The sections a Java pack's shadow map draws ([`Renderer`]'s `shadow`). +#[derive(Default)] +struct ShadowList { + visible: Vec, + draws: Vec<[u32; 5]>, + pages: Vec<(u32, Option)>, + /// How many of `draws` are solid. + solid: u32, + indirect: Option, + capacity: u64, +} + struct SectionGpu { /// Arena page and first vertex in it: solid quads, then translucent ones. page: u32, @@ -427,6 +439,10 @@ pub struct Renderer { /// built, and their pages. phase2_draws: Vec<[u32; 5]>, phase2_pages: Vec<(u32, Option)>, + /// A Java pack's shadow map (`gfx/java_terrain.rs`): the sections in + /// the light's view, their draws (solid then translucent, instances + /// after the camera's), and the indirect buffer they're uploaded to. + shadow: ShadowList, /// Block-entity blocks per meshed section (world position, state id). block_entities: HashMap>, /// Changes whenever `block_entities` does (unique across renderers). @@ -2193,6 +2209,7 @@ impl Renderer { draw_pages: Vec::new(), phase2_draws: Vec::new(), phase2_pages: Vec::new(), + shadow: ShadowList::default(), block_entities: HashMap::new(), block_entity_revision: next_block_entity_revision(), occlusion: occlusion::Occlusion::new(crate::chunk::MIN_Y, crate::chunk::HEIGHT / 16), @@ -2518,11 +2535,26 @@ impl Renderer { first: u32, count: u32, page_group: impl Fn(&mut wgpu::RenderPass<'_>, u32), + ) { + let list = (&self.draws[..], &self.draw_pages[..]); + self.draw_list(pass, indirect, list, base, first, count, page_group); + } + /// [`Self::draw_sections_with`] over another list of draws and pages. + #[allow(clippy::too_many_arguments)] + fn draw_list( + &self, + pass: &mut wgpu::RenderPass<'_>, + indirect: &wgpu::Buffer, + (draws, pages): (&[[u32; 5]], &[(u32, Option)]), + base: u32, + first: u32, + count: u32, + page_group: impl Fn(&mut wgpu::RenderPass<'_>, u32), ) { let (mut i, end) = (first as usize, (first + count) as usize); while i < end { - let (page, index_page) = self.draw_pages[i]; - let run = self.draw_pages[i..end] + let (page, index_page) = pages[i]; + let run = pages[i..end] .iter() .take_while(|&&p| p == (page, index_page)) .count(); @@ -2534,7 +2566,7 @@ impl Renderer { let offset = (i - base as usize) as u64 * 20; pass.multi_draw_indexed_indirect(indirect, offset, run as u32); } else { - for d in &self.draws[i..i + run] { + for d in &draws[i..i + run] { pass.draw_indexed(d[2]..d[2] + d[0], d[3] as i32, d[4]..d[4] + 1); } } @@ -2556,12 +2588,32 @@ impl Renderer { culling: bool, ) { use java_terrain::Layer; - let translucent = layer == Layer::Translucent; let page = |pass: &mut wgpu::RenderPass<'_>, page: u32| { if let Some(Some((_, group))) = self.java_pages.get(page as usize) { pass.set_bind_group(3, group, &[]); } }; + if matches!(layer, Layer::ShadowSolid | Layer::ShadowTranslucent) { + let shadow = &self.shadow; + let all = shadow.draws.len() as u32; + let (first, count) = if layer == Layer::ShadowSolid { + (0, shadow.solid) + } else { + (shadow.solid, all - shadow.solid) + }; + // Without multi-draw the draws are read from the list. + let indirect = shadow.indirect.as_ref().unwrap_or(&self.indirect); + if count == 0 { + return; + } + pass.set_bind_group(2, pipelines.group, &[]); + pass.set_pipeline(pipelines.instanced); + pass.set_vertex_buffer(1, self.instances.slice(..)); + let list = (&shadow.draws[..], &shadow.pages[..]); + self.draw_list(pass, indirect, list, 0, first, count, page); + return; + } + let translucent = layer == Layer::Translucent; pass.set_bind_group(2, pipelines.group, &[]); match (self.flat.as_ref().filter(|_| flat_frame), pipelines.flat) { // The flat path doesn't cull by occlusion: phase 1 is everything. @@ -2585,6 +2637,7 @@ impl Renderer { (Layer::Revealed, Some(c)) => (&c.phase2, phase1, phase1, solid - phase1), (Layer::Revealed, None) => return, (Layer::Translucent, _) => (&self.indirect, 0, solid, translucent_draws), + (Layer::ShadowSolid | Layer::ShadowTranslucent, _) => return, }; if count == 0 { return; @@ -3163,8 +3216,48 @@ impl Renderer { visible_lods.sort_unstable_by_key(|v| (v.distance, v.key)); } self.drawn_sections = visible.len() + visible_lods.len(); - if self.drawn_sections as u64 > self.instance_capacity { - self.instance_capacity = (self.drawn_sections as u64).next_power_of_two(); + // A Java pack's shadow map: the sections in the light's orthographic + // box, whatever the camera sees (Iris turns cave culling off too). + let mut shadow_visible = std::mem::take(&mut self.shadow.visible); + shadow_visible.clear(); + let shadow_view = match &self.pack { + Some(Pack::Java(j)) if !frame.title && self.java_table.is_some() => j.shadow_view( + frame.shader.dimension, + &java_stages::JavaFrame { + eye_light: frame.shader.eye_light, + sun_angle: frame.sky.sun_angle, + moon_angle: frame.sky.moon_angle, + }, + camera.as_vec3(), + ), + _ => None, + }; + if let Some((view, [half, near, far])) = shadow_view { + // Inside when `plane · (p, 1) >= 0`: |x|, |y| <= half and the + // eye depth between the near and far planes (GL looks down -z). + let (x, y, z) = (view.row(0), view.row(1), view.row(2)); + let planes = [ + Vec4::W * half - x, + Vec4::W * half + x, + Vec4::W * half - y, + Vec4::W * half + y, + -z - Vec4::W * near, + z + Vec4::W * far, + ]; + crate::spans::time("shadow visibility", || { + self.sections.visible( + camera, + (frame.detail_distance / 16.0) as i32, + &Frustum { planes }, + |_| true, + |_, _| false, + &mut shadow_visible, + ) + }); + } + let instances = self.drawn_sections + shadow_visible.len(); + if instances as u64 > self.instance_capacity { + self.instance_capacity = (instances as u64).next_power_of_two(); self.instances = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("Section origins"), size: self.instance_capacity * 16, @@ -3179,8 +3272,63 @@ impl Renderer { visible .iter() .map(|v| section_instance(v.origin)) - .chain(visible_lods.iter().map(|v| lod::instance(v.origin))), + .chain(visible_lods.iter().map(|v| lod::instance(v.origin))) + .chain(shadow_visible.iter().map(|v| section_instance(v.origin))), ); + // The shadow map's draws: every solid quad (no face is culled), then + // the translucent ones in the order the camera's sort left them. + let shadow = &mut self.shadow; + shadow.draws.clear(); + shadow.pages.clear(); + for pass in [false, true] { + for (j, v) in shadow_visible.iter().enumerate() { + let s = self.sections.get(v.slot); + let instance = (self.drawn_sections + j) as u32; + match (pass, s.sorted_indices) { + (false, _) if s.solid > 0 => { + shadow + .draws + .push([s.solid * 6, 1, 0, s.start as u32, instance]); + shadow.pages.push((s.page, None)); + } + (true, Some((index_page, index_start))) if s.translucent > 0 => { + let first = s.start + u64::from(s.solid) * 4; + shadow.draws.push([ + s.translucent * 6, + 1, + index_start as u32, + first as u32, + instance, + ]); + shadow.pages.push((s.page, Some(index_page))); + } + _ => {} + } + } + if !pass { + shadow.solid = shadow.draws.len() as u32; + } + } + if self.multi_draw && !shadow.draws.is_empty() { + if shadow.draws.len() as u64 > shadow.capacity || shadow.indirect.is_none() { + shadow.capacity = (shadow.draws.len() as u64).next_power_of_two(); + shadow.indirect = Some(self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Java shader pack shadow draws"), + size: shadow.capacity * 20, + usage: wgpu::BufferUsages::INDIRECT | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + })); + } + if let Some(indirect) = &shadow.indirect { + self.uploads.buffer( + &mut encoder, + indirect, + 0, + bytemuck::cast_slice(&shadow.draws), + ); + } + } + shadow.visible = shadow_visible; if !self.origins.is_empty() { self.uploads.buffer( &mut encoder, diff --git a/crates/horizon-client/src/gfx/java_stages.rs b/crates/horizon-client/src/gfx/java_stages.rs index 52bba0893..dbe03dae9 100644 --- a/crates/horizon-client/src/gfx/java_stages.rs +++ b/crates/horizon-client/src/gfx/java_stages.rs @@ -168,6 +168,19 @@ struct Views<'a> { depth_solid: &'a wgpu::TextureView, atlas: Option<&'a wgpu::TextureView>, lightmap: Option<&'a wgpu::TextureView>, + shadow: Option<&'a ShadowViews>, +} + +/// The shadow map's textures, as the passes read them. +struct ShadowViews { + /// `shadowtex0` and `shadowtex1` for comparisons (`Depth32Float`). + depth: wgpu::TextureView, + depth_solid: wgpu::TextureView, + /// The same as plain floats, for `sampler2D` reads (`R32Float`). + float: wgpu::TextureView, + float_solid: wgpu::TextureView, + /// `shadowcolor`, for the targets the shadow programs write. + colors: Vec>, } /// A colour target's two sides. @@ -190,10 +203,15 @@ enum Source { /// (the world's depth when the pack doesn't draw the terrain). DepthSolid, Noise, - /// `shadowtex*`: no shadow map yet, so a far depth (nothing in shadow); - /// also Distant Horizons' and Voxy's depth, as without those mods. - Shadow, - /// Anything else (`shadowcolor*`, custom textures): white or black. + /// `shadowtex0` (with translucent terrain) or `shadowtex1` (without): + /// the shadow map when the pack draws one, else a far depth (nothing in + /// shadow). + ShadowDepth(u32), + /// `shadowcolor`: the shadow map's colour target, else white. + ShadowColor(u32), + /// Distant Horizons' and Voxy's depth: far, as without those mods. + Far, + /// Anything else (custom textures): white or black. Blank(bool), /// In geometry programs: the block atlas (`gtexture`), the lightmap, /// and a flat normal map for `normals` (sprites have no LabPBR maps). @@ -212,9 +230,13 @@ fn source(name: &str, geometry: bool) -> Source { "depthtex0" | "gdepthtex" => Source::Depth, "depthtex1" | "depthtex2" => Source::DepthSolid, "noisetex" => Source::Noise, - "shadowtex0" | "shadowtex1" | "shadow" | "watershadow" => Source::Shadow, - n if n.starts_with("dhDepthTex") || n.starts_with("vxDepthTex") => Source::Shadow, - n if n.starts_with("shadowcolor") => Source::Blank(true), + "shadowtex0" | "shadow" | "watershadow" => Source::ShadowDepth(0), + "shadowtex1" => Source::ShadowDepth(1), + n if n.starts_with("dhDepthTex") || n.starts_with("vxDepthTex") => Source::Far, + "shadowcolor" => Source::ShadowColor(0), + n if let Some(i) = n.strip_prefix("shadowcolor").and_then(|i| i.parse().ok()) => { + Source::ShadowColor(i) + } n => target_index(n).map_or(Source::Blank(false), Source::Target), } } @@ -253,6 +275,8 @@ struct PassGpu { /// them), and the targets written on their alternate side. flat_pipeline: Option, geometry: Option>, + /// A shadow program: the light's matrices, `shadowcolor` targets. + shadow: bool, } /// What a pass draws into. @@ -269,6 +293,8 @@ struct GeometrySetup<'a> { /// Each draw buffer's blending. blends: &'a [Option], layouts: &'a GeometryLayouts<'a>, + /// A shadow program: no face culling (Iris's `ShadowRenderer`). + shadow: bool, } /// The renderer's bind group layouts a geometry program's pipelines use: @@ -284,6 +310,19 @@ struct FolderGeometry { terrain: PassGpu, water: Option, translucent_at: usize, + /// Its shadow programs, when it has some and they compile. + shadow: Option, +} + +/// A folder's shadow map: its programs over the solid and translucent +/// terrain, its `shadowcolor` targets, and where it runs. +struct FolderShadow { + solid: PassGpu, + water: Option, + /// Per `shadowcolor` target: its format and clear colour. + targets: Vec<(wgpu::TextureFormat, Option)>, + /// How many passes run before it (`begin*`). + at: usize, } /// What every pass of the pack shares. @@ -315,6 +354,7 @@ struct Bound { /// Per pass, then `final`. groups: Vec, geometry: Option, + shadow: Option, world_in: (wgpu::RenderPipeline, wgpu::BindGroup), /// The world goes to colortex0's alternate side. world_alt: bool, @@ -326,6 +366,25 @@ struct Bound { _blank: Vec, } +/// The shadow map's textures and its programs' groups. +struct BoundShadow { + views: ShadowViews, + /// The depth buffer the shadow programs draw with (`shadowtex0`), and + /// its copy before translucent terrain (`shadowtex1`). + depth: wgpu::Texture, + depth_solid: wgpu::Texture, + /// The `shadowcolor` targets cleared each frame, with their colour, + /// and those cleared only when made (kept between frames). + clears: Vec<(wgpu::TextureView, wgpu::Color)>, + initial: Vec<(wgpu::TextureView, wgpu::Color)>, + solid: wgpu::BindGroup, + water: Option, + /// `depth` for `depth_out` into the float copies. + out_group: wgpu::BindGroup, + /// A pass reads the depth as plain floats: the copies are made. + float_reads: bool, +} + /// What a folder's geometry programs draw with at one size. struct BoundGeometry { /// The depth buffer the geometry tests against: the world's, then the @@ -442,6 +501,24 @@ impl JavaStages { }) } + /// Where the pack's shadow map looks this frame in `dimension`, when + /// it draws one: its view of camera-relative positions (`camera` is the + /// camera's position), and its half width, near and far planes, for + /// the renderer to pick the sections it draws. + pub fn shadow_view( + &self, + dimension: i8, + world: &JavaFrame, + camera: Vec3, + ) -> Option<(Mat4, [f32; 3])> { + let index = self.folder_for[(dimension.clamp(-1, 1) + 1) as usize].unwrap_or(0); + let folder = self.folders.get(index)?; + folder.geometry.as_ref()?.shadow.as_ref()?; + let d = folder.directives; + let (view, _) = shadow_matrices(&d, shadow_angle(world), camera); + Some((view, [d.shadow.distance, d.shadow.near, d.shadow.far])) + } + /// Whether the pack draws the terrain in `dimension` (0 overworld, -1 /// the Nether, 1 the End): the renderer then leaves it out of the world /// and gives `run` a [`JavaWorld`]. @@ -480,9 +557,10 @@ impl JavaStages { self.atlas = Atlas::new(device, queue, w); self.bound = None; } - if self.bound.as_ref().is_none_or(|b| { + let fresh = self.bound.as_ref().is_none_or(|b| { b.folder != folder || b.size != size || b.geometry.is_some() != terrain.is_some() - }) { + }); + if fresh { self.bound = Some(self.bind(device, queue, folder, color, depth, size, post, terrain)); } let now = std::time::Instant::now(); @@ -498,6 +576,8 @@ impl JavaStages { self.previous, ); inputs.set_world(&world, directives.sun_path_rotation); + (inputs.shadow_view, inputs.shadow_projection) = + shadow_matrices(&directives, inputs.shadow_angle, inputs.camera); if let Some(atlas) = &self.atlas { inputs.atlas_size = atlas.size().map(|v| v as f32); } @@ -537,7 +617,14 @@ impl JavaStages { let translucent_at = geometry.map_or(usize::MAX, |((g, _), _)| { g.translucent_at.min(folder.passes.len()) }); + let shadow = geometry + .and_then(|((g, b), w)| Some((g.shadow.as_ref()?, bound.shadow.as_ref()?, b, w))); for i in 0..=folder.passes.len() { + if let Some((sh, b, g, w)) = shadow + && i == sh.at.min(folder.passes.len()) + { + draw_shadow(queue, encoder, sh, b, g, &inputs, w, fresh); + } if i == world_at { world_in(encoder, bound); if let Some(((g, b), w)) = geometry { @@ -594,6 +681,151 @@ impl JavaStages { &bound.output } + /// The shadow map's textures at the folder's `shadowMapResolution`, + /// and its programs' groups. + #[allow(clippy::too_many_arguments)] + fn bind_shadow( + &self, + device: &wgpu::Device, + queue: &wgpu::Queue, + folder: &Folder, + shadow: &FolderShadow, + targets: &BTreeMap, + world: Option<&JavaWorld>, + blank: &mut Vec, + ) -> BoundShadow { + let side = folder + .directives + .shadow + .resolution + .clamp(1, device.limits().max_texture_dimension_2d); + let texture = |label, format, usage| { + device.create_texture(&wgpu::TextureDescriptor { + label: Some(label), + size: wgpu::Extent3d { + width: side, + height: side, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage, + view_formats: &[], + }) + }; + use wgpu::TextureUsages as U; + let depth = texture( + "Java shader pack shadow depth", + wgpu::TextureFormat::Depth32Float, + U::RENDER_ATTACHMENT | U::TEXTURE_BINDING | U::COPY_SRC, + ); + let depth_solid = texture( + "Java shader pack shadow depth before translucent terrain", + wgpu::TextureFormat::Depth32Float, + U::TEXTURE_BINDING | U::COPY_DST, + ); + let float = |label| { + texture( + label, + wgpu::TextureFormat::R32Float, + U::RENDER_ATTACHMENT | U::TEXTURE_BINDING, + ) + .create_view(&Default::default()) + }; + // The colour targets the shadow programs write or a pass reads. + let passes = folder.passes.iter().chain(&folder.final_pass).chain( + folder + .geometry + .iter() + .flat_map(|g| std::iter::once(&g.terrain).chain(&g.water)), + ); + let mut used: BTreeSet = shadow + .solid + .draw_buffers + .iter() + .chain(shadow.water.iter().flat_map(|w| &w.draw_buffers)) + .copied() + .collect(); + let mut float_reads = false; + for s in passes.clone().flat_map(|p| &p.samplers) { + match s.source { + Source::ShadowColor(i) => { + used.insert(i); + } + Source::ShadowDepth(_) if !s.compare => float_reads = true, + _ => {} + } + } + let mut colors = Vec::new(); + let mut clears = Vec::new(); + let mut initial = Vec::new(); + for (i, &(format, clear)) in shadow.targets.iter().enumerate() { + if !used.contains(&(i as u32)) { + colors.push(None); + continue; + } + let view = texture( + "Java shader pack shadowcolor", + format, + U::RENDER_ATTACHMENT | U::TEXTURE_BINDING, + ) + .create_view(&Default::default()); + match clear { + Some(color) => clears.push((view.clone(), color)), + // Kept between frames: white to start with, as Iris's. + None => initial.push((view.clone(), wgpu::Color::WHITE)), + } + colors.push(Some(view)); + } + let views = ShadowViews { + depth: depth.create_view(&Default::default()), + depth_solid: depth_solid.create_view(&Default::default()), + float: float("Java shader pack shadowtex0"), + float_solid: float("Java shader pack shadowtex1"), + colors, + }; + // The shadow programs read neither the shadow map nor the size of + // the world's depth. + let unused = texture( + "Java shader pack shadow pass depth", + wgpu::TextureFormat::R32Float, + U::TEXTURE_BINDING, + ) + .create_view(&Default::default()); + let pass_views = Views { + depth: &unused, + depth_solid: &unused, + atlas: self.atlas.as_ref().map(|a| &a.view), + lightmap: world.map(|w| w.lightmap), + shadow: None, + }; + let mut bind = + |pass: &PassGpu| pass.bind(device, queue, targets, &pass_views, &self.common, blank); + let solid = bind(&shadow.solid); + let water = shadow.water.as_ref().map(&mut bind); + let out_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Java shader pack shadow depth"), + layout: &self.common.depth_layout, + entries: &[wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(&views.depth), + }], + }); + BoundShadow { + views, + depth, + depth_solid, + clears, + initial, + solid, + water, + out_group, + float_reads, + } + } + #[allow(clippy::too_many_arguments)] fn bind( &self, @@ -702,13 +934,17 @@ impl JavaStages { .create_view(&Default::default()), None => depth.clone(), }; + let mut blank = Vec::new(); + let shadow = geometry + .and_then(|g| g.shadow.as_ref()) + .map(|sh| self.bind_shadow(device, queue, folder, sh, &targets, world, &mut blank)); let views = Views { depth: &depth, depth_solid: &depth_solid, atlas: self.atlas.as_ref().map(|a| &a.view), lightmap: world.map(|w| w.lightmap), + shadow: shadow.as_ref().map(|s| &s.views), }; - let mut blank = Vec::new(); let groups = all .clone() .map(|pass| pass.bind(device, queue, &targets, &views, &self.common, &mut blank)) @@ -839,6 +1075,7 @@ impl JavaStages { depth_solid, groups, geometry, + shadow, world_in: (world_pipeline, world_group), world_alt: plan.flipped_after_prepare.contains(&0), final_target, @@ -869,6 +1106,7 @@ fn folder_geometry( flat_vertex: g.variants.first().unwrap_or(&g.program.vertex), blends, layouts, + shadow: false, }), ) }; @@ -882,11 +1120,15 @@ fn folder_geometry( terrain, water, translucent_at: plan.translucent_at, + shadow: None, }) }); let error = pollster::block_on(scope.pop()); match (made, error) { - (Ok(geometry), None) => Some(geometry), + (Ok(mut geometry), None) => { + geometry.shadow = folder_shadow(device, plan, layouts); + Some(geometry) + } (Err(e), _) => { log::warn!("Horizon: shader pack {}: {e}", terrain.program.pass.program); None @@ -898,6 +1140,210 @@ fn folder_geometry( } } +/// A folder's shadow programs on the GPU, or `None` (with a warning: the +/// pack then reads a shadow map with nothing in shadow) when wgpu refuses +/// them. +fn folder_shadow( + device: &wgpu::Device, + plan: &JavaFolder, + layouts: &GeometryLayouts, +) -> Option { + let solid = plan.shadow.as_ref()?; + let formats: Vec = plan + .shadow_targets + .iter() + .map(|t| target_format(&t.format, false)) + .collect(); + // Instanced draws only: the flat draws hold what the camera sees. + let layouts = GeometryLayouts { + flat: None, + page: layouts.page, + }; + let scope = device.push_error_scope(wgpu::ErrorFilter::Validation); + let gpu = |g: &GeometryProgram, blends: &[Option]| { + PassGpu::new( + device, + &g.program, + &formats, + Output::Geometry(GeometrySetup { + flat_vertex: &g.program.vertex, + blends, + layouts: &layouts, + shadow: true, + }), + ) + }; + let made = gpu(solid, &plan.shadow_blends).and_then(|solid_gpu| { + let water = plan + .shadow_water + .as_ref() + .map(|w| gpu(w, &plan.shadow_water_blends)) + .transpose()?; + Ok((solid_gpu, water)) + }); + let error = pollster::block_on(scope.pop()); + let warn = |e: &dyn std::fmt::Display| { + log::warn!("Horizon: shader pack {}: {e}", solid.program.pass.program); + }; + match (made, error) { + (Ok((solid_gpu, water)), None) => Some(FolderShadow { + solid: solid_gpu, + water, + targets: plan + .shadow_targets + .iter() + .zip(&formats) + .map(|(t, &format)| { + let clear = t.clear.then(|| { + let [r, g, b, a] = t.clear_color.unwrap_or([1.0; 4]); + wgpu::Color { + r: r.into(), + g: g.into(), + b: b.into(), + a: a.into(), + } + }); + (format, clear) + }) + .collect(), + at: plan.shadow_at, + }), + (Err(e), _) => { + warn(&e); + None + } + (_, Some(e)) => { + warn(&e); + None + } + } +} + +/// The shadow map: Horizon's terrain from the light with the pack's +/// shadow programs, solid then translucent (`ShadowRenderer`), with the +/// depth before translucent terrain kept for `shadowtex1`. +#[allow(clippy::too_many_arguments)] +fn draw_shadow( + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + shadow: &FolderShadow, + b: &BoundShadow, + geometry: &BoundGeometry, + inputs: &Inputs, + world: &JavaWorld, + fresh: bool, +) { + if fresh { + for (view, color) in &b.initial { + clear_view(encoder, view, *color); + } + } + for (view, color) in &b.clears { + clear_view(encoder, view, *color); + } + let draw = |encoder: &mut wgpu::CommandEncoder, + pass: &PassGpu, + group: &wgpu::BindGroup, + layer: Layer, + first: bool| { + pass.write_uniforms(queue, inputs); + let attachments: Vec> = pass + .draw_buffers + .iter() + .map(|&i| { + let view = b.views.colors.get(i as usize)?.as_ref()?; + Some(color_attachment(view, None)) + }) + .collect(); + let mut render = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some(&pass.program), + color_attachments: &attachments, + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: &b.views.depth, + depth_ops: Some(wgpu::Operations { + load: if first { + wgpu::LoadOp::Clear(1.0) + } else { + wgpu::LoadOp::Load + }, + store: wgpu::StoreOp::Store, + }), + stencil_ops: None, + }), + ..Default::default() + }); + (world.draw)( + &mut render, + layer, + &TerrainPipelines { + instanced: &pass.pipeline, + flat: None, + group, + }, + ); + }; + let float_out = |encoder: &mut wgpu::CommandEncoder, solid: bool| { + if !b.float_reads { + return; + } + let mut attachments = vec![Some(color_attachment(&b.views.float, None))]; + if solid { + attachments.push(Some(color_attachment(&b.views.float_solid, None))); + } + let mut render = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Java shader pack shadow depth"), + color_attachments: &attachments, + ..Default::default() + }); + render.set_pipeline(if solid { + &geometry.out_both + } else { + &geometry.out + }); + render.set_bind_group(0, &b.out_group, &[]); + render.draw(0..3, 0..1); + }; + draw(encoder, &shadow.solid, &b.solid, Layer::ShadowSolid, true); + encoder.copy_texture_to_texture( + b.depth.as_image_copy(), + b.depth_solid.as_image_copy(), + b.depth.size(), + ); + float_out(encoder, true); + if let (Some(pass), Some(group)) = (&shadow.water, &b.water) { + draw(encoder, pass, group, Layer::ShadowTranslucent, false); + float_out(encoder, false); + } +} + +/// Iris's `shadowModelView` and `shadowProjection` (`ShadowMatrices`): +/// the light's view of camera-relative positions, snapped to the pack's +/// `shadowIntervalSize` as the camera moves, and an orthographic +/// projection `shadowDistance` wide each way of the camera. +pub fn shadow_matrices(directives: &Directives, shadow_angle: f32, camera: Vec3) -> (Mat4, Mat4) { + let sky = if shadow_angle < 0.25 { + shadow_angle + 0.75 + } else { + shadow_angle - 0.25 + }; + let mut view = Mat4::from_rotation_x(90f32.to_radians()) + * Mat4::from_rotation_z((sky * -360.0).to_radians()) + * Mat4::from_rotation_x(directives.sun_path_rotation.to_radians()); + let d = &directives.shadow; + if d.interval != 0.0 { + // Java's `%` keeps the dividend's sign, as Rust's does. + let offset = Vec3::new( + camera.x % d.interval, + camera.y % d.interval, + camera.z % d.interval, + ) - Vec3::splat(d.interval / 2.0); + view *= Mat4::from_translation(offset); + } + let h = d.distance; + let projection = Mat4::orthographic_rh_gl(-h, h, -h, h, d.near, d.far); + (view, projection) +} + fn world_in(encoder: &mut wgpu::CommandEncoder, bound: &Bound) { let colortex0 = &bound.targets[&0]; let side = if bound.world_alt { @@ -1257,7 +1703,10 @@ impl PassGpu { )), ) } - (false, Source::Depth | Source::DepthSolid | Source::Shadow) => ( + ( + false, + Source::Depth | Source::DepthSolid | Source::ShadowDepth(_) | Source::Far, + ) => ( wgpu::TextureSampleType::Float { filterable: false }, Some(false), ), @@ -1441,6 +1890,7 @@ impl PassGpu { scale: program.pass.scale.clamp(0.0, 1.0), flat_pipeline: None, geometry: None, + shadow: false, }) } @@ -1523,9 +1973,10 @@ impl PassGpu { compilation_options: Default::default(), buffers: &buffers, }, - // The y flip into GL's layout turns the faces around. + // The y flip into GL's layout turns the faces around. The + // shadow map culls none (a mountain's back casts shadows). primitive: wgpu::PrimitiveState { - cull_mode: Some(wgpu::Face::Back), + cull_mode: (!setup.shadow).then_some(wgpu::Face::Back), front_face: wgpu::FrontFace::Cw, ..Default::default() }, @@ -1583,6 +2034,7 @@ impl PassGpu { scale: 1.0, flat_pipeline, geometry: Some(flipped), + shadow: setup.shadow, }) } @@ -1599,8 +2051,31 @@ impl PassGpu { let depth = textures.depth; let mut views = Vec::new(); for s in &self.samplers { + let shadow = textures + .shadow + .filter(|_| s.dimension == wgpu::TextureViewDimension::D2); let view = match (s.compare, s.source) { + (true, Source::ShadowDepth(i)) if let Some(sh) = shadow => { + if i == 0 { + sh.depth.clone() + } else { + sh.depth_solid.clone() + } + } (true, _) => blank_view(device, queue, blank, s, BlankKind::FarDepth), + (false, Source::ShadowDepth(i)) if let Some(sh) = shadow => { + if i == 0 { + sh.float.clone() + } else { + sh.float_solid.clone() + } + } + (false, Source::ShadowColor(i)) + if let Some(view) = + shadow.and_then(|sh| sh.colors.get(i as usize)?.as_ref()) => + { + view.clone() + } (false, Source::Target(i)) if s.dimension == wgpu::TextureViewDimension::D2 => { match targets.get(&i) { Some(t) if self.reads_alt.contains(&i) => t.alt_view.clone(), @@ -1629,7 +2104,12 @@ impl PassGpu { (false, Source::FlatNormal) => { blank_view(device, queue, blank, s, BlankKind::FlatNormal) } - (false, Source::Shadow) => blank_view(device, queue, blank, s, BlankKind::Far), + (false, Source::ShadowDepth(_) | Source::Far) => { + blank_view(device, queue, blank, s, BlankKind::Far) + } + (false, Source::ShadowColor(_)) => { + blank_view(device, queue, blank, s, BlankKind::Color(true)) + } (false, Source::Noise) if s.dimension == wgpu::TextureViewDimension::D2 => { common.noise.clone() } @@ -1648,7 +2128,10 @@ impl PassGpu { (true, _) => &common.compare, _ if s.signed.is_some() => &common.nearest, (false, Source::Noise) => &common.repeat, - (false, Source::Depth | Source::DepthSolid | Source::Shadow) => &common.nearest, + ( + false, + Source::Depth | Source::DepthSolid | Source::ShadowDepth(_) | Source::Far, + ) => &common.nearest, (false, Source::Atlas) => &common.atlas, (false, Source::Target(i)) => { match targets.get(&i).map(|t| sample_type(t.format)) { @@ -1697,7 +2180,12 @@ impl PassGpu { }; let mut bytes = vec![0u8; *block_size as usize]; for (name, slots) in &self.uniforms { - if let Some(values) = inputs.value(name, self.geometry.is_some()) { + let values = if self.shadow { + inputs.shadow(name).or_else(|| inputs.value(name, true)) + } else { + inputs.value(name, self.geometry.is_some()) + }; + if let Some(values) = values { for (&(offset, int), value) in slots.iter().zip(values) { let at = offset as usize..offset as usize + 4; bytes[at].copy_from_slice(&if int { @@ -2073,6 +2561,19 @@ struct Inputs { custom: HashMap>, /// `atlasSize`, in geometry programs. atlas_size: [f32; 2], + /// `shadowModelView` and `shadowProjection` ([`shadow_matrices`]). + shadow_view: Mat4, + shadow_projection: Mat4, +} + +/// `shadowAngle`: the sun's angle by day, the moon's by night, 0..1. +fn shadow_angle(world: &JavaFrame) -> f32 { + let sun = celestial_angle(world.sun_angle); + if sun < 180.0 { + sun / 360.0 + } else { + celestial_angle(world.moon_angle) / 360.0 + } } /// `CelestialUniforms.getSunAngle`: the body's angle plus 90, in 0..360 @@ -2128,6 +2629,8 @@ impl Inputs { is_day: true, custom: HashMap::new(), atlas_size: [0.0; 2], + shadow_view: Mat4::IDENTITY, + shadow_projection: Mat4::IDENTITY, }; out.set_world(&JavaFrame::default(), 0.0); out @@ -2153,11 +2656,7 @@ impl Inputs { let sun = celestial_angle(world.sun_angle); self.is_day = sun < 180.0; self.sun_angle = sun / 360.0; - self.shadow_angle = if self.is_day { - sun - } else { - celestial_angle(world.moon_angle) - } / 360.0; + self.shadow_angle = shadow_angle(world); } /// The value of uniform `name`, as its scalars in order: Iris's own, @@ -2207,6 +2706,26 @@ impl Inputs { }) } + /// The uniforms whose value differs in shadow programs: the light's + /// matrices instead of the camera's. + fn shadow(&self, name: &str) -> Option> { + let mat = |m: Mat4| m.to_cols_array().to_vec(); + let (view, projection) = (self.shadow_view, self.shadow_projection); + Some(match name { + "iris_ModelViewMatrix" | "modelViewMatrix" => mat(view), + "iris_ModelViewMatrixInverse" | "modelViewMatrixInverse" => mat(view.inverse()), + "iris_ProjectionMatrix" | "projectionMatrix" => mat(projection), + "iris_ProjectionMatrixInverse" | "projectionMatrixInverse" => mat(projection.inverse()), + "iris_ModelViewProjectionMatrix" => mat(projection * view), + "iris_NormalMatrix" | "normalMatrix" => Mat3::from_mat4(view) + .inverse() + .transpose() + .to_cols_array() + .to_vec(), + _ => return None, + }) + } + /// The value of Iris uniform `name`; `None` for one Horizon doesn't /// provide. fn builtin(&self, name: &str) -> Option> { @@ -2269,10 +2788,10 @@ impl Inputs { "iris_ProjectionMatrixInverse" => mat(screen.inverse()), "iris_TextureMatrix" => (0..8).flat_map(|_| mat(Mat4::IDENTITY)).collect(), "iris_NormalMatrix" => Mat3::IDENTITY.to_cols_array().to_vec(), - "shadowModelView" - | "shadowModelViewInverse" - | "shadowProjection" - | "shadowProjectionInverse" => mat(Mat4::IDENTITY), + "shadowModelView" => mat(self.shadow_view), + "shadowModelViewInverse" => mat(self.shadow_view.inverse()), + "shadowProjection" => mat(self.shadow_projection), + "shadowProjectionInverse" => mat(self.shadow_projection.inverse()), _ => return None, }) } @@ -2310,14 +2829,52 @@ mod tests { ); } + #[test] + fn shadow_matrices_are_iris_s() { + use horizon_shaderpack::pipeline::ShadowDirectives; + let close = |a: Mat4, b: Mat4| { + for (x, y) in a.to_cols_array().iter().zip(b.to_cols_array()) { + assert!((x - y).abs() < 1e-5, "{a} != {b}"); + } + }; + // ShadowMatrices.Tests: shadowDistance 32, planes 0.05 and 256. + let directives = Directives { + shadow: ShadowDirectives { + distance: 32.0, + near: 0.05, + far: 256.0, + interval: 0.0, + ..ShadowDirectives::default() + }, + ..Directives::default() + }; + let (view, projection) = shadow_matrices(&directives, 0.25, Vec3::ZERO); + close( + projection, + Mat4::from_cols_array(&[ + 0.03125, 0.0, 0.0, 0.0, 0.0, 0.03125, 0.0, 0.0, 0.0, 0.0, -0.007_814_026, 0.0, 0.0, + 0.0, -1.000_390_6, 1.0, + ]), + ); + // Noon: the light looks straight down (up is toward it, +z). + assert!((view.transform_vector3(Vec3::Y) - Vec3::Z).length() < 1e-5); + // Snapped to the interval: x 5.5 % 2 = 1.5 further than 0 % 2. + let directives = Directives::default(); + let (snapped, _) = shadow_matrices(&directives, 0.25, Vec3::new(5.5, 0.0, 0.0)); + let (plain, _) = shadow_matrices(&directives, 0.25, Vec3::ZERO); + close(snapped, plain * Mat4::from_translation(Vec3::new(1.5, 0.0, 0.0))); + } + #[test] fn samplers_read_what_iris_binds() { assert_eq!(source("colortex4", false), Source::Target(4)); assert_eq!(source("gaux1", false), Source::Target(4)); assert_eq!(source("gdepthtex", false), Source::Depth); - assert_eq!(source("shadowtex1", false), Source::Shadow); - assert_eq!(source("dhDepthTex0", false), Source::Shadow); - assert_eq!(source("shadowcolor0", false), Source::Blank(true)); + assert_eq!(source("shadowtex1", false), Source::ShadowDepth(1)); + assert_eq!(source("shadow", false), Source::ShadowDepth(0)); + assert_eq!(source("dhDepthTex0", false), Source::Far); + assert_eq!(source("shadowcolor1", false), Source::ShadowColor(1)); + assert_eq!(source("shadowcolor", false), Source::ShadowColor(0)); assert_eq!(source("cloudTexture", false), Source::Blank(false)); // Before translucent terrain; geometry programs' own textures. assert_eq!(source("depthtex1", false), Source::DepthSolid); diff --git a/crates/horizon-client/src/gfx/java_terrain.rs b/crates/horizon-client/src/gfx/java_terrain.rs index dd0416428..eb71959c9 100644 --- a/crates/horizon-client/src/gfx/java_terrain.rs +++ b/crates/horizon-client/src/gfx/java_terrain.rs @@ -214,6 +214,10 @@ pub enum Layer { /// found in sight (phase 2). Revealed, Translucent, + /// The shadow map's sections ([`super::Renderer`]'s shadow list), solid + /// then translucent. + ShadowSolid, + ShadowTranslucent, } /// Draws Horizon's terrain with a pack's pipelines. Set by the renderer, diff --git a/crates/horizon-client/src/java_pack.rs b/crates/horizon-client/src/java_pack.rs index f0a1b85f0..5035e7fd2 100644 --- a/crates/horizon-client/src/java_pack.rs +++ b/crates/horizon-client/src/java_pack.rs @@ -44,6 +44,16 @@ pub struct JavaFolder { /// Each draw buffer's blending in `terrain` and `water`. pub terrain_blends: Vec>, pub water_blends: Vec>, + /// The shadow map's programs over Horizon's solid and translucent + /// terrain (instanced draws only), drawn after `begin*`, into + /// `shadowcolor` targets set by `shadow_targets`. + pub shadow: Option, + pub shadow_water: Option, + pub shadow_targets: Vec, + pub shadow_blends: Vec>, + pub shadow_water_blends: Vec>, + /// How many of `passes` run before the shadow map (`begin*`). + pub shadow_at: usize, } /// A loaded Java pack. @@ -138,9 +148,14 @@ pub fn load( } // A geometry program that doesn't translate leaves that terrain to // Horizon, with a warning. - let geometry = |pass: &Option, alpha_test| { + let geometry_with = |pass: &Option, + alpha_test, + flat: &[bool]| { let pass = pass.as_ref()?; - let glues = [false, true].map(|flat| crate::gfx::java_terrain::glue(flat, alpha_test)); + let glues: Vec<_> = flat + .iter() + .map(|&flat| crate::gfx::java_terrain::glue(flat, alpha_test)) + .collect(); match pack.compile_geometry(pass, &plan.targets, &values, &env, &properties, &glues) { Ok(program) => Some(program), Err(e) => { @@ -149,9 +164,20 @@ pub fn load( } } }; + let geometry = |pass: &Option, alpha_test| { + geometry_with(pass, alpha_test, &[false, true]) + }; // Iris's alpha test of cutout terrain (`AlphaTests.ONE_TENTH_ALPHA`). let terrain = geometry(&plan.terrain, Some(0.1)); let water = terrain.as_ref().and_then(|_| geometry(&plan.water, None)); + // The shadow map draws only with the pack's terrain, and only from + // instanced draws (the flat draws hold what the camera sees). + let shadow = terrain + .as_ref() + .and_then(|_| geometry_with(&plan.shadow, Some(0.1), &[false])); + let shadow_water = shadow + .as_ref() + .and_then(|_| geometry_with(&plan.shadow_water, None, &[false])); let translucent_at = early.clone().count() + plan.deferred.len(); let blends = |g: &Option, default| { g.as_ref().map_or_else(Vec::new, |g| { @@ -164,6 +190,9 @@ pub fn load( }) }; let terrain_blends = blends(&terrain, None); + // Iris's shadow programs don't blend (`BlendModeOverride.OFF`). + let shadow_blends = blends(&shadow, None); + let shadow_water_blends = blends(&shadow_water, None); // Vanilla's translucent blending (`BlendFunction.TRANSLUCENT`). let water_blends = blends( &water, @@ -195,6 +224,12 @@ pub fn load( flipped_after_translucent: plan.flipped_after_translucent, terrain_blends, water_blends, + shadow, + shadow_water, + shadow_targets: plan.shadow_targets, + shadow_blends, + shadow_water_blends, + shadow_at: plan.begin.len(), }); } if folders.is_empty() { @@ -324,10 +359,13 @@ mod tests { .folders .iter() .flat_map(|f| f.passes.iter().chain(&f.final_pass)); - let geometry = pack - .folders - .iter() - .flat_map(|f| f.terrain.iter().chain(&f.water)); + let geometry = pack.folders.iter().flat_map(|f| { + f.terrain + .iter() + .chain(&f.water) + .chain(&f.shadow) + .chain(&f.shadow_water) + }); passes .flat_map(|p| [(p, &p.vertex, "vsh"), (p, &p.fragment, "fsh")]) .chain(geometry.flat_map(|g| { @@ -379,6 +417,8 @@ mod tests { .terrain .iter() .chain(&f.water) + .chain(&f.shadow) + .chain(&f.shadow_water) .map(|g| g.program.pass.program.as_str()) .collect(); format!("{} {n} passes, terrain {geometry:?}", f.folder) diff --git a/crates/horizon-shaderpack/src/pipeline.rs b/crates/horizon-shaderpack/src/pipeline.rs index bcc1f310d..1619bc497 100644 --- a/crates/horizon-shaderpack/src/pipeline.rs +++ b/crates/horizon-shaderpack/src/pipeline.rs @@ -325,6 +325,74 @@ pub struct Passes { /// The program its translucent terrain is drawn with /// ([`WATER_PROGRAMS`]), after `deferred`. pub water: Option, + /// The programs the shadow map's solid and translucent terrain are + /// drawn with ([`SHADOW_PROGRAMS`], [`SHADOW_WATER_PROGRAMS`]), after + /// `begin`. Their draw buffers are `shadowcolor` targets. + pub shadow: Option, + pub shadow_water: Option, + /// `shadowcolor0..7`: white and cleared each frame unless the pack + /// says otherwise. + pub shadow_targets: Vec, +} + +/// The programs Iris draws the shadow map's solid terrain with. Horizon's +/// solid layer holds cutout blocks too, so `shadow_cutout` (with its alpha +/// test) comes first. +pub const SHADOW_PROGRAMS: &[&str] = &["shadow_cutout", "shadow", "shadow_solid"]; + +/// The programs Iris draws the shadow map's translucent terrain with. +pub const SHADOW_WATER_PROGRAMS: &[&str] = &["shadow_water", "shadow"]; + +/// How many `shadowcolor` targets Iris has. +pub const MAX_SHADOW_COLOR_BUFFERS: u32 = 8; + +/// `shadowcolorFormat`, `Clear` and `ClearColor` from `fragments`. +pub fn shadow_target_settings<'a>( + fragments: impl IntoIterator, +) -> Vec { + let mut targets = vec![ + TargetSettings { + clear_color: Some([1.0; 4]), + ..TargetSettings::default() + }; + MAX_SHADOW_COLOR_BUFFERS as usize + ]; + let key = |key: &str, suffix: &str| { + let i: u32 = key + .strip_prefix("shadowcolor")? + .strip_suffix(suffix)? + .parse() + .ok()?; + (i < MAX_SHADOW_COLOR_BUFFERS).then_some(i as usize) + }; + for fragment in fragments { + for c in const_directives(fragment) { + match c.ty { + "int" => { + if let Some(i) = key(&c.key, "Format") { + let format = c.value.to_uppercase(); + if TEXTURE_FORMATS.contains(&format.as_str()) { + targets[i].format = format; + } + } + } + "bool" => { + if let (Some(i), Ok(clear)) = (key(&c.key, "Clear"), c.value.parse()) { + targets[i].clear = clear; + } + } + "vec4" => { + if let (Some(i), Some(color)) = + (key(&c.key, "ClearColor"), parse_vec4(&c.value)) + { + targets[i].clear_color = Some(color); + } + } + _ => {} + } + } + } + targets } /// The programs Iris draws solid terrain with, the first the pack has @@ -356,6 +424,7 @@ pub struct Directives { pub sun_path_rotation: f32, /// `eyeBrightnessHalflife`, tenths of a second: `eyeBrightnessSmooth`. pub eye_brightness_half_life: f32, + pub shadow: ShadowDirectives, } impl Default for Directives { @@ -363,6 +432,35 @@ impl Default for Directives { Self { sun_path_rotation: 0.0, eye_brightness_half_life: 10.0, + shadow: ShadowDirectives::default(), + } + } +} + +/// The shadow map's `const` directives (`PackShadowDirectives`), with +/// Iris's defaults. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ShadowDirectives { + /// `shadowMapResolution`: the shadow targets' width and height. + pub resolution: u32, + /// `shadowDistance`: half the side of the orthographic projection. + pub distance: f32, + /// `shadowNearPlane` and `shadowFarPlane` (`ShadowMatrices.NEAR`/`FAR`). + pub near: f32, + pub far: f32, + /// `shadowIntervalSize`: the light's view snaps to a grid this size as + /// the camera moves, so shadows don't shimmer. + pub interval: f32, +} + +impl Default for ShadowDirectives { + fn default() -> Self { + Self { + resolution: 1024, + distance: 160.0, + near: -100.05, + far: 156.0, + interval: 2.0, } } } @@ -378,6 +476,13 @@ impl Directives { match (c.ty, c.key.as_str(), value) { ("float", "sunPathRotation", Ok(v)) => out.sun_path_rotation = v, ("float", "eyeBrightnessHalflife", Ok(v)) => out.eye_brightness_half_life = v, + ("int", "shadowMapResolution", Ok(v)) if v >= 1.0 => { + out.shadow.resolution = v as u32; + } + ("float", "shadowDistance", Ok(v)) => out.shadow.distance = v, + ("float", "shadowNearPlane", Ok(v)) => out.shadow.near = v, + ("float", "shadowFarPlane", Ok(v)) => out.shadow.far = v, + ("float", "shadowIntervalSize", Ok(v)) => out.shadow.interval = v, _ => {} } } @@ -501,6 +606,7 @@ impl JavaPack { } let mut out = Passes { targets: target_settings(sources.iter().map(String::as_str), properties), + shadow_targets: shadow_target_settings(sources.iter().map(String::as_str)), directives: Directives::read(sources.iter().map(String::as_str)), ..Passes::default() }; @@ -529,6 +635,7 @@ impl JavaPack { }; let mut flipped = BTreeSet::new(); out.begin = run(&groups[0], "begin_pre", &mut flipped)?; + let flipped_after_begin = flipped.clone(); out.prepare = run(&groups[1], "prepare_pre", &mut flipped)?; out.flipped_after_prepare = flipped.clone(); out.deferred = run(&groups[2], "deferred_pre", &mut flipped)?; @@ -551,6 +658,8 @@ impl JavaPack { }; out.terrain = geometry(TERRAIN_PROGRAMS, &out.flipped_after_prepare)?; out.water = geometry(WATER_PROGRAMS, &out.flipped_after_translucent)?; + out.shadow = geometry(SHADOW_PROGRAMS, &flipped_after_begin)?; + out.shadow_water = geometry(SHADOW_WATER_PROGRAMS, &flipped_after_begin)?; if exists("final") { out.final_pass = Some(Pass { program: path("final"), @@ -849,6 +958,30 @@ mod tests { assert_eq!(d.eye_brightness_half_life, 4.0); } + #[test] + fn shadow_directives_and_targets() { + let text = "\ +const int shadowMapResolution = 2048; +const float shadowDistance = 128.0; +const float shadowIntervalSize = 3.0; +const bool shadowcolor0Clear = false; +const int shadowcolor1Format = RGBA16; +const vec4 shadowcolor1ClearColor = vec4(0.0, 0.0, 0.0, 0.0); +"; + let d = Directives::read([text]); + assert_eq!(d.shadow.resolution, 2048); + assert_eq!(d.shadow.distance, 128.0); + assert_eq!(d.shadow.interval, 3.0); + assert_eq!(d.shadow.near, ShadowDirectives::default().near); + let targets = shadow_target_settings([text]); + assert!(!targets[0].clear); + assert_eq!(targets[1].format, "RGBA16"); + assert_eq!(targets[1].clear_color, Some([0.0; 4])); + // Iris clears the others to white. + assert_eq!(targets[2].clear_color, Some([1.0; 4])); + assert!(targets[2].clear); + } + #[test] fn const_directives_and_target_settings() { let text = "\ diff --git a/docs/shader-packs.md b/docs/shader-packs.md index 263372d16..96013f15b 100644 --- a/docs/shader-packs.md +++ b/docs/shader-packs.md @@ -23,7 +23,8 @@ Both are off by default. With no pack selected the renderer draws exactly what i | Java shader packs: full-screen passes drawn (`java_pack.rs`, `gfx/java_stages.rs`: `begin`, `prepare`, `deferred*`, `composite*`, `final` over Horizon's world) | first slice: BSL and Complementary run (below) | | Java shader packs: custom uniforms (`horizon_shaderpack::uniforms`), `sunPathRotation`, `clouds`/`sun`/`moon`, eye light | done for the full-screen passes (below) | | Java shader packs: `gbuffers_terrain`, `gbuffers_water` (`gfx/java_terrain.rs`: Horizon's terrain fed to the pack's programs) | first slice: MakeUp Ultra Fast, Chocapic13' and BSL draw their own terrain and water (below) | -| Java shader packs: other `gbuffers_*`, `shadow`, custom textures, images, compute, option screen | planned | +| Java shader packs: `shadow` programs (`gfx/java_stages.rs`: the shadow map from Horizon's terrain) | first slice: terrain shadows for MakeUp Ultra Fast, Chocapic13' and BSL (below) | +| Java shader packs: other `gbuffers_*`, entity shadows, `shadowcomp`, custom textures, images, compute, option screen | planned | ## How the renderer draws a frame today @@ -371,6 +372,24 @@ Occlusion culling works as in Horizon's world pass where the GPU has it: the pac sections the last test saw, the boxes of the others are tested against that depth (in OpenGL's layout, in a pass of their own since the pack's targets vary), and the pack's program then draws the ones in sight. +When the pack has a `shadow` program (`shadow_cutout`, `shadow` or `shadow_solid` for the solid layer, which holds +cutout blocks; `shadow_water` or `shadow` for the translucent one), it draws a shadow map after `begin*`, as Iris's +`ShadowRenderer`: + +- the light's matrices are Iris's `ShadowMatrices`: `shadowModelView` turns camera-relative positions toward the sun + (the moon at night) with the pack's `sunPathRotation`, snapped to `shadowIntervalSize`; `shadowProjection` is + orthographic, `shadowDistance` each way, between `shadowNearPlane` and `shadowFarPlane` (Iris's defaults when the + pack sets none); the shadow programs get them as `gl_ModelViewMatrix` and `gl_ProjectionMatrix`; +- the renderer draws every section inside that box from its own list (not the camera's: cave culling is off as in + Iris, and no face is culled), solid then translucent, instanced draws only; +- `shadowtex0` holds all of it, `shadowtex1` the depth before translucent terrain; both are bound as depth textures + for `sampler2DShadow` (linear comparison, Iris's hardware filtering) and as float copies for `sampler2D` reads; +- `shadowcolor0..7` are `shadowMapResolution` square in their `shadowcolorFormat`, cleared each frame to + `shadowcolorClearColor` (white by default) unless `shadowcolorClear` is false. + +A shadow program that doesn't translate or that wgpu refuses leaves the pack without its shadow map, with a warning: +the terrain programs still run and every `shadowtex` reads as far (nothing in shadow). + What makes Horizon look like OpenGL to the pack: - **Layout.** The translator ends every vertex shader by flipping `gl_Position.y` and moving depth from `[-w, w]` to @@ -402,9 +421,10 @@ What makes Horizon look like OpenGL to the pack: Measured on the Mac mini (M4 Pro) with the packs' default options: BSL v10.1.8 and Complementary Reimagined r5.9.3 grade and light Horizon's world as their post-processing would. Sildur's Vibrant v2.02 draws only its sky: its `deferred` reads the albedo `gbuffers_*` write to `colortex4` (not checked again since the terrain programs run). -Without the other `gbuffers_*` and `shadow`, no pack has its shadows or sky look yet; Distant Horizons' and Voxy's depth read as far. Not supported yet: images and +Without the other `gbuffers_*`, no pack has its own sky yet, and only terrain casts shadows; Distant Horizons' and Voxy's depth read as far. Not supported yet: images and compute (`.csh`; a pack that needs them doesn't load), mipmapped targets (`colortexNMipmapEnabled` is read but -ignored), custom textures, the option screen; shadow matrices are identity. With the pack's terrain: entities, the +ignored), custom textures, the option screen, `shadowcomp` passes, `shadowMapFov` (a perspective shadow map), +`shadow.culling` and `shadowDistanceRenderMul` (the box above is the only bound). With the pack's terrain: entities, the sky, the hand, weather and clouds are still Horizon's (in `colortex0` only), block ids come from sprite names rather than block states, distant (LOD) terrain doesn't repeat its textures, and only the overworld has been checked. @@ -415,8 +435,8 @@ Tested on 2026-10-22 on the Mac mini (M4 Pro, Metal) with each pack's default op the authors' pages (dev-only test inputs, kept outside the repository). "Loads" means every pass the pack enables for the overworld, Nether and End is preprocessed, translated and validated, as the game does when the pack is picked (`java_pack::tests::real_packs_load` with `HORIZON_TEST_SHADERPACKS`); "drawn" means it was also picked in the game -and screenshotted. Full-screen passes, `gbuffers_terrain` and `gbuffers_water` run (above); no pack has its own -shadows, entities or sky yet. +and screenshotted. Full-screen passes, `gbuffers_terrain`, `gbuffers_water` and the terrain's shadow map run +(above); no pack has its own entities or sky yet. | Pack | Version | Result | First thing that stops it | | --- | --- | --- | --- | @@ -472,7 +492,7 @@ What the translator does for these packs, as Iris (JCPP and its GLSL transformer into Iris's attributes (`mc_Entity` from `block.properties`, `mc_midTexCoord`, `at_tangent`, lightmap), a second set of terrain pipelines writing the pack's render targets. 5. **Entities, block entities, hand, weather, clouds, particles** `gbuffers_*`. -6. **Shadow pass**: terrain and entities from the sun into `shadowtex0/1` and `shadowcolor0/1`, culled from the - light's view, with the pack's distortion. +6. **Shadow pass** (terrain done, above): entities and block entities from the sun into `shadowtex0/1` and + `shadowcolor0/1`, culled from the light's view, with the pack's distortion; `shadowcomp`. 7. **The rest**: custom textures, compute programs and images, per-dimension folders, `entity.properties`/`item.properties`. From 5858cb113e56af1cbc53e1a386b42b1d9c9c82aa Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 01:21:05 +0200 Subject: [PATCH 006/408] Java shader packs: the shadow map leaves out sections whose shadow can't reach the view A section's shadow is its box swept away from the light; when the box is outside one of the camera frustum's planes and the sweep never crosses it, nothing it casts can be seen (Iris's advanced shadow culling, conservatively). The picture is the same; BSL's 256-block shadow distance draws far fewer sections. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/gfx.rs | 57 ++++++++++++++++++-- crates/horizon-client/src/gfx/java_stages.rs | 23 ++++++-- docs/shader-packs.md | 5 +- 3 files changed, 77 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 8e7f765a6..d02755fb9 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -3232,10 +3232,10 @@ impl Renderer { ), _ => None, }; - if let Some((view, [half, near, far])) = shadow_view { + if let Some((light_view, [half, near, far])) = shadow_view { // Inside when `plane · (p, 1) >= 0`: |x|, |y| <= half and the // eye depth between the near and far planes (GL looks down -z). - let (x, y, z) = (view.row(0), view.row(1), view.row(2)); + let (x, y, z) = (light_view.row(0), light_view.row(1), light_view.row(2)); let planes = [ Vec4::W * half - x, Vec4::W * half + x, @@ -3244,12 +3244,23 @@ impl Renderer { -z - Vec4::W * near, z + Vec4::W * far, ]; + // Toward the light: the light's view looks down its -z. + let light = z.truncate().normalize_or_zero(); + let casts = |k: SectionKey| { + let min = DVec3::new( + f64::from(k.0 * 16), + f64::from(crate::chunk::MIN_Y + k.1 * 16), + f64::from(k.2 * 16), + ) - camera; + let min = min.as_vec3(); + view.casts_into(min, min + Vec3::splat(16.0), light) + }; crate::spans::time("shadow visibility", || { self.sections.visible( camera, (frame.detail_distance / 16.0) as i32, &Frustum { planes }, - |_| true, + casts, |_, _| false, &mut shadow_visible, ) @@ -4413,6 +4424,21 @@ impl Frustum { p.truncate().dot(v) + p.w < 0.0 }) } + /// Whether the camera-relative box `min..max`, lit from the direction + /// `light` (toward the light), can cast a shadow inside: its shadow is + /// the box swept away from the light, which stays outside a plane the + /// box is outside of unless the sweep crosses it (Iris's advanced + /// shadow culling, conservatively). + pub fn casts_into(&self, min: Vec3, max: Vec3, light: Vec3) -> bool { + !self.planes.iter().any(|p| { + let v = Vec3::new( + if p.x >= 0.0 { max.x } else { min.x }, + if p.y >= 0.0 { max.y } else { min.y }, + if p.z >= 0.0 { max.z } else { min.z }, + ); + p.truncate().dot(v) + p.w < 0.0 && p.truncate().dot(light) >= 0.0 + }) + } } /// Vanilla's `Projection`: reversed depth (near maps to 1, far to 0, tests /// are GREATER_THAN_OR_EQUAL), which keeps far faces a hair apart, like @@ -4505,6 +4531,31 @@ fn frustum(m: Mat4) -> [Vec4; 6] { #[cfg(test)] mod tests { + #[test] + fn shadow_casters_are_the_boxes_whose_shadow_can_reach_the_view() { + use glam::Vec3; + // Looking north (-z) from the origin, level. + let m = super::world_projection(70.0, 16.0 / 9.0, 256.0) + * crate::camera::view_matrix(180.0, 0.0); + let view = super::Frustum { + planes: super::frustum(m), + }; + let cube = + |x: f32, y: f32, z: f32| (Vec3::new(x, y, z), Vec3::new(x + 16.0, y + 16.0, z + 16.0)); + let noon = Vec3::Y; + // In view: casts. + let (min, max) = cube(-8.0, -8.0, -64.0); + assert!(view.intersects(min, max) && view.casts_into(min, max, noon)); + // Far above the view, the sun overhead: its shadow falls into it. + let (min, max) = cube(-8.0, 200.0, -64.0); + assert!(!view.intersects(min, max) && view.casts_into(min, max, noon)); + // Behind the camera: its shadow falls straight down, behind it too. + let (min, max) = cube(-8.0, -8.0, 32.0); + assert!(!view.casts_into(min, max, noon)); + // The same box with a low sun behind the camera (south): it does. + assert!(view.casts_into(min, max, Vec3::new(0.0, 0.2, 1.0).normalize())); + } + #[test] fn surface_is_8_bit_and_not_srgb() { use super::surface_format; diff --git a/crates/horizon-client/src/gfx/java_stages.rs b/crates/horizon-client/src/gfx/java_stages.rs index dbe03dae9..a8a445746 100644 --- a/crates/horizon-client/src/gfx/java_stages.rs +++ b/crates/horizon-client/src/gfx/java_stages.rs @@ -2852,8 +2852,22 @@ mod tests { close( projection, Mat4::from_cols_array(&[ - 0.03125, 0.0, 0.0, 0.0, 0.0, 0.03125, 0.0, 0.0, 0.0, 0.0, -0.007_814_026, 0.0, 0.0, - 0.0, -1.000_390_6, 1.0, + 0.03125, + 0.0, + 0.0, + 0.0, + 0.0, + 0.03125, + 0.0, + 0.0, + 0.0, + 0.0, + -0.007_814_026, + 0.0, + 0.0, + 0.0, + -1.000_390_6, + 1.0, ]), ); // Noon: the light looks straight down (up is toward it, +z). @@ -2862,7 +2876,10 @@ mod tests { let directives = Directives::default(); let (snapped, _) = shadow_matrices(&directives, 0.25, Vec3::new(5.5, 0.0, 0.0)); let (plain, _) = shadow_matrices(&directives, 0.25, Vec3::ZERO); - close(snapped, plain * Mat4::from_translation(Vec3::new(1.5, 0.0, 0.0))); + close( + snapped, + plain * Mat4::from_translation(Vec3::new(1.5, 0.0, 0.0)), + ); } #[test] diff --git a/docs/shader-packs.md b/docs/shader-packs.md index 96013f15b..de0e82717 100644 --- a/docs/shader-packs.md +++ b/docs/shader-packs.md @@ -380,8 +380,9 @@ cutout blocks; `shadow_water` or `shadow` for the translucent one), it draws a s (the moon at night) with the pack's `sunPathRotation`, snapped to `shadowIntervalSize`; `shadowProjection` is orthographic, `shadowDistance` each way, between `shadowNearPlane` and `shadowFarPlane` (Iris's defaults when the pack sets none); the shadow programs get them as `gl_ModelViewMatrix` and `gl_ProjectionMatrix`; -- the renderer draws every section inside that box from its own list (not the camera's: cave culling is off as in - Iris, and no face is culled), solid then translucent, instanced draws only; +- the renderer draws every section inside that box whose shadow can reach the camera's view (the box swept away + from the light against the view's planes, as Iris's advanced shadow culling), from its own list (cave culling is + off as in Iris, and no face is culled), solid then translucent, instanced draws only; - `shadowtex0` holds all of it, `shadowtex1` the depth before translucent terrain; both are bound as depth textures for `sampler2DShadow` (linear comparison, Iris's hardware filtering) and as float copies for `sampler2D` reads; - `shadowcolor0..7` are `shadowMapResolution` square in their `shadowcolorFormat`, cleared each frame to From d522d8fe50bcd275e95629886e17be406bc40bce Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 08:38:58 +0200 Subject: [PATCH 007/408] Saved state: burning, air and falling survive a reopen; InLove for every animal - Guests' player data saves Fire, Air and fall_distance and puts them back on their body when they come back (single player's players are guests of the integrated server), so a burning player still burns after a reopen (#1323); the old single player's level.dat keeps fall_distance too (#1327). - Every Animal saves and loads InLove, so a fed animal stays in love across a reopen and is not fed again (#1396). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/entity_nbt.rs | 8 +- crates/horizon-client/src/game.rs | 1 + crates/horizon-client/src/game/lan_actions.rs | 6 ++ crates/horizon-client/src/lan/guest.rs | 29 +++++++ crates/horizon-client/src/lan/playerdata.rs | 80 ++++++++++++++++++- crates/horizon-client/src/mobs/rabbit.rs | 12 +++ crates/horizon-client/src/motion.rs | 1 + 7 files changed, 135 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index aaccdd844..7faa94e21 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -175,12 +175,15 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { for (key, value) in [ ("Age", Tag::Int(0)), ("ForcedAge", Tag::Int(0)), - ("InLove", Tag::Int(0)), ("AgeLocked", Tag::Byte(0)), ] { map.entry(key.into()).or_insert(value); } } + // Animal.addAdditionalSaveData: the love ticks left, whatever the save had. + if m.kind.flags.animal { + map.insert("InLove".into(), Tag::Int(m.extra.in_love.max(0))); + } match id { "minecraft:creeper" => { for (key, value) in [("Fuse", Tag::Short(30)), ("ExplosionRadius", Tag::Byte(3))] { @@ -621,6 +624,9 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.extra.forced_age = number(tag.get("ForcedAge")).unwrap_or(0) as i32; m.extra.age_locked = flag(tag, "AgeLocked"); } + if m.kind.flags.animal { + m.extra.in_love = number(tag.get("InLove")).unwrap_or(0) as i32; + } m.name_visible = flag(tag, "CustomNameVisible"); m.no_ai = flag(tag, "NoAI"); m.no_gravity = flag(tag, "NoGravity"); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 0faca0ab4..6a2ebcf25 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -9534,6 +9534,7 @@ impl Game<'_> { ); map.insert("Air".into(), horizon_world::nbt::Tag::Short(p.air as i16)); } + level.fall_distance = p.fall_distance; level.food = p.health.food.food; level.saturation = p.health.food.saturation; diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 67764c090..77d68c6b9 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -217,6 +217,12 @@ impl Game<'_> { host.hub.guests[i].position[2], ); host.hub.guests[i].motion = PlayerMotion::new(self.motion, p).ok().map(Box::new); + // The first body after joining burns, breathes and falls on as saved. + if let Some(saved) = host.hub.guests[i].loaded_body.take() + && let Some(m) = host.hub.guests[i].motion.as_mut() + { + saved.apply(m); + } let kept = host.hub.guests[i].logs_kept.take(); if let (Some(m), Some((hurts, attacks))) = (host.hub.guests[i].motion.as_mut(), kept) { m.hurt_log = hurts; diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 948de7e20..227cd4335 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -18,6 +18,31 @@ pub const CREATIVE: i32 = 1; pub const ADVENTURE: i32 = 2; pub const SPECTATOR: i32 = 3; +/// The body state a player's file keeps that lives on `PlayerMotion`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SavedBody { + pub fire_ticks: i32, + pub air: i32, + pub fall_distance: f64, +} + +impl SavedBody { + /// The body state of `motion`, to save. + pub fn of(motion: &PlayerMotion) -> Self { + Self { + fire_ticks: motion.fire_ticks, + air: motion.air, + fall_distance: motion.fall_distance, + } + } + /// Put it on a new body. + pub fn apply(self, motion: &mut PlayerMotion) { + motion.fire_ticks = self.fire_ticks; + motion.air = self.air; + motion.fall_distance = self.fall_distance; + } +} + /// An effect as last sent in ClientboundUpdateMobEffectPacket. #[derive(Clone, Debug, PartialEq)] pub struct SentEffect { @@ -133,6 +158,9 @@ pub struct Guest { pub tracker: Tracker, // Player state the gameplay code reads and writes. pub motion: Option>, + /// What the player's file says of the body (`Entity.load`: the fire + /// and air ticks and the fall distance), for the first body it gets. + pub loaded_body: Option, /// The hurt and attack logs of the body it had before it respawned, /// until the new body takes them over (the control socket's `hurtlog` /// reads across a death). @@ -275,6 +303,7 @@ impl Guest { batch_quota: 0.0, tracker: Tracker::default(), motion: None, + loaded_body: None, logs_kept: None, inventory: vec![None; 36], armor: [None, None, None, None], diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index 24a4a9d65..180074f84 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -1,6 +1,6 @@ //! Guests' saved state: `players/data/.dat` in the vanilla player //! compound, through the same code that saves the host. -use super::guest::Guest; +use super::guest::{Guest, SavedBody}; use crate::{ items::ItemStack, save::{Level, read_dat, write_dat}, @@ -74,6 +74,17 @@ pub fn apply(guest: &mut Guest, level: &Level) { guest.spawn = level.spawn.map(|s| [s[0] + 0.5, s[1], s[2] + 0.5]); guest.respawn_elsewhere = level.respawn_elsewhere.clone(); guest.saved = level.player_extra.clone(); + let extra = level.player_extra.as_ref(); + let short = |key: &str, default: i64| { + extra + .and_then(|t| crate::save::number(t.get(key))) + .unwrap_or(default) as i32 + }; + guest.loaded_body = Some(SavedBody { + fire_ticks: short("Fire", -20), + air: short("Air", 300), + fall_distance: level.fall_distance, + }); guest.recipe_book = level.recipe_book.clone(); guest.dimension = match level.dimension.as_str() { d @ ("minecraft:the_nether" | "minecraft:the_end") => d.to_owned(), @@ -139,6 +150,24 @@ pub fn store(guest: &Guest, level: &mut Level) { level.respawn_elsewhere = guest.respawn_elsewhere.clone(); level.on_ground = guest.on_ground; level.player_extra = guest.saved.clone(); + // The live body's fire, air and fall distance (Entity.saveWithoutId), + // or what the file had while the player has no body yet. + let body = guest + .motion + .as_deref() + .map(SavedBody::of) + .or(guest.loaded_body); + if let Some(body) = body { + level.fall_distance = body.fall_distance; + let extra = level + .player_extra + .get_or_insert_with(|| horizon_world::nbt::Tag::Compound(Default::default())); + if let horizon_world::nbt::Tag::Compound(map) = extra { + let short = |v: i32| horizon_world::nbt::Tag::Short(v.clamp(-32768, 32767) as i16); + map.insert("Fire".into(), short(body.fire_ticks)); + map.insert("Air".into(), short(body.air)); + } + } level.recipe_book = guest.recipe_book.clone(); level.ender_items = guest.ender_items.clone(); level.inventory.clear(); @@ -162,3 +191,52 @@ pub fn store(guest: &Guest, level: &mut Level) { put(100, &guest.armor[3]); put(150, &guest.offhand); } + +#[cfg(test)] +mod tests { + use super::*; + use crate::lan::{Joined, PlayerSender}; + use horizon_protocol::packets::configuration::ClientInformation; + use std::sync::{Arc, atomic::AtomicI32, mpsc}; + + fn guest() -> Guest { + let (tx, _rx) = mpsc::channel(); + Guest::new( + Joined { + conn: 2, + uuid: 2, + name: "Alex".into(), + properties: Vec::new(), + info: ClientInformation::new(8), + brand: "test".into(), + sender: PlayerSender::new(tx, Arc::default()), + latency: Arc::new(AtomicI32::new(0)), + address: "127.0.0.1:25565".parse().unwrap(), + }, + 2, + [0.0, 64.0, 0.0], + 8, + ) + } + + #[test] + fn a_saved_burn_and_fall_come_back() { + // A player saved burning in mid-fall (#1323, #1327): Entity.saveWithoutId's + // Fire, Air and fall_distance, read back for the next body. + let mut g = guest(); + g.loaded_body = Some(SavedBody { + fire_ticks: 96, + air: 250, + fall_distance: 9.5, + }); + let mut level = Level::default(); + store(&g, &mut level); + let tag = level.player_tag(); + let mut read = Level::default(); + read.read_player(&tag); + read.player_extra = Some(tag); + let mut back = guest(); + apply(&mut back, &read); + assert_eq!(back.loaded_body, g.loaded_body); + } +} diff --git a/crates/horizon-client/src/mobs/rabbit.rs b/crates/horizon-client/src/mobs/rabbit.rs index 05ab0e390..a2ab6e95c 100644 --- a/crates/horizon-client/src/mobs/rabbit.rs +++ b/crates/horizon-client/src/mobs/rabbit.rs @@ -310,6 +310,18 @@ mod tests { } } + #[test] + fn love_ticks_survive_a_save() { + // Animal.addAdditionalSaveData / readAdditionalSaveData: "InLove" (#1396). + let mut m = rabbit(); + m.extra.in_love = 570; + let tag = crate::entity_nbt::mob_to_nbt(&m, [0, 0, 0, 1], None); + assert_eq!(tag.get("InLove"), Some(&horizon_world::nbt::Tag::Int(570))); + let types = HashMap::from([(m.kind.id.clone(), m.kind.clone())]); + let back = crate::entity_nbt::mob_from_nbt(&tag, &types, 2).unwrap(); + assert_eq!(back.extra.in_love, 570); + } + #[test] fn landing_waits_then_real_hop_clock_moves_the_model() { let mut m = rabbit(); diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 1920026b9..381cf8f88 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -337,6 +337,7 @@ impl PlayerMotion { self.air = extra .and_then(|t| crate::save::number(t.get("Air"))) .unwrap_or(300) as i32; + self.fall_distance = level.fall_distance; self.set_health(level.health, false)?; self.health.food.food = level.food; self.health.food.saturation = level.saturation; From 337d7d7a7a518e425d3f6dc9676f0b41b716a085 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 08:39:45 +0200 Subject: [PATCH 008/408] Entity use with either hand: bows and food past a mob, off-hand items on mobs, emptied frames - The remote client sends Interact for a targeted mob only for a hand vanilla's client-side Mob.interact would accept with it (leads, name tags, food, buckets, shears, saddled mounts, tamed pets, ...), so a bow drawn or food eaten while aiming at a cow goes on to useItem (#1350). - Both hands: the main hand's item, then the off hand's entity, block and item (Minecraft.startUseItem). The server runs Interact with the packet's hand (GuestUse::Entity), and mobs, armour stands, leads and mounts use the held hand's stack, so an off-hand bucket milks a cow and off-hand wheat feeds it (#1362). - The entity tracker sends an item frame's item and rotation when they go back to empty and 0, so a punched frame shows empty on clients (#1355). - lan_e2e `hands`: the bow, the golden apple, the off-hand bucket and wheat and the emptied frame, for the host and the guest. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 35 +++++-- .../horizon-client/src/game/armor_stands.rs | 4 +- crates/horizon-client/src/game/creatures.rs | 31 ++++--- crates/horizon-client/src/game/lan_actions.rs | 5 + crates/horizon-client/src/game/leads.rs | 4 +- crates/horizon-client/src/game/mounts.rs | 2 +- crates/horizon-client/src/game/remote.rs | 29 ++++-- .../horizon-client/src/game/remote_mob_use.rs | 91 +++++++++++++++++++ crates/horizon-client/src/lan/entity.rs | 39 +++++++- tools/lan_e2e.py | 86 +++++++++++++++++- 10 files changed, 288 insertions(+), 38 deletions(-) create mode 100644 crates/horizon-client/src/game/remote_mob_use.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 0faca0ab4..2d185b40e 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -121,6 +121,7 @@ mod pumpkin; mod raids; mod recipe_book; mod remote; +mod remote_mob_use; mod remote_objects; mod remote_projectiles; mod remote_stations; @@ -495,6 +496,9 @@ enum FallStep { enum GuestUse { OnBlock(Hand), Item(Hand), + /// `handleInteract`: `Player.interactOn` with the hand, nothing else (the + /// client sends UseItem itself when the entity passed). + Entity(Hand), } /// The client world as seen by the vanilla block-behaviour library. @@ -3210,6 +3214,9 @@ impl Game<'_> { // A guest's use packets name one hand and touch no entity: the client // sends one per hand and part of its click, and Interact for entities. let guest = self.guest_use; + if let Some(GuestUse::Entity(hand)) = guest { + return Ok(self.with_hand(hand, Game::interact_entity)?.then_some(hand)); + } let on_block = matches!(guest, Some(GuestUse::OnBlock(_))); if !on_block && self.riding.is_some() @@ -3218,14 +3225,7 @@ impl Game<'_> { { return Ok(Some(Hand::Main)); } - if guest.is_none() - && (self.interact_frame() - || self.interact_armor_stand() - || self.interact_boat() - || self.interact_cart() - || self.interact_mob()? - || self.interact_knot()) - { + if guest.is_none() && self.interact_entity()? { return Ok(Some(Hand::Main)); } // An EntityHitResult may fall through to Item.use, never to useItemOn. @@ -3235,16 +3235,33 @@ impl Game<'_> { self.pick() }; let hands = match guest { - Some(GuestUse::OnBlock(hand) | GuestUse::Item(hand)) => vec![hand], + Some(GuestUse::OnBlock(hand) | GuestUse::Item(hand) | GuestUse::Entity(hand)) => { + vec![hand] + } None => Hand::BOTH.to_vec(), }; + let entity = guest.is_none() && self.entity_targeted(); for hand in hands { + // The off hand's turn starts on the entity too (Minecraft.startUseItem). + if entity && hand == Hand::Off && self.with_hand(hand, Game::interact_entity)? { + return Ok(Some(hand)); + } if self.with_hand(hand, |game| game.use_hand(block_hit.as_ref()))? { return Ok(Some(hand)); } } Ok(None) } + /// `Player.interactOn` for the entity under the crosshair with the + /// acting hand: whether it took the click. + fn interact_entity(&mut self) -> Result { + Ok(self.interact_frame() + || self.interact_armor_stand() + || self.interact_boat() + || self.interact_cart() + || self.interact_mob()? + || self.interact_knot()) + } /// One hand's turn in `startUseItem`: `useItemOn` the block aimed at, /// then `useItem`. Whether the click ends here (it acted or failed). fn use_hand(&mut self, block_hit: Option<&Hit>) -> Result { diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index 6e06f21b0..f175af401 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -461,14 +461,14 @@ impl Game<'_> { count: 1, ..h.clone() }); - self.inventory[self.selected] = Some(ItemStack { + *self.held_mut() = Some(ItemStack { count: h.count - 1, ..h }); } h => { self.armor_stands[i].equipment[slot] = h; - self.inventory[self.selected] = current; + *self.held_mut() = current; } } let p = self.armor_stands[i].position; diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 969543601..06b96be2b 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2409,13 +2409,14 @@ impl Game<'_> { self.spawn_item(rest, self.eye_position().unwrap_or([0.0; 3]), [0.0; 3], 40); } } else { - self.inventory[self.selected] = Some(filled); + *self.held_mut() = Some(filled); } self.swing_arm(); return Ok(true); } let creative = self.creative; - let selected = self.selected; + // The hand's slot (Player.interactOn passes the hand). + let selected = self.held_slot(); if self.interact_zombie_villager(index, &item) { return Ok(true); } @@ -2447,10 +2448,10 @@ impl Game<'_> { // PiglinAi.mobInteract: hand over something gold to admire. if self.mobs[index].alive() && self.give_piglin(index, &item) { self.swing_arm(); - if !creative && let Some(stack) = self.inventory[selected].as_mut() { + if !creative && let Some(stack) = self.stack_in_mut(selected).as_mut() { stack.count -= 1; if stack.count == 0 { - self.inventory[selected] = None; + *self.stack_in_mut(selected) = None; } } return Ok(true); @@ -2761,11 +2762,11 @@ impl Game<'_> { } if consume && !creative - && let Some(stack) = self.inventory[selected].as_mut() + && let Some(stack) = self.stack_in_mut(selected).as_mut() { stack.count -= 1; if stack.count == 0 { - self.inventory[selected] = None; + *self.stack_in_mut(selected) = None; } } if let Some(g) = give { @@ -2775,8 +2776,8 @@ impl Game<'_> { damage: 0, extra: None, }; - if self.inventory[selected].is_none() { - self.inventory[selected] = Some(stack); + if self.stack_in(selected).is_none() { + *self.stack_in_mut(selected) = Some(stack); } else if let Some(rest) = self.give(stack) { let at = self.eye_position().unwrap_or(center); self.spawn_item(rest, at, [0.0, 0.0, 0.0], 40); @@ -2808,13 +2809,17 @@ impl Game<'_> { if self.creative { return; } - if let Some(stack) = self.inventory[self.selected].as_mut() - && let Some(info) = self.res.items().get(&stack.item) - && info.max_damage > 0 + let slot = self.held_slot(); + let max_damage = self + .held() + .and_then(|s| self.res.items().get(&s.item)) + .map_or(0, |i| i.max_damage); + if max_damage > 0 + && let Some(stack) = self.stack_in_mut(slot).as_mut() { stack.damage += 1; - if stack.damage >= info.max_damage { - self.inventory[self.selected] = None; + if stack.damage >= max_damage { + *self.stack_in_mut(slot) = None; } } } diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 67764c090..e3b94a87b 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -942,9 +942,14 @@ impl Game<'_> { .look_at_entity(host, gi, p.id, Some(p.location)) .is_some() { + // handleInteract: the entity and that hand only; a click the + // entity passes comes back as UseItem. + let hand = if p.hand == 1 { Hand::Off } else { Hand::Main }; let swung = self.as_guest(host, conn, |g| { + g.guest_use = Some(GuestUse::Entity(hand)); let swings = g.swings_started; let _ = g.use_item(); + g.guest_use = None; g.swings_started != swings }); self.lan_swing_back(host, conn, swung); diff --git a/crates/horizon-client/src/game/leads.rs b/crates/horizon-client/src/game/leads.rs index ae5d87fff..3a5112967 100644 --- a/crates/horizon-client/src/game/leads.rs +++ b/crates/horizon-client/src/game/leads.rs @@ -202,10 +202,10 @@ impl Game<'_> { self.mobs[index].extra.leash = Some(Holder::Player); self.lead_sound("tied", at); // The lead is always used up. - if let Some(stack) = self.inventory[self.selected].as_mut() { + if let Some(stack) = self.held_mut().as_mut() { stack.count -= 1; if stack.count == 0 { - self.inventory[self.selected] = None; + *self.held_mut() = None; } } return true; diff --git a/crates/horizon-client/src/game/mounts.rs b/crates/horizon-client/src/game/mounts.rs index c10d7a458..fa4bbc209 100644 --- a/crates/horizon-client/src/game/mounts.rs +++ b/crates/horizon-client/src/game/mounts.rs @@ -104,7 +104,7 @@ impl Game<'_> { } /// `AbstractHorse.mobInteract`. Returns whether the click was used. pub(super) fn interact_mount(&mut self, index: usize, item: &str) -> bool { - let held = self.inventory[self.selected].clone(); + let held = self.held().cloned(); let m = &self.mobs[index]; let species = m.species(); // A server player rides it already (`isVehicle`: no seat, no feeding). diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index f969cbeb9..76851364a 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3624,7 +3624,10 @@ impl Game<'_> { horizon_client::interaction_input::use_on_target(&mut RemoteUseWorld(self), entity); } - fn remote_use_entity(&mut self) -> bool { + /// `Minecraft.startUseItem`'s entity turn for `hand`: Interact goes to + /// the server, and whether the click ends there is what this client's + /// copy of the entity answers (`MultiPlayerGameMode.interact`). + fn remote_use_entity(&mut self, hand: Hand) -> bool { let sneaking = self.keys.contains(&KeyCode::ShiftLeft); // A boat, minecart, item frame, armor stand or painting nearer than // any mob: the server uses it (AbstractBoat.interact boards it). @@ -3632,6 +3635,10 @@ impl Game<'_> { && self.mob_hit().is_none_or(|(_, d)| hit.distance < d) && self.before_block(hit.distance) { + // The main hand's turn takes it; there is no off hand turn. + if hand == Hand::Off { + return false; + } self.send(S::Interact(play::Interact { id: hit.id, hand: 0, @@ -3647,18 +3654,18 @@ impl Game<'_> { let id = self.mobs[i].id as i32; self.send(S::Interact(play::Interact { id, - hand: 0, + hand: hand_id(hand), location: [0.0, 1.0, 0.0], secondary: sneaking, })); - // Player.interactOn: another player passes, and the held item is - // used instead (Minecraft.startUseItem). + // Player.interactOn: another player passes, and so does a mob + // the held item means nothing to: the item is used instead. let player = self .remote .as_ref() .is_some_and(|r| r.level_players.contains_key(&id)); - if !player { - self.swing_arm(); + if !player && self.remote_mob_takes(i, hand) { + self.with_hand(hand, Game::swing_arm); return true; } } @@ -3881,7 +3888,13 @@ impl Game<'_> { if self.remote_use_item(Hand::Main) { return; } - if !self.entity_targeted() && self.remote_use_block(Hand::Off) { + // The off hand's turn: the entity again, or the block. + let off_target = if self.entity_targeted() { + self.remote_use_entity(Hand::Off) + } else { + self.remote_use_block(Hand::Off) + }; + if off_target { return; } self.remote_use_item(Hand::Off); @@ -4986,7 +4999,7 @@ struct RemoteUseWorld<'g, 'a>(&'g mut Game<'a>); impl horizon_client::interaction_input::TargetUseWorld for RemoteUseWorld<'_, '_> { fn use_entity(&mut self) -> bool { - self.0.remote_use_entity() + self.0.remote_use_entity(Hand::Main) } fn use_block(&mut self) -> bool { self.0.remote_use_block(Hand::Main) diff --git a/crates/horizon-client/src/game/remote_mob_use.rs b/crates/horizon-client/src/game/remote_mob_use.rs new file mode 100644 index 000000000..9575cf925 --- /dev/null +++ b/crates/horizon-client/src/game/remote_mob_use.rs @@ -0,0 +1,91 @@ +//! A server's client right-clicking a mob: vanilla's client runs +//! `Player.interactOn` on its own level (`MultiPlayerGameMode.interact`) to +//! learn whether the click ends on the mob or goes on to the held item +//! (`Minecraft.startUseItem` then sends UseItem). The server does the real +//! interaction; this is what the client's copy of the mob answers. +use super::Game; +use horizon_client::{ + first_person::Hand, + mobs::{Species, equine, llama}, +}; + +impl Game<'_> { + /// Whether mob `i` takes a right click with `hand`'s item on this + /// client (`Mob.interact`'s result consumes the action). + pub(super) fn remote_mob_takes(&self, i: usize, hand: Hand) -> bool { + let Some(m) = self.mobs.get(i).filter(|m| m.alive()) else { + return false; + }; + let stack = match hand { + Hand::Main => self.stack_in(self.selected), + Hand::Off => self.offhand.as_ref(), + }; + let item = stack.map_or("", |s| &*s.item); + let baby = m.is_baby(); + // Mob.checkAndHandleImportantInteractions: a lead, a named name tag, + // a spawn egg of the mob's own kind. + if item == "minecraft:lead" + || item == "minecraft:name_tag" && stack.is_some_and(|s| s.custom_name().is_some()) + || item.strip_suffix("_spawn_egg") == Some(m.kind.id.as_str()) + { + return true; + } + // Animal.mobInteract: its food is CONSUME on a client. + if m.kind.flags.animal && m.kind.food.iter().any(|f| f.as_str() == item) { + return true; + } + let sneaking = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft); + match m.species() { + // Villager / WanderingTrader.mobInteract: trading, or a baby's head shake. + Species::Villager | Species::WanderingTrader => item != "minecraft:villager_spawn_egg", + // AbstractHorse, Camel: ridden (or their inventory opened); a baby only eats. + s if equine::is_equine(s) + || llama::is_llama(s) + || matches!(s, Species::Camel | Species::CamelHusk) => + { + !baby + } + // Pig / Strider.mobInteract: a saddled one is ridden. + Species::Pig | Species::Strider => m.extra.saddled && !sneaking, + // HappyGhast.mobInteract: a harnessed adult is ridden. + Species::HappyGhast => !baby && m.extra.head.is_some(), + // TamableAnimal (wolf, cat, parrot) on a client: CONSUME once tame. + Species::Wolf | Species::Cat | Species::Parrot => m.extra.tame, + // Allay.mobInteract: gives an item or takes it back. + Species::Allay => !item.is_empty() || m.extra.main_hand.is_some(), + Species::Cow | Species::Goat => item == "minecraft:bucket" && !baby, + Species::Mooshroom => { + matches!( + item, + "minecraft:bucket" | "minecraft:bowl" | "minecraft:shears" + ) && !baby + } + Species::Sheep => item == "minecraft:shears" || item.ends_with("_dye"), + // Bucketable.bucketMobPickup. + Species::Cod + | Species::Salmon + | Species::TropicalFish + | Species::Pufferfish + | Species::Axolotl + | Species::Tadpole => item == "minecraft:water_bucket", + Species::Armadillo => item == "minecraft:brush", + // ZombieVillager.mobInteract: CONSUME for a golden apple. + Species::ZombieVillager => item == "minecraft:golden_apple", + // Creeper.mobInteract: CREEPER_IGNITERS. + Species::Creeper => { + matches!(item, "minecraft:flint_and_steel" | "minecraft:fire_charge") + } + // PiglinAi.mobInteract: an adult admires what it loves. + Species::Piglin => { + !baby + && self + .res + .items() + .item_tags + .get("minecraft:piglin_loved") + .is_some_and(|tag| tag.contains(item)) + } + _ => false, + } + } +} diff --git a/crates/horizon-client/src/lan/entity.rs b/crates/horizon-client/src/lan/entity.rs index c4e8052c0..b7484a7be 100644 --- a/crates/horizon-client/src/lan/entity.rs +++ b/crates/horizon-client/src/lan/entity.rs @@ -460,12 +460,16 @@ impl ServerEntity { // A value back at its default is left out of the state, but the // clients still hold the old one: Entity's shared flags and pose go // back to 0 (a player standing up again, a mob no longer on fire), - // a sleeper's bed to none. + // a sleeper's bed to none, an item frame's item to empty and its + // rotation to 0 (ItemFrame.DATA_ITEM and DATA_ROTATION). + let frame = e.kind.ends_with("item_frame"); for (index, kind, _) in &self.meta { let default = match (*index, *kind) { (0, serializer::BYTE) => Value::Byte(0), (6, serializer::POSE) => Value::Id(0), (14, serializer::OPTIONAL_BLOCK_POS) => Value::OptPos(None), + (9, serializer::ITEM_STACK) if frame => Value::Item(None), + (10, serializer::INT) if frame => Value::Int(0), _ => continue, }; if !e.meta.iter().any(|m| m.0 == *index) { @@ -1040,6 +1044,39 @@ mod tests { assert!(changes(&mut s, &e).is_empty()); } + #[test] + fn an_emptied_item_frame_sends_its_empty_item_and_rotation() { + let mut e = state(0.0); + e.kind = "minecraft:item_frame".into(); + let mut s = added(&e); + changes(&mut s, &e); + e.meta = vec![ + ( + 9, + serializer::ITEM_STACK, + Value::Item(Some(Stack::new(5, 1))), + ), + (10, serializer::INT, Value::Int(3)), + ]; + changes(&mut s, &e); + // Punched out (ItemFrame.removeFramedMap, setItem(EMPTY)): both back to the default. + e.meta.clear(); + let data = changes(&mut s, &e) + .into_iter() + .find_map(|p| match p { + play::Clientbound::SetEntityData(d) => Some(d), + _ => None, + }) + .expect("the empty frame is sent"); + assert_eq!( + data.values, + vec![ + (9, serializer::ITEM_STACK, Value::Item(None)), + (10, serializer::INT, Value::Int(0)), + ] + ); + } + #[test] fn metadata_and_equipment_send_only_the_changes() { let mut e = state(0.0); diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 79250678e..d659c3811 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -130,6 +130,11 @@ address. The script then checks, from both sides, what a guest's game used to ge it (#1222). - frames: the host and the guest each put a diamond in an item frame and turn it, and put a helmet on an armor stand and take it back (#1222). +- hands: the host and the guest each, at a cow that cares for none of it: draw a bow and shoot, and + let go of a golden apple at once without eating it (the click goes on to the item); + milk the cow with a bucket in the off hand and feed it wheat from the off hand; and + punch the diamond out of an item frame, which then shows empty on both sides (#1350, + #1355, #1362). - mounts: the host and the guest each open a tamed horse's, donkey's and llama's inventory (shift + right click, then the inventory key while riding), put on a saddle, armour or a carpet and fill the chest by shift-clicking. @@ -179,7 +184,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'levels'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'hands', 'lightning', 'riding', 'mounts', 'levels'] class Game: @@ -2809,6 +2814,83 @@ def check_frames(host, guest, out): return result +def check_hands(host, guest, out): + """#1350, #1355, #1362: right clicks a cow passes go on to the item, the off hand gets its + turn on the cow, and a frame punched empty is empty for everyone.""" + result = {} + spots = apart(host, guest) + for label, player, other in (('host', host, guest), ('guest', guest, host)): + x, y, z = spots[label] + player('command', command='gamemode survival') + player('command', command='clear @s') + player('command', command='effect clear @s') + # A cow two blocks ahead that stays put, and a framed diamond on a wall behind the player. + player('command', command=f'summon minecraft:cow {x + 0.5} {y} {z + 3.5} {{NoAI:1b}}') + player('command', command=f'fill {x - 1} {y} {z - 2} {x + 1} {y + 2} {z - 2} minecraft:stone') + player('command', command=f'summon minecraft:item_frame {x + 0.5} {y + 1.5} {z - 0.97} ' + f'{{block_pos:[I;{x},{y + 1},{z - 1}],Facing:3b,Item:{{id:"minecraft:diamond",count:1}}}}') + player.wait(20) + counts = lambda: player('inventory')['counts'] + aim_cow = lambda: player.raw('look-at', f'{x + 0.5:.2f}', f'{y + 0.8:.2f}', f'{z + 3.5:.2f}') + try: + player('command', command='give @s minecraft:bow') + player('command', command='give @s minecraft:arrow 6') + player.wait(5) + player.raw('select', 'minecraft:bow') + aim_cow() + assert player('looking_at')['kind'] == 'entity', f'the {label} does not aim at the cow' + player.raw('mouse', 'right', 'down') + player.wait(25) + drawn = player('state')['using'] + player.raw('mouse', 'right', 'up') + player.wait(20) + assert drawn, f'the {label}\'s bow is not drawn at the cow' + assert counts().get('minecraft:arrow') == 5, f'the {label} shot no arrow: {counts()}' + player('command', command='clear @s') + player('command', command='give @s minecraft:golden_apple') + player.wait(5) + player.raw('select', 'minecraft:golden_apple') + aim_cow() + player.raw('mouse', 'right', 'down') + player.wait(5) + player.raw('mouse', 'right', 'up') + player.wait(40) + assert counts().get('minecraft:golden_apple') == 1, f'the {label} ate the apple let go of: {counts()}' + # The main hand empty, a bucket and then wheat in the off hand. + player('command', command='clear @s') + player('command', command='item replace entity @s weapon.offhand with minecraft:bucket') + player.wait(5) + aim_cow() + player.raw('mouse', 'right', 'click') + player.wait(15) + offhand = player('inventory')['offhand'] + assert offhand and offhand['item'] == 'minecraft:milk_bucket', f'the {label}\'s off hand holds {offhand}' + player('command', command='item replace entity @s weapon.offhand with minecraft:wheat 3') + player.wait(5) + aim_cow() + player.raw('mouse', 'right', 'click') + player.wait(15) + offhand = player('inventory')['offhand'] + assert offhand and offhand['count'] == 2, f'the {label}\'s cow ate no off hand wheat: {offhand}' + # The framed diamond, punched out. + frame = [o for o in player('status')['objects'] if o['kind'].endswith('item_frame') + and o['position'] == [x, y + 1, z - 1]] + assert frame and frame[0]['item'] == 'minecraft:diamond', f'the {label} sees the frame as {frame}' + player.raw('look-at', f'{x + 0.5:.2f}', f'{y + 1.5:.2f}', f'{z - 0.95:.2f}') + player.raw('mouse', 'left', 'click') + player.wait(20) + for side, game in ((label, player), ('other side', other)): + seen = [o for o in game('status')['objects'] if o['kind'].endswith('item_frame') + and o['position'] == [x, y + 1, z - 1]] + assert seen and seen[0].get('item') is None, f'the {side} sees the punched frame as {seen}' + result[label] = {'bow': 'shot', 'apple': 'kept', 'off hand': 'milked, fed', 'frame': 'emptied'} + finally: + player('command', command=f'kill @e[type=!minecraft:player,x={x - 3},y={y - 1},z={z - 3},dx=6,dy=4,dz=8]') + player('command', command=f'fill {x - 1} {y} {z - 2} {x + 1} {y + 2} {z - 2} minecraft:air') + player('command', command='clear @s') + return result + + # Animals a player rides: (kind, summon NBT, what readies it, what is held to ride, the test # while riding). `move` walks forward, `jump` charges the horse's jump bar, `rise` holds jump on # a happy ghast, `sit` only rides (a llama goes where it likes). @@ -3369,7 +3451,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, - 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts, + 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, 'hands': check_hands, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts, 'levels': check_levels} From c7abc8c718d6fd78bc5ed8f7766a3ab8491cb846 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 08:39:46 +0200 Subject: [PATCH 009/408] Chat: styled server components, click and hover events, legacy codes, message order MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A connection's chat keeps the server's component: SystemChat goes through the same translation and styles as the action bar, and player and disguised chat are decorated from their chat type's translation, parameters and style (ChatType.Bound.decorate), so colours, bold, hex colours, and the client's language are kept (#1372, #1389). - Components parse `click_event` (suggest_command, copy_to_clipboard; never open_file from a server) and `hover_event` show_text (#1377), and the chat screen draws the hovered part's tooltip (#1381). - `§` codes in chat colour the text with Chat Colors on and are stripped with it off (ComponentRenderUtils.wrapComponents) (#1379). - A command's operator broadcast skips the player whose command it was on the integrated server too (#1373), and /give fires InventoryChangeTrigger before its message, whose announcement is sent first (#1375). - The control socket's `messages` gives the chat lines as components; lan_e2e `styles` checks a styled tellraw, the advancement order and the missing echo for the host and the guest. Co-Authored-By: Claude Opus 5.5 --- .../examples/hud_fixture/kinds.rs | 1 + crates/horizon-client/src/chat.rs | 42 +++++++- crates/horizon-client/src/chat_tests.rs | 42 ++++++++ crates/horizon-client/src/component.rs | 19 ++++ crates/horizon-client/src/game/agent.rs | 2 + crates/horizon-client/src/game/chat.rs | 35 ++++++- crates/horizon-client/src/game/commands.rs | 5 + crates/horizon-client/src/game/integrated.rs | 4 +- crates/horizon-client/src/game/lan_actions.rs | 11 ++- crates/horizon-client/src/game/remote.rs | 95 +++++++++---------- crates/horizon-client/src/settings.rs | 1 + crates/horizon-client/src/text.rs | 28 ++++++ tools/lan_e2e.py | 74 ++++++++++++++- 13 files changed, 297 insertions(+), 62 deletions(-) diff --git a/crates/horizon-client/examples/hud_fixture/kinds.rs b/crates/horizon-client/examples/hud_fixture/kinds.rs index 850db5218..d1450f2e1 100644 --- a/crates/horizon-client/examples/hud_fixture/kinds.rs +++ b/crates/horizon-client/examples/hud_fixture/kinds.rs @@ -306,6 +306,7 @@ fn chat(c: &Value, h: i32, atlas: &HudAtlas) -> Vec { height_focused: option("chatHeightFocused"), height_unfocused: option("chatHeightUnfocused"), line_spacing: option("chatLineSpacing"), + colors: c["chatColors"].as_bool().unwrap_or(true), }; for m in c["messages"].as_array().into_iter().flatten() { // GuiMessageTag indicator colours: systemSinglePlayer and chatError. diff --git a/crates/horizon-client/src/chat.rs b/crates/horizon-client/src/chat.rs index 7c51a40f1..273b87153 100644 --- a/crates/horizon-client/src/chat.rs +++ b/crates/horizon-client/src/chat.rs @@ -29,10 +29,14 @@ pub struct ChatOptions { pub height_focused: f64, pub height_unfocused: f64, pub line_spacing: f64, + /// Chat Colors (`chatColors`): legacy `§` codes format the text, or are + /// left out. + pub colors: bool, } impl Default for ChatOptions { fn default() -> Self { Self { + colors: true, opacity: 1.0, background_opacity: 0.5, scale: 1.0, @@ -136,7 +140,8 @@ impl Chat { } fn add_lines(&mut self, atlas: &HudAtlas, message: &Message, focused: bool) { let width = self.max_width(); - for line in atlas.font.wrap_components(&message.content, width) { + let content = self.displayed(&message.content); + for line in atlas.font.wrap_components(&content, width) { if focused && self.scroll > 0 { self.new_since_scroll = true; self.scroll_by(1, focused); @@ -152,6 +157,16 @@ impl Chat { } self.lines.truncate(100); } + /// What a message's lines wrap (ComponentRenderUtils.wrapComponents): + /// without Chat Colors its `§` codes are stripped (stripColor); with + /// them the font draws them as formatting. + fn displayed(&self, content: &Text) -> Text { + if self.options.colors { + content.resolve_legacy() + } else { + content.strip_legacy() + } + } /// Re-wrap after a width or scale change (ChatComponent.rescaleChat). pub fn rescale(&mut self, atlas: &HudAtlas) { self.scroll = 0; @@ -308,6 +323,21 @@ impl Chat { x: f64, y: f64, ) -> Option { + self.style_at(font, height, x, y)?.click + } + /// The hover text under a GUI-space cursor while chat is focused + /// (ChatScreen.render's `renderComponentHoverEffect`). + pub fn hover_at(&self, font: &crate::font::Font, height: i32, x: f64, y: f64) -> Option { + self.style_at(font, height, x, y)?.hover.map(|h| *h) + } + /// ChatComponent.getClickedComponentStyleAt. + fn style_at( + &self, + font: &crate::font::Font, + height: i32, + x: f64, + y: f64, + ) -> Option { let scale = self.options.scale as f32; let mut x = x / f64::from(scale) - 4.0; let bottom = hud_layout::floor((height - 40) as f32 / scale); @@ -324,7 +354,7 @@ impl Chat { for (c, style) in content.chars() { x -= f64::from(font.advance(c, style)); if x < 0.0 { - return style.click.clone(); + return Some(style.clone()); } } None @@ -337,6 +367,14 @@ impl Chat { .map(|m| m.content.plain()) .collect() } + /// The newest messages as components, styles included (control socket). + pub fn recent_components(&self, n: usize) -> Vec { + self.messages + .iter() + .take(n) + .map(|m| m.content.component()) + .collect() + } } /// `CommandSuggestions.SuggestionsList`. diff --git a/crates/horizon-client/src/chat_tests.rs b/crates/horizon-client/src/chat_tests.rs index e1bf2feda..d0ce3f458 100644 --- a/crates/horizon-client/src/chat_tests.rs +++ b/crates/horizon-client/src/chat_tests.rs @@ -285,3 +285,45 @@ fn ask_server_nodes_wait_for_the_servers_completions() { screen.type_text(&m, &c, "/bossbar get pt"); assert_eq!(screen.take_request(), None); } + +#[test] +fn legacy_codes_colour_the_line_or_vanish_without_chat_colours() { + let mut chat = Chat::default(); + let red = Text::literal("\u{a7}cRED"); + let shown = chat.displayed(&red); + assert_eq!(shown.plain(), "RED"); + assert!(shown.chars().all(|(_, s)| s.color == Some(0xFF5555))); + chat.options.colors = false; + let shown = chat.displayed(&red); + assert_eq!(shown.plain(), "RED"); + assert!(shown.chars().all(|(_, s)| s.color.is_none())); + // A lone section sign or an unknown code stays as written. + assert_eq!( + chat.displayed(&Text::literal("a\u{a7}zb")).plain(), + "a\u{a7}zb" + ); +} + +#[test] +fn a_server_component_keeps_its_click_and_hover_events() { + let font = font(); + let json = serde_json::json!({ + "text": "CLICK", "color": "green", "bold": true, + "click_event": {"action": "suggest_command", "command": "/say clicked"}, + "hover_event": {"action": "show_text", "value": {"text": "Tip", "color": "aqua"}}, + }); + let line = crate::component::to_text(&json, &mut |s| Text::literal(s)); + let mut chat = Chat::default(); + add(&mut chat, &font, line); + let x = 4.0 + f64::from(font.width("CL")); + let Some(ClickEvent::SuggestCommand(command)) = chat.click_at(&font, 360, x, 315.0) else { + panic!("the line must suggest its command"); + }; + assert_eq!(command, "/say clicked"); + let hover = chat.hover_at(&font, 360, x, 315.0).expect("a hover text"); + assert_eq!(hover.plain(), "Tip"); + assert_eq!(hover.spans[0].style.color, Some(text::AQUA)); + // Past the (bold, so wider) text, nothing. + let past = 4.0 + f64::from(font.width("CLICK")) + 20.0; + assert!(chat.hover_at(&font, 360, past, 315.0).is_none()); +} diff --git a/crates/horizon-client/src/component.rs b/crates/horizon-client/src/component.rs index 68460054b..fced49898 100644 --- a/crates/horizon-client/src/component.rs +++ b/crates/horizon-client/src/component.rs @@ -168,6 +168,25 @@ fn object_style(o: &serde_json::Map) -> Style { style.strikethrough = flag("strikethrough"); style.obfuscated = flag("obfuscated"); style.font = o.get("font").and_then(crate::text::font_id); + // ClickEvent.CODEC: the actions a chat line acts on here. A component + // from a server never opens a file. + if let Some(e) = o.get("click_event").and_then(Value::as_object) { + let text = |k: &str| e.get(k).and_then(Value::as_str).map(str::to_owned); + style.click = match e.get("action").and_then(Value::as_str) { + Some("suggest_command") => text("command").map(crate::text::ClickEvent::SuggestCommand), + Some("copy_to_clipboard") => { + text("value").map(crate::text::ClickEvent::CopyToClipboard) + } + _ => None, + }; + } + // HoverEvent.ShowText. + if let Some(e) = o.get("hover_event").and_then(Value::as_object) + && e.get("action").and_then(Value::as_str) == Some("show_text") + && let Some(value) = e.get("value") + { + style.hover = Some(Box::new(to_text(value, &mut |s| Text::literal(s)))); + } style } /// `ComponentSerialization.CODEC` decoding into text. `selector` components diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 3d957efe0..3ee069778 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -673,6 +673,8 @@ impl Game<'_> { json!({ "chat": self.remote_chat(n).unwrap_or_else(|| self.ui.chat.recent_lines(n)), "order": "newest first", + // The chat lines as drawn: colours, click and hover events. + "styled": self.ui.chat.recent_components(n), "title": (titles.time > 0).then(|| titles.title.as_ref().map(|t| t.plain())).flatten(), "subtitle": (titles.time > 0).then(|| titles.subtitle.as_ref().map(|t| t.plain())).flatten(), "actionbar": (titles.overlay_time > 0).then(|| titles.overlay.as_ref().map(|t| t.plain())).flatten(), diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 20aeeb7fd..be73607ae 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -450,7 +450,7 @@ impl Game<'_> { // Connected to a server (single player's own included), the chat on // screen is the connection's: the game's own messages join it. if self.remote.is_some() { - self.chat_line(text.plain()); + self.chat_line(text); return; } let focused = self.screen == Screen::Chat; @@ -681,6 +681,16 @@ impl Game<'_> { let draws = screen.draw(&m, mouse, blink, background); horizon_client::screen_draw::paint(batch, &self.gui.atlas, &draws); self.ui.chat_screen = Some(screen); + // The hovered message part's tooltip, one row per line of its text. + if let Some(hover) = self.ui.chat.hover_at( + &self.gui.atlas.font, + batch.height as i32, + f64::from(self.cursor.0), + f64::from(self.cursor.1), + ) { + let lines = hover_rows(&hover); + self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1); + } } /// Advance the overworld clock (ServerClockManager.tick) when /// `advance_time` allows it. @@ -953,3 +963,26 @@ fn write_difficulty(world: &std::path::Path, difficulty: u8) -> horizon_client:: fn owner_permission(allow_commands: bool) -> u8 { if allow_commands { 4 } else { 0 } } + +/// A hover text's rows for the tooltip: split at line breaks, each in the +/// colour of its first styled character (white without one). +fn hover_rows(hover: &horizon_client::text::Text) -> Vec<(String, u32)> { + let mut rows = vec![(String::new(), None)]; + for (c, style) in hover.resolve_legacy().chars() { + if c == '\n' { + rows.push((String::new(), None)); + continue; + } + let row = rows.last_mut().expect("one row"); + if row.0.is_empty() { + row.1 = style.color; + } + row.0.push(c); + } + rows.into_iter() + .map(|(text, color)| { + let [_, r, g, b] = color.unwrap_or(0xFF_FFFF).to_be_bytes(); + (text, horizon_client::hud::rgba(r, g, b, 255)) + }) + .collect() +} diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index c6877a839..0a51f6119 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -1039,6 +1039,11 @@ impl Game<'_> { .play("minecraft:entity.item.pickup", Some(p), 0.2, pitch); } } + // containerMenu.broadcastChanges: InventoryChangeTrigger + // (and its announcement) comes before the command's message. + if g.player.is_some() { + g.check_inventory_trigger(); + } }); } // The prototype stack: one item. diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index ef5775174..bdb6fe892 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -465,8 +465,10 @@ impl Game<'_> { host = self.lan.take().expect("a command puts the hub back"); self.leave_guest(&mut host, swap); host.hub.sync_all_effects(); - // A teleport into another level happens before its feedback is sent. + // A teleport into another level happens before its feedback is + // sent, and what the command earned is announced before it too. self.run_level_teleports(&mut host); + self.announce_guest_advancements(&mut host); for line in lines { out.push(line.plain()); host.hub.send_to( diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 67764c090..a34eb417c 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -85,7 +85,7 @@ pub(super) struct GuestCommand { conn: u32, command: String, permission: u8, - /// An integrated server's: no admin feedback or level teleports (yet). + /// An integrated server's: no level teleports (yet). integrated: bool, } @@ -1382,6 +1382,8 @@ impl Game<'_> { // A teleport into another level happens before its feedback is sent. self.run_level_teleports(&mut host); } + // What the command earned is announced before its feedback. + self.announce_guest_advancements(&mut host); for line in lines { host.hub.send_to( c.conn, @@ -1391,9 +1393,8 @@ impl Game<'_> { }), ); } - if !c.integrated { - self.send_admin_feedback(&mut host, Some(c.conn)); - } + // The other operators hear of it; never the player whose command it was. + self.send_admin_feedback(&mut host, Some(c.conn)); self.lan = Some(host); } } @@ -1745,7 +1746,7 @@ impl Game<'_> { /// `PlayerList.broadcastSystemMessage` of the advancements guests made /// (their own actions, commands and ticks). - fn announce_guest_advancements(&mut self, host: &mut LanHost) { + pub(super) fn announce_guest_advancements(&mut self, host: &mut LanHost) { for text in std::mem::take(&mut self.adv.announced) { host.hub .system_message(horizon_client::lan::data::component_nbt(&text.component())); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index f969cbeb9..8dff41c6f 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -38,7 +38,7 @@ use horizon_protocol::{ play::{self, Clientbound as C, Serverbound as S}, }, registry::{Builtin, DimensionType, Dynamic, ceil_log2}, - text::{Language, format_java, plain}, + text::{Language, plain}, }; use horizon_world::{nbt::Tag, registry::BlockStateId}; use std::{ @@ -675,11 +675,14 @@ impl Game<'_> { } Some(stack) } - pub(super) fn chat_line(&mut self, text: String) { + /// A line in the connection's chat, with its styles, click and hover + /// events (ChatComponent.addMessage). + pub(super) fn chat_line(&mut self, content: horizon_client::text::Text) { + let text = content.plain(); log::info!("[chat] {text}"); self.ui.chat.add( &self.gui.atlas, - horizon_client::text::Text::literal(text.clone()), + content, None, self.ticks, self.screen == Screen::Chat, @@ -2256,42 +2259,27 @@ impl Game<'_> { } } C::SystemChat(p) => { - let text = plain( - &p.content, - &self - .remote - .as_ref() - .map(|r| r.lang.clone()) - .unwrap_or_default(), - ); - // ChatListener.handleOverlay. + // The component as sent, translated in the client's own + // language. ChatListener.handleOverlay for the action bar. + let text = remote_text(&p.content); if p.overlay { - self.titles.set_overlay(remote_text(&p.content), false); + self.titles.set_overlay(text, false); } else { self.chat_line(text); } } C::PlayerChat(p) => { - let lang = self - .remote - .as_ref() - .map(|r| r.lang.clone()) - .unwrap_or_default(); + use horizon_client::scoreboard::tag_to_json; let content = p .unsigned_content .as_ref() - .map_or_else(|| p.content.clone(), |t| plain(t, &lang)); - let line = self.format_chat(&p.chat_type, &content); + .map_or_else(|| serde_json::Value::from(p.content.as_str()), tag_to_json); + let line = self.format_chat(&p.chat_type, content); self.chat_line(line); } C::DisguisedChat(p) => { - let lang = self - .remote - .as_ref() - .map(|r| r.lang.clone()) - .unwrap_or_default(); - let content = plain(&p.message, &lang); - let line = self.format_chat(&p.chat_type, &content); + let content = horizon_client::scoreboard::tag_to_json(&p.message); + let line = self.format_chat(&p.chat_type, content); self.chat_line(line); } C::PlayerInfoUpdate(p) => { @@ -2723,11 +2711,17 @@ impl Game<'_> { true } /// ChatType decoration: `chat.translation_key` with sender/content parameters. - fn format_chat(&self, bound: &play::ChatTypeBound, content: &str) -> String { + /// ChatType.Bound.decorate: the chat type's translation, with the + /// sender, the target and the message as its parameters, in its style. + fn format_chat( + &self, + bound: &play::ChatTypeBound, + content: serde_json::Value, + ) -> horizon_client::text::Text { + use horizon_client::scoreboard::{comp_text, tag_to_json}; let Some(r) = self.remote.as_ref() else { - return content.to_owned(); + return comp_text(&content); }; - let sender = plain(&bound.name, &r.lang); let decoration = r .registries .data("minecraft:chat_type", bound.chat_type) @@ -2736,30 +2730,31 @@ impl Game<'_> { Some(Tag::String(s)) => s.to_string_lossy(), _ => "chat.type.text".into(), }; - let params: Vec = match decoration.and_then(|d| d.get("parameters")) { + let parameter = |name: &str| match name { + "sender" => tag_to_json(&bound.name), + "target" => bound + .target + .as_ref() + .map_or_else(|| serde_json::Value::from(""), tag_to_json), + _ => content.clone(), + }; + let with: Vec = match decoration.and_then(|d| d.get("parameters")) { Some(Tag::List(list)) => list .iter() .map(|p| match p { - Tag::String(s) => match s.to_string_lossy().as_str() { - "sender" => sender.clone(), - "target" => bound - .target - .as_ref() - .map(|t| plain(t, &r.lang)) - .unwrap_or_default(), - _ => content.to_owned(), - }, - _ => String::new(), + Tag::String(s) => parameter(&s.to_string_lossy()), + _ => serde_json::Value::from(""), }) .collect(), - _ => vec![sender, content.to_owned()], + _ => vec![parameter("sender"), parameter("content")], }; - let pattern = r - .lang - .get(&key) - .cloned() - .unwrap_or_else(|| "<%s> %s".into()); - format_java(&pattern, ¶ms) + let mut component = match decoration.and_then(|d| d.get("style")) { + Some(style @ Tag::Compound(_)) => tag_to_json(style), + _ => serde_json::json!({}), + }; + component["translate"] = key.into(); + component["with"] = with.into(); + comp_text(&component) } fn remote_item_data(&mut self, id: i32, stack: &Option) { let Some(stack) = self.to_stack(stack) else { @@ -4530,7 +4525,9 @@ impl Game<'_> { self.send(S::ContainerClose(play::ContainerClose { container: p.container, })); - self.chat_line(format!("(Horizon cannot show {menu} screens yet)")); + self.chat_line(horizon_client::text::Text::literal(format!( + "(Horizon cannot show {menu} screens yet)" + ))); return; } }; diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 1fadacf57..20f3ade23 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -593,6 +593,7 @@ impl Settings { height_focused: f64::from(self.chat_height_focused), height_unfocused: f64::from(self.chat_height_unfocused), line_spacing: f64::from(self.chat_line_spacing), + colors: self.chat_colors, } } } diff --git a/crates/horizon-client/src/text.rs b/crates/horizon-client/src/text.rs index 9f39155d1..41a21d285 100644 --- a/crates/horizon-client/src/text.rs +++ b/crates/horizon-client/src/text.rs @@ -428,6 +428,34 @@ impl Text { } out } + /// The text without its legacy `§` codes (ChatFormatting.stripFormatting: + /// a `§` and a code character, `0`-`9`, `a`-`f`, `k`-`o` or `r`). + pub fn strip_legacy(&self) -> Text { + if !self.spans.iter().any(|s| s.text.contains('§')) { + return self.clone(); + } + let code = + |c: char| matches!(c.to_ascii_lowercase(), '0'..='9' | 'a'..='f' | 'k'..='o' | 'r'); + let mut out = Text::default(); + for span in &self.spans { + let mut text = String::with_capacity(span.text.len()); + let mut chars = span.text.chars().peekable(); + while let Some(c) = chars.next() { + if c == '§' && chars.peek().is_some_and(|&n| code(n)) { + chars.next(); + } else { + text.push(c); + } + } + if !text.is_empty() { + out.spans.push(Span { + text, + style: span.style.clone(), + }); + } + } + out + } /// Characters with their effective styles. pub fn chars(&self) -> impl Iterator { self.spans diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 79250678e..00727d61d 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -61,6 +61,9 @@ address. The script then checks, from both sides, what a guest's game used to ge - feedback: the guest's command feedback names the guest and shows the numbers; - chat: a line the host sends reaches the guest's event log (`wait-for chat`), and on the server thread the host window's too; +- styles: a styled tellraw reaches the host and the guest (each its own) with its colour, bold, click and hover + events; each player's /give tells them of the Diamonds! advancement before the give's + own message, and never echoes their command back to them as `[Name: ...]`; - effects: a beacon's power reaches every player in range, the host and the guest; - distance: (--server-thread) the server follows the host's render distance, past vanilla's 32 too (IntegratedServer.tickServer), and the guest's chunks follow the server's (#804) @@ -179,7 +182,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'levels'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'styles', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'levels'] class Game: @@ -1310,8 +1313,8 @@ def check_loom(host, guest, out): def own_reply(event): """A chat event that answers the guest's own command. On the server thread the guest also gets - its own command's `[Guest: ...]` operator broadcast, a moment later, which an answer to the next - command must not be taken for.""" + its own command's `[Guest: ...]` operator broadcast before #1373, a moment later, which an answer + to the next command must not be taken for.""" return event.get('event') == 'chat' and not event.get('text', '').startswith(f'[{GUEST_NAME}: ') @@ -1876,6 +1879,69 @@ def check_chat(host, guest, out): return seen +def styled_parts(component): + """Every component in a chat line's tree (the line, its `extra` and `with` parts).""" + if isinstance(component, dict): + yield component + for key in ('extra', 'with'): + for part in component.get(key) or []: + yield from styled_parts(part) + elif isinstance(component, list): + for part in component: + yield from styled_parts(part) + + +def check_styles(host, guest, out): + # ChatComponent keeps what the server sent: the style, the click and the hover event. + stamp = f'STYLE {int(time.time())}' + line = {'text': stamp, 'color': 'green', 'bold': True, + 'click_event': {'action': 'suggest_command', 'command': '/say clicked'}, + 'hover_event': {'action': 'show_text', 'value': 'Tip'}} + seen = {} + for g in (host, guest): + # Each to itself: tellraw reaches only the player whose command it is here. + since = g.raw('events')['last'] + g('command', command='tellraw @s ' + json.dumps(line)) + g.raw('wait-for', 'chat', stamp, '--timeout', 10, '--since', since) + part = next((p for c in g.raw('messages', 10)['styled'] for p in styled_parts(c) + if stamp in str(p.get('text', ''))), None) or {} + seen[g.name] = {k: part.get(k) for k in ('color', 'bold', 'click_event', 'hover_event')} + hover = seen[g.name]['hover_event'] or {} + seen[g.name]['hover_event'] = [hover.get('action'), 'Tip' in str(hover.get('value'))] + # InventoryChangeTrigger fires inside /give, before its message; the operator echo + # (broadcastToAdmins) skips the player whose command it was. + order = {} + for g in (host, guest): + for command in ('advancement revoke @s everything', 'clear @s'): + g('command', command=command) + g.wait(5) + since = g.raw('events')['last'] + g('command', command='give @s minecraft:diamond') + g.raw('wait-for', 'chat', 'Diamonds!', '--timeout', 10, '--since', since) + g.wait(20) + chat = g.raw('messages', 8)['chat'] + name = GUEST_NAME if g is guest else host.player + gave = next((i for i, l in enumerate(chat) if l.startswith('Gave 1 [Diamond]')), None) + made = next((i for i, l in enumerate(chat) if '[Diamonds!]' in l), None) + echo = [l for l in chat if l.startswith(f'[{name}: ')] + # Newest first: the give's message is newer than the advancement's. + order[g.name] = {'gave': gave, 'advancement': made, 'echo': echo} + guest.raw('key', 't', 'tap') + guest.wait(5) + guest.shot(out, 'styles') + guest.raw('key', 'esc', 'tap') + want = {'color': 'green', 'bold': True, + 'click_event': {'action': 'suggest_command', 'command': '/say clicked'}, + 'hover_event': ['show_text', True]} + for name, got in seen.items(): + assert got == want, f'{name} styled line: {got}' + for name, o in order.items(): + assert o['gave'] is not None and o['advancement'] is not None, f'{name} chat: {o}' + assert o['gave'] < o['advancement'], f'{name}: the give came before the advancement: {o}' + assert not o['echo'], f'{name} heard its own command: {o}' + return {'styles': seen, 'order': order} + + def png_rows(path): """The rows of an 8-bit RGB or RGBA PNG, unfiltered, as bytes of 4 (or 3) per pixel.""" data = Path(path).read_bytes() @@ -3348,7 +3414,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'chest': check_chest, 'crafting': check_crafting, 'sign': check_sign, 'damage': check_damage, 'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp, 'respawn': check_respawn, - 'containers': check_containers, 'feedback': check_feedback, 'titles': check_titles, 'chat': check_chat, + 'containers': check_containers, 'feedback': check_feedback, 'titles': check_titles, 'chat': check_chat, 'styles': check_styles, 'machines': check_machines, 'brewing': check_brewing, 'loom': check_loom, From 7e5e469783dc63de53e88a21d7925a75fc8b3197 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 09:19:48 +0200 Subject: [PATCH 010/408] InLove only for vanilla's Animal subclasses (not allays) save_roundtrip found an allay saved with InLove 0: Horizon's `animal` flag is broader than vanilla's Animal class. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/entity_nbt.rs | 45 +++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 7faa94e21..298b54088 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -89,6 +89,47 @@ impl Base<'_> { } /// `LivingEntity` + `Mob` (+ `AgeableMob`, creeper and skeleton specifics). +/// The mobs whose class extends vanilla's `Animal` (and so save `InLove`): +/// not allays, villagers, golems, dolphins or fish. +fn is_animal(id: &str) -> bool { + matches!( + id.strip_prefix("minecraft:").unwrap_or(id), + "pig" + | "cow" + | "mooshroom" + | "sheep" + | "chicken" + | "rabbit" + | "horse" + | "donkey" + | "mule" + | "zombie_horse" + | "skeleton_horse" + | "llama" + | "trader_llama" + | "goat" + | "panda" + | "polar_bear" + | "fox" + | "wolf" + | "cat" + | "ocelot" + | "parrot" + | "bee" + | "turtle" + | "armadillo" + | "frog" + | "axolotl" + | "hoglin" + | "strider" + | "camel" + | "camel_husk" + | "sniffer" + | "happy_ghast" + | "nautilus" + | "zombie_nautilus" + ) +} pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { let base = Base { id: &m.kind.id, @@ -181,7 +222,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { } } // Animal.addAdditionalSaveData: the love ticks left, whatever the save had. - if m.kind.flags.animal { + if is_animal(id) { map.insert("InLove".into(), Tag::Int(m.extra.in_love.max(0))); } match id { @@ -624,7 +665,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.extra.forced_age = number(tag.get("ForcedAge")).unwrap_or(0) as i32; m.extra.age_locked = flag(tag, "AgeLocked"); } - if m.kind.flags.animal { + if is_animal(&m.kind.id) { m.extra.in_love = number(tag.get("InLove")).unwrap_or(0) as i32; } m.name_visible = flag(tag, "CustomNameVisible"); From f88fba8d05616d9cc5265c3420726630d544302d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 08:18:29 +0200 Subject: [PATCH 011/408] A server's attribute updates reach its player; new boss bars start visible The client of a server (single player on its server thread, LAN guests) ignored ClientboundUpdateAttributesPacket for its own player, so a new maximum health never reached it: its hearts stayed at ten and the health it was sent was clamped to 20. It now applies each synced instance's base and modifiers (handleUpdateAttributes) and re-applies the received health. BossBar::new started hidden; ServerBossEvent starts visible. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/bossbar.rs | 2 +- crates/horizon-client/src/game/control.rs | 6 +++ crates/horizon-client/src/game/remote.rs | 9 +++++ crates/horizon-client/src/lan/attributes.rs | 44 +++++++++++++++++++- tools/lan_e2e.py | 45 ++++++++++++++++++++- 5 files changed, 102 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/bossbar.rs b/crates/horizon-client/src/bossbar.rs index a976258f9..eab31a5e5 100644 --- a/crates/horizon-client/src/bossbar.rs +++ b/crates/horizon-client/src/bossbar.rs @@ -46,7 +46,7 @@ impl BossBar { style: "progress".into(), value: 0, max: 100, - visible: false, + visible: true, player: false, } } diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 5645441f0..ca15424d1 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -834,6 +834,12 @@ impl Game<'_> { "velocity": [p.velocity.x, p.velocity.y, p.velocity.z], "on_ground": p.ground.on_ground, "health": p.health.health(), + // The maximum the HUD's hearts last read (its cached value). + "max_health": p + .attributes + .lookup(p.attributes.key("minecraft:max_health").as_ref()) + .and_then(|h| p.attributes.instance(&h).ok()) + .map(|i| i.cached_value()), "food": p.health.food.food, }) }); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 578af5f69..b8777e8d2 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2128,6 +2128,15 @@ impl Game<'_> { m.swing(); } } + // The player's own instances: its maximum health (the hearts the + // HUD draws and the health it may hold), reach, speed and so on. + // Then the received health again, which the old maximum clamped. + C::UpdateAttributes(p) if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) => { + if let Some(pl) = self.player.as_mut() { + horizon_client::lan::attributes::apply(&mut pl.attributes, &p.values); + } + self.apply_remote_health(); + } C::UpdateMobEffect(p) => self.remote_effect(&p), C::RemoveMobEffect(p) => { if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) diff --git a/crates/horizon-client/src/lan/attributes.rs b/crates/horizon-client/src/lan/attributes.rs index bc208b6f9..eef565409 100644 --- a/crates/horizon-client/src/lan/attributes.rs +++ b/crates/horizon-client/src/lan/attributes.rs @@ -5,7 +5,7 @@ //! changed since (`getAttributesToSync`), to the trackers and the player itself. use horizon_protocol::packets::play::{AttributeModifier, AttributeSnapshot}; use horizon_world::attributes::{ - Instance, Operation, + Instance, Modifier, Operation, entity::{AttributeId, EntityAttributes}, live::LiveAttributes, }; @@ -70,6 +70,48 @@ pub fn take_dirty i32>(map: &mut LiveAttributes) -> Vec i32>(map: &mut LiveAttributes, values: &[AttributeSnapshot]) { + for s in values { + let Some(key) = map + .keys() + .iter() + .find(|k| k.attribute().registry_id() == s.attribute) + .cloned() + else { + continue; + }; + let Ok(Some(handle)) = map.get_instance(Some(key)) else { + continue; + }; + let modifiers: Vec<_> = s + .modifiers + .iter() + .filter_map(|m| Modifier::new(&m.id, m.amount, operation(m.operation)).ok()) + .collect(); + let _ = map.edit(&handle, |instance, observer| { + instance.set_base_value(s.base, observer)?; + instance.remove_all(observer)?; + for m in modifiers { + instance.add_transient(m, observer)?; + } + Ok(()) + }); + } +} + +/// `AttributeModifier.Operation.BY_ID`. +fn operation(id: i32) -> Operation { + match id { + 1 => Operation::AddMultipliedBase, + 2 => Operation::AddMultipliedTotal, + _ => Operation::AddValue, + } +} + /// The client-syncable instances of a generic attribute map. pub fn generic_syncable(map: &EntityAttributes) -> impl Iterator + '_ { let catalog = map.catalog(); diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index fd6e09ce1..fbb7e4e9c 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -213,7 +213,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] class Game: @@ -2711,6 +2711,46 @@ def check_sparks(host, guest, out): return result +def hearts(game): + """The player's maximum and current health as its own client holds them.""" + p = game('status')['player'] + return p.get('max_health'), round(p['health'], 1) + + +def check_hud(host, guest, out): + result = {} + for label, player in (('host', host), ('guest', guest)): + player('command', command='gamemode survival') + try: + for maximum in (40, 10): + player('command', command=f'attribute @s minecraft:max_health base set {maximum}') + player.wait(10) + player('command', command='effect give @s minecraft:instant_health 1 10') + seen = None + for _ in range(15): + player.wait(2) + seen = hearts(player) + if seen == (maximum, maximum): + break + result[f'{label} {maximum}'] = seen + player.shot(out, f'hearts-{label}-{maximum}') + finally: + player('command', command='attribute @s minecraft:max_health base reset') + player('command', command='effect give @s minecraft:instant_health 1 10') + # BossBarCommands' new bar starts visible (ServerBossEvent's constructor). + host('command', command='bossbar add lan_e2e:bar "LAN bar"') + try: + host('command', command='bossbar get lan_e2e:bar visible') + host.wait(5) + result['bar'] = [line for line in host.raw('messages', 5)['chat'] if 'lan_e2e:bar' in line or 'LAN bar' in line] + finally: + host('command', command='bossbar remove lan_e2e:bar') + wrong = {k: v for k, v in result.items() if k != 'bar' and v != (int(k.split()[1]),) * 2} + assert not wrong, f'hearts: {wrong}\n{result}' + assert any('currently visible' in line for line in result['bar']), f'bar: {result["bar"]}' + return result + + def check_blast(host, guest, out): guest('command', command='gamemode survival') guest('command', command='clear @s') @@ -4046,7 +4086,8 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'looks': check_looks, 'leads': check_leads, 'thrown': check_thrown, - 'sparks': check_sparks} + 'sparks': check_sparks, + 'hud': check_hud} def run(ctl, out, resources, checks): From 4aa1f8e14ab8957fdb1608d0eeffb3ca1db88e5e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 08:43:49 +0200 Subject: [PATCH 012/408] World border on a server's clients: its state, its walls, its damage The server told joining players of a default border and never of a change, so on single player's server thread and for LAN guests the wall neither showed nor stopped anyone. Players now get the real border on entering a level and each change as BorderChangeListener sends it. The player's movement collides with the border's walls (CollisionGetter.borderCollision) instead of being clamped after moving, which a sprint-jump got past. A guest (and single player's own player on its server thread) outside the border takes its damage on the server, as the host's player did. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/examples/lan_flat.rs | 1 + .../examples/scene_collision_probe.rs | 1 + crates/horizon-client/src/collisions.rs | 15 +- .../src/game/commands/terrain_cmds.rs | 38 +++-- crates/horizon-client/src/game/control.rs | 2 + crates/horizon-client/src/game/lan.rs | 6 + crates/horizon-client/src/game/lan_actions.rs | 4 +- crates/horizon-client/src/game/remote.rs | 1 + .../horizon-client/src/game/server_travel.rs | 1 + crates/horizon-client/src/lan/border.rs | 130 ++++++++++++++++++ crates/horizon-client/src/lan/hub.rs | 14 +- crates/horizon-client/src/lan/mod.rs | 1 + crates/horizon-client/src/motion.rs | 6 + crates/horizon-client/src/worldborder.rs | 4 + crates/horizon-client/tests/lan_bot.rs | 1 + tools/lan_e2e.py | 76 +++++++++- 16 files changed, 271 insertions(+), 30 deletions(-) create mode 100644 crates/horizon-client/src/lan/border.rs diff --git a/crates/horizon-client/examples/lan_flat.rs b/crates/horizon-client/examples/lan_flat.rs index f3dfea6b1..139528612 100644 --- a/crates/horizon-client/examples/lan_flat.rs +++ b/crates/horizon-client/examples/lan_flat.rs @@ -121,6 +121,7 @@ fn main() -> Result<(), Box> { tick_frozen: false, tick_steps: (0, 0), collision: None, + border: &horizon_client::worldborder::WorldBorder::default(), }; for event in hub.tick(&mut ctx) { match event { diff --git a/crates/horizon-client/examples/scene_collision_probe.rs b/crates/horizon-client/examples/scene_collision_probe.rs index ec20eee74..2dae2204c 100644 --- a/crates/horizon-client/examples/scene_collision_probe.rs +++ b/crates/horizon-client/examples/scene_collision_probe.rs @@ -78,6 +78,7 @@ fn main() -> Result<()> { let mut selected = collisions::EntityCollisions { blocks: scene, entities: &entities, + border: None, }; let movement = world_movement::resolve_world_movement( &mut selected, diff --git a/crates/horizon-client/src/collisions.rs b/crates/horizon-client/src/collisions.rs index 67f5d6027..cfca854dc 100644 --- a/crates/horizon-client/src/collisions.rs +++ b/crates/horizon-client/src/collisions.rs @@ -3,7 +3,7 @@ //! Entity-dependent rules use the defaults for players and the supported mobs. use crate::{Result, world::World}; use horizon_core::{ - geometry::{Aabb, Vec3, VoxelShape}, + geometry::{Aabb, Vec3, VoxelShape, border::BorderGeometry}, position::{BlockPos, ChunkPos}, }; use horizon_world::{ @@ -64,6 +64,9 @@ pub struct SceneCollisions<'w, 'r> { pub struct EntityCollisions<'a, W> { pub blocks: W, pub entities: &'a [Aabb], + /// The world border and the moving entity's x and z + /// (`CollisionGetter.borderCollision`); None: the blocks' answer. + pub border: Option<(&'a BorderGeometry, [f64; 2])>, } impl BlockCollisionWorld for EntityCollisions<'_, W> { type Error = W::Error; @@ -114,12 +117,20 @@ impl> EntityMovementWorld for EntityCo } Ok(shapes) } + /// `WorldBorder.isInsideCloseToBorder`: an entity inside the border and + /// near it collides with its walls. fn movement_border( &mut self, entity: EntityIdentity, bounds: Aabb, ) -> io::Result> { - self.blocks.movement_border(entity, bounds) + let Some((border, [x, z])) = self.border else { + return self.blocks.movement_border(entity, bounds); + }; + if !border.is_inside_close_to_border(x, z, bounds) { + return Ok(None); + } + border.collision_shape().map(Some).map_err(io::Error::other) } } impl SceneCollisions<'_, '_> { diff --git a/crates/horizon-client/src/game/commands/terrain_cmds.rs b/crates/horizon-client/src/game/commands/terrain_cmds.rs index 46df0ce7d..df52f2251 100644 --- a/crates/horizon-client/src/game/commands/terrain_cmds.rs +++ b/crates/horizon-client/src/game/commands/terrain_cmds.rs @@ -248,8 +248,32 @@ impl Game<'_> { /// Every tick: the size change, the wall the player cannot pass and /// damage outside the border. + /// `BorderChangeListener.DelegateBorderChangeListener`'s packets: what + /// changed on the border since the guests were last told of it. + pub(in crate::game) fn lan_sync_border(&mut self, host: &mut crate::game::lan::LanHost) { + let now = horizon_client::lan::border::Sent::of(&self.border); + if let Some(sent) = host.border_sent.replace(now) { + for packet in sent.changes(&self.border) { + host.hub.broadcast(&packet); + } + } + } pub(in crate::game) fn tick_worldborder(&mut self) { self.border.tick(); + self.player_border(); + self.border_damage(); + } + /// The player's movement collides with the border as it is now + /// (`CollisionGetter.borderCollision`): from inside, its walls stop it. + pub(in crate::game) fn player_border(&mut self) { + if let Some(p) = self.player.as_mut() { + p.border = Some(self.border.geometry().clone()); + } + } + /// `LivingEntity.baseTick`: a player outside the border, further than + /// its safe zone, is hurt by the blocks beyond it. The game's player, or + /// a guest's in their turn (`as_guest`). + pub(in crate::game) fn border_damage(&mut self) { let Some((px, pz, half)) = self.player.as_ref().map(|p| { ( p.position.x, @@ -269,20 +293,6 @@ impl Game<'_> { let amount = (-dist * self.border.damage_per_block).floor().max(1.0) as f32; self.hurt_player_by("minecraft:outside_border", amount); } - // From inside the border the wall stops movement. - if self.border.distance(px, pz) >= 0.0 { - let [x, z] = self.border.clamp(px, pz, half); - if let Some(p) = self.player.as_mut() { - if x != px { - p.velocity.x = 0.0; - } - if z != pz { - p.velocity.z = 0.0; - } - p.position.x = x; - p.position.z = z; - } - } } pub(super) fn cmd_worldborder(&mut self, id: &str, ctx: &Context) -> R { let float2 = |v: f64| format!("{v:.2}"); diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 261f207d4..f7e4c6b36 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -979,6 +979,8 @@ impl Game<'_> { status["projectiles"] = json!(self.projectiles_status()); // The particles made so far, by type. status["particles"] = json!(self.particles.made()); + // The world border this side knows of. + status["border"] = json!({ "center": self.border.center(), "size": self.border.size() }); // The scoreboard sidebar the HUD shows. status["sidebar"] = self.sidebar_status(); status diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 9bfad8581..e7d2cb95e 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -66,6 +66,8 @@ pub(super) struct LanHost { /// whose respawn replaces their waypoint. pub waypoints: std::collections::HashMap, pub waypoint_dead: std::collections::HashSet, + /// The world border as the guests were last told of it (lan/border.rs). + pub border_sent: Option, /// Guests' commands waiting for the hub to be back in `self.lan`, where /// a command can reach every player (game/lan_actions.rs). pub commands: Vec, @@ -561,6 +563,7 @@ impl Game<'_> { owner: None, waypoints: Default::default(), waypoint_dead: Default::default(), + border_sent: None, commands: Vec::new(), states: Default::default(), }); @@ -891,6 +894,7 @@ impl Game<'_> { tick_frozen: self.clock.frozen(), tick_steps: self.clock.step_state(), collision: Some(self.collision), + border: &self.border, }; host.hub.movement_checks = ( self.ui.rules.bool("player_movement_check"), @@ -998,6 +1002,7 @@ impl Game<'_> { self.lan_update_models(&mut host); self.lan_update_waypoints(&mut host, state.as_ref()); self.lan_sync_scoreboard(&mut host); + self.lan_sync_border(&mut host); drop(holding); lan::flush_all(host.hub.guests.iter().map(|g| &g.sender)); self.lan = Some(host); @@ -1074,6 +1079,7 @@ impl Game<'_> { tick_frozen: self.clock.frozen(), tick_steps: self.clock.step_state(), collision: Some(self.collision), + border: &self.border, }; host.hub.place_new_player(conn, &mut ctx); if elsewhere && let Err(e) = self.enter_level(Some(host), back) { diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 0527e30a0..6e3e74cd5 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1575,6 +1575,7 @@ impl Game<'_> { tick_frozen: self.clock.frozen(), tick_steps: self.clock.step_state(), collision: Some(self.collision), + border: &self.border, }; host.hub.respawn(i, spawn, &ctx); if let Some(config) = elsewhere { @@ -1912,7 +1913,8 @@ impl Game<'_> { for d in travelled { game.movement_stats(Vec3::new(d[0], d[1], d[2])); } - // LivingEntity.baseTick ends with tickEffects. + // LivingEntity.baseTick: outside the world border, then tickEffects. + game.border_damage(); game.tick_mob_effects(); let Some(player) = game.player.as_mut() else { return Vec::new(); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 46d8c6a65..f47dec497 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3043,6 +3043,7 @@ impl Game<'_> { self.remote_handle_input(); // ClientLevel.tick: the border's size change. self.border.tick(); + self.player_border(); self.tick_remote_entities(running); // ClientLevel.tickBlockEntities: chest lids, shulker boxes, bells. self.tick_block_entity_anims(); diff --git a/crates/horizon-client/src/game/server_travel.rs b/crates/horizon-client/src/game/server_travel.rs index 1e94ec995..02b94c0f6 100644 --- a/crates/horizon-client/src/game/server_travel.rs +++ b/crates/horizon-client/src/game/server_travel.rs @@ -455,6 +455,7 @@ impl Game<'_> { tick_frozen: self.clock.frozen(), tick_steps: self.clock.step_state(), collision: Some(self.collision), + border: &self.border, } } } diff --git a/crates/horizon-client/src/lan/border.rs b/crates/horizon-client/src/lan/border.rs new file mode 100644 index 000000000..b4e3ffc63 --- /dev/null +++ b/crates/horizon-client/src/lan/border.rs @@ -0,0 +1,130 @@ +//! The world border a server's players see: all of it when they enter a +//! level (`PlayerList.sendLevelInfo`), then each change as +//! `BorderChangeListener` broadcasts it: a new centre, a new size, a size +//! change in progress, a new warning time or distance. +use crate::worldborder::WorldBorder; +use horizon_protocol::packets::play::{self, Clientbound as C}; + +/// `ClientboundInitializeBorderPacket`. +pub fn initialize(b: &WorldBorder) -> play::InitializeBorder { + let [center_x, center_z] = b.center(); + play::InitializeBorder { + center_x, + center_z, + old_size: b.size(), + new_size: b.target_size(), + lerp_time: b.remaining_ticks(), + absolute_max_size: b.absolute_max_size(), + warning_blocks: b.warning_distance, + warning_time: b.warning_time, + } +} + +/// The border as the players were last told of it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Sent { + center: [f64; 2], + size: f64, + target: f64, + remaining: i64, + warning_distance: i32, + warning_time: i32, +} + +impl Sent { + pub fn of(b: &WorldBorder) -> Self { + Self { + center: b.center(), + size: b.size(), + target: b.target_size(), + remaining: b.remaining_ticks(), + warning_distance: b.warning_distance, + warning_time: b.warning_time, + } + } + + /// The packets that tell the players what changed since `self`, other + /// than a size change going on (which each client runs itself). + pub fn changes(&self, b: &WorldBorder) -> Vec { + let now = Self::of(b); + let mut out = Vec::new(); + if now.center != self.center { + out.push(C::SetBorderCenter(play::SetBorderCenter { + x: now.center[0], + z: now.center[1], + })); + } + // A change going on counts down a tick at a time (or not at all + // while the game is frozen), towards the same size. + let going_on = self.remaining > 0 + && now.target == self.target + && (now.remaining == self.remaining || now.remaining == self.remaining - 1); + if now.remaining > 0 { + if !going_on { + out.push(C::SetBorderLerpSize(play::SetBorderLerpSize { + old_size: now.size, + new_size: now.target, + lerp_time: now.remaining, + })); + } + } else if now.size != self.size && !(self.remaining > 0 && now.size == self.target) { + out.push(C::SetBorderSize(play::SetBorderSize { size: now.size })); + } + if now.warning_time != self.warning_time { + out.push(C::SetBorderWarningDelay(play::SetBorderWarningDelay { + delay: now.warning_time, + })); + } + if now.warning_distance != self.warning_distance { + out.push(C::SetBorderWarningDistance( + play::SetBorderWarningDistance { + blocks: now.warning_distance, + }, + )); + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn kinds(packets: &[C]) -> Vec<&'static str> { + packets + .iter() + .map(|p| match p { + C::SetBorderCenter(_) => "center", + C::SetBorderSize(_) => "size", + C::SetBorderLerpSize(_) => "lerp", + C::SetBorderWarningDelay(_) => "delay", + C::SetBorderWarningDistance(_) => "distance", + _ => "other", + }) + .collect() + } + + #[test] + fn each_change_is_sent_once() { + let mut b = WorldBorder::default(); + let mut sent = Sent::of(&b); + assert!(sent.changes(&b).is_empty()); + b.set_center([4.0, -2.0]); + b.set_size(10.0); + b.warning_time = 30; + assert_eq!(kinds(&sent.changes(&b)), ["center", "size", "delay"]); + sent = Sent::of(&b); + // A change over 3 ticks: sent once, then each client runs it. + b.lerp_to(20.0, 3); + assert_eq!(kinds(&sent.changes(&b)), ["lerp"]); + for _ in 0..4 { + sent = Sent::of(&b); + b.tick(); + assert!(sent.changes(&b).is_empty(), "{:?}", sent.changes(&b)); + } + assert_eq!(b.size(), 20.0); + b.warning_distance = 1; + assert_eq!(kinds(&Sent::of(&b).changes(&b)), [] as [&str; 0]); + assert_eq!(kinds(&sent.changes(&b)), ["distance"]); + } +} diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index c8f2e980d..48e21b1bc 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -111,6 +111,8 @@ pub struct TickCtx<'a> { /// Block collisions, for ServerGamePacketListenerImpl's moved-wrongly /// check (none: moves are not checked against blocks). pub collision: Option<&'a BlockCollisionRegistry<'a>>, + /// The level's world border (PlayerList.sendLevelInfo sends it). + pub border: &'a crate::worldborder::WorldBorder, } /// What the gameplay code has to do for a guest. @@ -898,17 +900,7 @@ impl Hub { fn send_level_info(&mut self, i: usize, ctx: &TickCtx) { let spawn = ctx.spawn; let g = &self.guests[i]; - g.send(&C::InitializeBorder(play::InitializeBorder { - center_x: 0.0, - center_z: 0.0, - old_size: 59_999_968.0, - new_size: 59_999_968.0, - lerp_time: 0, - absolute_max_size: 29_999_984, - warning_blocks: 5, - // WorldBorder.DEFAULT_WARNING_TIME, in ticks. - warning_time: 300, - })); + g.send(&C::InitializeBorder(super::border::initialize(ctx.border))); g.send(&self.time_packet(ctx.world, ctx.clock_rate)); g.send(&self.default_spawn(spawn)); let w = &ctx.world.weather; diff --git a/crates/horizon-client/src/lan/mod.rs b/crates/horizon-client/src/lan/mod.rs index d342c7fe5..d6dd78fc5 100644 --- a/crates/horizon-client/src/lan/mod.rs +++ b/crates/horizon-client/src/lan/mod.rs @@ -6,6 +6,7 @@ //! world that is not open to the network pays nothing. mod advancements; pub mod attributes; +pub mod border; pub mod chunks; mod command_order; pub mod command_suggestions; diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 339cb86b8..c7164b963 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -307,6 +307,9 @@ pub struct PlayerMotion { pub hurt_log: Vec, /// The last melee attacks made on mobs, newest last. pub attack_log: Vec, + /// The level's world border, whose walls stop the player's movement + /// from inside (the game keeps it current; None: no border). + pub border: Option, } fn attribute_error(error: impl std::fmt::Debug) -> io::Error { io::Error::other(format!("movement attribute: {error:?}")) @@ -460,6 +463,7 @@ impl PlayerMotion { powder_snow_entered: Vec::new(), hurt_log: Vec::new(), attack_log: Vec::new(), + border: None, }) } /// `Entity.getTicksRequiredToFreeze`. @@ -677,9 +681,11 @@ impl MotionWorld<'_, '_, '_> { fn movement_collisions( &self, ) -> crate::collisions::EntityCollisions<'_, SceneCollisions<'_, '_>> { + let at = [self.player.position.x, self.player.position.z]; crate::collisions::EntityCollisions { blocks: self.collisions(), entities: self.entities, + border: self.player.border.as_ref().map(|b| (b, at)), } } /// `Level.noCollision(player, bounds)`: blocks and the host's entity boxes. diff --git a/crates/horizon-client/src/worldborder.rs b/crates/horizon-client/src/worldborder.rs index 3ed4ea152..be65d17e5 100644 --- a/crates/horizon-client/src/worldborder.rs +++ b/crates/horizon-client/src/worldborder.rs @@ -81,6 +81,10 @@ impl PartialEq for WorldBorder { } } impl WorldBorder { + /// Its extent, for collisions. + pub fn geometry(&self) -> &BorderGeometry { + &self.geometry + } pub fn center(&self) -> [f64; 2] { self.geometry.center() } diff --git a/crates/horizon-client/tests/lan_bot.rs b/crates/horizon-client/tests/lan_bot.rs index fdafcbb68..6dd1b8258 100644 --- a/crates/horizon-client/tests/lan_bot.rs +++ b/crates/horizon-client/tests/lan_bot.rs @@ -200,6 +200,7 @@ impl Server { tick_frozen: false, tick_steps: (0, 0), collision: None, + border: &horizon_client::worldborder::WorldBorder::default(), }; let events = self.hub.tick(&mut ctx); for event in events { diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 72beb2acd..881443c3f 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -213,7 +213,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'sidebar', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'sidebar', 'border', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] class Game: @@ -2794,6 +2794,77 @@ def check_sidebar(host, guest, out): return result +def check_border(host, guest, out): + spots = apart(host, guest) + result = {} + try: + for label, player, other in (('host', host, guest), ('guest', guest, host)): + x, y, z = spots[label] + # A whole-block centre: the wall's collision box is the border's, rounded out to blocks. + cx, cz = float(x), float(z) + # The other player keeps out of harm outside the border meanwhile. + other('command', command='gamemode creative') + host('command', command=f'fill {x - 3} {y - 1} {z} {x + 4} {y - 1} {z + 10} minecraft:stone') + host('command', command=f'fill {x - 3} {y} {z} {x + 4} {y + 3} {z + 10} minecraft:air') + # A border 10 wide around the player, its wall 5 blocks ahead: both sides know it. + host('command', command=f'worldborder center {cx} {cz}') + host('command', command='worldborder set 10') + seen = None + for _ in range(10): + player.wait(2) + seen = [g('status').get('border') for g in (player, other)] + if all(b and b['size'] == 10 and b['center'] == [cx, cz] for b in seen): + break + result[f'{label} border'] = seen + # Sprint-jumping into the wall: it stops the player at the border. + player('command', command=f'tp @s {cx} {y} {cz} 0 0') + player.wait(10) + player.raw('look-at', f'{cx:.2f}', f'{y + 1.6:.2f}', f'{cz + 20:.2f}') + for k in ('w', 'ctrl', 'space'): + player.raw('key', k, 'down') + player.wait(40) + for k in ('space', 'ctrl', 'w'): + player.raw('key', k, 'up') + player.wait(10) + result[f'{label} reached'] = round(pos_of(player)[2] - cz, 2) + player.shot(out, f'border-{label}') + # Two blocks outside, with no safe zone: the border hurts. + host('command', command='worldborder damage buffer 0') + host('command', command='worldborder damage amount 1') + player('command', command='effect give @s minecraft:instant_health 1 5') + player.wait(20) + player('command', command=f'tp @s {cx} {y} {cz + 7}') + player.wait(5) + before = player('status')['player']['health'] + player.wait(40) + result[f'{label} hurt'] = [before, player('status')['player']['health']] + player('command', command=f'tp @s {cx} {y} {cz}') + player('command', command='effect give @s minecraft:instant_health 1 5') + host('command', command='worldborder damage amount 0.2') + host('command', command='worldborder damage buffer 5') + other('command', command='gamemode survival') + finally: + guest('command', command='gamemode survival') + host('command', command='gamemode survival') + host('command', command='worldborder damage amount 0.2') + host('command', command='worldborder damage buffer 5') + host('command', command='worldborder center 0 0') + host('command', command='worldborder set 59999968') + wrong = {} + for label in ('host', 'guest'): + x, y, z = spots[label] + known = result[f'{label} border'] + if not all(b and b['size'] == 10 and b['center'] == [x, z] for b in known): + wrong[f'{label} border'] = known + if not 4.0 < result[f'{label} reached'] <= 4.71: + wrong[f'{label} reached'] = result[f'{label} reached'] + before, after = result[f'{label} hurt'] + if not after < before: + wrong[f'{label} hurt'] = result[f'{label} hurt'] + assert not wrong, f'border: {wrong}\n{result}' + return result + + def check_blast(host, guest, out): guest('command', command='gamemode survival') guest('command', command='clear @s') @@ -4131,7 +4202,8 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'thrown': check_thrown, 'sparks': check_sparks, 'hud': check_hud, - 'sidebar': check_sidebar} + 'sidebar': check_sidebar, + 'border': check_border} def run(ctl, out, resources, checks): From c5fe5d4bcf3331164d7a7ade1f5ac7cff2481aa6 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 07:55:49 +0200 Subject: [PATCH 013/408] Thrown potions and eyes of ender fly on a server's clients A splash or lingering potion, an experience bottle or an eye of ender a player threw was never an entity a server tracked: on single player's server thread, for LAN guests and on a dedicated server the item was used up and nothing flew. The server now numbers them like its other projectiles and tracks them as vanilla's entities: splash_potion, lingering_potion and experience_bottle with ThrowableItemProjectile.DATA_ITEM_STACK (the potion, for its colour), and eye_of_ender. A client draws them where the server puts them and drops them when the server removes them. lan_e2e's new `thrown` check: the host and the guest each throw a splash potion and an eye of ender, and both sides see them fly. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/end.rs | 51 ++++++++++++ .../horizon-client/src/game/lan_entities.rs | 22 ++++++ crates/horizon-client/src/game/potions.rs | 78 +++++++++++++++++-- .../src/game/remote_projectiles.rs | 35 +++++++++ tools/lan_e2e.py | 36 ++++++++- 5 files changed, 212 insertions(+), 10 deletions(-) diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index d62c8ccc2..599158e3e 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -97,8 +97,58 @@ impl EndState { } } +impl EndState { + /// The eyes' entity ids, for a server to number them. + pub(super) fn eye_ids(&mut self) -> impl Iterator { + self.eyes.iter_mut().map(|e| &mut e.id) + } + /// The numbered eyes as a server's clients track them: (id, position, motion). + pub(super) fn eyes_tracked(&self) -> impl Iterator { + self.eyes + .iter() + .filter(|e| e.id != 0) + .map(|e| (e.id, e.position.to_array(), e.velocity.to_array())) + } + /// `handleAddEntity` for an eye of ender on a server's client: it flies + /// where the server says. + pub(super) fn add_remote_eye(&mut self, id: u32, at: [f64; 3], velocity: [f64; 3]) { + self.eyes.retain(|e| e.id != id); + let at = glam::DVec3::from_array(at); + self.eyes.push(EyeOfEnder { + id, + position: at, + previous: at, + velocity: glam::DVec3::from_array(velocity), + target: at, + life: 0, + survive: false, + }); + } + /// One tick of a server's client: `step` moves each toward where the + /// server put it. + pub(super) fn step_remote_eyes(&mut self, mut step: impl FnMut(u32, [f64; 3]) -> [f64; 3]) { + for e in &mut self.eyes { + e.previous = e.position; + e.life += 1; + e.position = glam::DVec3::from_array(step(e.id, e.position.to_array())); + } + } + pub(super) fn remove_remote_eye(&mut self, id: u32) { + self.eyes.retain(|e| e.id != id); + } + pub(super) fn clear_remote_eyes(&mut self) { + self.eyes.clear(); + } + /// Where each eye is, for `status`. + pub(super) fn eye_positions(&self) -> impl Iterator { + self.eyes.iter().map(|e| (e.id, e.position.to_array())) + } +} + /// The EyeOfEnder entity. struct EyeOfEnder { + /// Its entity id once a server's clients track it (0 until then). + id: u32, position: glam::DVec3, previous: glam::DVec3, velocity: glam::DVec3, @@ -1023,6 +1073,7 @@ impl Game<'_> { }; let survive = self.world.random.next_int_bound(5).unwrap_or(0) > 0; self.end.eyes.push(EyeOfEnder { + id: 0, position: start, previous: start, velocity: glam::DVec3::ZERO, diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index f3098408c..db0c3e8b2 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -277,6 +277,8 @@ impl Game<'_> { self.rockets.iter_mut().for_each(|r| give(&mut r.id)); self.crystals.iter_mut().for_each(|c| give(&mut c.id)); self.bolts.iter_mut().for_each(|b| give(&mut b.id)); + self.potions.thrown_ids().for_each(&mut give); + self.end.eye_ids().for_each(&mut give); } /// Primed TNT, falling blocks, projectiles, tridents, firework rockets and @@ -359,6 +361,26 @@ impl Game<'_> { } out.push(e); } + // Thrown potions and bottles: ThrowableItemProjectile.DATA_ITEM_STACK + // (the potion's colour), which a plain bottle's type already has. + for (id, kind, stack, position, velocity) in self.potions.thrown_tracked() { + let mut e = state(id, kind, at(position), 0.0, false); + e.velocity = at(velocity); + if stack.extra.is_some() || stack.count != 1 { + e.meta.push(( + 8, + serializer::ITEM_STACK, + Value::Item(hub.stack(&Some(stack.clone()))), + )); + } + out.push(e); + } + // EyeOfEnder: its item is the plain eye (DATA_ITEM_STACK's default). + for (id, position, velocity) in self.end.eyes_tracked() { + let mut e = state(id, "minecraft:eye_of_ender", position, 0.0, false); + e.velocity = velocity; + out.push(e); + } for t in self.tridents.iter().filter(|t| t.id != 0) { let mut e = state(t.id, "minecraft:trident", at(t.position), t.yaw, false); e.pitch = t.pitch; diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 72c8fe885..1664ae38e 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -18,6 +18,8 @@ use horizon_core::{geometry::Vec3, random::RandomSource}; /// A thrown splash or lingering potion in flight. #[derive(Clone, Debug)] pub(super) struct ThrownPotion { + /// Its entity id once a server's clients track it (0 until then). + id: u32, stack: ItemStack, /// The position before the last tick, for drawing between ticks. previous: Vec3, @@ -47,6 +49,7 @@ impl Game<'_> { /// player's throws and dispensers both end up here). pub(super) fn launch_thrown(&mut self, stack: ItemStack, position: Vec3, velocity: Vec3) { self.potions.thrown.push(ThrownPotion { + id: 0, stack, previous: position, position, @@ -90,19 +93,78 @@ impl PotionState { pub(super) fn thrown_entities(&self) -> Vec<(&'static str, Vec3, Vec3)> { self.thrown .iter() - .map(|t| { - let kind = match &*t.stack.item { - "minecraft:lingering_potion" => "minecraft:lingering_potion", - "minecraft:experience_bottle" => "minecraft:experience_bottle", - _ => "minecraft:splash_potion", - }; - (kind, t.position, t.velocity) - }) + .map(|t| (thrown_kind(&t.stack), t.position, t.velocity)) .collect() } pub(super) fn clear_thrown(&mut self) { self.thrown.clear(); } + /// Their entity ids, for a server to number them. + pub(super) fn thrown_ids(&mut self) -> impl Iterator { + self.thrown.iter_mut().map(|t| &mut t.id) + } + /// The numbered ones as a server's clients track them: (id, entity + /// type, item, position, motion). + pub(super) fn thrown_tracked( + &self, + ) -> impl Iterator { + self.thrown.iter().filter(|t| t.id != 0).map(|t| { + ( + t.id, + thrown_kind(&t.stack), + &t.stack, + t.position, + t.velocity, + ) + }) + } + /// `handleAddEntity` for a thrown potion or bottle on a server's client: + /// drawn where the server says (its item comes in its entity data). + pub(super) fn add_remote_thrown(&mut self, id: u32, kind: &str, at: Vec3, velocity: Vec3) { + self.thrown.retain(|t| t.id != id); + let item = match kind { + "minecraft:lingering_potion" | "minecraft:experience_bottle" => kind, + _ => "minecraft:splash_potion", + }; + self.thrown.push(ThrownPotion { + id, + stack: ItemStack::new(item, 1), + previous: at, + position: at, + velocity, + age: 0, + }); + } + /// ThrowableItemProjectile.DATA_ITEM_STACK: the potion it shows. + pub(super) fn remote_thrown_item(&mut self, id: u32, stack: ItemStack) { + if let Some(t) = self.thrown.iter_mut().find(|t| t.id == id) { + t.stack = stack; + } + } + /// One tick of a server's client: `step` moves each toward where the + /// server put it. + pub(super) fn step_remote_thrown(&mut self, mut step: impl FnMut(u32, Vec3) -> Vec3) { + for t in &mut self.thrown { + t.previous = t.position; + t.age += 1; + t.position = step(t.id, t.position); + } + } + pub(super) fn remove_remote_thrown(&mut self, id: u32) { + self.thrown.retain(|t| t.id != id); + } + pub(super) fn has_thrown(&self, id: u32) -> bool { + self.thrown.iter().any(|t| t.id == id) + } +} + +/// The entity type of a thrown potion or bottle. +fn thrown_kind(stack: &ItemStack) -> &'static str { + match &*stack.item { + "minecraft:lingering_potion" => "minecraft:lingering_potion", + "minecraft:experience_bottle" => "minecraft:experience_bottle", + _ => "minecraft:splash_potion", + } } impl Game<'_> { diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs index c008611f6..82d0a11e2 100644 --- a/crates/horizon-client/src/game/remote_projectiles.rs +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -79,6 +79,15 @@ impl Game<'_> { self.rockets .push(super::fireworks::Rocket::remote(id, at, velocity)); } + "minecraft:splash_potion" + | "minecraft:lingering_potion" + | "minecraft:experience_bottle" => { + self.potions.add_remote_thrown(id, kind, at, velocity); + } + "minecraft:eye_of_ender" => { + self.end + .add_remote_eye(id, position, [velocity.x, velocity.y, velocity.z]) + } "minecraft:end_crystal" => self.crystals.push(super::dragon::Crystal { id, position: at, @@ -105,6 +114,17 @@ impl Game<'_> { /// `handleSetEntityData` for these types: what changes how they look. pub(super) fn remote_projectile_data(&mut self, id: i32, values: &[(u8, i32, Value)]) { let id = id as u32; + if self.potions.has_thrown(id) { + // ThrowableItemProjectile.DATA_ITEM_STACK: the potion it is. + for (index, _, value) in values { + if let (8, Value::Item(stack)) = (index, value) + && let Some(stack) = self.to_stack(stack) + { + self.potions.remote_thrown_item(id, stack); + } + } + return; + } for (index, _, value) in values { if let Some(t) = self.tnts.iter_mut().find(|t| t.id == id) { // PrimedTnt.DATA_FUSE_ID. @@ -184,6 +204,11 @@ impl Game<'_> { c.time += 1; c.position = step(c.id, c.position); } + self.potions.step_remote_thrown(&mut step); + self.end.step_remote_eyes(|id, at| { + let at = step(id, Vec3::new(at[0], at[1], at[2])); + [at.x, at.y, at.z] + }); } pub(super) fn remove_remote_projectile(&mut self, id: u32) { @@ -193,6 +218,8 @@ impl Game<'_> { self.tridents.retain(|t| t.id != id); self.rockets.retain(|r| r.id != id); self.crystals.retain(|c| c.id != id); + self.potions.remove_remote_thrown(id); + self.end.remove_remote_eye(id); } /// Every one a server sent (a new connection, level or dimension). @@ -203,6 +230,8 @@ impl Game<'_> { self.tridents.clear(); self.rockets.clear(); self.crystals.clear(); + self.potions.clear_thrown(); + self.end.clear_remote_eyes(); } /// Their kind and place, for `status`. @@ -225,6 +254,12 @@ impl Game<'_> { for p in &self.creatures.projectiles { out.push(json!({"id": p.id, "kind": format!("{:?}", p.kind).split([' ', '{']).next().unwrap_or(""), "position": at(p.position)})); } + for (kind, p, _) in self.potions.thrown_entities() { + out.push(json!({"kind": kind, "position": at(p)})); + } + for (id, p) in self.end.eye_positions() { + out.push(json!({"id": id, "kind": "minecraft:eye_of_ender", "position": p})); + } out } } diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index b3dae9ef4..c4d8084ba 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -107,6 +107,8 @@ address. The script then checks, from both sides, what a guest's game used to ge guest as the host has them (kind, place, rotation, what they hold or wear, the variant). - projectiles: primed TNT (one falling), an end crystal and an arrow that lands reach the guest where the host has them; a falling block lands on both sides. +- thrown: a splash potion and an eye of ender the host and the guest each throw fly on both + sides (#1363, #1391); - fireball: a fire charge a dispenser shoots onto stone lights a fire both sides see, and the fire goes out on its own within a minute (it ticks: FireBlock.tick on a floor that doesn't burn) @@ -208,7 +210,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] class Game: @@ -2612,6 +2614,35 @@ def check_projectiles(host, guest, out): return f'{len(theirs)} identical, fuses (host, guest) {fuses}' +def check_thrown(host, guest, out): + spots = apart(host, guest) + result = {} + for label, player, other in (('host', host, guest), ('guest', guest, host)): + x, y, z = spots[label] + player('command', command='gamemode survival') + for item, kind in (('splash_potion', 'minecraft:splash_potion'), ('ender_eye', 'minecraft:eye_of_ender')): + player('command', command=f'item replace entity @s weapon.mainhand with minecraft:{item}') + player.wait(10) + # Up at 45 degrees, into open sky. + player.raw('look-at', f'{x + 0.5:.2f}', f'{y + 11.6:.2f}', f'{z + 10.5:.2f}') + player.raw('use-item') + seen = {'own': 0, 'other': 0} + for _ in range(10): + player.wait(2) + for side, game in (('own', player), ('other', other)): + if any(p['kind'] == kind for p in game('status')['projectiles']): + seen[side] += 1 + if all(seen.values()): + break + player.shot(out, f'thrown-{label}-{item}') + other.shot(out, f'thrown-{label}-{item}-seen') + player.wait(100) # it lands or drops + result[f'{label} {item}'] = seen + for name, seen in result.items(): + assert all(seen.values()), f'{name}: seen in flight (samples) {result}' + return result + + def check_blast(host, guest, out): guest('command', command='gamemode survival') guest('command', command='clear @s') @@ -3945,7 +3976,8 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'lava': check_lava, 'levels': check_levels, 'drops': check_drops, 'underwater': check_underwater, 'looks': check_looks, - 'leads': check_leads} + 'leads': check_leads, + 'thrown': check_thrown} def run(ctl, out, resources, checks): From 13772b4e5bbc153f2ea896f44543dd75002e7b69 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 08:08:42 +0200 Subject: [PATCH 014/408] Level events on a server's clients: spawner bursts, bone meal sparks, waxing A client of a server (single player on its server thread, a LAN guest, a dedicated server's player) played only three of the level events the server sent (a block broken, the dragon egg's and a consumable's teleport): a spawner's burst, waxing and scraping copper, a composter filling and the rest showed nothing. Every one now goes through the handler the in-frame game uses (LevelEventHandler). Bone meal's level event (1505) played its sound but never its growth particles, in either mode: it now spawns them as BoneMealItem. addGrowthParticles does (spread over a grass block's, nylium's, netherrack's or moss's neighbourhood and water, inside a growing block, below rooted dirt and mangrove leaves). The server also sends it to the player who used the bone meal, as vanilla's levelEvent names no player. Waxing copper with honeycomb and an axe or hoe's transforms (wax off, scrape, strip, till) make their particles and sound on the clicker's own client, as vanilla's client runs Item.useOn; the server sends them to the others only. The transform's preview is shared with the in-frame use. `horizon-ctl status` counts the particles made by type. lan_e2e's new `sparks` check: the host and the guest each use bone meal on wheat, wax copper and take the wax off, and a spawner spawns a zombie; both sides make the particles. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 92 +++++++++++-------- crates/horizon-client/src/game/control.rs | 2 + crates/horizon-client/src/game/lan.rs | 10 +- .../src/game/level_particles.rs | 67 +++++++++++++- crates/horizon-client/src/game/remote.rs | 61 +++++++----- crates/horizon-client/src/particles.rs | 8 ++ tools/lan_e2e.py | 73 ++++++++++++++- 7 files changed, 245 insertions(+), 68 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 27ac5f259..11d94ef48 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2573,6 +2573,17 @@ impl Game<'_> { LevelEvent::LevelEvent { id: 2004, pos, .. } => { self.spawner_burst([pos.x, pos.y, pos.z]) } + // LevelEventHandler 1505: the growth particles, then the sound. + LevelEvent::LevelEvent { + id: 1505, + pos, + data, + } => { + self.growth_particles(pos, data); + let at = [pos.x, pos.y, pos.z].map(|v| f64::from(v) + 0.5); + self.audio + .play("minecraft:item.bone_meal.use", Some(at), 1.0, 1.0); + } LevelEvent::LevelEvent { id: 2015, pos, @@ -2616,7 +2627,6 @@ impl Game<'_> { 1030 => Some(("minecraft:block.anvil.use", 1.0)), 1029 => Some(("minecraft:block.anvil.destroy", 1.0)), 1031 => Some(("minecraft:block.anvil.land", 0.3)), - 1505 => Some(("minecraft:item.bone_meal.use", 1.0)), 1042 => Some(("minecraft:block.grindstone.use", 1.0)), 1044 => Some(("minecraft:block.smithing_table.use", 1.0)), // LevelEvent.SOUND_PAGE_TURN (a lectern's page). @@ -8090,13 +8100,15 @@ impl Game<'_> { } Ok(true) } - /// `BlockTransformer.transformBlock` for a held axe, hoe or shovel. - fn use_block_transformer( - &mut self, + /// What `BlockTransformer.transformBlock` would do with a held axe, hoe + /// or shovel on the block at `pos`, without doing it: the new state, its + /// sound, loot table, the durability it costs and its particle. + pub(super) fn block_transform( + &self, stack: &ItemStack, pos: [i32; 3], face: [i32; 3], - ) -> Result { + ) -> Option<(BlockStateId, String, Option, u32, String)> { use horizon_client::block_transform::Around; struct Column<'w> { world: &'w World, @@ -8116,14 +8128,11 @@ impl Game<'_> { }) } } - let Some(id) = self + let id = self .res .items() .get(&stack.item) - .and_then(|i| i.block_transformer.clone()) - else { - return Ok(false); - }; + .and_then(|i| i.block_transformer.clone())?; // playerHasBlockingItemUseIntent: a shield in the off hand is raised // instead, unless sneaking. let shield = self @@ -8132,7 +8141,7 @@ impl Game<'_> { .and_then(|s| self.res.items().get(&s.item)) .is_some_and(|i| i.blocks_attacks.is_some()); if shield && !self.keys.contains(&KeyCode::ShiftLeft) { - return Ok(false); + return None; } let face_name = match face { [0, -1, 0] => "down", @@ -8143,38 +8152,47 @@ impl Game<'_> { _ => "east", }; let registry = self.pack.assets.registry; - let (state, sound, loot, damage, particle) = { - let around = Column { - world: &self.world, - registry, - pos, - }; - let Some((_, t, state)) = - self.res - .transformers() - .apply(self.res.items(), registry, &id, face_name, &around) - else { - return Ok(false); - }; - ( - state, - t.sound.clone(), - t.loot.clone(), - t.damage, - t.particle.clone(), - ) + let around = Column { + world: &self.world, + registry, + pos, }; - let Ok(new) = registry.resolve(&state) else { - return Ok(false); - }; - self.level_set(pos, new)?; - // BlockTransformer.TransformParticle.send. - match particle.as_str() { + let (_, t, state) = + self.res + .transformers() + .apply(self.res.items(), registry, &id, face_name, &around)?; + let new = registry.resolve(&state).ok()?; + Some(( + new, + t.sound.clone(), + t.loot.clone(), + t.damage, + t.particle.clone(), + )) + } + /// `BlockTransformer.TransformParticle.send`: its level event. + pub(super) fn transform_particle(&mut self, particle: &str, pos: [i32; 3]) { + match particle { "scrape" => self.level_event_at(3005, pos, 0), "wax_on" => self.level_event_at(3003, pos, 0), "wax_off" => self.level_event_at(3004, pos, 0), _ => {} } + } + /// `BlockTransformer.transformBlock` for a held axe, hoe or shovel. + fn use_block_transformer( + &mut self, + stack: &ItemStack, + pos: [i32; 3], + face: [i32; 3], + ) -> Result { + let Some((new, sound, loot, damage, particle)) = self.block_transform(stack, pos, face) + else { + return Ok(false); + }; + self.level_set(pos, new)?; + // BlockTransformer.TransformParticle.send. + self.transform_particle(&particle, pos); if loot.as_deref() == Some("minecraft:till/rooted_dirt") { self.pop_resource( [pos[0] + face[0], pos[1] + face[1], pos[2] + face[2]], diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 9132c7723..5645441f0 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -971,6 +971,8 @@ impl Game<'_> { "flashes": self.lightning_seen[1], "flash": self.flash}); // Primed TNT, falling blocks, projectiles, tridents and end crystals. status["projectiles"] = json!(self.projectiles_status()); + // The particles made so far, by type. + status["particles"] = json!(self.particles.made()); status } } diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 8467b6d3a..72b3b3fc5 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1087,8 +1087,14 @@ impl Game<'_> { } for e in events { if let horizon_world::level::LevelEvent::LevelEvent { id, pos, data } = e { - // The acting guest does not predict the egg's teleport particles. - let except = if *id == 2015 { None } else { self.lan_acting }; + // The acting guest does not predict the egg's teleport + // particles, nor bone meal's growth (BoneMealItem.useOn's + // levelEvent names no player). + let except = if matches!(*id, 2015 | 1505) { + None + } else { + self.lan_acting + }; self.lan_events .push((*id, [pos.x, pos.y, pos.z], *data, except)); } diff --git a/crates/horizon-client/src/game/level_particles.rs b/crates/horizon-client/src/game/level_particles.rs index 47d06254d..d239c69d0 100644 --- a/crates/horizon-client/src/game/level_particles.rs +++ b/crates/horizon-client/src/game/level_particles.rs @@ -1,10 +1,10 @@ //! Level events whose client handler (`LevelEventHandler`) spawns particles -//! on a block: dragon egg teleportation (2015), a consumable's teleport -//! (2017), electric sparks (3002), waxing (3003), wax off (3004) and -//! scraping (3005). +//! on a block: bone meal's growth (1505), dragon egg teleportation (2015), a +//! consumable's teleport (2017), electric sparks (3002), waxing (3003), wax +//! off (3004) and scraping (3005). use super::Game; use horizon_client::particles::{self, ParticleOptions, ParticleType}; -use horizon_core::position::BlockPos; +use horizon_core::{position::BlockPos, random::RandomSource}; use horizon_world::level::LevelEvent; impl Game<'_> { @@ -42,6 +42,65 @@ impl Game<'_> { self.particles.add(&options, p, v); } } + /// `BoneMealItem.addGrowthParticles` (event 1505, `count` the data): + /// happy villager sparks over a spreading block's neighbourhood (grass, + /// nylium, netherrack, moss) or water, or inside a growing block. + pub(super) fn growth_particles(&mut self, pos: BlockPos, count: i32) { + let p = [pos.x, pos.y, pos.z]; + let state = self.world.block(p[0], p[1], p[2]); + let facts = self.res.facts(); + // ParticleUtils.spawnParticles(level, pos, count, xzSpread, ySpread, + // allowFloatingParticles, particle). + let (at, count, xz, height, floating) = match self.res.behaviours().bone_meal_spreads(state) + { + Some(spreads) => { + // BonemealableBlock.getParticlePos: below for rooted dirt + // (its hanging roots) and mangrove leaves (their propagule). + let at = match &*facts.get(state).name { + "minecraft:rooted_dirt" | "minecraft:mangrove_leaves" => [p[0], p[1] - 1, p[2]], + _ => p, + }; + if spreads { + (at, count * 3, 3.0, 1.0, false) + } else { + // ParticleUtils.spawnParticleInBlock: up to the + // block's shape (a full block when air). + let inside = self.world.block(at[0], at[1], at[2]); + let height = if facts.is_air(inside) { + 1.0 + } else { + facts + .get(inside) + .outline + .iter() + .map(|b| b[4]) + .fold(0.0, f64::max) + }; + (at, count, 0.5, height, true) + } + } + None if &*facts.get(state).name == "minecraft:water" => (p, count * 3, 3.0, 1.0, false), + None => return, + }; + let options = ParticleOptions::simple(ParticleType::HappyVillager); + for _ in 0..count.max(0) { + let r = self.particles.level_random(); + let v = [0.0; 3].map(|_: f64| r.next_gaussian() * 0.02); + let start = 0.5 - xz; + let x = f64::from(at[0]) + start + r.next_double() * xz * 2.0; + let y = f64::from(at[1]) + r.next_double() * height; + let z = f64::from(at[2]) + start + r.next_double() * xz * 2.0; + let below = [x.floor() as i32, y.floor() as i32 - 1, z.floor() as i32]; + if floating + || !self + .res + .facts() + .is_air(self.world.block(below[0], below[1], below[2])) + { + self.particles.add(&options, [x, y, z], v); + } + } + } /// Queue and play level event `id` at `pos` (`Level.levelEvent`). pub(super) fn level_event_at(&mut self, id: i32, pos: [i32; 3], data: i32) { self.level_events.push(LevelEvent::LevelEvent { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index dfde08d7f..578af5f69 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1725,29 +1725,10 @@ impl Game<'_> { self.block_entity_event(p.pos, i32::from(p.b0), i32::from(p.b1)); } } - C::LevelEvent(p) if p.kind == 2015 => { - self.dragon_egg_particles(p.pos, p.data); - } - C::LevelEvent(p) if p.kind == 2017 => { - self.consume_teleport_particles(p.pos, p.data); - } - C::LevelEvent(p) if p.kind == 2001 => { - // LevelEvent.PARTICLES_DESTROY_BLOCK: someone else broke a block. - let state = BlockStateId(p.data.max(0) as u32); - let s = self.res.facts().get(state).sounds.clone(); - let at = [ - f64::from(p.pos[0]) + 0.5, - f64::from(p.pos[1]) + 0.5, - f64::from(p.pos[2]) + 0.5, - ]; - self.audio.play( - &s.break_sound, - Some(at), - (s.volume + 1.0) / 2.0, - s.pitch * 0.8, - ); - self.destroy_particles(p.pos, state); - } + // ClientLevel.levelEvent: LevelEventHandler, as this client's own + // level plays them (particles and sounds: a spawner's burst, bone + // meal, waxing, a block broken by someone else). + C::LevelEvent(p) => self.level_event_at(p.kind, p.pos, p.data), C::Sound(p) => { let name = match &p.sound.1 { Some((location, _)) => Some(location.clone()), @@ -3821,6 +3802,8 @@ impl Game<'_> { } if reacts { self.predict_use(&changes, seq); + } else if let Some(stack) = held.as_ref() { + self.predict_item_on_block(stack, &hit); } if held_block { if reacts @@ -3839,6 +3822,38 @@ impl Game<'_> { false } + /// `Item.useOn` on this client's level for the items whose effects are + /// the clicker's own (`Level.levelEvent(player, ...)` and + /// `playSound(player, ...)`: the server sends them to the others only): + /// honeycomb waxing copper, and an axe, hoe or shovel transforming a + /// block (stripping, scraping, removing wax, tilling, making a path). + fn predict_item_on_block(&mut self, stack: &ItemStack, hit: &super::Hit) { + let at = [ + f64::from(hit.pos[0]) + 0.5, + f64::from(hit.pos[1]) + 0.5, + f64::from(hit.pos[2]) + 0.5, + ]; + if &*stack.item == "minecraft:honeycomb" { + // HoneycombItem.useOn. + let registry = self.pack.assets.registry; + let clicked = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); + let waxes = registry + .state(clicked) + .and_then(|old| self.res.transformers().waxed(registry, old)) + .is_some(); + if waxes { + self.level_event_at(3003, hit.pos, 0); + self.audio + .play("minecraft:item.honeycomb.wax_on", Some(at), 1.0, 1.0); + } + } else if let Some((_, sound, _, _, particle)) = + self.block_transform(stack, hit.pos, hit.face) + { + self.transform_particle(&particle, hit.pos); + self.audio.play(&sound, Some(at), 1.0, 1.0); + } + } + /// MultiPlayerGameMode.useItemOn inside startPrediction: the blocks the /// use changed on this client's level at once, each kept as predicted /// under the use's sequence until the server acknowledges it (a use the diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index 55a7a5120..a5df97258 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -1158,6 +1158,8 @@ pub struct ParticleEngine { starters: Vec, /// Local sounds requested by particles (dripstone drips): (event, position, volume, pitch). pub sounds: Vec<(&'static str, [f64; 3], f32, f32)>, + /// How many of each type were made, for `horizon-ctl status`. + made: std::collections::BTreeMap<&'static str, u64>, /// The item particles' sprites (`BreakingItemParticle`'s slime ball, snowball /// and cobweb models, resolved for the ground), one per model layer. pub item_sprites: HashMap>, @@ -1183,6 +1185,7 @@ impl ParticleEngine { starters: Vec::new(), camera: [0.0; 3], sounds: Vec::new(), + made: Default::default(), item_sprites: HashMap::new(), }; let dir = root.join("assets/minecraft/particles"); @@ -1449,9 +1452,14 @@ impl ParticleEngine { pub fn create(&mut self, options: &ParticleOptions, p: [f64; 3], v: [f64; 3]) { let seed = self.seeds.next_long(); if let Some(particle) = self.make(options, p, v, seed) { + *self.made.entry(options.ty.name()).or_default() += 1; self.pending.push(particle); } } + /// How many particles of each type were made so far. + pub fn made(&self) -> &std::collections::BTreeMap<&'static str, u64> { + &self.made + } /// Parity probes: seed the provider (`ParticleEngine.random`), level and /// `SpellParticle.RANDOM` generators. pub fn seed_randoms(&mut self, provider: i64, level: i64, spell: i64) { diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index c4d8084ba..fd6e09ce1 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -109,6 +109,9 @@ address. The script then checks, from both sides, what a guest's game used to ge the host has them; a falling block lands on both sides. - thrown: a splash potion and an eye of ender the host and the guest each throw fly on both sides (#1363, #1391); +- sparks: level events' particles on both sides: the host's and the guest's bone meal on wheat + (growth sparks), honeycomb on copper and an axe taking the wax off, and a spawner's + burst when it spawns (#1395, #1401, #1402); - fireball: a fire charge a dispenser shoots onto stone lights a fire both sides see, and the fire goes out on its own within a minute (it ticks: FireBlock.tick on a floor that doesn't burn) @@ -210,7 +213,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] class Game: @@ -2643,6 +2646,71 @@ def check_thrown(host, guest, out): return result +def made(game, kind): + """How many `kind` particles `game` has made so far.""" + return game('status').get('particles', {}).get(kind, 0) + + +def sparked(player, other, kinds, act, ticks=20): + """The `kinds` particles each side makes while `act` runs and for up to `ticks` after.""" + before = {(side, k): made(g, k) for side, g in (('own', player), ('other', other)) for k in kinds} + act() + seen = {} + for _ in range(ticks // 2): + player.wait(2) + seen = {f'{side} {k}': made(g, k) - before[(side, k)] + for side, g in (('own', player), ('other', other)) for k in kinds} + if all(seen.values()): + break + return seen + + +def check_sparks(host, guest, out): + spots = apart(host, guest) + result = {} + for label, player, other in (('host', host, guest), ('guest', guest, host)): + x, y, z = spots[label] + at = (x, y, z + 2) + player('command', command='gamemode survival') + try: + player('command', command=f'setblock {at[0]} {at[1] - 1} {at[2]} minecraft:farmland') + player('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:wheat') + player('command', command='item replace entity @s weapon.mainhand with minecraft:bone_meal 8') + player.wait(10) + + def click(height): + player.raw('look-at', f'{at[0] + 0.5:.2f}', f'{at[1] + height:.2f}', f'{at[2] + 0.5:.2f}') + player.raw('mouse', 'right', 'click') + result[f'{label} bone meal'] = sparked(player, other, ['happy_villager'], lambda: click(0.1)) + player('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:copper_block') + player('command', command='item replace entity @s weapon.mainhand with minecraft:honeycomb') + player.wait(10) + result[f'{label} wax'] = sparked(player, other, ['wax_on'], lambda: click(0.5)) + player('command', command='item replace entity @s weapon.mainhand with minecraft:iron_axe') + player.wait(10) + result[f'{label} wax off'] = sparked(player, other, ['wax_off'], lambda: click(0.5)) + block = player.raw('block', *at).get('block', '') + result[f'{label} copper'] = block + finally: + player('command', command=f'fill {at[0]} {at[1] - 1} {at[2]} {at[0]} {at[1]} {at[2]} minecraft:air') + player('command', command=f'setblock {at[0]} {at[1] - 1} {at[2]} minecraft:stone') + player('command', command='clear @s') + # A spawner beside the host, at night: its burst when the zombie comes. + x, y, z = spots['host'] + host('command', command='time set midnight') + try: + host('command', command=f'setblock {x} {y} {z + 3} minecraft:spawner{{Delay:20s,SpawnCount:1s,' + 'SpawnData:{entity:{id:"minecraft:zombie",NoAI:1b}}}') + result['spawner'] = sparked(host, guest, ['flame', 'smoke'], lambda: None, ticks=200) + finally: + host('command', command=f'setblock {x} {y} {z + 3} minecraft:air') + host('command', command=f'kill @e[type=minecraft:zombie,x={x},y={y},z={z},distance=..12]') + host('command', command='time set day') + wrong = {k: v for k, v in result.items() if isinstance(v, dict) and not all(n > 0 for n in v.values())} + assert not wrong, f'no particles: {wrong}\n{result}' + return result + + def check_blast(host, guest, out): guest('command', command='gamemode survival') guest('command', command='clear @s') @@ -3977,7 +4045,8 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'underwater': check_underwater, 'looks': check_looks, 'leads': check_leads, - 'thrown': check_thrown} + 'thrown': check_thrown, + 'sparks': check_sparks} def run(ctl, out, resources, checks): From b7f4cba355f6cc18d6611b8f8eca8a987987f2fa Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 08:28:41 +0200 Subject: [PATCH 015/408] A server's scoreboard reaches its players: sidebar, teams, scores The server never sent its scoreboard, so a sidebar shown on single player's server thread or to a LAN guest stayed empty. Each tick a placed player is now sent what changed since it was last sent the board, as ServerScoreboard's callbacks do: every team, and the objectives in a display slot with their slots and scores (all of it on joining). A server's client also finds its team's sidebar by its profile name rather than single player's "Player". Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/control.rs | 2 + crates/horizon-client/src/game/lan.rs | 1 + crates/horizon-client/src/game/remote.rs | 4 + crates/horizon-client/src/game/scoreboard.rs | 51 ++- crates/horizon-client/src/lan/guest.rs | 3 + crates/horizon-client/src/lan/mod.rs | 1 + crates/horizon-client/src/lan/scoreboard.rs | 308 +++++++++++++++++++ tools/lan_e2e.py | 48 ++- 8 files changed, 410 insertions(+), 8 deletions(-) create mode 100644 crates/horizon-client/src/lan/scoreboard.rs diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index ca15424d1..261f207d4 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -979,6 +979,8 @@ impl Game<'_> { status["projectiles"] = json!(self.projectiles_status()); // The particles made so far, by type. status["particles"] = json!(self.particles.made()); + // The scoreboard sidebar the HUD shows. + status["sidebar"] = self.sidebar_status(); status } } diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 72b3b3fc5..9bfad8581 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -997,6 +997,7 @@ impl Game<'_> { self.lan_update_streaming(&host); self.lan_update_models(&mut host); self.lan_update_waypoints(&mut host, state.as_ref()); + self.lan_sync_scoreboard(&mut host); drop(holding); lan::flush_all(host.hub.guests.iter().map(|g| &g.sender)); self.lan = Some(host); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index b8777e8d2..46d8c6a65 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -164,6 +164,8 @@ pub(super) struct Remote { level_players: HashMap, /// The local player's profile UUID (always in the level). profile: u128, + /// The local player's profile name: its score holder and team member. + pub(super) profile_name: String, destroying: Option<([i32; 3], u8, f32)>, destroy_delay: u32, input: horizon_client::interaction_input::InteractionInput, @@ -411,6 +413,7 @@ impl Game<'_> { online_mode: false, level_players: HashMap::new(), profile: 0, + profile_name: String::new(), destroying: None, destroy_delay: 0, input: Default::default(), @@ -795,6 +798,7 @@ impl Game<'_> { if let Some(r) = self.remote.as_mut() { r.joined = true; r.profile = uuid; + r.profile_name = name.clone(); r.status = format!("Joined as {name}; loading terrain..."); } } diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 4d60c2df7..4905fb80f 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -324,6 +324,22 @@ impl Game<'_> { } } } + /// `ServerScoreboard`'s packets: each placed player's client is sent + /// what changed on the board since it was last sent it (all of it on + /// joining), lan/scoreboard.rs. + pub(super) fn lan_sync_scoreboard(&mut self, host: &mut super::lan::LanHost) { + if host.hub.guests.iter().all(|g| !g.placed) { + return; + } + self.load_scoreboard(); + let view = horizon_client::lan::scoreboard::View::of(&self.score.board); + for g in host.hub.guests.iter_mut().filter(|g| g.placed) { + if g.scoreboard != view { + g.send_all(&g.scoreboard.changes(&view)); + g.scoreboard = view.clone(); + } + } + } /// `ServerPlayer.doTick` score updates and the statistic criteria. pub(super) fn tick_scoreboard(&mut self) { self.load_scoreboard(); @@ -563,19 +579,42 @@ impl Game<'_> { // ---- the sidebar ----------------------------------------------------------- - /// `Hud.extractScoreboardSidebar` / `displayScoreboardSidebar`. - pub(super) fn draw_scoreboard(&self, batch: &mut HudBatch) { + /// The objective in the player's team's sidebar slot, else the sidebar's. + fn sidebar_objective(&self) -> Option<&sb::Objective> { let board = &self.score.board; if board.display.is_empty() { - return; + return None; } + // A server's client is in its team by its profile name. + let name = self + .remote + .as_ref() + .map_or(PLAYER_NAME, |r| r.profile_name.as_str()); let team_slot = board - .players_team(PLAYER_NAME) + .players_team(name) .and_then(|t| t.color.as_ref()) .map(|c| format!("sidebar.team.{c}")) .and_then(|slot| board.display_objective(&slot)); - let Some(objective) = team_slot.or_else(|| board.display_objective(sb::SLOT_SIDEBAR)) - else { + team_slot.or_else(|| board.display_objective(sb::SLOT_SIDEBAR)) + } + /// The sidebar the HUD shows: its objective and its lines, for `status`. + pub(super) fn sidebar_status(&self) -> serde_json::Value { + let board = &self.score.board; + let Some(objective) = self.sidebar_objective() else { + return serde_json::Value::Null; + }; + let scores: serde_json::Map = board + .scores + .iter() + .filter_map(|(holder, s)| Some((holder.clone(), s.get(&objective.name)?.value.into()))) + .collect(); + serde_json::json!({ "objective": objective.name, "title": objective.display_text().plain(), "scores": scores }) + } + + /// `Hud.extractScoreboardSidebar` / `displayScoreboardSidebar`. + pub(super) fn draw_scoreboard(&self, batch: &mut HudBatch) { + let board = &self.score.board; + let Some(objective) = self.sidebar_objective() else { return; }; let draws = hud_overlays::sidebar( diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 4236280cd..cb3a4927c 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -215,6 +215,8 @@ pub struct Guest { pub advancements_loaded: bool, pub advancements_visible: Vec, pub advancements_changed: std::collections::BTreeSet, + /// The server's scoreboard as this player's client has it (lan/scoreboard.rs). + pub scoreboard: super::scoreboard::View, /// Recipes unlocked since the client was last told /// (`ServerRecipeBook.addRecipes` sends them). pub recipes_unlocked: Vec, @@ -326,6 +328,7 @@ impl Guest { advancements_loaded: false, advancements_visible: Vec::new(), advancements_changed: Default::default(), + scoreboard: Default::default(), recipes_unlocked: Vec::new(), } } diff --git a/crates/horizon-client/src/lan/mod.rs b/crates/horizon-client/src/lan/mod.rs index c2f35bc8e..d342c7fe5 100644 --- a/crates/horizon-client/src/lan/mod.rs +++ b/crates/horizon-client/src/lan/mod.rs @@ -20,6 +20,7 @@ pub mod hub; pub mod menu; pub mod playerdata; mod recipes; +pub mod scoreboard; pub mod tracking; pub mod waypoints; diff --git a/crates/horizon-client/src/lan/scoreboard.rs b/crates/horizon-client/src/lan/scoreboard.rs new file mode 100644 index 000000000..cba0f914c --- /dev/null +++ b/crates/horizon-client/src/lan/scoreboard.rs @@ -0,0 +1,308 @@ +//! `ServerScoreboard`: what a player's client knows of the server's +//! scoreboard. Every team goes to every player; an objective goes once it +//! sits in a display slot (`startTrackingObjective`: its objective, its +//! slots, then its scores) and leaves when it sits in none +//! (`stopTrackingObjective`). A joining player gets it all +//! (`PlayerList.updateEntireScoreboard`). +//! +//! A server's commands change the board in place; each tick a player is +//! sent the packets that turn what it was last sent into what it should +//! have now, which are the ones `ServerScoreboard`'s callbacks send. +use crate::scoreboard::{NumberFormat, RenderType, Scoreboard, component_tag, display_slots}; +use crate::text::COLORS; +use horizon_protocol::packets::play::{ + self, Clientbound as C, ResetScore, SetDisplayObjective, SetObjective, SetPlayerTeam, SetScore, + TeamParameters, +}; +use horizon_world::nbt::Tag; +use std::collections::{BTreeMap, BTreeSet}; + +type Format = Option; + +/// The scoreboard as one player's client has it. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct View { + /// The tracked objectives: display name, render type (1 hearts), format. + objectives: BTreeMap, + /// `DisplaySlot` id to objective. + display: BTreeMap, + /// The tracked objectives' scores, by holder and objective. + scores: BTreeMap<(String, String), (i32, Option, Format)>, + /// Every team: its parameters and players, in the team's order. + teams: BTreeMap)>, +} + +fn format(f: Option<&NumberFormat>) -> Format { + f.map(|f| match f { + NumberFormat::Blank => play::NumberFormat::Blank, + NumberFormat::Styled(s) => play::NumberFormat::Styled(crate::scoreboard::json_to_tag(s)), + NumberFormat::Fixed(c) => play::NumberFormat::Fixed(component_tag(c)), + }) +} + +impl View { + /// What the board's state gives a client. + pub fn of(board: &Scoreboard) -> Self { + let slots = display_slots(); + let display: BTreeMap = board + .display + .iter() + .filter_map(|(slot, o)| Some((slots.iter().position(|s| s == slot)? as i32, o.clone()))) + .collect(); + let tracked: BTreeSet<&String> = display.values().collect(); + let objectives = board + .objectives + .iter() + .filter(|o| tracked.contains(&o.name)) + .map(|o| { + let render = i32::from(o.render_type == RenderType::Hearts); + ( + o.name.clone(), + ( + component_tag(&o.display_name), + render, + format(o.number_format.as_ref()), + ), + ) + }) + .collect(); + let scores = board + .scores + .iter() + .flat_map(|(holder, scores)| { + scores + .iter() + .filter(|(o, _)| tracked.contains(o)) + .map(move |(o, s)| { + ( + (holder.clone(), o.clone()), + ( + s.value, + s.display.as_ref().map(component_tag), + format(s.number_format.as_ref()), + ), + ) + }) + }) + .collect(); + let teams = board + .teams + .iter() + .map(|t| { + let params = TeamParameters { + display_name: component_tag(&t.display_name), + prefix: component_tag(&t.prefix), + suffix: component_tag(&t.suffix), + name_tag_visibility: t.nametag_visibility as i32, + collision_rule: t.collision_rule as i32, + color: t + .color + .as_deref() + .and_then(|c| COLORS.iter().position(|(_, n, _)| *n == c)) + .map(|i| i as i32), + options: i8::from(t.allow_friendly_fire) + | (i8::from(t.see_friendly_invisibles) << 1), + }; + ( + t.name.clone(), + (params, t.players.iter().cloned().collect()), + ) + }) + .collect(); + Self { + objectives, + display, + scores, + teams, + } + } + + /// The packets that take a client from `self` to `next`. + pub fn changes(&self, next: &View) -> Vec { + let mut out = Vec::new(); + let team = |name: &str, method, parameters, players| { + C::SetPlayerTeam(SetPlayerTeam { + name: name.to_owned(), + method, + parameters, + players, + }) + }; + for name in self.teams.keys().filter(|n| !next.teams.contains_key(*n)) { + out.push(team(name, 1, None, Vec::new())); + } + for (name, (params, players)) in &next.teams { + let Some((was, had)) = self.teams.get(name) else { + out.push(team(name, 0, Some(params.clone()), players.clone())); + continue; + }; + if was != params { + out.push(team(name, 2, Some(params.clone()), Vec::new())); + } + let joined: Vec<_> = players + .iter() + .filter(|p| !had.contains(p)) + .cloned() + .collect(); + if !joined.is_empty() { + out.push(team(name, 3, None, joined)); + } + let left: Vec<_> = had + .iter() + .filter(|p| !players.contains(p)) + .cloned() + .collect(); + if !left.is_empty() { + out.push(team(name, 4, None, left)); + } + } + for (name, display) in &next.objectives { + let method = match self.objectives.get(name) { + None => 0, + Some(was) if was != display => 2, + Some(_) => continue, + }; + out.push(C::SetObjective(SetObjective { + name: name.clone(), + method, + display: Some(display.clone()), + })); + } + let slots: BTreeSet = self + .display + .keys() + .chain(next.display.keys()) + .copied() + .collect(); + for slot in slots { + let objective = next.display.get(&slot); + if self.display.get(&slot) != objective { + out.push(C::SetDisplayObjective(SetDisplayObjective { + slot, + objective: objective.cloned().unwrap_or_default(), + })); + } + } + for ((holder, objective), (value, display, number_format)) in &next.scores { + let key = (holder.clone(), objective.clone()); + if self.scores.get(&key) != Some(&(*value, display.clone(), number_format.clone())) { + out.push(C::SetScore(SetScore { + owner: holder.clone(), + objective: objective.clone(), + score: *value, + display: display.clone(), + number_format: number_format.clone(), + })); + } + } + for (holder, objective) in self.scores.keys() { + let key = (holder.clone(), objective.clone()); + if !next.scores.contains_key(&key) && next.objectives.contains_key(objective) { + out.push(C::ResetScore(ResetScore { + owner: holder.clone(), + objective: Some(objective.clone()), + })); + } + } + for name in self + .objectives + .keys() + .filter(|n| !next.objectives.contains_key(*n)) + { + out.push(C::SetObjective(SetObjective { + name: name.clone(), + method: 1, + display: None, + })); + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn methods(packets: &[C]) -> Vec { + packets + .iter() + .map(|p| match p { + C::SetObjective(o) => format!("objective {} {}", o.name, o.method), + C::SetDisplayObjective(d) => format!("display {} {}", d.slot, d.objective), + C::SetScore(s) => format!("score {} {} {}", s.owner, s.objective, s.score), + C::ResetScore(r) => format!("reset {} {:?}", r.owner, r.objective), + C::SetPlayerTeam(t) => format!("team {} {} {:?}", t.name, t.method, t.players), + _ => "other".into(), + }) + .collect() + } + + #[test] + fn a_shown_objective_goes_with_its_scores_and_leaves_when_hidden() { + let mut board = Scoreboard::default(); + board.add_objective( + "audit", + "dummy", + json!("Audit"), + RenderType::Integer, + false, + None, + ); + board.score_mut("Alpha", "audit").value = 7; + let empty = View::default(); + // Not displayed: not tracked, nothing sent. + let hidden = View::of(&board); + assert!(empty.changes(&hidden).is_empty()); + board.set_display_objective("sidebar", Some("audit")); + let shown = View::of(&board); + assert_eq!( + methods(&hidden.changes(&shown)), + [ + "objective audit 0", + "display 1 audit", + "score Alpha audit 7" + ] + ); + board.score_mut("Alpha", "audit").value = 12; + board.score_mut("Beta", "audit").value = 3; + board.reset_one("Beta", "audit"); + let changed = View::of(&board); + assert_eq!(methods(&shown.changes(&changed)), ["score Alpha audit 12"]); + board.reset_one("Alpha", "audit"); + let reset = View::of(&board); + assert_eq!( + methods(&changed.changes(&reset)), + ["reset Alpha Some(\"audit\")"] + ); + board.set_display_objective("sidebar", None); + assert_eq!( + methods(&reset.changes(&View::of(&board))), + ["display 1 ", "objective audit 1"] + ); + } + + #[test] + fn teams_go_to_everyone_with_their_players() { + let mut board = Scoreboard::default(); + board.add_team("red"); + board.add_to_team("Alpha", "red"); + let first = View::of(&board); + assert_eq!( + methods(&View::default().changes(&first)), + ["team red 0 [\"Alpha\"]"] + ); + board.add_to_team("Beta", "red"); + board.remove_from_team("Alpha"); + let second = View::of(&board); + assert_eq!( + methods(&first.changes(&second)), + ["team red 3 [\"Beta\"]", "team red 4 [\"Alpha\"]"] + ); + board.remove_team("red"); + assert_eq!( + methods(&second.changes(&View::of(&board))), + ["team red 1 []"] + ); + } +} diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index fbb7e4e9c..72beb2acd 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -213,7 +213,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'sidebar', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] class Game: @@ -2751,6 +2751,49 @@ def check_hud(host, guest, out): return result +def sidebars(host, guest, want, ticks=40): + """Each side's sidebar (objective and scores) once both show `want` (host, guest), or after `ticks`.""" + seen = None + for _ in range(ticks // 2): + host.wait(2) + seen = tuple(g('status').get('sidebar') for g in (host, guest)) + got = tuple(s and (s['objective'], s['scores']) for s in seen) + if got == want: + break + return seen + + +def check_sidebar(host, guest, out): + result = {} + run = lambda *cmds: [host('command', command=c) for c in cmds] + try: + run('scoreboard objectives add audit dummy {"text":"Audit board","color":"aqua"}', + 'scoreboard players set Alpha audit 7', 'scoreboard players set Beta audit 3', + 'scoreboard objectives setdisplay sidebar audit') + both = ('audit', {'Alpha': 7, 'Beta': 3}) + result['shown'] = sidebars(host, guest, (both, both)) + host.shot(out, 'sidebar') + guest.shot(out, 'sidebar') + run('scoreboard players set Alpha audit 12', 'scoreboard players reset Beta audit') + both = ('audit', {'Alpha': 12}) + result['changed'] = sidebars(host, guest, (both, both)) + # The guest's team's sidebar replaces the sidebar for the guest only. + run('team add red', 'team modify red color red', f'team join red {GUEST_NAME}', + 'scoreboard objectives add reds dummy', f'scoreboard players set {GUEST_NAME} reds 5', + 'scoreboard objectives setdisplay sidebar.team.red reds') + result['team'] = sidebars(host, guest, (both, ('reds', {GUEST_NAME: 5}))) + run('scoreboard objectives remove reds', 'scoreboard objectives setdisplay sidebar') + result['cleared'] = sidebars(host, guest, (None, None)) + finally: + run('scoreboard objectives remove audit', 'scoreboard objectives remove reds', 'team remove red') + want = {'shown': (('audit', {'Alpha': 7, 'Beta': 3}),) * 2, 'changed': (('audit', {'Alpha': 12}),) * 2, + 'team': (('audit', {'Alpha': 12}), ('reds', {GUEST_NAME: 5})), 'cleared': (None, None)} + got = {k: tuple(s and (s['objective'], s['scores']) for s in v) for k, v in result.items()} + wrong = {k: v for k, v in got.items() if v != want[k]} + assert not wrong, f'sidebars: {wrong}\n{result}' + return result + + def check_blast(host, guest, out): guest('command', command='gamemode survival') guest('command', command='clear @s') @@ -4087,7 +4130,8 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'leads': check_leads, 'thrown': check_thrown, 'sparks': check_sparks, - 'hud': check_hud} + 'hud': check_hud, + 'sidebar': check_sidebar} def run(ctl, out, resources, checks): From 4b8fecfe58c2544a57dd9af14e73821ae0abbe80 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 09:03:08 +0200 Subject: [PATCH 016/408] Particles from a server: /particle and explosions reach its players A server never sent particles: /particle on single player's server thread drew into the server's own engine, and TNT exploded without its burst for anyone but an old-mode host. The protocol gains ClientboundLevelParticlesPacket and ClientboundExplodePacket; /particle sends the particles to each viewer in range (every player without viewers, as PlayerList.getPlayers) and an explosion sends its packet to the players within 64 blocks; their clients draw them as handleParticleEvent and handleExplosion do. /particle's spread was measured from the command's source as if it were a position; it is the spread as given (Vec3Argument.getVec3). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 1 + .../src/game/commands/world_cmds.rs | 76 +++++- crates/horizon-client/src/game/explosion.rs | 1 + .../horizon-client/src/game/lan_particles.rs | 228 ++++++++++++++++++ crates/horizon-client/src/game/remote.rs | 4 +- crates/horizon-protocol/src/packets/play.rs | 142 ++++++++++- tools/lan_e2e.py | 42 +++- 7 files changed, 477 insertions(+), 17 deletions(-) create mode 100644 crates/horizon-client/src/game/lan_particles.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 11d94ef48..d7f523dac 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -73,6 +73,7 @@ mod lan_crafting; mod lan_entities; mod lan_mobs; mod lan_mount_menu; +mod lan_particles; mod lan_pvp; mod lan_screen; mod lan_stations; diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index 7e02626d2..1f7504d8a 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -8,6 +8,7 @@ use horizon_client::{ text::Text, }; use horizon_core::random::RandomSource; +use horizon_protocol::packets::play::{self, Clientbound as C}; use horizon_world::attribute_map::ValueKind; use horizon_world::nbt::Tag; @@ -409,6 +410,8 @@ impl Game<'_> { ], _ => [1.0, 0.0, 0.0], }; + // The block state of a block particle, for its packet. + let mut block_state = None; let options = match ty { ParticleType::Dust => ParticleOptions::dust( rgb, @@ -470,6 +473,7 @@ impl Game<'_> { match block { Ok(Arg::Block(b)) => { let state = self.block_state(&b)?; + block_state = Some(state); let at = self .position_arg(ctx, "pos") .unwrap_or_else(|| self.source_position()) @@ -487,10 +491,9 @@ impl Game<'_> { let pos = self .position_arg(ctx, "pos") .unwrap_or_else(|| self.source_position()); - let delta = self.position_arg(ctx, "delta").map_or([0.0; 3], |d| { - let s = self.source_position(); - [d[0] - s[0], d[1] - s[1], d[2] - s[2]] - }); + // Vec3Argument.getVec3: the spread as given (relative parts from the + // source), not a position to measure from the source. + let delta = self.position_arg(ctx, "delta").unwrap_or([0.0; 3]); let speed = match ctx.get("speed") { Some(Arg::Float(v)) => *v, _ => 0.0, @@ -501,27 +504,74 @@ impl Game<'_> { }; // ParticleCommand.sendParticles: the viewers it reached, each within // 32 blocks (512 with `force`) of the particle's block centre. + // Without viewers, every player (PlayerList.getPlayers). let viewers = if ctx.get("viewers").is_some() { self.entities(ctx, "viewers", true)? } else { - vec![Target::Player] + let acting = self.lan_acting; + let guests = self.lan.iter().flat_map(|h| h.hub.guests.iter()); + self.player + .as_ref() + .map(|_| Target::Player) + .into_iter() + .chain( + guests + .filter(|g| g.placed && Some(g.conn) != acting) + .map(|g| Target::Guest(g.conn)), + ) + .collect() }; - let limit = if ctx.has("force") { 512.0 } else { 32.0 }; - let reached = viewers - .iter() - .filter(|&&t| { + let force = ctx.has("force"); + let limit = if force { 512.0 } else { 32.0 }; + let reached: Vec = viewers + .into_iter() + .filter(|&t| { self.target_position(t).is_some_and(|p| { let c = p.map(|v| v.floor() + 0.5); (c[0] - pos[0]).powi(2) + (c[1] - pos[1]).powi(2) + (c[2] - pos[2]).powi(2) < limit * limit }) }) - .count() as i32; - if reached == 0 { + .collect(); + if reached.is_empty() { return Err(err("commands.particle.failed", &[])); } - // `ServerLevel.sendParticles`: no count means one particle with the delta as velocity. - if count <= 0 { + // ServerLevel.sendParticles: each viewer a server serves is sent the + // particles (the player in place too when it is a guest); the + // window's own player draws them. + let packet = self + .network_particle(&options, block_state) + .map(|particle| { + C::LevelParticles(play::LevelParticles { + particle, + override_limiter: force, + always_show: false, + pos, + dist: delta.map(|d| d as f32), + max_speed: [speed; 3], + count: count.max(0), + randomization: 0, + }) + }); + let mut local = false; + for &t in &reached { + match (t, &packet) { + (Target::Player, Some(p)) if self.lan_acting.is_some() => { + self.guest_packets.push(p.clone()); + } + (Target::Player, _) => local = true, + (Target::Guest(conn), Some(p)) => { + if let Some(host) = self.lan.as_ref() { + host.hub.send_to(conn, p); + } + } + _ => {} + } + } + let reached = reached.len() as i32; + if !local { + } else if count <= 0 { + // No count: one particle with the delta as velocity. self.particles.create(&options, pos, delta); } else { for _ in 0..count { diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 0923b4110..6ecba3a54 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -580,6 +580,7 @@ impl Game<'_> { self.particles.explosion(center, radius, block_count, &|b| { facts.is_air(world.block(b[0], b[1], b[2])) }); + self.lan_explode(center, radius, block_count); Ok(()) } /// `BlockBehaviour.onExplosionHit` (TNT: `wasExploded` primes a short fuse). diff --git a/crates/horizon-client/src/game/lan_particles.rs b/crates/horizon-client/src/game/lan_particles.rs new file mode 100644 index 000000000..2cacfabdb --- /dev/null +++ b/crates/horizon-client/src/game/lan_particles.rs @@ -0,0 +1,228 @@ +//! Particles a server sends its players and its clients draw: +//! `ClientboundLevelParticlesPacket` (`ServerLevel.sendParticles`, which +//! `/particle` uses) and `ClientboundExplodePacket` (`ServerLevel.explode`). +use super::Game; +use horizon_client::particles::{ParticleOptions, ParticleType}; +use horizon_core::random::RandomSource; +use horizon_protocol::{ + entity_data::{Particle, ParticleData}, + packets::play::{self, Clientbound as C}, +}; +use horizon_world::registry::BlockStateId; + +/// An ARGB colour as the options' RGBA. +fn rgba(argb: i32) -> [f32; 4] { + let c = |shift: i32| ((argb >> shift) & 255) as f32 / 255.0; + [c(16), c(8), c(0), c(24)] +} +/// The options' RGB as an RGB colour (`ARGB.colorFromFloat` without alpha). +fn rgb_int(c: [f32; 3]) -> i32 { + let b = |v: f32| ((v.clamp(0.0, 1.0) * 255.0).round() as i32) & 255; + (b(c[0]) << 16) | (b(c[1]) << 8) | b(c[2]) +} +fn rgb(c: [f32; 4]) -> [f32; 3] { + [c[0], c[1], c[2]] +} + +impl Game<'_> { + /// `ParticleTypes.STREAM_CODEC`'s value for `options`: the type's + /// network id and the data it carries (`state` for the block particles). + /// None while not serving, or for a particle whose data isn't sent from + /// here (items, vibrations, trails). + pub(super) fn network_particle( + &self, + options: &ParticleOptions, + state: Option, + ) -> Option { + let name = format!("minecraft:{}", options.ty.name()); + let id = self + .lan + .as_ref()? + .hub + .registry_id("minecraft:particle_type", &name)?; + use ParticleType as T; + let c = options.color; + let data = match options.ty { + T::Block | T::BlockMarker | T::FallingDust | T::DustPillar | T::BlockCrumble => { + Some(ParticleData::State(state?.0 as i32)) + } + T::Dust => Some(ParticleData::ColorScale(rgb_int(rgb(c)), options.scale)), + T::DustColorTransition => Some(ParticleData::ColorScale2( + rgb_int(rgb(c)), + rgb_int(options.to_color), + options.scale, + )), + T::Effect | T::InstantEffect => { + Some(ParticleData::ColorPower(rgb_int(rgb(c)), options.scale)) + } + T::EntityEffect | T::TintedLeaves => Some(ParticleData::Color( + (((c[3].clamp(0.0, 1.0) * 255.0).round() as i32) << 24) | rgb_int(rgb(c)), + )), + T::DragonBreath | T::SculkCharge => Some(ParticleData::Scalar(options.scale)), + T::Shriek => Some(ParticleData::Delay(options.scale as i32)), + T::Item | T::Trail | T::Vibration => return None, + _ => None, + }; + Some(Particle { id, data }) + } + + /// The options a server's particle stands for (None for a type or data + /// this client doesn't draw). + fn received_particle(&mut self, p: &Particle, at: [f64; 3]) -> Option { + let name = self + .remote + .as_ref()? + .builtin + .get("minecraft:particle_type")? + .name(p.id)? + .to_owned(); + let ty = ParticleType::from_name(&name)?; + Some(match &p.data { + None => ParticleOptions::simple(ty), + Some(ParticleData::State(s)) => { + let pos = at.map(|v| v.floor() as i32); + let (sprite, tint) = self + .particle_sprite(BlockStateId(*s as u32), pos) + .unwrap_or_else(|| ("block/stone".into(), 0xFFFFFF)); + ParticleOptions::block(ty, sprite, tint) + } + Some(ParticleData::ColorScale(c, scale)) => { + ParticleOptions::dust(rgb(rgba(*c)), *scale) + } + Some(ParticleData::ColorScale2(from, to, scale)) => { + ParticleOptions::dust_transition(rgb(rgba(*from)), rgb(rgba(*to)), *scale) + } + Some(ParticleData::ColorPower(c, power)) => ParticleOptions { + scale: *power, + ..ParticleOptions::colored(ty, [rgba(*c)[0], rgba(*c)[1], rgba(*c)[2], 1.0]) + }, + Some(ParticleData::Color(c)) => ParticleOptions::colored(ty, rgba(*c)), + Some(ParticleData::Scalar(v)) if ty == ParticleType::SculkCharge => { + ParticleOptions::sculk_charge(*v) + } + Some(ParticleData::Scalar(v)) => ParticleOptions { + scale: *v, + ..ParticleOptions::simple(ty) + }, + Some(ParticleData::Delay(d)) => ParticleOptions::shriek(*d), + Some(ParticleData::Trail(target, color, duration)) => { + ParticleOptions::trail(*target, *color as u32 & 0xFF_FFFF, *duration) + } + Some(_) => return None, + }) + } + + /// `ClientPacketListener.handleParticleEvent`: no count is one particle + /// moving by speed times spread; otherwise each is spread and sped up by + /// gaussians on each axis. + pub(super) fn remote_level_particles(&mut self, p: &play::LevelParticles) { + let Some(options) = self.received_particle(&p.particle, p.pos) else { + return; + }; + let (d, s) = (p.dist.map(f64::from), p.max_speed.map(f64::from)); + // ClientLevel.addParticle: the camera's 32 blocks unless the packet + // (`force`) or the type overrides the limiter. + let add = |particles: &mut horizon_client::particles::ParticleEngine, at, v| { + if p.override_limiter { + particles.create(&options, at, v); + } else { + particles.add(&options, at, v); + } + }; + if p.count == 0 { + add( + &mut self.particles, + p.pos, + [s[0] * d[0], s[1] * d[1], s[2] * d[2]], + ); + return; + } + for _ in 0..p.count { + let r = self.particles.random(); + let at = [ + p.pos[0] + r.next_gaussian() * d[0], + p.pos[1] + r.next_gaussian() * d[1], + p.pos[2] + r.next_gaussian() * d[2], + ]; + let v = [ + r.next_gaussian() * s[0], + r.next_gaussian() * s[1], + r.next_gaussian() * s[2], + ]; + add(&mut self.particles, at, v); + } + } + + /// `ClientPacketListener.handleExplosion`: the blast's particles (and its + /// sound, when the packet carries it). + pub(super) fn remote_explode(&mut self, p: &play::Explode) { + if p.play_sound { + let pitch = (1.0 + + (self.particles.random().next_float() - self.particles.random().next_float()) + * 0.2) + * 0.7; + self.audio.play( + "minecraft:entity.generic.explode", + Some(p.center), + 4.0, + pitch, + ); + } + let (world, facts) = (&self.world, self.res.facts()); + self.particles + .explosion(p.center, p.radius, p.block_count.max(0) as usize, &|b| { + facts.is_air(world.block(b[0], b[1], b[2])) + }); + } + + /// `ServerLevel.explode`'s packet to each player within 64 blocks. The + /// sound and the push reach them on their own (the level's sounds, the + /// players' motion), so the packet carries neither. + pub(super) fn lan_explode(&self, center: [f64; 3], radius: f32, block_count: usize) { + let Some(host) = self.lan.as_ref() else { + return; + }; + let particle = |name: &str| { + Some(Particle { + id: host.hub.registry_id("minecraft:particle_type", name)?, + data: None, + }) + }; + let emitter = if radius < 2.0 { + "minecraft:explosion" + } else { + "minecraft:explosion_emitter" + }; + let (Some(at_center), Some(poof), Some(smoke)) = ( + particle(emitter), + particle("minecraft:poof"), + particle("minecraft:smoke"), + ) else { + return; + }; + // Level.DEFAULT_EXPLOSION_BLOCK_PARTICLES. + let info = |particle, scaling| play::ExplosionParticle { + particle, + scaling, + speed: 1.0, + weight: 1, + }; + let packet = C::Explode(play::Explode { + center, + radius, + block_count: block_count as i32, + knockback: None, + particle: at_center, + sound: match host + .hub + .registry_id("minecraft:sound_event", "minecraft:entity.generic.explode") + { + Some(id) => (id, None), + None => (-1, Some(("minecraft:entity.generic.explode".into(), None))), + }, + block_particles: vec![info(poof, 0.5), info(smoke, 1.0)], + play_sound: false, + }); + host.hub.broadcast_near(center, 64.0, &packet, None); + } +} diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index f47dec497..118db7710 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -101,7 +101,7 @@ fn place_interpolated(m: &mut Mob, at: PosRot) { pub(super) struct Remote { pub session: Session, pub brand: String, - builtin: Arc, + pub(super) builtin: Arc, lang: Arc, pub(super) registries: Arc, joined: bool, @@ -1733,6 +1733,8 @@ impl Game<'_> { // level plays them (particles and sounds: a spawner's burst, bone // meal, waxing, a block broken by someone else). C::LevelEvent(p) => self.level_event_at(p.kind, p.pos, p.data), + C::LevelParticles(p) => self.remote_level_particles(&p), + C::Explode(p) => self.remote_explode(&p), C::Sound(p) => { let name = match &p.sound.1 { Some((location, _)) => Some(location.clone()), diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 23ba00699..be3c4eb07 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -7,7 +7,7 @@ use crate::{ Vec3d, Writer, }, chunk::{ChunkData, LightData}, - entity_data::{EntityData, Value}, + entity_data::{EntityData, Particle, Value}, item::{Hashed, HashedSlot, Slot, Stack}, packet, packet_enum, packets::{ @@ -883,6 +883,116 @@ impl Codec for SetObjective { } } } +/// ClientboundLevelParticlesPacket: a particle, whether it ignores the +/// client's particle setting (`overrideLimiter`) and its distance limit +/// (`alwaysShow`), where, the spread and the speed on each axis, how many +/// (0: one, moving by speed times spread) and the randomization type +/// (0 default: gaussian spread and speed). +#[derive(Clone, Debug, PartialEq)] +pub struct LevelParticles { + pub particle: Particle, + pub override_limiter: bool, + pub always_show: bool, + pub pos: [f64; 3], + pub dist: [f32; 3], + pub max_speed: [f32; 3], + pub count: i32, + pub randomization: i32, +} +impl Codec for LevelParticles { + fn read(r: &mut Reader) -> Result { + Ok(Self { + particle: Particle::read(r)?, + override_limiter: r.bool()?, + always_show: r.bool()?, + pos: Vec3d::read(r)?, + dist: [r.f32()?, r.f32()?, r.f32()?], + max_speed: [r.f32()?, r.f32()?, r.f32()?], + count: r.varint()?, + randomization: r.varint()?, + }) + } + fn write(v: &Self, w: &mut Writer) { + v.particle.write(w); + w.bool(v.override_limiter); + w.bool(v.always_show); + Vec3d::write(&v.pos, w); + for f in v.dist.iter().chain(&v.max_speed) { + w.f32(*f); + } + w.varint(v.count); + w.varint(v.randomization); + } +} +/// `ExplosionParticleInfo` in a `WeightedList`: a particle the blast +/// scatters, its scaling and speed, then its weight. +#[derive(Clone, Debug, PartialEq)] +pub struct ExplosionParticle { + pub particle: Particle, + pub scaling: f32, + pub speed: f32, + pub weight: i32, +} +/// ClientboundExplodePacket: the centre, radius and blocks destroyed, the +/// push the receiving player takes, the particle at the centre, the sound, +/// the particles the blast scatters, and whether the sound plays. +#[derive(Clone, Debug, PartialEq)] +pub struct Explode { + pub center: [f64; 3], + pub radius: f32, + pub block_count: i32, + pub knockback: Option<[f64; 3]>, + pub particle: Particle, + pub sound: (i32, Option<(String, Option)>), + pub block_particles: Vec, + pub play_sound: bool, +} +impl Codec for Explode { + fn read(r: &mut Reader) -> Result { + let center = Vec3d::read(r)?; + let radius = r.f32()?; + let block_count = r.i32()?; + let knockback = >::read(r)?; + let particle = Particle::read(r)?; + let sound = SoundHolder::read(r)?; + let n = r.varint()?; + let mut block_particles = Vec::new(); + for _ in 0..n { + block_particles.push(ExplosionParticle { + particle: Particle::read(r)?, + scaling: r.f32()?, + speed: r.f32()?, + weight: r.varint()?, + }); + } + Ok(Self { + center, + radius, + block_count, + knockback, + particle, + sound, + block_particles, + play_sound: r.bool()?, + }) + } + fn write(v: &Self, w: &mut Writer) { + Vec3d::write(&v.center, w); + w.f32(v.radius); + w.i32(v.block_count); + >::write(&v.knockback, w); + v.particle.write(w); + SoundHolder::write(&v.sound, w); + w.varint(v.block_particles.len() as i32); + for b in &v.block_particles { + b.particle.write(w); + w.f32(b.scaling); + w.f32(b.speed); + w.varint(b.weight); + } + w.bool(v.play_sound); + } +} /// `ClientboundSetPlayerTeamPacket.Parameters`. #[derive(Clone, Debug, PartialEq)] pub struct TeamParameters { @@ -1566,6 +1676,8 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { TickingStep(TickingStep) = TICKING_STEP, UpdateAdvancements(UpdateAdvancements) = UPDATE_ADVANCEMENTS, UpdateAttributes(UpdateAttributes) = UPDATE_ATTRIBUTES, + LevelParticles(LevelParticles) = LEVEL_PARTICLES, + Explode(Explode) = EXPLODE, UpdateMobEffect(UpdateMobEffect) = UPDATE_MOB_EFFECT, UpdateTags(UpdateTags) = UPDATE_TAGS, TrackedWaypoint(TrackedWaypoint) = WAYPOINT, @@ -2270,6 +2382,34 @@ mod tests { passengers: vec![3, 300], }), Clientbound::SetEntityLink(SetEntityLink { source: 2, dest: 0 }), + Clientbound::LevelParticles(LevelParticles { + particle: Particle { + id: 21, + data: Some(crate::entity_data::ParticleData::ColorScale(0xFF0000, 1.5)), + }, + override_limiter: true, + always_show: false, + pos: [0.5, 101.0, 3.0], + dist: [0.2, 0.0, 0.2], + max_speed: [0.0; 3], + count: 60, + randomization: 0, + }), + Clientbound::Explode(Explode { + center: [1.0, 2.0, 3.0], + radius: 4.0, + block_count: 12, + knockback: Some([0.5, 0.1, 0.0]), + particle: Particle { id: 29, data: None }, + sound: (-1, Some(("minecraft:entity.generic.explode".into(), None))), + block_particles: vec![ExplosionParticle { + particle: Particle { id: 69, data: None }, + scaling: 0.5, + speed: 1.0, + weight: 1, + }], + play_sound: true, + }), Clientbound::ProjectilePower(ProjectilePower { id: 4, power: 0.1 }), Clientbound::SetEquipment(SetEquipment { id: 2, diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 881443c3f..a00d3afea 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -213,7 +213,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'sidebar', 'border', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'sidebar', 'border', 'particles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] class Game: @@ -2865,6 +2865,43 @@ def check_border(host, guest, out): return result +def check_particles(host, guest, out): + spots = apart(host, guest) + result = {} + for label, player, other in (('host', host, guest), ('guest', guest, host)): + # For the player alone (`@s`), then for every player near. + before = {side: made(g, 'flame') for side, g in (('own', player), ('other', other))} + player('command', command='particle minecraft:flame ~ ~1 ~3 .2 .2 .2 0 60 force @s') + player.wait(10) + result[f'{label} @s'] = {side: made(g, 'flame') - before[side] for side, g in (('own', player), ('other', other))} + player.shot(out, f'flame-{label}') + # No spread: one point, wherever the player stands. + player('command', command='particle minecraft:flame ~ ~1 ~3 0 0 0 0 200 force @s') + player.wait(3) + player.shot(out, f'zero-spread-{label}') + result[f'{label} all'] = sparked(player, other, ['dust'], lambda: player( + 'command', command='particle minecraft:dust{color:[1,0,0],scale:2} ~ ~1 ~3 0 0 0 0 10')) + # A TNT's blast between the players: its burst on both sides. + x, y, z = spots['host'] + host('command', command='gamemode creative') + guest('command', command='gamemode creative') + try: + result['blast'] = sparked(host, guest, ['explosion_emitter'], lambda: host( + 'command', command=f'summon minecraft:tnt {x + 6.5} {y} {z + 4.5} {{fuse:10s}}'), ticks=40) + host.shot(out, 'blast') + finally: + host('command', command='gamemode survival') + guest('command', command='gamemode survival') + host('command', command=f'fill {x - 3} {y - 1} {z - 3} {x + 16} {y - 1} {z + 8} minecraft:stone') + # Without the server thread a guest's command reaches no host player (as `@a` doesn't). + if not SERVER_THREAD: + result['guest all'].pop('other dust') + wrong = {k: v for k, v in result.items() if not k.endswith('@s') and not all(n > 0 for n in v.values())} + wrong.update({k: v for k, v in result.items() if k.endswith('@s') and not (v['own'] >= 30 and v['other'] == 0)}) + assert not wrong, f'particles: {wrong}\n{result}' + return result + + def check_blast(host, guest, out): guest('command', command='gamemode survival') guest('command', command='clear @s') @@ -4203,7 +4240,8 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'sparks': check_sparks, 'hud': check_hud, 'sidebar': check_sidebar, - 'border': check_border} + 'border': check_border, + 'particles': check_particles} def run(ctl, out, resources, checks): From 0e65e8587825144712e797bd9f5ac399ec94cd24 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 11:53:00 +0200 Subject: [PATCH 017/408] Releases: one channel, every release is the latest once its checks pass Ludovic's decision (2026-10-23): no more Alpha and Stable. release.yml publishes every game release as the release and GitHub's latest instead of a pre-release that promote.yml made stable once a day. The checks that gated a promotion run in the release itself: `decide` holds the train while an issue labelled release-blocker is open (forced runs too), and the publish job runs `release_train.py gate` right before publishing: the Mac mini's smoke-test.json must be there and show a world was drawn, and no blocker may be open. Otherwise nothing is published. Notes cover everything since the last release that is not a pre-release, so the first single-channel release lists all of it since v0.2.0. promote.yml, tools/release_channels.py and its tests are deleted. The cadence is unchanged (5 minutes of settling, 20 at most, release-now at once). Docs and site: one channel in release-flow, versioning, security, the FAQ, install, the home page and the Releases page (Game / Launcher filter); no player-facing Alpha wording left. Co-Authored-By: Claude Opus 5.5 --- .github/CODEOWNERS | 1 - .github/workflows/promote.yml | 55 --------- .github/workflows/release.yml | 35 ++++-- docs/release-flow.md | 107 ++++++---------- docs/security.md | 21 ++-- docs/versioning.md | 16 +-- tests/test_release_channels.py | 147 ---------------------- tests/test_release_train.py | 28 ++++- tools/release_channels.py | 220 --------------------------------- tools/release_train.py | 99 ++++++++++----- website/build.mjs | 7 +- website/docs/faq.md | 2 +- website/docs/index.md | 2 +- website/docs/install.md | 13 +- website/docs/multiplayer.md | 2 +- website/docs/settings.md | 4 +- website/src/index.html | 2 +- website/src/main.js | 8 +- website/src/releases.html | 7 +- website/src/releases.js | 6 +- website/src/style.css | 5 +- 21 files changed, 208 insertions(+), 579 deletions(-) delete mode 100644 .github/workflows/promote.yml delete mode 100644 tests/test_release_channels.py delete mode 100644 tools/release_channels.py diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 8d8687753..5567eb184 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -6,7 +6,6 @@ /.github/ @ludovic111 /tools/ci/ @ludovic111 /tools/release_train.py @ludovic111 -/tools/release_channels.py @ludovic111 /crates/horizon-release-sign/ @ludovic111 /crates/horizon-server/src/update.rs @ludovic111 /crates/horizon-server/Cargo.toml @ludovic111 diff --git a/.github/workflows/promote.yml b/.github/workflows/promote.yml deleted file mode 100644 index 3966f571b..000000000 --- a/.github/workflows/promote.yml +++ /dev/null @@ -1,55 +0,0 @@ -name: promote -# Beta game releases become stable once a day (docs/release-flow.md, "Channels"): at 20:00 UTC (21:00 in Paris in -# winter time, 22:00 in summer) tools/release_channels.py promotes the newest beta that had been out 6 hours by then, -# passed its release smoke test and isn't covered by an issue labelled release-blocker. Launchers on the Alpha -# channel install every beta when it is published; Stable gets the day's promotion. The later runs of the evening are -# retries for a run GitHub starts late or skips: they promote the same beta, so stable still moves once. -# By hand, from GitHub's app too (Actions > promote > Run workflow): -# gh workflow run promote -f tag=v0.2.3 # that beta now, without waiting for 20:00 -# gh workflow run promote -f tag=v0.2.3 -f force=true # even blocked or without its smoke test -# gh workflow run promote -f dry_run=true # say what would be promoted -# Holding betas back: label an issue release-blocker. While it is open it holds every beta; closed as completed it -# still holds the betas published before it closed. The issue's text is never read (its author could edit it). -# When the oldest waiting beta is 30 hours old (it missed a promotion it was due for), an issue "Promotion to stable -# has stalled" says so; it closes itself after the next promotion. -on: - schedule: - - cron: '7,37 20-21 * * *' - workflow_dispatch: - inputs: - tag: - description: The beta to promote now (empty = the newest beta that is due) - type: string - default: '' - force: - description: Promote that tag even if a release-blocker covers it or its smoke test didn't run - type: boolean - default: false - dry_run: - description: Say what would be promoted, change nothing - type: boolean - default: false -permissions: - contents: write - issues: write -concurrency: - group: promote - cancel-in-progress: false -jobs: - promote: - runs-on: ubuntu-latest - timeout-minutes: 10 - steps: - - uses: actions/checkout@v4 - with: - # The notes of a promoted release cover every pull request since the last stable one. - fetch-depth: 0 - # gh uses GH_TOKEN below; nothing needs git credentials on disk. - persist-credentials: false - - name: Promote - env: - GH_TOKEN: ${{ github.token }} - TAG: ${{ inputs.tag }} - FORCE: ${{ inputs.force && 'yes' || '' }} - DRY_RUN: ${{ (inputs.dry_run || github.ref != 'refs/heads/main') && 'yes' || '' }} - run: python3 tools/release_channels.py promote ${TAG:+--tag "$TAG"} ${FORCE:+--force} ${DRY_RUN:+--dry-run} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b19ba9ce5..95a2fec64 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -3,12 +3,15 @@ name: release # release waiting for merges to settle goes out without another merge) and by hand, tools/release_train.py decides: # a release when pull requests merged since the last one changed what players run and the newest merged 5 minutes # ago (the oldest 20 minutes ago, if merges never pause), or at once for a pull request labelled release-now. -# RELEASES_PAUSED=1 (repository variable) stops them. +# RELEASES_PAUSED=1 (repository variable) stops them; so does an open issue labelled release-blocker, forced runs too. # Builds Linux (an older Ubuntu, so the binary runs on any recent distribution and on NixOS through nix-ld) and # Windows on GitHub, macOS on the Mac mini's runner (MAC_RUNNER=macos-latest sends it to GitHub), then # publishes vX.Y.Z on the release line in .github/release-line.txt (docs/versioning.md; without it, the dated -# vYYYY.MM.DD[.N] from before 0.2) with notes from the merged pull requests, as a beta (a pre-release) that promote.yml makes -# stable in its daily promotion. macOS: with the repository variable MACOS_SIGN_IDENTITY set, the programs are signed with +# vYYYY.MM.DD[.N] from before 0.2) with notes from the merged pull requests, as the release and GitHub's latest: one +# channel, which launchers, `horizon-server update` and install.sh follow at once. So it is published only after the +# checks that used to gate a promotion pass in this run: the Mac mini's smoke test drew a world, and no release-blocker +# is open (tools/release_train.py gate); otherwise nothing is published. macOS: with the repository variable +# MACOS_SIGN_IDENTITY set, the programs are signed with # Developer ID and the hardened runtime and the zip is notarized, from the runner's signing keychain # (packaging/macos/README.md); unset (forks), ad hoc. # gh workflow run release --ref # dry run: builds and notes, publishes nothing @@ -32,6 +35,8 @@ on: default: false permissions: contents: read + # The open release-blocker issues (decide). + issues: read concurrency: group: game-release cancel-in-progress: false @@ -203,7 +208,7 @@ jobs: or not report.get("meshed_sections") or not report.get("player"): sys.exit("the smoke run did not draw a world") EOF - # Published with the release: a beta becomes stable only with it (tools/release_channels.py). + # Published with the release; the publish job checks it again before it publishes anything. cp "$home/smoke.json" "$RUNNER_TEMP/smoke-test.json" - uses: actions/upload-artifact@v4 if: runner.environment == 'self-hosted' @@ -319,6 +324,7 @@ jobs: timeout-minutes: 15 permissions: contents: write + issues: read steps: - uses: actions/checkout@v4 with: @@ -341,6 +347,17 @@ jobs: run: | key=(); [[ -n "$EPHEMERAL" ]] && key=(--key "$(cat dist/ephemeral.pub)") cargo run --locked --quiet -p horizon-release-sign -- verify --tag "$TAG" --publishing "${key[@]}" dist + - name: Ready to publish (the smoke test passed, no release-blocker is open) + # Right before publishing: an issue labelled while the builds ran still holds this release. A dry run only + # reports what a real run would do. + env: + GH_TOKEN: ${{ github.token }} + DRY_RUN: ${{ needs.decide.outputs.dry_run }} + run: | + if ! python3 tools/release_train.py gate --kind game --smoke dist/smoke-test.json --blockers; then + [[ "$DRY_RUN" == true ]] || { echo "::error::Nothing published"; exit 1; } + echo "::warning::A real run would publish nothing" + fi - name: Publish ${{ needs.decide.outputs.tag }} if: needs.decide.outputs.dry_run != 'true' env: @@ -348,17 +365,15 @@ jobs: TAG: ${{ needs.decide.outputs.tag }} run: | signature=(); [[ -f dist/SHA256SUMS.sig ]] && signature=(dist/SHA256SUMS.sig) - smoke=(); [[ -f dist/smoke-test.json ]] && smoke=(dist/smoke-test.json) - # A beta (pre-release), the Alpha channel's: promote.yml makes it stable and latest in its daily promotion - # (docs/release-flow.md). + # The release and the latest at once: there is one channel (docs/release-flow.md). gh release create "$TAG" --target "${{ needs.decide.outputs.head }}" --title "$(cat notes/title.txt)" \ - --notes-file notes/body.md --prerelease --latest=false dist/horizon-linux-x86_64.tar.gz \ + --notes-file notes/body.md --latest dist/horizon-linux-x86_64.tar.gz \ dist/horizon-windows-x64.zip dist/horizon-macos-arm64.zip dist/horizon-server-linux-x86_64.tar.gz \ - dist/SHA256SUMS "${signature[@]}" "${smoke[@]}" + dist/SHA256SUMS "${signature[@]}" dist/smoke-test.json - name: Dry run, the release that would be published if: needs.decide.outputs.dry_run == 'true' run: | - echo "Would publish ${{ needs.decide.outputs.tag }} at ${{ needs.decide.outputs.head }}: $(cat notes/title.txt)" + echo "Would publish ${{ needs.decide.outputs.tag }} at ${{ needs.decide.outputs.head }} as the release and latest: $(cat notes/title.txt)" ls -l dist - uses: actions/upload-artifact@v4 with: diff --git a/docs/release-flow.md b/docs/release-flow.md index 6cc4bcd3c..72a5c53a9 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -2,9 +2,8 @@ How a change gets from a pull request to players: the checks a pull request passes, how it merges, and the automatic releases that follow. Releases are automatic and frequent so the latest Horizon is always playable. -Each one goes out as an **alpha** build, which launchers on the **Alpha** channel install at once, and becomes **stable** in -the next daily promotion unless something holds it back ([Channels](#channels)): launchers and servers install -stable builds unless their owner picks Alpha. +There is one channel ([One channel](#one-channel)): each release is published as the release and GitHub's *latest* +once its smoke test passed and no `release-blocker` is open, and launchers and servers install it at once. ## Pull request checks @@ -101,12 +100,11 @@ flowchart LR windows["Windows x64
GitHub windows-latest"] mac["macOS arm64
Mac mini runner
+ offscreen game run"] end - build --> publish["publish vX.Y.Z as an alpha
notes from the merged PRs"] - publish --> alpha(["launchers on Alpha install it"]) - publish --> promote{"promote.yml, daily at 20:00 UTC:
6 h old by then, smoke test, no release-blocker"} - promote --> stable["stable and latest
notes since the last stable"] - stable --> launcher(["every launcher and server installs it"]) - stable --> kira(["Kira posts it;
pings only with ### New"]) + build --> gate{"gate: the smoke test drew a world,
no release-blocker is open"} + gate -- no --> nothing(["nothing is published"]) + gate -- yes --> publish["publish vX.Y.Z as the release and latest
notes from the merged PRs"] + publish --> launcher(["every launcher and server installs it"]) + publish --> kira(["Kira posts it; the first release
after 20:00 UTC pings, once a day"]) ``` ### When it releases @@ -121,9 +119,10 @@ commits) since the last **published** game release: - It releases when at least one pull request counts and the newest of them merged at least 5 minutes ago, so a wave of merges becomes one release; if merges never pause, it releases once the oldest has waited 20 minutes. There is no minimum time between releases: every settled player-facing change ships, limited only by the release already - building. That is the Alpha channel, many releases a day. + building: many releases a day. - A pull request labelled `release-now` (a crash or a blocker) releases at once. - A pull request labelled `skip-release` (work players don't see) doesn't count and isn't listed in the notes. +- An open issue labelled `release-blocker` holds every game release, forced ones too (`held by release-blocker #N`). - One release at a time (concurrency group `game-release`); a run that finds nothing new does nothing. - A scheduled or hand-started run releases main's newest commit whose `checks` passed; after `checks`, the commit they passed on. @@ -137,7 +136,7 @@ How releases are numbered, and how installs from before 0.2 reach it: [versionin the patch after the newest release tagged on that line (`v0.2.0` first). A `feature` label doesn't change the line: only that file does, by pull request. - Without the file (every release before 0.2), `vYYYY.MM.DD`, then `.01`, `.02`… the same UTC day. -- Every reader (`release_train.py`, `release_channels.py`, the launcher, `horizon-server update`, the website) ranks +- Every reader (`release_train.py`, the launcher, `horizon-server update`, the website) ranks every `vX.Y.Z` tag above every dated one. ### Labels @@ -149,7 +148,7 @@ How releases are numbered, and how installs from before 0.2 reach it: [versionin | `skip-release` | Doesn't trigger a release and isn't listed in the notes | | `run-parity` | Runs the parity job once on a fork's pull request | | `parity-regression` | Opened by the nightly audit for a harness that fails on main | -| `release-blocker` | On an issue: holds every beta back from stable while it is open ([Channels](#channels)) | +| `release-blocker` | On an issue: no game release is published while it is open ([One channel](#one-channel)) | Pull requests without `feature` are listed under **Fixed**. Titles are written for players, since they become the notes. @@ -180,63 +179,38 @@ runs the game: GitHub's runners have neither a GPU worth the name nor the game f - `### Known issues`: the bullets of [docs/known-issues.md](known-issues.md); - thanks to outside contributors, how to install, the disclaimer. -Kira posts every release in Discord's #releases. An Alpha build (a game pre-release) is posted silently: no ping and -Discord's @silent flag, so nobody gets a notification. When the same release becomes Stable it is posted again, and -that post pings the releases role when the notes have a `### New` section (at most once every 6 hours). Launcher -releases post without a ping. +Kira posts every release once in Discord's #releases. It pings the releases role at most once a day: the first game +release published after 20:00 UTC, with a short list of what came out since its last ping. Every other post is +silent (no ping and Discord's @silent flag). Launcher releases post without a ping. -### Channels +### One channel -Every game release is published as an **alpha** build, a GitHub pre-release (the workflows, tools and labels -call it a *beta*: `release-blocker` holds every beta), so GitHub's *latest* release stays the last -**stable** one. The launcher's Settings has an **Updates** choice of two channels (`update_channel` in its -`settings.json`, `horizon-launcher update-channel`): +Since 2026-10-23 there is one channel. Every game release is published as the release, never a pre-release, and +marked GitHub's *latest*: the launcher, `horizon-server update` and `install.sh` take it at once. Because nothing +promotes it later, the checks that used to gate a promotion run in the release itself, and the publish job +(`tools/release_train.py gate`) publishes nothing unless both pass: -- **Stable**, the default: a tested build about once a day, the alpha builds promoted below. -- **Alpha**: every alpha build as soon as it is built, many times a day; it can break. "Alpha" is the project's - word for builds that are still being tested (the whole of Horizon is in beta); Stable is the tested ones. An open - launcher looks for releases every 30 minutes on Alpha (4 hours on Stable). Launchers from before 0.2 had a "Beta - builds" switch instead; on, it reads as Alpha. +- the release smoke test: the macOS build runs the game offscreen on the Mac mini and keeps its report, + `smoke-test.json`, only when the game drew a world. The gate reads the report again before publishing, and the + release carries it. A run whose macOS build went to GitHub (`MAC_RUNNER=macos-latest`) has no report, so it + publishes nothing; +- no open issue labelled `release-blocker`. `decide` checks first, so a blocked train builds nothing; the gate checks + again right before publishing, so an issue labelled while the builds ran still holds the release. Only the label + and the issue's state count, never its text: whoever opened the issue can edit the text after a maintainer + labels it. Close the issue (or remove the label) and the next run releases everything waiting, with notes + covering all of it. -`horizon-server update` installs stable builds (`--version ` takes an alpha build by name). In Discord's #releases every -Alpha is posted silently and only Stable posts notify (above). +A failed gate fails the run; the next run (10 minutes later) decides again. Nothing older than the latest release is +ever published: tags only count up. -`.github/workflows/promote.yml` runs `tools/release_channels.py promote` once a day at 20:00 UTC (21:00 in Paris in -winter time, 22:00 in summer), with retries until 21:37 for a run GitHub starts late or skips. It promotes the newest -beta that +The launcher has no channel setting any more and looks for releases every 30 minutes. The game pre-releases of the +old Alpha channel (v0.2.1 on, published before this change) stay listed for anyone who wants one by hand, but no +launcher installs them as an update, and `release_train.py` ignores them: the first release of the single channel +lists everything since the last release that was not a pre-release (v0.2.0). Launchers from before this change keep +updating either way: with Alpha (or 0.17's "Beta builds") on they take every release, pre-release or not; with it +off, every release that is not a pre-release, which is now every new one. -- is newer than the stable release, -- had been out 6 hours at 20:00 UTC (published by 14:00 UTC that day; one published later waits for the next day), - so every run of the evening picks the same beta and stable moves once a day, -- passed its release smoke test: the macOS build attaches `smoke-test.json` (the offscreen game run's report) only - when the game drew a world on the Mac mini, so a release built while `MAC_RUNNER` sends macOS to GitHub waits - for a hand, -- and isn't covered by an issue labelled `release-blocker`. An open blocker holds every beta; closed as completed - it still holds the betas published before it closed (they have the bug); closed as not planned it holds - nothing. Only the label and the issue's state count, never its text: whoever opened the issue can edit the - text after a maintainer labels it, so it can't pick which betas go out. - -Nothing older than the stable release is ever promoted, not even with `force`: GitHub's latest release is what -`horizon-server update` and `install.sh` download, so it only moves forward. - -When the oldest beta newer than the stable release has waited 30 hours (it missed a daily promotion it was due for; -on a normal day a beta waits at most that long and is promoted), promote.yml opens an issue titled -"Promotion to stable has stalled" with the reason from the last check (a blocker left open, smoke tests not -running). It closes itself after the next promotion. - -Promoting marks the beta stable and latest and rewrites its notes to list everything since the previous stable -release (`release_train.py notes --stable`), so players who skipped the betas see all of it. Older betas stay -betas. By hand, from a phone too (GitHub app: Actions, promote, Run workflow): - -```sh -gh workflow run promote -f tag=v0.2.3 # that beta now: no wait for 20:00, still no blocker -gh workflow run promote -f tag=v0.2.3 -f force=true # even blocked or without a smoke test -gh workflow run promote -f dry_run=true # what would be promoted now -``` - -An alpha build's notes cover only what changed since the release before it (alpha or stable), and say it is an alpha build. -`release_train.py decide` counts pull requests from the newest release of either channel, so betas don't -release the same changes again. +`promote.yml` and `tools/release_channels.py` (the daily promotion at 20:00 UTC) are gone. ### Signed checksums @@ -298,7 +272,8 @@ gh variable set RELEASES_PAUSED --body 1 # no automatic game or launcher rel gh variable delete RELEASES_PAUSED # back on; the next hourly run catches up ``` -While paused, runs still decide and say why in their summary; `force=true` still releases. +While paused, runs still decide and say why in their summary; `force=true` still releases, but never past an open +`release-blocker`. ### Rolling back @@ -308,8 +283,8 @@ A bad release is withdrawn by turning it back into a draft: gh release edit v0.2.3 --draft ``` -A beta that is not promoted yet needs no rollback: label an issue about it `release-blocker`. For a stable -release: launchers list only published releases, so the previous version becomes the newest one again, launchers that +To stop the next releases while a problem is fixed, label an issue about it `release-blocker`. For the bad +release itself: launchers list only published releases, so the previous version becomes the newest one again, launchers that didn't install the bad one won't, and players who did can pick the previous version in the launcher's version list (`launcher/src/backend.rs` tests `withdrawn_release_is_never_offered`). The tag stays, so the next release that day takes the next number, and its notes start from the last *published* release, so they list the diff --git a/docs/security.md b/docs/security.md index 175e5d21d..886f149d5 100644 --- a/docs/security.md +++ b/docs/security.md @@ -38,7 +38,7 @@ and some are waiting for Ludovic: | Private vulnerability reporting | **Live** (see the end of this page). | | Signed checksums on releases | **Live** for new releases (#1011): the `release` environment holds the key, and its public half is in `release-keys.txt` (#1023). Releases from before then are unsigned. | | Launchers and servers checking signatures | **Not yet**: #1014 waits as a draft until a signed stable game release and a signed launcher release exist. Until then they trust GitHub's checksum, as before. | -| Alpha, then stable | **Live** (#1012): every release is first an alpha build. The launcher's Updates setting picks Stable (the default) or Alpha (the pre-releases). | +| Smoke test and release-blocker before publishing | **Live**: since 2026-10-23 every release is the latest at once (one channel, Ludovic's decision), so it is published only after its smoke test passed and while no `release-blocker` is open. The 6-hour beta of the old Alpha, then stable flow (#1012) is gone. | | Reports marked suspicious | **Partly**: the scan of Discord for agents does it. Kira's issues do it once its pull request merges. | | Code owners' review of the pipeline | **Not yet**: `.github/CODEOWNERS` and its protection (#1015) wait for the App, below. Until then pipeline changes merge like any other once `verify` passes. | | Agents on their own GitHub App | **Not yet**: prepared, waiting for Ludovic to create it. Agents still use his account. | @@ -53,11 +53,10 @@ and some are waiting for Ludovic: - **`verify` always runs.** Labels no longer start the checks, and the required `verify` job has no condition, so the only `verify` a change can have is one that ran. Main requires it, from GitHub Actions only, for everyone, admins included. -- **Alpha, then stable.** Every release is first an **alpha** build (a GitHub pre-release). It becomes **stable**, the version launchers and - servers install by themselves, in the daily promotion (20:00 UTC), only after it has been out 6 hours and passed its - smoke test (the game started and drew a world on the Mac mini), and only while no issue labelled `release-blocker` - is open. If a beta misses a promotion it was due for, an issue says so. Players who want the newest builds at once - pick **Alpha** under Updates in the launcher's Settings. Discord announces stable releases only. +- **Checked before it is published.** Every release is published as the latest, which launchers and servers + install by themselves, so the release run publishes it only after its smoke test passed (the game started and + drew a world on the Mac mini) and only while no issue labelled `release-blocker` is open; otherwise nothing is + published. - **Signed updates.** Each release carries a list of its files' checksums, signed with Horizon's release key. The launcher (for the game and for itself) and `horizon-server update` check that signature against the public key built into them, then check the download against the list. Anything unsigned, signed with another key, signed @@ -78,9 +77,8 @@ and some are waiting for Ludovic: ## What still needs Ludovic - **Approving pipeline changes** (rare): a pull request touching a file in `.github/CODEOWNERS`. -- **Holding a release back or speeding one up**, from his phone if he likes. Label an issue `release-blocker` to - hold every beta until it is closed. Run the `promote` workflow (GitHub app: Actions, - promote, Run workflow) to make a beta stable at once. +- **Holding releases back or speeding one up**, from his phone if he likes. Label an issue `release-blocker` to + hold every release until it is closed; label a pull request `release-now` to release it as soon as it merges. - **Creating the GitHub App**: one link, "Create GitHub App", then "Install". His login, his clicks. - **Fork pull requests**: their checks run only after a maintainer approves them, and they run on the Mac mini only after a maintainer has read them and added `run-parity`. @@ -90,8 +88,9 @@ and some are waiting for Ludovic: ## What this doesn't solve - **Code that merges is code that ships.** Signing proves a build came from Horizon's pipeline, not that the code - is good. Against a bad change, the safety nets are the checks and harnesses, review, the 6-hour beta and the - release-blocker label. + is good. Against a bad change, the safety nets are the checks and harnesses, review, the release smoke test and + the release-blocker label. Since the single channel there is no 6-hour beta: a change reaches every player + within minutes of merging. - **Until agents switch to the App**, they still work with Ludovic's own account, so nothing technical tells his actions from theirs. Code owners' reviews are switched on together with the App. - **The Mac mini** builds the macOS release and also runs pull requests' parity checks: a pull request from this diff --git a/docs/versioning.md b/docs/versioning.md index 6032b54a1..4ed0484e1 100644 --- a/docs/versioning.md +++ b/docs/versioning.md @@ -22,10 +22,10 @@ game and the launcher of the 0.2 line. 0.2. A `feature` label no longer bumps anything: it only lists the change under **New**. - **Patch releases** are every release the train makes: the patch after the newest release tagged on the line, game and launcher counted separately (the game releases more often, so `v0.2.14` can go with `launcher@0.2.3`). -- **Alpha builds** are not separate tags. As before, every game release is published as a GitHub pre-release (an alpha build, what - the launcher's Alpha channel installs) under its final tag and promoted in place to stable in the daily - promotion at 20:00 UTC, once it has been out 6 hours ([Channels](release-flow.md#channels)). `v0.2.4` is the same - build whether it is still a beta or already stable. +- **One channel** (since 2026-10-23): every game release is published under its final tag as the release and + GitHub's latest, once its smoke test passed and no `release-blocker` is open + ([One channel](release-flow.md#one-channel)). The game pre-releases from before (v0.2.1 on, the old Alpha + channel) keep their tags and stay pre-releases. - **Pre-release tags** (`v0.3.0-rc.1`, `v0.3.0-beta.2`) are semver's and are reserved for a hand-made preview of a new line; the train never makes them. Every reader orders them before their release and after the release before (`v0.2.9` < `v0.3.0-beta.1` < `v0.3.0-rc.1` < `v0.3.0`). @@ -43,7 +43,7 @@ Every 0.2 tag is newer than every tag from before 0.2. Within each: A tag is a 0.2 tag when it is `v` or `launcher@` followed by exactly three numbers (and an optional `-PRE`) with a major below 1000; a date's first number is a year, so `v2026.10.21` never is. The rule is written once per language, with the same tests: `crates/horizon-server/src/update.rs` (`newer`), `launcher/src/backend.rs` -(`release_order`), `tools/release_train.py` (`tag_key`, also used by `tools/release_channels.py`) and +(`release_order`), `tools/release_train.py` (`tag_key`) and `website/src/versions.js`. ## The workflows @@ -55,9 +55,6 @@ language, with the same tests: `crates/horizon-server/src/update.rs` (`newer`), - **`launcher.yml`**: `decide --kind launcher` picks `launcher@0.2.N`; the build gets `HORIZON_LAUNCHER_VERSION` (`0.2.N`) and `HORIZON_LAUNCHER_TAG` (`launcher@0.2.N`). The tag tells the launcher which line it is on: a release built with only the version (every launcher before 0.2) is a `launcher-v` one. -- **`promote.yml`**: `tools/release_channels.py` promotes the newest due beta, never one older than the stable - release; with the shared order, `v0.2.0` follows the last dated stable release and no dated beta can follow - `v0.2.0`. - **Notes**: a line's first release (`X.Y.0`) opens with a paragraph saying so; `v0.2.0`'s and `launcher@0.2.0`'s say that releases are numbered from now on, and tell server owners to run `horizon-server update` (or, if their server says it is up to date, `horizon-server update --version v0.2.0`). @@ -98,6 +95,9 @@ the fleet's `release-kick` and the orchestrator's heartbeat prompts. ## The day Ludovic says go +Done on 2026-10-22; kept as the record of how 0.2 went out. `promote.yml` and `tools/release_channels.py`, which +it uses, are gone since the single channel (2026-10-23, [One channel](release-flow.md#one-channel)). + Run by the orchestrator, in this order. Until step 3, nothing is published. 1. Merge, in order: this page, the `horizon-server update` order, the launcher order, the release line (train, diff --git a/tests/test_release_channels.py b/tests/test_release_channels.py deleted file mode 100644 index 288fa7939..000000000 --- a/tests/test_release_channels.py +++ /dev/null @@ -1,147 +0,0 @@ -import datetime as dt -import unittest - -from tools import release_channels as channels -from tools import release_train as train - -# Just after the daily promotion (PROMOTE_AT, 20:00 UTC): a beta is due when it had been out 6 hours by 20:00. -NOW = dt.datetime(2026, 10, 19, 20, 30, tzinfo=dt.timezone.utc) - - -def release(tag, hours_ago, prerelease=True, smoke=True, draft=False): - published = (NOW - dt.timedelta(hours=hours_ago)).isoformat().replace("+00:00", "Z") - assets = [{"name": "horizon-linux-x86_64.tar.gz"}] + ([{"name": channels.SMOKE_ASSET}] if smoke else []) - return {"tag_name": tag, "published_at": published, "prerelease": prerelease, "draft": draft, "assets": assets} - - -def blocker(number, title, body="", state="open", reason=None, closed_hours_ago=None): - closed = None if closed_hours_ago is None else (NOW - dt.timedelta(hours=closed_hours_ago)).isoformat() - return {"number": number, "title": title, "body": body, "state": state, "state_reason": reason, "closed_at": closed} - - -STABLE = release("v2026.10.18.04", 30, prerelease=False) - - -class ReleaseChannelTests(unittest.TestCase): - def test_the_newest_beta_out_six_hours_with_a_smoke_test_is_promoted(self): - releases = [STABLE, release("v2026.10.19", 9), release("v2026.10.19.01", 7), release("v2026.10.19.02", 2)] - chosen, why = channels.choose(releases, [], NOW) - self.assertEqual(chosen["tag_name"], "v2026.10.19.01") - self.assertIn("6 h", why) - - def test_nothing_is_due_before_six_hours(self): - chosen, why = channels.choose([STABLE, release("v2026.10.19", 6)], [], NOW) - self.assertIsNone(chosen, "out 5 h 30 min at 20:00") - self.assertIn("the one at 2026-10-20 20:00 UTC takes it", why) - late = channels.choose([STABLE, release("v2026.10.19", 0.5)], [], NOW)[1] - self.assertIn("the one at 2026-10-20 20:00 UTC takes it", late, "out after 20:00: 6 h by the next one") - - def test_stable_moves_once_a_day_whenever_the_run_starts(self): - hour = dt.timedelta(hours=1) - releases = [STABLE, release("v2026.10.19", 9), release("v2026.10.19.01", 6)] - # Before 20:00 nothing new is due, even what has been out 6 hours by now. - before = channels.choose(releases, [], NOW - hour) - self.assertIsNone(before[0], before[1]) - # The 20:00 run and a late one or a retry pick the same beta; once it is stable, the evening's later runs - # promote nothing, though v2026.10.19.01 has been out 6 hours by then. - for late in (0, 1, 3): - self.assertEqual(channels.choose(releases, [], NOW + late * hour)[0]["tag_name"], "v2026.10.19") - promoted = [release("v2026.10.19", 9, prerelease=False), releases[2]] - self.assertIsNone(channels.choose(promoted, [], NOW + 3 * hour)[0]) - # A run GitHub skipped is caught up by the next one, at any hour before the next day's promotion. - self.assertEqual(channels.choose(releases, [], NOW + 20 * hour)[0]["tag_name"], "v2026.10.19") - # The next day's promotion takes the one that came out too late for today's. - self.assertEqual(channels.choose(promoted, [], NOW + 24 * hour)[0]["tag_name"], "v2026.10.19.01") - self.assertEqual(channels.promotion_time(NOW), dt.datetime(2026, 10, 19, 20, 0, tzinfo=dt.timezone.utc)) - self.assertEqual(channels.promotion_time(NOW - hour), dt.datetime(2026, 10, 18, 20, 0, tzinfo=dt.timezone.utc)) - - def test_a_beta_without_its_smoke_test_waits_for_a_hand(self): - releases = [STABLE, release("v2026.10.19", 8, smoke=False)] - self.assertIsNone(channels.choose(releases, [], NOW)[0]) - self.assertIsNone(channels.choose(releases, [], NOW, tag="v2026.10.19")[0]) - self.assertEqual(channels.choose(releases, [], NOW, tag="v2026.10.19", force=True)[0]["tag_name"], "v2026.10.19") - - def test_by_hand_skips_the_wait_but_not_a_blocker(self): - releases = [STABLE, release("v2026.10.19.02", 1)] - self.assertEqual(channels.choose(releases, [], NOW, tag="v2026.10.19.02")[0]["tag_name"], "v2026.10.19.02") - blocked = [blocker(5, "Crash on start in 2026.10.19.2")] - chosen, why = channels.choose(releases, blocked, NOW, tag="v2026.10.19.02") - self.assertIsNone(chosen) - self.assertIn("#5", why) - self.assertIsNotNone(channels.choose(releases, blocked, NOW, tag="v2026.10.19.02", force=True)[0]) - - def test_stable_releases_and_drafts_are_never_promoted(self): - self.assertIsNone(channels.choose([STABLE], [], NOW, tag=STABLE["tag_name"])[0]) - withdrawn = release("v2026.10.19", 9, draft=True) - self.assertIsNone(channels.choose([STABLE, withdrawn], [], NOW)[0]) - older = release("v2026.10.18.03", 40) - self.assertIsNone(channels.choose([STABLE, older], [], NOW)[0]) - - def test_an_open_blocker_holds_every_beta_whatever_its_text_says(self): - releases = [STABLE, release("v2026.10.19", 12), release("v2026.10.19.01", 10), release("v2026.10.19.02", 8)] - # The issue's author can edit its text after it is labelled: naming a later version must not free a beta. - for text in ("Something is badly wrong", "Only in v2099.01.01", "Since v2026.10.19.01 the chests…"): - chosen, why = channels.choose(releases, [blocker(7, text, body=text)], NOW) - self.assertIsNone(chosen, text) - self.assertIn("release-blocker #7", why) - - def test_a_fixed_blocker_still_holds_the_betas_published_before_the_fix(self): - fixed = blocker(9, "Crash", state="closed", reason="completed", closed_hours_ago=7.5) - releases = [STABLE, release("v2026.10.19", 12), release("v2026.10.19.01", 7)] - self.assertEqual(channels.choose(releases, [fixed], NOW)[0]["tag_name"], "v2026.10.19.01") - self.assertIsNone(channels.choose(releases[:2], [fixed], NOW)[0]) - not_planned = blocker(10, "Crash", state="closed", reason="not_planned", closed_hours_ago=1) - self.assertEqual(channels.choose(releases[:2], [not_planned], NOW)[0]["tag_name"], "v2026.10.19") - - def test_force_never_moves_latest_backwards(self): - # horizon-server update and install.sh download GitHub's latest: an older beta must never become it. - older = release("v2026.10.18.03", 40, smoke=False) - chosen, why = channels.choose([STABLE, older], [blocker(3, "x")], NOW, tag="v2026.10.18.03", force=True) - self.assertIsNone(chosen) - self.assertIn("not newer than the stable v2026.10.18.04", why) - same = release("v2026.10.18.04", 30, prerelease=False) - self.assertIsNone(channels.choose([same], [], NOW, tag="v2026.10.18.04", force=True)[0]) - - def test_0_2_follows_the_dated_releases(self): - bridge = release("v2026.10.21", 30, prerelease=False) - first = release("v0.2.0", 7) - chosen, why = channels.choose([bridge, first], [], NOW) - self.assertEqual(chosen["tag_name"], "v0.2.0", why) - stable = release("v0.2.0", 30, prerelease=False) - older = release("v2026.10.22", 8) - self.assertIsNone(channels.choose([stable, older], [], NOW)[0], "a dated beta never follows 0.2") - chosen, why = channels.choose([stable, older], [], NOW, tag="v2026.10.22", force=True) - self.assertIsNone(chosen) - self.assertIn("not newer than the stable v0.2.0", why) - patch = release("v0.2.1", 7) - self.assertEqual(channels.choose([stable, older, patch], [], NOW)[0]["tag_name"], "v0.2.1") - self.assertEqual(channels.stable([stable, bridge])["tag_name"], "v0.2.0") - launcher = release("launcher@0.2.0", 7) - self.assertIsNone(channels.choose([bridge, launcher], [], NOW)[0], "launcher releases are never game betas") - - def test_a_stall_is_reported_once_the_oldest_waiting_beta_missed_a_daily_promotion(self): - # Out at 14:31 yesterday: just too late for yesterday's 20:00, so 29 h 59 min of waiting is a normal day. - self.assertIsNone(channels.stalled([STABLE, release("v2026.10.19", 29.99), release("v2026.10.19.01", 2)], NOW)) - releases = [STABLE, release("v2026.10.19", 31), release("v2026.10.19.01", 2)] - oldest, age = channels.stalled(releases, NOW) - self.assertEqual(oldest["tag_name"], "v2026.10.19") - title, body = channels.stall_issue(releases, (oldest, age), "no beta is due (release-blocker #4)") - self.assertEqual(title, "Promotion to stable has stalled: v2026.10.19 has waited 31 h") - self.assertIn("v2026.10.18.04", body) - self.assertIn("release-blocker #4", body) - # Betas older than the stable release are contained in it: they aren't waiting. - self.assertIsNone(channels.stalled([STABLE, release("v2026.10.18.03", 40)], NOW)) - self.assertIsNone(channels.stalled([STABLE], NOW)) - - def test_beta_notes_say_so_and_stable_notes_do_not(self): - pr = {"number": 1, "title": "Fix a thing", "labels": [], "paths": ["crates/x.rs"], "issues": [], "author": "ludovic111"} - _, beta = train.notes("game", "v2026.10.19", [pr], [], beta=True) - _, stable = train.notes("game", "v2026.10.19", [pr], [], beta=False) - self.assertIn("This is an alpha build: launchers on the Alpha channel", beta) - self.assertNotIn("alpha", stable.lower()) - _, launcher = train.notes("launcher", "launcher-v0.9.0", [pr], [], beta=True) - self.assertNotIn("alpha", launcher.lower()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_release_train.py b/tests/test_release_train.py index 2a41ae810..298077352 100644 --- a/tests/test_release_train.py +++ b/tests/test_release_train.py @@ -104,7 +104,7 @@ class ReleaseTrainTests(unittest.TestCase): self.assertFalse(train.decision("game", [], NOW)[0]) def test_the_first_release_of_0_2_says_what_changed(self): - title, body = train.notes("game", "v0.2.0", [pr(1)], [], beta=True, previous="v2026.10.21") + title, body = train.notes("game", "v0.2.0", [pr(1)], [], previous="v2026.10.21") self.assertTrue(title.startswith("Horizon 0.2.0: "), title) self.assertTrue(body.startswith("Horizon is numbered from now on: this is Horizon 0.2.0, the release after 2026.10.21.")) self.assertIn("`horizon-server update --version v0.2.0`", body) @@ -132,6 +132,32 @@ class ReleaseTrainTests(unittest.TestCase): self.assertFalse(decide([pr(1)], paused=True)) self.assertTrue(decide([], paused=True, force=True)) + def test_an_open_release_blocker_holds_every_release_even_forced(self): + release, why = train.decision("game", [pr(1, labels=["release-now"])], NOW, blockers=[7, 9]) + self.assertFalse(release) + self.assertEqual(why, "held by release-blocker #7, release-blocker #9") + self.assertFalse(train.decision("game", [], NOW, force=True, blockers=[7])[0]) + self.assertFalse(train.decision("game", [], NOW, new_line="0.3", blockers=[7])[0]) + self.assertTrue(train.decision("game", [pr(1)], NOW, blockers=[])[0]) + + def test_a_release_is_published_only_after_its_smoke_test_and_with_no_blocker(self): + drew = {"error": None, "frames": 12710, "chunks": 81, "meshed_sections": 550, "player": [160.5, 71.0, 156.5]} + self.assertIsNone(train.gate(drew, [])) + self.assertEqual(train.gate(drew, [4]), "release-blocker #4 is open") + self.assertEqual(train.gate(None, []), "no smoke-test.json: the release smoke test did not run") + self.assertEqual(train.gate(None, [4]), + "no smoke-test.json: the release smoke test did not run; release-blocker #4 is open") + self.assertEqual(train.smoke_problem({**drew, "error": "device lost"}), "the smoke run failed: device lost") + for broken in ({**drew, "frames": 1499}, {**drew, "chunks": 0}, {**drew, "meshed_sections": 0}, + {**drew, "player": None}, {}): + self.assertEqual(train.smoke_problem(broken), "the smoke run did not draw a world", broken) + + def test_notes_never_call_a_release_alpha_or_beta(self): + _, body = train.notes("game", "v0.2.12", [pr(1)], []) + self.assertNotIn("alpha", body.lower()) + self.assertNotIn("beta", body.lower()) + self.assertNotIn("Stable", body) + def test_notes(self): prs = [pr(5, "Nether portals: vanilla timing and linking (fixes #94)", issues=[94]), pr(6, "Controllers: gilrs input layer and gameplay", labels=["feature"], author="cosmic"), diff --git a/tools/release_channels.py b/tools/release_channels.py deleted file mode 100644 index 869127c5c..000000000 --- a/tools/release_channels.py +++ /dev/null @@ -1,220 +0,0 @@ -#!/usr/bin/env python3 -"""Promotes Horizon's beta game releases to stable once a day (.github/workflows/promote.yml, docs/release-flow.md). - - python3 tools/release_channels.py promote # the newest beta that is due, if any - python3 tools/release_channels.py promote --tag v2026.10.19.03 # that beta now (by hand) - python3 tools/release_channels.py promote --tag v2026.10.19.03 --force # even if blocked or untested - python3 tools/release_channels.py promote --dry-run # say what would happen, change nothing - -Every game release goes out as a beta (a GitHub pre-release): launchers on the Alpha channel install it at once. -Stable moves once a day, at PROMOTE_AT (20:00 UTC). A beta is due for stable when: -- it is newer than the stable release (GitHub's "latest", which launchers and servers install by default), -- it had been out PROMOTE_AFTER (6 hours) at the day's promotion time, so every run until the next one picks the - same beta and a run GitHub starts late (or a second try) never promotes twice; by hand (--tag) skips the wait, -- its release smoke test passed: release.yml attaches smoke-test.json only after the Mac mini ran the game, -- and no issue labelled release-blocker covers it. An open blocker holds every beta; one closed as completed keeps - holding the betas published before it closed (they still have the bug); one closed as not planned holds nothing. - Only people who can triage the repository can add the label, and the issue's text is never read: whoever wrote - the issue could edit it afterwards, so it can't decide which betas go out. - -The newest due beta is promoted: marked stable and latest, with notes covering everything since the previous -stable release (tools/release_train.py notes --stable). Older betas stay betas: the stable one contains them. -Nothing older than the current stable release is ever promoted, even with --force: GitHub's "latest" is what -horizon-server update and install.sh download, and it only moves forward. - -When the oldest beta newer than the stable release has waited STALL_AFTER (30 hours: past one daily promotion it -was due for, so a normal day never trips it), promotion has stalled -(blocked, smoke tests not running, the schedule off): an issue says so, and is closed once a beta is promoted. -""" - -import argparse -import datetime as dt -import json -import os -from pathlib import Path -import subprocess -import sys -import tempfile - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -from tools.release_train import is_game_tag, tag_key # noqa: E402 (vYYYY.MM.DD[.N] and v0.2.0: docs/versioning.md) - -REPO = os.environ.get("GITHUB_REPOSITORY", "ludovic111/horizon") -PROMOTE_AFTER = dt.timedelta(hours=6) -# The daily promotion (21:00 in Paris in winter time, 22:00 in summer); promote.yml's schedule runs just after it. -PROMOTE_AT = dt.time(20, 0) -SMOKE_ASSET = "smoke-test.json" -BLOCKER = "release-blocker" -STALL_AFTER = dt.timedelta(hours=30) -STALLED = "Promotion to stable has stalled" - - -def parse_time(text): - return dt.datetime.fromisoformat(text.replace("Z", "+00:00")) if text else None - - -def covers(blocker, release): - """Whether a release-blocker issue holds this beta back. Only its state and dates count, never its text.""" - if blocker.get("state") != "closed": - return True - closed = parse_time(blocker.get("closed_at")) - return blocker.get("state_reason") == "completed" and bool(closed) and parse_time(release["published_at"]) < closed - - -def promotion_time(now): - """The last daily promotion time (PROMOTE_AT, UTC) at or before now.""" - now = now.astimezone(dt.timezone.utc) - at = dt.datetime.combine(now.date(), PROMOTE_AT, dt.timezone.utc) - return at if at <= now else at - dt.timedelta(days=1) - - -def stable(releases): - """The newest stable (non pre-release) game release.""" - stables = [r for r in releases if not r["prerelease"]] - return max(stables, key=lambda r: tag_key(r["tag_name"]), default=None) - - -def reasons_against(release, current, blockers, now, by_hand=False): - """Why this beta can't become stable now: an empty list when it can.""" - reasons = [] - if not release["prerelease"]: - reasons.append("it is already stable") - if current and tag_key(release["tag_name"]) <= tag_key(current["tag_name"]): - reasons.append(f"it is not newer than the stable {current['tag_name']}") - ready = parse_time(release["published_at"]) + PROMOTE_AFTER - if not by_hand and ready > promotion_time(now): - due = promotion_time(ready) - due += dt.timedelta(days=1 if due < ready else 0) - reasons.append(f"it had not been out {PROMOTE_AFTER.seconds // 3600} h at a daily promotion yet: " - f"the one at {due:%Y-%m-%d %H:%M} UTC takes it") - if not any(asset["name"] == SMOKE_ASSET for asset in release.get("assets", [])): - reasons.append(f"it has no {SMOKE_ASSET}: the release smoke test did not run") - for blocker in blockers: - if covers(blocker, release): - reasons.append(f"release-blocker #{blocker['number']}") - return reasons - - -def choose(releases, blockers, now, tag=None, force=False): - """(the beta to promote or None, a line saying why) for the game releases `releases`.""" - games = [r for r in releases if not r["draft"] and is_game_tag(r["tag_name"])] - current = stable(games) - if tag: - release = next((r for r in games if r["tag_name"] == tag), None) - if not release: - return None, f"no published game release is tagged {tag}" - reasons = reasons_against(release, current, blockers, now, by_hand=True) - if force: - # Even forced, "latest" only moves forward: horizon-server update and install.sh follow it. - reasons = [r for r in reasons if r == "it is already stable" or r.startswith("it is not newer")] - if reasons: - return None, f"{tag} stays a beta: " + "; ".join(reasons) - return release, f"{tag} promoted by hand" + (" with force" if force else "") - betas = sorted((r for r in games if r["prerelease"]), key=lambda r: tag_key(r["tag_name"]), reverse=True) - held = [] - for release in betas: - reasons = reasons_against(release, current, blockers, now) - if not reasons: - return release, f"{release['tag_name']} had been out {PROMOTE_AFTER.seconds // 3600} h at the daily promotion, " \ - "passed its smoke test and no release-blocker covers it" - held.append(f"{release['tag_name']}: " + "; ".join(reasons)) - return None, "no beta is due" + (" (" + " / ".join(held[:3]) + ")" if held else "") - - -def stalled(releases, now): - """(the oldest beta newer than the stable release, how long it has waited) once that is STALL_AFTER, else None.""" - games = [r for r in releases if not r["draft"] and is_game_tag(r["tag_name"])] - current = stable(games) - waiting = [r for r in games if r["prerelease"] and (not current or tag_key(r["tag_name"]) > tag_key(current["tag_name"]))] - if not waiting: - return None - oldest = min(waiting, key=lambda r: parse_time(r["published_at"])) - age = now - parse_time(oldest["published_at"]) - return (oldest, age) if age >= STALL_AFTER else None - - -def stall_issue(releases, stall, reason): - """The title and body of the issue saying promotion has stalled.""" - oldest, age = stall - current = stable([r for r in releases if not r["draft"] and is_game_tag(r["tag_name"])]) - hours = int(age.total_seconds() // 3600) - body = (f"Opened by .github/workflows/promote.yml, not by a person.\n\n" - f"No beta has become stable for {hours} hours: {oldest['tag_name']} has waited since " - f"{oldest['published_at']}, and launchers, servers and install.sh still get " - f"{current['tag_name'] if current else 'no stable release'}.\n\n" - f"The last check said: {reason}\n\n" - "Usual causes: an open `release-blocker` issue (it holds every beta until it is closed), the Mac mini's " - "release smoke test not running (no smoke-test.json on the betas), or the promote workflow disabled. " - "To promote a beta by hand: `gh workflow run promote -f tag=` (add `-f force=true` to skip the " - "smoke test and blockers). This issue closes itself once a beta is promoted.") - return f"{STALLED}: {oldest['tag_name']} has waited {hours} h", body - - -def gh(*arguments, capture=True): - result = subprocess.run(["gh", *arguments], cwd=ROOT, capture_output=capture, text=True) - if result.returncode: - raise SystemExit(f"gh {' '.join(arguments)}: {(result.stderr or '').strip()}") - return result.stdout - - -def gh_pages(path): - return [item for page in json.loads(gh("api", path, "--paginate", "--slurp") or "[]") for item in page] - - -def promote(release): - """Marks the beta stable and latest, with notes covering everything since the previous stable release.""" - tag = release["tag_name"] - with tempfile.TemporaryDirectory() as out: - subprocess.run([sys.executable, str(ROOT / "tools" / "release_train.py"), "notes", "--kind", "game", "--tag", tag, - "--head", tag, "--stable", "--out", out], cwd=ROOT, check=True, stdout=subprocess.DEVNULL) - title = (Path(out) / "title.txt").read_text().strip() - gh("release", "edit", tag, "--repo", REPO, "--prerelease=false", "--latest", "--title", title, - "--notes-file", str(Path(out) / "body.md")) - - -def main(): - parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument("command", choices=["promote"]) - parser.add_argument("--tag", help="promote this beta now (by hand: no wait for the daily promotion)") - parser.add_argument("--force", action="store_true", help="with --tag: even without a smoke test or with a blocker") - parser.add_argument("--dry-run", action="store_true", help="say what would be promoted, change nothing") - parser.add_argument("--now", help="the time to decide at (ISO 8601; default now)") - args = parser.parse_args() - if args.force and not args.tag: - parser.error("--force needs --tag: only a named beta is forced") - now = dt.datetime.fromisoformat(args.now) if args.now else dt.datetime.now(dt.timezone.utc) - now = now if now.tzinfo else now.replace(tzinfo=dt.timezone.utc) - releases = gh_pages(f"repos/{REPO}/releases?per_page=100") - blockers = [issue for issue in gh_pages(f"repos/{REPO}/issues?labels={BLOCKER}&state=all&per_page=100") - if "pull_request" not in issue] - release, reason = choose(releases, blockers, now, args.tag, args.force) - if release and not args.dry_run: - promote(release) - line = ("Would promote: " if release and args.dry_run else "") + reason - print(line) - if os.environ.get("GITHUB_STEP_SUMMARY"): - with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as summary: - summary.write(f"### {line}\n") - report_stall(releases, release, reason, now, args.dry_run) - return 1 if args.tag and not release else 0 - - -def report_stall(releases, promoted, reason, now, dry_run): - """Opens the stalled-promotion issue when one is due and none is open; closes it after a promotion.""" - open_issues = [issue for issue in gh_pages(f"repos/{REPO}/issues?state=open&per_page=100") - if "pull_request" not in issue and issue["title"].startswith(STALLED)] - stall = None if promoted else stalled(releases, now) - if stall and not open_issues: - title, body = stall_issue(releases, stall, reason) - print(("Would open: " if dry_run else "Opening: ") + title) - if not dry_run: - gh("issue", "create", "--repo", REPO, "--title", title, "--body", body) - if promoted and not dry_run: - for issue in open_issues: - gh("issue", "close", str(issue["number"]), "--repo", REPO, "--comment", - f"{promoted['tag_name']} is stable now (promote.yml).") - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tools/release_train.py b/tools/release_train.py index 0cc37eef7..b8d6468bb 100644 --- a/tools/release_train.py +++ b/tools/release_train.py @@ -4,13 +4,14 @@ python3 tools/release_train.py decide --kind game [--head SHA] [--force] python3 tools/release_train.py decide --kind launcher python3 tools/release_train.py notes --kind game --tag v2026.10.15 --out dist/notes - python3 tools/release_train.py notes --kind game --tag v2026.10.15 --head v2026.10.15 --stable # at promotion + python3 tools/release_train.py gate --kind game --smoke dist/smoke-test.json [--blockers] # before publishing A kind releases when a pull request merged into main since its last published release changed one of its player-facing paths (GAME_PATHS, LAUNCHER_PATHS) and the newest of them merged at least DEBOUNCE ago (a burst of merges becomes one release), or the oldest at least MAX_WAIT ago (merges that never pause still ship), or when one of those pull requests is labelled release-now. Pull requests labelled skip-release (work players don't see) don't count -towards a release and aren't listed in the notes. RELEASES_PAUSED=1 (a repository variable) stops automatic releases. +towards a release and aren't listed in the notes. RELEASES_PAUSED=1 (a repository variable) stops automatic releases, +and an open issue labelled release-blocker stops game releases, even forced ones, until it is closed. Tags (docs/versioning.md): with a release line in .github/release-line.txt (MAJOR.MINOR, e.g. 0.2), game releases are vMAJOR.MINOR.PATCH and launcher releases launcher@MAJOR.MINOR.PATCH, each the patch after the last tag of its kind @@ -19,9 +20,11 @@ file, the tags from before 0.2: vYYYY.MM.DD, then .01, .02 the same UTC day, and the last launcher tag or the next minor when a merged pull request is labelled feature. Every 0.2 tag is newer than every tag from before (tag_key). Notes: "### New" lists the pull requests labelled feature, "### Fixed" the others, "### Known issues" the bullets of -docs/known-issues.md. Game releases go out as betas (GitHub pre-releases) and tools/release_channels.py promotes -them to stable; a beta's notes cover what changed since the release before it (beta or stable), a promoted -release's (--stable) everything since the last stable one. See docs/release-flow.md. +docs/known-issues.md. Every release is published as the release, GitHub's latest, which launchers, servers and +install.sh take at once; one channel, no promotion. A game release is published only after `gate`: its smoke test +passed and no release-blocker is open. Notes cover everything since the last published release; the game +pre-releases of the old Alpha channel (v0.2.1 on) don't count, so the first release after them lists all of +it since v0.2.0. See docs/release-flow.md. Prints the decision as JSON and writes it to $GITHUB_OUTPUT when set. Needs git history and the gh CLI. """ @@ -37,7 +40,7 @@ import sys ROOT = Path(__file__).resolve().parents[1] REPO = os.environ.get("GITHUB_REPOSITORY", "ludovic111/horizon") -# Alpha builds ship constantly: a merge starts a release within minutes, once its wave of merges has settled. +# Releases ship constantly: a merge starts a release within minutes, once its wave of merges has settled. DEBOUNCE = dt.timedelta(minutes=5) MAX_WAIT = dt.timedelta(minutes=20) # Kept as typed in release titles, where the clauses after the first are lowercased. @@ -72,12 +75,13 @@ LAUNCHER_IGNORED = ["launcher/links.json", "launcher/docs/", "launcher/tests/"] FOOTER = { "game": "Install or update it from the Horizon launcher: it installs new versions by itself. " "New here? Get the launcher at https://playhorizon.dev. You need your own copy of Minecraft: Java Edition.", - "beta": "This is an alpha build: launchers on the Alpha channel (Settings, Updates) install it now; Stable gets it " - "in the next daily update if it holds up.", "launcher": "Your launcher updates itself. New here? Download the archive for your system below, extract it, " "and run `horizon-launcher`. Website: https://playhorizon.dev", } DISCLAIMER = "Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft." +# An open issue with this label holds every game release (docs/release-flow.md). Only people who can triage the +# repository can add it, and the issue's text is never read: its author could edit it afterwards. +BLOCKER = "release-blocker" def run(*command, check=True): @@ -225,11 +229,37 @@ def pull_request(number): } -def published_releases(betas=True): - """Published (not draft) releases with their tags and dates; without betas (pre-releases) when betas is False.""" +def published_releases(): + """Published releases with their tags and dates: no drafts, and no pre-releases (the old Alpha channel's).""" releases = gh_json("api", f"repos/{REPO}/releases?per_page=100", "--paginate", "--slurp") flat = [release for page in releases for release in page] - return [release for release in flat if not release["draft"] and (betas or not release["prerelease"])] + return [release for release in flat if not release["draft"] and not release["prerelease"]] + + +def open_blockers(): + """The numbers of the open issues labelled release-blocker (pull requests left out).""" + issues = gh_json("api", f"repos/{REPO}/issues?labels={BLOCKER}&state=open&per_page=100", "--paginate", "--slurp") + return sorted(issue["number"] for page in issues for issue in page if "pull_request" not in issue) + + +def smoke_problem(report): + """Why a release smoke test's report (the game's --smoke-report) fails, or None when the game drew a world.""" + if report is None: + return "no smoke-test.json: the release smoke test did not run" + if report.get("error") is not None: + return f"the smoke run failed: {report['error']}" + if report.get("frames", 0) < 1500 or not report.get("chunks") or not report.get("meshed_sections") \ + or not report.get("player"): + return "the smoke run did not draw a world" + return None + + +def gate(report, blockers): + """Why a built game release must not be published, or None: it is published as the latest at once, so its + smoke test must have passed and no release-blocker may be open.""" + problems = [problem for problem in [smoke_problem(report)] if problem] + problems += [f"release-blocker #{number} is open" for number in blockers] + return "; ".join(problems) or None def last_release(releases, kind): @@ -238,13 +268,16 @@ def last_release(releases, kind): return max(ours, key=lambda release: tag_key(release["tag_name"]), default=None) -def decision(kind, prs, now, paused=False, force=False, new_line=None): +def decision(kind, prs, now, paused=False, force=False, new_line=None, blockers=()): """Whether to release now, and why. prs: the merged pull requests since the last release, each with the files it changed under "paths" (player-facing ones only) and when it merged ("merged_at"). new_line: the - release line ("0.2") when it has no release of this kind yet; its first goes out at once.""" + release line ("0.2") when it has no release of this kind yet; its first goes out at once. blockers: the open + release-blocker issues; they hold every release, forced ones too.""" counted = [pr for pr in prs if pr["paths"] and "skip-release" not in pr["labels"]] urgent = [pr for pr in counted if "release-now" in pr["labels"]] merged = [pr["merged_at"] for pr in counted if pr.get("merged_at")] + if blockers: + return False, "held by " + ", ".join(f"release-blocker #{number}" for number in blockers) if force: return True, "started by hand with force" if paused: @@ -323,9 +356,8 @@ def line_intro(kind, version, previous): f"`horizon-server update --version {version}`.") -def notes(kind, version, prs, issues, beta=False, previous=None): - """(title, body) of a release; a game beta's say it is one. previous: the release before it, for a line's - first release.""" +def notes(kind, version, prs, issues, previous=None): + """(title, body) of a release. previous: the release before it, for a line's first release.""" shown = [pr for pr in prs if pr["paths"] and "skip-release" not in pr["labels"]] new = [pr for pr in shown if "feature" in pr["labels"]] fixed = [pr for pr in shown if "feature" not in pr["labels"]] @@ -346,17 +378,15 @@ def notes(kind, version, prs, issues, beta=False, previous=None): contributors = sorted({pr["author"] for pr in shown if pr["author"] and pr["author"] != REPO.split("/")[0]}) if contributors: parts.append("Thanks to " + ", ".join(f"@{name}" for name in contributors) + ".") - if beta and kind == "game": - parts.append(FOOTER["beta"]) parts.append(FOOTER[kind]) parts.append(DISCLAIMER) return title, "\n\n".join(parts) + "\n" -def gather(kind, head, releases=None, betas=True): - """The last published release of this kind (stable only when betas is False) and the pull requests merged - since, with their player-facing paths.""" - releases = published_releases(betas) if releases is None else releases +def gather(kind, head, releases=None): + """The last published release of this kind and the pull requests merged since, with their player-facing + paths.""" + releases = published_releases() if releases is None else releases last = last_release(releases, kind) base = last["tag_name"] if last else run("git", "rev-list", "--max-parents=0", head).split()[0] exporter_paths = exporters() @@ -387,18 +417,29 @@ def write_outputs(values): def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument("command", choices=["decide", "notes"]) + parser.add_argument("command", choices=["decide", "notes", "gate"]) parser.add_argument("--kind", choices=["game", "launcher"], required=True) parser.add_argument("--head", help="the commit to release (default: the newest commit on main whose checks passed)") parser.add_argument("--tag", help="notes: the release's tag") parser.add_argument("--force", action="store_true", help="release even without player-facing changes, before merges settle or while paused") parser.add_argument("--out", type=Path, help="notes: write title.txt and body.md here") parser.add_argument("--now", help="the time to decide at (ISO 8601; default now)") - parser.add_argument("--stable", action="store_true", - help="notes: for promoting a beta to stable, so since the last stable release, without the beta line") + parser.add_argument("--smoke", type=Path, help="gate: the release smoke test's report (smoke-test.json)") + parser.add_argument("--blockers", action="store_true", help="gate: also check that no release-blocker is open") args = parser.parse_args() now = dt.datetime.fromisoformat(args.now) if args.now else dt.datetime.now(dt.timezone.utc) + if args.command == "gate": + report = json.loads(args.smoke.read_text()) if args.smoke and args.smoke.exists() else None + problem = gate(report, open_blockers() if args.blockers else []) + line = f"Not publishing: {problem}" if problem else "Ready to publish: the smoke test passed" + ( + " and no release-blocker is open" if args.blockers else "") + print(json.dumps(report) if report else "", line, sep="\n") + if os.environ.get("GITHUB_STEP_SUMMARY"): + with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as summary: + summary.write(f"### {line}\n") + return 1 if problem else 0 + head = args.head or green_main_head() if not head: result = {"release": False, "reason": "main's latest checks did not pass"} @@ -406,11 +447,11 @@ def main(): write_outputs({"release": "false", "reason": result["reason"]}) return 0 head = run("git", "rev-parse", head).strip() - last, prs = gather(args.kind, head, betas=not args.stable) + last, prs = gather(args.kind, head) if args.command == "notes": version = args.tag or "unreleased" previous = last["tag_name"] if last and last["tag_name"] != version else None - title, body = notes(args.kind, version, prs, known_issues(), beta=not args.stable, previous=previous) + title, body = notes(args.kind, version, prs, known_issues(), previous=previous) if args.out: args.out.mkdir(parents=True, exist_ok=True) (args.out / "title.txt").write_text(title + "\n") @@ -422,7 +463,9 @@ def main(): line = release_line() prefix = GAME_PREFIX if args.kind == "game" else LAUNCHER_PREFIX new_line = f"{line[0]}.{line[1]}" if line and first_on_line(tags, prefix, line) else None - release, reason = decision(args.kind, prs, now, os.environ.get("RELEASES_PAUSED") == "1", args.force, new_line) + blockers = open_blockers() if args.kind == "game" else [] + release, reason = decision(args.kind, prs, now, os.environ.get("RELEASES_PAUSED") == "1", args.force, new_line, + blockers) minor = any("feature" in pr["labels"] for pr in prs if pr["paths"]) tag = next_game_tag(tags, now.date(), line) if args.kind == "game" else next_launcher_tag(tags, minor, line) result = { diff --git a/website/build.mjs b/website/build.mjs index a47a40a79..781e838bb 100644 --- a/website/build.mjs +++ b/website/build.mjs @@ -55,7 +55,8 @@ try { if (batch.length < 100) break; } if (!res.ok) console.warn(`releases: ${res.status} from GitHub; the pages will load them themselves`); - // A day of betas can push the stable release out of the newest 100: it is GitHub's "latest" (betas never are). + // Pre-releases of the old Alpha channel could push the newest release out of the newest 100: it is GitHub's + // "latest" (pre-releases never are). if (res.ok && !releases.some((r) => isGame(r.tag_name) && !r.prerelease)) { const latest = await fetch(`https://api.github.com/repos/${REPO}/releases/latest`, { headers: githubHeaders, signal: AbortSignal.timeout(15000) }); if (latest.ok) releases.push(await latest.json()); @@ -121,8 +122,8 @@ const parityHeadline = matching === body.length ? "Every subsystem matches vanil // --- The releases ---------------------------------------------------------------------- -// Newest first by tag: every 0.2 tag is newer than the dated ones (src/versions.js). Alpha builds are GitHub -// pre-releases, Stable the others (docs/release-flow.md, "Channels"). +// Newest first by tag: every 0.2 tag is newer than the dated ones (src/versions.js). One channel since 2026-10-23 +// (docs/release-flow.md, "One channel"); the old Alpha channel's pre-releases stay listed. const byTag = (a, b) => newestFirst(a.tag_name, b.tag_name); const ours = releases.filter((r) => isGame(r.tag_name) || isLauncher(r.tag_name)).sort(byTag); const game = ours.filter((r) => isGame(r.tag_name)); diff --git a/website/docs/faq.md b/website/docs/faq.md index 6793c7e8f..666766c6b 100644 --- a/website/docs/faq.md +++ b/website/docs/faq.md @@ -60,7 +60,7 @@ Only if you say yes, and each kind has its own switch. Everything is off by defa ## How often does it update? -Often. Every change players can see is released automatically after it is merged, so new versions can come out several times a day. On the **Alpha** channel the launcher installs each one as soon as it is built; on **Stable**, the default, it installs a tested build about once a day. See [Install](/docs/install#updating). +Often. Every change players can see is released automatically after it is merged, so new versions can come out several times a day. Each one is tested before it goes out (the game has to start and draw a world), and the launcher installs it as soon as it is out. There is one version for everyone. See [Install](/docs/install#updating). ## What do the version numbers mean? diff --git a/website/docs/index.md b/website/docs/index.md index e146e520c..2b16c4db9 100644 --- a/website/docs/index.md +++ b/website/docs/index.md @@ -7,7 +7,7 @@ Horizon is Minecraft: Java Edition 26.3 rewritten in Rust. You install it with a - **A new game program, not a mod.** Horizon is written from scratch in Rust. It reads the same worlds, plays by the same rules and generates the same terrain as the Java game. - **Checked against vanilla.** {{HARNESSES}} automated tests ("harnesses") feed the same inputs to Horizon and to the real game, then compare the results. Today every subsystem matches in every harness that compares it. That is {{PERCENT}} of what the harnesses compare, which is not proof that nothing else differs. The [status table](/#parity) lists what is covered. - **Light and fast.** It starts quickly, uses little memory and draws efficiently. See [Performance](/docs/performance) for what is measured and what is not. -- **A few things vanilla doesn't have.** Its own settings, added to vanilla's menus the way mods add theirs, graphics presets, distant terrain, controller support, optional extras such as zoom, a minimap and dynamic lights (dynamic lights are in Alpha builds for now), an invite code to play your world with friends, and a server you can run without Java. +- **A few things vanilla doesn't have.** Its own settings, added to vanilla's menus the way mods add theirs, graphics presets, distant terrain, controller support, optional extras such as zoom, a minimap and dynamic lights, an invite code to play your world with friends, and a server you can run without Java. ## What Horizon is not diff --git a/website/docs/install.md b/website/docs/install.md index b6ecdff7d..c1a65f3ee 100644 --- a/website/docs/install.md +++ b/website/docs/install.md @@ -34,19 +34,14 @@ The game opens on vanilla's title screen. Your worlds, options and logs live in ## Updating -- **Horizon.** The launcher looks for a new release when it starts and every four hours while it is open. With **Install new versions automatically** on (the default), it installs one and moves you to it if you were on the newest. New releases come out many times a day, and old versions stay installed until you remove them on the **Versions** page. +- **Horizon.** The launcher looks for a new release when it starts and every 30 minutes while it is open. With **Install new versions automatically** on (the default), it installs one and moves you to it if you were on the newest. New releases come out many times a day, and old versions stay installed until you remove them on the **Versions** page. - **The launcher.** It updates itself from its own releases, then shows **Restart** in its footer. A launcher from before 0.2 (0.16 or older) updates twice in a row: first to 0.17, then to 0.2. Then it installs Horizon 0.2 like any update. -## Stable and Alpha +## One version for everyone -> **Next launcher release.** The Updates switch below is merged but not in a launcher release yet. Launcher 0.17 has a **Beta builds** switch in Settings instead, which installs every new build at once, as Alpha does. +There is one channel: every release is the version everyone gets. Before a release goes out, the game has to start and draw a world on our test machine, and nothing goes out while a serious problem is open. New releases come out many times a day, and you can install any older version by hand on the **Versions** page. -In **Settings**, **Updates** picks which builds install by themselves: - -- **Stable** (the default): a tested build about once a day. -- **Alpha**: every change as soon as it is built, several times a day. It can break. A launcher left open looks for new builds every 30 minutes, instead of every four hours. - -Every new release is an Alpha build first. Once a day (20:00 UTC, 21:00 in Paris in winter), the newest one that has been out for six hours, passed its smoke test and has no known blocker becomes Stable. Alpha builds come out many times a day, and Horizon as a whole is still in beta; Stable is the tested ones. The **Versions** page shows each version's channel, and you can install any of them by hand. +Launchers from before this change still show an **Updates** choice in Settings. Either option now gets every new release, and the choice goes away once the launcher has updated itself. ## The Versions page diff --git a/website/docs/multiplayer.md b/website/docs/multiplayer.md index b45ece0a9..e344c8fbc 100644 --- a/website/docs/multiplayer.md +++ b/website/docs/multiplayer.md @@ -20,7 +20,7 @@ There is no Horizon server in the middle. The code holds the host's addresses an Guests join with the name their game uses. There is no account check, so only share the code with people you trust. -In Alpha builds, guests can also use the host's workstations: the crafter, loom, stonecutter, grindstone, anvil, smithing table, enchanting table, beacon, lectern and cartography table. Stable gets this once it has passed. +Guests can also use the host's workstations: the crafter, loom, stonecutter, grindstone, anvil, smithing table, enchanting table, beacon, lectern and cartography table. ## Open to LAN diff --git a/website/docs/settings.md b/website/docs/settings.md index e1860cd4a..b3566ff2f 100644 --- a/website/docs/settings.md +++ b/website/docs/settings.md @@ -46,7 +46,7 @@ Shader packs are **experimental**. Put a pack's folder in the `shaderpacks` fold Horizon can run the full-screen effects of Java shader packs (OptiFine and Iris packs: colour grading, bloom, sky and fog effects). It does not run their geometry and shadow passes yet, so packs do not look as they do in Iris. Horizon also has its own shader pack format, in WGSL, with a `pack.toml` manifest, options and hot reload. It has full-screen passes too; stages that draw the world's terrain and shadows are planned. The details are in the [shader pack notes](https://github.com/ludovic111/horizon/blob/main/docs/shader-packs.md). -In Alpha builds, the **Shader Packs** page shows the full path of the `shaderpacks` folder with an **Open Folder** button, then one switch per pack. Turning a pack on picks it, and turning it off gives the vanilla picture. Packs tested so far: BSL, Complementary Reimagined, Steadfast and Sildur's Vibrant Extreme draw their full-screen passes; Bliss, Bloop, Noble, Photon and Rethinking Voxels do not load yet. To find packs, the launcher's **Mods** page installs shader packs from Modrinth (see [Mods and data packs](/docs/mods#finding-resource-packs-shader-packs-and-modpacks)). +The **Shader Packs** page shows the full path of the `shaderpacks` folder with an **Open Folder** button, then one switch per pack. Turning a pack on picks it, and turning it off gives the vanilla picture. Packs tested so far: BSL, Complementary Reimagined, Steadfast and Sildur's Vibrant Extreme draw their full-screen passes; Bliss, Bloop, Noble, Photon and Rethinking Voxels do not load yet. To find packs, the launcher's **Mods** page installs shader packs from Modrinth (see [Mods and data packs](/docs/mods#finding-resource-packs-shader-packs-and-modpacks)). ## Resource packs @@ -67,7 +67,7 @@ Horizon plays with PlayStation (DualShock 4 and DualSense), Xbox (360, One and S ## Extras -**Options, Horizon Settings, Extras** holds small, optional conveniences. Every one is off by default, so a fresh install behaves like vanilla: fullbright, zoom, a minimap, an FPS counter, a keystroke display, auto-reconnect, Mouse Tweaks-style inventory controls and inventory sorting. In Alpha builds there is one more, **dynamic lights**: a torch, lantern or other light source that you hold, that lies dropped as an item, or a burning mob, lights the blocks around it. It is client-side only, so other players do not see it. +**Options, Horizon Settings, Extras** holds small, optional conveniences. Every one is off by default, so a fresh install behaves like vanilla: fullbright, zoom, a minimap, an FPS counter, a keystroke display, auto-reconnect, Mouse Tweaks-style inventory controls and inventory sorting. One more is **dynamic lights**: a torch, lantern or other light source that you hold, that lies dropped as an item, or a burning mob, lights the blocks around it. It is client-side only, so other players do not see it. ## Where your settings are stored diff --git a/website/src/index.html b/website/src/index.html index 9c7c3ca3e..29d32d5ba 100644 --- a/website/src/index.html +++ b/website/src/index.html @@ -202,7 +202,7 @@

05Releases

Recently added

-

Alpha builds come out many times a day, as changes land; about once a day the tested ones become Stable, the launcher's default. The newest, and what they added:

+

New versions come out many times a day, as changes land, and the launcher installs each one once it has passed its test. The newest, and what they added:

{{RECENT}} diff --git a/website/src/main.js b/website/src/main.js index 4298cf1fd..7a0714d1b 100644 --- a/website/src/main.js +++ b/website/src/main.js @@ -17,9 +17,9 @@ const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)").matches; const isLauncher = (r) => isLauncherTag(r.tag_name) && !r.prerelease; -// The newest 100 releases (GitHub's most per page). Game betas come out several times a day, so the stable game -// release and the newest launcher release can both be older than all of them. The stable game release is then -// GitHub's "latest" (betas and launcher releases are never marked latest); the launcher release is looked up by its +// The newest 100 releases (GitHub's most per page). The newest game release that is not a pre-release (the old +// Alpha channel's, docs/release-flow.md) and the newest launcher release can be older than all of them. The game +// release is then GitHub's "latest" (pre-releases and launcher releases never are); the launcher release is looked up by its // tag (the newest launcher@ tag with a published release, or launcher-v before 0.2: docs/versioning.md). async function loadReleases() { const list = (await get(`https://api.github.com/repos/${REPO}/releases?per_page=100`)).filter((r) => !r.draft).map(slim); @@ -83,7 +83,7 @@ async function setUpDownload() { // --- Recently added and the links from main --------------------------------- -// "Recently added": the newest game releases, Alpha and Stable. +// "Recently added": the newest game releases. async function setUpRecent() { const html = recentHtml((await releases).filter((r) => isGame(r.tag_name))); if (html) document.getElementById("recent-releases").innerHTML = html; diff --git a/website/src/releases.html b/website/src/releases.html index f0e4b2de4..989164653 100644 --- a/website/src/releases.html +++ b/website/src/releases.html @@ -4,7 +4,7 @@ Releases · Horizon - + @@ -30,11 +30,10 @@

ReleasesEvery version, newest first

What's new in Horizon

-

Each release lists what it adds and fixes, then its full notes and its downloads. Alpha builds come out many times a day as changes land and can break; about once a day the tested ones become Stable, what the launcher installs unless you pick Alpha in its Settings. The launcher has its own releases.

+

Each release lists what it adds and fixes, then its full notes and its downloads. New versions come out many times a day as changes land, and the launcher installs each one once it has passed its test. The launcher has its own releases.

- - +

{{RELEASE_COUNT}}

diff --git a/website/src/releases.js b/website/src/releases.js index 2e6a2e524..de59c8fef 100644 --- a/website/src/releases.js +++ b/website/src/releases.js @@ -1,13 +1,13 @@ // The release notes on the site: the home page's "Recently added" block and the Releases page (every release, // newest first). Shared by build.mjs (baked into the pages) and the pages' scripts (refreshed from GitHub). // Tags: the game's vX.Y.Z and the launcher's launcher@X.Y.Z from 0.2, vYYYY.MM.DD[.N] and launcher-vX.Y.Z before -// (src/versions.js). Alpha is a game pre-release, Stable a game release (docs/release-flow.md, "Channels"). +// (src/versions.js). One channel (docs/release-flow.md, "One channel"): a release is the game's or the launcher's. import { markdown, inline, escape } from "./markdown.js"; import { isLauncher, launcherVersion, newestFirst } from "./versions.js"; const REPO = "ludovic111/horizon"; -export const channel = (r) => (isLauncher(r.tag_name) ? "Launcher" : r.prerelease ? "Alpha" : "Stable"); +export const channel = (r) => (isLauncher(r.tag_name) ? "Launcher" : "Game"); const anchor = (r) => `release-${r.tag_name.replace(/[^\w.-]/g, "-")}`; // "Horizon 0.2.3: Cave culling, weather" (before 0.2, "Horizon 2026.10.13: …") reads as the version and its line. @@ -90,7 +90,7 @@ export function recentHtml(list, { rows = 5, picks = 3 } = {}) { }) .join(""); // What landed last: the "New" items of the newest releases with the highest pull request numbers (a release's - // notes list everything since the last Stable, oldest first). + // notes list everything since the release before it, oldest first). const pr = (item) => Math.max(0, ...[...item.matchAll(/#(\d+)/g)].map((m) => Number(m[1]))); const seen = new Set(); const picked = game diff --git a/website/src/style.css b/website/src/style.css index 8517a2f43..323cd6e83 100644 --- a/website/src/style.css +++ b/website/src/style.css @@ -630,14 +630,13 @@ code { border-radius: 0; background: var(--well); box-shadow: 0 0 0 1px var(--ou .page-main > .container > .lede { font-size: var(--text-body); } .page-main .disclaimer { margin-top: 48px; } -/* Channel and source badges: small square tags. */ +/* Release and source badges: small square tags. */ .badge { display: inline-flex; align-items: center; height: 22px; padding: 0 8px; margin-right: 10px; vertical-align: 2px; font: 500 12px / 1 var(--pixel); letter-spacing: 0.02em; text-transform: uppercase; white-space: nowrap; border: var(--block-outline) solid var(--outline); background: var(--well); color: var(--ink-soft); } -.badge-stable { background: color-mix(in srgb, var(--success) 22%, var(--panel)); color: var(--ink); } -.badge-alpha { background: color-mix(in srgb, var(--warn) 24%, var(--panel)); color: var(--ink); } +.badge-game { background: color-mix(in srgb, var(--success) 22%, var(--panel)); color: var(--ink); } .badge-launcher { background: color-mix(in srgb, var(--accent) 20%, var(--panel)); color: var(--ink); } .badge-us { background: color-mix(in srgb, var(--accent) 20%, var(--panel)); color: var(--ink); } .badge-players { background: color-mix(in srgb, var(--success) 22%, var(--panel)); color: var(--ink); } From 630f5210722059eb1d50d64f79e12fc21bac4f47 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 11:53:00 +0200 Subject: [PATCH 018/408] Launcher: one update channel, and the menu entry is never taken over Every release is now published as the release (one channel, Ludovic's decision of 2026-10-23), so the launcher drops its Stable/Alpha choice: the Updates row in Settings, `horizon-launcher update-channel` and its MCP tool, the channel on the Versions page, in `versions` and in the footer. It updates to the newest game release that is not a pre-release (GitHub's latest) and looks every 30 minutes. The pre-releases of the old Alpha channel stay listed and installable by hand, never as an update. Old `update_channel` / `beta_builds` keys in settings.json are ignored. On Linux a release build that starts no longer rewrites the applications-menu entry to point at itself. It writes the entry only when there is none, or when the program it starts (TryExec, else Exec) no longer exists; turning the Settings switch on or `desktop-entry` still points it at this launcher, and HORIZON_LAUNCHER_DESKTOP_EXEC is still honored. A test build started with the real HOME took over a working entry and then left it broken when its target/ was deleted (2026-10-23). Co-Authored-By: Claude Opus 5.5 --- docs/agent-control.md | 3 +- docs/launcher-commands.md | 10 - launcher/README.md | 30 +-- launcher/src/backend.rs | 233 +++++------------- launcher/src/backend/release_loading_tests.rs | 4 - launcher/src/cli.rs | 26 +- launcher/src/cli_tools.rs | 1 - launcher/src/desktop.rs | 147 ++++++++++- launcher/src/main.rs | 63 +---- website/docs/agents.md | 2 +- 10 files changed, 230 insertions(+), 289 deletions(-) diff --git a/docs/agent-control.md b/docs/agent-control.md index 5383cc03c..9d5db2597 100644 --- a/docs/agent-control.md +++ b/docs/agent-control.md @@ -71,7 +71,6 @@ passes on without checking it). | Dedicated server here: start, console, log, stop | Servers | yes | yes | yes | yes | `server`; MCP `server`, `server_command`, `server_log`, `server_stop` | | Hosted servers: list, create, set up, run a command, forget | Servers | yes | no | yes | yes | `servers ...`; `servers_forget` needs `confirm` | | Accounts: list, sign in, sign out, select, offline | Settings | yes | part | yes | yes | names and UUIDs only; sign-in is a device code; `account_offline` was missing | -| Update channel (Alpha, Stable) | Settings | yes | yes | yes | yes | | | Game folder, server folder, install new versions, opening animation | Settings | no | no | yes | yes | `settings [KEY VALUE]` | | Extra game arguments | Settings | yes | no | yes | yes | `game-args` | | Applications menu entry (Linux) | Settings | yes | no | yes | yes | `desktop-entry` | @@ -148,7 +147,7 @@ The switch is in three places: Settings > AI in the launcher, Horizon Settings i | Companion (#1068) | uses the same switch (see horizon-parity companion-notes.md) | Every other launcher command stays usable: versions, install, remove, prepare, play, server, -notes, links, account, update-channel, settings, game-args, logs, update, desktop-entry, data, +notes, links, account, settings, game-args, logs, update, desktop-entry, data, modpack, mods, servers, no-ai and benchmark. None of them drives the game for an agent. The launcher itself, packagers, the docs and players' scripts need them, and `no-ai` has to stay to turn the switch off. diff --git a/docs/launcher-commands.md b/docs/launcher-commands.md index 579659e68..9e09cd00b 100644 --- a/docs/launcher-commands.md +++ b/docs/launcher-commands.md @@ -130,16 +130,6 @@ Play offline, without an account. MCP: `account_offline`. -## `horizon-launcher update-channel` - -Show or set which Horizon releases install by themselves: stable (a tested build about once a day) or alpha (every release as soon as it is built; can break). - - horizon-launcher update-channel [CHANNEL] - -- `CHANNEL` (stable, alpha): Omit to show the current channel - -MCP: `update_channel`. - ## `horizon-launcher settings` Show the launcher's settings, or set one (the Settings page): selected-version TAG, minecraft-dir PATH, server-dir PATH ("default" resets a folder), install-new-versions on|off, opening-animation on|off. diff --git a/launcher/README.md b/launcher/README.md index e12ed2439..16ef197c7 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -78,16 +78,13 @@ page `servers.json` (the list), `servers//` (the servers created there) an `server-runtime/` (the programs and game files they run). - **Settings**: install new Horizon versions automatically (on unless you turn it off; the - selected version only moves to the new one if you were on the newest), which ones (Updates, - below), the opening animation, the game's extra command-line arguments, and the launcher's own - version and update state. -- **Updates**: **Stable** (the default) installs a tested build about once a day, the betas that - `promote.yml` makes stable; **Alpha** installs every release as soon as it is built, several - times a day, and can break (docs/release-flow.md, "Channels"). While it is open, the launcher - looks for new releases every 4 hours on Stable and every 30 minutes on Alpha. Kept as `update_channel` in - `settings.json`; a `beta_builds: true` from launchers before 0.2 reads as Alpha (so does a `nightly` from the channel's first name). - `horizon-launcher update-channel [stable|alpha]` shows or sets it. The **Versions** page - shows each release's channel. The launcher's own updates don't depend on it. + selected version only moves to the new one if you were on the newest), the opening animation, + the game's extra command-line arguments, and the launcher's own version and update state. +- **Updates**: there is one channel. Every release is published as the release, GitHub's latest, + once its smoke test passed (docs/release-flow.md), and the launcher installs it. The game + pre-releases of the old Alpha channel (v0.2.1 on) stay on the Versions page to install + by hand, but are never installed as an update. The `update_channel` and `beta_builds` keys + older launchers wrote in `settings.json` are ignored and dropped on the next save. - **Game arguments**: extra arguments added to the game's command line (for example `--server-thread`), one line where quotes group a word with spaces. They are appended after the launcher's own arguments, kept as `game_args` in `settings.json`, and apply the next time the @@ -102,7 +99,7 @@ their content overflows. Drag the thumb or click the track to navigate without a ## Updates -The launcher looks for a newer Horizon release when it starts and every four hours while it +The launcher looks for a newer Horizon release when it starts and every 30 minutes while it is open, and shows a small "available, Install" line on Play. It also updates itself from GitHub releases tagged `launcher@X.Y.Z` (Horizon's own are `vX.Y.Z`; @@ -111,8 +108,14 @@ every 0.2 tag counts as newer than all of those (docs/versioning.md). It downloa own binary, and offers "Restart" in the footer. Development builds and `HORIZON_LAUNCHER_NO_SELF_UPDATE=1` never replace themselves. +On Linux a release build that starts writes its applications-menu entry only when there is +none, or when the program the entry starts (its `TryExec`, else its `Exec`) no longer exists. +An entry pointing at another launcher that works is left alone, so a test or development build +never takes it over. Turning the Settings switch on, or `horizon-launcher desktop-entry`, +points the entry at this launcher whatever is there. + Linux packagers can set `HORIZON_LAUNCHER_DESKTOP_EXEC` to a wrapper's absolute path. -Menu entries created by Settings or `desktop-entry` then start that wrapper, which can +Menu entries the launcher writes then start that wrapper, which can set `HORIZON_LAUNCHER_NO_SELF_UPDATE=1` to keep launcher updates with the package manager. Launcher releases are automatic (docs/release-flow.md in the repository): when main changes the @@ -134,7 +137,6 @@ The same binary is a command-line tool; without a subcommand it opens the window horizon-launcher server [--dir ] [--version ] [--accept-eula] horizon-launcher notes [] patch notes as plain text horizon-launcher links the Discord, sponsor and website links - horizon-launcher update-channel [stable|alpha] show or set which releases install by themselves horizon-launcher game-args [] show or set the extra arguments the game starts with horizon-launcher update [--check] Horizon and the launcher horizon-launcher logs [--lines N] [--crash] the end of the game's log, or its newest crash report @@ -168,7 +170,7 @@ The same binary is a command-line tool; without a subcommand it opens the window horizon-launcher data benchmark upload a benchmark report, printed first `--json` prints JSON where there is something to report (`versions`, `install`, `notes`, -`next`, `links`, `update-channel`, `game-args`, `update --check`, `logs`, `account`, `benchmark`, `data`, `modpack`). Errors go to stderr with exit code 1. `server` runs in the terminal, +`next`, `links`, `game-args`, `update --check`, `logs`, `account`, `benchmark`, `data`, `modpack`). Errors go to stderr with exit code 1. `server` runs in the terminal, so lines you type reach its console. `HORIZON_LAUNCHER_HOME` replaces the data folder (for scripts and tests). diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index f88171c4e..87034c43f 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -37,8 +37,9 @@ pub struct Release { pub body: String, pub date: String, pub asset: Option<(String, u64)>, - /// A beta: a game release not promoted to stable yet (a GitHub pre-release, docs/release-flow.md). - pub beta: bool, + /// A GitHub pre-release: the Alpha builds from before every release went out as the release + /// (v0.2.1 on, docs/release-flow.md). Listed and installed by hand, never as an update. + pub prerelease: bool, } #[cfg(all(target_os = "linux", target_arch = "x86_64"))] @@ -264,7 +265,7 @@ fn parse_releases( .take(10) .collect(), asset: found, - beta: r["prerelease"].as_bool().unwrap_or(false), + prerelease: r["prerelease"].as_bool().unwrap_or(false), }); } out.sort_by(|a, b| compare_versions(&b.tag, &a.tag)); @@ -348,75 +349,14 @@ pub fn latest(releases: &[Release]) -> Option<&Release> { releases.iter().find(|r| r.asset.is_some()) } -/// The releases a launcher installs by itself: stable ones, and betas too on the Alpha channel. -pub fn channel(releases: &[Release], channel: UpdateChannel) -> Vec { - releases - .iter() - .filter(|r| channel.takes(r)) - .cloned() - .collect() +/// The releases a launcher installs by itself: every one that is published as a release, so +/// GitHub's latest when it comes out. The pre-releases of the old Alpha channel are left out. +pub fn installable_updates(releases: &[Release]) -> Vec { + releases.iter().filter(|r| !r.prerelease).cloned().collect() } -/// Which game releases install by themselves (Settings, "Updates"; docs/release-flow.md, "Channels"). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum UpdateChannel { - /// A tested build about once a day: the betas promote.yml makes stable. - #[default] - Stable, - /// Every release as soon as it is built, pre-releases included. It was called "nightly" - /// while the channels were new: that name is still read. - #[serde(alias = "nightly")] - Alpha, -} - -impl UpdateChannel { - pub fn name(self) -> &'static str { - match self { - UpdateChannel::Stable => "stable", - UpdateChannel::Alpha => "alpha", - } - } - - /// Its name in Settings and on the Versions page. - pub fn label(self) -> &'static str { - match self { - UpdateChannel::Stable => "Stable", - UpdateChannel::Alpha => "Alpha", - } - } - - pub fn parse(name: &str) -> Option { - match name { - "stable" => Some(UpdateChannel::Stable), - "alpha" | "nightly" => Some(UpdateChannel::Alpha), - _ => None, - } - } - - /// Whether this channel installs `release`: betas only reach Alpha. - pub fn takes(self, release: &Release) -> bool { - self == UpdateChannel::Alpha || !release.beta - } - - /// How often a launcher left open looks for new releases: Alpha's come many times a day, - /// Stable's once. - pub fn check_every(self) -> std::time::Duration { - std::time::Duration::from_secs(match self { - UpdateChannel::Stable => 4 * 3600, - UpdateChannel::Alpha => 30 * 60, - }) - } - - /// The channel a release is on when it is listed: betas are Alpha's only. - pub fn of(release: &Release) -> Self { - if release.beta { - UpdateChannel::Alpha - } else { - UpdateChannel::Stable - } - } -} +/// How often a launcher left open looks for new releases: they come out several times a day. +pub const CHECK_EVERY: std::time::Duration = std::time::Duration::from_secs(30 * 60); /// The community, sponsor and website links, from `launcher/links.json` on main, so they can change /// without a launcher release. An empty address hides its button. @@ -1745,17 +1685,10 @@ fn launcher_update_from(releases: &[Release], own: &str) -> Option { pub fn releases_and_updates( on_releases: impl FnOnce(Result, String>), ) -> Result { - releases_and_updates_with( - Settings::load().update_channel, - release_list, - installed, - launcher_releases_in, - on_releases, - ) + releases_and_updates_with(release_list, installed, launcher_releases_in, on_releases) } fn releases_and_updates_with( - update_channel: UpdateChannel, load: impl FnOnce() -> Result, installed: impl FnOnce() -> Vec, launchers: impl FnOnce(&serde_json::Value) -> Vec, @@ -1769,7 +1702,7 @@ fn releases_and_updates_with( } }; let releases = parse_releases(&list, ASSET, is_game_tag); - let horizon = horizon_update(&channel(&releases, update_channel), &installed()); + let horizon = horizon_update(&installable_updates(&releases), &installed()); on_releases(Ok(releases)); Ok(Updates { horizon, @@ -1791,15 +1724,14 @@ pub fn select_after_update(selected: Option<&str>, installed_before: &[String]) } } -/// Installs `tag` (or with "latest" the newest release of the player's channel), then updates the selection as +/// Installs `tag` (or with "latest" the newest release, pre-releases left out), then updates the selection as /// `select_after_update` says when `as_update`, or always selects it otherwise. pub fn install_tag(tag: &str, as_update: bool, progress: impl Fn(f32)) -> Result { let releases = releases()?; let release = if tag == "latest" { - let update_channel = Settings::load().update_channel; releases .iter() - .find(|r| r.asset.is_some() && update_channel.takes(r)) + .find(|r| r.asset.is_some() && !r.prerelease) .ok_or("No release has a build for this platform yet.")? } else { releases @@ -2262,10 +2194,6 @@ pub struct Settings { /// default. Appended after the launcher's own arguments, so they can add to or override them. #[serde(default, skip_serializing_if = "String::is_empty")] pub game_args: String, - /// Which releases install by themselves: Stable by default. Launchers before 0.2 had a "Beta - /// builds" switch instead; [`Settings::parse`] reads its `beta_builds: true` as Alpha. - #[serde(default)] - pub update_channel: UpdateChannel, /// Dark, Light, or the system's: the launcher's look. Dark by default. #[serde(default)] pub appearance: Appearance, @@ -2284,20 +2212,7 @@ impl Settings { return Self::default(); }; if let Some(fields) = value.as_object_mut() { - // The switch from before 0.2: on meant every release at once, the Alpha channel. - if fields.remove("beta_builds") == Some(serde_json::Value::Bool(true)) { - fields - .entry("update_channel") - .or_insert_with(|| UpdateChannel::Alpha.name().into()); - } - // A channel this launcher doesn't know is Stable, not a reason to lose every setting. - if fields - .get("update_channel") - .is_some_and(|c| c.as_str().and_then(UpdateChannel::parse).is_none()) - { - fields.remove("update_channel"); - } - // The same for an appearance from a newer launcher. + // An appearance from a newer launcher is Dark, not a reason to lose every setting. if fields .get("appearance") .is_some_and(|a| serde_json::from_value::(a.clone()).is_err()) @@ -2517,41 +2432,35 @@ mod tests { assert_eq!(offered(&["v2026.10.15.1", "v2026.10.14"]), None); } - /// Betas (GitHub pre-releases) install by themselves only on the Alpha channel; Stable waits - /// for promote.yml's daily promotion (docs/release-flow.md, "Channels"). + /// Every release is published as the release, and launchers update to it. The pre-releases + /// of the old Alpha channel (v0.2.1 on) are only installed by hand: a launcher that + /// had one installed waits for the next release instead of going back. #[test] - fn updates_follow_the_stable_channel_unless_alpha_is_picked() { + fn updates_follow_every_release_and_leave_the_old_alpha_ones_out() { let asset = ASSET.unwrap_or("horizon-linux-x86_64.tar.gz"); let list = serde_json::json!([ - {"tag_name": "v2026.10.19.02", "prerelease": true, "assets": [{"name": asset, "browser_download_url": "b", "size": 1}]}, - {"tag_name": "v2026.10.19.01", "assets": [{"name": asset, "browser_download_url": "s", "size": 1}]}, + {"tag_name": "v0.2.13", "assets": [{"name": asset, "browser_download_url": "n", "size": 1}]}, + {"tag_name": "v0.2.12", "prerelease": true, "assets": [{"name": asset, "browser_download_url": "a", "size": 1}]}, + {"tag_name": "v0.2.0", "assets": [{"name": asset, "browser_download_url": "s", "size": 1}]}, ]); let releases = parse_releases(&list, Some(asset), is_game_tag); assert_eq!( - releases.iter().map(|r| r.beta).collect::>(), - [true, false] + releases.iter().map(|r| r.prerelease).collect::>(), + [false, true, false] ); - let offered = |alpha: bool, installed: &[&str]| { + let offered = |releases: &[Release], installed: &[&str]| { let installed: Vec = installed.iter().map(|t| t.to_string()).collect(); - let on = if alpha { - UpdateChannel::Alpha - } else { - UpdateChannel::Stable - }; - horizon_update(&channel(&releases, on), &installed).map(|r| r.tag) + horizon_update(&installable_updates(releases), &installed).map(|r| r.tag) }; - assert_eq!(offered(false, &[]), Some("v2026.10.19.01".into())); - assert_eq!( - offered(true, &["v2026.10.19.01"]), - Some("v2026.10.19.02".into()) - ); - assert_eq!(offered(false, &["v2026.10.19.01"]), None); - // A beta installed earlier is never "updated" to an older stable build. - assert_eq!(offered(false, &["v2026.10.19.02"]), None); - assert_eq!( - releases.iter().map(UpdateChannel::of).collect::>(), - [UpdateChannel::Alpha, UpdateChannel::Stable] - ); + assert_eq!(offered(&releases, &[]), Some("v0.2.13".into())); + assert_eq!(offered(&releases, &["v0.2.0"]), Some("v0.2.13".into())); + assert_eq!(offered(&releases, &["v0.2.12"]), Some("v0.2.13".into())); + assert_eq!(offered(&releases, &["v0.2.13"]), None); + // Before the first release of the single channel: the old Alpha one stays where it is. + let before = &releases[1..]; + assert_eq!(offered(before, &["v0.2.0"]), None); + assert_eq!(offered(before, &["v0.2.12", "v0.2.0"]), None); + assert_eq!(CHECK_EVERY.as_secs(), 30 * 60); } #[test] @@ -2573,48 +2482,20 @@ mod tests { } #[test] - fn the_update_channel_is_stored_by_name_and_the_old_beta_switch_reads_as_alpha() { - let read = |text: &str| Settings::parse(text).update_channel; - assert_eq!(read(""), UpdateChannel::Stable); - assert_eq!(read("{}"), UpdateChannel::Stable); - assert_eq!( - read(r#"{"update_channel": "stable"}"#), - UpdateChannel::Stable - ); - assert_eq!(read(r#"{"update_channel": "alpha"}"#), UpdateChannel::Alpha); - // The channel's first name, from launchers built while it was called Nightly. - assert_eq!( - read(r#"{"update_channel": "nightly"}"#), - UpdateChannel::Alpha - ); - assert_eq!(UpdateChannel::parse("nightly"), Some(UpdateChannel::Alpha)); - // Launchers before 0.2: "Beta builds" on is Alpha, off is Stable. - assert_eq!(read(r#"{"beta_builds": true}"#), UpdateChannel::Alpha); - assert_eq!(read(r#"{"beta_builds": false}"#), UpdateChannel::Stable); - // Once a channel is picked, it wins over a switch left behind. - let both = r#"{"beta_builds": true, "update_channel": "stable"}"#; - assert_eq!(read(both), UpdateChannel::Stable); - // An unknown channel is Stable, and the rest of the settings survive it. - let odd = - Settings::parse(r#"{"update_channel": "beta", "game_args": "--x", "beta_builds": 1}"#); - assert_eq!(odd.update_channel, UpdateChannel::Stable); - assert_eq!(odd.game_args, "--x"); - // Saved as a name, without the old switch. - let mut settings = Settings::parse(r#"{"selected": "v0.2.0", "beta_builds": true}"#); - let saved = serde_json::to_value(&settings).unwrap(); - assert_eq!(saved["update_channel"], "alpha"); - assert!(saved.get("beta_builds").is_none()); - assert_eq!(saved["selected"], "v0.2.0"); - settings.update_channel = UpdateChannel::Stable; - let text = serde_json::to_string(&settings).unwrap(); - assert_eq!(read(&text), UpdateChannel::Stable); - for c in [UpdateChannel::Stable, UpdateChannel::Alpha] { - assert_eq!(UpdateChannel::parse(c.name()), Some(c)); + fn the_old_update_channel_settings_are_dropped_and_the_rest_kept() { + for old in [ + r#"{"update_channel": "alpha", "game_args": "--x", "selected": "v0.2.0"}"#, + r#"{"update_channel": "stable", "game_args": "--x", "selected": "v0.2.0"}"#, + r#"{"beta_builds": true, "game_args": "--x", "selected": "v0.2.0"}"#, + r#"{"beta_builds": false, "update_channel": "nightly", "game_args": "--x", "selected": "v0.2.0"}"#, + ] { + let settings = Settings::parse(old); + assert_eq!(settings.game_args, "--x", "{old}"); + assert_eq!(settings.selected.as_deref(), Some("v0.2.0"), "{old}"); + let saved = serde_json::to_value(&settings).unwrap(); + assert!(saved.get("update_channel").is_none(), "{old}"); + assert!(saved.get("beta_builds").is_none(), "{old}"); } - // An open launcher looks again every 4 hours on Stable, every 30 minutes on Alpha. - let minutes = |c: UpdateChannel| c.check_every().as_secs() / 60; - assert_eq!(minutes(UpdateChannel::Stable), 240); - assert_eq!(minutes(UpdateChannel::Alpha), 30); } #[test] @@ -2635,7 +2516,7 @@ mod tests { body: String::new(), date: String::new(), asset: Some(("u".into(), 1)), - beta: false, + prerelease: false, }; assert!(launcher_update(&[r(own_tag())]).is_none()); assert_eq!(launcher_version(&own_tag()), Some(VERSION)); @@ -2675,7 +2556,7 @@ mod tests { body: String::new(), date: String::new(), asset: Some(("u".into(), 1)), - beta: false, + prerelease: false, }; let mut list = vec![ r("launcher-v0.16.0"), @@ -2744,10 +2625,14 @@ mod tests { ]); let releases = parse_releases(&list, Some(asset), is_game_tag); let installed = ["v2026.10.19.15".to_string(), "v2026.10.12".to_string()]; - let offered = |on| horizon_update(&channel(&releases, on), &installed).map(|r| r.tag); - // A beta 0.2.0 reaches launchers on Alpha; Stable ones wait for its promotion. - assert_eq!(offered(UpdateChannel::Alpha), Some("v0.2.0".into())); - assert_eq!(offered(UpdateChannel::Stable), None); + // A pre-release 0.2.0 is not an update; once published as the release, it is one. + let offered = |releases: &[Release]| { + horizon_update(&installable_updates(releases), &installed).map(|r| r.tag) + }; + assert_eq!(offered(&releases), None); + let mut released = releases.clone(); + released[0].prerelease = false; + assert_eq!(offered(&released), Some("v0.2.0".into())); let mut sorted = vec![ "v2026.10.19.15".to_string(), "v0.2.1".into(), @@ -2837,7 +2722,7 @@ mod tests { body: String::new(), date: String::new(), asset: Some(("u".into(), 1)), - beta: false, + prerelease: false, }; let releases = [r("v2026.10.13"), r("v2026.10.12")]; assert_eq!( diff --git a/launcher/src/backend/release_loading_tests.rs b/launcher/src/backend/release_loading_tests.rs index 4aaa616a2..d7f839bde 100644 --- a/launcher/src/backend/release_loading_tests.rs +++ b/launcher/src/backend/release_loading_tests.rs @@ -45,7 +45,6 @@ fn baseline(load: impl Fn() -> Result) -> (Vec Result) -> (Vec, Updates) { let mut releases = None; let updates = releases_and_updates_with( - UpdateChannel::Stable, load, installed_fixture, |list| parse_releases(list, LAUNCHER_ASSET, is_launcher_tag), @@ -82,7 +81,6 @@ fn errors_reach_releases_and_updates_without_fallback() { ] { let mut published = None; let result = releases_and_updates_with( - UpdateChannel::Stable, || Err(error.into()), || panic!("no installed scan after failure"), |_| panic!("no fallback after failure"), @@ -97,7 +95,6 @@ fn errors_reach_releases_and_updates_without_fallback() { fn publish_games_before_older_launcher_fallback() { let events = RefCell::new(Vec::new()); let result = releases_and_updates_with( - UpdateChannel::Stable, || Ok(serde_json::json!([{"tag_name": "v2026.10.14", "assets": []}])), Vec::new, |list| { @@ -132,7 +129,6 @@ fn failed_launcher_fallback_keeps_game_result_and_checks_stay_fresh() { for day in [14, 15] { let mut published = None; let updates = releases_and_updates_with( - UpdateChannel::Stable, || { requests.fetch_add(1, Ordering::Relaxed); Ok(serde_json::json!([{"tag_name": format!("v2026.10.{day}")}])) diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index 732aa872b..9d8e51d93 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -287,13 +287,6 @@ enum Cmd { #[command(subcommand)] action: Option, }, - /// Show or set which Horizon releases install by themselves: stable (a tested build about once - /// a day) or alpha (every release as soon as it is built; can break) - UpdateChannel { - /// Omit to show the current channel - #[arg(value_parser = ["stable", "alpha"])] - channel: Option, - }, /// Show the launcher's settings, or set one (the Settings page): selected-version TAG, /// minecraft-dir PATH, server-dir PATH ("default" resets a folder), install-new-versions /// on|off, opening-animation on|off @@ -435,7 +428,6 @@ fn settings_json(s: &backend::Settings) -> serde_json::Value { "server_dir": backend::server_dir(None), "install_new_versions": s.install_new_versions.unwrap_or(true), "opening_animation": !s.skip_opening, - "update_channel": s.update_channel.name(), "game_args": s.game_args, "desktop_entry": s.desktop_entry.unwrap_or(true), "no_ai": backend::no_ai(), @@ -504,7 +496,7 @@ fn attached(mut cmd: Command) -> Result<(), String> { fn release_json(r: &Release) -> serde_json::Value { serde_json::json!({ - "tag": r.tag, "name": r.name, "date": r.date, "channel": backend::UpdateChannel::of(r).name(), + "tag": r.tag, "name": r.name, "date": r.date, "prerelease": r.prerelease, "available_here": r.asset.is_some(), "installed": backend::installed().contains(&r.tag), }) } @@ -555,8 +547,7 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { (false, true) => "", (false, false) => "no build for this platform", }; - let channel = backend::UpdateChannel::of(r).name(); - println!("{:<15} {} {:<7} {}", r.tag, r.date, channel, state); + println!("{:<15} {} {}", r.tag, r.date, state); } } Cmd::Install { tag } => { @@ -733,19 +724,6 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { } } } - Cmd::UpdateChannel { channel } => { - let mut settings = backend::Settings::load(); - if let Some(channel) = channel.as_deref().and_then(backend::UpdateChannel::parse) { - settings.update_channel = channel; - settings.save(); - } - let channel = settings.update_channel.name(); - if as_json { - json(serde_json::json!({ "update_channel": channel })); - } else { - println!("Update channel: {channel}"); - } - } Cmd::GameArgs { args } => { let mut settings = backend::Settings::load(); if let Some(line) = args { diff --git a/launcher/src/cli_tools.rs b/launcher/src/cli_tools.rs index 307f17dba..7653311ac 100644 --- a/launcher/src/cli_tools.rs +++ b/launcher/src/cli_tools.rs @@ -366,7 +366,6 @@ mod tests { "prepare", "notes", "update", - "update_channel", "game_args", "settings", "logs", diff --git a/launcher/src/desktop.rs b/launcher/src/desktop.rs index 1c9fe931e..281850cb6 100644 --- a/launcher/src/desktop.rs +++ b/launcher/src/desktop.rs @@ -2,8 +2,12 @@ //! `applications/horizon-launcher.desktop` (pointing at wherever the binary is now) and Horizon's //! icon into the `hicolor` theme, under `$XDG_DATA_HOME` (`~/.local/share` by default), so no root //! is needed; `horizon.desktop` (hidden from menus) gives the game's window its icon on Wayland. -//! A release build does this when it starts, and again whenever the binary has moved; the -//! Settings switch and `horizon-launcher desktop-entry --remove` take it all away again. +//! A release build writes it when it starts only if there is no entry yet or the one there starts +//! a program that is gone ([`repair`]), so a development or test build never takes over a working +//! entry. Turning the Settings switch on (or `horizon-launcher desktop-entry`) points it at this +//! binary whatever is there ([`install`]); the switch off and `desktop-entry --remove` take it all +//! away again. +use std::ffi::OsStr; use std::fs; use std::io; use std::path::{Path, PathBuf}; @@ -153,15 +157,85 @@ pub fn remove_in(data: &Path) -> io::Result<()> { Ok(()) } -/// Registers the launcher, using a distributor's wrapper when one is configured. -/// Both GUI registration (including the settings switch) and the CLI use this path. +/// The program an entry starts: its `TryExec`, else the first word of its `Exec` (unquoted as +/// [`quote`] writes it). None when the entry names neither. +fn entry_target(entry: &str) -> Option { + let mut in_main = false; + let (mut exec, mut try_exec) = (None, None); + for line in entry.lines().map(str::trim) { + if line.starts_with('[') { + in_main = line == "[Desktop Entry]"; + } else if let Some((key, value)) = line.split_once('=').filter(|_| in_main) { + match key.trim() { + "TryExec" if try_exec.is_none() => try_exec = Some(value.trim()), + "Exec" if exec.is_none() => exec = Some(value.trim()), + _ => {} + } + } + } + if let Some(program) = try_exec.filter(|p| !p.is_empty()) { + return Some(program.to_string()); + } + let exec = exec?; + let program = match exec.strip_prefix('"') { + Some(rest) => { + let (mut out, mut chars) = (String::new(), rest.chars()); + while let Some(c) = chars.next() { + match c { + '"' => break, + '\\' => out.extend(chars.next()), + c => out.push(c), + } + } + out + } + None => exec.split_whitespace().next()?.to_string(), + }; + (!program.is_empty()).then_some(program) +} + +/// Whether an entry's program is there: a path that exists, or a bare name found on `path` +/// (`$PATH`), as menus look `TryExec` up. +fn target_exists(program: &str, path: Option<&OsStr>) -> bool { + if program.contains('/') { + return Path::new(program).exists(); + } + path.is_some_and(|dirs| std::env::split_paths(dirs).any(|dir| dir.join(program).is_file())) +} + +/// Whether the launcher may write its entry by itself: there is none under `data`, or the one +/// there starts a program that no longer exists. An entry pointing at another launcher that +/// still works is left alone. +pub fn needs_repair_in(data: &Path, path: Option<&OsStr>) -> bool { + match fs::read_to_string(data.join("applications").join(LAUNCHER_ENTRY)) { + Ok(entry) => !entry_target(&entry).is_some_and(|p| target_exists(&p, path)), + Err(e) => e.kind() == io::ErrorKind::NotFound, + } +} + +/// What the entry starts: a distributor's wrapper (`HORIZON_LAUNCHER_DESKTOP_EXEC`) when one is +/// configured, else the binary at `exe`. +fn target(exe: &Path) -> PathBuf { + std::env::var_os("HORIZON_LAUNCHER_DESKTOP_EXEC") + .filter(|path| !path.is_empty()) + .map_or_else(|| exe.to_path_buf(), PathBuf::from) +} + +/// Registers the launcher whatever entry is there: for the player turning it on (the Settings +/// switch, `horizon-launcher desktop-entry`). pub fn install(exe: &Path) -> Result { let data = data_home().ok_or("No home folder to put the menu entry in.")?; - let wrapper = std::env::var_os("HORIZON_LAUNCHER_DESKTOP_EXEC") - .filter(|path| !path.is_empty()) - .map(PathBuf::from); - install_in(&data, wrapper.as_deref().unwrap_or(exe)) - .map_err(|e| format!("{}: {e}", data.display())) + install_in(&data, &target(exe)).map_err(|e| format!("{}: {e}", data.display())) +} + +/// At start: registers the launcher only when [`needs_repair_in`] says so. Returns whether it +/// wrote anything. +pub fn repair(exe: &Path) -> Result { + let data = data_home().ok_or("No home folder to put the menu entry in.")?; + if !needs_repair_in(&data, std::env::var_os("PATH").as_deref()) { + return Ok(false); + } + install_in(&data, &target(exe)).map_err(|e| format!("{}: {e}", data.display())) } pub fn remove() -> Result<(), String> { @@ -206,4 +280,59 @@ mod tests { remove_in(&data).unwrap(); let _ = fs::remove_dir_all(&data); } + + #[test] + fn the_target_is_try_exec_else_the_first_word_of_exec() { + let ours = launcher_entry(Path::new("/opt/a b/horizon \"x\"/horizon-launcher")); + assert_eq!( + entry_target(&ours).as_deref(), + Some("/opt/a b/horizon \"x\"/horizon-launcher") + ); + let without_try = ours.replace("TryExec=", "X-Old="); + assert_eq!( + entry_target(&without_try).as_deref(), + Some("/opt/a b/horizon \"x\"/horizon-launcher") + ); + let wrapper = "[Desktop Entry]\nExec=flatpak run dev.horizon.Launcher %U\n"; + assert_eq!(entry_target(wrapper).as_deref(), Some("flatpak")); + // Only the main group counts: an action's Exec is not the launcher. + let action = "[Desktop Action play]\nExec=/a\n[Desktop Entry]\nExec=/b --x\n"; + assert_eq!(entry_target(action).as_deref(), Some("/b")); + assert_eq!(entry_target("[Desktop Entry]\nName=Horizon\n"), None); + assert_eq!(entry_target("[Desktop Entry]\nExec=\nTryExec=\n"), None); + } + + /// A build that starts never takes over an entry that works (a test or development build + /// started on a player's machine, 2026-10-23); it writes one only when there is none or the + /// program it starts is gone. + #[test] + fn a_start_writes_the_entry_only_when_none_works() { + let root = + std::env::temp_dir().join(format!("horizon-desktop-repair-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + let (data, bin) = (root.join("data"), root.join("bin")); + fs::create_dir_all(&bin).unwrap(); + let installed = bin.join("horizon-launcher"); + fs::write(&installed, b"").unwrap(); + let entry = data.join("applications").join(LAUNCHER_ENTRY); + let path = Some(bin.as_os_str()); + + // No entry: write one. + assert!(needs_repair_in(&data, path)); + install_in(&data, &installed).unwrap(); + // Ours works: a build elsewhere leaves it alone. + assert!(!needs_repair_in(&data, path)); + // So does one another launcher wrote, found on PATH or by its path. + fs::write(&entry, "[Desktop Entry]\nExec=horizon-launcher %U\n").unwrap(); + assert!(!needs_repair_in(&data, path)); + assert!(needs_repair_in(&data, None)); + // The program is gone (a deleted target/ folder, a moved binary): write it again. + install_in(&data, &installed).unwrap(); + fs::remove_file(&installed).unwrap(); + assert!(needs_repair_in(&data, path)); + // An entry that starts nothing is broken too. + fs::write(&entry, "[Desktop Entry]\nName=Horizon\n").unwrap(); + assert!(needs_repair_in(&data, path)); + let _ = fs::remove_dir_all(&root); + } } diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 128bf1bcf..18e8295b1 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -238,15 +238,16 @@ impl Launcher { if settings.minecraft_dir.is_none() { settings.minecraft_dir = backend::default_minecraft_dir(); } - // Release builds on Linux keep their entry in the applications menu up to date (a moved - // binary changes it); `HORIZON_LAUNCHER_DESKTOP_ENTRY=1` does it in a development build. + // Release builds on Linux put their entry back in the applications menu when there is + // none or it starts a program that is gone (a moved or deleted binary), never over one + // that works; `HORIZON_LAUNCHER_DESKTOP_ENTRY=1` does it in a development build. if cfg!(target_os = "linux") && settings.desktop_entry() && (!cfg!(debug_assertions) || std::env::var_os("HORIZON_LAUNCHER_DESKTOP_ENTRY").is_some()) { std::thread::spawn(|| { - let _ = horizon_launcher::desktop::install(backend::exe_path()); + let _ = horizon_launcher::desktop::repair(backend::exe_path()); }); } let installed = backend::installed(); @@ -658,8 +659,10 @@ impl Launcher { changed = true; } } - let every = self.settings.update_channel.check_every(); - if self.checked.is_some_and(|at| at.elapsed() > every) { + if self + .checked + .is_some_and(|at| at.elapsed() > backend::CHECK_EVERY) + { self.check_updates(); } if changed { @@ -1698,14 +1701,10 @@ impl Launcher { )); } foot = foot.child( - caps(format!( - "Launcher {} · {}", - backend::VERSION, - self.settings.update_channel.label() - )) - .px(px(8.)) - .pt(px(6.)) - .text_color(t.muted), + caps(format!("Launcher {}", backend::VERSION)) + .px(px(8.)) + .pt(px(6.)) + .text_color(t.muted), ); div() .id("sidebar") @@ -2339,25 +2338,6 @@ impl Launcher { cx.notify(); }), ); - use backend::UpdateChannel::{Alpha, Stable}; - let this = cx.entity().downgrade(); - let update_channel = segments( - "update-channel", - &[(Stable, Stable.label()), (Alpha, Alpha.label())], - self.settings.update_channel, - &t, - move |picked, _, cx| { - let _ = this.update(cx, |this, cx| { - if this.settings.update_channel != picked { - this.settings.update_channel = picked; - this.settings.save(); - // What counts as new changed: check again (and install it if that is on). - this.check_updates(); - } - cx.notify(); - }); - }, - ); let opening = switch("opening", !self.settings.skip_opening, &t).on_click(cx.listener( |this, _: &ClickEvent, _, cx| { this.settings.skip_opening = !this.settings.skip_opening; @@ -2487,22 +2467,6 @@ impl Launcher { Some(toggle.into_any_element()), &t, )) - .child(index_row( - n + 2, - "Updates", - Some( - div() - .flex() - .flex_col() - .child("Stable: a tested build about once a day.") - .child( - "Alpha: every change as soon as it is built, several times a day; can break.", - ) - .into_any_element(), - ), - Some(update_channel.into_any_element()), - &t, - )) .child(group("Launcher", "monitor")) .child(index_row( n + 3, @@ -2955,8 +2919,7 @@ impl Launcher { let tag = release.tag.clone(); let installed = self.installed.contains(&tag); let selected = self.selected() == Some(&tag); - let channel = backend::UpdateChannel::of(&release).label(); - let mut meta = vec![channel.to_string(), release.date.clone()]; + let mut meta = vec![release.date.clone()]; if let Some((_, size)) = release.asset { meta.push(megabytes(size)); } diff --git a/website/docs/agents.md b/website/docs/agents.md index 32ba58362..02042be4d 100644 --- a/website/docs/agents.md +++ b/website/docs/agents.md @@ -9,7 +9,7 @@ Everything you can do with the mouse and keyboard, through commands instead of c - **In the launcher:** - install, remove and prepare versions; - start the game, alone or with a world, or a server; - - your settings, the update channel and the extra game arguments; + - your settings and the extra game arguments; - the mod browser (mods, resource packs, shader packs, modpacks), imported modpacks and hosted servers; - your accounts (names only), logs and crash reports, patch notes, the data collection settings and the benchmark. - **In the game:** From 9fcf91e4bce67dce335874e97fa8eb3fbc05dfec Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 11:09:56 +0200 Subject: [PATCH 019/408] Metal: occlusion culling of solid sections, the depth test in the shader GPU occlusion culling ran on Vulkan only: its test needs early fragment tests, which naga's Metal backend does not emit. On Metal the boxes are tested in a pass of their own: phase 1's depth is bound read-only as the attachment and as a texture, and the fragment shader compares its own depth with it (reversed Z, greater or equal), as the fixed-function test would. HORIZON_GPU_CULL=shader takes this path on Vulkan too, for checks. Frames drawn flat (the default on Apple GPUs at high render distances) still skip culling here. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/gfx.rs | 64 +++++-- crates/horizon-client/src/gfx/cull.rs | 213 ++++++++++++++++++++---- crates/horizon-client/src/gfx/cull.wgsl | 28 +++- 3 files changed, 246 insertions(+), 59 deletions(-) diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index e379ace7c..183f7823e 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -316,7 +316,8 @@ pub struct Renderer { flat: Option, /// `flat` draws this frame's sections (off: the per-section draws). flat_on: bool, - /// Occlusion culling of solid section draws, where multi-draw is native. + /// Occlusion culling of solid section draws, where the GPU's instance + /// counts reach a multi-draw's entries (Vulkan, Metal). cull: Option, cull_on: bool, sky: wgpu::RenderPipeline, @@ -1408,7 +1409,6 @@ impl Renderer { usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); - let depth = Self::depth(&device, &config); let (atlas_pixels, atlas_width, atlas_height) = hud_atlas; let atlas = device.create_texture_with_data( &queue, @@ -2112,14 +2112,22 @@ impl Renderer { .features() .contains(wgpu::Features::INDIRECT_FIRST_INSTANCE); // HORIZON_GPU_CULL=0 turns occlusion culling off, `all` culls every - // frame however little it hides (A/B checks). + // frame however little it hides, `shader` tests in the shader as on + // Metal (A/B checks). let cull_env = std::env::var("HORIZON_GPU_CULL"); - let cull = (cull_env.as_deref() != Ok("0") && cull::Cull::supported(&adapter, &device)) - .then(|| { - let mut cull = cull::Cull::new(&device, config.format.remove_srgb_suffix()); + let cull = cull::Cull::supported(&adapter, &device) + .filter(|_| cull_env.as_deref() != Ok("0")) + .map(|depth_test| match cull_env.as_deref() { + Ok("shader") => cull::DepthTest::InShader, + _ => depth_test, + }) + .map(|depth_test| { + let mut cull = + cull::Cull::new(&device, config.format.remove_srgb_suffix(), depth_test); cull.always = cull_env.as_deref() == Ok("all"); cull }); + let depth = Self::depth(&device, &config, cull.as_ref()); let world_post = world_post::Post::new(&device, config.format.remove_srgb_suffix()); let uploads = upload::Uploads::new(&device); let section_uploads = upload::Uploads::with_chunk(&device, SECTION_UPLOAD_CHUNK); @@ -2327,7 +2335,13 @@ impl Renderer { self.surface = Some(surface); Ok(()) } - fn depth(device: &wgpu::Device, config: &wgpu::SurfaceConfiguration) -> wgpu::TextureView { + /// The world's depth, which occlusion culling's test may read. + fn depth( + device: &wgpu::Device, + config: &wgpu::SurfaceConfiguration, + cull: Option<&cull::Cull>, + ) -> wgpu::TextureView { + let read = cull.is_some_and(|c| c.depth_test() == cull::DepthTest::InShader); device .create_texture(&wgpu::TextureDescriptor { label: Some("Horizon depth"), @@ -2340,7 +2354,11 @@ impl Renderer { sample_count: 1, dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::Depth32Float, - usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + usage: if read { + wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING + } else { + wgpu::TextureUsages::RENDER_ATTACHMENT + }, view_formats: &[], }) .create_view(&Default::default()) @@ -2391,7 +2409,7 @@ impl Renderer { } else { self.offscreen = Some(Self::offscreen_target(&self.device, &self.config)); } - self.depth = Self::depth(&self.device, &self.config); + self.depth = Self::depth(&self.device, &self.config, self.cull.as_ref()); } /// Whether sections are drawn as one index list per frame (`flat`). pub fn flat_draws(&self) -> bool { @@ -3096,16 +3114,18 @@ impl Renderer { .inverse() .transform_point3(Vec3::ZERO); // Occlusion culling leaves the sections its last result did not see - // to phase 2, after the others, with instance counts of 0. + // to phase 2, after the others, with instance counts of 0. Frames + // drawn flat are not culled (phase 2's counts reach only per-section + // draws): those with as many draws as the last frame drew flat. + let flat_likely = self.flat_on + && self + .flat + .as_ref() + .is_some_and(|f| self.section_draws >= f.min_draws); let mut cull = self .cull .as_mut() - .filter(|_| { - self.cull_on - && !frame.title - && self.multi_draw - && !(self.flat_on && self.flat.is_some()) - }) + .filter(|_| self.cull_on && !frame.title && self.multi_draw && !flat_likely) .and_then(|cull| cull.begin(&self.device).then_some(cull)); self.phase2_draws.clear(); self.phase2_pages.clear(); @@ -3493,7 +3513,10 @@ impl Renderer { ); let flat_frame = match &mut self.flat { Some(flat) - if self.flat_on && !self.draws.is_empty() && self.draws.len() >= flat.min_draws => + if self.flat_on + && !culling + && !self.draws.is_empty() + && self.draws.len() >= flat.min_draws => { let sections = &self.sections; let lods = &self.lods; @@ -3567,6 +3590,9 @@ impl Renderer { Some((color, depth)) => (color, depth), None => (&view_target, &self.depth), }; + if culling && let Some(cull) = &mut self.cull { + cull.bind_depth(&self.device, world_depth); + } let cull = self.cull.as_ref().filter(|_| culling && solid_draws > 0); { let attachments = [Some(wgpu::RenderPassColorAttachment { @@ -3659,12 +3685,14 @@ impl Renderer { pass.set_vertex_buffer(1, self.instances.slice(..)); match cull { Some(cull) => { - // Phase 1 and the boxes against its depth, then + // Phase 1 and the boxes against its depth (in + // its pass, or one of their own on Metal), then // what they found in sight, in a pass that loads // both targets (it reads the test's results). self.draw_sections(&mut pass, &self.indirect, 0, 0, phase1_draws); cull.test(&mut pass); drop(pass); + cull.test_pass(&mut encoder); let attachments = [Some(wgpu::RenderPassColorAttachment { view: world_view, resolve_target: None, diff --git a/crates/horizon-client/src/gfx/cull.rs b/crates/horizon-client/src/gfx/cull.rs index bcb738de3..77574e850 100644 --- a/crates/horizon-client/src/gfx/cull.rs +++ b/crates/horizon-client/src/gfx/cull.rs @@ -22,8 +22,16 @@ //! Every solid draw is an entry of one of the two lists, so the CPU records //! as many draws as without culling: drivers that unroll an indirect //! multi-draw on the CPU (Mesa's on Intel Gen9) pay per entry. Phase 2's -//! counts come from the GPU, which needs a native multi-draw and forced -//! early depth tests: Vulkan. Translucent draws are not culled. +//! counts come from the GPU, which reads them from the draws themselves: +//! Vulkan's native multi-draw, and Metal's, which wgpu replays as one +//! indirect draw per entry. Translucent draws are not culled. +//! +//! Metal cannot force the depth test before a fragment shader that writes +//! storage (naga writes no `[[early_fragment_tests]]`), so there the boxes +//! are drawn in a pass of their own between the phases, which reads phase +//! 1's depth as a texture and makes the same comparison in the shader: the +//! fragment's depth against the stored one, greater or equal passing. The +//! same fragments pass, so the same sections are seen. use std::num::NonZeroU64; use std::sync::{ Arc, @@ -74,10 +82,40 @@ struct Group { group: wgpu::BindGroup, } +/// Where the boxes' depth test runs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DepthTest { + /// Forced before the fragment shader, in phase 1's pass (Vulkan). + Early, + /// In the fragment shader, against phase 1's depth read as a texture, + /// in a pass of its own (Metal). + InShader, +} + +/// The Vulkan entry point: the depth test forced early, which naga cannot +/// write for Metal (so it is not in `cull.wgsl`, which every backend takes). +const EARLY_TEST: &str = " +@fragment +@early_depth_test(force) +fn fs_box_early(in: Box) -> @location(0) vec4 { + see(in.test); + return vec4(0.0); +} +"; + +/// The test's depth texture binding (`InShader`), for the view it was made with. +struct DepthGroup { + view: wgpu::TextureView, + group: wgpu::BindGroup, +} + pub struct Cull { pipeline: wgpu::RenderPipeline, layout: wgpu::BindGroupLayout, group: Option, + depth_test: DepthTest, + depth_layout: Option, + depth_group: Option, params: wgpu::Buffer, /// Phase 2's draws: the solid draws after phase 1's in the frame's list. pub phase2: wgpu::Buffer, @@ -134,20 +172,33 @@ impl Cull { pub fn features(adapter: &wgpu::Adapter) -> wgpu::Features { adapter.features() & wgpu::Features::SHADER_EARLY_DEPTH_TEST } - /// Whether the device draws an indirect multi-draw natively and runs - /// fragment shaders that write storage only past an early depth test. - pub fn supported(adapter: &wgpu::Adapter, device: &wgpu::Device) -> bool { - adapter.get_info().backend == wgpu::Backend::Vulkan - && device.features().contains( - wgpu::Features::SHADER_EARLY_DEPTH_TEST | wgpu::Features::INDIRECT_FIRST_INSTANCE, - ) + /// Where the device can run the test, if it can: Vulkan with early + /// depth tests, or Metal, both drawing an indirect multi-draw's entries + /// with the instance counts the GPU wrote, with fragment shaders that + /// write storage. + pub fn supported(adapter: &wgpu::Adapter, device: &wgpu::Device) -> Option { + let depth_test = match adapter.get_info().backend { + wgpu::Backend::Vulkan + if device + .features() + .contains(wgpu::Features::SHADER_EARLY_DEPTH_TEST) => + { + DepthTest::Early + } + wgpu::Backend::Metal => DepthTest::InShader, + _ => return None, + }; + (device + .features() + .contains(wgpu::Features::INDIRECT_FIRST_INSTANCE) && adapter.get_downlevel_capabilities().flags.contains( wgpu::DownlevelFlags::VERTEX_STORAGE | wgpu::DownlevelFlags::FRAGMENT_WRITABLE_STORAGE, - ) + )) + .then_some(depth_test) } /// `color` is the world pass's colour format. - pub fn new(device: &wgpu::Device, color: wgpu::TextureFormat) -> Self { + pub fn new(device: &wgpu::Device, color: wgpu::TextureFormat, depth_test: DepthTest) -> Self { let entry = |binding, visibility, ty| wgpu::BindGroupLayoutEntry { binding, visibility, @@ -180,13 +231,41 @@ impl Cull { }); let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("Section culling"), - source: wgpu::ShaderSource::Wgsl(include_str!("cull.wgsl").into()), + source: wgpu::ShaderSource::Wgsl(source(depth_test).into()), + }); + let depth_layout = (depth_test == DepthTest::InShader).then(|| { + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Section culling depth"), + entries: &[entry( + 0, + fragment, + wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Depth, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + )], + }) }); let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("Section culling"), - bind_group_layouts: &[Some(&layout)], + bind_group_layouts: &[Some(&layout), depth_layout.as_ref()], ..Default::default() }); + // In the shader: no colour target, and phase 1's depth attached read + // only (a pass needs an attachment), its test left to the shader. + let (fragment_entry, targets, depth_compare) = match depth_test { + DepthTest::Early => ( + "fs_box_early", + &[Some(wgpu::ColorTargetState { + format: color, + blend: None, + write_mask: wgpu::ColorWrites::empty(), + })][..], + wgpu::CompareFunction::GreaterEqual, + ), + DepthTest::InShader => ("fs_box", &[][..], wgpu::CompareFunction::Always), + }; let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("Section culling"), layout: Some(&pipeline_layout), @@ -204,20 +283,16 @@ impl Cull { depth_stencil: Some(wgpu::DepthStencilState { format: wgpu::TextureFormat::Depth32Float, depth_write_enabled: Some(false), - depth_compare: Some(wgpu::CompareFunction::GreaterEqual), + depth_compare: Some(depth_compare), stencil: Default::default(), bias: Default::default(), }), multisample: Default::default(), fragment: Some(wgpu::FragmentState { module: &module, - entry_point: Some("fs_box"), + entry_point: Some(fragment_entry), compilation_options: Default::default(), - targets: &[Some(wgpu::ColorTargetState { - format: color, - blend: None, - write_mask: wgpu::ColorWrites::empty(), - })], + targets, }), multiview_mask: None, cache: None, @@ -226,6 +301,9 @@ impl Cull { pipeline, layout, group: None, + depth_test, + depth_layout, + depth_group: None, params: buffer( device, "Section culling parameters", @@ -399,17 +477,69 @@ impl Cull { } } - /// In the world pass after phase 1: draw the tested boxes against its - /// depth. Leaves the pass's pipeline and group 0 changed. + pub fn depth_test(&self) -> DepthTest { + self.depth_test + } + + /// In the world pass after phase 1 (`Early`): draw the tested boxes + /// against its depth. Leaves the pass's pipeline and group 0 changed. pub fn test(&self, pass: &mut wgpu::RenderPass<'_>) { let Some(Group { group, .. }) = &self.group else { return; }; + if self.depth_test != DepthTest::Early || self.test_data.is_empty() { + return; + } + pass.set_pipeline(&self.pipeline); + pass.set_bind_group(0, group, &[]); + pass.draw(0..36, 0..self.test_data.len() as u32); + } + + /// Before the world pass (`InShader`): the binding of the depth the + /// world is drawn with this frame. + pub fn bind_depth(&mut self, device: &wgpu::Device, depth: &wgpu::TextureView) { + let Some(layout) = &self.depth_layout else { + return; + }; + if self.depth_group.as_ref().is_none_or(|g| g.view != *depth) { + self.depth_group = Some(DepthGroup { + view: depth.clone(), + group: device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Section culling depth"), + layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(depth), + }], + }), + }); + } + } + + /// Between the phases (`InShader`): draw the tested boxes in a pass of + /// their own that reads phase 1's depth, bound by `bind_depth`. + pub fn test_pass(&self, encoder: &mut wgpu::CommandEncoder) { + let (Some(Group { group, .. }), Some(DepthGroup { view, group: depth })) = + (&self.group, &self.depth_group) + else { + return; + }; if self.test_data.is_empty() { return; } + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Section culling"), + color_attachments: &[], + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view, + depth_ops: None, + stencil_ops: None, + }), + ..Default::default() + }); pass.set_pipeline(&self.pipeline); pass.set_bind_group(0, group, &[]); + pass.set_bind_group(1, depth, &[]); pass.draw(0..36, 0..self.test_data.len() as u32); } @@ -498,16 +628,33 @@ impl Cull { } } -#[cfg(test)] -mod tests { - #[test] - fn shader_validates() { - let module = naga::front::wgsl::parse_str(include_str!("cull.wgsl")).unwrap(); - naga::valid::Validator::new( - naga::valid::ValidationFlags::all(), - naga::valid::Capabilities::all(), - ) - .validate(&module) - .unwrap(); +/// The test's shader for `depth_test`. +fn source(depth_test: DepthTest) -> String { + let common = include_str!("cull.wgsl"); + match depth_test { + DepthTest::Early => format!("{common}{EARLY_TEST}"), + DepthTest::InShader => common.to_owned(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn shaders_validate() { + for (depth_test, capabilities) in [ + (DepthTest::Early, naga::valid::Capabilities::all()), + // What wgpu's Metal backend allows: no early depth test. + ( + DepthTest::InShader, + naga::valid::Capabilities::all() - naga::valid::Capabilities::EARLY_DEPTH_TEST, + ), + ] { + let module = naga::front::wgsl::parse_str(&source(depth_test)).unwrap(); + naga::valid::Validator::new(naga::valid::ValidationFlags::all(), capabilities) + .validate(&module) + .unwrap_or_else(|e| panic!("{depth_test:?}: {e:?}")); + } } } diff --git a/crates/horizon-client/src/gfx/cull.wgsl b/crates/horizon-client/src/gfx/cull.wgsl index faa495caf..b06d4ccc2 100644 --- a/crates/horizon-client/src/gfx/cull.wgsl +++ b/crates/horizon-client/src/gfx/cull.wgsl @@ -86,16 +86,28 @@ fn vs_box(@builtin(vertex_index) v: u32, @builtin(instance_index) t: u32) -> Box return out; } -// Runs only for fragments that pass the depth test (forced early). -@fragment -@early_depth_test(force) -fn fs_box(in: Box) -> @location(0) vec4 { - if results[in.test] != params.stamp { - results[in.test] = params.stamp; - let test = tests[in.test]; +// The box is seen at this fragment: store the stamp, and give its phase 2 +// draws their instance. +fn see(t: u32) { + if results[t] != params.stamp { + results[t] = params.stamp; + let test = tests[t]; for (var k = 0u; k < test.z; k++) { phase2[(test.y + k) * 5u + 1u] = 1u; } } - return vec4(0.0); +} + +// Phase 1's depth, where the test runs in the shader (gfx/cull.rs). +@group(1) @binding(0) var depth: texture_depth_2d; + +// The world pass's reversed depth test, greater or equal passing, made here: +// where it cannot be forced before a shader that writes storage, a fragment +// that fails it would still write. Where it can, `fs_box_early` (cull.rs) +// runs only for the fragments that pass it. +@fragment +fn fs_box(in: Box) { + if in.position.z >= textureLoad(depth, vec2(in.position.xy), 0) { + see(in.test); + } } From 14be6ca3943944c6a80ff9f747375e6c363fe7b5 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 12:03:25 +0200 Subject: [PATCH 020/408] Metal: occlusion culling with flat draws too Flat draws (one index list per frame, the default on Apple GPUs at high render distances) turned occlusion culling off. Now phase 2's draws are flattened after the test, by a compute pass that copies only the sections the test saw, and each page run is drawn indirectly with the count it reached. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/gfx.rs | 132 +++-- crates/horizon-client/src/gfx/flat.rs | 587 ++++++++++++++++----- crates/horizon-client/src/gfx/flatten.wgsl | 47 +- 3 files changed, 577 insertions(+), 189 deletions(-) diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 183f7823e..91da4f616 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -83,6 +83,40 @@ mod world_post; const COMPLETE_COLUMN: u32 = (1 << (crate::chunk::HEIGHT / 16)) - 1; /// A section's instance: its camera-relative origin and, in `w`, the step of /// its fixed-point UVs (`terrain.wgsl`'s `terrain_uv`). +/// The world pass again after occlusion culling's test: it loads both +/// targets (phase 2 draws over phase 1, reading the test's results). +fn world_pass_after_culling<'e>( + encoder: &'e mut wgpu::CommandEncoder, + view: &wgpu::TextureView, + depth: &wgpu::TextureView, + pack: bool, +) -> wgpu::RenderPass<'e> { + encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Horizon world, after culling"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Load, + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: depth, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Load, + store: if pack { + wgpu::StoreOp::Store + } else { + wgpu::StoreOp::Discard + }, + }), + stencil_ops: None, + }), + ..Default::default() + }) +} fn section_instance(origin: [f32; 3]) -> [f32; 4] { [ origin[0], @@ -3114,18 +3148,11 @@ impl Renderer { .inverse() .transform_point3(Vec3::ZERO); // Occlusion culling leaves the sections its last result did not see - // to phase 2, after the others, with instance counts of 0. Frames - // drawn flat are not culled (phase 2's counts reach only per-section - // draws): those with as many draws as the last frame drew flat. - let flat_likely = self.flat_on - && self - .flat - .as_ref() - .is_some_and(|f| self.section_draws >= f.min_draws); + // to phase 2, after the others, with instance counts of 0. let mut cull = self .cull .as_mut() - .filter(|_| self.cull_on && !frame.title && self.multi_draw && !flat_likely) + .filter(|_| self.cull_on && !frame.title && self.multi_draw) .and_then(|cull| cull.begin(&self.device).then_some(cull)); self.phase2_draws.clear(); self.phase2_pages.clear(); @@ -3511,16 +3538,24 @@ impl Renderer { frame.hud, [self.config.width, self.config.height], ); + if culling && let Some(cull) = &mut self.cull { + cull.upload( + &self.device, + &mut self.uploads, + &mut encoder, + &self.draws[phase1_draws as usize..solid_draws as usize], + &self.instances, + &self.globals, + ); + } let flat_frame = match &mut self.flat { Some(flat) - if self.flat_on - && !culling - && !self.draws.is_empty() - && self.draws.len() >= flat.min_draws => + if self.flat_on && !self.draws.is_empty() && self.draws.len() >= flat.min_draws => { let sections = &self.sections; let lods = &self.lods; let sorted = &self.sorted_indices; + let phase2 = self.cull.as_ref().filter(|_| culling).map(|c| &c.phase2); crate::spans::time("flatten", || { flat.prepare( &self.device, @@ -3528,7 +3563,9 @@ impl Renderer { &mut self.uploads, &self.draws, &self.draw_pages, + phase1_draws as usize, solid_draws as usize, + phase2, visible .iter() .filter_map(|v| { @@ -3563,16 +3600,6 @@ impl Renderer { 0, bytemuck::cast_slice(&self.draws), ); - if culling && let Some(cull) = &mut self.cull { - cull.upload( - &self.device, - &mut self.uploads, - &mut encoder, - &self.draws[phase1_draws as usize..solid_draws as usize], - &self.instances, - &self.globals, - ); - } } let view_target = target_texture.create_view(&wgpu::TextureViewDescriptor { format: Some(self.config.format.remove_srgb_suffix()), @@ -3673,9 +3700,28 @@ impl Renderer { match self.flat.as_ref().filter(|_| flat_frame) { Some(flat) => { pass.set_pipeline(&flat.solid); - flat.draw(&mut pass, &flat.calls[..flat.solid_calls], |p| { - self.arena.buffer(p) - }); + let vertices = |p| self.arena.buffer(p); + match cull { + // As below: phase 1, the test, then phase 2's draws + // that the test saw, copied after it. + Some(cull) => { + flat.draw(&mut pass, &flat.calls[..flat.phase1_calls], vertices); + cull.test(&mut pass); + drop(pass); + cull.test_pass(&mut encoder); + flat.flatten_phase2(&mut encoder); + pass = world_pass_after_culling( + &mut encoder, + world_view, + world_depth, + pack, + ); + pass.set_bind_group(0, &self.group, &[]); + pass.set_pipeline(&flat.solid); + flat.draw_phase2(&mut pass, vertices); + } + None => flat.draw(&mut pass, &flat.calls[..flat.solid_calls], vertices), + } pass.set_bind_group(0, &self.group, &[]); pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); } @@ -3693,34 +3739,12 @@ impl Renderer { cull.test(&mut pass); drop(pass); cull.test_pass(&mut encoder); - let attachments = [Some(wgpu::RenderPassColorAttachment { - view: world_view, - resolve_target: None, - depth_slice: None, - ops: wgpu::Operations { - load: wgpu::LoadOp::Load, - store: wgpu::StoreOp::Store, - }, - })]; - pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { - label: Some("Horizon world, after culling"), - color_attachments: &attachments, - depth_stencil_attachment: Some( - wgpu::RenderPassDepthStencilAttachment { - view: world_depth, - depth_ops: Some(wgpu::Operations { - load: wgpu::LoadOp::Load, - store: if pack { - wgpu::StoreOp::Store - } else { - wgpu::StoreOp::Discard - }, - }), - stencil_ops: None, - }, - ), - ..Default::default() - }); + pass = world_pass_after_culling( + &mut encoder, + world_view, + world_depth, + pack, + ); pass.set_bind_group(0, &self.group, &[]); pass.set_pipeline(&self.solid); pass.set_index_buffer( diff --git a/crates/horizon-client/src/gfx/flat.rs b/crates/horizon-client/src/gfx/flat.rs index a1ae20d09..2d0a8d27c 100644 --- a/crates/horizon-client/src/gfx/flat.rs +++ b/crates/horizon-client/src/gfx/flat.rs @@ -11,11 +11,37 @@ //! so each block names one section: its id here, which indexes the frame's //! camera-relative origins (computed on the CPU exactly as for the instance //! attribute). +//! +//! With occlusion culling (`cull`), phase 1's draws and the translucent ones +//! are copied before the world pass, as without it. Phase 2's draws are +//! copied after the test, which tells which ones it saw: each run of a page +//! reserves room for all of its draws, the copy packs the seen ones at its +//! start, and the run is drawn indirectly with the count the copy reached. use super::arena::GRAIN; /// One section draw for `flatten.wgsl`: index count, first sorted index (or -/// `QUADS` for a solid draw), base vertex, first index in the list. +/// `QUADS` for a solid draw; phase 2: its entry in phase 2's draws), base +/// vertex, first index in the list (phase 2: its draw call in phase 2). type Range = [u32; 4]; + +/// Where a group of ranges takes its indices. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Source { + /// Solid draws: quads. + Quads, + /// Occlusion culling's phase 2: quads, of the sections its test saw. + Seen, + /// Translucent draws: this sorted index page. + Sorted(u32), +} + +/// The frame's draw calls, as `plan` lays them out. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Plan { + phase1_calls: usize, + solid_calls: usize, + total: u64, +} const QUADS: u32 = u32::MAX; const GROUP_LIMIT: u32 = 65535; @@ -38,6 +64,15 @@ pub struct Flat { pub translucent: wgpu::RenderPipeline, flatten: wgpu::ComputePipeline, compute_layout: wgpu::BindGroupLayout, + flatten_seen: wgpu::ComputePipeline, + seen_layout: wgpu::BindGroupLayout, + /// Phase 2's draw calls (`DrawIndexedIndirectArgs`), whose index counts + /// `flatten_seen` makes. + phase2_calls: wgpu::Buffer, + phase2_call_capacity: u64, + phase2_call_data: Vec<[u32; 5]>, + /// The copy of phase 2's draws, and its ranges. + phase2_group: Option<(wgpu::BindGroup, u32)>, draw_layout: wgpu::BindGroupLayout, blocks_per_page: u64, pages: Vec>, @@ -52,12 +87,14 @@ pub struct Flat { ranges: wgpu::Buffer, range_capacity: u64, range_data: Vec, - /// Segments of `range_data` by index source: (sorted index page or - /// `None` for solid draws, first range, ranges). - segments: Vec<(Option, u64, u64)>, + /// Segments of `range_data` by index source: (source, first range, + /// ranges). + segments: Vec<(Source, u64, u64)>, empty: wgpu::Buffer, - /// This frame's draw calls: solid ones, then translucent ones. + /// This frame's draw calls: solid ones (phase 1's, then phase 2's when + /// culling), then translucent ones. pub calls: Vec, + pub phase1_calls: usize, pub solid_calls: usize, /// Frames with fewer section draws keep the per-section draws. pub min_draws: usize, @@ -121,42 +158,60 @@ fn buffer( /// Lays out the frame's index list: each draw's range (destinations in draw /// order) grouped by index source into `ranges`, every group padded to /// `align` entries for binding, with `segments` naming each group; and the -/// draw calls, one per run of draws in the same vertex page, solid and -/// translucent apart. Returns the first translucent call and the list's -/// length. +/// draw calls, one per run of draws in the same vertex page, phase 1's solid +/// ones, phase 2's (draws `phase1_draws..solid_draws`) and translucent ones +/// apart. A phase 2 range names its draw in phase 2 and its call in phase 2 +/// instead of a destination: the call's room holds all of its draws. fn plan( draws: &[[u32; 5]], pages: &[(u32, Option)], + phase1_draws: usize, solid_draws: usize, align: u64, calls: &mut Vec, ranges: &mut Vec, - segments: &mut Vec<(Option, u64, u64)>, -) -> (usize, u64) { + segments: &mut Vec<(Source, u64, u64)>, +) -> Plan { calls.clear(); ranges.clear(); segments.clear(); - let mut solid_calls = None; + let (mut phase1_calls, mut solid_calls) = (None, None); let mut total = 0u64; - let mut by_source: Vec<(Option, Vec)> = Vec::new(); + let mut by_source: Vec<(Source, Vec)> = Vec::new(); for (i, (d, &(page, sorted))) in draws.iter().zip(pages).enumerate() { - let first = if sorted.is_some() { d[2] } else { QUADS }; - let range = [d[0], first, d[3], total as u32]; - match by_source.iter_mut().find(|(s, _)| *s == sorted) { - Some((_, list)) => list.push(range), - None => by_source.push((sorted, vec![range])), + if i == phase1_draws { + phase1_calls.get_or_insert(calls.len()); } if i == solid_draws { solid_calls = Some(calls.len()); } match calls.last_mut() { - Some(last) if last.page == page && i != solid_draws => last.count += d[0], + Some(last) if last.page == page && i != phase1_draws && i != solid_draws => { + last.count += d[0] + } _ => calls.push(Call { page, first: total as u32, count: d[0], }), } + let (source, range) = match sorted { + Some(p) => (Source::Sorted(p), [d[0], d[2], d[3], total as u32]), + None if (phase1_draws..solid_draws).contains(&i) => ( + Source::Seen, + [ + d[0], + (i - phase1_draws) as u32, + d[3], + (calls.len() - 1 - phase1_calls.unwrap_or(0)) as u32, + ], + ), + None => (Source::Quads, [d[0], QUADS, d[3], total as u32]), + }; + match by_source.iter_mut().find(|(s, _)| *s == source) { + Some((_, list)) => list.push(range), + None => by_source.push((source, vec![range])), + } total += u64::from(d[0]); } for (source, list) in by_source { @@ -165,7 +220,12 @@ fn plan( let padded = (ranges.len() as u64).next_multiple_of(align); ranges.resize(padded as usize, [0; 4]); } - (solid_calls.unwrap_or(calls.len()), total) + let solid_calls = solid_calls.unwrap_or(calls.len()); + Plan { + phase1_calls: phase1_calls.unwrap_or(calls.len()).min(solid_calls), + solid_calls, + total, + } } impl Flat { @@ -201,24 +261,37 @@ impl Flat { storage(2, compute, false), ], }); + let seen_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Flatten phase 2 section draws"), + entries: &[ + storage(0, compute, true), + storage(2, compute, false), + storage(3, compute, true), + storage(4, compute, false), + ], + }); let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("Flatten section draws"), source: wgpu::ShaderSource::Wgsl(include_str!("flatten.wgsl").into()), }); - let flatten = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some("Flatten section draws"), - layout: Some( - &device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("Flatten section draws"), - bind_group_layouts: &[Some(&compute_layout)], - ..Default::default() - }), - ), - module: &module, - entry_point: Some("flatten"), - compilation_options: Default::default(), - cache: None, - }); + let compute_pipeline = |layout: &wgpu::BindGroupLayout, entry| { + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("Flatten section draws"), + layout: Some( + &device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Flatten section draws"), + bind_group_layouts: &[Some(layout)], + ..Default::default() + }), + ), + module: &module, + entry_point: Some(entry), + compilation_options: Default::default(), + cache: None, + }) + }; + let flatten = compute_pipeline(&compute_layout, "flatten"); + let flatten_seen = compute_pipeline(&seen_layout, "flatten_seen"); let storage_usage = wgpu::BufferUsages::STORAGE; Self { solid: pipeline(&layout, "Terrain solid (flat)", "fs_solid", None), @@ -230,6 +303,17 @@ impl Flat { ), flatten, compute_layout, + flatten_seen, + seen_layout, + phase2_calls: buffer( + device, + "Flat section draw calls, phase 2", + 20, + wgpu::BufferUsages::INDIRECT | storage_usage, + ), + phase2_call_capacity: 1, + phase2_call_data: Vec::new(), + phase2_group: None, draw_layout, blocks_per_page: page_vertices.div_ceil(GRAIN), pages: Vec::new(), @@ -251,6 +335,7 @@ impl Flat { segments: Vec::new(), empty: buffer(device, "No sorted indices", 16, storage_usage), calls: Vec::new(), + phase1_calls: 0, solid_calls: 0, min_draws: if std::env::var("HORIZON_FLAT_DRAWS").as_deref() == Ok("1") { 0 @@ -321,6 +406,9 @@ impl Flat { /// the origins of the sections they draw by id. Records the copy into /// `encoder`; `calls` then lists the frame's draw calls. False when the /// frame cannot be drawn flat (the per-section draws then apply). + /// + /// When culling, the solid draws from `phase1_draws` are phase 2's, which + /// `phase2` holds as the test leaves them: `flatten_phase2` copies them. #[allow(clippy::too_many_arguments)] pub fn prepare( &mut self, @@ -329,10 +417,18 @@ impl Flat { uploads: &mut super::upload::Uploads, draws: &[[u32; 5]], pages: &[(u32, Option)], + phase1_draws: usize, solid_draws: usize, + phase2: Option<&wgpu::Buffer>, origins: impl Iterator, sorted_page: impl Fn(u32) -> wgpu::Buffer, ) -> bool { + self.phase2_group = None; + let phase1_draws = if phase2.is_some() { + phase1_draws + } else { + solid_draws + }; // Origins by section id. self.origin_data.clear(); for (id, o) in origins { @@ -362,18 +458,25 @@ impl Flat { bytemuck::cast_slice(&self.origin_data), ); } - let (solid_calls, total) = plan( + let Plan { + phase1_calls, + solid_calls, + total, + } = plan( draws, pages, + phase1_draws, solid_draws, self.range_align, &mut self.calls, &mut self.range_data, &mut self.segments, ); + self.phase1_calls = phase1_calls; self.solid_calls = solid_calls; if total == 0 || total * 4 > device.limits().max_storage_buffer_binding_size { self.calls.clear(); + self.phase1_calls = 0; self.solid_calls = 0; return false; } @@ -401,22 +504,82 @@ impl Flat { 0, bytemuck::cast_slice(&self.range_data), ); + // Phase 2's calls start empty, each at the start of its room. + self.phase2_call_data.clear(); + self.phase2_call_data.extend( + self.calls[phase1_calls..solid_calls] + .iter() + .map(|c| [0, 1, c.first, 0, 0]), + ); + let phase2_calls = self.phase2_call_data.len() as u64; + if phase2_calls > self.phase2_call_capacity { + self.phase2_call_capacity = phase2_calls.next_power_of_two(); + self.phase2_calls = buffer( + device, + "Flat section draw calls, phase 2", + self.phase2_call_capacity * 20, + wgpu::BufferUsages::INDIRECT | wgpu::BufferUsages::STORAGE, + ); + } + if phase2_calls > 0 { + uploads.buffer( + encoder, + &self.phase2_calls, + 0, + bytemuck::cast_slice(&self.phase2_call_data), + ); + } + let ranges_at = |first: u64, count: u64| { + wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &self.ranges, + offset: first * 16, + size: wgpu::BufferSize::new(count * 16), + }) + }; + if let (Some(phase2), Some(&(_, first, count))) = ( + phase2, + self.segments.iter().find(|(s, ..)| *s == Source::Seen), + ) { + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Flatten phase 2 section draws"), + layout: &self.seen_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: ranges_at(first, count), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: self.indices.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: phase2.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 4, + resource: self.phase2_calls.as_entire_binding(), + }, + ], + }); + self.phase2_group = Some((group, count as u32)); + } let groups: Vec<(wgpu::BindGroup, u32)> = self .segments .iter() - .map(|&(source, first, count)| { - let sorted = source.map(&sorted_page); + .filter_map(|&(source, first, count)| { + let sorted = match source { + Source::Quads => None, + Source::Seen => return None, + Source::Sorted(page) => Some(sorted_page(page)), + }; let group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("Flatten section draws"), layout: &self.compute_layout, entries: &[ wgpu::BindGroupEntry { binding: 0, - resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { - buffer: &self.ranges, - offset: first * 16, - size: wgpu::BufferSize::new(count * 16), - }), + resource: ranges_at(first, count), }, wgpu::BindGroupEntry { binding: 1, @@ -428,7 +591,7 @@ impl Flat { }, ], }); - (group, count as u32) + Some((group, count as u32)) }) .collect(); let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { @@ -464,6 +627,19 @@ impl Flat { } true } + /// After occlusion culling's test: copies the phase 2 draws it saw. + pub fn flatten_phase2(&self, encoder: &mut wgpu::CommandEncoder) { + let Some((group, count)) = &self.phase2_group else { + return; + }; + let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("Flatten phase 2 section draws"), + timestamp_writes: None, + }); + pass.set_pipeline(&self.flatten_seen); + pass.set_bind_group(0, group, &[]); + pass.dispatch_workgroups((*count).min(GROUP_LIMIT), count.div_ceil(GROUP_LIMIT), 1); + } /// Draws `calls` with a flat pipeline set and `vertices` giving each /// page's vertex buffer. pub fn draw<'a>( @@ -474,15 +650,38 @@ impl Flat { ) { pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); for call in calls { - let table = self.pages[call.page as usize] - .as_ref() - .and_then(|t| t.group.as_ref()) - .expect("prepared page"); - pass.set_vertex_buffer(0, vertices(call.page).slice(..)); - pass.set_bind_group(1, table, &[]); + self.bind_page(pass, call.page, &vertices); pass.draw_indexed(call.first..call.first + call.count, 0, 0..1); } } + /// Draws phase 2's calls, as `flatten_phase2` left them. + pub fn draw_phase2<'a>( + &self, + pass: &mut wgpu::RenderPass<'_>, + vertices: impl Fn(u32) -> &'a wgpu::Buffer, + ) { + pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); + for (k, call) in self.calls[self.phase1_calls..self.solid_calls] + .iter() + .enumerate() + { + self.bind_page(pass, call.page, &vertices); + pass.draw_indexed_indirect(&self.phase2_calls, k as u64 * 20); + } + } + fn bind_page<'a>( + &self, + pass: &mut wgpu::RenderPass<'_>, + page: u32, + vertices: &impl Fn(u32) -> &'a wgpu::Buffer, + ) { + let table = self.pages[page as usize] + .as_ref() + .and_then(|t| t.group.as_ref()) + .expect("prepared page"); + pass.set_vertex_buffer(0, vertices(page).slice(..)); + pass.set_bind_group(1, table, &[]); + } } #[cfg(test)] @@ -516,16 +715,22 @@ mod tests { fn plan_draws_runs_of_a_page_in_order() { let (draws, pages, solid) = sample(); let (mut calls, mut ranges, mut segments) = (Vec::new(), Vec::new(), Vec::new()); - let (solid_calls, total) = plan( + let Plan { + phase1_calls, + solid_calls, + total, + } = plan( &draws, &pages, solid, + solid, 4, &mut calls, &mut ranges, &mut segments, ); assert_eq!(total, 6 * 13); + assert_eq!(phase1_calls, solid_calls); let call = |page, first, count| Call { page, first, count }; // Pages 0, 0 | 1 | 0, then translucent 0, 0 (never merged with solid). assert_eq!( @@ -539,16 +744,65 @@ mod tests { ); assert_eq!(solid_calls, 3); // Solid ranges, then each sorted page's, every group padded to 4. - assert_eq!(segments, [(None, 0, 4), (Some(0), 4, 1), (Some(1), 8, 1)]); + assert_eq!( + segments, + [ + (Source::Quads, 0, 4), + (Source::Sorted(0), 4, 1), + (Source::Sorted(1), 8, 1) + ] + ); assert_eq!(ranges[3], [24, QUADS, 1024, 36]); assert_eq!(ranges[4], [12, 6, 768, 60]); assert_eq!(ranges[8], [6, 0, 40, 72]); assert_eq!(ranges.len(), 12); } + /// Phase 2's draws (here the third and fourth) get calls of their own, + /// each with room for all of its draws, and ranges naming their draw + /// and call in phase 2. + #[test] + fn plan_gives_phase_2_calls_of_its_own() { + let (draws, pages, solid) = sample(); + let (mut calls, mut ranges, mut segments) = (Vec::new(), Vec::new(), Vec::new()); + let plan = plan( + &draws, + &pages, + 2, + solid, + 4, + &mut calls, + &mut ranges, + &mut segments, + ); + assert_eq!( + plan, + Plan { + phase1_calls: 1, + solid_calls: 3, + total: 6 * 13 + } + ); + let call = |page, first, count| Call { page, first, count }; + // Phase 1: page 0 | phase 2: page 1, page 0 | translucent: page 0. + assert_eq!( + calls, + [ + call(0, 0, 30), + call(1, 30, 6), + call(0, 36, 24), + call(0, 60, 18) + ] + ); + assert_eq!(segments[1], (Source::Seen, 4, 2)); + assert_eq!(ranges[4], [6, 0, 256, 0]); + assert_eq!(ranges[5], [24, 1, 1024, 1]); + } + /// The compute pass writes exactly the indices the per-section draws /// read: quads 0 1 2 0 2 3 for solid draws, sorted indices otherwise, - /// plus the base vertex. + /// plus the base vertex. With culling, phase 2's runs hold the indices + /// of the draws the test saw, in order, and their calls count them. #[test] fn flatten_writes_the_indices_of_the_per_section_draws() { let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); @@ -564,101 +818,170 @@ mod tests { use wgpu::util::DeviceExt; let (draws, pages, solid) = sample(); let align = (u64::from(device.limits().min_storage_buffer_offset_alignment) / 16).max(1); - let (mut calls, mut ranges, mut segments) = (Vec::new(), Vec::new(), Vec::new()); - let (_, total) = plan( - &draws, - &pages, - solid, - align, - &mut calls, - &mut ranges, - &mut segments, - ); let sorted: [Vec; 2] = [ (0..32).map(|i| (i * 7) % 32).collect(), (0..8).rev().collect(), ]; - let mut expected = Vec::new(); - for (d, (_, page)) in draws.iter().zip(&pages) { - for k in 0..d[0] { - let i = match page { - None => (k / 6) * 4 + [0, 1, 2, 0, 2, 3][(k % 6) as usize], - Some(p) => sorted[*p as usize][(d[2] + k) as usize], - }; - expected.push(d[3] + i); - } - } - let storage = |entries: &[u32]| { + let indices = |d: &[u32; 5], sorted_page: Option| -> Vec { + (0..d[0]) + .map(|k| { + d[3] + match sorted_page { + None => (k / 6) * 4 + [0, 1, 2, 0, 2, 3][(k % 6) as usize], + Some(p) => sorted[p as usize][(d[2] + k) as usize], + } + }) + .collect() + }; + let storage = |entries: &[u32], usage| { device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: None, contents: bytemuck::cast_slice(entries), - usage: wgpu::BufferUsages::STORAGE, + usage: wgpu::BufferUsages::STORAGE | usage, }) }; - let range_buffer = storage(bytemuck::cast_slice(&ranges)); - let sorted_buffers = [storage(&sorted[0]), storage(&sorted[1]), storage(&[0; 4])]; - let out = device.create_buffer(&wgpu::BufferDescriptor { - label: None, - size: total * 4, - usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, - mapped_at_creation: false, - }); - let read = device.create_buffer(&wgpu::BufferDescriptor { - label: None, - size: total * 4, - usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); + let none = wgpu::BufferUsages::empty(); + let sorted_buffers = [ + storage(&sorted[0], none), + storage(&sorted[1], none), + storage(&[0; 4], none), + ]; let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(include_str!("flatten.wgsl").into()), }); - let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: None, - layout: None, - module: &module, - entry_point: Some("flatten"), - compilation_options: Default::default(), - cache: None, - }); - let mut encoder = device.create_command_encoder(&Default::default()); - { - let mut pass = encoder.begin_compute_pass(&Default::default()); - pass.set_pipeline(&pipeline); - for &(source, first, count) in &segments { - let group = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: None, - layout: &pipeline.get_bind_group_layout(0), - entries: &[ - wgpu::BindGroupEntry { - binding: 0, - resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { - buffer: &range_buffer, - offset: first * 16, - size: wgpu::BufferSize::new(count * 16), - }), - }, - wgpu::BindGroupEntry { - binding: 1, - resource: sorted_buffers[source.map_or(2, |p| p as usize)] - .as_entire_binding(), - }, - wgpu::BindGroupEntry { - binding: 2, - resource: out.as_entire_binding(), - }, - ], - }); - pass.set_bind_group(0, &group, &[]); - pass.dispatch_workgroups(count as u32, 1, 1); + let pipeline = |entry| { + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: None, + module: &module, + entry_point: Some(entry), + compilation_options: Default::default(), + cache: None, + }) + }; + let (flatten, flatten_seen) = (pipeline("flatten"), pipeline("flatten_seen")); + let read_back = |buffer: &wgpu::Buffer, words: u64| -> Vec { + let read = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: words * 4, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let mut encoder = device.create_command_encoder(&Default::default()); + encoder.copy_buffer_to_buffer(buffer, 0, &read, 0, words * 4); + queue.submit([encoder.finish()]); + read.slice(..).map_async(wgpu::MapMode::Read, |_| {}); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + bytemuck::cast_slice(&read.slice(..).get_mapped_range().unwrap()).to_vec() + }; + // Without culling, then with the third and fourth draws in phase 2, + // of which the test saw only the fourth. + for phase1 in [solid, 2] { + let (mut calls, mut ranges, mut segments) = (Vec::new(), Vec::new(), Vec::new()); + let plan = plan( + &draws, + &pages, + phase1, + solid, + align, + &mut calls, + &mut ranges, + &mut segments, + ); + // Phase 2's draws as the test leaves them: instance counts of 0, + // 1 where it saw the section. + let mut phase2: Vec<[u32; 5]> = draws[phase1..solid] + .iter() + .map(|&[count, _, first, base, instance]| [count, 0, first, base, instance]) + .collect(); + if let Some(last) = phase2.last_mut() { + last[1] = 1; + } + let phase2_calls: Vec<[u32; 5]> = calls[plan.phase1_calls..plan.solid_calls] + .iter() + .map(|c| [0, 1, c.first, 0, 0]) + .collect(); + let range_buffer = storage(bytemuck::cast_slice(&ranges), none); + let phase2_buffer = storage( + bytemuck::cast_slice(&[phase2.as_slice(), &[[0; 5]]].concat()), + none, + ); + let calls_buffer = storage( + bytemuck::cast_slice(&[phase2_calls.as_slice(), &[[0; 5]]].concat()), + wgpu::BufferUsages::COPY_SRC, + ); + let out = storage(&vec![0; plan.total as usize], wgpu::BufferUsages::COPY_SRC); + let mut encoder = device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + for &(source, first, count) in &segments { + let ranges = wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &range_buffer, + offset: first * 16, + size: wgpu::BufferSize::new(count * 16), + }); + let entry = |binding, resource| wgpu::BindGroupEntry { binding, resource }; + let (pipeline, entries) = match source { + Source::Seen => ( + &flatten_seen, + vec![ + entry(0, ranges), + entry(2, out.as_entire_binding()), + entry(3, phase2_buffer.as_entire_binding()), + entry(4, calls_buffer.as_entire_binding()), + ], + ), + Source::Quads | Source::Sorted(_) => { + let page = match source { + Source::Sorted(p) => p as usize, + _ => 2, + }; + ( + &flatten, + vec![ + entry(0, ranges), + entry(1, sorted_buffers[page].as_entire_binding()), + entry(2, out.as_entire_binding()), + ], + ) + } + }; + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, + layout: &pipeline.get_bind_group_layout(0), + entries: &entries, + }); + pass.set_pipeline(pipeline); + pass.set_bind_group(0, &group, &[]); + pass.dispatch_workgroups(count as u32, 1, 1); + } + } + queue.submit([encoder.finish()]); + let got = read_back(&out, plan.total); + // Phase 1's and the translucent calls: each of their draws, in order. + let expected: Vec = (0..draws.len()) + .filter(|i| !(phase1..solid).contains(i)) + .flat_map(|i| indices(&draws[i], pages[i].1)) + .collect(); + let drawn: Vec = calls + .iter() + .enumerate() + .filter(|(c, _)| !(plan.phase1_calls..plan.solid_calls).contains(c)) + .flat_map(|(_, c)| got[c.first as usize..(c.first + c.count) as usize].to_vec()) + .collect(); + assert_eq!(drawn, expected); + // Phase 2: page 1's run drew nothing; page 0's holds the fourth + // draw's indices. + if phase1 < solid { + let counts = read_back(&calls_buffer, phase2_calls.len() as u64 * 5); + assert_eq!(counts[0], 0); + assert_eq!(counts[5], draws[3][0]); + let run = &calls[plan.phase1_calls + 1]; + assert_eq!( + got[run.first as usize..(run.first + draws[3][0]) as usize], + indices(&draws[3], None) + ); } } - encoder.copy_buffer_to_buffer(&out, 0, &read, 0, total * 4); - queue.submit([encoder.finish()]); - read.slice(..).map_async(wgpu::MapMode::Read, |_| {}); - device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); - let got: Vec = - bytemuck::cast_slice(&read.slice(..).get_mapped_range().unwrap()).to_vec(); - assert_eq!(got, expected); } } diff --git a/crates/horizon-client/src/gfx/flatten.wgsl b/crates/horizon-client/src/gfx/flatten.wgsl index 2f57f8775..d722d7b9f 100644 --- a/crates/horizon-client/src/gfx/flatten.wgsl +++ b/crates/horizon-client/src/gfx/flatten.wgsl @@ -4,9 +4,11 @@ // translucent ones read their sorted indices. struct Range { count: u32, - // First sorted index, or QUADS for a solid draw. + // First sorted index, or QUADS for a solid draw (`flatten_seen`: its + // entry in occlusion culling's phase 2 draws). first: u32, base: u32, + // First index in the list (`flatten_seen`: its draw call). dst: u32, } const QUADS: u32 = 0xffffffffu; @@ -14,6 +16,13 @@ const GROUP: u32 = 64u; @group(0) @binding(0) var ranges: array; @group(0) @binding(1) var sorted: array; @group(0) @binding(2) var out: array; + +// Index `k` of a solid draw: quad k / 6's vertices 0 1 2 0 2 3. +fn quad(k: u32) -> u32 { + let c = k % 6u; + return (k / 6u) * 4u + select(select(c - 2u, 0u, c == 3u), c, c < 3u); +} + @compute @workgroup_size(64) fn flatten(@builtin(workgroup_id) group: vec3, @builtin(local_invocation_index) lane: u32) { @@ -25,11 +34,43 @@ fn flatten(@builtin(workgroup_id) group: vec3, for (var k = lane; k < d.count; k += GROUP) { var i: u32; if d.first == QUADS { - let c = k % 6u; - i = (k / 6u) * 4u + select(select(c - 2u, 0u, c == 3u), c, c < 3u); + i = quad(k); } else { i = sorted[d.first + k]; } out[d.dst + k] = d.base + i; } } + +// Occlusion culling's phase 2 (gfx/cull.rs), after its test: the draws as +// the test left them (`DrawIndexedIndirectArgs`, the instance count 1 where +// it saw the section), and phase 2's draw calls, whose index counts start +// at 0. A draw the test saw takes the next indices of its call's run. +@group(0) @binding(3) var draws: array; +@group(0) @binding(4) var calls: array>; +const UNSEEN: u32 = 0xffffffffu; +var start: u32; + +@compute @workgroup_size(64) +fn flatten_seen(@builtin(workgroup_id) group: vec3, + @builtin(local_invocation_index) lane: u32) { + let r = group.y * 65535u + group.x; + if r >= arrayLength(&ranges) { + return; + } + let d = ranges[r]; + if lane == 0u { + var s = UNSEEN; + if draws[d.first * 5u + 1u] != 0u { + s = atomicLoad(&calls[d.dst * 5u + 2u]) + atomicAdd(&calls[d.dst * 5u], d.count); + } + start = s; + } + let s = workgroupUniformLoad(&start); + if s == UNSEEN { + return; + } + for (var k = lane; k < d.count; k += GROUP) { + out[s + k] = d.base + quad(k); + } +} From 173a55e60803eec759082107ab79bb71fbb2cff4 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 12:08:35 +0200 Subject: [PATCH 021/408] Delete pub items nothing uses, and the stubs that hid unused code 93 pub items (78 functions and methods, 14 constants, 1 struct) in horizon-client, horizon-world, horizon-core, horizon-friends and horizon-server-files had no caller anywhere in the repository: not in the crate, the other crates, the examples, the tests or the binaries. rustc can't flag them because horizon-client and the others are libraries, where a pub item counts as used. The imports and the private helpers only they used go with them (title.rs date_string, goals.rs flag_index). Also drops the #[allow(dead_code)]/#[allow(unused)] items that only hid dead code: chat_debug_fill, merchant_title and Goals::locked_by had no caller, and four stubs (_keep, _unused, _rule_kind, const _) existed only to keep an import used. LightTables::from_parts is used by its tests, so it is #[cfg(test)] instead of allowed. Protocol id tables and entity data serializer ids stay: they mirror vanilla's registries in full. The launcher's three unused items are left for a launcher PR. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/banner.rs | 8 +--- crates/horizon-client/src/block_entities.rs | 3 -- .../horizon-client/src/block_entity_anim.rs | 12 ------ .../horizon-client/src/block_entity_render.rs | 7 ---- crates/horizon-client/src/clock.rs | 4 -- crates/horizon-client/src/command/args.rs | 8 ---- .../horizon-client/src/command/component.rs | 6 +-- crates/horizon-client/src/command/item.rs | 4 -- crates/horizon-client/src/command/mod.rs | 30 --------------- crates/horizon-client/src/command/snbt.rs | 6 +-- crates/horizon-client/src/command/vanilla.rs | 8 +--- crates/horizon-client/src/containers.rs | 18 --------- crates/horizon-client/src/debug_chart.rs | 6 --- crates/horizon-client/src/enchant.rs | 17 --------- crates/horizon-client/src/first_person.rs | 9 ----- crates/horizon-client/src/game/chat.rs | 6 +-- crates/horizon-client/src/game/lan_trading.rs | 17 --------- crates/horizon-client/src/gfx.rs | 4 -- crates/horizon-client/src/gfx/lod.rs | 4 -- crates/horizon-client/src/gossip.rs | 1 - crates/horizon-client/src/graphics_ui.rs | 8 ---- crates/horizon-client/src/hud.rs | 18 --------- crates/horizon-client/src/item_render.rs | 11 ------ crates/horizon-client/src/keybinds.rs | 9 ----- crates/horizon-client/src/keymapping.rs | 2 - crates/horizon-client/src/lan/guest.rs | 6 --- crates/horizon-client/src/lan/hub.rs | 22 ----------- crates/horizon-client/src/lan/mod.rs | 6 --- crates/horizon-client/src/lang.rs | 6 --- crates/horizon-client/src/light.rs | 2 +- crates/horizon-client/src/mobs/anim.rs | 4 -- .../horizon-client/src/mobs/creaking_heart.rs | 4 -- crates/horizon-client/src/mobs/goals.rs | 37 ------------------- crates/horizon-client/src/mobs/happy_ghast.rs | 1 - .../horizon-client/src/mobs/monster_brain.rs | 4 -- crates/horizon-client/src/mobs/nautilus.rs | 8 ---- crates/horizon-client/src/mobs/nav.rs | 22 ----------- .../src/mobs/spawn_selection.rs | 13 ------- crates/horizon-client/src/mobs/spawning.rs | 19 ---------- .../horizon-client/src/mobs/villager_brain.rs | 6 +-- crates/horizon-client/src/mobs/world.rs | 8 +--- crates/horizon-client/src/packs.rs | 5 --- crates/horizon-client/src/recipe_book.rs | 15 -------- crates/horizon-client/src/save.rs | 6 --- crates/horizon-client/src/sculk.rs | 5 --- crates/horizon-client/src/settings.rs | 4 -- crates/horizon-client/src/tab_list.rs | 3 -- crates/horizon-client/src/text.rs | 3 -- crates/horizon-client/src/title.rs | 20 ---------- crates/horizon-client/src/ui.rs | 4 -- crates/horizon-client/src/worldborder.rs | 1 - crates/horizon-core/src/density/beardifier.rs | 3 -- .../horizon-core/src/geometry/shape/join.rs | 2 - crates/horizon-core/src/paletted.rs | 28 -------------- crates/horizon-core/src/ticks/generation.rs | 3 -- crates/horizon-core/src/ticks/mod.rs | 3 -- crates/horizon-core/src/version.rs | 4 -- crates/horizon-friends/src/guest.rs | 10 ----- crates/horizon-server-files/src/user_cache.rs | 8 ---- crates/horizon-server-files/src/user_lists.rs | 5 --- crates/horizon-world/src/block_entities.rs | 3 -- crates/horizon-world/src/block_render.rs | 12 ------ crates/horizon-world/src/block_support.rs | 19 ---------- crates/horizon-world/src/block_survival.rs | 8 ---- .../horizon-world/src/component_durability.rs | 8 ---- crates/horizon-world/src/datafix/dynamic.rs | 21 ----------- crates/horizon-world/src/entity_move.rs | 3 -- .../horizon-world/src/entity_obstruction.rs | 14 ------- crates/horizon-world/src/fluid.rs | 7 ---- crates/horizon-world/src/level/bonemeal.rs | 10 ----- crates/horizon-world/src/level/classes.rs | 3 -- crates/horizon-world/src/level/mod.rs | 1 - crates/horizon-world/src/level/states.rs | 6 --- crates/horizon-world/src/level/ticks.rs | 3 -- crates/horizon-world/src/registry_fluid.rs | 3 -- crates/horizon-world/src/retrogen.rs | 3 -- crates/horizon-world/src/worldgen/aquifer.rs | 5 --- .../src/worldgen/feature_region.rs | 17 --------- .../src/worldgen/material_condition/codec.rs | 6 --- .../src/worldgen/state_provider.rs | 6 --- crates/horizon-world/src/worldgen/terrain.rs | 12 ------ 81 files changed, 8 insertions(+), 688 deletions(-) diff --git a/crates/horizon-client/src/banner.rs b/crates/horizon-client/src/banner.rs index 861294722..aa470a552 100644 --- a/crates/horizon-client/src/banner.rs +++ b/crates/horizon-client/src/banner.rs @@ -2,7 +2,7 @@ //! `banner_patterns` layers carried by banner items, shields and placed //! banners, and the loom rules of `LoomMenu` (selectable patterns, the //! six-layer limit and the result stack). -use crate::{block_entity_render::DYES, item_data, items::ItemStack, items::Items}; +use crate::{block_entity_render::DYES, items::ItemStack, items::Items}; use horizon_world::nbt::Tag; use serde_json::Value; use std::{collections::HashMap, fs, path::Path, sync::Arc}; @@ -261,12 +261,6 @@ pub fn layers_from_nbt(tag: Option<&Tag>) -> Vec { }) .collect() } -/// Keeps `item_data` linked: the `StackData` fields the banner code reads. -pub fn set_layers(stack: &mut ItemStack, layers: Vec) { - let data: &mut item_data::StackData = stack.data_mut(); - data.banner_patterns = layers; - stack.tidy(); -} #[cfg(test)] mod tests { diff --git a/crates/horizon-client/src/block_entities.rs b/crates/horizon-client/src/block_entities.rs index 93abb3711..03fff85ca 100644 --- a/crates/horizon-client/src/block_entities.rs +++ b/crates/horizon-client/src/block_entities.rs @@ -144,9 +144,6 @@ impl BlockEntities { pub fn set_states(&mut self, states: Vec) { self.states = states; } - pub fn take_states(&mut self) -> Vec { - std::mem::take(&mut self.states) - } pub fn ticking(&self, state: u32) -> Ticking { self.states.get(state as usize).copied().unwrap_or_default() } diff --git a/crates/horizon-client/src/block_entity_anim.rs b/crates/horizon-client/src/block_entity_anim.rs index 2a35c9835..d91748e73 100644 --- a/crates/horizon-client/src/block_entity_anim.rs +++ b/crates/horizon-client/src/block_entity_anim.rs @@ -382,10 +382,6 @@ impl Shulker { } out } - /// `getProgress(a)`: `Mth.lerp(a, progressOld, progress)`. - pub fn get_progress(&self, a: f32) -> f32 { - self.progress_old + a * (self.progress - self.progress_old) - } /// `ShulkerBoxBlock.canOpen`: a closed box only opens when its lid has room /// (`level.noCollision` of the half-block lid box, deflated by 1e-6). pub fn lid_box(pos: [i32; 3], facing: u8) -> [f64; 6] { @@ -668,14 +664,6 @@ impl Skull { self.animating = false; } } - /// `getAnimation(a)`. - pub fn get_animation(&self, a: f32) -> f32 { - if self.animating { - self.tick_count as f32 + a - } else { - self.tick_count as f32 - } - } } /// `DecoratedPotBlockEntity.WobbleStyle`. diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 21376d698..af4168307 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -875,13 +875,6 @@ impl BlockEntityRenderer { visibility: None, } } - /// The standing banner's pole-and-bar and flag models (`BannerRenderer.submitSpecial`). - pub fn banner_models(&self) -> Option<(&ModelPart, &ModelPart)> { - Some(( - self.models.get("standing_banner")?, - self.models.get("standing_banner_flag")?, - )) - } fn kind(&self, state: u32) -> &Kind { self.kinds.get(state as usize).unwrap_or(&Kind::None) } diff --git a/crates/horizon-client/src/clock.rs b/crates/horizon-client/src/clock.rs index 3240944ba..1aebf644a 100644 --- a/crates/horizon-client/src/clock.rs +++ b/crates/horizon-client/src/clock.rs @@ -169,10 +169,6 @@ impl TickRateManager { self.frozen_ticks_to_run -= 1; } } - /// `isEntityFrozen` for an entity that is not (and does not carry) a player. - pub fn is_entity_frozen(&self, is_player_or_carries_player: bool) -> bool { - !self.runs_normally() && !is_player_or_carries_player - } } /// What `/tick sprint` reports when it ends. diff --git a/crates/horizon-client/src/command/args.rs b/crates/horizon-client/src/command/args.rs index 68d41e14f..ccced67a7 100644 --- a/crates/horizon-client/src/command/args.rs +++ b/crates/horizon-client/src/command/args.rs @@ -812,14 +812,6 @@ pub fn java_parse_int(s: &str) -> Option { } s.parse().ok() } -/// Long.parseLong. -pub fn java_parse_long(s: &str) -> Option { - let digits = s.strip_prefix(['-', '+']).unwrap_or(s); - if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) { - return None; - } - s.parse().ok() -} /// Double.parseDouble over the characters StringReader reads as a number. pub fn java_parse_double(s: &str) -> Option { let t = s.trim_matches(|c: char| c <= ' '); diff --git a/crates/horizon-client/src/command/component.rs b/crates/horizon-client/src/command/component.rs index 9bc0668d5..15a8fa6a0 100644 --- a/crates/horizon-client/src/command/component.rs +++ b/crates/horizon-client/src/command/component.rs @@ -1,7 +1,7 @@ //! ComponentSerialization.CODEC and Style.Serializer.MAP_CODEC decoding of //! SNBT text components, with the data-fixer-upper error messages //! (ComponentArgument, StyleArgument and component-valued item data). -use super::codec::{get, no_key, not_list, not_map, snbt}; +use super::codec::{get, no_key, not_list, not_map}; use horizon_world::nbt::{Compound, Tag}; /// A DataResult error: its message and whether it carries a partial result. @@ -362,7 +362,3 @@ pub fn decode_style(t: &Tag) -> Result<(), String> { _ => Err(not_map(t)), } } -#[allow(unused)] -fn _keep(t: &Tag) -> String { - snbt(t) -} diff --git a/crates/horizon-client/src/command/item.rs b/crates/horizon-client/src/command/item.rs index 7c8abe84a..f2abc91ef 100644 --- a/crates/horizon-client/src/command/item.rs +++ b/crates/horizon-client/src/command/item.rs @@ -632,10 +632,6 @@ pub fn parse_predicate(reader: &mut Reader, reg: &Registries) -> CmdResult String { - snbt(t) -} #[cfg(test)] mod tests { diff --git a/crates/horizon-client/src/command/mod.rs b/crates/horizon-client/src/command/mod.rs index e9aeaae51..a61c8c08d 100644 --- a/crates/horizon-client/src/command/mod.rs +++ b/crates/horizon-client/src/command/mod.rs @@ -183,9 +183,6 @@ impl<'a> Reader<'a> { pub fn read_int(&mut self) -> CmdResult { self.number("int") } - pub fn read_long(&mut self) -> CmdResult { - self.number("long") - } pub fn read_double(&mut self) -> CmdResult { self.number("double") } @@ -222,21 +219,6 @@ impl<'a> Reader<'a> { } Err(CommandError::tr_at("parsing.quote.expected.end", &[], self)) } - pub fn read_quoted_string(&mut self) -> CmdResult { - if !self.can_read() { - return Ok(String::new()); - } - let next = self.peek(); - if next != '"' && next != '\'' { - return Err(CommandError::tr_at( - "parsing.quote.expected.start", - &[], - self, - )); - } - self.skip(); - self.read_string_until(next) - } pub fn read_string(&mut self) -> CmdResult { if !self.can_read() { return Ok(String::new()); @@ -539,18 +521,6 @@ impl<'a> SuggestionsBuilder<'a> { } } } - /// The same with a tooltip per candidate. - pub fn suggest_matching_tooltip<'b>( - &mut self, - candidates: impl IntoIterator, - ) { - let lower = self.remaining_lower(); - for (c, tip) in candidates { - if args::matches_sub_str(&lower, &c.to_lowercase()) { - self.suggest_tooltip(c, tip); - } - } - } } /// String.compareToIgnoreCase. pub fn compare_ignore_case(a: &str, b: &str) -> std::cmp::Ordering { diff --git a/crates/horizon-client/src/command/snbt.rs b/crates/horizon-client/src/command/snbt.rs index 05fe6d9bc..7472c7ae3 100644 --- a/crates/horizon-client/src/command/snbt.rs +++ b/crates/horizon-client/src/command/snbt.rs @@ -1,8 +1,6 @@ //! SnbtGrammar and TagParser: vanilla's packrat SNBT grammar, with its //! error messages and completion suggestions, producing NBT tags. -use super::packrat::{ - Grammar, Reason, Rule, State, Sugg, Term, Value, alt, ch, chs, look, opt, seq, -}; +use super::packrat::{Grammar, Reason, State, Sugg, Term, Value, alt, ch, chs, look, opt, seq}; use super::{CmdResult, CommandError, Reader, SuggestionsBuilder}; use horizon_world::nbt::{Compound, JavaString, Tag}; use std::rc::Rc; @@ -981,5 +979,3 @@ pub fn rule_in( } } } -#[allow(unused)] -fn _rule_kind(_: Rule) {} diff --git a/crates/horizon-client/src/command/vanilla.rs b/crates/horizon-client/src/command/vanilla.rs index fd23b82cd..cdd4848d7 100644 --- a/crates/horizon-client/src/command/vanilla.rs +++ b/crates/horizon-client/src/command/vanilla.rs @@ -3,7 +3,7 @@ //! mode keywords are read back from the parsed literals. use super::{ Dispatcher, - args::{ArgType, GameMode, Resource, integer}, + args::{ArgType, Resource, integer}, }; use crate::gamerules::{RULES, Value}; @@ -509,10 +509,6 @@ fn clone_mode(d: &mut Dispatcher, node: usize) { d.executes(l, "clone"); } } -/// Game mode names for selector `gamemode=` and the argument. -pub fn game_modes() -> [&'static str; 4] { - GameMode::ALL.map(GameMode::name) -} /// The shared vanilla tree. /// Reorder node children as vanilla registers them (Brigadier keeps /// children in registration order; smart usage lists them that way). @@ -559,5 +555,3 @@ pub fn release_dispatcher() -> &'static Dispatcher { static TREE: std::sync::OnceLock = std::sync::OnceLock::new(); TREE.get_or_init(|| build_with(false)) } -#[allow(unused)] -const _: (u8, u8) = (ALL, GAMEMASTERS); diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 854332815..6ecdf0d93 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -252,24 +252,6 @@ impl BlockEntity { }; Some(Self::Chest(vec![None; size])) } - /// The vanilla block entity type id of a container block. - pub fn id_for_block(name: &str) -> Option<&'static str> { - Some(match name { - "minecraft:chest" => "minecraft:chest", - n if n.ends_with("copper_chest") => "minecraft:chest", - "minecraft:trapped_chest" => "minecraft:trapped_chest", - "minecraft:barrel" => "minecraft:barrel", - "minecraft:hopper" => "minecraft:hopper", - "minecraft:dispenser" => "minecraft:dispenser", - "minecraft:dropper" => "minecraft:dropper", - "minecraft:furnace" => "minecraft:furnace", - "minecraft:blast_furnace" => "minecraft:blast_furnace", - "minecraft:smoker" => "minecraft:smoker", - n if n.ends_with("shulker_box") => "minecraft:shulker_box", - "minecraft:crafter" => "minecraft:crafter", - _ => return None, - }) - } pub fn id(&self) -> &'static str { match self { Self::Chest(items) => match items.len() { diff --git a/crates/horizon-client/src/debug_chart.rs b/crates/horizon-client/src/debug_chart.rs index 35fd40bd4..3d9cc5556 100644 --- a/crates/horizon-client/src/debug_chart.rs +++ b/crates/horizon-client/src/debug_chart.rs @@ -17,8 +17,6 @@ use std::{ pub const CAPACITY: usize = 240; /// `AbstractDebugChart.CHART_HEIGHT`. pub const CHART_HEIGHT: i32 = 60; -/// `TpsDebugDimensions`: a tick sample's values. -pub const FULL_TICK: usize = 0; pub const TICK_SERVER_METHOD: usize = 1; pub const SCHEDULED_TASKS: usize = 2; pub const IDLE: usize = 3; @@ -252,10 +250,6 @@ impl Chart { pub fn width(max_width: i32) -> i32 { (CAPACITY as i32 + 2).min(max_width) } - /// `getFullHeight`: the box and the min/avg/max line above it. - pub fn full_height() -> i32 { - CHART_HEIGHT + 9 - } /// `AbstractDebugChart.extractRenderState`. pub fn draw( self, diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-client/src/enchant.rs index ca2ea6f5c..2fc9ef2fb 100644 --- a/crates/horizon-client/src/enchant.rs +++ b/crates/horizon-client/src/enchant.rs @@ -359,10 +359,6 @@ impl Enchantments { } out } - /// Whether a stack draws the enchantment glint. - pub fn has_glint(&self, stack: &ItemStack) -> bool { - stack.has_any_enchantments() || self.props(&stack.item).is_some_and(|p| p.glint) - } // ---- Enchanting table (EnchantmentHelper) ---- @@ -514,19 +510,6 @@ impl Enchantments { .is_some_and(|e| e.effects.get(component).is_some()) }) } - /// The highest level among enchantments on `stack` that have `component`. - pub fn component_level(&self, stack: &ItemStack, component: &str) -> u32 { - stack - .enchantments() - .iter() - .filter(|(id, _)| { - self.get(id) - .is_some_and(|e| e.effects.get(component).is_some()) - }) - .map(|(_, l)| *l) - .max() - .unwrap_or(0) - } /// `minecraft:attributes` contributions of `stack`: (attribute, id, amount, operation). pub fn attributes(&self, stack: &ItemStack) -> Vec<(String, String, f64, String)> { let mut out = Vec::new(); diff --git a/crates/horizon-client/src/first_person.rs b/crates/horizon-client/src/first_person.rs index 463d51437..02132d942 100644 --- a/crates/horizon-client/src/first_person.rs +++ b/crates/horizon-client/src/first_person.rs @@ -289,15 +289,6 @@ impl Default for HandHeights { } } } -/// What `FirstPersonHandsAndItems.tick` decides about a hand's visible item. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct HandChange { - /// The visible item is not the hand's item after the instant replacement - /// (`mainHandItem != nextMainHand`): the hand lowers. - pub changed: bool, - /// The visible item becomes the hand's item this tick. - pub replace: bool, -} impl HandHeights { /// `FirstPersonHandsAndItems.tick`'s heights. `changed` says per hand /// whether the visible item differs from the held one once diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 20aeeb7fd..0247896f5 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -5,7 +5,7 @@ use horizon_client::{ chat::{Chat, ChatAction, ChatScreen, Commands, SYSTEM_INDICATOR}, command::Registries, gamerules::GameRules, - hud::{HudBatch, rgba}, + hud::HudBatch, screen_draw::Measure, text::{ClickEvent, Style, Text}, }; @@ -883,10 +883,6 @@ impl Game<'_> { .chat .add(&self.gui.atlas, message, None, self.ticks, focused); } - #[allow(dead_code)] - fn chat_debug_fill(&self, batch: &mut HudBatch) { - batch.fill(&self.gui.atlas, 0.0, 0.0, 1.0, 1.0, rgba(0, 0, 0, 0)); - } } /// `yyyy-MM-dd_HH.mm.ss[_n].png` (Util.getFilenameFormattedDateTime, local time /// approximated as UTC). diff --git a/crates/horizon-client/src/game/lan_trading.rs b/crates/horizon-client/src/game/lan_trading.rs index 786399dac..83aafecc2 100644 --- a/crates/horizon-client/src/game/lan_trading.rs +++ b/crates/horizon-client/src/game/lan_trading.rs @@ -129,23 +129,6 @@ impl Game<'_> { } /// The screen title: the custom name, else the profession (the client /// adds the level itself). - #[allow(dead_code)] - fn merchant_title(&self, state: &MerchantState) -> String { - if let Some(name) = &state.name { - return name.clone(); - } - let e = &self.res.stations().enchantments; - let profession = state.session.profession.trim_start_matches("minecraft:"); - if state.session.villager { - e.translate(&format!("entity.minecraft.villager.{profession}")) - .unwrap_or(profession) - .to_owned() - } else { - e.translate("entity.minecraft.wandering_trader") - .unwrap_or("Wandering Trader") - .to_owned() - } - } /// `ServerPlayer.sendMerchantOffers`, when the offers changed. fn lan_send_offers( &mut self, diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index e379ace7c..e7997fb05 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -2307,10 +2307,6 @@ impl Renderer { view_formats: &config.view_formats, }) } - /// Rendering to a texture instead of the window (`--offscreen`). - pub fn is_offscreen(&self) -> bool { - self.surface.is_none() - } /// Release the window surface before another renderer uses the same window. pub fn release_surface(&mut self) { self.surface = None; diff --git a/crates/horizon-client/src/gfx/lod.rs b/crates/horizon-client/src/gfx/lod.rs index 734110b5c..3ebec378b 100644 --- a/crates/horizon-client/src/gfx/lod.rs +++ b/crates/horizon-client/src/gfx/lod.rs @@ -119,10 +119,6 @@ impl Tile { } impl Renderer { - pub fn resident_lods(&self) -> usize { - self.lods.len() - } - pub fn upload_lod(&mut self, key: TileKey, mesh: &SectionMesh) { self.remove_lod(key); if let Some(bounds) = Bounds::mesh(mesh) diff --git a/crates/horizon-client/src/gossip.rs b/crates/horizon-client/src/gossip.rs index 9a964a3e6..9ea4a668d 100644 --- a/crates/horizon-client/src/gossip.rs +++ b/crates/horizon-client/src/gossip.rs @@ -7,7 +7,6 @@ use std::collections::BTreeMap; /// `ReputationEventType` amounts. pub const REPUTATION_CHANGE_PER_EVENT: i32 = 25; -pub const REPUTATION_CHANGE_PER_EVERLASTING_MEMORY: i32 = 20; pub const REPUTATION_CHANGE_PER_TRADE: i32 = 2; /// `GossipContainer.DISCARD_THRESHOLD`: values below this are forgotten. const DISCARD_THRESHOLD: i32 = 2; diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs index 514e64a88..d7ed82132 100644 --- a/crates/horizon-client/src/graphics_ui.rs +++ b/crates/horizon-client/src/graphics_ui.rs @@ -485,14 +485,6 @@ impl Item { _ => return None, }) } - /// Caption and value text, split from the label ("Caption: Value"). - pub fn caption_value(self, s: &Settings) -> (String, String) { - let label = self.label(s).plain(); - match label.split_once(": ") { - Some((c, v)) => (c.to_owned(), v.to_owned()), - None => (label, String::new()), - } - } pub fn slider(self, s: &Settings) -> Option { match self { Item::Vanilla(o) => o.slider_position(s), diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 82e606947..480cf6ef9 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -783,24 +783,6 @@ impl HudBatch { }; self.text_styled(atlas, &t, x, y, color, shadow) } - /// `text_styled` under a pose: GUI positions scaled by `scale`, then - /// moved to `origin` (Matrix3x2fStack translate + scale). - pub fn text_posed( - &mut self, - atlas: &HudAtlas, - text: &crate::text::Text, - at: [f32; 2], - color: u32, - scale: f32, - origin: [f32; 2], - ) -> f32 { - let start = self.vertices.len(); - let advance = self.text_styled(atlas, text, at[0], at[1], color, true); - for v in &mut self.vertices[start..] { - v.pos = [origin[0] + v.pos[0] * scale, origin[1] + v.pos[1] * scale]; - } - advance - } /// Font.drawInternal: styled glyphs, shadows first, with bold, italic, /// underline and strikethrough. `color` is the default colour and alpha. pub fn text_styled( diff --git a/crates/horizon-client/src/item_render.rs b/crates/horizon-client/src/item_render.rs index 45531bedd..c2f5c8400 100644 --- a/crates/horizon-client/src/item_render.rs +++ b/crates/horizon-client/src/item_render.rs @@ -124,17 +124,6 @@ impl ItemRenderState { pub fn is_empty(&self) -> bool { self.layers.is_empty() } - /// `pickParticleMaterial`: a random layer's particle sprite. - pub fn pick_particle( - &self, - random: &mut impl horizon_core::random::RandomSource, - ) -> Option { - if self.layers.is_empty() { - return None; - } - let i = random.next_int_bound(self.layers.len() as i32).unwrap_or(0) as usize; - self.layers.get(i).map(|l| l.particle.clone()) - } /// `usesBlockLight` of the first layer (GUI lighting choice). pub fn uses_block_light(&self) -> bool { self.layers.first().is_some_and(|l| l.uses_block_light) diff --git a/crates/horizon-client/src/keybinds.rs b/crates/horizon-client/src/keybinds.rs index 5f8c0876b..a59aa627c 100644 --- a/crates/horizon-client/src/keybinds.rs +++ b/crates/horizon-client/src/keybinds.rs @@ -295,15 +295,6 @@ impl KeyBinds { self.keys.insert(n, key.to_owned()); } } - /// Load `key_` from options.txt; false for unknown mappings. - pub fn set_saved(&mut self, name: &str, key: &str) -> bool { - if MAPPINGS.iter().any(|m| m.0 == name) { - self.set(name, key); - true - } else { - false - } - } pub fn saved(&self) -> Vec<(&'static str, String)> { MAPPINGS .iter() diff --git a/crates/horizon-client/src/keymapping.rs b/crates/horizon-client/src/keymapping.rs index e598fbf71..e438c27ce 100644 --- a/crates/horizon-client/src/keymapping.rs +++ b/crates/horizon-client/src/keymapping.rs @@ -104,8 +104,6 @@ pub const SNEAK: usize = 0; pub const SPRINT: usize = 1; /// Attack (mouse). pub const ATTACK: usize = 2; -/// Use (mouse). -pub const USE: usize = 3; /// The `ToggleKeyMapping`s `Options` builds: sneak and sprint (keyboard, /// restored after a screen), attack (mouse, restored) and use (mouse, not diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 4236280cd..9251107ca 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -15,7 +15,6 @@ use std::{ /// GameType ids. pub const SURVIVAL: i32 = 0; pub const CREATIVE: i32 = 1; -pub const ADVENTURE: i32 = 2; pub const SPECTATOR: i32 = 3; /// An effect as last sent in ClientboundUpdateMobEffectPacket. @@ -332,11 +331,6 @@ impl Guest { pub fn send(&self, packet: &play::Clientbound) { self.sender.send(packet.encode()); } - pub fn send_all(&self, packets: &[play::Clientbound]) { - for p in packets { - self.send(p); - } - } pub fn chunk(&self) -> (i32, i32) { ( (self.position[0].floor() as i32) >> 4, diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 1330b0ae4..cbe0ecab7 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -172,13 +172,6 @@ pub struct Hub { fn string(s: &str) -> Tag { Tag::String(JavaString::from(s)) } -pub fn yellow_translation(key: &str, args: &[&str]) -> Tag { - let mut t = translatable(key, args); - if let Tag::Compound(map) = &mut t { - map.insert(JavaString::from("color"), string("yellow")); - } - t -} /// Player.getDisplayName for a player in no team: the name, suggesting /// `/tell NAME `, showing the player on hover and inserting the name. @@ -1360,21 +1353,6 @@ impl Hub { (!batch.is_empty()).then_some(batch) } - /// Resend a chunk to everyone who has it (a block entity changed, relight). - pub fn resend_chunk(&mut self, world: &World, x: i32, z: i32) { - let Some(chunk) = world.chunks.get(&(x, z)) else { - return; - }; - let body = self.encoder.body_in(chunk, world); - for g in self - .guests - .iter() - .filter(|g| g.sent_chunks.contains(&(x, z))) - { - g.sender.send(body.clone()); - } - } - /// `ChunkHolder.broadcastChanges`' light part: the light sections that /// changed in a column go to the players for whom it is on the border of /// what they track (`ChunkMap.isChunkOnTrackedBorder`); the others light diff --git a/crates/horizon-client/src/lan/mod.rs b/crates/horizon-client/src/lan/mod.rs index c2f35bc8e..5e4aedbab 100644 --- a/crates/horizon-client/src/lan/mod.rs +++ b/crates/horizon-client/src/lan/mod.rs @@ -272,9 +272,6 @@ impl Shared { pub fn max_players(&self) -> usize { self.max_players.load(Ordering::Relaxed) } - pub fn set_max_players(&self, n: usize) { - self.max_players.store(n, Ordering::Relaxed); - } pub fn release(&self, uuid: u128) { self.online.lock().unwrap().retain(|(u, _)| *u != uuid); } @@ -513,9 +510,6 @@ impl Lan { pub fn reserve(&self, uuid: u128) { self.shared.reserved.lock().unwrap().insert(uuid); } - pub fn set_motd(&self, motd: &str) { - *self.shared.motd.lock().unwrap() = motd.to_owned(); - } pub fn stop(&mut self) { self.shared.stop.store(true, Ordering::Relaxed); self.stop_listening(); diff --git a/crates/horizon-client/src/lang.rs b/crates/horizon-client/src/lang.rs index 9f04ef27a..15f47285a 100644 --- a/crates/horizon-client/src/lang.rs +++ b/crates/horizon-client/src/lang.rs @@ -77,12 +77,6 @@ pub fn apply_deprecated(map: &mut HashMap, json: &[u8]) { } impl Language { - pub fn from_map(code: &str, map: HashMap) -> Self { - Self { - code: code.to_owned(), - map, - } - } /// ClientLanguage.loadFrom: en_us first, then the selected language, each /// from every namespace and every source in priority order (later sources /// override). diff --git a/crates/horizon-client/src/light.rs b/crates/horizon-client/src/light.rs index d7ea7d7fd..6cb4b65b1 100644 --- a/crates/horizon-client/src/light.rs +++ b/crates/horizon-client/src/light.rs @@ -203,7 +203,7 @@ impl LightTables { Ok(tables) } /// Assembled tables (tests and benchmarks): derives the packed light cache. - #[allow(dead_code)] + #[cfg(test)] fn from_parts(cells: Vec, occludes: Vec, faces: usize) -> Self { let mut tables = Self { cells, diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index 1410bf858..aa0d8fb2a 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -239,10 +239,6 @@ pub enum ArmPose { /// Raising a trident to throw it (or to launch with Riptide). ThrowTrident, } -/// HumanoidModel.setupAnim for piglins: `PiglinModel` poses the arms itself. -pub fn humanoid_item(p: &mut Poses, s: &State, _holding: bool) { - humanoid(p, s, &Hum::new(ArmPose::Empty, ArmPose::Empty)); -} /// HumanoidModel.setupAnim with empty hands (endermen). pub fn humanoid_pub(p: &mut Poses, s: &State, _m: &Mob) { humanoid(p, s, &Hum::new(ArmPose::Empty, ArmPose::Empty)); diff --git a/crates/horizon-client/src/mobs/creaking_heart.rs b/crates/horizon-client/src/mobs/creaking_heart.rs index e3c0e4cb7..1172b229c 100644 --- a/crates/horizon-client/src/mobs/creaking_heart.rs +++ b/crates/horizon-client/src/mobs/creaking_heart.rs @@ -152,10 +152,6 @@ pub fn protector(heart: &mut CreakingHeart, host: &impl HeartHost) -> Option bool { - protector(heart, host) == Some(id) -} fn distance_to_creaking(heart: &mut CreakingHeart, pos: [i32; 3], host: &impl HeartHost) -> f64 { protector(heart, host) .and_then(|id| host.mob(id)) diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index c12f9e7ee..7f73e32c4 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -76,9 +76,6 @@ pub struct GoalSelector { locked: [Option; 4], pub disabled: u8, } -fn flag_index(f: u8) -> usize { - f.trailing_zeros() as usize -} impl GoalSelector { pub fn add(&mut self, priority: i32, goal: impl Goal + 'static) { self.goals.push(Wrapped { @@ -174,10 +171,6 @@ impl GoalSelector { } self.locked = [None; 4]; } - #[allow(dead_code)] - fn locked_by(&self, flag: u8) -> Option { - self.locked[flag_index(flag)] - } } // --- random positions (DefaultRandomPos / LandRandomPos / RandomPos) ------- @@ -565,36 +558,6 @@ impl Mob { m.land_up_out_of_solid(w, p) }) } - /// LandRandomPos.getPosTowards - pub fn land_random_pos_towards( - &mut self, - w: &MobWorld, - h: i32, - v: i32, - to: [f64; 3], - ) -> Option<[f64; 3]> { - let (xd, zd) = (to[0] - self.position.x, to[2] - self.position.z); - self.pick_best(w, |m| { - let d = m.random_direction_within( - 0.0, - f64::from(h), - v, - 0, - xd, - zd, - std::f64::consts::FRAC_PI_2, - )?; - let p = m.toward(f64::from(h), d); - if p[1] < crate::chunk::MIN_Y - || p[1] >= 320 - || m.restricted(f64::from(h), p) - || !m.stable_destination(w, p) - { - return None; - } - m.land_up_out_of_solid(w, p) - }) - } pub fn target_info(&self, w: &MobWorld) -> Option { self.ai.target.and_then(|t| w.target_info(t)) } diff --git a/crates/horizon-client/src/mobs/happy_ghast.rs b/crates/horizon-client/src/mobs/happy_ghast.rs index c0ee860dd..6fc07e898 100644 --- a/crates/horizon-client/src/mobs/happy_ghast.rs +++ b/crates/horizon-client/src/mobs/happy_ghast.rs @@ -17,7 +17,6 @@ use horizon_core::{ // Happy ghast state: `head` the harness, `scratch[0]` 1 once set up as a // baby and 2 as an adult, `ai.home` the restriction, `counter` // the end tick of the follow-an-adult range pick. -pub const BABY_SCALE: f64 = 0.2375; /// `Attributes.FLYING_SPEED` and the speed `travel` uses (`* 5 / 3`). pub const FLYING_SPEED: f64 = 0.05; pub const AIR_SPEED: f32 = 0.05 * 5.0 / 3.0; diff --git a/crates/horizon-client/src/mobs/monster_brain.rs b/crates/horizon-client/src/mobs/monster_brain.rs index eeb2c42f2..1099e0bc3 100644 --- a/crates/horizon-client/src/mobs/monster_brain.rs +++ b/crates/horizon-client/src/mobs/monster_brain.rs @@ -250,10 +250,6 @@ pub fn nearest_players(m: &Mob) -> Vec { .and_then(|b| b.mem.nearest_players.value()) .unwrap_or_default() } -/// The damage the brain remembers (`HURT_BY`). -pub fn hurt_by_present(m: &Mob) -> bool { - brain(m).is_some_and(|b| b.mem.hurt_by.present()) -} /// `HURT_BY`'s damage source entity, if a living one. fn hurt_by_entity(m: &Mob, w: &MobWorld) -> Option { let t = brain(m)?.mem.hurt_by.value()?; diff --git a/crates/horizon-client/src/mobs/nautilus.rs b/crates/horizon-client/src/mobs/nautilus.rs index efeb5cc40..2fcf7eb46 100644 --- a/crates/horizon-client/src/mobs/nautilus.rs +++ b/crates/horizon-client/src/mobs/nautilus.rs @@ -76,14 +76,6 @@ pub fn finalize(m: &mut Mob, warm_ocean: bool) { m.extra.variant = u8::from(warm_ocean); } } -/// `checkNautilusSpawnRules`: 5 to 25 blocks below sea level, water below -/// and above. -pub fn spawn_rules_ok(w: &MobWorld, x: i32, y: i32, z: i32) -> bool { - let sea = 63; - (sea - 25..=sea - 5).contains(&y) - && w.fluid(x, y - 1, z) == Fluid::Water - && w.block_name(x, y + 1, z) == "minecraft:water" -} /// `getControllingPassenger`: a player on a saddled nautilus. pub fn controlled(m: &Mob) -> bool { m.rider.is_some() && m.extra.saddled diff --git a/crates/horizon-client/src/mobs/nav.rs b/crates/horizon-client/src/mobs/nav.rs index 24dafa48d..793303c6d 100644 --- a/crates/horizon-client/src/mobs/nav.rs +++ b/crates/horizon-client/src/mobs/nav.rs @@ -582,26 +582,4 @@ impl Mob { NavKind::Amphibious => !w.facts.is_air(w.world.block(p[0], p[1] - 1, p[2])), } } - pub fn should_recompute_path(&self, p: [i32; 3]) -> bool { - if self.ai.nav.delayed_recompute { - return false; - } - let Some(path) = &self.ai.nav.path else { - return false; - }; - if path.is_done() || path.nodes.is_empty() { - return false; - } - let Some(end) = path.end() else { return false }; - let mid = [ - (f64::from(end.x) + self.position.x) / 2.0, - (f64::from(end.y) + self.position.y) / 2.0, - (f64::from(end.z) + self.position.z) / 2.0, - ]; - let d = (f64::from(p[0]) + 0.5 - mid[0]).powi(2) - + (f64::from(p[1]) + 0.5 - mid[1]).powi(2) - + (f64::from(p[2]) + 0.5 - mid[2]).powi(2); - let r = (path.nodes.len() - path.next) as f64; - d < r * r - } } diff --git a/crates/horizon-client/src/mobs/spawn_selection.rs b/crates/horizon-client/src/mobs/spawn_selection.rs index 046583a1f..4e51722f1 100644 --- a/crates/horizon-client/src/mobs/spawn_selection.rs +++ b/crates/horizon-client/src/mobs/spawn_selection.rs @@ -769,19 +769,6 @@ pub fn weighted_pick(list: &[SpawnEntry], random: &mut impl RandomSource) -> Opt None } -/// `NaturalSpawner.getRandomSpawnMobAt`. -pub fn random_spawn_mob_at( - list: &[SpawnEntry], - category: &str, - reduced_water_ambient: bool, - random: &mut impl RandomSource, -) -> Option { - if category == "water_ambient" && reduced_water_ambient && random.next_float() < 0.98 { - return None; - } - weighted_pick(list, random) -} - /// `SpawnerData.count().sample(random)`: a constant draws nothing. pub fn sample_count(entry: &SpawnEntry, random: &mut impl RandomSource) -> u32 { if entry.constant { diff --git a/crates/horizon-client/src/mobs/spawning.rs b/crates/horizon-client/src/mobs/spawning.rs index 0bfd5d223..93e3fe119 100644 --- a/crates/horizon-client/src/mobs/spawning.rs +++ b/crates/horizon-client/src/mobs/spawning.rs @@ -30,25 +30,6 @@ pub struct BiomeFacts { pub fn placement_ok(species: Species, w: &MobWorld, x: i32, y: i32, z: i32) -> bool { super::spawn_rules::is_spawn_position_ok(species, w, x, y, z) } -/// `SpawnPlacements.checkSpawnRules` for a natural spawn. -pub fn spawn_rules_ok( - species: Species, - w: &MobWorld, - random: &mut impl RandomSource, - x: i32, - y: i32, - z: i32, -) -> bool { - super::spawn_rules::check_spawn_rules( - species, - w, - super::spawn_rules::Reason::Natural, - random, - x, - y, - z, - ) -} /// Mob.finalizeSpawn for natural, chunk-generation and summoned mobs. /// `DifficultyInstance`: the local difficulty at a position. #[derive(Clone, Copy, Debug)] diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index e02cfa176..194bd75ff 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -10,7 +10,7 @@ //! other `GateBehavior`s shuffle with a random of their own, seeded with //! `Brain::shuffle_seed` when the brain is built. use super::{ - Mob, MobEvent, MobWorld, Seen, Species, Who, + Mob, MobEvent, MobWorld, Species, Who, path::{Path, PathNode}, }; use horizon_core::{ @@ -4156,10 +4156,6 @@ pub fn woken(m: &mut Mob, now: i64) { pub fn potential_job_site(m: &Mob) -> Option<[i32; 3]> { mem_ref(m).and_then(|mm| mm.potential_job_site.value()) } -/// Whether a seen mob is a villager wanting to breed (`AgeableMob::canBreed`). -pub fn seen_can_breed(s: &Seen) -> bool { - s.species == Species::Villager && s.in_love -} /// The memories other villagers read: the interaction target, the path's /// nodes (while it is not done), whether a golem was seen lately and the /// last sleep. diff --git a/crates/horizon-client/src/mobs/world.rs b/crates/horizon-client/src/mobs/world.rs index 79bbaa30c..7836a49ef 100644 --- a/crates/horizon-client/src/mobs/world.rs +++ b/crates/horizon-client/src/mobs/world.rs @@ -1,7 +1,7 @@ //! What mobs read from the level: block solidity, ray clipping for line of //! sight (`ClipContext.Block.COLLIDER`), sky visibility, light-dependent //! values and the positions of other entities. -use super::{MobWorld, Seen, Species, Who, data}; +use super::{MobWorld, Seen, Who, data}; use crate::{ blocks::{BlockFacts, Fluid}, collisions::SceneCollisions, @@ -269,12 +269,6 @@ impl MobWorld<'_> { }); v.into_iter() } - pub fn count_species(&self, species: Species) -> usize { - self.others - .iter() - .filter(|s| s.species == species && s.alive) - .count() - } } /// Level.clip with VISUAL shapes and no fluids: the block the segment first diff --git a/crates/horizon-client/src/packs.rs b/crates/horizon-client/src/packs.rs index 7bd4fd782..5daaaacad 100644 --- a/crates/horizon-client/src/packs.rs +++ b/crates/horizon-client/src/packs.rs @@ -804,11 +804,6 @@ impl SelectionModel { false } } - /// Whether activating the entry asks first (`handlePackSelection`'s - /// ConfirmScreen for an incompatible pack). - pub fn needs_confirmation(&self, selected: bool, i: usize) -> bool { - self.can_select(selected, i) && !self.unselected[i].compatible - } /// `moveUp` / `moveDown` when allowed. pub fn move_by(&mut self, selected: bool, i: usize, up: bool) -> bool { let ok = if up { diff --git a/crates/horizon-client/src/recipe_book.rs b/crates/horizon-client/src/recipe_book.rs index 27051bbc6..fa247a695 100644 --- a/crates/horizon-client/src/recipe_book.rs +++ b/crates/horizon-client/src/recipe_book.rs @@ -384,21 +384,6 @@ impl Book { order, } } - /// Which book a recipe id belongs to. - pub fn book_of(&self, id: &str) -> Option { - let e = self.entries.iter().find(|e| e.id == id)?; - Some(match e.category { - Category::CraftingBuilding - | Category::CraftingRedstone - | Category::CraftingEquipment - | Category::CraftingMisc => BookType::Crafting, - Category::FurnaceFood | Category::FurnaceBlocks | Category::FurnaceMisc => { - BookType::Furnace - } - Category::BlastBlocks | Category::BlastMisc => BookType::BlastFurnace, - Category::SmokerFood => BookType::Smoker, - }) - } /// `RecipeDisplayEntry.canCraft`: the recipe's placement ingredients /// (`craftingRequirements`) can all be found in `stock`. pub fn can_craft(&self, entry: &Entry, stock: &crate::menu::place::Stacked) -> bool { diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index dd86c8f9c..7819a9b0b 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -750,12 +750,6 @@ fn heightmaps(chunk: &Chunk, tables: &SaveTables) -> Tag { ) })) } -/// The heightmaps a ClientboundLevelChunkPacketData carries (the types with -/// sendToClient: WORLD_SURFACE, MOTION_BLOCKING, MOTION_BLOCKING_NO_LEAVES), -/// as (network id, packed longs) in Heightmap.Types order. -pub fn client_heightmaps(chunk: &Chunk, tables: &SaveTables) -> Vec<(i32, Vec)> { - client_heightmaps_in(&chunk.sections, tables, MIN_Y, SECTIONS as i32 * 16) -} /// The client heightmaps of a column's sections, in a level from `min_y`, /// `height` blocks high. pub fn client_heightmaps_in( diff --git a/crates/horizon-client/src/sculk.rs b/crates/horizon-client/src/sculk.rs index 58ac921ff..3affbda77 100644 --- a/crates/horizon-client/src/sculk.rs +++ b/crates/horizon-client/src/sculk.rs @@ -78,7 +78,6 @@ pub const RESONANCE: [&str; 15] = [ ]; pub const SHRIEK: &str = "minecraft:shriek"; pub const TENDRILS_CLICKING: &str = "minecraft:sculk_sensor_tendrils_clicking"; -pub const NO_VIBRATION_FREQUENCY: i32 = 0; /// `VibrationSystem.getGameEventFrequency`. pub fn frequency(event: &str) -> i32 { @@ -567,10 +566,6 @@ pub struct WardenSpawnTracker { } impl WardenSpawnTracker { pub const MAX_WARNING_LEVEL: i32 = 4; - /// Blocks around a shrieker within which players are warned. - pub const PLAYER_SEARCH_RADIUS: f64 = 16.0; - /// `AABB.ofSize(centre, 48, 48, 48)` for an existing warden. - pub const WARNING_CHECK_DIAMETER: f64 = 48.0; const DECREASE_EVERY: i32 = 12000; const INCREASE_COOLDOWN: i32 = 200; pub fn tick(&mut self) { diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 1fadacf57..97acc91c9 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -81,10 +81,6 @@ pub fn sound_source(event: &str) -> usize { index("master") } } -/// Volume multiplier of an event's source (master applied separately). -pub fn event_volume(event: &str) -> f32 { - source_volume(sound_source(event)) -} /// Volume multiplier of a sound source by index. pub fn source_volume(i: usize) -> f32 { if i == 0 { diff --git a/crates/horizon-client/src/tab_list.rs b/crates/horizon-client/src/tab_list.rs index 2c03f999f..0374e3fc2 100644 --- a/crates/horizon-client/src/tab_list.rs +++ b/crates/horizon-client/src/tab_list.rs @@ -317,9 +317,6 @@ impl TabList { self.visible = visible; } } - pub fn is_visible(&self) -> bool { - self.visible - } /// `reset`. pub fn reset(&mut self) { self.header = None; diff --git a/crates/horizon-client/src/text.rs b/crates/horizon-client/src/text.rs index 9f39155d1..11abb3328 100644 --- a/crates/horizon-client/src/text.rs +++ b/crates/horizon-client/src/text.rs @@ -455,9 +455,6 @@ impl Text { } out } - pub fn char_count(&self) -> usize { - self.spans.iter().map(|s| s.text.chars().count()).sum() - } } /// The style fields of a component's JSON. diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index b4958c600..f77ac93eb 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -1630,26 +1630,6 @@ fn caret_field<'a>( _ => None, } } -/// `yyyy/MM/dd HH:mm` (UTC) for a modification time in Unix seconds. -pub fn date_label(secs: u64) -> String { - date_string(secs) -} -fn date_string(secs: u64) -> String { - // Civil date from Unix time (days-from-civil inverse), UTC. - let days = (secs / 86400) as i64; - let (h, m) = ((secs % 86400) / 3600, (secs % 3600) / 60); - let z = days + 719_468; - let era = z.div_euclid(146_097); - let doe = z - era * 146_097; - let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; - let y = yoe + era * 400; - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let d = doy - (153 * mp + 2) / 5 + 1; - let mo = if mp < 10 { mp + 3 } else { mp - 9 }; - let y = if mo <= 2 { y + 1 } else { y }; - format!("{y}-{mo:02}-{d:02} {h:02}:{m:02}") -} #[cfg(test)] mod classic_tests { diff --git a/crates/horizon-client/src/ui.rs b/crates/horizon-client/src/ui.rs index b1ffab866..63a6d1de7 100644 --- a/crates/horizon-client/src/ui.rs +++ b/crates/horizon-client/src/ui.rs @@ -793,10 +793,6 @@ impl EditBox { text_color: rgba(224, 224, 224, 255), } } - /// When the field gained focus, for the cursor's blink. - pub fn focused_since(&mut self, at: Instant) { - self.focused_at = at; - } pub fn inner_width(&self) -> f32 { if self.bordered { self.width - 8.0 diff --git a/crates/horizon-client/src/worldborder.rs b/crates/horizon-client/src/worldborder.rs index 3ed4ea152..3673db403 100644 --- a/crates/horizon-client/src/worldborder.rs +++ b/crates/horizon-client/src/worldborder.rs @@ -7,7 +7,6 @@ pub use horizon_core::geometry::border::BorderStatus; /// `WorldBorder.MAX_SIZE` (the float 5.999997E7 as a double). pub const MAX_SIZE: f64 = 59_999_968.0; -pub const MAX_CENTER: f64 = 2.999_998_4e7; /// `BorderStatus.getColor`: the wall colour. pub fn status_color(status: BorderStatus) -> u32 { diff --git a/crates/horizon-core/src/density/beardifier.rs b/crates/horizon-core/src/density/beardifier.rs index 5dec64189..b041be160 100644 --- a/crates/horizon-core/src/density/beardifier.rs +++ b/crates/horizon-core/src/density/beardifier.rs @@ -168,9 +168,6 @@ impl Beardifier { self.kernel_junctions = junctions; self } - pub fn affected_bounds(&self) -> Option { - self.affected - } fn sample_unchecked(&self, [x, y, z]: [i32; 3]) -> f32 { let mut value = 0.; // The kernel is a process-wide constant; resolving it once keeps the diff --git a/crates/horizon-core/src/geometry/shape/join.rs b/crates/horizon-core/src/geometry/shape/join.rs index 57c981e65..261c33802 100644 --- a/crates/horizon-core/src/geometry/shape/join.rs +++ b/crates/horizon-core/src/geometry/shape/join.rs @@ -13,8 +13,6 @@ impl ShapeOp { pub const XOR: Self = Self(6); pub const ONLY_FIRST: Self = Self(4); pub const ONLY_SECOND: Self = Self(2); - pub const FIRST: Self = Self(12); - pub const SECOND: Self = Self(10); pub const fn from_truth_table(bits: u8) -> Self { Self(bits & 15) } diff --git a/crates/horizon-core/src/paletted.rs b/crates/horizon-core/src/paletted.rs index d9ade23f2..802eac225 100644 --- a/crates/horizon-core/src/paletted.rs +++ b/crates/horizon-core/src/paletted.rs @@ -466,34 +466,6 @@ impl PalettedContainer { } } } - /// Block ids as 16-bit values (callers whose registry fits in 16 bits). - pub fn unpack_u16(&self, out: &mut [u16; 4096]) { - debug_assert_eq!(self.strategy.entries(), 4096); - match &self.palette { - Palette::Single(value) => out.fill(*value as u16), - Palette::List(list) => { - let bits = usize::from(self.bits); - let per = 64 / bits; - let m = mask(self.bits); - for (chunk, &word) in out.chunks_mut(per).zip(&self.words) { - for (slot, cell) in chunk.iter_mut().enumerate() { - let id = ((word >> (slot * bits)) & m) as usize; - *cell = list[id] as u16; - } - } - } - Palette::Global => { - let bits = usize::from(self.bits); - let per = 64 / bits; - let m = mask(self.bits); - for (chunk, &word) in out.chunks_mut(per).zip(&self.words) { - for (slot, cell) in chunk.iter_mut().enumerate() { - *cell = ((word >> (slot * bits)) & m) as u16; - } - } - } - } - } /// A container holding `values` in the smallest configuration for their /// distinct count, with palette ids in first-occurrence order, like a /// container unpacked from disk. diff --git a/crates/horizon-core/src/ticks/generation.rs b/crates/horizon-core/src/ticks/generation.rs index 4e1fdce6f..f81d9353e 100644 --- a/crates/horizon-core/src/ticks/generation.rs +++ b/crates/horizon-core/src/ticks/generation.rs @@ -91,9 +91,6 @@ impl WorldGenTickAccess { pub fn containers_mut(&mut self) -> &mut C { &mut self.containers } - pub fn into_containers(self) -> C { - self.containers - } pub fn schedule(&mut self, tick: ScheduledTick) -> Result { Ok(self.containers.container_at(tick.pos)?.schedule(tick)) } diff --git a/crates/horizon-core/src/ticks/mod.rs b/crates/horizon-core/src/ticks/mod.rs index f3cc83999..693aab130 100644 --- a/crates/horizon-core/src/ticks/mod.rs +++ b/crates/horizon-core/src/ticks/mod.rs @@ -636,7 +636,4 @@ impl LevelTicks { pub fn copy_area(&mut self, area: TickArea, offset: BlockPos) { self.schedule_copy(self.area_ticks(area), offset); } - pub fn copy_area_from(&mut self, source: &Self, area: TickArea, offset: BlockPos) { - self.schedule_copy(source.area_ticks(area), offset); - } } diff --git a/crates/horizon-core/src/version.rs b/crates/horizon-core/src/version.rs index 29994823c..cb3e85629 100644 --- a/crates/horizon-core/src/version.rs +++ b/crates/horizon-core/src/version.rs @@ -11,10 +11,6 @@ pub const PROTOCOL_VERSION: i32 = 777; pub const DATA_VERSION: i32 = 5023; /// `WorldVersion.packVersion(PackType.CLIENT_RESOURCES)`: (major, minor). pub const RESOURCE_PACK_FORMAT: (i64, i64) = (97, 1); -/// `WorldVersion.packVersion(PackType.SERVER_DATA)`: (major, minor). -pub const DATA_PACK_FORMAT: (i64, i64) = (121, 0); -/// The Java major version the game runs on. -pub const JAVA_VERSION: u32 = 25; /// `WorldVersion.stable()`: false for snapshots and pre-releases. pub const STABLE: bool = true; /// `WorldVersion.buildTime()` as `Date.toString()` prints it in UTC (`/version`). diff --git a/crates/horizon-friends/src/guest.rs b/crates/horizon-friends/src/guest.rs index 4f64bb1cc..492f4d482 100644 --- a/crates/horizon-friends/src/guest.rs +++ b/crates/horizon-friends/src/guest.rs @@ -296,14 +296,4 @@ impl Tunnel { })?; Ok((port, thread)) } - /// The protected stream itself (tests, or a client that reads it - /// directly). - pub fn into_stream( - self, - ) -> ( - crypto::SecureReader, - crypto::SecureWriter, - ) { - self.secure - } } diff --git a/crates/horizon-server-files/src/user_cache.rs b/crates/horizon-server-files/src/user_cache.rs index c8ccd6cf0..38e779488 100644 --- a/crates/horizon-server-files/src/user_cache.rs +++ b/crates/horizon-server-files/src/user_cache.rs @@ -190,14 +190,6 @@ impl UserCache { result } - /// `get(UUID)`: a cached player by id (expired or not). - pub fn get_by_id(&mut self, id: u128) -> Option { - let index = *self.by_uuid.get(&id)?; - self.operations += 1; - self.infos[index].last_access = self.operations; - Some(self.infos[index].user.clone()) - } - /// The file's text: the 1000 most recently used entries, most recent /// first, as Gson writes them (compact, HTML-safe). pub fn to_json(&self) -> String { diff --git a/crates/horizon-server-files/src/user_lists.rs b/crates/horizon-server-files/src/user_lists.rs index 77de64e31..5bef4f38f 100644 --- a/crates/horizon-server-files/src/user_lists.rs +++ b/crates/horizon-server-files/src/user_lists.rs @@ -416,11 +416,6 @@ pub type WhiteList = UserList; pub type BanList = UserList>; pub type IpBanList = UserList>; -/// IpBanList.getIpFromAddress. -pub fn ip_of(address: &std::net::SocketAddr) -> String { - address.ip().to_string() -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/horizon-world/src/block_entities.rs b/crates/horizon-world/src/block_entities.rs index 22a2bc959..1ee8a90e0 100644 --- a/crates/horizon-world/src/block_entities.rs +++ b/crates/horizon-world/src/block_entities.rs @@ -62,9 +62,6 @@ impl ProtoBlockEntities { pub fn active(&self, position: BlockPos) -> Option<&E> { self.active.get(&position) } - pub fn active_mut(&mut self, position: BlockPos) -> Option<&mut E> { - self.active.get_mut(&position) - } pub fn pending(&self, position: BlockPos) -> Option<&Tag> { self.pending.get(&position) } diff --git a/crates/horizon-world/src/block_render.rs b/crates/horizon-world/src/block_render.rs index 1ed9c51af..aa10d361c 100644 --- a/crates/horizon-world/src/block_render.rs +++ b/crates/horizon-world/src/block_render.rs @@ -157,12 +157,6 @@ impl FaceVisibility { } } } - /// Whether the state's occlusion face toward `direction` is the full square. - pub fn full_face(&self, state: BlockStateId, direction: Direction) -> bool { - self.states - .get(state.0 as usize) - .is_some_and(|s| s.faces[direction as usize] == 1) - } /// The state's occlusion face toward `direction` (`getFaceOcclusionShape`) and /// its shared ID: 0 is the empty singleton, 1 the full-block singleton. pub fn occlusion_face( @@ -173,12 +167,6 @@ impl FaceVisibility { let id = self.states.get(state.0 as usize)?.faces[direction as usize]; Some((id, &self.faces[id as usize])) } - /// Whether the state's occlusion face toward `direction` is empty. - pub fn empty_face(&self, state: BlockStateId, direction: Direction) -> bool { - self.states - .get(state.0 as usize) - .is_none_or(|s| s.faces[direction as usize] == 0) - } pub fn skip_rendering( &self, state: BlockStateId, diff --git a/crates/horizon-world/src/block_support.rs b/crates/horizon-world/src/block_support.rs index 295999d18..d3ac386cd 100644 --- a/crates/horizon-world/src/block_support.rs +++ b/crates/horizon-world/src/block_support.rs @@ -186,25 +186,6 @@ impl<'r> BlockSupportRegistry<'r> { pub fn registry(&self) -> &'r BlockRegistry { self.cached.registry() } - pub fn support_shape( - &self, - world: &mut W, - state: BlockStateId, - position: [i32; 3], - ) -> Result> { - if let Some(shape) = self - .cached - .cached_shape(state) - .map_err(SupportQueryError::Data)? - { - return Ok(shape.clone()); - } - self.dynamic - .get(&state) - .ok_or(SupportQueryError::Unsupported(state))? - .shape(world, position) - .map_err(SupportQueryError::Dynamic) - } pub fn is_face_sturdy( &self, world: &mut W, diff --git a/crates/horizon-world/src/block_survival.rs b/crates/horizon-world/src/block_survival.rs index bb21f46df..ae53451ba 100644 --- a/crates/horizon-world/src/block_survival.rs +++ b/crates/horizon-world/src/block_survival.rs @@ -524,14 +524,6 @@ impl<'r> BlockSurvivalRegistry<'r> { bubble_down: tag_states("minecraft:enables_bubble_column_drag_down")?, }) } - pub fn supported_states(&self) -> usize { - self.rules.iter().filter(|r| r.is_some()).count() - } - pub fn supports_state(&self, state: BlockStateId) -> bool { - self.rules - .get(state.0 as usize) - .is_some_and(Option::is_some) - } fn read( &self, world: &mut W, diff --git a/crates/horizon-world/src/component_durability.rs b/crates/horizon-world/src/component_durability.rs index 15237133b..5bf576c08 100644 --- a/crates/horizon-world/src/component_durability.rs +++ b/crates/horizon-world/src/component_durability.rs @@ -3,7 +3,6 @@ use crate::{ component_patch::{ComponentMap, MissingPrototype, Patch, Prototype}, item_durability::DurabilityStorage, - item_use_catalog::UseComponents, }; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Key { @@ -52,13 +51,6 @@ impl DurabilityPrototype { } Self(Prototype::new(entries)) } - pub fn from_defaults(defaults: &UseComponents) -> Self { - Self::new([ - Change::MaxDamage(defaults.max_damage), - Change::Damage(defaults.damage), - Change::Unbreakable(defaults.unbreakable), - ]) - } } #[derive(Clone, Debug)] pub struct DurabilityPatch(Patch); diff --git a/crates/horizon-world/src/datafix/dynamic.rs b/crates/horizon-world/src/datafix/dynamic.rs index 44336729c..69cca1453 100644 --- a/crates/horizon-world/src/datafix/dynamic.rs +++ b/crates/horizon-world/src/datafix/dynamic.rs @@ -157,12 +157,6 @@ pub fn map(tag: &Tag) -> Option<&Compound> { _ => None, } } -pub fn map_mut(tag: &mut Tag) -> Option<&mut Compound> { - match tag { - Tag::Compound(c) => Some(c), - _ => None, - } -} /// `Dynamic.set`: only maps change. pub fn set(tag: &mut Tag, field: &str, value: Tag) { if let Tag::End = tag { @@ -193,12 +187,6 @@ pub fn update(tag: &mut Tag, field: &str, f: impl FnOnce(Tag) -> Tag) { set(tag, field, f(v)); } } -/// `Dynamic.update` in place. -pub fn update_mut(tag: &mut Tag, field: &str, f: impl FnOnce(&mut Tag)) { - if let Some(v) = tag.get_mut(field) { - f(v); - } -} /// `Dynamic.renameAndFixField`: the fixed value under the new name, removed when /// the fix gives nothing. pub fn rename_and_fix(tag: &mut Tag, from: &str, to: &str, f: impl FnOnce(Tag) -> Option) { @@ -223,15 +211,6 @@ pub fn is_empty_map(tag: &Tag) -> bool { pub fn or_empty_map(tag: Option<&Tag>) -> Tag { tag.cloned().unwrap_or_else(empty_map) } -/// Apply `f` to every element of a list field (`Dynamic.createList(asStream().map(f))`). -pub fn map_list(tag: &mut Tag, field: &str, mut f: impl FnMut(Tag) -> Tag) { - if let Some(v) = tag.get(field) - && is_list(Some(v)) - { - let list = stream(Some(v)).into_iter().map(&mut f).collect(); - set(tag, field, Tag::List(list)); - } -} /// `NamespacedSchema.ensureNamespaced`. pub fn namespaced(id: &str) -> String { match crate::datafix::identifier(id) { diff --git a/crates/horizon-world/src/entity_move.rs b/crates/horizon-world/src/entity_move.rs index b3b189df0..25d7aef14 100644 --- a/crates/horizon-world/src/entity_move.rs +++ b/crates/horizon-world/src/entity_move.rs @@ -44,9 +44,6 @@ impl MovementHistory { } self.records.push_back(record); } - pub fn remove_latest(&mut self) { - self.records.pop_back(); - } pub fn clear(&mut self) { self.records.clear(); } diff --git a/crates/horizon-world/src/entity_obstruction.rs b/crates/horizon-world/src/entity_obstruction.rs index 89f7f586b..aac2306b6 100644 --- a/crates/horizon-world/src/entity_obstruction.rs +++ b/crates/horizon-world/src/entity_obstruction.rs @@ -73,17 +73,3 @@ pub fn is_unobstructed( } Ok(true) } - -/// Entity obstruction for the unit cube used by the vanilla block predicate. -/// Translate the voxel shape in floating point: integer MAX + 1 must not wrap. -pub fn is_block_unobstructed( - world: &mut W, - position: [i32; 3], -) -> Result> { - let shape = VoxelShape::block().moved(horizon_core::geometry::Vec3::new( - f64::from(position[0]), - f64::from(position[1]), - f64::from(position[2]), - )); - is_unobstructed(world, None, &shape) -} diff --git a/crates/horizon-world/src/fluid.rs b/crates/horizon-world/src/fluid.rs index 4a89764a8..ab03d6a52 100644 --- a/crates/horizon-world/src/fluid.rs +++ b/crates/horizon-world/src/fluid.rs @@ -272,13 +272,6 @@ impl FluidStateTable { pub fn get(&self, state: BlockStateId) -> Option { self.0.get(state.0 as usize).copied() } - pub fn matching_states(&self, mask: u8) -> impl Iterator + '_ { - self.0 - .iter() - .enumerate() - .filter(move |(_, state)| state.kind.mask() & mask != 0) - .map(|(i, _)| BlockStateId(i as u32)) - } } /// Bound identities for converting fluid states into their legacy liquid blocks. diff --git a/crates/horizon-world/src/level/bonemeal.rs b/crates/horizon-world/src/level/bonemeal.rs index 274512138..ef52ca625 100644 --- a/crates/horizon-world/src/level/bonemeal.rs +++ b/crates/horizon-world/src/level/bonemeal.rs @@ -160,16 +160,6 @@ impl Behaviours { ) -> bool { self.sim(level, ticks).grow_water_plant(pos, face) } - /// The `BonemealableBlock.Type` particle spread of a block at level event - /// 1505: Some(true) for `NEIGHBOR_SPREADER` (particles over a 3-block - /// area above), Some(false) for `GROWER`, None when not bonemealable. - pub fn bone_meal_spreads(&self, state: BlockStateId) -> Option { - let kind = self.bonemeal_kind(state)?; - Some(matches!( - kind, - Kind::Grass | Kind::Nylium | Kind::Netherrack | Kind::FeaturePlacer - )) - } fn bonemeal_kind(&self, state: BlockStateId) -> Option { let data = self.data(state); if !data.implements(Interface::Bonemealable) { diff --git a/crates/horizon-world/src/level/classes.rs b/crates/horizon-world/src/level/classes.rs index 9540a5a47..2d0193de5 100644 --- a/crates/horizon-world/src/level/classes.rs +++ b/crates/horizon-world/src/level/classes.rs @@ -15,9 +15,6 @@ macro_rules! classes { pub fn from_java(name: &str) -> Option { match name { $($java => Some(Class::$name),)* _ => None } } - pub const fn java_name(self) -> &'static str { - match self { $(Class::$name => $java,)* } - } } }; } diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index e343e06a7..696777386 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -148,7 +148,6 @@ pub mod flags { pub const UPDATE_NEIGHBORS: i32 = 1; pub const UPDATE_CLIENTS: i32 = 2; pub const UPDATE_INVISIBLE: i32 = 4; - pub const UPDATE_IMMEDIATE: i32 = 8; pub const UPDATE_KNOWN_SHAPE: i32 = 16; pub const UPDATE_SUPPRESS_DROPS: i32 = 32; pub const UPDATE_MOVE_BY_PISTON: i32 = 64; diff --git a/crates/horizon-world/src/level/states.rs b/crates/horizon-world/src/level/states.rs index c7fe012dc..8d2544953 100644 --- a/crates/horizon-world/src/level/states.rs +++ b/crates/horizon-world/src/level/states.rs @@ -348,10 +348,4 @@ impl StateTable { } result } - pub fn property_names(&self, block: BlockId) -> impl Iterator { - self.info(block) - .slots - .iter() - .map(|slot| self.key_names[slot.key.0 as usize].as_str()) - } } diff --git a/crates/horizon-world/src/level/ticks.rs b/crates/horizon-world/src/level/ticks.rs index fbad6c28d..c8d715623 100644 --- a/crates/horizon-world/src/level/ticks.rs +++ b/crates/horizon-world/src/level/ticks.rs @@ -149,9 +149,6 @@ impl Ticks { self.blocks .has_scheduled(pos, TickTypeId(u32::from(block.0))) } - pub fn has_fluid_tick(&self, pos: BlockPos, fluid: FluidKind) -> bool { - self.fluids.has_scheduled(pos, TickTypeId(fluid as u32)) - } pub fn will_block_tick_this_tick(&mut self, pos: BlockPos, block: BlockId) -> bool { self.blocks .will_tick_this_tick(pos, TickTypeId(u32::from(block.0))) diff --git a/crates/horizon-world/src/registry_fluid.rs b/crates/horizon-world/src/registry_fluid.rs index eb0f4ffe0..a122a8978 100644 --- a/crates/horizon-world/src/registry_fluid.rs +++ b/crates/horizon-world/src/registry_fluid.rs @@ -62,9 +62,6 @@ impl<'r> FluidRegistry<'r> { pub fn blocks_flow(&self, id: BlockStateId) -> io::Result { Ok(self.state(id)?.blocks_flow) } - pub fn is_ice(&self, id: BlockStateId) -> io::Result { - Ok(self.state(id)?.ice) - } } /// Both queries return state IDs from the same registry. Separate entry points /// preserve native world dispatch when reading a block versus its fluid cell. diff --git a/crates/horizon-world/src/retrogen.rs b/crates/horizon-world/src/retrogen.rs index fc9f450bf..2f048f48e 100644 --- a/crates/horizon-world/src/retrogen.rs +++ b/crates/horizon-world/src/retrogen.rs @@ -33,9 +33,6 @@ impl BelowZeroRetrogen { .get(index / 64) .is_some_and(|word| word & (1_u64 << (index % 64)) != 0) } - pub fn missing_bedrock_words(&self) -> &[u64] { - &self.missing_bedrock - } pub fn from_nbt(tag: &Tag) -> io::Result { if !matches!(tag, Tag::Compound(_)) { return Err(invalid("retrogen is not a compound")); diff --git a/crates/horizon-world/src/worldgen/aquifer.rs b/crates/horizon-world/src/worldgen/aquifer.rs index 2b4f6e7c3..44500313b 100644 --- a/crates/horizon-world/src/worldgen/aquifer.rs +++ b/crates/horizon-world/src/worldgen/aquifer.rs @@ -50,11 +50,6 @@ impl GlobalFluidPicker { disabled: false, } } - /// Matches the vanilla developer flag. Regular gameplay keeps this false. - pub const fn with_disabled(mut self, disabled: bool) -> Self { - self.disabled = disabled; - self - } } impl FluidPicker for GlobalFluidPicker { fn compute(&self, [_, y, _]: [i32; 3]) -> FluidStatus { diff --git a/crates/horizon-world/src/worldgen/feature_region.rs b/crates/horizon-world/src/worldgen/feature_region.rs index b4e8c07b0..e1d80e8bc 100644 --- a/crates/horizon-world/src/worldgen/feature_region.rs +++ b/crates/horizon-world/src/worldgen/feature_region.rs @@ -212,9 +212,6 @@ impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { pub fn tick_clock(&self) -> (i64, i64) { (self.game_time, self.next_tick_order) } - pub fn set_game_time(&mut self, game_time: i64) { - self.game_time = game_time; - } /// Raw tick identities are default block-state IDs for block ticks and /// `FluidKind` discriminants for fluid ticks, in separate namespaces. pub fn schedule_tick( @@ -224,15 +221,6 @@ impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { ) -> Result { WorldGenTickAccess::new(RegionTickContainers { region: self, kind }).schedule(tick) } - pub fn has_scheduled_tick( - &mut self, - kind: TickKind, - position: BlockPos, - tick_type: TickTypeId, - ) -> Result { - WorldGenTickAccess::new(RegionTickContainers { region: self, kind }) - .has_scheduled(position, tick_type) - } fn request_tick( &mut self, kind: TickKind, @@ -251,11 +239,6 @@ impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { self.schedule_tick(kind, tick)?; Ok(()) } - /// Override world sea level without changing generator placement anchors. - pub fn with_world_sea_level(mut self, sea_level: i32) -> Self { - self.sea_level = sea_level; - self - } /// Release the resident chunks, ordered by X then Z; match them by position. pub fn into_chunks(self) -> Vec> { self.chunks diff --git a/crates/horizon-world/src/worldgen/material_condition/codec.rs b/crates/horizon-world/src/worldgen/material_condition/codec.rs index ec646697e..aa159bd1e 100644 --- a/crates/horizon-world/src/worldgen/material_condition/codec.rs +++ b/crates/horizon-world/src/worldgen/material_condition/codec.rs @@ -65,12 +65,6 @@ impl MaterialConditionRegistry { pub fn from_json(definitions: &BTreeMap) -> Result { Self::load(definitions, None) } - pub fn from_json_with_biomes( - definitions: &BTreeMap, - biomes: &BTreeSet, - ) -> Result { - Self::from_json_with_biome_tags(definitions, biomes, &BTreeMap::new()) - } /// Bind resolved biome tags, such as `TagDefinitions::build().tags`. /// Names and memberships remain immutable for the lifetime of this registry. pub fn from_json_with_biome_tags( diff --git a/crates/horizon-world/src/worldgen/state_provider.rs b/crates/horizon-world/src/worldgen/state_provider.rs index 098decdf1..da39cd246 100644 --- a/crates/horizon-world/src/worldgen/state_provider.rs +++ b/crates/horizon-world/src/worldgen/state_provider.rs @@ -344,12 +344,6 @@ impl BlockStateProvider { _ => Err(DecodeError::Field("exclusive state or provider")), } } - pub fn from_typed_json( - json: &str, - bindings: &StateProviderBindings<'_>, - ) -> Result { - Self::decode_typed(json, bindings, 0, &mut 65536, None) - } fn decode_typed( json: &str, bindings: &StateProviderBindings<'_>, diff --git a/crates/horizon-world/src/worldgen/terrain.rs b/crates/horizon-world/src/worldgen/terrain.rs index 8ea3b01be..5ecc48045 100644 --- a/crates/horizon-world/src/worldgen/terrain.rs +++ b/crates/horizon-world/src/worldgen/terrain.rs @@ -432,18 +432,6 @@ impl<'r, B: TerrainBlockStates> TerrainChunk<'r, B> { )?; Ok(()) } - pub fn set_heightmap_raw( - &mut self, - kind: HeightmapType, - words: &[u64], - ) -> Result<(), TerrainError> { - self.ensure_heightmap(kind); - self.heightmaps[kind as usize] - .as_mut() - .unwrap() - .set_raw_data(&self.blocks, words)?; - Ok(()) - } /// Before replaying a saved chunk's `PostProcessing` lists. pub fn clear_postprocessing(&mut self) { self.postprocessing.iter_mut().for_each(Vec::clear); From 660407fa58d03fa6e41fe2edc7d4ae3658841233 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 13:22:10 +0200 Subject: [PATCH 022/408] Metal: cull only frames with 4,096 section draws or more On Apple's GPUs the passes the test adds cost a fixed share of the frame (it is stored and reloaded at each), which the hidden sections repay only at high render distances: at 12 culling cost an M4 Pro 0.05 ms of GPU time a frame, at 32 it saved 0.25 to 1.6 ms. Other backends keep culling every frame; HORIZON_GPU_CULL=all culls every frame on Metal too. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/gfx.rs | 14 ++++++++++---- crates/horizon-client/src/gfx/cull.rs | 10 ++++++++++ 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 91da4f616..022d14dcd 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -2146,8 +2146,8 @@ impl Renderer { .features() .contains(wgpu::Features::INDIRECT_FIRST_INSTANCE); // HORIZON_GPU_CULL=0 turns occlusion culling off, `all` culls every - // frame however little it hides, `shader` tests in the shader as on - // Metal (A/B checks). + // frame however few its draws and little it hides, `shader` tests in + // the shader as on Metal (A/B checks). let cull_env = std::env::var("HORIZON_GPU_CULL"); let cull = cull::Cull::supported(&adapter, &device) .filter(|_| cull_env.as_deref() != Ok("0")) @@ -2159,6 +2159,9 @@ impl Renderer { let mut cull = cull::Cull::new(&device, config.format.remove_srgb_suffix(), depth_test); cull.always = cull_env.as_deref() == Ok("all"); + if !cull.always && adapter.get_info().backend == wgpu::Backend::Metal { + cull.min_draws = cull::TILED_MIN_DRAWS; + } cull }); let depth = Self::depth(&device, &config, cull.as_ref()); @@ -3148,11 +3151,14 @@ impl Renderer { .inverse() .transform_point3(Vec3::ZERO); // Occlusion culling leaves the sections its last result did not see - // to phase 2, after the others, with instance counts of 0. + // to phase 2, after the others, with instance counts of 0. Whether + // the frame has draws enough goes by the last one's. let mut cull = self .cull .as_mut() - .filter(|_| self.cull_on && !frame.title && self.multi_draw) + .filter(|c| { + self.cull_on && !frame.title && self.multi_draw && self.section_draws >= c.min_draws + }) .and_then(|cull| cull.begin(&self.device).then_some(cull)); self.phase2_draws.clear(); self.phase2_pages.clear(); diff --git a/crates/horizon-client/src/gfx/cull.rs b/crates/horizon-client/src/gfx/cull.rs index 77574e850..57049eb4d 100644 --- a/crates/horizon-client/src/gfx/cull.rs +++ b/crates/horizon-client/src/gfx/cull.rs @@ -46,6 +46,13 @@ const RETEST: u32 = 8; /// more than they save. Else one frame in `PROBE` tests every section. const MIN_SHARE: f32 = 0.1; const PROBE: u32 = 64; +/// On Metal, section draws from which a frame culls. Apple's GPUs store and +/// reload the whole frame at each of the passes the test adds, a fixed cost +/// that the sections it hides repay only at high render distances: on an M4 +/// Pro at 1080p and render distance 12 (1,000–1,600 draws) culling added +/// about 0.05 ms of GPU time while hiding 15–30% of the solid indices; at +/// 32 (drawn flat, over this many draws) it saved 0.25–1.6 ms. +pub const TILED_MIN_DRAWS: usize = 4096; /// Boxes over more than this share of the screen count as seen untested. const BIG: f32 = 0.25; /// Results read back at once, some frames late so the CPU never waits. @@ -141,6 +148,8 @@ pub struct Cull { pub hidden: ([usize; 2], f32), /// Cull every frame, whatever the hidden share (A/B checks). pub always: bool, + /// Frames with fewer section draws than this do not cull. + pub min_draws: usize, } fn buffer( @@ -337,6 +346,7 @@ impl Cull { stamp: 0, hidden: ([0; 2], 1.0), always: false, + min_draws: 0, } } From 4a61134eddb414c367be96bb4c57bf654bf1e7a8 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 14:06:25 +0200 Subject: [PATCH 023/408] CI verify: test without building the examples cargo test --workspace built and linked all ~275 examples, 59% of the test build (review-plan section 1), though none of their tests run. Test the libraries, binaries and integration tests, then the doc tests, as tools/gate.py and tools/pr_ready.py already do. Clippy --all-targets still type-checks every example, and the parity job builds and runs them. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8966854c2..17075add1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -64,9 +64,13 @@ jobs: cargo +stable clippy --workspace --all-targets -- -D warnings # The server build (released as horizon-engine): the game without sound or controllers. cargo +stable clippy -p horizon-client --all-targets --no-default-features -- -D warnings + # Libraries, binaries and integration tests, then doc tests: not the ~275 examples, which clippy above already + # type-checks and the parity job builds and runs (they were most of this step's build and link time). - name: Test Rust core and voxel kernel correctness if: steps.rust.outputs.required != 'false' - run: cargo +stable test --workspace + run: | + cargo +stable test --workspace --lib --bins --tests + cargo +stable test --workspace --doc parity: if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository uses: ./.github/workflows/parity.yml From ac54227465703e3e18c5462eb22735fa44fd1439 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 14:08:47 +0200 Subject: [PATCH 024/408] parity: prebuild probes with each harness's own package selection The probe prebuild ran `cargo build --workspace --examples --bins` (or named targets with --workspace). The harnesses build with `-p `, and Cargo unifies features over the selected packages: under --workspace, flate2, libc, memchr, syn, thiserror, postcard and digest get other features for horizon-world, and horizon-mods (pack) and horizon-telemetry (upload) for horizon-client. So every probe the prebuild made was a variant no harness used, and each harness rebuilt its crate and its probe again while the others waited on Cargo's lock. Record each probe with its command's package and feature flags and whether that command builds examples (which turns dev-dependencies on), and prebuild one Cargo run per such selection. --bins and --examples are recorded too, so the fast-profile horizon-client build that save_roundtrip and world_reopen run is prebuilt as well. A harness that never ran here takes its probes from the shared dependency lists instead of a build of all ~275 examples. Co-Authored-By: Claude Opus 5.5 --- tests/test_parity_runner.py | 31 +++++++++-- tools/parity.py | 103 ++++++++++++++++++++++++++++-------- 2 files changed, 110 insertions(+), 24 deletions(-) diff --git a/tests/test_parity_runner.py b/tests/test_parity_runner.py index ffec8d3d5..beffb557d 100644 --- a/tests/test_parity_runner.py +++ b/tests/test_parity_runner.py @@ -16,10 +16,35 @@ class ParityRunnerTests(unittest.TestCase): def test_artifacts_follow_profile_and_stop_at_program_arguments(self): self.assertEqual(parity.artifacts_of(["cargo", "build", "--release", "--example", "a", "--bin", "b"]), - [["example", "a", "release"], ["bin", "b", "release"]]) + [["example", "a", "release", [], True], ["bin", "b", "release", [], True]]) self.assertEqual(parity.artifacts_of(["cargo", "run", "--profile", "fast", "--example", "c", "--", "--example", "x"]), - [["example", "c", "fast"]]) - self.assertEqual(parity.artifacts_of(["cargo", "build", "--example", "d"]), [["example", "d", "dev"]]) + [["example", "c", "fast", [], True]]) + self.assertEqual(parity.artifacts_of(["cargo", "build", "--example", "d"]), [["example", "d", "dev", [], True]]) + + def test_artifacts_keep_the_package_and_feature_selection(self): + self.assertEqual(parity.artifacts_of(["cargo", "build", "--locked", "--profile=fast", "-j", "4", "--package", + "horizon-client", "--bins", "-F", "x"]), + [["bins", "", "fast", ["-p", "horizon-client", "--features", "x"], False]]) + self.assertEqual(parity.artifacts_of(["cargo", "build", "--release", "-p", "horizon-world", "--bin=horizon-world"]), + [["bin", "horizon-world", "release", ["-p", "horizon-world"], False]]) + + def test_prebuild_repeats_each_harness_selection(self): + artifacts = [ + *parity.artifacts_of(["cargo", "build", "--release", "-p", "horizon-world", "--example", "a"]), + *parity.artifacts_of(["cargo", "build", "--release", "-p", "horizon-world", "--example", "b"]), + *parity.artifacts_of(["cargo", "build", "--release", "-p", "horizon-world", "--bin", "horizon-world"]), + *parity.artifacts_of(["cargo", "build", "--release", "--bin", "horizon-world"]), + *parity.artifacts_of(["cargo", "run", "--profile", "fast", "-p", "horizon-client", "--example", "c"]), + ["example", "old", "release"], # recorded before selections were kept: its own crate's -p + ["example", "unknown", "release"], # no longer in the workspace: left to its harness + ] + self.assertEqual(parity.prebuild_commands(artifacts, {("example", "old"): "horizon-world"}), [ + ["cargo", "build", "--locked", "--profile", "fast", "-p", "horizon-client", "--example", "c"], + ["cargo", "build", "--locked", "--profile", "release", "--bin", "horizon-world"], + ["cargo", "build", "--locked", "--profile", "release", "-p", "horizon-world", "--bin", "horizon-world"], + ["cargo", "build", "--locked", "--profile", "release", "-p", "horizon-world", "--example", "a", "--example", "b", + "--example", "old"], + ]) def test_java_sources_include_classes_pulled_from_the_sourcepath(self): with tempfile.TemporaryDirectory() as temp: diff --git a/tools/parity.py b/tools/parity.py index 6ba4c0d90..5dbf13554 100644 --- a/tools/parity.py +++ b/tools/parity.py @@ -27,9 +27,10 @@ Harness probes build into .local/parity-target with release optimisations but without LTO and with 16 codegen units (`PROFILE` below), which builds in seconds instead of minutes. Rust does not let those settings change results: there is no fast-math, and overflow checks stay as in release. Probes built in -the dev profile are optimised too, keeping their overflow checks. Probes the -recorded harnesses need are built in one Cargo run before the harnesses start, -so parallel harnesses don't queue on Cargo's lock. +the dev profile are optimised too, keeping their overflow checks. The probes the +selected harnesses built last time are built before they start, so parallel +harnesses don't queue on Cargo's lock, with each harness's own package and +feature flags so that its Cargo run then finds them fresh. """ import argparse @@ -210,18 +211,42 @@ def artifact_path(kind, name, profile): return TARGET / directory / ("examples" if kind == "example" else "") / name +SELECTION_FLAGS = {"-p", "--package", "-F", "--features"} # followed by a value +SELECTION_SWITCHES = {"--workspace", "--all", "--all-features", "--no-default-features"} + + def artifacts_of(arguments): - """The [kind, name, profile] targets a cargo build/run command line names.""" + """The [kind, name, profile, selection, examples] targets a cargo build/run command line names. + + kind is example, bin, or examples/bins (every one, name ""). selection is the command's package and feature + flags, and examples whether the command builds any example (which turns on dev-dependencies): together they + decide how Cargo unifies features, so the probe prebuild must repeat them exactly. A `--workspace` build of + the same example gives its dependencies other features, and the harness's own `-p` build then compiles + everything again.""" arguments = arguments[:arguments.index("--")] if "--" in arguments else arguments profile = "release" if "--release" in arguments else "dev" - if "--profile" in arguments: - profile = arguments[arguments.index("--profile") + 1] + selection = [] found = [] - for flag, kind in (("--example", "example"), ("--bin", "bin")): - for index, argument in enumerate(arguments[:-1]): - if argument == flag: - found.append([kind, arguments[index + 1], profile]) - return found + index = 1 + while index < len(arguments): + argument = arguments[index] + flag, _, value = argument.partition("=") + if flag in SELECTION_FLAGS | {"--profile", "--example", "--bin"} and not value and index + 1 < len(arguments): + value = arguments[index + 1] + index += 1 + if flag == "--profile": + profile = value + elif flag in SELECTION_FLAGS: + selection += ["-p" if flag == "--package" else "--features" if flag == "-F" else flag, value] + elif flag in SELECTION_SWITCHES: + selection.append("--workspace" if flag == "--all" else flag) + elif flag in ("--example", "--bin"): + found.append([flag[2:], value]) + elif flag in ("--examples", "--bins"): + found.append([flag[2:], ""]) + index += 1 + examples = any(kind in ("example", "examples") for kind, _ in found) + return [[kind, name, profile, selection, examples] for kind, name in found] RUST_PATH = re.compile(r"(? Date: Fri, 23 Oct 2026 14:36:58 +0200 Subject: [PATCH 025/408] parity: run world_spawn in four shards world_spawn starts a vanilla and a Horizon server for each of 60 seeds, one at a time: 1,144-1,548 s on the CI runner, the parity job's longest harness and its floor whenever a PR's changes reach it. With PARITY_SHARDS = 4 each shard creates every fourth seed's worlds, in its own build directory. The shard helper datafix had moves to tools/parity_shard.py, which both use. It stays out of lab.py, which every harness imports. Co-Authored-By: Claude Opus 5.5 --- tools/parity_shard.py | 21 +++++++++++++++++++++ tools/test_datafix_parity.py | 14 +++----------- tools/test_world_spawn_parity.py | 12 +++++++++--- 3 files changed, 33 insertions(+), 14 deletions(-) create mode 100644 tools/parity_shard.py diff --git a/tools/parity_shard.py b/tools/parity_shard.py new file mode 100644 index 000000000..249235ffb --- /dev/null +++ b/tools/parity_shard.py @@ -0,0 +1,21 @@ +"""A sharded harness's share of its cases. + +A harness that declares PARITY_SHARDS = n runs as n entries in tools/parity.py, which sets PARITY_SHARD=i/n for +each. Outside the runner PARITY_SHARD is unset and a harness runs everything. Kept out of lab.py: every harness +imports lab.py, so a change there reruns them all. +""" +import os + + +def shard(items): + """Every n-th item from the i-th, or all of them outside the runner.""" + spec = os.environ.get("PARITY_SHARD") + if not spec: + return items + index, count = map(int, spec.split("/")) + return items[index - 1::count] + + +def label(): + """A directory name for this share ("2-4", or "all"): shards run at once and must not share outputs.""" + return os.environ.get("PARITY_SHARD", "all").replace("/", "-") diff --git a/tools/test_datafix_parity.py b/tools/test_datafix_parity.py index a2d11009c..4c189983f 100644 --- a/tools/test_datafix_parity.py +++ b/tools/test_datafix_parity.py @@ -33,6 +33,7 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) import anvil_dump # noqa: E402 +import parity_shard # noqa: E402 ROOT = Path(__file__).resolve().parent.parent LOCAL = ROOT / '.local' / 'datafix' @@ -63,7 +64,7 @@ def java_classpath(): import test_model_baking_parity as baking lock, jars, _ = base.verify_artifacts() libraries = baking.client_libraries() - build = LOCAL / 'build' / os.environ.get('PARITY_SHARD', 'all').replace('/', '-') # shards compile apart + build = LOCAL / 'build' / parity_shard.label() # shards compile apart build.mkdir(parents=True, exist_ok=True) classes, dependencies, _ = harness.compile_oracle(build, 'VanillaDataFixOracle', jars, libraries, lock['minecraft']['java_major']) @@ -78,15 +79,6 @@ def build_rust(): return Path(meta['target_directory']) / 'release' / 'examples' / 'datafix_world' -def shard(items): - """This run's share of items when tools/parity.py runs the harness in parts (PARITY_SHARD=i/n).""" - spec = os.environ.get('PARITY_SHARD') - if not spec: - return items - index, count = map(int, spec.split('/')) - return items[index - 1::count] - - def run_vanilla(classpath, world, out, target=None): # The oracle replaces OUT itself: left in place, an unchanged run's outputs can be reused. log = out.parent / (out.name + '.log') @@ -226,7 +218,7 @@ def main(): band = args.band if band and not args.versions: # worlds in the layout of before 1.16, saved before the target worlds = [w for w in worlds if json.loads((world_path(w) / 'datafix-source.json').read_text())['data_version'] < band] - versions = shard(args.versions or worlds) + versions = parity_shard.shard(args.versions or worlds) classpath = java_classpath() binary = None if args.vanilla_only else Path(args.binary) if args.binary else build_rust() total = 0 diff --git a/tools/test_world_spawn_parity.py b/tools/test_world_spawn_parity.py index 9b495c3dc..4247a0ee7 100644 --- a/tools/test_world_spawn_parity.py +++ b/tools/test_world_spawn_parity.py @@ -29,6 +29,10 @@ Seeds: the player report's seed (1891623539983467248: Horizon spawned at -48 -48, vanilla at 152 145), the chunk generation harness's seeds and --random seeds from a fixed generator. +tools/parity.py runs it in PARITY_SHARDS parts, each creating the worlds of +every PARITY_SHARDS-th seed: each seed is a vanilla and a Horizon server start, +~15 s, and 60 seeds in one run were the longest harness (~25 min). + usage: test_world_spawn_parity.py [--random N] [--jobs N] [--origins-only] """ import argparse @@ -43,16 +47,18 @@ from concurrent.futures import ThreadPoolExecutor from pathlib import Path try: - from . import anvil_dump, lab, oracle_harness as oh, test_rust_parity as base + from . import anvil_dump, lab, oracle_harness as oh, parity_shard, test_rust_parity as base from .test_dedicated_server_parity import Server, free_port except ImportError: import anvil_dump import lab import oracle_harness as oh + import parity_shard import test_rust_parity as base from test_dedicated_server_parity import Server, free_port NAME = 'world-spawn-parity' +PARITY_SHARDS = 4 REPORT = 1891623539983467248 SEEDS = [REPORT, 12345, -7046029254386353131, 987654321987, 4242, -1, 0x5DEECE66D, 20260607, 777, 0] RESOURCES = lab.RESOURCES @@ -107,7 +113,7 @@ def main(): parser.add_argument('--seed', type=int, action='append', help='only these seeds (repeatable)') args = parser.parse_args() lock, jars, libraries = base.verify_artifacts() - build = lab.LOCAL / NAME + build = lab.LOCAL / NAME / parity_shard.label() # shards run at once build.mkdir(parents=True, exist_ok=True) dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) classes = build / 'classes' @@ -116,7 +122,7 @@ def main(): '-d', classes, lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldSpawnOracle.java'], build, 'compile-java') oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'spawn_origin'], build, 'compile-probe') - all_seeds = args.seed or seeds(args.random) + all_seeds = parity_shard.shard(args.seed or seeds(args.random)) started = time.time() vanilla, rust = origins(build, classes, dependencies, all_seeds) From 7cc47e2b55817b1cba0daaa88b1aa3af495c8e56 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 14:41:40 +0200 Subject: [PATCH 026/408] Delete ten tools/ scripts nothing references command_parse_summary, structure_start_oracle, fetch_client_assets, compare_structure_starts, profile_behaviour_cache, command_tree_diff, compare_loot_fill, compare_structure_blocks, test_lan_lifecycle and PROFILE_SHARED_JSON.md: no workflow, doc, harness, test or other tool names them (review-plan.md, Dead code). History keeps them. Co-Authored-By: Claude Opus 5.5 --- tools/PROFILE_SHARED_JSON.md | 85 ------------ tools/command_parse_summary.py | 36 ----- tools/command_tree_diff.py | 79 ----------- tools/compare_loot_fill.py | 91 ------------ tools/compare_structure_blocks.py | 113 --------------- tools/compare_structure_starts.py | 55 -------- tools/fetch_client_assets.py | 46 ------- tools/profile_behaviour_cache.py | 57 -------- tools/structure_start_oracle.py | 38 ----- tools/test_lan_lifecycle.py | 222 ------------------------------ 10 files changed, 822 deletions(-) delete mode 100644 tools/PROFILE_SHARED_JSON.md delete mode 100644 tools/command_parse_summary.py delete mode 100644 tools/command_tree_diff.py delete mode 100644 tools/compare_loot_fill.py delete mode 100644 tools/compare_structure_blocks.py delete mode 100644 tools/compare_structure_starts.py delete mode 100644 tools/fetch_client_assets.py delete mode 100644 tools/profile_behaviour_cache.py delete mode 100644 tools/structure_start_oracle.py delete mode 100644 tools/test_lan_lifecycle.py diff --git a/tools/PROFILE_SHARED_JSON.md b/tools/PROFILE_SHARED_JSON.md deleted file mode 100644 index 976e43ecb..000000000 --- a/tools/PROFILE_SHARED_JSON.md +++ /dev/null @@ -1,85 +0,0 @@ -# Reproducing PR #607 block-facts startup profiles - -These are loader-only measurements. They include `Assets::load`, `BlockFacts`, and -`Behaviours` and exclude content root preparation, graphics, input setup, first -frame, and the rest of the client startup sequence. No full-client startup gain -has been measured. The prepared `26.3` resource root must match the revision. - -## Historical release builds - -From the PR branch checkout, use an absolute prepared resource-root path and a -single, explicit Cargo release profile for each detached historical worktree: - -```sh -PR_ROOT="$(pwd)" -BENCH_ROOT="$(mktemp -d)" -mkdir -p "$BENCH_ROOT/bin" -CARGO_TARGET_DIR="$BENCH_ROOT/target" -export CARGO_TARGET_DIR - -for entry in baseline:e422bd13 a01:a01d47f2 cf:cf837118 cd:cd61e11b; do - name="${entry%%:*}" - revision="${entry#*:}" - git worktree add --detach "$BENCH_ROOT/$name" "$revision" -done - -# e422bd13 predates the profiler; add the same baseline example source used -# for the benchmark, without changing any production implementation. -cp "$PR_ROOT/tools/baseline_loader_profile.rs" \ - "$BENCH_ROOT/baseline/crates/horizon-client/examples/shared_json_startup_profile.rs" - -for name in baseline a01 cf cd; do - (cd "$BENCH_ROOT/$name" && \ - cargo build --offline --release -p horizon-client --example shared_json_startup_profile) - cp "$CARGO_TARGET_DIR/release/examples/shared_json_startup_profile" \ - "$BENCH_ROOT/bin/$name" -done - -cargo build --offline --release -p horizon-client --example shared_json_startup_profile -cp "$CARGO_TARGET_DIR/release/examples/shared_json_startup_profile" "$BENCH_ROOT/bin/current" - -python3 tools/profile_shared_json.py \ - --resources /absolute/path/to/.local/horizon-client/26.3 \ - --baseline-binary "$BENCH_ROOT/bin/baseline" \ - --a01-binary "$BENCH_ROOT/bin/a01" \ - --cf-binary "$BENCH_ROOT/bin/cf" \ - --cd-binary "$BENCH_ROOT/bin/cd" \ - --binary "$BENCH_ROOT/bin/current" \ - --repeats 10 --output "$BENCH_ROOT/five-way.json" -``` - -The source tree of each historical revision is exact. The baseline profiler is -an added standalone measurement example, and therefore does not alter its -historical loader logic. Comparisons use alternating forward/reverse process -order, separate processes, Linux `wait4` CPU time and peak RSS, and saved raw -samples with 25th/75th percentiles, extrema, build hashes and system load. -Keep concurrent compilation and other CPU-intensive jobs idle if possible. -`ru_maxrss` records process peak residency and cannot establish the real game's -memory usage after rendering begins. If system load rises, preserve rather than -discard outliers and report the uncertainty. - -## Decoding passes and buffer lifetime - -```sh -cargo build --offline --release -p horizon-client --example gameplay_decode_profile -python3 tools/profile_gameplay_decode.py \ - --resources /absolute/path/to/.local/horizon-client/26.3 \ - --repeats 10 --output "$BENCH_ROOT/decode.json" - -python3 tools/profile_shared_json.py \ - --resources /absolute/path/to/.local/horizon-client/26.3 \ - --variant released="$BENCH_ROOT/bin/current"@deferred \ - --variant retained="$BENCH_ROOT/bin/current"@deferred-held \ - --repeats 10 --output "$BENCH_ROOT/lifetime.json" -``` - -The decoder profile measures the `Validate` pass and typed `Gameplay` pass -separately, including the JSON read in `total_ms`. The primary facts loader -continues both passes to preserve JSON validation, error precedence and useful -diagnostics, including overwritten fields and raw geometry. The lifetime -comparison measures current process `VmRSS` after materialisation, plus peak -RSS across the process. An explicit `drop` releases owned Rust values, but the -allocator may retain physical pages, so immediate RSS savings are not implied. - -When finished, `git worktree remove` each temporary historical worktree. Do -not `git clean` or reset the active PR working tree. diff --git a/tools/command_parse_summary.py b/tools/command_parse_summary.py deleted file mode 100644 index 2cd8d1f68..000000000 --- a/tools/command_parse_summary.py +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env python3 -"""Group the mismatches of tools/test_command_parse_parity.py by cause. - -usage: command_parse_summary.py MISMATCHES.jsonl [ROOT] -""" -import collections -import json -import sys -from pathlib import Path - - -def describe(side, kind): - if kind == 'parse': - if side.get('ok'): - return 'OK' - return f"ERR {side.get('error')!r}@{'c' if side.get('cursor') else '0'}" - return f"SUGG[{len(side['list'])}]" - - -path = Path(sys.argv[1]) -only = sys.argv[2] if len(sys.argv) > 2 else None -groups = collections.Counter() -examples = {} -for line in path.open(encoding='utf-8'): - m = json.loads(line) - root = m['in'].split(' ')[0] - if only and root != only: - continue - key = (m['kind'], describe(m['vanilla'], m['kind']), describe(m['rust'], m['kind'])) - if m['kind'] == 'parse': - key = key[:1] + (key[1][:90], key[2][:90]) - groups[key] += 1 - examples.setdefault(key, m) -for key, count in sorted(groups.items(), key=lambda kv: -kv[1])[:int(sys.argv[3]) if len(sys.argv) > 3 else 40]: - ex = examples[key] - print(f'{count:6} {key[0]} vanilla={key[1]} rust={key[2]}\n e.g. {ex["in"]!r}') diff --git a/tools/command_tree_diff.py b/tools/command_tree_diff.py deleted file mode 100644 index 8bd049b7a..000000000 --- a/tools/command_tree_diff.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python3 -"""Structural diff between vanilla's exported command tree and Horizon's. - -usage: command_tree_diff.py VANILLA_TREE.json RUST_TREE.json [ROOT] - -Reports, for every shared node, the children Horizon lacks or adds, differing -argument parsers and executable/redirect flags. Missing subtrees are reported -once at their root. -""" -import json -import sys - -LOOSE = { - # Horizon's coarse argument kinds that stand in for several vanilla parsers. - 'brigadier:string': {'brigadier:string', 'minecraft:message', 'minecraft:component'}, -} - - -def same_parser(vanilla, rust): - if vanilla == rust: - return True - return False - - -def keyed(children): - """Literals by name; arguments by position (their names are internal).""" - out = {} - index = 0 - for name, child in children.items(): - if child['type'] == 'literal': - out[('l', name)] = (name, child) - else: - out[('a', index)] = (name, child) - index += 1 - return out - - -def diff(path, v, r, out): - vc, rc = keyed(v.get('children', {})), keyed(r.get('children', {})) - for key, (name, node) in vc.items(): - if key not in rc: - out.append(('missing', path + [name], node.get('parser') or 'literal', count(node))) - for key, (name, node) in rc.items(): - if key not in vc: - out.append(('extra', path + [name], node.get('parser') or 'literal', count(node))) - for key, (name, a) in vc.items(): - if key not in rc: - continue - _, b = rc[key] - if a['type'] == 'argument' and not same_parser(a['parser'], b['parser']): - out.append(('parser', path + [name], f"{a['parser']} vs {b['parser']}", 0)) - if bool(a.get('executable')) != bool(b.get('executable')): - out.append(('executable', path + [name], f"vanilla={bool(a.get('executable'))}", 0)) - if bool(a.get('redirect')) != bool(b.get('redirect')): - out.append(('redirect', path + [name], f"vanilla={bool(a.get('redirect'))}", 0)) - diff(path + [name], a, b, out) - - -def count(node): - return 1 + sum(count(c) for c in node.get('children', {}).values()) - - -def main(): - vanilla = json.load(open(sys.argv[1])) - rust = json.load(open(sys.argv[2])) - only = sys.argv[3] if len(sys.argv) > 3 else None - if only: - vanilla = {'children': {only: vanilla['children'][only]}, 'type': 'root'} - rust = {'children': {only: rust['children'].get(only, {'children': {}, 'type': 'literal'})}, 'type': 'root'} - out = [] - diff([], vanilla, rust, out) - for kind, path, detail, size in out: - print(f'{kind:10} {" ".join(path)} [{detail}]' + (f' ({size} nodes)' if size else '')) - missing = sum(size for kind, _, _, size in out if kind == 'missing') - print(f'-- {len(out)} differences, {missing} vanilla nodes missing in Horizon') - - -if __name__ == '__main__': - main() diff --git a/tools/compare_loot_fill.py b/tools/compare_loot_fill.py deleted file mode 100644 index 7ad307420..000000000 --- a/tools/compare_loot_fill.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/env python3 -"""Compare Rust container loot (examples/loot_fill) with vanilla LootTable.fill. - -usage: compare_loot_fill.py RESOURCES TABLES SEED... -TABLES is a comma-separated list or `chests` for every chest table. Builds the -loot_fill example, runs VanillaLootFillOracle and diffs slot contents -(enchantments compared as sets). Tables vanilla cannot fill without a level -(exploration maps) are reported and skipped. -""" -import collections -import os -import subprocess -import sys -from pathlib import Path -try: - from . import lab, test_rust_parity as base -except ImportError: - import lab - import test_rust_parity as base - - -def build_dir(): - return Path(os.environ['HORIZON_ORACLE_BUILD']) if os.environ.get('HORIZON_ORACLE_BUILD') else lab.LOCAL/'loot-fill-oracle' - - -def run_oracle(out, tables, seeds): - lock, jars, libraries = base.verify_artifacts() - source = lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLootFillOracle.java' - build = build_dir() - classes = build/'classes' - classes.mkdir(parents=True, exist_ok=True) - dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) - compiled = subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-cp', dependencies, - '-d', str(classes), str(source)], capture_output=True, text=True) - if compiled.returncode: - raise SystemExit('javac failed:\n' + compiled.stderr[-3000:]) - result = subprocess.run(['java', '-Xmx2G', '-cp', str(classes)+os.pathsep+dependencies, - 'dev.horizonlab.parity.VanillaLootFillOracle', str(out), tables, *seeds], - capture_output=True, text=True) - if result.returncode: - lines = [line for line in (result.stdout + result.stderr).splitlines() if 'Exception' in line or 'Caused' in line] - raise SystemExit('oracle failed: ' + ' | '.join(lines[:5])) - - -def parse(lines): - fills, errors = collections.defaultdict(list), set() - for line in lines: - t = line.split() - if not t: - continue - if t[0] == 'table': - fills[(t[1], t[2])] - elif t[0] == 'error': - errors.add((t[1], t[2])) - elif t[0] == 'fill': - fills[(t[1], t[2])].append((int(t[3]), t[4], t[5], t[6], tuple(sorted(t[7:])))) - return fills, errors - - -def main(): - resources, tables, seeds = sys.argv[1], sys.argv[2], sys.argv[3:] - out = build_dir()/'vanilla.txt' - out.parent.mkdir(parents=True, exist_ok=True) - run_oracle(out, tables, seeds) - vanilla, errors = parse(out.read_text().splitlines()) - names = sorted({k[0] for k in vanilla} | {k[0] for k in errors}) - subprocess.run(['cargo', 'build', '--profile', 'fast', '-q', '-p', 'horizon-world', '--example', 'loot_fill'], - check=True, cwd=lab.ROOT) - rust_out = subprocess.run([str(lab.cargo_target()/'fast/examples/loot_fill'), resources, ','.join(names), *seeds], - check=True, capture_output=True, text=True).stdout - rust, _ = parse(rust_out.splitlines()) - matched = differ = 0 - for key in sorted(vanilla): - if key in errors: - continue - if vanilla[key] == rust.get(key): - matched += 1 - continue - differ += 1 - if differ <= 20: - print('DIFF', key, '\n vanilla', vanilla[key], '\n rust ', rust.get(key)) - tables = collections.Counter(k[0] for k in vanilla if k not in errors and vanilla[k] != rust.get(k)) - if tables: - print('differing tables:', dict(tables)) - skipped = sorted({k[0] for k in errors}) - print(f'{matched} of {matched + differ} fills match; skipped (needs a level): {skipped}') - return 1 if differ else 0 - - -if __name__ == '__main__': - sys.exit(main()) diff --git a/tools/compare_structure_blocks.py b/tools/compare_structure_blocks.py deleted file mode 100644 index 51d71f57b..000000000 --- a/tools/compare_structure_blocks.py +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/env python3 -"""Compare structure placement (terrain + structure pieces, no placed features) -between vanilla and Rust for target chunks. - -usage: compare_structure_blocks.py RESOURCES SEED DIMENSION CX,CZ... -Runs VanillaStructurePlacementOracle and the structure_blocks example and -reports, per chunk, the blocks and block entities that differ. -""" -import json -import os -import subprocess -import sys -from pathlib import Path -try: - from . import lab, test_rust_parity as base -except ImportError: - import lab - import test_rust_parity as base - - -def build_dir(): - return Path(os.environ['HORIZON_ORACLE_BUILD']) if os.environ.get('HORIZON_ORACLE_BUILD') else lab.LOCAL/'structure-placement-oracle' - - -def run_oracle(out, args): - lock, jars, libraries = base.verify_artifacts() - source = lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructurePlacementOracle.java' - classes = build_dir()/'classes' - classes.mkdir(parents=True, exist_ok=True) - dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) - compiled = subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-cp', dependencies, - '-d', str(classes), str(source)], capture_output=True, text=True) - if compiled.returncode: - raise SystemExit('javac failed:\n' + compiled.stderr[-3000:]) - result = subprocess.run(['java', '-Xmx4G', '-cp', str(classes)+os.pathsep+dependencies, - 'dev.horizonlab.parity.VanillaStructurePlacementOracle', str(out), *args], - capture_output=True, text=True) - if result.returncode: - lines = [line for line in (result.stdout + result.stderr).splitlines() if 'Exception' in line or 'Error' in line or '\tat ' in line] - raise SystemExit('oracle failed: ' + ' | '.join(lines[:8])) - - -def parse(lines): - chunks, current = {}, None - for line in lines: - t = line.split() - if not t: - continue - if t[0] == 'chunk': - current = (int(t[1]), int(t[2])) - chunks[current] = {'rows': {}, 'be': []} - elif t[0] == 'y' and current: - chunks[current]['rows'][int(t[1])] = t[2:] - elif t[0] == 'be' and current: - # Position, loot table and seed; the block entity type follows - # from the (separately compared) block state. - chunks[current]['be'].append(' '.join(t[1:4] + t[5:])) - return chunks - - -def state_names(resources): - names = {} - report = lab.LOCAL/'datagen/out/reports/blocks.json' - if report.exists(): - for block, info in json.loads(report.read_text()).items(): - for state in info['states']: - props = ','.join(f'{k}={v}' for k, v in sorted(state.get('properties', {}).items())) - names[str(state['id'])] = block + (f'[{props}]' if props else '') - return names - - -def main(): - resources, seed, dimension, targets = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4:] - out = build_dir()/'vanilla.txt' - out.parent.mkdir(parents=True, exist_ok=True) - run_oracle(out, [seed, dimension, *targets]) - vanilla = parse(out.read_text().splitlines()) - subprocess.run(['cargo', 'build', '--profile', 'fast', '-q', '-p', 'horizon-world', '--example', 'structure_blocks'], - check=True, cwd=lab.ROOT) - rust_out = subprocess.run([str(lab.cargo_target()/'fast/examples/structure_blocks'), resources, seed, dimension, *targets], - check=True, capture_output=True, text=True).stdout - (build_dir()/'rust.txt').write_text(rust_out) - rust = parse(rust_out.splitlines()) - names = state_names(resources) - failed = 0 - for key in sorted(vanilla): - v, r = vanilla[key], rust.get(key) - if r is None: - print(key, 'missing from Rust') - failed += 1 - continue - diffs = [] - for y, row in v['rows'].items(): - other = r['rows'].get(y, []) - for i, (a, b) in enumerate(zip(row, other)): - if a != b: - diffs.append((key[0] * 16 + i % 16, y, key[1] * 16 + i // 16, a, b)) - total = sum(len(row) for row in v['rows'].values()) - be_v, be_r = set(v['be']), set(r['be']) - status = 'match' if not diffs and be_v == be_r else 'DIFF' - print(f'chunk {key}: {status}; {total - len(diffs)} of {total} blocks equal; block entities {len(be_v & be_r)} of {len(be_v)} equal') - for x, y, z, a, b in diffs[:12]: - print(f' {x} {y} {z} vanilla {names.get(a, a)} rust {names.get(b, b)}') - for e in sorted(be_v - be_r)[:6]: - print(' only vanilla be', e) - for e in sorted(be_r - be_v)[:6]: - print(' only rust be', e) - failed += status != 'match' - return 1 if failed else 0 - - -if __name__ == '__main__': - sys.exit(main()) diff --git a/tools/compare_structure_starts.py b/tools/compare_structure_starts.py deleted file mode 100644 index 363e7b76f..000000000 --- a/tools/compare_structure_starts.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python3 -"""Compare Rust structure starts (chunkgen_bench --starts) with the vanilla oracle. - -usage: compare_structure_starts.py VANILLA RUST [--all] -Pieces are compared by type, bounding box and (for jigsaw pieces) position, -rotation, ground level delta and junction count. Without --all, vanilla -starts of structure types Rust does not generate yet are only counted. -""" -import collections -import sys - - -def load(path): - starts = {} - current = None - for line in open(path): - t = line.split() - if not t: - continue - if t[0] == 'start': - current = (int(t[1]), int(t[2]), t[3]) - starts[current] = [' '.join(t[4:])] - elif t[0] == 'piece' and current: - starts[current].append(' '.join(t[1:14])) - return starts - - -def main(): - vanilla, rust = load(sys.argv[1]), load(sys.argv[2]) - generated = {k[2] for k in rust} - matched = 0 - missing = collections.Counter() - for key in sorted(vanilla): - if key not in rust: - missing[key[2]] += 1 - if key[2] in generated or '--all' in sys.argv: - print('missing', key) - continue - if vanilla[key] == rust[key]: - matched += 1 - continue - v, r = vanilla[key], rust[key] - print('DIFF', key, 'pieces', len(v) - 1, len(r) - 1) - for i, (a, b) in enumerate(zip(v, r)): - if a != b: - print(' first difference at line', i, '\n vanilla', a, '\n rust ', b) - break - for key in sorted(set(rust) - set(vanilla)): - print('extra', key) - print(f'{matched} of {len(vanilla)} vanilla starts match exactly; not generated by Rust:', dict(missing)) - return 0 if matched == len(rust) == sum(1 for k in vanilla if k[2] in generated) else 1 - - -if __name__ == '__main__': - sys.exit(main()) diff --git a/tools/fetch_client_assets.py b/tools/fetch_client_assets.py deleted file mode 100644 index 2027593c5..000000000 --- a/tools/fetch_client_assets.py +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env python3 -"""Copy the pinned version's indexed client assets that are not in the game -jar from your own official launcher install: language files and the language -list (pack.mcmeta), the unifont glyph archives and their font definitions, and -the built-in Programmer Art and High Contrast resource packs. Every object's -SHA-1 is verified. Nothing is downloaded; files go to the private client -resource directory (or --target) and are never committed.""" -import argparse -from pathlib import Path -import shutil - -import lab - - -def wanted(name): - return (name == 'pack.mcmeta' - or name.startswith('minecraft/lang/') - or name.startswith('minecraft/font/') - or name.startswith('minecraft/resourcepacks/')) - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--target', type=Path, default=lab.RESOURCES, - help='prepared resource directory (default: .local/horizon-client/)') - parser.add_argument('--minecraft-dir', type=Path, - help="official launcher game directory (default: the launcher's own)") - args = parser.parse_args() - lock, directory = lab.config() - manifest = lab.import_manifest(lock, directory, args.minecraft_dir) - store, index = lab.launcher_assets(manifest, args.minecraft_dir) - target = args.target - target.mkdir(parents=True, exist_ok=True) - shutil.copyfile(index, target / 'asset-index.json') - objects = lab.json.loads(index.read_text())['objects'] - selected = {name: info for name, info in objects.items() if wanted(name)} - total = 0 - for name, info in selected.items(): - source = lab.launcher_object(store, info['hash']) - lab.import_copy(source, target / 'assets' / name, info['hash']) - total += info['size'] - print(f'Client assets ready: {len(selected)} files, {total / 1e6:.1f} MB') - - -if __name__ == '__main__': - main() diff --git a/tools/profile_behaviour_cache.py b/tools/profile_behaviour_cache.py deleted file mode 100644 index 00ba65a6d..000000000 --- a/tools/profile_behaviour_cache.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python3 -"""Measure the resource-dependent Behaviours::load portion of client startup. - -Build the behaviour_load_profile example in the checkout to be measured first: - cargo build --release -p horizon-world --example behaviour_load_profile - -Run the profiler from the repository root with the matching example binary. -This measures behaviour loading, not time to first rendered frame. With ---cache-dir, the example reads and refreshes the resolved snapshot there, as the -client does with its .horizon-cache folder: the first load of a run builds it -when it is missing, the next loads restore it. -""" -import argparse -import json -import re -import statistics -import subprocess -from pathlib import Path - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--binary", type=Path, default=Path("target/release/examples/behaviour_load_profile")) - parser.add_argument("--resources", type=Path, default=Path(".local/horizon-client/26.3")) - parser.add_argument("--cache-dir", type=Path, - help="snapshot folder (default: no snapshot, every load is uncached)") - parser.add_argument("--repeats", type=int, default=5) - parser.add_argument("--output", type=Path) - args = parser.parse_args() - if args.repeats < 1: - parser.error("--repeats must be at least one") - samples = [] - for _ in range(args.repeats): - command = [str(args.binary.resolve()), str(args.resources.resolve())] - if args.cache_dir: - command.append(str(args.cache_dir.resolve())) - run = subprocess.run(command, text=True, capture_output=True, check=True) - values = {key: float(value) for key, value in - re.findall(r"^(registry_ms|behaviours_[0-2]_ms)=([\d.]+)$", run.stderr, re.M)} - if len(values) != 4: - raise RuntimeError(f"incomplete profile output: {run.stderr}") - samples.append(values) - summary = {key: {"median_ms": round(statistics.median(row[key] for row in samples), 3), - "samples_ms": [row[key] for row in samples]} - for key in samples[0]} - result = {"scope": "behaviour loader only; not full client startup", - "binary": str(args.binary), "resources": str(args.resources), "repeats": args.repeats, - "cache_dir": str(args.cache_dir) if args.cache_dir else None, - "metrics": summary} - print(json.dumps(result, indent=2)) - if args.output: - args.output.parent.mkdir(parents=True, exist_ok=True) - args.output.write_text(json.dumps(result, indent=2) + "\n") - - -if __name__ == "__main__": - main() diff --git a/tools/structure_start_oracle.py b/tools/structure_start_oracle.py deleted file mode 100644 index dc622ae19..000000000 --- a/tools/structure_start_oracle.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env python3 -"""Run the vanilla structure-start oracle for a seed and chunk rectangle. - -usage: structure_start_oracle.py OUT SEED X0 Z0 X1 Z1 -""" -import os -import subprocess -from pathlib import Path -import sys -try: - from . import lab, test_rust_parity as base -except ImportError: - import lab - import test_rust_parity as base - - -def main(): - out, seed, x0, z0, x1, z1 = sys.argv[1:7] - lock, jars, libraries = base.verify_artifacts() - source = lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureStartOracle.java' - build = Path(os.environ['HORIZON_ORACLE_BUILD']) if os.environ.get('HORIZON_ORACLE_BUILD') else lab.LOCAL/'structure-start-oracle' - classes = build/'classes' - classes.mkdir(parents=True, exist_ok=True) - dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) - compiled = subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-cp', dependencies, - '-d', str(classes), str(source)], capture_output=True, text=True) - if compiled.returncode: - raise SystemExit('javac failed:\n' + compiled.stderr[-3000:]) - result = subprocess.run(['java', '-Xmx2G', '-cp', str(classes)+os.pathsep+dependencies, - 'dev.horizonlab.parity.VanillaStructureStartOracle', out, seed, x0, z0, x1, z1], - capture_output=True, text=True) - if result.returncode: - lines = [line for line in (result.stdout + result.stderr).splitlines() if 'Exception' in line or 'Caused' in line] - raise SystemExit('oracle failed: ' + ' | '.join(lines[:5])) - - -if __name__ == '__main__': - main() diff --git a/tools/test_lan_lifecycle.py b/tools/test_lan_lifecycle.py deleted file mode 100644 index 389b8438c..000000000 --- a/tools/test_lan_lifecycle.py +++ /dev/null @@ -1,222 +0,0 @@ -#!/usr/bin/env python3 -"""Check LAN shutdown when leaving a singleplayer world through the pause menu, -and that offline guests joining with their default names are not refused as the -host's profile (#195: everyone was "Player"). - -Requires a built horizon-client, prepared resources and a display on Unix: - xvfb-run -a python3 tools/test_lan_lifecycle.py --client target/fast/horizon-client -Worlds and settings are created in a temporary directory. -""" -import argparse -import json -import os -from pathlib import Path -import socket -import subprocess -import tempfile -import time - -try: - from . import lab -except ImportError: - import lab - -ROOT = Path(__file__).resolve().parents[1] -GROUP = '224.0.2.60' -DISCOVERY_PORT = 4445 - - -def command(endpoint, line): - with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection: - connection.settimeout(60) - connection.connect(str(endpoint)) - connection.sendall((line + '\n').encode()) - with connection.makefile('r') as reply: - result = json.loads(reply.readline()) - assert 'error' not in result, (line, result) - return result - - -def wait_for(endpoint, line, predicate, timeout=60): - deadline = time.monotonic() + timeout - while time.monotonic() < deadline: - try: - result = command(endpoint, line) - except (FileNotFoundError, ConnectionRefusedError): - time.sleep(0.1) - continue - if predicate(result): - return result - time.sleep(0.1) - raise AssertionError(f'timed out waiting for {line}') - - -def announcement(scanner, port, timeout): - deadline = time.monotonic() + timeout - marker = f'[AD]{port}[/AD]'.encode() - while time.monotonic() < deadline: - scanner.settimeout(max(0.001, deadline - time.monotonic())) - try: - message, _ = scanner.recvfrom(4096) - except socket.timeout: - return False - if marker in message: - return True - return False - - -def scenario(endpoint, scanner): - wait_for(endpoint, 'screen', lambda value: value['screen'] == 'title') - command(endpoint, 'open LanLifecycle 0 creative') - wait_for(endpoint, 'status', lambda value: value['player'] is not None - and value['pending_chunks'] == 0) - assert command(endpoint, 'lan status') == {'open': False} - port = 0 - for _ in range(2): - port = command(endpoint, f'lan open {port}')['port'] - with socket.create_connection(('127.0.0.1', port), timeout=2): - pass - assert announcement(scanner, port, 5), 'LAN world was not advertised' - command(endpoint, 'key esc tap') - screen = wait_for(endpoint, 'screen', lambda value: any( - button['label'] == 'Save and Quit to Title' for button in value['buttons'])) - assert screen['screen'] == 'paused', screen - command(endpoint, 'click-button Save and Quit to Title') - wait_for(endpoint, 'screen', lambda value: value['screen'] == 'title') - assert command(endpoint, 'lan status') == {'open': False}, 'LAN stayed open after leaving' - try: - connection = socket.create_connection(('127.0.0.1', port), timeout=2) - except ConnectionRefusedError: - pass - else: - connection.close() - raise AssertionError('LAN still accepts connections after leaving') - # Discard datagrams queued before shutdown, then listen for more than - # two announcement intervals (the pinger sends every 1.5 seconds). - scanner.setblocking(False) - try: - while True: - scanner.recvfrom(4096) - except BlockingIOError: - pass - assert not announcement(scanner, port, 3.5), 'LAN kept advertising after leaving' - command(endpoint, 'open LanLifecycle') - wait_for(endpoint, 'status', lambda value: value['player'] is not None - and value['pending_chunks'] == 0) - assert command(endpoint, 'lan status') == {'open': False}, 'LAN reopened with the world' - command(endpoint, 'lan open 0') - command(endpoint, 'quit') - - -def start_client(client, resources, home, endpoint, log, *extra): - return subprocess.Popen([ - str(client), '--resources', str(resources), '--render-distance', '2', - '--test-terrain', '--control-socket', str(endpoint), '--timeout-seconds', '180', *extra, - ], cwd=home, env=dict(os.environ, HORIZON_HOME=str(home), HORIZON_NO_AUDIO='1', - HORIZON_PLAYER_NAME=''), - stdout=log, stderr=subprocess.STDOUT) - - -def guest_names(endpoint, port, guests): - """Two guests with default names join together; a guest named like the host is refused.""" - names = [] - for home, guest in guests: - wait_for(guest, 'screen', lambda value: value['screen'] == 'title') - command(guest, f'connect 127.0.0.1:{port}') - wait_for(guest, 'status', lambda value: (value.get('server') or {}).get('joined')) - kept = (home / 'horizon-player.txt').read_text() - assert kept.startswith('name:Player') and kept.strip() != 'name:Player', kept - names.append(kept.strip().removeprefix('name:')) - assert names[0] != names[1], names - status = wait_for(endpoint, 'lan status', lambda value: len(value['guests']) == 2) - assert sorted(g['name'] for g in status['guests']) == sorted(names), status - # The same home keeps its name: leave and join again as the same profile. - home, guest = guests[0] - command(guest, 'disconnect') - wait_for(endpoint, 'lan status', lambda value: len(value['guests']) == 1) - command(guest, f'connect 127.0.0.1:{port}') - wait_for(guest, 'status', lambda value: (value.get('server') or {}).get('joined')) - assert (home / 'horizon-player.txt').read_text().strip() == f'name:{names[0]}' - # A guest that really is the host's offline profile is refused, the others stay. - command(guest, 'disconnect') - command(guest, f'connect 127.0.0.1:{port} Player') - refused = wait_for(guest, 'screen', lambda value: (value.get('menu') or {}).get('disconnected')) - assert 'another location' in refused['menu']['disconnected'], refused - status = command(endpoint, 'lan status') - assert [g['name'] for g in status['guests']] == [names[1]], status - return names - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--client', type=Path, required=True) - parser.add_argument('--resources', type=Path, default=lab.RESOURCES) - args = parser.parse_args() - client, resources = args.client.resolve(), args.resources.resolve() - with tempfile.TemporaryDirectory(prefix='horizon-lan-') as directory: - work = Path(directory) - endpoint = work / 'control.sock' - with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as scanner: - scanner.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - scanner.bind(('', DISCOVERY_PORT)) - scanner.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, - socket.inet_aton(GROUP) + socket.inet_aton('0.0.0.0')) - with (work / 'client.log').open('w+') as log: - process = start_client(client, resources, work, endpoint, log) - try: - scenario(endpoint, scanner) - assert process.wait(timeout=20) == 0, 'client exited unsuccessfully' - except Exception: - log.seek(0) - print('\n'.join(log.read().splitlines()[-20:])) - raise - finally: - stop(process) - names = guests_scenario(client, resources, work) - print('LAN lifecycle passed: leaving stops hosting and discovery; reopening stays private') - print(f'LAN guests passed: default names {names[0]} and {names[1]} joined together and kept; ' - '"Player" refused as the host\'s profile') - - -def stop(process): - if process.poll() is None: - process.terminate() - try: - process.wait(timeout=10) - except subprocess.TimeoutExpired: - process.kill() - process.wait(timeout=10) - - -def guests_scenario(client, resources, work): - host_home = work / 'host' - homes = [work / 'guest-a', work / 'guest-b'] - processes, logs = [], [] - try: - for home in [host_home, *homes]: - home.mkdir() - log = (home / 'client.log').open('w+') - logs.append(log) - processes.append(start_client(client, resources, home, home / 'control.sock', log)) - endpoint = host_home / 'control.sock' - wait_for(endpoint, 'screen', lambda value: value['screen'] == 'title') - command(endpoint, 'open LanGuests 0 creative') - wait_for(endpoint, 'status', lambda value: value['player'] is not None - and value['pending_chunks'] == 0) - port = command(endpoint, 'lan open 0')['port'] - return guest_names(endpoint, port, [(home, home / 'control.sock') for home in homes]) - except Exception: - for log in logs: - log.seek(0) - print(f'--- {log.name}') - print('\n'.join(log.read().splitlines()[-20:])) - raise - finally: - for process in processes: - stop(process) - for log in logs: - log.close() - - -if __name__ == '__main__': - main() From eeb4cdb680bb16739a1f4c85e3bea24ad2097052 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:06:50 +0200 Subject: [PATCH 027/408] Mod SDK: export_mod! exports only in WebAssembly, so the guests link on macOS A host build of a mod (cargo build or test on the workspace) made a cdylib whose component exports macOS's ld couldn't take: its exported-symbols list cuts `horizon:mods/events@0.1.0#init` at the `#`, so coords-hud and horizon-mods-test-guest failed to link. The exports now exist only for wasm32; on the host the macro still checks the mod and keeps it used. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-mod-sdk/src/lib.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/horizon-mod-sdk/src/lib.rs b/crates/horizon-mod-sdk/src/lib.rs index ccfdb7947..71c36cf80 100644 --- a/crates/horizon-mod-sdk/src/lib.rs +++ b/crates/horizon-mod-sdk/src/lib.rs @@ -135,7 +135,13 @@ macro_rules! export_mod { with(|m| $crate::Mod::chat(m, &text)) } } + // Only WebAssembly has the component's exports: a host build (cargo test or + // clippy on the workspace) checks the mod without them, which macOS + // couldn't link (its exported-symbols list cuts names at the `#`). + #[cfg(target_arch = "wasm32")] $crate::__export_horizon_mod!(Export); + #[cfg(not(target_arch = "wasm32"))] + let _ = ::init; }; }; } From 5ca16b97fcd4be7924064bd22cbc5fe4e86a6e4c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:07:38 +0200 Subject: [PATCH 028/408] Keep version.rs as tools/gen_version_consts.py writes it The file is generated from the pinned version lock, and test_gen_version_consts checks JAVA_VERSION against it; deleting constants by hand breaks the next regeneration and that test. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-core/src/version.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/horizon-core/src/version.rs b/crates/horizon-core/src/version.rs index cb3e85629..29994823c 100644 --- a/crates/horizon-core/src/version.rs +++ b/crates/horizon-core/src/version.rs @@ -11,6 +11,10 @@ pub const PROTOCOL_VERSION: i32 = 777; pub const DATA_VERSION: i32 = 5023; /// `WorldVersion.packVersion(PackType.CLIENT_RESOURCES)`: (major, minor). pub const RESOURCE_PACK_FORMAT: (i64, i64) = (97, 1); +/// `WorldVersion.packVersion(PackType.SERVER_DATA)`: (major, minor). +pub const DATA_PACK_FORMAT: (i64, i64) = (121, 0); +/// The Java major version the game runs on. +pub const JAVA_VERSION: u32 = 25; /// `WorldVersion.stable()`: false for snapshots and pre-releases. pub const STABLE: bool = true; /// `WorldVersion.buildTime()` as `Date.toString()` prints it in UTC (`/version`). From b15e5e893ed96733ebcdb1e8a1e7e41969251f59 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 14:58:39 +0200 Subject: [PATCH 029/408] Code mods are the client's mods feature: tests and probes skip wasmtime horizon-mods' runtime is no longer a default feature, and its sandbox test requires runtime and pack instead of a dev-dependency on itself (that dev-dependency turned the runtime on in every workspace build with examples, the parity probe build included). The client gets a mods feature that turns the runtime on; without it game/mods.rs keeps content mods and logs why code mods don't start, and every hook does nothing. Release builds (client and server) pass the feature, CI's clippy and tests pass it (and pack, for the sandbox test), and pr_ready does where horizon-mods is checked. horizon_mods::find moves to manifest.rs: content mods use it without the runtime. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 5 +- .github/workflows/release.yml | 8 ++- Cargo.lock | 1 - crates/horizon-client/Cargo.toml | 6 +- crates/horizon-client/src/game/chat.rs | 4 +- crates/horizon-client/src/game/extras.rs | 2 +- crates/horizon-client/src/game/mods.rs | 83 ++++++++++++++++++++---- crates/horizon-mods/Cargo.toml | 11 ++-- crates/horizon-mods/src/lib.rs | 2 +- crates/horizon-mods/src/manifest.rs | 20 +++++- crates/horizon-mods/src/runtime.rs | 17 ----- docs/mods.md | 12 +++- tests/test_pr_ready.py | 5 +- tools/pr_ready.py | 14 +++- 14 files changed, 138 insertions(+), 52 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8966854c2..32ad79497 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -61,12 +61,13 @@ jobs: if: steps.rust.outputs.required != 'false' run: | cargo +stable fmt --all -- --check - cargo +stable clippy --workspace --all-targets -- -D warnings + # With the game's code mods (on in every release build, off by default). + cargo +stable clippy --workspace --all-targets --features horizon-client/mods -- -D warnings # The server build (released as horizon-engine): the game without sound or controllers. cargo +stable clippy -p horizon-client --all-targets --no-default-features -- -D warnings - name: Test Rust core and voxel kernel correctness if: steps.rust.outputs.required != 'false' - run: cargo +stable test --workspace + run: cargo +stable test --workspace --features horizon-client/mods,horizon-mods/pack parity: if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository uses: ./.github/workflows/parity.yml diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b19ba9ce5..bb3be5480 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -128,7 +128,8 @@ jobs: if: runner.os == 'Linux' run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev libudev-dev - name: Build the client, horizon-ctl, horizon-prepare and horizon-server - run: cargo build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare --bin horizon-prepare -p horizon-server --bin horizon-server + # `horizon-client/mods`: every released game runs code mods (the feature is off in dev builds). + run: cargo build --release --locked --features horizon-client/mods -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare --bin horizon-prepare -p horizon-server --bin horizon-server - name: Every program the release folder takes was built run: | for binary in horizon-client horizon-ctl horizon-prepare horizon-server; do @@ -250,8 +251,9 @@ jobs: run: | set -euo pipefail # After the client is packaged: target/release/horizon-client is rebuilt without the audio and - # controllers features, so it needs neither libasound nor libudev (minimal server images lack them). - cargo build --release --locked -p horizon-client --no-default-features --bin horizon-client + # controllers features, so it needs neither libasound nor libudev (minimal server images lack them), + # and with code mods like the client. + cargo build --release --locked -p horizon-client --no-default-features --features mods --bin horizon-client cargo run --locked -p xtask -- package-server target/release/horizon-client "dist/${{ matrix.server_dir }}" folder="dist/${{ matrix.server_dir }}" python3 tools/check_imports.py --server "$folder/horizon-engine" "$folder/horizon-server" "$folder/horizon-prepare" diff --git a/Cargo.lock b/Cargo.lock index 2f832e248..1a1b288c9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1493,7 +1493,6 @@ dependencies = [ name = "horizon-mods" version = "0.1.0" dependencies = [ - "horizon-mods", "log", "serde", "serde_json", diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index cd5d86fe7..94ba949d0 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -18,7 +18,8 @@ horizon-protocol = { path = "../horizon-protocol" } horizon-server-files = { path = "../horizon-server-files" } horizon-friends = { path = "../horizon-friends" } # Horizon mods: sandboxed WebAssembly components, off unless installed and turned on (docs/mods.md). -horizon-mods = { path = "../horizon-mods" } +# Their runtime is the `mods` feature. +horizon-mods = { path = "../horizon-mods", default-features = false } wgpu = { version = "30.0.1", default-features = false, features = ["std", "parking_lot", "vulkan", "metal", "wgsl"] } winit = "0.30.13" pollster = "0.4" @@ -78,6 +79,9 @@ default = ["audio", "controllers"] audio = ["dep:cpal"] # Controllers: gilrs, and the DualSense's own output. Without it only `horizon-ctl pad`'s virtual pad. controllers = ["dep:gilrs", "dep:horizon-dualsense"] +# Runs code mods (wasmtime and cranelift: a quarter of a clean build). On in every release build +# (release.yml); the tests and probes don't need it. Content mods load without it. +mods = ["horizon-mods/runtime"] # Records the call sites of mob random draws (`mob_ai_probe` traces). rng-trace = ["horizon-core/rng-trace"] diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 20aeeb7fd..3d10d57b6 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -454,7 +454,7 @@ impl Game<'_> { return; } let focused = self.screen == Screen::Chat; - let heard = self.mods.mods.is_running().then(|| text.plain()); + let heard = self.mods.running().then(|| text.plain()); self.ui.chat.add( &self.gui.atlas, text, @@ -583,7 +583,7 @@ impl Game<'_> { &[Text::literal(PLAYER_NAME), Text::literal(message)], ); let focused = self.screen == Screen::Chat; - let heard = self.mods.mods.is_running().then(|| line.plain()); + let heard = self.mods.running().then(|| line.plain()); self.ui .chat .add(&self.gui.atlas, line, None, self.ticks, focused); diff --git a/crates/horizon-client/src/game/extras.rs b/crates/horizon-client/src/game/extras.rs index c16c54447..cee173fda 100644 --- a/crates/horizon-client/src/game/extras.rs +++ b/crates/horizon-client/src/game/extras.rs @@ -237,7 +237,7 @@ impl Game<'_> { /// the caller). The top left corner gives way to the debug screen. pub(super) fn draw_extras(&mut self, batch: &mut HudBatch) { let e = &self.settings.extras; - let mod_panels = self.mods.mods.panels().next().is_some(); + let mod_panels = self.mods.has_panels(); if !e.fps && !e.keystrokes && !e.minimap && !mod_panels { return; } diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 01787ec02..572f9fe2b 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -2,43 +2,76 @@ //! their tick, frame, chat and command hooks, their HUD panels and what //! they print. With no mod on, `horizon_mods::Mods` holds no engine and //! every hook here returns after one check. -use super::{Game, Screen}; +//! +//! Code mods run only in builds with the `mods` feature (release builds): +//! without it the game links no wasmtime, and every hook does nothing. +//! Content mods (`content_root`) load in every build. +use super::Game; use horizon_client::{ command::{Dispatcher, vanilla}, - extras::Corner, - extras_hud::{self, Corners}, + extras_hud::Corners, hud::HudBatch, - mod_list::{self, Installed}, - text::{self, Text}, + mod_list, }; -use horizon_mods::{Clock, Mods, Output, Player, Snapshot, Status}; -use std::{ - path::PathBuf, - time::{Duration, Instant}, +use std::{path::PathBuf, time::Duration}; +#[cfg(feature = "mods")] +use { + super::Screen, + horizon_client::{ + extras::Corner, + extras_hud, + mod_list::Installed, + text::{self, Text}, + }, + horizon_mods::{Clock, Mods, Output, Player, Snapshot, Status}, + std::time::Instant, }; #[derive(Default)] pub(super) struct ModsState { - pub(super) mods: Mods, + #[cfg(feature = "mods")] + mods: Mods, /// `--dev-mod PATH`: always on, reloaded when rebuilt. pub(super) dev: Vec, /// When dev mods were last checked for a rebuild. + #[cfg(feature = "mods")] checked: Option, /// The chat's command tree while a running mod owns commands. + #[cfg(feature = "mods")] tree: Option, } impl ModsState { /// The chat's command tree: vanilla's, plus the running mods' commands. pub(super) fn dispatcher(&self) -> &Dispatcher { - self.tree - .as_ref() - .unwrap_or_else(|| vanilla::game_dispatcher()) + #[cfg(feature = "mods")] + if let Some(tree) = &self.tree { + return tree; + } + vanilla::game_dispatcher() + } + /// Whether a mod runs: the chat keeps its lines for them. + pub(super) fn running(&self) -> bool { + #[cfg(feature = "mods")] + if self.mods.is_running() { + return true; + } + false + } + /// Whether a mod draws a HUD panel. + pub(super) fn has_panels(&self) -> bool { + #[cfg(feature = "mods")] + if self.mods.panels().next().is_some() { + return true; + } + false } } /// How often dev mods are checked for a rebuild. +#[cfg(feature = "mods")] const RELOAD_CHECK: Duration = Duration::from_secs(1); /// A vanilla command name: mods may not take it. +#[cfg(feature = "mods")] fn vanilla_command(name: &str) -> bool { let d = vanilla::game_dispatcher(); d.nodes[0] @@ -112,6 +145,30 @@ pub(super) fn content_root( } } +/// A build without the `mods` feature: no mod runs. +#[cfg(not(feature = "mods"))] +impl Game<'_> { + /// Says why the installed and dev mods don't run. + pub(super) fn start_mods(&mut self) { + let dir = Self::options_path().with_file_name(mod_list::DIR); + let found = horizon_mods::find(&dir).len() + self.mods.dev.len(); + if found > 0 { + log::warn!( + "Horizon: {found} mod(s) not started: this build has no mod runtime (build with --features mods)" + ); + } + } + pub(super) fn sync_mods(&mut self) {} + pub(super) fn tick_mods(&mut self) {} + pub(super) fn mods_frame(&mut self, _elapsed: Duration) {} + pub(super) fn mod_command(&mut self, _command: &str) -> bool { + false + } + pub(super) fn mods_chat(&mut self, _line: &str) {} + pub(super) fn draw_mod_panels(&self, _batch: &mut HudBatch, _corners: &mut Corners) {} +} + +#[cfg(feature = "mods")] impl Game<'_> { /// Reads `horizon-mods/` and the dev mods, and starts the ones turned on. pub(super) fn start_mods(&mut self) { diff --git a/crates/horizon-mods/Cargo.toml b/crates/horizon-mods/Cargo.toml index 8db24ac35..013d38a99 100644 --- a/crates/horizon-mods/Cargo.toml +++ b/crates/horizon-mods/Cargo.toml @@ -19,13 +19,16 @@ wit-component = { version = "0.239", optional = true } wit-parser = { version = "0.239", optional = true } [features] -default = ["runtime"] -# Loads and runs mods; without it only manifests and packaging (cargo horizon-mod). +# Loads and runs mods (the game's `mods` feature); without it only manifests, +# content and packaging. Off by default so builds that don't run mods (the +# game's tests and probes) skip wasmtime and cranelift. runtime = ["dep:wasmtime"] pack = ["dep:wit-component", "dep:wit-parser"] -[dev-dependencies] -horizon-mods = { path = ".", features = ["pack"] } +# Runs real mods: `cargo test -p horizon-mods --features runtime,pack`. +[[test]] +name = "sandbox" +required-features = ["runtime", "pack"] [lints] workspace = true diff --git a/crates/horizon-mods/src/lib.rs b/crates/horizon-mods/src/lib.rs index ec9ebe67d..5060bf747 100644 --- a/crates/horizon-mods/src/lib.rs +++ b/crates/horizon-mods/src/lib.rs @@ -11,6 +11,6 @@ pub mod manifest; mod runtime; pub use content::Content; -pub use manifest::{Capability, Manifest, Package, Side}; +pub use manifest::{Capability, Manifest, Package, Side, find}; #[cfg(feature = "runtime")] pub use runtime::*; diff --git a/crates/horizon-mods/src/manifest.rs b/crates/horizon-mods/src/manifest.rs index 44cdbd418..a71210883 100644 --- a/crates/horizon-mods/src/manifest.rs +++ b/crates/horizon-mods/src/manifest.rs @@ -1,6 +1,10 @@ //! `horizon-mod.toml`, a mod's manifest, and the `.hmod` file around it. use serde::Deserialize; -use std::{fmt, io::Read, path::Path}; +use std::{ + fmt, + io::Read, + path::{Path, PathBuf}, +}; /// The manifest's file name, beside `mod.wasm`. pub const MANIFEST: &str = "horizon-mod.toml"; @@ -282,6 +286,20 @@ impl Package { } } +/// The `.hmod` files and mod folders in `dir`, by name. +pub fn find(dir: &Path) -> Vec { + let Ok(read) = std::fs::read_dir(dir) else { + return Vec::new(); + }; + let mut found: Vec = read + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|e| e == "hmod") || p.join(MANIFEST).is_file()) + .collect(); + found.sort(); + found +} + /// Turns a `wasm32-unknown-unknown` cdylib built with the SDK into the /// component the game loads. #[cfg(feature = "pack")] diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index 975cd1461..9dd2eb54e 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -131,23 +131,6 @@ pub struct Mods { out: Vec, } -/// The `.hmod` files and mod folders in `dir`, by name. -pub fn find(dir: &Path) -> Vec { - let Ok(read) = std::fs::read_dir(dir) else { - return Vec::new(); - }; - let mut found: Vec = read - .flatten() - .map(|e| e.path()) - .filter(|p| { - p.extension().is_some_and(|e| e == "hmod") - || p.join(crate::manifest::MANIFEST).is_file() - }) - .collect(); - found.sort(); - found -} - impl Mods { /// Reads every mod at `paths` and starts those `enabled` says are on. /// A command that `reserved` (vanilla's commands) or an earlier mod diff --git a/docs/mods.md b/docs/mods.md index 4b356d336..4521d312d 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -137,10 +137,17 @@ proposal, no profiling. Its cranelift backend generates native code for x86-64 and ARM64 on Windows, macOS and Linux, which is why one `.hmod` serves them all. +The game links it only with its `mods` feature: every release build turns it +on (`release.yml`), and a build from source needs +`cargo build --release -p horizon-client --features mods` to run code mods. +Without it (the tests and probes) wasmtime and cranelift aren't built, a +quarter of a clean build; content mods still load, and the game logs why the +code mods don't start. + ### Performance Measured on the Mac mini (M4 Pro), release build, `cargo test -p -horizon-mods --release --test sandbox -- --ignored --nocapture`: +horizon-mods --features runtime,pack --release --test sandbox -- --ignored --nocapture`: | | per call | |---|---| @@ -180,7 +187,8 @@ chat (`Mod Test Guest stopped: it took too long (an endless loop?)`), marks it on the Mods page and carries on; the other mods keep running. Host functions clip what a mod hands back (chat lines per call, HUD lines and lengths). Tests: `crates/horizon-mods/tests/sandbox.rs` (an endless loop, a panic and a 1 GiB -allocation, next to a healthy mod). +allocation, next to a healthy mod; `cargo test -p horizon-mods --features +runtime,pack`). ## Playing with mods diff --git a/tests/test_pr_ready.py b/tests/test_pr_ready.py index c10e7b2ac..8268d5ab7 100644 --- a/tests/test_pr_ready.py +++ b/tests/test_pr_ready.py @@ -9,6 +9,7 @@ PACKAGES = {"horizon-core": "crates/horizon-core", "horizon-client": "crates/hor "horizon-theme": "crates/horizon-theme", "xtask": "xtask"} LIBRARIES = set(PACKAGES) - {"xtask"} DEPENDENCIES = {"horizon-client": {"horizon-core"}} +MODS = " --features horizon-mods/runtime,horizon-mods/pack,horizon-client/mods" def args(host="local", quick=False): @@ -58,9 +59,9 @@ class PrReadyTests(unittest.TestCase): steps = pr_ready.plan(args(quick=True), "origin/main", {path}, PACKAGES, LIBRARIES, DEPENDENCIES) by_name = {step.name: step for step in steps} self.assertEqual(by_name["clippy"].command, - "cargo clippy --workspace --all-targets --locked -- -D warnings") + "cargo clippy --workspace" + MODS + " --all-targets --locked -- -D warnings") self.assertEqual(by_name["tests: workspace"].command, - "cargo test --locked --workspace --tests") + "cargo test --locked --workspace" + MODS + " --tests") self.assertEqual(by_name["doc tests"].command, "cargo test --locked --workspace --doc") def test_non_rust_changes_skip_workspace_checks(self): diff --git a/tools/pr_ready.py b/tools/pr_ready.py index e3e317ef8..a944e2116 100755 --- a/tools/pr_ready.py +++ b/tools/pr_ready.py @@ -274,6 +274,16 @@ def parity_summary(output): return text +def mod_features(crates): + """Code mods are off by default (docs/mods.md): on wherever horizon-mods is checked, as in CI.""" + if crates is not None and "horizon-mods" not in crates: + return "" + features = ["horizon-mods/runtime", "horizon-mods/pack"] + if crates is None or "horizon-client" in crates: + features.append("horizon-client/mods") + return f" --features {','.join(features)}" + + def plan(args, base, changed, crates_of, libraries, dependencies): """The checks for these changed files, in the order they run.""" rust = any(workspace_rust(path) for path in changed) @@ -297,10 +307,10 @@ def plan(args, base, changed, crates_of, libraries, dependencies): Step("Python tests", "python3 -m unittest discover -s tests", where="here", skip=None if python else "no Python change", summary=unittest_passed), Step("rustfmt", "cargo fmt --all -- --check", skip=None if rust else no_rust), - Step("clippy", f"cargo clippy {clippy_selection} --all-targets --locked -- -D warnings", + Step("clippy", f"cargo clippy {clippy_selection}{mod_features(clippy_crates)} --all-targets --locked -- -D warnings", skip=None if rust else no_rust), Step("tests" + (": workspace" if crates is None else f": {', '.join(crates)}" if crates else ""), - f"cargo test --locked {selection} --tests", + f"cargo test --locked {selection}{mod_features(crates)} --tests", skip=test_skip, summary=tests_passed), Step("doc tests", f"cargo test --locked {doc_selection} --doc", skip=test_skip or (None if doc_crates else "no library touched"), summary=tests_passed), From 3960c09159e17ae88ecd3bfc437a6947b5a00ad9 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 14:46:56 +0200 Subject: [PATCH 030/408] tools: one copy of the helpers harnesses share, in lab.py free_port (7 copies), offline_uuid (4), varint and parse_varint (3 and 2), dbits (6), fbits (4) and settled (2) move into lab.py; every caller uses lab's. The other server harnesses keep importing free_port from test_dedicated_server_parity, which now takes lab's. Imports the moved code left unused go too. Co-Authored-By: Claude Opus 5.5 --- tools/datafix_scene_12.py | 8 +- tools/datafix_worlds.py | 67 ++++------------ tools/lab.py | 65 +++++++++++++++- tools/server_bench.py | 9 +-- tools/test_ambient_sound_parity.py | 14 ++-- tools/test_auto_jump_parity.py | 34 +++----- tools/test_camera_parity.py | 78 +++++++++---------- tools/test_dedicated_server_parity.py | 8 +- tools/test_first_person_parity.py | 16 +--- tools/test_friends.py | 8 +- tools/test_game_loop_parity.py | 32 +++----- tools/test_save_roundtrip_parity.py | 8 +- tools/test_secure_chat_parity.py | 20 ++--- tools/test_server_dimension_players_parity.py | 13 +--- tools/test_server_player_targets_parity.py | 25 +----- tools/test_sound_engine_parity.py | 12 +-- tools/upgrade_world.py | 9 +-- tools/vanilla_client.py | 11 +-- tools/vanilla_login.py | 55 +++---------- tools/vanilla_world_check.py | 14 ++-- 20 files changed, 189 insertions(+), 317 deletions(-) diff --git a/tools/datafix_scene_12.py b/tools/datafix_scene_12.py index 3d4a6366f..a73b16c28 100644 --- a/tools/datafix_scene_12.py +++ b/tools/datafix_scene_12.py @@ -23,6 +23,8 @@ import threading import time from pathlib import Path +import lab + BX, BZ, SIZE = 144, 144, 96 # south-west corner and size of the platforms (inside the spawn chunks) LAYERS = list(range(100, 245, 16)) # platform y levels: one chunk section each, the last one reaches y = 255 UUID_HI = 0x6000 @@ -1743,7 +1745,7 @@ LAST = {} def populate(server, Bot, port, protocol, name, problems): """Build the whole 1.12.2 scene, save it for good and return the (still joined) bot.""" harness = sys.modules[Bot.__module__] - Player = make_player(Bot, harness.varint, harness.parse_varint, harness.mcstring) + Player = make_player(Bot, lab.varint, lab.parse_varint, harness.mcstring) set_protocol(protocol) say = lambda cmds, **kw: batch(server, cmds, problems, **kw) if ERA < 12: @@ -1874,7 +1876,7 @@ def build_flat(h, force=False): return [] work = h.LOCAL / 'gen' / (version + '-flat') shutil.rmtree(work, ignore_errors=True) - port = h.free_port() + port = lab.free_port() class FlatServer(h.Server): def __init__(self, directory): # as Server.__init__, with a flat world @@ -1900,7 +1902,7 @@ def build_flat(h, force=False): # A flat world's spawn is found far away; make it (64, 64), and let a bot visit the scene's area so that its chunks # are loaded (they stay loaded, being within the spawn radius). batch(server, ['setworldspawn 64 4 64'], problems) - Player = make_player(h.Bot, h.varint, h.parse_varint, h.mcstring) + Player = make_player(h.Bot, lab.varint, lab.parse_varint, h.mcstring) visitor = Player(port, protocol, h.BOT) time.sleep(2) for x, z in ((24, 24), (24, 72), (24, 104), (72, 24), (72, 72), (72, 104), (104, 24), (104, 72), (104, 104), (72, 123), (-8, 63), (32, 103)): diff --git a/tools/datafix_worlds.py b/tools/datafix_worlds.py index de32e4c09..8411afbc2 100644 --- a/tools/datafix_worlds.py +++ b/tools/datafix_worlds.py @@ -23,7 +23,6 @@ import sys import threading import time import urllib.request -import uuid import zipfile import zlib from pathlib import Path @@ -31,6 +30,7 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) import datafix_scene as scene # noqa: E402 import datafix_scene_12 as scene12 # noqa: E402 +import lab # noqa: E402 ROOT = Path(__file__).resolve().parent.parent LOCAL = ROOT / '.local' / 'datafix' @@ -159,12 +159,6 @@ def install_runtime(pin, home): target.symlink_to(to) -def free_port(): - with socket.socket() as s: - s.bind(('127.0.0.1', 0)) - return s.getsockname()[1] - - class Server: def __init__(self, directory, jar, port, packs=(), java='java', props_override=None): directory.mkdir(parents=True, exist_ok=True) @@ -230,38 +224,9 @@ def failed(lines): # ------------------------------------------------------------------ minimal bot -def varint(v): - out = b'' - v &= 0xFFFFFFFF - while True: - b = v & 0x7F - v >>= 7 - out += bytes([b | (0x80 if v else 0)]) - if not v: - return out - - def mcstring(s): data = s.encode() - return varint(len(data)) + data - - -def parse_varint(data, pos): - value = shift = 0 - while True: - b = data[pos] - pos += 1 - value |= (b & 0x7F) << shift - shift += 7 - if not b & 0x80: - return pos, value - - -def offline_uuid(name): - digest = bytearray(hashlib.md5(('OfflinePlayer:' + name).encode()).digest()) - digest[6] = (digest[6] & 0x0F) | 0x30 - digest[8] = (digest[8] & 0x3F) | 0x80 - return uuid.UUID(bytes=bytes(digest)) + return lab.varint(len(data)) + data class Bot: @@ -273,21 +238,21 @@ class Bot: self.buffer = b'' self.protocol = protocol self.stop = threading.Event() - self.send(0, varint(protocol) + mcstring('127.0.0.1') + struct.pack('>H', port) + varint(2)) + self.send(0, lab.varint(protocol) + mcstring('127.0.0.1') + struct.pack('>H', port) + lab.varint(2)) if protocol <= 758: # 1.18.2: the name only self.send(0, mcstring(name)) elif protocol == 759: # 1.19: no signature data self.send(0, mcstring(name) + b'\x00') elif protocol == 760: # 1.19.2: no signature data, optional UUID - self.send(0, mcstring(name) + b'\x00' + b'\x01' + offline_uuid(name).bytes) + self.send(0, mcstring(name) + b'\x00' + b'\x01' + lab.offline_uuid(name).bytes) elif protocol <= 763: # 1.19.3 - 1.20.1: optional UUID - self.send(0, mcstring(name) + b'\x01' + offline_uuid(name).bytes) + self.send(0, mcstring(name) + b'\x01' + lab.offline_uuid(name).bytes) else: - self.send(0, mcstring(name) + offline_uuid(name).bytes) + self.send(0, mcstring(name) + lab.offline_uuid(name).bytes) while True: pid, data = self.receive() if pid == 3: - self.threshold = parse_varint(data, 0)[1] + self.threshold = lab.parse_varint(data, 0)[1] elif pid == 2: break elif pid == 0: @@ -312,15 +277,15 @@ class Bot: elif pid == disconnect: raise RuntimeError(f'disconnected during configuration: {data!r}') elif not old and self.known_packs(data): - self.send(7, varint(0)) # claim no packs: the server sends full registries + self.send(7, lab.varint(0)) # claim no packs: the server sends full registries @staticmethod def known_packs(data): try: - pos, count = parse_varint(data, 0) + pos, count = lab.parse_varint(data, 0) if count < 1: return False - pos, n = parse_varint(data, pos) + pos, n = lab.parse_varint(data, pos) return data[pos:pos + n] == b'minecraft' except IndexError: return False @@ -359,18 +324,18 @@ class Bot: return value def send(self, packet_id, payload=b''): - body = varint(packet_id) + payload + body = lab.varint(packet_id) + payload if self.threshold >= 0: - body = varint(len(body)) + zlib.compress(body) if len(body) >= self.threshold else varint(0) + body - self.sock.sendall(varint(len(body)) + body) + body = lab.varint(len(body)) + zlib.compress(body) if len(body) >= self.threshold else lab.varint(0) + body + self.sock.sendall(lab.varint(len(body)) + body) def receive(self): length = self.read_varint() body = self.read_exact(length) if self.threshold >= 0: - pos, size = parse_varint(body, 0) + pos, size = lab.parse_varint(body, 0) body = zlib.decompress(body[pos:]) if size else body[pos:] - pos, packet_id = parse_varint(body, 0) + pos, packet_id = lab.parse_varint(body, 0) return packet_id, body[pos:] @@ -428,7 +393,7 @@ def build(name, force=False): era = scene.era(data_version) work = LOCAL / 'gen' / name shutil.rmtree(work, ignore_errors=True) - port = free_port() + port = lab.free_port() server = Server(work, jar, port, scene.experiments(data_version), java(version), props) problems = [] diff --git a/tools/lab.py b/tools/lab.py index 87713276d..a62a38f59 100644 --- a/tools/lab.py +++ b/tools/lab.py @@ -1,7 +1,8 @@ #!/usr/bin/env python3 """Pinned Java Edition import/decompilation. Game files come from the user's own copy (their official launcher install and the server jar they downloaded); all -generated files stay in .local/.""" +generated files stay in .local/. Also the small helpers the harnesses share +(free ports, offline UUIDs, VarInts, float bits).""" import argparse from collections import Counter @@ -12,11 +13,13 @@ import platform from pathlib import Path, PurePosixPath import re import shutil +import socket import struct import subprocess import sys import tempfile import urllib.request +import uuid import zipfile ROOT = Path(__file__).resolve().parents[1] @@ -61,6 +64,66 @@ def digest(path, algorithm): return hashlib.file_digest(stream, algorithm).hexdigest() +def free_port(): + """A free local TCP port, for a server a harness starts.""" + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def offline_uuid(name): + """UUIDUtil.createOfflinePlayerUUID: the UUID an offline-mode server gives a player name.""" + digest = bytearray(hashlib.md5(("OfflinePlayer:" + name).encode()).digest()) + digest[6] = (digest[6] & 0x0F) | 0x30 + digest[8] = (digest[8] & 0x3F) | 0x80 + return uuid.UUID(bytes=bytes(digest)) + + +def varint(value): + """FriendlyByteBuf.writeVarInt: the int's 32 bits, 7 at a time.""" + out = b"" + value &= 0xFFFFFFFF + while True: + b = value & 0x7F + value >>= 7 + out += bytes([b | (0x80 if value else 0)]) + if not value: + return out + + +def parse_varint(data, pos): + """The VarInt at data[pos]: (the position after it, its unsigned value).""" + value = shift = 0 + while True: + b = data[pos] + pos += 1 + value |= (b & 0x7F) << shift + shift += 7 + if not b & 0x80: + return pos, value + + +def fbits(value): + """A float's IEEE 754 bits in hex, as the Java oracles print them.""" + return struct.pack(">f", value).hex() + + +def dbits(value): + """A double's IEEE 754 bits in hex, as the Java oracles print them.""" + return struct.pack(">d", value).hex() + + +def settled(lines): + """One player's lines of one step, in order, with the waypoint packets reduced to the last for each waypoint: + what the locator bar shows once the step is over. Arriving in a level, vanilla sends the same waypoint more + than once on the way there; the packet by packet order is test_locator_bar_parity's.""" + def waypoint(line): + parts = line.split(" ") + return parts[3] if len(parts) > 3 and parts[2] in ("track", "untrack", "update") else None + last = {waypoint(l): i for i, l in enumerate(lines) if waypoint(l)} + return [l for i, l in enumerate(lines) if not waypoint(l) or last[waypoint(l)] == i] + + def download(url, destination, checksum, algorithm="sha1"): """Never promote an unverified or partial download into the artifact cache.""" destination.parent.mkdir(parents=True, exist_ok=True) diff --git a/tools/server_bench.py b/tools/server_bench.py index ebd2a1a99..a9a494efd 100755 --- a/tools/server_bench.py +++ b/tools/server_bench.py @@ -45,7 +45,6 @@ from pathlib import Path import platform import re import shutil -import socket import statistics import subprocess import sys @@ -81,12 +80,6 @@ PROPERTIES = { } -def free_port(): - with socket.socket() as s: - s.bind(('127.0.0.1', 0)) - return s.getsockname()[1] - - def cpu_seconds(text): """ps's cumulative CPU time: [[DD-]HH:]MM:SS[.ss].""" days, _, rest = text.rpartition('-') @@ -282,7 +275,7 @@ def run_once(kind, bots, behaviour, args, out): directory = out / name shutil.rmtree(directory, ignore_errors=True) directory.mkdir(parents=True) - port = free_port() + port = lab.free_port() props = dict(PROPERTIES, **{'server-port': str(port), 'level-seed': str(args.seed)}) (directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items())) (directory / 'eula.txt').write_text('eula=true\n') diff --git a/tools/test_ambient_sound_parity.py b/tools/test_ambient_sound_parity.py index 8906d2d7a..85cfb20e1 100644 --- a/tools/test_ambient_sound_parity.py +++ b/tools/test_ambient_sound_parity.py @@ -17,16 +17,12 @@ playing instance and the subtitle notifications. Horizon's `Ambience` and """ import json import random -import struct try: - from . import audio_harness as h + from . import audio_harness as h, lab except ImportError: import audio_harness as h - - -def dbits(v): - return struct.pack('>d', v).hex() + import lab def settings(): @@ -54,11 +50,11 @@ class Script: self.lines.append(' '.join(map(str, parts))) def sounds(self, value): - mood = '-' if value['mood'] is None else '{},{},{},{}'.format(value['mood'][0], value['mood'][1], value['mood'][2], dbits(value['mood'][3])) - self.add('sounds', value['loop'] or '-', mood, *[f'{s},{dbits(c)}' for s, c in value['additions']]) + mood = '-' if value['mood'] is None else '{},{},{},{}'.format(value['mood'][0], value['mood'][1], value['mood'][2], lab.dbits(value['mood'][3])) + self.add('sounds', value['loop'] or '-', mood, *[f'{s},{lab.dbits(c)}' for s, c in value['additions']]) def player(self, at=(0.5, 64.0, 0.5), eye=1.62, water=0, spectator=0, removed=0, mode=0, height=1.8, columns=()): - self.add('player', *map(dbits, at), h.bits(eye), water, spectator, removed, mode, h.bits(height), + self.add('player', *map(lab.dbits, at), h.bits(eye), water, spectator, removed, mode, h.bits(height), *[f'{x},{y},{z},{d}' for x, y, z, d in columns]) def tick(self, n=1): diff --git a/tools/test_auto_jump_parity.py b/tools/test_auto_jump_parity.py index da0c16b7b..3e9da7d5a 100644 --- a/tools/test_auto_jump_parity.py +++ b/tools/test_auto_jump_parity.py @@ -8,11 +8,9 @@ overhangs approached from every angle with varied speeds, input vectors, sizes, jump boost and the canAutoJump preconditions.""" import json import math -import os from pathlib import Path import platform import random -import struct import subprocess try: @@ -23,14 +21,6 @@ except ImportError: import test_native_client as client -def fbits(v): - return struct.pack('>f', v).hex() - - -def dbits(v): - return struct.pack('>d', v).hex() - - BLOCKS = [ ('stone', {}), ('stone', {}), ('stone', {}), ('stone_slab', {'type': 'bottom'}), ('stone_slab', {'type': 'top'}), ('stone_slab', {'type': 'double'}), @@ -64,12 +54,12 @@ DIMS = [(0.6, 1.8), (0.6, 1.8), (0.6, 1.5), (0.6, 0.6), (0.3, 0.9), (1.2, 3.6), def player(rng, x, y, z, yaw): w, h = rng.choice(DIMS) - return dict(pos=[dbits(x), dbits(y), dbits(z)], ground=rng.random() < 0.9, shift=rng.random() < 0.08, - yr=fbits(yaw), xr=fbits(rng.choice([0.0, 30.0, -45.0, 90.0, rng.uniform(-90, 90)])), - speed=fbits(rng.choice([0.1, 0.13000001, 0.03, 0.0, 0.2, rng.uniform(0, 0.3)])), - move=[fbits(v) for v in rng.choice([(0.0, 1.0), (0.0, 1.0), (1.0, 0.0), (-1.0, 0.0), (0.70710677, 0.70710677), + return dict(pos=[lab.dbits(x), lab.dbits(y), lab.dbits(z)], ground=rng.random() < 0.9, shift=rng.random() < 0.08, + yr=lab.fbits(yaw), xr=lab.fbits(rng.choice([0.0, 30.0, -45.0, 90.0, rng.uniform(-90, 90)])), + speed=lab.fbits(rng.choice([0.1, 0.13000001, 0.03, 0.0, 0.2, rng.uniform(0, 0.3)])), + move=[lab.fbits(v) for v in rng.choice([(0.0, 1.0), (0.0, 1.0), (1.0, 0.0), (-1.0, 0.0), (0.70710677, 0.70710677), (0.0, -1.0), (0.0, 0.0), (0.3, 0.3)])], - width=fbits(w), height=fbits(h), boost=rng.choice([None] * 6 + [0, 1, 4, 255]), + width=lab.fbits(w), height=lab.fbits(h), boost=rng.choice([None] * 6 + [0, 1, 4, 255]), enabled=rng.random() < 0.93, time=rng.choice([0] * 12 + [1, -3, 2])) @@ -86,18 +76,18 @@ def cases(rng): x = ox + 0.5 - dx * 1.1 z = oz + 0.5 - dz * 1.1 p = player(rng, x, float(oy), z, yaw) - p.update(ground=True, shift=False, enabled=True, time=0, boost=None, move=[fbits(0.0), fbits(1.0)], - width=fbits(0.6), height=fbits(1.8), xr=fbits(0.0)) - yield dict(blocks=blocks, player=p, xa=fbits(dx * step), za=fbits(dz * step)) + p.update(ground=True, shift=False, enabled=True, time=0, boost=None, move=[lab.fbits(0.0), lab.fbits(1.0)], + width=lab.fbits(0.6), height=lab.fbits(1.8), xr=lab.fbits(0.0)) + yield dict(blocks=blocks, player=p, xa=lab.fbits(dx * step), za=lab.fbits(dz * step)) # Ceilings above the player and above the step. for ceiling in range(2, 6): for step_height in (0, 1): blocks = [[ox, oy + step_height, oz, 'minecraft:stone', {}], [ox - 1, oy + ceiling, oz, 'minecraft:stone', {}], [ox, oy + ceiling + step_height, oz, 'minecraft:stone_slab', {'type': 'top'}]] p = player(rng, ox - 0.5, float(oy), oz + 0.5, -90.0) - p.update(ground=True, shift=False, enabled=True, time=0, boost=None, move=[fbits(0.0), fbits(1.0)], - width=fbits(0.6), height=fbits(1.8)) - yield dict(blocks=blocks, player=p, xa=fbits(0.2), za=fbits(0.0)) + p.update(ground=True, shift=False, enabled=True, time=0, boost=None, move=[lab.fbits(0.0), lab.fbits(1.0)], + width=lab.fbits(0.6), height=lab.fbits(1.8)) + yield dict(blocks=blocks, player=p, xa=lab.fbits(0.2), za=lab.fbits(0.0)) for _ in range(9000): blocks = placed(rng, rng.choice([1, 2, 4, 8, 16, 30])) x = ox + rng.uniform(-2, 3) @@ -108,7 +98,7 @@ def cases(rng): move = rng.choice([0.0, 0.0, 0.01, 0.1, 0.215, 0.3, rng.uniform(0, 0.4)]) angle = rng.uniform(0, 6.283) - yield dict(blocks=blocks, player=p, xa=fbits(math.cos(angle) * move), za=fbits(math.sin(angle) * move)) + yield dict(blocks=blocks, player=p, xa=lab.fbits(math.cos(angle) * move), za=lab.fbits(math.sin(angle) * move)) def main(): diff --git a/tools/test_camera_parity.py b/tools/test_camera_parity.py index 3cd0e403d..bde9ea897 100644 --- a/tools/test_camera_parity.py +++ b/tools/test_camera_parity.py @@ -20,14 +20,6 @@ except ImportError: import lab, oracle_harness as harness -def fbits(v): - return struct.pack('>f', v).hex() - - -def dbits(v): - return struct.pack('>d', v).hex() - - def f32(v): return struct.unpack('>f', struct.pack('>f', v))[0] @@ -39,8 +31,8 @@ TICKS = [0, 1, 5, 10, 19, 20, 21, 72000, -5, 3] def fov_fields(rng): use = rng.choice([None, None, ['bow', rng.choice(TICKS)], ['spyglass', rng.choice(TICKS)], ['other', rng.choice(TICKS)]]) - return dict(flying=rng.random() < 0.3, ws=fbits(rng.choice(WALK + [rng.uniform(-0.3, 0.3)])), - speed=dbits(rng.choice(SPEED + [rng.uniform(0, 2)])), use=use) + return dict(flying=rng.random() < 0.3, ws=lab.fbits(rng.choice(WALK + [rng.uniform(-0.3, 0.3)])), + speed=lab.dbits(rng.choice(SPEED + [rng.uniform(0, 2)])), use=use) def fov_cases(rng): @@ -50,9 +42,9 @@ def fov_cases(rng): for use in [None, ['bow', 0], ['bow', 7], ['bow', 20], ['bow', 40], ['spyglass', 2], ['other', 5]]: for fp in (False, True): for scale in (0.0, 0.5, 1.0): - yield dict(t='fov', flying=flying, ws=fbits(ws), speed=dbits(speed), use=use, fp=fp, scale=fbits(scale)) + yield dict(t='fov', flying=flying, ws=lab.fbits(ws), speed=lab.dbits(speed), use=use, fp=fp, scale=lab.fbits(scale)) for _ in range(3000): - yield dict(t='fov', **fov_fields(rng), fp=rng.random() < 0.6, scale=fbits(rng.choice([0.0, 1.0, rng.random()]))) + yield dict(t='fov', **fov_fields(rng), fp=rng.random() < 0.6, scale=lab.fbits(rng.choice([0.0, 1.0, rng.random()]))) FULL = [[0, 0, 0, 1, 1, 1]] @@ -65,7 +57,7 @@ def world(rng, center): cx, cy, cz = center for _ in range(rng.choice([0, 3, 10, 40, 120])): p = (cx + rng.randint(-6, 6), cy + rng.randint(-3, 5), cz + rng.randint(-6, 6)) - cells[f'{p[0]} {p[1]} {p[2]}'] = [[dbits(v) for v in box] for box in rng.choice(SHAPES)] + cells[f'{p[0]} {p[1]} {p[2]}'] = [[lab.dbits(v) for v in box] for box in rng.choice(SHAPES)] return cells @@ -81,22 +73,22 @@ def entity_state(rng, center): prev = [p - rng.choice([0, 0, 0.1, 0.3, 1.0, rng.uniform(-1, 1)]) for p in pos] kind = 'player' if rng.random() < 0.85 else 'marker' xr, yr = angle(rng), angle(rng) - s = dict(kind=kind, pos=[dbits(v) for v in pos], prev=[dbits(v) for v in prev], xr=fbits(xr), yr=fbits(yr), - xro=fbits(rng.choice([xr, xr - 5, angle(rng)])), yro=fbits(rng.choice([yr, yr + 10, angle(rng)])), - eye=fbits(rng.choice([1.62, 1.27, 0.4, 0.2, 0.81, 3.24, rng.uniform(0, 4)]))) + s = dict(kind=kind, pos=[lab.dbits(v) for v in pos], prev=[lab.dbits(v) for v in prev], xr=lab.fbits(xr), yr=lab.fbits(yr), + xro=lab.fbits(rng.choice([xr, xr - 5, angle(rng)])), yro=lab.fbits(rng.choice([yr, yr + 10, angle(rng)])), + eye=lab.fbits(rng.choice([1.62, 1.27, 0.4, 0.2, 0.81, 3.24, rng.uniform(0, 4)]))) s.update(fov_fields(rng)) - s.update(scale_attr=dbits(rng.choice([1.0, 1.0, 0.5, 2.0, 0.0625, 16.0, rng.uniform(0.0625, 3)])), - dist=dbits(rng.choice([4.0, 4.0, 0.0, 1.0, 10.0, 32.0, rng.uniform(0, 32)])), + s.update(scale_attr=lab.dbits(rng.choice([1.0, 1.0, 0.5, 2.0, 0.0625, 16.0, rng.uniform(0.0625, 3)])), + dist=lab.dbits(rng.choice([4.0, 4.0, 0.0, 1.0, 10.0, 32.0, rng.uniform(0, 32)])), sleeping=rng.choice([None] * 6 + [[None], [0], [1], [2], [3]]), dead=rng.choice([None] * 6 + [0, 1, 5, 19, 20, 25]), - mount=rng.choice([None] * 4 + [[dbits(rng.choice([1.0, 2.0, 0.5])), dbits(rng.choice([4.0, 8.0, 1.0]))]])) + mount=rng.choice([None] * 4 + [[lab.dbits(rng.choice([1.0, 2.0, 0.5])), lab.dbits(rng.choice([4.0, 8.0, 1.0]))]])) return s def window(rng): """Window size and Camera.depthFar for the world and hand projections.""" w, h = rng.choice([(1600, 1000), (854, 480), (1920, 1080), (800, 1200), (1, 1), (rng.randint(1, 4000), rng.randint(1, 3000))]) - return [fbits(w), fbits(h), fbits(rng.choice([768.0, 128.0, 2048.0, 4096.0, rng.uniform(32, 4096)]))] + return [lab.fbits(w), lab.fbits(h), lab.fbits(rng.choice([768.0, 128.0, 2048.0, 4096.0, rng.uniform(32, 4096)]))] def camera_cases(rng): @@ -113,11 +105,11 @@ def camera_cases(rng): ops.append(['tick']) elif kind == 'frame': pt = rng.choice([0.0, 1.0, 0.5, 0.25, 0.999, rng.random()]) - ops.append(['frame', fbits(pt), rng.choice([0, 0, 0, 1, 2, 3]), rng.random() < 0.05] + window(rng)) + ops.append(['frame', lab.fbits(pt), rng.choice([0, 0, 0, 1, 2, 3]), rng.random() < 0.05] + window(rng)) else: ops.append(['type', rng.randrange(3)]) yield dict(t='camera', fov=rng.choice([70, 30, 110, 90, rng.randint(30, 110)]), - effect=dbits(rng.choice([1.0, 0.0, 0.5, rng.random()])), type=rng.choice([0, 1, 1, 2]), + effect=lab.dbits(rng.choice([1.0, 0.0, 0.5, rng.random()])), type=rng.choice([0, 1, 1, 2]), cells=world(rng, center), ops=ops) # The hand's projection at FOV 30, 70 and 110 while walking, sprinting, under # speed, drawing a bow, dying and in fluids: GameRenderer.render3dHud uses @@ -127,13 +119,13 @@ def camera_cases(rng): for use in (None, ['bow', 10]): for dead in (None, 5): for fluid in (0, 1, 2): - s = dict(kind='player', pos=[dbits(0.5), dbits(64.0), dbits(0.5)], prev=[dbits(0.5), dbits(64.0), dbits(0.5)], - xr=fbits(0.0), yr=fbits(0.0), xro=fbits(0.0), yro=fbits(0.0), eye=fbits(1.62), flying=False, - ws=fbits(0.1), speed=dbits(speed), use=use, scale_attr=dbits(1.0), dist=dbits(4.0), + s = dict(kind='player', pos=[lab.dbits(0.5), lab.dbits(64.0), lab.dbits(0.5)], prev=[lab.dbits(0.5), lab.dbits(64.0), lab.dbits(0.5)], + xr=lab.fbits(0.0), yr=lab.fbits(0.0), xro=lab.fbits(0.0), yro=lab.fbits(0.0), eye=lab.fbits(1.62), flying=False, + ws=lab.fbits(0.1), speed=lab.dbits(speed), use=use, scale_attr=lab.dbits(1.0), dist=lab.dbits(4.0), sleeping=None, dead=dead, mount=None) - ops = [['entity', s]] + [['tick']] * 8 + [['frame', fbits(pt), fluid, False, fbits(1600.0), fbits(1000.0), fbits(768.0)] + ops = [['entity', s]] + [['tick']] * 8 + [['frame', lab.fbits(pt), fluid, False, lab.fbits(1600.0), lab.fbits(1000.0), lab.fbits(768.0)] for pt in (0.0, 0.5, 1.0)] - yield dict(t='camera', fov=fov, effect=dbits(1.0), type=0, cells={}, ops=ops) + yield dict(t='camera', fov=fov, effect=lab.dbits(1.0), type=0, cells={}, ops=ops) # A walled-in third-person camera stepping through every distance bound. for dist in [0.0, 0.5, 1.0, 2.0, 4.0, 8.0, 32.0]: for wall in range(0, 6): @@ -141,28 +133,28 @@ def camera_cases(rng): cells = {} for dx in range(-6, 7): for dy in range(62, 68): - cells[f'{dx} {dy} {-wall - 1}'] = [[dbits(v) for v in box] for box in FULL] - cells[f'{dx} {dy} {wall + 1}'] = [[dbits(v) for v in box] for box in FULL] - s = dict(kind='player', pos=[dbits(0.5), dbits(64.0), dbits(0.5)], prev=[dbits(0.5), dbits(64.0), dbits(0.5)], - xr=fbits(15.0), yr=fbits(yaw), xro=fbits(15.0), yro=fbits(yaw), eye=fbits(1.62), flying=False, - ws=fbits(0.1), speed=dbits(f32(0.1)), use=None, scale_attr=dbits(1.0), dist=dbits(dist), + cells[f'{dx} {dy} {-wall - 1}'] = [[lab.dbits(v) for v in box] for box in FULL] + cells[f'{dx} {dy} {wall + 1}'] = [[lab.dbits(v) for v in box] for box in FULL] + s = dict(kind='player', pos=[lab.dbits(0.5), lab.dbits(64.0), lab.dbits(0.5)], prev=[lab.dbits(0.5), lab.dbits(64.0), lab.dbits(0.5)], + xr=lab.fbits(15.0), yr=lab.fbits(yaw), xro=lab.fbits(15.0), yro=lab.fbits(yaw), eye=lab.fbits(1.62), flying=False, + ws=lab.fbits(0.1), speed=lab.dbits(f32(0.1)), use=None, scale_attr=lab.dbits(1.0), dist=lab.dbits(dist), sleeping=None, dead=None, mount=None) - ops = [['entity', s]] + [['tick']] * 6 + [['frame', fbits(pt), 0, False] + window(rng) for pt in (0.0, 0.5, 1.0)] - yield dict(t='camera', fov=70, effect=dbits(1.0), type=1 + (wall % 2), cells=cells, ops=ops) + ops = [['entity', s]] + [['tick']] * 6 + [['frame', lab.fbits(pt), 0, False] + window(rng) for pt in (0.0, 0.5, 1.0)] + yield dict(t='camera', fov=70, effect=lab.dbits(1.0), type=1 + (wall % 2), cells=cells, ops=ops) def bob_cases(rng): for n in range(6000): living = None if rng.random() < 0.8: - living = dict(hurt=fbits(rng.choice([-1.0, -0.5, 0.0, 10.0, 9.5, 5.25, 1.0, rng.uniform(-2, 11)])), - duration=rng.choice([10, 10, 0, 5, 20]), dir=fbits(rng.choice([0.0, 90.0, -45.0, 180.0, rng.uniform(-360, 360)])), - death=rng.choice([None, None, None, fbits(rng.choice([0.0, 0.5, 19.5, 20.0, 25.0, rng.uniform(0, 30)]))])) + living = dict(hurt=lab.fbits(rng.choice([-1.0, -0.5, 0.0, 10.0, 9.5, 5.25, 1.0, rng.uniform(-2, 11)])), + duration=rng.choice([10, 10, 0, 5, 20]), dir=lab.fbits(rng.choice([0.0, 90.0, -45.0, 180.0, rng.uniform(-360, 360)])), + death=rng.choice([None, None, None, lab.fbits(rng.choice([0.0, 0.5, 19.5, 20.0, 25.0, rng.uniform(0, 30)]))])) player = None if rng.random() < 0.8: - player = [fbits(rng.choice([0.0, -0.3, -1.7, -100.25, rng.uniform(-1000, 0)])), - fbits(rng.choice([0.0, 0.1, 0.05, 0.0999, rng.uniform(0, 0.1)]))] - yield dict(t='bob', living=living, player=player, tilt=dbits(rng.choice([1.0, 0.0, 0.5, rng.random()])), + player = [lab.fbits(rng.choice([0.0, -0.3, -1.7, -100.25, rng.uniform(-1000, 0)])), + lab.fbits(rng.choice([0.0, 0.1, 0.05, 0.0999, rng.uniform(0, 0.1)]))] + yield dict(t='bob', living=living, player=player, tilt=lab.dbits(rng.choice([1.0, 0.0, 0.5, rng.random()])), view=rng.random() < 0.8) @@ -174,12 +166,12 @@ def avatar_cases(rng): if kind == 'tick': ops.append(['tick']) elif kind == 'move': - ops.append(['move', fbits(rng.choice([0.0, 0.2158, -0.1, rng.uniform(-1, 1)])), fbits(rng.choice([0.0, 0.2806, rng.uniform(-1, 1)]))]) + ops.append(['move', lab.fbits(rng.choice([0.0, 0.2158, -0.1, rng.uniform(-1, 1)])), lab.fbits(rng.choice([0.0, 0.2806, rng.uniform(-1, 1)]))]) elif kind == 'bob': v = [rng.choice([0.0, 0.05, -0.2, rng.uniform(-0.5, 0.5)]), rng.uniform(-1, 1), rng.choice([0.0, 0.08, rng.uniform(-0.5, 0.5)])] - ops.append(['bob', rng.random() < 0.7, rng.random() < 0.1, rng.random() < 0.1, [dbits(x) for x in v]]) + ops.append(['bob', rng.random() < 0.7, rng.random() < 0.1, rng.random() < 0.1, [lab.dbits(x) for x in v]]) elif kind == 'frame': - ops.append(['frame', fbits(rng.choice([0.0, 1.0, 0.5, rng.random()]))]) + ops.append(['frame', lab.fbits(rng.choice([0.0, 1.0, 0.5, rng.random()]))]) else: ops.append(['reset']) yield dict(t='avatar', ops=ops) diff --git a/tools/test_dedicated_server_parity.py b/tools/test_dedicated_server_parity.py index 22677bf07..07d61f3d5 100644 --- a/tools/test_dedicated_server_parity.py +++ b/tools/test_dedicated_server_parity.py @@ -68,10 +68,12 @@ import zlib try: from . import lab, oracle_harness as oh, test_rust_parity as base + from .lab import free_port # the other server harnesses import it from here except ImportError: import lab import oracle_harness as oh import test_rust_parity as base + from lab import free_port NAME = 'dedicated-server-parity' SEED = 12345 @@ -89,12 +91,6 @@ PROPERTIES = { } -def free_port(): - with socket.socket() as s: - s.bind(('127.0.0.1', 0)) - return s.getsockname()[1] - - def icon_png(): """A 64x64 RGBA PNG (server-icon.png).""" rows = b''.join(b'\0' + b''.join(bytes((x * 4, y * 4, (x ^ y) * 4, 255)) for x in range(64)) for y in range(64)) diff --git a/tools/test_first_person_parity.py b/tools/test_first_person_parity.py index 476d2cc52..fcb1206ec 100644 --- a/tools/test_first_person_parity.py +++ b/tools/test_first_person_parity.py @@ -18,14 +18,6 @@ except ImportError: import lab, oracle_harness as harness -def fbits(v): - return struct.pack('>f', v).hex() - - -def dbits(v): - return struct.pack('>d', v).hex() - - def f32(v): return struct.unpack('>f', struct.pack('>f', v))[0] @@ -52,15 +44,15 @@ def step(hit=('miss',), ac=0, uc=0, ad=False, ud=False, busy=False, using=False, """rot: the player's (xRot, yRot) from this step on (LocalPlayer.applyInput's hand sway).""" return dict(hit=list(hit), ac=ac, uc=uc, ad=ad, ud=ud, busy=busy, using=using, uses=uses or dict(entity='pass', block='pass', item='pass'), shrink=shrink, set=set, - rot=None if rot is None else [fbits(rot[0]), fbits(rot[1])]) + rot=None if rot is None else [lab.fbits(rot[0]), lab.fbits(rot[1])]) def case(steps, creative=False, main=None, off=None, blocks=None, haste=None, fatigue=None): return dict(creative=creative, main=main, off=off, haste=haste, fatigue=fatigue, blocks=[[*p, b] for p, b in (blocks or {}).items()], steps=steps, - rust=dict(blocks={k: [fbits(v[0]), v[1]] for k, v in BLOCKS.items()}, - tools={k: [fbits(v[0]), v[1]] for k, v in TOOLS.items()}, - attack_speed={k: dbits(v) for k, v in SPEEDS.items()})) + rust=dict(blocks={k: [lab.fbits(v[0]), v[1]] for k, v in BLOCKS.items()}, + tools={k: [lab.fbits(v[0]), v[1]] for k, v in TOOLS.items()}, + attack_speed={k: lab.dbits(v) for k, v in SPEEDS.items()})) def block_hit(pos, face=1): diff --git a/tools/test_friends.py b/tools/test_friends.py index 3daeb28e7..8fa1a4fee 100644 --- a/tools/test_friends.py +++ b/tools/test_friends.py @@ -72,12 +72,6 @@ def wait_for(endpoint, line, predicate, timeout=60, what=None): raise AssertionError(f'timed out waiting for {what or line}: {last}') -def free_port(): - with socket.socket() as s: - s.bind(('127.0.0.1', 0)) - return s.getsockname()[1] - - def health(relay_url): with urllib.request.urlopen(f'http://{relay_url}/health', timeout=5) as r: return json.loads(r.read()) @@ -204,7 +198,7 @@ def leave(host, guest, name): def start_relay(args, work): """A relay on a free local port, as anyone would run their own.""" - port = free_port() + port = lab.free_port() url = f'127.0.0.1:{port}' log = (work / 'relay.log').open('w+') process = subprocess.Popen([str(args.relay.resolve())], env=dict(os.environ, PORT=str(port)), diff --git a/tools/test_game_loop_parity.py b/tools/test_game_loop_parity.py index 101b3f238..f5f5e94a3 100644 --- a/tools/test_game_loop_parity.py +++ b/tools/test_game_loop_parity.py @@ -6,9 +6,7 @@ and absolute motion, sensitivity curve, cinematic smoothing, inversion, scroll accumulation and discrete scrolling), Entity.turn and ToggleKeyMapping, all driven with identical synthetic input and time sequences.""" import json -import math import random -import struct try: from . import lab, oracle_harness as harness @@ -16,14 +14,6 @@ except ImportError: import lab, oracle_harness as harness -def fbits(v): - return struct.pack('>f', v).hex() - - -def dbits(v): - return struct.pack('>d', v).hex() - - def timer_cases(rng): for n in range(700): tps = rng.choice([20.0, 20.0, 10.0, 60.0, 1.0, 144.0]) @@ -38,12 +28,12 @@ def timer_cases(rng): now -= rng.randrange(0, 30) if kind == 'adv': mspt = rng.choice([None, None, None, 50.0, 25.0, 100.0, 500.0, 1000.0, 0.5, 5.0, 0.1]) - ops.append(['adv', now, None if mspt is None else fbits(mspt)]) + ops.append(['adv', now, None if mspt is None else lab.fbits(mspt)]) elif kind == 'real': ops.append(['real', now]) else: ops.append([kind, rng.random() < 0.5]) - yield dict(t='timer', tps=fbits(tps), start=start, ops=ops) + yield dict(t='timer', tps=lab.fbits(tps), start=start, ops=ops) def rate_cases(rng): @@ -55,7 +45,7 @@ def rate_cases(rng): kind = rng.choice(['rate', 'freeze', 'step', 'stopstep', 'sprint', 'check', 'check', 'check', 'end', 'stopsprint', 'tick', 'tick', 'tick']) if kind == 'rate': - ops.append(['rate', fbits(rng.choice(rates))]) + ops.append(['rate', lab.fbits(rng.choice(rates))]) elif kind == 'freeze': ops.append(['freeze', rng.random() < 0.5]) elif kind == 'step': @@ -78,7 +68,7 @@ def scale_cases(rng): for uni in (False, True): sw, sh = rng.choice([(w, h), (max(w // 2, 1), max(h // 2, 1)), (w + 1, h + 3)]) yield dict(t='scale', w=w, h=h, max=maxs, uni=uni, sw=sw, sh=sh, - x=dbits(rng.uniform(0, w)), y=dbits(rng.uniform(0, h))) + x=lab.dbits(rng.uniform(0, w)), y=lab.dbits(rng.uniform(0, h))) def limit_cases(rng): @@ -103,13 +93,13 @@ def mouse_cases(rng): if kind == 'move': x, y = rng.uniform(0, 1920), rng.uniform(0, 1080) big = rng.choice([1, 1, 1, 50, 5000]) - ops.append(['move', dbits(x), dbits(y), dbits(rng.uniform(-30, 30) * big), dbits(rng.uniform(-30, 30) * big)]) + ops.append(['move', lab.dbits(x), lab.dbits(y), lab.dbits(rng.uniform(-30, 30) * big), lab.dbits(rng.uniform(-30, 30) * big)]) elif kind == 'frame': time += rng.choice([0.0, 0.001, 0.0069, 0.016, 0.0167, 0.05, 0.5, 2.0]) - ops.append(['frame', dbits(time)]) + ops.append(['frame', lab.dbits(time)]) else: ops.append(['ignore']) - yield dict(t='mouse', sens=dbits(sens), smooth=rng.random() < 0.4, scoping=rng.random() < 0.3, + yield dict(t='mouse', sens=lab.dbits(sens), smooth=rng.random() < 0.4, scoping=rng.random() < 0.3, ix=rng.random() < 0.3, iy=rng.random() < 0.3, grabbed=rng.random() < 0.85, active=rng.random() < 0.9, ops=ops) @@ -119,14 +109,14 @@ def scroll_cases(rng): for _ in range(rng.randrange(1, 40)): x = rng.choice([0.0, 0.0, 0.0, 1.0, -1.0, 0.25, -0.25, 0.4, 2.0, 5.5, -7.0, rng.uniform(-3, 3)]) y = rng.choice([0.0, 1.0, -1.0, 1.0, -1.0, 0.1, -0.3, 0.5, -0.5, 2.0, -3.0, 120.0, rng.uniform(-3, 3)]) - ops.append([dbits(x), dbits(y)]) - case = dict(t='scroll', discrete=rng.random() < 0.4, sens=dbits(rng.choice([1.0, 0.01, 10.0, 0.5, 2.0, 3.1622776601683795])), + ops.append([lab.dbits(x), lab.dbits(y)]) + case = dict(t='scroll', discrete=rng.random() < 0.4, sens=lab.dbits(rng.choice([1.0, 0.01, 10.0, 0.5, 2.0, 3.1622776601683795])), slot=rng.randrange(9), ops=ops) yield case yield dict(case, spectator=True) # Bounds, recovery from each bound, fractional accumulation, and horizontal-only input. - yield dict(t='scroll', discrete=False, sens=dbits(1.0), slot=4, spectator=True, - ops=[[dbits(x), dbits(y)] for x, y in + yield dict(t='scroll', discrete=False, sens=lab.dbits(1.0), slot=4, spectator=True, + ops=[[lab.dbits(x), lab.dbits(y)] for x, y in [(0, 100), (0, -1), (0, -100), (0, 1), (0, .4), (0, .7), (0, -.4), (0, -.7), (5, 0), (-5, 0)]]) diff --git a/tools/test_save_roundtrip_parity.py b/tools/test_save_roundtrip_parity.py index 72bea8845..bd8b07a29 100644 --- a/tools/test_save_roundtrip_parity.py +++ b/tools/test_save_roundtrip_parity.py @@ -109,15 +109,9 @@ BENIGN = re.compile(r'(Unpacking |OFFLINE/INSECURE|online-mode|authenticate user # ---------------------------------------------------------------- vanilla server -def free_port(): - with socket.socket() as s: - s.bind(('127.0.0.1', 0)) - return s.getsockname()[1] - - class Vanilla: def __init__(self, directory, port=None, world='world', extra=None): - port = port or free_port() + port = port or lab.free_port() directory.mkdir(parents=True, exist_ok=True) (directory / 'eula.txt').write_text('eula=true\n') props = { diff --git a/tools/test_secure_chat_parity.py b/tools/test_secure_chat_parity.py index ed408efa3..c6c76a892 100644 --- a/tools/test_secure_chat_parity.py +++ b/tools/test_secure_chat_parity.py @@ -41,12 +41,12 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer try: from . import lab, oracle_harness as oh, test_rust_parity as base - from .test_dedicated_server_parity import Server, free_port + from .test_dedicated_server_parity import Server except ImportError: import lab import oracle_harness as oh import test_rust_parity as base - from test_dedicated_server_parity import Server, free_port + from test_dedicated_server_parity import Server NAME = 'secure-chat-parity' SCENARIOS = { @@ -153,20 +153,10 @@ def dashed(u): return f'{u[:8]}-{u[8:12]}-{u[12:16]}-{u[16:20]}-{u[20:]}' -def varint(n): - out = b'' - while True: - b = n & 0x7F - n >>= 7 - out += bytes([b | (0x80 if n else 0)]) - if not n: - return out - - def status(port): """The status response's JSON (ServerStatus).""" def packet(body): - return varint(len(body)) + body + return lab.varint(len(body)) + body def read_varint(s): value = 0 @@ -177,7 +167,7 @@ def status(port): return value with socket.create_connection(('127.0.0.1', port), timeout=10) as s: host = b'127.0.0.1' - s.sendall(packet(b'\x00' + varint(777) + varint(len(host)) + host + port.to_bytes(2, 'big') + b'\x01')) + s.sendall(packet(b'\x00' + lab.varint(777) + lab.varint(len(host)) + host + port.to_bytes(2, 'big') + b'\x01')) s.sendall(packet(b'\x00')) length = read_varint(s) data = b'' @@ -212,7 +202,7 @@ def chat_lines(lines): def run_side(label, scenario, command, directory, client): - port = free_port() + port = lab.free_port() shutil.rmtree(directory, ignore_errors=True) directory.mkdir(parents=True) props = dict(PROPERTIES, **SCENARIOS[scenario], **{'server-port': str(port)}) diff --git a/tools/test_server_dimension_players_parity.py b/tools/test_server_dimension_players_parity.py index 8453d14af..b1efc4378 100644 --- a/tools/test_server_dimension_players_parity.py +++ b/tools/test_server_dimension_players_parity.py @@ -96,17 +96,6 @@ def run_side(label, server_command, client_command, build, world): SHOWN = ('add', 'remove', 'respawn', 'track', 'untrack', 'update') -def settled(lines): - """One player's lines of one step, in order, with the waypoint packets reduced to the last for each waypoint: - what the locator bar shows once the step is over. Arriving in a level, vanilla sends the same waypoint more - than once on the way there; the packet by packet order is test_locator_bar_parity's.""" - def waypoint(line): - parts = line.split(' ') - return parts[3] if len(parts) > 3 and parts[2] in ('track', 'untrack', 'update') else None - last = {waypoint(l): i for i, l in enumerate(lines) if waypoint(l)} - return [l for i, l in enumerate(lines) if not waypoint(l) or last[waypoint(l)] == i] - - def shown(lines): """Each player's adds, removes, respawns and waypoints (as the step leaves them), step by step; sorted within a step (the packets of one step may leave in another order within the tick).""" @@ -115,7 +104,7 @@ def shown(lines): parts = line.split(' ', 2) if len(parts) == 3 and parts[2].split(' ')[0] in SHOWN: steps.setdefault((parts[0], parts[1]), []).append(line) - return [l for key in steps for l in sorted(settled(steps[key]))] + return [l for key in steps for l in sorted(lab.settled(steps[key]))] def main(): diff --git a/tools/test_server_player_targets_parity.py b/tools/test_server_player_targets_parity.py index 71416223b..cad8782cc 100644 --- a/tools/test_server_player_targets_parity.py +++ b/tools/test_server_player_targets_parity.py @@ -15,7 +15,6 @@ in sorted order (the packets of one step may leave in another order within the t waypoints as each step leaves them (one manager per level: a player in another level is untracked). What a death does besides its messages is left to its own harness. """ -import hashlib import os from pathlib import Path import platform @@ -23,7 +22,6 @@ import shutil import subprocess import sys import time -import uuid as uuidlib try: from . import lab, test_rust_parity as base @@ -39,20 +37,12 @@ NAME = 'server-player-targets-parity' NETHER, OVERWORLD = 'minecraft:the_nether', 'minecraft:overworld' -def offline_uuid(name): - """UUIDUtil.createOfflinePlayerUUID.""" - digest = bytearray(hashlib.md5(f'OfflinePlayer:{name}'.encode()).digest()) - digest[6] = (digest[6] & 0x0F) | 0x30 - digest[8] = (digest[8] & 0x3F) | 0x80 - return str(uuidlib.UUID(bytes=bytes(digest))) - - # (label, what the console does, what the players do). SCRIPT = [ ('console-give', ['give Bob minecraft:diamond 3'], []), ('console-give-all', ['give @a minecraft:apple'], []), ('alice-give-bob', [], ['cmd Alice give Bob minecraft:stick 2']), - ('console-give-uuid', [f'give {offline_uuid("Bob")} minecraft:iron_ingot'], []), + ('console-give-uuid', [f'give {lab.offline_uuid("Bob")} minecraft:iron_ingot'], []), ('console-give-nearest', ['give @p minecraft:emerald'], []), ('alice-give-random', [], ['cmd Alice give @r[name=Bob] minecraft:gold_ingot']), ('console-gamemode', ['gamemode survival Bob'], []), @@ -83,17 +73,6 @@ DEATH_STEP = 'step=console-kill' STEP_SECONDS = 2.5 -def settled(lines): - """One player's lines of one step, in order, with the waypoint packets reduced to the last for each waypoint: - what the locator bar shows once the step is over. Arriving in a level, vanilla sends the same waypoint more - than once on the way there; the packet by packet order is test_locator_bar_parity's.""" - def waypoint(line): - parts = line.split(' ') - return parts[3] if len(parts) > 3 and parts[2] in ('track', 'untrack', 'update') else None - last = {waypoint(l): i for i, l in enumerate(lines) if waypoint(l)} - return [l for i, l in enumerate(lines) if not waypoint(l) or last[waypoint(l)] == i] - - def run_side(label, server_command, client_command, build, world): directory = build / label port = server_dir(directory, world) @@ -151,7 +130,7 @@ def run_side(label, server_command, client_command, build, world): steps.setdefault((who, step), []).append(line) order = {f'step={s}': i for i, (s, _, _) in enumerate(SCRIPT)} keys = sorted(steps, key=lambda k: (k[0], order.get(k[1], -1))) - return [l for k in keys for l in sorted(settled(steps[k]))], errors + return [l for k in keys for l in sorted(lab.settled(steps[k]))], errors def main(): diff --git a/tools/test_sound_engine_parity.py b/tools/test_sound_engine_parity.py index 36095542c..8eb02a7fe 100644 --- a/tools/test_sound_engine_parity.py +++ b/tools/test_sound_engine_parity.py @@ -18,14 +18,10 @@ import math import random try: - from . import audio_harness as h + from . import audio_harness as h, lab except ImportError: import audio_harness as h - - -def dbits(v): - import struct - return struct.pack('>d', v).hex() + import lab class Script: @@ -37,11 +33,11 @@ class Script: self.lines.append(' '.join(map(str, parts))) def play(self, name, event, source=4, volume=1.0, pitch=1.0, at=(0.0, 0.0, 0.0), looping=0, delay=0, linear=True, relative=0, seed=0, kind='simple'): - self.add('play', name, kind, event, source, h.bits(volume), h.bits(pitch), *map(dbits, at), looping, delay, + self.add('play', name, kind, event, source, h.bits(volume), h.bits(pitch), *map(lab.dbits, at), looping, delay, 'linear' if linear else 'none', relative, seed) def cart(self, name, at, delta, removed=0): - self.add('cart', name, *map(dbits, at), *map(dbits, delta), removed) + self.add('cart', name, *map(lab.dbits, at), *map(lab.dbits, delta), removed) def tick(self, n=1, paused=0): for _ in range(n): diff --git a/tools/upgrade_world.py b/tools/upgrade_world.py index 9db5e4517..5f42988f1 100755 --- a/tools/upgrade_world.py +++ b/tools/upgrade_world.py @@ -9,7 +9,6 @@ level.dat, player and data/*.dat files) is applied exactly. The original is kept upgrade_world.py SOURCE_WORLD DEST_WORLD """ import shutil -import socket import subprocess import sys import tempfile @@ -24,12 +23,6 @@ ROOT = Path(__file__).resolve().parent.parent SERVER = lab.GAME / 'jars' / 'server.jar' -def free_port(): - with socket.socket() as s: - s.bind(('127.0.0.1', 0)) - return s.getsockname()[1] - - def main(): if len(sys.argv) != 3: sys.exit(__doc__) @@ -42,7 +35,7 @@ def main(): scratch = Path(scratch) (scratch / 'eula.txt').write_text('eula=true\n') (scratch / 'server.properties').write_text( - f'level-name=world\nonline-mode=false\nserver-port={free_port()}\n') + f'level-name=world\nonline-mode=false\nserver-port={lab.free_port()}\n') shutil.copytree(source, scratch / 'world') # The server upgrades at startup, then keeps running as a normal server: stop it # once it reports "Done". diff --git a/tools/vanilla_client.py b/tools/vanilla_client.py index 64eb82691..2cdfeec21 100644 --- a/tools/vanilla_client.py +++ b/tools/vanilla_client.py @@ -14,12 +14,10 @@ that skips the first-run screens, keeps the game running unfocused and renders few chunks, so a harness can drive it with vscreen keys. """ import argparse -import hashlib import json import os import subprocess import sys -import uuid import zipfile from pathlib import Path @@ -56,13 +54,6 @@ if sys.platform == "darwin": OPTIONS["enableVsync"] = "false" -def offline_uuid(name): - digest = bytearray(hashlib.md5(("OfflinePlayer:" + name).encode()).digest()) - digest[6] = (digest[6] & 0x0F) | 0x30 - digest[8] = (digest[8] & 0x3F) | 0x80 - return uuid.UUID(bytes=bytes(digest)) - - def host_library(path): name = Path(path).name if "natives-" in name: @@ -127,7 +118,7 @@ def command(args): f"-Djava.library.path={natives}", f"-Dorg.lwjgl.system.SharedLibraryExtractPath={natives}", f"-Dio.netty.native.workdir={natives}", "-cp", os.pathsep.join(map(str, jars)), "net.minecraft.client.main.Main", - "--username", args.name, "--uuid", offline_uuid(args.name).hex, + "--username", args.name, "--uuid", lab.offline_uuid(args.name).hex, "--accessToken", "0", "--offlineDeveloperMode", "--version", lab.VERSION, "--gameDir", str(args.game_dir), "--assetsDir", str(assets), "--assetIndex", json.loads((GAME / "manifest.json").read_text())["assetIndex"]["id"], diff --git a/tools/vanilla_login.py b/tools/vanilla_login.py index fa2664c9d..ecc9715b4 100644 --- a/tools/vanilla_login.py +++ b/tools/vanilla_login.py @@ -11,12 +11,10 @@ its log reports the position it read, and console commands such as `data get entity NAME` can inspect the loaded player meanwhile. """ import argparse -import hashlib import socket import struct import sys import time -import uuid import zlib try: @@ -25,27 +23,9 @@ except ImportError: import lab -def offline_uuid(name): - digest = bytearray(hashlib.md5(('OfflinePlayer:' + name).encode()).digest()) - digest[6] = (digest[6] & 0x0F) | 0x30 - digest[8] = (digest[8] & 0x3F) | 0x80 - return uuid.UUID(bytes=bytes(digest)) - - -def varint(v): - out = b'' - v &= 0xFFFFFFFF - while True: - b = v & 0x7F - v >>= 7 - out += bytes([b | (0x80 if v else 0)]) - if not v: - return out - - def string(s): data = s.encode() - return varint(len(data)) + data + return lab.varint(len(data)) + data class Connection: @@ -73,44 +53,33 @@ class Connection: return value def send(self, packet_id, payload=b''): - body = varint(packet_id) + payload + body = lab.varint(packet_id) + payload if self.threshold >= 0: if len(body) >= self.threshold: - body = varint(len(body)) + zlib.compress(body) + body = lab.varint(len(body)) + zlib.compress(body) else: - body = varint(0) + body - self.sock.sendall(varint(len(body)) + body) + body = lab.varint(0) + body + self.sock.sendall(lab.varint(len(body)) + body) def receive(self): length = self.read_varint() body = self.read_exact(length) if self.threshold >= 0: - pos, size = parse_varint(body, 0) + pos, size = lab.parse_varint(body, 0) body = zlib.decompress(body[pos:]) if size else body[pos:] - pos, packet_id = parse_varint(body, 0) + pos, packet_id = lab.parse_varint(body, 0) return packet_id, body[pos:] -def parse_varint(data, pos): - value = shift = 0 - while True: - b = data[pos] - pos += 1 - value |= (b & 0x7F) << shift - shift += 7 - if not b & 0x80: - return pos, value - - def join(host, port, name, seconds): c = Connection(host, port) - c.send(0, varint(lab.version_info()['protocol_version']) + string(host) + struct.pack('>H', port) + varint(2)) - c.send(0, string(name) + offline_uuid(name).bytes) + c.send(0, lab.varint(lab.version_info()['protocol_version']) + string(host) + struct.pack('>H', port) + lab.varint(2)) + c.send(0, string(name) + lab.offline_uuid(name).bytes) # Login: compression, then login finished. while True: pid, data = c.receive() if pid == 3: - c.threshold = parse_varint(data, 0)[1] + c.threshold = lab.parse_varint(data, 0)[1] elif pid == 2: break elif pid == 0: @@ -119,7 +88,7 @@ def join(host, port, name, seconds): while True: pid, data = c.receive() if pid == 15: # select known packs: claim none, receive full registries - c.send(7, varint(0)) + c.send(7, lab.varint(0)) elif pid == 4: # keep alive c.send(4, data) elif pid == 5: # ping @@ -153,7 +122,7 @@ def main(): p.add_argument('--uuid', action='store_true') args = p.parse_args() if args.uuid: - print(offline_uuid(args.name)) + print(lab.offline_uuid(args.name)) return 0 join(args.host, args.port, args.name, args.seconds) return 0 diff --git a/tools/vanilla_world_check.py b/tools/vanilla_world_check.py index 1bbc64004..317b7e998 100644 --- a/tools/vanilla_world_check.py +++ b/tools/vanilla_world_check.py @@ -17,12 +17,16 @@ load failures. import argparse import os import re -import socket import subprocess import sys import threading import time +try: + from . import lab +except ImportError: + import lab + SUSPICIOUS = re.compile( r'(ERROR|login failed|Exception|Couldn\'t load|Failed to|Skipping|Invalid|Unknown|corrupt|' r'Recreating|upgrad|DataFix|out of bounds|missing|Mismatch)', re.IGNORECASE) @@ -31,12 +35,6 @@ BENIGN = re.compile(r'(Unpacking |OFFLINE/INSECURE|online-mode|authenticate user r'Failed to load properties|Failed to load eula)') -def free_port(): - with socket.socket() as s: - s.bind(('127.0.0.1', 0)) - return s.getsockname()[1] - - def main(): p = argparse.ArgumentParser() p.add_argument('--jar', required=True) @@ -48,7 +46,7 @@ def main(): p.add_argument('--wait-after', type=float, default=1.0) p.add_argument('--timeout', type=float, default=240) args = p.parse_args() - port = args.port or free_port() + port = args.port or lab.free_port() os.makedirs(args.dir, exist_ok=True) with open(os.path.join(args.dir, 'eula.txt'), 'w') as f: f.write('eula=true\n') From 60bad91a5004891ca5b746639a84c3a8b6538fdd Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:31:51 +0200 Subject: [PATCH 031/408] Client zip.rs reads archives with the zip crate it already links The 120-line hand-written central-directory and local-header parser goes: the zip crate (already the client's dependency for world backups) indexes the archive, zip64 and odd offsets included. Entries are still read raw and inflated here, so as with Java's ZipFile (vanilla's FilePackResources) their CRC isn't checked. New tests: folder entries, a nested pack root, a Windows-style name, one broken entry among good ones, and files that aren't zips. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/zip.rs | 206 ++++++++++++++++++------------- 1 file changed, 122 insertions(+), 84 deletions(-) diff --git a/crates/horizon-client/src/zip.rs b/crates/horizon-client/src/zip.rs index a0551c829..22cab132d 100644 --- a/crates/horizon-client/src/zip.rs +++ b/crates/horizon-client/src/zip.rs @@ -1,75 +1,35 @@ -//! Minimal read-only ZIP archive support (stored and deflated entries), used -//! for resource packs and the unifont glyph archive. -use std::{collections::BTreeMap, fs, io, path::Path}; +//! Read-only ZIP archives held in memory (resource packs, data packs and the +//! unifont glyph archive), on the `zip` crate. Like Java's `ZipFile` (what +//! vanilla's `FilePackResources` reads with), entries aren't CRC-checked. +use std::{ + collections::BTreeMap, + fs, + io::{self, Cursor, Read}, + path::Path, + sync::Arc, +}; +use zip::{CompressionMethod, ZipArchive}; -/// One archive held in memory with its central directory indexed by name. +/// One archive with its entries indexed by name (`\` read as `/`, folders +/// left out). pub struct Zip { - data: Vec, - entries: BTreeMap, + archive: ZipArchive>>, + entries: BTreeMap, } -#[derive(Clone, Copy)] -struct Entry { - method: u16, - compressed: usize, - size: usize, - header: usize, -} -fn invalid(message: &str) -> io::Error { - io::Error::new(io::ErrorKind::InvalidData, message) -} -fn u16_at(d: &[u8], at: usize) -> io::Result { - d.get(at..at + 2) - .map(|b| u16::from_le_bytes([b[0], b[1]])) - .ok_or_else(|| invalid("truncated zip")) -} -fn u32_at(d: &[u8], at: usize) -> io::Result { - d.get(at..at + 4) - .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])) - .ok_or_else(|| invalid("truncated zip")) +fn invalid(e: impl std::fmt::Display) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, e.to_string()) } impl Zip { pub fn open(path: &Path) -> io::Result { Self::from_bytes(fs::read(path)?) } pub fn from_bytes(data: Vec) -> io::Result { - // End of central directory: the last "PK\x05\x06" within 64 KiB of the end. - let min = data.len().saturating_sub(22 + 65_535); - let eocd = (min..=data.len().saturating_sub(22)) - .rev() - .find(|&i| data[i..i + 4] == [0x50, 0x4b, 0x05, 0x06]) - .ok_or_else(|| invalid("not a zip archive"))?; - let count = usize::from(u16_at(&data, eocd + 10)?); - let mut at = u32_at(&data, eocd + 16)? as usize; - let mut entries = BTreeMap::new(); - for _ in 0..count { - if u32_at(&data, at)? != 0x0201_4b50 { - return Err(invalid("bad central directory entry")); - } - let method = u16_at(&data, at + 10)?; - let compressed = u32_at(&data, at + 20)? as usize; - let size = u32_at(&data, at + 24)? as usize; - let name_len = usize::from(u16_at(&data, at + 28)?); - let extra_len = usize::from(u16_at(&data, at + 30)?); - let comment_len = usize::from(u16_at(&data, at + 32)?); - let header = u32_at(&data, at + 42)? as usize; - let name = data - .get(at + 46..at + 46 + name_len) - .ok_or_else(|| invalid("truncated zip name"))?; - let name = String::from_utf8_lossy(name).replace('\\', "/"); - if !name.ends_with('/') { - entries.insert( - name, - Entry { - method, - compressed, - size, - header, - }, - ); - } - at += 46 + name_len + extra_len + comment_len; - } - Ok(Self { data, entries }) + let archive = ZipArchive::new(Cursor::new(Arc::from(data))).map_err(invalid)?; + let entries = (0..archive.len()) + .filter_map(|i| Some((archive.name_for_index(i)?.replace('\\', "/"), i))) + .filter(|(name, _)| !name.ends_with('/')) + .collect(); + Ok(Self { archive, entries }) } pub fn names(&self) -> impl Iterator { self.entries.keys().map(String::as_str) @@ -78,30 +38,21 @@ impl Zip { self.entries.contains_key(name) } pub fn read(&self, name: &str) -> io::Result> { - let e = *self + let &index = self .entries .get(name) .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, name.to_owned()))?; - if u32_at(&self.data, e.header)? != 0x0403_4b50 { - return Err(invalid("bad local file header")); - } - let start = e.header - + 30 - + usize::from(u16_at(&self.data, e.header + 26)?) - + usize::from(u16_at(&self.data, e.header + 28)?); - let raw = self - .data - .get(start..start + e.compressed) - .ok_or_else(|| invalid("truncated zip entry"))?; - match e.method { - 0 => Ok(raw.to_vec()), - 8 => { - let out = miniz_oxide::inflate::decompress_to_vec_with_limit( - raw, - e.size.max(1) * 2 + 1024, - ) - .map_err(|_| invalid("corrupt deflate stream"))?; - Ok(out) + // A clone shares the bytes and the central directory: reading needs `&mut`. + let mut archive = self.archive.clone(); + let mut entry = archive.by_index_raw(index).map_err(invalid)?; + let (method, size) = (entry.compression(), entry.size() as usize); + let mut raw = Vec::with_capacity(entry.compressed_size() as usize); + entry.read_to_end(&mut raw)?; + match method { + CompressionMethod::Stored => Ok(raw), + CompressionMethod::Deflated => { + miniz_oxide::inflate::decompress_to_vec_with_limit(&raw, size.max(1) * 2 + 1024) + .map_err(|_| invalid("corrupt deflate stream")) } _ => Err(invalid("unsupported zip compression")), } @@ -163,10 +114,97 @@ mod tests { } #[test] fn reads_stored_and_deflated_entries() { + // Its CRCs are zero: Java's ZipFile doesn't check them either. let zip = Zip::from_bytes(archive()).unwrap(); assert_eq!(zip.names().collect::>(), ["a/b.txt", "pack.mcmeta"]); assert_eq!(zip.read("pack.mcmeta").unwrap(), b"{\"pack\":{}}"); assert_eq!(zip.read("a/b.txt").unwrap(), b"hello hello hello hello"); assert!(zip.read("missing").is_err()); } + + /// A pack as zip tools write it: folder entries, a nested pack root, + /// stored and deflated files, and a Windows-style name. + fn written() -> Vec { + use std::io::Write; + use zip::write::SimpleFileOptions; + let mut w = zip::ZipWriter::new(Cursor::new(Vec::new())); + let stored = SimpleFileOptions::default().compression_method(CompressionMethod::Stored); + let deflated = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated); + w.add_directory("Pack-main/", stored).unwrap(); + w.add_directory("Pack-main/assets/minecraft/", stored) + .unwrap(); + w.start_file("Pack-main/pack.mcmeta", stored).unwrap(); + w.write_all(b"{\"pack\":{\"pack_format\":64}}").unwrap(); + w.start_file("Pack-main/assets/minecraft/lang/en_us.json", deflated) + .unwrap(); + w.write_all("{\"a\":\"b\"}".repeat(100).as_bytes()).unwrap(); + w.start_file( + "Pack-main\\assets\\minecraft\\texts\\splashes.txt", + deflated, + ) + .unwrap(); + w.write_all(b"Also try Horizon!").unwrap(); + w.finish().unwrap().into_inner() + } + + #[test] + fn reads_nested_folders_and_skips_folder_entries() { + let zip = Zip::from_bytes(written()).unwrap(); + assert_eq!( + zip.names().collect::>(), + [ + "Pack-main/assets/minecraft/lang/en_us.json", + "Pack-main/assets/minecraft/texts/splashes.txt", + "Pack-main/pack.mcmeta", + ] + ); + assert!(zip.contains("Pack-main/pack.mcmeta")); + assert!(!zip.contains("Pack-main/")); + assert_eq!( + zip.read("Pack-main/assets/minecraft/lang/en_us.json") + .unwrap(), + "{\"a\":\"b\"}".repeat(100).as_bytes() + ); + assert_eq!( + zip.read("Pack-main/assets/minecraft/texts/splashes.txt") + .unwrap(), + b"Also try Horizon!" + ); + } + + #[test] + fn a_bad_entry_fails_alone() { + let mut bytes = written(); + // The deflated lang file's stream becomes a reserved block type. + let (start, len) = { + let mut archive = ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap(); + let index = archive + .index_for_name("Pack-main/assets/minecraft/lang/en_us.json") + .unwrap(); + let entry = archive.by_index_raw(index).unwrap(); + ( + entry.data_start() as usize, + entry.compressed_size() as usize, + ) + }; + bytes[start..start + len].fill(0xff); + let zip = Zip::from_bytes(bytes).unwrap(); + assert!( + zip.read("Pack-main/assets/minecraft/lang/en_us.json") + .is_err() + ); + assert_eq!( + zip.read("Pack-main/pack.mcmeta").unwrap(), + b"{\"pack\":{\"pack_format\":64}}" + ); + } + + #[test] + fn refuses_what_is_not_a_zip() { + assert!(Zip::from_bytes(b"PK not really".to_vec()).is_err()); + assert!(Zip::from_bytes(Vec::new()).is_err()); + let mut cut = written(); + cut.truncate(cut.len() / 2); + assert!(Zip::from_bytes(cut).is_err()); + } } From 2eb699228a0064182aa9a8e8da4412c6cd1b6a4e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:18:44 +0200 Subject: [PATCH 032/408] AGENTS.md and docs/architecture.md: a map of the code for agents AGENTS.md (CLAUDE.md links to it): the crates and what each owns, how to build and test fast, where each subsystem of horizon-client lives, how Game is organised, the two single-player paths and how to test both, the vanilla reference, and the rules that bite. docs/architecture.md: feature -> files -> checks for the 40 areas changed most in the last 30 days. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 175 +++++++++++++++++++++++++++++++++++++++++++ CLAUDE.md | 1 + docs/README.md | 1 + docs/architecture.md | 57 ++++++++++++++ 4 files changed, 234 insertions(+) create mode 100644 AGENTS.md create mode 120000 CLAUDE.md create mode 100644 docs/architecture.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 000000000..d869aed2a --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,175 @@ +# Horizon: a map for agents + +Minecraft: Java Edition 26.3 rewritten in Rust (wgpu). Vanilla is the specification wherever it has the +feature. Read [CONTRIBUTING.md](CONTRIBUTING.md) once; this page tells you where things are. +Feature → files → harness for the most-changed areas: [docs/architecture.md](docs/architecture.md). + +## Rules that bite + +- **Never commit Mojang's files**: game jars, assets, decompiled source, prepared resources (`.local/`). + `tools/check_public_tree.py` rejects them; `git config core.hooksPath .githooks` runs it on commit. +- **Keep your runs away from real player data.** Any game or launcher you start gets fresh `mktemp -d` + folders in `HORIZON_HOME` (the game's data), `HORIZON_LAUNCHER_HOME`, `XDG_DATA_HOME` and + `XDG_CONFIG_HOME`, plus `HORIZON_LAUNCHER_NO_SELF_UPDATE=1` and `HORIZON_NO_AUDIO=1`. Never write to + `~/.local/share/{applications,horizon,horizon-launcher}` or `~/.local/bin`. +- **Mark what an agent posts.** A PR body starts with + `> 🤖 Opened by Ludovic's AI agent (Claude), not by Ludovic himself.` (issues: "Filed by", reviews: + "Review by"); every comment starts with `🤖 Agent:`. Never write as Ludovic. +- **Attribution.** Commits end with `Co-Authored-By: Claude `; PR bodies end + with `🤖 Generated with [Claude Code](https://claude.com/claude-code)`. +- Everything players run is Rust. Python/Java only for dev tools and harness drivers in `tools/`. +- Horizon-only features follow [docs/design-system.md](docs/design-system.md) and are off by default where + they would change the vanilla look. +- Small PRs (< ~500 lines). Labels: `feature` (players get something new), `skip-release` (they see no + change), none for a fix, `release-now` for crash fixes. Every merge to main ships + ([docs/release-flow.md](docs/release-flow.md)). +- Contributors first: `gh pr list --state open --search ` before you start; never duplicate theirs. + +## Crates + +Game workspace (root `Cargo.toml`); `launcher/` and `crates/horizon-telemetry-server` are separate workspaces. + +| Crate | Owns | +|---|---| +| `horizon-client` | The game: a lib (`src/lib.rs`, ~190 flat modules) and the bin (`src/main.rs` → `game.rs` + `game/`), plus `horizon-ctl` (`src/bin/horizon-ctl/`). Also the dedicated server (`--dedicated`) | +| `horizon-world` | Vanilla world data with no gameplay loop: NBT, regions, chunks, `datafix/`, `worldgen/`, `level/` (server-side block behaviour, ticks, redstone), entity physics, items, effects, food, damage | +| `horizon-core` | Simulation primitives: Java `Random`s, `jmath` (HotSpot-exact `Math`), positions, noise, density, paletted storage, `version.rs` (the pinned version) | +| `horizon-protocol` | Network protocol 777: codecs, framing, encryption, `packets/{handshake,status,login,configuration,play}.rs`, `entity_data.rs` | +| `horizon-assets` | Resource decoding: block-state and item models, baking, atlases | +| `horizon-prepare` | Builds `.local/horizon-client/26.3` from the player's own Minecraft install (runs the Java exporters) | +| `horizon-server` | `horizon-server`: `server.toml`, CLI, supervisor of the headless game ([docs/hosting.md](docs/hosting.md)) | +| `horizon-server-files` | `server.properties`, eula, ops/whitelist/bans, usercache | +| `horizon-friends`, `horizon-relay` | Play with Friends: invite codes, encrypted tunnel, the relay ([docs/play-with-friends.md](docs/play-with-friends.md)) | +| `horizon-shaderpack` | OptiFine/Iris packs: preprocessor, GLSL → WGSL ([docs/shader-packs.md](docs/shader-packs.md)) | +| `horizon-mods`, `horizon-mod-sdk`, `cargo-horizon-mod` | Sandboxed WebAssembly mods: runtime, SDK + WIT, `cargo horizon-mod` ([docs/mods.md](docs/mods.md)) | +| `horizon-port-pack` | Porting Java modpacks ([docs/modpacks.md](docs/modpacks.md)) | +| `horizon-theme` | Design tokens and fonts for the launcher, the game's own menus and the website | +| `horizon-telemetry`, `horizon-telemetry-server`, `horizon-bench` | Opt-in data collection, its ingest server, the benchmark report format | +| `horizon-dualsense`, `horizon-threads`, `horizon-release-sign`, `horizon-bots`, `voxel-kernels`, `xtask` | DualSense output, thread priorities, signed release checksums, load-test bots, occupancy kernels, repo tasks | +| `launcher/` | GPUI launcher: `main.rs` (UI), `backend.rs` (installs, updates), `cli.rs`, `mcp.rs`, `*_page.rs` | + +Other top-level folders: `tools/` (harnesses and dev scripts), `tests/` (Python unit tests: `python3 -m +unittest discover -s tests`), `mods/horizon/src/test/java/dev/horizonlab/parity/` (Java oracles), +`website/` (playhorizon.dev; its paths are relative to `website/`), `docs/`, `.github/workflows/`. + +## Build and test fast + +```sh +python3 tools/pr_ready.py # the self-check: fmt, clippy -D warnings, touched crates' tests, harnesses; paste its block in the PR +python3 tools/pr_ready.py --quick # same without harnesses +cargo test -p horizon-client --lib --bins --tests # skips the 104 examples (pr_ready does this); `--doc` separately +cargo build --profile fast -p horizon-client # optimized, quick to link: use it to play or run lan_e2e +python3 tools/parity.py --changed origin/main # the harnesses your branch can affect (CI's parity job) +python3 tools/parity.py --changed-files paths.txt --list # which harnesses cover these files, without running them +python3 tools/parity.py mob_ai sculk # named harnesses +python3 tools/lan_e2e.py --check chest # two real games over LAN (host in-frame); --server-thread for the host on its server thread +python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end +``` + +- Harnesses and the game need the vanilla data in `.local/` (`minecraft/`, `horizon-client/26.3`, `datagen/`, + `tools/`): see [docs/parity-workflow.md](docs/parity-workflow.md). Without it, pr_ready lists the + harnesses for CI. +- A harness = `tools/test__parity.py` (324 of them) + a Java oracle (`mods/horizon/src/test/java/dev/horizonlab/parity/Vanilla*Oracle.java`) + + a Rust probe: `crates//examples/_{probe,fixture}.rs` (horizon-world 175, horizon-client 104), + or the game binary with a fixture env var (`game/dispense_fixture.rs`, `game/sculk_fixture.rs`, + `game/command_harness.rs`, `game/net_harness.rs`). Copy a nearby harness for a new one. +- Probes build into `.local/parity-target/`; harnesses find binaries via `lab.cargo_target()`, never `target/`. +- What a change reruns (of 329 harnesses, measured 2026-10-23): a file of the game binary (`game.rs`, `game/`) + ~25, a file of the client lib ~103, of `horizon-world` ~103–109, of `horizon-core` ~119. Plan for it. +- Rust integration tests: `crates/horizon-client/tests/` (`lan_bot.rs`, `generation_saves.rs`, `streaming_meshes.rs`). +- **macOS:** `cargo build/test --workspace` may fail to link the two wasm guest cdylibs (undefined + `horizon:mods/events` symbols) until #1446 lands: add `--exclude coords-hud --exclude horizon-mods-test-guest`. + Their real check is `cargo test -p horizon-mods` (builds them for `wasm32-unknown-unknown`). +- Linux needs `libasound2-dev libudev-dev`; `--no-default-features` drops audio and controllers (the server build). +- Run and drive the game (starts the `horizon-client` beside `horizon-ctl`; other arguments go to the game): + `target/fast/horizon-ctl --socket $PWD/ctl.sock launch --world W --creative --offscreen --wait --resources $PWD/.local/horizon-client/26.3`, + then `horizon-ctl --socket … state|keys|turn|command|screenshot|quit` + ([docs/horizon-ctl-commands.md](docs/horizon-ctl-commands.md)). + +## Vanilla reference + +- Decompiled sources: `.local/minecraft/26.3/sources/{client,server}/` (`python3 tools/lab.py decompile`). +- Bytecode queries (callers through lambdas, every overload): + `python3 tools/rea_vanilla.py method net.minecraft.world.level.block.DispenserBlock dispenseFrom` + ([docs/decompilation-status.md](docs/decompilation-status.md)). +- A harness runs the oracle against the real 26.3 jars and the Rust probe on the same inputs, then compares + their JSON. Oracle runs are cached by `tools/parity_shim.py`; `--fresh` reruns them. +- Mirror vanilla's `Math` calls with `horizon_core::jmath`, and vanilla's RNG with `horizon_core::random`: + random draws must happen in vanilla's order. + +## horizon-client: where things live + +`L:` = lib (`crates/horizon-client/src/`), `G:` = bin (`crates/horizon-client/src/game/`). The lib can't see +`Game`; bin code reaches the lib as `horizon_client::`. + +| Subsystem | Files | +|---|---| +| Game loop, tick, frame | `game.rs`: `fn run`, `impl ApplicationHandler for Game` (`window_event`, `about_to_wait`), `fn tick`, `fn tick_world`, `fn render`; L: `clock.rs`, `window.rs`, `spans.rs` | +| Rendering | L: `gfx.rs` (`Renderer::new`, `Renderer::render`), `gfx/` (cull, occlusion, translucency, upload, timing, lod, weather, stars, end_sky), `*.wgsl`, `particles.rs`, `block_entity_render.rs`, `item_render.rs`, `fog.rs`, `clouds.rs`, `camera.rs`, `first_person.rs`; G: `render_tick.rs`, `item_draw.rs` | +| Chunks, streaming, light | L: `streaming.rs` (worker pool: generate, light, mesh), `world.rs`, `chunk.rs`, `chunk_map.rs`, `light.rs`, `mesher.rs` + `mesher/`, `vanillagen.rs` (binds horizon-world's generator), `lod.rs` + `lod/`, `ticket_levels.rs`; G: `world_loading.rs`, `postprocess.rs`; game.rs `fn update_world` | +| World generation | `crates/horizon-world/src/worldgen/` (`generator*.rs`, `feature_graph.rs`, `structure/`, `carver/`) | +| Block behaviour | `crates/horizon-world/src/level/` (`mod.rs`, `tick.rs`, `hooks.rs`, `redstone.rs`, `place.rs`, `interact.rs`); game.rs `fn tick_blocks`, `fn process_level_events` | +| Mobs | L: `mobs.rs` (types), `mobs/` (`ai.rs`, `goals.rs`, `brain.rs`, `*_brain.rs`, `nav.rs`, `path.rs`, `species.rs`, `spawning.rs`, `render.rs`, `anim.rs`); G: `creatures.rs` (ticking, spawning, mob events), one file per mob family (`dragon.rs`, `wither.rs`, `villagers.rs`, `piglins.rs`, `golems.rs`...), `natural_spawning.rs` | +| Other entities | L: `entities.rs`, `projectiles.rs`, `arrows.rs`; G: `boats.rs`, `minecarts.rs`, `mounts.rs`, `armor_stands.rs`, `paintings.rs`, `frames.rs`, `fireworks.rs`, `tnt.rs`, `explosion.rs` | +| Player actions | game.rs (`fn use_hand`, `fn use_item`, `fn attack`, `fn tick_mining`, `fn break_block`); G: `hand.rs`, `combat.rs`, `consume.rs`, `potions.rs`, `shield.rs`, `crossbow.rs`, `trident.rs`, `fishing.rs`; L: `motion.rs` + `motion/` (movement), `collisions.rs`, `items.rs`, `item_data.rs` | +| Inventory and containers | L: `menu.rs` (`AbstractContainerMenu.clicked`), `container_screen.rs`, `containers.rs`, `creative.rs`, `crafting.rs`, `recipe_book*.rs`, `stations.rs`, `merchant.rs`; game.rs `fn menu_ops`, `fn click_inventory`; G: `stations.rs`, `trading.rs`, `recipe_book.rs`, `machines.rs` | +| Commands | parse: L: `command/` (`args.rs`, `selector.rs`, `tree_*.rs`, `vanilla.rs`); run: G: `commands.rs` (dispatch) + `commands/*.rs` (`admin`, `execute`, `items`, `players`, `world_cmds`...); L: `scoreboard_cmd.rs`, `data_cmd.rs`, `nbt_path.rs`; G: `functions.rs`, `command_blocks.rs` | +| UI screens | `Screen` enum in game.rs; L: `title.rs` + `title/`, `options_ui.rs`, `multiplayer.rs`, `pack_screen.rs`, `graphics_ui.rs`, `screen_draw.rs`, `ui.rs` (widgets), `hud.rs`, `hud_layout.rs`, `hud_overlays.rs`, `chat.rs`, `tab_list.rs`; G: `startup_menu.rs`, `screens.rs` (pause, death), `options.rs`, `lan_screen.rs`, `chat.rs`, `sign_edit.rs`, `books.rs` | +| Multiplayer client | L: `net.rs` (network thread); G: `remote.rs` (`fn handle_packet`, `fn tick_remote`), `remote_*.rs` (mob data, objects, projectiles, vehicles, stations) | +| LAN host / server side | L: `lan/` (`conn.rs` handshake + login threads, `hub.rs` + `hub/` play state, `chunks.rs`, `entity.rs`, `tracking.rs`, `guest.rs`, `playerdata.rs`); G: `lan.rs` (`LanHost`), `lan_actions.rs` (`fn as_guest`, `fn tick_guests`), `lan_*.rs` per feature, `lan_entities.rs` (tracked entities) | +| Integrated server | G: `integrated.rs` (the server thread), `levels.rs` (one level per dimension, `fn tick_server`), `server_travel.rs` | +| Dedicated server | G: `dedicated.rs`, `dedicated/status.rs`; crates `horizon-server-files`, `horizon-server` | +| Save and load | L: `save.rs` (level.dat, regions, playerdata), `entity_nbt.rs`, `block_entity_nbt.rs`, `options_file.rs`; G: `saving.rs`, `persist.rs` (entities); `crates/horizon-world/src/{region.rs,nbt.rs,datafix/}` | +| Input | game.rs `fn window_event`, `fn key_pressed`, `fn play_mouse`; L: `keybinds.rs`, `keymapping.rs`, `key_names.rs`, `mouse.rs`, `input.rs`, `interaction_input.rs`, `gamepad.rs`, `osk.rs`, `clipboard.rs`; G: `pad.rs`, `pad_menu.rs` | +| Audio | L: `audio.rs` (mixer), `sound_engine.rs`, `sound_events.rs`, `music.rs`, `ambience.rs`; G: `music.rs`, `subtitle_hud.rs` | +| Resource packs | L: `packs.rs` + `packs/`, `pack_screen.rs`, `atlas_sources.rs`, `sprites.rs`, `mipmap.rs`, `model_library.rs`, `font.rs`, `lang.rs`; crate `horizon-assets`; G: `packs.rs` | +| Shader packs | L: `shader_pack.rs` (Horizon WGSL packs), `java_pack.rs` + crate `horizon-shaderpack` (Iris/OptiFine), `gfx/pack_stages.rs`, `gfx/java_stages.rs`; G: `shader_packs.rs` | +| Agent control | L: `control.rs` (socket), `bin/horizon-ctl/`; G: `control.rs`, `agent.rs`, `events.rs`, `ui_control.rs` ([docs/agent-control.md](docs/agent-control.md)) | +| Mods | crate `horizon-mods`; G: `mods.rs`; L: `mod_content.rs`, `mod_list.rs` | +| Horizon extras, settings | L: `extras.rs`, `graphics.rs`, `settings.rs`, `minimap.rs`; G: `extras.rs`, `tweaks.rs`, `options.rs` | + +## How `Game` is organised + +- `struct Game` (game.rs, ~290 fields) holds everything. Its methods are spread over ~180 files: game.rs keeps + the core (tick, render, input, inventory, world open/close) and each `game/.rs` adds an + `impl Game<'_>` block for one feature, with its own state types. Fields are private to the bin. +- Find a feature's code: `grep -rn "fn tick_\|fn _" crates/horizon-client/src/game*`; + the file is usually `game/s.rs`. Who calls it: grep the name in game.rs's `fn tick` / `fn tick_world`. +- Fields that say which mode runs: `remote` (this window is a client of a server: multiplayer, LAN guest, or + single player on its server thread), `lan` (`LanHost`: this world is open to the network), `integrated` + (the window's own server thread), `serving` (this `Game` *is* that server thread), `options.dedicated`. + `fn tick` returns `tick_remote()` when `remote` is set; nothing else of the local simulation runs. +- A server's players run through the same gameplay code as the local player: `as_guest` swaps the guest's + state (position, inventory, mode, mining, item use) into `Game` for one call (`game/lan_actions.rs`), and + `levels.rs` swaps whole dimensions in the same way. Changes reach clients through the block log, level + events and the entity tracker (`lan/tracking.rs`, `game/lan_entities.rs`). +- Shared read-only data: `Resources` (`res`: blocks, items, recipes, mob types, biomes) and `PackResources` + (`pack`), both in game.rs. + +## The two single-player paths + +1. **In-frame (default since #1428):** the window's `Game` ticks the world itself, one level that follows + the player (`fn enter_dimension`). This is what Stable players run and what harnesses test. +2. **Server thread (`--server-thread` or `HORIZON_SERVER_THREAD=1`):** `game/integrated.rs` runs a second + `Game` (`serving`) on a "Server thread" with one level per dimension; the window joins it as a client + through memory (`remote`), exactly as a LAN guest or a dedicated server's player does. Not at parity yet: + open `[server-thread]` issues list the gaps. + +LAN guests and dedicated servers always use the server code, so a fix there serves both. Test both paths +when you touch player-facing gameplay: + +```sh +cargo run --profile fast -p horizon-client -- --resources .local/horizon-client/26.3 --world T # in-frame +cargo run --profile fast -p horizon-client -- --resources .local/horizon-client/26.3 --world T --server-thread # server thread +python3 tools/lan_e2e.py --check # host in-frame, guest is a server client +python3 tools/lan_e2e.py --server-thread --check # host on its server thread (portals, levels, distance, lava need it) +python3 tools/parity.py dedicated_server server_entities server_player_damage +``` + +## Docs worth knowing + +[docs/parity-workflow.md](docs/parity-workflow.md) (runner, gate, shards, scopes) · +[docs/native-client.md](docs/native-client.md) (options, controls, horizon-ctl) · +[docs/server-levels.md](docs/server-levels.md) (levels per dimension) · +[docs/rust-parity.md](docs/rust-parity.md) (what is ported) · [docs/known-issues.md](docs/known-issues.md) · +[docs/release-flow.md](docs/release-flow.md) · [docs/README.md](docs/README.md) (index). diff --git a/CLAUDE.md b/CLAUDE.md new file mode 120000 index 000000000..47dc3e3d8 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +AGENTS.md \ No newline at end of file diff --git a/docs/README.md b/docs/README.md index b4398ebfc..2e06b6e89 100644 --- a/docs/README.md +++ b/docs/README.md @@ -4,6 +4,7 @@ To play, use [the launcher](../launcher/README.md); the project site is [playhor ## Build and run +- [AGENTS.md](../AGENTS.md) and [Architecture](architecture.md): where each part of the code lives, how `Game` is organised, which harness checks which area. - [Build from source](../README.md#build-from-source): your own copy of the game, resource preparation, `cargo run`. - [Native client](native-client.md): options, controls, the dedicated server, `horizon-ctl` scripting, packaging, architecture. - [Host a server](hosting.md): install `horizon-server`, prepare the game files, first run, `server.toml`, the commands, the web panel, backups, services and Docker; what works today and what doesn't yet. diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 000000000..99e9b630e --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,57 @@ +# Architecture: feature → files → checks + +The 40 areas changed most often in the 30 days to 2026-10-23 (commits on main touching the area; `game.rs` is +counted only for the game loop because nearly every gameplay change touches it). The crate map, how `Game` is +organised and how to build and test are in [AGENTS.md](../AGENTS.md). + +Paths: `L/` = `crates/horizon-client/src/`, `G/` = `crates/horizon-client/src/game/`, `W/` = +`crates/horizon-world/src/`. Checks: a bare name is a harness (`python3 tools/parity.py `, script +`tools/test__parity.py`); `lan_e2e ` is `python3 tools/lan_e2e.py --check `. + +For the full set of harnesses a file can affect, ask the runner: +`printf '%s\n' > /tmp/p.txt && python3 tools/parity.py --changed-files /tmp/p.txt --list`. +Any file of the game binary (`game.rs`, `game/`) selects the ~25 harnesses that run the binary; a client lib +file selects ~103. + +| # | Area (commits) | Files | Checks | +|---|---|---|---| +| 1 | Game loop, tick order, frame pacing (554) | `L/game.rs` (`fn tick`, `fn tick_world`, `fn render`, `about_to_wait`), `L/clock.rs`, `L/window.rs`, `L/spans.rs` | game_loop, frame_limiter, interaction_input, tick | +| 2 | Mobs in the game loop, spawning (166) | `G/creatures.rs`, `G/natural_spawning.rs`, `L/mobs/spawning.rs`, `L/mobs/spawn_rules.rs`, `L/mobs/spawn_selection.rs`, `L/mobs/finalize.rs`, `G/spawner.rs`, `G/trial_spawner.rs` | natural_spawn, spawn_rules, finalize_spawn, spawner, trial_spawner, mob_ai | +| 3 | World save and load (163) | `L/save.rs`, `G/saving.rs`, `G/persist.rs` (entities), `L/entity_nbt.rs`, `L/block_entity_nbt.rs`, `W/region.rs`, `W/nbt.rs` | save_roundtrip, world_reopen, world, datafix | +| 4 | World generation (153) | `W/worldgen.rs`, `W/worldgen/` (`generator*.rs`, `feature_graph.rs`, `structure/`, `placement/`), `L/vanillagen.rs` | chunk_generation, worldgen, server_world_gen, world_spawn, feature_graph, feature_placement, decoration and the other worldgen harnesses | +| 5 | Multiplayer client, packets in (145) | `G/remote.rs` (`fn handle_packet`, `fn tick_remote`), `G/remote_*.rs`, `L/net.rs` | dedicated_server, server_entities, lan_e2e (all) | +| 6 | Agent control, horizon-ctl (145) | `L/control.rs`, `L/bin/horizon-ctl/`, `G/control.rs`, `G/agent.rs`, `G/events.rs`, `G/ui_control.rs` | `python3 tools/agent_control_e2e.py`; `cargo test -p horizon-client --bin horizon-ctl` | +| 7 | CI and release (134) | `.github/workflows/` (`ci.yml`, `parity.yml`, `release.yml`, `launcher.yml`), `tools/ci/`, `tools/parity.py`, `tools/pr_ready.py` | `python3 -m unittest discover -s tests`; actionlint (`.github/actionlint.yaml`) | +| 8 | LAN host: connections, play state, tracking (133) | `L/lan/` (`conn.rs`, `hub.rs` + `hub/`, `chunks.rs`, `entity.rs`, `tracking.rs`, `guest.rs`, `playerdata.rs`), `G/lan.rs` | lan, lan_e2e (all), `cargo test -p horizon-client --test lan_bot` | +| 9 | Renderer core (132) | `L/gfx.rs` (`Renderer::new`, `Renderer::render`), `L/gfx/` (cull, occlusion, translucency, upload, timing, lod) | client_graphics, culling_rays, translucency; `horizon-client --benchmark standard` | +| 10 | Launcher (124) | `launcher/src/` (`main.rs`, `backend.rs`, `cli.rs`, `mcp.rs`, `servers_page.rs`) | `cd launcher && cargo test`; `python3 tools/launcher_mcp_e2e.py` | +| 11 | Mob types and species (117) | `L/mobs.rs`, `L/mobs/species.rs`, `L/mobs/data.rs`, `L/mobs/living.rs`, `L/mobs/drops.rs`, `L/mobs/gear.rs` | mob_attributes, entity_attribute, entity_death_loot, mob_ai | +| 12 | Guests' actions on a server (98) | `G/lan_actions.rs` (`fn as_guest`, `fn tick_guests`), `G/lan_{attributes,pvp,chat,crafting,stations,trading,mount_menu,waypoints}.rs` | server_player_combat, server_player_damage, server_player_targets, lan_e2e (all) | +| 13 | Modpack porting, mod content (97) | `crates/horizon-port-pack/`, `L/mod_content.rs`, `tools/port_*.py`, `packs/` | `cargo test -p horizon-port-pack`; `python3 tools/mod_port_harness.py` | +| 14 | Mob AI (96) | `L/mobs/ai.rs`, `goals.rs`, `brain.rs`, `*_brain.rs`, `nav.rs`, `path.rs`, `control.rs` | mob_ai (probe `examples/mob_ai_probe.rs`; known failure on main: drowned_*, #290) | +| 15 | Items and item use (96) | `L/items.rs`, `L/item_data.rs`, `G/hand.rs`, `G/consume.rs`, `G/potions.rs`, `L/effects.rs`; game.rs `fn use_hand`, `fn use_item` | use_item_on, item_use, item_use_lifecycle, consumable, consume_effect, status_effect | +| 16 | Options and settings screens (93) | `L/options_ui.rs`, `G/options.rs`, `L/settings.rs`, `L/options_file.rs`, `L/graphics_ui.rs`, `L/graphics.rs` | options, toggle_keys | +| 17 | HUD, chat, tab list (93) | `L/hud.rs`, `L/hud_layout.rs`, `L/hud_overlays.rs`, `L/chat.rs`, `G/chat.rs`, `L/tab_list.rs`, `L/locator_bar.rs`, `G/locator_bar.rs` | hud, tab_list, locator_bar, chat_screen, secure_chat | +| 18 | Command execution (88) | `G/commands.rs`, `G/commands/*.rs`, `L/scoreboard_cmd.rs`, `L/data_cmd.rs`, `G/functions.rs` | command_exec (corpus `tools/command_exec_corpus.py`), scoreboard, server_ops_feedback, lan_e2e commands | +| 19 | Chunk streaming, light, tickets (85) | `L/streaming.rs`, `L/world.rs`, `L/chunk.rs`, `L/chunk_map.rs`, `L/light.rs`, `L/ticket_levels.rs`, `L/tick_chunk_membership.rs`, `G/world_loading.rs` | light, chunk_status, random_tick_sections; `cargo test -p horizon-client --test streaming_meshes` | +| 20 | Mob models and animation (78) | `L/mobs/render.rs`, `L/mobs/anim.rs`, `L/mobs/body_anim.rs`, `L/mobs/keyframes.rs`, `L/entity.wgsl` | entity_model | +| 21 | Block behaviour, server side (78) | `W/level/` (`mod.rs`, `tick.rs`, `hooks.rs`, `data.rs`, `redstone.rs`, `place.rs`), `G/block_entity_ticks.rs`, `G/moving_pistons.rs` | block_update, redstone, random_tick, simple_block, piston_movement, block_entity_tickers | +| 22 | Player movement and collision (75) | `L/motion.rs` + `L/motion/`, `L/collisions.rs`, `W/entity_move.rs`, `W/player_travel.rs`, `W/collision.rs` | collision, entity_move, player_travel, living_motion, climbing, swimming; `python3 tools/test_native_scene_motion.py` | +| 23 | Resource packs and models (65) | `L/packs.rs` + `L/packs/`, `L/pack_screen.rs`, `L/atlas_sources.rs`, `L/sprites.rs`, `L/model_library.rs`, `G/packs.rs`, `crates/horizon-assets/` | resource_pack, pack_selection, pack_screen, model_resolution, item_model, mipmap | +| 24 | Container menus and inventory (61) | `L/menu.rs`, `L/container_screen.rs`, `L/containers.rs`, `L/creative.rs`; game.rs `fn menu_ops`, `fn click_inventory` | menu_click, container_screen, creative, lan_e2e containers clicks | +| 25 | Workstations (60) | `L/stations.rs`, `G/stations.rs`, `L/enchant.rs`, `L/brewing.rs` | enchanting, screen_layout, lan_e2e brewing loom stonecutter grindstone anvil smithing | +| 26 | Crafting and the recipe book (59) | `L/crafting.rs`, `L/recipe_book.rs`, `L/recipe_book_screen.rs`, `G/recipe_book.rs`, `G/machines.rs`, `G/machines/crafter.rs` | recipe, recipe_book, recipe_book_view, place_recipe, ghost_recipe, crafter | +| 27 | Vehicles and mounts (54) | `G/boats.rs`, `G/minecarts.rs`, `G/mounts.rs`, `G/mount_menu.rs`, `G/llamas.rs`, `G/passengers.rs` | server_entities, lan_e2e boats minecarts riding mounts | +| 28 | Villagers, trading, raids (50) | `L/mobs/villager*.rs`, `L/merchant.rs`, `G/trading.rs`, `G/villagers.rs`, `L/raid.rs`, `G/raids.rs`, `L/gossip.rs` | trading, raid, mob_ai | +| 29 | Title, worlds, startup (49) | `L/title.rs` + `L/title/`, `G/startup_menu.rs`, `L/title_edition.rs` | world_options; `cargo test -p horizon-client --lib title` | +| 30 | Dedicated server, horizon-server (48) | `G/dedicated.rs`, `G/dedicated/status.rs`, `crates/horizon-server/`, `crates/horizon-server-files/` | dedicated_server, server_files, user_cache, online_mode, server_ops_feedback | +| 31 | Particles and client effects (46) | `L/particles.rs`, `G/render_tick.rs`, `G/level_particles.rs`, `L/animate_tick.rs` | particle_providers, block_particles, entity_particles, emitter_particles, marker_particles | +| 32 | Bosses and the End (45) | `G/dragon.rs`, `G/wither.rs`, `G/end.rs` | server_dragon, end_podium, end_gateway | +| 33 | Protocol and packets (44) | `crates/horizon-protocol/src/` (`packets/play.rs`, `entity_data.rs`, `connection.rs`) | dedicated_server, online_mode, secure_chat; `cargo test -p horizon-protocol` | +| 34 | Multiplayer and LAN screens, friends (44) | `L/multiplayer.rs`, `G/lan_screen.rs`, `G/friends.rs`, `L/friends_screen.rs`, `crates/horizon-friends/`, `crates/horizon-relay/` | lan, world_options; `python3 tools/test_friends.py` | +| 35 | Dispensers (43) | `G/dispenser.rs`, `G/dispense_fixture.rs` (the harness side) | dispenser | +| 36 | Audio and music (38) | `L/audio.rs`, `L/sound_engine.rs`, `L/sound_events.rs`, `L/music.rs`, `G/music.rs`, `L/ambience.rs`, `G/subtitle_hud.rs` | sound_engine, sound_event, music, situational_music, ambient_sound, subtitle | +| 37 | Integrated server and levels (34) | `G/integrated.rs`, `G/levels.rs`, `G/server_travel.rs` | server_dimension_players, `lan_e2e --server-thread` (portals, levels, distance, lava) | +| 38 | Command parsing (34) | `L/command/` (`args.rs`, `selector.rs`, `tree_*.rs`, `vanilla.rs`) | command_parse (corpus `tools/command_parse_corpus.py`) | +| 39 | Benchmarks and telemetry (34) | `L/benchmark.rs`, `tools/perf_bench.py`, `L/telemetry.rs`, `crates/horizon-telemetry*/`, `crates/horizon-bench/` | `python3 -m unittest tests.test_perf_bench`; [benchmark.md](benchmark.md) | +| 40 | Explosions and TNT (31) | `G/explosion.rs`, `G/tnt.rs` | lan_e2e blast; no dedicated harness yet | From 22ad65611e85746cc00ad1f5ca25725f40b42d8f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:39:11 +0200 Subject: [PATCH 033/408] High-resolution resource packs no longer crash the game at launch The shared GUI atlas was always 4096 texels wide, so Faithful 64x needed 4096x32768: past the 16384 texels a side GPUs allow, and wgpu panicked in create_texture at every launch until the pack was removed (#1442). - The atlas widens (4096, 8192, 16384) until it fits within 16384 a side, so Faithful 64x loads. Its height rounds up to a multiple of 1024 instead of a power of two: the default resources' atlas drops from 4096x8192 to 4096x5120, Faithful 32x's from 4096x16384 to 4096x12288. - Textures that still don't fit are an error, not a GPU panic. At startup it rolls the packs back as Minecraft.rollbackResourcePacks does: the game starts with its own resources, and the selection is cleared and saved (clearResourcePacksOnError), so the next launch doesn't fail again. The existing "Resource reload failed" screen shows the reason. - The renderer refuses an atlas larger than the device allows with an error instead of a wgpu validation panic. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 20 ++++++- crates/horizon-client/src/gfx.rs | 7 +++ crates/horizon-client/src/hud.rs | 98 ++++++++++++++++++++++++++----- 3 files changed, 108 insertions(+), 17 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index dc6be85b7..df9400e4b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -12108,7 +12108,20 @@ fn load_resources( // loads; the synchronous launch instead carries it in `Loaded`. let mut loaded_gui = None; let mut ui_ready = false; - if let Ok(ui) = UiResources::load(&root) { + let mut pack_error = None; + let ui = match UiResources::load(&root) { + Ok(ui) => Some(ui), + // Minecraft.rollbackResourcePacks: the packs' textures don't fit, start + // with the game's own resources. + Err(e) if root != vanilla_root => { + log::warn!("Horizon: resource packs failed to load ({e}); using the default resources"); + pack_error = Some(e.to_string()); + root = vanilla_root.to_path_buf(); + None + } + Err(_) => None, + }; + if let Some(ui) = ui { if menu { horizon_client::telemetry::mark_ui_ready(); log::info!( @@ -12122,7 +12135,6 @@ fn load_resources( ui_ready = true; } progress.set(0); - let mut pack_error = None; let (assets, render) = match Assets::load(&root).and_then(|assets| { let render = assets.reload(&root)?; Ok((assets, render)) @@ -12560,6 +12572,10 @@ fn start_game<'a>( game.rest_loader = rest_loader; game.ui.vanilla_root = vanilla_root; if let Some(error) = pack_error { + // Minecraft.clearResourcePacksOnError: the selection is cleared and + // saved, so the next launch starts without the packs. + game.settings.resource_packs.clear(); + game.settings.save(&Game::options_path()); game.open_options_at(true, horizon_client::options_ui::Page::Packs); game.ui.options.resource_error = Some(error); } diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 82a9603e2..adeaf1c35 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -1491,6 +1491,13 @@ impl Renderer { mapped_at_creation: false, }); let (atlas_pixels, atlas_width, atlas_height) = hud_atlas; + let limit = device.limits().max_texture_dimension_2d; + if atlas_width.max(atlas_height) > limit { + return Err(format!( + "the shared atlas is {atlas_width}x{atlas_height}; this GPU allows {limit}x{limit}" + ) + .into()); + } let atlas = device.create_texture_with_data( &queue, &wgpu::TextureDescriptor { diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 82e606947..1d0ab91b9 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -54,6 +54,9 @@ pub struct HudAtlas { } /// Atlas rows reserved for glyphs rasterized at run time. pub const GLYPH_ROWS: u32 = 512; +/// The largest atlas side: the 2D texture limit of the GPUs Horizon runs on +/// (Apple silicon, RADV and Intel allow 16384; NVIDIA 32768). +pub const MAX_ATLAS_SIZE: u32 = 16384; /// 128x128 atlas slots for map textures. A lobby paints its signs as walls of /// framed maps, so the pool holds a wall; too few slots re-upload every map /// every frame. 26.3's `MapTextureManager` keeps a texture per map instead. @@ -269,6 +272,43 @@ impl HudAtlas { atlas.pixels = Vec::new(); Ok(atlas) } + /// Shelf placements of `images` (tallest first) in the narrowest atlas + /// width from 4096 up that keeps the atlas, glyph rows included, within + /// `max` texels a side; and the first row free for glyphs. High-resolution + /// packs fill a 4096-wide atlas past what GPUs allow (Faithful 64x needs + /// 32768 rows); vanilla's stitcher fails the reload when its atlases don't + /// fit, and the packs are then turned off (`Minecraft.clearResourcePacksOnError`). + fn layout(images: &[PackedImage], max: u32) -> Result<(u32, Vec<(u32, u32)>, u32)> { + let mut width = 4096.min(max); + loop { + let mut placements = Vec::with_capacity(images.len()); + let (mut x, mut y, mut row) = (0u32, 0u32, 0u32); + for (_, w, h, _) in images { + if x + w + 1 > width { + x = 0; + y += row + 1; + row = 0; + } + placements.push((x, y)); + x += w + 1; + row = row.max(*h); + } + let glyph_region = y + row + 1; + let wide_enough = images.iter().all(|i| i.1 < width); + if wide_enough && glyph_region + GLYPH_ROWS <= max { + return Ok((width, placements, glyph_region)); + } + if width >= max { + let texels: u64 = images.iter().map(|i| u64::from(i.1) * u64::from(i.2)).sum(); + return Err(format!( + "the textures ({} images, {texels} texels) do not fit a {max}x{max} atlas", + images.len() + ) + .into()); + } + width = (width * 2).min(max); + } + } /// Pack the textures under these folders of `textures/`, and for the /// `full` atlas the generated sprites and the run-time slots too. fn pack(root: &Path, folders: &[&str], full: bool) -> Result { @@ -351,21 +391,10 @@ impl HudAtlas { } } images.sort_by(|a, b| b.2.cmp(&a.2).then(b.1.cmp(&a.1))); - let width = 4096u32; - let mut placements = Vec::with_capacity(images.len()); - let (mut x, mut y, mut row) = (0u32, 0u32, 0u32); - for (_, w, h, _) in &images { - if x + w + 1 > width { - x = 0; - y += row + 1; - row = 0; - } - placements.push((x, y)); - x += w + 1; - row = row.max(*h); - } - let glyph_region = y + row + 1; - let height = (glyph_region + GLYPH_ROWS).next_power_of_two(); + let (width, placements, glyph_region) = Self::layout(&images, MAX_ATLAS_SIZE)?; + // A multiple of 1024 rather than a power of two: the default resources + // need 4096x5120 (8192 rows before), Faithful 32x 4096x12288 (16384). + let height = (glyph_region + GLYPH_ROWS).next_multiple_of(1024); let mut pixels = vec![0u8; (width * height * 4) as usize]; let mut sprites = HashMap::new(); for ((name, w, h, data), (px, py)) in images.iter().zip(placements) { @@ -1340,6 +1369,45 @@ impl HudRenderer { mod tests { use super::*; + /// `count` images of `w x h`; layout reads only their sizes. + fn sized(count: usize, w: u32, h: u32) -> Vec { + (0..count) + .map(|i| (format!("i{i}"), w, h, Vec::new())) + .collect() + } + fn assert_inside(images: &[PackedImage], width: u32, placements: &[(u32, u32)], free: u32) { + for ((_, w, h, _), (x, y)) in images.iter().zip(placements) { + assert!( + x + w <= width && y + h < free, + "{x},{y} {w}x{h} outside {width}x{free}" + ); + } + } + #[test] + fn the_default_textures_keep_a_4096_wide_atlas() { + let images = sized(400, 64, 64); + let (width, placements, free) = HudAtlas::layout(&images, MAX_ATLAS_SIZE).unwrap(); + assert_eq!(width, 4096); + assert_inside(&images, width, &placements, free); + } + #[test] + fn a_high_resolution_pack_widens_the_atlas_to_fit_the_gpu() { + // 34 rows of three 1024x512 GUI textures: 17442 rows at 4096 wide, + // past the 16384 GPUs allow (Faithful 64x needed 32768). + let images = sized(100, 1024, 512); + let (width, placements, free) = HudAtlas::layout(&images, MAX_ATLAS_SIZE).unwrap(); + assert_eq!(width, 8192); + assert!(free + GLYPH_ROWS <= MAX_ATLAS_SIZE); + assert_inside(&images, width, &placements, free); + } + #[test] + fn textures_that_cannot_fit_are_an_error_not_a_gpu_panic() { + let error = HudAtlas::layout(&sized(300, 1024, 1024), MAX_ATLAS_SIZE).unwrap_err(); + assert!(error.to_string().contains("do not fit a 16384x16384 atlas")); + // One image wider than the largest atlas. + assert!(HudAtlas::layout(&sized(1, 2048, 16), 2048).is_err()); + } + #[test] fn a_wrapped_border_repeats_the_opposite_edges() { // 2x2 texels a b / c d, one byte each in red. From 79ee670d7915a1ea4e7cdd4355053aa1a1ff513f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:59:07 +0200 Subject: [PATCH 034/408] High-resolution resource packs draw the GUI at its size With Faithful 32x the inventory showed the top-left quarter of its background stretched over the screen, tooltips lost their background and toasts doubled in size (#1442): the GUI code drew every atlas sprite in texels, where vanilla draws in GUI units whatever the pack's resolution. - Atlas sprites carry their GUI size: the size of the default resources' texture of that name (what vanilla's `blit(..., 256, 256)` calls and sprite sizes assume), their texels only for what copies pixels (font sheets, fire frames). Textures only a pack has keep their own size. The texture size filter reads the GUI size too, so Faithful 64x's 1024x1024 container backgrounds are no longer dropped. - Nine-slice sprites follow `GuiGraphicsExtractor.blitNineSlicedSprite`: their `gui.scaling` width, height and borders (Faithful's tooltip background is 50x50 with a 10-pixel border), `stretch_inner`, the single-quad and three-part cases, and borders capped at half the drawn size by integer division. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/font.rs | 5 +- crates/horizon-client/src/game.rs | 10 +- crates/horizon-client/src/game/packs.rs | 2 +- crates/horizon-client/src/hud.rs | 128 +++++++-- crates/horizon-client/src/ui.rs | 329 ++++++++++++++++++------ 5 files changed, 378 insertions(+), 96 deletions(-) diff --git a/crates/horizon-client/src/font.rs b/crates/horizon-client/src/font.rs index c5e5760f3..a25568df5 100644 --- a/crates/horizon-client/src/font.rs +++ b/crates/horizon-client/src/font.rs @@ -271,7 +271,10 @@ fn load_bitmap( .flatten(); // The sheet: its size, and its pixels when they are not in the atlas. let (sw, sh, sheet) = match in_atlas { - Some(rect) => (rect.w, rect.h, None), + Some(rect) => { + let (w, h) = rect.texels(atlas); + (w, h, None) + } None => match crate::hud::decode(&root.join(resource_path(file, "textures", ""))) { Ok((w, h, rgba)) => (w, h, Some(Arc::new((w, rgba)))), Err(_) => { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index df9400e4b..8d2d45a9e 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1021,9 +1021,11 @@ pub struct UiResources { pub panorama: Arc, } impl UiResources { - pub fn load(root: &std::path::Path) -> Result { + /// From a resource root layering packs over `defaults`, the game's own + /// resources (`root` itself when no pack is on). + pub fn load(root: &std::path::Path, defaults: &std::path::Path) -> Result { Ok(Self { - atlas: HudAtlas::build(root)?, + atlas: HudAtlas::build_over(root, defaults)?, panorama: Arc::new(horizon_client::gfx::panorama::Faces::load(root)), }) } @@ -12109,7 +12111,7 @@ fn load_resources( let mut loaded_gui = None; let mut ui_ready = false; let mut pack_error = None; - let ui = match UiResources::load(&root) { + let ui = match UiResources::load(&root, vanilla_root) { Ok(ui) => Some(ui), // Minecraft.rollbackResourcePacks: the packs' textures don't fit, start // with the game's own resources. @@ -12161,7 +12163,7 @@ fn load_resources( let render = Arc::new(render); // The menu bundle must come from the same root as the world bundle. if !ui_ready || root != requested_root { - let ui = UiResources::load(&root)?; + let ui = UiResources::load(&root, vanilla_root)?; if menu { horizon_client::telemetry::mark_ui_ready(); log::info!( diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index 94e61d948..ae2de00e6 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -133,7 +133,7 @@ impl Game<'_> { } fn reload_resources(&mut self, root: &Path) -> horizon_client::Result<()> { let render = std::sync::Arc::new(self.pack.assets.reload(root)?); - let mut atlas = HudAtlas::build(root)?; + let mut atlas = HudAtlas::build_over(root, &self.vanilla_root())?; atlas.font.uniform = self.settings.force_unicode; atlas.font.japanese = self.settings.japanese_glyphs; let gui = super::UiResources { diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 1d0ab91b9..9d30ae0e6 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -9,6 +9,11 @@ use std::{ }; use wgpu::util::DeviceExt; +/// A sprite's atlas region, and its size in GUI pixels: the size of the +/// default resources' texture of that name, whatever the resolution of the +/// pack that replaced it (vanilla's GUI code draws in those units: `blit` +/// divides by the texture size it is given, sprites by their `gui.scaling` +/// size). Textures the default resources lack keep their own size. #[derive(Clone, Copy, Debug)] pub struct Rect { pub u0: f32, @@ -18,6 +23,15 @@ pub struct Rect { pub w: u32, pub h: u32, } +impl Rect { + /// The region's size in texels of an atlas this large. + pub fn texels(&self, (width, height): (u32, u32)) -> (u32, u32) { + ( + ((self.u1 - self.u0) * width as f32).round() as u32, + ((self.v1 - self.v0) * height as f32).round() as u32, + ) + } +} /// `TextureMetadataSection`'s `blur` and `clamp`: how vanilla samples a /// standalone texture (`ReloadableTexture.setSampler`: linear rather than /// nearest filtering, clamp-to-edge rather than repeat addressing). @@ -92,6 +106,15 @@ pub fn decode_bytes(data: &[u8]) -> Result<(u32, u32, Vec)> { } Ok((info.width, info.height, rgba)) } +/// A PNG's width and height, from its header alone. +fn png_size(path: &Path) -> Option<(u32, u32)> { + use std::io::Read; + let mut header = [0u8; 24]; + fs::File::open(path).ok()?.read_exact(&mut header).ok()?; + let field = |at: usize| u32::from_be_bytes(header[at..at + 4].try_into().unwrap_or_default()); + (header[..8] == *b"\x89PNG\r\n\x1a\n" && header[12..16] == *b"IHDR") + .then(|| (field(16), field(20))) +} fn walk(dir: &Path, out: &mut Vec) { let Ok(entries) = fs::read_dir(dir) else { return; @@ -204,8 +227,14 @@ impl HudAtlas { (g.rect, g.advance) } pub fn build(root: &Path) -> Result { + Self::build_over(root, root) + } + /// The atlas of a resource root that layers packs over `defaults` (the + /// game's own resources), whose textures give the sprites' GUI sizes. + pub fn build_over(root: &Path, defaults: &Path) -> Result { Self::pack( root, + defaults, &[ "gui", "item", @@ -268,7 +297,7 @@ impl HudAtlas { /// holding its textures. The pixels are dropped once the glyph widths are /// read, since nothing uploads them. pub fn fonts(root: &Path) -> Result { - let mut atlas = Self::pack(root, &["font"], false)?; + let mut atlas = Self::pack(root, root, &["font"], false)?; atlas.pixels = Vec::new(); Ok(atlas) } @@ -311,8 +340,10 @@ impl HudAtlas { } /// Pack the textures under these folders of `textures/`, and for the /// `full` atlas the generated sprites and the run-time slots too. - fn pack(root: &Path, folders: &[&str], full: bool) -> Result { + fn pack(root: &Path, defaults: &Path, folders: &[&str], full: bool) -> Result { let textures = root.join("assets/minecraft/textures"); + let default_textures = + (defaults != root).then(|| defaults.join("assets/minecraft/textures")); let mut files = Vec::new(); for folder in folders { walk(&textures.join(folder), &mut files); @@ -321,7 +352,8 @@ impl HudAtlas { let s = p.to_string_lossy(); !s.contains("title/background") && !s.contains("realms") && !s.contains("presets") }); - let decode_one = |path: &PathBuf| -> Option<(PackedImage, Option)> { + type Decoded = (PackedImage, Option, Option<(u32, u32)>); + let decode_one = |path: &PathBuf| -> Option { let name = path .strip_prefix(&textures) .ok()? @@ -329,18 +361,29 @@ impl HudAtlas { .to_string_lossy() .replace('\\', "/"); let (w, mut h, pixels) = decode(path).ok()?; - let is_frame_strip = (name.starts_with("block/") || name.starts_with("item/")) && h > w; - let pixels = if is_frame_strip { + // Animated strips keep their first frame. + let frames = name.starts_with("block/") || name.starts_with("item/"); + let pixels = if frames && h > w { h = w; pixels[..(w * w * 4) as usize].to_vec() } else { pixels }; + // The default texture's size, when a pack's differs from it. + let gui_size = default_textures + .as_ref() + .and_then(|d| png_size(&d.join(format!("{name}.png")))) + .map(|(dw, dh)| (dw, if frames { dh.min(dw) } else { dh })) + .filter(|&size| size != (w, h)); let flags = fs::read_to_string(path.with_extension("png.mcmeta")) .ok() .and_then(|json| TextureFlags::from_mcmeta(&json)); - (w <= 1024 && (h <= 512 || name.starts_with("font/"))) - .then_some(((name, w, h, pixels), flags)) + let (gw, gh) = gui_size.unwrap_or((w, h)); + (gw <= 1024 && (gh <= 512 || name.starts_with("font/"))).then_some(( + (name, w, h, pixels), + flags, + gui_size, + )) }; let threads = std::thread::available_parallelism().map_or(2, |n| n.get()); let chunk = files.len().div_ceil(threads).max(1); @@ -357,11 +400,15 @@ impl HudAtlas { .collect() }); let mut flags = HashMap::new(); + let mut gui_sizes = HashMap::new(); let mut images: Vec = Vec::with_capacity(decoded.len()); - for (image, image_flags) in decoded { + for (image, image_flags, gui_size) in decoded { if let Some(f) = image_flags { flags.insert(image.0.clone(), f); } + if let Some(size) = gui_size { + gui_sizes.insert(image.0.clone(), size); + } images.push(image); } if full { @@ -405,6 +452,7 @@ impl HudAtlas { } let b = u32::from(bordered.contains(name)); let (px, py, w, h) = (px + b, py + b, w - 2 * b, h - 2 * b); + let (gw, gh) = gui_sizes.get(name).copied().unwrap_or((w, h)); sprites.insert( name.clone(), Rect { @@ -412,8 +460,8 @@ impl HudAtlas { v0: py as f32 / height as f32, u1: (px + w) as f32 / width as f32, v1: (py + h) as f32 / height as f32, - w, - h, + w: gw, + h: gh, }, ); } @@ -433,14 +481,15 @@ impl HudAtlas { .find(|a| a.layer == layer) .cloned() { - let image = animation.resized_pixels(animation.frame(0), rect.w, rect.h); + let (tw, th) = rect.texels((width, height)); + let image = animation.resized_pixels(animation.frame(0), tw, th); let x = (rect.u0 * width as f32).round() as usize; let y = (rect.v0 * height as f32).round() as usize; - for row in 0..rect.h as usize { + let row_bytes = tw as usize * 4; + for row in 0..th as usize { let dst = ((y + row) * width as usize + x) * 4; - let src = row * rect.w as usize * 4; - pixels[dst..dst + rect.w as usize * 4] - .copy_from_slice(&image[src..src + rect.w as usize * 4]); + let src = row * row_bytes; + pixels[dst..dst + row_bytes].copy_from_slice(&image[src..src + row_bytes]); } fire_animations.push((rect, animation)); } @@ -1191,7 +1240,8 @@ impl HudRenderer { if frame == *previous { continue; } - let pixels = animation.resized_pixels(frame, rect.w, rect.h); + let (w, h) = rect.texels((texture.width(), texture.height())); + let pixels = animation.resized_pixels(frame, w, h); uploads.texture( encoder, wgpu::TexelCopyTextureInfo { @@ -1204,8 +1254,8 @@ impl HudRenderer { }, aspect: wgpu::TextureAspect::All, }, - rect.w, - rect.h, + w, + h, &pixels, ); *previous = frame; @@ -1383,6 +1433,48 @@ mod tests { ); } } + fn write_png(root: &Path, name: &str, w: u32, h: u32) { + let path = root.join(format!("assets/minecraft/textures/{name}.png")); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + let mut encoder = png::Encoder::new(fs::File::create(path).unwrap(), w, h); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + let pixels = vec![255; (w * h * 4) as usize]; + encoder + .write_header() + .unwrap() + .write_image_data(&pixels) + .unwrap(); + } + #[test] + fn a_pack_texture_keeps_the_default_textures_gui_size() { + let temp = std::env::temp_dir().join(format!("horizon-gui-size-{}", std::process::id())); + let (defaults, pack) = (temp.join("defaults"), temp.join("pack")); + write_png(&defaults, "gui/container/inventory", 256, 256); + write_png(&defaults, "gui/sprites/widget/button", 200, 20); + write_png(&defaults, "block/stone", 16, 16); + write_png(&defaults, "item/compass", 16, 512); + // Faithful 64x's inventory (past the 512 rows a texture may have), + // 32x's button and stone, an animated strip, and a texture of its own. + write_png(&pack, "gui/container/inventory", 1024, 1024); + write_png(&pack, "gui/sprites/widget/button", 400, 40); + write_png(&pack, "block/stone", 32, 32); + write_png(&pack, "item/compass", 32, 1024); + write_png(&pack, "gui/sprites/pack_only", 30, 10); + let atlas = HudAtlas::build_over(&pack, &defaults).unwrap(); + let _ = fs::remove_dir_all(&temp); + let size = (atlas.width, atlas.height); + for (name, gui, texels) in [ + ("gui/container/inventory", (256, 256), (1024, 1024)), + ("gui/sprites/widget/button", (200, 20), (400, 40)), + ("block/stone", (16, 16), (32, 32)), + ("item/compass", (16, 16), (32, 32)), + ("gui/sprites/pack_only", (30, 10), (30, 10)), + ] { + let r = atlas.sprites[name]; + assert_eq!(((r.w, r.h), r.texels(size)), (gui, texels), "{name}"); + } + } #[test] fn the_default_textures_keep_a_4096_wide_atlas() { let images = sized(400, 64, 64); diff --git a/crates/horizon-client/src/ui.rs b/crates/horizon-client/src/ui.rs index b1ffab866..8ddfa91ff 100644 --- a/crates/horizon-client/src/ui.rs +++ b/crates/horizon-client/src/ui.rs @@ -7,9 +7,40 @@ use crate::{ }; use std::{collections::HashMap, path::Path, sync::RwLock, time::Instant}; -/// Nine-slice borders (left, top, right, bottom) from `.png.mcmeta` files. -static NINE_SLICE: RwLock>> = RwLock::new(None); +/// `GuiSpriteScaling.NineSlice`: the sprite's size in GUI pixels, whatever +/// its texture's resolution, its borders (left, top, right, bottom) in the +/// same units, and whether the edges and centre stretch rather than tile. +#[derive(Clone, Copy, Debug, PartialEq)] +struct NineSlice { + width: u32, + height: u32, + border: [u32; 4], + stretch_inner: bool, +} +/// Nine-slice scaling from `.png.mcmeta` files. +static NINE_SLICE: RwLock>> = RwLock::new(None); +/// A `gui.scaling` section of type `nine_slice`. +fn parse_nine_slice(v: &serde_json::Value) -> Option { + let s = &v["gui"]["scaling"]; + if s["type"] != "nine_slice" { + return None; + } + let size = |k: &str| s[k].as_u64().map(|n| n as u32); + let border = &s["border"]; + let border = if let Some(n) = border.as_u64() { + [n as u32; 4] + } else { + let g = |k: &str| border[k].as_u64().unwrap_or(0) as u32; + [g("left"), g("top"), g("right"), g("bottom")] + }; + Some(NineSlice { + width: size("width")?, + height: size("height")?, + border, + stretch_inner: s["stretch_inner"].as_bool().unwrap_or(false), + }) +} /// Read `gui.scaling` metadata for every GUI sprite under `root`. pub fn load_metadata(root: &Path) { let mut map = HashMap::new(); @@ -32,47 +63,48 @@ pub fn load_metadata(root: &Path) { let Ok(text) = std::fs::read_to_string(&p) else { continue; }; - let Ok(v) = serde_json::from_str::(&text) else { + let Some(nine_slice) = serde_json::from_str(&text) + .ok() + .as_ref() + .and_then(parse_nine_slice) + else { continue; }; - let s = &v["gui"]["scaling"]; - if s["type"] != "nine_slice" { - continue; - } - let border = &s["border"]; - let b = if let Some(n) = border.as_u64() { - [n as u32; 4] - } else { - let g = |k: &str| border[k].as_u64().unwrap_or(0) as u32; - [g("left"), g("top"), g("right"), g("bottom")] - }; let key = Path::new(stripped) .strip_prefix(&base) .map(|r| r.to_string_lossy().replace('\\', "/")) .unwrap_or_default(); - map.insert(key, b); + map.insert(key, nine_slice); } } *NINE_SLICE.write().unwrap_or_else(|e| e.into_inner()) = Some(map); } -fn border(sprite: &str) -> [u32; 4] { +/// The sprite's nine-slice metadata; without any (no resources loaded), its +/// GUI size and the widgets' usual borders. +fn scaling(sprite: &str, r: &Rect) -> NineSlice { NINE_SLICE .read() .unwrap_or_else(|e| e.into_inner()) .as_ref() .and_then(|m| m.get(sprite).copied()) - .unwrap_or(match sprite { - "gui/sprites/widget/button" - | "gui/sprites/widget/button_highlighted" - | "gui/sprites/widget/button_disabled" => [3; 4], - "gui/sprites/widget/slider_handle" | "gui/sprites/widget/slider_handle_highlighted" => { - [2, 2, 2, 3] - } - _ => [1; 4], + .unwrap_or(NineSlice { + width: r.w, + height: r.h, + border: match sprite { + "gui/sprites/widget/button" + | "gui/sprites/widget/button_highlighted" + | "gui/sprites/widget/button_disabled" => [3; 4], + "gui/sprites/widget/slider_handle" + | "gui/sprites/widget/slider_handle_highlighted" => [2, 2, 2, 3], + _ => [1; 4], + }, + stretch_inner: false, }) } -fn sub(r: Rect, x: f32, y: f32, w: f32, h: f32) -> Rect { - let (du, dv) = ((r.u1 - r.u0) / r.w as f32, (r.v1 - r.v0) / r.h as f32); +/// The region `[x, y, w, h]` of a sprite `size` GUI pixels large, in its +/// own units (`TextureAtlasSprite.getU(x / width)`). +fn sub(r: Rect, size: [f32; 2], [x, y, w, h]: [f32; 4]) -> Rect { + let (du, dv) = ((r.u1 - r.u0) / size[0], (r.v1 - r.v0) / size[1]); Rect { u0: r.u0 + x * du, v0: r.v0 + y * dv, @@ -82,8 +114,9 @@ fn sub(r: Rect, x: f32, y: f32, w: f32, h: f32) -> Rect { h: h as u32, } } -/// Tile `src` (a sub-rectangle of a sprite, in its pixels) over a target area. -fn tile(batch: &mut HudBatch, r: Rect, src: [f32; 4], dst: [f32; 4], color: u32) { +/// `blitTiledSprite`: `src` (a region of a sprite `size` large, in its +/// units) repeated over `dst` from its top left, the last row and column cut. +fn tile(batch: &mut HudBatch, r: Rect, size: [f32; 2], src: [f32; 4], dst: [f32; 4], color: u32) { let [sx, sy, sw, sh] = src; let [dx, dy, dw, dh] = dst; if sw <= 0.0 || sh <= 0.0 || dw <= 0.0 || dh <= 0.0 { @@ -95,13 +128,16 @@ fn tile(batch: &mut HudBatch, r: Rect, src: [f32; 4], dst: [f32; 4], color: u32) let mut x = 0.0; while x < dw { let w = sw.min(dw - x); - batch.rect_uv(dx + x, dy + y, w, h, sub(r, sx, sy, w, h), color); + batch.rect_uv(dx + x, dy + y, w, h, sub(r, size, [sx, sy, w, h]), color); x += sw; } y += sh; } } -/// GuiGraphics.blitSprite with nine-slice scaling (inner parts tiled). +/// `GuiGraphicsExtractor.blitNineSlicedSprite`: the corners at their size, +/// the edges and centre tiled (or stretched with `stretch_inner`), all in +/// the sprite's `gui.scaling` units, so a high-resolution pack's sprite draws +/// as the default one does. pub fn nine_slice( batch: &mut HudBatch, atlas: &HudAtlas, @@ -112,47 +148,73 @@ pub fn nine_slice( h: f32, color: u32, ) { - let Some(r) = atlas.sprites.get(sprite).copied() else { - return; + if let Some(r) = atlas.sprites.get(sprite) { + draw_nine_slice(batch, *r, scaling(sprite, r), [x, y, w, h], color); + } +} +fn draw_nine_slice( + batch: &mut HudBatch, + r: Rect, + n: NineSlice, + [x, y, w, h]: [f32; 4], + color: u32, +) { + let size = [n.width as f32, n.height as f32]; + let [sw, sh] = size; + let [l, t, rr, b] = n.border.map(|v| v as f32); + let (half_w, half_h) = ((w / 2.0).floor(), (h / 2.0).floor()); + let (l, rr, t, b) = (l.min(half_w), rr.min(half_w), t.min(half_h), b.min(half_h)); + // blitSprite(sprite, width, height, textureX, textureY, x, y, w, h). + let part = |batch: &mut HudBatch, tx: f32, ty: f32, dst: [f32; 4]| { + if dst[2] != 0.0 && dst[3] != 0.0 { + batch.rect_uv( + dst[0], + dst[1], + dst[2], + dst[3], + sub(r, size, [tx, ty, dst[2], dst[3]]), + color, + ); + } }; - let [l, t, rr, b] = border(sprite).map(|v| v as f32); - let (sw, sh) = (r.w as f32, r.h as f32); - let l = l.min(w / 2.0); - let rr = rr.min(w / 2.0); - let t = t.min(h / 2.0); - let b = b.min(h / 2.0); - let (cw, ch) = (w - l - rr, h - t - b); - let (scw, sch) = (sw - l - rr, sh - t - b); - // Corners. - batch.rect_uv(x, y, l, t, sub(r, 0.0, 0.0, l, t), color); - batch.rect_uv(x + w - rr, y, rr, t, sub(r, sw - rr, 0.0, rr, t), color); - batch.rect_uv(x, y + h - b, l, b, sub(r, 0.0, sh - b, l, b), color); - batch.rect_uv( - x + w - rr, - y + h - b, - rr, - b, - sub(r, sw - rr, sh - b, rr, b), - color, - ); - // Edges and centre. - tile(batch, r, [l, 0.0, scw, t], [x + l, y, cw, t], color); - tile( - batch, - r, - [l, sh - b, scw, b], - [x + l, y + h - b, cw, b], - color, - ); - tile(batch, r, [0.0, t, l, sch], [x, y + t, l, ch], color); - tile( - batch, - r, - [sw - rr, t, rr, sch], - [x + w - rr, y + t, rr, ch], - color, - ); - tile(batch, r, [l, t, scw, sch], [x + l, y + t, cw, ch], color); + // blitNineSliceInnerSegment. + let inner = |batch: &mut HudBatch, dst: [f32; 4], src: [f32; 4]| { + if dst[2] <= 0.0 || dst[3] <= 0.0 { + return; + } + if n.stretch_inner { + batch.rect_uv(dst[0], dst[1], dst[2], dst[3], sub(r, size, src), color); + } else { + tile(batch, r, size, src, dst, color); + } + }; + if w == sw && h == sh { + part(batch, 0.0, 0.0, [x, y, w, h]); + return; + } + if h == sh { + part(batch, 0.0, 0.0, [x, y, l, h]); + inner(batch, [x + l, y, w - rr - l, h], [l, 0.0, sw - rr - l, sh]); + part(batch, sw - rr, 0.0, [x + w - rr, y, rr, h]); + return; + } + if w == sw { + part(batch, 0.0, 0.0, [x, y, w, t]); + inner(batch, [x, y + t, w, h - b - t], [0.0, t, sw, sh - b - t]); + part(batch, 0.0, sh - b, [x, y + h - b, w, b]); + return; + } + let (cw, ch) = (w - rr - l, h - b - t); + let (scw, sch) = (sw - rr - l, sh - b - t); + part(batch, 0.0, 0.0, [x, y, l, t]); + inner(batch, [x + l, y, cw, t], [l, 0.0, scw, t]); + part(batch, sw - rr, 0.0, [x + w - rr, y, rr, t]); + part(batch, 0.0, sh - b, [x, y + h - b, l, b]); + inner(batch, [x + l, y + h - b, cw, b], [l, sh - b, scw, b]); + part(batch, sw - rr, sh - b, [x + w - rr, y + h - b, rr, b]); + inner(batch, [x, y + t, l, ch], [0.0, t, l, sch]); + inner(batch, [x + l, y + t, cw, ch], [l, t, scw, sch]); + inner(batch, [x + w - rr, y + t, rr, ch], [sw - rr, t, rr, sch]); } /// Repeat a whole texture with each copy drawn `size` GUI pixels square. pub fn tiled( @@ -169,7 +231,6 @@ pub fn tiled( let Some(r) = atlas.sprites.get(sprite).copied() else { return; }; - let scale = r.w as f32 / size; let mut yy = 0.0; while yy < h { let th = size.min(h - yy); @@ -181,7 +242,7 @@ pub fn tiled( y + yy, tw, th, - sub(r, 0.0, 0.0, tw * scale, th * scale), + sub(r, [size, size], [0.0, 0.0, tw, th]), color, ); xx += size; @@ -1128,6 +1189,130 @@ impl EditBox { #[cfg(test)] mod tests { use super::*; + + /// The quads' destination rectangles and their UVs. + fn quads(batch: &HudBatch) -> Vec<([f32; 4], [f32; 4])> { + batch + .vertices + .chunks(6) + .map(|q| { + let (a, c) = (q[0], q[2]); + ( + [a.pos[0], a.pos[1], c.pos[0], c.pos[1]], + [a.uv[0], a.uv[1], c.uv[0], c.uv[1]], + ) + }) + .collect() + } + /// Destination and UV rectangles equal to within f32 rounding. + fn assert_quad(actual: ([f32; 4], [f32; 4]), expected: ([f32; 4], [f32; 4])) { + let close = |a: [f32; 4], b: [f32; 4]| a.iter().zip(b).all(|(a, b)| (a - b).abs() < 1e-5); + assert!( + close(actual.0, expected.0) && close(actual.1, expected.1), + "{actual:?} != {expected:?}" + ); + } + /// A sprite filling the atlas, `w x h` texels as a 32x pack draws it. + fn sprite(w: u32, h: u32) -> Rect { + Rect { + u0: 0.0, + v0: 0.0, + u1: 1.0, + v1: 1.0, + w, + h, + } + } + fn faithful(json: &str) -> NineSlice { + parse_nine_slice(&serde_json::from_str(json).unwrap()).unwrap() + } + #[test] + fn a_high_resolution_button_slices_in_its_gui_units() { + // Faithful 32x's widget/button: 400x40 texels, gui.scaling 200x20. + let n = faithful( + r#"{"gui":{"scaling":{"type":"nine_slice","width":200,"height":20, + "border":{"left":20,"top":4,"right":20,"bottom":4}}}}"#, + ); + let mut batch = HudBatch::new([640, 480]); + draw_nine_slice( + &mut batch, + sprite(400, 40), + n, + [10.0, 5.0, 150.0, 20.0], + u32::MAX, + ); + let q = quads(&batch); + // Full height: left border, the centre tiled, right border + // (blitNineSlicedSprite's height == nineSlice.height case). + assert_quad(q[0], ([10.0, 5.0, 30.0, 25.0], [0.0, 0.0, 0.1, 1.0])); + assert_quad(q[1], ([30.0, 5.0, 140.0, 25.0], [0.1, 0.0, 0.65, 1.0])); + assert_quad(q[2], ([140.0, 5.0, 160.0, 25.0], [0.9, 0.0, 1.0, 1.0])); + assert_eq!(q.len(), 3); + } + #[test] + fn nine_slice_corners_and_a_stretched_centre() { + // Faithful 32x's tooltip/frame: 200x200 texels, 100x100, border 12, stretched. + let n = faithful( + r#"{"gui":{"scaling":{"type":"nine_slice","width":100,"height":100,"border":12,"stretch_inner":true}}}"#, + ); + let mut batch = HudBatch::new([640, 480]); + draw_nine_slice( + &mut batch, + sprite(200, 200), + n, + [0.0, 0.0, 300.0, 40.0], + u32::MAX, + ); + let q = quads(&batch); + assert_eq!(q.len(), 9); + // Top left corner: 12 GUI pixels, 12/100 of the sprite. + assert_quad(q[0], ([0.0, 0.0, 12.0, 12.0], [0.0, 0.0, 0.12, 0.12])); + // The centre is one stretched quad (blitNineSliceInnerSegment, stretch_inner). + assert_quad(q[7], ([12.0, 12.0, 288.0, 28.0], [0.12, 0.12, 0.88, 0.88])); + // Bottom right corner. + assert_quad(q[5], ([288.0, 28.0, 300.0, 40.0], [0.88, 0.88, 1.0, 1.0])); + } + #[test] + fn a_sprite_drawn_at_its_own_size_is_one_quad() { + let n = NineSlice { + width: 50, + height: 50, + border: [10; 4], + stretch_inner: false, + }; + let mut batch = HudBatch::new([640, 480]); + draw_nine_slice( + &mut batch, + sprite(100, 100), + n, + [4.0, 4.0, 50.0, 50.0], + u32::MAX, + ); + let q = quads(&batch); + assert_eq!(q.len(), 1); + assert_quad(q[0], ([4.0, 4.0, 54.0, 54.0], [0.0, 0.0, 1.0, 1.0])); + } + #[test] + fn borders_shrink_to_half_the_drawn_size() { + let n = NineSlice { + width: 20, + height: 20, + border: [8; 4], + stretch_inner: true, + }; + let mut batch = HudBatch::new([640, 480]); + // 9 wide: borders of floor(9 / 2) = 4, as vanilla's integer division. + draw_nine_slice( + &mut batch, + sprite(20, 20), + n, + [0.0, 0.0, 9.0, 30.0], + u32::MAX, + ); + let q = quads(&batch); + assert_quad(q[0], ([0.0, 0.0, 4.0, 8.0], [0.0, 0.0, 0.2, 0.4])); + assert_quad(q[2], ([5.0, 0.0, 9.0, 8.0], [0.8, 0.0, 1.0, 0.4])); + } #[test] fn append_fields_highlight_the_whole_value_and_blink_their_cursor() { use crate::hud::Blend; From 7c42cc63ce78a1b181033286dac63df31e1c0605 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:30:27 +0200 Subject: [PATCH 035/408] parity: leave out of the prebuild probes that no longer exist A record naming an example since renamed or deleted made the whole Cargo run fail ("no example target named ..."), so no probe was prebuilt and every harness built its own: the probe binaries rename ~250 of them. Co-Authored-By: Claude Opus 5.5 --- tests/test_parity_runner.py | 5 ++++- tools/parity.py | 10 +++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/tests/test_parity_runner.py b/tests/test_parity_runner.py index beffb557d..a9b7ff595 100644 --- a/tests/test_parity_runner.py +++ b/tests/test_parity_runner.py @@ -35,10 +35,13 @@ class ParityRunnerTests(unittest.TestCase): *parity.artifacts_of(["cargo", "build", "--release", "-p", "horizon-world", "--bin", "horizon-world"]), *parity.artifacts_of(["cargo", "build", "--release", "--bin", "horizon-world"]), *parity.artifacts_of(["cargo", "run", "--profile", "fast", "-p", "horizon-client", "--example", "c"]), + *parity.artifacts_of(["cargo", "build", "--release", "-p", "horizon-world", "--example", "renamed"]), ["example", "old", "release"], # recorded before selections were kept: its own crate's -p ["example", "unknown", "release"], # no longer in the workspace: left to its harness ] - self.assertEqual(parity.prebuild_commands(artifacts, {("example", "old"): "horizon-world"}), [ + packages = {("example", "a"): "horizon-world", ("example", "b"): "horizon-world", ("example", "c"): "horizon-client", + ("bin", "horizon-world"): "horizon-world", ("example", "old"): "horizon-world"} + self.assertEqual(parity.prebuild_commands(artifacts, packages), [ ["cargo", "build", "--locked", "--profile", "fast", "-p", "horizon-client", "--example", "c"], ["cargo", "build", "--locked", "--profile", "release", "--bin", "horizon-world"], ["cargo", "build", "--locked", "--profile", "release", "-p", "horizon-world", "--bin", "horizon-world"], diff --git a/tools/parity.py b/tools/parity.py index 5dbf13554..4113cc791 100644 --- a/tools/parity.py +++ b/tools/parity.py @@ -555,10 +555,14 @@ def prebuild_commands(artifacts, packages=None): """The Cargo runs that build the recorded probes exactly as their harnesses do: one per profile, package and feature selection, and whether examples are among the command's targets (see artifacts_of). - A [kind, name, profile] record from before selections were kept is taken as built with `-p` and its own crate, - as nearly every harness does (packages: target_packages()); the harness's next run records the real one.""" + packages: target_packages(). Records of targets that no longer exist (a probe renamed or deleted since a harness + ran it) are left out, since one unknown target fails its whole Cargo run. A [kind, name, profile] record from + before selections were kept is taken as built with `-p` and its own crate, as nearly every harness does; the + harness's next run records the real one.""" groups = {} for artifact in artifacts: + if packages and artifact[1] and tuple(artifact[:2]) not in packages: + continue if len(artifact) == 3 and (packages or {}).get(tuple(artifact[:2])): kind, name, profile = artifact artifact = [kind, name, profile, ["-p", packages[(kind, name)]], kind == "example"] @@ -578,7 +582,7 @@ def prebuild(artifacts, jobs): environment = run_environment() environment["CARGO_BUILD_JOBS"] = str(jobs) errors = "" - packages = target_packages() if any(len(artifact) == 3 for artifact in artifacts) else None + packages = target_packages() for command in prebuild_commands(artifacts, packages): result = subprocess.run(command, cwd=ROOT, env=environment, capture_output=True, text=True) if result.returncode: From 1960dc6eb26600d32145eecece3d494ee4f9d019 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:30:31 +0200 Subject: [PATCH 036/408] AGENTS.md: agents never add release-now Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index d869aed2a..9534fba83 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -21,7 +21,7 @@ Feature → files → harness for the most-changed areas: [docs/architecture.md] - Horizon-only features follow [docs/design-system.md](docs/design-system.md) and are off by default where they would change the vanilla look. - Small PRs (< ~500 lines). Labels: `feature` (players get something new), `skip-release` (they see no - change), none for a fix, `release-now` for crash fixes. Every merge to main ships + change), none for a fix. Agents never add `release-now`: the maintainer decides it. Every merge to main ships ([docs/release-flow.md](docs/release-flow.md)). - Contributors first: `gh pr list --state open --search ` before you start; never duplicate theirs. From fdae4b895c6d3e64464bcafa64b825f15b5ad777 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 14:21:46 +0200 Subject: [PATCH 037/408] horizon-world probes: one binary, `probe ` The 168 horizon-world examples the parity harnesses run become modules of one example, examples/probe, that dispatches on its first argument; crate::args() gives each the command line its example saw. Linking ~170 binaries, each instantiating horizon-world's generics again, was most of the parity job's probe build (review plan, section 1). The harnesses build `--example probe` and run `probe ...`. tools/parity.py counts only the probes a harness ran, and the support modules they name, as its dependencies, so editing one probe still reruns only its own harnesses (and PARITY_RUST_SCOPE keeps working). The six manual tools (benches, loot_fill, structure_blocks, vanilla_diff, attribute_memory, behaviour_load_profile) stay separate examples. Co-Authored-By: Claude Opus 5.5 --- .../{ => probe}/active_effect_tick_fixture.rs | 6 +- .../{ => probe}/active_effects_fixture.rs | 6 +- .../examples/{ => probe}/anchor_fixture.rs | 4 +- .../examples/{ => probe}/attribute_fixture.rs | 4 +- .../{ => probe}/attribute_health_fixture.rs | 6 +- .../attribute_map_queries_fixture.rs | 4 +- .../{ => probe}/attribute_updates_fixture.rs | 6 +- .../{ => probe}/basic_feature_fixture.rs | 4 +- .../{ => probe}/biome_chunk_fixture.rs | 4 +- .../{ => probe}/biome_generation_fixture.rs | 4 +- .../{ => probe}/biome_placement_fixture.rs | 4 +- .../{ => probe}/biome_source_codec_fixture.rs | 4 +- .../{ => probe}/biome_source_fixture.rs | 4 +- .../{ => probe}/biome_temperature_fixture.rs | 4 +- .../block_collision_scan_fixture.rs | 4 +- .../block_entity_storage_fixture.rs | 4 +- .../{ => probe}/block_landing_fixture.rs | 4 +- .../{ => probe}/block_properties_fixture.rs | 4 +- .../{ => probe}/block_push_fixture.rs | 4 +- .../{ => probe}/block_state_codec_fixture.rs | 4 +- .../{ => probe}/block_support_fixture.rs | 4 +- .../{ => probe}/block_survival_fixture.rs | 4 +- .../{ => probe}/block_update_fixture.rs | 4 +- .../blocking_item_damage_fixture.rs | 4 +- .../{ => probe}/blocking_rules_fixture.rs | 4 +- .../{ => probe}/bulk_section_fixture.rs | 4 +- .../{ => probe}/bundle_weight_fixture.rs | 4 +- .../{ => probe}/canyon_carver_fixture.rs | 4 +- .../{ => probe}/carving_geometry_fixture.rs | 4 +- .../{ => probe}/carving_mask_fixture.rs | 4 +- .../{ => probe}/cave_carver_fixture.rs | 4 +- .../examples/{ => probe}/chunk_dump.rs | 4 +- .../{ => probe}/chunk_stage_fixture.rs | 4 +- .../{ => probe}/chunk_status_fixture.rs | 4 +- .../examples/{ => probe}/climbing_fixture.rs | 4 +- .../{ => probe}/collision_context_fixture.rs | 4 +- .../examples/{ => probe}/collision_fixture.rs | 8 +- .../{ => probe}/combat_rules_fixture.rs | 4 +- .../component_durability_fixture.rs | 4 +- .../{ => probe}/component_patch_fixture.rs | 4 +- .../consumable_emission_fixture.rs | 4 +- .../{ => probe}/consumable_fixture.rs | 4 +- .../{ => probe}/consume_effect_fixture.rs | 4 +- .../{ => probe}/damage_immunity_fixture.rs | 4 +- .../{ => probe}/damage_reduction_fixture.rs | 4 +- .../{ => probe}/damage_source_fixture.rs | 4 +- .../examples/{ => probe}/datafix_world.rs | 6 +- .../{ => probe}/decoration_fixture.rs | 4 +- .../{ => probe}/decoration_region_fixture.rs | 7 +- .../{ => probe}/dynamic_support_fixture.rs | 4 +- .../{ => probe}/edge_backoff_fixture.rs | 4 +- .../effect_attribute_modifiers_fixture.rs | 4 +- .../effect_notifications_fixture.rs | 6 +- .../{ => probe}/effect_sync_fixture.rs | 4 +- .../{ => probe}/entity_attribute_fixture.rs | 4 +- .../{ => probe}/entity_collision_fixture.rs | 4 +- .../{ => probe}/entity_fluid_fixture.rs | 4 +- .../{ => probe}/entity_move_fixture.rs | 4 +- .../{ => probe}/entity_obstruction_fixture.rs | 4 +- .../{ => probe}/extra_items_fixture.rs | 4 +- .../{ => probe}/face_support_fixture.rs | 4 +- .../{ => probe}/face_visibility_fixture.rs | 4 +- .../{ => probe}/fall_damage_fixture.rs | 4 +- .../{ => probe}/feature_catalog_fixture.rs | 4 +- .../{ => probe}/feature_graph_fixture.rs | 4 +- .../{ => probe}/feature_placement_fixture.rs | 7 +- .../{ => probe}/feature_region_fixture.rs | 4 +- .../{ => probe}/feature_sort_fixture.rs | 4 +- .../{ => probe}/fill_layer_fixture.rs | 4 +- .../examples/{ => probe}/fluid_box_fixture.rs | 4 +- .../examples/{ => probe}/fluid_fixture.rs | 4 +- .../{ => probe}/fluid_flow_fixture.rs | 4 +- .../{ => probe}/fluid_occupancy_fixture.rs | 4 +- .../{ => probe}/fluid_shape_fixture.rs | 4 +- .../examples/{ => probe}/food_fixture.rs | 4 +- .../{ => probe}/food_properties_fixture.rs | 4 +- .../{ => probe}/food_storage_fixture.rs | 4 +- .../{ => probe}/ground_state_fixture.rs | 4 +- .../{ => probe}/height_provider_fixture.rs | 4 +- .../examples/{ => probe}/heightmap_fixture.rs | 4 +- .../{ => probe}/interaction_shape_fixture.rs | 4 +- .../{ => probe}/inventory_pickup_fixture.rs | 4 +- .../{ => probe}/inventory_tick_fixture.rs | 4 +- .../{ => probe}/inventory_use_fixture.rs | 4 +- .../inventory_use_start_fixture.rs | 4 +- .../{ => probe}/item_after_use_fixture.rs | 4 +- .../{ => probe}/item_blocking_fixture.rs | 4 +- .../{ => probe}/item_cooldowns_fixture.rs | 4 +- .../{ => probe}/item_durability_fixture.rs | 4 +- .../{ => probe}/item_particles_fixture.rs | 4 +- .../{ => probe}/item_stack_storage_fixture.rs | 4 +- .../{ => probe}/item_template_fixture.rs | 4 +- .../{ => probe}/item_use_catalog_fixture.rs | 4 +- .../examples/{ => probe}/item_use_fixture.rs | 4 +- .../{ => probe}/item_use_lifecycle_fixture.rs | 4 +- .../{ => probe}/item_use_start_fixture.rs | 4 +- .../{ => probe}/java_hash_map_fixture.rs | 4 +- .../{ => probe}/java_identity_map_fixture.rs | 6 +- .../{ => probe}/level_place_fixture.rs | 4 +- .../{ => probe}/level_shape_fixture.rs | 4 +- .../live_attribute_updates_fixture.rs | 4 +- .../{ => probe}/live_attributes_fixture.rs | 4 +- .../{ => probe}/living_air_fixture.rs | 4 +- .../{ => probe}/living_damage_fixture.rs | 4 +- .../{ => probe}/living_fall_fixture.rs | 4 +- .../{ => probe}/living_fluid_fixture.rs | 4 +- .../{ => probe}/living_health_fixture.rs | 4 +- .../{ => probe}/living_hurt_fixture.rs | 4 +- .../{ => probe}/living_landing_fixture.rs | 4 +- .../{ => probe}/living_motion_fixture.rs | 4 +- crates/horizon-world/examples/probe/main.rs | 384 ++++++++++++++++++ .../{ => probe}/material_condition_fixture.rs | 4 +- .../{ => probe}/material_extension_fixture.rs | 4 +- .../{ => probe}/material_stage_fixture.rs | 4 +- .../{ => probe}/material_surface_fixture.rs | 4 +- .../{ => probe}/movement_emission_fixture.rs | 4 +- .../{ => probe}/movement_registry_fixture.rs | 4 +- .../{ => probe}/movement_support_fixture.rs | 4 +- .../{ => probe}/object_open_map_fixture.rs | 4 +- .../{ => probe}/object_open_set_fixture.rs | 4 +- .../{ => probe}/piston_movement_fixture.rs | 4 +- .../{ => probe}/piston_shape_fixture.rs | 4 +- .../examples/{ => probe}/placement_fixture.rs | 7 +- .../{ => probe}/player_equipment_fixture.rs | 4 +- .../{ => probe}/player_food_fixture.rs | 4 +- .../{ => probe}/player_health_fixture.rs | 4 +- .../{ => probe}/player_hurt_fixture.rs | 4 +- .../{ => probe}/player_inventory_fixture.rs | 4 +- .../{ => probe}/player_travel_fixture.rs | 4 +- .../{ => probe}/portal_travel_fixture.rs | 4 +- .../registered_player_combat_fixture.rs | 4 +- .../registry_collision_scan_fixture.rs | 4 +- .../{ => probe}/registry_fall_ray_fixture.rs | 4 +- .../{ => probe}/registry_fluid_fixture.rs | 4 +- .../{ => probe}/replace_block_fixture.rs | 4 +- .../{ => probe}/restitution_fixture.rs | 4 +- .../{ => probe}/retrogen_data_fixture.rs | 4 +- .../examples/{ => probe}/rule_test_fixture.rs | 4 +- .../{ => probe}/scattered_ore_fixture.rs | 4 +- .../server_player_combat_fixture.rs | 6 +- .../server_player_damage_fixture.rs | 4 +- .../{ => probe}/simple_block_fixture.rs | 4 +- .../{ => probe}/simple_container_fixture.rs | 4 +- .../examples/{ => probe}/spawn_origin.rs | 4 +- .../{ => probe}/state_provider_fixture.rs | 4 +- .../{ => probe}/status_effect_fixture.rs | 4 +- .../{ => probe}/status_tick_fixture.rs | 4 +- .../stepped_interpolation_fixture.rs | 4 +- .../{ => probe}/stored_consume_fixture.rs | 6 +- .../stored_effect_attributes_fixture.rs | 4 +- .../stored_effect_notifications_fixture.rs | 4 +- .../{ => probe}/structure_density_fixture.rs | 4 +- .../{ => probe}/suffocation_fixture.rs | 4 +- .../{ => probe}/support/decoration_storage.rs | 0 .../{ => probe}/support/placement_queries.rs | 0 .../examples/{ => probe}/swimming_fixture.rs | 4 +- .../{ => probe}/synced_bytes_fixture.rs | 4 +- .../{ => probe}/synced_floats_fixture.rs | 4 +- .../{ => probe}/teleport_consume_fixture.rs | 4 +- .../examples/{ => probe}/terrain_fixture.rs | 4 +- .../examples/{ => probe}/tick_fixture.rs | 8 +- .../{ => probe}/tree_feature_fixture.rs | 4 +- .../{ => probe}/use_flag_reaction_fixture.rs | 4 +- .../{ => probe}/use_remainder_fixture.rs | 4 +- .../{ => probe}/value_provider_fixture.rs | 4 +- .../{ => probe}/view_direction_fixture.rs | 4 +- .../{ => probe}/water_splash_fixture.rs | 4 +- .../{ => probe}/world_border_fixture.rs | 4 +- .../examples/{ => probe}/world_fixture.rs | 8 +- .../examples/{ => probe}/world_ray_fixture.rs | 4 +- .../{ => probe}/worldgen_random_fixture.rs | 4 +- docs/parity-workflow.md | 2 + docs/world-generation.md | 2 +- tests/test_parity_runner.py | 15 + tools/block_update_harness.py | 4 +- tools/parity.py | 36 +- tools/test_active_effect_tick_parity.py | 8 +- tools/test_active_effects_parity.py | 8 +- tools/test_anchor_parity.py | 8 +- tools/test_attribute_health_parity.py | 8 +- tools/test_attribute_map_queries_parity.py | 10 +- tools/test_attribute_parity.py | 8 +- tools/test_attribute_updates_parity.py | 8 +- tools/test_basic_feature_parity.py | 8 +- tools/test_biome_chunk_parity.py | 8 +- tools/test_biome_generation_parity.py | 8 +- tools/test_biome_placement_parity.py | 8 +- tools/test_biome_source_codec_parity.py | 8 +- tools/test_biome_source_parity.py | 8 +- tools/test_biome_temperature_parity.py | 8 +- tools/test_block_collision_scan_parity.py | 8 +- tools/test_block_entity_storage_parity.py | 8 +- tools/test_block_landing_parity.py | 8 +- tools/test_block_properties_parity.py | 8 +- tools/test_block_push_parity.py | 8 +- tools/test_block_state_codec_parity.py | 8 +- tools/test_block_support_parity.py | 8 +- tools/test_block_survival_parity.py | 8 +- tools/test_blocking_item_damage_parity.py | 8 +- tools/test_blocking_rules_parity.py | 8 +- tools/test_bulk_section_parity.py | 8 +- tools/test_bundle_weight_parity.py | 8 +- tools/test_canyon_carver_parity.py | 8 +- tools/test_carving_geometry_parity.py | 8 +- tools/test_carving_mask_parity.py | 8 +- tools/test_cave_carver_parity.py | 8 +- tools/test_chunk_generation_parity.py | 8 +- tools/test_chunk_stage_parity.py | 8 +- tools/test_chunk_status_parity.py | 8 +- tools/test_climbing_parity.py | 4 +- tools/test_collision_context_parity.py | 8 +- tools/test_collision_parity.py | 8 +- tools/test_combat_rules_parity.py | 8 +- tools/test_component_durability_parity.py | 8 +- tools/test_component_patch_parity.py | 8 +- tools/test_consumable_emission_parity.py | 8 +- tools/test_consumable_parity.py | 8 +- tools/test_consume_effect_parity.py | 8 +- tools/test_contextual_collision_parity.py | 8 +- tools/test_damage_immunity_parity.py | 8 +- tools/test_damage_reduction_parity.py | 8 +- tools/test_damage_source_parity.py | 8 +- tools/test_datafix_parity.py | 11 +- tools/test_decoration_parity.py | 8 +- tools/test_decoration_region_parity.py | 8 +- tools/test_dynamic_support_parity.py | 8 +- tools/test_edge_backoff_parity.py | 8 +- .../test_effect_attribute_modifiers_parity.py | 8 +- tools/test_effect_notifications_parity.py | 8 +- tools/test_effect_sync_parity.py | 8 +- tools/test_entity_attribute_parity.py | 8 +- tools/test_entity_collision_parity.py | 8 +- tools/test_entity_fluid_parity.py | 8 +- tools/test_entity_fluid_tick_parity.py | 8 +- tools/test_entity_move_parity.py | 8 +- tools/test_entity_obstruction_parity.py | 8 +- tools/test_extra_items_parity.py | 8 +- tools/test_face_support_parity.py | 8 +- tools/test_face_visibility_parity.py | 8 +- tools/test_fall_damage_parity.py | 8 +- tools/test_feature_catalog_parity.py | 8 +- tools/test_feature_graph_parity.py | 8 +- tools/test_feature_placement_parity.py | 8 +- tools/test_feature_region_parity.py | 8 +- tools/test_feature_sort_parity.py | 8 +- tools/test_fill_layer_parity.py | 8 +- tools/test_fluid_box_parity.py | 8 +- tools/test_fluid_flow_parity.py | 8 +- tools/test_fluid_occupancy_parity.py | 4 +- tools/test_fluid_parity.py | 8 +- tools/test_fluid_shape_parity.py | 8 +- tools/test_food_parity.py | 8 +- tools/test_food_properties_parity.py | 8 +- tools/test_food_storage_parity.py | 8 +- tools/test_free_space_parity.py | 8 +- tools/test_ground_support_parity.py | 6 +- tools/test_height_provider_parity.py | 8 +- tools/test_heightmap_parity.py | 8 +- tools/test_interaction_shape_parity.py | 8 +- tools/test_inventory_pickup_parity.py | 8 +- tools/test_inventory_tick_parity.py | 8 +- tools/test_inventory_use_parity.py | 8 +- tools/test_inventory_use_start_parity.py | 8 +- tools/test_item_after_use_parity.py | 8 +- tools/test_item_blocking_parity.py | 8 +- tools/test_item_cooldowns_parity.py | 8 +- tools/test_item_durability_parity.py | 8 +- tools/test_item_particles_parity.py | 8 +- tools/test_item_stack_storage_parity.py | 8 +- tools/test_item_template_parity.py | 8 +- tools/test_item_use_catalog_parity.py | 8 +- tools/test_item_use_lifecycle_parity.py | 8 +- tools/test_item_use_parity.py | 8 +- tools/test_item_use_start_parity.py | 8 +- tools/test_java_hash_map_parity.py | 8 +- tools/test_java_identity_map_parity.py | 8 +- tools/test_level_place_parity.py | 4 +- tools/test_level_shape_parity.py | 4 +- tools/test_liquid_collision_parity.py | 8 +- tools/test_live_attribute_updates_parity.py | 10 +- tools/test_live_attributes_parity.py | 8 +- tools/test_living_air_parity.py | 8 +- tools/test_living_damage_parity.py | 8 +- tools/test_living_fall_parity.py | 8 +- tools/test_living_fluid_parity.py | 8 +- tools/test_living_health_parity.py | 8 +- tools/test_living_hurt_parity.py | 8 +- tools/test_living_landing_parity.py | 8 +- tools/test_living_motion_parity.py | 8 +- tools/test_material_condition_parity.py | 8 +- tools/test_material_extension_parity.py | 6 +- tools/test_material_rule_library_parity.py | 8 +- tools/test_material_stage_parity.py | 4 +- tools/test_material_surface_parity.py | 8 +- tools/test_movement_emission_parity.py | 8 +- tools/test_movement_registry_parity.py | 8 +- tools/test_movement_support_parity.py | 8 +- tools/test_nether_portal_parity.py | 4 +- tools/test_object_open_map_parity.py | 8 +- tools/test_object_open_set_parity.py | 8 +- tools/test_piston_movement_parity.py | 8 +- tools/test_piston_shape_parity.py | 8 +- tools/test_placement_parity.py | 8 +- tools/test_player_equipment_parity.py | 8 +- tools/test_player_food_parity.py | 8 +- tools/test_player_health_parity.py | 8 +- tools/test_player_hurt_parity.py | 8 +- tools/test_player_inventory_parity.py | 8 +- tools/test_player_travel_parity.py | 8 +- tools/test_powder_snow_collision_parity.py | 8 +- tools/test_registered_entity_fluid_parity.py | 4 +- tools/test_registered_player_combat_parity.py | 8 +- tools/test_registry_collision_scan_parity.py | 8 +- tools/test_registry_fall_ray_parity.py | 4 +- tools/test_registry_fluid_parity.py | 4 +- tools/test_replace_block_parity.py | 8 +- tools/test_restitution_parity.py | 8 +- tools/test_retrogen_chunk_parity.py | 8 +- tools/test_retrogen_data_parity.py | 8 +- tools/test_rule_test_parity.py | 8 +- tools/test_scaffolding_collision_parity.py | 8 +- tools/test_scattered_ore_parity.py | 8 +- tools/test_server_player_combat_parity.py | 10 +- tools/test_server_player_damage_parity.py | 8 +- tools/test_simple_block_parity.py | 8 +- tools/test_simple_container_parity.py | 8 +- tools/test_state_provider_parity.py | 8 +- tools/test_status_effect_parity.py | 8 +- tools/test_status_tick_parity.py | 8 +- tools/test_stepped_interpolation_parity.py | 2 +- tools/test_stored_consume_parity.py | 8 +- tools/test_stored_effect_attributes_parity.py | 8 +- ...test_stored_effect_notifications_parity.py | 10 +- tools/test_structure_density_parity.py | 8 +- tools/test_suffocation_parity.py | 8 +- tools/test_swimming_parity.py | 8 +- tools/test_synced_bytes_parity.py | 8 +- tools/test_synced_floats_parity.py | 8 +- tools/test_teleport_consume_parity.py | 8 +- tools/test_terrain_parity.py | 8 +- tools/test_tick_parity.py | 8 +- tools/test_tree_feature_parity.py | 8 +- tools/test_use_flag_reaction_parity.py | 8 +- tools/test_use_remainder_parity.py | 8 +- tools/test_value_provider_parity.py | 8 +- tools/test_view_direction_parity.py | 8 +- tools/test_water_splash_parity.py | 8 +- tools/test_world_border_parity.py | 8 +- tools/test_world_collision_check_parity.py | 8 +- tools/test_world_edge_backoff_parity.py | 8 +- tools/test_world_movement_parity.py | 8 +- tools/test_world_parity.py | 4 +- tools/test_world_ray_parity.py | 8 +- tools/test_world_spawn_parity.py | 4 +- tools/test_worldgen_random_parity.py | 8 +- 355 files changed, 1482 insertions(+), 1061 deletions(-) rename crates/horizon-world/examples/{ => probe}/active_effect_tick_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/active_effects_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/anchor_fixture.rs (94%) rename crates/horizon-world/examples/{ => probe}/attribute_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/attribute_health_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/attribute_map_queries_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/attribute_updates_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/basic_feature_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/biome_chunk_fixture.rs (96%) rename crates/horizon-world/examples/{ => probe}/biome_generation_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/biome_placement_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/biome_source_codec_fixture.rs (95%) rename crates/horizon-world/examples/{ => probe}/biome_source_fixture.rs (95%) rename crates/horizon-world/examples/{ => probe}/biome_temperature_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/block_collision_scan_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/block_entity_storage_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/block_landing_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/block_properties_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/block_push_fixture.rs (96%) rename crates/horizon-world/examples/{ => probe}/block_state_codec_fixture.rs (94%) rename crates/horizon-world/examples/{ => probe}/block_support_fixture.rs (94%) rename crates/horizon-world/examples/{ => probe}/block_survival_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/block_update_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/blocking_item_damage_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/blocking_rules_fixture.rs (96%) rename crates/horizon-world/examples/{ => probe}/bulk_section_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/bundle_weight_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/canyon_carver_fixture.rs (96%) rename crates/horizon-world/examples/{ => probe}/carving_geometry_fixture.rs (96%) rename crates/horizon-world/examples/{ => probe}/carving_mask_fixture.rs (95%) rename crates/horizon-world/examples/{ => probe}/cave_carver_fixture.rs (96%) rename crates/horizon-world/examples/{ => probe}/chunk_dump.rs (99%) rename crates/horizon-world/examples/{ => probe}/chunk_stage_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/chunk_status_fixture.rs (95%) rename crates/horizon-world/examples/{ => probe}/climbing_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/collision_context_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/collision_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/combat_rules_fixture.rs (96%) rename crates/horizon-world/examples/{ => probe}/component_durability_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/component_patch_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/consumable_emission_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/consumable_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/consume_effect_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/damage_immunity_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/damage_reduction_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/damage_source_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/datafix_world.rs (92%) rename crates/horizon-world/examples/{ => probe}/decoration_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/decoration_region_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/dynamic_support_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/edge_backoff_fixture.rs (96%) rename crates/horizon-world/examples/{ => probe}/effect_attribute_modifiers_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/effect_notifications_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/effect_sync_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/entity_attribute_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/entity_collision_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/entity_fluid_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/entity_move_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/entity_obstruction_fixture.rs (96%) rename crates/horizon-world/examples/{ => probe}/extra_items_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/face_support_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/face_visibility_fixture.rs (96%) rename crates/horizon-world/examples/{ => probe}/fall_damage_fixture.rs (96%) rename crates/horizon-world/examples/{ => probe}/feature_catalog_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/feature_graph_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/feature_placement_fixture.rs (94%) rename crates/horizon-world/examples/{ => probe}/feature_region_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/feature_sort_fixture.rs (93%) rename crates/horizon-world/examples/{ => probe}/fill_layer_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/fluid_box_fixture.rs (96%) rename crates/horizon-world/examples/{ => probe}/fluid_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/fluid_flow_fixture.rs (96%) rename crates/horizon-world/examples/{ => probe}/fluid_occupancy_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/fluid_shape_fixture.rs (96%) rename crates/horizon-world/examples/{ => probe}/food_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/food_properties_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/food_storage_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/ground_state_fixture.rs (96%) rename crates/horizon-world/examples/{ => probe}/height_provider_fixture.rs (93%) rename crates/horizon-world/examples/{ => probe}/heightmap_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/interaction_shape_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/inventory_pickup_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/inventory_tick_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/inventory_use_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/inventory_use_start_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/item_after_use_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/item_blocking_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/item_cooldowns_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/item_durability_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/item_particles_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/item_stack_storage_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/item_template_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/item_use_catalog_fixture.rs (96%) rename crates/horizon-world/examples/{ => probe}/item_use_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/item_use_lifecycle_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/item_use_start_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/java_hash_map_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/java_identity_map_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/level_place_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/level_shape_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/live_attribute_updates_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/live_attributes_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/living_air_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/living_damage_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/living_fall_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/living_fluid_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/living_health_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/living_hurt_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/living_landing_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/living_motion_fixture.rs (98%) create mode 100644 crates/horizon-world/examples/probe/main.rs rename crates/horizon-world/examples/{ => probe}/material_condition_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/material_extension_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/material_stage_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/material_surface_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/movement_emission_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/movement_registry_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/movement_support_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/object_open_map_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/object_open_set_fixture.rs (96%) rename crates/horizon-world/examples/{ => probe}/piston_movement_fixture.rs (93%) rename crates/horizon-world/examples/{ => probe}/piston_shape_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/placement_fixture.rs (94%) rename crates/horizon-world/examples/{ => probe}/player_equipment_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/player_food_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/player_health_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/player_hurt_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/player_inventory_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/player_travel_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/portal_travel_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/registered_player_combat_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/registry_collision_scan_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/registry_fall_ray_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/registry_fluid_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/replace_block_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/restitution_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/retrogen_data_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/rule_test_fixture.rs (96%) rename crates/horizon-world/examples/{ => probe}/scattered_ore_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/server_player_combat_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/server_player_damage_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/simple_block_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/simple_container_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/spawn_origin.rs (96%) rename crates/horizon-world/examples/{ => probe}/state_provider_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/status_effect_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/status_tick_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/stepped_interpolation_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/stored_consume_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/stored_effect_attributes_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/stored_effect_notifications_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/structure_density_fixture.rs (96%) rename crates/horizon-world/examples/{ => probe}/suffocation_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/support/decoration_storage.rs (100%) rename crates/horizon-world/examples/{ => probe}/support/placement_queries.rs (100%) rename crates/horizon-world/examples/{ => probe}/swimming_fixture.rs (96%) rename crates/horizon-world/examples/{ => probe}/synced_bytes_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/synced_floats_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/teleport_consume_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/terrain_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/tick_fixture.rs (93%) rename crates/horizon-world/examples/{ => probe}/tree_feature_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/use_flag_reaction_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/use_remainder_fixture.rs (99%) rename crates/horizon-world/examples/{ => probe}/value_provider_fixture.rs (94%) rename crates/horizon-world/examples/{ => probe}/view_direction_fixture.rs (94%) rename crates/horizon-world/examples/{ => probe}/water_splash_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/world_border_fixture.rs (97%) rename crates/horizon-world/examples/{ => probe}/world_fixture.rs (96%) rename crates/horizon-world/examples/{ => probe}/world_ray_fixture.rs (98%) rename crates/horizon-world/examples/{ => probe}/worldgen_random_fixture.rs (97%) diff --git a/crates/horizon-world/examples/active_effect_tick_fixture.rs b/crates/horizon-world/examples/probe/active_effect_tick_fixture.rs similarity index 99% rename from crates/horizon-world/examples/active_effect_tick_fixture.rs rename to crates/horizon-world/examples/probe/active_effect_tick_fixture.rs index 7a4ed3c29..1e366bf44 100644 --- a/crates/horizon-world/examples/active_effect_tick_fixture.rs +++ b/crates/horizon-world/examples/probe/active_effect_tick_fixture.rs @@ -512,9 +512,9 @@ fn run(f: Value, out: &mut dyn Write, make: fn(i64) -> R) { writeln!(w.out, "random {i} {} {}", r.next_long(), r.next_long()).unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); - let side = std::env::args().nth(2).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); + let side = crate::args().nth(2).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{side}.txt")))?); for line in fs::read_to_string(dir.join(format!("inputs-{side}.txt")))?.lines() { diff --git a/crates/horizon-world/examples/active_effects_fixture.rs b/crates/horizon-world/examples/probe/active_effects_fixture.rs similarity index 98% rename from crates/horizon-world/examples/active_effects_fixture.rs rename to crates/horizon-world/examples/probe/active_effects_fixture.rs index dba99cccd..70395e813 100644 --- a/crates/horizon-world/examples/active_effects_fixture.rs +++ b/crates/horizon-world/examples/probe/active_effects_fixture.rs @@ -304,9 +304,9 @@ fn run(f: Value, out: &mut dyn Write) { w.all(&s); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); - let side = std::env::args().nth(2).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); + let side = crate::args().nth(2).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{side}.txt")))?); for line in fs::read_to_string(dir.join(format!("inputs-{side}.txt")))?.lines() { diff --git a/crates/horizon-world/examples/anchor_fixture.rs b/crates/horizon-world/examples/probe/anchor_fixture.rs similarity index 94% rename from crates/horizon-world/examples/anchor_fixture.rs rename to crates/horizon-world/examples/probe/anchor_fixture.rs index c6c15e65e..230b05699 100644 --- a/crates/horizon-world/examples/anchor_fixture.rs +++ b/crates/horizon-world/examples/probe/anchor_fixture.rs @@ -18,8 +18,8 @@ fn anchor( a.to_json().unwrap_or_else(|_| "error".to_owned()) ) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/attribute_fixture.rs b/crates/horizon-world/examples/probe/attribute_fixture.rs similarity index 98% rename from crates/horizon-world/examples/attribute_fixture.rs rename to crates/horizon-world/examples/probe/attribute_fixture.rs index 450400c21..e5432a6a3 100644 --- a/crates/horizon-world/examples/attribute_fixture.rs +++ b/crates/horizon-world/examples/probe/attribute_fixture.rs @@ -80,8 +80,8 @@ fn state(out: &mut dyn Write, id: usize, a: &Instance, pool: &[Modifier]) -> io: } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/attribute_health_fixture.rs b/crates/horizon-world/examples/probe/attribute_health_fixture.rs similarity index 98% rename from crates/horizon-world/examples/attribute_health_fixture.rs rename to crates/horizon-world/examples/probe/attribute_health_fixture.rs index 3bf0d8d75..5efe0cb96 100644 --- a/crates/horizon-world/examples/attribute_health_fixture.rs +++ b/crates/horizon-world/examples/probe/attribute_health_fixture.rs @@ -304,10 +304,10 @@ fn run(dir: &Path, output: &str) -> Result<(), Box Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); - if std::env::args().nth(2).as_deref() == Some("live") { + if crate::args().nth(2).as_deref() == Some("live") { run::(dir, "rust-live.txt") } else { run::(dir, "rust.txt") diff --git a/crates/horizon-world/examples/attribute_map_queries_fixture.rs b/crates/horizon-world/examples/probe/attribute_map_queries_fixture.rs similarity index 99% rename from crates/horizon-world/examples/attribute_map_queries_fixture.rs rename to crates/horizon-world/examples/probe/attribute_map_queries_fixture.rs index 28ee0c73a..bffcbf9e5 100644 --- a/crates/horizon-world/examples/attribute_map_queries_fixture.rs +++ b/crates/horizon-world/examples/probe/attribute_map_queries_fixture.rs @@ -271,7 +271,7 @@ mod integration { } } pub fn run() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); + let args: Vec<_> = crate::args().collect(); let dir = Path::new(&args[1]); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{}.txt", args[2])))?); @@ -499,6 +499,6 @@ mod integration { Ok(()) } } -fn main() -> Result<(), Box> { +pub fn main() -> Result<(), Box> { integration::run() } diff --git a/crates/horizon-world/examples/attribute_updates_fixture.rs b/crates/horizon-world/examples/probe/attribute_updates_fixture.rs similarity index 99% rename from crates/horizon-world/examples/attribute_updates_fixture.rs rename to crates/horizon-world/examples/probe/attribute_updates_fixture.rs index 461a552b8..6bf9d815e 100644 --- a/crates/horizon-world/examples/attribute_updates_fixture.rs +++ b/crates/horizon-world/examples/probe/attribute_updates_fixture.rs @@ -625,9 +625,9 @@ fn run(f: Value, out: &mut dyn Write) { w.all(&s); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); - let side = std::env::args().nth(2).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); + let side = crate::args().nth(2).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{side}.txt")))?); for line in fs::read_to_string(dir.join(format!("inputs-{side}.txt")))?.lines() { diff --git a/crates/horizon-world/examples/basic_feature_fixture.rs b/crates/horizon-world/examples/probe/basic_feature_fixture.rs similarity index 97% rename from crates/horizon-world/examples/basic_feature_fixture.rs rename to crates/horizon-world/examples/probe/basic_feature_fixture.rs index f8ec7f53c..2e6bf9d73 100644 --- a/crates/horizon-world/examples/basic_feature_fixture.rs +++ b/crates/horizon-world/examples/probe/basic_feature_fixture.rs @@ -156,8 +156,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let ids: [u32; 5] = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let blocks = ids.map(BlockStateId); diff --git a/crates/horizon-world/examples/biome_chunk_fixture.rs b/crates/horizon-world/examples/probe/biome_chunk_fixture.rs similarity index 96% rename from crates/horizon-world/examples/biome_chunk_fixture.rs rename to crates/horizon-world/examples/probe/biome_chunk_fixture.rs index 69f7c897d..e0c7f1686 100644 --- a/crates/horizon-world/examples/biome_chunk_fixture.rs +++ b/crates/horizon-world/examples/probe/biome_chunk_fixture.rs @@ -20,8 +20,8 @@ fn biome_key(id: &i32) -> Option<&str> { _ => Some("horizon:other"), } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/biome_generation_fixture.rs b/crates/horizon-world/examples/probe/biome_generation_fixture.rs similarity index 97% rename from crates/horizon-world/examples/biome_generation_fixture.rs rename to crates/horizon-world/examples/probe/biome_generation_fixture.rs index 2377747f9..f5a609a5c 100644 --- a/crates/horizon-world/examples/biome_generation_fixture.rs +++ b/crates/horizon-world/examples/probe/biome_generation_fixture.rs @@ -20,8 +20,8 @@ use std::{ fn n(v: &Value) -> i32 { v.as_i64().unwrap() as i32 } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let bundle: Value = serde_json::from_str(&fs::read_to_string(dir.join("registries.json"))?)?; let noises: BTreeMap = serde_json::from_value(bundle["noises"].clone())?; diff --git a/crates/horizon-world/examples/biome_placement_fixture.rs b/crates/horizon-world/examples/probe/biome_placement_fixture.rs similarity index 97% rename from crates/horizon-world/examples/biome_placement_fixture.rs rename to crates/horizon-world/examples/probe/biome_placement_fixture.rs index a412b9924..36a8cb7e6 100644 --- a/crates/horizon-world/examples/biome_placement_fixture.rs +++ b/crates/horizon-world/examples/probe/biome_placement_fixture.rs @@ -150,8 +150,8 @@ fn fixture( writeln!(world.out, "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/biome_source_codec_fixture.rs b/crates/horizon-world/examples/probe/biome_source_codec_fixture.rs similarity index 95% rename from crates/horizon-world/examples/biome_source_codec_fixture.rs rename to crates/horizon-world/examples/probe/biome_source_codec_fixture.rs index d45dcdd3a..70347bbc6 100644 --- a/crates/horizon-world/examples/biome_source_codec_fixture.rs +++ b/crates/horizon-world/examples/probe/biome_source_codec_fixture.rs @@ -26,8 +26,8 @@ fn normalized(value: Value) -> Value { value => value, } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name: &str| -> Result, Box> { Ok(serde_json::from_str(&fs::read_to_string( diff --git a/crates/horizon-world/examples/biome_source_fixture.rs b/crates/horizon-world/examples/probe/biome_source_fixture.rs similarity index 95% rename from crates/horizon-world/examples/biome_source_fixture.rs rename to crates/horizon-world/examples/probe/biome_source_fixture.rs index cbf262a7c..021e67a0f 100644 --- a/crates/horizon-world/examples/biome_source_fixture.rs +++ b/crates/horizon-world/examples/probe/biome_source_fixture.rs @@ -29,8 +29,8 @@ impl DensitySampler for Erosion { } } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/biome_temperature_fixture.rs b/crates/horizon-world/examples/probe/biome_temperature_fixture.rs similarity index 97% rename from crates/horizon-world/examples/biome_temperature_fixture.rs rename to crates/horizon-world/examples/probe/biome_temperature_fixture.rs index 86b1393ce..e5b367947 100644 --- a/crates/horizon-world/examples/biome_temperature_fixture.rs +++ b/crates/horizon-world/examples/probe/biome_temperature_fixture.rs @@ -68,8 +68,8 @@ fn operations(worker: &mut BiomeTemperature, ops: &Value, out: &mut impl Write) } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/block_collision_scan_fixture.rs b/crates/horizon-world/examples/probe/block_collision_scan_fixture.rs similarity index 98% rename from crates/horizon-world/examples/block_collision_scan_fixture.rs rename to crates/horizon-world/examples/probe/block_collision_scan_fixture.rs index 4c4764c5f..c27c554b1 100644 --- a/crates/horizon-world/examples/block_collision_scan_fixture.rs +++ b/crates/horizon-world/examples/probe/block_collision_scan_fixture.rs @@ -174,8 +174,8 @@ impl BlockCollisionWorld for World { Ok(self.palette[block.state.0 as usize].shape.clone()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let out = Rc::new(RefCell::new(io::BufWriter::new(fs::File::create( dir.join("rust.txt"), diff --git a/crates/horizon-world/examples/block_entity_storage_fixture.rs b/crates/horizon-world/examples/probe/block_entity_storage_fixture.rs similarity index 98% rename from crates/horizon-world/examples/block_entity_storage_fixture.rs rename to crates/horizon-world/examples/probe/block_entity_storage_fixture.rs index e321f23fe..687eed790 100644 --- a/crates/horizon-world/examples/block_entity_storage_fixture.rs +++ b/crates/horizon-world/examples/probe/block_entity_storage_fixture.rs @@ -72,8 +72,8 @@ fn pending(tag: Option<&Tag>) -> String { } } } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let mut out = io::BufWriter::new(fs::File::create(&args[2])?); let mut position = ChunkPos::default(); let mut chunk = ProtoBlockEntities::::new(position); diff --git a/crates/horizon-world/examples/block_landing_fixture.rs b/crates/horizon-world/examples/probe/block_landing_fixture.rs similarity index 98% rename from crates/horizon-world/examples/block_landing_fixture.rs rename to crates/horizon-world/examples/probe/block_landing_fixture.rs index 9e20d5a1b..77b42f418 100644 --- a/crates/horizon-world/examples/block_landing_fixture.rs +++ b/crates/horizon-world/examples/probe/block_landing_fixture.rs @@ -237,8 +237,8 @@ impl BlockLandingWorld for World<'_, '_> { self.query(format!("level-event {e} {} {d}", pos(p))) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); let read = |name: &str| -> Result> { diff --git a/crates/horizon-world/examples/block_properties_fixture.rs b/crates/horizon-world/examples/probe/block_properties_fixture.rs similarity index 97% rename from crates/horizon-world/examples/block_properties_fixture.rs rename to crates/horizon-world/examples/probe/block_properties_fixture.rs index 3404b1fa1..6169041a2 100644 --- a/crates/horizon-world/examples/block_properties_fixture.rs +++ b/crates/horizon-world/examples/probe/block_properties_fixture.rs @@ -20,8 +20,8 @@ fn bbox(v: &Value) -> Aabb { .collect::>(); Aabb::new(Vec3::new(v[0], v[1], v[2]), Vec3::new(v[3], v[4], v[5])) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name: &str| -> Result> { Ok( diff --git a/crates/horizon-world/examples/block_push_fixture.rs b/crates/horizon-world/examples/probe/block_push_fixture.rs similarity index 96% rename from crates/horizon-world/examples/block_push_fixture.rs rename to crates/horizon-world/examples/probe/block_push_fixture.rs index 8871b1070..2c77a8059 100644 --- a/crates/horizon-world/examples/block_push_fixture.rs +++ b/crates/horizon-world/examples/probe/block_push_fixture.rs @@ -97,8 +97,8 @@ impl BlockPushWorld for World<'_> { Ok(()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/block_state_codec_fixture.rs b/crates/horizon-world/examples/probe/block_state_codec_fixture.rs similarity index 94% rename from crates/horizon-world/examples/block_state_codec_fixture.rs rename to crates/horizon-world/examples/probe/block_state_codec_fixture.rs index d0632ae86..c0372d4fd 100644 --- a/crates/horizon-world/examples/block_state_codec_fixture.rs +++ b/crates/horizon-world/examples/probe/block_state_codec_fixture.rs @@ -22,8 +22,8 @@ fn tag(v: &Value) -> Tag { _ => panic!("invalid registry metadata"), } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let registry = BlockRegistry::from_nbt(&Tag::compound([ diff --git a/crates/horizon-world/examples/block_support_fixture.rs b/crates/horizon-world/examples/probe/block_support_fixture.rs similarity index 94% rename from crates/horizon-world/examples/block_support_fixture.rs rename to crates/horizon-world/examples/probe/block_support_fixture.rs index 9c43d5798..5d58fe159 100644 --- a/crates/horizon-world/examples/block_support_fixture.rs +++ b/crates/horizon-world/examples/probe/block_support_fixture.rs @@ -9,8 +9,8 @@ use std::{ io::{self, Write}, path::Path, }; -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name: &str| -> Result> { Ok( diff --git a/crates/horizon-world/examples/block_survival_fixture.rs b/crates/horizon-world/examples/probe/block_survival_fixture.rs similarity index 98% rename from crates/horizon-world/examples/block_survival_fixture.rs rename to crates/horizon-world/examples/probe/block_survival_fixture.rs index e062eb8da..b357d1577 100644 --- a/crates/horizon-world/examples/block_survival_fixture.rs +++ b/crates/horizon-world/examples/probe/block_survival_fixture.rs @@ -103,8 +103,8 @@ impl SurvivalWorld for World<'_, W> { Ok(self.neighbors[old as usize % self.neighbors.len()]) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name: &str| -> Result> { Ok( diff --git a/crates/horizon-world/examples/block_update_fixture.rs b/crates/horizon-world/examples/probe/block_update_fixture.rs similarity index 99% rename from crates/horizon-world/examples/block_update_fixture.rs rename to crates/horizon-world/examples/probe/block_update_fixture.rs index bc90232cb..5be9be731 100644 --- a/crates/horizon-world/examples/block_update_fixture.rs +++ b/crates/horizon-world/examples/probe/block_update_fixture.rs @@ -191,8 +191,8 @@ fn summary(level: &Cells, before: &HashMap, out: &mut St } } -fn main() -> Result<(), Box> { - let mut args = std::env::args().skip(1); +pub fn main() -> Result<(), Box> { + let mut args = crate::args().skip(1); let resources = args.next().expect("resource directory"); let cases = args.next().expect("case file"); let output = args.next().expect("output file"); diff --git a/crates/horizon-world/examples/blocking_item_damage_fixture.rs b/crates/horizon-world/examples/probe/blocking_item_damage_fixture.rs similarity index 97% rename from crates/horizon-world/examples/blocking_item_damage_fixture.rs rename to crates/horizon-world/examples/probe/blocking_item_damage_fixture.rs index 2fd39bea0..eb2a6de60 100644 --- a/crates/horizon-world/examples/blocking_item_damage_fixture.rs +++ b/crates/horizon-world/examples/probe/blocking_item_damage_fixture.rs @@ -117,8 +117,8 @@ impl BlockingItemDamageWorld for World<'_> { Ok(self.flag("server")) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/blocking_rules_fixture.rs b/crates/horizon-world/examples/probe/blocking_rules_fixture.rs similarity index 96% rename from crates/horizon-world/examples/blocking_rules_fixture.rs rename to crates/horizon-world/examples/probe/blocking_rules_fixture.rs index c0e19d541..c8613725c 100644 --- a/crates/horizon-world/examples/blocking_rules_fixture.rs +++ b/crates/horizon-world/examples/probe/blocking_rules_fixture.rs @@ -51,8 +51,8 @@ impl TypeMatchWorld for World<'_> { }) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/bulk_section_fixture.rs b/crates/horizon-world/examples/probe/bulk_section_fixture.rs similarity index 98% rename from crates/horizon-world/examples/bulk_section_fixture.rs rename to crates/horizon-world/examples/probe/bulk_section_fixture.rs index b9be692a7..eefdd9e52 100644 --- a/crates/horizon-world/examples/bulk_section_fixture.rs +++ b/crates/horizon-world/examples/probe/bulk_section_fixture.rs @@ -151,8 +151,8 @@ fn fixture( } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let bundle: Value = serde_json::from_str(&fs::read_to_string(dir.join("tags.json"))?)?; diff --git a/crates/horizon-world/examples/bundle_weight_fixture.rs b/crates/horizon-world/examples/probe/bundle_weight_fixture.rs similarity index 98% rename from crates/horizon-world/examples/bundle_weight_fixture.rs rename to crates/horizon-world/examples/probe/bundle_weight_fixture.rs index 2a47cdc37..8e077b807 100644 --- a/crates/horizon-world/examples/bundle_weight_fixture.rs +++ b/crates/horizon-world/examples/probe/bundle_weight_fixture.rs @@ -69,8 +69,8 @@ fn maximum(v: &Value) -> Option { fn fraction(f: Fraction) -> String { format!("{}/{}", f.numerator(), f.denominator()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/canyon_carver_fixture.rs b/crates/horizon-world/examples/probe/canyon_carver_fixture.rs similarity index 96% rename from crates/horizon-world/examples/canyon_carver_fixture.rs rename to crates/horizon-world/examples/probe/canyon_carver_fixture.rs index 023ffa356..76eaad452 100644 --- a/crates/horizon-world/examples/canyon_carver_fixture.rs +++ b/crates/horizon-world/examples/probe/canyon_carver_fixture.rs @@ -82,8 +82,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/carving_geometry_fixture.rs b/crates/horizon-world/examples/probe/carving_geometry_fixture.rs similarity index 96% rename from crates/horizon-world/examples/carving_geometry_fixture.rs rename to crates/horizon-world/examples/probe/carving_geometry_fixture.rs index 1f0ce0ea2..c45ae4cda 100644 --- a/crates/horizon-world/examples/carving_geometry_fixture.rs +++ b/crates/horizon-world/examples/probe/carving_geometry_fixture.rs @@ -47,8 +47,8 @@ impl CarverOutput for Output<'_> { Ok(()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/carving_mask_fixture.rs b/crates/horizon-world/examples/probe/carving_mask_fixture.rs similarity index 95% rename from crates/horizon-world/examples/carving_mask_fixture.rs rename to crates/horizon-world/examples/probe/carving_mask_fixture.rs index c7675ce47..17c82fd3c 100644 --- a/crates/horizon-world/examples/carving_mask_fixture.rs +++ b/crates/horizon-world/examples/probe/carving_mask_fixture.rs @@ -9,8 +9,8 @@ use std::{ fn n(v: &Value) -> i32 { v.as_i64().unwrap() as i32 } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/cave_carver_fixture.rs b/crates/horizon-world/examples/probe/cave_carver_fixture.rs similarity index 96% rename from crates/horizon-world/examples/cave_carver_fixture.rs rename to crates/horizon-world/examples/probe/cave_carver_fixture.rs index ad0d37612..79917c336 100644 --- a/crates/horizon-world/examples/cave_carver_fixture.rs +++ b/crates/horizon-world/examples/probe/cave_carver_fixture.rs @@ -82,8 +82,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/chunk_dump.rs b/crates/horizon-world/examples/probe/chunk_dump.rs similarity index 99% rename from crates/horizon-world/examples/chunk_dump.rs rename to crates/horizon-world/examples/probe/chunk_dump.rs index 125509d99..f6a93e660 100644 --- a/crates/horizon-world/examples/chunk_dump.rs +++ b/crates/horizon-world/examples/probe/chunk_dump.rs @@ -106,8 +106,8 @@ fn canonical(tag: &Tag, out: &mut String) { } } -fn main() -> Result<(), Error> { - let mut args = std::env::args().skip(1); +pub fn main() -> Result<(), Error> { + let mut args = crate::args().skip(1); let resources = std::path::PathBuf::from(args.next().ok_or("client resource directory")?); let seed: i64 = args.next().ok_or("seed")?.parse()?; let dimension = format!("minecraft:{}", args.next().ok_or("dimension")?); diff --git a/crates/horizon-world/examples/chunk_stage_fixture.rs b/crates/horizon-world/examples/probe/chunk_stage_fixture.rs similarity index 98% rename from crates/horizon-world/examples/chunk_stage_fixture.rs rename to crates/horizon-world/examples/probe/chunk_stage_fixture.rs index ee57f8930..0ae093dcd 100644 --- a/crates/horizon-world/examples/chunk_stage_fixture.rs +++ b/crates/horizon-world/examples/probe/chunk_stage_fixture.rs @@ -223,8 +223,8 @@ fn fixture( } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let bundle: Value = serde_json::from_str(&fs::read_to_string(dir.join("tags.json"))?)?; diff --git a/crates/horizon-world/examples/chunk_status_fixture.rs b/crates/horizon-world/examples/probe/chunk_status_fixture.rs similarity index 95% rename from crates/horizon-world/examples/chunk_status_fixture.rs rename to crates/horizon-world/examples/probe/chunk_status_fixture.rs index 92c5fe7bd..e124517fa 100644 --- a/crates/horizon-world/examples/chunk_status_fixture.rs +++ b/crates/horizon-world/examples/probe/chunk_status_fixture.rs @@ -4,8 +4,8 @@ use std::{ fs, io::{self, Write}, }; -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let mut out = io::BufWriter::new(fs::File::create(&args[2])?); writeln!( out, diff --git a/crates/horizon-world/examples/climbing_fixture.rs b/crates/horizon-world/examples/probe/climbing_fixture.rs similarity index 98% rename from crates/horizon-world/examples/climbing_fixture.rs rename to crates/horizon-world/examples/probe/climbing_fixture.rs index 19badd19b..48a28b8d3 100644 --- a/crates/horizon-world/examples/climbing_fixture.rs +++ b/crates/horizon-world/examples/probe/climbing_fixture.rs @@ -69,8 +69,8 @@ impl ClimbingWorld for World<'_> { self.last = Some(p); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let registry = BlockRegistry::from_nbt( &nbt::read_named( diff --git a/crates/horizon-world/examples/collision_context_fixture.rs b/crates/horizon-world/examples/probe/collision_context_fixture.rs similarity index 99% rename from crates/horizon-world/examples/collision_context_fixture.rs rename to crates/horizon-world/examples/probe/collision_context_fixture.rs index e99673e11..86620ab99 100644 --- a/crates/horizon-world/examples/collision_context_fixture.rs +++ b/crates/horizon-world/examples/probe/collision_context_fixture.rs @@ -244,8 +244,8 @@ impl PowderSnowWorld for RegistryWorld<'_, W> { Ok(self.feet.is_item("minecraft:leather_boots")) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let registry = if dir.join("block-registry.nbt").exists() { Some(BlockRegistry::from_nbt( diff --git a/crates/horizon-world/examples/collision_fixture.rs b/crates/horizon-world/examples/probe/collision_fixture.rs similarity index 97% rename from crates/horizon-world/examples/collision_fixture.rs rename to crates/horizon-world/examples/probe/collision_fixture.rs index f8f2651c9..b2601f137 100644 --- a/crates/horizon-world/examples/collision_fixture.rs +++ b/crates/horizon-world/examples/probe/collision_fixture.rs @@ -56,12 +56,8 @@ impl Input<'_> { Vec3::new(self.number(), self.number(), self.number()) } } -fn main() -> Result<(), Box> { - let base = PathBuf::from( - std::env::args() - .nth(1) - .ok_or("fixture directory required")?, - ); +pub fn main() -> Result<(), Box> { + let base = PathBuf::from(crate::args().nth(1).ok_or("fixture directory required")?); let (registry_root, _) = nbt::read_named( &fs::read(base.join("block-registry.nbt"))?, Limits::default(), diff --git a/crates/horizon-world/examples/combat_rules_fixture.rs b/crates/horizon-world/examples/probe/combat_rules_fixture.rs similarity index 96% rename from crates/horizon-world/examples/combat_rules_fixture.rs rename to crates/horizon-world/examples/probe/combat_rules_fixture.rs index 42d01285d..973596f6c 100644 --- a/crates/horizon-world/examples/combat_rules_fixture.rs +++ b/crates/horizon-world/examples/probe/combat_rules_fixture.rs @@ -56,8 +56,8 @@ impl ArmorWorld for World<'_> { Ok(v) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/component_durability_fixture.rs b/crates/horizon-world/examples/probe/component_durability_fixture.rs similarity index 98% rename from crates/horizon-world/examples/component_durability_fixture.rs rename to crates/horizon-world/examples/probe/component_durability_fixture.rs index 99f6c2389..7c5d89111 100644 --- a/crates/horizon-world/examples/component_durability_fixture.rs +++ b/crates/horizon-world/examples/probe/component_durability_fixture.rs @@ -135,8 +135,8 @@ impl DurabilityWorld for World<'_> { writeln!(self.out, "copy-after {}", snapshot(©)) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/component_patch_fixture.rs b/crates/horizon-world/examples/probe/component_patch_fixture.rs similarity index 97% rename from crates/horizon-world/examples/component_patch_fixture.rs rename to crates/horizon-world/examples/probe/component_patch_fixture.rs index 29b345c8d..9bd740061 100644 --- a/crates/horizon-world/examples/component_patch_fixture.rs +++ b/crates/horizon-world/examples/probe/component_patch_fixture.rs @@ -88,8 +88,8 @@ fn snapshot( maps[1] == maps[2] ) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/consumable_emission_fixture.rs b/crates/horizon-world/examples/probe/consumable_emission_fixture.rs similarity index 98% rename from crates/horizon-world/examples/consumable_emission_fixture.rs rename to crates/horizon-world/examples/probe/consumable_emission_fixture.rs index 966cec1d6..55dcf0100 100644 --- a/crates/horizon-world/examples/consumable_emission_fixture.rs +++ b/crates/horizon-world/examples/probe/consumable_emission_fixture.rs @@ -237,8 +237,8 @@ fn run(f: Value, out: &mut dyn Write, make: fn(i64) -> R) { writeln!(w.out, "random {i} {} {}", r.next_long(), r.next_long()).unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/consumable_fixture.rs b/crates/horizon-world/examples/probe/consumable_fixture.rs similarity index 99% rename from crates/horizon-world/examples/consumable_fixture.rs rename to crates/horizon-world/examples/probe/consumable_fixture.rs index bfb1ad786..b5eec06dc 100644 --- a/crates/horizon-world/examples/consumable_fixture.rs +++ b/crates/horizon-world/examples/probe/consumable_fixture.rs @@ -403,8 +403,8 @@ fn run(f: Value, out: &mut dyn Write, make: fn(i64) -> R) { writeln!(w.out, "random {i} {} {}", r.next_long(), r.next_long()).unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/consume_effect_fixture.rs b/crates/horizon-world/examples/probe/consume_effect_fixture.rs similarity index 98% rename from crates/horizon-world/examples/consume_effect_fixture.rs rename to crates/horizon-world/examples/probe/consume_effect_fixture.rs index 5e4b878b5..85c3b530b 100644 --- a/crates/horizon-world/examples/consume_effect_fixture.rs +++ b/crates/horizon-world/examples/probe/consume_effect_fixture.rs @@ -206,8 +206,8 @@ fn run(f: Value, out: &mut dyn Write, make: fn(i64) -> R) { writeln!(w.out, "random {i} {} {}", r.next_long(), r.next_long()).unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/damage_immunity_fixture.rs b/crates/horizon-world/examples/probe/damage_immunity_fixture.rs similarity index 97% rename from crates/horizon-world/examples/damage_immunity_fixture.rs rename to crates/horizon-world/examples/probe/damage_immunity_fixture.rs index b404b27b2..f477c08de 100644 --- a/crates/horizon-world/examples/damage_immunity_fixture.rs +++ b/crates/horizon-world/examples/probe/damage_immunity_fixture.rs @@ -91,8 +91,8 @@ impl ImmunityWorld for Env<'_> { self.query("loaded", "loaded") } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let slots: Value = serde_json::from_str(&fs::read_to_string(dir.join("slots.json"))?)?; let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); diff --git a/crates/horizon-world/examples/damage_reduction_fixture.rs b/crates/horizon-world/examples/probe/damage_reduction_fixture.rs similarity index 97% rename from crates/horizon-world/examples/damage_reduction_fixture.rs rename to crates/horizon-world/examples/probe/damage_reduction_fixture.rs index 16d37af2f..766a53439 100644 --- a/crates/horizon-world/examples/damage_reduction_fixture.rs +++ b/crates/horizon-world/examples/probe/damage_reduction_fixture.rs @@ -115,8 +115,8 @@ impl DamageReductionWorld for World<'_> { Ok(0.0) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let slots: Value = serde_json::from_str(&fs::read_to_string(dir.join("slots.json"))?)?; let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); diff --git a/crates/horizon-world/examples/damage_source_fixture.rs b/crates/horizon-world/examples/probe/damage_source_fixture.rs similarity index 98% rename from crates/horizon-world/examples/damage_source_fixture.rs rename to crates/horizon-world/examples/probe/damage_source_fixture.rs index 7e8bfdaee..f50f11d22 100644 --- a/crates/horizon-world/examples/damage_source_fixture.rs +++ b/crates/horizon-world/examples/probe/damage_source_fixture.rs @@ -85,8 +85,8 @@ impl SourceWorld for World<'_> { Ok(self.state()["creative"][id].as_bool().unwrap()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let catalog = Catalog::from_json( &serde_json::from_str(&fs::read_to_string(dir.join("catalog.json"))?)?, diff --git a/crates/horizon-world/examples/datafix_world.rs b/crates/horizon-world/examples/probe/datafix_world.rs similarity index 92% rename from crates/horizon-world/examples/datafix_world.rs rename to crates/horizon-world/examples/probe/datafix_world.rs index d3e189d85..f2e119d42 100644 --- a/crates/horizon-world/examples/datafix_world.rs +++ b/crates/horizon-world/examples/probe/datafix_world.rs @@ -4,7 +4,7 @@ //! With a TARGET DataVersion only the data fixes up to it run, on a world in the //! layout of before 1.16. use horizon_world::datafix::files; -use std::{env, fs, io, path::Path, process::ExitCode}; +use std::{fs, io, path::Path, process::ExitCode}; fn copy(from: &Path, to: &Path) -> io::Result<()> { fs::create_dir_all(to)?; @@ -20,8 +20,8 @@ fn copy(from: &Path, to: &Path) -> io::Result<()> { Ok(()) } -fn main() -> ExitCode { - let args: Vec = env::args().skip(1).collect(); +pub fn main() -> ExitCode { + let args: Vec = crate::args().skip(1).collect(); let (input, output, target) = match args.as_slice() { [input, output] => (input, output, None), [input, output, target] => (input, output, target.parse::().ok()), diff --git a/crates/horizon-world/examples/decoration_fixture.rs b/crates/horizon-world/examples/probe/decoration_fixture.rs similarity index 98% rename from crates/horizon-world/examples/decoration_fixture.rs rename to crates/horizon-world/examples/probe/decoration_fixture.rs index 57c33d24b..1d8e53561 100644 --- a/crates/horizon-world/examples/decoration_fixture.rs +++ b/crates/horizon-world/examples/probe/decoration_fixture.rs @@ -102,8 +102,8 @@ impl PlacementContext for World<'_, W> { .is_some_and(|steps| steps.iter().flatten().any(|id| *id == feature))) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/decoration_region_fixture.rs b/crates/horizon-world/examples/probe/decoration_region_fixture.rs similarity index 98% rename from crates/horizon-world/examples/decoration_region_fixture.rs rename to crates/horizon-world/examples/probe/decoration_region_fixture.rs index db1fb4206..bad115a50 100644 --- a/crates/horizon-world/examples/decoration_region_fixture.rs +++ b/crates/horizon-world/examples/probe/decoration_region_fixture.rs @@ -1,5 +1,4 @@ -#[path = "support/decoration_storage.rs"] -mod storage; +use crate::support::decoration_storage as storage; use horizon_core::{ biome::obfuscate_seed, position::{BlockPos, ChunkPos}, @@ -292,8 +291,8 @@ fn fixture( } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let (registry, states) = storage::load(dir)?; let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); diff --git a/crates/horizon-world/examples/dynamic_support_fixture.rs b/crates/horizon-world/examples/probe/dynamic_support_fixture.rs similarity index 98% rename from crates/horizon-world/examples/dynamic_support_fixture.rs rename to crates/horizon-world/examples/probe/dynamic_support_fixture.rs index a321f97d0..92f8c159a 100644 --- a/crates/horizon-world/examples/dynamic_support_fixture.rs +++ b/crates/horizon-world/examples/probe/dynamic_support_fixture.rs @@ -152,8 +152,8 @@ impl PistonCollisionWorld for World<'_, W> { .map_err(io::Error::other) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts.json"))?)?; let states = facts["states"] diff --git a/crates/horizon-world/examples/edge_backoff_fixture.rs b/crates/horizon-world/examples/probe/edge_backoff_fixture.rs similarity index 96% rename from crates/horizon-world/examples/edge_backoff_fixture.rs rename to crates/horizon-world/examples/probe/edge_backoff_fixture.rs index f12ce4431..ad9eb235a 100644 --- a/crates/horizon-world/examples/edge_backoff_fixture.rs +++ b/crates/horizon-world/examples/probe/edge_backoff_fixture.rs @@ -73,8 +73,8 @@ impl EdgeBackoffWorld for World<'_> { .unwrap_or(false)) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/effect_attribute_modifiers_fixture.rs b/crates/horizon-world/examples/probe/effect_attribute_modifiers_fixture.rs similarity index 99% rename from crates/horizon-world/examples/effect_attribute_modifiers_fixture.rs rename to crates/horizon-world/examples/probe/effect_attribute_modifiers_fixture.rs index 8616303de..1ff3e79b6 100644 --- a/crates/horizon-world/examples/effect_attribute_modifiers_fixture.rs +++ b/crates/horizon-world/examples/probe/effect_attribute_modifiers_fixture.rs @@ -228,8 +228,8 @@ fn error(e: Error) -> &'static str { Error::World(Stop::Duplicate) => "duplicate", } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/effect_notifications_fixture.rs b/crates/horizon-world/examples/probe/effect_notifications_fixture.rs similarity index 99% rename from crates/horizon-world/examples/effect_notifications_fixture.rs rename to crates/horizon-world/examples/probe/effect_notifications_fixture.rs index 248c77a97..195fa9b4b 100644 --- a/crates/horizon-world/examples/effect_notifications_fixture.rs +++ b/crates/horizon-world/examples/probe/effect_notifications_fixture.rs @@ -494,9 +494,9 @@ fn run(f: Value, out: &mut dyn Write) { w.all(&s); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); - let side = std::env::args().nth(2).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); + let side = crate::args().nth(2).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{side}.txt")))?); for line in fs::read_to_string(dir.join(format!("inputs-{side}.txt")))?.lines() { diff --git a/crates/horizon-world/examples/effect_sync_fixture.rs b/crates/horizon-world/examples/probe/effect_sync_fixture.rs similarity index 99% rename from crates/horizon-world/examples/effect_sync_fixture.rs rename to crates/horizon-world/examples/probe/effect_sync_fixture.rs index 6c7b5f3ae..9c8a2aa09 100644 --- a/crates/horizon-world/examples/effect_sync_fixture.rs +++ b/crates/horizon-world/examples/probe/effect_sync_fixture.rs @@ -330,8 +330,8 @@ impl EffectSyncWorld for World<'_> { sync::update_invisibility(s, self) } } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let dir = Path::new(&args[1]); let metadata: Value = serde_json::from_str(&fs::read_to_string(dir.join("catalog.json"))?)?; let catalog = Catalog::from_json(&metadata)?; diff --git a/crates/horizon-world/examples/entity_attribute_fixture.rs b/crates/horizon-world/examples/probe/entity_attribute_fixture.rs similarity index 97% rename from crates/horizon-world/examples/entity_attribute_fixture.rs rename to crates/horizon-world/examples/probe/entity_attribute_fixture.rs index eb1bc8358..2e94b8b1c 100644 --- a/crates/horizon-world/examples/entity_attribute_fixture.rs +++ b/crates/horizon-world/examples/probe/entity_attribute_fixture.rs @@ -36,8 +36,8 @@ fn lookup(out: &mut dyn Write, label: &str, result: Result) -> ), } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let catalog = Arc::new(Catalog::from_json(&serde_json::from_str( &fs::read_to_string(dir.join("catalog.json"))?, diff --git a/crates/horizon-world/examples/entity_collision_fixture.rs b/crates/horizon-world/examples/probe/entity_collision_fixture.rs similarity index 97% rename from crates/horizon-world/examples/entity_collision_fixture.rs rename to crates/horizon-world/examples/probe/entity_collision_fixture.rs index edf258069..815d9c249 100644 --- a/crates/horizon-world/examples/entity_collision_fixture.rs +++ b/crates/horizon-world/examples/probe/entity_collision_fixture.rs @@ -142,8 +142,8 @@ impl EntityCollisionWorld for World<'_, W> { && source.is_none_or(|id| self.entities[id.0 as usize - 1].root != entity.root)) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/entity_fluid_fixture.rs b/crates/horizon-world/examples/probe/entity_fluid_fixture.rs similarity index 99% rename from crates/horizon-world/examples/entity_fluid_fixture.rs rename to crates/horizon-world/examples/probe/entity_fluid_fixture.rs index 1178c63bf..ad9b6ba2a 100644 --- a/crates/horizon-world/examples/entity_fluid_fixture.rs +++ b/crates/horizon-world/examples/probe/entity_fluid_fixture.rs @@ -319,8 +319,8 @@ fn limit_checks(template: &Value, states: [FluidState; 5]) { assert!(!interaction.update(&mut world, false, 0).unwrap()); assert!(interaction.trackers().is_empty()); } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); let load = |n: &str| -> Result<_, Box> { diff --git a/crates/horizon-world/examples/entity_move_fixture.rs b/crates/horizon-world/examples/probe/entity_move_fixture.rs similarity index 99% rename from crates/horizon-world/examples/entity_move_fixture.rs rename to crates/horizon-world/examples/probe/entity_move_fixture.rs index fbcbb8ed1..fb31c8f79 100644 --- a/crates/horizon-world/examples/entity_move_fixture.rs +++ b/crates/horizon-world/examples/probe/entity_move_fixture.rs @@ -327,8 +327,8 @@ impl RestitutionWorld for Bounce<'_, '_> { self.0.set_velocity(v) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/entity_obstruction_fixture.rs b/crates/horizon-world/examples/probe/entity_obstruction_fixture.rs similarity index 96% rename from crates/horizon-world/examples/entity_obstruction_fixture.rs rename to crates/horizon-world/examples/probe/entity_obstruction_fixture.rs index ef8f0acc8..0d585170b 100644 --- a/crates/horizon-world/examples/entity_obstruction_fixture.rs +++ b/crates/horizon-world/examples/probe/entity_obstruction_fixture.rs @@ -69,8 +69,8 @@ fn bbox(v: &Value) -> Aabb { Vec3::new(values[3], values[4], values[5]), ) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/extra_items_fixture.rs b/crates/horizon-world/examples/probe/extra_items_fixture.rs similarity index 99% rename from crates/horizon-world/examples/extra_items_fixture.rs rename to crates/horizon-world/examples/probe/extra_items_fixture.rs index 0cbdd98d0..f317e318c 100644 --- a/crates/horizon-world/examples/extra_items_fixture.rs +++ b/crates/horizon-world/examples/probe/extra_items_fixture.rs @@ -392,8 +392,8 @@ impl AfterUseWorld for World { c.apply(self, original) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/face_support_fixture.rs b/crates/horizon-world/examples/probe/face_support_fixture.rs similarity index 97% rename from crates/horizon-world/examples/face_support_fixture.rs rename to crates/horizon-world/examples/probe/face_support_fixture.rs index e6bee0e7a..60c228136 100644 --- a/crates/horizon-world/examples/face_support_fixture.rs +++ b/crates/horizon-world/examples/probe/face_support_fixture.rs @@ -77,8 +77,8 @@ fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/face_visibility_fixture.rs b/crates/horizon-world/examples/probe/face_visibility_fixture.rs similarity index 96% rename from crates/horizon-world/examples/face_visibility_fixture.rs rename to crates/horizon-world/examples/probe/face_visibility_fixture.rs index b2ef8716c..3c653f1e1 100644 --- a/crates/horizon-world/examples/face_visibility_fixture.rs +++ b/crates/horizon-world/examples/probe/face_visibility_fixture.rs @@ -12,8 +12,8 @@ use std::{ io::{BufRead, BufReader, BufWriter, Write}, path::Path, }; -fn main() -> Result<(), Box> { - let path = std::env::args().nth(1).ok_or("private fixture directory")?; +pub fn main() -> Result<(), Box> { + let path = crate::args().nth(1).ok_or("private fixture directory")?; let dir = Path::new(&path); let read = |name: &str| -> Result> { Ok( diff --git a/crates/horizon-world/examples/fall_damage_fixture.rs b/crates/horizon-world/examples/probe/fall_damage_fixture.rs similarity index 96% rename from crates/horizon-world/examples/fall_damage_fixture.rs rename to crates/horizon-world/examples/probe/fall_damage_fixture.rs index 092208c95..af77d212f 100644 --- a/crates/horizon-world/examples/fall_damage_fixture.rs +++ b/crates/horizon-world/examples/probe/fall_damage_fixture.rs @@ -100,8 +100,8 @@ impl FallDamageWorld for World<'_> { Ok(()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/feature_catalog_fixture.rs b/crates/horizon-world/examples/probe/feature_catalog_fixture.rs similarity index 98% rename from crates/horizon-world/examples/feature_catalog_fixture.rs rename to crates/horizon-world/examples/probe/feature_catalog_fixture.rs index c12b9c1a0..d140a64e9 100644 --- a/crates/horizon-world/examples/feature_catalog_fixture.rs +++ b/crates/horizon-world/examples/probe/feature_catalog_fixture.rs @@ -189,8 +189,8 @@ fn tag(v: &Value) -> Tag { _ => panic!("invalid registry metadata"), } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let resources: Value = serde_json::from_str(&fs::read_to_string(dir.join("catalog.json"))?)?; let definitions = |name: &str| { diff --git a/crates/horizon-world/examples/feature_graph_fixture.rs b/crates/horizon-world/examples/probe/feature_graph_fixture.rs similarity index 97% rename from crates/horizon-world/examples/feature_graph_fixture.rs rename to crates/horizon-world/examples/probe/feature_graph_fixture.rs index fae5b6e2e..381972f44 100644 --- a/crates/horizon-world/examples/feature_graph_fixture.rs +++ b/crates/horizon-world/examples/probe/feature_graph_fixture.rs @@ -161,8 +161,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let ids: [u32; 5] = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let blocks = ids.map(BlockStateId); diff --git a/crates/horizon-world/examples/feature_placement_fixture.rs b/crates/horizon-world/examples/probe/feature_placement_fixture.rs similarity index 94% rename from crates/horizon-world/examples/feature_placement_fixture.rs rename to crates/horizon-world/examples/probe/feature_placement_fixture.rs index c7500fa4f..5310b240f 100644 --- a/crates/horizon-world/examples/feature_placement_fixture.rs +++ b/crates/horizon-world/examples/probe/feature_placement_fixture.rs @@ -1,6 +1,5 @@ //! Transport for native modifier chains and a feature callback sharing the RNG. -#[path = "support/placement_queries.rs"] -mod queries; +use crate::support::placement_queries as queries; use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; use horizon_world::worldgen::{ anchor::WorldGenerationContext, @@ -74,8 +73,8 @@ fn fixture( writeln!(out.borrow_mut(), "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/feature_region_fixture.rs b/crates/horizon-world/examples/probe/feature_region_fixture.rs similarity index 99% rename from crates/horizon-world/examples/feature_region_fixture.rs rename to crates/horizon-world/examples/probe/feature_region_fixture.rs index a6cb08b10..755c5306d 100644 --- a/crates/horizon-world/examples/feature_region_fixture.rs +++ b/crates/horizon-world/examples/probe/feature_region_fixture.rs @@ -496,8 +496,8 @@ fn query_state( } writeln!(out, "tags {bits}") } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let bundle: Value = serde_json::from_str(&fs::read_to_string(dir.join("tags.json"))?)?; diff --git a/crates/horizon-world/examples/feature_sort_fixture.rs b/crates/horizon-world/examples/probe/feature_sort_fixture.rs similarity index 93% rename from crates/horizon-world/examples/feature_sort_fixture.rs rename to crates/horizon-world/examples/probe/feature_sort_fixture.rs index 6e645601c..370a16325 100644 --- a/crates/horizon-world/examples/feature_sort_fixture.rs +++ b/crates/horizon-world/examples/probe/feature_sort_fixture.rs @@ -7,8 +7,8 @@ use std::{ io::{self, Write}, path::Path, }; -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/fill_layer_fixture.rs b/crates/horizon-world/examples/probe/fill_layer_fixture.rs similarity index 98% rename from crates/horizon-world/examples/fill_layer_fixture.rs rename to crates/horizon-world/examples/probe/fill_layer_fixture.rs index d10cd2b72..a0a35dd93 100644 --- a/crates/horizon-world/examples/fill_layer_fixture.rs +++ b/crates/horizon-world/examples/probe/fill_layer_fixture.rs @@ -145,8 +145,8 @@ fn tag(v: &Value) -> Tag { _ => panic!("invalid registry metadata"), } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let registry = BlockRegistry::from_nbt(&Tag::compound([ diff --git a/crates/horizon-world/examples/fluid_box_fixture.rs b/crates/horizon-world/examples/probe/fluid_box_fixture.rs similarity index 96% rename from crates/horizon-world/examples/fluid_box_fixture.rs rename to crates/horizon-world/examples/probe/fluid_box_fixture.rs index 50e5b7caf..0b348d7bb 100644 --- a/crates/horizon-world/examples/fluid_box_fixture.rs +++ b/crates/horizon-world/examples/probe/fluid_box_fixture.rs @@ -91,8 +91,8 @@ impl BoatFluidBoxWorld for World<'_> { self.boat } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/fluid_fixture.rs b/crates/horizon-world/examples/probe/fluid_fixture.rs similarity index 97% rename from crates/horizon-world/examples/fluid_fixture.rs rename to crates/horizon-world/examples/probe/fluid_fixture.rs index 466b85230..1e16480a9 100644 --- a/crates/horizon-world/examples/fluid_fixture.rs +++ b/crates/horizon-world/examples/probe/fluid_fixture.rs @@ -51,8 +51,8 @@ fn tag(v: &Value) -> Tag { _ => panic!("invalid registry metadata"), } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let registry = BlockRegistry::from_nbt(&Tag::compound([ diff --git a/crates/horizon-world/examples/fluid_flow_fixture.rs b/crates/horizon-world/examples/probe/fluid_flow_fixture.rs similarity index 96% rename from crates/horizon-world/examples/fluid_flow_fixture.rs rename to crates/horizon-world/examples/probe/fluid_flow_fixture.rs index 4da9f6a07..ec7810509 100644 --- a/crates/horizon-world/examples/fluid_flow_fixture.rs +++ b/crates/horizon-world/examples/probe/fluid_flow_fixture.rs @@ -60,8 +60,8 @@ impl FluidFlowWorld for World<'_> { Ok(self.f["states"][s]["faces"].as_u64().unwrap() & (1 << (d as u8)) != 0) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/fluid_occupancy_fixture.rs b/crates/horizon-world/examples/probe/fluid_occupancy_fixture.rs similarity index 98% rename from crates/horizon-world/examples/fluid_occupancy_fixture.rs rename to crates/horizon-world/examples/probe/fluid_occupancy_fixture.rs index bb178e300..7fc884f49 100644 --- a/crates/horizon-world/examples/fluid_occupancy_fixture.rs +++ b/crates/horizon-world/examples/probe/fluid_occupancy_fixture.rs @@ -67,8 +67,8 @@ impl FluidOccupancyWorld for World<'_, '_> { Ok(self.min + self.height - 1) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let registry = BlockRegistry::from_nbt( &nbt::read_named( diff --git a/crates/horizon-world/examples/fluid_shape_fixture.rs b/crates/horizon-world/examples/probe/fluid_shape_fixture.rs similarity index 96% rename from crates/horizon-world/examples/fluid_shape_fixture.rs rename to crates/horizon-world/examples/probe/fluid_shape_fixture.rs index 7e42203ec..9c14d5849 100644 --- a/crates/horizon-world/examples/fluid_shape_fixture.rs +++ b/crates/horizon-world/examples/probe/fluid_shape_fixture.rs @@ -34,8 +34,8 @@ impl FluidHeightWorld for World<'_> { panic!("ray shape does not use camera immersion support") } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/food_fixture.rs b/crates/horizon-world/examples/probe/food_fixture.rs similarity index 97% rename from crates/horizon-world/examples/food_fixture.rs rename to crates/horizon-world/examples/probe/food_fixture.rs index d0645ea44..2852eaf3e 100644 --- a/crates/horizon-world/examples/food_fixture.rs +++ b/crates/horizon-world/examples/probe/food_fixture.rs @@ -84,8 +84,8 @@ impl FoodWorld for World<'_> { self.query(f, &format!("hurt {:08x}", bits(v))) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/food_properties_fixture.rs b/crates/horizon-world/examples/probe/food_properties_fixture.rs similarity index 98% rename from crates/horizon-world/examples/food_properties_fixture.rs rename to crates/horizon-world/examples/probe/food_properties_fixture.rs index 59524b0dc..50b88bccc 100644 --- a/crates/horizon-world/examples/food_properties_fixture.rs +++ b/crates/horizon-world/examples/probe/food_properties_fixture.rs @@ -160,8 +160,8 @@ fn run(f: Value, out: &mut dyn Write, make: fn(i64) -> R) { writeln!(w.out, "random {i} {} {}", r.next_long(), r.next_long()).unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/food_storage_fixture.rs b/crates/horizon-world/examples/probe/food_storage_fixture.rs similarity index 97% rename from crates/horizon-world/examples/food_storage_fixture.rs rename to crates/horizon-world/examples/probe/food_storage_fixture.rs index 4aafe920e..bf7759a93 100644 --- a/crates/horizon-world/examples/food_storage_fixture.rs +++ b/crates/horizon-world/examples/probe/food_storage_fixture.rs @@ -49,8 +49,8 @@ fn tag(v: &Value) -> Option { _ => panic!("tag type"), }) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/ground_state_fixture.rs b/crates/horizon-world/examples/probe/ground_state_fixture.rs similarity index 96% rename from crates/horizon-world/examples/ground_state_fixture.rs rename to crates/horizon-world/examples/probe/ground_state_fixture.rs index 7b41515b3..398757854 100644 --- a/crates/horizon-world/examples/ground_state_fixture.rs +++ b/crates/horizon-world/examples/probe/ground_state_fixture.rs @@ -33,8 +33,8 @@ fn position(v: &Value) -> Option { )) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/height_provider_fixture.rs b/crates/horizon-world/examples/probe/height_provider_fixture.rs similarity index 93% rename from crates/horizon-world/examples/height_provider_fixture.rs rename to crates/horizon-world/examples/probe/height_provider_fixture.rs index 7ada87a18..94b2524f7 100644 --- a/crates/horizon-world/examples/height_provider_fixture.rs +++ b/crates/horizon-world/examples/probe/height_provider_fixture.rs @@ -33,8 +33,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/heightmap_fixture.rs b/crates/horizon-world/examples/probe/heightmap_fixture.rs similarity index 98% rename from crates/horizon-world/examples/heightmap_fixture.rs rename to crates/horizon-world/examples/probe/heightmap_fixture.rs index 35d7bc5c2..14cebbc59 100644 --- a/crates/horizon-world/examples/heightmap_fixture.rs +++ b/crates/horizon-world/examples/probe/heightmap_fixture.rs @@ -187,8 +187,8 @@ fn fixture( } Ok(()) } -fn main() -> Result<(), Box> { - let directory = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let directory = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&directory); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let tags: Value = serde_json::from_str(&fs::read_to_string(dir.join("tags.json"))?)?; diff --git a/crates/horizon-world/examples/interaction_shape_fixture.rs b/crates/horizon-world/examples/probe/interaction_shape_fixture.rs similarity index 97% rename from crates/horizon-world/examples/interaction_shape_fixture.rs rename to crates/horizon-world/examples/probe/interaction_shape_fixture.rs index 60b9742b8..6e10326f0 100644 --- a/crates/horizon-world/examples/interaction_shape_fixture.rs +++ b/crates/horizon-world/examples/probe/interaction_shape_fixture.rs @@ -77,8 +77,8 @@ impl RayWorld for World<'_, '_> { panic!("direct interaction clip") } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); let read = |n: &str| -> Result> { diff --git a/crates/horizon-world/examples/inventory_pickup_fixture.rs b/crates/horizon-world/examples/probe/inventory_pickup_fixture.rs similarity index 99% rename from crates/horizon-world/examples/inventory_pickup_fixture.rs rename to crates/horizon-world/examples/probe/inventory_pickup_fixture.rs index b3f742aa0..58170e871 100644 --- a/crates/horizon-world/examples/inventory_pickup_fixture.rs +++ b/crates/horizon-world/examples/probe/inventory_pickup_fixture.rs @@ -218,8 +218,8 @@ impl horizon_world::inventory_pickup::PickupHooks for World { Ok(self.op["infinite"].as_bool().unwrap()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/inventory_tick_fixture.rs b/crates/horizon-world/examples/probe/inventory_tick_fixture.rs similarity index 98% rename from crates/horizon-world/examples/inventory_tick_fixture.rs rename to crates/horizon-world/examples/probe/inventory_tick_fixture.rs index 974ed6760..1dfb9655e 100644 --- a/crates/horizon-world/examples/inventory_tick_fixture.rs +++ b/crates/horizon-world/examples/probe/inventory_tick_fixture.rs @@ -149,8 +149,8 @@ impl InventoryTickWorld for World { Ok(()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/inventory_use_fixture.rs b/crates/horizon-world/examples/probe/inventory_use_fixture.rs similarity index 99% rename from crates/horizon-world/examples/inventory_use_fixture.rs rename to crates/horizon-world/examples/probe/inventory_use_fixture.rs index 2f5ed557b..f00d97c9f 100644 --- a/crates/horizon-world/examples/inventory_use_fixture.rs +++ b/crates/horizon-world/examples/probe/inventory_use_fixture.rs @@ -230,8 +230,8 @@ impl UseServices for Services { self.event(view, state, &format!("synced {id}")) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/inventory_use_start_fixture.rs b/crates/horizon-world/examples/probe/inventory_use_start_fixture.rs similarity index 99% rename from crates/horizon-world/examples/inventory_use_start_fixture.rs rename to crates/horizon-world/examples/probe/inventory_use_start_fixture.rs index f887e5688..fc46a58b7 100644 --- a/crates/horizon-world/examples/inventory_use_start_fixture.rs +++ b/crates/horizon-world/examples/probe/inventory_use_start_fixture.rs @@ -295,8 +295,8 @@ impl StartServices for Services { self.kinetic_count = 0; } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/item_after_use_fixture.rs b/crates/horizon-world/examples/probe/item_after_use_fixture.rs similarity index 99% rename from crates/horizon-world/examples/item_after_use_fixture.rs rename to crates/horizon-world/examples/probe/item_after_use_fixture.rs index 3daf5dfce..30c35b871 100644 --- a/crates/horizon-world/examples/item_after_use_fixture.rs +++ b/crates/horizon-world/examples/probe/item_after_use_fixture.rs @@ -277,8 +277,8 @@ impl AfterUseWorld for World { c.apply(self, original) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/item_blocking_fixture.rs b/crates/horizon-world/examples/probe/item_blocking_fixture.rs similarity index 98% rename from crates/horizon-world/examples/item_blocking_fixture.rs rename to crates/horizon-world/examples/probe/item_blocking_fixture.rs index c4889925a..7bfdcdc99 100644 --- a/crates/horizon-world/examples/item_blocking_fixture.rs +++ b/crates/horizon-world/examples/probe/item_blocking_fixture.rs @@ -157,8 +157,8 @@ impl ItemBlockingWorld for World<'_> { self.event(&format!("block-using 0 {:08x} {fully}", bits(damage))) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/item_cooldowns_fixture.rs b/crates/horizon-world/examples/probe/item_cooldowns_fixture.rs similarity index 98% rename from crates/horizon-world/examples/item_cooldowns_fixture.rs rename to crates/horizon-world/examples/probe/item_cooldowns_fixture.rs index fb92d462f..e43f1c6bb 100644 --- a/crates/horizon-world/examples/item_cooldowns_fixture.rs +++ b/crates/horizon-world/examples/probe/item_cooldowns_fixture.rs @@ -130,8 +130,8 @@ impl CooldownUser for User<'_> { self.book.add(group(&stack), ticks, self.events) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/item_durability_fixture.rs b/crates/horizon-world/examples/probe/item_durability_fixture.rs similarity index 97% rename from crates/horizon-world/examples/item_durability_fixture.rs rename to crates/horizon-world/examples/probe/item_durability_fixture.rs index f051bb91c..de0af24c3 100644 --- a/crates/horizon-world/examples/item_durability_fixture.rs +++ b/crates/horizon-world/examples/probe/item_durability_fixture.rs @@ -82,8 +82,8 @@ impl DurabilityWorld for World<'_> { self.event(s, "break") } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/item_particles_fixture.rs b/crates/horizon-world/examples/probe/item_particles_fixture.rs similarity index 98% rename from crates/horizon-world/examples/item_particles_fixture.rs rename to crates/horizon-world/examples/probe/item_particles_fixture.rs index 9eead88ca..6fe11ea7d 100644 --- a/crates/horizon-world/examples/item_particles_fixture.rs +++ b/crates/horizon-world/examples/probe/item_particles_fixture.rs @@ -178,8 +178,8 @@ fn run(f: Value, out: &mut dyn Write, make: fn(i64) -> R) { writeln!(w.out, "random {i} {} {}", r.next_long(), r.next_long()).unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/item_stack_storage_fixture.rs b/crates/horizon-world/examples/probe/item_stack_storage_fixture.rs similarity index 98% rename from crates/horizon-world/examples/item_stack_storage_fixture.rs rename to crates/horizon-world/examples/probe/item_stack_storage_fixture.rs index bceb9f797..31c741b3e 100644 --- a/crates/horizon-world/examples/item_stack_storage_fixture.rs +++ b/crates/horizon-world/examples/probe/item_stack_storage_fixture.rs @@ -86,8 +86,8 @@ fn append(arena: &mut Vec, copy: CopyResult) -> usize { } } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/item_template_fixture.rs b/crates/horizon-world/examples/probe/item_template_fixture.rs similarity index 98% rename from crates/horizon-world/examples/item_template_fixture.rs rename to crates/horizon-world/examples/probe/item_template_fixture.rs index 6a8df6cc0..b6a538b04 100644 --- a/crates/horizon-world/examples/item_template_fixture.rs +++ b/crates/horizon-world/examples/probe/item_template_fixture.rs @@ -115,8 +115,8 @@ fn all( } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/item_use_catalog_fixture.rs b/crates/horizon-world/examples/probe/item_use_catalog_fixture.rs similarity index 96% rename from crates/horizon-world/examples/item_use_catalog_fixture.rs rename to crates/horizon-world/examples/probe/item_use_catalog_fixture.rs index 406ba521d..7d7871720 100644 --- a/crates/horizon-world/examples/item_use_catalog_fixture.rs +++ b/crates/horizon-world/examples/probe/item_use_catalog_fixture.rs @@ -33,8 +33,8 @@ fn snapshot(out: &mut dyn Write, s: &ItemUseStack<'_>) -> io::Result<()> { s.use_on_release() ) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let catalog = ItemUseCatalog::from_json(&serde_json::from_str(&fs::read_to_string( dir.join("catalog.json"), diff --git a/crates/horizon-world/examples/item_use_fixture.rs b/crates/horizon-world/examples/probe/item_use_fixture.rs similarity index 97% rename from crates/horizon-world/examples/item_use_fixture.rs rename to crates/horizon-world/examples/probe/item_use_fixture.rs index 74436d1f3..28bf66743 100644 --- a/crates/horizon-world/examples/item_use_fixture.rs +++ b/crates/horizon-world/examples/probe/item_use_fixture.rs @@ -85,8 +85,8 @@ impl ItemUseWorld for World<'_> { Ok(self.state()["virtual_remaining"].as_i64().unwrap() as i32) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/item_use_lifecycle_fixture.rs b/crates/horizon-world/examples/probe/item_use_lifecycle_fixture.rs similarity index 98% rename from crates/horizon-world/examples/item_use_lifecycle_fixture.rs rename to crates/horizon-world/examples/probe/item_use_lifecycle_fixture.rs index 404f6ba17..f7d3df48a 100644 --- a/crates/horizon-world/examples/item_use_lifecycle_fixture.rs +++ b/crates/horizon-world/examples/probe/item_use_lifecycle_fixture.rs @@ -166,8 +166,8 @@ impl UseLifecycleWorld for World<'_> { Ok(()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/item_use_start_fixture.rs b/crates/horizon-world/examples/probe/item_use_start_fixture.rs similarity index 98% rename from crates/horizon-world/examples/item_use_start_fixture.rs rename to crates/horizon-world/examples/probe/item_use_start_fixture.rs index 19cb859f8..be927e42e 100644 --- a/crates/horizon-world/examples/item_use_start_fixture.rs +++ b/crates/horizon-world/examples/probe/item_use_start_fixture.rs @@ -199,8 +199,8 @@ impl StartUseWorld for World<'_> { self.kinetic_count = 0; } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/java_hash_map_fixture.rs b/crates/horizon-world/examples/probe/java_hash_map_fixture.rs similarity index 97% rename from crates/horizon-world/examples/java_hash_map_fixture.rs rename to crates/horizon-world/examples/probe/java_hash_map_fixture.rs index cc2f6860d..de441a488 100644 --- a/crates/horizon-world/examples/java_hash_map_fixture.rs +++ b/crates/horizon-world/examples/probe/java_hash_map_fixture.rs @@ -35,8 +35,8 @@ impl JavaKey for Key { fn opt(v: Option) -> String { v.map_or("none".into(), |v| v.to_string()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/java_identity_map_fixture.rs b/crates/horizon-world/examples/probe/java_identity_map_fixture.rs similarity index 97% rename from crates/horizon-world/examples/java_identity_map_fixture.rs rename to crates/horizon-world/examples/probe/java_identity_map_fixture.rs index c73d20f7d..700b5b329 100644 --- a/crates/horizon-world/examples/java_identity_map_fixture.rs +++ b/crates/horizon-world/examples/probe/java_identity_map_fixture.rs @@ -48,10 +48,10 @@ impl JavaKey for Key { fn opt(v: Option) -> String { v.map_or("none".into(), |v| v.to_string()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); - let side = std::env::args().nth(2).unwrap(); + let side = crate::args().nth(2).unwrap(); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{side}.txt")))?); for line in fs::read_to_string(dir.join(format!("inputs-{side}.txt")))?.lines() { let f: Value = serde_json::from_str(line)?; diff --git a/crates/horizon-world/examples/level_place_fixture.rs b/crates/horizon-world/examples/probe/level_place_fixture.rs similarity index 97% rename from crates/horizon-world/examples/level_place_fixture.rs rename to crates/horizon-world/examples/probe/level_place_fixture.rs index 13595726d..0b9b4f883 100644 --- a/crates/horizon-world/examples/level_place_fixture.rs +++ b/crates/horizon-world/examples/probe/level_place_fixture.rs @@ -43,8 +43,8 @@ impl LevelAccess for Cells { } } -fn main() -> Result<(), Box> { - let mut args = std::env::args().skip(1); +pub fn main() -> Result<(), Box> { + let mut args = crate::args().skip(1); let resources = args.next().expect("resource directory"); let cases = args.next().expect("case file"); let output = args.next().expect("output file"); diff --git a/crates/horizon-world/examples/level_shape_fixture.rs b/crates/horizon-world/examples/probe/level_shape_fixture.rs similarity index 98% rename from crates/horizon-world/examples/level_shape_fixture.rs rename to crates/horizon-world/examples/probe/level_shape_fixture.rs index 1e4909928..696ac62ab 100644 --- a/crates/horizon-world/examples/level_shape_fixture.rs +++ b/crates/horizon-world/examples/probe/level_shape_fixture.rs @@ -43,8 +43,8 @@ impl LevelAccess for Cells { } } -fn main() -> Result<(), Box> { - let mut args = std::env::args().skip(1); +pub fn main() -> Result<(), Box> { + let mut args = crate::args().skip(1); let resources = args.next().expect("resource directory"); let cases = args.next().expect("case file"); let output = args.next().expect("output file"); diff --git a/crates/horizon-world/examples/live_attribute_updates_fixture.rs b/crates/horizon-world/examples/probe/live_attribute_updates_fixture.rs similarity index 99% rename from crates/horizon-world/examples/live_attribute_updates_fixture.rs rename to crates/horizon-world/examples/probe/live_attribute_updates_fixture.rs index 9f73a07e3..03b271ef1 100644 --- a/crates/horizon-world/examples/live_attribute_updates_fixture.rs +++ b/crates/horizon-world/examples/probe/live_attribute_updates_fixture.rs @@ -474,7 +474,7 @@ mod integration { } } pub fn run() -> std::result::Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); + let args: Vec<_> = crate::args().collect(); let dir = Path::new(&args[1]); let catalog = Arc::new(Catalog::from_json(&serde_json::from_str( &fs::read_to_string(dir.join("catalog.json"))?, @@ -593,6 +593,6 @@ mod integration { Ok(()) } } -fn main() -> Result<(), Box> { +pub fn main() -> Result<(), Box> { integration::run() } diff --git a/crates/horizon-world/examples/live_attributes_fixture.rs b/crates/horizon-world/examples/probe/live_attributes_fixture.rs similarity index 98% rename from crates/horizon-world/examples/live_attributes_fixture.rs rename to crates/horizon-world/examples/probe/live_attributes_fixture.rs index e90d8cb4f..2bbff5bdd 100644 --- a/crates/horizon-world/examples/live_attributes_fixture.rs +++ b/crates/horizon-world/examples/probe/live_attributes_fixture.rs @@ -65,8 +65,8 @@ fn effect_error(e: effects::Error) -> Error { _ => panic!("fixture definitions unexpectedly invalid"), } } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let dir = Path::new(&args[1]); let catalog = Arc::new(Catalog::from_json(&serde_json::from_str( &fs::read_to_string(dir.join("catalog.json"))?, diff --git a/crates/horizon-world/examples/living_air_fixture.rs b/crates/horizon-world/examples/probe/living_air_fixture.rs similarity index 98% rename from crates/horizon-world/examples/living_air_fixture.rs rename to crates/horizon-world/examples/probe/living_air_fixture.rs index fe581f54f..bf77ce86f 100644 --- a/crates/horizon-world/examples/living_air_fixture.rs +++ b/crates/horizon-world/examples/probe/living_air_fixture.rs @@ -193,8 +193,8 @@ impl LivingAirWorld for World<'_> { Ok(self.flag("omni")) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/living_damage_fixture.rs b/crates/horizon-world/examples/probe/living_damage_fixture.rs similarity index 98% rename from crates/horizon-world/examples/living_damage_fixture.rs rename to crates/horizon-world/examples/probe/living_damage_fixture.rs index b77048866..4e3c06887 100644 --- a/crates/horizon-world/examples/living_damage_fixture.rs +++ b/crates/horizon-world/examples/probe/living_damage_fixture.rs @@ -151,8 +151,8 @@ impl HealthWorld for World<'_> { DamageWorld::set_health(self, v) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/living_fall_fixture.rs b/crates/horizon-world/examples/probe/living_fall_fixture.rs similarity index 97% rename from crates/horizon-world/examples/living_fall_fixture.rs rename to crates/horizon-world/examples/probe/living_fall_fixture.rs index 64dc1f2df..84d7fb9a3 100644 --- a/crates/horizon-world/examples/living_fall_fixture.rs +++ b/crates/horizon-world/examples/probe/living_fall_fixture.rs @@ -169,8 +169,8 @@ fn run(world: &mut World<'_>) -> io::Result<()> { }; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/living_fluid_fixture.rs b/crates/horizon-world/examples/probe/living_fluid_fixture.rs similarity index 99% rename from crates/horizon-world/examples/living_fluid_fixture.rs rename to crates/horizon-world/examples/probe/living_fluid_fixture.rs index 55ccdd8f5..0bada6334 100644 --- a/crates/horizon-world/examples/living_fluid_fixture.rs +++ b/crates/horizon-world/examples/probe/living_fluid_fixture.rs @@ -248,8 +248,8 @@ impl LivingFluidWorld for World<'_> { Ok(self.flag("float_tag")) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/living_health_fixture.rs b/crates/horizon-world/examples/probe/living_health_fixture.rs similarity index 98% rename from crates/horizon-world/examples/living_health_fixture.rs rename to crates/horizon-world/examples/probe/living_health_fixture.rs index 958d43b7d..2b2f98129 100644 --- a/crates/horizon-world/examples/living_health_fixture.rs +++ b/crates/horizon-world/examples/probe/living_health_fixture.rs @@ -82,8 +82,8 @@ impl HealthWorld for World<'_> { living_health::set_health(self, v) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/living_hurt_fixture.rs b/crates/horizon-world/examples/probe/living_hurt_fixture.rs similarity index 98% rename from crates/horizon-world/examples/living_hurt_fixture.rs rename to crates/horizon-world/examples/probe/living_hurt_fixture.rs index e9addb406..4c9e46230 100644 --- a/crates/horizon-world/examples/living_hurt_fixture.rs +++ b/crates/horizon-world/examples/probe/living_hurt_fixture.rs @@ -205,8 +205,8 @@ impl HurtWorld for Env<'_> { self.event("attacker") } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/living_landing_fixture.rs b/crates/horizon-world/examples/probe/living_landing_fixture.rs similarity index 98% rename from crates/horizon-world/examples/living_landing_fixture.rs rename to crates/horizon-world/examples/probe/living_landing_fixture.rs index 156f8a2bd..87b438978 100644 --- a/crates/horizon-world/examples/living_landing_fixture.rs +++ b/crates/horizon-world/examples/probe/living_landing_fixture.rs @@ -158,8 +158,8 @@ impl LivingLandingWorld for World<'_> { self.climbable = false; } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/living_motion_fixture.rs b/crates/horizon-world/examples/probe/living_motion_fixture.rs similarity index 98% rename from crates/horizon-world/examples/living_motion_fixture.rs rename to crates/horizon-world/examples/probe/living_motion_fixture.rs index 92b4db938..174527053 100644 --- a/crates/horizon-world/examples/living_motion_fixture.rs +++ b/crates/horizon-world/examples/probe/living_motion_fixture.rs @@ -118,8 +118,8 @@ impl LivingMotionWorld for World<'_> { Ok(number(&self.f["drag_modifier"])) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/probe/main.rs b/crates/horizon-world/examples/probe/main.rs new file mode 100644 index 000000000..470fabd2b --- /dev/null +++ b/crates/horizon-world/examples/probe/main.rs @@ -0,0 +1,384 @@ +//! Every horizon-world parity probe in one binary: `probe [arguments]` runs `.rs` as its own +//! example did (tools/test_*_parity.py). Linking ~170 examples, each instantiating the crate's generics again, +//! was most of the parity job's probe build; one binary builds them once. +use std::process::{ExitCode, Termination}; + +/// Code shared by several probes. +mod support { + pub mod decoration_storage; + pub mod placement_queries; +} + +mod active_effect_tick_fixture; +mod active_effects_fixture; +mod anchor_fixture; +mod attribute_fixture; +mod attribute_health_fixture; +mod attribute_map_queries_fixture; +mod attribute_updates_fixture; +mod basic_feature_fixture; +mod biome_chunk_fixture; +mod biome_generation_fixture; +mod biome_placement_fixture; +mod biome_source_codec_fixture; +mod biome_source_fixture; +mod biome_temperature_fixture; +mod block_collision_scan_fixture; +mod block_entity_storage_fixture; +mod block_landing_fixture; +mod block_properties_fixture; +mod block_push_fixture; +mod block_state_codec_fixture; +mod block_support_fixture; +mod block_survival_fixture; +mod block_update_fixture; +mod blocking_item_damage_fixture; +mod blocking_rules_fixture; +mod bulk_section_fixture; +mod bundle_weight_fixture; +mod canyon_carver_fixture; +mod carving_geometry_fixture; +mod carving_mask_fixture; +mod cave_carver_fixture; +mod chunk_dump; +mod chunk_stage_fixture; +mod chunk_status_fixture; +mod climbing_fixture; +mod collision_context_fixture; +mod collision_fixture; +mod combat_rules_fixture; +mod component_durability_fixture; +mod component_patch_fixture; +mod consumable_emission_fixture; +mod consumable_fixture; +mod consume_effect_fixture; +mod damage_immunity_fixture; +mod damage_reduction_fixture; +mod damage_source_fixture; +mod datafix_world; +mod decoration_fixture; +mod decoration_region_fixture; +mod dynamic_support_fixture; +mod edge_backoff_fixture; +mod effect_attribute_modifiers_fixture; +mod effect_notifications_fixture; +mod effect_sync_fixture; +mod entity_attribute_fixture; +mod entity_collision_fixture; +mod entity_fluid_fixture; +mod entity_move_fixture; +mod entity_obstruction_fixture; +mod extra_items_fixture; +mod face_support_fixture; +mod face_visibility_fixture; +mod fall_damage_fixture; +mod feature_catalog_fixture; +mod feature_graph_fixture; +mod feature_placement_fixture; +mod feature_region_fixture; +mod feature_sort_fixture; +mod fill_layer_fixture; +mod fluid_box_fixture; +mod fluid_fixture; +mod fluid_flow_fixture; +mod fluid_occupancy_fixture; +mod fluid_shape_fixture; +mod food_fixture; +mod food_properties_fixture; +mod food_storage_fixture; +mod ground_state_fixture; +mod height_provider_fixture; +mod heightmap_fixture; +mod interaction_shape_fixture; +mod inventory_pickup_fixture; +mod inventory_tick_fixture; +mod inventory_use_fixture; +mod inventory_use_start_fixture; +mod item_after_use_fixture; +mod item_blocking_fixture; +mod item_cooldowns_fixture; +mod item_durability_fixture; +mod item_particles_fixture; +mod item_stack_storage_fixture; +mod item_template_fixture; +mod item_use_catalog_fixture; +mod item_use_fixture; +mod item_use_lifecycle_fixture; +mod item_use_start_fixture; +mod java_hash_map_fixture; +mod java_identity_map_fixture; +mod level_place_fixture; +mod level_shape_fixture; +mod live_attribute_updates_fixture; +mod live_attributes_fixture; +mod living_air_fixture; +mod living_damage_fixture; +mod living_fall_fixture; +mod living_fluid_fixture; +mod living_health_fixture; +mod living_hurt_fixture; +mod living_landing_fixture; +mod living_motion_fixture; +mod material_condition_fixture; +mod material_extension_fixture; +mod material_stage_fixture; +mod material_surface_fixture; +mod movement_emission_fixture; +mod movement_registry_fixture; +mod movement_support_fixture; +mod object_open_map_fixture; +mod object_open_set_fixture; +mod piston_movement_fixture; +mod piston_shape_fixture; +mod placement_fixture; +mod player_equipment_fixture; +mod player_food_fixture; +mod player_health_fixture; +mod player_hurt_fixture; +mod player_inventory_fixture; +mod player_travel_fixture; +mod portal_travel_fixture; +mod registered_player_combat_fixture; +mod registry_collision_scan_fixture; +mod registry_fall_ray_fixture; +mod registry_fluid_fixture; +mod replace_block_fixture; +mod restitution_fixture; +mod retrogen_data_fixture; +mod rule_test_fixture; +mod scattered_ore_fixture; +mod server_player_combat_fixture; +mod server_player_damage_fixture; +mod simple_block_fixture; +mod simple_container_fixture; +mod spawn_origin; +mod state_provider_fixture; +mod status_effect_fixture; +mod status_tick_fixture; +mod stepped_interpolation_fixture; +mod stored_consume_fixture; +mod stored_effect_attributes_fixture; +mod stored_effect_notifications_fixture; +mod structure_density_fixture; +mod suffocation_fixture; +mod swimming_fixture; +mod synced_bytes_fixture; +mod synced_floats_fixture; +mod teleport_consume_fixture; +mod terrain_fixture; +mod tick_fixture; +mod tree_feature_fixture; +mod use_flag_reaction_fixture; +mod use_remainder_fixture; +mod value_provider_fixture; +mod view_direction_fixture; +mod water_splash_fixture; +mod world_border_fixture; +mod world_fixture; +mod world_ray_fixture; +mod worldgen_random_fixture; + +/// `run(name)` runs the probe module `name`; NAMES lists them. +macro_rules! probes { + ($($name:ident,)*) => { + const NAMES: &[&str] = &[$(stringify!($name)),*]; + + fn run(name: &str) -> Option { + Some(match name { + $(stringify!($name) => $name::main().report(),)* + _ => return None, + }) + } + }; +} + +probes! { + active_effect_tick_fixture, + active_effects_fixture, + anchor_fixture, + attribute_fixture, + attribute_health_fixture, + attribute_map_queries_fixture, + attribute_updates_fixture, + basic_feature_fixture, + biome_chunk_fixture, + biome_generation_fixture, + biome_placement_fixture, + biome_source_codec_fixture, + biome_source_fixture, + biome_temperature_fixture, + block_collision_scan_fixture, + block_entity_storage_fixture, + block_landing_fixture, + block_properties_fixture, + block_push_fixture, + block_state_codec_fixture, + block_support_fixture, + block_survival_fixture, + block_update_fixture, + blocking_item_damage_fixture, + blocking_rules_fixture, + bulk_section_fixture, + bundle_weight_fixture, + canyon_carver_fixture, + carving_geometry_fixture, + carving_mask_fixture, + cave_carver_fixture, + chunk_dump, + chunk_stage_fixture, + chunk_status_fixture, + climbing_fixture, + collision_context_fixture, + collision_fixture, + combat_rules_fixture, + component_durability_fixture, + component_patch_fixture, + consumable_emission_fixture, + consumable_fixture, + consume_effect_fixture, + damage_immunity_fixture, + damage_reduction_fixture, + damage_source_fixture, + datafix_world, + decoration_fixture, + decoration_region_fixture, + dynamic_support_fixture, + edge_backoff_fixture, + effect_attribute_modifiers_fixture, + effect_notifications_fixture, + effect_sync_fixture, + entity_attribute_fixture, + entity_collision_fixture, + entity_fluid_fixture, + entity_move_fixture, + entity_obstruction_fixture, + extra_items_fixture, + face_support_fixture, + face_visibility_fixture, + fall_damage_fixture, + feature_catalog_fixture, + feature_graph_fixture, + feature_placement_fixture, + feature_region_fixture, + feature_sort_fixture, + fill_layer_fixture, + fluid_box_fixture, + fluid_fixture, + fluid_flow_fixture, + fluid_occupancy_fixture, + fluid_shape_fixture, + food_fixture, + food_properties_fixture, + food_storage_fixture, + ground_state_fixture, + height_provider_fixture, + heightmap_fixture, + interaction_shape_fixture, + inventory_pickup_fixture, + inventory_tick_fixture, + inventory_use_fixture, + inventory_use_start_fixture, + item_after_use_fixture, + item_blocking_fixture, + item_cooldowns_fixture, + item_durability_fixture, + item_particles_fixture, + item_stack_storage_fixture, + item_template_fixture, + item_use_catalog_fixture, + item_use_fixture, + item_use_lifecycle_fixture, + item_use_start_fixture, + java_hash_map_fixture, + java_identity_map_fixture, + level_place_fixture, + level_shape_fixture, + live_attribute_updates_fixture, + live_attributes_fixture, + living_air_fixture, + living_damage_fixture, + living_fall_fixture, + living_fluid_fixture, + living_health_fixture, + living_hurt_fixture, + living_landing_fixture, + living_motion_fixture, + material_condition_fixture, + material_extension_fixture, + material_stage_fixture, + material_surface_fixture, + movement_emission_fixture, + movement_registry_fixture, + movement_support_fixture, + object_open_map_fixture, + object_open_set_fixture, + piston_movement_fixture, + piston_shape_fixture, + placement_fixture, + player_equipment_fixture, + player_food_fixture, + player_health_fixture, + player_hurt_fixture, + player_inventory_fixture, + player_travel_fixture, + portal_travel_fixture, + registered_player_combat_fixture, + registry_collision_scan_fixture, + registry_fall_ray_fixture, + registry_fluid_fixture, + replace_block_fixture, + restitution_fixture, + retrogen_data_fixture, + rule_test_fixture, + scattered_ore_fixture, + server_player_combat_fixture, + server_player_damage_fixture, + simple_block_fixture, + simple_container_fixture, + spawn_origin, + state_provider_fixture, + status_effect_fixture, + status_tick_fixture, + stepped_interpolation_fixture, + stored_consume_fixture, + stored_effect_attributes_fixture, + stored_effect_notifications_fixture, + structure_density_fixture, + suffocation_fixture, + swimming_fixture, + synced_bytes_fixture, + synced_floats_fixture, + teleport_consume_fixture, + terrain_fixture, + tick_fixture, + tree_feature_fixture, + use_flag_reaction_fixture, + use_remainder_fixture, + value_provider_fixture, + view_direction_fixture, + water_splash_fixture, + world_border_fixture, + world_fixture, + world_ray_fixture, + worldgen_random_fixture, +} + +/// The probe's command line as its own example saw it: the program, then the arguments after the probe's name. +fn args() -> std::vec::IntoIter { + let mut args: Vec = std::env::args().collect(); + if args.len() > 1 { + args.remove(1); + } + args.into_iter() +} + +fn main() -> ExitCode { + let name = std::env::args().nth(1).unwrap_or_default(); + run(&name).unwrap_or_else(|| { + eprintln!( + "usage: probe [arguments...]\nprobes: {}", + NAMES.join(" ") + ); + ExitCode::from(2) + }) +} diff --git a/crates/horizon-world/examples/material_condition_fixture.rs b/crates/horizon-world/examples/probe/material_condition_fixture.rs similarity index 99% rename from crates/horizon-world/examples/material_condition_fixture.rs rename to crates/horizon-world/examples/probe/material_condition_fixture.rs index 0cbb03168..86017d1eb 100644 --- a/crates/horizon-world/examples/material_condition_fixture.rs +++ b/crates/horizon-world/examples/probe/material_condition_fixture.rs @@ -646,8 +646,8 @@ where } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); let definitions = serde_json::from_str(&fs::read_to_string(dir.join("conditions.json"))?)?; diff --git a/crates/horizon-world/examples/material_extension_fixture.rs b/crates/horizon-world/examples/probe/material_extension_fixture.rs similarity index 98% rename from crates/horizon-world/examples/material_extension_fixture.rs rename to crates/horizon-world/examples/probe/material_extension_fixture.rs index a48943723..1d7170b6d 100644 --- a/crates/horizon-world/examples/material_extension_fixture.rs +++ b/crates/horizon-world/examples/probe/material_extension_fixture.rs @@ -189,8 +189,8 @@ where } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let noises = serde_json::from_str(&fs::read_to_string(dir.join("noises.json"))?)?; let biomes = serde_json::from_str(&fs::read_to_string(dir.join("biomes.json"))?)?; diff --git a/crates/horizon-world/examples/material_stage_fixture.rs b/crates/horizon-world/examples/probe/material_stage_fixture.rs similarity index 99% rename from crates/horizon-world/examples/material_stage_fixture.rs rename to crates/horizon-world/examples/probe/material_stage_fixture.rs index 6682b04b7..9ae27db9d 100644 --- a/crates/horizon-world/examples/material_stage_fixture.rs +++ b/crates/horizon-world/examples/probe/material_stage_fixture.rs @@ -705,8 +705,8 @@ fn dump( } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name: &str| -> Result, Box> { Ok(serde_json::from_str(&fs::read_to_string( diff --git a/crates/horizon-world/examples/material_surface_fixture.rs b/crates/horizon-world/examples/probe/material_surface_fixture.rs similarity index 97% rename from crates/horizon-world/examples/material_surface_fixture.rs rename to crates/horizon-world/examples/probe/material_surface_fixture.rs index c7cb93bbd..3b3373f86 100644 --- a/crates/horizon-world/examples/material_surface_fixture.rs +++ b/crates/horizon-world/examples/probe/material_surface_fixture.rs @@ -105,8 +105,8 @@ fn fixture( } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private directory"); let dir = Path::new(&arg); let noises: BTreeMap = serde_json::from_str(&fs::read_to_string(dir.join("noises.json"))?)?; diff --git a/crates/horizon-world/examples/movement_emission_fixture.rs b/crates/horizon-world/examples/probe/movement_emission_fixture.rs similarity index 98% rename from crates/horizon-world/examples/movement_emission_fixture.rs rename to crates/horizon-world/examples/probe/movement_emission_fixture.rs index 36439e118..b49ac7b33 100644 --- a/crates/horizon-world/examples/movement_emission_fixture.rs +++ b/crates/horizon-world/examples/probe/movement_emission_fixture.rs @@ -178,8 +178,8 @@ impl MovementEmissionWorld for World<'_> { Ok(emission(&self.f["flap_emission"])) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/movement_registry_fixture.rs b/crates/horizon-world/examples/probe/movement_registry_fixture.rs similarity index 97% rename from crates/horizon-world/examples/movement_registry_fixture.rs rename to crates/horizon-world/examples/probe/movement_registry_fixture.rs index a04f5c124..4ebe76a39 100644 --- a/crates/horizon-world/examples/movement_registry_fixture.rs +++ b/crates/horizon-world/examples/probe/movement_registry_fixture.rs @@ -48,8 +48,8 @@ impl MovementBlockProvider for World<'_> { )) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); let read = |name: &str| -> Result> { diff --git a/crates/horizon-world/examples/movement_support_fixture.rs b/crates/horizon-world/examples/probe/movement_support_fixture.rs similarity index 97% rename from crates/horizon-world/examples/movement_support_fixture.rs rename to crates/horizon-world/examples/probe/movement_support_fixture.rs index 096559250..df6ffb046 100644 --- a/crates/horizon-world/examples/movement_support_fixture.rs +++ b/crates/horizon-world/examples/probe/movement_support_fixture.rs @@ -84,8 +84,8 @@ impl MovementBlockWorld for World<'_> { self.factor(id, "speed") } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/object_open_map_fixture.rs b/crates/horizon-world/examples/probe/object_open_map_fixture.rs similarity index 98% rename from crates/horizon-world/examples/object_open_map_fixture.rs rename to crates/horizon-world/examples/probe/object_open_map_fixture.rs index 63073aa8d..ae03169dd 100644 --- a/crates/horizon-world/examples/object_open_map_fixture.rs +++ b/crates/horizon-world/examples/probe/object_open_map_fixture.rs @@ -74,8 +74,8 @@ fn mutation(map: &mut ObjectOpenMap, keys: &[Key], op: &Value) -> Stri _ => panic!("mutation"), } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/object_open_set_fixture.rs b/crates/horizon-world/examples/probe/object_open_set_fixture.rs similarity index 96% rename from crates/horizon-world/examples/object_open_set_fixture.rs rename to crates/horizon-world/examples/probe/object_open_set_fixture.rs index d4c06f39d..c624d336d 100644 --- a/crates/horizon-world/examples/object_open_set_fixture.rs +++ b/crates/horizon-world/examples/probe/object_open_set_fixture.rs @@ -25,8 +25,8 @@ impl ObjectKey for Key { fn desc(key: Option<&Key>) -> String { key.map_or("null".into(), |k| format!("{}:{}", k.id, k.object)) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/piston_movement_fixture.rs b/crates/horizon-world/examples/probe/piston_movement_fixture.rs similarity index 93% rename from crates/horizon-world/examples/piston_movement_fixture.rs rename to crates/horizon-world/examples/probe/piston_movement_fixture.rs index 3c324aa00..68af8348e 100644 --- a/crates/horizon-world/examples/piston_movement_fixture.rs +++ b/crates/horizon-world/examples/probe/piston_movement_fixture.rs @@ -19,8 +19,8 @@ fn bits(v: f64) -> u64 { v.to_bits() } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/piston_shape_fixture.rs b/crates/horizon-world/examples/probe/piston_shape_fixture.rs similarity index 97% rename from crates/horizon-world/examples/piston_shape_fixture.rs rename to crates/horizon-world/examples/probe/piston_shape_fixture.rs index 06c62803b..4eb07b4d8 100644 --- a/crates/horizon-world/examples/piston_shape_fixture.rs +++ b/crates/horizon-world/examples/probe/piston_shape_fixture.rs @@ -125,8 +125,8 @@ fn number(v: &Value) -> f32 { fn float_bits(v: f32) -> u32 { if v.is_nan() { 0x7fc0_0000 } else { v.to_bits() } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name: &str| -> Result> { Ok( diff --git a/crates/horizon-world/examples/placement_fixture.rs b/crates/horizon-world/examples/probe/placement_fixture.rs similarity index 94% rename from crates/horizon-world/examples/placement_fixture.rs rename to crates/horizon-world/examples/probe/placement_fixture.rs index b3e6c4747..6214e630e 100644 --- a/crates/horizon-world/examples/placement_fixture.rs +++ b/crates/horizon-world/examples/probe/placement_fixture.rs @@ -1,6 +1,5 @@ //! Transport for placement decoding, emissions, failures and random state. -#[path = "support/placement_queries.rs"] -mod queries; +use crate::support::placement_queries as queries; use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; use horizon_world::worldgen::{anchor::WorldGenerationContext, placement::PlacementModifier}; use serde_json::Value; @@ -67,8 +66,8 @@ fn fixture( writeln!(out.borrow_mut(), "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/player_equipment_fixture.rs b/crates/horizon-world/examples/probe/player_equipment_fixture.rs similarity index 98% rename from crates/horizon-world/examples/player_equipment_fixture.rs rename to crates/horizon-world/examples/probe/player_equipment_fixture.rs index a7349b78c..0a356e31d 100644 --- a/crates/horizon-world/examples/player_equipment_fixture.rs +++ b/crates/horizon-world/examples/probe/player_equipment_fixture.rs @@ -131,8 +131,8 @@ impl EquipWorld for World { } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/player_food_fixture.rs b/crates/horizon-world/examples/probe/player_food_fixture.rs similarity index 97% rename from crates/horizon-world/examples/player_food_fixture.rs rename to crates/horizon-world/examples/probe/player_food_fixture.rs index 7478be35f..e2ef7d450 100644 --- a/crates/horizon-world/examples/player_food_fixture.rs +++ b/crates/horizon-world/examples/probe/player_food_fixture.rs @@ -96,8 +96,8 @@ fn run(w: &mut W, f: &Value) -> Result, W::Erro _ => panic!("mode"), } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/player_health_fixture.rs b/crates/horizon-world/examples/probe/player_health_fixture.rs similarity index 98% rename from crates/horizon-world/examples/player_health_fixture.rs rename to crates/horizon-world/examples/probe/player_health_fixture.rs index f7b687f65..4a4987de3 100644 --- a/crates/horizon-world/examples/player_health_fixture.rs +++ b/crates/horizon-world/examples/probe/player_health_fixture.rs @@ -96,8 +96,8 @@ impl State { .unwrap() } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let ids: Value = serde_json::from_str(&fs::read_to_string(dir.join("ids.json"))?)?; let ids = PlayerFloatIds { diff --git a/crates/horizon-world/examples/player_hurt_fixture.rs b/crates/horizon-world/examples/probe/player_hurt_fixture.rs similarity index 99% rename from crates/horizon-world/examples/player_hurt_fixture.rs rename to crates/horizon-world/examples/probe/player_hurt_fixture.rs index 54a5ed5e4..765f7b04b 100644 --- a/crates/horizon-world/examples/player_hurt_fixture.rs +++ b/crates/horizon-world/examples/probe/player_hurt_fixture.rs @@ -263,8 +263,8 @@ impl ServerPlayerHurtWorld for Env<'_> { Ok(self.flag("can_harm")) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/player_inventory_fixture.rs b/crates/horizon-world/examples/probe/player_inventory_fixture.rs similarity index 99% rename from crates/horizon-world/examples/player_inventory_fixture.rs rename to crates/horizon-world/examples/probe/player_inventory_fixture.rs index a3e2625e2..418fb9a3e 100644 --- a/crates/horizon-world/examples/player_inventory_fixture.rs +++ b/crates/horizon-world/examples/probe/player_inventory_fixture.rs @@ -142,8 +142,8 @@ impl Output { writeln!(self.out, "empty {e}").unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/player_travel_fixture.rs b/crates/horizon-world/examples/probe/player_travel_fixture.rs similarity index 97% rename from crates/horizon-world/examples/player_travel_fixture.rs rename to crates/horizon-world/examples/probe/player_travel_fixture.rs index 47adeaeb7..5627ef6a2 100644 --- a/crates/horizon-world/examples/player_travel_fixture.rs +++ b/crates/horizon-world/examples/probe/player_travel_fixture.rs @@ -115,8 +115,8 @@ impl PlayerTravelWorld for World<'_> { Ok(()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/portal_travel_fixture.rs b/crates/horizon-world/examples/probe/portal_travel_fixture.rs similarity index 98% rename from crates/horizon-world/examples/portal_travel_fixture.rs rename to crates/horizon-world/examples/probe/portal_travel_fixture.rs index b0843e411..cda3ae248 100644 --- a/crates/horizon-world/examples/portal_travel_fixture.rs +++ b/crates/horizon-world/examples/probe/portal_travel_fixture.rs @@ -246,8 +246,8 @@ fn run(case: &Value, b: &Behaviours, air: BlockStateId, out: &mut Vec) { )); } -fn main() -> Result<(), Box> { - let mut args = std::env::args().skip(1); +pub fn main() -> Result<(), Box> { + let mut args = crate::args().skip(1); let resources = args.next().expect("resource directory"); let cases = args.next().expect("case file"); let output = args.next().expect("output file"); diff --git a/crates/horizon-world/examples/registered_player_combat_fixture.rs b/crates/horizon-world/examples/probe/registered_player_combat_fixture.rs similarity index 99% rename from crates/horizon-world/examples/registered_player_combat_fixture.rs rename to crates/horizon-world/examples/probe/registered_player_combat_fixture.rs index 01afec289..4029b4918 100644 --- a/crates/horizon-world/examples/registered_player_combat_fixture.rs +++ b/crates/horizon-world/examples/probe/registered_player_combat_fixture.rs @@ -401,8 +401,8 @@ impl CombatEnvironment for Env<'_> { self.dead } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let damage_catalog = DamageCatalog::from_json( &serde_json::from_str(&fs::read_to_string(dir.join("damage/catalog.json"))?)?, diff --git a/crates/horizon-world/examples/registry_collision_scan_fixture.rs b/crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs similarity index 99% rename from crates/horizon-world/examples/registry_collision_scan_fixture.rs rename to crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs index 9e3a19914..f2504eab4 100644 --- a/crates/horizon-world/examples/registry_collision_scan_fixture.rs +++ b/crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs @@ -382,8 +382,8 @@ impl CollisionChunks for World<'_> { &mut self.chunks.get_mut(&(p.x, p.z)).unwrap().1 } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name| -> Result<_, Box> { Ok( diff --git a/crates/horizon-world/examples/registry_fall_ray_fixture.rs b/crates/horizon-world/examples/probe/registry_fall_ray_fixture.rs similarity index 97% rename from crates/horizon-world/examples/registry_fall_ray_fixture.rs rename to crates/horizon-world/examples/probe/registry_fall_ray_fixture.rs index 3f2ebce75..c3861308e 100644 --- a/crates/horizon-world/examples/registry_fall_ray_fixture.rs +++ b/crates/horizon-world/examples/probe/registry_fall_ray_fixture.rs @@ -86,8 +86,8 @@ impl FallRayWorld for World<'_, '_, '_> { Ok(self.f["delay"].as_i64().unwrap() as i32) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); let read = |n: &str| -> Result> { diff --git a/crates/horizon-world/examples/registry_fluid_fixture.rs b/crates/horizon-world/examples/probe/registry_fluid_fixture.rs similarity index 97% rename from crates/horizon-world/examples/registry_fluid_fixture.rs rename to crates/horizon-world/examples/probe/registry_fluid_fixture.rs index de6e111a6..45cd272b0 100644 --- a/crates/horizon-world/examples/registry_fluid_fixture.rs +++ b/crates/horizon-world/examples/probe/registry_fluid_fixture.rs @@ -67,8 +67,8 @@ impl DynamicSupportWorld for World<'_> { Ok(None) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); let load = |n: &str| -> Result<_, Box> { diff --git a/crates/horizon-world/examples/replace_block_fixture.rs b/crates/horizon-world/examples/probe/replace_block_fixture.rs similarity index 98% rename from crates/horizon-world/examples/replace_block_fixture.rs rename to crates/horizon-world/examples/probe/replace_block_fixture.rs index 7a8d00363..7d4f05d7c 100644 --- a/crates/horizon-world/examples/replace_block_fixture.rs +++ b/crates/horizon-world/examples/probe/replace_block_fixture.rs @@ -146,8 +146,8 @@ fn tag(v: &Value) -> Tag { _ => panic!("invalid registry metadata"), } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let registry = BlockRegistry::from_nbt(&Tag::compound([ diff --git a/crates/horizon-world/examples/restitution_fixture.rs b/crates/horizon-world/examples/probe/restitution_fixture.rs similarity index 97% rename from crates/horizon-world/examples/restitution_fixture.rs rename to crates/horizon-world/examples/probe/restitution_fixture.rs index d32532a82..1432d92a8 100644 --- a/crates/horizon-world/examples/restitution_fixture.rs +++ b/crates/horizon-world/examples/probe/restitution_fixture.rs @@ -121,8 +121,8 @@ impl RestitutionWorld for World<'_, W> { Ok(()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/retrogen_data_fixture.rs b/crates/horizon-world/examples/probe/retrogen_data_fixture.rs similarity index 97% rename from crates/horizon-world/examples/retrogen_data_fixture.rs rename to crates/horizon-world/examples/probe/retrogen_data_fixture.rs index 1f35cb363..3980d1234 100644 --- a/crates/horizon-world/examples/retrogen_data_fixture.rs +++ b/crates/horizon-world/examples/probe/retrogen_data_fixture.rs @@ -51,8 +51,8 @@ fn tag(row: &Value) -> Tag { _ => panic!("unknown tag"), } } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let mut out = io::BufWriter::new(fs::File::create(&args[2])?); for (index, line) in fs::read_to_string(&args[1])?.lines().enumerate() { writeln!(out, "case {index}")?; diff --git a/crates/horizon-world/examples/rule_test_fixture.rs b/crates/horizon-world/examples/probe/rule_test_fixture.rs similarity index 96% rename from crates/horizon-world/examples/rule_test_fixture.rs rename to crates/horizon-world/examples/probe/rule_test_fixture.rs index 31fa4c436..8974eed1a 100644 --- a/crates/horizon-world/examples/rule_test_fixture.rs +++ b/crates/horizon-world/examples/probe/rule_test_fixture.rs @@ -52,8 +52,8 @@ fn tag(v: &Value) -> Tag { _ => panic!("invalid registry metadata"), } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let registry = BlockRegistry::from_nbt(&Tag::compound([ diff --git a/crates/horizon-world/examples/scattered_ore_fixture.rs b/crates/horizon-world/examples/probe/scattered_ore_fixture.rs similarity index 98% rename from crates/horizon-world/examples/scattered_ore_fixture.rs rename to crates/horizon-world/examples/probe/scattered_ore_fixture.rs index bc9dd9200..2c43f2b83 100644 --- a/crates/horizon-world/examples/scattered_ore_fixture.rs +++ b/crates/horizon-world/examples/probe/scattered_ore_fixture.rs @@ -170,8 +170,8 @@ fn tag(v: &Value) -> Tag { _ => panic!("invalid registry metadata"), } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let registry = BlockRegistry::from_nbt(&Tag::compound([ diff --git a/crates/horizon-world/examples/server_player_combat_fixture.rs b/crates/horizon-world/examples/probe/server_player_combat_fixture.rs similarity index 99% rename from crates/horizon-world/examples/server_player_combat_fixture.rs rename to crates/horizon-world/examples/probe/server_player_combat_fixture.rs index ac911a7c8..cceb1f001 100644 --- a/crates/horizon-world/examples/server_player_combat_fixture.rs +++ b/crates/horizon-world/examples/probe/server_player_combat_fixture.rs @@ -461,10 +461,10 @@ impl CombatEnvironment for Env<'_> { self.dead } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); - if std::env::args().nth(2).as_deref() == Some("--live") { + if crate::args().nth(2).as_deref() == Some("--live") { run::(dir, "rust-live.txt") } else { run::(dir, "rust.txt") diff --git a/crates/horizon-world/examples/server_player_damage_fixture.rs b/crates/horizon-world/examples/probe/server_player_damage_fixture.rs similarity index 98% rename from crates/horizon-world/examples/server_player_damage_fixture.rs rename to crates/horizon-world/examples/probe/server_player_damage_fixture.rs index e6eadb806..fadcbf83f 100644 --- a/crates/horizon-world/examples/server_player_damage_fixture.rs +++ b/crates/horizon-world/examples/probe/server_player_damage_fixture.rs @@ -182,8 +182,8 @@ impl ServerDamageEnvironment for Env<'_> { self.event("damage-event") } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let ids: Value = serde_json::from_str(&fs::read_to_string(dir.join("ids.json"))?)?; let ids = PlayerFloatIds { diff --git a/crates/horizon-world/examples/simple_block_fixture.rs b/crates/horizon-world/examples/probe/simple_block_fixture.rs similarity index 99% rename from crates/horizon-world/examples/simple_block_fixture.rs rename to crates/horizon-world/examples/probe/simple_block_fixture.rs index 742f3b39f..232e56f94 100644 --- a/crates/horizon-world/examples/simple_block_fixture.rs +++ b/crates/horizon-world/examples/probe/simple_block_fixture.rs @@ -553,8 +553,8 @@ fn fixture( )?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name: &str| -> Result> { Ok( diff --git a/crates/horizon-world/examples/simple_container_fixture.rs b/crates/horizon-world/examples/probe/simple_container_fixture.rs similarity index 98% rename from crates/horizon-world/examples/simple_container_fixture.rs rename to crates/horizon-world/examples/probe/simple_container_fixture.rs index 44f9a382a..c6aef9c2a 100644 --- a/crates/horizon-world/examples/simple_container_fixture.rs +++ b/crates/horizon-world/examples/probe/simple_container_fixture.rs @@ -120,8 +120,8 @@ impl ContainerHooks for World { self.event(c, "changed") } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/spawn_origin.rs b/crates/horizon-world/examples/probe/spawn_origin.rs similarity index 96% rename from crates/horizon-world/examples/spawn_origin.rs rename to crates/horizon-world/examples/probe/spawn_origin.rs index 727b25a91..bf62726af 100644 --- a/crates/horizon-world/examples/spawn_origin.rs +++ b/crates/horizon-world/examples/probe/spawn_origin.rs @@ -39,8 +39,8 @@ fn registry(resources: &Path) -> Result<&'static BlockRegistry, Error> { Ok(Box::leak(Box::new(registry))) } -fn main() -> Result<(), Error> { - let mut args = std::env::args().skip(1); +pub fn main() -> Result<(), Error> { + let mut args = crate::args().skip(1); let resources = std::path::PathBuf::from(args.next().ok_or("client resource directory")?); let data = GeneratorData::load(&resources.join("worldgen"), registry(&resources)?)?; for seed in args { diff --git a/crates/horizon-world/examples/state_provider_fixture.rs b/crates/horizon-world/examples/probe/state_provider_fixture.rs similarity index 99% rename from crates/horizon-world/examples/state_provider_fixture.rs rename to crates/horizon-world/examples/probe/state_provider_fixture.rs index e8a8f9f5a..68d91a1cf 100644 --- a/crates/horizon-world/examples/state_provider_fixture.rs +++ b/crates/horizon-world/examples/probe/state_provider_fixture.rs @@ -299,8 +299,8 @@ fn tag(v: &Value) -> Tag { _ => panic!("invalid registry metadata"), } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let registry = BlockRegistry::from_nbt(&Tag::compound([ diff --git a/crates/horizon-world/examples/status_effect_fixture.rs b/crates/horizon-world/examples/probe/status_effect_fixture.rs similarity index 97% rename from crates/horizon-world/examples/status_effect_fixture.rs rename to crates/horizon-world/examples/probe/status_effect_fixture.rs index 759aad818..c1307dd3a 100644 --- a/crates/horizon-world/examples/status_effect_fixture.rs +++ b/crates/horizon-world/examples/probe/status_effect_fixture.rs @@ -138,8 +138,8 @@ fn run(f: Value, out: &mut dyn Write) { dump(out, &slots, &mut ids); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/status_tick_fixture.rs b/crates/horizon-world/examples/probe/status_tick_fixture.rs similarity index 98% rename from crates/horizon-world/examples/status_tick_fixture.rs rename to crates/horizon-world/examples/probe/status_tick_fixture.rs index 22aa0d412..23492971c 100644 --- a/crates/horizon-world/examples/status_tick_fixture.rs +++ b/crates/horizon-world/examples/probe/status_tick_fixture.rs @@ -210,8 +210,8 @@ fn run(f: Value, out: &mut dyn Write) { w.all(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/stepped_interpolation_fixture.rs b/crates/horizon-world/examples/probe/stepped_interpolation_fixture.rs similarity index 98% rename from crates/horizon-world/examples/stepped_interpolation_fixture.rs rename to crates/horizon-world/examples/probe/stepped_interpolation_fixture.rs index d2228d8b5..568e5ded8 100644 --- a/crates/horizon-world/examples/stepped_interpolation_fixture.rs +++ b/crates/horizon-world/examples/probe/stepped_interpolation_fixture.rs @@ -10,8 +10,8 @@ fn set_rot(entity: &mut PosRot, yaw: f32, pitch: f32) { entity.pitch = (pitch % 360.0 % 360.0).clamp(-90.0, 90.0); } -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let input = std::fs::read_to_string(&args[1]).expect("input"); let mut out = String::new(); let mut handler = SteppedInterpolation::new(0); diff --git a/crates/horizon-world/examples/stored_consume_fixture.rs b/crates/horizon-world/examples/probe/stored_consume_fixture.rs similarity index 98% rename from crates/horizon-world/examples/stored_consume_fixture.rs rename to crates/horizon-world/examples/probe/stored_consume_fixture.rs index 7fd9abc91..8f8f6046a 100644 --- a/crates/horizon-world/examples/stored_consume_fixture.rs +++ b/crates/horizon-world/examples/probe/stored_consume_fixture.rs @@ -390,9 +390,9 @@ fn run(f: Value, out: &mut dyn Write, make: fn(i64) -> R) { writeln!(w.out, "random {i} {} {}", r.next_long(), r.next_long()).unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); - let side = std::env::args().nth(2).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); + let side = crate::args().nth(2).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{side}.txt")))?); for line in fs::read_to_string(dir.join(format!("inputs-{side}.txt")))?.lines() { diff --git a/crates/horizon-world/examples/stored_effect_attributes_fixture.rs b/crates/horizon-world/examples/probe/stored_effect_attributes_fixture.rs similarity index 99% rename from crates/horizon-world/examples/stored_effect_attributes_fixture.rs rename to crates/horizon-world/examples/probe/stored_effect_attributes_fixture.rs index 6abc4f79f..b904a0520 100644 --- a/crates/horizon-world/examples/stored_effect_attributes_fixture.rs +++ b/crates/horizon-world/examples/probe/stored_effect_attributes_fixture.rs @@ -348,8 +348,8 @@ fn effect_error(e: effects::Error) -> Stop { effects::Error::MissingTemplate | effects::Error::Cursor(_) => Stop::Null, } } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let dir = Path::new(&args[1]); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{}.txt", args[2])))?); for line in fs::read_to_string(dir.join(format!("inputs-{}.txt", args[2])))?.lines() { diff --git a/crates/horizon-world/examples/stored_effect_notifications_fixture.rs b/crates/horizon-world/examples/probe/stored_effect_notifications_fixture.rs similarity index 99% rename from crates/horizon-world/examples/stored_effect_notifications_fixture.rs rename to crates/horizon-world/examples/probe/stored_effect_notifications_fixture.rs index 96c089857..31b4b047b 100644 --- a/crates/horizon-world/examples/stored_effect_notifications_fixture.rs +++ b/crates/horizon-world/examples/probe/stored_effect_notifications_fixture.rs @@ -169,7 +169,7 @@ mod integration { } } pub fn run() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); + let args: Vec<_> = crate::args().collect(); let dir = Path::new(&args[1]); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{}.txt", args[2])))?); @@ -352,6 +352,6 @@ mod integration { Ok(()) } } -fn main() -> Result<(), Box> { +pub fn main() -> Result<(), Box> { integration::run() } diff --git a/crates/horizon-world/examples/structure_density_fixture.rs b/crates/horizon-world/examples/probe/structure_density_fixture.rs similarity index 96% rename from crates/horizon-world/examples/structure_density_fixture.rs rename to crates/horizon-world/examples/probe/structure_density_fixture.rs index 55ef66f83..2159bc566 100644 --- a/crates/horizon-world/examples/structure_density_fixture.rs +++ b/crates/horizon-world/examples/probe/structure_density_fixture.rs @@ -31,8 +31,8 @@ fn bits(value: f32) -> u32 { value.to_bits() } } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let mut out = io::BufWriter::new(fs::File::create(&args[2])?); for line in fs::read_to_string(&args[1])?.lines() { let f: Value = serde_json::from_str(line)?; diff --git a/crates/horizon-world/examples/suffocation_fixture.rs b/crates/horizon-world/examples/probe/suffocation_fixture.rs similarity index 97% rename from crates/horizon-world/examples/suffocation_fixture.rs rename to crates/horizon-world/examples/probe/suffocation_fixture.rs index 79a3ccfa0..3e1683394 100644 --- a/crates/horizon-world/examples/suffocation_fixture.rs +++ b/crates/horizon-world/examples/probe/suffocation_fixture.rs @@ -58,8 +58,8 @@ impl DynamicCollisionWorld for World<'_, W> { Ok(None) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name| -> Result<_, Box> { Ok( diff --git a/crates/horizon-world/examples/support/decoration_storage.rs b/crates/horizon-world/examples/probe/support/decoration_storage.rs similarity index 100% rename from crates/horizon-world/examples/support/decoration_storage.rs rename to crates/horizon-world/examples/probe/support/decoration_storage.rs diff --git a/crates/horizon-world/examples/support/placement_queries.rs b/crates/horizon-world/examples/probe/support/placement_queries.rs similarity index 100% rename from crates/horizon-world/examples/support/placement_queries.rs rename to crates/horizon-world/examples/probe/support/placement_queries.rs diff --git a/crates/horizon-world/examples/swimming_fixture.rs b/crates/horizon-world/examples/probe/swimming_fixture.rs similarity index 96% rename from crates/horizon-world/examples/swimming_fixture.rs rename to crates/horizon-world/examples/probe/swimming_fixture.rs index ebf58cf8b..b31c3a109 100644 --- a/crates/horizon-world/examples/swimming_fixture.rs +++ b/crates/horizon-world/examples/probe/swimming_fixture.rs @@ -79,8 +79,8 @@ impl PlayerSwimmingWorld for World<'_> { self.f["flying"].as_bool().unwrap() } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/synced_bytes_fixture.rs b/crates/horizon-world/examples/probe/synced_bytes_fixture.rs similarity index 98% rename from crates/horizon-world/examples/synced_bytes_fixture.rs rename to crates/horizon-world/examples/probe/synced_bytes_fixture.rs index 288e5fa7c..b6932a4fe 100644 --- a/crates/horizon-world/examples/synced_bytes_fixture.rs +++ b/crates/horizon-world/examples/probe/synced_bytes_fixture.rs @@ -114,8 +114,8 @@ impl Observer for Callback<'_> { self.event(&format!("assigned {}", values(Some(v)))) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/synced_floats_fixture.rs b/crates/horizon-world/examples/probe/synced_floats_fixture.rs similarity index 98% rename from crates/horizon-world/examples/synced_floats_fixture.rs rename to crates/horizon-world/examples/probe/synced_floats_fixture.rs index 4eb2e8046..8209c4aa5 100644 --- a/crates/horizon-world/examples/synced_floats_fixture.rs +++ b/crates/horizon-world/examples/probe/synced_floats_fixture.rs @@ -102,8 +102,8 @@ impl Observer for Callback<'_> { self.event(&format!("assigned {}", values(Some(v)))) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/teleport_consume_fixture.rs b/crates/horizon-world/examples/probe/teleport_consume_fixture.rs similarity index 98% rename from crates/horizon-world/examples/teleport_consume_fixture.rs rename to crates/horizon-world/examples/probe/teleport_consume_fixture.rs index 0c21b359c..cf82d3b67 100644 --- a/crates/horizon-world/examples/teleport_consume_fixture.rs +++ b/crates/horizon-world/examples/probe/teleport_consume_fixture.rs @@ -220,8 +220,8 @@ fn run(f: Value, out: &mut dyn Write, make: fn(i64) -> R) { writeln!(w.out, "random {i} {} {}", r.next_long(), r.next_long()).unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/terrain_fixture.rs b/crates/horizon-world/examples/probe/terrain_fixture.rs similarity index 98% rename from crates/horizon-world/examples/terrain_fixture.rs rename to crates/horizon-world/examples/probe/terrain_fixture.rs index 09868a340..7d23227d9 100644 --- a/crates/horizon-world/examples/terrain_fixture.rs +++ b/crates/horizon-world/examples/probe/terrain_fixture.rs @@ -239,8 +239,8 @@ fn fixture( } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let bundle: Value = serde_json::from_str(&fs::read_to_string(dir.join("registries.json"))?)?; diff --git a/crates/horizon-world/examples/tick_fixture.rs b/crates/horizon-world/examples/probe/tick_fixture.rs similarity index 93% rename from crates/horizon-world/examples/tick_fixture.rs rename to crates/horizon-world/examples/probe/tick_fixture.rs index 7b5bfa8ed..9e31fa5b6 100644 --- a/crates/horizon-world/examples/tick_fixture.rs +++ b/crates/horizon-world/examples/probe/tick_fixture.rs @@ -11,12 +11,8 @@ use horizon_world::{ tick_data::TickKind, }; use std::{collections::BTreeMap, error::Error, fs, path::PathBuf}; -fn main() -> Result<(), Box> { - let base = PathBuf::from( - std::env::args() - .nth(1) - .ok_or("expected fixture directory")?, - ); +pub fn main() -> Result<(), Box> { + let base = PathBuf::from(crate::args().nth(1).ok_or("expected fixture directory")?); let bytes = fs::read(base.join("ticks-input.nbt"))?; let (root, used) = nbt::read_named(&bytes, Limits::default())?; assert_eq!(used, bytes.len()); diff --git a/crates/horizon-world/examples/tree_feature_fixture.rs b/crates/horizon-world/examples/probe/tree_feature_fixture.rs similarity index 99% rename from crates/horizon-world/examples/tree_feature_fixture.rs rename to crates/horizon-world/examples/probe/tree_feature_fixture.rs index 0de4fd562..3222254bd 100644 --- a/crates/horizon-world/examples/tree_feature_fixture.rs +++ b/crates/horizon-world/examples/probe/tree_feature_fixture.rs @@ -486,8 +486,8 @@ fn survival_rule(rule: &str) -> SurvivalRule { _ => panic!("unknown rule {rule}"), } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name: &str| -> Result> { Ok( diff --git a/crates/horizon-world/examples/use_flag_reaction_fixture.rs b/crates/horizon-world/examples/probe/use_flag_reaction_fixture.rs similarity index 99% rename from crates/horizon-world/examples/use_flag_reaction_fixture.rs rename to crates/horizon-world/examples/probe/use_flag_reaction_fixture.rs index 038b529fc..6c7c7fb97 100644 --- a/crates/horizon-world/examples/use_flag_reaction_fixture.rs +++ b/crates/horizon-world/examples/probe/use_flag_reaction_fixture.rs @@ -243,8 +243,8 @@ impl DurationServices for Services { Ok(self.config()["durations"][kind].as_i64().unwrap() as i32) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/use_remainder_fixture.rs b/crates/horizon-world/examples/probe/use_remainder_fixture.rs similarity index 99% rename from crates/horizon-world/examples/use_remainder_fixture.rs rename to crates/horizon-world/examples/probe/use_remainder_fixture.rs index b572b3ce9..534abb167 100644 --- a/crates/horizon-world/examples/use_remainder_fixture.rs +++ b/crates/horizon-world/examples/probe/use_remainder_fixture.rs @@ -115,8 +115,8 @@ fn all( } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/value_provider_fixture.rs b/crates/horizon-world/examples/probe/value_provider_fixture.rs similarity index 94% rename from crates/horizon-world/examples/value_provider_fixture.rs rename to crates/horizon-world/examples/probe/value_provider_fixture.rs index be7bf8afe..9cb895e1c 100644 --- a/crates/horizon-world/examples/value_provider_fixture.rs +++ b/crates/horizon-world/examples/probe/value_provider_fixture.rs @@ -51,8 +51,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/view_direction_fixture.rs b/crates/horizon-world/examples/probe/view_direction_fixture.rs similarity index 94% rename from crates/horizon-world/examples/view_direction_fixture.rs rename to crates/horizon-world/examples/probe/view_direction_fixture.rs index 6fa6ccd55..0121de934 100644 --- a/crates/horizon-world/examples/view_direction_fixture.rs +++ b/crates/horizon-world/examples/probe/view_direction_fixture.rs @@ -22,8 +22,8 @@ fn bits(v: f64) -> u64 { v.to_bits() } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/water_splash_fixture.rs b/crates/horizon-world/examples/probe/water_splash_fixture.rs similarity index 97% rename from crates/horizon-world/examples/water_splash_fixture.rs rename to crates/horizon-world/examples/probe/water_splash_fixture.rs index dd8c71080..08f5bd7b9 100644 --- a/crates/horizon-world/examples/water_splash_fixture.rs +++ b/crates/horizon-world/examples/probe/water_splash_fixture.rs @@ -154,8 +154,8 @@ fn run(f: &Value, out: &mut dyn Write, rng: R) -> io::Result<() writeln!(w.out, "next {}", w.rng.next_long())?; writeln!(w.out, "queries {}", w.calls) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); let input = fs::read_to_string(dir.join("inputs.txt"))?; diff --git a/crates/horizon-world/examples/world_border_fixture.rs b/crates/horizon-world/examples/probe/world_border_fixture.rs similarity index 97% rename from crates/horizon-world/examples/world_border_fixture.rs rename to crates/horizon-world/examples/probe/world_border_fixture.rs index 60cabdd3d..ba00b2ca0 100644 --- a/crates/horizon-world/examples/world_border_fixture.rs +++ b/crates/horizon-world/examples/probe/world_border_fixture.rs @@ -75,8 +75,8 @@ fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/world_fixture.rs b/crates/horizon-world/examples/probe/world_fixture.rs similarity index 96% rename from crates/horizon-world/examples/world_fixture.rs rename to crates/horizon-world/examples/probe/world_fixture.rs index d972643cc..fd89e767b 100644 --- a/crates/horizon-world/examples/world_fixture.rs +++ b/crates/horizon-world/examples/probe/world_fixture.rs @@ -6,12 +6,8 @@ use horizon_world::{ }; use std::{error::Error, fs, path::PathBuf}; -fn main() -> Result<(), Box> { - let base = PathBuf::from( - std::env::args() - .nth(1) - .ok_or("expected fixture directory")?, - ); +pub fn main() -> Result<(), Box> { + let base = PathBuf::from(crate::args().nth(1).ok_or("expected fixture directory")?); let output = base.join("rust/palettes"); fs::create_dir_all(&output)?; for entry in fs::read_dir(base.join("palettes"))? { diff --git a/crates/horizon-world/examples/world_ray_fixture.rs b/crates/horizon-world/examples/probe/world_ray_fixture.rs similarity index 98% rename from crates/horizon-world/examples/world_ray_fixture.rs rename to crates/horizon-world/examples/probe/world_ray_fixture.rs index b418785b0..5b8a3b9fb 100644 --- a/crates/horizon-world/examples/world_ray_fixture.rs +++ b/crates/horizon-world/examples/probe/world_ray_fixture.rs @@ -137,8 +137,8 @@ impl RayWorld for World<'_> { Ok(self.shapes[s][4].clone()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/worldgen_random_fixture.rs b/crates/horizon-world/examples/probe/worldgen_random_fixture.rs similarity index 97% rename from crates/horizon-world/examples/worldgen_random_fixture.rs rename to crates/horizon-world/examples/probe/worldgen_random_fixture.rs index 1cf37b1f9..1db24cf8a 100644 --- a/crates/horizon-world/examples/worldgen_random_fixture.rs +++ b/crates/horizon-world/examples/probe/worldgen_random_fixture.rs @@ -118,8 +118,8 @@ fn layers(f: &Value, mut source: impl WorldgenSource, out: &mut impl Write) -> i _ => panic!("unsupported layer count"), } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/docs/parity-workflow.md b/docs/parity-workflow.md index dde4b5d41..37202411c 100644 --- a/docs/parity-workflow.md +++ b/docs/parity-workflow.md @@ -26,6 +26,8 @@ Vanilla oracle runs are reused as well. `tools/parity_shim.py` stands in for `ja Probes build into `.local/parity-target/` with release optimisation but no LTO and 16 codegen units. On ludodesktop that rebuilds every `horizon-world` probe in 3 seconds after a one-line change, against 122 seconds with the release profile. Rust gives these settings identical results (no fast-math; overflow checks as in release), and the full harness suite passes under them. Probes that harnesses build in the dev profile get `opt-level = 3` too, keeping their overflow checks and debug assertions. Harnesses must locate binaries through `cargo metadata` or `lab.cargo_target()`, never a hard-coded `target/`. +The `horizon-world` probes are one binary, `cargo build --release -p horizon-world --example probe`: a harness runs `probe [arguments]`, and `` is a module in `crates/horizon-world/examples/probe/` (add it to the `mod` list and the `probes!` list in its `main.rs`; read arguments with `crate::args()`, which drops the name). Code several probes share goes in `examples/probe/support/`. Linking one binary instead of ~170 examples is most of what a probe build used to cost. The runner counts only the probes a harness ran (and the support modules they name) as its dependencies, so editing one probe reruns only its harnesses. + Passes are shared between worktrees. A harness's key depends only on the content of its dependencies, not on where they are, so every pass is also written to `parity-shared/` beside the shared vanilla data (`PARITY_SHARED` overrides it). A worktree whose files match those a harness passed with, in any worktree, counts that pass without running the harness: after merging the integration branch, an agent's gate only runs the harnesses its own changes affect. Every runner on the machine shares `PARITY_MACHINE_JOBS` slots (default: half the CPU threads), so several agents' runs together can't overload it. Parallel harnesses are also admitted by memory: each harness's recorded peak is reserved, within three quarters of the memory available at the start, and a harness starts only if the memory free at that moment still leaves 2 GB. `-j` caps the count here (default: `PARITY_LOCAL_JOBS`, else 3 while other machines help or a third of the CPU threads alone, within `$FLEET_LOAD_JOBS`). diff --git a/docs/world-generation.md b/docs/world-generation.md index 42cc07cff..f55cbdcb2 100644 --- a/docs/world-generation.md +++ b/docs/world-generation.md @@ -195,7 +195,7 @@ above remains a record of its narrower tested source snapshot. `tools/test_chunk_generation_parity.py` generates chunks in actual vanilla classes (`VanillaChunkGenerationOracle`: structure starts and references, biomes, noise, surface, carvers, then biome decoration and structure pieces through real `WorldGenRegion`s) and with -`crates/horizon-world/examples/chunk_dump.rs`, and compares every block state, quart biome and block entity (canonical NBT) of each target +`crates/horizon-world/examples/probe/chunk_dump.rs`, and compares every block state, quart biome and block entity (canonical NBT) of each target chunk, and the scheduled block and fluid ticks each proto chunk carries into the live world. Cases are terrain sites for several seeds across the overworld, Nether and End, plus rectangles around every structure kind found by scanning the seed. `--phase structures` isolates terrain plus structure pieces, `--phase terrain` stops before features. `HORIZON_ORDER` (a file of `x z` lines) makes both sides diff --git a/tests/test_parity_runner.py b/tests/test_parity_runner.py index a9b7ff595..9e0f2a2ec 100644 --- a/tests/test_parity_runner.py +++ b/tests/test_parity_runner.py @@ -49,6 +49,21 @@ class ParityRunnerTests(unittest.TestCase): "--example", "old"], ]) + def test_a_probe_binary_depends_only_on_the_probes_it_ran(self): + commands = [["/t/release/examples/probe", "a_fixture", "/dir"], ["cargo", "run", "--example", "probe", "--", "b_fixture"]] + self.assertEqual(parity.probes_run(commands), {"a_fixture", "b_fixture"}) + with tempfile.TemporaryDirectory() as temp, mock.patch.object(parity, "ROOT", Path(temp)): + probe = Path(temp, "crates/w/examples/probe") + (probe / "support").mkdir(parents=True) + (probe / "a_fixture.rs").write_text("use crate::support::shared as s;") + for name in ("b_fixture.rs", "c_fixture.rs", "main.rs", "support/shared.rs", "support/other.rs"): + (probe / name).write_text("") + paths = [f"crates/w/examples/probe/{name}" for name in + ("a_fixture.rs", "b_fixture.rs", "c_fixture.rs", "main.rs", "support/other.rs", "support/shared.rs")] + self.assertEqual(parity.only_probes_run(["crates/w/src/lib.rs", *paths], {"a_fixture", "b_fixture"}), + ["crates/w/src/lib.rs", *paths[:2], paths[3], paths[5]]) + self.assertEqual(parity.only_probes_run(paths, set()), paths) + def test_java_sources_include_classes_pulled_from_the_sourcepath(self): with tempfile.TemporaryDirectory() as temp: sources, classes = Path(temp, "src"), Path(temp, "classes") diff --git a/tools/block_update_harness.py b/tools/block_update_harness.py index 24483f5ed..852c013d5 100644 --- a/tools/block_update_harness.py +++ b/tools/block_update_harness.py @@ -133,8 +133,8 @@ def execute(name, cases, args, facts, origin_of=None): '-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaBlockUpdateOracle.java')]) run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaBlockUpdateOracle', str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')]) - run(['cargo', 'run', '-q', '--release', '-p', 'horizon-world', '--example', 'block_update_fixture', '--', - str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], cwd=lab.ROOT, env={**os.environ, 'CARGO_BUILD_JOBS': '3'}) + run(['cargo', 'run', '-q', '--release', '-p', 'horizon-world', '--example', 'probe', '--', + 'block_update_fixture', str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], cwd=lab.ROOT, env={**os.environ, 'CARGO_BUILD_JOBS': '3'}) ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) native = split_cases((work / 'native.txt').read_text(), ignore) rust = split_cases((work / 'rust.txt').read_text(), ignore) diff --git a/tools/parity.py b/tools/parity.py index 4113cc791..271baee6f 100644 --- a/tools/parity.py +++ b/tools/parity.py @@ -464,6 +464,39 @@ def narrow_rust_sources(sources, scope): return sorted(kept), None +PROBE_SOURCE = re.compile(r"/examples/probe/(?:(support)/)?(\w+)\.rs$") + + +def probes_run(commands): + """The probes a harness ran through a crate's probe binary: `probe ...`, or + `cargo run --example probe -- ...`.""" + names = set() + for arguments in commands: + program = Path(arguments[0]).name if arguments else "" + if program in ("probe", "probe.exe") and len(arguments) > 1: + names.add(arguments[1]) + elif program == "cargo" and "--" in arguments and "probe" in arguments[:arguments.index("--")] \ + and len(arguments) > arguments.index("--") + 1: + names.add(arguments[arguments.index("--") + 1]) + return names + + +def only_probes_run(paths, names): + """A probe binary's dep-info lists every probe in it. Keep those the harness ran and the shared support + modules they name (support::), so that editing one probe reruns only its own harnesses.""" + if not names: + return paths + ran = [path for path in paths if (match := PROBE_SOURCE.search(path)) and not match.group(1) and match.group(2) in names] + used = "".join((ROOT / path).read_text(encoding="utf-8", errors="replace") for path in ran) + kept = [] + for path in paths: + match = PROBE_SOURCE.search(path) + if not match or (match.group(1) and f"support::{match.group(2)}" in used) \ + or (not match.group(1) and match.group(2) in (*names, "main")): + kept.append(path) + return kept + + def dependencies(trace, scope=None): """Repository files a traced harness depended on, relative to ROOT, and the probes it built. @@ -495,7 +528,8 @@ def dependencies(trace, scope=None): for artifact in artifacts: if artifact not in unique: unique.append(artifact) - kept, note = narrow_rust_sources(sorted(kept), scope) if scope else (sorted(kept), None) + kept = only_probes_run(sorted(kept), probes_run(trace["commands"])) + kept, note = narrow_rust_sources(kept, scope) if scope else (kept, None) if note: print(f"note: PARITY_RUST_SCOPE not applied: {note}", flush=True) return kept, unique diff --git a/tools/test_active_effect_tick_parity.py b/tools/test_active_effect_tick_parity.py index 61207ca45..dcb34ae21 100644 --- a/tools/test_active_effect_tick_parity.py +++ b/tools/test_active_effect_tick_parity.py @@ -61,7 +61,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaActiveEffectTickOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/active_effect_tick_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/active_effect_tick_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -72,14 +72,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaActiveEffectTickOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','active_effect_tick_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('active_effect_tick_fixture.exe' if os.name=='nt' else 'active_effect_tick_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';enriched_hash=base.source_hashes([enriched]) - run([binary,build,side],'rust-'+side) + run([binary,'active_effect_tick_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';rust_output=build/f'rust-{side}.txt';matched=base.compare(reference,rust_output) base.ensure_sources_unchanged([enriched],enriched_hash) tested_fixtures.update(enriched_hash);fixture_paths.append(enriched) diff --git a/tools/test_active_effects_parity.py b/tools/test_active_effects_parity.py index 16338b15f..926c2ecf8 100644 --- a/tools/test_active_effects_parity.py +++ b/tools/test_active_effects_parity.py @@ -50,7 +50,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaActiveEffectsOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/active_effects_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/active_effects_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -61,14 +61,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaActiveEffectsOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','active_effects_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('active_effects_fixture.exe' if os.name=='nt' else 'active_effects_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';enriched_hash=base.source_hashes([enriched]) - run([binary,build,side],'rust-'+side) + run([binary,'active_effects_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';rust_output=build/f'rust-{side}.txt';matched=base.compare(reference,rust_output) base.ensure_sources_unchanged([enriched],enriched_hash) tested_fixtures.update(enriched_hash);fixture_paths.append(enriched) diff --git a/tools/test_anchor_parity.py b/tools/test_anchor_parity.py index fbff1d7e6..19b8f6e4b 100644 --- a/tools/test_anchor_parity.py +++ b/tools/test_anchor_parity.py @@ -45,7 +45,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAnchorOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/anchor_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/anchor_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -53,10 +53,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","anchor_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("anchor_fixture.exe" if os.name=="nt" else "anchor_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"anchor_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_attribute_health_parity.py b/tools/test_attribute_health_parity.py index e243b60ea..eaf06d857 100644 --- a/tools/test_attribute_health_parity.py +++ b/tools/test_attribute_health_parity.py @@ -48,7 +48,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAttributeHealthOracle.java' helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAttributeOracle.java' - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/attribute_health_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/attribute_health_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaAttributeHealthOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'catalog.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','attribute_health_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('attribute_health_fixture.exe' if os.name=='nt' else 'attribute_health_fixture') - run([binary,build],'rust');run([binary,build,'live'],'rust-live');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'attribute_health_fixture',build],'rust');run([binary,'attribute_health_fixture',build,'live'],'rust-live');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') live_matched=base.compare(reference,build/'rust-live.txt') diff --git a/tools/test_attribute_map_queries_parity.py b/tools/test_attribute_map_queries_parity.py index 24c1b134e..ca222a07c 100644 --- a/tools/test_attribute_map_queries_parity.py +++ b/tools/test_attribute_map_queries_parity.py @@ -69,9 +69,9 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAttributeMapQueriesOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/attribute_map_queries_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/attribute_map_queries_fixture.rs'] helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStoredEffectAttributesOracle.java' - sources.extend([helper,lab.ROOT/'crates/horizon-world/examples/stored_effect_attributes_fixture.rs',lab.ROOT/'tools/test_stored_effect_attributes_parity.py',lab.ROOT/'tools/test_stored_effect_notifications_parity.py']) + sources.extend([helper,lab.ROOT/'crates/horizon-world/examples/probe/stored_effect_attributes_fixture.rs',lab.ROOT/'tools/test_stored_effect_attributes_parity.py',lab.ROOT/'tools/test_stored_effect_notifications_parity.py']) tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -82,14 +82,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaAttributeMapQueriesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','attribute_map_queries_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('attribute_map_queries_fixture.exe' if os.name=='nt' else 'attribute_map_queries_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';fixture_paths.append(enriched);tested_fixtures.update(base.source_hashes([enriched])) - run([binary,build,side],'rust-'+side) + run([binary,'attribute_map_queries_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';candidate=build/f'rust-{side}.txt';matched=base.compare(reference,candidate) references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched,'rust_output_sha256':lab.digest(candidate,'sha256')}) print(f'{side}: {matched:,} attribute map query output lines match Rust',flush=True) diff --git a/tools/test_attribute_parity.py b/tools/test_attribute_parity.py index c5bd95210..02051188d 100644 --- a/tools/test_attribute_parity.py +++ b/tools/test_attribute_parity.py @@ -78,7 +78,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAttributeOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/attribute_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/attribute_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -89,10 +89,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaAttributeOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'attributes.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'attributes.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','attribute_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('attribute_fixture.exe' if os.name=='nt' else 'attribute_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'attribute_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_attribute_updates_parity.py b/tools/test_attribute_updates_parity.py index f4959be0a..cc4f70d1a 100644 --- a/tools/test_attribute_updates_parity.py +++ b/tools/test_attribute_updates_parity.py @@ -59,7 +59,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAttributeUpdatesOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/"tools/test_effect_notifications_parity.py",lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/attribute_updates_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/"tools/test_effect_notifications_parity.py",lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/attribute_updates_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -70,14 +70,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaAttributeUpdatesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','attribute_updates_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('attribute_updates_fixture.exe' if os.name=='nt' else 'attribute_updates_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';enriched_hash=base.source_hashes([enriched]) - run([binary,build,side],'rust-'+side) + run([binary,'attribute_updates_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';rust_output=build/f'rust-{side}.txt';matched=base.compare(reference,rust_output) base.ensure_sources_unchanged([enriched],enriched_hash) tested_fixtures.update(enriched_hash);fixture_paths.append(enriched) diff --git a/tools/test_basic_feature_parity.py b/tools/test_basic_feature_parity.py index 001397965..2de93cd1a 100644 --- a/tools/test_basic_feature_parity.py +++ b/tools/test_basic_feature_parity.py @@ -57,7 +57,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBasicFeatureOracle.java" helper=oracle.with_name("VanillaPlacementOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/basic_feature_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/basic_feature_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -71,10 +71,10 @@ def main(): fixture_paths.append(path) if json.loads((build/"facts-client.json").read_text())!=json.loads((build/"facts-server.json").read_text()):raise ValueError("reference feature block states differ") tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","basic_feature_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("basic_feature_fixture.exe" if os.name=="nt" else "basic_feature_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"basic_feature_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_biome_chunk_parity.py b/tools/test_biome_chunk_parity.py index f484c1c5f..f24370455 100644 --- a/tools/test_biome_chunk_parity.py +++ b/tools/test_biome_chunk_parity.py @@ -49,7 +49,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeChunkOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/biome_chunk_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/biome_chunk_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -57,10 +57,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=3600,stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","biome_chunk_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("biome_chunk_fixture.exe" if os.name=="nt" else "biome_chunk_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"biome_chunk_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_biome_generation_parity.py b/tools/test_biome_generation_parity.py index 4c38070d7..67c642585 100644 --- a/tools/test_biome_generation_parity.py +++ b/tools/test_biome_generation_parity.py @@ -53,7 +53,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeGenerationOracle.java" exporter=oracle.with_name("VanillaBiomeExport.java") sources=[oracle,exporter,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/biome_generation_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/biome_generation_fixture.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -76,10 +76,10 @@ def main(): registries=build/'registries.json';registries.write_text(json.dumps(bundle,separators=(',',':')),encoding='utf-8') fixtures=list(corpus(bundle));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') fixture_paths=[inputs,registries,*exports];tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","biome_generation_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("biome_generation_fixture.exe" if os.name=="nt" else "biome_generation_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"biome_generation_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_biome_placement_parity.py b/tools/test_biome_placement_parity.py index 21408e20f..caf99b7c9 100644 --- a/tools/test_biome_placement_parity.py +++ b/tools/test_biome_placement_parity.py @@ -44,7 +44,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomePlacementOracle.java' helper=oracle.with_name("VanillaPlacementOracle.java") - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/biome_placement_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/biome_placement_fixture.rs'] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) @@ -53,10 +53,10 @@ def main(): with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle,helper],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','biome_placement_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('biome_placement_fixture.exe' if os.name=='nt' else 'biome_placement_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'biome_placement_fixture',build],'rust');references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependency_path]),'dev.horizonlab.parity.VanillaBiomePlacementOracle',side,build],side) reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_biome_source_codec_parity.py b/tools/test_biome_source_codec_parity.py index 58989d884..9363378af 100644 --- a/tools/test_biome_source_codec_parity.py +++ b/tools/test_biome_source_codec_parity.py @@ -72,7 +72,7 @@ def main(): exporter=oracle.with_name("VanillaBiomeExport.java") helpers=[oracle.with_name(name+".java") for name in ["VanillaMaterialConditionOracle","VanillaAnchorOracle","VanillaBiomeTemperatureOracle"]] sources=[oracle,exporter,*helpers,lab.ROOT/"tools/test_biome_temperature_parity.py",lab.ROOT/"tools/test_material_condition_parity.py",Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/biome_source_codec_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/biome_source_codec_fixture.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -95,10 +95,10 @@ def main(): fixtures=list(corpus(bundle));inputs=build/'inputs.txt';inputs.write_text('\n'.join(fixtures)+'\n',encoding='utf-8') (build/'positions.json').write_text(json.dumps(positions(),separators=(',',':')),encoding='utf-8') fixture_paths=[inputs,*exports,build/'positions.json',*[build/(name+'.json') for name in bundle]];tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","biome_source_codec_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("biome_source_codec_fixture.exe" if os.name=="nt" else "biome_source_codec_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"biome_source_codec_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_biome_source_parity.py b/tools/test_biome_source_parity.py index 093c92427..7616f7545 100644 --- a/tools/test_biome_source_parity.py +++ b/tools/test_biome_source_parity.py @@ -36,7 +36,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeSourceOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/biome_source_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/biome_source_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -44,10 +44,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","biome_source_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("biome_source_fixture.exe" if os.name=="nt" else "biome_source_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"biome_source_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_biome_temperature_parity.py b/tools/test_biome_temperature_parity.py index 1edec516e..af8d75976 100644 --- a/tools/test_biome_temperature_parity.py +++ b/tools/test_biome_temperature_parity.py @@ -74,7 +74,7 @@ def main(): (build/'biomes.json').write_text(json.dumps(biomes,separators=(',',':')),encoding='utf-8') oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeTemperatureOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/biome_temperature_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/biome_temperature_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=[*corpus(),*codec_corpus(biomes)];inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs,build/"biomes.json"];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -82,10 +82,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","biome_temperature_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("biome_temperature_fixture.exe" if os.name=="nt" else "biome_temperature_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"biome_temperature_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_block_collision_scan_parity.py b/tools/test_block_collision_scan_parity.py index 97c6e12b7..a59bfd8f9 100644 --- a/tools/test_block_collision_scan_parity.py +++ b/tools/test_block_collision_scan_parity.py @@ -57,7 +57,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockCollisionScanOracle.java' helpers=[oracle.with_name('VanillaFaceSupportOracle.java')] - sources=[oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/block_collision_scan_fixture.rs'] + sources=[oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/block_collision_scan_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -68,10 +68,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBlockCollisionScanOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','block_collision_scan_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('block_collision_scan_fixture.exe' if os.name=='nt' else 'block_collision_scan_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'block_collision_scan_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_block_entity_storage_parity.py b/tools/test_block_entity_storage_parity.py index 7e90ac530..a1f378f31 100644 --- a/tools/test_block_entity_storage_parity.py +++ b/tools/test_block_entity_storage_parity.py @@ -67,7 +67,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityStorageOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/block_entity_storage_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/block_entity_storage_fixture.rs'] tested_sources=base.source_hashes(sources) commands=list(corpus());inputs=build/'inputs.txt';inputs.write_text('\n'.join(commands)+'\n') tested_fixtures=base.source_hashes([inputs]);classes=build/'classes';classes.mkdir(exist_ok=True) @@ -75,10 +75,10 @@ def main(): with (build/(name+'.log')).open('w') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=3600,stdout=log,stderr=subprocess.STDOUT) dependencies=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependencies,'-d',classes,oracle],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','block_entity_storage_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('block_entity_storage_fixture.exe' if os.name=='nt' else 'block_entity_storage_fixture') - run([binary,inputs,build/'rust.txt'],'rust') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'block_entity_storage_fixture',inputs,build/'rust.txt'],'rust') references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependencies]),'dev.horizonlab.parity.VanillaBlockEntityStorageOracle',inputs,build/(side+'.txt')],side) diff --git a/tools/test_block_landing_parity.py b/tools/test_block_landing_parity.py index 0b2792d82..822ff1614 100644 --- a/tools/test_block_landing_parity.py +++ b/tools/test_block_landing_parity.py @@ -56,7 +56,7 @@ def main(): lock,jars,libraries=base.verify_artifacts();build=lab.LOCAL/'rust-block-landing-parity';build.mkdir(exist_ok=True);report_path=build/'report.json';report_path.unlink(missing_ok=True) root=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity' oracles=[root/(n+'.java') for n in ['VanillaBlockLandingOracle','VanillaMovementRegistryOracle','VanillaHeightmapOracle','VanillaCollisionOracle']] - sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/block_landing_fixture.rs'] + sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/probe/block_landing_fixture.rs'] for crate in ['horizon-core','horizon-world']:sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] tested=base.source_hashes(sources);classes=build/'classes';classes.mkdir(exist_ok=True);dependencies=os.pathsep.join(map(str,libraries)) def run(command,name): @@ -69,9 +69,9 @@ def main(): with (build/'inputs.txt').open('w') as output: for f in corpus(states,definitions):output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 fixture_paths=[build/n for n in ['inputs.txt','landing-states.json','landing-definitions.json','movement-properties.nbt','block-registry.nbt','cached-collision.nbt']];fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','block_landing_fixture'],'compile-rust') - metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('block_landing_fixture.exe' if os.name=='nt' else 'block_landing_fixture') - run([binary,build],'rust');references=[] + run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'block_landing_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side);matched=base.compare(build/(side+'.txt'),build/'rust.txt');references.append(dict(side=side,jar_sha256=lab.digest(jar,'sha256'),output_sha256=lab.digest(build/(side+'.txt'),'sha256'),matched_output_lines=matched));print(f'{side}: {matched:,} registered block landing lines match',flush=True) base.ensure_sources_unchanged(sources,tested);base.ensure_sources_unchanged(fixture_paths,fixtures) diff --git a/tools/test_block_properties_parity.py b/tools/test_block_properties_parity.py index da2f9dd11..28cd2832c 100644 --- a/tools/test_block_properties_parity.py +++ b/tools/test_block_properties_parity.py @@ -45,7 +45,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockPropertiesOracle.java' helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionOracle.java' - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/block_properties_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/block_properties_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): java('server','export',build) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'block-registry.nbt',build/'cached-collision.nbt',build/'block-properties.nbt'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','block_properties_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('block_properties_fixture.exe' if os.name=='nt' else 'block_properties_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'block_properties_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_block_push_parity.py b/tools/test_block_push_parity.py index 273f9e8de..986a3b1c9 100644 --- a/tools/test_block_push_parity.py +++ b/tools/test_block_push_parity.py @@ -42,7 +42,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockPushOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/block_push_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/block_push_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -53,10 +53,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBlockPushOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','block_push_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('block_push_fixture.exe' if os.name=='nt' else 'block_push_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'block_push_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_block_state_codec_parity.py b/tools/test_block_state_codec_parity.py index 1eb3ebe4a..e6db50860 100644 --- a/tools/test_block_state_codec_parity.py +++ b/tools/test_block_state_codec_parity.py @@ -45,7 +45,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockStateCodecOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/block_state_codec_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/block_state_codec_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -60,10 +60,10 @@ def main(): if len(facts['states'])!=35723:raise ValueError('incomplete pinned state registry') fixtures=list(corpus(facts));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'facts-client.json',build/'facts-server.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','block_state_codec_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('block_state_codec_fixture.exe' if os.name=='nt' else 'block_state_codec_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'block_state_codec_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_block_support_parity.py b/tools/test_block_support_parity.py index 2d7cb8b9c..928f099d1 100644 --- a/tools/test_block_support_parity.py +++ b/tools/test_block_support_parity.py @@ -24,7 +24,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockSupportOracle.java' helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionOracle.java' - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/block_support_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/block_support_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -35,10 +35,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBlockSupportOracle',mode,path],side+'-'+mode) java('server','export',build) fixture_paths=[build/'block-registry.nbt',build/'cached-support.nbt'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','block_support_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('block_support_fixture.exe' if os.name=='nt' else 'block_support_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'block_support_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_block_survival_parity.py b/tools/test_block_survival_parity.py index fac8f64b1..e8d220854 100644 --- a/tools/test_block_survival_parity.py +++ b/tools/test_block_survival_parity.py @@ -205,7 +205,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockSurvivalOracle.java' helpers=[oracle.with_name(name+'.java') for name in ['VanillaBlockPropertiesOracle','VanillaBlockSupportOracle','VanillaBlockStateCodecOracle','VanillaCollisionOracle','VanillaHeightmapOracle']] - sources=[oracle,*helpers,lab.ROOT/'tools/test_worldgen_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/block_survival_fixture.rs'] + sources=[oracle,*helpers,lab.ROOT/'tools/test_worldgen_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/block_survival_fixture.rs'] tested_sources=base.source_hashes(sources) environment={'minecraft':lock['minecraft']['version'],'manifest_sha1':lock['minecraft']['manifest_sha1'],'platform':platform.platform(),'java':subprocess.check_output(['java','--version'],text=True).splitlines()[0],'rustc':subprocess.check_output(['rustc','--version'],text=True).strip(),'dependencies':{str(path):lab.digest(path,'sha256') for path in [*jars.values(),*libraries]}} checkpoint=load_checkpoint(checkpoint_path,tested_sources,environment) if args.resume else None @@ -236,11 +236,11 @@ def main(): output.write(json.dumps(fixture,separators=(',',':'))+'\n');fixture_count+=1 fixture_paths=[inputs,build/'survival-extra-definitions.json',build/'fluid-tags.json',build/'survival-placement-classes.json',build/'survival-support-tags.json',build/'facts.json',build/'survival-classes.json',build/'survival-rules.json',build/'tags.json',build/'block-registry.nbt',build/'cached-collision.nbt',build/'block-properties.nbt',build/'cached-support.nbt'] tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','block_survival_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('block_survival_fixture.exe' if os.name=='nt' else 'block_survival_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') base.ensure_sources_unchanged(sources,tested_sources) - checkpoint={'schema':1,'environment':environment,'sources_sha256':tested_sources,'fixtures_sha256':{str(lab.ROOT/name):digest for name,digest in tested_fixtures.items()},'artifacts_sha256':{str(path):lab.digest(path,'sha256') for path in [binary,*sorted(classes.rglob('*.class'))]},'binary':str(binary),'counts':{'supported_blocks':len(definitions),'supported_states':sum(state['id'] in definitions for state in facts['states']),'survival_rules':len(set(definitions.values())),'survival_rule_kinds':len({rule.split(':',1)[0] for rule in definitions.values()}),'fluid_tag_files':len(fluid_tags),'fixtures':fixture_count},'outputs':{}} + checkpoint={'schema':1,'environment':environment,'sources_sha256':tested_sources,'fixtures_sha256':{str(lab.ROOT/name):digest for name,digest in tested_fixtures.items()},'artifacts_sha256':{str(path):lab.digest(path,'sha256') for path in [binary,'block_survival_fixture',*sorted(classes.rglob('*.class'))]},'binary':str(binary),'counts':{'supported_blocks':len(definitions),'supported_states':sum(state['id'] in definitions for state in facts['states']),'survival_rules':len(set(definitions.values())),'survival_rule_kinds':len({rule.split(':',1)[0] for rule in definitions.values()}),'fluid_tag_files':len(fluid_tags),'fixtures':fixture_count},'outputs':{}} save_checkpoint(checkpoint_path,checkpoint) print('Verified inputs and compiled executables checkpointed',flush=True) def stage(name, action): diff --git a/tools/test_blocking_item_damage_parity.py b/tools/test_blocking_item_damage_parity.py index d9a8c9669..b8b3ea251 100644 --- a/tools/test_blocking_item_damage_parity.py +++ b/tools/test_blocking_item_damage_parity.py @@ -49,7 +49,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockingItemDamageOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/blocking_item_damage_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/blocking_item_damage_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -60,10 +60,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBlockingItemDamageOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','blocking_item_damage_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('blocking_item_damage_fixture.exe' if os.name=='nt' else 'blocking_item_damage_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'blocking_item_damage_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_blocking_rules_parity.py b/tools/test_blocking_rules_parity.py index 5afc38333..2ff5763d6 100644 --- a/tools/test_blocking_rules_parity.py +++ b/tools/test_blocking_rules_parity.py @@ -49,7 +49,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockingRulesOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/blocking_rules_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/blocking_rules_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -60,10 +60,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBlockingRulesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','blocking_rules_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('blocking_rules_fixture.exe' if os.name=='nt' else 'blocking_rules_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'blocking_rules_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_bulk_section_parity.py b/tools/test_bulk_section_parity.py index 414613067..b9a9ae3a8 100644 --- a/tools/test_bulk_section_parity.py +++ b/tools/test_bulk_section_parity.py @@ -52,7 +52,7 @@ def main(): helper=oracle.with_name("VanillaHeightmapOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock", lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/bulk_section_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/bulk_section_fixture.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -70,10 +70,10 @@ def main(): (build/"tags.json").write_text(json.dumps(tags,separators=(",",":")),encoding="utf-8") fixture_paths=[inputs,build/"tags.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","bulk_section_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("bulk_section_fixture.exe" if os.name=="nt" else "bulk_section_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"bulk_section_fixture",build],"rust") references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_bundle_weight_parity.py b/tools/test_bundle_weight_parity.py index 0d42a2ded..c509e08a1 100644 --- a/tools/test_bundle_weight_parity.py +++ b/tools/test_bundle_weight_parity.py @@ -53,7 +53,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBundleWeightOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/bundle_weight_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/bundle_weight_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -64,10 +64,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBundleWeightOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','bundle_weight_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('bundle_weight_fixture.exe' if os.name=='nt' else 'bundle_weight_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'bundle_weight_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_canyon_carver_parity.py b/tools/test_canyon_carver_parity.py index 81d281a4c..25fbc30de 100644 --- a/tools/test_canyon_carver_parity.py +++ b/tools/test_canyon_carver_parity.py @@ -54,7 +54,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCanyonCarverOracle.java" helper=oracle.with_name("VanillaAnchorOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/canyon_carver_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/canyon_carver_fixture.rs"] tested_sources=base.source_hashes(sources) resources=worldgen.registry_resources(jars['server'],'carver') if not resources or resources!=worldgen.registry_resources(jars['client'],'carver'):raise ValueError('reference carver resources differ') @@ -65,10 +65,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,helper],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","canyon_carver_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("canyon_carver_fixture.exe" if os.name=="nt" else "canyon_carver_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"canyon_carver_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_carving_geometry_parity.py b/tools/test_carving_geometry_parity.py index 0ad9e6da0..e69331bbe 100644 --- a/tools/test_carving_geometry_parity.py +++ b/tools/test_carving_geometry_parity.py @@ -63,7 +63,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCarvingGeometryOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/carving_geometry_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/carving_geometry_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") reach=list(reach_corpus());reach_path=build/'reach.txt';reach_path.write_text(''.join(json.dumps(q,separators=(',',':'))+'\n' for q in reach),encoding='utf-8') @@ -72,10 +72,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","carving_geometry_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("carving_geometry_fixture.exe" if os.name=="nt" else "carving_geometry_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"carving_geometry_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_carving_mask_parity.py b/tools/test_carving_mask_parity.py index a3d4e375c..15dacf52e 100644 --- a/tools/test_carving_mask_parity.py +++ b/tools/test_carving_mask_parity.py @@ -57,7 +57,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCarvingMaskOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/carving_mask_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/carving_mask_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -65,10 +65,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","carving_mask_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("carving_mask_fixture.exe" if os.name=="nt" else "carving_mask_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"carving_mask_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_cave_carver_parity.py b/tools/test_cave_carver_parity.py index 863dd15d4..d79914762 100644 --- a/tools/test_cave_carver_parity.py +++ b/tools/test_cave_carver_parity.py @@ -49,7 +49,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCaveCarverOracle.java" helper=oracle.with_name("VanillaAnchorOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/cave_carver_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/cave_carver_fixture.rs"] tested_sources=base.source_hashes(sources) resources=worldgen.registry_resources(jars['server'],'carver') if not resources or resources!=worldgen.registry_resources(jars['client'],'carver'):raise ValueError('reference carver resources differ') @@ -60,10 +60,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,helper],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","cave_carver_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("cave_carver_fixture.exe" if os.name=="nt" else "cave_carver_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"cave_carver_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_chunk_generation_parity.py b/tools/test_chunk_generation_parity.py index 13262dc3b..6951e4355 100644 --- a/tools/test_chunk_generation_parity.py +++ b/tools/test_chunk_generation_parity.py @@ -4,7 +4,7 @@ Vanilla side: VanillaChunkGenerationOracle drives the actual ChunkGenerator stages (structure starts and references, biomes, terrain with surface and carvers, then biome decoration with every placed feature and structure piece) -through real WorldGenRegion instances. Horizon side: the chunk_dump example +through real WorldGenRegion instances. Horizon side: the chunk_dump probe runs the same stages in the same order. Every block state, quart biome and block entity (canonical NBT) of each target chunk is compared. @@ -71,9 +71,9 @@ class Oracle: def rust_binary(): - subprocess.run(['cargo', 'build', '--release', '-q', '-p', 'horizon-world', '--example', 'chunk_dump'], check=True, cwd=lab.ROOT) + subprocess.run(['cargo', 'build', '--release', '-q', '-p', 'horizon-world', '--example', 'probe'], check=True, cwd=lab.ROOT) metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - return Path(metadata['target_directory']) / 'release/examples/chunk_dump' + return Path(metadata['target_directory']) / 'release/examples/probe' def run_rust(binary, out, seed, dimension, rects, scan=False): @@ -81,7 +81,7 @@ def run_rust(binary, out, seed, dimension, rects, scan=False): if scan: env['HORIZON_SCAN'] = '1' with open(out, 'w') as handle: - result = subprocess.run([str(binary), str(RESOURCES), str(seed), dimension, *rects], stdout=handle, stderr=subprocess.PIPE, text=True, env=env, cwd=lab.ROOT) + result = subprocess.run([str(binary), 'chunk_dump', str(RESOURCES), str(seed), dimension, *rects], stdout=handle, stderr=subprocess.PIPE, text=True, env=env, cwd=lab.ROOT) if result.returncode: raise SystemExit('chunk_dump failed: ' + result.stderr[-2000:]) return result.stderr diff --git a/tools/test_chunk_stage_parity.py b/tools/test_chunk_stage_parity.py index 6e055f631..b8aaa6153 100644 --- a/tools/test_chunk_stage_parity.py +++ b/tools/test_chunk_stage_parity.py @@ -55,7 +55,7 @@ def main(): helper=oracle.with_name("VanillaHeightmapOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock", lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/chunk_stage_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/chunk_stage_fixture.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -73,10 +73,10 @@ def main(): (build/"tags.json").write_text(json.dumps(tags,separators=(",",":")),encoding="utf-8") fixture_paths=[inputs,build/"tags.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","chunk_stage_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("chunk_stage_fixture.exe" if os.name=="nt" else "chunk_stage_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"chunk_stage_fixture",build],"rust") references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_chunk_status_parity.py b/tools/test_chunk_status_parity.py index cd6c7a2d6..17c3d65ed 100644 --- a/tools/test_chunk_status_parity.py +++ b/tools/test_chunk_status_parity.py @@ -34,7 +34,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkStatusOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/chunk_status_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/chunk_status_fixture.rs'] tested_sources=base.source_hashes(sources) commands=list(corpus());inputs=build/'inputs.txt';inputs.write_text('\n'.join(json.dumps(command) for command in commands)+'\n') tested_fixtures=base.source_hashes([inputs]);classes=build/'classes';classes.mkdir(exist_ok=True) @@ -42,10 +42,10 @@ def main(): with (build/(name+'.log')).open('w') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=3600,stdout=log,stderr=subprocess.STDOUT) dependencies=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependencies,'-d',classes,oracle],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','chunk_status_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('chunk_status_fixture.exe' if os.name=='nt' else 'chunk_status_fixture') - run([binary,inputs,build/'rust.txt'],'rust') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'chunk_status_fixture',inputs,build/'rust.txt'],'rust') references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependencies]),'dev.horizonlab.parity.VanillaChunkStatusOracle',inputs,build/(side+'.txt')],side) diff --git a/tools/test_climbing_parity.py b/tools/test_climbing_parity.py index 9c5a57260..7b54fc4fb 100644 --- a/tools/test_climbing_parity.py +++ b/tools/test_climbing_parity.py @@ -40,7 +40,7 @@ def corpus(info): def main(): lock,jars,libraries=base.verify_artifacts();build=lab.LOCAL/'rust-climbing-parity';build.mkdir(exist_ok=True);report_path=build/'report.json';report_path.unlink(missing_ok=True) root=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity';oracles=[root/(n+'.java') for n in ['VanillaClimbingOracle','VanillaHeightmapOracle']] - sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/climbing_fixture.rs'] + sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/probe/climbing_fixture.rs'] for crate in ['horizon-core','horizon-world']:sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] tested=base.source_hashes(sources);tags=worldgen.tag_resources(jars['server']) if tags!=worldgen.tag_resources(jars['client']):raise AssertionError('Native tags differ between artifacts') @@ -54,7 +54,7 @@ def main(): with (build/'inputs.txt').open('w') as output: for f in corpus(info):output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 fixture_paths=[build/n for n in ['inputs.txt','info.json','block-registry.nbt','tags.json']];fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','climbing_fixture'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('climbing_fixture.exe' if os.name=='nt' else 'climbing_fixture');run([binary,build],'rust');references=[] + run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'climbing_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side);matched=base.compare(build/(side+'.txt'),build/'rust.txt');references.append(dict(side=side,jar_sha256=lab.digest(jar,'sha256'),output_sha256=lab.digest(build/(side+'.txt'),'sha256'),matched_output_lines=matched));print(f'{side}: {matched:,} climbing output lines match Rust',flush=True) base.ensure_sources_unchanged(sources,tested);base.ensure_sources_unchanged(fixture_paths,fixtures) diff --git a/tools/test_collision_context_parity.py b/tools/test_collision_context_parity.py index 212e0d28e..da1f382db 100644 --- a/tools/test_collision_context_parity.py +++ b/tools/test_collision_context_parity.py @@ -48,7 +48,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionContextOracle.java' helpers=[oracle.with_name('VanillaFaceSupportOracle.java')] - sources=[oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/collision_context_fixture.rs'] + sources=[oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/collision_context_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaCollisionContextOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','collision_context_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('collision_context_fixture.exe' if os.name=='nt' else 'collision_context_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'collision_context_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_collision_parity.py b/tools/test_collision_parity.py index b4d2904a8..3031e47b2 100644 --- a/tools/test_collision_parity.py +++ b/tools/test_collision_parity.py @@ -39,7 +39,7 @@ def main(): lock, jars, libraries = test_rust_parity.verify_artifacts() base = Path(tempfile.mkdtemp(prefix="run-", dir=directory)) oracle = lab.ROOT / "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionOracle.java" - sources = [oracle, Path(__file__).resolve(), lab.ROOT / "tools/test_rust_parity.py", lab.ROOT / "Cargo.toml", lab.ROOT / "Cargo.lock", lab.ROOT / "crates/horizon-core/Cargo.toml", lab.ROOT / "crates/horizon-world/Cargo.toml", *sorted((lab.ROOT / "crates/horizon-core/src").rglob("*.rs")), *sorted((lab.ROOT / "crates/horizon-world/src").rglob("*.rs")), lab.ROOT / "crates/horizon-world/examples/collision_fixture.rs"] + sources = [oracle, Path(__file__).resolve(), lab.ROOT / "tools/test_rust_parity.py", lab.ROOT / "Cargo.toml", lab.ROOT / "Cargo.lock", lab.ROOT / "crates/horizon-core/Cargo.toml", lab.ROOT / "crates/horizon-world/Cargo.toml", *sorted((lab.ROOT / "crates/horizon-core/src").rglob("*.rs")), *sorted((lab.ROOT / "crates/horizon-world/src").rglob("*.rs")), lab.ROOT / "crates/horizon-world/examples/probe/collision_fixture.rs"] tested_sources = test_rust_parity.source_hashes(sources) classes = base / "classes" classes.mkdir() @@ -51,10 +51,10 @@ def main(): result.check_returncode() return result.stdout expected = counts(java("server", "generate")) - test_rust_parity.run(["cargo", "build", "--release", "-p", "horizon-world", "--example", "collision_fixture"]) + test_rust_parity.run(["cargo", "build", "--release", "-p", "horizon-world", "--example", "probe"]) metadata = json.loads(subprocess.check_output(["cargo", "metadata", "--no-deps", "--format-version", "1"], cwd=lab.ROOT, text=True)) - binary = Path(metadata["target_directory"]) / "release/examples" / ("collision_fixture.exe" if os.name == "nt" else "collision_fixture") - actual = counts(subprocess.check_output([str(binary), str(base)], cwd=lab.ROOT, text=True)) + binary = Path(metadata["target_directory"]) / "release/examples" / ("probe.exe" if os.name=="nt" else "probe") + actual = counts(subprocess.check_output([str(binary), "collision_fixture", str(base)], cwd=lab.ROOT, text=True)) if actual != expected: raise AssertionError(f"Collision coverage differs: vanilla={expected}, Rust={actual}") canonical = {"empty_states":0,"block_states":0,"other_cached_states":0} diff --git a/tools/test_combat_rules_parity.py b/tools/test_combat_rules_parity.py index e7d2f89ac..642c0603d 100644 --- a/tools/test_combat_rules_parity.py +++ b/tools/test_combat_rules_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCombatRulesOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/combat_rules_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/combat_rules_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaCombatRulesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','combat_rules_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('combat_rules_fixture.exe' if os.name=='nt' else 'combat_rules_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'combat_rules_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_component_durability_parity.py b/tools/test_component_durability_parity.py index fa97e30d4..e912fa80b 100644 --- a/tools/test_component_durability_parity.py +++ b/tools/test_component_durability_parity.py @@ -60,7 +60,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaComponentDurabilityOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/component_durability_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/component_durability_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -71,10 +71,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaComponentDurabilityOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','component_durability_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('component_durability_fixture.exe' if os.name=='nt' else 'component_durability_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'component_durability_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_component_patch_parity.py b/tools/test_component_patch_parity.py index dcbb1ed27..bae69bb56 100644 --- a/tools/test_component_patch_parity.py +++ b/tools/test_component_patch_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaComponentPatchOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/component_patch_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/component_patch_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaComponentPatchOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','component_patch_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('component_patch_fixture.exe' if os.name=='nt' else 'component_patch_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'component_patch_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_consumable_emission_parity.py b/tools/test_consumable_emission_parity.py index 3919be5bc..7e8085087 100644 --- a/tools/test_consumable_emission_parity.py +++ b/tools/test_consumable_emission_parity.py @@ -44,7 +44,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaConsumableEmissionOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/consumable_emission_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/consumable_emission_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -55,10 +55,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaConsumableEmissionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','consumable_emission_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('consumable_emission_fixture.exe' if os.name=='nt' else 'consumable_emission_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'consumable_emission_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_consumable_parity.py b/tools/test_consumable_parity.py index 36ccf0138..083ff810f 100644 --- a/tools/test_consumable_parity.py +++ b/tools/test_consumable_parity.py @@ -50,7 +50,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaConsumableOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/consumable_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/consumable_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -61,10 +61,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaConsumableOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','consumable_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('consumable_fixture.exe' if os.name=='nt' else 'consumable_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'consumable_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_consume_effect_parity.py b/tools/test_consume_effect_parity.py index bf3a31961..4f4037073 100644 --- a/tools/test_consume_effect_parity.py +++ b/tools/test_consume_effect_parity.py @@ -44,7 +44,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaConsumeEffectOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/consume_effect_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/consume_effect_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -55,10 +55,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaConsumeEffectOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','consume_effect_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('consume_effect_fixture.exe' if os.name=='nt' else 'consume_effect_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'consume_effect_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_contextual_collision_parity.py b/tools/test_contextual_collision_parity.py index 2a2eb9090..bbfe45b02 100644 --- a/tools/test_contextual_collision_parity.py +++ b/tools/test_contextual_collision_parity.py @@ -36,7 +36,7 @@ def main(): oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionContextOracle.java' helpers=[oracle.with_name(name+'.java') for name in ['VanillaFaceSupportOracle','VanillaCollisionOracle','VanillaContextualCollisionAudit']] runner=lab.ROOT/'tools/test_collision_context_parity.py' - sources=[oracle,*helpers,runner,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/collision_context_fixture.rs'] + sources=[oracle,*helpers,runner,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/collision_context_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -48,10 +48,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars['server']),dependency_path]),'dev.horizonlab.parity.VanillaCollisionOracle','generate',build],'export') fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'block-registry.nbt',build/'cached-collision.nbt'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','collision_context_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('collision_context_fixture.exe' if os.name=='nt' else 'collision_context_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'collision_context_fixture',build],'rust');references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependency_path]),'dev.horizonlab.parity.VanillaContextualCollisionAudit',side,build],side+'-audit') audited=base.compare(build/(side+'-audit.txt'),build/'rust-audit.txt') diff --git a/tools/test_damage_immunity_parity.py b/tools/test_damage_immunity_parity.py index 962634bcc..d68277dd8 100644 --- a/tools/test_damage_immunity_parity.py +++ b/tools/test_damage_immunity_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDamageImmunityOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/damage_immunity_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/damage_immunity_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaDamageImmunityOracle',mode,path],side+'-'+mode) java('server','export',build);fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'slots.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','damage_immunity_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('damage_immunity_fixture.exe' if os.name=='nt' else 'damage_immunity_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'damage_immunity_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_damage_reduction_parity.py b/tools/test_damage_reduction_parity.py index ad53500fb..06c827dcf 100644 --- a/tools/test_damage_reduction_parity.py +++ b/tools/test_damage_reduction_parity.py @@ -53,7 +53,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDamageReductionOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/damage_reduction_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/damage_reduction_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -65,10 +65,10 @@ def main(): java('server','export',build) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'slots.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','damage_reduction_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('damage_reduction_fixture.exe' if os.name=='nt' else 'damage_reduction_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'damage_reduction_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_damage_source_parity.py b/tools/test_damage_source_parity.py index a532e4ff0..75f360822 100644 --- a/tools/test_damage_source_parity.py +++ b/tools/test_damage_source_parity.py @@ -45,7 +45,7 @@ def main(): resources={'minecraft:'+n[len(prefix):-5]:archive.read(n).decode('utf-8') for n in sorted(archive.namelist()) if n.startswith(prefix) and n.endswith('.json')};lab.write_json(build/file,resources) oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDamageSourceOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/damage_source_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/damage_source_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -56,10 +56,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaDamageSourceOracle',mode,path],side+'-'+mode) java('server','export',build);catalog=json.loads((build/'catalog.json').read_text());fixtures=list(corpus(catalog));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json',build/'types.json',build/'tags.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','damage_source_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('damage_source_fixture.exe' if os.name=='nt' else 'damage_source_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'damage_source_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_datafix_parity.py b/tools/test_datafix_parity.py index 4c189983f..dc5a2495b 100644 --- a/tools/test_datafix_parity.py +++ b/tools/test_datafix_parity.py @@ -9,7 +9,7 @@ generated automatically when missing), two upgrades run on a copy: vanilla VanillaDataFixOracle: FileFixerUpper, then DataFixers on level.dat, every chunk, entity chunk and POI chunk, player, saved data, advancements and statistics file, exactly as 26.3 does when it opens the world - horizon the `datafix_world` example of horizon-world, which does the same with + horizon the `datafix_world` probe of horizon-world, which does the same with horizon_world::datafix Then every file is compared: region files chunk by chunk, NBT files and JSON @@ -72,11 +72,11 @@ def java_classpath(): def build_rust(): - subprocess.run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'datafix_world'], + subprocess.run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], cwd=ROOT, check=True) meta = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=ROOT)) - return Path(meta['target_directory']) / 'release' / 'examples' / 'datafix_world' + return Path(meta['target_directory']) / 'release' / 'examples' / 'probe' def run_vanilla(classpath, world, out, target=None): @@ -92,7 +92,8 @@ def run_horizon(binary, world, out, target=None): shutil.rmtree(out, ignore_errors=True) log = out.parent / (out.name + '.log') with log.open('w') as f: - subprocess.run([str(binary), str(world), str(out), *([str(target)] if target else [])], check=True, stdout=f, stderr=subprocess.STDOUT) + subprocess.run([str(binary), 'datafix_world', str(world), str(out), *([str(target)] if target else [])], check=True, + stdout=f, stderr=subprocess.STDOUT) # ---------------------------------------------------------------- comparison @@ -201,7 +202,7 @@ def main(): p.add_argument('versions', nargs='*') p.add_argument('--keep', action='store_true') p.add_argument('--vanilla-only', action='store_true', help='only run the oracle') - p.add_argument('--binary', help='a prebuilt datafix_world example') + p.add_argument('--binary', help='a prebuilt horizon-world probe binary') p.add_argument('--band', type=int, metavar='TARGET', help='check the data fixes up to this DataVersion only (not the ' 'file fixes), on the sample worlds saved before it, for developing the fixes of a range of versions') args = p.parse_args() diff --git a/tools/test_decoration_parity.py b/tools/test_decoration_parity.py index 1b8fa4065..ae8c7ce02 100644 --- a/tools/test_decoration_parity.py +++ b/tools/test_decoration_parity.py @@ -65,7 +65,7 @@ def main(): resources=sort.biome_features(jars['server']) if len(resources)!=67 or resources!=sort.biome_features(jars['client']):raise ValueError('pinned biome feature resources differ') oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDecorationOracle.java';helper=oracle.with_name('VanillaPlacementOracle.java') - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_feature_sort_parity.py',lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/decoration_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_feature_sort_parity.py',lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/decoration_fixture.rs'] tested_sources=base.source_hashes(sources) fixtures=list(corpus(resources));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') resource_path=build/'biome-features.json';resource_path.write_text(json.dumps(resources,separators=(',',':')),encoding='utf-8') @@ -75,10 +75,10 @@ def main(): with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle,helper],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','decoration_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('decoration_fixture.exe' if os.name=='nt' else 'decoration_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'decoration_fixture',build],'rust');references=[] for side,jar in jars.items(): run(['java','-Xmx768M','-cp',os.pathsep.join([str(classes),str(jar),dependency_path]),'dev.horizonlab.parity.VanillaDecorationOracle',side,build],side) reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_decoration_region_parity.py b/tools/test_decoration_region_parity.py index 0b59c4817..c91ab86e8 100644 --- a/tools/test_decoration_region_parity.py +++ b/tools/test_decoration_region_parity.py @@ -55,7 +55,7 @@ def main(): placement_helper=oracle.with_name("VanillaPlacementOracle.java") sources=[oracle,helper,placement_helper,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_feature_region_parity.py",lab.ROOT/"tools/test_decoration_parity.py",lab.ROOT/"tools/test_feature_sort_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock", lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/decoration_region_fixture.rs",lab.ROOT/"crates/horizon-world/examples/support/decoration_storage.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/decoration_region_fixture.rs",lab.ROOT/"crates/horizon-world/examples/probe/support/decoration_storage.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -73,10 +73,10 @@ def main(): (build/"tags.json").write_text(json.dumps(tags,separators=(",",":")),encoding="utf-8") fixture_paths=[inputs,build/"tags.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","decoration_region_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("decoration_region_fixture.exe" if os.name=="nt" else "decoration_region_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"decoration_region_fixture",build],"rust") references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_dynamic_support_parity.py b/tools/test_dynamic_support_parity.py index ac876fa5a..76beb65c8 100644 --- a/tools/test_dynamic_support_parity.py +++ b/tools/test_dynamic_support_parity.py @@ -68,7 +68,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDynamicSupportOracle.java' helpers=[oracle.with_name(name+'.java') for name in ['VanillaFaceSupportOracle','VanillaBlockStateCodecOracle','VanillaCollisionOracle']] - sources=[oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/dynamic_support_fixture.rs'] + sources=[oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/dynamic_support_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -82,10 +82,10 @@ def main(): if len(states)!=199:raise ValueError('incomplete uncached support registry') fixtures=list(collision_corpus(facts,states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'facts.json',build/'uncached-states.json',build/'block-registry.nbt',build/'cached-collision.nbt'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','dynamic_support_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('dynamic_support_fixture.exe' if os.name=='nt' else 'dynamic_support_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'dynamic_support_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_edge_backoff_parity.py b/tools/test_edge_backoff_parity.py index 60dd0d66d..58d5ba8dd 100644 --- a/tools/test_edge_backoff_parity.py +++ b/tools/test_edge_backoff_parity.py @@ -45,7 +45,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEdgeBackoffOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/edge_backoff_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/edge_backoff_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -56,10 +56,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEdgeBackoffOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','edge_backoff_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('edge_backoff_fixture.exe' if os.name=='nt' else 'edge_backoff_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'edge_backoff_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_effect_attribute_modifiers_parity.py b/tools/test_effect_attribute_modifiers_parity.py index 0d6a45619..9fd9694aa 100644 --- a/tools/test_effect_attribute_modifiers_parity.py +++ b/tools/test_effect_attribute_modifiers_parity.py @@ -112,7 +112,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEffectAttributeModifiersOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/effect_attribute_modifiers_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/effect_attribute_modifiers_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -123,10 +123,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEffectAttributeModifiersOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','effect_attribute_modifiers_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('effect_attribute_modifiers_fixture.exe' if os.name=='nt' else 'effect_attribute_modifiers_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'effect_attribute_modifiers_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_effect_notifications_parity.py b/tools/test_effect_notifications_parity.py index 58f5b2ca6..e39258a8b 100644 --- a/tools/test_effect_notifications_parity.py +++ b/tools/test_effect_notifications_parity.py @@ -65,7 +65,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEffectNotificationsOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/effect_notifications_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/effect_notifications_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -76,14 +76,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEffectNotificationsOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','effect_notifications_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('effect_notifications_fixture.exe' if os.name=='nt' else 'effect_notifications_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';enriched_hash=base.source_hashes([enriched]) - run([binary,build,side],'rust-'+side) + run([binary,'effect_notifications_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';rust_output=build/f'rust-{side}.txt';matched=base.compare(reference,rust_output) base.ensure_sources_unchanged([enriched],enriched_hash) tested_fixtures.update(enriched_hash);fixture_paths.append(enriched) diff --git a/tools/test_effect_sync_parity.py b/tools/test_effect_sync_parity.py index ecfd8fe68..5aeeae09b 100644 --- a/tools/test_effect_sync_parity.py +++ b/tools/test_effect_sync_parity.py @@ -101,7 +101,7 @@ def main(): lab.ROOT / 'crates/horizon-core/Cargo.toml', lab.ROOT / 'crates/horizon-world/Cargo.toml', *sorted((lab.ROOT / 'crates/horizon-core/src').rglob('*.rs')), *sorted((lab.ROOT / 'crates/horizon-world/src').rglob('*.rs')), - lab.ROOT / 'crates/horizon-world/examples/effect_sync_fixture.rs'] + lab.ROOT / 'crates/horizon-world/examples/probe/effect_sync_fixture.rs'] tested_sources = base.source_hashes(sources) classes = build / 'classes' classes.mkdir(exist_ok=True) @@ -129,16 +129,16 @@ def main(): inputs.write_text(''.join(json.dumps(row, separators=(',', ':')) + '\n' for row in fixtures), encoding='utf-8') fixture_paths = [inputs, build / 'catalog.json', build / 'catalog-client.json', build / 'catalog-server.json'] tested_fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'effect_sync_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('effect_sync_fixture.exe' if os.name == 'nt' else 'effect_sync_fixture') + binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') references = [] for side, jar in jars.items(): java(side, side) enriched = build / f'inputs-{side}.txt' fixture_paths.append(enriched) tested_fixtures.update(base.source_hashes([enriched])) - run([binary, build, side], 'rust-' + side) + run([binary, 'effect_sync_fixture', build, side], 'rust-' + side) reference = build / f'{side}.txt' candidate = build / f'rust-{side}.txt' matched = base.compare(reference, candidate) diff --git a/tools/test_entity_attribute_parity.py b/tools/test_entity_attribute_parity.py index b117694d2..045488ee3 100644 --- a/tools/test_entity_attribute_parity.py +++ b/tools/test_entity_attribute_parity.py @@ -43,7 +43,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAttributeOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/entity_attribute_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/entity_attribute_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -54,10 +54,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEntityAttributeOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'catalog.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','entity_attribute_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('entity_attribute_fixture.exe' if os.name=='nt' else 'entity_attribute_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'entity_attribute_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_entity_collision_parity.py b/tools/test_entity_collision_parity.py index b57afa4b6..6fe12a7aa 100644 --- a/tools/test_entity_collision_parity.py +++ b/tools/test_entity_collision_parity.py @@ -54,7 +54,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityCollisionOracle.java' helper=oracle.with_name('VanillaFaceSupportOracle.java') - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/entity_collision_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/entity_collision_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -65,10 +65,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEntityCollisionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','entity_collision_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('entity_collision_fixture.exe' if os.name=='nt' else 'entity_collision_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'entity_collision_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_entity_fluid_parity.py b/tools/test_entity_fluid_parity.py index 609a869de..712db03b5 100644 --- a/tools/test_entity_fluid_parity.py +++ b/tools/test_entity_fluid_parity.py @@ -68,7 +68,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityFluidOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/entity_fluid_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/entity_fluid_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -79,10 +79,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEntityFluidOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','entity_fluid_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('entity_fluid_fixture.exe' if os.name=='nt' else 'entity_fluid_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'entity_fluid_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_entity_fluid_tick_parity.py b/tools/test_entity_fluid_tick_parity.py index f9b4699ce..58380bd03 100644 --- a/tools/test_entity_fluid_tick_parity.py +++ b/tools/test_entity_fluid_tick_parity.py @@ -53,7 +53,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityFluidOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_entity_fluid_parity.py',lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/entity_fluid_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_entity_fluid_parity.py',lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/entity_fluid_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -64,10 +64,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEntityFluidOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','entity_fluid_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('entity_fluid_fixture.exe' if os.name=='nt' else 'entity_fluid_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'entity_fluid_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_entity_move_parity.py b/tools/test_entity_move_parity.py index 2f5dc0da1..d17bb2444 100644 --- a/tools/test_entity_move_parity.py +++ b/tools/test_entity_move_parity.py @@ -45,7 +45,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityMoveOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/entity_move_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/entity_move_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -56,10 +56,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEntityMoveOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','entity_move_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('entity_move_fixture.exe' if os.name=='nt' else 'entity_move_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'entity_move_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_entity_obstruction_parity.py b/tools/test_entity_obstruction_parity.py index 8dc86453d..210c2080f 100644 --- a/tools/test_entity_obstruction_parity.py +++ b/tools/test_entity_obstruction_parity.py @@ -50,7 +50,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityObstructionOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/entity_obstruction_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/entity_obstruction_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -61,10 +61,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEntityObstructionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','entity_obstruction_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('entity_obstruction_fixture.exe' if os.name=='nt' else 'entity_obstruction_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'entity_obstruction_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_extra_items_parity.py b/tools/test_extra_items_parity.py index b9b060ee3..83752e515 100644 --- a/tools/test_extra_items_parity.py +++ b/tools/test_extra_items_parity.py @@ -56,7 +56,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaExtraItemsOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/extra_items_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/extra_items_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -67,10 +67,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaExtraItemsOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','extra_items_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('extra_items_fixture.exe' if os.name=='nt' else 'extra_items_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'extra_items_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_face_support_parity.py b/tools/test_face_support_parity.py index c82c23453..ad6db8922 100644 --- a/tools/test_face_support_parity.py +++ b/tools/test_face_support_parity.py @@ -50,7 +50,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFaceSupportOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/face_support_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/face_support_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -61,10 +61,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFaceSupportOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','face_support_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('face_support_fixture.exe' if os.name=='nt' else 'face_support_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'face_support_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_face_visibility_parity.py b/tools/test_face_visibility_parity.py index c505fd03f..fa8c6696a 100644 --- a/tools/test_face_visibility_parity.py +++ b/tools/test_face_visibility_parity.py @@ -49,7 +49,7 @@ def main(): oracle = lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFaceVisibilityOracle.java' helpers = [oracle.with_name(name) for name in ['VanillaCollisionOracle.java','VanillaHeightmapOracle.java']] sources = [oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py', - lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/face_visibility_fixture.rs'] + lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/probe/face_visibility_fixture.rs'] for crate in ['horizon-core','horizon-world']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] tested = base.source_hashes(sources) @@ -71,10 +71,10 @@ def main(): for a,b in pairs(definitions):output.write(f'{a} {b}\n');pair_count+=1 fixture_paths = [build/name for name in ['pairs.txt','block-registry.nbt','occlusion.nbt','definitions.json','tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','face_visibility_fixture'],'compile-rust') + run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata = json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('face_visibility_fixture.exe' if os.name=='nt' else 'face_visibility_fixture') - run([binary,build],'rust');references=[] + binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'face_visibility_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side) matched = base.compare(build/(side+'.txt'),build/'rust.txt') diff --git a/tools/test_fall_damage_parity.py b/tools/test_fall_damage_parity.py index 2f080215d..585084eb4 100644 --- a/tools/test_fall_damage_parity.py +++ b/tools/test_fall_damage_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFallDamageOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/fall_damage_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/fall_damage_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFallDamageOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','fall_damage_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('fall_damage_fixture.exe' if os.name=='nt' else 'fall_damage_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'fall_damage_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_feature_catalog_parity.py b/tools/test_feature_catalog_parity.py index 39a290ed3..52a19a652 100644 --- a/tools/test_feature_catalog_parity.py +++ b/tools/test_feature_catalog_parity.py @@ -85,7 +85,7 @@ def main(): helper=oracle.with_name("VanillaPlacementOracle.java") state_helper=oracle.with_name("VanillaBlockStateCodecOracle.java") sources=[oracle,helper,state_helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/feature_catalog_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/feature_catalog_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") resources=build/"catalog.json";resources.write_text(json.dumps(catalog(),separators=(",",":")),encoding="utf-8") @@ -100,10 +100,10 @@ def main(): fixture_paths.append(path) if json.loads((build/"facts-client.json").read_text())!=json.loads((build/"facts-server.json").read_text()):raise ValueError("reference feature block states differ") tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","feature_catalog_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("feature_catalog_fixture.exe" if os.name=="nt" else "feature_catalog_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"feature_catalog_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_feature_graph_parity.py b/tools/test_feature_graph_parity.py index 876b9bc3c..553baaf09 100644 --- a/tools/test_feature_graph_parity.py +++ b/tools/test_feature_graph_parity.py @@ -69,7 +69,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFeatureGraphOracle.java" helper=oracle.with_name("VanillaPlacementOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/feature_graph_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/feature_graph_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -83,10 +83,10 @@ def main(): fixture_paths.append(path) if json.loads((build/"facts-client.json").read_text())!=json.loads((build/"facts-server.json").read_text()):raise ValueError("reference feature block states differ") tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","feature_graph_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("feature_graph_fixture.exe" if os.name=="nt" else "feature_graph_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"feature_graph_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_feature_placement_parity.py b/tools/test_feature_placement_parity.py index 630b593bf..58dc3167a 100644 --- a/tools/test_feature_placement_parity.py +++ b/tools/test_feature_placement_parity.py @@ -79,7 +79,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFeaturePlacementOracle.java" helper=oracle.with_name("VanillaPlacementOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/feature_placement_fixture.rs",lab.ROOT/"crates/horizon-world/examples/support/placement_queries.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/feature_placement_fixture.rs",lab.ROOT/"crates/horizon-world/examples/probe/support/placement_queries.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -87,10 +87,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,helper],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","feature_placement_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("feature_placement_fixture.exe" if os.name=="nt" else "feature_placement_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"feature_placement_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_feature_region_parity.py b/tools/test_feature_region_parity.py index 901743e1c..2cc8d78a7 100644 --- a/tools/test_feature_region_parity.py +++ b/tools/test_feature_region_parity.py @@ -75,7 +75,7 @@ def main(): placement_helper=oracle.with_name("VanillaPlacementOracle.java") sources=[oracle,helper,placement_helper,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock", lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/feature_region_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/feature_region_fixture.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -107,10 +107,10 @@ def main(): height_inputs=build/'heights.json';height_inputs.write_text(json.dumps(heights,separators=(',',':'))) fixture_paths=[height_inputs,zone_inputs,inputs,build/"tags.json",build/"fluid-tags.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","feature_region_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("feature_region_fixture.exe" if os.name=="nt" else "feature_region_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"feature_region_fixture",build],"rust") references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_feature_sort_parity.py b/tools/test_feature_sort_parity.py index 9da7f17e4..6c0e4a44e 100644 --- a/tools/test_feature_sort_parity.py +++ b/tools/test_feature_sort_parity.py @@ -54,7 +54,7 @@ def main(): resources=biome_features(jars['server']) if len(resources)!=67 or resources!=biome_features(jars['client']):raise ValueError('pinned biome feature resources differ') oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFeatureSortOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/feature_sort_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/feature_sort_fixture.rs'] tested_sources=base.source_hashes(sources) fixtures=list(corpus(resources));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') resource_path=build/'biome-features.json';resource_path.write_text(json.dumps(resources,separators=(',',':')),encoding='utf-8') @@ -64,10 +64,10 @@ def main(): with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','feature_sort_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('feature_sort_fixture.exe' if os.name=='nt' else 'feature_sort_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'feature_sort_fixture',build],'rust');references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependency_path]),'dev.horizonlab.parity.VanillaFeatureSortOracle',side,build],side) reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_fill_layer_parity.py b/tools/test_fill_layer_parity.py index 0adf9f6c1..b23521d02 100644 --- a/tools/test_fill_layer_parity.py +++ b/tools/test_fill_layer_parity.py @@ -42,7 +42,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFillLayerOracle.java" helper=oracle.with_name("VanillaBlockStateCodecOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/fill_layer_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/fill_layer_fixture.rs"] tested_sources=base.source_hashes(sources) fixture_paths=[];classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -60,10 +60,10 @@ def main(): fixtures=list(corpus(facts));inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths.append(inputs) tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","fill_layer_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("fill_layer_fixture.exe" if os.name=="nt" else "fill_layer_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"fill_layer_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_fluid_box_parity.py b/tools/test_fluid_box_parity.py index 40056ed31..1b4e7743c 100644 --- a/tools/test_fluid_box_parity.py +++ b/tools/test_fluid_box_parity.py @@ -47,7 +47,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFluidBoxOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/fluid_box_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/fluid_box_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -58,10 +58,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFluidBoxOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','fluid_box_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('fluid_box_fixture.exe' if os.name=='nt' else 'fluid_box_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'fluid_box_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_fluid_flow_parity.py b/tools/test_fluid_flow_parity.py index b243fa34b..ef1606d91 100644 --- a/tools/test_fluid_flow_parity.py +++ b/tools/test_fluid_flow_parity.py @@ -56,7 +56,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFluidFlowOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/fluid_flow_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/fluid_flow_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -67,10 +67,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFluidFlowOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'fluid-states.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'fluid-states.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','fluid_flow_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('fluid_flow_fixture.exe' if os.name=='nt' else 'fluid_flow_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'fluid_flow_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_fluid_occupancy_parity.py b/tools/test_fluid_occupancy_parity.py index 50906f32e..90af340d3 100644 --- a/tools/test_fluid_occupancy_parity.py +++ b/tools/test_fluid_occupancy_parity.py @@ -44,7 +44,7 @@ def corpus(info): def main(): lock,jars,libraries=base.verify_artifacts();build=lab.LOCAL/'rust-fluid-occupancy-parity';build.mkdir(exist_ok=True);report_path=build/'report.json';report_path.unlink(missing_ok=True) root=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity';oracles=[root/(n+'.java') for n in ['VanillaFluidOccupancyOracle']] - sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/fluid_occupancy_fixture.rs'] + sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/probe/fluid_occupancy_fixture.rs'] for crate in ['horizon-core','horizon-world']:sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] tested=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True);dependencies=os.pathsep.join(map(str,libraries)) @@ -57,7 +57,7 @@ def main(): with (build/'inputs.txt').open('w') as output: for f in corpus(info):output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 fixture_paths=[build/n for n in ['inputs.txt','info.json','block-registry.nbt']];fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','fluid_occupancy_fixture'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('fluid_occupancy_fixture.exe' if os.name=='nt' else 'fluid_occupancy_fixture');run([binary,build],'rust');references=[] + run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'fluid_occupancy_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side);matched=base.compare(build/(side+'.txt'),build/'rust.txt');references.append(dict(side=side,jar_sha256=lab.digest(jar,'sha256'),output_sha256=lab.digest(build/(side+'.txt'),'sha256'),matched_output_lines=matched));print(f'{side}: {matched:,} fluid-occupancy output lines match Rust',flush=True) base.ensure_sources_unchanged(sources,tested);base.ensure_sources_unchanged(fixture_paths,fixtures) diff --git a/tools/test_fluid_parity.py b/tools/test_fluid_parity.py index f8fb98b4e..3acfc3702 100644 --- a/tools/test_fluid_parity.py +++ b/tools/test_fluid_parity.py @@ -46,7 +46,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFluidOracle.java' helper=oracle.with_name('VanillaBlockStateCodecOracle.java') - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/fluid_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/fluid_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -62,10 +62,10 @@ def main(): fixtures=list(corpus(facts));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') codec_inputs=build/'codec-inputs.txt';codec_fixtures=list(codec_corpus());codec_inputs.write_text(''.join(json.dumps(v,separators=(',',':'))+'\n' for v in codec_fixtures),encoding='utf-8') fixture_paths=[inputs,codec_inputs,build/'facts-client.json',build/'facts-server.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','fluid_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('fluid_fixture.exe' if os.name=='nt' else 'fluid_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'fluid_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_fluid_shape_parity.py b/tools/test_fluid_shape_parity.py index 55d395ffa..1378d33a5 100644 --- a/tools/test_fluid_shape_parity.py +++ b/tools/test_fluid_shape_parity.py @@ -37,7 +37,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFluidShapeOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/fluid_shape_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/fluid_shape_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -48,10 +48,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFluidShapeOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'fluid-states.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'fluid-states.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','fluid_shape_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('fluid_shape_fixture.exe' if os.name=='nt' else 'fluid_shape_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'fluid_shape_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_food_parity.py b/tools/test_food_parity.py index 519be39e6..c2e451fd0 100644 --- a/tools/test_food_parity.py +++ b/tools/test_food_parity.py @@ -57,7 +57,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFoodOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/food_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/food_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -68,10 +68,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFoodOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','food_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('food_fixture.exe' if os.name=='nt' else 'food_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'food_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_food_properties_parity.py b/tools/test_food_properties_parity.py index 195c554ab..950c19ee3 100644 --- a/tools/test_food_properties_parity.py +++ b/tools/test_food_properties_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFoodPropertiesOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/food_properties_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/food_properties_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFoodPropertiesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','food_properties_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('food_properties_fixture.exe' if os.name=='nt' else 'food_properties_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'food_properties_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_food_storage_parity.py b/tools/test_food_storage_parity.py index fc974185c..aeedde587 100644 --- a/tools/test_food_storage_parity.py +++ b/tools/test_food_storage_parity.py @@ -41,7 +41,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFoodStorageOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/food_storage_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/food_storage_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -52,10 +52,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFoodStorageOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','food_storage_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('food_storage_fixture.exe' if os.name=='nt' else 'food_storage_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'food_storage_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_free_space_parity.py b/tools/test_free_space_parity.py index 19e421265..a81fb0fe7 100644 --- a/tools/test_free_space_parity.py +++ b/tools/test_free_space_parity.py @@ -64,7 +64,7 @@ def main(): sources = [oracle, *helpers, Path(__file__), lab.ROOT/'tools/test_rust_parity.py', lab.ROOT/'tools/test_worldgen_parity.py', lab.ROOT/'tools/lab.py', lab.ROOT/'Cargo.toml', lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-world/examples/registry_collision_scan_fixture.rs'] + lab.ROOT/'crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs'] for crate in ['horizon-core', 'horizon-world']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml', *sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] @@ -94,10 +94,10 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'facts.json', 'definitions.json', 'block-registry.nbt', 'cached-collision.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'registry_collision_scan_fixture'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('registry_collision_scan_fixture.exe' if os.name=='nt' else 'registry_collision_scan_fixture') - run([binary, build], 'rust');references = [] + binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'registry_collision_scan_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) matched = base.compare(build/(side+'.txt'), build/'rust.txt') diff --git a/tools/test_ground_support_parity.py b/tools/test_ground_support_parity.py index 931aaa372..4393daf21 100644 --- a/tools/test_ground_support_parity.py +++ b/tools/test_ground_support_parity.py @@ -65,7 +65,7 @@ def main(): sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_block_collision_scan_parity.py',lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock'] for crate in ['horizon-core','horizon-world']:sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] names=['block_collision_scan_fixture','ground_state_fixture'] - sources += [lab.ROOT/'crates/horizon-world/examples'/(name+'.rs') for name in names] + sources += [lab.ROOT/'crates/horizon-world/examples/probe'/(name+'.rs') for name in names] tested=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True);dependencies=os.pathsep.join(map(str,libraries)) def run(command,name): @@ -78,10 +78,10 @@ def main(): for f in corpus():output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 counts[name]=count;fixture_paths.append(path) fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example',names[0],'--example',names[1]],'compile-rust') + run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT)) for group,name in zip(['selection','state'],names): - binary=Path(metadata['target_directory'])/'release/examples'/(name+'.exe' if os.name=='nt' else name);run([binary,build/group],'rust-'+group) + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,name,build/group],'rust-'+group) references=[] for side,jar in jars.items(): results=[] diff --git a/tools/test_height_provider_parity.py b/tools/test_height_provider_parity.py index a14b7f8ca..4f63c80cd 100644 --- a/tools/test_height_provider_parity.py +++ b/tools/test_height_provider_parity.py @@ -65,7 +65,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightProviderOracle.java" helper=oracle.with_name("VanillaAnchorOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/height_provider_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/height_provider_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -73,10 +73,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,helper],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","height_provider_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("height_provider_fixture.exe" if os.name=="nt" else "height_provider_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"height_provider_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_heightmap_parity.py b/tools/test_heightmap_parity.py index 86368997c..502f165ab 100644 --- a/tools/test_heightmap_parity.py +++ b/tools/test_heightmap_parity.py @@ -82,7 +82,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightmapOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock", lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/heightmap_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/heightmap_fixture.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -100,10 +100,10 @@ def main(): (build/"tags.json").write_text(json.dumps(tags,separators=(",",":")),encoding="utf-8") fixture_paths=[inputs,build/"tags.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","heightmap_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("heightmap_fixture.exe" if os.name=="nt" else "heightmap_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"heightmap_fixture",build],"rust") references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_interaction_shape_parity.py b/tools/test_interaction_shape_parity.py index 6e372fcda..d40ca2c0b 100644 --- a/tools/test_interaction_shape_parity.py +++ b/tools/test_interaction_shape_parity.py @@ -36,7 +36,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaInteractionShapeOracle.java' helper=oracle.with_name('VanillaCollisionOracle.java') - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/interaction_shape_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/interaction_shape_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -47,10 +47,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaInteractionShapeOracle',mode,path],side+'-'+mode) java('server','export',build);info=json.loads((build/'info.json').read_text());fixtures=list(corpus(info));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'info.json',build/'block-registry.nbt',build/'interaction-shapes.nbt'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','interaction_shape_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('interaction_shape_fixture.exe' if os.name=='nt' else 'interaction_shape_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'interaction_shape_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_inventory_pickup_parity.py b/tools/test_inventory_pickup_parity.py index 073b56a50..a3172f472 100644 --- a/tools/test_inventory_pickup_parity.py +++ b/tools/test_inventory_pickup_parity.py @@ -61,7 +61,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaInventoryPickupOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/inventory_pickup_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/inventory_pickup_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -72,10 +72,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaInventoryPickupOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','inventory_pickup_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('inventory_pickup_fixture.exe' if os.name=='nt' else 'inventory_pickup_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'inventory_pickup_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_inventory_tick_parity.py b/tools/test_inventory_tick_parity.py index 02941c7b7..2dd34b76f 100644 --- a/tools/test_inventory_tick_parity.py +++ b/tools/test_inventory_tick_parity.py @@ -49,7 +49,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaInventoryTickOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/inventory_tick_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/inventory_tick_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -60,10 +60,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaInventoryTickOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','inventory_tick_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('inventory_tick_fixture.exe' if os.name=='nt' else 'inventory_tick_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'inventory_tick_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_inventory_use_parity.py b/tools/test_inventory_use_parity.py index f4ba01980..925567c3f 100644 --- a/tools/test_inventory_use_parity.py +++ b/tools/test_inventory_use_parity.py @@ -44,7 +44,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaInventoryUseOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/inventory_use_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/inventory_use_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -55,10 +55,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaInventoryUseOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','inventory_use_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('inventory_use_fixture.exe' if os.name=='nt' else 'inventory_use_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'inventory_use_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_inventory_use_start_parity.py b/tools/test_inventory_use_start_parity.py index 9de828505..67e282c06 100644 --- a/tools/test_inventory_use_start_parity.py +++ b/tools/test_inventory_use_start_parity.py @@ -44,7 +44,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaInventoryUseStartOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/inventory_use_start_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/inventory_use_start_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -55,10 +55,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaInventoryUseStartOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','inventory_use_start_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('inventory_use_start_fixture.exe' if os.name=='nt' else 'inventory_use_start_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'inventory_use_start_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_after_use_parity.py b/tools/test_item_after_use_parity.py index 9073cdee7..4aa5258f9 100644 --- a/tools/test_item_after_use_parity.py +++ b/tools/test_item_after_use_parity.py @@ -43,7 +43,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemAfterUseOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_after_use_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_after_use_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -54,10 +54,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemAfterUseOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_after_use_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_after_use_fixture.exe' if os.name=='nt' else 'item_after_use_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_after_use_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_blocking_parity.py b/tools/test_item_blocking_parity.py index f72fd6977..08d8dce24 100644 --- a/tools/test_item_blocking_parity.py +++ b/tools/test_item_blocking_parity.py @@ -47,7 +47,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemBlockingOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_blocking_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_blocking_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -58,10 +58,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemBlockingOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_blocking_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_blocking_fixture.exe' if os.name=='nt' else 'item_blocking_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_blocking_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_cooldowns_parity.py b/tools/test_item_cooldowns_parity.py index 003394f88..807c576dc 100644 --- a/tools/test_item_cooldowns_parity.py +++ b/tools/test_item_cooldowns_parity.py @@ -53,7 +53,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemCooldownsOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_cooldowns_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_cooldowns_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -64,10 +64,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemCooldownsOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_cooldowns_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_cooldowns_fixture.exe' if os.name=='nt' else 'item_cooldowns_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_cooldowns_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_durability_parity.py b/tools/test_item_durability_parity.py index 92b34c9e6..e3cdebb07 100644 --- a/tools/test_item_durability_parity.py +++ b/tools/test_item_durability_parity.py @@ -50,7 +50,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemDurabilityOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_durability_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_durability_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -61,10 +61,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemDurabilityOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_durability_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_durability_fixture.exe' if os.name=='nt' else 'item_durability_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_durability_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_particles_parity.py b/tools/test_item_particles_parity.py index eb11f85da..0e030a3b3 100644 --- a/tools/test_item_particles_parity.py +++ b/tools/test_item_particles_parity.py @@ -42,7 +42,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemParticlesOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_particles_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_particles_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -53,10 +53,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemParticlesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_particles_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_particles_fixture.exe' if os.name=='nt' else 'item_particles_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_particles_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_stack_storage_parity.py b/tools/test_item_stack_storage_parity.py index 5f41b968e..953dc8300 100644 --- a/tools/test_item_stack_storage_parity.py +++ b/tools/test_item_stack_storage_parity.py @@ -48,7 +48,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemStackStorageOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_stack_storage_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_stack_storage_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemStackStorageOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_stack_storage_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_stack_storage_fixture.exe' if os.name=='nt' else 'item_stack_storage_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_stack_storage_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_template_parity.py b/tools/test_item_template_parity.py index 1e01cef69..837465bb3 100644 --- a/tools/test_item_template_parity.py +++ b/tools/test_item_template_parity.py @@ -47,7 +47,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemTemplateOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_template_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_template_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -58,10 +58,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemTemplateOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_template_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_template_fixture.exe' if os.name=='nt' else 'item_template_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_template_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_use_catalog_parity.py b/tools/test_item_use_catalog_parity.py index ca83e3c26..38664bd03 100644 --- a/tools/test_item_use_catalog_parity.py +++ b/tools/test_item_use_catalog_parity.py @@ -48,7 +48,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemUseCatalogOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_use_catalog_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_use_catalog_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -63,10 +63,10 @@ def main(): if exports[0]!=exports[1]:raise RuntimeError('native item catalogs differ') catalog_path=build/'catalog.json';lab.write_json(catalog_path,exports[0]);fixtures=list(corpus(exports[0]));inputs=build/'inputs.txt' ;inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,catalog_path];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_use_catalog_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_use_catalog_fixture.exe' if os.name=='nt' else 'item_use_catalog_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_use_catalog_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_use_lifecycle_parity.py b/tools/test_item_use_lifecycle_parity.py index f0615c64c..0c3c4ee6e 100644 --- a/tools/test_item_use_lifecycle_parity.py +++ b/tools/test_item_use_lifecycle_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemUseLifecycleOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_use_lifecycle_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_use_lifecycle_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemUseLifecycleOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_use_lifecycle_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_use_lifecycle_fixture.exe' if os.name=='nt' else 'item_use_lifecycle_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_use_lifecycle_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_use_parity.py b/tools/test_item_use_parity.py index 9460ffb83..f69d49e35 100644 --- a/tools/test_item_use_parity.py +++ b/tools/test_item_use_parity.py @@ -55,7 +55,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemUseOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_use_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_use_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -66,10 +66,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemUseOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_use_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_use_fixture.exe' if os.name=='nt' else 'item_use_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_use_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_use_start_parity.py b/tools/test_item_use_start_parity.py index 6325fc5a6..e59945e82 100644 --- a/tools/test_item_use_start_parity.py +++ b/tools/test_item_use_start_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemUseStartOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_use_start_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_use_start_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemUseStartOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_use_start_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_use_start_fixture.exe' if os.name=='nt' else 'item_use_start_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_use_start_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_java_hash_map_parity.py b/tools/test_java_hash_map_parity.py index c51404aa8..5ae1cce41 100644 --- a/tools/test_java_hash_map_parity.py +++ b/tools/test_java_hash_map_parity.py @@ -62,7 +62,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaJavaHashMapOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/java_hash_map_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/java_hash_map_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -73,10 +73,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaJavaHashMapOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','java_hash_map_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('java_hash_map_fixture.exe' if os.name=='nt' else 'java_hash_map_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'java_hash_map_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_java_identity_map_parity.py b/tools/test_java_identity_map_parity.py index c104eafcc..9e9f04c1d 100644 --- a/tools/test_java_identity_map_parity.py +++ b/tools/test_java_identity_map_parity.py @@ -56,7 +56,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaJavaIdentityMapOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/java_identity_map_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/java_identity_map_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -67,14 +67,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaJavaIdentityMapOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','java_identity_map_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('java_identity_map_fixture.exe' if os.name=='nt' else 'java_identity_map_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';enriched_hash=base.source_hashes([enriched]) - run([binary,build,side],'rust-'+side) + run([binary,'java_identity_map_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';rust_output=build/f'rust-{side}.txt';matched=base.compare(reference,rust_output) base.ensure_sources_unchanged([enriched],enriched_hash) tested_fixtures.update(enriched_hash);fixture_paths.append(enriched) diff --git a/tools/test_level_place_parity.py b/tools/test_level_place_parity.py index 23a68800c..18e90e348 100644 --- a/tools/test_level_place_parity.py +++ b/tools/test_level_place_parity.py @@ -105,8 +105,8 @@ def main(): subprocess.run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaBlockPlacementOracle', str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')], check=True) - subprocess.run(['cargo', 'run', '-q', '-j2', '--release', '-p', 'horizon-world', '--example', 'level_place_fixture', '--', - str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], check=True, cwd=lab.ROOT) + subprocess.run(['cargo', 'run', '-q', '-j2', '--release', '-p', 'horizon-world', '--example', 'probe', '--', + 'level_place_fixture', str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], check=True, cwd=lab.ROOT) native = (work / 'native.txt').read_text().splitlines() rust = (work / 'rust.txt').read_text().splitlines() differences = {} diff --git a/tools/test_level_shape_parity.py b/tools/test_level_shape_parity.py index 212284656..c86f51fe6 100644 --- a/tools/test_level_shape_parity.py +++ b/tools/test_level_shape_parity.py @@ -80,8 +80,8 @@ def main(): subprocess.run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaLevelShapeOracle', str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')], check=True) - subprocess.run(['cargo', 'run', '-q', '-j2', '--release', '-p', 'horizon-world', '--example', 'level_shape_fixture', '--', - str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], check=True, cwd=lab.ROOT) + subprocess.run(['cargo', 'run', '-q', '-j2', '--release', '-p', 'horizon-world', '--example', 'probe', '--', + 'level_shape_fixture', str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], check=True, cwd=lab.ROOT) native = (work / 'native.txt').read_text().splitlines() rust = (work / 'rust.txt').read_text().splitlines() differences = {} diff --git a/tools/test_liquid_collision_parity.py b/tools/test_liquid_collision_parity.py index 9989da2e7..6a4ca638b 100644 --- a/tools/test_liquid_collision_parity.py +++ b/tools/test_liquid_collision_parity.py @@ -59,7 +59,7 @@ def main(): oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionContextOracle.java' helpers=[oracle.with_name('VanillaFaceSupportOracle.java')] runner=lab.ROOT/'tools/test_collision_context_parity.py' - sources=[oracle,*helpers,runner,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/collision_context_fixture.rs'] + sources=[oracle,*helpers,runner,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/collision_context_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -70,10 +70,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaCollisionContextOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','collision_context_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('collision_context_fixture.exe' if os.name=='nt' else 'collision_context_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'collision_context_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_live_attribute_updates_parity.py b/tools/test_live_attribute_updates_parity.py index cd619de72..1e05f4bae 100644 --- a/tools/test_live_attribute_updates_parity.py +++ b/tools/test_live_attribute_updates_parity.py @@ -131,8 +131,8 @@ def main(): lab.ROOT / 'crates/horizon-core/Cargo.toml', lab.ROOT / 'crates/horizon-world/Cargo.toml', *sorted((lab.ROOT / 'crates/horizon-core/src').rglob('*.rs')), *sorted((lab.ROOT / 'crates/horizon-world/src').rglob('*.rs')), - lab.ROOT / 'crates/horizon-world/examples/live_attribute_updates_fixture.rs', - lab.ROOT / 'crates/horizon-world/examples/live_attributes_fixture.rs'] + lab.ROOT / 'crates/horizon-world/examples/probe/live_attribute_updates_fixture.rs', + lab.ROOT / 'crates/horizon-world/examples/probe/live_attributes_fixture.rs'] tested_sources = base.source_hashes(sources) classes = build / 'classes' classes.mkdir(exist_ok=True) @@ -160,16 +160,16 @@ def main(): inputs.write_text(''.join(json.dumps(row, separators=(',', ':')) + '\n' for row in fixtures), encoding='utf-8') fixture_paths = [inputs, build / 'catalog.json', build / 'catalog-client.json', build / 'catalog-server.json'] tested_fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'live_attribute_updates_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('live_attribute_updates_fixture.exe' if os.name == 'nt' else 'live_attribute_updates_fixture') + binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') references = [] for side, jar in jars.items(): java(side, side) enriched = build / f'inputs-{side}.txt' fixture_paths.append(enriched) tested_fixtures.update(base.source_hashes([enriched])) - run([binary, build, side], 'rust-' + side) + run([binary, 'live_attribute_updates_fixture', build, side], 'rust-' + side) reference = build / f'{side}.txt' candidate = build / f'rust-{side}.txt' matched = base.compare(reference, candidate) diff --git a/tools/test_live_attributes_parity.py b/tools/test_live_attributes_parity.py index 74bd083f2..f221fa27e 100644 --- a/tools/test_live_attributes_parity.py +++ b/tools/test_live_attributes_parity.py @@ -104,7 +104,7 @@ def main(): lab.ROOT / 'crates/horizon-core/Cargo.toml', lab.ROOT / 'crates/horizon-world/Cargo.toml', *sorted((lab.ROOT / 'crates/horizon-core/src').rglob('*.rs')), *sorted((lab.ROOT / 'crates/horizon-world/src').rglob('*.rs')), - lab.ROOT / 'crates/horizon-world/examples/live_attributes_fixture.rs'] + lab.ROOT / 'crates/horizon-world/examples/probe/live_attributes_fixture.rs'] tested_sources = base.source_hashes(sources) classes = build / 'classes' classes.mkdir(exist_ok=True) @@ -132,16 +132,16 @@ def main(): inputs.write_text(''.join(json.dumps(row, separators=(',', ':')) + '\n' for row in fixtures), encoding='utf-8') fixture_paths = [inputs, build / 'catalog.json', build / 'catalog-client.json', build / 'catalog-server.json'] tested_fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'live_attributes_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('live_attributes_fixture.exe' if os.name == 'nt' else 'live_attributes_fixture') + binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') references = [] for side, jar in jars.items(): java(side, side) enriched = build / f'inputs-{side}.txt' fixture_paths.append(enriched) tested_fixtures.update(base.source_hashes([enriched])) - run([binary, build, side], 'rust-' + side) + run([binary, 'live_attributes_fixture', build, side], 'rust-' + side) reference = build / f'{side}.txt' candidate = build / f'rust-{side}.txt' matched = base.compare(reference, candidate) diff --git a/tools/test_living_air_parity.py b/tools/test_living_air_parity.py index 85da124e3..4d837f02a 100644 --- a/tools/test_living_air_parity.py +++ b/tools/test_living_air_parity.py @@ -70,7 +70,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLivingAirOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/living_air_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/living_air_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -81,10 +81,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingAirOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','living_air_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('living_air_fixture.exe' if os.name=='nt' else 'living_air_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'living_air_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_living_damage_parity.py b/tools/test_living_damage_parity.py index 43c45c926..ae97c4686 100644 --- a/tools/test_living_damage_parity.py +++ b/tools/test_living_damage_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLivingDamageOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/living_damage_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/living_damage_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingDamageOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','living_damage_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('living_damage_fixture.exe' if os.name=='nt' else 'living_damage_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'living_damage_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_living_fall_parity.py b/tools/test_living_fall_parity.py index db79c440f..db55b5728 100644 --- a/tools/test_living_fall_parity.py +++ b/tools/test_living_fall_parity.py @@ -48,7 +48,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLivingFallOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/living_fall_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/living_fall_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingFallOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','living_fall_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('living_fall_fixture.exe' if os.name=='nt' else 'living_fall_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'living_fall_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_living_fluid_parity.py b/tools/test_living_fluid_parity.py index f50289e04..19748fef2 100644 --- a/tools/test_living_fluid_parity.py +++ b/tools/test_living_fluid_parity.py @@ -66,7 +66,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLivingFluidOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/living_fluid_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/living_fluid_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -77,10 +77,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingFluidOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','living_fluid_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('living_fluid_fixture.exe' if os.name=='nt' else 'living_fluid_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'living_fluid_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_living_health_parity.py b/tools/test_living_health_parity.py index b58f3e357..ab97d0061 100644 --- a/tools/test_living_health_parity.py +++ b/tools/test_living_health_parity.py @@ -48,7 +48,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLivingHealthOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/living_health_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/living_health_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingHealthOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','living_health_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('living_health_fixture.exe' if os.name=='nt' else 'living_health_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'living_health_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_living_hurt_parity.py b/tools/test_living_hurt_parity.py index 4e7d951b8..38ade5720 100644 --- a/tools/test_living_hurt_parity.py +++ b/tools/test_living_hurt_parity.py @@ -50,7 +50,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLivingHurtOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/living_hurt_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/living_hurt_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -61,10 +61,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingHurtOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','living_hurt_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('living_hurt_fixture.exe' if os.name=='nt' else 'living_hurt_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'living_hurt_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_living_landing_parity.py b/tools/test_living_landing_parity.py index 84e6c705d..eb65800da 100644 --- a/tools/test_living_landing_parity.py +++ b/tools/test_living_landing_parity.py @@ -55,7 +55,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLivingLandingOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/living_landing_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/living_landing_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -66,10 +66,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingLandingOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','living_landing_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('living_landing_fixture.exe' if os.name=='nt' else 'living_landing_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'living_landing_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_living_motion_parity.py b/tools/test_living_motion_parity.py index 66190f812..39935303c 100644 --- a/tools/test_living_motion_parity.py +++ b/tools/test_living_motion_parity.py @@ -69,7 +69,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLivingMotionOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/living_motion_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/living_motion_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -80,10 +80,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingMotionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','living_motion_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('living_motion_fixture.exe' if os.name=='nt' else 'living_motion_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'living_motion_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_material_condition_parity.py b/tools/test_material_condition_parity.py index 43e0fa48b..adddd336b 100644 --- a/tools/test_material_condition_parity.py +++ b/tools/test_material_condition_parity.py @@ -285,7 +285,7 @@ def main(): anchor_oracle=oracle.with_name("VanillaAnchorOracle.java") biome_oracle=oracle.with_name("VanillaBiomeTemperatureOracle.java") sources=[oracle,anchor_oracle,biome_oracle,lab.ROOT/"tools/test_biome_temperature_parity.py",Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/material_condition_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/material_condition_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=[*corpus(),*codec_corpus(conditions),*rule_corpus(conditions),*noise_corpus(noises),*biome_corpus(biomes),*biome_tag_corpus(biomes,biome_tags),*preliminary_corpus(),*ore_corpus()];inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs,build/"noises.json",build/"conditions.json",build/"biomes.json",build/"biome_tags.json"];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -293,10 +293,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,anchor_oracle,biome_oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","material_condition_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("material_condition_fixture.exe" if os.name=="nt" else "material_condition_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"material_condition_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_material_extension_parity.py b/tools/test_material_extension_parity.py index 7ce03502c..4036ecc37 100644 --- a/tools/test_material_extension_parity.py +++ b/tools/test_material_extension_parity.py @@ -60,15 +60,15 @@ def main(): if not biomes or biomes!=biome.biome_resources(jars['client']):raise ValueError('reference biome resources differ') for name,data in [('noises',noises),('biomes',biomes)]:(build/(name+'.json')).write_text(json.dumps(data,separators=(',',':')),encoding='utf-8') folder=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity';oracles=[folder/(name+'.java') for name in ['VanillaMaterialExtensionOracle','VanillaBiomeTemperatureOracle']] - sources=[*oracles,Path(__file__),*[lab.ROOT/'tools'/name for name in ['test_biome_temperature_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/material_extension_fixture.rs'] + sources=[*oracles,Path(__file__),*[lab.ROOT/'tools'/name for name in ['test_biome_temperature_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/material_extension_fixture.rs'] tested_sources=base.source_hashes(sources);fixtures=list(corpus(biomes));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'noises.json',build/'biomes.json'];tested_fixtures=base.source_hashes(fixture_paths);classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependencies=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependencies,'-d',classes,*oracles],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','material_extension_fixture'],'compile-rust') - metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('material_extension_fixture.exe' if os.name=='nt' else 'material_extension_fixture');run([binary,build],'rust');references=[] + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'material_extension_fixture',build],'rust');references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependencies]),'dev.horizonlab.parity.VanillaMaterialExtensionOracle',side,build],side) reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt');references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched});print(f'{side}: {matched:,} material-extension output lines match Rust',flush=True) diff --git a/tools/test_material_rule_library_parity.py b/tools/test_material_rule_library_parity.py index d2e7023ae..1e9b82357 100644 --- a/tools/test_material_rule_library_parity.py +++ b/tools/test_material_rule_library_parity.py @@ -67,7 +67,7 @@ def main(): for field,value in bundle.items():(build/(field+'.json')).write_text(json.dumps(value,separators=(',',':')),encoding='utf-8') folder=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity' oracles=[folder/(name+'.java') for name in ['VanillaMaterialConditionOracle','VanillaAnchorOracle','VanillaBiomeTemperatureOracle','VanillaBlockStateCodecOracle']] - sources=[*oracles,Path(__file__),*[lab.ROOT/'tools'/name for name in ['test_material_condition_parity.py','test_biome_temperature_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/material_condition_fixture.rs'] + sources=[*oracles,Path(__file__),*[lab.ROOT/'tools'/name for name in ['test_material_condition_parity.py','test_biome_temperature_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/material_condition_fixture.rs'] tested_sources=base.source_hashes(sources);classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) @@ -79,9 +79,9 @@ def main(): if facts!=json.loads((build/'facts-client.json').read_text()):raise ValueError('reference block metadata differs') fixtures=list(corpus(bundle['rules'],bundle['biomes']));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'facts-client.json',build/'facts-server.json',*[build/(field+'.json') for field in bundle]];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','material_condition_fixture'],'compile-rust') - metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('material_condition_fixture.exe' if os.name=='nt' else 'material_condition_fixture') - run([binary,build],'rust');references=[] + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'material_condition_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,'VanillaMaterialConditionOracle',side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched});print(f'{side}: {matched:,} material-rule library output lines match Rust',flush=True) diff --git a/tools/test_material_stage_parity.py b/tools/test_material_stage_parity.py index 29de0d9e0..46bb4649b 100644 --- a/tools/test_material_stage_parity.py +++ b/tools/test_material_stage_parity.py @@ -110,7 +110,7 @@ def main(): counts={key:len(value) for key,value in bundle.items()};bundle['rules'].update(synthetic_rules()) for name,value in bundle.items():(build/(name+'.json')).write_text(json.dumps(value,separators=(',',':')),encoding='utf-8') folder=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity';oracles=[folder/(name+'.java') for name in ['VanillaMaterialStageOracle','VanillaMaterialConditionOracle','VanillaAnchorOracle','VanillaBiomeTemperatureOracle','VanillaHeightmapOracle','VanillaBiomeExport']] - sources=[*oracles,Path(__file__),*[lab.ROOT/'tools'/name for name in ['test_material_condition_parity.py','test_biome_temperature_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/material_stage_fixture.rs'] + sources=[*oracles,Path(__file__),*[lab.ROOT/'tools'/name for name in ['test_material_condition_parity.py','test_biome_temperature_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/material_stage_fixture.rs'] tested_sources=base.source_hashes(sources);classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) @@ -132,7 +132,7 @@ def main(): f['top_queries']=top_queries(f);f['carving']=carving_fixture(f,facts) inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') fixture_paths=[inputs,*preset_exports,build/'facts-client.json',build/'facts-server.json',*[build/(name+'.json') for name in bundle]];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','material_stage_fixture'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('material_stage_fixture.exe' if os.name=='nt' else 'material_stage_fixture');run([binary,build],'rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'material_stage_fixture',build],'rust') with (build/'rust.txt').open() as stream: if any((line.startswith('surface ') or line.startswith('top ') or line.startswith('carving ') or line.startswith('generatedcarving ')) and line.endswith(' error\n') for line in stream):raise AssertionError('valid surface fixture failed; inspect private Rust log') references=[] diff --git a/tools/test_material_surface_parity.py b/tools/test_material_surface_parity.py index 30df0f4da..120decbe7 100644 --- a/tools/test_material_surface_parity.py +++ b/tools/test_material_surface_parity.py @@ -44,7 +44,7 @@ def main(): (build/"noises.json").write_text(json.dumps(noises,separators=(",",":")),encoding="utf-8") oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMaterialSurfaceOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/material_surface_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/material_surface_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs,build/"noises.json"];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -52,10 +52,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","material_surface_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("material_surface_fixture.exe" if os.name=="nt" else "material_surface_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"material_surface_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_movement_emission_parity.py b/tools/test_movement_emission_parity.py index 14977b45b..7db2c16d0 100644 --- a/tools/test_movement_emission_parity.py +++ b/tools/test_movement_emission_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMovementEmissionOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/movement_emission_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/movement_emission_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaMovementEmissionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','movement_emission_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('movement_emission_fixture.exe' if os.name=='nt' else 'movement_emission_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'movement_emission_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_movement_registry_parity.py b/tools/test_movement_registry_parity.py index ef1542415..190c34d37 100644 --- a/tools/test_movement_registry_parity.py +++ b/tools/test_movement_registry_parity.py @@ -40,7 +40,7 @@ def main(): sources = [oracle, *helpers, Path(__file__), lab.ROOT/'tools/test_rust_parity.py', lab.ROOT/'tools/test_worldgen_parity.py', lab.ROOT/'tools/lab.py', lab.ROOT/'Cargo.toml', lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-world/examples/movement_registry_fixture.rs'] + lab.ROOT/'crates/horizon-world/examples/probe/movement_registry_fixture.rs'] for crate in ['horizon-core', 'horizon-world']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml', *sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] @@ -69,10 +69,10 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'registry-info.json', 'movement-properties.nbt', 'block-registry.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'movement_registry_fixture'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('movement_registry_fixture.exe' if os.name=='nt' else 'movement_registry_fixture') - run([binary, build], 'rust');references = [] + binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'movement_registry_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) matched = base.compare(build/(side+'.txt'), build/'rust.txt') diff --git a/tools/test_movement_support_parity.py b/tools/test_movement_support_parity.py index dbc727c76..793804a9e 100644 --- a/tools/test_movement_support_parity.py +++ b/tools/test_movement_support_parity.py @@ -48,7 +48,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMovementSupportOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/movement_support_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/movement_support_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaMovementSupportOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','movement_support_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('movement_support_fixture.exe' if os.name=='nt' else 'movement_support_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'movement_support_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_nether_portal_parity.py b/tools/test_nether_portal_parity.py index 08e707e90..71cbf7be8 100644 --- a/tools/test_nether_portal_parity.py +++ b/tools/test_nether_portal_parity.py @@ -145,8 +145,8 @@ def main(): '-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaPortalOracle.java')]) h.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaPortalOracle', str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')]) - h.run(['cargo', 'run', '-q', '--release', '-p', 'horizon-world', '--example', 'portal_travel_fixture', '--', - str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], cwd=lab.ROOT) + h.run(['cargo', 'run', '-q', '--release', '-p', 'horizon-world', '--example', 'probe', '--', + 'portal_travel_fixture', str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], cwd=lab.ROOT) native = h.split_cases((work / 'native.txt').read_text(), ()) rust = h.split_cases((work / 'rust.txt').read_text(), ()) assert len(native) == len(rust) == len(all_cases), (len(native), len(rust), len(all_cases)) diff --git a/tools/test_object_open_map_parity.py b/tools/test_object_open_map_parity.py index 0a4633b3d..72bafc1a4 100644 --- a/tools/test_object_open_map_parity.py +++ b/tools/test_object_open_map_parity.py @@ -117,7 +117,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaObjectOpenMapOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/object_open_map_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/object_open_map_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -128,10 +128,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaObjectOpenMapOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','object_open_map_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('object_open_map_fixture.exe' if os.name=='nt' else 'object_open_map_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'object_open_map_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_object_open_set_parity.py b/tools/test_object_open_set_parity.py index cdbe43a15..3801cdb60 100644 --- a/tools/test_object_open_set_parity.py +++ b/tools/test_object_open_set_parity.py @@ -66,7 +66,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaObjectOpenSetOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/object_open_set_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/object_open_set_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -77,10 +77,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaObjectOpenSetOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','object_open_set_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('object_open_set_fixture.exe' if os.name=='nt' else 'object_open_set_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'object_open_set_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_piston_movement_parity.py b/tools/test_piston_movement_parity.py index 9b580c1ee..82bcd09ca 100644 --- a/tools/test_piston_movement_parity.py +++ b/tools/test_piston_movement_parity.py @@ -49,7 +49,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPistonMovementOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/piston_movement_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/piston_movement_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -60,10 +60,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPistonMovementOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','piston_movement_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('piston_movement_fixture.exe' if os.name=='nt' else 'piston_movement_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'piston_movement_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_piston_shape_parity.py b/tools/test_piston_shape_parity.py index 0816b3f8b..74ae48e39 100644 --- a/tools/test_piston_shape_parity.py +++ b/tools/test_piston_shape_parity.py @@ -49,7 +49,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPistonShapeOracle.java' helpers=[oracle.with_name(name+'.java') for name in ['VanillaFaceSupportOracle','VanillaBlockStateCodecOracle','VanillaCollisionOracle']] - sources=[oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/piston_shape_fixture.rs'] + sources=[oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/piston_shape_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -63,10 +63,10 @@ def main(): if len(facts['states'])!=35723:raise ValueError('incomplete pinned registry') fixtures=list(corpus(facts));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'facts.json',build/'block-registry.nbt',build/'cached-collision.nbt'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','piston_shape_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('piston_shape_fixture.exe' if os.name=='nt' else 'piston_shape_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'piston_shape_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_placement_parity.py b/tools/test_placement_parity.py index 8ac2f9247..d4e84eaf8 100644 --- a/tools/test_placement_parity.py +++ b/tools/test_placement_parity.py @@ -100,7 +100,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlacementOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/placement_fixture.rs",lab.ROOT/"crates/horizon-world/examples/support/placement_queries.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/placement_fixture.rs",lab.ROOT/"crates/horizon-world/examples/probe/support/placement_queries.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -108,10 +108,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","placement_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("placement_fixture.exe" if os.name=="nt" else "placement_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"placement_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_player_equipment_parity.py b/tools/test_player_equipment_parity.py index dd54b4c24..5f2499eab 100644 --- a/tools/test_player_equipment_parity.py +++ b/tools/test_player_equipment_parity.py @@ -51,7 +51,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerEquipmentOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/player_equipment_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/player_equipment_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -62,10 +62,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPlayerEquipmentOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','player_equipment_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('player_equipment_fixture.exe' if os.name=='nt' else 'player_equipment_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'player_equipment_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_player_food_parity.py b/tools/test_player_food_parity.py index 5f8bf6784..ff38abe39 100644 --- a/tools/test_player_food_parity.py +++ b/tools/test_player_food_parity.py @@ -48,7 +48,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerFoodOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/player_food_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/player_food_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPlayerFoodOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','player_food_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('player_food_fixture.exe' if os.name=='nt' else 'player_food_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'player_food_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_player_health_parity.py b/tools/test_player_health_parity.py index 40d6d2e5e..256ffdf46 100644 --- a/tools/test_player_health_parity.py +++ b/tools/test_player_health_parity.py @@ -47,7 +47,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerHealthOracle.java' helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAttributeOracle.java' - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/player_health_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/player_health_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -58,10 +58,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPlayerHealthOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'catalog.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json',build/'ids.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','player_health_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('player_health_fixture.exe' if os.name=='nt' else 'player_health_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'player_health_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_player_hurt_parity.py b/tools/test_player_hurt_parity.py index abc429a0c..34ce6a9dd 100644 --- a/tools/test_player_hurt_parity.py +++ b/tools/test_player_hurt_parity.py @@ -71,7 +71,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerHurtOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/player_hurt_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/player_hurt_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -82,10 +82,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPlayerHurtOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','player_hurt_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('player_hurt_fixture.exe' if os.name=='nt' else 'player_hurt_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'player_hurt_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_player_inventory_parity.py b/tools/test_player_inventory_parity.py index 13d90b9c0..10f6af812 100644 --- a/tools/test_player_inventory_parity.py +++ b/tools/test_player_inventory_parity.py @@ -57,7 +57,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerInventoryOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/player_inventory_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/player_inventory_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -68,10 +68,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPlayerInventoryOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','player_inventory_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('player_inventory_fixture.exe' if os.name=='nt' else 'player_inventory_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'player_inventory_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_player_travel_parity.py b/tools/test_player_travel_parity.py index 2fc9e1b48..9b96ba8e8 100644 --- a/tools/test_player_travel_parity.py +++ b/tools/test_player_travel_parity.py @@ -55,7 +55,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerTravelOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/player_travel_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/player_travel_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -66,10 +66,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPlayerTravelOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','player_travel_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('player_travel_fixture.exe' if os.name=='nt' else 'player_travel_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'player_travel_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_powder_snow_collision_parity.py b/tools/test_powder_snow_collision_parity.py index 737e367be..10c287cc5 100644 --- a/tools/test_powder_snow_collision_parity.py +++ b/tools/test_powder_snow_collision_parity.py @@ -51,7 +51,7 @@ def main(): oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionContextOracle.java' helpers=[oracle.with_name('VanillaFaceSupportOracle.java')] runner=lab.ROOT/'tools/test_collision_context_parity.py' - sources=[oracle,*helpers,runner,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/collision_context_fixture.rs'] + sources=[oracle,*helpers,runner,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/collision_context_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -62,10 +62,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaCollisionContextOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','collision_context_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('collision_context_fixture.exe' if os.name=='nt' else 'collision_context_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'collision_context_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_registered_entity_fluid_parity.py b/tools/test_registered_entity_fluid_parity.py index c994c392a..ff7a83eb6 100644 --- a/tools/test_registered_entity_fluid_parity.py +++ b/tools/test_registered_entity_fluid_parity.py @@ -53,7 +53,7 @@ def corpus(info): def main(): lock,jars,libraries=base.verify_artifacts();build=lab.LOCAL/'rust-registered-entity-fluid-parity';build.mkdir(exist_ok=True);report_path=build/'report.json';report_path.unlink(missing_ok=True) root=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity';oracles=[root/(n+'.java') for n in ['VanillaRegisteredEntityFluidOracle','VanillaEntityFluidOracle','VanillaRegistryFluidOracle','VanillaHeightmapOracle','VanillaBlockSupportOracle','VanillaCollisionOracle','VanillaBlockStateCodecOracle']] - sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_entity_fluid_parity.py',lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/entity_fluid_fixture.rs'] + sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_entity_fluid_parity.py',lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/probe/entity_fluid_fixture.rs'] for crate in ['horizon-core','horizon-world']:sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] tested=base.source_hashes(sources);tags=worldgen.tag_resources(jars['server']) if tags!=worldgen.tag_resources(jars['client']):raise AssertionError('Native tags differ between artifacts') @@ -67,7 +67,7 @@ def main(): with (build/'inputs.txt').open('w') as output: for f in corpus(info):output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 fixture_paths=[build/n for n in ['inputs.txt','facts.json','fluid-info.json','block-registry.nbt','cached-support.nbt','tags.json']];fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','entity_fluid_fixture'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('entity_fluid_fixture.exe' if os.name=='nt' else 'entity_fluid_fixture');run([binary,build],'rust');references=[] + run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'entity_fluid_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side);matched=base.compare(build/(side+'.txt'),build/'rust.txt');references.append(dict(side=side,jar_sha256=lab.digest(jar,'sha256'),output_sha256=lab.digest(build/(side+'.txt'),'sha256'),matched_output_lines=matched));print(f'{side}: {matched:,} registered entity fluid output lines match Rust',flush=True) base.ensure_sources_unchanged(sources,tested);base.ensure_sources_unchanged(fixture_paths,fixtures) diff --git a/tools/test_registered_player_combat_parity.py b/tools/test_registered_player_combat_parity.py index 219d75e52..eecb6e6cf 100644 --- a/tools/test_registered_player_combat_parity.py +++ b/tools/test_registered_player_combat_parity.py @@ -48,7 +48,7 @@ def main(): helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAttributeOracle.java' health_helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerHealthOracle.java' damage_helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDamageSourceOracle.java' - sources=[oracle,helper,health_helper,damage_helper,lab.ROOT/'tools/test_server_player_combat_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_player_hurt_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/registered_player_combat_fixture.rs'] + sources=[oracle,helper,health_helper,damage_helper,lab.ROOT/'tools/test_server_player_combat_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_player_hurt_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/registered_player_combat_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaRegisteredPlayerCombatOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'catalog.json').read_text());damage=json.loads((damage_dir/'catalog.json').read_text());fixtures=list(corpus(states,damage));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json',build/'ids.json',build/'slots.json',build/'head.json',damage_dir/'catalog.json',damage_dir/'types.json',damage_dir/'tags.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','registered_player_combat_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('registered_player_combat_fixture.exe' if os.name=='nt' else 'registered_player_combat_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'registered_player_combat_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_registry_collision_scan_parity.py b/tools/test_registry_collision_scan_parity.py index e183875ca..5b40d7285 100644 --- a/tools/test_registry_collision_scan_parity.py +++ b/tools/test_registry_collision_scan_parity.py @@ -66,7 +66,7 @@ def main(): sources = [oracle, *helpers, Path(__file__), lab.ROOT/'tools/test_rust_parity.py', lab.ROOT/'tools/test_worldgen_parity.py', lab.ROOT/'tools/lab.py', lab.ROOT/'Cargo.toml', lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-world/examples/registry_collision_scan_fixture.rs'] + lab.ROOT/'crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs'] for crate in ['horizon-core', 'horizon-world']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml', *sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] @@ -96,10 +96,10 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'facts.json', 'definitions.json', 'block-registry.nbt', 'cached-collision.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'registry_collision_scan_fixture'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('registry_collision_scan_fixture.exe' if os.name=='nt' else 'registry_collision_scan_fixture') - run([binary, build], 'rust');references = [] + binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'registry_collision_scan_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) matched = base.compare(build/(side+'.txt'), build/'rust.txt') diff --git a/tools/test_registry_fall_ray_parity.py b/tools/test_registry_fall_ray_parity.py index b343663e3..a7639c3ab 100644 --- a/tools/test_registry_fall_ray_parity.py +++ b/tools/test_registry_fall_ray_parity.py @@ -47,7 +47,7 @@ def corpus(info): def main(): lock,jars,libraries=base.verify_artifacts();build=lab.LOCAL/'rust-registry-fall-ray-parity';build.mkdir(exist_ok=True);report_path=build/'report.json';report_path.unlink(missing_ok=True) root=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity';oracles=[root/(n+'.java') for n in ['VanillaRegistryFallRayOracle','VanillaInteractionShapeOracle','VanillaCollisionOracle','VanillaHeightmapOracle']] - sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/registry_fall_ray_fixture.rs'] + sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/probe/registry_fall_ray_fixture.rs'] for crate in ['horizon-core','horizon-world']:sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] tested=base.source_hashes(sources);tags=worldgen.tag_resources(jars['server']);fluids=fluid_tags(jars['server']) if tags!=worldgen.tag_resources(jars['client']) or fluids!=fluid_tags(jars['client']):raise AssertionError('Native tags differ between artifacts') @@ -61,7 +61,7 @@ def main(): with (build/'inputs.txt').open('w') as output: for f in corpus(info):output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 fixture_paths=[build/n for n in ['inputs.txt','info.json','block-registry.nbt','interaction-shapes.nbt','tags.json','fluid-tags.json','bound-tags.json']];fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','registry_fall_ray_fixture'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('registry_fall_ray_fixture.exe' if os.name=='nt' else 'registry_fall_ray_fixture');run([binary,build],'rust');references=[] + run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'registry_fall_ray_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side);matched=base.compare(build/(side+'.txt'),build/'rust.txt');references.append(dict(side=side,jar_sha256=lab.digest(jar,'sha256'),output_sha256=lab.digest(build/(side+'.txt'),'sha256'),matched_output_lines=matched));print(f'{side}: {matched:,} registered fall-ray output lines match Rust',flush=True) base.ensure_sources_unchanged(sources,tested);base.ensure_sources_unchanged(fixture_paths,fixtures) diff --git a/tools/test_registry_fluid_parity.py b/tools/test_registry_fluid_parity.py index 2ae0486fe..fd0fb106b 100644 --- a/tools/test_registry_fluid_parity.py +++ b/tools/test_registry_fluid_parity.py @@ -48,7 +48,7 @@ def corpus(info): def main(): lock,jars,libraries=base.verify_artifacts();build=lab.LOCAL/'rust-registry_fluid-parity';build.mkdir(exist_ok=True);report_path=build/'report.json';report_path.unlink(missing_ok=True) root=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity';oracles=[root/(n+'.java') for n in ['VanillaRegistryFluidOracle','VanillaHeightmapOracle','VanillaBlockSupportOracle','VanillaCollisionOracle','VanillaBlockStateCodecOracle']] - sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/registry_fluid_fixture.rs'] + sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/probe/registry_fluid_fixture.rs'] for crate in ['horizon-core','horizon-world']:sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] tested=base.source_hashes(sources);tags=worldgen.tag_resources(jars['server']) if tags!=worldgen.tag_resources(jars['client']):raise AssertionError('Native tags differ between artifacts') @@ -62,7 +62,7 @@ def main(): with (build/'inputs.txt').open('w') as output: for f in corpus(info):output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 fixture_paths=[build/n for n in ['inputs.txt','facts.json','fluid-info.json','block-registry.nbt','cached-support.nbt','tags.json']];fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','registry_fluid_fixture'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('registry_fluid_fixture.exe' if os.name=='nt' else 'registry_fluid_fixture');run([binary,build],'rust');references=[] + run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'registry_fluid_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side);matched=base.compare(build/(side+'.txt'),build/'rust.txt');references.append(dict(side=side,jar_sha256=lab.digest(jar,'sha256'),output_sha256=lab.digest(build/(side+'.txt'),'sha256'),matched_output_lines=matched));print(f'{side}: {matched:,} registry_fluid output lines match Rust',flush=True) base.ensure_sources_unchanged(sources,tested);base.ensure_sources_unchanged(fixture_paths,fixtures) diff --git a/tools/test_replace_block_parity.py b/tools/test_replace_block_parity.py index 8ca916b07..e96bf4c72 100644 --- a/tools/test_replace_block_parity.py +++ b/tools/test_replace_block_parity.py @@ -51,7 +51,7 @@ def main(): if not tags or tags!=worldgen.tag_resources(jars['client']):raise ValueError('client/server tags differ') (build/'tags.json').write_text(json.dumps(tags,separators=(',',':')),encoding='utf-8') sources=[oracle,helper,tag_helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/replace_block_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/replace_block_fixture.rs"] tested_sources=base.source_hashes(sources) fixture_paths=[build/"tags.json"];classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -68,10 +68,10 @@ def main(): fixtures=list(corpus(facts));inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths.append(inputs) tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","replace_block_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("replace_block_fixture.exe" if os.name=="nt" else "replace_block_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"replace_block_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_restitution_parity.py b/tools/test_restitution_parity.py index bbb2d95ba..ada050a13 100644 --- a/tools/test_restitution_parity.py +++ b/tools/test_restitution_parity.py @@ -51,7 +51,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRestitutionOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/restitution_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/restitution_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -62,10 +62,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaRestitutionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','restitution_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('restitution_fixture.exe' if os.name=='nt' else 'restitution_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'restitution_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_retrogen_chunk_parity.py b/tools/test_retrogen_chunk_parity.py index 2fe4be7ef..9a13e1303 100644 --- a/tools/test_retrogen_chunk_parity.py +++ b/tools/test_retrogen_chunk_parity.py @@ -56,7 +56,7 @@ def main(): helper=oracle.with_name("VanillaHeightmapOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock", lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/chunk_stage_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/chunk_stage_fixture.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -74,10 +74,10 @@ def main(): (build/"tags.json").write_text(json.dumps(tags,separators=(",",":")),encoding="utf-8") fixture_paths=[inputs,build/"tags.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","chunk_stage_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("chunk_stage_fixture.exe" if os.name=="nt" else "chunk_stage_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"chunk_stage_fixture",build],"rust") references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_retrogen_data_parity.py b/tools/test_retrogen_data_parity.py index 5904cbe93..242f3b5d3 100644 --- a/tools/test_retrogen_data_parity.py +++ b/tools/test_retrogen_data_parity.py @@ -38,7 +38,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRetrogenDataOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/retrogen_data_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/retrogen_data_fixture.rs'] tested_sources=base.source_hashes(sources) commands=list(corpus());inputs=build/'inputs.txt';inputs.write_text('\n'.join(json.dumps(command) for command in commands)+'\n') tested_fixtures=base.source_hashes([inputs]);classes=build/'classes';classes.mkdir(exist_ok=True) @@ -46,10 +46,10 @@ def main(): with (build/(name+'.log')).open('w') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=3600,stdout=log,stderr=subprocess.STDOUT) dependencies=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependencies,'-d',classes,oracle],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','retrogen_data_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('retrogen_data_fixture.exe' if os.name=='nt' else 'retrogen_data_fixture') - run([binary,inputs,build/'rust.txt'],'rust') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'retrogen_data_fixture',inputs,build/'rust.txt'],'rust') references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependencies]),'dev.horizonlab.parity.VanillaRetrogenDataOracle',inputs,build/(side+'.txt')],side) diff --git a/tools/test_rule_test_parity.py b/tools/test_rule_test_parity.py index f87283982..8fef86b95 100644 --- a/tools/test_rule_test_parity.py +++ b/tools/test_rule_test_parity.py @@ -58,7 +58,7 @@ def main(): tags=worldgen.tag_resources(jars['server']) if not tags or tags!=worldgen.tag_resources(jars['client']):raise ValueError('client/server tags differ') (build/'tags.json').write_text(json.dumps(tags,separators=(',',':')),encoding='utf-8') - sources=[oracle,*helpers,lab.ROOT/'tools/test_worldgen_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/rule_test_fixture.rs'] + sources=[oracle,*helpers,lab.ROOT/'tools/test_worldgen_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/rule_test_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -73,10 +73,10 @@ def main(): if len(facts['states'])!=35723:raise ValueError('incomplete pinned state registry') fixtures=list(corpus(facts,tags));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'tags.json',build/'facts-client.json',build/'facts-server.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','rule_test_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('rule_test_fixture.exe' if os.name=='nt' else 'rule_test_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'rule_test_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_scaffolding_collision_parity.py b/tools/test_scaffolding_collision_parity.py index 3e60f229a..bebd63087 100644 --- a/tools/test_scaffolding_collision_parity.py +++ b/tools/test_scaffolding_collision_parity.py @@ -44,7 +44,7 @@ def main(): oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionContextOracle.java' helpers=[oracle.with_name('VanillaFaceSupportOracle.java')] runner=lab.ROOT/'tools/test_collision_context_parity.py' - sources=[oracle,*helpers,runner,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/collision_context_fixture.rs'] + sources=[oracle,*helpers,runner,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/collision_context_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -55,10 +55,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaCollisionContextOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','collision_context_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('collision_context_fixture.exe' if os.name=='nt' else 'collision_context_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'collision_context_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_scattered_ore_parity.py b/tools/test_scattered_ore_parity.py index b6bbd5aa7..0cbb6fcac 100644 --- a/tools/test_scattered_ore_parity.py +++ b/tools/test_scattered_ore_parity.py @@ -52,7 +52,7 @@ def main(): if not tags or tags!=worldgen.tag_resources(jars['client']):raise ValueError('client/server tags differ') (build/'tags.json').write_text(json.dumps(tags,separators=(',',':')),encoding='utf-8') sources=[oracle,helper,tag_helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/scattered_ore_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/scattered_ore_fixture.rs"] tested_sources=base.source_hashes(sources) fixture_paths=[build/"tags.json"];classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -69,10 +69,10 @@ def main(): fixtures=list(corpus(facts));inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths.append(inputs) tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","scattered_ore_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("scattered_ore_fixture.exe" if os.name=="nt" else "scattered_ore_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"scattered_ore_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_server_player_combat_parity.py b/tools/test_server_player_combat_parity.py index 7192e7109..161c4cbcf 100644 --- a/tools/test_server_player_combat_parity.py +++ b/tools/test_server_player_combat_parity.py @@ -66,7 +66,7 @@ def main(): oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaServerPlayerCombatOracle.java' helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAttributeOracle.java' health_helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerHealthOracle.java' - sources=[oracle,helper,health_helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_player_hurt_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/server_player_combat_fixture.rs'] + sources=[oracle,helper,health_helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_player_hurt_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/server_player_combat_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -77,11 +77,11 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaServerPlayerCombatOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'catalog.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json',build/'ids.json',build/'slots.json',build/'head.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','server_player_combat_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('server_player_combat_fixture.exe' if os.name=='nt' else 'server_player_combat_fixture') - run([binary,build],'rust') - run([binary,build,'--live'],'rust-live') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'server_player_combat_fixture',build],'rust') + run([binary,'server_player_combat_fixture',build,'--live'],'rust-live') base.compare(build/'rust.txt',build/'rust-live.txt');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_server_player_damage_parity.py b/tools/test_server_player_damage_parity.py index 4a0e0b9c7..8e1418f4e 100644 --- a/tools/test_server_player_damage_parity.py +++ b/tools/test_server_player_damage_parity.py @@ -51,7 +51,7 @@ def main(): oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaServerPlayerDamageOracle.java' helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAttributeOracle.java' health_helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerHealthOracle.java' - sources=[oracle,helper,health_helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/server_player_damage_fixture.rs'] + sources=[oracle,helper,health_helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/server_player_damage_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -62,10 +62,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaServerPlayerDamageOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'catalog.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json',build/'ids.json',build/'slots.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','server_player_damage_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('server_player_damage_fixture.exe' if os.name=='nt' else 'server_player_damage_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'server_player_damage_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_simple_block_parity.py b/tools/test_simple_block_parity.py index f68f3c92e..3af85a241 100644 --- a/tools/test_simple_block_parity.py +++ b/tools/test_simple_block_parity.py @@ -93,7 +93,7 @@ def run(corpus, build_name, source_file, scope): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts();oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSimpleBlockOracle.java' helpers=[oracle.with_name(name+'.java') for name in ['VanillaPlacementOracle','VanillaBlockSurvivalOracle','VanillaBlockPropertiesOracle','VanillaBlockSupportOracle','VanillaBlockStateCodecOracle','VanillaCollisionOracle','VanillaHeightmapOracle']] - sources=[oracle,*helpers,Path(__file__),Path(source_file),*[lab.ROOT/'tools'/name for name in ['test_block_survival_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/simple_block_fixture.rs'] + sources=[oracle,*helpers,Path(__file__),Path(source_file),*[lab.ROOT/'tools'/name for name in ['test_block_survival_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/simple_block_fixture.rs'] tested_sources=base.source_hashes(sources);classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): with (build/(name+'.log')).open('w',encoding='utf-8') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=3600,stdout=log,stderr=subprocess.STDOUT) @@ -116,9 +116,9 @@ def run(corpus, build_name, source_file, scope): with inputs.open('w',encoding='utf-8') as output: for fixture in corpus(facts,placement):output.write(json.dumps(fixture,separators=(',',':'))+'\n');fixture_count+=1 fixtures=[inputs,*sorted(build.glob('*.nbt')),*[p for p in sorted(build.glob('*.json')) if p.name!='report.json']];tested_fixtures=base.source_hashes(fixtures);print(f'Prepared {fixture_count:,} placement fixtures',flush=True) - run(['cargo','build','--release','-p','horizon-world','--example','simple_block_fixture'],'compile-rust') - metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('simple_block_fixture.exe' if os.name=='nt' else 'simple_block_fixture') - run([binary,build],'rust');references=[] + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'simple_block_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);matched=base.compare(build/(side+'.txt'),build/'rust.txt');print(f'{side}: {matched:,} {label} output lines match Rust',flush=True) references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(build/(side+'.txt'),'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_simple_container_parity.py b/tools/test_simple_container_parity.py index 8365276dd..0af91292a 100644 --- a/tools/test_simple_container_parity.py +++ b/tools/test_simple_container_parity.py @@ -59,7 +59,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSimpleContainerOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/simple_container_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/simple_container_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -70,10 +70,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaSimpleContainerOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','simple_container_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('simple_container_fixture.exe' if os.name=='nt' else 'simple_container_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'simple_container_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_state_provider_parity.py b/tools/test_state_provider_parity.py index 1cc74b2b3..2ff8647a5 100644 --- a/tools/test_state_provider_parity.py +++ b/tools/test_state_provider_parity.py @@ -309,7 +309,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStateProviderOracle.java' helpers=[oracle.with_name(name+'.java') for name in ['VanillaBlockStateCodecOracle','VanillaHeightmapOracle','VanillaMaterialConditionOracle','VanillaBiomeTemperatureOracle','VanillaAnchorOracle','VanillaBlockPropertiesOracle','VanillaBlockSupportOracle','VanillaBlockSurvivalOracle','VanillaCollisionOracle']] - sources=[oracle,*helpers,lab.ROOT/'tools/test_block_survival_parity.py',lab.ROOT/'tools/test_biome_temperature_parity.py',lab.ROOT/'tools/test_material_condition_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/state_provider_fixture.rs'] + sources=[oracle,*helpers,lab.ROOT/'tools/test_block_survival_parity.py',lab.ROOT/'tools/test_biome_temperature_parity.py',lab.ROOT/'tools/test_material_condition_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/state_provider_fixture.rs'] tested_sources=base.source_hashes(sources) environment={'minecraft':lock['minecraft']['version'],'manifest_sha1':lock['minecraft']['manifest_sha1'],'platform':platform.platform(),'java':subprocess.check_output(['java','--version'],text=True).splitlines()[0],'rustc':subprocess.check_output(['rustc','--version'],text=True).strip(),'dependencies':{str(path):lab.digest(path,'sha256') for path in [*jars.values(),*libraries]}} checkpoint=survival.load_checkpoint(checkpoint_path,tested_sources,environment) if args.resume else None @@ -371,12 +371,12 @@ def main(): output.write(json.dumps(fixture,separators=(',',':'))+'\n') fixture_count+=1;requested_samples+=len(fixture['states'])*fixture['repeats']*2 fixture_paths=[inputs,build/'survival-extra-definitions.json',build/'survival-placement-classes.json',build/'survival-support-tags.json',build/'survival-classes.json',build/'survival-rules.json',build/'cached-support.nbt',build/'support-cached-states.json',build/'block-properties.nbt',build/'cached-collision.nbt',build/'biomes.json',build/'biome_tags.json',build/'fluid-tags.json',build/'catalog.json',build/'providers.json',build/'tags.json',build/'facts-client.json',build/'facts-server.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','state_provider_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('state_provider_fixture.exe' if os.name=='nt' else 'state_provider_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') counts={'block_states':len(facts['states']),'blocks':len(facts['defaults']),'integer_properties':len(facts['integers']),'codec_inputs':fixture_count,'provider_types':10,'named_providers':len(catalog_resources),'rule_predicate_types':16,'survival_supported_blocks':len(survival_rules),'survival_supported_states':sum(s['id'] in survival_rules for s in facts['states']),'support_cached_states':len(support_states),'support_dynamic_states':len(facts['states'])-len(support_states),'biomes':len(biomes),'biome_tag_files':len(biome_tags),'fluid_tag_files':len(fluid_tags),'bundled_provider_definitions':len(provider_resources),'block_tag_files':len(tags),'requested_samples':requested_samples} base.ensure_sources_unchanged(sources,tested_sources) - checkpoint={'schema':1,'environment':environment,'sources_sha256':tested_sources,'fixtures_sha256':{str(lab.ROOT/name):digest for name,digest in tested_fixtures.items()},'artifacts_sha256':{str(path):lab.digest(path,'sha256') for path in [binary,*sorted(classes.rglob('*.class'))]},'binary':str(binary),'counts':counts,'outputs':{}} + checkpoint={'schema':1,'environment':environment,'sources_sha256':tested_sources,'fixtures_sha256':{str(lab.ROOT/name):digest for name,digest in tested_fixtures.items()},'artifacts_sha256':{str(path):lab.digest(path,'sha256') for path in [binary,'state_provider_fixture',*sorted(classes.rglob('*.class'))]},'binary':str(binary),'counts':counts,'outputs':{}} survival.save_checkpoint(checkpoint_path,checkpoint) print('Verified inputs and compiled executables checkpointed',flush=True) def stage(name,action): diff --git a/tools/test_status_effect_parity.py b/tools/test_status_effect_parity.py index 5c94af434..6f369c683 100644 --- a/tools/test_status_effect_parity.py +++ b/tools/test_status_effect_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStatusEffectOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/status_effect_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/status_effect_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaStatusEffectOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','status_effect_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('status_effect_fixture.exe' if os.name=='nt' else 'status_effect_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'status_effect_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_status_tick_parity.py b/tools/test_status_tick_parity.py index c14f72bf9..40786fe3c 100644 --- a/tools/test_status_tick_parity.py +++ b/tools/test_status_tick_parity.py @@ -47,7 +47,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStatusTickOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/status_tick_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/status_tick_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -58,10 +58,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaStatusTickOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','status_tick_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('status_tick_fixture.exe' if os.name=='nt' else 'status_tick_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'status_tick_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_stepped_interpolation_parity.py b/tools/test_stepped_interpolation_parity.py index 998d5a4ba..e5586c981 100644 --- a/tools/test_stepped_interpolation_parity.py +++ b/tools/test_stepped_interpolation_parity.py @@ -94,7 +94,7 @@ def main(): 'dev.horizonlab.parity.VanillaSteppedInterpolationOracle', str(events), str(build / 'vanilla.txt')], check=True) subprocess.run(['cargo', 'run', '--quiet', '--release', '-p', 'horizon-world', '--example', - 'stepped_interpolation_fixture', '--', str(events), str(build / 'rust.txt')], cwd=lab.ROOT, check=True) + 'probe', '--', 'stepped_interpolation_fixture', str(events), str(build / 'rust.txt')], cwd=lab.ROOT, check=True) matched = base.compare(build / 'vanilla.txt', build / 'rust.txt') print(f'Stepped interpolation parity passed: {matched} entity positions and rotations match vanilla') diff --git a/tools/test_stored_consume_parity.py b/tools/test_stored_consume_parity.py index e10a020ca..3ddfed86a 100644 --- a/tools/test_stored_consume_parity.py +++ b/tools/test_stored_consume_parity.py @@ -55,7 +55,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStoredConsumeOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/stored_consume_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/stored_consume_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -66,14 +66,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaStoredConsumeOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','stored_consume_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('stored_consume_fixture.exe' if os.name=='nt' else 'stored_consume_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';enriched_hash=base.source_hashes([enriched]) - run([binary,build,side],'rust-'+side) + run([binary,'stored_consume_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';rust_output=build/f'rust-{side}.txt';matched=base.compare(reference,rust_output) base.ensure_sources_unchanged([enriched],enriched_hash) tested_fixtures.update(enriched_hash);fixture_paths.append(enriched) diff --git a/tools/test_stored_effect_attributes_parity.py b/tools/test_stored_effect_attributes_parity.py index 3d3d0a543..2a8fe799d 100644 --- a/tools/test_stored_effect_attributes_parity.py +++ b/tools/test_stored_effect_attributes_parity.py @@ -83,7 +83,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStoredEffectAttributesOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/stored_effect_attributes_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/stored_effect_attributes_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -94,14 +94,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaStoredEffectAttributesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','stored_effect_attributes_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('stored_effect_attributes_fixture.exe' if os.name=='nt' else 'stored_effect_attributes_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';fixture_paths.append(enriched);tested_fixtures.update(base.source_hashes([enriched])) - run([binary,build,side],'rust-'+side) + run([binary,'stored_effect_attributes_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';candidate=build/f'rust-{side}.txt';matched=base.compare(reference,candidate) references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched,'rust_output_sha256':lab.digest(candidate,'sha256')}) print(f'{side}: {matched:,} stored effect attribute output lines match Rust',flush=True) diff --git a/tools/test_stored_effect_notifications_parity.py b/tools/test_stored_effect_notifications_parity.py index 82bcb65ad..6a0cee403 100644 --- a/tools/test_stored_effect_notifications_parity.py +++ b/tools/test_stored_effect_notifications_parity.py @@ -60,9 +60,9 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStoredEffectNotificationsOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/stored_effect_notifications_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/stored_effect_notifications_fixture.rs'] helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStoredEffectAttributesOracle.java' - sources.extend([helper,lab.ROOT/'crates/horizon-world/examples/stored_effect_attributes_fixture.rs',lab.ROOT/'tools/test_stored_effect_attributes_parity.py']) + sources.extend([helper,lab.ROOT/'crates/horizon-world/examples/probe/stored_effect_attributes_fixture.rs',lab.ROOT/'tools/test_stored_effect_attributes_parity.py']) tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -73,14 +73,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaStoredEffectNotificationsOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','stored_effect_notifications_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('stored_effect_notifications_fixture.exe' if os.name=='nt' else 'stored_effect_notifications_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';fixture_paths.append(enriched);tested_fixtures.update(base.source_hashes([enriched])) - run([binary,build,side],'rust-'+side) + run([binary,'stored_effect_notifications_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';candidate=build/f'rust-{side}.txt';matched=base.compare(reference,candidate) references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched,'rust_output_sha256':lab.digest(candidate,'sha256')}) print(f'{side}: {matched:,} stored effect notification output lines match Rust',flush=True) diff --git a/tools/test_structure_density_parity.py b/tools/test_structure_density_parity.py index 75094c3e6..ad15790e0 100644 --- a/tools/test_structure_density_parity.py +++ b/tools/test_structure_density_parity.py @@ -60,7 +60,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureDensityOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/structure_density_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/structure_density_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") tested_fixtures=base.source_hashes([inputs]);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -68,10 +68,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","structure_density_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("structure_density_fixture.exe" if os.name=="nt" else "structure_density_fixture") - run([binary,inputs,build/"rust.txt"],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"structure_density_fixture",inputs,build/"rust.txt"],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_suffocation_parity.py b/tools/test_suffocation_parity.py index c9d8d37ec..ffe80b31f 100644 --- a/tools/test_suffocation_parity.py +++ b/tools/test_suffocation_parity.py @@ -42,7 +42,7 @@ def main(): sources = [oracle, *helpers, Path(__file__), lab.ROOT/'tools/test_rust_parity.py', lab.ROOT/'tools/test_worldgen_parity.py', lab.ROOT/'tools/lab.py', lab.ROOT/'Cargo.toml', lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-world/examples/suffocation_fixture.rs'] + lab.ROOT/'crates/horizon-world/examples/probe/suffocation_fixture.rs'] for crate in ['horizon-core', 'horizon-world']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml', *sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] @@ -72,10 +72,10 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'facts.json', 'definitions.json', 'block-registry.nbt', 'cached-collision.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'suffocation_fixture'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('suffocation_fixture.exe' if os.name=='nt' else 'suffocation_fixture') - run([binary, build], 'rust');references = [] + binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'suffocation_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) matched = base.compare(build/(side+'.txt'), build/'rust.txt') diff --git a/tools/test_swimming_parity.py b/tools/test_swimming_parity.py index d63ce66e1..574b72e5b 100644 --- a/tools/test_swimming_parity.py +++ b/tools/test_swimming_parity.py @@ -40,7 +40,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSwimmingOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/swimming_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/swimming_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -51,10 +51,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaSwimmingOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','swimming_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('swimming_fixture.exe' if os.name=='nt' else 'swimming_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'swimming_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_synced_bytes_parity.py b/tools/test_synced_bytes_parity.py index cc0024a1c..a6659bf21 100644 --- a/tools/test_synced_bytes_parity.py +++ b/tools/test_synced_bytes_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSyncedBytesOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/synced_bytes_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/synced_bytes_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaSyncedBytesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','synced_bytes_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('synced_bytes_fixture.exe' if os.name=='nt' else 'synced_bytes_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'synced_bytes_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_synced_floats_parity.py b/tools/test_synced_floats_parity.py index 768192ea2..fa7ca7132 100644 --- a/tools/test_synced_floats_parity.py +++ b/tools/test_synced_floats_parity.py @@ -50,7 +50,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSyncedFloatsOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/synced_floats_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/synced_floats_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -61,10 +61,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaSyncedFloatsOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','synced_floats_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('synced_floats_fixture.exe' if os.name=='nt' else 'synced_floats_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'synced_floats_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_teleport_consume_parity.py b/tools/test_teleport_consume_parity.py index c24dda3a1..8f51361f8 100644 --- a/tools/test_teleport_consume_parity.py +++ b/tools/test_teleport_consume_parity.py @@ -43,7 +43,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTeleportConsumeOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/teleport_consume_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/teleport_consume_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -54,10 +54,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaTeleportConsumeOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','teleport_consume_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('teleport_consume_fixture.exe' if os.name=='nt' else 'teleport_consume_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'teleport_consume_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_terrain_parity.py b/tools/test_terrain_parity.py index 3bd4dbcc6..a818dcabb 100644 --- a/tools/test_terrain_parity.py +++ b/tools/test_terrain_parity.py @@ -75,7 +75,7 @@ def main(): exporter=oracle.with_name("VanillaHeightmapOracle.java") sources=[oracle,exporter,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock", lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/terrain_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/terrain_fixture.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -99,10 +99,10 @@ def main(): (build/"registries.json").write_text(json.dumps(bundle,separators=(",",":")),encoding="utf-8") fixture_paths=[inputs,build/"registries.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","terrain_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("terrain_fixture.exe" if os.name=="nt" else "terrain_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"terrain_fixture",build],"rust") references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_tick_parity.py b/tools/test_tick_parity.py index 4efcc93e9..47dd842d0 100644 --- a/tools/test_tick_parity.py +++ b/tools/test_tick_parity.py @@ -145,7 +145,7 @@ def main(): inputs.write_text("\n".join(commands) + "\n", encoding="utf-8") oracle = lab.ROOT / "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTickOracle.java" data_oracle = oracle.with_name("VanillaTickDataOracle.java") - sources = [oracle, data_oracle, Path(__file__).resolve(), lab.ROOT / "tools/test_rust_parity.py", lab.ROOT / "Cargo.toml", lab.ROOT / "Cargo.lock", lab.ROOT / "crates/horizon-core/Cargo.toml", lab.ROOT / "crates/horizon-world/Cargo.toml", *sorted((lab.ROOT / "crates/horizon-core/src").rglob("*.rs")), *sorted((lab.ROOT / "crates/horizon-world/src").rglob("*.rs")), lab.ROOT / "crates/horizon-world/examples/tick_fixture.rs"] + sources = [oracle, data_oracle, Path(__file__).resolve(), lab.ROOT / "tools/test_rust_parity.py", lab.ROOT / "Cargo.toml", lab.ROOT / "Cargo.lock", lab.ROOT / "crates/horizon-core/Cargo.toml", lab.ROOT / "crates/horizon-world/Cargo.toml", *sorted((lab.ROOT / "crates/horizon-core/src").rglob("*.rs")), *sorted((lab.ROOT / "crates/horizon-world/src").rglob("*.rs")), lab.ROOT / "crates/horizon-world/examples/probe/tick_fixture.rs"] tested_sources = test_rust_parity.source_hashes(sources) classes = base / "classes" classes.mkdir() @@ -163,9 +163,9 @@ def main(): completed.check_returncode() return completed.stdout data_java("server", "generate") - test_rust_parity.run(["cargo", "build", "--release", "-p", "horizon-world", "--example", "tick_fixture"]) - fixture = Path(metadata["target_directory"]) / "release/examples" / ("tick_fixture.exe" if os.name == "nt" else "tick_fixture") - test_rust_parity.run([str(fixture), str(base)]) + test_rust_parity.run(["cargo", "build", "--release", "-p", "horizon-world", "--example", "probe"]) + fixture = Path(metadata["target_directory"]) / "release/examples" / ("probe.exe" if os.name=="nt" else "probe") + test_rust_parity.run([str(fixture), "tick_fixture", str(base)]) references = [] for side, jar in jars.items(): reference = base / f"vanilla-{side}.txt" diff --git a/tools/test_tree_feature_parity.py b/tools/test_tree_feature_parity.py index 66f7a6eb7..b3f9ace68 100644 --- a/tools/test_tree_feature_parity.py +++ b/tools/test_tree_feature_parity.py @@ -109,7 +109,7 @@ def main(): oracle=parity/'VanillaTreeFeatureOracle.java';exporter=parity/'VanillaSimpleBlockOracle.java' helpers=[parity/(name+'.java') for name in ['VanillaPlacementOracle','VanillaBlockSurvivalOracle','VanillaBlockPropertiesOracle','VanillaBlockSupportOracle','VanillaBlockStateCodecOracle','VanillaCollisionOracle','VanillaHeightmapOracle']] sources=[oracle,exporter,*helpers,Path(__file__),*[lab.ROOT/'tools'/name for name in ['test_block_survival_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock', - *sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/tree_feature_fixture.rs'] + *sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/tree_feature_fixture.rs'] tested_sources=base.source_hashes(sources);classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): with (build/(name+'.log')).open('w',encoding='utf-8') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=7200,stdout=log,stderr=subprocess.STDOUT) @@ -135,10 +135,10 @@ def main(): output.write(json.dumps(fixture,separators=(',',':'))+'\n');count+=1 fixtures=[inputs,*sorted(build.glob('*.nbt')),*[p for p in sorted(build.glob('*.json')) if p.name!='report.json']];tested_fixtures=fixture_hashes(fixtures) print(f'Prepared {count:,} feature fixtures',flush=True) - run(['cargo','build','--release','-p','horizon-world','--example','tree_feature_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('tree_feature_fixture.exe' if os.name=='nt' else 'tree_feature_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'tree_feature_fixture',build],'rust');references=[] for side,jar in jars.items(): java('VanillaTreeFeatureOracle',side,side,build);matched=base.compare(build/(side+'.txt'),build/'rust.txt');print(f'{side}: {matched:,} tree/ore output lines match Rust',flush=True) references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(build/(side+'.txt'),'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_use_flag_reaction_parity.py b/tools/test_use_flag_reaction_parity.py index b52f0b868..de3b5fa20 100644 --- a/tools/test_use_flag_reaction_parity.py +++ b/tools/test_use_flag_reaction_parity.py @@ -49,7 +49,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaUseFlagReactionOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/use_flag_reaction_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/use_flag_reaction_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -60,10 +60,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaUseFlagReactionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','use_flag_reaction_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('use_flag_reaction_fixture.exe' if os.name=='nt' else 'use_flag_reaction_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'use_flag_reaction_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_use_remainder_parity.py b/tools/test_use_remainder_parity.py index 05b964325..853d12acb 100644 --- a/tools/test_use_remainder_parity.py +++ b/tools/test_use_remainder_parity.py @@ -48,7 +48,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaUseRemainderOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/use_remainder_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/use_remainder_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaUseRemainderOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','use_remainder_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('use_remainder_fixture.exe' if os.name=='nt' else 'use_remainder_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'use_remainder_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_value_provider_parity.py b/tools/test_value_provider_parity.py index f276e4f31..589a97632 100644 --- a/tools/test_value_provider_parity.py +++ b/tools/test_value_provider_parity.py @@ -66,7 +66,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaValueProviderOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/value_provider_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/value_provider_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -74,10 +74,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","value_provider_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("value_provider_fixture.exe" if os.name=="nt" else "value_provider_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"value_provider_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_view_direction_parity.py b/tools/test_view_direction_parity.py index 9dbb47de5..f2738dcff 100644 --- a/tools/test_view_direction_parity.py +++ b/tools/test_view_direction_parity.py @@ -47,7 +47,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaViewDirectionOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/view_direction_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/view_direction_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -58,10 +58,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaViewDirectionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','view_direction_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('view_direction_fixture.exe' if os.name=='nt' else 'view_direction_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'view_direction_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_water_splash_parity.py b/tools/test_water_splash_parity.py index b746b31c0..84f89d360 100644 --- a/tools/test_water_splash_parity.py +++ b/tools/test_water_splash_parity.py @@ -48,7 +48,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWaterSplashOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/water_splash_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/water_splash_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaWaterSplashOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','water_splash_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('water_splash_fixture.exe' if os.name=='nt' else 'water_splash_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'water_splash_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_world_border_parity.py b/tools/test_world_border_parity.py index 62aa58ddf..618194978 100644 --- a/tools/test_world_border_parity.py +++ b/tools/test_world_border_parity.py @@ -59,7 +59,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldBorderOracle.java' helper=oracle.with_name('VanillaFaceSupportOracle.java') - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/world_border_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/world_border_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -70,10 +70,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaWorldBorderOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','world_border_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('world_border_fixture.exe' if os.name=='nt' else 'world_border_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'world_border_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_world_collision_check_parity.py b/tools/test_world_collision_check_parity.py index d6f7e0bfb..3dae747d5 100644 --- a/tools/test_world_collision_check_parity.py +++ b/tools/test_world_collision_check_parity.py @@ -50,7 +50,7 @@ def main(): sources = [oracle, *helpers, Path(__file__), lab.ROOT/'tools/test_rust_parity.py', lab.ROOT/'tools/test_worldgen_parity.py', lab.ROOT/'tools/lab.py', lab.ROOT/'Cargo.toml', lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-world/examples/registry_collision_scan_fixture.rs'] + lab.ROOT/'crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs'] for crate in ['horizon-core', 'horizon-world']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml', *sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] @@ -80,10 +80,10 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'facts.json', 'definitions.json', 'block-registry.nbt', 'cached-collision.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'registry_collision_scan_fixture'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('registry_collision_scan_fixture.exe' if os.name=='nt' else 'registry_collision_scan_fixture') - run([binary, build], 'rust');references = [] + binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'registry_collision_scan_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) matched = base.compare(build/(side+'.txt'), build/'rust.txt') diff --git a/tools/test_world_edge_backoff_parity.py b/tools/test_world_edge_backoff_parity.py index bf4c39c70..10cf1316f 100644 --- a/tools/test_world_edge_backoff_parity.py +++ b/tools/test_world_edge_backoff_parity.py @@ -51,7 +51,7 @@ def main(): sources = [oracle, *helpers, Path(__file__), lab.ROOT/'tools/test_rust_parity.py', lab.ROOT/'tools/test_worldgen_parity.py', lab.ROOT/'tools/lab.py', lab.ROOT/'Cargo.toml', lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-world/examples/registry_collision_scan_fixture.rs'] + lab.ROOT/'crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs'] for crate in ['horizon-core', 'horizon-world']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml', *sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] @@ -81,10 +81,10 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'facts.json', 'definitions.json', 'block-registry.nbt', 'cached-collision.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'registry_collision_scan_fixture'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('registry_collision_scan_fixture.exe' if os.name=='nt' else 'registry_collision_scan_fixture') - run([binary, build], 'rust');references = [] + binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'registry_collision_scan_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) matched = base.compare(build/(side+'.txt'), build/'rust.txt') diff --git a/tools/test_world_movement_parity.py b/tools/test_world_movement_parity.py index e01a989f5..5a583ecb7 100644 --- a/tools/test_world_movement_parity.py +++ b/tools/test_world_movement_parity.py @@ -76,7 +76,7 @@ def main(): sources = [oracle, *helpers, Path(__file__), lab.ROOT/'tools/test_rust_parity.py', lab.ROOT/'tools/test_worldgen_parity.py', lab.ROOT/'tools/lab.py', lab.ROOT/'Cargo.toml', lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-world/examples/registry_collision_scan_fixture.rs'] + lab.ROOT/'crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs'] for crate in ['horizon-core', 'horizon-world']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml', *sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] @@ -106,10 +106,10 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'facts.json', 'definitions.json', 'block-registry.nbt', 'cached-collision.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'registry_collision_scan_fixture'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('registry_collision_scan_fixture.exe' if os.name=='nt' else 'registry_collision_scan_fixture') - run([binary, build], 'rust');references = [] + binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'registry_collision_scan_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) matched = base.compare(build/(side+'.txt'), build/'rust.txt') diff --git a/tools/test_world_parity.py b/tools/test_world_parity.py index 802dc3884..e2781866e 100644 --- a/tools/test_world_parity.py +++ b/tools/test_world_parity.py @@ -51,12 +51,12 @@ def main(): print("Generating vanilla world-data fixtures...", flush=True) print(java("server", "generate").split("HORIZON_WORLD_GENERATED")[-1].strip(), flush=True) - run(["cargo", "build", "--release", "-p", "horizon-world", "--bin", "horizon-world", "--example", "world_fixture"], base / "compile-rust.log") + run(["cargo", "build", "--release", "-p", "horizon-world", "--bin", "horizon-world", "--example", "probe"], base / "compile-rust.log") metadata = json.loads(run(["cargo", "metadata", "--no-deps", "--format-version", "1"])) target = Path(metadata["target_directory"]) / "release" suffix = ".exe" if os.name == "nt" else "" binary = target / ("horizon-world" + suffix) - run([target / "examples" / ("world_fixture" + suffix), base], base / "rust-fixture.log") + run([target / "examples" / ("probe" + suffix), "world_fixture", base], base / "rust-fixture.log") for network in [False, True]: kind = "network" if network else "nbt" output = base / "rust" / kind diff --git a/tools/test_world_ray_parity.py b/tools/test_world_ray_parity.py index 93f2dfcef..87189d611 100644 --- a/tools/test_world_ray_parity.py +++ b/tools/test_world_ray_parity.py @@ -49,7 +49,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldRayOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/world_ray_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/world_ray_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -60,10 +60,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaWorldRayOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','world_ray_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('world_ray_fixture.exe' if os.name=='nt' else 'world_ray_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'world_ray_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_world_spawn_parity.py b/tools/test_world_spawn_parity.py index 4247a0ee7..f73da3a8c 100644 --- a/tools/test_world_spawn_parity.py +++ b/tools/test_world_spawn_parity.py @@ -79,7 +79,7 @@ def origins(build, classes, dependencies, all_seeds): vanilla_out = build / 'origins-vanilla.txt' oh.run_logged(['java', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaWorldSpawnOracle', vanilla_out, *all_seeds], build, 'origins-vanilla') - rust = subprocess.run([target_dir() / 'examples/spawn_origin', RESOURCES, *map(str, all_seeds)], + rust = subprocess.run([target_dir() / 'examples/probe', 'spawn_origin', RESOURCES, *map(str, all_seeds)], capture_output=True, text=True, check=True, cwd=lab.ROOT).stdout vanilla = vanilla_out.read_text() parse = lambda text: {int(l.split()[0]): tuple(map(int, l.split()[1:])) for l in text.splitlines() if l} @@ -121,7 +121,7 @@ def main(): oh.run_logged(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-cp', dependencies, '-d', classes, lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldSpawnOracle.java'], build, 'compile-java') - oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'spawn_origin'], build, 'compile-probe') + oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'probe'], build, 'compile-probe') all_seeds = parity_shard.shard(args.seed or seeds(args.random)) started = time.time() diff --git a/tools/test_worldgen_random_parity.py b/tools/test_worldgen_random_parity.py index 7b2d37a6f..29eedfa49 100644 --- a/tools/test_worldgen_random_parity.py +++ b/tools/test_worldgen_random_parity.py @@ -44,7 +44,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldgenRandomOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/worldgen_random_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/worldgen_random_fixture.rs'] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) @@ -53,10 +53,10 @@ def main(): with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','worldgen_random_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('worldgen_random_fixture.exe' if os.name=='nt' else 'worldgen_random_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'worldgen_random_fixture',build],'rust');references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependency_path]),'dev.horizonlab.parity.VanillaWorldgenRandomOracle',side,build],side) reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') From 7092f16a06f73d825cc73c6cdf132674a418fc70 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 14:23:44 +0200 Subject: [PATCH 038/408] horizon-world probes: one copy of the helpers they shared Now that the probes are modules of one binary, the helpers copied between them live once in examples/probe/support: the collision probes' shape printer (emit, values, box_values, bounds, 8 copies each), the canonical NaN bits of f64 and f32 (50 copies), the registry JSON-to-NBT reader (15) and the JSON block position (4). -1,097 lines of copies. f64::NAN.to_bits() is 0x7ff8000000000000, the literal some copies used, so every probe prints the same bytes. tools/parity.py follows include!: three probes include another probe's source, and stay dependent on it. Co-Authored-By: Claude Opus 5.5 --- .../examples/probe/attribute_fixture.rs | 22 ++--- .../probe/attribute_health_fixture.rs | 22 ++--- .../probe/attribute_map_queries_fixture.rs | 10 +-- .../probe/block_collision_scan_fixture.rs | 67 +-------------- .../examples/probe/block_landing_fixture.rs | 30 ++----- .../examples/probe/block_push_fixture.rs | 28 ++---- .../probe/block_state_codec_fixture.rs | 12 +-- .../examples/probe/blocking_rules_fixture.rs | 10 +-- .../examples/probe/bulk_section_fixture.rs | 12 +-- .../probe/carving_geometry_fixture.rs | 14 +-- .../examples/probe/chunk_dump.rs | 12 +-- .../examples/probe/chunk_stage_fixture.rs | 12 +-- .../probe/collision_context_fixture.rs | 67 +-------------- .../examples/probe/combat_rules_fixture.rs | 10 +-- .../probe/consumable_emission_fixture.rs | 20 ++--- .../examples/probe/consumable_fixture.rs | 26 +++--- .../probe/damage_reduction_fixture.rs | 12 +-- .../examples/probe/damage_source_fixture.rs | 14 +-- .../examples/probe/dynamic_support_fixture.rs | 67 +-------------- .../examples/probe/edge_backoff_fixture.rs | 26 +++--- .../effect_attribute_modifiers_fixture.rs | 29 +++---- .../probe/entity_attribute_fixture.rs | 14 +-- .../probe/entity_collision_fixture.rs | 67 +-------------- .../examples/probe/entity_fluid_fixture.rs | 30 +++---- .../examples/probe/entity_move_fixture.rs | 32 ++----- .../examples/probe/face_support_fixture.rs | 67 +-------------- .../examples/probe/fall_damage_fixture.rs | 24 ++---- .../examples/probe/feature_catalog_fixture.rs | 12 +-- .../examples/probe/feature_region_fixture.rs | 12 +-- .../examples/probe/fill_layer_fixture.rs | 12 +-- .../examples/probe/fluid_fixture.rs | 12 +-- .../examples/probe/food_fixture.rs | 20 ++--- .../examples/probe/food_storage_fixture.rs | 18 ++-- .../examples/probe/ground_state_fixture.rs | 20 ++--- .../probe/interaction_shape_fixture.rs | 26 +++--- .../examples/probe/item_blocking_fixture.rs | 12 +-- .../examples/probe/item_particles_fixture.rs | 20 ++--- .../examples/probe/item_use_fixture.rs | 10 +-- .../probe/live_attribute_updates_fixture.rs | 8 +- .../examples/probe/live_attributes_fixture.rs | 23 ++--- .../examples/probe/living_air_fixture.rs | 22 +++-- .../examples/probe/living_damage_fixture.rs | 28 +++--- .../examples/probe/living_fall_fixture.rs | 16 ++-- .../examples/probe/living_fluid_fixture.rs | 22 +++-- .../examples/probe/living_health_fixture.rs | 18 ++-- .../examples/probe/living_hurt_fixture.rs | 22 ++--- .../examples/probe/living_landing_fixture.rs | 32 +++---- .../examples/probe/living_motion_fixture.rs | 22 ++--- crates/horizon-world/examples/probe/main.rs | 2 + .../examples/probe/material_stage_fixture.rs | 12 +-- .../probe/movement_emission_fixture.rs | 21 +---- .../probe/movement_registry_fixture.rs | 8 +- .../probe/movement_support_fixture.rs | 8 +- .../examples/probe/piston_movement_fixture.rs | 20 ++--- .../examples/probe/piston_shape_fixture.rs | 67 +-------------- .../examples/probe/player_food_fixture.rs | 12 +-- .../examples/probe/player_health_fixture.rs | 18 ++-- .../examples/probe/player_hurt_fixture.rs | 22 ++--- .../examples/probe/player_travel_fixture.rs | 15 ++-- .../probe/registered_player_combat_fixture.rs | 34 +++----- .../probe/registry_collision_scan_fixture.rs | 65 +------------- .../probe/registry_fall_ray_fixture.rs | 14 +-- .../examples/probe/replace_block_fixture.rs | 12 +-- .../examples/probe/restitution_fixture.rs | 16 ++-- .../examples/probe/rule_test_fixture.rs | 12 +-- .../examples/probe/scattered_ore_fixture.rs | 12 +-- .../probe/server_player_combat_fixture.rs | 34 +++----- .../probe/server_player_damage_fixture.rs | 24 ++---- .../examples/probe/spawn_origin.rs | 12 +-- .../examples/probe/state_provider_fixture.rs | 12 +-- .../probe/stored_effect_attributes_fixture.rs | 19 ++--- .../stored_effect_notifications_fixture.rs | 2 +- .../examples/probe/support/common.rs | 49 +++++++++++ .../examples/probe/support/shapes.rs | 85 +++++++++++++++++++ .../examples/probe/synced_floats_fixture.rs | 16 ++-- .../probe/teleport_consume_fixture.rs | 34 +++----- .../examples/probe/terrain_fixture.rs | 12 +-- .../examples/probe/view_direction_fixture.rs | 20 ++--- .../examples/probe/water_splash_fixture.rs | 15 ++-- .../examples/probe/world_border_fixture.rs | 67 +-------------- .../examples/probe/world_ray_fixture.rs | 14 +-- tests/test_parity_runner.py | 9 +- tools/parity.py | 24 +++--- 83 files changed, 561 insertions(+), 1400 deletions(-) create mode 100644 crates/horizon-world/examples/probe/support/common.rs create mode 100644 crates/horizon-world/examples/probe/support/shapes.rs diff --git a/crates/horizon-world/examples/probe/attribute_fixture.rs b/crates/horizon-world/examples/probe/attribute_fixture.rs index e5432a6a3..79cf4e236 100644 --- a/crates/horizon-world/examples/probe/attribute_fixture.rs +++ b/crates/horizon-world/examples/probe/attribute_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_world::attributes::{ AttributeError, Definition, Instance, Modifier, Observer, Operation, Packed, }; @@ -10,13 +11,6 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } -} fn refs<'a>(mods: impl IntoIterator, pool: &[Modifier]) -> String { let s = mods .into_iter() @@ -43,9 +37,9 @@ impl Observer for Callback<'_> { self.out, "dirty {} {:016x} {} {:016x} {} {}", self.target, - bits(a.base_value()), + f64_bits(a.base_value()), a.is_dirty(), - bits(a.cached_value()), + f64_bits(a.cached_value()), a.modifiers().len(), a.permanent_modifiers().len() )?; @@ -55,7 +49,7 @@ impl Observer for Callback<'_> { return Err(io::Error::other("injected attribute observer failure")); } if self.op["read"].as_bool().unwrap() { - writeln!(self.out, "observed {:016x}", bits(a.value()))?; + writeln!(self.out, "observed {:016x}", f64_bits(a.value()))?; } Ok(()) } @@ -64,9 +58,9 @@ fn state(out: &mut dyn Write, id: usize, a: &Instance, pool: &[Modifier]) -> io: writeln!( out, "state {id} {:016x} {} {:016x}", - bits(a.base_value()), + f64_bits(a.base_value()), a.is_dirty(), - bits(a.cached_value()) + f64_bits(a.cached_value()) )?; writeln!(out, "all {}", refs(a.modifiers(), pool))?; writeln!(out, "permanent {}", refs(a.permanent_modifiers(), pool))?; @@ -165,7 +159,7 @@ pub fn main() -> Result<(), Box> { writeln!( cb.out, "packed {:016x} {}", - bits(p.base), + f64_bits(p.base), refs(&p.modifiers, &pool) )?; packed = Some(p); @@ -181,7 +175,7 @@ pub fn main() -> Result<(), Box> { ), "many" => instances[target].add_permanent_many(mods(), &mut cb), "value" => { - writeln!(cb.out, "value {:016x}", bits(instances[target].value()))?; + writeln!(cb.out, "value {:016x}", f64_bits(instances[target].value()))?; Ok(()) } _ => panic!("fixture mode"), diff --git a/crates/horizon-world/examples/probe/attribute_health_fixture.rs b/crates/horizon-world/examples/probe/attribute_health_fixture.rs index 5efe0cb96..05e779aac 100644 --- a/crates/horizon-world/examples/probe/attribute_health_fixture.rs +++ b/crates/horizon-world/examples/probe/attribute_health_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::{ attribute_health::{AttributeHealth, HealthAttributes, HealthError, HealthObserver}, attributes::{ @@ -21,13 +22,6 @@ fn single(v: &Value) -> f32 { fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn double_bits(v: f64) -> u64 { if v.is_nan() { f64::NAN.to_bits() @@ -55,7 +49,7 @@ impl Observer<'_> { impl HealthObserver for Observer<'_> { type Error = io::Error; fn updated(&mut self, h: &mut SyncedFloat) -> io::Result<()> { - self.effect(&format!("updated {:08x}", bits(h.value()))) + self.effect(&format!("updated {:08x}", f32_bits(h.value()))) } } // This fixture observes health/food values, not cross-attribute hash order. @@ -168,7 +162,7 @@ impl FoodWorld for World<'_, A> { } fn hurt_starvation(&mut self, _: (), _: &mut FoodData, v: f32) -> Result<(), Self::Error> { self.observer - .effect(&format!("starve {:08x}", bits(v))) + .effect(&format!("starve {:08x}", f32_bits(v))) .map_err(HealthError::Observer) } } @@ -261,7 +255,7 @@ fn run(dir: &Path, output: &str) -> Result<(), Box(dir: &Path, output: &str) -> Result<(), Box { 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!( diff --git a/crates/horizon-world/examples/probe/block_collision_scan_fixture.rs b/crates/horizon-world/examples/probe/block_collision_scan_fixture.rs index c27c554b1..e39fe2b8d 100644 --- a/crates/horizon-world/examples/probe/block_collision_scan_fixture.rs +++ b/crates/horizon-world/examples/probe/block_collision_scan_fixture.rs @@ -1,5 +1,6 @@ +use crate::support::shapes::emit; use horizon_core::{ - geometry::{Aabb, Axis, ShapeOp, Vec3, VoxelShape}, + geometry::{Aabb, ShapeOp, Vec3, VoxelShape}, position::{BlockPos, ChunkPos}, }; use horizon_world::{ @@ -20,70 +21,6 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn values( - out: &mut impl Write, - label: &str, - values: impl IntoIterator, -) -> io::Result<()> { - write!(out, "{label}")?; - for v in values { - let bits = if v.is_nan() { - 0x7ff8_0000_0000_0000 - } else { - v.to_bits() - }; - write!(out, " {bits:016x}")?; - } - writeln!(out) -} -fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { - values( - out, - label, - [ - b.min(Axis::X), - b.min(Axis::Y), - b.min(Axis::Z), - b.max(Axis::X), - b.max(Axis::Y), - b.max(Axis::Z), - ], - ) -} -fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { - writeln!( - out, - "shape {} {} {}", - shape.is_empty(), - shape.boxes().len(), - shape.is_cube() - )?; - for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { - values(out, name, shape.coordinates(axis).iter().copied())?; - } - let axes = shape.cube_coordinate_axes(); - writeln!( - out, - "axes {}", - u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) - )?; - values( - out, - "extrema", - Axis::ALL - .map(|a| shape.min(a)) - .into_iter() - .chain(Axis::ALL.map(|a| shape.max(a))), - )?; - match shape.bounds() { - Some(b) => box_values(out, "bounds", b)?, - None => writeln!(out, "bounds none")?, - } - for b in shape.boxes() { - box_values(out, "box", *b)?; - } - Ok(()) -} fn shape(index: u64) -> VoxelShape { let cuboid = |min, max| VoxelShape::from_box(Aabb::new(min, max)).unwrap(); diff --git a/crates/horizon-world/examples/probe/block_landing_fixture.rs b/crates/horizon-world/examples/probe/block_landing_fixture.rs index 77b42f418..a6ab6ac33 100644 --- a/crates/horizon-world/examples/probe/block_landing_fixture.rs +++ b/crates/horizon-world/examples/probe/block_landing_fixture.rs @@ -1,5 +1,7 @@ +use crate::support::common::f64_bits; +use crate::support::shapes::bounds; use horizon_core::{ - geometry::{Aabb, Axis, Vec3, VoxelShape}, + geometry::{Aabb, Vec3, VoxelShape}, position::BlockPos, }; use horizon_world::{ @@ -24,13 +26,6 @@ fn number(v: &Value) -> f64 { fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn fbits(v: f32) -> u32 { if v.is_nan() { 0x7fc00000 } else { v.to_bits() } } @@ -43,17 +38,6 @@ fn bbox(v: &Value) -> Aabb { Vec3::new(number(&v[3]), number(&v[4]), number(&v[5])), ) } -fn bounds(label: &str, b: Aabb) -> String { - format!( - "{label} {:016x} {:016x} {:016x} {:016x} {:016x} {:016x}", - bits(b.min(Axis::X)), - bits(b.min(Axis::Y)), - bits(b.min(Axis::Z)), - bits(b.max(Axis::X)), - bits(b.max(Axis::Y)), - bits(b.max(Axis::Z)) - ) -} struct World<'a, 'r> { f: &'a Value, out: &'a mut dyn Write, @@ -100,9 +84,9 @@ impl BlockPushWorld for World<'_, '_> { self.query(format!( "teleport {} {:016x} {:016x} {:016x}", e.0, - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) ))?; let i = e.0 as usize; self.entities[i] = self.entities[i].move_by(v); @@ -169,7 +153,7 @@ impl BlockLandingWorld for World<'_, '_> { Ok(k) } fn cause_fall_damage(&mut self, d: f64, m: f32, s: Self::DamageSource) -> io::Result { - self.query(format!("damage {:016x} {:08x} {s}", bits(d), fbits(m)))?; + self.query(format!("damage {:016x} {:08x} {s}", f64_bits(d), fbits(m)))?; Ok(self.flag("damage")) } fn known_sound(&self, s: LandingSound) -> Self::Sound { diff --git a/crates/horizon-world/examples/probe/block_push_fixture.rs b/crates/horizon-world/examples/probe/block_push_fixture.rs index 2c77a8059..678e0fa24 100644 --- a/crates/horizon-world/examples/probe/block_push_fixture.rs +++ b/crates/horizon-world/examples/probe/block_push_fixture.rs @@ -1,5 +1,7 @@ +use crate::support::common::f64_bits; +use crate::support::shapes::bounds; use horizon_core::{ - geometry::{Aabb, Axis, ShapeOp, Vec3, VoxelShape}, + geometry::{Aabb, ShapeOp, Vec3, VoxelShape}, position::BlockPos, }; use horizon_world::{ @@ -16,30 +18,12 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn bbox(v: &Value) -> Aabb { Aabb::new( Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])), Vec3::new(number(&v[3]), number(&v[4]), number(&v[5])), ) } -fn bounds(label: &str, b: Aabb) -> String { - format!( - "{label} {:016x} {:016x} {:016x} {:016x} {:016x} {:016x}", - bits(b.min(Axis::X)), - bits(b.min(Axis::Y)), - bits(b.min(Axis::Z)), - bits(b.max(Axis::X)), - bits(b.max(Axis::Y)), - bits(b.max(Axis::Z)) - ) -} fn shape(v: &Value) -> Result> { let mut s = VoxelShape::empty(); for b in v.as_array().unwrap() { @@ -85,9 +69,9 @@ impl BlockPushWorld for World<'_> { self.query(format!( "teleport {} {:016x} {:016x} {:016x}", e.0, - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) ))?; let index = e.0 as usize; self.entities[index] = self.entities[index].move_by(v); diff --git a/crates/horizon-world/examples/probe/block_state_codec_fixture.rs b/crates/horizon-world/examples/probe/block_state_codec_fixture.rs index c0372d4fd..40d51d4c2 100644 --- a/crates/horizon-world/examples/probe/block_state_codec_fixture.rs +++ b/crates/horizon-world/examples/probe/block_state_codec_fixture.rs @@ -1,4 +1,5 @@ //! Original JSON block-state codec comparison transport. +use crate::support::common::tag; use horizon_world::{ DATA_VERSION, nbt::Tag, @@ -11,17 +12,6 @@ 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"), - } -} pub fn main() -> Result<(), Box> { let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); diff --git a/crates/horizon-world/examples/probe/blocking_rules_fixture.rs b/crates/horizon-world/examples/probe/blocking_rules_fixture.rs index c8613725c..19d3bb8d5 100644 --- a/crates/horizon-world/examples/probe/blocking_rules_fixture.rs +++ b/crates/horizon-world/examples/probe/blocking_rules_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::blocking_rules::{ BlockingRules, DamageReduction, ItemDamageFunction, TypeMatchWorld, }; @@ -13,13 +14,6 @@ fn single(v: &Value) -> f32 { fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} struct World<'a> { f: &'a Value, out: &'a mut dyn Write, @@ -96,7 +90,7 @@ pub fn main() -> Result<(), Box> { )?; writeln!(w.out, "item {}", rules.item_damage.apply(damage))?; match rules.resolve(&mut w, damage, number(&f["angle"])) { - Ok(v) => writeln!(w.out, "blocked {:08x}\nresult ok", bits(v))?, + Ok(v) => writeln!(w.out, "blocked {:08x}\nresult ok", f32_bits(v))?, Err(_) => writeln!(w.out, "result error")?, }; writeln!(w.out, "queries {} {}", w.calls, w.changed)?; diff --git a/crates/horizon-world/examples/probe/bulk_section_fixture.rs b/crates/horizon-world/examples/probe/bulk_section_fixture.rs index eefdd9e52..a7bcc834a 100644 --- a/crates/horizon-world/examples/probe/bulk_section_fixture.rs +++ b/crates/horizon-world/examples/probe/bulk_section_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::tag; use horizon_world::worldgen::{ anchor::WorldGenerationContext, bulk_section::TerrainBulkAccess, feature_region::TerrainRegion, }; @@ -55,17 +56,6 @@ impl TerrainBlockStates for Properties<'_> { fn n(v: &Value) -> i32 { v.as_i64().unwrap() as i32 } -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(i) => Tag::Int(i.as_i64().unwrap() as i32), - Value::Object(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - _ => panic!("unsupported registry fixture value"), - } -} fn fixture( f: &Value, registry: &BlockRegistry, diff --git a/crates/horizon-world/examples/probe/carving_geometry_fixture.rs b/crates/horizon-world/examples/probe/carving_geometry_fixture.rs index c45ae4cda..52582b45b 100644 --- a/crates/horizon-world/examples/probe/carving_geometry_fixture.rs +++ b/crates/horizon-world/examples/probe/carving_geometry_fixture.rs @@ -1,4 +1,5 @@ //! Transport for shared cave/canyon geometry and ordered output failures. +use crate::support::common::f64_bits; use horizon_core::{ carving::{CarverOutput, CarvingMask, can_reach, carve_ellipsoid}, position::ChunkPos, @@ -15,13 +16,6 @@ fn n(v: &Value) -> i32 { fn d(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} struct Output<'a> { mask: &'a mut CarvingMask, trace: &'a std::cell::RefCell>, @@ -78,9 +72,9 @@ pub fn main() -> Result<(), Box> { }; trace.borrow_mut().push(format!( "skip {:x} {:x} {:x} {by} {skip}", - bits(x), - bits(y), - bits(z) + f64_bits(x), + f64_bits(y), + f64_bits(z) )); skip }, diff --git a/crates/horizon-world/examples/probe/chunk_dump.rs b/crates/horizon-world/examples/probe/chunk_dump.rs index f6a93e660..d36944989 100644 --- a/crates/horizon-world/examples/probe/chunk_dump.rs +++ b/crates/horizon-world/examples/probe/chunk_dump.rs @@ -11,6 +11,7 @@ //! quart layer (16 columns, z-major), one `y Y ID...` line per block row and //! one `be X Y Z CANONICAL_NBT` line per block entity and one `t block|fluid //! NAME X Y Z PRIORITY` line per scheduled tick. +use crate::support::common::tag; use horizon_core::position::ChunkPos; use horizon_world::{ DATA_VERSION, @@ -23,17 +24,6 @@ use std::{collections::HashMap, fmt::Write as _, fs, io::Write as _, path::Path} type Error = Box; -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - Value::Object(o) => { - Tag::Compound(o.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - _ => panic!("invalid registry metadata"), - } -} fn registry(resources: &Path) -> Result<&'static BlockRegistry, Error> { let facts: Value = serde_json::from_str(&fs::read_to_string(resources.join("facts.json"))?)?; let states = facts["states"].as_array().ok_or("facts states")?; diff --git a/crates/horizon-world/examples/probe/chunk_stage_fixture.rs b/crates/horizon-world/examples/probe/chunk_stage_fixture.rs index 0ae093dcd..2929de2f1 100644 --- a/crates/horizon-world/examples/probe/chunk_stage_fixture.rs +++ b/crates/horizon-world/examples/probe/chunk_stage_fixture.rs @@ -1,4 +1,5 @@ //! Test transport for pre-light ProtoChunk writes and stage heightmap transitions. +use crate::support::common::tag; use horizon_core::position::ChunkPos; use horizon_world::{ DATA_VERSION, @@ -54,17 +55,6 @@ impl TerrainBlockStates for Properties<'_> { fn n(v: &Value) -> i32 { v.as_i64().unwrap() as i32 } -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(i) => Tag::Int(i.as_i64().unwrap() as i32), - Value::Object(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - _ => panic!("unsupported registry fixture value"), - } -} fn fixture( f: &Value, registry: &BlockRegistry, diff --git a/crates/horizon-world/examples/probe/collision_context_fixture.rs b/crates/horizon-world/examples/probe/collision_context_fixture.rs index 86620ab99..f26137fef 100644 --- a/crates/horizon-world/examples/probe/collision_context_fixture.rs +++ b/crates/horizon-world/examples/probe/collision_context_fixture.rs @@ -1,5 +1,6 @@ +use crate::support::shapes::emit; use horizon_core::{ - geometry::{Aabb, Axis, ShapeOp, Vec3, VoxelShape}, + geometry::{Aabb, ShapeOp, Vec3, VoxelShape}, position::BlockPos, }; use horizon_world::{ @@ -31,70 +32,6 @@ const ITEMS: [&str; 5] = [ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn values( - out: &mut impl Write, - label: &str, - values: impl IntoIterator, -) -> io::Result<()> { - write!(out, "{label}")?; - for v in values { - let bits = if v.is_nan() { - 0x7ff8_0000_0000_0000 - } else { - v.to_bits() - }; - write!(out, " {bits:016x}")?; - } - writeln!(out) -} -fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { - values( - out, - label, - [ - b.min(Axis::X), - b.min(Axis::Y), - b.min(Axis::Z), - b.max(Axis::X), - b.max(Axis::Y), - b.max(Axis::Z), - ], - ) -} -fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { - writeln!( - out, - "shape {} {} {}", - shape.is_empty(), - shape.boxes().len(), - shape.is_cube() - )?; - for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { - values(out, name, shape.coordinates(axis).iter().copied())?; - } - let axes = shape.cube_coordinate_axes(); - writeln!( - out, - "axes {}", - u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) - )?; - values( - out, - "extrema", - Axis::ALL - .map(|a| shape.min(a)) - .into_iter() - .chain(Axis::ALL.map(|a| shape.max(a))), - )?; - match shape.bounds() { - Some(b) => box_values(out, "bounds", b)?, - None => writeln!(out, "bounds none")?, - } - for b in shape.boxes() { - box_values(out, "box", *b)?; - } - Ok(()) -} struct LiquidWorld<'a, W> { out: &'a mut W, calls: i32, diff --git a/crates/horizon-world/examples/probe/combat_rules_fixture.rs b/crates/horizon-world/examples/probe/combat_rules_fixture.rs index 973596f6c..9e523a30d 100644 --- a/crates/horizon-world/examples/probe/combat_rules_fixture.rs +++ b/crates/horizon-world/examples/probe/combat_rules_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::combat_rules::{self, ArmorWorld}; use serde_json::Value; use std::{ @@ -8,13 +9,6 @@ use std::{ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} struct World<'a> { f: &'a Value, out: &'a mut dyn Write, @@ -77,7 +71,7 @@ pub fn main() -> Result<(), Box> { }; match result { Ok(v) => { - writeln!(w.out, "value {:08x}\nresult ok", bits(v))?; + writeln!(w.out, "value {:08x}\nresult ok", f32_bits(v))?; } Err(_) => writeln!(w.out, "result error")?, } diff --git a/crates/horizon-world/examples/probe/consumable_emission_fixture.rs b/crates/horizon-world/examples/probe/consumable_emission_fixture.rs index 55dcf0100..6bff122e1 100644 --- a/crates/horizon-world/examples/probe/consumable_emission_fixture.rs +++ b/crates/horizon-world/examples/probe/consumable_emission_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{ geometry::Vec3, random::{LegacyRandom, RandomSource, XoroshiroRandom}, @@ -23,13 +24,6 @@ fn n(v: &Value, k: &str) -> i32 { fn fl(v: &Value, k: &str) -> f32 { f32::from_bits(v[k].as_u64().unwrap() as u32) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn opt(v: Option<&i32>) -> String { v.map_or("none".into(), i32::to_string) } @@ -142,12 +136,12 @@ impl ItemParticleWorld for World<'_, R> { "particle {level} {} {} {damage} {same} {} {} {} {} {} {}", t.item(), t.count(), - bits(p.x), - bits(p.y), - bits(p.z), - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z), + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) )) } } diff --git a/crates/horizon-world/examples/probe/consumable_fixture.rs b/crates/horizon-world/examples/probe/consumable_fixture.rs index b5eec06dc..fccf46129 100644 --- a/crates/horizon-world/examples/probe/consumable_fixture.rs +++ b/crates/horizon-world/examples/probe/consumable_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{ geometry::Vec3, random::{LegacyRandom, RandomSource, XoroshiroRandom}, @@ -33,13 +34,6 @@ fn n(v: &Value, k: &str) -> i32 { fn fl(v: &Value, k: &str) -> f32 { f32::from_bits(v[k].as_u64().unwrap() as u32) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn opt(v: Option<&Component>) -> String { match v { None => "none".into(), @@ -189,12 +183,12 @@ impl ItemParticleWorld for World<'_, R> { "particle {level} {} {} {damage} {same} {} {} {} {} {} {}", t.item(), t.count(), - bits(p.x), - bits(p.y), - bits(p.z), - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z), + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) )) } } @@ -263,9 +257,9 @@ impl FoodConsumptionWorld for World<'_, R> { "food-sound {} {} {category} {} {} {} {} {}", s.level, s.sound, - bits(s.position.x), - bits(s.position.y), - bits(s.position.z), + f64_bits(s.position.x), + f64_bits(s.position.y), + f64_bits(s.position.z), fbits(s.volume), fbits(s.pitch) )) diff --git a/crates/horizon-world/examples/probe/damage_reduction_fixture.rs b/crates/horizon-world/examples/probe/damage_reduction_fixture.rs index 766a53439..7310ca43e 100644 --- a/crates/horizon-world/examples/probe/damage_reduction_fixture.rs +++ b/crates/horizon-world/examples/probe/damage_reduction_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::{ combat_rules::ArmorWorld, damage_reduction::{self, Bypass, DamageReductionWorld}, @@ -14,13 +15,6 @@ fn single(v: &Value) -> f32 { fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} struct World<'a> { f: &'a Value, out: &'a mut dyn Write, @@ -73,7 +67,7 @@ impl DamageReductionWorld for World<'_> { Ok(self.state()[format!("bypass_{n}")].as_bool().unwrap()) } fn hurt_armor(&mut self, v: f32) -> io::Result<()> { - self.query(&format!("hurt-armor {:08x}", bits(v))) + self.query(&format!("hurt-armor {:08x}", f32_bits(v))) } fn armor_value(&mut self) -> io::Result { self.query("armor")?; @@ -139,7 +133,7 @@ pub fn main() -> Result<(), Box> { } else { damage_reduction::after_magic(&mut w, d) }; - r.and_then(|v| writeln!(w.out, "float {:08x}", bits(v))) + r.and_then(|v| writeln!(w.out, "float {:08x}", f32_bits(v))) }; writeln!( w.out, diff --git a/crates/horizon-world/examples/probe/damage_source_fixture.rs b/crates/horizon-world/examples/probe/damage_source_fixture.rs index f50f11d22..8599e3cac 100644 --- a/crates/horizon-world/examples/probe/damage_source_fixture.rs +++ b/crates/horizon-world/examples/probe/damage_source_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_world::damage_source::{Catalog, EntityKind, SourceWorld}; use serde_json::Value; use std::{ @@ -11,21 +12,14 @@ fn number(v: &Value) -> f64 { fn position(v: &Value) -> [f64; 3] { std::array::from_fn(|i| number(&v[i])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } -} fn vec(v: Option<[f64; 3]>) -> String { match v { None => "none".into(), Some(v) => format!( "{:016x} {:016x} {:016x}", - bits(v[0]), - bits(v[1]), - bits(v[2]) + f64_bits(v[0]), + f64_bits(v[1]), + f64_bits(v[2]) ), } } diff --git a/crates/horizon-world/examples/probe/dynamic_support_fixture.rs b/crates/horizon-world/examples/probe/dynamic_support_fixture.rs index 92f8c159a..84a176ea4 100644 --- a/crates/horizon-world/examples/probe/dynamic_support_fixture.rs +++ b/crates/horizon-world/examples/probe/dynamic_support_fixture.rs @@ -1,4 +1,5 @@ -use horizon_core::geometry::{Aabb, Axis, Direction, VoxelShape}; +use crate::support::shapes::{emit, values}; +use horizon_core::geometry::{Direction, VoxelShape}; use horizon_world::{ block_collision::{DynamicCollisionWorld, ShulkerCollisionState}, block_support::SupportType, @@ -15,70 +16,6 @@ use std::{ io::{self, Write}, path::Path, }; -fn values( - out: &mut impl Write, - label: &str, - values: impl IntoIterator, -) -> io::Result<()> { - write!(out, "{label}")?; - for v in values { - let bits = if v.is_nan() { - 0x7ff8_0000_0000_0000 - } else { - v.to_bits() - }; - write!(out, " {bits:016x}")?; - } - writeln!(out) -} -fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { - values( - out, - label, - [ - b.min(Axis::X), - b.min(Axis::Y), - b.min(Axis::Z), - b.max(Axis::X), - b.max(Axis::Y), - b.max(Axis::Z), - ], - ) -} -fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { - writeln!( - out, - "shape {} {} {}", - shape.is_empty(), - shape.boxes().len(), - shape.is_cube() - )?; - for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { - values(out, name, shape.coordinates(axis).iter().copied())?; - } - let axes = shape.cube_coordinate_axes(); - writeln!( - out, - "axes {}", - u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) - )?; - values( - out, - "extrema", - Axis::ALL - .map(|a| shape.min(a)) - .into_iter() - .chain(Axis::ALL.map(|a| shape.max(a))), - )?; - match shape.bounds() { - Some(b) => box_values(out, "bounds", b)?, - None => writeln!(out, "bounds none")?, - } - for b in shape.boxes() { - box_values(out, "box", *b)?; - } - Ok(()) -} struct World<'a, W> { collisions: &'a CachedCollisionRegistry<'a>, pistons: &'a PistonBlockBindings<'a>, diff --git a/crates/horizon-world/examples/probe/edge_backoff_fixture.rs b/crates/horizon-world/examples/probe/edge_backoff_fixture.rs index ad9eb235a..a805cbb1e 100644 --- a/crates/horizon-world/examples/probe/edge_backoff_fixture.rs +++ b/crates/horizon-world/examples/probe/edge_backoff_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::geometry::{Aabb, Axis, Vec3}; use horizon_world::edge_backoff::{EdgeBackoffInput, EdgeBackoffWorld, back_off_from_edge}; use serde_json::Value; @@ -12,13 +13,6 @@ fn number(v: &Value) -> f64 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} struct World<'a> { input: &'a Value, out: &'a mut dyn Write, @@ -56,12 +50,12 @@ impl EdgeBackoffWorld for World<'_> { fn no_collision(&mut self, b: Aabb) -> io::Result { self.query(format!( "clear {:016x} {:016x} {:016x} {:016x} {:016x} {:016x}", - bits(b.min(Axis::X)), - bits(b.min(Axis::Y)), - bits(b.min(Axis::Z)), - bits(b.max(Axis::X)), - bits(b.max(Axis::Y)), - bits(b.max(Axis::Z)) + f64_bits(b.min(Axis::X)), + f64_bits(b.min(Axis::Y)), + f64_bits(b.min(Axis::Z)), + f64_bits(b.max(Axis::X)), + f64_bits(b.max(Axis::Y)), + f64_bits(b.max(Axis::Z)) ))?; let p = self.probes; self.probes += 1; @@ -105,9 +99,9 @@ pub fn main() -> Result<(), Box> { Ok(v) => writeln!( world.out, "movement {:016x} {:016x} {:016x}", - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) )?, Err(_) => writeln!(world.out, "error")?, }; diff --git a/crates/horizon-world/examples/probe/effect_attribute_modifiers_fixture.rs b/crates/horizon-world/examples/probe/effect_attribute_modifiers_fixture.rs index 1ff3e79b6..160dcdc28 100644 --- a/crates/horizon-world/examples/probe/effect_attribute_modifiers_fixture.rs +++ b/crates/horizon-world/examples/probe/effect_attribute_modifiers_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_hex; use horizon_world::{ attributes::{AttributeError, Definition, Instance, Modifier, Observer, Operation}, effect_attribute_modifiers::{self as effects, Definitions, Error, ModifierWorld, Template}, @@ -24,21 +25,11 @@ enum Stop { Callback, Duplicate, } -fn bits(v: f64) -> String { - format!( - "{:016x}", - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } - ) -} fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } fn desc(m: &Modifier) -> String { - format!("{}:{}:{}", m.id(), bits(m.amount()), m.operation() as u8) + format!("{}:{}:{}", m.id(), f64_hex(m.amount()), m.operation() as u8) } fn key_desc(k: Option<&Key>) -> String { k.map_or("null".into(), |k| k.id.to_string()) @@ -66,7 +57,7 @@ impl Shared { .iter() .map(|(k, v)| { let v = v.as_ref().map_or("null".into(), |t| { - format!("{}:{}:{}", t.id(), bits(t.amount()), t.operation() as u8) + format!("{}:{}:{}", t.id(), f64_hex(t.amount()), t.operation() as u8) }); format!("{}={v}", key_desc(k.as_ref())) }) @@ -126,9 +117,9 @@ impl Shared { fn state(&mut self, id: usize, a: &Instance) { self.logs.push(format!( "instance {id} {} {} {} | {} | {}", - bits(a.base_value()), + f64_hex(a.base_value()), a.is_dirty(), - bits(a.cached_value()), + f64_hex(a.cached_value()), self.refs(a.modifiers()), self.refs(a.permanent_modifiers()) )); @@ -153,7 +144,7 @@ impl Observer for Dirty<'_> { if self.shared.op["read"].as_bool().unwrap() { self.shared .logs - .push(format!("observed {}", bits(a.value()))); + .push(format!("observed {}", f64_hex(a.value()))); } Ok(()) } @@ -316,10 +307,10 @@ pub fn main() -> Result<(), Box> { } "value" => { let id = op["target"].as_u64().unwrap() as usize; - world - .shared - .logs - .push(format!("value {id} {}", bits(world.instances[id].value()))); + world.shared.logs.push(format!( + "value {id} {}", + f64_hex(world.instances[id].value()) + )); Ok(()) } _ => { diff --git a/crates/horizon-world/examples/probe/entity_attribute_fixture.rs b/crates/horizon-world/examples/probe/entity_attribute_fixture.rs index 2e94b8b1c..e5fe13b98 100644 --- a/crates/horizon-world/examples/probe/entity_attribute_fixture.rs +++ b/crates/horizon-world/examples/probe/entity_attribute_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_world::attributes::{ AttributeError, Modifier, Operation, entity::{Catalog, LookupError}, @@ -12,17 +13,10 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } -} fn lookup(out: &mut dyn Write, label: &str, result: Result) -> io::Result<()> { match result { Ok(v) => { - writeln!(out, "{label} {:016x}", bits(v))?; + writeln!(out, "{label} {:016x}", f64_bits(v))?; writeln!(out, "ok") } Err(e) => writeln!( @@ -114,9 +108,9 @@ pub fn main() -> Result<(), Box> { writeln!( out, "state {i} {:016x} {} {:016x} {} {} {} {}", - bits(a.base_value()), + f64_bits(a.base_value()), a.is_dirty(), - bits(a.cached_value()), + f64_bits(a.cached_value()), map.needs_update(id), map.needs_sync(id), a.modifiers().len(), diff --git a/crates/horizon-world/examples/probe/entity_collision_fixture.rs b/crates/horizon-world/examples/probe/entity_collision_fixture.rs index 815d9c249..d801e7d34 100644 --- a/crates/horizon-world/examples/probe/entity_collision_fixture.rs +++ b/crates/horizon-world/examples/probe/entity_collision_fixture.rs @@ -1,4 +1,5 @@ -use horizon_core::geometry::{Aabb, Axis, Vec3, VoxelShape}; +use crate::support::shapes::{box_values, emit}; +use horizon_core::geometry::{Aabb, Vec3}; use horizon_world::{ entity_collision::{CollisionCandidate, EntityCollisionWorld, entity_collision_shapes}, entity_obstruction::EntityIdentity, @@ -12,70 +13,6 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn values( - out: &mut impl Write, - label: &str, - values: impl IntoIterator, -) -> io::Result<()> { - write!(out, "{label}")?; - for v in values { - let bits = if v.is_nan() { - 0x7ff8_0000_0000_0000 - } else { - v.to_bits() - }; - write!(out, " {bits:016x}")?; - } - writeln!(out) -} -fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { - values( - out, - label, - [ - b.min(Axis::X), - b.min(Axis::Y), - b.min(Axis::Z), - b.max(Axis::X), - b.max(Axis::Y), - b.max(Axis::Z), - ], - ) -} -fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { - writeln!( - out, - "shape {} {} {}", - shape.is_empty(), - shape.boxes().len(), - shape.is_cube() - )?; - for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { - values(out, name, shape.coordinates(axis).iter().copied())?; - } - let axes = shape.cube_coordinate_axes(); - writeln!( - out, - "axes {}", - u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) - )?; - values( - out, - "extrema", - Axis::ALL - .map(|a| shape.min(a)) - .into_iter() - .chain(Axis::ALL.map(|a| shape.max(a))), - )?; - match shape.bounds() { - Some(b) => box_values(out, "bounds", b)?, - None => writeln!(out, "bounds none")?, - } - for b in shape.boxes() { - box_values(out, "box", *b)?; - } - Ok(()) -} fn bounds(v: &Value) -> Aabb { Aabb::new( Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])), diff --git a/crates/horizon-world/examples/probe/entity_fluid_fixture.rs b/crates/horizon-world/examples/probe/entity_fluid_fixture.rs index ad9b6ba2a..d897eea1c 100644 --- a/crates/horizon-world/examples/probe/entity_fluid_fixture.rs +++ b/crates/horizon-world/examples/probe/entity_fluid_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::{f64_bits, position}; use horizon_core::{ geometry::{Aabb, Vec3}, position::BlockPos, @@ -28,26 +29,17 @@ fn single(v: &Value) -> f32 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } -} fn show(v: Vec3) -> String { - format!("{:016x} {:016x} {:016x}", bits(v.x), bits(v.y), bits(v.z)) + format!( + "{:016x} {:016x} {:016x}", + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) + ) } fn pos(p: BlockPos) -> String { format!("{} {} {}", p.x, p.y, p.z) } -fn position(v: &Value) -> BlockPos { - BlockPos::new( - v[0].as_i64().unwrap() as i32, - v[1].as_i64().unwrap() as i32, - v[2].as_i64().unwrap() as i32, - ) -} #[derive(Clone, Copy, Default)] struct Tick { touch: bool, @@ -446,7 +438,7 @@ pub fn main() -> Result<(), Box> { w.out, "tracker {} {:016x} {}", t.fluid as u8, - bits(t.height), + f64_bits(t.height), t.eyes_inside )?; } @@ -455,7 +447,7 @@ pub fn main() -> Result<(), Box> { w.out, "current {} {:016x} {} {}", tag.0, - bits(c.height), + f64_bits(c.height), show(c.accumulated), c.count )?; @@ -465,7 +457,7 @@ pub fn main() -> Result<(), Box> { let height = interaction.fluid_height(&w, tag); let inside = interaction.is_in_fluid(&w, tag); let eyes = interaction.is_eye_in_fluid(&w, tag); - writeln!(w.out, "tag {t} {:016x} {inside} {eyes}", bits(height))?; + writeln!(w.out, "tag {t} {:016x} {inside} {eyes}", f64_bits(height))?; } writeln!(w.out, "final {}", show(w.velocity))?; writeln!(w.out, "queries {}", w.calls)?; @@ -476,7 +468,7 @@ pub fn main() -> Result<(), Box> { "tick {} {} {:016x}", tick.touch, tick.first, - bits(tick.fall) + f64_bits(tick.fall) )?; } } diff --git a/crates/horizon-world/examples/probe/entity_move_fixture.rs b/crates/horizon-world/examples/probe/entity_move_fixture.rs index fb31c8f79..c31e485a9 100644 --- a/crates/horizon-world/examples/probe/entity_move_fixture.rs +++ b/crates/horizon-world/examples/probe/entity_move_fixture.rs @@ -1,5 +1,7 @@ +use crate::support::common::f64_bits; +use crate::support::shapes::bounds; use horizon_core::{ - geometry::{Aabb, Axis, Vec3, VoxelShape, resolve_shape_movement}, + geometry::{Aabb, Vec3, VoxelShape, resolve_shape_movement}, position::BlockPos, }; use horizon_world::{ @@ -23,30 +25,12 @@ fn single(v: &Value) -> f32 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn vec(label: &str, v: Vec3) -> String { format!( "{label} {:016x} {:016x} {:016x}", - bits(v.x), - bits(v.y), - bits(v.z) - ) -} -fn bounds(label: &str, b: Aabb) -> String { - format!( - "{label} {:016x} {:016x} {:016x} {:016x} {:016x} {:016x}", - bits(b.min(Axis::X)), - bits(b.min(Axis::Y)), - bits(b.min(Axis::Z)), - bits(b.max(Axis::X)), - bits(b.max(Axis::Y)), - bits(b.max(Axis::Z)) + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) ) } fn pos(p: BlockPos) -> String { @@ -213,7 +197,7 @@ impl EntityMoveWorld for World<'_> { _: BlockStateId, p: BlockPos, ) -> io::Result<()> { - self.query(format!("fall {:016x} {ground} {}", bits(dy), pos(p)))?; + self.query(format!("fall {:016x} {ground} {}", f64_bits(dy), pos(p)))?; if self.flag("fall_mutates") { self.fall = 3.0; self.velocity = Vec3::new(17.0, 18.0, 19.0); @@ -399,7 +383,7 @@ pub fn main() -> Result<(), Box> { w.flags.minor, w.grounded, w.removed, - bits(w.fall) + f64_bits(w.fall) )?; writeln!(w.out, "history {}", w.history.records().len())?; for r in w.history.records() { diff --git a/crates/horizon-world/examples/probe/face_support_fixture.rs b/crates/horizon-world/examples/probe/face_support_fixture.rs index 60c228136..28e6fa81d 100644 --- a/crates/horizon-world/examples/probe/face_support_fixture.rs +++ b/crates/horizon-world/examples/probe/face_support_fixture.rs @@ -1,4 +1,5 @@ -use horizon_core::geometry::{Aabb, Axis, Direction, ShapeOp, Vec3, VoxelShape}; +use crate::support::shapes::emit; +use horizon_core::geometry::{Aabb, Direction, ShapeOp, Vec3, VoxelShape}; use horizon_world::block_support::SupportType; use serde_json::Value; use std::{ @@ -13,70 +14,6 @@ fn numbers(v: &Value) -> Vec { .map(|v| f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap())) .collect() } -fn values( - out: &mut impl Write, - label: &str, - values: impl IntoIterator, -) -> io::Result<()> { - write!(out, "{label}")?; - for v in values { - let bits = if v.is_nan() { - 0x7ff8_0000_0000_0000 - } else { - v.to_bits() - }; - write!(out, " {bits:016x}")?; - } - writeln!(out) -} -fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { - values( - out, - label, - [ - b.min(Axis::X), - b.min(Axis::Y), - b.min(Axis::Z), - b.max(Axis::X), - b.max(Axis::Y), - b.max(Axis::Z), - ], - ) -} -fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { - writeln!( - out, - "shape {} {} {}", - shape.is_empty(), - shape.boxes().len(), - shape.is_cube() - )?; - for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { - values(out, name, shape.coordinates(axis).iter().copied())?; - } - let axes = shape.cube_coordinate_axes(); - writeln!( - out, - "axes {}", - u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) - )?; - values( - out, - "extrema", - Axis::ALL - .map(|a| shape.min(a)) - .into_iter() - .chain(Axis::ALL.map(|a| shape.max(a))), - )?; - match shape.bounds() { - Some(b) => box_values(out, "bounds", b)?, - None => writeln!(out, "bounds none")?, - } - for b in shape.boxes() { - box_values(out, "box", *b)?; - } - Ok(()) -} pub fn main() -> Result<(), Box> { let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); diff --git a/crates/horizon-world/examples/probe/fall_damage_fixture.rs b/crates/horizon-world/examples/probe/fall_damage_fixture.rs index af77d212f..573b9c1e9 100644 --- a/crates/horizon-world/examples/probe/fall_damage_fixture.rs +++ b/crates/horizon-world/examples/probe/fall_damage_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::fall_damage::{FallDamageWorld, check_fall_damage}; use serde_json::Value; @@ -9,13 +10,6 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn support(v: &Value) -> Option { if v.is_null() { None @@ -66,7 +60,7 @@ impl FallDamageWorld for World<'_> { p.x, p.y, p.z, - bits(distance) + f64_bits(distance) ))?; if self.input["mutate"].as_bool().unwrap() { self.fall = 17.25; @@ -88,9 +82,9 @@ impl FallDamageWorld for World<'_> { fn hit_ground(&mut self, p: Vec3, s: u8) -> io::Result<()> { self.query(format!( "hit-ground {:016x} {:016x} {:016x} {}", - bits(p.x), - bits(p.y), - bits(p.z), + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z), if s == 1 { "queried" } else { "input" } )) } @@ -130,10 +124,10 @@ pub fn main() -> Result<(), Box> { writeln!( world.out, "final {:016x} {:016x} {:016x} {:016x}", - bits(world.fall), - bits(p.x), - bits(p.y), - bits(p.z) + f64_bits(world.fall), + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z) )?; if let Some(p) = world.support { writeln!(world.out, "support {} {} {}", p.x, p.y, p.z)?; diff --git a/crates/horizon-world/examples/probe/feature_catalog_fixture.rs b/crates/horizon-world/examples/probe/feature_catalog_fixture.rs index d140a64e9..bbc69ffd3 100644 --- a/crates/horizon-world/examples/probe/feature_catalog_fixture.rs +++ b/crates/horizon-world/examples/probe/feature_catalog_fixture.rs @@ -1,4 +1,5 @@ //! Feature world transport retaining ordered mutations and partial failures. +use crate::support::common::tag; use horizon_core::random::{LegacyRandom, RandomSource, WorldgenRandom, XoroshiroRandom}; use horizon_world::{ DATA_VERSION, @@ -178,17 +179,6 @@ 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"), - } -} pub fn main() -> Result<(), Box> { let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); diff --git a/crates/horizon-world/examples/probe/feature_region_fixture.rs b/crates/horizon-world/examples/probe/feature_region_fixture.rs index 755c5306d..6a244998d 100644 --- a/crates/horizon-world/examples/probe/feature_region_fixture.rs +++ b/crates/horizon-world/examples/probe/feature_region_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::tag; use horizon_core::random::{LegacyRandom, RandomSource, WorldgenRandom, XoroshiroRandom}; use horizon_world::worldgen::{ anchor::WorldGenerationContext, @@ -66,17 +67,6 @@ impl TerrainBlockStates for Properties<'_> { fn n(v: &Value) -> i32 { v.as_i64().unwrap() as i32 } -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(i) => Tag::Int(i.as_i64().unwrap() as i32), - Value::Object(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - _ => panic!("unsupported registry fixture value"), - } -} fn fixture( f: &Value, registry: &BlockRegistry, diff --git a/crates/horizon-world/examples/probe/fill_layer_fixture.rs b/crates/horizon-world/examples/probe/fill_layer_fixture.rs index a0a35dd93..e107a6383 100644 --- a/crates/horizon-world/examples/probe/fill_layer_fixture.rs +++ b/crates/horizon-world/examples/probe/fill_layer_fixture.rs @@ -1,4 +1,5 @@ //! Feature world transport retaining ordered mutations and partial failures. +use crate::support::common::tag; use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; use horizon_world::{ DATA_VERSION, @@ -134,17 +135,6 @@ 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"), - } -} pub fn main() -> Result<(), Box> { let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); diff --git a/crates/horizon-world/examples/probe/fluid_fixture.rs b/crates/horizon-world/examples/probe/fluid_fixture.rs index 1e16480a9..1c5ed4a85 100644 --- a/crates/horizon-world/examples/probe/fluid_fixture.rs +++ b/crates/horizon-world/examples/probe/fluid_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::tag; use horizon_world::{ DATA_VERSION, fluid::{FluidBlockBindings, FluidHeightWorld, FluidKind, FluidState, FluidStateTable}, @@ -40,17 +41,6 @@ impl FluidHeightWorld for World<'_, W> { Ok(self.sturdy) } } -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - Value::Object(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - _ => panic!("invalid registry metadata"), - } -} pub fn main() -> Result<(), Box> { let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); diff --git a/crates/horizon-world/examples/probe/food_fixture.rs b/crates/horizon-world/examples/probe/food_fixture.rs index 2852eaf3e..c12106dfb 100644 --- a/crates/horizon-world/examples/probe/food_fixture.rs +++ b/crates/horizon-world/examples/probe/food_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::food::{Difficulty, FoodData, FoodWorld}; use serde_json::Value; use std::{ @@ -8,13 +9,6 @@ use std::{ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn state(v: &Value) -> FoodData { FoodData { food: v["food"].as_i64().unwrap() as i32, @@ -72,7 +66,7 @@ impl FoodWorld for World<'_> { Ok(self.world()["hurt"].as_bool().unwrap()) } fn heal(&mut self, f: &mut FoodData, v: f32) -> io::Result<()> { - self.query(f, &format!("heal {:08x}", bits(v))) + self.query(f, &format!("heal {:08x}", f32_bits(v))) } fn health(&mut self, f: &mut FoodData) -> io::Result { self.query(f, "health")?; @@ -81,7 +75,7 @@ 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))) } } pub fn main() -> Result<(), Box> { @@ -123,8 +117,8 @@ pub fn main() -> Result<(), Box> { w.out, "state {} {:08x} {:08x} {} {} {}", food.food, - bits(food.saturation), - bits(food.exhaustion), + f32_bits(food.saturation), + f32_bits(food.exhaustion), food.timer, food.has_enough_food(), food.needs_food() @@ -135,8 +129,8 @@ pub fn main() -> Result<(), Box> { w.out, "final {} {:08x} {:08x} {}", food.food, - bits(food.saturation), - bits(food.exhaustion), + f32_bits(food.saturation), + f32_bits(food.exhaustion), food.timer )?; writeln!(w.out, "queries {}", w.calls)?; diff --git a/crates/horizon-world/examples/probe/food_storage_fixture.rs b/crates/horizon-world/examples/probe/food_storage_fixture.rs index bf7759a93..13e9a52dc 100644 --- a/crates/horizon-world/examples/probe/food_storage_fixture.rs +++ b/crates/horizon-world/examples/probe/food_storage_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::{ food::FoodData, nbt::{Compound, Tag}, @@ -17,13 +18,6 @@ const KEYS: [&str; 4] = [ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn tag(v: &Value) -> Option { let value = &v["value"]; Some(match v["type"].as_i64().unwrap() { @@ -82,8 +76,8 @@ pub fn main() -> Result<(), Box> { "state {} {} {:08x} {:08x}", food.food, food.timer, - bits(food.saturation), - bits(food.exhaustion) + f32_bits(food.saturation), + f32_bits(food.exhaustion) )?; let mut saved = Compound::new(); saved.insert("unrelated".into(), Tag::Int(42)); @@ -96,7 +90,7 @@ pub fn main() -> Result<(), Box> { for key in KEYS { match saved[&key.into()] { Tag::Int(v) => writeln!(out, "tag 3 {v}")?, - Tag::Float(v) => writeln!(out, "tag 5 {:08x}", bits(f32::from_bits(v)))?, + Tag::Float(v) => writeln!(out, "tag 5 {:08x}", f32_bits(f32::from_bits(v)))?, _ => panic!("saved type"), } } @@ -106,8 +100,8 @@ pub fn main() -> Result<(), Box> { "roundtrip {} {} {:08x} {:08x}", food.food, food.timer, - bits(food.saturation), - bits(food.exhaustion) + f32_bits(food.saturation), + f32_bits(food.exhaustion) )?; } Ok(()) diff --git a/crates/horizon-world/examples/probe/ground_state_fixture.rs b/crates/horizon-world/examples/probe/ground_state_fixture.rs index 398757854..47611587f 100644 --- a/crates/horizon-world/examples/probe/ground_state_fixture.rs +++ b/crates/horizon-world/examples/probe/ground_state_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{ geometry::{Aabb, Axis, Vec3}, position::BlockPos, @@ -15,13 +16,6 @@ fn number(v: &Value) -> f64 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn position(v: &Value) -> Option { if v.is_null() { None @@ -62,12 +56,12 @@ pub fn main() -> Result<(), Box> { writeln!( out, "find {:016x} {:016x} {:016x} {:016x} {:016x} {:016x}", - bits(b.min(Axis::X)), - bits(b.min(Axis::Y)), - bits(b.min(Axis::Z)), - bits(b.max(Axis::X)), - bits(b.max(Axis::Y)), - bits(b.max(Axis::Z)) + f64_bits(b.min(Axis::X)), + f64_bits(b.min(Axis::Y)), + f64_bits(b.min(Axis::Z)), + f64_bits(b.max(Axis::X)), + f64_bits(b.max(Axis::Y)), + f64_bits(b.max(Axis::Z)) )?; let call = calls; calls += 1; diff --git a/crates/horizon-world/examples/probe/interaction_shape_fixture.rs b/crates/horizon-world/examples/probe/interaction_shape_fixture.rs index 6e10326f0..c1ca5700b 100644 --- a/crates/horizon-world/examples/probe/interaction_shape_fixture.rs +++ b/crates/horizon-world/examples/probe/interaction_shape_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{ geometry::{Aabb, Axis, ShapeOp, Vec3, VoxelShape}, position::BlockPos, @@ -20,13 +21,6 @@ fn number(v: &Value) -> f64 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn shape(v: &Value) -> Result> { let mut result = VoxelShape::empty(); for b in v.as_array().unwrap() { @@ -131,12 +125,12 @@ pub fn main() -> Result<(), Box> { writeln!( out, "box {:016x} {:016x} {:016x} {:016x} {:016x} {:016x}", - bits(b.min(Axis::X)), - bits(b.min(Axis::Y)), - bits(b.min(Axis::Z)), - bits(b.max(Axis::X)), - bits(b.max(Axis::Y)), - bits(b.max(Axis::Z)) + f64_bits(b.min(Axis::X)), + f64_bits(b.min(Axis::Y)), + f64_bits(b.min(Axis::Z)), + f64_bits(b.max(Axis::X)), + f64_bits(b.max(Axis::Y)), + f64_bits(b.max(Axis::Z)) )?; } } @@ -160,9 +154,9 @@ pub fn main() -> Result<(), Box> { Some(h) => writeln!( out, "hit {:016x} {:016x} {:016x} {} {} {} {} {}", - bits(h.location.x), - bits(h.location.y), - bits(h.location.z), + f64_bits(h.location.x), + f64_bits(h.location.y), + f64_bits(h.location.z), format!("{:?}", h.direction).to_lowercase(), h.block.x, h.block.y, diff --git a/crates/horizon-world/examples/probe/item_blocking_fixture.rs b/crates/horizon-world/examples/probe/item_blocking_fixture.rs index 7bfdcdc99..e3f622a6d 100644 --- a/crates/horizon-world/examples/probe/item_blocking_fixture.rs +++ b/crates/horizon-world/examples/probe/item_blocking_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_core::geometry::Vec3; use horizon_world::{ blocking_rules::{BlockingRules, DamageReduction, ItemDamageFunction, TypeMatchWorld}, @@ -19,13 +20,6 @@ fn number(v: &Value) -> f64 { fn vec(v: &Value) -> Option { (!v.is_null()).then(|| Vec3::new(number(&v[0]), number(&v[1]), number(&v[2]))) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} struct Component { present: bool, bypass: Option, @@ -154,7 +148,7 @@ 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))) } } pub fn main() -> Result<(), Box> { @@ -207,7 +201,7 @@ pub fn main() -> Result<(), Box> { changed: false, }; match item_blocking::apply(&mut w, single(&f["damage"])) { - Ok(v) => writeln!(w.out, "blocked {:08x}\nresult ok", bits(v))?, + Ok(v) => writeln!(w.out, "blocked {:08x}\nresult ok", f32_bits(v))?, Err(_) => writeln!(w.out, "result error")?, }; writeln!(w.out, "queries {} {}", w.calls, w.changed)?; diff --git a/crates/horizon-world/examples/probe/item_particles_fixture.rs b/crates/horizon-world/examples/probe/item_particles_fixture.rs index 6fe11ea7d..3b7375e17 100644 --- a/crates/horizon-world/examples/probe/item_particles_fixture.rs +++ b/crates/horizon-world/examples/probe/item_particles_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{ geometry::Vec3, random::{LegacyRandom, RandomSource, XoroshiroRandom}, @@ -22,13 +23,6 @@ fn n(v: &Value, k: &str) -> i32 { fn fl(v: &Value, k: &str) -> f32 { f32::from_bits(v[k].as_u64().unwrap() as u32) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn opt(v: Option<&i32>) -> String { v.map_or("none".into(), i32::to_string) } @@ -141,12 +135,12 @@ impl ItemParticleWorld for World<'_, R> { "particle {level} {} {} {damage} {same} {} {} {} {} {} {}", t.item(), t.count(), - bits(p.x), - bits(p.y), - bits(p.z), - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z), + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) )) } } diff --git a/crates/horizon-world/examples/probe/item_use_fixture.rs b/crates/horizon-world/examples/probe/item_use_fixture.rs index 28bf66743..8d88aae7a 100644 --- a/crates/horizon-world/examples/probe/item_use_fixture.rs +++ b/crates/horizon-world/examples/probe/item_use_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::{ blocking_rules::{BlockingRules, ItemDamageFunction}, item_use::{self, ItemUseWorld}, @@ -11,13 +12,6 @@ use std::{ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} struct World<'a> { f: &'a Value, out: &'a mut dyn Write, @@ -127,7 +121,7 @@ pub fn main() -> Result<(), Box> { item_use::ticks_using_item(&mut w).and_then(|v| writeln!(w.out, "ticks {v}")) } "partial" => item_use::ticks_using_item_partial(&mut w, single(&f["partial"])) - .and_then(|v| writeln!(w.out, "float {:08x}", bits(v))), + .and_then(|v| writeln!(w.out, "float {:08x}", f32_bits(v))), _ => panic!("mode"), }; writeln!( diff --git a/crates/horizon-world/examples/probe/live_attribute_updates_fixture.rs b/crates/horizon-world/examples/probe/live_attribute_updates_fixture.rs index 03b271ef1..b053c2c82 100644 --- a/crates/horizon-world/examples/probe/live_attribute_updates_fixture.rs +++ b/crates/horizon-world/examples/probe/live_attribute_updates_fixture.rs @@ -252,9 +252,9 @@ mod integration { "instance {} {} {} {} {} | {} | {}", h.index(), key.name(), - bits(a.base_value()), + f64_hex(a.base_value()), a.is_dirty(), - bits(a.cached_value()), + f64_hex(a.cached_value()), refs(a.modifiers(), &mut self.pools[i]), refs(a.permanent_modifiers(), &mut self.pools[i]) ) @@ -541,8 +541,8 @@ mod integration { None, ); let result = match op["mode"].as_str().unwrap() { - "value" => w.attribute_value(key).map(bits), - "base" => live_updates::value(&mut w, key, ValueKind::Base).map(bits), + "value" => w.attribute_value(key).map(f64_hex), + "base" => live_updates::value(&mut w, key, ValueKind::Base).map(f64_hex), "set-health" => w .dispatch_set_health(single(&op["value"])) .map(|()| "ok".into()), diff --git a/crates/horizon-world/examples/probe/live_attributes_fixture.rs b/crates/horizon-world/examples/probe/live_attributes_fixture.rs index 2bbff5bdd..1c4a868f5 100644 --- a/crates/horizon-world/examples/probe/live_attributes_fixture.rs +++ b/crates/horizon-world/examples/probe/live_attributes_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_hex; use horizon_world::{ attribute_map::ValueKind, attributes::{ @@ -17,16 +18,6 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> String { - format!( - "{:016x}", - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } - ) -} fn error(e: Error) -> &'static str { match e { Error::NullAttribute | Error::MissingInstanceModifier => "null", @@ -52,7 +43,7 @@ fn refs(mods: &[Modifier], pool: &mut Vec) -> String { format!( "{id}:{}:{}:{}", m.id(), - bits(m.amount()), + f64_hex(m.amount()), m.operation() as u8 ) }) @@ -104,11 +95,11 @@ pub fn main() -> Result<(), Box> { )?; let mode = op["mode"].as_str().unwrap(); let result: Result = match mode { - "value" => attrs.value(key, ValueKind::Computed).map(bits), - "base" => attrs.value(key, ValueKind::Base).map(bits), + "value" => attrs.value(key, ValueKind::Computed).map(f64_hex), + "base" => attrs.value(key, ValueKind::Base).map(f64_hex), "has" => attrs.has_attribute(key).map(|v| v.to_string()), "has_modifier" => attrs.has_modifier(key, m.id()).map(|v| v.to_string()), - "modifier" => attrs.modifier_value(key, m.id()).map(bits), + "modifier" => attrs.modifier_value(key, m.id()).map(f64_hex), "ensure" => attrs.get_instance(key).map(|h| handle(h.as_ref())), "reset" => attrs.reset_base(key).map(|v| v.to_string()), "ack_update" => { @@ -208,9 +199,9 @@ pub fn main() -> Result<(), Box> { "instance {} {} {} {} {} | {} | {}", h.index(), key.name(), - bits(a.base_value()), + f64_hex(a.base_value()), a.is_dirty(), - bits(a.cached_value()), + f64_hex(a.cached_value()), refs(a.modifiers(), &mut pool), refs(a.permanent_modifiers(), &mut pool) )?; diff --git a/crates/horizon-world/examples/probe/living_air_fixture.rs b/crates/horizon-world/examples/probe/living_air_fixture.rs index bf77ce86f..882c5a8f3 100644 --- a/crates/horizon-world/examples/probe/living_air_fixture.rs +++ b/crates/horizon-world/examples/probe/living_air_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::living_air::*; use serde_json::Value; @@ -15,18 +16,16 @@ fn single(v: &Value) -> f32 { fn vec(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn fbits(v: f32) -> u32 { if v.is_nan() { 0x7fc00000 } else { v.to_bits() } } fn vector(v: Vec3) -> String { - format!("{:016x} {:016x} {:016x}", bits(v.x), bits(v.y), bits(v.z)) + format!( + "{:016x} {:016x} {:016x}", + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) + ) } struct World<'a> { f: &'a Value, @@ -239,7 +238,12 @@ pub fn main() -> Result<(), Box> { "result {}", if result.is_ok() { "ok" } else { "error" } )?; - writeln!(w.out, "final {} {:016x}", vector(w.velocity), bits(w.fall))?; + writeln!( + w.out, + "final {} {:016x}", + vector(w.velocity), + f64_bits(w.fall) + )?; writeln!(w.out, "queries {}", w.calls)?; } Ok(()) diff --git a/crates/horizon-world/examples/probe/living_damage_fixture.rs b/crates/horizon-world/examples/probe/living_damage_fixture.rs index 4e3c06887..d8097bde9 100644 --- a/crates/horizon-world/examples/probe/living_damage_fixture.rs +++ b/crates/horizon-world/examples/probe/living_damage_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::{ living_damage::{self, DamageStat, DamageWorld}, living_health::{self, HealthWorld}, @@ -14,13 +15,6 @@ fn single(v: &Value) -> f32 { fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn stat(s: DamageStat) -> &'static str { match s { DamageStat::Absorbed => "absorbed", @@ -69,11 +63,11 @@ impl DamageWorld for World<'_> { Ok(self.state()["invulnerable"].as_bool().unwrap()) } fn after_armor(&mut self, v: f32) -> io::Result { - self.query(&format!("armor {:08x}", bits(v)))?; + self.query(&format!("armor {:08x}", f32_bits(v)))?; Ok(single(&self.state()["armor"])) } fn after_magic(&mut self, v: f32) -> io::Result { - self.query(&format!("magic {:08x}", bits(v)))?; + self.query(&format!("magic {:08x}", f32_bits(v)))?; Ok(single(&self.state()["magic"])) } fn absorption(&mut self) -> io::Result { @@ -98,13 +92,13 @@ impl DamageWorld for World<'_> { Ok(single(&self.state()["food_exhaustion"])) } fn cause_food_exhaustion(&mut self, v: f32) -> io::Result<()> { - self.query(&format!("exhaust {:08x}", bits(v)))?; + self.query(&format!("exhaust {:08x}", f32_bits(v)))?; self.exhaustion += v; Ok(()) } fn record_damage(&mut self, v: f32) -> io::Result<()> { self.query("tracker")?; - self.query(&format!("record {:08x}", bits(v)))?; + self.query(&format!("record {:08x}", f32_bits(v)))?; self.recorded = v; Ok(()) } @@ -113,7 +107,7 @@ impl DamageWorld for World<'_> { Ok(self.health) } fn set_health(&mut self, v: f32) -> io::Result<()> { - self.query(&format!("set-health {:08x}", bits(v)))?; + self.query(&format!("set-health {:08x}", f32_bits(v)))?; self.health = v; Ok(()) } @@ -140,7 +134,7 @@ impl HealthWorld for World<'_> { DamageWorld::set_health(self, v) } fn store_absorption(&mut self, v: f32) -> io::Result<()> { - self.query(&format!("set-absorption {:08x}", bits(v)))?; + self.query(&format!("set-absorption {:08x}", f32_bits(v)))?; self.absorption = v; Ok(()) } @@ -181,10 +175,10 @@ pub fn main() -> Result<(), Box> { writeln!( w.out, "final {:08x} {:08x} {:08x} {:08x}", - bits(w.health), - bits(w.absorption), - bits(w.exhaustion), - bits(w.recorded) + f32_bits(w.health), + f32_bits(w.absorption), + f32_bits(w.exhaustion), + f32_bits(w.recorded) )?; writeln!(w.out, "queries {}", w.calls)?; } diff --git a/crates/horizon-world/examples/probe/living_fall_fixture.rs b/crates/horizon-world/examples/probe/living_fall_fixture.rs index 84d7fb9a3..2d65929ff 100644 --- a/crates/horizon-world/examples/probe/living_fall_fixture.rs +++ b/crates/horizon-world/examples/probe/living_fall_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::geometry::Vec3; use horizon_world::living_fall::{ ImpulseContext, LivingFallWorld, calculate_fall_damage, cause_living_fall_damage, @@ -14,13 +15,6 @@ fn number(v: &Value) -> f64 { fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn vector(v: &Value) -> Option { if v.is_null() { None @@ -60,9 +54,9 @@ impl World<'_> { writeln!( self.out, "impact {:016x} {:016x} {:016x}", - bits(p.x), - bits(p.y), - bits(p.z) + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z) ) } else { writeln!(self.out, "impact none") @@ -100,7 +94,7 @@ impl LivingFallWorld for World<'_> { fn propagate_fall_to_passengers(&mut self, d: f64, m: f32) -> io::Result<()> { self.query(format!( "passengers {:016x} {:08x}", - bits(d), + f64_bits(d), if m.is_nan() { 0x7fc00000 } else { m.to_bits() } ))?; if self.f["mutate"].as_bool().unwrap() { diff --git a/crates/horizon-world/examples/probe/living_fluid_fixture.rs b/crates/horizon-world/examples/probe/living_fluid_fixture.rs index 0bada6334..bd3704965 100644 --- a/crates/horizon-world/examples/probe/living_fluid_fixture.rs +++ b/crates/horizon-world/examples/probe/living_fluid_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::living_air::*; use horizon_world::living_fluid::*; @@ -16,18 +17,16 @@ fn single(v: &Value) -> f32 { fn vec(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn fbits(v: f32) -> u32 { if v.is_nan() { 0x7fc00000 } else { v.to_bits() } } fn vector(v: Vec3) -> String { - format!("{:016x} {:016x} {:016x}", bits(v.x), bits(v.y), bits(v.z)) + format!( + "{:016x} {:016x} {:016x}", + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) + ) } struct World<'a> { f: &'a Value, @@ -320,7 +319,12 @@ pub fn main() -> Result<(), Box> { "result {}", if result.is_ok() { "ok" } else { "error" } )?; - writeln!(w.out, "final {} {:016x}", vector(w.velocity), bits(w.fall))?; + writeln!( + w.out, + "final {} {:016x}", + vector(w.velocity), + f64_bits(w.fall) + )?; writeln!(w.out, "queries {}", w.calls)?; } Ok(()) diff --git a/crates/horizon-world/examples/probe/living_health_fixture.rs b/crates/horizon-world/examples/probe/living_health_fixture.rs index 2b2f98129..53d00b076 100644 --- a/crates/horizon-world/examples/probe/living_health_fixture.rs +++ b/crates/horizon-world/examples/probe/living_health_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::living_health::{self, HealthWorld, SyncedFloat}; use serde_json::Value; use std::{ @@ -11,13 +12,6 @@ fn single(v: &Value) -> f32 { fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} struct Context<'a> { f: &'a Value, out: &'a mut dyn Write, @@ -70,7 +64,7 @@ impl HealthWorld for World<'_> { self.stores[data].set(v, false, |_| self.ctx.query("updated")) } fn store_absorption(&mut self, v: f32) -> io::Result<()> { - self.ctx.query(&format!("absorption {:08x}", bits(v)))?; + self.ctx.query(&format!("absorption {:08x}", f32_bits(v)))?; self.absorption = v; Ok(()) } @@ -78,7 +72,7 @@ impl HealthWorld for World<'_> { self.ctx.world()["dead"].as_bool().unwrap() } fn dispatch_set_health(&mut self, v: f32) -> io::Result<()> { - self.ctx.query(&format!("set {:08x}", bits(v)))?; + self.ctx.query(&format!("set {:08x}", f32_bits(v)))?; living_health::set_health(self, v) } } @@ -123,7 +117,7 @@ pub fn main() -> Result<(), Box> { "packed {}", w.stores[w.ctx.active] .take_dirty() - .map(|v| format!("{:08x}", bits(v))) + .map(|v| format!("{:08x}", f32_bits(v))) .unwrap_or_else(|| "none".into()) ) } @@ -138,7 +132,7 @@ pub fn main() -> Result<(), Box> { writeln!( w.ctx.out, "data {i} {:08x} {} {} {}", - bits(s.value()), + f32_bits(s.value()), s.is_dirty(), s.item_dirty(), s.is_default() @@ -149,7 +143,7 @@ pub fn main() -> Result<(), Box> { w.ctx.out, "state {} {:08x} {dead} {}", w.ctx.active, - bits(w.absorption), + f32_bits(w.absorption), w.ctx.calls )?; } diff --git a/crates/horizon-world/examples/probe/living_hurt_fixture.rs b/crates/horizon-world/examples/probe/living_hurt_fixture.rs index 4c9e46230..b5ab3e890 100644 --- a/crates/horizon-world/examples/probe/living_hurt_fixture.rs +++ b/crates/horizon-world/examples/probe/living_hurt_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::living_hurt::{HurtState, HurtTag, HurtWorld, hurt_server}; use serde_json::Value; use std::{ @@ -8,19 +9,12 @@ use std::{ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn state(s: &HurtState<()>) -> String { format!( "{} {} {:08x} {} {} {} {}", s.no_action_time, s.cooldown, - bits(s.last_hurt), + f32_bits(s.last_hurt), s.hurt_duration, s.hurt_time, s.last_source.is_some(), @@ -126,7 +120,7 @@ impl HurtWorld for Env<'_> { Ok(self.flag("component")) } fn apply_blocking(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result { - self.event(&format!("blocking {:08x}", bits(v)))?; + self.event(&format!("blocking {:08x}", f32_bits(v)))?; Ok(single(&self.op["blocked"])) } fn helmet_empty(&mut self, _: &mut HurtState<()>) -> io::Result { @@ -134,10 +128,10 @@ impl HurtWorld for Env<'_> { Ok(!self.flag("helmet")) } fn hurt_helmet(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result<()> { - self.event(&format!("hurt-helmet {:08x}", bits(v))) + self.event(&format!("hurt-helmet {:08x}", f32_bits(v))) } fn actually_hurt(&mut self, s: &mut HurtState<()>, v: f32) -> io::Result<()> { - self.event(&format!("hurt {:08x} {}", bits(v), state(s)))?; + self.event(&format!("hurt {:08x} {}", f32_bits(v), state(s)))?; self.hit = true; self.recorded = v; if self.flag("mutate_hit") { @@ -155,7 +149,7 @@ impl HurtWorld for Env<'_> { Ok(()) } fn knockback(&mut self, _: &mut HurtState<()>, v: f32, b: bool) -> io::Result<()> { - self.event(&format!("knockback {:08x} {b}", bits(v))) + self.event(&format!("knockback {:08x} {b}", f32_bits(v))) } fn death_protection(&mut self, _: &mut HurtState<()>) -> io::Result { self.event("tag bypasses_invulnerability")?; @@ -179,7 +173,7 @@ impl HurtWorld for Env<'_> { fn effects_on_hurt(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result<()> { self.event("effects")?; for i in 0..self.op["effects"].as_u64().unwrap() { - self.event(&format!("effect {i} {:08x}", bits(v)))?; + self.event(&format!("effect {i} {:08x}", f32_bits(v)))?; } Ok(()) } @@ -239,7 +233,7 @@ pub fn main() -> Result<(), Box> { e.out, "state {} {:08x} {} {}", state(&s), - bits(recorded), + f32_bits(recorded), e.hit, e.calls )?; diff --git a/crates/horizon-world/examples/probe/living_landing_fixture.rs b/crates/horizon-world/examples/probe/living_landing_fixture.rs index 87b438978..3c3e333d7 100644 --- a/crates/horizon-world/examples/probe/living_landing_fixture.rs +++ b/crates/horizon-world/examples/probe/living_landing_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::fall_damage::FallDamageWorld; use horizon_world::living_landing::{LivingLandingWorld, check_living_fall_damage}; @@ -10,13 +11,6 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn support(v: &Value) -> Option { if v.is_null() { None @@ -69,7 +63,7 @@ impl FallDamageWorld for World<'_> { p.x, p.y, p.z, - bits(distance) + f64_bits(distance) ))?; if self.input["mutate"].as_bool().unwrap() { self.fall = 17.25; @@ -91,9 +85,9 @@ impl FallDamageWorld for World<'_> { fn hit_ground(&mut self, p: Vec3, s: u8) -> io::Result<()> { self.query(format!( "hit-ground {:016x} {:016x} {:016x} {}", - bits(p.x), - bits(p.y), - bits(p.z), + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z), if s == 1 { "queried" } else { "input" } )) } @@ -142,11 +136,11 @@ impl LivingLandingWorld for World<'_> { assert_eq!(s, 0); self.query(format!( "particles {:016x} {:016x} {:016x} {} {:016x}", - bits(p.x), - bits(p.y), - bits(p.z), + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z), count, - bits(speed) + f64_bits(speed) ))?; if self.input["particle_mutate"].as_bool().unwrap() { self.fall = number(&self.input["after_fall"]); @@ -194,10 +188,10 @@ pub fn main() -> Result<(), Box> { writeln!( world.out, "final {:016x} {:016x} {:016x} {:016x}", - bits(world.fall), - bits(p.x), - bits(p.y), - bits(p.z) + f64_bits(world.fall), + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z) )?; if let Some(p) = world.support { writeln!(world.out, "support {} {} {}", p.x, p.y, p.z)?; diff --git a/crates/horizon-world/examples/probe/living_motion_fixture.rs b/crates/horizon-world/examples/probe/living_motion_fixture.rs index 174527053..96c0792ac 100644 --- a/crates/horizon-world/examples/probe/living_motion_fixture.rs +++ b/crates/horizon-world/examples/probe/living_motion_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::geometry::Vec3; use horizon_world::living_motion::*; use serde_json::Value; @@ -15,18 +16,16 @@ fn single(v: &Value) -> f32 { fn vec(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn fbits(v: f32) -> u32 { if v.is_nan() { 0x7fc00000 } else { v.to_bits() } } fn vector(v: Vec3) -> String { - format!("{:016x} {:016x} {:016x}", bits(v.x), bits(v.y), bits(v.z)) + format!( + "{:016x} {:016x} {:016x}", + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) + ) } struct World<'a> { f: &'a Value, @@ -138,10 +137,11 @@ pub fn main() -> Result<(), Box> { "power" => jump_power(&mut w, single(&f["scale"])) .and_then(|v| writeln!(w.out, "float {:08x}", fbits(v))), "jump" => jump_from_ground(&mut w), - "gravity" => gravity(&mut w).and_then(|v| writeln!(w.out, "double {:016x}", bits(v))), - "effective" => { - effective_gravity(&mut w).and_then(|v| writeln!(w.out, "double {:016x}", bits(v))) + "gravity" => { + gravity(&mut w).and_then(|v| writeln!(w.out, "double {:016x}", f64_bits(v))) } + "effective" => effective_gravity(&mut w) + .and_then(|v| writeln!(w.out, "double {:016x}", f64_bits(v))), "apply" => apply_gravity(&mut w), "up" => swim_vertical(&mut w, true), "down" => swim_vertical(&mut w, false), diff --git a/crates/horizon-world/examples/probe/main.rs b/crates/horizon-world/examples/probe/main.rs index 470fabd2b..d9a0289b8 100644 --- a/crates/horizon-world/examples/probe/main.rs +++ b/crates/horizon-world/examples/probe/main.rs @@ -5,8 +5,10 @@ use std::process::{ExitCode, Termination}; /// Code shared by several probes. mod support { + pub mod common; pub mod decoration_storage; pub mod placement_queries; + pub mod shapes; } mod active_effect_tick_fixture; diff --git a/crates/horizon-world/examples/probe/material_stage_fixture.rs b/crates/horizon-world/examples/probe/material_stage_fixture.rs index 9ae27db9d..31a563f7c 100644 --- a/crates/horizon-world/examples/probe/material_stage_fixture.rs +++ b/crates/horizon-world/examples/probe/material_stage_fixture.rs @@ -1,4 +1,5 @@ //! Original transport for complete surface-stage chunk comparison. +use crate::support::common::tag; use horizon_core::{ biome::{BiomeZoom, obfuscate_seed}, carving::CarvingMask, @@ -78,17 +79,6 @@ impl TerrainBlockStates for Properties<'_> { self.0[id.0 as usize] } } -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - Value::Object(o) => { - Tag::Compound(o.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - _ => panic!("invalid registry metadata"), - } -} fn n(v: &Value) -> i32 { v.as_i64().unwrap() as i32 } diff --git a/crates/horizon-world/examples/probe/movement_emission_fixture.rs b/crates/horizon-world/examples/probe/movement_emission_fixture.rs index b49ac7b33..70ef1b32b 100644 --- a/crates/horizon-world/examples/probe/movement_emission_fixture.rs +++ b/crates/horizon-world/examples/probe/movement_emission_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::{f64_bits, position}; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::movement_emission::*; use serde_json::Value; @@ -15,23 +16,9 @@ fn single(v: &Value) -> f32 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn position(v: &Value) -> BlockPos { - BlockPos::new( - v[0].as_i64().unwrap() as i32, - v[1].as_i64().unwrap() as i32, - v[2].as_i64().unwrap() as i32, - ) -} fn pos(p: BlockPos) -> String { format!("{} {} {}", p.x, p.y, p.z) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn fbits(v: f32) -> u32 { if v.is_nan() { 0x7fc00000 } else { v.to_bits() } } @@ -137,9 +124,9 @@ impl MovementEmissionWorld for World<'_> { let p = vector(&self.f["position"]); self.query(format!( "step {s} {:016x} {:016x} {:016x}", - bits(p.x), - bits(p.y), - bits(p.z) + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z) ))?; self.mutate(); Ok(()) diff --git a/crates/horizon-world/examples/probe/movement_registry_fixture.rs b/crates/horizon-world/examples/probe/movement_registry_fixture.rs index 4ebe76a39..28a934ee5 100644 --- a/crates/horizon-world/examples/probe/movement_registry_fixture.rs +++ b/crates/horizon-world/examples/probe/movement_registry_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::position; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::movement_support::{self as support, MovementLocation}; use horizon_world::{ @@ -21,13 +22,6 @@ fn number(v: &Value) -> f64 { fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn position(v: &Value) -> BlockPos { - BlockPos::new( - v[0].as_i64().unwrap() as i32, - v[1].as_i64().unwrap() as i32, - v[2].as_i64().unwrap() as i32, - ) -} struct World<'a> { input: &'a Value, out: &'a mut dyn Write, diff --git a/crates/horizon-world/examples/probe/movement_support_fixture.rs b/crates/horizon-world/examples/probe/movement_support_fixture.rs index df6ffb046..1206aa0dc 100644 --- a/crates/horizon-world/examples/probe/movement_support_fixture.rs +++ b/crates/horizon-world/examples/probe/movement_support_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::position; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::movement_support::{self as support, MovementBlockWorld, MovementLocation}; use serde_json::Value; @@ -12,13 +13,6 @@ fn number(v: &Value) -> f64 { fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn position(v: &Value) -> BlockPos { - BlockPos::new( - v[0].as_i64().unwrap() as i32, - v[1].as_i64().unwrap() as i32, - v[2].as_i64().unwrap() as i32, - ) -} struct World<'a> { input: &'a Value, out: &'a mut dyn Write, diff --git a/crates/horizon-world/examples/probe/piston_movement_fixture.rs b/crates/horizon-world/examples/probe/piston_movement_fixture.rs index 68af8348e..804ccec2e 100644 --- a/crates/horizon-world/examples/probe/piston_movement_fixture.rs +++ b/crates/horizon-world/examples/probe/piston_movement_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::geometry::Vec3; use horizon_world::piston_movement::PistonMovement; use serde_json::Value; @@ -12,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() - } -} pub fn main() -> Result<(), Box> { let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); @@ -45,18 +39,18 @@ pub fn main() -> Result<(), Box> { Ok(v) => writeln!( out, "movement {:016x} {:016x} {:016x}", - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) )?, Err(_) => writeln!(out, "error")?, } writeln!( out, "deltas {:016x} {:016x} {:016x}", - bits(state.deltas[0]), - bits(state.deltas[1]), - bits(state.deltas[2]) + f64_bits(state.deltas[0]), + f64_bits(state.deltas[1]), + f64_bits(state.deltas[2]) )?; writeln!(out, "tick {}", state.game_time)?; writeln!(out, "queries {calls}")?; diff --git a/crates/horizon-world/examples/probe/piston_shape_fixture.rs b/crates/horizon-world/examples/probe/piston_shape_fixture.rs index 4eb07b4d8..ec75a9502 100644 --- a/crates/horizon-world/examples/probe/piston_shape_fixture.rs +++ b/crates/horizon-world/examples/probe/piston_shape_fixture.rs @@ -1,4 +1,5 @@ -use horizon_core::geometry::{Aabb, Axis, Direction, VoxelShape}; +use crate::support::shapes::emit; +use horizon_core::geometry::{Direction, VoxelShape}; use horizon_world::{ collision::CachedCollisionRegistry, dynamic_support::{DynamicSupport, DynamicSupportWorld}, @@ -12,70 +13,6 @@ use std::{ io::{self, Write}, path::Path, }; -fn values( - out: &mut impl Write, - label: &str, - values: impl IntoIterator, -) -> io::Result<()> { - write!(out, "{label}")?; - for v in values { - let bits = if v.is_nan() { - 0x7ff8_0000_0000_0000 - } else { - v.to_bits() - }; - write!(out, " {bits:016x}")?; - } - writeln!(out) -} -fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { - values( - out, - label, - [ - b.min(Axis::X), - b.min(Axis::Y), - b.min(Axis::Z), - b.max(Axis::X), - b.max(Axis::Y), - b.max(Axis::Z), - ], - ) -} -fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { - writeln!( - out, - "shape {} {} {}", - shape.is_empty(), - shape.boxes().len(), - shape.is_cube() - )?; - for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { - values(out, name, shape.coordinates(axis).iter().copied())?; - } - let axes = shape.cube_coordinate_axes(); - writeln!( - out, - "axes {}", - u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) - )?; - values( - out, - "extrema", - Axis::ALL - .map(|a| shape.min(a)) - .into_iter() - .chain(Axis::ALL.map(|a| shape.max(a))), - )?; - match shape.bounds() { - Some(b) => box_values(out, "bounds", b)?, - None => writeln!(out, "bounds none")?, - } - for b in shape.boxes() { - box_values(out, "box", *b)?; - } - Ok(()) -} struct World<'a, 'r, W> { collisions: &'a CachedCollisionRegistry<'r>, dynamic: &'a [Option], diff --git a/crates/horizon-world/examples/probe/player_food_fixture.rs b/crates/horizon-world/examples/probe/player_food_fixture.rs index e2ef7d450..186ec6332 100644 --- a/crates/horizon-world/examples/probe/player_food_fixture.rs +++ b/crates/horizon-world/examples/probe/player_food_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::{ food::FoodData, player_food::{self, PlayerFoodWorld, StoredPlayerFood}, @@ -11,13 +12,6 @@ use std::{ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} struct World<'a> { f: &'a Value, out: &'a mut dyn Write, @@ -68,7 +62,7 @@ impl PlayerFoodWorld for World<'_> { } fn add_exhaustion_direct(&mut self, v: f32) -> io::Result<()> { let i = self.index("direct"); - self.query(&format!("exhaust {i} {:08x}", bits(v)))?; + self.query(&format!("exhaust {i} {:08x}", f32_bits(v)))?; self.foods[i].add_exhaustion(v); Ok(()) } @@ -136,7 +130,7 @@ pub fn main() -> Result<(), Box> { w.out, "food {i} {} {:08x}", food.food, - bits(food.exhaustion) + f32_bits(food.exhaustion) )?; } writeln!(w.out, "queries {}", w.calls)?; diff --git a/crates/horizon-world/examples/probe/player_health_fixture.rs b/crates/horizon-world/examples/probe/player_health_fixture.rs index 4a4987de3..24163bb75 100644 --- a/crates/horizon-world/examples/probe/player_health_fixture.rs +++ b/crates/horizon-world/examples/probe/player_health_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::{ attributes::{ Modifier, Operation, @@ -19,20 +20,13 @@ fn single(v: &Value) -> f32 { fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn values(v: Option<&[FloatValue]>) -> String { match v { None => "none".into(), Some([]) => "empty".into(), Some(v) => v .iter() - .map(|v| format!("{}:{:08x}", v.id, bits(v.value))) + .map(|v| format!("{}:{:08x}", v.id, f32_bits(v.value))) .collect::>() .join(","), } @@ -59,7 +53,7 @@ impl Observer for Callback<'_> { fn updated(&mut self, data: &mut SyncedFloats, id: u8) -> io::Result<()> { self.event(&format!( "updated {id} {:08x} {}", - bits(data.get(id).unwrap()), + f32_bits(data.get(id).unwrap()), data.is_dirty() ))?; if self.op["pack_callback"].as_bool().unwrap() { @@ -145,7 +139,7 @@ pub fn main() -> Result<(), Box> { .bind(&mut cb) .absorption() .map_err(|_| ()) - .and_then(|v| writeln!(cb.out, "float {:08x}", bits(v)).map_err(|_| ())), + .and_then(|v| writeln!(cb.out, "float {:08x}", f32_bits(v)).map_err(|_| ())), "hurt" => state .bind(&mut cb) .is_hurt() @@ -227,8 +221,8 @@ pub fn main() -> Result<(), Box> { writeln!( cb.out, "state {:08x} {:08x} {} {} {} {} {} {}", - bits(state.data.get(ids.health).unwrap()), - bits(state.data.get(ids.absorption).unwrap()), + f32_bits(state.data.get(ids.health).unwrap()), + f32_bits(state.data.get(ids.absorption).unwrap()), state.data.is_dirty(), state.data.item_dirty(ids.health).unwrap(), state.data.item_dirty(ids.absorption).unwrap(), diff --git a/crates/horizon-world/examples/probe/player_hurt_fixture.rs b/crates/horizon-world/examples/probe/player_hurt_fixture.rs index 765f7b04b..6e77abf71 100644 --- a/crates/horizon-world/examples/probe/player_hurt_fixture.rs +++ b/crates/horizon-world/examples/probe/player_hurt_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::living_hurt::{HurtState, HurtTag, HurtWorld}; use horizon_world::{ food::Difficulty, @@ -15,19 +16,12 @@ use std::{ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn state(s: &HurtState<()>) -> String { format!( "{} {} {:08x} {} {} {} {}", s.no_action_time, s.cooldown, - bits(s.last_hurt), + f32_bits(s.last_hurt), s.hurt_duration, s.hurt_time, s.last_source.is_some(), @@ -134,7 +128,7 @@ impl HurtWorld for Env<'_> { Ok(self.flag("component")) } fn apply_blocking(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result { - self.event(&format!("blocking {:08x}", bits(v)))?; + self.event(&format!("blocking {:08x}", f32_bits(v)))?; Ok(single(&self.op["blocked"])) } fn helmet_empty(&mut self, _: &mut HurtState<()>) -> io::Result { @@ -142,10 +136,10 @@ impl HurtWorld for Env<'_> { Ok(!self.flag("helmet")) } fn hurt_helmet(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result<()> { - self.event(&format!("hurt-helmet {:08x}", bits(v))) + self.event(&format!("hurt-helmet {:08x}", f32_bits(v))) } fn actually_hurt(&mut self, s: &mut HurtState<()>, v: f32) -> io::Result<()> { - self.event(&format!("hurt {:08x} {}", bits(v), state(s)))?; + self.event(&format!("hurt {:08x} {}", f32_bits(v), state(s)))?; self.hit = true; self.recorded = v; if self.flag("mutate_hit") { @@ -163,7 +157,7 @@ impl HurtWorld for Env<'_> { Ok(()) } fn knockback(&mut self, _: &mut HurtState<()>, v: f32, b: bool) -> io::Result<()> { - self.event(&format!("knockback {:08x} {b}", bits(v))) + self.event(&format!("knockback {:08x} {b}", f32_bits(v))) } fn death_protection(&mut self, _: &mut HurtState<()>) -> io::Result { self.event("tag bypasses_invulnerability")?; @@ -187,7 +181,7 @@ impl HurtWorld for Env<'_> { fn effects_on_hurt(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result<()> { self.event("effects")?; for i in 0..self.op["effects"].as_u64().unwrap() { - self.event(&format!("effect {i} {:08x}", bits(v)))?; + self.event(&format!("effect {i} {:08x}", f32_bits(v)))?; } Ok(()) } @@ -303,7 +297,7 @@ pub fn main() -> Result<(), Box> { e.out, "state {} {:08x} {} {}", state(&s), - bits(recorded), + f32_bits(recorded), e.hit, e.calls )?; diff --git a/crates/horizon-world/examples/probe/player_travel_fixture.rs b/crates/horizon-world/examples/probe/player_travel_fixture.rs index 5627ef6a2..e4d493662 100644 --- a/crates/horizon-world/examples/probe/player_travel_fixture.rs +++ b/crates/horizon-world/examples/probe/player_travel_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::player_travel::*; use serde_json::Value; @@ -15,18 +16,16 @@ fn single(v: &Value) -> f32 { fn vec(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn fbits(v: f32) -> u32 { if v.is_nan() { 0x7fc00000 } else { v.to_bits() } } fn vector(v: Vec3) -> String { - format!("{:016x} {:016x} {:016x}", bits(v.x), bits(v.y), bits(v.z)) + format!( + "{:016x} {:016x} {:016x}", + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) + ) } struct World<'a> { f: &'a Value, diff --git a/crates/horizon-world/examples/probe/registered_player_combat_fixture.rs b/crates/horizon-world/examples/probe/registered_player_combat_fixture.rs index 4029b4918..c70881165 100644 --- a/crates/horizon-world/examples/probe/registered_player_combat_fixture.rs +++ b/crates/horizon-world/examples/probe/registered_player_combat_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::damage_immunity::{DamageRule, ImmunityTag, ImmunityWorld}; use horizon_world::damage_source::{ Catalog as DamageCatalog, DamageSource, EntityKind, SourceWorld, @@ -31,19 +32,12 @@ use std::{ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn state(s: &HurtState<()>) -> String { format!( "{} {} {:08x} {} {} {} {}", s.no_action_time, s.cooldown, - bits(s.last_hurt), + f32_bits(s.last_hurt), s.hurt_duration, s.hurt_time, s.last_source.is_some(), @@ -151,7 +145,7 @@ impl HurtWorld for Env<'_> { Ok(self.flag("component")) } fn apply_blocking(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result { - self.event(&format!("blocking {:08x}", bits(v)))?; + self.event(&format!("blocking {:08x}", f32_bits(v)))?; Ok(single(&self.op["blocked"])) } fn helmet_empty(&mut self, _: &mut HurtState<()>) -> io::Result { @@ -159,7 +153,7 @@ impl HurtWorld for Env<'_> { Ok(!self.flag("helmet")) } fn hurt_helmet(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result<()> { - self.event(&format!("hurt-helmet {:08x}", bits(v))) + self.event(&format!("hurt-helmet {:08x}", f32_bits(v))) } fn actually_hurt(&mut self, _s: &mut HurtState<()>, _v: f32) -> io::Result<()> { panic!("combat binding supplies actual inner damage") @@ -171,7 +165,7 @@ impl HurtWorld for Env<'_> { Ok(()) } fn knockback(&mut self, _: &mut HurtState<()>, v: f32, b: bool) -> io::Result<()> { - self.event(&format!("knockback {:08x} {b}", bits(v))) + self.event(&format!("knockback {:08x} {b}", f32_bits(v))) } fn death_protection(&mut self, _: &mut HurtState<()>) -> io::Result { if !self @@ -197,7 +191,7 @@ impl HurtWorld for Env<'_> { fn effects_on_hurt(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result<()> { self.event("effects")?; for i in 0..self.op["effects"].as_u64().unwrap() { - self.event(&format!("effect {i} {:08x}", bits(v)))?; + self.event(&format!("effect {i} {:08x}", f32_bits(v)))?; } Ok(()) } @@ -280,7 +274,7 @@ fn values(v: Option<&[FloatValue]>) -> String { Some([]) => "empty".into(), Some(v) => v .iter() - .map(|v| format!("{}:{:08x}", v.id, bits(v.value))) + .map(|v| format!("{}:{:08x}", v.id, f32_bits(v.value))) .collect::>() .join(","), } @@ -290,7 +284,7 @@ impl Observer for Env<'_> { fn updated(&mut self, data: &mut SyncedFloats, id: u8) -> io::Result<()> { self.event(&format!( "updated {id} {:08x} {}", - bits(data.get(id).unwrap()), + f32_bits(data.get(id).unwrap()), data.is_dirty() ))?; if self.flag("pack_callback") { @@ -329,7 +323,7 @@ impl ServerDamageEnvironment for Env<'_> { Ok(self.source.bypasses(b)) } fn hurt_armor(&mut self, a: &mut EntityAttributes, v: f32) -> io::Result<()> { - self.event(&format!("hurt-armor {:08x}", bits(v)))?; + self.event(&format!("hurt-armor {:08x}", f32_bits(v)))?; if self.flag("break_armor") { let id = a.catalog().id("minecraft:armor").unwrap(); a.edit(id, |a, o| { @@ -387,7 +381,7 @@ impl ServerDamageEnvironment for Env<'_> { } fn record_damage(&mut self, v: f32) -> io::Result<()> { self.event("tracker")?; - self.event(&format!("record {:08x}", bits(v)))?; + self.event(&format!("record {:08x}", f32_bits(v)))?; self.recorded = v; self.hit = true; Ok(()) @@ -513,16 +507,16 @@ pub fn main() -> Result<(), Box> { e.out, "state {} {:08x} {} {}", state(&s), - bits(recorded), + f32_bits(recorded), e.hit, e.calls )?; writeln!( e.out, "storage {:08x} {:08x} {:08x} {} {} {} {}", - bits(data.get(ids.health).unwrap()), - bits(data.get(ids.absorption).unwrap()), - bits(food.exhaustion), + f32_bits(data.get(ids.health).unwrap()), + f32_bits(data.get(ids.absorption).unwrap()), + f32_bits(food.exhaustion), data.is_dirty(), data.item_dirty(ids.health).unwrap(), data.item_dirty(ids.absorption).unwrap(), diff --git a/crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs b/crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs index f2504eab4..b66812142 100644 --- a/crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs +++ b/crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs @@ -1,4 +1,5 @@ //! Integrated registry/cursor differential transport using resident TerrainChunk storage. +use crate::support::shapes::{emit, values}; use horizon_core::{ geometry::{Aabb, Axis, Vec3, VoxelShape}, position::{BlockPos, ChunkPos}, @@ -43,70 +44,6 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn values( - out: &mut impl Write, - label: &str, - values: impl IntoIterator, -) -> io::Result<()> { - write!(out, "{label}")?; - for v in values { - let bits = if v.is_nan() { - 0x7ff8_0000_0000_0000 - } else { - v.to_bits() - }; - write!(out, " {bits:016x}")?; - } - writeln!(out) -} -fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { - values( - out, - label, - [ - b.min(Axis::X), - b.min(Axis::Y), - b.min(Axis::Z), - b.max(Axis::X), - b.max(Axis::Y), - b.max(Axis::Z), - ], - ) -} -fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { - writeln!( - out, - "shape {} {} {}", - shape.is_empty(), - shape.boxes().len(), - shape.is_cube() - )?; - for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { - values(out, name, shape.coordinates(axis).iter().copied())?; - } - let axes = shape.cube_coordinate_axes(); - writeln!( - out, - "axes {}", - u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) - )?; - values( - out, - "extrema", - Axis::ALL - .map(|a| shape.min(a)) - .into_iter() - .chain(Axis::ALL.map(|a| shape.max(a))), - )?; - match shape.bounds() { - Some(b) => box_values(out, "bounds", b)?, - None => writeln!(out, "bounds none")?, - } - for b in shape.boxes() { - box_values(out, "box", *b)?; - } - Ok(()) -} struct Trace { out: io::BufWriter, calls: i32, diff --git a/crates/horizon-world/examples/probe/registry_fall_ray_fixture.rs b/crates/horizon-world/examples/probe/registry_fall_ray_fixture.rs index c3861308e..c4f61644c 100644 --- a/crates/horizon-world/examples/probe/registry_fall_ray_fixture.rs +++ b/crates/horizon-world/examples/probe/registry_fall_ray_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::{ entity_obstruction::EntityIdentity, @@ -21,13 +22,6 @@ fn number(v: &Value) -> f64 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn pos(p: BlockPos) -> String { format!("{} {} {}", p.x, p.y, p.z) } @@ -181,9 +175,9 @@ pub fn main() -> Result<(), Box> { w.out, "hit {} {:016x} {:016x} {:016x} {} {} {}", r.miss, - bits(h.location.x), - bits(h.location.y), - bits(h.location.z), + f64_bits(h.location.x), + f64_bits(h.location.y), + f64_bits(h.location.z), format!("{:?}", h.direction).to_lowercase(), pos(h.block), h.inside diff --git a/crates/horizon-world/examples/probe/replace_block_fixture.rs b/crates/horizon-world/examples/probe/replace_block_fixture.rs index 7d4f05d7c..d0a742f99 100644 --- a/crates/horizon-world/examples/probe/replace_block_fixture.rs +++ b/crates/horizon-world/examples/probe/replace_block_fixture.rs @@ -1,4 +1,5 @@ //! Feature world transport retaining ordered mutations and partial failures. +use crate::support::common::tag; use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; use horizon_world::{ DATA_VERSION, @@ -135,17 +136,6 @@ 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"), - } -} pub fn main() -> Result<(), Box> { let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); diff --git a/crates/horizon-world/examples/probe/restitution_fixture.rs b/crates/horizon-world/examples/probe/restitution_fixture.rs index 1432d92a8..0d630274e 100644 --- a/crates/horizon-world/examples/probe/restitution_fixture.rs +++ b/crates/horizon-world/examples/probe/restitution_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::{ movement_restitution::{RestitutionInput, RestitutionWorld, restitute_movement}, @@ -18,19 +19,12 @@ fn single(v: &Value) -> f32 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn vector_text(prefix: &str, v: Vec3) -> String { format!( "{prefix} {:016x} {:016x} {:016x}", - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) ) } struct World<'a, W> { @@ -102,7 +96,7 @@ impl RestitutionWorld for World<'_, W> { p.x, p.y, p.z, - bits(fall) + f64_bits(fall) ))?; if self.f["mutate"].as_bool().unwrap() { self.velocity = Vec3::new(17.0, 18.0, 19.0); diff --git a/crates/horizon-world/examples/probe/rule_test_fixture.rs b/crates/horizon-world/examples/probe/rule_test_fixture.rs index 8974eed1a..42a25532c 100644 --- a/crates/horizon-world/examples/probe/rule_test_fixture.rs +++ b/crates/horizon-world/examples/probe/rule_test_fixture.rs @@ -1,4 +1,5 @@ //! Differential transport for replacement rules over pinned block identities. +use crate::support::common::tag; use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; use horizon_world::{ DATA_VERSION, @@ -41,17 +42,6 @@ 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"), - } -} pub fn main() -> Result<(), Box> { let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); diff --git a/crates/horizon-world/examples/probe/scattered_ore_fixture.rs b/crates/horizon-world/examples/probe/scattered_ore_fixture.rs index 2c43f2b83..91b6821b7 100644 --- a/crates/horizon-world/examples/probe/scattered_ore_fixture.rs +++ b/crates/horizon-world/examples/probe/scattered_ore_fixture.rs @@ -1,4 +1,5 @@ //! Feature world transport retaining ordered mutations and partial failures. +use crate::support::common::tag; use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; use horizon_world::{ DATA_VERSION, @@ -159,17 +160,6 @@ 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"), - } -} pub fn main() -> Result<(), Box> { let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); diff --git a/crates/horizon-world/examples/probe/server_player_combat_fixture.rs b/crates/horizon-world/examples/probe/server_player_combat_fixture.rs index cceb1f001..9607dcec2 100644 --- a/crates/horizon-world/examples/probe/server_player_combat_fixture.rs +++ b/crates/horizon-world/examples/probe/server_player_combat_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::damage_immunity::{DamageRule, ImmunityTag, ImmunityWorld}; use horizon_world::living_hurt::{HurtState, HurtTag, HurtWorld}; use horizon_world::{ @@ -84,19 +85,12 @@ impl FixtureAttributes for Live { fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn state(s: &HurtState<()>) -> String { format!( "{} {} {:08x} {} {} {} {}", s.no_action_time, s.cooldown, - bits(s.last_hurt), + f32_bits(s.last_hurt), s.hurt_duration, s.hurt_time, s.last_source.is_some(), @@ -208,7 +202,7 @@ impl HurtWorld for Env<'_> { Ok(self.flag("component")) } fn apply_blocking(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result { - self.event(&format!("blocking {:08x}", bits(v)))?; + self.event(&format!("blocking {:08x}", f32_bits(v)))?; Ok(single(&self.op["blocked"])) } fn helmet_empty(&mut self, _: &mut HurtState<()>) -> io::Result { @@ -216,7 +210,7 @@ impl HurtWorld for Env<'_> { Ok(!self.flag("helmet")) } fn hurt_helmet(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result<()> { - self.event(&format!("hurt-helmet {:08x}", bits(v))) + self.event(&format!("hurt-helmet {:08x}", f32_bits(v))) } fn actually_hurt(&mut self, _s: &mut HurtState<()>, _v: f32) -> io::Result<()> { panic!("combat binding supplies actual inner damage") @@ -228,7 +222,7 @@ impl HurtWorld for Env<'_> { Ok(()) } fn knockback(&mut self, _: &mut HurtState<()>, v: f32, b: bool) -> io::Result<()> { - self.event(&format!("knockback {:08x} {b}", bits(v))) + self.event(&format!("knockback {:08x} {b}", f32_bits(v))) } fn death_protection(&mut self, _: &mut HurtState<()>) -> io::Result { self.event("tag bypasses_invulnerability")?; @@ -252,7 +246,7 @@ impl HurtWorld for Env<'_> { fn effects_on_hurt(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result<()> { self.event("effects")?; for i in 0..self.op["effects"].as_u64().unwrap() { - self.event(&format!("effect {i} {:08x}", bits(v)))?; + self.event(&format!("effect {i} {:08x}", f32_bits(v)))?; } Ok(()) } @@ -337,7 +331,7 @@ fn values(v: Option<&[FloatValue]>) -> String { Some([]) => "empty".into(), Some(v) => v .iter() - .map(|v| format!("{}:{:08x}", v.id, bits(v.value))) + .map(|v| format!("{}:{:08x}", v.id, f32_bits(v.value))) .collect::>() .join(","), } @@ -347,7 +341,7 @@ impl Observer for Env<'_> { fn updated(&mut self, data: &mut SyncedFloats, id: u8) -> io::Result<()> { self.event(&format!( "updated {id} {:08x} {}", - bits(data.get(id).unwrap()), + f32_bits(data.get(id).unwrap()), data.is_dirty() ))?; if self.flag("pack_callback") { @@ -393,7 +387,7 @@ impl ServerDamageEnvironment for Env<'_> { Ok(self.flag(&format!("bypass_{n}"))) } fn hurt_armor(&mut self, a: &mut A, v: f32) -> io::Result<()> { - self.event(&format!("hurt-armor {:08x}", bits(v)))?; + self.event(&format!("hurt-armor {:08x}", f32_bits(v)))?; if self.flag("break_armor") { a.configure("minecraft:armor", number(&self.op["armor_after"]), None); } @@ -447,7 +441,7 @@ impl ServerDamageEnvironment for Env<'_> { } fn record_damage(&mut self, v: f32) -> io::Result<()> { self.event("tracker")?; - self.event(&format!("record {:08x}", bits(v)))?; + self.event(&format!("record {:08x}", f32_bits(v)))?; self.recorded = v; self.hit = true; Ok(()) @@ -554,16 +548,16 @@ fn run(dir: &Path, output: &str) -> Result<(), Box f32 { fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn values(v: Option<&[FloatValue]>) -> String { match v { None => "none".into(), Some([]) => "empty".into(), Some(v) => v .iter() - .map(|v| format!("{}:{:08x}", v.id, bits(v.value))) + .map(|v| format!("{}:{:08x}", v.id, f32_bits(v.value))) .collect::>() .join(","), } @@ -69,7 +63,7 @@ impl Observer for Env<'_> { fn updated(&mut self, data: &mut SyncedFloats, id: u8) -> io::Result<()> { self.event(&format!( "updated {id} {:08x} {}", - bits(data.get(id).unwrap()), + f32_bits(data.get(id).unwrap()), data.is_dirty() ))?; if self.flag("pack_callback") { @@ -115,7 +109,7 @@ impl ServerDamageEnvironment for Env<'_> { Ok(self.flag(&format!("bypass_{n}"))) } fn hurt_armor(&mut self, a: &mut EntityAttributes, v: f32) -> io::Result<()> { - self.event(&format!("hurt-armor {:08x}", bits(v)))?; + self.event(&format!("hurt-armor {:08x}", f32_bits(v)))?; if self.flag("break_armor") { let id = a.catalog().id("minecraft:armor").unwrap(); a.edit(id, |a, o| { @@ -174,7 +168,7 @@ impl ServerDamageEnvironment for Env<'_> { } fn record_damage(&mut self, v: f32) -> io::Result<()> { self.event("tracker")?; - self.event(&format!("record {:08x}", bits(v)))?; + self.event(&format!("record {:08x}", f32_bits(v)))?; self.recorded = v; Ok(()) } @@ -255,10 +249,10 @@ pub fn main() -> Result<(), Box> { writeln!( env.out, "state {:08x} {:08x} {:08x} {:08x} {} {} {} {}", - bits(data.get(ids.health).unwrap()), - bits(data.get(ids.absorption).unwrap()), - bits(food.exhaustion), - bits(recorded), + f32_bits(data.get(ids.health).unwrap()), + f32_bits(data.get(ids.absorption).unwrap()), + f32_bits(food.exhaustion), + f32_bits(recorded), data.is_dirty(), data.item_dirty(ids.health).unwrap(), data.item_dirty(ids.absorption).unwrap(), diff --git a/crates/horizon-world/examples/probe/spawn_origin.rs b/crates/horizon-world/examples/probe/spawn_origin.rs index bf62726af..7162a00a8 100644 --- a/crates/horizon-world/examples/probe/spawn_origin.rs +++ b/crates/horizon-world/examples/probe/spawn_origin.rs @@ -3,6 +3,7 @@ //! (NoiseBasedChunkGenerator.getOrigin), as `seed x z chunk_x chunk_z` lines. //! //! usage: spawn_origin ... +use crate::support::common::tag; use horizon_world::{ DATA_VERSION, nbt::Tag, @@ -14,17 +15,6 @@ use std::{fs, path::Path}; type Error = Box; -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - Value::Object(o) => { - Tag::Compound(o.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - _ => panic!("invalid registry metadata"), - } -} fn registry(resources: &Path) -> Result<&'static BlockRegistry, Error> { let facts: Value = serde_json::from_str(&fs::read_to_string(resources.join("facts.json"))?)?; let states = facts["states"].as_array().ok_or("facts states")?; diff --git a/crates/horizon-world/examples/probe/state_provider_fixture.rs b/crates/horizon-world/examples/probe/state_provider_fixture.rs index 68d91a1cf..6164e5d6c 100644 --- a/crates/horizon-world/examples/probe/state_provider_fixture.rs +++ b/crates/horizon-world/examples/probe/state_provider_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::tag; use horizon_core::random::{LegacyRandom, RandomSource, WorldgenRandom, XoroshiroRandom}; use horizon_world::{ DATA_VERSION, @@ -288,17 +289,6 @@ 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"), - } -} pub fn main() -> Result<(), Box> { let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); diff --git a/crates/horizon-world/examples/probe/stored_effect_attributes_fixture.rs b/crates/horizon-world/examples/probe/stored_effect_attributes_fixture.rs index b904a0520..10ae7bf63 100644 --- a/crates/horizon-world/examples/probe/stored_effect_attributes_fixture.rs +++ b/crates/horizon-world/examples/probe/stored_effect_attributes_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_hex; use horizon_world::{ attribute_map::AttributeMap, attributes::{AttributeError, Definition, Instance, Modifier, Observer, Operation}, @@ -38,16 +39,6 @@ enum Stop { Null, Bounds, } -fn bits(v: f64) -> String { - format!( - "{:016x}", - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } - ) -} fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } @@ -118,7 +109,7 @@ impl World { format!( "{id}:{}:{}:{}", m.id(), - bits(m.amount()), + f64_hex(m.amount()), m.operation() as u8 ) }) @@ -162,9 +153,9 @@ impl World { let prefix = format!( "instance {id} {} {} {} {}", n.key.id, - bits(a.base_value()), + f64_hex(a.base_value()), a.is_dirty(), - bits(a.cached_value()) + f64_hex(a.cached_value()) ); let all = a.modifiers().to_vec(); let permanent = a.permanent_modifiers().to_vec(); @@ -469,7 +460,7 @@ pub fn main() -> Result<(), Box> { "value" => world .handle(op["instance"].as_i64().unwrap()) .and_then(|h| h.ok_or(Stop::Null)) - .map(|h| bits(world.instances[h.id].value.as_mut().unwrap().value())), + .map(|h| f64_hex(world.instances[h.id].value.as_mut().unwrap().value())), _ => world.raw(&mut map, op).map(|()| "ok".into()), }; world.logs.push(format!( diff --git a/crates/horizon-world/examples/probe/stored_effect_notifications_fixture.rs b/crates/horizon-world/examples/probe/stored_effect_notifications_fixture.rs index 31b4b047b..9dccc7cf8 100644 --- a/crates/horizon-world/examples/probe/stored_effect_notifications_fixture.rs +++ b/crates/horizon-world/examples/probe/stored_effect_notifications_fixture.rs @@ -329,7 +329,7 @@ mod integration { "value" => world .handle(op["instance"].as_i64().unwrap()) .and_then(|h| h.ok_or(Stop::Null)) - .map(|h| bits(world.instances[h.id].value.as_mut().unwrap().value())), + .map(|h| f64_hex(world.instances[h.id].value.as_mut().unwrap().value())), _ => world.raw(&mut map, op).map(|()| "ok".into()), }; world.logs.push(format!( diff --git a/crates/horizon-world/examples/probe/support/common.rs b/crates/horizon-world/examples/probe/support/common.rs new file mode 100644 index 000000000..17c453363 --- /dev/null +++ b/crates/horizon-world/examples/probe/support/common.rs @@ -0,0 +1,49 @@ +//! Number formats and JSON readers several probes share. +use horizon_core::position::BlockPos; +use horizon_world::nbt::Tag; +use serde_json::Value; + +/// An f64's bits, every NaN as Java's canonical one (Double.doubleToLongBits). +pub fn f64_bits(v: f64) -> u64 { + if v.is_nan() { + f64::NAN.to_bits() + } else { + v.to_bits() + } +} + +/// An f32's bits, every NaN as Java's canonical one (Float.floatToIntBits). +pub fn f32_bits(v: f32) -> u32 { + if v.is_nan() { + f32::NAN.to_bits() + } else { + v.to_bits() + } +} + +/// f64_bits as 16 hex digits. +pub fn f64_hex(v: f64) -> String { + format!("{:016x}", f64_bits(v)) +} + +/// Registry metadata from the oracle's JSON as NBT: strings, ints, lists and compounds. +pub fn tag(v: &Value) -> Tag { + match v { + Value::String(s) => Tag::String(s.as_str().into()), + Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), + Value::Array(a) => Tag::List(a.iter().map(tag).collect()), + Value::Object(m) => { + Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) + } + _ => panic!("invalid registry metadata"), + } +} + +/// A block position from a JSON `[x, y, z]`. +pub fn position(v: &Value) -> BlockPos { + BlockPos::new( + v[0].as_i64().unwrap() as i32, + v[1].as_i64().unwrap() as i32, + v[2].as_i64().unwrap() as i32, + ) +} diff --git a/crates/horizon-world/examples/probe/support/shapes.rs b/crates/horizon-world/examples/probe/support/shapes.rs new file mode 100644 index 000000000..eed5f436d --- /dev/null +++ b/crates/horizon-world/examples/probe/support/shapes.rs @@ -0,0 +1,85 @@ +//! Shapes and boxes printed the same way by the collision probes. +use super::common::f64_bits; +use horizon_core::geometry::{Aabb, Axis, VoxelShape}; +use std::io::{self, Write}; + +pub fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { + writeln!( + out, + "shape {} {} {}", + shape.is_empty(), + shape.boxes().len(), + shape.is_cube() + )?; + for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { + values(out, name, shape.coordinates(axis).iter().copied())?; + } + let axes = shape.cube_coordinate_axes(); + writeln!( + out, + "axes {}", + u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) + )?; + values( + out, + "extrema", + Axis::ALL + .map(|a| shape.min(a)) + .into_iter() + .chain(Axis::ALL.map(|a| shape.max(a))), + )?; + match shape.bounds() { + Some(b) => box_values(out, "bounds", b)?, + None => writeln!(out, "bounds none")?, + } + for b in shape.boxes() { + box_values(out, "box", *b)?; + } + Ok(()) +} + +/// `label` and each value's bits in hex, NaN as Java's canonical one. +pub fn values( + out: &mut impl Write, + label: &str, + values: impl IntoIterator, +) -> io::Result<()> { + write!(out, "{label}")?; + for v in values { + let bits = if v.is_nan() { + 0x7ff8_0000_0000_0000 + } else { + v.to_bits() + }; + write!(out, " {bits:016x}")?; + } + writeln!(out) +} + +pub fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { + values( + out, + label, + [ + b.min(Axis::X), + b.min(Axis::Y), + b.min(Axis::Z), + b.max(Axis::X), + b.max(Axis::Y), + b.max(Axis::Z), + ], + ) +} + +/// `label` and the box's six bounds' bits in hex. +pub fn bounds(label: &str, b: Aabb) -> String { + format!( + "{label} {:016x} {:016x} {:016x} {:016x} {:016x} {:016x}", + f64_bits(b.min(Axis::X)), + f64_bits(b.min(Axis::Y)), + f64_bits(b.min(Axis::Z)), + f64_bits(b.max(Axis::X)), + f64_bits(b.max(Axis::Y)), + f64_bits(b.max(Axis::Z)) + ) +} diff --git a/crates/horizon-world/examples/probe/synced_floats_fixture.rs b/crates/horizon-world/examples/probe/synced_floats_fixture.rs index 8209c4aa5..7f649c18b 100644 --- a/crates/horizon-world/examples/probe/synced_floats_fixture.rs +++ b/crates/horizon-world/examples/probe/synced_floats_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::synced_floats::{DataError, FloatValue, Observer, SyncedFloats}; use serde_json::Value; use std::{ @@ -8,13 +9,6 @@ use std::{ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn parse(v: &Value) -> Vec { v.as_array() .unwrap() @@ -31,7 +25,7 @@ fn values(v: Option<&[FloatValue]>) -> String { Some([]) => "empty".into(), Some(v) => v .iter() - .map(|v| format!("{}:{:08x}", v.id, bits(v.value))) + .map(|v| format!("{}:{:08x}", v.id, f32_bits(v.value))) .collect::>() .join(","), } @@ -59,7 +53,7 @@ impl Observer for Callback<'_> { fn updated(&mut self, data: &mut SyncedFloats, id: u8) -> io::Result<()> { self.event(&format!( "updated {id} {:08x} {} {}", - bits(data.get(id).unwrap()), + f32_bits(data.get(id).unwrap()), data.is_dirty(), data.item_dirty(id).unwrap() ))?; @@ -129,7 +123,7 @@ pub fn main() -> Result<(), Box> { ), "assign" => data.assign(&parse(&op["values"]), &mut cb), "get" => data.get(id).map_err(DataError::UnknownId).and_then(|v| { - writeln!(cb.out, "get {:08x}", bits(v)).map_err(DataError::Observer) + writeln!(cb.out, "get {:08x}", f32_bits(v)).map_err(DataError::Observer) }), "pack" => writeln!(cb.out, "packed {}", values(data.take_dirty().as_deref())) .map_err(DataError::Observer), @@ -149,7 +143,7 @@ pub fn main() -> Result<(), Box> { writeln!( cb.out, "state {id} {:08x} {} {}", - bits(data.get(*id).unwrap()), + f32_bits(data.get(*id).unwrap()), data.item_dirty(*id).unwrap(), data.is_default(*id).unwrap() )?; diff --git a/crates/horizon-world/examples/probe/teleport_consume_fixture.rs b/crates/horizon-world/examples/probe/teleport_consume_fixture.rs index cf82d3b67..595fa3855 100644 --- a/crates/horizon-world/examples/probe/teleport_consume_fixture.rs +++ b/crates/horizon-world/examples/probe/teleport_consume_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{ geometry::Vec3, position::BlockPos, @@ -13,13 +14,6 @@ use std::{ fn n(v: &Value, k: &str) -> i32 { v[k].as_i64().unwrap() as i32 } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} struct World<'a, R> { f: Value, out: &'a mut dyn Write, @@ -63,10 +57,10 @@ impl World<'_, R> { self.attempts, self.changed, self.riding, - bits(self.pos.x), - bits(self.pos.y), - bits(self.pos.z), - bits(self.fall), + f64_bits(self.pos.x), + f64_bits(self.pos.y), + f64_bits(self.pos.z), + f64_bits(self.fall), self.grace, self.impact ) @@ -128,9 +122,9 @@ impl TeleportConsumeWorld for World<'_, R> { self.attempts += 1; self.event(format!( "teleport {} {} {}", - bits(p.x), - bits(p.y), - bits(p.z) + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z) ))?; let at = n(self.config(), "success_at"); let success = at >= 0 && i >= at; @@ -142,9 +136,9 @@ impl TeleportConsumeWorld for World<'_, R> { fn teleport_event(&mut self, l: i32, p: Vec3) -> Result<(), Self::Error> { self.event(format!( "game-event {l} {} {} {}", - bits(p.x), - bits(p.y), - bits(p.z) + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z) )) } fn is_fox(&self) -> bool { @@ -153,9 +147,9 @@ impl TeleportConsumeWorld for World<'_, R> { fn teleport_sound(&mut self, l: i32, p: Vec3, fox: bool) -> Result<(), Self::Error> { self.event(format!( "sound {l} {fox} {} {} {}", - bits(p.x), - bits(p.y), - bits(p.z) + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z) )) } fn block_position(&mut self) -> Result { diff --git a/crates/horizon-world/examples/probe/terrain_fixture.rs b/crates/horizon-world/examples/probe/terrain_fixture.rs index 7d23227d9..506273a10 100644 --- a/crates/horizon-world/examples/probe/terrain_fixture.rs +++ b/crates/horizon-world/examples/probe/terrain_fixture.rs @@ -1,4 +1,5 @@ //! Test transport for registry-backed noise-stage filling against vanilla doFill. +use crate::support::common::tag; use horizon_core::{ density::{ Beardifier, JigsawJunction, RigidPiece, SamplerContext, StructureBounds, TerrainAdjustment, @@ -67,17 +68,6 @@ impl TerrainBlockStates for Properties<'_> { fn n(v: &Value) -> i32 { v.as_i64().unwrap() as i32 } -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(i) => Tag::Int(i.as_i64().unwrap() as i32), - Value::Object(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - _ => panic!("unsupported registry fixture value"), - } -} fn structure(v: &Value) -> Beardifier { let bounds = |v: &Value| { StructureBounds::new( diff --git a/crates/horizon-world/examples/probe/view_direction_fixture.rs b/crates/horizon-world/examples/probe/view_direction_fixture.rs index 0121de934..0c5f483df 100644 --- a/crates/horizon-world/examples/probe/view_direction_fixture.rs +++ b/crates/horizon-world/examples/probe/view_direction_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::geometry::Vec3; use horizon_world::view_direction; use serde_json::Value; @@ -15,13 +16,6 @@ fn number(v: &Value) -> f64 { fn vec(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } -} pub fn main() -> Result<(), Box> { let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); @@ -32,22 +26,22 @@ pub fn main() -> Result<(), Box> { "acos" => writeln!( out, "angle {:016x}", - bits(view_direction::acos(number(&f["value"]))) + f64_bits(view_direction::acos(number(&f["value"]))) )?, "view" => { let v = view_direction::view_vector(single(&f["pitch"]), single(&f["yaw"])); writeln!( out, "view {:016x} {:016x} {:016x}", - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) )?; } "blocking" => writeln!( out, "angle {:016x}", - bits(view_direction::blocking_angle( + f64_bits(view_direction::blocking_angle( vec(&f["source"]), vec(&f["position"]), single(&f["yaw"]) @@ -56,7 +50,7 @@ pub fn main() -> Result<(), Box> { "fallback" => writeln!( out, "angle {:016x}", - bits(view_direction::BLOCKING_FALLBACK_ANGLE) + f64_bits(view_direction::BLOCKING_FALLBACK_ANGLE) )?, _ => panic!("mode"), } diff --git a/crates/horizon-world/examples/probe/water_splash_fixture.rs b/crates/horizon-world/examples/probe/water_splash_fixture.rs index 08f5bd7b9..8d6eabc79 100644 --- a/crates/horizon-world/examples/probe/water_splash_fixture.rs +++ b/crates/horizon-world/examples/probe/water_splash_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{ geometry::Vec3, random::{LegacyRandom, RandomSource, XoroshiroRandom}, @@ -18,13 +19,6 @@ fn single(v: &Value) -> f32 { fn vec(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } -} fn float_bits(v: f32) -> u32 { if v.is_nan() { f32::NAN.to_bits() @@ -33,7 +27,12 @@ fn float_bits(v: f32) -> u32 { } } fn vector(v: Vec3) -> String { - format!("{:016x} {:016x} {:016x}", bits(v.x), bits(v.y), bits(v.z)) + format!( + "{:016x} {:016x} {:016x}", + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) + ) } struct World<'a, R> { f: &'a Value, diff --git a/crates/horizon-world/examples/probe/world_border_fixture.rs b/crates/horizon-world/examples/probe/world_border_fixture.rs index ba00b2ca0..ab0b8795b 100644 --- a/crates/horizon-world/examples/probe/world_border_fixture.rs +++ b/crates/horizon-world/examples/probe/world_border_fixture.rs @@ -1,5 +1,6 @@ +use crate::support::shapes::{emit, values}; use horizon_core::geometry::{ - Aabb, Axis, Vec3, VoxelShape, + Aabb, Vec3, border::{BorderGeometry, BorderStatus}, }; use serde_json::Value; @@ -11,70 +12,6 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn values( - out: &mut impl Write, - label: &str, - values: impl IntoIterator, -) -> io::Result<()> { - write!(out, "{label}")?; - for v in values { - let bits = if v.is_nan() { - 0x7ff8_0000_0000_0000 - } else { - v.to_bits() - }; - write!(out, " {bits:016x}")?; - } - writeln!(out) -} -fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { - values( - out, - label, - [ - b.min(Axis::X), - b.min(Axis::Y), - b.min(Axis::Z), - b.max(Axis::X), - b.max(Axis::Y), - b.max(Axis::Z), - ], - ) -} -fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { - writeln!( - out, - "shape {} {} {}", - shape.is_empty(), - shape.boxes().len(), - shape.is_cube() - )?; - for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { - values(out, name, shape.coordinates(axis).iter().copied())?; - } - let axes = shape.cube_coordinate_axes(); - writeln!( - out, - "axes {}", - u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) - )?; - values( - out, - "extrema", - Axis::ALL - .map(|a| shape.min(a)) - .into_iter() - .chain(Axis::ALL.map(|a| shape.max(a))), - )?; - match shape.bounds() { - Some(b) => box_values(out, "bounds", b)?, - None => writeln!(out, "bounds none")?, - } - for b in shape.boxes() { - box_values(out, "box", *b)?; - } - Ok(()) -} pub fn main() -> Result<(), Box> { let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); diff --git a/crates/horizon-world/examples/probe/world_ray_fixture.rs b/crates/horizon-world/examples/probe/world_ray_fixture.rs index 5b8a3b9fb..ded8645c7 100644 --- a/crates/horizon-world/examples/probe/world_ray_fixture.rs +++ b/crates/horizon-world/examples/probe/world_ray_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{ geometry::{Aabb, ShapeOp, Vec3, VoxelShape}, position::BlockPos, @@ -15,13 +16,6 @@ fn number(v: &Value) -> f64 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn pos(p: BlockPos) -> String { format!("{} {} {}", p.x, p.y, p.z) } @@ -185,9 +179,9 @@ pub fn main() -> Result<(), Box> { w.out, "hit {} {:016x} {:016x} {:016x} {} {} {}", r.miss, - bits(h.location.x), - bits(h.location.y), - bits(h.location.z), + f64_bits(h.location.x), + f64_bits(h.location.y), + f64_bits(h.location.z), format!("{:?}", h.direction).to_lowercase(), pos(h.block), h.inside diff --git a/tests/test_parity_runner.py b/tests/test_parity_runner.py index 9e0f2a2ec..1ecd790f0 100644 --- a/tests/test_parity_runner.py +++ b/tests/test_parity_runner.py @@ -55,13 +55,14 @@ class ParityRunnerTests(unittest.TestCase): with tempfile.TemporaryDirectory() as temp, mock.patch.object(parity, "ROOT", Path(temp)): probe = Path(temp, "crates/w/examples/probe") (probe / "support").mkdir(parents=True) - (probe / "a_fixture.rs").write_text("use crate::support::shared as s;") + (probe / "a_fixture.rs").write_text('mod integration { include!("d_fixture.rs"); }') + (probe / "d_fixture.rs").write_text("use crate::support::shared as s;") for name in ("b_fixture.rs", "c_fixture.rs", "main.rs", "support/shared.rs", "support/other.rs"): (probe / name).write_text("") - paths = [f"crates/w/examples/probe/{name}" for name in - ("a_fixture.rs", "b_fixture.rs", "c_fixture.rs", "main.rs", "support/other.rs", "support/shared.rs")] + paths = [f"crates/w/examples/probe/{name}" for name in ("a_fixture.rs", "b_fixture.rs", "c_fixture.rs", + "d_fixture.rs", "main.rs", "support/other.rs", "support/shared.rs")] self.assertEqual(parity.only_probes_run(["crates/w/src/lib.rs", *paths], {"a_fixture", "b_fixture"}), - ["crates/w/src/lib.rs", *paths[:2], paths[3], paths[5]]) + ["crates/w/src/lib.rs", *paths[:2], *paths[3:5], paths[6]]) self.assertEqual(parity.only_probes_run(paths, set()), paths) def test_java_sources_include_classes_pulled_from_the_sourcepath(self): diff --git a/tools/parity.py b/tools/parity.py index 271baee6f..8d12963e1 100644 --- a/tools/parity.py +++ b/tools/parity.py @@ -482,19 +482,21 @@ def probes_run(commands): def only_probes_run(paths, names): - """A probe binary's dep-info lists every probe in it. Keep those the harness ran and the shared support - modules they name (support::), so that editing one probe reruns only its own harnesses.""" + """A probe binary's dep-info lists every probe in it. Keep those the harness ran, the probes they include! + and the shared support modules they name (support::), so that editing one probe reruns only its own + harnesses.""" if not names: return paths - ran = [path for path in paths if (match := PROBE_SOURCE.search(path)) and not match.group(1) and match.group(2) in names] - used = "".join((ROOT / path).read_text(encoding="utf-8", errors="replace") for path in ran) - kept = [] - for path in paths: - match = PROBE_SOURCE.search(path) - if not match or (match.group(1) and f"support::{match.group(2)}" in used) \ - or (not match.group(1) and match.group(2) in (*names, "main")): - kept.append(path) - return kept + names, used = {*names, "main"}, "" + while True: + ran = [path for path in paths if (match := PROBE_SOURCE.search(path)) and not match.group(1) and match.group(2) in names] + used = "".join((ROOT / path).read_text(encoding="utf-8", errors="replace") for path in ran) + included = set(re.findall(r'include!\("(\w+)\.rs"\)', used)) - names + if not included: + break + names |= included + return [path for path in paths if not (match := PROBE_SOURCE.search(path)) + or (f"support::{match.group(2)}" in used if match.group(1) else match.group(2) in names)] def dependencies(trace, scope=None): From ab4c246cda75268cec6de1968229250ac992111d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 14:26:02 +0200 Subject: [PATCH 039/408] Delete the 11 examples nothing references Eight benches (block_facts, chunk, entity_geometry, json_readers, load, save, streaming, tick_chunk_membership), lan_flat, save_parity and vanilla_diff: no harness, tool, doc or workflow names them (review plan, section 1, dead code). -2,222 lines; Git history keeps them. Co-Authored-By: Claude Opus 5.5 --- .../examples/block_facts_bench.rs | 104 ----- crates/horizon-client/examples/chunk_bench.rs | 216 --------- .../examples/entity_geometry_bench.rs | 140 ------ .../examples/json_readers_bench.rs | 205 -------- crates/horizon-client/examples/lan_flat.rs | 143 ------ crates/horizon-client/examples/load_bench.rs | 153 ------ crates/horizon-client/examples/save_bench.rs | 128 ----- crates/horizon-client/examples/save_parity.rs | 265 ----------- .../examples/streaming_bench.rs | 284 ----------- .../examples/tick_chunk_membership_bench.rs | 143 ------ crates/horizon-world/examples/vanilla_diff.rs | 441 ------------------ 11 files changed, 2222 deletions(-) delete mode 100644 crates/horizon-client/examples/block_facts_bench.rs delete mode 100644 crates/horizon-client/examples/chunk_bench.rs delete mode 100644 crates/horizon-client/examples/entity_geometry_bench.rs delete mode 100644 crates/horizon-client/examples/json_readers_bench.rs delete mode 100644 crates/horizon-client/examples/lan_flat.rs delete mode 100644 crates/horizon-client/examples/load_bench.rs delete mode 100644 crates/horizon-client/examples/save_bench.rs delete mode 100644 crates/horizon-client/examples/save_parity.rs delete mode 100644 crates/horizon-client/examples/streaming_bench.rs delete mode 100644 crates/horizon-client/examples/tick_chunk_membership_bench.rs delete mode 100644 crates/horizon-world/examples/vanilla_diff.rs diff --git a/crates/horizon-client/examples/block_facts_bench.rs b/crates/horizon-client/examples/block_facts_bench.rs deleted file mode 100644 index f68dcf999..000000000 --- a/crates/horizon-client/examples/block_facts_bench.rs +++ /dev/null @@ -1,104 +0,0 @@ -//! Full production fact loading, including file reads, interning and temporary destruction. -//! cargo run --profile fast -p horizon-client --example block_facts_bench -- ROOT [SAMPLES] -//! Use SAMPLES=1 with an OS peak-RSS wrapper; `digest` checks all facts -//! and the shape sharing partition (including sharing between outlines and edges). -use horizon_client::blocks::BlockFacts; -use horizon_world::{DATA_VERSION, nbt::Tag, registry::BlockRegistry}; -use serde_json::Value; -use std::{ - collections::{HashMap, hash_map::DefaultHasher}, - fs, - hash::{Hash, Hasher}, - hint::black_box, - path::Path, - time::Instant, -}; -type Result = horizon_client::Result; - -fn tag(value: &Value) -> Result { - Ok(match value { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(n) => Tag::Int(i32::try_from(n.as_i64().ok_or("registry number")?)?), - Value::Array(a) => Tag::List(a.iter().map(tag).collect::>()?), - Value::Object(o) => Tag::Compound( - o.iter() - .map(|(k, v)| Ok((k.as_str().into(), tag(v)?))) - .collect::>()?, - ), - _ => return Err("registry value".into()), - }) -} -fn registry(root: &Path) -> Result { - let facts: Value = serde_json::from_slice(&fs::read(root.join("facts.json"))?)?; - Ok(BlockRegistry::from_nbt(&Tag::compound([ - ("DataVersion", Tag::Int(DATA_VERSION)), - ( - "states", - Tag::List( - facts["states"] - .as_array() - .ok_or("registry states")? - .iter() - .map(|s| tag(&s[4])) - .collect::>()?, - ), - ), - ("defaults", tag(&facts["defaults"])?), - ]))?) -} -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); - let root = Path::new( - args.first() - .ok_or("usage: block_facts_bench ROOT [SAMPLES|digest]")?, - ); - let setup = Instant::now(); - let registry = registry(root)?; - println!( - "registry_setup_ms={:.3}", - setup.elapsed().as_secs_f64() * 1000.0 - ); - if args.get(1).is_some_and(|s| s == "digest") { - let facts = BlockFacts::load(root, ®istry)?; - let mut hash = DefaultHasher::new(); - let mut shapes = HashMap::new(); - facts.air.hash(&mut hash); - for state in &facts.states { - format!("{state:?}").hash(&mut hash); - for shape in [&state.outline, &state.outline_edges] { - let next = shapes.len(); - shapes - .entry((shape.as_ptr(), shape.len())) - .or_insert(next) - .hash(&mut hash); - } - } - println!( - "states={} shared_shapes={} digest={:016x}", - facts.states.len(), - shapes.len(), - hash.finish() - ); - return Ok(()); - } - let samples: usize = args.get(1).map(|s| s.parse()).transpose()?.unwrap_or(9); - assert!(samples > 0); - // First load is reported separately; OS file caches are not forcibly evicted. - let load = || -> Result { - let start = Instant::now(); - let facts = black_box(BlockFacts::load(black_box(root), black_box(®istry))?); - let ms = start.elapsed().as_secs_f64() * 1000.0; - drop(facts); - Ok(ms) - }; - println!("first_load_ms={:.3}", load()?); - if samples > 1 { - load()?; - load()?; - let mut times = (0..samples).map(|_| load()).collect::>>()?; - println!("samples_ms={times:.3?}"); - times.sort_by(f64::total_cmp); - println!("median_ms={:.3}", times[times.len() / 2]); - } - Ok(()) -} diff --git a/crates/horizon-client/examples/chunk_bench.rs b/crates/horizon-client/examples/chunk_bench.rs deleted file mode 100644 index be619245f..000000000 --- a/crates/horizon-client/examples/chunk_bench.rs +++ /dev/null @@ -1,216 +0,0 @@ -//! Resident chunk storage benchmark: generates a block of vanilla terrain, then -//! reports the resident block/biome memory, the cost of lookups, meshing and -//! lighting on it. -//! -//! chunk_bench [--seed S] [--size N] -#![forbid(unsafe_code)] -use horizon_client::{ - assets::Assets, - biome::Biomes, - blocks::BlockFacts, - chunk::{Chunk, MIN_Y, SECTIONS}, - light::{LightTables, apply_lighting, light_chunk}, - mesher::{MeshTables, Mesher}, - models, - streaming::{ChunkGenerator, Proto}, - vanillagen::VanillaTerrain, -}; -use horizon_core::biome::BiomeZoom; -use std::{path::PathBuf, sync::Arc, time::Instant}; -type Result = std::result::Result>; - -fn main() -> Result<()> { - let args: Vec = std::env::args().skip(1).collect(); - let root = PathBuf::from(args.first().ok_or("usage: chunk_bench RESOURCES")?); - let flag = |name: &str, default: i64| -> i64 { - args.iter() - .position(|a| a == name) - .and_then(|i| args.get(i + 1)) - .and_then(|v| v.parse().ok()) - .unwrap_or(default) - }; - let (seed, size) = (flag("--seed", 12345), flag("--size", 8) as i32); - let assets = Assets::load(&root)?; - let render = assets.reload(&root)?; - let facts = BlockFacts::load(&root, assets.registry)?; - let biomes = Biomes::load(&root)?; - let tables = MeshTables::new( - &assets, - &render, - &facts, - models::load_visibility(&root, assets.registry)?, - )?; - let light = LightTables::load(&root, assets.registry, &facts)?; - let terrain = VanillaTerrain::new(&root.join("worldgen"), assets.registry, &biomes, seed)?; - let mut worker = terrain.worker(); - - // Protos for size+4 columns, decorated for the inner size+2, finished as size+2. - let started = Instant::now(); - let outer = size + 4; - let mut protos: Vec> = (0..outer * outer) - .map(|i| Some(terrain.proto(&mut worker, i % outer, i / outer))) - .collect(); - eprintln!("proto: {:.2}s", started.elapsed().as_secs_f64()); - let started = Instant::now(); - let inner = size + 2; - for z in 1..=inner { - for x in 1..=inner { - let mut region: [Proto; 9] = std::array::from_fn(|k| { - let (dx, dz) = (k as i32 % 3 - 1, k as i32 / 3 - 1); - protos[((z + dz) * outer + x + dx) as usize] - .take() - .expect("proto") - }); - terrain.decorate(&mut worker, &mut region); - for (k, p) in region.into_iter().enumerate() { - let (dx, dz) = (k as i32 % 3 - 1, k as i32 / 3 - 1); - protos[((z + dz) * outer + x + dx) as usize] = Some(p); - } - } - } - eprintln!("decorate: {:.2}s", started.elapsed().as_secs_f64()); - let started = Instant::now(); - let mut chunks: Vec = Vec::new(); - for z in 1..=inner { - for x in 1..=inner { - let proto = protos[(z * outer + x) as usize].take().expect("proto"); - let mut chunk = terrain.finish(proto); - chunk.x = x; - chunk.z = z; - chunks.push(chunk); - } - } - let finish = started.elapsed().as_secs_f64(); - println!( - "finish (proto -> resident chunk): {:.1} ms per chunk", - finish * 1e3 / chunks.len() as f64 - ); - - let chunks: Vec> = chunks.into_iter().map(Arc::new).collect(); - let at = |x: i32, z: i32| chunks[((z - 1) * inner + x - 1) as usize].clone(); - - // Light all inner-inner columns. - let started = Instant::now(); - let mut lit = Vec::new(); - for z in 2..inner { - for x in 2..inner { - let region: [[Option>; 3]; 3] = std::array::from_fn(|dz| { - std::array::from_fn(|dx| Some(at(x + dx as i32 - 1, z + dz as i32 - 1))) - }); - let borrowed = horizon_client::mesher::borrow(®ion); - lit.push(((x, z), light_chunk(&borrowed, &light, true))); - } - } - println!( - "light: {:.2} ms per column", - started.elapsed().as_secs_f64() * 1e3 / lit.len() as f64 - ); - let mut chunks: Vec = chunks.iter().map(|c| (**c).clone()).collect(); - for ((x, z), sections) in lit { - apply_lighting(&mut chunks[((z - 1) * inner + x - 1) as usize], sections); - } - let chunks: Vec> = chunks.into_iter().map(Arc::new).collect(); - let at = |x: i32, z: i32| chunks[((z - 1) * inner + x - 1) as usize].clone(); - - // Memory. - let (mut bytes, mut sections, mut uniform) = (0usize, 0usize, 0usize); - for chunk in &chunks { - bytes += chunk.heap_bytes(); - for s in &chunk.sections { - sections += 1; - uniform += usize::from(s.is_uniform(s.get(0))); - } - } - println!( - "resident: {} chunks, {} sections ({} uniform), {:.1} KiB per chunk ({:.2} MiB total)", - chunks.len(), - sections, - uniform, - bytes as f64 / 1024.0 / chunks.len() as f64, - bytes as f64 / 1048576.0 - ); - - // Meshing. - let mut mesher = Mesher { - nether_shading: false, - assets: &assets, - render: &render, - tables: &tables, - biomes: &biomes, - visibility: tables.visibility.clone(), - zoom: BiomeZoom::new(7), - blend_radius: 2, - smooth_lighting: true, - cutout_leaves: true, - cull_leaves: false, - }; - let mut best = f64::MAX; - let mut quads = 0usize; - for _ in 0..3 { - let started = Instant::now(); - let mut jobs = 0; - quads = 0; - for z in 2..inner { - for x in 2..inner { - let region: [[Option>; 3]; 3] = std::array::from_fn(|dz| { - std::array::from_fn(|dx| Some(at(x + dx as i32 - 1, z + dz as i32 - 1))) - }); - let borrowed = horizon_client::mesher::borrow(®ion); - for sy in 0..SECTIONS as i32 { - let mesh = mesher.mesh(&borrowed, sy); - quads += (mesh.solid.len() + mesh.translucent.len()) / 4; - jobs += 1; - } - } - } - best = best.min(started.elapsed().as_secs_f64() / f64::from(jobs)); - } - println!( - "mesh: {:.1} us per section ({} quads total)", - best * 1e6, - quads - ); - - // Random lookups, as collision and entity queries do. - let mut state = 0x9E37_79B9_7F4A_7C15u64; - let started = Instant::now(); - let mut sum = 0u64; - let lookups = 20_000_000u64; - for _ in 0..lookups { - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - let cx = 2 + (state % u64::from((inner - 2) as u32)) as i32; - let cz = 2 + ((state >> 8) % u64::from((inner - 2) as u32)) as i32; - let chunk = &chunks[((cz - 1) * inner + cx - 1) as usize]; - let (x, y, z) = ( - (state >> 16) as i32 & 15, - MIN_Y + ((state >> 24) % 384) as i32, - (state >> 40) as i32 & 15, - ); - sum += u64::from(chunk.get(x, y, z)); - } - println!( - "random get: {:.2} ns per lookup (checksum {sum})", - started.elapsed().as_secs_f64() * 1e9 / lookups as f64 - ); - // Coherent scan, as a column or area query does. - let started = Instant::now(); - let mut sum = 0u64; - for _ in 0..4 { - for chunk in &chunks { - for y in MIN_Y..MIN_Y + 384 { - for z in 0..16 { - for x in 0..16 { - sum += u64::from(chunk.get(x, y, z)); - } - } - } - } - } - println!( - "scan get: {:.2} ns per lookup (checksum {sum})", - started.elapsed().as_secs_f64() * 1e9 / (4.0 * chunks.len() as f64 * 98304.0) - ); - Ok(()) -} diff --git a/crates/horizon-client/examples/entity_geometry_bench.rs b/crates/horizon-client/examples/entity_geometry_bench.rs deleted file mode 100644 index 57104f58b..000000000 --- a/crates/horizon-client/examples/entity_geometry_bench.rs +++ /dev/null @@ -1,140 +0,0 @@ -//! Isolated production mob-model builder benchmark; no assets, Game, GPU or full-frame work. -//! CARGO_TARGET_DIR=/home/bob/Documents/horizon/target CARGO_INCREMENTAL=0 \ -//! cargo run --profile fast -p horizon-client --example entity_geometry_bench -use horizon_client::{ - mesher::Vertex, - mobs::{Part, Polygon, anim::Poses, render}, -}; -use std::{hint::black_box, time::Instant}; - -fn cube(name: String, position: f32) -> Part { - let polygons = (0..6) - .map(|face| { - let axis = face / 2; - let side = (face % 2) as f32; - let mut normal = [0.0; 3]; - normal[axis] = side * 2.0 - 1.0; - Polygon { - normal, - vertices: [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]].map(|uv| { - let mut vertex = [0.0; 5]; - vertex[axis] = side * 8.0; - vertex[(axis + 1) % 3] = uv[0] * 8.0; - vertex[(axis + 2) % 3] = uv[1] * 8.0; - vertex[3] = uv[0]; - vertex[4] = uv[1]; - vertex - }), - } - }) - .collect(); - Part { - name, - pose: [position, 0.0, 0.0, 0.1, 0.2, 0.0, 1.0, 1.0, 1.0], - polygons, - children: Vec::new(), - } -} - -fn build(model: &Part, poses: &Poses, count: usize, out: &mut Vec) { - for i in 0..count { - render::draw( - black_box(model), - glam::Mat4::from_translation(glam::Vec3::new((i % 32) as f32, 0.0, (i / 32) as f32)), - black_box(poses), - [0.125, 0.25, 0.5, 0.75], - 0xffc0_d0e0, - 0xf0f0, - 0, - out, - ); - } - black_box(out.as_slice()); -} - -fn measure(model: &Part, poses: &Poses, count: usize, iterations: usize, reuse: bool) -> f64 { - let mut retained = Vec::new(); - build(model, poses, count, &mut retained); // Untimed warmup. - let start = Instant::now(); - for _ in 0..iterations { - let mut out = if reuse { - std::mem::take(&mut retained) - } else { - Vec::new() - }; - out.clear(); - build(model, poses, count, &mut out); - if reuse { - retained = out; - } - } - start.elapsed().as_secs_f64() * 1e6 / iterations as f64 -} - -fn main() { - let mut model = cube("body".into(), 0.0); - model.children = (1..6).map(|i| cube(format!("part{i}"), i as f32)).collect(); - let poses = Poses::new(&model); - for count in [32, 256, 1024, 4096, 8192] { - let mut expected = Vec::new(); - build(&model, &poses, count, &mut expected); - let mut retained = Vec::new(); - build(&model, &poses, count, &mut retained); - let (pointer, capacity) = (retained.as_ptr(), retained.capacity()); - // Populated -> empty/reset -> smaller -> populated must never leave stale vertices. - for n in [0, count / 2, count, count] { - retained.clear(); - build(&model, &poses, n, &mut retained); - let mut fresh = Vec::new(); - build(&model, &poses, n, &mut fresh); - assert_eq!( - bytemuck::cast_slice::(&retained), - bytemuck::cast_slice::(&fresh) - ); - assert_eq!( - (retained.as_ptr(), retained.capacity()), - (pointer, capacity) - ); - } - assert_eq!( - bytemuck::cast_slice::(&retained), - bytemuck::cast_slice::(&expected) - ); - let iterations = (100_000 / count).clamp(40, 1000); - let mut fresh = Vec::new(); - let mut reused = Vec::new(); - let mut paired_speedups = Vec::new(); - // Alternate order, reporting medians over eleven warmed batches. - for batch in 0..11 { - let mut pair = [0.0; 2]; - for reuse in if batch % 2 == 0 { - [false, true] - } else { - [true, false] - } { - let time = measure(&model, &poses, count, iterations, reuse); - pair[usize::from(reuse)] = time; - if reuse { - reused.push(time); - } else { - fresh.push(time); - } - } - paired_speedups.push(pair[0] / pair[1]); - } - paired_speedups.sort_by(f64::total_cmp); - fresh.sort_by(f64::total_cmp); - reused.sort_by(f64::total_cmp); - println!( - "entities={count} vertices={} capacity={capacity} retained_bytes={} fresh_us={:.3} reused_us={:.3} speedup={:.3}x paired_speedup_median={:.3}x paired_speedup_range={:.3}..{:.3}x iterations={iterations} batches=11 byte_equivalence=pass pointer_capacity_reuse=pass", - retained.len(), - capacity * size_of::(), - fresh[5], - reused[5], - fresh[5] / reused[5], - paired_speedups[5], - paired_speedups[0], - paired_speedups[10] - ); - } -} diff --git a/crates/horizon-client/examples/json_readers_bench.rs b/crates/horizon-client/examples/json_readers_bench.rs deleted file mode 100644 index a9e370f0a..000000000 --- a/crates/horizon-client/examples/json_readers_bench.rs +++ /dev/null @@ -1,205 +0,0 @@ -//! Compare the exact read/deserialize sequences used by the model loaders. -//! Run with `cargo run -p horizon-client --profile fast --example json_readers_bench`. -//! Optional arguments: resource directory, repetitions (default 9). -use serde_json::{Map, Value, json}; -use std::{ - collections::BTreeMap, - fmt::Debug, - fs::{self, File}, - hint::black_box, - io::BufReader, - path::{Path, PathBuf}, - time::Instant, -}; - -type Result = horizon_client::Result; - -#[derive(Clone, Copy)] -enum Reader { - File, - Buffered, - Slice, -} -const READERS: [Reader; 3] = [Reader::File, Reader::Buffered, Reader::Slice]; - -// These match the map types and reader expressions at all three production sites. -macro_rules! reader { - ($name:ident, $map:ty) => { - fn $name(path: &Path, reader: Reader) -> Result<$map> { - Ok(match reader { - Reader::File => serde_json::from_reader(File::open(path)?)?, - Reader::Buffered => serde_json::from_reader(BufReader::new(File::open(path)?))?, - Reader::Slice => serde_json::from_slice(&fs::read(path)?)?, - }) - } - }; -} -reader!(prepare_facts, Map); -reader!(catalog_facts, BTreeMap); - -struct Fixture(PathBuf); -impl Fixture { - fn new() -> Result { - let root = - std::env::temp_dir().join(format!("horizon-json-readers-{}", std::process::id())); - fs::create_dir(&root)?; - Ok(Self(root)) - } -} -impl Drop for Fixture { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.0); - } -} - -fn fixtures(root: &Path) -> Result<()> { - let states: Vec<_> = (0..56) - .map(|i| { - json!({"facing": (["north", "east", "south", "west"][i % 4]), - "powered": if i / 4 % 2 == 0 { "false" } else { "true" }, - "age": (i / 8).to_string()}) - }) - .collect(); - let mut models = Map::new(); - let mut render = Map::new(); - for i in 0..1024 { - let name = format!("minecraft:fixture_block_{i:04}"); - models.insert( - name.clone(), - json!({ - "schema": {"facing": {"named": ["north", "east", "south", "west"]}, - "powered": {"named": ["false", "true"]}, "age": {"integer": [0, 6]}}, - "states": states - }), - ); - render.insert( - name, - json!({"rule": "never", "can_occlude": true, "bars_tag": false}), - ); - } - fs::write(root.join("model-states.json"), serde_json::to_vec(&models)?)?; - fs::write( - root.join("render-definitions.json"), - serde_json::to_vec(&render)?, - )?; - Ok(()) -} - -fn benchmark( - label: &str, - path: &Path, - repetitions: usize, - read: impl Fn(&Path, Reader) -> Result, -) -> Result<()> { - let expected = read(path, Reader::File)?; - for reader in READERS { - assert_eq!(expected, read(path, reader)?); - for _ in 0..2 { - black_box(read(black_box(path), reader)?); - } - } - drop(expected); - let mut samples: [Vec; 3] = std::array::from_fn(|_| Vec::new()); - for repetition in 0..repetitions { - // Rotate reader order to distribute drift across implementations. - for offset in 0..3 { - let index = (repetition + offset) % 3; - let start = Instant::now(); - let value = black_box(read(black_box(path), READERS[index])?); - samples[index].push(start.elapsed().as_secs_f64() * 1000.0); - drop(value); // Match the loaders: retain the parsed tree after loading. - } - } - let median: Vec<_> = samples - .iter_mut() - .map(|s| { - s.sort_by(f64::total_cmp); - s[s.len() / 2] - }) - .collect(); - println!( - "{label}: {} bytes, {repetitions} samples/reader, median ms: File={:.3}, BufReader={:.3}, read+slice={:.3}; slice speedup={:.2}x", - fs::metadata(path)?.len(), - median[0], - median[1], - median[2], - median[0] / median[2] - ); - Ok(()) -} - -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); - let fixture = if args.is_empty() { - Some(Fixture::new()?) - } else { - None - }; - let root = fixture - .as_ref() - .map(|f| f.0.clone()) - .unwrap_or_else(|| PathBuf::from(&args[0])); - if fixture.is_some() { - fixtures(&root)?; - println!( - "Generated representative fixtures: 1024 blocks, 57344 model states; warm filesystem cache." - ); - } - let repetitions = args.get(1).map(|s| s.parse()).transpose()?.unwrap_or(9); - assert!(repetitions > 0, "repetitions must be positive"); - benchmark( - "prepare model states", - &root.join("model-states.json"), - repetitions, - prepare_facts, - )?; - benchmark( - "catalog model states", - &root.join("model-states.json"), - repetitions, - catalog_facts, - )?; - benchmark( - "render definitions", - &root.join("render-definitions.json"), - repetitions, - catalog_facts, - ) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn reader_equivalence_and_errors() -> Result<()> { - let fixture = Fixture::new()?; - let path = fixture.0.join("test.json"); - fs::write(&path, br#"{"minecraft:stone":{"schema":{},"states":[{}]},"unicode":"\u2603","duplicate":1,"duplicate":2}"#)?; - let expected = prepare_facts(&path, Reader::File)?; - for reader in READERS { - assert_eq!(expected, prepare_facts(&path, reader)?); - assert_eq!( - expected.iter().collect::>(), - catalog_facts(&path, reader)?.iter().collect() - ); - } - for invalid in [b"{\"a\": ".as_slice(), b"{} trailing", b"{\"a\":\"\xff\"}"] { - fs::write(&path, invalid)?; - for reader in READERS { - let error = prepare_facts(&path, reader).unwrap_err(); - assert!(error.downcast_ref::().is_some()); - assert!(catalog_facts(&path, reader).is_err()); - } - } - fs::remove_file(&path)?; - for reader in READERS { - let error = prepare_facts(&path, reader).unwrap_err(); - assert_eq!( - error.downcast_ref::().unwrap().kind(), - std::io::ErrorKind::NotFound - ); - } - Ok(()) - } -} diff --git a/crates/horizon-client/examples/lan_flat.rs b/crates/horizon-client/examples/lan_flat.rs deleted file mode 100644 index f3dfea6b1..000000000 --- a/crates/horizon-client/examples/lan_flat.rs +++ /dev/null @@ -1,143 +0,0 @@ -//! Serve a small flat world on the LAN server without the game, for joining -//! with a real client while developing the protocol: -//! `cargo run --release --example lan_flat -- RESOURCES PORT`. -use horizon_client::{ - assets::Assets, - blocks::BlockFacts, - chunk::{Chunk, MIN_Y}, - lan::{ - Lan, - chunks::ChunkEncoder, - data::SyncData, - hub::{HostEvent, HostState, Hub, HubConfig, TickCtx}, - }, - world::World, -}; -use horizon_protocol::packets::play::Serverbound as S; -use std::{path::PathBuf, sync::Arc, time::Duration}; - -fn main() -> Result<(), Box> { - let mut args = std::env::args().skip(1); - let root = PathBuf::from(args.next().ok_or("RESOURCES PORT")?); - let port: u16 = args.next().ok_or("port")?.parse()?; - let assets = Assets::load(&root)?; - let facts = BlockFacts::load(&root, assets.registry)?; - let state = |name: &str| assets.registry.default_state(name).map_or(0, |s| s.0); - let sync = Arc::new(SyncData::load(&root)?); - let biomes: Vec = sync - .dynamic - .registries - .get("minecraft:worldgen/biome") - .map(|v| v.iter().map(|(n, _)| n.clone()).collect()) - .unwrap_or_default(); - let encoder = ChunkEncoder::new( - facts - .states - .iter() - .map(|s| (s.name.clone(), s.fluid_level > 0 || s.waterlogged)), - &sync.builtin, - &biomes, - &biomes, - ); - let (stone, dirt, grass) = ( - state("minecraft:stone"), - state("minecraft:dirt"), - state("minecraft:grass_block"), - ); - let mut world = World::new(facts.air, 0); - for cz in -8..=8 { - for cx in -8..=8 { - let mut chunk = Chunk::empty(cx, cz); - for z in 0..16 { - for x in 0..16 { - for y in MIN_Y..60 { - let v = if y == 59 { - grass - } else if y > 55 { - dirt - } else { - stone - }; - chunk.set(x, y, z, v); - } - } - } - chunk.lit = true; - world.chunks.insert((cx, cz), Arc::new(chunk)); - } - } - let lan = Lan::start(sync.clone(), port, "Flat - Example".into(), 8)?; - println!("listening on {}", lan.port); - let mut hub = Hub::new( - lan, - sync, - encoder, - HubConfig { - default_game_mode: 1, - guest_commands: true, - force_game_mode: false, - hardcore: false, - view_distance: 8, - simulation_distance: 8, - dimension: "minecraft:overworld".into(), - seed: 0, - max_players: 8, - dedicated: false, - integrated: false, - }, - ); - let mut next_entity = 100u32; - let host = HostState { - uuid: 42, - name: "Host".into(), - entity_id: 1, - position: [0.5, 60.0, 0.5], - yaw: 0.0, - pitch: 0.0, - head_yaw: 0.0, - on_ground: true, - game_mode: 1, - sneaking: false, - sprinting: false, - equipment: Default::default(), - health: 20.0, - attributes: Vec::new(), - bed: None, - living_flags: 0, - }; - loop { - world.game_time += 1; - world.day_time += 1; - let mut ctx = TickCtx { - world: &mut world, - host: Some(&host), - entities: &[], - next_entity: &mut next_entity, - spawn: [8.5, 60.0, 8.5], - difficulty: 2, - difficulty_locked: false, - clock_rate: 1.0, - tick_rate: 20.0, - tick_frozen: false, - tick_steps: (0, 0), - collision: None, - }; - for event in hub.tick(&mut ctx) { - match event { - HostEvent::Joined(conn) => hub.place_new_player(conn, &mut ctx), - HostEvent::Packet(_, packet) => { - if std::env::var_os("HORIZON_NET_DEBUG").is_some() - && !matches!(*packet, S::ClientTickEnd(_)) - { - eprintln!("[lan] {packet:?}"); - } - } - HostEvent::Chat { line, .. } | HostEvent::Warn(line) | HostEvent::Error(line) => { - println!("{line}") - } - HostEvent::Left(_) => {} - } - } - std::thread::sleep(Duration::from_millis(50)); - } -} diff --git a/crates/horizon-client/examples/load_bench.rs b/crates/horizon-client/examples/load_bench.rs deleted file mode 100644 index 5c30a71ff..000000000 --- a/crates/horizon-client/examples/load_bench.rs +++ /dev/null @@ -1,153 +0,0 @@ -//! Read-only saved chunk benchmark. All timings exclude resource/corpus setup. -//! -//! load_bench RESOURCES DIMENSION_DIR [--rounds N] [--limit N] [--checksum] -//! Add --profile-worker when a sampling collector cannot sample the main thread. -//! Reports warm filesystem SaveDir::load (read, inflate, NBT, decode and light), -//! plus isolated inflate/NBT and native decode. No files in the save are changed. -use horizon_client::{ - assets::Assets, - biome::Biomes, - blocks::BlockFacts, - save::{SaveDir, SaveTables, decode_with}, -}; -use horizon_world::{nbt::Limits, region::RegionFile}; -use sha2::{Digest, Sha256}; -use std::{hint::black_box, path::PathBuf, sync::Arc, time::Instant}; - -type Result = std::result::Result>; - -fn main() -> Result<()> { - if std::env::args().any(|a| a == "--profile-worker") { - std::thread::spawn(|| run().map_err(|e| e.to_string())) - .join() - .expect("benchmark worker") - .map_err(Into::into) - } else { - run() - } -} - -fn run() -> Result<()> { - let args: Vec = std::env::args().skip(1).collect(); - let usage = "load_bench RESOURCES DIMENSION_DIR [--rounds N] [--limit N] [--checksum]"; - let root = PathBuf::from(args.first().ok_or(usage)?); - let dimension = PathBuf::from(args.get(1).ok_or(usage)?); - let flag = |name: &str, default: usize| -> Result { - Ok(match args.iter().position(|a| a == name) { - Some(i) => args.get(i + 1).ok_or(usage)?.parse()?, - None => default, - }) - }; - let rounds = flag("--rounds", 5)?; - let limit = flag("--limit", 256)?; - if rounds == 0 || limit == 0 { - return Err("rounds and limit must be positive".into()); - } - let assets = Assets::load(&root)?; - let facts = BlockFacts::load(&root, assets.registry)?; - let biomes = Biomes::load(&root)?; - let tables = Arc::new(SaveTables::new(&assets).with_block_entities(&facts)); - let source = SaveDir::new(dimension.clone()); - let _ = source.tables.set(tables.clone()); - let mut paths: Vec<_> = std::fs::read_dir(dimension.join("region"))? - .map(|e| e.map(|e| e.path())) - .collect::>()?; - paths.retain(|p| p.extension().is_some_and(|e| e == "mca")); - paths.sort(); - let mut corpus = Vec::new(); - 'regions: for path in paths { - let mut region = RegionFile::open(path)?; - let mut positions: Vec<_> = region.chunks().map(|(pos, _)| pos).collect(); - positions.sort_by_key(|p| (p.x, p.z)); - for pos in positions { - let record = region.read(pos)?.ok_or("missing record")?; - let tag = record.nbt(Limits::default())?; - if decode_with(&tag, assets.registry, &biomes, Some(&tables)).is_none() { - continue; - } - corpus.push((pos, record, tag)); - if corpus.len() == limit { - break 'regions; - } - } - } - if corpus.is_empty() { - return Err("no full chunks in corpus".into()); - } - let mut records_hash = Sha256::new(); - for (pos, record, _) in &corpus { - records_hash.update(pos.x.to_le_bytes()); - records_hash.update(pos.z.to_le_bytes()); - records_hash.update((record.compressed.len() as u64).to_le_bytes()); - records_hash.update(&record.compressed); - } - println!( - "{}", - serde_json::json!({"corpus": dimension, "chunks": corpus.len(), "rounds": rounds, - "compressed_records_sha256": format!("{:x}", records_hash.finalize()), - "compressed_bytes": corpus.iter().map(|(_, r, _)| r.compressed.len()).sum::()}) - ); - // Prime SaveDir's region handles and the filesystem cache before measurement. - for (pos, _, _) in &corpus { - black_box( - source - .load(pos.x, pos.z, assets.registry, &biomes) - .ok_or("load failed")?, - ); - } - for round in 0..rounds { - let started = Instant::now(); - for (pos, _, _) in &corpus { - black_box( - source - .load(pos.x, pos.z, assets.registry, &biomes) - .ok_or("load failed")?, - ); - } - let load_s = started.elapsed().as_secs_f64(); - let started = Instant::now(); - for (_, record, _) in &corpus { - black_box(record.nbt(Limits::default())?); - } - let nbt_s = started.elapsed().as_secs_f64(); - let started = Instant::now(); - for (_, _, tag) in &corpus { - black_box( - decode_with(tag, assets.registry, &biomes, Some(&tables)).ok_or("decode failed")?, - ); - } - let decode_s = started.elapsed().as_secs_f64(); - println!( - "{}", - serde_json::json!({"round": round, "load_s": load_s, - "inflate_nbt_s": nbt_s, "decode_s": decode_s}) - ); - } - if args.iter().any(|a| a == "--checksum") { - let mut hash = Sha256::new(); - let mut light_loaded = 0; - for (pos, _, _) in &corpus { - let chunk = source - .load(pos.x, pos.z, assets.registry, &biomes) - .ok_or("load failed")?; - hash.update(pos.x.to_le_bytes()); - hash.update(pos.z.to_le_bytes()); - light_loaded += usize::from(chunk.light_loaded); - for section in &chunk.sections { - for i in 0..4096 { - hash.update(section.get(i).to_le_bytes()); - hash.update([section.light(i)]); - } - for i in 0..64 { - hash.update(section.biomes.get(i).to_le_bytes()); - } - } - } - println!( - "{}", - serde_json::json!({"blocks_biomes_light_sha256": format!("{:x}", hash.finalize()), - "light_loaded": light_loaded}) - ); - } - Ok(()) -} diff --git a/crates/horizon-client/examples/save_bench.rs b/crates/horizon-client/examples/save_bench.rs deleted file mode 100644 index 30625be65..000000000 --- a/crates/horizon-client/examples/save_bench.rs +++ /dev/null @@ -1,128 +0,0 @@ -//! The region writer on real chunks, without a window: how long a world's -//! chunks take to be encoded, compressed and written by `SaveDir`, against -//! the same encoding and compression done one chunk after another (what the -//! writer thread did alone before it had helpers). -//! -//! save_bench RESOURCES DIMENSION_DIR [--rounds N] -//! -//! DIMENSION_DIR is a saved dimension folder (`saves/W/dimensions/minecraft/ -//! overworld`); its chunks are read once, then each round saves them all into -//! a scratch folder with `save_later` + `flush`, and times the one-thread -//! baseline. The written chunks are checked byte for byte against the -//! baseline's compressed records. -use horizon_client::{ - assets::Assets, - biome::Biomes, - blocks::BlockFacts, - save::{SaveDir, SaveTables, encode_with}, -}; -use horizon_core::position::ChunkPos; -use horizon_world::{ - compression::Compression, - nbt::Limits, - region::{ChunkRecord, RegionFile}, -}; -use std::{path::PathBuf, sync::Arc, time::Instant}; - -type Result = std::result::Result>; - -fn main() -> Result<()> { - let args: Vec = std::env::args().skip(1).collect(); - let usage = "usage: save_bench RESOURCES DIMENSION_DIR [--rounds N]"; - let root = PathBuf::from(args.first().ok_or(usage)?); - let dimension = PathBuf::from(args.get(1).ok_or(usage)?); - let rounds: usize = args - .iter() - .position(|a| a == "--rounds") - .and_then(|i| args.get(i + 1)) - .and_then(|v| v.parse().ok()) - .unwrap_or(5); - - let assets = Assets::load(&root)?; - let facts = BlockFacts::load(&root, assets.registry)?; - let biomes = Arc::new(Biomes::load(&root)?); - let tables = Arc::new(SaveTables::new(&assets).with_block_entities(&facts)); - let registry = assets.registry; - - let source = SaveDir::new(dimension.clone()); - let _ = source.tables.set(tables.clone()); - let mut chunks = Vec::new(); - for entry in std::fs::read_dir(dimension.join("region"))? { - let path = entry?.path(); - if path.extension().is_none_or(|e| e != "mca") { - continue; - } - let region = RegionFile::open(&path)?; - for (pos, _) in region.chunks() { - if let Some(chunk) = source.load(pos.x, pos.z, registry, &biomes) { - chunks.push(Arc::new(chunk)); - } - } - } - chunks.sort_by_key(|c| (c.x, c.z)); - println!("{} chunks from {}", chunks.len(), dimension.display()); - - let scratch = std::env::temp_dir().join(format!("save_bench_{}", std::process::id())); - // Encoding and compressing on one thread (what the writer did alone), - // then SaveDir's writer with its helpers. - let mut times = [Vec::new(), Vec::new(), Vec::new()]; - let mut written = Vec::new(); - for round in 0..rounds { - let started = Instant::now(); - let tags: Vec<_> = chunks - .iter() - .map(|c| encode_with(c, registry, &biomes, Some(&tables), true)) - .collect(); - times[0].push(started.elapsed().as_secs_f64()); - let started = Instant::now(); - let baseline: Vec = tags - .iter() - .map(|tag| ChunkRecord::from_nbt(tag, Compression::Zlib, 0, Limits::default())) - .collect::>()?; - times[1].push(started.elapsed().as_secs_f64()); - drop(tags); - - let _ = std::fs::remove_dir_all(&scratch); - let save = SaveDir::new(scratch.clone()); - let _ = save.tables.set(tables.clone()); - let started = Instant::now(); - save.save_later(&chunks, registry, &biomes)?; - save.flush().unwrap(); - times[2].push(started.elapsed().as_secs_f64()); - drop(save); - - if round == 0 { - for (chunk, want) in chunks.iter().zip(&baseline) { - let path = scratch.join(format!("region/r.{}.{}.mca", chunk.x >> 5, chunk.z >> 5)); - let got = RegionFile::open(&path)? - .read(ChunkPos::new(chunk.x, chunk.z))? - .ok_or("a saved chunk is missing")?; - if got.compressed != want.compressed { - return Err(format!("chunk {} {} differs", chunk.x, chunk.z).into()); - } - } - written = baseline.iter().map(|r| r.compressed.len()).collect(); - } - } - let _ = std::fs::remove_dir_all(&scratch); - println!( - "{} KiB compressed, identical to the one-thread records", - written.iter().sum::() / 1024 - ); - let per_chunk = 1000.0 / chunks.len() as f64; - let names = [ - "one thread: encode", - "one thread: compress", - "SaveDir (encode, compress, write)", - ]; - for (name, t) in names.iter().zip(&mut times) { - t.sort_by(f64::total_cmp); - println!( - "{name}: best {:.0} ms, median {:.0} ms of {rounds} ({:.3} ms per chunk at best)", - t[0] * 1000.0, - t[t.len() / 2] * 1000.0, - t[0] * per_chunk - ); - } - Ok(()) -} diff --git a/crates/horizon-client/examples/save_parity.rs b/crates/horizon-client/examples/save_parity.rs deleted file mode 100644 index 3954e3bb3..000000000 --- a/crates/horizon-client/examples/save_parity.rs +++ /dev/null @@ -1,265 +0,0 @@ -//! Differential save test: load every full chunk of a world written by the -//! vanilla 26.3 server, light it, encode it again with Horizon's chunk writer -//! and compare the result with the original NBT: block states, biomes, -//! heightmaps, light layers (by value), block entities and scheduled ticks. -//! -//! cargo run --profile fast -p horizon-client --example save_parity -- \ -//! RESOURCES DIMENSION_DIR [--nether] -use horizon_client::{ - assets::Assets, - biome::Biomes, - blocks::BlockFacts, - chunk::{Chunk, MIN_Y, SECTIONS}, - light::{LightTables, apply_lighting, light_chunk}, - save::{self, SaveTables}, -}; -use horizon_core::position::ChunkPos; -use horizon_world::{ - chunk::BlockState, - nbt::{Limits, NamedTag, Tag}, - region::RegionFile, -}; -use std::{ - collections::{BTreeMap, HashMap}, - path::PathBuf, -}; - -/// Block state names per section index, decoded independently of Horizon. -fn block_names(tag: &Tag) -> BTreeMap> { - let mut out = BTreeMap::new(); - let Some(Tag::List(sections)) = tag.get("sections") else { - return out; - }; - for s in sections { - let Some(Tag::Byte(y)) = s.get("Y") else { - continue; - }; - let Some(states) = s.get("block_states") else { - continue; - }; - let Some(Tag::List(palette)) = states.get("palette") else { - continue; - }; - let names: Vec = palette - .iter() - .map(|p| { - let st = BlockState::from_nbt(p).expect("palette entry"); - format!("{}{:?}", st.name, st.properties) - }) - .collect(); - let bits = (usize::BITS - (names.len().max(1) - 1).leading_zeros()).max(4); - let per = 64 / bits as usize; - let data = match states.get("data") { - Some(Tag::LongArray(d)) => d.clone(), - _ => Vec::new(), - }; - let blocks = (0..4096) - .map(|i| { - if names.len() == 1 { - return names[0].clone(); - } - let v = (data[i / per] as u64 >> ((i % per) as u32 * bits)) & ((1 << bits) - 1); - names[v as usize].clone() - }) - .collect(); - out.insert(i64::from(*y), blocks); - } - out -} -fn light(tag: &Tag, key: &str) -> HashMap> { - let mut out = HashMap::new(); - if let Some(Tag::List(sections)) = tag.get("sections") { - for s in sections { - if let (Some(Tag::Byte(y)), Some(Tag::ByteArray(a))) = (s.get("Y"), s.get(key)) { - out.insert(i64::from(*y), a.clone()); - } - } - } - out -} -/// Light value with vanilla's reading of missing layers. -fn value( - layers: &HashMap>, - sy: i64, - i: usize, - sky: bool, - empty: bool, - top: i64, -) -> u8 { - let nibble = |a: &Vec, i: usize| (a[i >> 1] >> ((i & 1) * 4)) & 15; - if let Some(a) = layers.get(&sy) { - return nibble(a, i); - } - if !sky || !empty { - return 0; - } - ((sy + 1)..=top) - .find_map(|y| layers.get(&y)) - .map_or(15, |a| nibble(a, i & 255)) -} -fn count(tag: &Tag, key: &str) -> usize { - match tag.get(key) { - Some(Tag::List(l)) => l.len(), - _ => 0, - } -} - -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().skip(1).collect(); - let root = PathBuf::from( - args.first() - .ok_or("usage: save_parity RESOURCES DIMENSION_DIR")?, - ); - let dim = PathBuf::from(args.get(1).ok_or("missing dimension directory")?); - let sky_light = !args.iter().any(|a| a == "--nether"); - let assets = Assets::load(&root)?; - let facts = BlockFacts::load(&root, assets.registry)?; - let biomes = Biomes::load(&root)?; - let lights = LightTables::load(&root, assets.registry, &facts)?; - let tables = SaveTables::new(&assets).with_block_entities(&facts); - let mut originals: HashMap<(i32, i32), NamedTag> = HashMap::new(); - let mut chunks: HashMap<(i32, i32), Chunk> = HashMap::new(); - for entry in std::fs::read_dir(dim.join("region"))? { - let mut region = RegionFile::open(entry?.path())?; - let positions: Vec = region.chunks().map(|(p, _)| p).collect(); - for p in positions { - let Some(record) = region.read(p)? else { - continue; - }; - let tag = record.nbt(Limits::default())?; - if tag.tag.get("isLightOn") != Some(&Tag::Byte(1)) { - continue; - } - if let Some(c) = save::decode_with(&tag, assets.registry, &biomes, Some(&tables)) { - chunks.insert((c.x, c.z), c); - originals.insert((p.x, p.z), tag); - } - } - } - let mut keys: Vec<_> = chunks - .keys() - .copied() - .filter(|&(x, z)| { - (-1..=1).all(|dz| (-1..=1).all(|dx| chunks.contains_key(&(x + dx, z + dz)))) - }) - .collect(); - keys.sort_unstable(); - let ( - mut blocks_bad, - mut biomes_bad, - mut heightmaps_bad, - mut light_bad, - mut light_total, - mut other_bad, - ) = (0, 0, 0, 0u64, 0u64, 0); - for &(x, z) in &keys { - let region: [[Option<&Chunk>; 3]; 3] = std::array::from_fn(|dz| { - std::array::from_fn(|dx| chunks.get(&(x + dx as i32 - 1, z + dz as i32 - 1))) - }); - let mut chunk = chunks[&(x, z)].clone(); - apply_lighting(&mut chunk, light_chunk(®ion, &lights, sky_light)); - chunk.lit = true; - let ours = save::encode_with(&chunk, assets.registry, &biomes, Some(&tables), sky_light); - let theirs = &originals[&(x, z)]; - let (a, b) = (&ours.tag, &theirs.tag); - // Block states: compare every non-empty vanilla section. - let (na, nb) = (block_names(a), block_names(b)); - for (y, vb) in &nb { - match na.get(y) { - Some(va) if va == vb => {} - Some(va) => { - let n = va.iter().zip(vb).filter(|(p, q)| p != q).count(); - if blocks_bad < 5 { - let i = va.iter().zip(vb).position(|(p, q)| p != q).unwrap_or(0); - eprintln!( - "chunk {x} {z} section {y}: {n} blocks differ, e.g. {} vs {}", - va[i], vb[i] - ); - } - blocks_bad += 1; - } - None if vb.iter().all(|s| s.starts_with("minecraft:air")) => {} - None => blocks_bad += 1, - } - } - let biome_of = |t: &Tag| -> Vec { - match t.get("sections") { - Some(Tag::List(l)) => l.iter().filter_map(|s| s.get("biomes").cloned()).collect(), - _ => Vec::new(), - } - }; - if biome_of(a) != biome_of(b) { - biomes_bad += 1; - } - for kind in [ - "WORLD_SURFACE", - "OCEAN_FLOOR", - "MOTION_BLOCKING", - "MOTION_BLOCKING_NO_LEAVES", - ] { - let get = |t: &Tag| t.get("Heightmaps").and_then(|h| h.get(kind)).cloned(); - if get(a) != get(b) { - if heightmaps_bad < 5 { - eprintln!("chunk {x} {z}: heightmap {kind} differs"); - } - heightmaps_bad += 1; - } - } - for (key, sky) in [("SkyLight", true), ("BlockLight", false)] { - if sky && !sky_light { - continue; - } - let (la, lb) = (light(a, key), light(b, key)); - let top = i64::from((MIN_Y >> 4) + SECTIONS as i32); - for si in 0..SECTIONS { - let sy = i64::from((MIN_Y >> 4) + si as i32); - let empty = chunk.sections[si].is_uniform(tables_air(&assets)); - for i in 0..4096 { - light_total += 1; - if value(&la, sy, i, sky, empty, top) != value(&lb, sy, i, sky, empty, top) { - light_bad += 1; - } - } - } - } - for key in ["block_entities", "block_ticks", "fluid_ticks"] { - if count(a, key) != count(b, key) { - if other_bad < 5 { - eprintln!( - "chunk {x} {z}: {key} {} vs {}", - count(a, key), - count(b, key) - ); - } - other_bad += 1; - } - } - for key in [ - "structures", - "PostProcessing", - "InhabitedTime", - "Status", - "DataVersion", - "yPos", - ] { - if a.get(key) != b.get(key) { - if other_bad < 5 { - eprintln!("chunk {x} {z}: {key} differs"); - } - other_bad += 1; - } - } - } - println!( - "{} chunks: {blocks_bad} sections with different blocks, {biomes_bad} chunks with different biomes, \ - {heightmaps_bad} different heightmaps, {light_bad} of {light_total} light values differ, {other_bad} other differences", - keys.len() - ); - Ok(()) -} -fn tables_air(assets: &Assets) -> u32 { - assets - .registry - .default_state("minecraft:air") - .map_or(0, |s| s.0) -} diff --git a/crates/horizon-client/examples/streaming_bench.rs b/crates/horizon-client/examples/streaming_bench.rs deleted file mode 100644 index b8c56b28c..000000000 --- a/crates/horizon-client/examples/streaming_bench.rs +++ /dev/null @@ -1,284 +0,0 @@ -//! The chunk pipeline (generation, decoration, lighting, meshing) on its worker -//! pool, without a window: how fast a render distance fills with N workers, and -//! what the render thread pays for it in `Streaming::update`. -//! -//! streaming_bench RESOURCES [--threads N] [--radius R] [--seed S] [--fly CHUNKS_PER_S] [--seconds T] [--hz F] -//! [--dimension overworld|the_nether|the_end] [--center-x X] [--center-z Z] -//! -//! First the area around (0, 0) fills; then, with `--fly`, the centre moves along +x -//! at that speed for T seconds while frames run at F per second. Each phase reports -//! its wall time, chunks generated and sections meshed, and the time `update` -//! took on the calling thread (the render thread in the game): total, median, -//! p99 and slowest. Compile with HORIZON_BENCH_COUNT_ALLOCATIONS=1 to count the -//! allocations made on the calling thread during updates and by everything. -use horizon_client::{ - assets::Assets, - biome::Biomes, - blocks::BlockFacts, - light::LightTables, - mesher::MeshTables, - models, - streaming::{Streaming, WorkerContext}, - vanillagen::VanillaTerrain, - world::World, -}; -use std::{ - alloc::{GlobalAlloc, Layout, System}, - cell::Cell, - path::PathBuf, - sync::{ - Arc, - atomic::{AtomicU64, Ordering::Relaxed}, - }, - time::{Duration, Instant}, -}; - -const TRACK: bool = option_env!("HORIZON_BENCH_COUNT_ALLOCATIONS").is_some(); -static ALLOCATIONS: AtomicU64 = AtomicU64::new(0); -static BYTES: AtomicU64 = AtomicU64::new(0); -thread_local! { - static LOCAL: Cell<(u64, u64)> = const { Cell::new((0, 0)) }; -} -fn count(size: usize) { - if TRACK { - ALLOCATIONS.fetch_add(1, Relaxed); - BYTES.fetch_add(size as u64, Relaxed); - let _ = LOCAL.try_with(|c| { - let (n, b) = c.get(); - c.set((n + 1, b + size as u64)); - }); - } -} -struct CountingAllocator; -// Delegates every operation and layout unchanged to System. -unsafe impl GlobalAlloc for CountingAllocator { - unsafe fn alloc(&self, layout: Layout) -> *mut u8 { - count(layout.size()); - unsafe { System.alloc(layout) } - } - unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { - count(layout.size()); - unsafe { System.alloc_zeroed(layout) } - } - unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { - unsafe { System.dealloc(ptr, layout) }; - } - unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, size: usize) -> *mut u8 { - count(size); - unsafe { System.realloc(ptr, layout, size) } - } -} -#[global_allocator] -static ALLOCATOR: CountingAllocator = CountingAllocator; - -type Result = std::result::Result>; - -fn cpu_seconds() -> f64 { - std::fs::read_to_string("/proc/self/stat") - .ok() - .and_then(|stat| { - let fields = stat - .rsplit_once(')')? - .1 - .split_whitespace() - .collect::>(); - Some((fields[11].parse::().ok()? + fields[12].parse::().ok()?) / 100.0) - }) - .unwrap_or(0.0) -} - -#[derive(Default)] -struct Phase { - updates: Vec, - local: (u64, u64), - uploads: usize, - stage_samples: [u64; 7], - cpu_start: f64, -} -impl Phase { - fn update(&mut self, streaming: &mut Streaming, world: &mut World) { - if self.updates.is_empty() { - self.cpu_start = cpu_seconds(); - } - let before = LOCAL.with(Cell::get); - let started = Instant::now(); - let (uploads, _) = streaming.update(world); - self.updates.push(started.elapsed().as_secs_f64() * 1e3); - let after = LOCAL.with(Cell::get); - self.local.0 += after.0 - before.0; - self.local.1 += after.1 - before.1; - self.uploads += uploads.len(); - drop(uploads); - for (sum, (_, count)) in self.stage_samples.iter_mut().zip(streaming.stages()) { - *sum += count as u64; - } - } - fn report(&self, name: &str, wall: Duration, streaming: &Streaming, generated: u64) { - let mut sorted = self.updates.clone(); - sorted.sort_by(f64::total_cmp); - let at = |p: f64| sorted[((sorted.len() as f64 * p) as usize).min(sorted.len() - 1)]; - let total: f64 = sorted.iter().sum(); - println!( - "{name}: {:.2} s, {} chunks generated, {} sections meshed; update {:.1} ms total over {} calls, p50 {:.3} p99 {:.3} max {:.2} ms", - wall.as_secs_f64(), - streaming.generated_total - generated, - self.uploads, - total, - sorted.len(), - at(0.5), - at(0.99), - sorted.last().copied().unwrap_or(0.0), - ); - println!( - "BENCH {}", - serde_json::json!({ - "phase": name, "wall_s": wall.as_secs_f64(), - "cpu_s": cpu_seconds() - self.cpu_start, - "chunks": streaming.generated_total - generated, "sections": self.uploads, - "updates": self.updates.len(), "update_ms": total, - "mean_stages": self.stage_samples.map(|n| n as f64 / self.updates.len() as f64), - }) - ); - if TRACK { - println!( - " update allocations: {} ({:.1} MiB)", - self.local.0, - self.local.1 as f64 / 1048576.0 - ); - } - } -} - -/// Nothing queued or in flight. Sections at the edge of the area stay dirty -/// (their outer neighbours are never lit), so they don't count. -fn settled(streaming: &Streaming) -> bool { - streaming - .stages() - .iter() - .all(|&(name, n)| name == "protos" || n == 0) -} - -fn main() -> Result<()> { - let args: Vec = std::env::args().skip(1).collect(); - let root = PathBuf::from(args.first().ok_or("usage: streaming_bench RESOURCES")?); - let flag = |name: &str, default: f64| -> f64 { - args.iter() - .position(|a| a == name) - .and_then(|i| args.get(i + 1)) - .and_then(|v| v.parse().ok()) - .unwrap_or(default) - }; - let auto = std::thread::available_parallelism().map_or(2, |n| n.get() - 1); - let threads = flag("--threads", auto as f64) as usize; - let radius = flag("--radius", 8.0) as i32; - let seed = flag("--seed", 1234.0) as i64; - let fly = flag("--fly", 0.0); - let seconds = flag("--seconds", 10.0); - let hz = flag("--hz", 240.0); - let dimension = args - .iter() - .position(|a| a == "--dimension") - .and_then(|i| args.get(i + 1)) - .map(|d| { - if d.contains(':') { - d.clone() - } else { - format!("minecraft:{d}") - } - }) - .unwrap_or_else(|| "minecraft:overworld".into()); - let center = ( - flag("--center-x", 0.0) as i32, - flag("--center-z", 0.0) as i32, - ); - - let assets = Arc::new(Assets::load(&root)?); - let render = Arc::new(assets.reload(&root)?); - let facts = BlockFacts::load(&root, assets.registry)?; - let biomes = Arc::new(Biomes::load(&root)?); - let tables = Arc::new(MeshTables::new( - &assets, - &render, - &facts, - models::load_visibility(&root, assets.registry)?, - )?); - let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?); - let terrain = Arc::new(VanillaTerrain::for_dimension( - &root.join("worldgen"), - assets.registry, - &biomes, - seed, - &dimension, - )?); - let context = Arc::new(WorkerContext { - assets, - render: render.clone(), - tables, - biomes, - light, - }); - let mut world = World::new(facts.air, seed); - let mut streaming = Streaming::new(terrain, context, threads); - streaming.radius = radius; - streaming.center = center; - streaming.nether_shading = dimension == "minecraft:the_nether"; - streaming.sky_light = dimension != "minecraft:the_nether"; - println!( - "{threads} workers, radius {radius}, seed {seed}, dimension {dimension}, center {center:?}" - ); - let (allocations, bytes) = (ALLOCATIONS.load(Relaxed), BYTES.load(Relaxed)); - - // Fill: update as often as the game would uncapped, until settled. - let mut phase = Phase::default(); - let started = Instant::now(); - let mut quiet = 0; - while quiet < 20 { - let uploads = phase.uploads; - phase.update(&mut streaming, &mut world); - quiet = if settled(&streaming) && phase.uploads == uploads { - quiet + 1 - } else { - 0 - }; - std::thread::sleep(Duration::from_micros(500)); - } - phase.report("fill", started.elapsed(), &streaming, 0); - - if fly > 0.0 { - let mut phase = Phase::default(); - let generated = streaming.generated_total; - let frame = Duration::from_secs_f64(1.0 / hz); - let started = Instant::now(); - let mut behind = Vec::new(); - while started.elapsed().as_secs_f64() < seconds { - let next = Instant::now() + frame; - let x = center.0 + (started.elapsed().as_secs_f64() * fly) as i32; - streaming.center = (x, center.1); - phase.update(&mut streaming, &mut world); - // Columns within 2 chunks of the player still missing their meshes. - let near = (-2..=2) - .flat_map(|dz| (-2..=2).map(move |dx| (x + dx, center.1 + dz))) - .filter(|&(cx, cz)| !streaming.is_lit(cx, cz)) - .count(); - behind.push(near); - if let Some(wait) = next.checked_duration_since(Instant::now()) { - std::thread::sleep(wait); - } - } - phase.report("fly", started.elapsed(), &streaming, generated); - let unlit = behind.iter().filter(|&&n| n > 0).count(); - println!( - " frames with an unlit column within 2 chunks of the player: {unlit} of {} ({:.1}%)", - behind.len(), - unlit as f64 * 100.0 / behind.len().max(1) as f64 - ); - } - if TRACK { - println!( - "all threads: {} allocations ({:.1} MiB)", - ALLOCATIONS.load(Relaxed) - allocations, - (BYTES.load(Relaxed) - bytes) as f64 / 1048576.0 - ); - } - Ok(()) -} diff --git a/crates/horizon-client/examples/tick_chunk_membership_bench.rs b/crates/horizon-client/examples/tick_chunk_membership_bench.rs deleted file mode 100644 index 6b9cb8a0a..000000000 --- a/crates/horizon-client/examples/tick_chunk_membership_bench.rs +++ /dev/null @@ -1,143 +0,0 @@ -//! Resident-key synchronization used by Game (registration callback work excluded). -//! Run: CARGO_INCREMENTAL=0 cargo run -p horizon-client --profile fast --example tick_chunk_membership_bench -use horizon_client::{ - chunk::Chunk, chunk_map::ChunkMap, tick_chunk_membership::TickChunkMembership, -}; -use std::{collections::HashSet, hint::black_box, sync::Arc, time::Instant}; - -type Key = (i32, i32); -#[derive(Default)] -struct Old { - keys: HashSet, -} -impl Old { - fn sync(&mut self, map: &ChunkMap) -> (usize, usize) { - let loaded: HashSet<_> = map.keys().copied().collect(); - let mut counts = (0, 0); - for key in loaded.difference(&self.keys.clone()) { - black_box(key); - counts.0 += 1; - } - for key in self.keys.difference(&loaded) { - black_box(key); - counts.1 += 1; - } - self.keys = loaded; - counts - } -} -fn new_sync(cache: &mut TickChunkMembership, map: &ChunkMap) -> (usize, usize) { - if !cache.synchronize(map) { - return (0, 0); - } - let added = cache.take_added(); - for key in &added { - black_box(key); - } - for key in cache.removed() { - black_box(key); - } - let counts = (added.len(), cache.removed().len()); - cache.recycle_added(added); - counts -} -fn map(offset: i32) -> ChunkMap { - let mut map = ChunkMap::default(); - // Share a payload: the synchronization path reads only keys, not block data. - let chunk = Arc::new(Chunk::empty(0, 0)); - for x in -16..=16 { - for z in -16..=16 { - map.insert((x + offset, z), chunk.clone()); - } - } - map -} -fn run(new: bool, scenario: usize, iterations: usize) -> (f64, (usize, usize)) { - let mut a = map(0); - let b = map(33); - let chunk = Arc::new(Chunk::empty(0, 0)); - let mut old = Old::default(); - let mut cache = TickChunkMembership::default(); - for _ in 0..64 { - if new { - black_box(new_sync(&mut cache, &a)); - } else { - black_box(old.sync(&a)); - } - } - let mut total = (0, 0); - let start = Instant::now(); - for i in 0..iterations { - let resident = match scenario { - 0 => &a, - 1 => { - let (previous, next) = if i % 2 == 0 { - ((-16, -16), (-17, -16)) - } else { - ((-17, -16), (-16, -16)) - }; - a.remove(&previous); - a.insert(next, chunk.clone()); - &a - } - 2 => { - if i % 2 == 0 { - &b - } else { - &a - } - } - _ => unreachable!(), - }; - let counts = if new { - new_sync(black_box(&mut cache), black_box(resident)) - } else { - old.sync(black_box(resident)) - }; - total.0 += counts.0; - total.1 += counts.1; - } - ( - start.elapsed().as_secs_f64() * 1e9 / iterations as f64, - black_box(total), - ) -} -fn main() { - println!("1089 keys, 64 warmup calls, 9 samples; ns/sync, median"); - for (scenario, name, iterations) in [ - (0, "stable", 10_000), - (1, "one-key same-count replacement", 2_000), - (2, "whole-map replacement", 1_000), - ] { - let mut before = Vec::new(); - let mut after = Vec::new(); - for sample in 0..9 { - let (old, new) = if sample % 2 == 0 { - ( - run(false, scenario, iterations), - run(true, scenario, iterations), - ) - } else { - let new = run(true, scenario, iterations); - (run(false, scenario, iterations), new) - }; - assert_eq!(old.1, new.1); - let expected = match scenario { - 0 => (0, 0), - 1 => (iterations, iterations), - _ => (1089 * iterations, 1089 * iterations), - }; - assert_eq!(new.1, expected); - before.push(old.0); - after.push(new.0); - } - before.sort_by(f64::total_cmp); - after.sort_by(f64::total_cmp); - println!( - "{name}: {:.1} -> {:.1} ns, {:.2}x; {iterations} iterations/sample", - before[4], - after[4], - before[4] / after[4] - ); - } -} diff --git a/crates/horizon-world/examples/vanilla_diff.rs b/crates/horizon-world/examples/vanilla_diff.rs deleted file mode 100644 index 52eb77737..000000000 --- a/crates/horizon-world/examples/vanilla_diff.rs +++ /dev/null @@ -1,441 +0,0 @@ -//! Differential check of decorated chunks against a vanilla world. -//! -//! vanilla_diff --seed S -//! [--dimension minecraft:overworld] [--from CX CZ] [--size N] -//! [--threads T] [--show FROM->TO] [--limit N] [--reverse] [--shuffle SEED] -//! [--other ] -//! -//! Generates an (N+4)² chunk area with the Rust pipeline, decorates the inner -//! (N+2)² chunks (vanilla FEATURES writes reach one neighbor) and compares the -//! N² chunks starting at (CX, CZ) block by block with the region files of a -//! vanilla world generated for the same seed (with ticks frozen, see -//! docs/parity/worldgen.md). Prints mismatches grouped by vanilla → Rust block. -use horizon_core::position::{BlockPos, ChunkPos}; -use horizon_world::{ - DATA_VERSION, - chunk::{BlockSection, BlockState, ChunkData}, - nbt::{Limits, Tag}, - region::RegionFile, - registry::BlockRegistry, - worldgen::generator::{GeneratorData, OverworldGenerator, ProtoChunk}, -}; -use serde_json::Value; -use std::{ - collections::{BTreeMap, HashMap}, - fs, - path::{Path, PathBuf}, - sync::{ - Mutex, - atomic::{AtomicUsize, Ordering}, - }, -}; - -type Error = Box; - -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - Value::Object(o) => { - Tag::Compound(o.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - _ => panic!("invalid registry metadata"), - } -} - -fn registry(resources: &Path) -> Result<&'static BlockRegistry, Error> { - let facts: Value = serde_json::from_str(&fs::read_to_string(resources.join("facts.json"))?)?; - let registry = BlockRegistry::from_nbt(&Tag::compound([ - ("DataVersion", Tag::Int(DATA_VERSION)), - ( - "states", - Tag::List( - facts["states"] - .as_array() - .unwrap() - .iter() - .map(|v| tag(&v[4])) - .collect(), - ), - ), - ("defaults", tag(&facts["defaults"])), - ]))?; - Ok(Box::leak(Box::new(registry))) -} - -fn describe(state: &BlockState) -> String { - if state.properties.is_empty() { - return state.name.clone(); - } - let props: Vec = state - .properties - .iter() - .map(|(k, v)| format!("{k}={v}")) - .collect(); - format!("{}[{}]", state.name, props.join(",")) -} - -fn region_dir(world: &Path, dimension: &str) -> PathBuf { - let modern = world - .join("dimensions") - .join(dimension.replace(':', "/")) - .join("region"); - if modern.is_dir() { - return modern; - } - match dimension { - "minecraft:the_nether" => world.join("DIM-1/region"), - "minecraft:the_end" => world.join("DIM1/region"), - _ => world.join("region"), - } -} - -/// Terrain-stage chunks of the `full`² area at `origin`, row-major. -fn generate_area( - generator: &OverworldGenerator, - origin: (i32, i32), - full: i32, - threads: usize, -) -> Result, Error> { - let count = (full * full) as usize; - let next = AtomicUsize::new(0); - let slots: Vec>> = (0..count).map(|_| Mutex::new(None)).collect(); - std::thread::scope(|scope| -> Result<(), Error> { - let handles = (0..threads) - .map(|_| { - scope.spawn(|| -> Result<(), Error> { - let mut worker = generator.worker(); - loop { - let i = next.fetch_add(1, Ordering::Relaxed); - if i >= count { - return Ok(()); - } - let pos = ChunkPos::new( - origin.0 + (i as i32 % full), - origin.1 + (i as i32 / full), - ); - *slots[i].lock().unwrap() = Some(worker.generate_proto(pos)?); - } - }) - }) - .collect::>(); - handles.into_iter().try_for_each(|h| h.join().unwrap()) - })?; - Ok(slots - .into_iter() - .map(|s| s.into_inner().unwrap().unwrap()) - .collect()) -} - -/// Decorates the chunks at `order` (indices into the `full`² area, each with -/// all eight neighbors present) in that order, one FEATURES pass each. -fn decorate_area( - generator: &OverworldGenerator, - protos: Vec, - full: i32, - order: &[(i32, i32)], -) -> Result, Error> { - let mut chunks: Vec> = protos.into_iter().map(Some).collect(); - let mut worker = generator.worker(); - let (mut unsupported_roots, mut failed) = (0, 0); - let mut skipped = std::collections::BTreeSet::new(); - for &(x, z) in order { - let mut region = Vec::with_capacity(9); - for dz in -1..=1 { - for dx in -1..=1 { - region.push(chunks[((z + dz) * full + x + dx) as usize].take().unwrap()); - } - } - let mut region: [ProtoChunk; 9] = region.try_into().map_err(|_| "region")?; - let stats = worker.decorate(&mut region)?; - unsupported_roots += stats.unsupported; - failed += stats.failed; - skipped.extend(stats.skipped); - for (i, chunk) in region.into_iter().enumerate() { - let (dx, dz) = (i as i32 % 3 - 1, i as i32 / 3 - 1); - chunks[((z + dz) * full + x + dx) as usize] = Some(chunk); - } - } - println!("decoration: unsupported roots {unsupported_roots}, failed {failed}"); - if !skipped.is_empty() { - println!( - "skipped: {}", - skipped.into_iter().collect::>().join(" ") - ); - } - Ok(chunks.into_iter().map(Option::unwrap).collect()) -} - -/// Lazily opened region files of one dimension. -struct Regions { - dir: PathBuf, - files: HashMap<(i32, i32), Option>, -} -impl Regions { - fn new(dir: PathBuf) -> Self { - Self { - dir, - files: HashMap::new(), - } - } - fn chunk(&mut self, pos: ChunkPos) -> Result, Error> { - let key = (pos.x >> 5, pos.z >> 5); - let dir = &self.dir; - let file = self.files.entry(key).or_insert_with(|| { - RegionFile::open(dir.join(format!("r.{}.{}.mca", key.0, key.1))).ok() - }); - let Some(file) = file else { return Ok(None) }; - let Some(record) = file.read(pos)? else { - return Ok(None); - }; - Ok(Some(ChunkData::new(record.nbt(Limits::default())?)?)) - } -} - -fn main() -> Result<(), Error> { - let mut args = std::env::args().skip(1); - let resources = PathBuf::from(args.next().expect("client resource directory")); - let world = PathBuf::from(args.next().expect("vanilla world directory")); - let (mut seed, mut from, mut size, mut threads) = (0i64, (0, 0), 8i32, 4usize); - let mut dimension = String::from("minecraft:overworld"); - let mut show: Option = None; - let mut limit = 40usize; - let mut other: Option = None; - let (mut reverse, mut shuffle) = (false, 0i64); - while let Some(arg) = args.next() { - let mut next = || args.next().expect("argument value"); - match arg.as_str() { - "--seed" => seed = next().parse()?, - "--from" => from = (next().parse()?, next().parse()?), - "--size" => size = next().parse()?, - "--threads" => threads = next().parse()?, - "--dimension" => dimension = next(), - "--show" => show = Some(next()), - "--limit" => limit = next().parse()?, - "--other" => other = Some(PathBuf::from(next())), - "--reverse" => reverse = true, - "--shuffle" => shuffle = next().parse()?, - _ => return Err(format!("unknown argument {arg}").into()), - } - } - let registry = registry(&resources)?; - let data = GeneratorData::load(&resources.join("worldgen"), registry)?; - let generator = OverworldGenerator::for_dimension(data, seed, "minecraft:normal", &dimension)?; - let unsupported = generator.unsupported_features(); - println!("unsupported placed features: {}", unsupported.len()); - - // Rust: terrain for (size+4)², decoration for the inner (size+2)². - let full = size + 4; - let (x0, z0) = (from.0 - 2, from.1 - 2); - let mut order: Vec<(i32, i32)> = (1..full - 1) - .flat_map(|z| (1..full - 1).map(move |x| (x, z))) - .collect(); - if reverse { - let mut reversed = order.clone(); - reversed.reverse(); - let alternate = decorate_area( - &generator, - generate_area(&generator, (x0, z0), full, threads)?, - full, - &reversed, - )?; - let chunks = decorate_area( - &generator, - generate_area(&generator, (x0, z0), full, threads)?, - full, - &order, - )?; - let mut pairs: BTreeMap<(String, String), usize> = BTreeMap::new(); - let mut total = 0; - let name = |id| { - registry - .state(id) - .map(|s: &BlockState| s.name.trim_start_matches("minecraft:").to_owned()) - .unwrap_or_default() - }; - for (a, b) in chunks.iter().zip(&alternate) { - let p = a.position(); - if p.x < from.0 || p.z < from.1 || p.x >= from.0 + size || p.z >= from.1 + size { - continue; - } - for section in 0..a.terrain.height() as usize / 16 { - let (sa, sb) = ( - a.terrain.section(section).unwrap(), - b.terrain.section(section).unwrap(), - ); - for index in 0..4096 { - let (x, y) = (sa.get(index)?, sb.get(index)?); - if x != y { - total += 1; - *pairs.entry((name(x), name(y))).or_default() += 1; - } - } - } - } - println!("decoration order sensitivity (raster vs reverse): {total} blocks differ"); - let mut sorted: Vec<_> = pairs.into_iter().collect(); - sorted.sort_by_key(|p| std::cmp::Reverse(p.1)); - for ((v, r), n) in sorted.iter().take(limit) { - println!("{n:>9} {v} <-> {r}"); - } - return Ok(()); - } - if shuffle != 0 { - // Deterministic Fisher-Yates with a 64-bit LCG. - let mut state = shuffle as u64; - for i in (1..order.len()).rev() { - state = state - .wrapping_mul(6364136223846793005) - .wrapping_add(1442695040888963407); - order.swap(i, (state >> 33) as usize % (i + 1)); - } - } - let chunks = match other { - Some(_) => Vec::new(), - None => decorate_area( - &generator, - generate_area(&generator, (x0, z0), full, threads)?, - full, - &order, - )?, - }; - let (min_y, height) = match dimension.as_str() { - "minecraft:overworld" => (-64, 384), - _ => (0, 256), - }; - - // Vanilla region files. - let mut vanilla = Regions::new(region_dir(&world, &dimension)); - let mut second = other.map(|w| Regions::new(region_dir(&w, &dimension))); - let air = registry.default_state("minecraft:air").unwrap(); - let mut pairs: BTreeMap<(String, String), usize> = BTreeMap::new(); - let mut examples: Vec<[i32; 3]> = Vec::new(); - let (mut compared, mut differ, mut missing) = (0usize, 0usize, 0usize); - let mut per_chunk = Vec::new(); - for cz in from.1..from.1 + size { - for cx in from.0..from.0 + size { - let pos = ChunkPos::new(cx, cz); - let Some(theirs) = vanilla.chunk(pos)? else { - missing += 1; - continue; - }; - let ours = match &mut second { - Some(second) => match second.chunk(pos)? { - Some(chunk) => Some(chunk), - None => { - missing += 1; - continue; - } - }, - None => None, - }; - let status = match theirs.root().tag.get("Status") { - Some(Tag::String(s)) => s.to_string().unwrap_or_default(), - _ => String::new(), - }; - let rust = chunks.get(((cz - z0) * full + cx - x0) as usize); - if size == 1 { - println!( - "vanilla structures: {:?}", - theirs.root().tag.get("structures") - ); - if let Some(rust) = rust { - println!("rust structures: {:?}", rust.structures()); - } - } - if status != "minecraft:full" { - println!("chunk {cx} {cz}: vanilla status {status}"); - } - let mut chunk_differ = 0; - for section in 0..height as usize / 16 { - let base_y = min_y + section as i32 * 16; - let at = BlockPos::new(cx * 16, base_y, cz * 16); - let ours_loaded; - let ours: Option<&BlockSection> = match (&ours, rust) { - (Some(chunk), _) => { - ours_loaded = chunk.load_block_section(at, registry)?; - ours_loaded.as_ref() - } - (None, Some(rust)) => rust.terrain.section(section), - (None, None) => None, - }; - let theirs = theirs.load_block_section(at, registry)?; - for index in 0..4096 { - let a = ours.map_or(Ok(air), |s| s.get(index))?; - let b = theirs.as_ref().map_or(Ok(air), |s| s.get(index))?; - compared += 1; - if a == b { - continue; - } - differ += 1; - chunk_differ += 1; - let (va, ru) = ( - registry.state(b).map(describe).unwrap_or_default(), - registry.state(a).map(describe).unwrap_or_default(), - ); - let short = |s: &str| { - s.split('[') - .next() - .unwrap() - .trim_start_matches("minecraft:") - .to_owned() - }; - let pair = (short(&va), short(&ru)); - let p = [ - cx * 16 + (index & 15) as i32, - base_y + (index >> 8) as i32, - cz * 16 + ((index >> 4) & 15) as i32, - ]; - if let Some(filter) = &show { - let label = format!("{}->{}", pair.0, pair.1); - if &label == filter && examples.len() < limit { - examples.push(p); - println!(" {p:?}: vanilla {va} rust {ru}"); - } - } - *pairs.entry(pair).or_default() += 1; - } - } - per_chunk.push(((cx, cz), chunk_differ)); - } - } - println!( - "compared {compared} blocks in {} chunks ({missing} missing): {differ} differ ({:.4}%)", - per_chunk.len(), - differ as f64 * 100.0 / compared.max(1) as f64 - ); - let mut sorted: Vec<_> = pairs.into_iter().collect(); - sorted.sort_by_key(|p| std::cmp::Reverse(p.1)); - for ((v, r), n) in sorted.iter().take(limit) { - println!("{n:>9} vanilla {v} -> rust {r}"); - } - // Decoration order at chunk borders differs between runs (vanilla's own - // runs disagree), which mostly swaps blocks symmetrically. One-sided - // differences point at real generation differences. - let counts: BTreeMap<_, _> = sorted.iter().cloned().collect(); - let mut net: Vec<(i64, &(String, String))> = counts - .iter() - .map(|(pair, &n)| { - let back = counts - .get(&(pair.1.clone(), pair.0.clone())) - .copied() - .unwrap_or(0); - (n as i64 - back as i64, pair) - }) - .filter(|(n, _)| *n > 0) - .collect(); - net.sort_by_key(|p| std::cmp::Reverse(p.0)); - println!("one-sided differences:"); - for (n, (v, r)) in net.iter().take(limit) { - println!("{n:>9} vanilla {v} -> rust {r}"); - } - let clean = per_chunk.iter().filter(|(_, n)| *n == 0).count(); - println!("chunks identical: {clean}/{}", per_chunk.len()); - let mut worst = per_chunk.clone(); - worst.sort_by_key(|p| std::cmp::Reverse(p.1)); - for ((x, z), n) in worst.iter().take(8).filter(|(_, n)| *n > 0) { - println!(" chunk {x} {z}: {n}"); - } - Ok(()) -} From ed847d43dcf1b8411ea05164ec424dbfbec14062 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 14:47:03 +0200 Subject: [PATCH 040/408] Keep the probe list out of the harnesses' dependencies main.rs now only lists the probes; dispatch.rs runs them. The runner leaves main.rs out of a probe-binary harness's dependencies and keeps dispatch.rs, so adding a probe no longer reruns (or flake-checks) every harness of its crate. It also follows crate:: references between probes. Co-Authored-By: Claude Opus 5.5 --- .../horizon-world/examples/probe/dispatch.rs | 40 ++++++++++++++++++ crates/horizon-world/examples/probe/main.rs | 42 ++++--------------- tests/test_parity_runner.py | 8 ++-- tools/parity.py | 11 ++--- 4 files changed, 58 insertions(+), 43 deletions(-) create mode 100644 crates/horizon-world/examples/probe/dispatch.rs diff --git a/crates/horizon-world/examples/probe/dispatch.rs b/crates/horizon-world/examples/probe/dispatch.rs new file mode 100644 index 000000000..0b396edab --- /dev/null +++ b/crates/horizon-world/examples/probe/dispatch.rs @@ -0,0 +1,40 @@ +//! How the probe binary runs a probe. main.rs lists the probes and nothing else (tools/parity.py leaves it out of +//! the harnesses' dependencies); code every probe relies on goes here. +use std::process::ExitCode; + +/// `probes! { a, b, }` declares the binary's `main`, which runs the probe module named by its first argument. +macro_rules! probes { + ($($name:ident,)*) => { + fn run(name: &str) -> Option { + use std::process::Termination; + Some(match name { + $(stringify!($name) => $name::main().report(),)* + _ => return None, + }) + } + + fn main() -> std::process::ExitCode { + dispatch::main(&[$(stringify!($name)),*], run) + } + }; +} + +/// The probe's command line as its own example saw it: the program, then the arguments after the probe's name. +pub fn args() -> std::vec::IntoIter { + let mut args: Vec = std::env::args().collect(); + if args.len() > 1 { + args.remove(1); + } + args.into_iter() +} + +pub fn main(names: &[&str], run: fn(&str) -> Option) -> ExitCode { + let name = std::env::args().nth(1).unwrap_or_default(); + run(&name).unwrap_or_else(|| { + eprintln!( + "usage: probe [arguments...]\nprobes: {}", + names.join(" ") + ); + ExitCode::from(2) + }) +} diff --git a/crates/horizon-world/examples/probe/main.rs b/crates/horizon-world/examples/probe/main.rs index d9a0289b8..f3b9b6ef5 100644 --- a/crates/horizon-world/examples/probe/main.rs +++ b/crates/horizon-world/examples/probe/main.rs @@ -1,7 +1,13 @@ //! Every horizon-world parity probe in one binary: `probe [arguments]` runs `.rs` as its own //! example did (tools/test_*_parity.py). Linking ~170 examples, each instantiating the crate's generics again, //! was most of the parity job's probe build; one binary builds them once. -use std::process::{ExitCode, Termination}; +//! +//! This file only lists the probes, so that adding one reruns no harness: tools/parity.py leaves it out of +//! their dependencies. How a probe runs is in dispatch.rs. +#[macro_use] +mod dispatch; + +use dispatch::args; /// Code shared by several probes. mod support { @@ -180,20 +186,6 @@ mod world_fixture; mod world_ray_fixture; mod worldgen_random_fixture; -/// `run(name)` runs the probe module `name`; NAMES lists them. -macro_rules! probes { - ($($name:ident,)*) => { - const NAMES: &[&str] = &[$(stringify!($name)),*]; - - fn run(name: &str) -> Option { - Some(match name { - $(stringify!($name) => $name::main().report(),)* - _ => return None, - }) - } - }; -} - probes! { active_effect_tick_fixture, active_effects_fixture, @@ -364,23 +356,3 @@ probes! { world_ray_fixture, worldgen_random_fixture, } - -/// The probe's command line as its own example saw it: the program, then the arguments after the probe's name. -fn args() -> std::vec::IntoIter { - let mut args: Vec = std::env::args().collect(); - if args.len() > 1 { - args.remove(1); - } - args.into_iter() -} - -fn main() -> ExitCode { - let name = std::env::args().nth(1).unwrap_or_default(); - run(&name).unwrap_or_else(|| { - eprintln!( - "usage: probe [arguments...]\nprobes: {}", - NAMES.join(" ") - ); - ExitCode::from(2) - }) -} diff --git a/tests/test_parity_runner.py b/tests/test_parity_runner.py index 1ecd790f0..633163bf5 100644 --- a/tests/test_parity_runner.py +++ b/tests/test_parity_runner.py @@ -57,12 +57,14 @@ class ParityRunnerTests(unittest.TestCase): (probe / "support").mkdir(parents=True) (probe / "a_fixture.rs").write_text('mod integration { include!("d_fixture.rs"); }') (probe / "d_fixture.rs").write_text("use crate::support::shared as s;") - for name in ("b_fixture.rs", "c_fixture.rs", "main.rs", "support/shared.rs", "support/other.rs"): + (probe / "b_fixture.rs").write_text("use crate::e_fixture;") + for name in ("c_fixture.rs", "dispatch.rs", "e_fixture.rs", "main.rs", "support/shared.rs", "support/other.rs"): (probe / name).write_text("") paths = [f"crates/w/examples/probe/{name}" for name in ("a_fixture.rs", "b_fixture.rs", "c_fixture.rs", - "d_fixture.rs", "main.rs", "support/other.rs", "support/shared.rs")] + "d_fixture.rs", "dispatch.rs", "e_fixture.rs", "main.rs", + "support/other.rs", "support/shared.rs")] self.assertEqual(parity.only_probes_run(["crates/w/src/lib.rs", *paths], {"a_fixture", "b_fixture"}), - ["crates/w/src/lib.rs", *paths[:2], *paths[3:5], paths[6]]) + ["crates/w/src/lib.rs", *paths[:2], *paths[3:6], paths[8]]) self.assertEqual(parity.only_probes_run(paths, set()), paths) def test_java_sources_include_classes_pulled_from_the_sourcepath(self): diff --git a/tools/parity.py b/tools/parity.py index 8d12963e1..68ff16e73 100644 --- a/tools/parity.py +++ b/tools/parity.py @@ -482,16 +482,17 @@ def probes_run(commands): def only_probes_run(paths, names): - """A probe binary's dep-info lists every probe in it. Keep those the harness ran, the probes they include! - and the shared support modules they name (support::), so that editing one probe reruns only its own - harnesses.""" + """A probe binary's dep-info lists every probe in it. Keep those the harness ran, the probes they include! or + name (crate::) and the shared support modules they name (support::), so that editing one probe + reruns only its own harnesses. Files in a probe's own subdirectory and dispatch.rs, which runs them, are always + kept; main.rs, which only lists them, is left out, so adding a probe reruns nothing.""" if not names: return paths - names, used = {*names, "main"}, "" + names, used = {*names, "dispatch"}, "" while True: ran = [path for path in paths if (match := PROBE_SOURCE.search(path)) and not match.group(1) and match.group(2) in names] used = "".join((ROOT / path).read_text(encoding="utf-8", errors="replace") for path in ran) - included = set(re.findall(r'include!\("(\w+)\.rs"\)', used)) - names + included = {*re.findall(r'include!\("(\w+)\.rs"\)', used), *re.findall(r"\bcrate::(\w+)", used)} - names if not included: break names |= included From 858f701ee8b234f194c65f8c2c29e8b2a77e07c8 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 14:46:08 +0200 Subject: [PATCH 041/408] Run the horizon-client parity probes from one binary 81 client examples that harnesses run become modules of examples/probe: harnesses run `probe ...` (or `cargo run --example probe -- `), and the shared helpers (audio_common, hud_fixture, chat_screen_fixture) move with them. The benchmarks and manual tools stay standalone examples. Co-Authored-By: Claude Opus 5.5 --- .../examples/{ => probe}/ambient_fixture.rs | 7 +- .../examples/{ => probe}/arrow_probe.rs | 4 +- .../{ => probe}/audio_attributes_fixture.rs | 4 +- .../examples/{ => probe}/audio_common/mod.rs | 0 .../examples/{ => probe}/auto_jump_probe.rs | 4 +- .../{ => probe}/block_entity_anim_fixture.rs | 4 +- .../block_entity_render_fixture.rs | 4 +- .../block_entity_tickers_fixture.rs | 4 +- .../{ => probe}/block_particles_fixture.rs | 4 +- .../{ => probe}/block_transform_fixture.rs | 4 +- .../examples/{ => probe}/breaking_fixture.rs | 4 +- .../examples/{ => probe}/camera_probe.rs | 4 +- .../examples/{ => probe}/cauldron_fixture.rs | 4 +- .../{ => probe}/chat_screen_fixture.rs | 8 +- .../chat_screen_fixture/registries.rs | 0 .../examples/{ => probe}/cloud_fixture.rs | 4 +- .../{ => probe}/command_parse_fixture.rs | 4 +- .../{ => probe}/container_screen_probe.rs | 4 +- .../{ => probe}/creative_search_fixture.rs | 4 +- .../{ => probe}/emitter_particles_probe.rs | 4 +- .../{ => probe}/enchanting_fixture.rs | 4 +- .../{ => probe}/entity_anim_fixture.rs | 6 +- .../{ => probe}/entity_components_probe.rs | 4 +- .../{ => probe}/entity_death_loot_fixture.rs | 4 +- .../{ => probe}/entity_particles_probe.rs | 4 +- .../{ => probe}/environment_fixture.rs | 4 +- .../{ => probe}/finalize_spawn_fixture.rs | 4 +- .../{ => probe}/fire_starter_sound_probe.rs | 4 +- .../{ => probe}/firework_tooltip_fixture.rs | 4 +- .../{ => probe}/first_person_probe.rs | 4 +- .../{ => probe}/frame_limiter_probe.rs | 4 +- .../examples/{ => probe}/game_loop_probe.rs | 4 +- .../{ => probe}/ghost_recipe_fixture.rs | 4 +- .../examples/{ => probe}/held_drop_fixture.rs | 2 +- .../examples/{ => probe}/hotbar_fixture.rs | 4 +- .../examples/{ => probe}/hud_fixture.rs | 4 +- .../examples/{ => probe}/hud_fixture/kinds.rs | 0 .../examples/{ => probe}/input_probe.rs | 4 +- .../{ => probe}/interaction_input_fixture.rs | 4 +- .../examples/{ => probe}/lan_probe.rs | 4 +- .../examples/{ => probe}/light_parity.rs | 6 +- crates/horizon-client/examples/probe/main.rs | 215 ++++++++++++++++++ .../{ => probe}/marker_particles_probe.rs | 4 +- .../examples/{ => probe}/menu_fixture.rs | 4 +- .../examples/{ => probe}/mipmap_probe.rs | 4 +- .../examples/{ => probe}/mob_ai_probe.rs | 4 +- .../{ => probe}/mob_attributes_fixture.rs | 4 +- .../examples/{ => probe}/music_fixture.rs | 7 +- .../{ => probe}/natural_spawn_fixture.rs | 4 +- .../examples/{ => probe}/options_probe.rs | 4 +- .../{ => probe}/pack_resources_fixture.rs | 4 +- .../{ => probe}/pack_screen_fixture.rs | 4 +- .../{ => probe}/pack_selection_fixture.rs | 4 +- .../{ => probe}/particle_providers_probe.rs | 4 +- .../{ => probe}/pick_block_data_fixture.rs | 4 +- .../{ => probe}/place_recipe_fixture.rs | 4 +- .../{ => probe}/player_sync_fixture.rs | 4 +- .../examples/{ => probe}/raid_fixture.rs | 4 +- .../{ => probe}/random_tick_sections_probe.rs | 4 +- .../{ => probe}/recipe_book_fixture.rs | 4 +- .../{ => probe}/recipe_book_render_fixture.rs | 4 +- .../{ => probe}/recipe_book_view_fixture.rs | 4 +- .../examples/{ => probe}/recipe_fixture.rs | 4 +- .../{ => probe}/scene_collision_probe.rs | 4 +- .../{ => probe}/scene_motion_probe.rs | 4 +- .../{ => probe}/scoreboard_fixture.rs | 4 +- .../{ => probe}/screen_layout_fixture.rs | 4 +- .../{ => probe}/section_mesh_fixture.rs | 4 +- .../{ => probe}/server_files_probe.rs | 4 +- .../{ => probe}/situational_music_fixture.rs | 4 +- .../{ => probe}/skin_image_fixture.rs | 4 +- .../{ => probe}/sound_engine_fixture.rs | 7 +- .../{ => probe}/sound_event_fixture.rs | 4 +- .../{ => probe}/spawn_rules_fixture.rs | 4 +- .../examples/{ => probe}/sprint_probe.rs | 4 +- .../examples/{ => probe}/subtitle_fixture.rs | 4 +- .../examples/{ => probe}/tab_list_fixture.rs | 4 +- .../{ => probe}/team_rules_fixture.rs | 4 +- .../examples/{ => probe}/toggle_keys_probe.rs | 4 +- .../{ => probe}/tooltip_display_fixture.rs | 4 +- .../examples/{ => probe}/trading_fixture.rs | 4 +- .../{ => probe}/translucency_fixture.rs | 4 +- .../examples/{ => probe}/weather_fixture.rs | 4 +- .../world_border_render_fixture.rs | 4 +- .../{ => probe}/world_options_fixture.rs | 4 +- docs/parity-workflow.md | 2 +- docs/parity/meshing.md | 2 +- docs/rust-parity.md | 4 +- tools/audio_harness.py | 10 +- tools/interaction_lab.py | 2 +- tools/oracle_harness.py | 11 +- tools/port_regen.py | 6 +- tools/test_arrow_parity.py | 12 +- tools/test_auto_jump_parity.py | 6 +- tools/test_block_entity_anim_parity.py | 6 +- tools/test_block_entity_render_parity.py | 6 +- tools/test_block_entity_tickers_parity.py | 4 +- tools/test_block_particles_parity.py | 6 +- tools/test_breaking_model_parity.py | 6 +- tools/test_chat_screen_parity.py | 2 +- tools/test_command_parse_parity.py | 6 +- tools/test_creative_parity.py | 2 +- tools/test_enchanting_parity.py | 8 +- tools/test_entity_death_loot_parity.py | 8 +- tools/test_entity_model_parity.py | 6 +- tools/test_entity_particles_parity.py | 4 +- tools/test_environment_render_parity.py | 6 +- tools/test_finalize_spawn_parity.py | 8 +- tools/test_firework_tooltip_parity.py | 2 +- tools/test_ghost_recipe_parity.py | 2 +- tools/test_held_drop_parity.py | 2 +- tools/test_hotbar_parity.py | 2 +- tools/test_hud_parity.py | 6 +- tools/test_light_parity.py | 4 +- tools/test_local_input_parity.py | 8 +- tools/test_mob_ai_parity.py | 6 +- tools/test_mob_attributes_parity.py | 6 +- tools/test_native_scene_collision.py | 8 +- tools/test_native_scene_motion.py | 10 +- tools/test_natural_spawn_parity.py | 8 +- tools/test_pack_screen_parity.py | 2 +- tools/test_pack_selection_parity.py | 6 +- tools/test_particle_providers_parity.py | 4 +- tools/test_place_recipe_parity.py | 2 +- tools/test_raid_parity.py | 8 +- tools/test_random_tick_sections_parity.py | 2 +- tools/test_recipe_book_parity.py | 2 +- tools/test_recipe_book_render_parity.py | 2 +- tools/test_recipe_book_view_parity.py | 2 +- tools/test_resource_pack_parity.py | 2 +- tools/test_scoreboard_parity.py | 8 +- tools/test_screen_layout_parity.py | 2 +- tools/test_section_mesh_parity.py | 10 +- tools/test_server_files_parity.py | 6 +- tools/test_spawn_rules_parity.py | 8 +- tools/test_spawner_parity.py | 8 +- tools/test_sprint_input_parity.py | 8 +- tools/test_subtitle_parity.py | 8 +- tools/test_tab_list_parity.py | 12 +- tools/test_team_rules_parity.py | 8 +- tools/test_trading_parity.py | 8 +- tools/test_translucency_parity.py | 2 +- tools/test_trial_spawner_parity.py | 8 +- tools/test_vault_parity.py | 8 +- tools/test_world_border_render_parity.py | 4 +- 145 files changed, 551 insertions(+), 340 deletions(-) rename crates/horizon-client/examples/{ => probe}/ambient_fixture.rs (98%) rename crates/horizon-client/examples/{ => probe}/arrow_probe.rs (99%) rename crates/horizon-client/examples/{ => probe}/audio_attributes_fixture.rs (97%) rename crates/horizon-client/examples/{ => probe}/audio_common/mod.rs (100%) rename crates/horizon-client/examples/{ => probe}/auto_jump_probe.rs (98%) rename crates/horizon-client/examples/{ => probe}/block_entity_anim_fixture.rs (99%) rename crates/horizon-client/examples/{ => probe}/block_entity_render_fixture.rs (99%) rename crates/horizon-client/examples/{ => probe}/block_entity_tickers_fixture.rs (98%) rename crates/horizon-client/examples/{ => probe}/block_particles_fixture.rs (95%) rename crates/horizon-client/examples/{ => probe}/block_transform_fixture.rs (96%) rename crates/horizon-client/examples/{ => probe}/breaking_fixture.rs (96%) rename crates/horizon-client/examples/{ => probe}/camera_probe.rs (99%) rename crates/horizon-client/examples/{ => probe}/cauldron_fixture.rs (98%) rename crates/horizon-client/examples/{ => probe}/chat_screen_fixture.rs (95%) rename crates/horizon-client/examples/{ => probe}/chat_screen_fixture/registries.rs (100%) rename crates/horizon-client/examples/{ => probe}/cloud_fixture.rs (92%) rename crates/horizon-client/examples/{ => probe}/command_parse_fixture.rs (99%) rename crates/horizon-client/examples/{ => probe}/container_screen_probe.rs (97%) rename crates/horizon-client/examples/{ => probe}/creative_search_fixture.rs (95%) rename crates/horizon-client/examples/{ => probe}/emitter_particles_probe.rs (96%) rename crates/horizon-client/examples/{ => probe}/enchanting_fixture.rs (94%) rename crates/horizon-client/examples/{ => probe}/entity_anim_fixture.rs (99%) rename crates/horizon-client/examples/{ => probe}/entity_components_probe.rs (96%) rename crates/horizon-client/examples/{ => probe}/entity_death_loot_fixture.rs (99%) rename crates/horizon-client/examples/{ => probe}/entity_particles_probe.rs (95%) rename crates/horizon-client/examples/{ => probe}/environment_fixture.rs (97%) rename crates/horizon-client/examples/{ => probe}/finalize_spawn_fixture.rs (99%) rename crates/horizon-client/examples/{ => probe}/fire_starter_sound_probe.rs (91%) rename crates/horizon-client/examples/{ => probe}/firework_tooltip_fixture.rs (92%) rename crates/horizon-client/examples/{ => probe}/first_person_probe.rs (99%) rename crates/horizon-client/examples/{ => probe}/frame_limiter_probe.rs (97%) rename crates/horizon-client/examples/{ => probe}/game_loop_probe.rs (99%) rename crates/horizon-client/examples/{ => probe}/ghost_recipe_fixture.rs (96%) rename crates/horizon-client/examples/{ => probe}/held_drop_fixture.rs (98%) rename crates/horizon-client/examples/{ => probe}/hotbar_fixture.rs (94%) rename crates/horizon-client/examples/{ => probe}/hud_fixture.rs (98%) rename crates/horizon-client/examples/{ => probe}/hud_fixture/kinds.rs (100%) rename crates/horizon-client/examples/{ => probe}/input_probe.rs (94%) rename crates/horizon-client/examples/{ => probe}/interaction_input_fixture.rs (96%) rename crates/horizon-client/examples/{ => probe}/lan_probe.rs (96%) rename crates/horizon-client/examples/{ => probe}/light_parity.rs (98%) create mode 100644 crates/horizon-client/examples/probe/main.rs rename crates/horizon-client/examples/{ => probe}/marker_particles_probe.rs (97%) rename crates/horizon-client/examples/{ => probe}/menu_fixture.rs (98%) rename crates/horizon-client/examples/{ => probe}/mipmap_probe.rs (94%) rename crates/horizon-client/examples/{ => probe}/mob_ai_probe.rs (99%) rename crates/horizon-client/examples/{ => probe}/mob_attributes_fixture.rs (95%) rename crates/horizon-client/examples/{ => probe}/music_fixture.rs (97%) rename crates/horizon-client/examples/{ => probe}/natural_spawn_fixture.rs (99%) rename crates/horizon-client/examples/{ => probe}/options_probe.rs (94%) rename crates/horizon-client/examples/{ => probe}/pack_resources_fixture.rs (97%) rename crates/horizon-client/examples/{ => probe}/pack_screen_fixture.rs (98%) rename crates/horizon-client/examples/{ => probe}/pack_selection_fixture.rs (96%) rename crates/horizon-client/examples/{ => probe}/particle_providers_probe.rs (99%) rename crates/horizon-client/examples/{ => probe}/pick_block_data_fixture.rs (96%) rename crates/horizon-client/examples/{ => probe}/place_recipe_fixture.rs (97%) rename crates/horizon-client/examples/{ => probe}/player_sync_fixture.rs (96%) rename crates/horizon-client/examples/{ => probe}/raid_fixture.rs (99%) rename crates/horizon-client/examples/{ => probe}/random_tick_sections_probe.rs (98%) rename crates/horizon-client/examples/{ => probe}/recipe_book_fixture.rs (98%) rename crates/horizon-client/examples/{ => probe}/recipe_book_render_fixture.rs (99%) rename crates/horizon-client/examples/{ => probe}/recipe_book_view_fixture.rs (98%) rename crates/horizon-client/examples/{ => probe}/recipe_fixture.rs (97%) rename crates/horizon-client/examples/{ => probe}/scene_collision_probe.rs (97%) rename crates/horizon-client/examples/{ => probe}/scene_motion_probe.rs (99%) rename crates/horizon-client/examples/{ => probe}/scoreboard_fixture.rs (99%) rename crates/horizon-client/examples/{ => probe}/screen_layout_fixture.rs (98%) rename crates/horizon-client/examples/{ => probe}/section_mesh_fixture.rs (99%) rename crates/horizon-client/examples/{ => probe}/server_files_probe.rs (99%) rename crates/horizon-client/examples/{ => probe}/situational_music_fixture.rs (96%) rename crates/horizon-client/examples/{ => probe}/skin_image_fixture.rs (90%) rename crates/horizon-client/examples/{ => probe}/sound_engine_fixture.rs (98%) rename crates/horizon-client/examples/{ => probe}/sound_event_fixture.rs (97%) rename crates/horizon-client/examples/{ => probe}/spawn_rules_fixture.rs (98%) rename crates/horizon-client/examples/{ => probe}/sprint_probe.rs (97%) rename crates/horizon-client/examples/{ => probe}/subtitle_fixture.rs (97%) rename crates/horizon-client/examples/{ => probe}/tab_list_fixture.rs (98%) rename crates/horizon-client/examples/{ => probe}/team_rules_fixture.rs (97%) rename crates/horizon-client/examples/{ => probe}/toggle_keys_probe.rs (95%) rename crates/horizon-client/examples/{ => probe}/tooltip_display_fixture.rs (93%) rename crates/horizon-client/examples/{ => probe}/trading_fixture.rs (99%) rename crates/horizon-client/examples/{ => probe}/translucency_fixture.rs (93%) rename crates/horizon-client/examples/{ => probe}/weather_fixture.rs (95%) rename crates/horizon-client/examples/{ => probe}/world_border_render_fixture.rs (98%) rename crates/horizon-client/examples/{ => probe}/world_options_fixture.rs (93%) diff --git a/crates/horizon-client/examples/ambient_fixture.rs b/crates/horizon-client/examples/probe/ambient_fixture.rs similarity index 98% rename from crates/horizon-client/examples/ambient_fixture.rs rename to crates/horizon-client/examples/probe/ambient_fixture.rs index d75a1b568..3fd507902 100644 --- a/crates/horizon-client/examples/ambient_fixture.rs +++ b/crates/horizon-client/examples/probe/ambient_fixture.rs @@ -1,8 +1,7 @@ //! Replays `tools/test_ambient_sound_parity.py` scripts through Horizon's //! ambient sound handlers over its `SoundEngine`: //! `ambient_fixture ROOT INPUT OUTPUT`. -#[path = "audio_common/mod.rs"] -mod common; +use crate::audio_common as common; use common::{Fake, d, f, flush}; use horizon_client::ambience::{Ambience, AmbientContext, AmbientSounds, Mood, bubble_column_in}; use horizon_client::sound_engine::{Bound, SoundEngine, TickContext, Ticking}; @@ -47,8 +46,8 @@ fn sounds(a: &[&str]) -> AmbientSounds { } } -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let mut engine = SoundEngine::new(SoundRegistry::load(std::path::Path::new(&args[1]))); engine.listening = true; let mut backend = Fake::default(); diff --git a/crates/horizon-client/examples/arrow_probe.rs b/crates/horizon-client/examples/probe/arrow_probe.rs similarity index 99% rename from crates/horizon-client/examples/arrow_probe.rs rename to crates/horizon-client/examples/probe/arrow_probe.rs index 63ff2df32..f72e6276e 100644 --- a/crates/horizon-client/examples/arrow_probe.rs +++ b/crates/horizon-client/examples/probe/arrow_probe.rs @@ -50,8 +50,8 @@ fn particle(k: ArrowParticle) -> &'static str { ArrowParticle::Splash => "splash", } } -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); if args.len() != 3 { return Err("usage: arrow_probe RESOURCES FIXTURE_DIRECTORY --describe|REFERENCE".into()); } diff --git a/crates/horizon-client/examples/audio_attributes_fixture.rs b/crates/horizon-client/examples/probe/audio_attributes_fixture.rs similarity index 97% rename from crates/horizon-client/examples/audio_attributes_fixture.rs rename to crates/horizon-client/examples/probe/audio_attributes_fixture.rs index 73f463fc4..4bbb3a239 100644 --- a/crates/horizon-client/examples/audio_attributes_fixture.rs +++ b/crates/horizon-client/examples/probe/audio_attributes_fixture.rs @@ -18,8 +18,8 @@ fn music(m: Option<&Music>) -> String { }) } -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let root = std::path::Path::new(&args[1]); let tables = MusicTables::load(root); let ambient = AmbientTables::load(root); diff --git a/crates/horizon-client/examples/audio_common/mod.rs b/crates/horizon-client/examples/probe/audio_common/mod.rs similarity index 100% rename from crates/horizon-client/examples/audio_common/mod.rs rename to crates/horizon-client/examples/probe/audio_common/mod.rs diff --git a/crates/horizon-client/examples/auto_jump_probe.rs b/crates/horizon-client/examples/probe/auto_jump_probe.rs similarity index 98% rename from crates/horizon-client/examples/auto_jump_probe.rs rename to crates/horizon-client/examples/probe/auto_jump_probe.rs index d8dee95df..c15565850 100644 --- a/crates/horizon-client/examples/auto_jump_probe.rs +++ b/crates/horizon-client/examples/probe/auto_jump_probe.rs @@ -24,8 +24,8 @@ fn db(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); let [root, input, output, scene_json] = &args[..] else { return Err("usage: auto_jump_probe RESOURCES INPUT OUTPUT SCENE_JSON".into()); }; diff --git a/crates/horizon-client/examples/block_entity_anim_fixture.rs b/crates/horizon-client/examples/probe/block_entity_anim_fixture.rs similarity index 99% rename from crates/horizon-client/examples/block_entity_anim_fixture.rs rename to crates/horizon-client/examples/probe/block_entity_anim_fixture.rs index e108c53b3..3a3a0ef14 100644 --- a/crates/horizon-client/examples/block_entity_anim_fixture.rs +++ b/crates/horizon-client/examples/probe/block_entity_anim_fixture.rs @@ -118,8 +118,8 @@ fn status(s: ShulkerStatus) -> &'static str { } } -fn main() -> Result<()> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [root, inputs, output] = args.as_slice() else { return Err("usage: block_entity_anim_fixture RESOURCES INPUTS OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/block_entity_render_fixture.rs b/crates/horizon-client/examples/probe/block_entity_render_fixture.rs similarity index 99% rename from crates/horizon-client/examples/block_entity_render_fixture.rs rename to crates/horizon-client/examples/probe/block_entity_render_fixture.rs index d844c4e44..a0e3471bc 100644 --- a/crates/horizon-client/examples/block_entity_render_fixture.rs +++ b/crates/horizon-client/examples/probe/block_entity_render_fixture.rs @@ -110,8 +110,8 @@ fn intern(s: &str) -> &'static str { } } -fn main() -> Result<()> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [root, inputs, textures, output] = args.as_slice() else { return Err("usage: block_entity_render_fixture RESOURCES INPUTS TEXTURES OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/block_entity_tickers_fixture.rs b/crates/horizon-client/examples/probe/block_entity_tickers_fixture.rs similarity index 98% rename from crates/horizon-client/examples/block_entity_tickers_fixture.rs rename to crates/horizon-client/examples/probe/block_entity_tickers_fixture.rs index f08c333f6..d375f1b74 100644 --- a/crates/horizon-client/examples/block_entity_tickers_fixture.rs +++ b/crates/horizon-client/examples/probe/block_entity_tickers_fixture.rs @@ -26,8 +26,8 @@ fn entity(name: &str) -> BlockEntity { .unwrap_or_else(|| panic!("no block entity for {name}")) } -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let input = std::fs::read_to_string(&args[1]).expect("input"); let mut out = String::new(); let mut entities = BlockEntities::default(); diff --git a/crates/horizon-client/examples/block_particles_fixture.rs b/crates/horizon-client/examples/probe/block_particles_fixture.rs similarity index 95% rename from crates/horizon-client/examples/block_particles_fixture.rs rename to crates/horizon-client/examples/probe/block_particles_fixture.rs index 63ef242b7..0e58d99ea 100644 --- a/crates/horizon-client/examples/block_particles_fixture.rs +++ b/crates/horizon-client/examples/probe/block_particles_fixture.rs @@ -8,8 +8,8 @@ use std::{ io::{BufRead, BufReader, BufWriter, Write}, path::Path, }; -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let root = Path::new(&args[1]); let assets = Assets::load(root)?; let render = assets.reload(root)?; diff --git a/crates/horizon-client/examples/block_transform_fixture.rs b/crates/horizon-client/examples/probe/block_transform_fixture.rs similarity index 96% rename from crates/horizon-client/examples/block_transform_fixture.rs rename to crates/horizon-client/examples/probe/block_transform_fixture.rs index 01d92a047..9d8d1d7db 100644 --- a/crates/horizon-client/examples/block_transform_fixture.rs +++ b/crates/horizon-client/examples/probe/block_transform_fixture.rs @@ -51,8 +51,8 @@ impl Around for Column { } } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: block_transform_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/breaking_fixture.rs b/crates/horizon-client/examples/probe/breaking_fixture.rs similarity index 96% rename from crates/horizon-client/examples/breaking_fixture.rs rename to crates/horizon-client/examples/probe/breaking_fixture.rs index da696b88e..c5a816ccd 100644 --- a/crates/horizon-client/examples/breaking_fixture.rs +++ b/crates/horizon-client/examples/probe/breaking_fixture.rs @@ -16,8 +16,8 @@ use std::{ }; /// The stage sprite origin the cracks carry (the oracle compares the geometry and UVs only). const STAGE: [f32; 2] = [0.25, 0.5]; -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let root = Path::new(&args[1]); let assets = Assets::load(root)?; let render = assets.reload(root)?; diff --git a/crates/horizon-client/examples/camera_probe.rs b/crates/horizon-client/examples/probe/camera_probe.rs similarity index 99% rename from crates/horizon-client/examples/camera_probe.rs rename to crates/horizon-client/examples/probe/camera_probe.rs index 2d7f716f0..38f3c23be 100644 --- a/crates/horizon-client/examples/camera_probe.rs +++ b/crates/horizon-client/examples/probe/camera_probe.rs @@ -323,8 +323,8 @@ fn avatar(c: &Value, out: &mut impl Write) -> Result<()> { Ok(()) } -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let input = BufReader::new(File::open(&args[1])?); let mut out = BufWriter::new(File::create(&args[2])?); for (n, line) in input.lines().enumerate() { diff --git a/crates/horizon-client/examples/cauldron_fixture.rs b/crates/horizon-client/examples/probe/cauldron_fixture.rs similarity index 98% rename from crates/horizon-client/examples/cauldron_fixture.rs rename to crates/horizon-client/examples/probe/cauldron_fixture.rs index 6aa942d42..95b075d70 100644 --- a/crates/horizon-client/examples/cauldron_fixture.rs +++ b/crates/horizon-client/examples/probe/cauldron_fixture.rs @@ -70,8 +70,8 @@ fn describe(state: &BlockState) -> String { format!("{}|{}", state.name, props.join(",")) } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: cauldron_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/chat_screen_fixture.rs b/crates/horizon-client/examples/probe/chat_screen_fixture.rs similarity index 95% rename from crates/horizon-client/examples/chat_screen_fixture.rs rename to crates/horizon-client/examples/probe/chat_screen_fixture.rs index c5cba6b9d..229d8d861 100644 --- a/crates/horizon-client/examples/chat_screen_fixture.rs +++ b/crates/horizon-client/examples/probe/chat_screen_fixture.rs @@ -5,6 +5,7 @@ //! the oracle's JSON form. //! //! usage: chat_screen_fixture RESOURCES REGISTRIES CASES OUTPUT +use crate::pack_screen_fixture; use horizon_client::{ chat::{ChatAction, ChatScreen, Commands}, command::vanilla, @@ -15,14 +16,11 @@ use horizon_client::{ use serde_json::{Value, json}; use std::{fmt::Write as _, fs, path::PathBuf}; use winit::keyboard::KeyCode as K; -#[path = "pack_screen_fixture.rs"] -#[allow(dead_code)] -mod pack_screen_fixture; #[path = "chat_screen_fixture/registries.rs"] mod registries; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [root, registries, inputs, output] = args.as_slice() else { return Err("usage: chat_screen_fixture RESOURCES REGISTRIES CASES OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/chat_screen_fixture/registries.rs b/crates/horizon-client/examples/probe/chat_screen_fixture/registries.rs similarity index 100% rename from crates/horizon-client/examples/chat_screen_fixture/registries.rs rename to crates/horizon-client/examples/probe/chat_screen_fixture/registries.rs diff --git a/crates/horizon-client/examples/cloud_fixture.rs b/crates/horizon-client/examples/probe/cloud_fixture.rs similarity index 92% rename from crates/horizon-client/examples/cloud_fixture.rs rename to crates/horizon-client/examples/probe/cloud_fixture.rs index 7c00bfb3a..4ba072dbb 100644 --- a/crates/horizon-client/examples/cloud_fixture.rs +++ b/crates/horizon-client/examples/probe/cloud_fixture.rs @@ -1,8 +1,8 @@ //! CloudRenderer face selection and mesh traversal, without a GPU. use horizon_client::clouds; use std::{fmt::Write, fs}; -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let mut output = String::new(); for (case, line) in fs::read_to_string(&args[1])?.lines().enumerate() { let values: Vec = line diff --git a/crates/horizon-client/examples/command_parse_fixture.rs b/crates/horizon-client/examples/probe/command_parse_fixture.rs similarity index 99% rename from crates/horizon-client/examples/command_parse_fixture.rs rename to crates/horizon-client/examples/probe/command_parse_fixture.rs index 1cc1f95d5..17437cd72 100644 --- a/crates/horizon-client/examples/command_parse_fixture.rs +++ b/crates/horizon-client/examples/probe/command_parse_fixture.rs @@ -132,8 +132,8 @@ fn tree(d: &Dispatcher, node: usize) -> Value { v } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); if args.get(1).map(String::as_str) == Some("tree") { let d = &vanilla::registered(false); let mut v = tree(d, 0); diff --git a/crates/horizon-client/examples/container_screen_probe.rs b/crates/horizon-client/examples/probe/container_screen_probe.rs similarity index 97% rename from crates/horizon-client/examples/container_screen_probe.rs rename to crates/horizon-client/examples/probe/container_screen_probe.rs index b89b23a2a..e82b5bdf5 100644 --- a/crates/horizon-client/examples/container_screen_probe.rs +++ b/crates/horizon-client/examples/probe/container_screen_probe.rs @@ -24,8 +24,8 @@ fn input_name(input: Input) -> &'static str { } } -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let input = BufReader::new(File::open(&args[1])?); let mut out = BufWriter::new(File::create(&args[2])?); for (n, line) in input.lines().enumerate() { diff --git a/crates/horizon-client/examples/creative_search_fixture.rs b/crates/horizon-client/examples/probe/creative_search_fixture.rs similarity index 95% rename from crates/horizon-client/examples/creative_search_fixture.rs rename to crates/horizon-client/examples/probe/creative_search_fixture.rs index 628e0486d..1f4f04b37 100644 --- a/crates/horizon-client/examples/creative_search_fixture.rs +++ b/crates/horizon-client/examples/probe/creative_search_fixture.rs @@ -11,8 +11,8 @@ use horizon_client::{ use serde_json::{Value, json}; use std::{fs, path::Path}; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let usage = "usage: creative_search_fixture RESOURCES CREATIVE_JSON VANILLA_JSON OUTPUT"; let names = Names::load(Path::new(args.get(1).ok_or(usage)?)); let creative = Creative::from_json(&serde_json::from_slice(&fs::read( diff --git a/crates/horizon-client/examples/emitter_particles_probe.rs b/crates/horizon-client/examples/probe/emitter_particles_probe.rs similarity index 96% rename from crates/horizon-client/examples/emitter_particles_probe.rs rename to crates/horizon-client/examples/probe/emitter_particles_probe.rs index 7469bb368..6349eb8dc 100644 --- a/crates/horizon-client/examples/emitter_particles_probe.rs +++ b/crates/horizon-client/examples/probe/emitter_particles_probe.rs @@ -14,8 +14,8 @@ fn d(v: f64) -> String { format!("{:016x}", v.to_bits()) } -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let mut out = BufWriter::new(File::create(&args[2])?); for (n, line) in BufReader::new(File::open(&args[1])?).lines().enumerate() { let c: Value = serde_json::from_str(&line?)?; diff --git a/crates/horizon-client/examples/enchanting_fixture.rs b/crates/horizon-client/examples/probe/enchanting_fixture.rs similarity index 94% rename from crates/horizon-client/examples/enchanting_fixture.rs rename to crates/horizon-client/examples/probe/enchanting_fixture.rs index 736b9189e..4c0fe6350 100644 --- a/crates/horizon-client/examples/enchanting_fixture.rs +++ b/crates/horizon-client/examples/probe/enchanting_fixture.rs @@ -10,8 +10,8 @@ use horizon_client::{ }; use std::{fmt::Write as _, fs, path::Path}; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: enchanting_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/entity_anim_fixture.rs b/crates/horizon-client/examples/probe/entity_anim_fixture.rs similarity index 99% rename from crates/horizon-client/examples/entity_anim_fixture.rs rename to crates/horizon-client/examples/probe/entity_anim_fixture.rs index e5a146ef9..0a2e2951f 100644 --- a/crates/horizon-client/examples/entity_anim_fixture.rs +++ b/crates/horizon-client/examples/probe/entity_anim_fixture.rs @@ -3,7 +3,7 @@ //! posed model with `mobs::render::draw` under the case's living-entity root //! transform and writes each drawn part's packed vertex normals. //! -//! cargo run --profile fast -p horizon-client --example entity_anim_fixture -- \ +//! cargo run --profile fast -p horizon-client --example probe -- entity_anim_fixture \ //! RESOURCES VANILLA.jsonl OUT.jsonl use horizon_client::mesher::Vertex; use horizon_client::mobs::{ @@ -288,8 +288,8 @@ fn entity_state(mob: &mut Mob, species: Species, case: &Value) { } } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().skip(1).collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().skip(1).collect(); let root = PathBuf::from(&args[0]); let types = MobTypes::load(&root)?; let animations = MobData::load_animations(&root); diff --git a/crates/horizon-client/examples/entity_components_probe.rs b/crates/horizon-client/examples/probe/entity_components_probe.rs similarity index 96% rename from crates/horizon-client/examples/entity_components_probe.rs rename to crates/horizon-client/examples/probe/entity_components_probe.rs index 0d4a51e8c..2b1c3233f 100644 --- a/crates/horizon-client/examples/entity_components_probe.rs +++ b/crates/horizon-client/examples/probe/entity_components_probe.rs @@ -61,8 +61,8 @@ fn species(id: &str) -> Species { } } -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let input = BufReader::new(File::open(&args[1])?); let mut out = BufWriter::new(File::create(&args[2])?); for (n, line) in input.lines().enumerate() { diff --git a/crates/horizon-client/examples/entity_death_loot_fixture.rs b/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs similarity index 99% rename from crates/horizon-client/examples/entity_death_loot_fixture.rs rename to crates/horizon-client/examples/probe/entity_death_loot_fixture.rs index a8eceb8ca..86ef275d9 100644 --- a/crates/horizon-client/examples/entity_death_loot_fixture.rs +++ b/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs @@ -53,8 +53,8 @@ fn line(s: &LootStack) -> String { out } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: entity_death_loot_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/entity_particles_probe.rs b/crates/horizon-client/examples/probe/entity_particles_probe.rs similarity index 95% rename from crates/horizon-client/examples/entity_particles_probe.rs rename to crates/horizon-client/examples/probe/entity_particles_probe.rs index ef38f1000..cdb0344df 100644 --- a/crates/horizon-client/examples/entity_particles_probe.rs +++ b/crates/horizon-client/examples/probe/entity_particles_probe.rs @@ -13,8 +13,8 @@ fn d(v: f64) -> String { format!("{:016x}", v.to_bits()) } -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let mut out = BufWriter::new(File::create(&args[2])?); for (n, line) in BufReader::new(File::open(&args[1])?).lines().enumerate() { let c: Value = serde_json::from_str(&line?)?; diff --git a/crates/horizon-client/examples/environment_fixture.rs b/crates/horizon-client/examples/probe/environment_fixture.rs similarity index 97% rename from crates/horizon-client/examples/environment_fixture.rs rename to crates/horizon-client/examples/probe/environment_fixture.rs index 7f331962a..27846fe82 100644 --- a/crates/horizon-client/examples/environment_fixture.rs +++ b/crates/horizon-client/examples/probe/environment_fixture.rs @@ -9,8 +9,8 @@ use horizon_client::{ }; use std::{collections::HashMap, fmt::Write as _, fs, path::Path}; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: environment_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/finalize_spawn_fixture.rs b/crates/horizon-client/examples/probe/finalize_spawn_fixture.rs similarity index 99% rename from crates/horizon-client/examples/finalize_spawn_fixture.rs rename to crates/horizon-client/examples/probe/finalize_spawn_fixture.rs index 9b1ba4f38..b1b25e723 100644 --- a/crates/horizon-client/examples/finalize_spawn_fixture.rs +++ b/crates/horizon-client/examples/probe/finalize_spawn_fixture.rs @@ -388,8 +388,8 @@ fn describe(m: &Mob, all: &[Mob], regs: &SpawnRegistries) -> String { t.join(" ") } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: finalize_spawn_fixture RESOURCES INPUT OUTPUT HALLOWEEN")?, diff --git a/crates/horizon-client/examples/fire_starter_sound_probe.rs b/crates/horizon-client/examples/probe/fire_starter_sound_probe.rs similarity index 91% rename from crates/horizon-client/examples/fire_starter_sound_probe.rs rename to crates/horizon-client/examples/probe/fire_starter_sound_probe.rs index 62fab117a..18c1b487a 100644 --- a/crates/horizon-client/examples/fire_starter_sound_probe.rs +++ b/crates/horizon-client/examples/probe/fire_starter_sound_probe.rs @@ -11,8 +11,8 @@ use std::{ io::{BufRead, BufReader, BufWriter, Write}, }; -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let input = BufReader::new(File::open(&args[1])?); let mut out = BufWriter::new(File::create(&args[2])?); for line in input.lines() { diff --git a/crates/horizon-client/examples/firework_tooltip_fixture.rs b/crates/horizon-client/examples/probe/firework_tooltip_fixture.rs similarity index 92% rename from crates/horizon-client/examples/firework_tooltip_fixture.rs rename to crates/horizon-client/examples/probe/firework_tooltip_fixture.rs index 7f10278b7..385776837 100644 --- a/crates/horizon-client/examples/firework_tooltip_fixture.rs +++ b/crates/horizon-client/examples/probe/firework_tooltip_fixture.rs @@ -4,8 +4,8 @@ use horizon_client::{enchant::Enchantments, item_data::parse_stack, item_tooltip::firework_lines}; use std::{error::Error, fmt::Write, path::PathBuf}; -fn main() -> Result<(), Box> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec = crate::args().collect(); let input = std::fs::read_to_string(&args[1])?; let root = input .lines() diff --git a/crates/horizon-client/examples/first_person_probe.rs b/crates/horizon-client/examples/probe/first_person_probe.rs similarity index 99% rename from crates/horizon-client/examples/first_person_probe.rs rename to crates/horizon-client/examples/probe/first_person_probe.rs index 7b1143114..cb4c38e58 100644 --- a/crates/horizon-client/examples/first_person_probe.rs +++ b/crates/horizon-client/examples/probe/first_person_probe.rs @@ -458,8 +458,8 @@ impl HandWorld for ResetWorld<'_, '_> { } } -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let input = BufReader::new(File::open(&args[1])?); let mut out = BufWriter::new(File::create(&args[2])?); for (n, line) in input.lines().enumerate() { diff --git a/crates/horizon-client/examples/frame_limiter_probe.rs b/crates/horizon-client/examples/probe/frame_limiter_probe.rs similarity index 97% rename from crates/horizon-client/examples/frame_limiter_probe.rs rename to crates/horizon-client/examples/probe/frame_limiter_probe.rs index 7a5d4e437..b11338afc 100644 --- a/crates/horizon-client/examples/frame_limiter_probe.rs +++ b/crates/horizon-client/examples/probe/frame_limiter_probe.rs @@ -50,8 +50,8 @@ impl LimiterClock for Script { } } -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let input = BufReader::new(File::open(&args[1])?); let mut out = BufWriter::new(File::create(&args[2])?); for (n, line) in input.lines().enumerate() { diff --git a/crates/horizon-client/examples/game_loop_probe.rs b/crates/horizon-client/examples/probe/game_loop_probe.rs similarity index 99% rename from crates/horizon-client/examples/game_loop_probe.rs rename to crates/horizon-client/examples/probe/game_loop_probe.rs index 66a428162..598f480e6 100644 --- a/crates/horizon-client/examples/game_loop_probe.rs +++ b/crates/horizon-client/examples/probe/game_loop_probe.rs @@ -291,8 +291,8 @@ fn key(c: &Value, out: &mut impl Write) -> Result<()> { Ok(()) } -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); let mut out = BufWriter::new(File::create(&args[1])?); for line in BufReader::new(File::open(&args[0])?).lines() { let c: Value = serde_json::from_str(&line?)?; diff --git a/crates/horizon-client/examples/ghost_recipe_fixture.rs b/crates/horizon-client/examples/probe/ghost_recipe_fixture.rs similarity index 96% rename from crates/horizon-client/examples/ghost_recipe_fixture.rs rename to crates/horizon-client/examples/probe/ghost_recipe_fixture.rs index 0860fd409..b8c6553be 100644 --- a/crates/horizon-client/examples/ghost_recipe_fixture.rs +++ b/crates/horizon-client/examples/probe/ghost_recipe_fixture.rs @@ -13,8 +13,8 @@ use horizon_client::{ use serde_json::Value; use std::{fmt::Write as _, fs, path::Path}; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let usage = "usage: ghost_recipe_fixture RESOURCES CASES OUTPUT"; let root = Path::new(args.get(1).ok_or(usage)?); let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?; diff --git a/crates/horizon-client/examples/held_drop_fixture.rs b/crates/horizon-client/examples/probe/held_drop_fixture.rs similarity index 98% rename from crates/horizon-client/examples/held_drop_fixture.rs rename to crates/horizon-client/examples/probe/held_drop_fixture.rs index a0c5d92ba..1275021bb 100644 --- a/crates/horizon-client/examples/held_drop_fixture.rs +++ b/crates/horizon-client/examples/probe/held_drop_fixture.rs @@ -2,7 +2,7 @@ use horizon_client::command::args::GameMode; use horizon_client::items::{ItemStack, take_held_drop}; -fn main() { +pub fn main() { for mode in [ GameMode::Survival, GameMode::Creative, diff --git a/crates/horizon-client/examples/hotbar_fixture.rs b/crates/horizon-client/examples/probe/hotbar_fixture.rs similarity index 94% rename from crates/horizon-client/examples/hotbar_fixture.rs rename to crates/horizon-client/examples/probe/hotbar_fixture.rs index beac564ec..4c89a919f 100644 --- a/crates/horizon-client/examples/hotbar_fixture.rs +++ b/crates/horizon-client/examples/probe/hotbar_fixture.rs @@ -10,8 +10,8 @@ use serde_json::Value; use std::path::Path; use std::{fmt::Write as _, fs}; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let usage = "usage: hotbar_fixture RESOURCES CASES OUTPUT"; let items = Items::catalog(Path::new(args.first().and(args.get(1)).ok_or(usage)?))?; let known = |id: &str| items.get(id).is_some(); diff --git a/crates/horizon-client/examples/hud_fixture.rs b/crates/horizon-client/examples/probe/hud_fixture.rs similarity index 98% rename from crates/horizon-client/examples/hud_fixture.rs rename to crates/horizon-client/examples/probe/hud_fixture.rs index 4a4c78869..a6f27fcda 100644 --- a/crates/horizon-client/examples/hud_fixture.rs +++ b/crates/horizon-client/examples/probe/hud_fixture.rs @@ -20,8 +20,8 @@ type Result = std::result::Result>; #[path = "hud_fixture/kinds.rs"] mod kinds; -fn main() -> Result<()> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [root, inputs, output] = args.as_slice() else { return Err("usage: hud_fixture RESOURCES INPUTS OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/hud_fixture/kinds.rs b/crates/horizon-client/examples/probe/hud_fixture/kinds.rs similarity index 100% rename from crates/horizon-client/examples/hud_fixture/kinds.rs rename to crates/horizon-client/examples/probe/hud_fixture/kinds.rs diff --git a/crates/horizon-client/examples/input_probe.rs b/crates/horizon-client/examples/probe/input_probe.rs similarity index 94% rename from crates/horizon-client/examples/input_probe.rs rename to crates/horizon-client/examples/probe/input_probe.rs index b628bce5d..ae66f77a6 100644 --- a/crates/horizon-client/examples/input_probe.rs +++ b/crates/horizon-client/examples/probe/input_probe.rs @@ -11,8 +11,8 @@ fn number(v: &Value) -> f32 { fn bits(v: f32) -> u32 { if v.is_nan() { 0x7fc00000 } else { v.to_bits() } } -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); let mut out = BufWriter::new(File::create(&args[1])?); for line in BufReader::new(File::open(&args[0])?).lines() { let f: Value = serde_json::from_str(&line?)?; diff --git a/crates/horizon-client/examples/interaction_input_fixture.rs b/crates/horizon-client/examples/probe/interaction_input_fixture.rs similarity index 96% rename from crates/horizon-client/examples/interaction_input_fixture.rs rename to crates/horizon-client/examples/probe/interaction_input_fixture.rs index bb408dd88..a6beffc05 100644 --- a/crates/horizon-client/examples/interaction_input_fixture.rs +++ b/crates/horizon-client/examples/probe/interaction_input_fixture.rs @@ -82,8 +82,8 @@ impl TargetUseWorld for World { } } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let input = std::io::BufReader::new(std::fs::File::open(&args[1])?); let mut out = std::io::BufWriter::new(std::fs::File::create(&args[2])?); for (i, line) in input.lines().enumerate() { diff --git a/crates/horizon-client/examples/lan_probe.rs b/crates/horizon-client/examples/probe/lan_probe.rs similarity index 96% rename from crates/horizon-client/examples/lan_probe.rs rename to crates/horizon-client/examples/probe/lan_probe.rs index 43ce51f9d..3be556e3b 100644 --- a/crates/horizon-client/examples/lan_probe.rs +++ b/crates/horizon-client/examples/probe/lan_probe.rs @@ -14,8 +14,8 @@ fn unhex(s: &str) -> Vec { .collect() } -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let cases = std::fs::read_to_string(&args[1]).unwrap(); let mut out = String::new(); let mut games: Vec = Vec::new(); diff --git a/crates/horizon-client/examples/light_parity.rs b/crates/horizon-client/examples/probe/light_parity.rs similarity index 98% rename from crates/horizon-client/examples/light_parity.rs rename to crates/horizon-client/examples/probe/light_parity.rs index f660189a2..41c2ba784 100644 --- a/crates/horizon-client/examples/light_parity.rs +++ b/crates/horizon-client/examples/probe/light_parity.rs @@ -2,7 +2,7 @@ //! server with Horizon's light engine and compare every SkyLight/BlockLight //! value with the arrays vanilla stored. //! -//! cargo run --profile fast -p horizon-client --example light_parity -- \ +//! cargo run --profile fast -p horizon-client --example probe -- light_parity \ //! RESOURCES DIMENSION_DIR [--nether] [--chunks X0 Z0 X1 Z1] use horizon_client::{ assets::Assets, @@ -21,8 +21,8 @@ use std::{collections::HashMap, path::PathBuf}; type Arrays = HashMap>, Option>)>; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().skip(1).collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().skip(1).collect(); let root = PathBuf::from( args.first() .ok_or("usage: light_parity RESOURCES DIMENSION_DIR")?, diff --git a/crates/horizon-client/examples/probe/main.rs b/crates/horizon-client/examples/probe/main.rs new file mode 100644 index 000000000..c6f98e4ac --- /dev/null +++ b/crates/horizon-client/examples/probe/main.rs @@ -0,0 +1,215 @@ +//! Every horizon-client parity probe in one binary: `probe [arguments]` runs `.rs` as its own +//! example did (tools/test_*_parity.py, tools/oracle_harness.py, tools/audio_harness.py). Linking ~80 examples, +//! each with the whole client in it, was most of the parity job's probe build; one binary builds it once. +use std::process::{ExitCode, Termination}; + +mod ambient_fixture; +mod arrow_probe; +mod audio_attributes_fixture; +/// Sound-engine fakes the audio probes share. +mod audio_common; +mod auto_jump_probe; +mod block_entity_anim_fixture; +mod block_entity_render_fixture; +mod block_entity_tickers_fixture; +mod block_particles_fixture; +mod block_transform_fixture; +mod breaking_fixture; +mod camera_probe; +mod cauldron_fixture; +mod chat_screen_fixture; +mod cloud_fixture; +mod command_parse_fixture; +mod container_screen_probe; +mod creative_search_fixture; +mod emitter_particles_probe; +mod enchanting_fixture; +mod entity_anim_fixture; +mod entity_components_probe; +mod entity_death_loot_fixture; +mod entity_particles_probe; +mod environment_fixture; +mod finalize_spawn_fixture; +mod fire_starter_sound_probe; +mod firework_tooltip_fixture; +mod first_person_probe; +mod frame_limiter_probe; +mod game_loop_probe; +mod ghost_recipe_fixture; +mod held_drop_fixture; +mod hotbar_fixture; +mod hud_fixture; +mod input_probe; +mod interaction_input_fixture; +mod lan_probe; +mod light_parity; +mod marker_particles_probe; +mod menu_fixture; +mod mipmap_probe; +mod mob_ai_probe; +mod mob_attributes_fixture; +mod music_fixture; +mod natural_spawn_fixture; +mod options_probe; +mod pack_resources_fixture; +mod pack_screen_fixture; +mod pack_selection_fixture; +mod particle_providers_probe; +mod pick_block_data_fixture; +mod place_recipe_fixture; +mod player_sync_fixture; +mod raid_fixture; +mod random_tick_sections_probe; +mod recipe_book_fixture; +mod recipe_book_render_fixture; +mod recipe_book_view_fixture; +mod recipe_fixture; +mod scene_collision_probe; +mod scene_motion_probe; +mod scoreboard_fixture; +mod screen_layout_fixture; +mod section_mesh_fixture; +mod server_files_probe; +mod situational_music_fixture; +mod skin_image_fixture; +mod sound_engine_fixture; +mod sound_event_fixture; +mod spawn_rules_fixture; +mod sprint_probe; +mod subtitle_fixture; +mod tab_list_fixture; +mod team_rules_fixture; +mod toggle_keys_probe; +mod tooltip_display_fixture; +mod trading_fixture; +mod translucency_fixture; +mod weather_fixture; +mod world_border_render_fixture; +mod world_options_fixture; + +/// `run(name)` runs the probe module `name`; NAMES lists them. +macro_rules! probes { + ($($name:ident,)*) => { + const NAMES: &[&str] = &[$(stringify!($name)),*]; + + fn run(name: &str) -> Option { + Some(match name { + $(stringify!($name) => $name::main().report(),)* + _ => return None, + }) + } + }; +} + +probes! { + ambient_fixture, + arrow_probe, + audio_attributes_fixture, + auto_jump_probe, + block_entity_anim_fixture, + block_entity_render_fixture, + block_entity_tickers_fixture, + block_particles_fixture, + block_transform_fixture, + breaking_fixture, + camera_probe, + cauldron_fixture, + chat_screen_fixture, + cloud_fixture, + command_parse_fixture, + container_screen_probe, + creative_search_fixture, + emitter_particles_probe, + enchanting_fixture, + entity_anim_fixture, + entity_components_probe, + entity_death_loot_fixture, + entity_particles_probe, + environment_fixture, + finalize_spawn_fixture, + fire_starter_sound_probe, + firework_tooltip_fixture, + first_person_probe, + frame_limiter_probe, + game_loop_probe, + ghost_recipe_fixture, + held_drop_fixture, + hotbar_fixture, + hud_fixture, + input_probe, + interaction_input_fixture, + lan_probe, + light_parity, + marker_particles_probe, + menu_fixture, + mipmap_probe, + mob_ai_probe, + mob_attributes_fixture, + music_fixture, + natural_spawn_fixture, + options_probe, + pack_resources_fixture, + pack_screen_fixture, + pack_selection_fixture, + particle_providers_probe, + pick_block_data_fixture, + place_recipe_fixture, + player_sync_fixture, + raid_fixture, + random_tick_sections_probe, + recipe_book_fixture, + recipe_book_render_fixture, + recipe_book_view_fixture, + recipe_fixture, + scene_collision_probe, + scene_motion_probe, + scoreboard_fixture, + screen_layout_fixture, + section_mesh_fixture, + server_files_probe, + situational_music_fixture, + skin_image_fixture, + sound_engine_fixture, + sound_event_fixture, + spawn_rules_fixture, + sprint_probe, + subtitle_fixture, + tab_list_fixture, + team_rules_fixture, + toggle_keys_probe, + tooltip_display_fixture, + trading_fixture, + translucency_fixture, + weather_fixture, + world_border_render_fixture, + world_options_fixture, +} + +/// The probe's command line as its own example saw it: the program, then the arguments after the probe's name. +fn args() -> std::vec::IntoIter { + let mut args: Vec = std::env::args().collect(); + if args.len() > 1 { + args.remove(1); + } + args.into_iter() +} + +/// args(), as OsStrings. +fn args_os() -> std::vec::IntoIter { + let mut args: Vec<_> = std::env::args_os().collect(); + if args.len() > 1 { + args.remove(1); + } + args.into_iter() +} + +fn main() -> ExitCode { + let name = std::env::args().nth(1).unwrap_or_default(); + run(&name).unwrap_or_else(|| { + eprintln!( + "usage: probe [arguments...]\nprobes: {}", + NAMES.join(" ") + ); + ExitCode::from(2) + }) +} diff --git a/crates/horizon-client/examples/marker_particles_probe.rs b/crates/horizon-client/examples/probe/marker_particles_probe.rs similarity index 97% rename from crates/horizon-client/examples/marker_particles_probe.rs rename to crates/horizon-client/examples/probe/marker_particles_probe.rs index edf624e73..190751d79 100644 --- a/crates/horizon-client/examples/marker_particles_probe.rs +++ b/crates/horizon-client/examples/probe/marker_particles_probe.rs @@ -22,8 +22,8 @@ use std::{ sync::Arc, }; -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new(".local/horizon-client/26.3"); let assets = Assets::load(root)?; let facts = BlockFacts::load(root, assets.registry)?; diff --git a/crates/horizon-client/examples/menu_fixture.rs b/crates/horizon-client/examples/probe/menu_fixture.rs similarity index 98% rename from crates/horizon-client/examples/menu_fixture.rs rename to crates/horizon-client/examples/probe/menu_fixture.rs index 1da4a0278..fd226ff88 100644 --- a/crates/horizon-client/examples/menu_fixture.rs +++ b/crates/horizon-client/examples/probe/menu_fixture.rs @@ -74,8 +74,8 @@ fn state(menu: &Menu) -> String { format!("{line} | inv{items}") } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: menu_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/mipmap_probe.rs b/crates/horizon-client/examples/probe/mipmap_probe.rs similarity index 94% rename from crates/horizon-client/examples/mipmap_probe.rs rename to crates/horizon-client/examples/probe/mipmap_probe.rs index 99155fb32..fa94f4e90 100644 --- a/crates/horizon-client/examples/mipmap_probe.rs +++ b/crates/horizon-client/examples/probe/mipmap_probe.rs @@ -4,8 +4,8 @@ //! rows like VanillaMipmapOracle. use std::{fmt::Write as _, fs, path::Path}; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().skip(1).collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().skip(1).collect(); let input = fs::read_to_string(&args[0])?; let mut lines = input.lines(); let root = Path::new(lines.next().ok_or("no resources root")?); diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/probe/mob_ai_probe.rs similarity index 99% rename from crates/horizon-client/examples/mob_ai_probe.rs rename to crates/horizon-client/examples/probe/mob_ai_probe.rs index a3abb54d9..d773a509b 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/probe/mob_ai_probe.rs @@ -759,8 +759,8 @@ fn villager(m: &Mob) -> String { s } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().skip(1).collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().skip(1).collect(); if args.len() != 3 { return Err("usage: mob_ai_probe RESOURCES SCENARIOS OUTPUT".into()); } diff --git a/crates/horizon-client/examples/mob_attributes_fixture.rs b/crates/horizon-client/examples/probe/mob_attributes_fixture.rs similarity index 95% rename from crates/horizon-client/examples/mob_attributes_fixture.rs rename to crates/horizon-client/examples/probe/mob_attributes_fixture.rs index 7f8359920..f1fcec701 100644 --- a/crates/horizon-client/examples/mob_attributes_fixture.rs +++ b/crates/horizon-client/examples/probe/mob_attributes_fixture.rs @@ -6,8 +6,8 @@ use horizon_client::mobs::{Mob, MobTypes}; use horizon_core::geometry::Vec3; use std::{fmt::Write as _, fs, path::Path, sync::Arc}; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: mob_attributes_fixture RESOURCES OUTPUT")?, diff --git a/crates/horizon-client/examples/music_fixture.rs b/crates/horizon-client/examples/probe/music_fixture.rs similarity index 97% rename from crates/horizon-client/examples/music_fixture.rs rename to crates/horizon-client/examples/probe/music_fixture.rs index 29ccb99b2..02aecb373 100644 --- a/crates/horizon-client/examples/music_fixture.rs +++ b/crates/horizon-client/examples/probe/music_fixture.rs @@ -1,7 +1,6 @@ //! Replays `tools/test_music_parity.py` scripts through Horizon's //! `MusicManager` over its `SoundEngine`: `music_fixture ROOT INPUT OUTPUT`. -#[path = "audio_common/mod.rs"] -mod common; +use crate::audio_common as common; use common::{Fake, describe, f, flush}; use horizon_client::music::{Music, MusicFrequency, MusicManager}; use horizon_client::sound_engine::{Bound, MUSIC, SoundEngine, TickContext}; @@ -21,8 +20,8 @@ fn music(spec: &str) -> Option { )) } -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let mut engine = SoundEngine::new(SoundRegistry::load(std::path::Path::new(&args[1]))); engine.listening = true; let mut backend = Fake::default(); diff --git a/crates/horizon-client/examples/natural_spawn_fixture.rs b/crates/horizon-client/examples/probe/natural_spawn_fixture.rs similarity index 99% rename from crates/horizon-client/examples/natural_spawn_fixture.rs rename to crates/horizon-client/examples/probe/natural_spawn_fixture.rs index e4c9b1ce6..c19adc4e1 100644 --- a/crates/horizon-client/examples/natural_spawn_fixture.rs +++ b/crates/horizon-client/examples/probe/natural_spawn_fixture.rs @@ -508,8 +508,8 @@ fn yaw_text(entity: &str, v: f32) -> String { } } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: natural_spawn_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/options_probe.rs b/crates/horizon-client/examples/probe/options_probe.rs similarity index 94% rename from crates/horizon-client/examples/options_probe.rs rename to crates/horizon-client/examples/probe/options_probe.rs index f186af994..97c76c030 100644 --- a/crates/horizon-client/examples/options_probe.rs +++ b/crates/horizon-client/examples/probe/options_probe.rs @@ -7,8 +7,8 @@ use horizon_client::{ }; use std::{fs, io::Write}; -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); let mut names: Vec<_> = fs::read_dir(&args[0])? .map(|e| e.map(|e| e.path())) .collect::>()?; diff --git a/crates/horizon-client/examples/pack_resources_fixture.rs b/crates/horizon-client/examples/probe/pack_resources_fixture.rs similarity index 97% rename from crates/horizon-client/examples/pack_resources_fixture.rs rename to crates/horizon-client/examples/probe/pack_resources_fixture.rs index 00238fa94..80dbf3496 100644 --- a/crates/horizon-client/examples/pack_resources_fixture.rs +++ b/crates/horizon-client/examples/probe/pack_resources_fixture.rs @@ -30,8 +30,8 @@ fn types(root: &std::path::Path, file: PathBuf, key: &str) -> String { }) .collect() } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let input = fs::read_to_string(&args[1])?; let mut lines = input.lines(); let root: Vec<&str> = lines.next().ok_or("empty input")?.split(' ').collect(); diff --git a/crates/horizon-client/examples/pack_screen_fixture.rs b/crates/horizon-client/examples/probe/pack_screen_fixture.rs similarity index 98% rename from crates/horizon-client/examples/pack_screen_fixture.rs rename to crates/horizon-client/examples/probe/pack_screen_fixture.rs index ca7cba7b8..881570990 100644 --- a/crates/horizon-client/examples/pack_screen_fixture.rs +++ b/crates/horizon-client/examples/probe/pack_screen_fixture.rs @@ -66,8 +66,8 @@ pub fn encode(draws: &[Draw]) -> Value { ) } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [root, inputs, output] = args.as_slice() else { return Err("usage: pack_screen_fixture RESOURCES CASES OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/pack_selection_fixture.rs b/crates/horizon-client/examples/probe/pack_selection_fixture.rs similarity index 96% rename from crates/horizon-client/examples/pack_selection_fixture.rs rename to crates/horizon-client/examples/probe/pack_selection_fixture.rs index 65ed2471a..91c587343 100644 --- a/crates/horizon-client/examples/pack_selection_fixture.rs +++ b/crates/horizon-client/examples/probe/pack_selection_fixture.rs @@ -35,8 +35,8 @@ fn lists(m: &SelectionModel) -> Value { json!({"unselected": side(false), "selected": side(true)}) } -fn main() -> Result<()> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [inputs, output] = args.as_slice() else { return Err("usage: pack_selection_fixture INPUTS OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/particle_providers_probe.rs b/crates/horizon-client/examples/probe/particle_providers_probe.rs similarity index 99% rename from crates/horizon-client/examples/particle_providers_probe.rs rename to crates/horizon-client/examples/probe/particle_providers_probe.rs index 8b8bd1e0d..c8cd9d88d 100644 --- a/crates/horizon-client/examples/particle_providers_probe.rs +++ b/crates/horizon-client/examples/probe/particle_providers_probe.rs @@ -140,8 +140,8 @@ fn world(assets: &Assets, facts: &BlockFacts, floor: bool, water: bool) -> Resul Ok(world) } -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let root = &Path::new(".local/horizon-client").join(horizon_core::VANILLA_VERSION); let assets = Assets::load(root)?; let facts = BlockFacts::load(root, assets.registry)?; diff --git a/crates/horizon-client/examples/pick_block_data_fixture.rs b/crates/horizon-client/examples/probe/pick_block_data_fixture.rs similarity index 96% rename from crates/horizon-client/examples/pick_block_data_fixture.rs rename to crates/horizon-client/examples/probe/pick_block_data_fixture.rs index b47f56733..7496ceb8e 100644 --- a/crates/horizon-client/examples/pick_block_data_fixture.rs +++ b/crates/horizon-client/examples/probe/pick_block_data_fixture.rs @@ -78,8 +78,8 @@ fn case(line: &str) -> Option { Some(out) } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let input = fs::read_to_string( args.get(1) .ok_or("usage: pick_block_data_fixture INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/place_recipe_fixture.rs b/crates/horizon-client/examples/probe/place_recipe_fixture.rs similarity index 97% rename from crates/horizon-client/examples/place_recipe_fixture.rs rename to crates/horizon-client/examples/probe/place_recipe_fixture.rs index 1e2b66dbf..e59750aaf 100644 --- a/crates/horizon-client/examples/place_recipe_fixture.rs +++ b/crates/horizon-client/examples/probe/place_recipe_fixture.rs @@ -28,8 +28,8 @@ fn state(menu: &Menu) -> String { ) } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let usage = "usage: place_recipe_fixture RESOURCES CASES ORDERS OUTPUT"; let root = Path::new(args.get(1).ok_or(usage)?); let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?; diff --git a/crates/horizon-client/examples/player_sync_fixture.rs b/crates/horizon-client/examples/probe/player_sync_fixture.rs similarity index 96% rename from crates/horizon-client/examples/player_sync_fixture.rs rename to crates/horizon-client/examples/probe/player_sync_fixture.rs index b50a672af..034aa6400 100644 --- a/crates/horizon-client/examples/player_sync_fixture.rs +++ b/crates/horizon-client/examples/probe/player_sync_fixture.rs @@ -8,8 +8,8 @@ fn number(value: &Value) -> f64 { f64::from_bits(u64::from_str_radix(value.as_str().unwrap(), 16).unwrap()) } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let input = std::io::BufReader::new(std::fs::File::open(&args[1])?); let mut out = std::io::BufWriter::new(std::fs::File::create(&args[2])?); for line in input.lines() { diff --git a/crates/horizon-client/examples/raid_fixture.rs b/crates/horizon-client/examples/probe/raid_fixture.rs similarity index 99% rename from crates/horizon-client/examples/raid_fixture.rs rename to crates/horizon-client/examples/probe/raid_fixture.rs index dfe517e51..648851474 100644 --- a/crates/horizon-client/examples/raid_fixture.rs +++ b/crates/horizon-client/examples/probe/raid_fixture.rs @@ -459,8 +459,8 @@ fn run_codec(c: &BTreeMap<&str, &str>) -> Result { Ok(log.join(" ; ")) } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: raid_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/random_tick_sections_probe.rs b/crates/horizon-client/examples/probe/random_tick_sections_probe.rs similarity index 98% rename from crates/horizon-client/examples/random_tick_sections_probe.rs rename to crates/horizon-client/examples/probe/random_tick_sections_probe.rs index 91c861f45..27eaf8196 100644 --- a/crates/horizon-client/examples/random_tick_sections_probe.rs +++ b/crates/horizon-client/examples/probe/random_tick_sections_probe.rs @@ -51,8 +51,8 @@ impl LevelAccess for Air { fn emit(&mut self, _: LevelEvent) {} } -fn main() -> Result<(), Box> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec = crate::args().collect(); let input = std::fs::read_to_string(&args[1])?; let root = input .lines() diff --git a/crates/horizon-client/examples/recipe_book_fixture.rs b/crates/horizon-client/examples/probe/recipe_book_fixture.rs similarity index 98% rename from crates/horizon-client/examples/recipe_book_fixture.rs rename to crates/horizon-client/examples/probe/recipe_book_fixture.rs index e165dea9b..7117d4bbe 100644 --- a/crates/horizon-client/examples/recipe_book_fixture.rs +++ b/crates/horizon-client/examples/probe/recipe_book_fixture.rs @@ -57,8 +57,8 @@ fn compound(tag: &Tag) -> String { out } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let usage = "usage: recipe_book_fixture RESOURCES CASES OUTPUT"; let root = Path::new(args.get(1).ok_or(usage)?); let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?; diff --git a/crates/horizon-client/examples/recipe_book_render_fixture.rs b/crates/horizon-client/examples/probe/recipe_book_render_fixture.rs similarity index 99% rename from crates/horizon-client/examples/recipe_book_render_fixture.rs rename to crates/horizon-client/examples/probe/recipe_book_render_fixture.rs index cd904db79..702471700 100644 --- a/crates/horizon-client/examples/recipe_book_render_fixture.rs +++ b/crates/horizon-client/examples/probe/recipe_book_render_fixture.rs @@ -30,8 +30,8 @@ fn round(v: f32) -> f32 { (v * 1e4).round() / 1e4 } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let usage = "usage: recipe_book_render_fixture RESOURCES CASES OUTPUT"; let root = Path::new(args.get(1).ok_or(usage)?); let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?; diff --git a/crates/horizon-client/examples/recipe_book_view_fixture.rs b/crates/horizon-client/examples/probe/recipe_book_view_fixture.rs similarity index 98% rename from crates/horizon-client/examples/recipe_book_view_fixture.rs rename to crates/horizon-client/examples/probe/recipe_book_view_fixture.rs index 8a1e5da0e..b94952ec5 100644 --- a/crates/horizon-client/examples/recipe_book_view_fixture.rs +++ b/crates/horizon-client/examples/probe/recipe_book_view_fixture.rs @@ -15,8 +15,8 @@ use horizon_client::{ use serde_json::Value; use std::{fmt::Write as _, fs, path::Path}; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let usage = "usage: recipe_book_view_fixture RESOURCES CASES OUTPUT"; let root = Path::new(args.get(1).ok_or(usage)?); let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?; diff --git a/crates/horizon-client/examples/recipe_fixture.rs b/crates/horizon-client/examples/probe/recipe_fixture.rs similarity index 97% rename from crates/horizon-client/examples/recipe_fixture.rs rename to crates/horizon-client/examples/probe/recipe_fixture.rs index e68258e4d..8bdffecd0 100644 --- a/crates/horizon-client/examples/recipe_fixture.rs +++ b/crates/horizon-client/examples/probe/recipe_fixture.rs @@ -12,8 +12,8 @@ use horizon_client::{ }; use std::{fs, path::Path}; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: recipe_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/scene_collision_probe.rs b/crates/horizon-client/examples/probe/scene_collision_probe.rs similarity index 97% rename from crates/horizon-client/examples/scene_collision_probe.rs rename to crates/horizon-client/examples/probe/scene_collision_probe.rs index ec20eee74..95354abdf 100644 --- a/crates/horizon-client/examples/scene_collision_probe.rs +++ b/crates/horizon-client/examples/probe/scene_collision_probe.rs @@ -28,8 +28,8 @@ fn vector(value: &Value) -> Result { }; Ok(Vec3::new(number(0)?, number(1)?, number(2)?)) } -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); if args.len() != 3 { return Err("usage: scene_collision_probe RESOURCES FIXTURE_DIRECTORY RADIUS".into()); } diff --git a/crates/horizon-client/examples/scene_motion_probe.rs b/crates/horizon-client/examples/probe/scene_motion_probe.rs similarity index 99% rename from crates/horizon-client/examples/scene_motion_probe.rs rename to crates/horizon-client/examples/probe/scene_motion_probe.rs index f4ff07ebf..21977eeab 100644 --- a/crates/horizon-client/examples/scene_motion_probe.rs +++ b/crates/horizon-client/examples/probe/scene_motion_probe.rs @@ -233,8 +233,8 @@ fn snapshot(out: &mut impl Write, player: &PlayerMotion) -> Result<()> { writeln!(out, "events {}", events.join(" | "))?; Ok(()) } -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); if args.len() != 3 { return Err( "usage: scene_motion_probe RESOURCES FIXTURE_DIRECTORY --describe|REFERENCE".into(), diff --git a/crates/horizon-client/examples/scoreboard_fixture.rs b/crates/horizon-client/examples/probe/scoreboard_fixture.rs similarity index 99% rename from crates/horizon-client/examples/scoreboard_fixture.rs rename to crates/horizon-client/examples/probe/scoreboard_fixture.rs index 1fe5bab91..4a2534b32 100644 --- a/crates/horizon-client/examples/scoreboard_fixture.rs +++ b/crates/horizon-client/examples/probe/scoreboard_fixture.rs @@ -370,8 +370,8 @@ fn score_json(sc: &sb::Score) -> Value { }) } -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let registries: Value = serde_json::from_str(&fs::read_to_string(&args[1]).expect("registries")).expect("json"); let list = |k: &str| -> Vec { diff --git a/crates/horizon-client/examples/screen_layout_fixture.rs b/crates/horizon-client/examples/probe/screen_layout_fixture.rs similarity index 98% rename from crates/horizon-client/examples/screen_layout_fixture.rs rename to crates/horizon-client/examples/probe/screen_layout_fixture.rs index f364037ab..1103f3647 100644 --- a/crates/horizon-client/examples/screen_layout_fixture.rs +++ b/crates/horizon-client/examples/probe/screen_layout_fixture.rs @@ -60,8 +60,8 @@ fn draw_json(d: &ScreenDraw) -> Value { } } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let usage = "usage: screen_layout_fixture RESOURCES INPUT OUTPUT"; let banners = Banners::load(Path::new(args.get(1).ok_or(usage)?)); let input = fs::read_to_string(args.get(2).ok_or(usage)?)?; diff --git a/crates/horizon-client/examples/section_mesh_fixture.rs b/crates/horizon-client/examples/probe/section_mesh_fixture.rs similarity index 99% rename from crates/horizon-client/examples/section_mesh_fixture.rs rename to crates/horizon-client/examples/probe/section_mesh_fixture.rs index 13f1a0f1a..98a4fdc34 100644 --- a/crates/horizon-client/examples/section_mesh_fixture.rs +++ b/crates/horizon-client/examples/probe/section_mesh_fixture.rs @@ -170,8 +170,8 @@ fn scene( } Ok(json!({"name": row["name"], "quads": quads})) } -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); if args.len() != 3 { return Err( "usage: section_mesh_fixture RESOURCES (INPUT.jsonl | facts) OUTPUT.jsonl".into(), diff --git a/crates/horizon-client/examples/server_files_probe.rs b/crates/horizon-client/examples/probe/server_files_probe.rs similarity index 99% rename from crates/horizon-client/examples/server_files_probe.rs rename to crates/horizon-client/examples/probe/server_files_probe.rs index ce146be78..85b33a764 100644 --- a/crates/horizon-client/examples/server_files_probe.rs +++ b/crates/horizon-client/examples/probe/server_files_probe.rs @@ -11,8 +11,8 @@ use horizon_client::server::{ use horizon_protocol::crypto::uuid_string; use std::{fmt::Write as _, path::Path}; -fn main() -> Result<(), Box> { - let mut args = std::env::args().skip(1); +pub fn main() -> Result<(), Box> { + let mut args = crate::args().skip(1); let root = std::path::PathBuf::from(args.next().ok_or("CASES OUTPUT")?); let output = args.next().ok_or("OUTPUT")?; let mut cases: Vec<_> = std::fs::read_dir(&root)? diff --git a/crates/horizon-client/examples/situational_music_fixture.rs b/crates/horizon-client/examples/probe/situational_music_fixture.rs similarity index 96% rename from crates/horizon-client/examples/situational_music_fixture.rs rename to crates/horizon-client/examples/probe/situational_music_fixture.rs index ae47426bb..898893c09 100644 --- a/crates/horizon-client/examples/situational_music_fixture.rs +++ b/crates/horizon-client/examples/probe/situational_music_fixture.rs @@ -5,8 +5,8 @@ use horizon_client::music::{BackgroundMusic, Music, MusicTables, Situation}; use horizon_client::sound_events::normalize; use std::io::Write; -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let tables = MusicTables::load(std::path::Path::new(&args[1])); let input = std::fs::read_to_string(&args[2]).expect("input"); let mut out = std::io::BufWriter::new(std::fs::File::create(&args[3]).expect("output")); diff --git a/crates/horizon-client/examples/skin_image_fixture.rs b/crates/horizon-client/examples/probe/skin_image_fixture.rs similarity index 90% rename from crates/horizon-client/examples/skin_image_fixture.rs rename to crates/horizon-client/examples/probe/skin_image_fixture.rs index 9373fb1f5..e85be6a16 100644 --- a/crates/horizon-client/examples/skin_image_fixture.rs +++ b/crates/horizon-client/examples/probe/skin_image_fixture.rs @@ -9,8 +9,8 @@ use std::{ }; type Result = std::result::Result>; -fn main() -> Result<()> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [inputs, output] = args.as_slice() else { return Err("usage: skin_image_fixture INPUTS OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/sound_engine_fixture.rs b/crates/horizon-client/examples/probe/sound_engine_fixture.rs similarity index 98% rename from crates/horizon-client/examples/sound_engine_fixture.rs rename to crates/horizon-client/examples/probe/sound_engine_fixture.rs index c42ea8bf9..327a8e9d1 100644 --- a/crates/horizon-client/examples/sound_engine_fixture.rs +++ b/crates/horizon-client/examples/probe/sound_engine_fixture.rs @@ -1,8 +1,7 @@ //! Replays `tools/test_sound_engine_parity.py` scripts through Horizon's //! `SoundEngine` with a backend recording what an OpenAL source would hold: //! `sound_engine_fixture ROOT INPUT OUTPUT`. -#[path = "audio_common/mod.rs"] -mod common; +use crate::audio_common as common; use common::{Fake, d, describe, f, flush, result_name}; use horizon_client::sound_engine::{ Attenuation, Backend, CartSound, InstanceId, SoundEngine, SoundInstance, TickContext, @@ -12,8 +11,8 @@ use horizon_core::random::LegacyRandom; use std::collections::BTreeMap; use std::io::Write; -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let mut engine = SoundEngine::new(SoundRegistry::load(std::path::Path::new(&args[1]))); engine.listening = true; let mut backend = Fake::default(); diff --git a/crates/horizon-client/examples/sound_event_fixture.rs b/crates/horizon-client/examples/probe/sound_event_fixture.rs similarity index 97% rename from crates/horizon-client/examples/sound_event_fixture.rs rename to crates/horizon-client/examples/probe/sound_event_fixture.rs index 57c6dd7be..6b52dfc9c 100644 --- a/crates/horizon-client/examples/sound_event_fixture.rs +++ b/crates/horizon-client/examples/probe/sound_event_fixture.rs @@ -9,8 +9,8 @@ fn bits(v: f32) -> String { format!("{:08x}", v.to_bits()) } -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let registry = SoundRegistry::load(std::path::Path::new(&args[1])); let mut engine = SoundEngine::new(registry); let input = std::fs::read_to_string(&args[2]).expect("input"); diff --git a/crates/horizon-client/examples/spawn_rules_fixture.rs b/crates/horizon-client/examples/probe/spawn_rules_fixture.rs similarity index 98% rename from crates/horizon-client/examples/spawn_rules_fixture.rs rename to crates/horizon-client/examples/probe/spawn_rules_fixture.rs index dc491be00..661194f6d 100644 --- a/crates/horizon-client/examples/spawn_rules_fixture.rs +++ b/crates/horizon-client/examples/probe/spawn_rules_fixture.rs @@ -136,8 +136,8 @@ fn reason(name: &str) -> Reason { } } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: spawn_rules_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/sprint_probe.rs b/crates/horizon-client/examples/probe/sprint_probe.rs similarity index 97% rename from crates/horizon-client/examples/sprint_probe.rs rename to crates/horizon-client/examples/probe/sprint_probe.rs index ab538ffe1..5c161da4f 100644 --- a/crates/horizon-client/examples/sprint_probe.rs +++ b/crates/horizon-client/examples/probe/sprint_probe.rs @@ -20,8 +20,8 @@ fn keys(mask: u64) -> Keys { analog: None, } } -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); let mut out = BufWriter::new(File::create(&args[1])?); for line in BufReader::new(File::open(&args[0])?).lines() { let f: Value = serde_json::from_str(&line?)?; diff --git a/crates/horizon-client/examples/subtitle_fixture.rs b/crates/horizon-client/examples/probe/subtitle_fixture.rs similarity index 97% rename from crates/horizon-client/examples/subtitle_fixture.rs rename to crates/horizon-client/examples/probe/subtitle_fixture.rs index ac8e8d4d8..8f690f130 100644 --- a/crates/horizon-client/examples/subtitle_fixture.rs +++ b/crates/horizon-client/examples/probe/subtitle_fixture.rs @@ -21,8 +21,8 @@ fn pose(m: [f32; 6]) -> Value { json!(m) } -fn main() -> Result<(), Box> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> Result<(), Box> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [root, inputs, output] = args.as_slice() else { return Err("usage: subtitle_fixture RESOURCES INPUTS OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/tab_list_fixture.rs b/crates/horizon-client/examples/probe/tab_list_fixture.rs similarity index 98% rename from crates/horizon-client/examples/tab_list_fixture.rs rename to crates/horizon-client/examples/probe/tab_list_fixture.rs index aca50e204..6ea822fba 100644 --- a/crates/horizon-client/examples/tab_list_fixture.rs +++ b/crates/horizon-client/examples/probe/tab_list_fixture.rs @@ -53,8 +53,8 @@ fn runs(t: &Text) -> Value { out.into_iter().map(|(r, k)| json!([r, k])).collect() } -fn main() -> Result<()> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [root, inputs, output] = args.as_slice() else { return Err("usage: tab_list_fixture RESOURCES INPUTS OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/team_rules_fixture.rs b/crates/horizon-client/examples/probe/team_rules_fixture.rs similarity index 97% rename from crates/horizon-client/examples/team_rules_fixture.rs rename to crates/horizon-client/examples/probe/team_rules_fixture.rs index ec56b67ee..9a2d716ff 100644 --- a/crates/horizon-client/examples/team_rules_fixture.rs +++ b/crates/horizon-client/examples/probe/team_rules_fixture.rs @@ -8,8 +8,8 @@ use horizon_client::scoreboard::{self as sb, CollisionRule, NameView, Scoreboard use serde_json::{Value, json}; use std::{fs, io::Write}; -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let mut out = std::io::BufWriter::new(fs::File::create(&args[2]).expect("output")); for line in fs::read_to_string(&args[1]).expect("inputs").lines() { let c: Value = serde_json::from_str(line).expect("case"); diff --git a/crates/horizon-client/examples/toggle_keys_probe.rs b/crates/horizon-client/examples/probe/toggle_keys_probe.rs similarity index 95% rename from crates/horizon-client/examples/toggle_keys_probe.rs rename to crates/horizon-client/examples/probe/toggle_keys_probe.rs index 01ef5fd4d..d05acdd5c 100644 --- a/crates/horizon-client/examples/toggle_keys_probe.rs +++ b/crates/horizon-client/examples/probe/toggle_keys_probe.rs @@ -11,8 +11,8 @@ use std::{ io::{BufRead, BufReader, BufWriter, Write}, }; -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let input = BufReader::new(File::open(&args[1])?); let mut out = BufWriter::new(File::create(&args[2])?); for (n, line) in input.lines().enumerate() { diff --git a/crates/horizon-client/examples/tooltip_display_fixture.rs b/crates/horizon-client/examples/probe/tooltip_display_fixture.rs similarity index 93% rename from crates/horizon-client/examples/tooltip_display_fixture.rs rename to crates/horizon-client/examples/probe/tooltip_display_fixture.rs index ec61159cd..8a7525785 100644 --- a/crates/horizon-client/examples/tooltip_display_fixture.rs +++ b/crates/horizon-client/examples/probe/tooltip_display_fixture.rs @@ -3,8 +3,8 @@ use horizon_client::{item_tooltip::TooltipDisplay, items::ItemStack}; use horizon_world::nbt::Tag; use std::{error::Error, fmt::Write}; -fn main() -> Result<(), Box> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec = crate::args().collect(); let mut output = String::new(); for line in std::fs::read_to_string(&args[1])?.lines() { let fields: Vec<&str> = line.split('\t').collect(); diff --git a/crates/horizon-client/examples/trading_fixture.rs b/crates/horizon-client/examples/probe/trading_fixture.rs similarity index 99% rename from crates/horizon-client/examples/trading_fixture.rs rename to crates/horizon-client/examples/probe/trading_fixture.rs index 58824257c..c2215d327 100644 --- a/crates/horizon-client/examples/trading_fixture.rs +++ b/crates/horizon-client/examples/probe/trading_fixture.rs @@ -231,8 +231,8 @@ fn prepare(m: &mut Merchant, gossips: &mut Gossips, kv: &HashMap } } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let usage = "usage: trading_fixture RESOURCES INPUT VANILLA_OUTPUT OUTPUT"; let root = Path::new(args.get(1).ok_or(usage)?); let input = fs::read_to_string(args.get(2).ok_or(usage)?)?; diff --git a/crates/horizon-client/examples/translucency_fixture.rs b/crates/horizon-client/examples/probe/translucency_fixture.rs similarity index 93% rename from crates/horizon-client/examples/translucency_fixture.rs rename to crates/horizon-client/examples/probe/translucency_fixture.rs index 11083d6b2..8ea42c1dc 100644 --- a/crates/horizon-client/examples/translucency_fixture.rs +++ b/crates/horizon-client/examples/probe/translucency_fixture.rs @@ -14,8 +14,8 @@ struct Case { cameras: Vec<[f64; 3]>, } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().skip(1).collect(); let [input, output] = args.as_slice() else { return Err("usage: translucency_fixture INPUT OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/weather_fixture.rs b/crates/horizon-client/examples/probe/weather_fixture.rs similarity index 95% rename from crates/horizon-client/examples/weather_fixture.rs rename to crates/horizon-client/examples/probe/weather_fixture.rs index 3cf6c31be..b85dd3e09 100644 --- a/crates/horizon-client/examples/weather_fixture.rs +++ b/crates/horizon-client/examples/probe/weather_fixture.rs @@ -8,8 +8,8 @@ fn bits(value: f32) -> String { format!("{:x}", value.to_bits()) } } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let mut output = String::new(); let mut parameters = weather::ParameterCache::default(); for (case, line) in fs::read_to_string(&args[1])?.lines().enumerate() { diff --git a/crates/horizon-client/examples/world_border_render_fixture.rs b/crates/horizon-client/examples/probe/world_border_render_fixture.rs similarity index 98% rename from crates/horizon-client/examples/world_border_render_fixture.rs rename to crates/horizon-client/examples/probe/world_border_render_fixture.rs index 1de15eeeb..535118959 100644 --- a/crates/horizon-client/examples/world_border_render_fixture.rs +++ b/crates/horizon-client/examples/probe/world_border_render_fixture.rs @@ -24,8 +24,8 @@ fn doubles(v: &[f64]) -> Value { v.iter().map(|f| f.to_bits() as i64).collect() } -fn main() -> Result<()> { - let args: Vec = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().skip(1).collect(); let [inputs, output] = args.as_slice() else { return Err("usage: world_border_render_fixture INPUTS OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/world_options_fixture.rs b/crates/horizon-client/examples/probe/world_options_fixture.rs similarity index 93% rename from crates/horizon-client/examples/world_options_fixture.rs rename to crates/horizon-client/examples/probe/world_options_fixture.rs index 5bbf9f1c7..5bd3026bc 100644 --- a/crates/horizon-client/examples/world_options_fixture.rs +++ b/crates/horizon-client/examples/probe/world_options_fixture.rs @@ -2,8 +2,8 @@ use horizon_protocol::{buf::Reader, packets::play::*}; use std::{error::Error, fmt::Write}; -fn main() -> Result<(), Box> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec = crate::args().collect(); let mut output = String::new(); for line in std::fs::read_to_string(&args[1])?.lines() { let fields: Vec<&str> = line.split('\t').collect(); diff --git a/docs/parity-workflow.md b/docs/parity-workflow.md index a9a453baf..a2cd10584 100644 --- a/docs/parity-workflow.md +++ b/docs/parity-workflow.md @@ -26,7 +26,7 @@ Vanilla oracle runs are reused as well. `tools/parity_shim.py` stands in for `ja Probes build into `.local/parity-target/` with release optimisation but no LTO and 16 codegen units. On ludodesktop that rebuilds every `horizon-world` probe in 3 seconds after a one-line change, against 122 seconds with the release profile. Rust gives these settings identical results (no fast-math; overflow checks as in release), and the full harness suite passes under them. Probes that harnesses build in the dev profile get `opt-level = 3` too, keeping their overflow checks and debug assertions. Harnesses must locate binaries through `cargo metadata` or `lab.cargo_target()`, never a hard-coded `target/`. -The `horizon-world` probes are one binary, `cargo build --release -p horizon-world --example probe`: a harness runs `probe [arguments]`, and `` is a module in `crates/horizon-world/examples/probe/` (add it to the `mod` list and the `probes!` list in its `main.rs`; read arguments with `crate::args()`, which drops the name). Code several probes share goes in `examples/probe/support/`. Linking one binary instead of ~170 examples is most of what a probe build used to cost. The runner counts only the probes a harness ran, the probes and support modules they name and `dispatch.rs` as its dependencies, not `main.rs`, which only lists the probes: editing one probe reruns only its harnesses, and adding one reruns none. +The probes of `horizon-world` and of `horizon-client` are one binary per crate, `cargo build --release -p --example probe`: a harness runs `probe [arguments]`, and `` is a module in `crates//examples/probe/` (add it to the `mod` list and the `probes!` list in its `main.rs`; read arguments with `crate::args()` or `crate::args_os()`, which drop the name). Code several probes share goes in `examples/probe/support/` or a module of its own. Linking one binary instead of ~250 examples is most of what a probe build used to cost. The runner counts only the probes a harness ran, the probes and support modules they name, their own subdirectories and `dispatch.rs` as its dependencies, not `main.rs`, which only lists the probes: editing one probe reruns only its harnesses, and adding one reruns none. Passes are shared between worktrees. A harness's key depends only on the content of its dependencies, not on where they are, so every pass is also written to `parity-shared/` beside the shared vanilla data (`PARITY_SHARED` overrides it). A worktree whose files match those a harness passed with, in any worktree, counts that pass without running the harness: after merging the integration branch, an agent's gate only runs the harnesses its own changes affect. diff --git a/docs/parity/meshing.md b/docs/parity/meshing.md index 5b746e76c..bcd1cbc6a 100644 --- a/docs/parity/meshing.md +++ b/docs/parity/meshing.md @@ -20,7 +20,7 @@ emit for the same scenes. `FluidRenderer.tesselate`, then `RenderShape.MODEL` blocks through `ModelBlockRenderer.tesselateBlock` with smooth lighting on, culling on, cutout leaves, `BlockColors.createDefault()` and `state.getSeed(pos)`. -- **Horizon side**: `crates/horizon-client/examples/section_mesh_fixture.rs` +- **Horizon side**: `crates/horizon-client/examples/probe/section_mesh_fixture.rs` loads the prepared resources (`Assets`, `BlockFacts`, `Biomes`, `load_visibility`, `MeshTables`), builds the same blocks and light in real client `Chunk`s (a 3x3 chunk region), sets every biome's colours to the diff --git a/docs/rust-parity.md b/docs/rust-parity.md index fee801463..98bff8f82 100644 --- a/docs/rust-parity.md +++ b/docs/rust-parity.md @@ -1471,7 +1471,7 @@ the `hp` text when they no longer fit; and the header and footer wrapped by the list in single player unless a `list` objective is set. `tools/test_tab_list_parity.py` runs vanilla's own `extractRenderState` frame after frame (`VanillaTabListOracle`: stand-in connection, level and options, -real `Scoreboard`) against `examples/tab_list_fixture` and compares every fill, +real `Scoreboard`) against `examples/probe/tab_list_fixture.rs` and compares every fill, styled text run, sprite and face blit (as `hud_layout::GuiDraw` calls, painted like the rest of the HUD): **1,000 cases, 3,476 frames and 844,758 calls match**. The game draws the same layout while the player-list key is @@ -1492,7 +1492,7 @@ nearest first. `WorldBorder::warning_strength` feeds `hud_overlays::vignette` the border's warning strength at the camera. `tools/test_world_border_render_parity.py` drives vanilla's border, renderer and vignette (`VanillaWorldBorderRenderOracle`, with a stand-in GPU device, dynamic-uniform writer and render pass) against -`examples/world_border_render_fixture`: **1,500 cases and 16,859 frames match +`examples/probe/world_border_render_fixture.rs`: **1,500 cases and 16,859 frames match bit for bit** (8,513 with the wall drawn). The game draws the wall with `RenderPipelines.WORLD_BORDER`'s overlay blend and the mipmapped forcefield texture, and follows the server's border packets. One border is kept for all diff --git a/tools/audio_harness.py b/tools/audio_harness.py index 6a26f2d44..1d5908fe0 100644 --- a/tools/audio_harness.py +++ b/tools/audio_harness.py @@ -37,7 +37,7 @@ def require_sounds(): def run_harness(name, oracle, example, inputs_text, extra_sources=(), java_args=(), rust_args=(), scope='', timeout=1800): - """Run oracle and example on inputs; returns the number of matched lines.""" + """Run oracle and the client probe `example` on inputs; returns the number of matched lines.""" require_sounds() lock, jars, _ = base.verify_artifacts() libraries = baking.client_libraries() @@ -46,7 +46,7 @@ def run_harness(name, oracle, example, inputs_text, extra_sources=(), java_args= report = build / 'report.json' report.unlink(missing_ok=True) oracle_path = lab.ROOT / f'mods/horizon/src/test/java/dev/horizonlab/parity/{oracle}.java' - example_path = lab.ROOT / f'crates/horizon-client/examples/{example}.rs' + example_path = lab.ROOT / f'crates/horizon-client/examples/probe/{example}.rs' sources = [*COMMON_SOURCES, oracle_path, example_path, *[Path(s) for s in extra_sources]] tested = base.source_hashes(sources) inputs = build / 'inputs.txt' @@ -65,10 +65,10 @@ def run_harness(name, oracle, example, inputs_text, extra_sources=(), java_args= dependencies = os.pathsep.join(map(str, [jars['client'], *libraries])) run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle_path], 'compile-java') - run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', example], 'compile-rust') + run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory']) / 'debug/examples' / (example + ('.exe' if os.name == 'nt' else '')) - run([binary, *rust_args, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'debug/examples' / ('probe.exe' if os.name == 'nt' else 'probe') + run([binary, example, *rust_args, inputs, build / 'rust.txt'], 'rust') env = dict(os.environ, ALSOFT_DRIVERS='null') run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, f'dev.horizonlab.parity.{oracle}', *java_args, inputs, build / 'client.txt'], 'client', env=env) diff --git a/tools/interaction_lab.py b/tools/interaction_lab.py index 0851b6d06..bc574b73d 100644 --- a/tools/interaction_lab.py +++ b/tools/interaction_lab.py @@ -50,7 +50,7 @@ def cargo_example(package, example, *args, profile=None): command = ['cargo', 'run', '-q', '-j3'] if profile: command += ['--profile', profile] - command += ['-p', package, '--example', example, '--', *map(str, args)] + command += ['-p', package, '--example', 'probe', '--', example, *map(str, args)] subprocess.run(command, check=True, cwd=lab.ROOT) diff --git a/tools/oracle_harness.py b/tools/oracle_harness.py index a19b5ba94..c6f45553f 100644 --- a/tools/oracle_harness.py +++ b/tools/oracle_harness.py @@ -31,12 +31,13 @@ def compile_oracle(build, oracle_name, jars, libraries, java_major): def build_probe(build, example): - run_logged(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', example], + """Build the horizon-client probe binary; returns the command that runs probe `example`.""" + run_logged(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'probe'], build, 'compile-rust-' + example, env=dict(os.environ, CARGO_BUILD_JOBS='3')) import json metadata = json.loads(subprocess.check_output( ['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - return Path(metadata['target_directory']) / 'debug/examples' / example + return [Path(metadata['target_directory']) / 'debug/examples/probe', example] def java_run(build, classes, dependencies, main_class, args, name, jvm=()): @@ -64,13 +65,13 @@ def differential(name, oracle, probe, make_input, scope, sources=(), expected_li all_sources = [Path(__file__).resolve(), lab.ROOT / 'tools/oracle_harness.py', lab.ROOT / 'tools/test_rust_parity.py', lab.ROOT / 'tools/lab.py', oracle_path, lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock', lab.ROOT / 'crates/horizon-client/Cargo.toml', lab.ROOT / 'crates/horizon-client/src/lib.rs', - lab.ROOT / f'crates/horizon-client/examples/{probe}.rs', *map(Path, sources)] + lab.ROOT / f'crates/horizon-client/examples/probe/{probe}.rs', *map(Path, sources)] tested = base.source_hashes(all_sources) input_path, units = make_input(build) input_hash = lab.digest(input_path, 'sha256') if input_path.is_file() else None classes, dependencies, _ = compile_oracle(build, oracle, jars, libraries, lock['minecraft']['java_major']) - binary = build_probe(build, probe) - run_logged([binary, input_path, build / 'rust.txt'], build, 'rust') + command = build_probe(build, probe) + run_logged([*command, input_path, build / 'rust.txt'], build, 'rust') java_run(build, classes, dependencies, oracle, [input_path, build / 'client.txt'], 'client') try: matched = base.compare(build / 'client.txt', build / 'rust.txt') diff --git a/tools/port_regen.py b/tools/port_regen.py index be2d31843..c47e7cc35 100644 --- a/tools/port_regen.py +++ b/tools/port_regen.py @@ -229,10 +229,10 @@ def gen_vanilla_order(root, version, store, build): "dev.horizonlab.parity.VanillaCommandParseOracle", "tree", build], build) env = dict(os.environ, CARGO_TARGET_DIR=str(root / ".local" / "port-target")) jobs = os.environ.get("FLEET_LOAD_JOBS") - run(["cargo", "build", "-p", "horizon-client", "--example", "command_parse_fixture", + run(["cargo", "build", "-p", "horizon-client", "--example", "probe", *(["-j", jobs] if jobs else [])], root, env=env) - fixture = root / ".local/port-target/debug/examples/command_parse_fixture" - run([fixture, "tree", build / "rust_tree.json"], root) + fixture = root / ".local/port-target/debug/examples/probe" + run([fixture, "command_parse_fixture", "tree", build / "rust_tree.json"], root) return [python(), "tools/generate_command_order.py", build / "tree.json", build / "rust_tree.json"] diff --git a/tools/test_arrow_parity.py b/tools/test_arrow_parity.py index 0daa2e311..72692eb55 100644 --- a/tools/test_arrow_parity.py +++ b/tools/test_arrow_parity.py @@ -3,7 +3,7 @@ Real vanilla `Arrow` entities tick in an independently built copy of the scene (`VanillaArrowOracle`, client and server jars); Horizon's -`arrows::tick` runs over the scene itself (`examples/arrow_probe.rs`). Every +`arrows::tick` runs over the scene itself (`examples/probe/arrow_probe.rs`). Every operation prints the arrow's position, motion, rotation, ground state, life, shake, stuck block, fire ticks, water flags, fluid heights, removal, crit flag, fall distance and old position (what rendering interpolates from) by exact @@ -224,7 +224,7 @@ def main(): 'VanillaHeightmapOracle', 'VanillaCollisionOracle', 'VanillaBlockStateCodecOracle', 'VanillaSuffocationOracle', 'VanillaFaceSupportOracle', 'VanillaEntityAttributeOracle', 'VanillaBlockLandingOracle', 'VanillaMovementRegistryOracle', 'VanillaDamageSourceOracle']] sources = [Path(__file__), lab.ROOT / 'tools/test_native_client.py', lab.ROOT / 'tools/test_rust_parity.py', lab.ROOT / 'tools/lab.py', - oracle, *helpers, lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock', lab.ROOT / 'crates/horizon-client/examples/arrow_probe.rs'] + oracle, *helpers, lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock', lab.ROOT / 'crates/horizon-client/examples/probe/arrow_probe.rs'] for crate in ['horizon-core', 'horizon-world', 'horizon-assets', 'horizon-client']: sources += [lab.ROOT / 'crates' / crate / 'Cargo.toml', *sorted((lab.ROOT / 'crates' / crate / 'src').rglob('*.rs'))] tested = base.source_hashes(sources) @@ -241,15 +241,15 @@ def main(): expected = 3 * operations + len(fixtures) (build / 'inputs.txt').write_text(''.join(json.dumps(f, separators=(',', ':')) + '\n' for f in fixtures)) input_hash = lab.digest(build / 'inputs.txt', 'sha256') - run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'arrow_probe'], 'compile-rust') + run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory']) / 'debug/examples' / ('arrow_probe.exe' if os.name == 'nt' else 'arrow_probe') - run([binary, resources, build, '--describe'], 'describe') + binary = Path(metadata['target_directory']) / 'debug/examples' / ('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'arrow_probe',resources, build, '--describe'], 'describe') references = [] for side, jar in jars.items(): run(['java', '-Xmx768M', '-cp', os.pathsep.join([str(classes), str(jar), dependencies]), 'dev.horizonlab.parity.VanillaArrowOracle', side, build, resources], side) - run([binary, resources, build, side], 'rust-' + side) + run([binary, 'arrow_probe',resources, build, side], 'rust-' + side) matched = base.compare(build / (side + '.txt'), build / ('rust-' + side + '.txt')) if matched != expected: raise AssertionError('Incomplete arrow output') diff --git a/tools/test_auto_jump_parity.py b/tools/test_auto_jump_parity.py index da0c16b7b..21eb5ef5e 100644 --- a/tools/test_auto_jump_parity.py +++ b/tools/test_auto_jump_parity.py @@ -125,7 +125,7 @@ def main(): sources = [Path(__file__).resolve(), lab.ROOT / 'tools/oracle_harness.py', lab.ROOT / 'tools/lab.py', parity / (oracle + '.java'), parity / 'VanillaSceneCollisionOracle.java', parity / 'VanillaRegistryCollisionScanOracle.java', lab.ROOT / 'Cargo.lock', - lab.ROOT / 'crates/horizon-client/examples/auto_jump_probe.rs', + lab.ROOT / 'crates/horizon-client/examples/probe/auto_jump_probe.rs', lab.ROOT / 'crates/horizon-client/src/auto_jump.rs', lab.ROOT / 'crates/horizon-client/src/motion.rs'] tested = base.source_hashes(sources) fixtures = list(cases(random.Random(0x4155544f))) @@ -133,8 +133,8 @@ def main(): inputs.write_text(''.join(json.dumps(f, separators=(',', ':')) + '\n' for f in fixtures)) input_hash = lab.digest(inputs, 'sha256') classes, dependencies, _ = harness.compile_oracle(build, oracle, jars, libraries, lock['minecraft']['java_major']) - binary = harness.build_probe(build, 'auto_jump_probe') - harness.run_logged([binary, resources, inputs, build / 'rust.txt', build / 'scene.json'], build, 'rust', timeout=3600) + command = harness.build_probe(build, 'auto_jump_probe') + harness.run_logged([*command, resources, inputs, build / 'rust.txt', build / 'scene.json'], build, 'rust', timeout=3600) harness.java_run(build, classes, dependencies, oracle, [inputs, build / 'client.txt', resources, build / 'scene.json'], 'client') matched = harness.compare(build / 'client.txt', build / 'rust.txt', 2 * len(fixtures)) base.ensure_sources_unchanged(sources, tested) diff --git a/tools/test_block_entity_anim_parity.py b/tools/test_block_entity_anim_parity.py index 8935afef4..b0c462aee 100755 --- a/tools/test_block_entity_anim_parity.py +++ b/tools/test_block_entity_anim_parity.py @@ -9,7 +9,7 @@ on a stand-in client level, then per scripted step applies the block event (triggerEvent), runs the entity's own client ticker and the renderer's extractRenderState, printing the fields, the level calls the tick made (neighbour updates, entity pushes/queries, sounds, particles) and the render -state. `examples/block_entity_anim_fixture` replays the steps through +state. `examples/probe/block_entity_anim_fixture` replays the steps through `horizon_client::block_entity_anim` and derives the render state from the `BlockAnim` Horizon's renderer reads. Lines must match exactly (floats as bits). @@ -279,8 +279,8 @@ def main(): *(PARITY / f'{n}.java' for n in ('ParityData', 'VanillaBlockEntityAnimOracle'))], 'compile-java') run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaBlockEntityAnimOracle', inputs, build / 'vanilla.txt'], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'block_entity_anim_fixture', '--', - resources, inputs, build / 'rust.txt'], 'rust') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'block_entity_anim_fixture', resources, inputs, build / 'rust.txt'], 'rust') def split(path): result, current = {}, None diff --git a/tools/test_block_entity_render_parity.py b/tools/test_block_entity_render_parity.py index 3c096bdcc..901f4300f 100644 --- a/tools/test_block_entity_render_parity.py +++ b/tools/test_block_entity_render_parity.py @@ -5,7 +5,7 @@ The Java oracle (VanillaBlockEntityRenderOracle) builds each case's vanilla block entity, sets its animation fields, runs the real BlockEntityRenderer's extractRenderState and submit, and captures what it submits: model vertices after setupAnim and the pose stack (sprite-local UVs, tint, normal, light), -text calls and items. `examples/block_entity_render_fixture` replays the case +text calls and items. `examples/probe/block_entity_render_fixture` replays the case through Horizon's BlockEntityRenderer. Quads are matched by texture and position; colours compare vanilla's tint times the entity shader's `minecraft_mix_light` for the vanilla normal with Horizon's baked colour. @@ -303,8 +303,8 @@ def main(): vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] textures = sorted({s['texture'] for v in vanilla for s in v.get('submits', []) if 'texture' in s}) (build / 'textures.txt').write_text(''.join(t + '\n' for t in textures)) - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'block_entity_render_fixture', '--', - resources, inputs, build / 'textures.txt', build / 'rust.jsonl'], 'rust') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'block_entity_render_fixture', resources, inputs, build / 'textures.txt', build / 'rust.jsonl'], 'rust') rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] assert len(vanilla) == len(rust), (len(vanilla), len(rust)) groups, errors, skipped, passed = {}, {}, {}, 0 diff --git a/tools/test_block_entity_tickers_parity.py b/tools/test_block_entity_tickers_parity.py index 459e7a926..66a84cf48 100644 --- a/tools/test_block_entity_tickers_parity.py +++ b/tools/test_block_entity_tickers_parity.py @@ -6,7 +6,7 @@ one chunk to make its block entity map grow), place, replace and remove block entities, give jukeboxes a record and take it, and unload chunks, with ticks in between. `VanillaBlockEntityTickerOracle` runs them on real `LevelChunk`s of a server level and prints, after each tick, the positions of the live -tickers in list order; `examples/block_entity_tickers_fixture` runs the same +tickers in list order; `examples/probe/block_entity_tickers_fixture` runs the same on `horizon_client::block_entities::BlockEntities`. The block entities are the kinds the game ticks in that list (hoppers, furnaces, beacons, spawners, trial spawners, vaults, hives, crafters, brewing stands, jukebox), with chests and barrels, @@ -120,7 +120,7 @@ def main(): run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaBlockEntityTickerOracle', inputs, build / 'vanilla.txt'], 'vanilla') run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', - 'block_entity_tickers_fixture', '--', inputs, build / 'rust.txt'], 'rust') + 'probe', '--', 'block_entity_tickers_fixture', inputs, build / 'rust.txt'], 'rust') matched = base.compare(build / 'vanilla.txt', build / 'rust.txt') ticks = sum(1 for line in lines if line == 'tick') listed = sum(len(line.split()) - 1 for line in (build / 'vanilla.txt').read_text().splitlines()) diff --git a/tools/test_block_particles_parity.py b/tools/test_block_particles_parity.py index 3f0f0f99c..7e08e98f8 100644 --- a/tools/test_block_particles_parity.py +++ b/tools/test_block_particles_parity.py @@ -13,7 +13,7 @@ def main(): resources = lab.RESOURCES build = lab.LOCAL / "block-particles-parity" build.mkdir(exist_ok=True) - paths = [lab.ROOT / p for p in ["tools/test_block_particles_parity.py", "tools/test_breaking_model_parity.py", "tools/oracle_harness.py", "tools/lab.py", "crates/horizon-client/src/particles.rs", "crates/horizon-client/src/game.rs", "crates/horizon-client/src/blocks.rs", "crates/horizon-client/src/mesher.rs", "crates/horizon-client/examples/block_particles_fixture.rs", "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockParticlesOracle.java", "crates/horizon-core/src/random.rs", "Cargo.lock", "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameplayFactsExporter.java"]] + paths = [lab.ROOT / p for p in ["tools/test_block_particles_parity.py", "tools/test_breaking_model_parity.py", "tools/oracle_harness.py", "tools/lab.py", "crates/horizon-client/src/particles.rs", "crates/horizon-client/src/game.rs", "crates/horizon-client/src/blocks.rs", "crates/horizon-client/src/mesher.rs", "crates/horizon-client/examples/probe/block_particles_fixture.rs", "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockParticlesOracle.java", "crates/horizon-core/src/random.rs", "Cargo.lock", "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameplayFactsExporter.java"]] tested = base.source_hashes(paths) rows = [dict(case=i, seed=(-1 if i % 2 else 1) * i * 987654321, **row) for i, row in enumerate(breaking.cases(resources))] rows[0]["seed"] = -(2**63) @@ -21,8 +21,8 @@ def main(): inputs = build / "inputs.jsonl" inputs.write_text("".join(json.dumps(row)+"\n" for row in rows)) classes, dependencies, _ = harness.compile_oracle(build, "VanillaBlockParticlesOracle", jars, baking.client_libraries(), lock["minecraft"]["java_major"]) - binary = harness.build_probe(build, "block_particles_fixture") - harness.run_logged([binary, resources, inputs, build / "rust.jsonl"], build, "rust") + command = harness.build_probe(build, "block_particles_fixture") + harness.run_logged([*command, resources, inputs, build / "rust.jsonl"], build, "rust") harness.java_run(build, classes, dependencies, "VanillaBlockParticlesOracle", [inputs, build / "client.jsonl"], "client") count = hits = burst = 0 max_error = 0.0 diff --git a/tools/test_breaking_model_parity.py b/tools/test_breaking_model_parity.py index 92b74d582..272e57dea 100644 --- a/tools/test_breaking_model_parity.py +++ b/tools/test_breaking_model_parity.py @@ -29,13 +29,13 @@ def canonical(quads): def main(): lock,jars,_=base.verify_artifacts();libraries=baking.client_libraries() resources=lab.RESOURCES;build=lab.LOCAL/"breaking-model-parity";build.mkdir(exist_ok=True) - paths=[lab.ROOT/"tools/test_breaking_model_parity.py",lab.ROOT/"crates/horizon-client/src/breaking.rs",lab.ROOT/"crates/horizon-client/src/game.rs",lab.ROOT/"crates/horizon-client/src/gfx.rs",lab.ROOT/"crates/horizon-client/src/entity.wgsl",lab.ROOT/"crates/horizon-client/src/models/catalog.rs",lab.ROOT/"crates/horizon-client/src/mesher.rs",lab.ROOT/"crates/horizon-client/src/camera.rs",lab.ROOT/"crates/horizon-client/examples/breaking_fixture.rs",lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBreakingModelOracle.java",lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSectionMeshOracle.java",lab.ROOT/"Cargo.lock"] + paths=[lab.ROOT/"tools/test_breaking_model_parity.py",lab.ROOT/"crates/horizon-client/src/breaking.rs",lab.ROOT/"crates/horizon-client/src/game.rs",lab.ROOT/"crates/horizon-client/src/gfx.rs",lab.ROOT/"crates/horizon-client/src/entity.wgsl",lab.ROOT/"crates/horizon-client/src/models/catalog.rs",lab.ROOT/"crates/horizon-client/src/mesher.rs",lab.ROOT/"crates/horizon-client/src/camera.rs",lab.ROOT/"crates/horizon-client/examples/probe/breaking_fixture.rs",lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBreakingModelOracle.java",lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSectionMeshOracle.java",lab.ROOT/"Cargo.lock"] tested=base.source_hashes(paths) rows=[dict(case=i,**row) for i,row in enumerate(cases(resources))] inputs=build/"inputs.jsonl";inputs.write_text("".join(json.dumps(row)+"\n" for row in rows)) classes,dependencies,_=harness.compile_oracle(build,"VanillaBreakingModelOracle",jars,libraries,lock["minecraft"]["java_major"]) - binary=harness.build_probe(build,"breaking_fixture") - harness.run_logged([binary,resources,inputs,build/"rust.jsonl"],build,"rust") + command=harness.build_probe(build,"breaking_fixture") + harness.run_logged([*command,resources,inputs,build/"rust.jsonl"],build,"rust") harness.java_run(build,classes,dependencies,"VanillaBreakingModelOracle",[inputs,build/"client.jsonl"],"client") count=vertices=0;max_error=0.0 with (build/"client.jsonl").open() as native, (build/"rust.jsonl").open() as rust: diff --git a/tools/test_chat_screen_parity.py b/tools/test_chat_screen_parity.py index 1447ebaa6..fead1b5cb 100644 --- a/tools/test_chat_screen_parity.py +++ b/tools/test_chat_screen_parity.py @@ -8,7 +8,7 @@ all, history up and down, Tab and Shift+Tab through suggestions, Escape) and clicks (on the suggestion list, on the input). The Java oracle (VanillaChatScreenOracle) drives a real ChatScreen, whose CommandSuggestions parse with vanilla's client command tree and ask the server's dispatcher -for the suggestions a node leaves to it; examples/chat_screen_fixture runs +for the suggestions a node leaves to it; examples/probe/chat_screen_fixture runs horizon_client::chat::ChatScreen on Horizon's dispatcher. After the actions the input's value, cursor, selection and scroll and the screen's GUI calls (the input background, the EditBox with its argument colouring, cursor, diff --git a/tools/test_command_parse_parity.py b/tools/test_command_parse_parity.py index 192cc5b9f..c43e66b54 100644 --- a/tools/test_command_parse_parity.py +++ b/tools/test_command_parse_parity.py @@ -64,9 +64,9 @@ def main(): registries = json.loads((build / 'registries.json').read_text()) corpus = corpus_module.corpus(tree, registries) (build / 'corpus.txt').write_text(''.join(line + '\n' for line in corpus), encoding='utf-8') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'command_parse_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('command_parse_fixture.exe' if os.name == 'nt' else 'command_parse_fixture') + binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') resources = lab.RESOURCES total_failures = 0 summary = [] @@ -79,7 +79,7 @@ def main(): if not (stamp.exists() and stamp.read_text() == digest and (level_dir / 'vanilla.jsonl').exists()): java('run', str(level_dir), str(build / 'corpus.txt'), str(permission)) stamp.write_text(digest) - run([binary, resources, build / 'registries.json', build / 'corpus.txt', str(permission), level_dir / 'rust.jsonl'], f'rust{permission}') + run([binary, 'command_parse_fixture',resources, build / 'registries.json', build / 'corpus.txt', str(permission), level_dir / 'rust.jsonl'], f'rust{permission}') failures = compare(level_dir / 'vanilla.jsonl', level_dir / 'rust.jsonl', args.limit) count = sum(1 for _ in (level_dir / 'vanilla.jsonl').open()) print(f'permission {permission}: {count - failures}/{count} commands match', flush=True) diff --git a/tools/test_creative_parity.py b/tools/test_creative_parity.py index aa23cbbc9..6a96d3c52 100644 --- a/tools/test_creative_parity.py +++ b/tools/test_creative_parity.py @@ -7,7 +7,7 @@ tab built by vanilla's CreativeModeTabs over the vanilla data pack's registries), then what the vanilla client shows: every tab's display items and, for each search query, CreativeModeInventoryScreen.refreshSearchResults' items, searched through the client's own SessionSearchTrees. -examples/creative_search_fixture loads the export into +examples/probe/creative_search_fixture loads the export into horizon_client::creative::Creative. The tabs it shows (id, title, icon, position, every stack with its components), the search tab's stacks and the results of every query must agree. The queries are QUERIES below, then every diff --git a/tools/test_enchanting_parity.py b/tools/test_enchanting_parity.py index 4b5c975d0..9f5f5647f 100644 --- a/tools/test_enchanting_parity.py +++ b/tools/test_enchanting_parity.py @@ -42,7 +42,7 @@ def main(): catalog = json.loads((resources / 'items.json').read_text()) items = sorted(k for k, v in catalog.items() if 'minecraft:enchantable' in v) oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEnchantingOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/enchanting_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/enchanting_fixture.rs', *sorted((lab.ROOT / 'crates/horizon-client/src').glob('*.rs'))] tested = base.source_hashes(sources) inputs = build / 'inputs.txt' @@ -56,10 +56,10 @@ def main(): with (build / (name + '.log')).open('w', encoding='utf-8') as log: base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT) run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'), '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'enchanting_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('enchanting_fixture.exe' if os.name == 'nt' else 'enchanting_fixture') - run([binary, resources, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'enchanting_fixture',resources, inputs, build / 'rust.txt'], 'rust') references = [] for side in ['server']: run(['java', '-Xmx1G', '-cp', os.pathsep.join([str(classes), str(jars[side]), deps]), 'dev.horizonlab.parity.VanillaEnchantingOracle', inputs, build / f'{side}.txt'], side) diff --git a/tools/test_entity_death_loot_parity.py b/tools/test_entity_death_loot_parity.py index 000a2ea6f..b0f77cbfd 100644 --- a/tools/test_entity_death_loot_parity.py +++ b/tools/test_entity_death_loot_parity.py @@ -122,7 +122,7 @@ def main(): tables = resources / 'data/minecraft/loot_table/entities' types = sorted('minecraft:' + p.stem for p in tables.glob('*.json') if p.stem not in SKIPPED) oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityDeathLootOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/entity_death_loot_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/entity_death_loot_fixture.rs', lab.ROOT / 'crates/horizon-client/src/mobs/drops.rs', lab.ROOT / 'crates/horizon-world/src/loot.rs'] tested = base.source_hashes(sources) inputs = build / 'inputs.txt' @@ -139,10 +139,10 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx2G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaEntityDeathLootOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'entity_death_loot_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/entity_death_loot_fixture' - run([binary, resources, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples/probe' + run([binary, 'entity_death_loot_fixture', resources, inputs, build / 'rust.txt'], 'rust') errors = [l for l in (build / 'server.txt').read_text().splitlines() if l.startswith('error ')] if errors: raise SystemExit(f'oracle errors ({len(errors)}): {errors[:5]}') diff --git a/tools/test_entity_model_parity.py b/tools/test_entity_model_parity.py index 37c61b4ac..ba54797fa 100644 --- a/tools/test_entity_model_parity.py +++ b/tools/test_entity_model_parity.py @@ -4,7 +4,7 @@ The Java oracle bakes each vanilla model layer, builds the model's own render state class with the generated walk/age/head/attack inputs (plus per-species state fields), runs the real `setupAnim` and writes every part's pose. -`examples/entity_anim_fixture` replays the same inputs through Horizon's +`examples/probe/entity_anim_fixture` replays the same inputs through Horizon's `mobs::anim::setup` and the loaded model tree; the two must agree on every part pose and on the baked polygon count and vertex sums. @@ -364,8 +364,8 @@ def main(): run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', dependencies, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaEntityAnimOracle', inputs, build / 'vanilla.jsonl', jars['client']], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'entity_anim_fixture', '--', - resources, build / 'vanilla.jsonl', build / 'rust.jsonl'], 'rust') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'entity_anim_fixture', resources, build / 'vanilla.jsonl', build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] assert len(vanilla) == len(rust), (len(vanilla), len(rust)) diff --git a/tools/test_entity_particles_parity.py b/tools/test_entity_particles_parity.py index 2156f97ec..b89a5b675 100644 --- a/tools/test_entity_particles_parity.py +++ b/tools/test_entity_particles_parity.py @@ -79,8 +79,8 @@ def main(): cases_path, units = make_cases(build) classes, dependencies, _ = harness.compile_oracle(build, oracle, jars, baking.client_libraries(), lock['minecraft']['java_major']) - binary = harness.build_probe(build, probe) - harness.run_logged([binary, cases_path, build / 'rust.txt'], build, 'rust') + command = harness.build_probe(build, probe) + harness.run_logged([*command, cases_path, build / 'rust.txt'], build, 'rust') harness.java_run(build, classes, dependencies, oracle, [cases_path, build / 'client.txt'], 'client') vanilla = (build / 'client.txt').read_text().splitlines() rust = (build / 'rust.txt').read_text().splitlines() diff --git a/tools/test_environment_render_parity.py b/tools/test_environment_render_parity.py index 2e14bb356..893a1c70d 100755 --- a/tools/test_environment_render_parity.py +++ b/tools/test_environment_render_parity.py @@ -5,7 +5,7 @@ The Java oracle builds vanilla's `EnvironmentAttributeSystem` from the data pack (dimension attributes, one biome's attributes, the dimension timelines and the weather layers) and prints every visual/gameplay attribute for a grid of dimensions, world times, rain/thunder levels and biomes. -`examples/environment_fixture` samples the same cases through Horizon's +`examples/probe/environment_fixture` samples the same cases through Horizon's `Environment::sample` + `apply_weather`; every attribute Horizon computes must agree with vanilla. @@ -66,8 +66,8 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx1G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaEnvironmentOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'environment_fixture', '--', - resources, inputs, build / 'rust.jsonl'], 'rust') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'environment_fixture', resources, inputs, build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] assert len(vanilla) == len(rust), (len(vanilla), len(rust)) diff --git a/tools/test_finalize_spawn_parity.py b/tools/test_finalize_spawn_parity.py index 7c995fa83..c3130d380 100644 --- a/tools/test_finalize_spawn_parity.py +++ b/tools/test_finalize_spawn_parity.py @@ -118,7 +118,7 @@ def main(): lock, jars, libraries = base.verify_artifacts() resources = lab.RESOURCES oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFinalizeSpawnOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/finalize_spawn_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/finalize_spawn_fixture.rs', lab.ROOT / 'crates/horizon-client/src/mobs/finalize.rs'] tested = base.source_hashes([s for s in sources if s.exists()]) inputs = build / 'inputs.txt' @@ -148,10 +148,10 @@ def main(): print(f'{len(vanilla)} oracle lines') return halloween = vanilla[0].split()[1] - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'finalize_spawn_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/finalize_spawn_fixture' - run([binary, resources, inputs, build / 'rust.txt', halloween], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples/probe' + run([binary, 'finalize_spawn_fixture', resources, inputs, build / 'rust.txt', halloween], 'rust') rust = (build / 'rust.txt').read_text().splitlines() bad = [(a, b) for a, b in zip(vanilla, rust) if a != b] if bad or len(vanilla) != len(rust): diff --git a/tools/test_firework_tooltip_parity.py b/tools/test_firework_tooltip_parity.py index b3114c01a..14a4138b5 100644 --- a/tools/test_firework_tooltip_parity.py +++ b/tools/test_firework_tooltip_parity.py @@ -4,7 +4,7 @@ Random rockets (flight durations 0 to 3 and higher, up to six explosions, runs of equal ones) and stars, with dye and custom colours, fade colours, trails and twinkles, some without the component (a rocket's default) and some whose tooltip_display hides it. Vanilla prints what `Fireworks.addToTooltip` and `FireworkExplosion.addToTooltip` add -(VanillaFireworkTooltipOracle); Horizon what `item_tooltip::firework_lines` gives (examples/firework_tooltip_fixture). +(VanillaFireworkTooltipOracle); Horizon what `item_tooltip::firework_lines` gives (examples/probe/firework_tooltip_fixture). """ import random try: diff --git a/tools/test_ghost_recipe_parity.py b/tools/test_ghost_recipe_parity.py index ad722109b..ac902a68c 100644 --- a/tools/test_ghost_recipe_parity.py +++ b/tools/test_ghost_recipe_parity.py @@ -10,7 +10,7 @@ against the real menu for every display of the recipe and prints the GhostSlots it fills: the menu slot, whether it is the result and the stacks the slot cycles through (PlaceRecipeHelper's centred placement of shaped recipes, the first slots for shapeless ones, every fuel for an empty fuel slot); -examples/ghost_recipe_fixture prints the same from +examples/probe/ghost_recipe_fixture prints the same from horizon_client::recipe_book::Book::ghost, which the game fills its ghost slots from. The lines must agree. """ diff --git a/tools/test_held_drop_parity.py b/tools/test_held_drop_parity.py index 842ad3d8a..faed08959 100644 --- a/tools/test_held_drop_parity.py +++ b/tools/test_held_drop_parity.py @@ -35,7 +35,7 @@ def main(): 'dev.horizonlab.parity.VanillaHeldDropOracle', str(build / 'vanilla.txt')], check=True) with (build / 'rust.txt').open('w') as out: subprocess.run(['cargo', 'run', '--quiet', '-p', 'horizon-client', '--example', - 'held_drop_fixture'], cwd=lab.ROOT, stdout=out, check=True) + 'probe'], cwd=lab.ROOT, stdout=out, check=True) matched = base.compare(build / 'vanilla.txt', build / 'rust.txt') print(f'Held drop parity passed: {matched} inventory/drop/swing/packet snapshots match vanilla') diff --git a/tools/test_hotbar_parity.py b/tools/test_hotbar_parity.py index 336bda274..b8c83b87c 100644 --- a/tools/test_hotbar_parity.py +++ b/tools/test_hotbar_parity.py @@ -9,7 +9,7 @@ id), rows of the wrong size or type and garbage. The Java oracle (VanillaHotbarOracle) writes the file and loads it with the client's real HotbarManager and DataFixers (DataFixTypes.HOTBAR, so EmptyItemInHotbarFix and every item stack fixer), then Hotbar.load on each row; -examples/hotbar_fixture runs horizon_client::hotbar on the same tag. The nine +examples/probe/hotbar_fixture runs horizon_client::hotbar on the same tag. The nine rows' stacks are compared. """ import argparse diff --git a/tools/test_hud_parity.py b/tools/test_hud_parity.py index a0baa3214..4dcd19a7b 100644 --- a/tools/test_hud_parity.py +++ b/tools/test_hud_parity.py @@ -5,7 +5,7 @@ The Java oracle (VanillaHudOracle) runs vanilla's own code on a stand-in client whose player answers from the case, and records every GuiGraphicsExtractor blit (sprite, texture, position, size, region, colour, pose), fill, text call (string, style runs, position, colour, shadow, pose) -and hotbar item (slot, position, seed, pose). `examples/hud_fixture` lays +and hotbar item (slot, position, seed, pose). `examples/probe/hud_fixture` lays out the same state with `horizon_client::hud_layout`, `hud_overlays` and `chat`; the ordered call lists (and any state read back) must agree. @@ -114,8 +114,8 @@ def main(): *(PARITY / f'{n}.java' for n in ('ParityData', 'ParityFont', 'VanillaHudOracle'))], 'compile-java') run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaHudOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'hud_fixture', '--', - resources, inputs, build / 'rust.jsonl'], 'rust') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'hud_fixture', resources, inputs, build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] assert len(vanilla) == len(rust) diff --git a/tools/test_light_parity.py b/tools/test_light_parity.py index ad3945ba8..3ed2351fa 100755 --- a/tools/test_light_parity.py +++ b/tools/test_light_parity.py @@ -4,7 +4,7 @@ Builds a scene of slabs, stairs, snow layers, trapdoors, lanterns, glass, leaves, water and glowstone in a fresh vanilla world, lets the vanilla light engine settle, stops the server so the SkyLight/BlockLight arrays are saved, -then relights every saved chunk with `examples/light_parity` and requires every +then relights every saved chunk with `examples/probe/light_parity` and requires every value to agree. The example also replays block edits through the incremental `light::relight` and checks them against a full relight. @@ -92,7 +92,7 @@ def main(): dimension = run / 'world' for extra in (['--chunks', '0', '0', '2', '3'], ['--incremental', '100']): status = subprocess.run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', - '--example', 'light_parity', '--', str(RESOURCES), str(dimension), *extra], + '--example', 'probe', '--', 'light_parity', str(RESOURCES), str(dimension), *extra], cwd=ROOT).returncode if status: sys.exit('light mismatch against vanilla') diff --git a/tools/test_local_input_parity.py b/tools/test_local_input_parity.py index 2873f11a7..adfea1a4b 100644 --- a/tools/test_local_input_parity.py +++ b/tools/test_local_input_parity.py @@ -35,7 +35,7 @@ def main(): build=lab.LOCAL/'rust-local-input';build.mkdir(exist_ok=True) report=build/'report.json';report.unlink(missing_ok=True) oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLocalInputOracle.java' - sources=[Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_model_baking_parity.py',lab.ROOT/'tools/lab.py',oracle,lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-client/Cargo.toml',lab.ROOT/'crates/horizon-client/src/input.rs',lab.ROOT/'crates/horizon-client/src/lib.rs',lab.ROOT/'crates/horizon-client/examples/input_probe.rs'] + sources=[Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_model_baking_parity.py',lab.ROOT/'tools/lab.py',oracle,lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-client/Cargo.toml',lab.ROOT/'crates/horizon-client/src/input.rs',lab.ROOT/'crates/horizon-client/src/lib.rs',lab.ROOT/'crates/horizon-client/examples/probe/input_probe.rs'] tested=base.source_hashes(sources) def run(command,name): with (build/(name+'.log')).open('w') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=600,stdout=log,stderr=subprocess.STDOUT) @@ -44,10 +44,10 @@ def main(): classes=build/'classes';classes.mkdir(exist_ok=True) dependencies=os.pathsep.join(map(str,[jars['client'],*libraries])) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',dependencies,'-d',classes,oracle],'compile-java') - run(['cargo','build','--locked','-p','horizon-client','--example','input_probe'],'compile-rust') + run(['cargo','build','--locked','-p','horizon-client','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT)) - binary=Path(metadata['target_directory'])/'debug/examples'/('input_probe.exe' if os.name=='nt' else 'input_probe') - run([binary,inputs,build/'rust.txt'],'rust') + binary=Path(metadata['target_directory'])/'debug/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'input_probe',inputs,build/'rust.txt'],'rust') run(['java','-Xmx768M','-cp',str(classes)+os.pathsep+dependencies,'dev.horizonlab.parity.VanillaLocalInputOracle',inputs,build/'client.txt'],'client') matched=base.compare(build/'client.txt',build/'rust.txt') if matched!=len(fixtures):raise AssertionError('Incomplete input output') diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index 01ed4680f..07f41b2af 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -467,7 +467,7 @@ def main(): 'dev.horizonlab.parity.VanillaMobAiOracle', inputs, build / 'vanilla.txt', world], build, 'vanilla', timeout=3600) if not args.java_only: - command = ['cargo', 'build', '--locked', '--release', '-p', 'horizon-client', '--example', 'mob_ai_probe'] + command = ['cargo', 'build', '--locked', '--release', '-p', 'horizon-client', '--example', 'probe'] target, env = lab.cargo_target(), None if args.trace: target = lab.LOCAL / 'mob-ai-trace-target' @@ -475,8 +475,8 @@ def main(): env = dict(os.environ, CARGO_TARGET_DIR=str(target), CARGO_PROFILE_RELEASE_DEBUG='line-tables-only', CARGO_PROFILE_RELEASE_LTO='false', CARGO_PROFILE_RELEASE_CODEGEN_UNITS='16') oracle_harness.run_logged(command, build, 'compile-rust', env=env) - binary = target / 'release/examples/mob_ai_probe' - oracle_harness.run_logged([binary, lab.RESOURCES, inputs, build / 'horizon.txt'], build, 'horizon') + binary = target / 'release/examples/probe' + oracle_harness.run_logged([binary, 'mob_ai_probe', lab.RESOURCES, inputs, build / 'horizon.txt'], build, 'horizon') if args.java_only: return names = {s[0] for _, s in chosen} diff --git a/tools/test_mob_attributes_parity.py b/tools/test_mob_attributes_parity.py index 1e4057eb7..6cefdc4b8 100755 --- a/tools/test_mob_attributes_parity.py +++ b/tools/test_mob_attributes_parity.py @@ -62,10 +62,10 @@ def main(): subprocess.run(list(map(str, cmd)), cwd=lab.ROOT, check=True, timeout=3600, stdout=log, stderr=subprocess.STDOUT) run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx1G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaMobAttributesOracle', build / 'vanilla.txt'], 'java') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'mob_attributes_fixture'], 'compile-rust') - binary = lab.cargo_target() / 'release/examples/mob_attributes_fixture' + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') + binary = lab.cargo_target() / 'release/examples/probe' resources = lab.RESOURCES - run([binary, resources, build / 'rust.txt'], 'rust') + run([binary, 'mob_attributes_fixture', resources, build / 'rust.txt'], 'rust') vanilla, rust = parse(build / 'vanilla.txt'), parse(build / 'rust.txt') problems = [] living = [i for i, r in vanilla.items() if 'attrs' in r] diff --git a/tools/test_native_scene_collision.py b/tools/test_native_scene_collision.py index a70cf48fb..8efc6946b 100644 --- a/tools/test_native_scene_collision.py +++ b/tools/test_native_scene_collision.py @@ -70,7 +70,7 @@ def main(): sources = [Path(__file__), lab.ROOT/'tools/test_native_client.py', lab.ROOT/'tools/test_rust_parity.py', lab.ROOT/'tools/lab.py', lab.ROOT/'tools/prepare_native_client.py', oracle, *helpers, lab.ROOT/'Cargo.toml', lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-client/examples/scene_collision_probe.rs'] + lab.ROOT/'crates/horizon-client/examples/probe/scene_collision_probe.rs'] for crate in ['horizon-core', 'horizon-world', 'horizon-assets', 'horizon-client']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml', *sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] tested = base.source_hashes(sources) @@ -82,16 +82,16 @@ def main(): dependencies = os.pathsep.join(map(str, libraries)) run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', str(jars['server'])+os.pathsep+dependencies, '-d', classes, oracle, *helpers], 'compile-java') - run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'scene_collision_probe'], 'compile-rust') + run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - executable = Path(metadata['target_directory'])/'debug/examples'/('scene_collision_probe.exe' if os.name == 'nt' else 'scene_collision_probe') + executable = Path(metadata['target_directory'])/'debug/examples'/('probe.exe' if os.name=='nt' else 'probe') cases = [] for radius in [1, 2]: build = root/str(radius); build.mkdir(exist_ok=True) fixtures = list(corpus(radius)) (build/'inputs.txt').write_text(''.join(json.dumps(f, separators=(',', ':'))+'\n' for f in fixtures)) input_hash = lab.digest(build/'inputs.txt', 'sha256') - run([executable, resources, build, radius], f'rust-{radius}') + run([executable, 'scene_collision_probe',resources, build, radius], f'rust-{radius}') scene_hash = lab.digest(build/'scene.json', 'sha256') references = [] for side, jar in jars.items(): diff --git a/tools/test_native_scene_motion.py b/tools/test_native_scene_motion.py index 4b8089795..a917d7337 100644 --- a/tools/test_native_scene_motion.py +++ b/tools/test_native_scene_motion.py @@ -789,7 +789,7 @@ def main(): if args.sprint_input:helpers.append(oracle.with_name('VanillaSprintInputOracle.java')) sources=[Path(__file__),lab.ROOT/'tools/test_native_client.py',lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py', lab.ROOT/'tools/prepare_native_client.py',oracle,*helpers,lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-client/examples/scene_motion_probe.rs'] + lab.ROOT/'crates/horizon-client/examples/probe/scene_motion_probe.rs'] for crate in ['horizon-core','horizon-world','horizon-assets','horizon-client']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] if args.sprint_input:sources.append(lab.ROOT/'tools/test_model_baking_parity.py') @@ -807,16 +807,16 @@ def main(): damage_dir=build/'damage';damage_dir.mkdir(exist_ok=True) for target, source in [('types.json','damage-types.json'),('tags.json','damage-tags.json')]: (damage_dir/target).write_bytes((resources/source).read_bytes()) - run(['cargo','build','--locked','-p','horizon-client','--example','scene_motion_probe'],'compile-rust') + run(['cargo','build','--locked','-p','horizon-client','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT)) - binary=Path(metadata['target_directory'])/'debug/examples'/('scene_motion_probe.exe' if os.name=='nt' else 'scene_motion_probe') - run([binary,resources,build,'--describe'],'describe') + binary=Path(metadata['target_directory'])/'debug/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'scene_motion_probe',resources,build,'--describe'],'describe') references=[] for side,jar in jars.items(): run(['java','-Xmx768M','-cp',os.pathsep.join([str(classes),str(jar),dependencies]), 'dev.horizonlab.parity.VanillaSceneMotionOracle',side,build,resources],side) replay_hash=lab.digest(build/('inputs-'+side+'.txt'),'sha256') - run([binary,resources,build,side],'rust-'+side) + run([binary,'scene_motion_probe',resources,build,side],'rust-'+side) if replay_hash!=lab.digest(build/('inputs-'+side+'.txt'),'sha256'):raise AssertionError('Identity replay changed') matched=base.compare(build/(side+'.txt'),build/('rust-'+side+'.txt')) if matched!=expected_lines:raise AssertionError('Incomplete motion output') diff --git a/tools/test_natural_spawn_parity.py b/tools/test_natural_spawn_parity.py index fabdc184b..3c95e6ac2 100644 --- a/tools/test_natural_spawn_parity.py +++ b/tools/test_natural_spawn_parity.py @@ -550,7 +550,7 @@ def main(): lock, jars, libraries = base.verify_artifacts() resources = lab.RESOURCES oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/natural_spawn_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/natural_spawn_fixture.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawn_selection.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawn_rules.rs'] tested = base.source_hashes(sources) @@ -568,10 +568,10 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'natural_spawn_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/natural_spawn_fixture' - run([binary, resources, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples/probe' + run([binary, 'natural_spawn_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] if errors: diff --git a/tools/test_pack_screen_parity.py b/tools/test_pack_screen_parity.py index a73f734fe..1f3f03ede 100644 --- a/tools/test_pack_screen_parity.py +++ b/tools/test_pack_screen_parity.py @@ -14,7 +14,7 @@ records every GuiGraphicsExtractor call of the screen shown at the end (widgets, list backgrounds, scissor, separators, scroll bars, entries with their incompatibility tint, hover overlay and arrows, the selection outline, the search box, the buttons and their tooltip); -examples/pack_screen_fixture runs horizon_client::pack_screen, which the +examples/probe/pack_screen_fixture runs horizon_client::pack_screen, which the game's pack screen is, through the same actions. The call lists must agree. test_pack_screen_parity.py [--count N] [--detail N] diff --git a/tools/test_pack_selection_parity.py b/tools/test_pack_selection_parity.py index 8610d85f3..9af372d1e 100644 --- a/tools/test_pack_selection_parity.py +++ b/tools/test_pack_selection_parity.py @@ -7,7 +7,7 @@ initial selection as options.txt stores it, and the actions the screen's entries take on a click or key press: select (an incompatible pack only when its confirmation is accepted), unselect, move up, move down. The Java oracle (VanillaPackSelectionOracle) runs vanilla's PackRepository and -PackSelectionModel; examples/pack_selection_fixture runs +PackSelectionModel; examples/probe/pack_selection_fixture runs horizon_client::packs::SelectionModel, which the game's pack screen uses. After every action both lists, in order, with each entry's canSelect, canUnselect, canMoveUp and canMoveDown, and the selection committed at the @@ -71,8 +71,8 @@ def main(): *(PARITY / f'{n}.java' for n in ('ParityData', 'VanillaPackSelectionOracle'))], 'compile-java') run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaPackSelectionOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'pack_selection_fixture', '--', - inputs, build / 'rust.jsonl'], 'rust') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'pack_selection_fixture', inputs, build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] assert len(vanilla) == len(rust) == len(chosen) diff --git a/tools/test_particle_providers_parity.py b/tools/test_particle_providers_parity.py index 2fdd510d9..3695722bf 100644 --- a/tools/test_particle_providers_parity.py +++ b/tools/test_particle_providers_parity.py @@ -201,10 +201,10 @@ def main(): tested = base.source_hashes(sources) cases_path, units = make_cases(build) classes, dependencies, _ = harness.compile_oracle(build, oracle, jars, libraries, lock['minecraft']['java_major']) - binary = harness.build_probe(build, probe) + command = harness.build_probe(build, probe) # The oracle runs first: the probe replays the particle seeds it recovered. harness.java_run(build, classes, dependencies, oracle, [cases_path, build / 'client.txt'], 'client') - harness.run_logged([binary, cases_path, build / 'client.txt', build / 'rust.txt'], build, 'rust') + harness.run_logged([*command, cases_path, build / 'client.txt', build / 'rust.txt'], build, 'rust') tolerance = 0 try: matched = base.compare(build / 'client.txt', build / 'rust.txt') diff --git a/tools/test_place_recipe_parity.py b/tools/test_place_recipe_parity.py index 405ad8009..0b4bdf08e 100644 --- a/tools/test_place_recipe_parity.py +++ b/tools/test_place_recipe_parity.py @@ -9,7 +9,7 @@ renamed copies the book must not use, junk, and sometimes a nearly full inventory; the grid is empty, holds the same recipe already (placing again adds one set, or a full stack with shift) or something else. The Java oracle (VanillaPlaceRecipeOracle) runs RecipeBookMenu.handlePlacement as the server's -packet handler does; examples/place_recipe_fixture runs +packet handler does; examples/probe/place_recipe_fixture runs horizon_client::menu's place_recipe. Every menu slot, the whole inventory, the drops and whether the client gets a ghost recipe are compared. diff --git a/tools/test_raid_parity.py b/tools/test_raid_parity.py index 6df5f8fa6..be1ed7e25 100644 --- a/tools/test_raid_parity.py +++ b/tools/test_raid_parity.py @@ -316,7 +316,7 @@ def main(): lock, jars, libraries = base.verify_artifacts() resources = lab.RESOURCES oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRaidOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/raid_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/raid_fixture.rs', lab.ROOT / 'crates/horizon-client/src/raid.rs', lab.ROOT / 'crates/horizon-client/src/patrol.rs'] tested = base.source_hashes(sources) inputs = build / 'inputs.txt' @@ -335,10 +335,10 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaRaidOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'raid_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/raid_fixture' - run([binary, resources, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples/probe' + run([binary, 'raid_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] if errors: diff --git a/tools/test_random_tick_sections_parity.py b/tools/test_random_tick_sections_parity.py index 632808523..0b78afadb 100644 --- a/tools/test_random_tick_sections_parity.py +++ b/tools/test_random_tick_sections_parity.py @@ -7,7 +7,7 @@ Each case loads sections (every block state fills one, alone, so each state's ow ticking and a non-ticking state), ticks, sets and removes randomly ticking blocks (leaving them in the palette), and ticks again. Vanilla runs ServerLevel.tickChunk's section loop on real sections with the real getBlockRandomPos (VanillaRandomTickSectionsOracle); Horizon runs Behaviours::tick_chunk_random with the game's RandomTickSections -(examples/random_tick_sections_probe). Both print every drawn position, whether its block and its fluid tick +(examples/probe/random_tick_sections_probe). Both print every drawn position, whether its block and its fluid tick randomly, and the final randValue. """ import itertools diff --git a/tools/test_recipe_book_parity.py b/tools/test_recipe_book_parity.py index 4aa91686e..c25f180ac 100644 --- a/tools/test_recipe_book_parity.py +++ b/tools/test_recipe_book_parity.py @@ -8,7 +8,7 @@ having seen a highlighted recipe, the open and filter settings of the four book types, and saving and loading the player's recipeBook compound (with unknown ids dropped, and a compound missing a list ignored). The Java oracle (VanillaRecipeBookOracle) drives ServerRecipeBook and its codec; -examples/recipe_book_fixture drives horizon_client::recipe_book. After each +examples/probe/recipe_book_fixture drives horizon_client::recipe_book. After each operation the count, the known and highlighted recipes, the settings and the saved compound are compared. """ diff --git a/tools/test_recipe_book_render_parity.py b/tools/test_recipe_book_render_parity.py index 78d911d72..f60ac83fb 100644 --- a/tools/test_recipe_book_render_parity.py +++ b/tools/test_recipe_book_render_parity.py @@ -11,7 +11,7 @@ the mouse. The Java oracle (VanillaRecipeBookScreenOracle) builds vanilla's widgets for that state as RecipeBookComponent.initVisuals and RecipeBookPage.init do and records every GuiGraphicsExtractor call of their extractRenderState, the tooltips and GhostSlots.extractRenderState, with its -pose; examples/recipe_book_render_fixture lays out the same state with +pose; examples/probe/recipe_book_render_fixture lays out the same state with horizon_client::recipe_book_screen, which the game paints. The call lists must agree. """ diff --git a/tools/test_recipe_book_view_parity.py b/tools/test_recipe_book_view_parity.py index a38d04eca..dcdc88a88 100644 --- a/tools/test_recipe_book_view_parity.py +++ b/tools/test_recipe_book_view_parity.py @@ -8,7 +8,7 @@ grid, the furnace, blast furnace or smoker) with random inventory and menu contents and the craftable filter on or off. The Java oracle (VanillaRecipeBookViewOracle, on the client jar) runs ClientRecipeBook, RecipeCollection.selectRecipes and the tab and page logic of -RecipeBookComponent; examples/recipe_book_view_fixture runs +RecipeBookComponent; examples/probe/recipe_book_view_fixture runs horizon_client::recipe_book::ClientBook. Per tab: visibility, pages and every button's displays with their selected and craftable flags, in order (the client's HashMap of display ids decides it). Most cases also carry a diff --git a/tools/test_resource_pack_parity.py b/tools/test_resource_pack_parity.py index 6169542c5..2d9ae2a85 100644 --- a/tools/test_resource_pack_parity.py +++ b/tools/test_resource_pack_parity.py @@ -9,7 +9,7 @@ sources) and selects them over the prepared vanilla resources. The Java oracle and MultiPackResourceManager and asks what each reload listener reads: which pack a file comes from, translations (ClientLanguage), sound events (SoundManager.prepare), font providers (FontManager) and atlas sources -(SpriteSourceList). examples/pack_resources_fixture builds Horizon's resource +(SpriteSourceList). examples/probe/pack_resources_fixture builds Horizon's resource root for the same selection (packs::build_overlay) and reads it with Horizon's loaders. Every answer must agree. """ diff --git a/tools/test_scoreboard_parity.py b/tools/test_scoreboard_parity.py index 8a035eb17..db308d861 100644 --- a/tools/test_scoreboard_parity.py +++ b/tools/test_scoreboard_parity.py @@ -13,7 +13,7 @@ of each collection in vanilla's iteration order (objectivesByName and playerScores as fastutil open hash maps, teamsByName, each team's HashSet of players), and the ScoreboardSaveData.Packed codec output that data/minecraft/scoreboard.dat holds, before and after loading it back. -`examples/scoreboard_fixture` runs the same cases on +`examples/probe/scoreboard_fixture` runs the same cases on `horizon_client::scoreboard`, reloads vanilla's NBT, and vanilla reloads Horizon's NBT; all must agree. The one order vanilla leaves to identity hash codes (each holder's scores within PlayerScores) is compared as a set. @@ -250,10 +250,10 @@ def main(): inputs = build / 'inputs.jsonl' inputs.write_text(''.join(json.dumps(c, ensure_ascii=False) + '\n' for c in chosen), encoding='utf-8') run([*oracle, 'run', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'scoreboard_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('scoreboard_fixture.exe' if os.name == 'nt' else 'scoreboard_fixture') - run([binary, build / 'registries.json', inputs, build / 'rust.jsonl', build / 'vanilla.jsonl'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'scoreboard_fixture',build / 'registries.json', inputs, build / 'rust.jsonl', build / 'vanilla.jsonl'], 'rust') read = lambda p: [json.loads(l) for l in p.read_text(encoding='utf-8').splitlines()] vanilla, rust = read(build / 'vanilla.jsonl'), read(build / 'rust.jsonl') assert len(vanilla) == len(rust) diff --git a/tools/test_screen_layout_parity.py b/tools/test_screen_layout_parity.py index d488716f6..c9e791afb 100644 --- a/tools/test_screen_layout_parity.py +++ b/tools/test_screen_layout_parity.py @@ -6,7 +6,7 @@ a loom screen and menu whose state comes from the case (inputs present, the selectable patterns, the selected one, the scroller, the result banner or the six-layer error, the mouse over a pattern button) and CrafterScreen's background, disabled slots and redstone arrow, recording every -GuiGraphicsExtractor call; examples/screen_layout_fixture lays out the same +GuiGraphicsExtractor call; examples/probe/screen_layout_fixture lays out the same state with horizon_client::screen_layout, which the game paints. The ordered call lists must agree. """ diff --git a/tools/test_section_mesh_parity.py b/tools/test_section_mesh_parity.py index 78c0d68e9..65878bc97 100644 --- a/tools/test_section_mesh_parity.py +++ b/tools/test_section_mesh_parity.py @@ -481,7 +481,7 @@ def main(): oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSectionMeshOracle.java' helpers = [oracle.with_name(n + '.java') for n in ['VanillaCuboidModelOracle', 'VanillaHeightmapOracle']] sources = [Path(__file__), lab.ROOT / 'tools/lab.py', lab.ROOT / 'tools/test_rust_parity.py', oracle, *helpers, - lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock', lab.ROOT / 'crates/horizon-client/examples/section_mesh_fixture.rs'] + lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock', lab.ROOT / 'crates/horizon-client/examples/probe/section_mesh_fixture.rs'] for crate in ['horizon-core', 'horizon-world', 'horizon-assets', 'horizon-client']: sources += [lab.ROOT / 'crates' / crate / 'Cargo.toml', *sorted((lab.ROOT / 'crates' / crate / 'src').rglob('*.rs'))] tested = base.source_hashes(sources) @@ -502,14 +502,14 @@ def main(): dependencies = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()])) run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'), '-cp', dependencies, '-d', classes, oracle, *helpers], 'compile-java') env_jobs = os.environ.get('CARGO_BUILD_JOBS', '3') - run(['cargo', 'build', '--locked', '--profile', 'fast', '-j', env_jobs, '-p', 'horizon-client', '--example', 'section_mesh_fixture'], 'compile-rust') + run(['cargo', 'build', '--locked', '--profile', 'fast', '-j', env_jobs, '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory']) / 'fast/examples' / ('section_mesh_fixture.exe' if os.name == 'nt' else 'section_mesh_fixture') + binary = Path(metadata['target_directory']) / 'fast/examples' / ('probe.exe' if os.name=='nt' else 'probe') java = ['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaSectionMeshOracle'] - run([binary, resources, inputs, BUILD / 'rust.jsonl'], 'rust') + run([binary, 'section_mesh_fixture',resources, inputs, BUILD / 'rust.jsonl'], 'rust') run([*java, inputs, BUILD / 'client.jsonl', resources], 'client') run([*java, 'facts', BUILD / 'client-facts.jsonl', resources], 'client-facts') - run([binary, resources, 'facts', BUILD / 'rust-facts.jsonl'], 'rust-facts') + run([binary, 'section_mesh_fixture',resources, 'facts', BUILD / 'rust-facts.jsonl'], 'rust-facts') report = {'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'scenes': len(rows), 'client_quads': 0, 'rust_quads': 0, 'matched_quads': 0, 'identical_quads': 0, 'categories': {}, 'examples': {}, 'per_scene': {}, 'facts': {}} diff --git a/tools/test_server_files_parity.py b/tools/test_server_files_parity.py index 735bca302..82c0eaa8a 100644 --- a/tools/test_server_files_parity.py +++ b/tools/test_server_files_parity.py @@ -194,7 +194,7 @@ def main(): oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaServerFilesOracle.java' sources = [Path(__file__).resolve(), oracle, lab.ROOT / 'tools/oracle_harness.py', lab.ROOT / 'tools/lab.py', lab.ROOT / 'tools/test_rust_parity.py', lab.ROOT / 'Cargo.lock', - lab.ROOT / 'crates/horizon-client/examples/server_files_probe.rs', + lab.ROOT / 'crates/horizon-client/examples/probe/server_files_probe.rs', *sorted((lab.ROOT / 'crates/horizon-client/src/server').glob('*.rs'))] tested = base.source_hashes(sources) cases, count = make_cases(build) @@ -204,8 +204,8 @@ def main(): oh.run_logged(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], build, 'compile-java') - binary = oh.build_probe(build, 'server_files_probe') - oh.run_logged([binary, cases, build / 'rust.txt'], build, 'rust') + command = oh.build_probe(build, 'server_files_probe') + oh.run_logged([*command, cases, build / 'rust.txt'], build, 'rust') oh.run_logged(['java', '-Xmx1g', '-Duser.timezone=UTC', '-Djava.awt.headless=true', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaServerFilesOracle', cases, build / 'server.txt'], build, 'server') diff --git a/tools/test_spawn_rules_parity.py b/tools/test_spawn_rules_parity.py index e71a032b5..19bd8db46 100644 --- a/tools/test_spawn_rules_parity.py +++ b/tools/test_spawn_rules_parity.py @@ -138,7 +138,7 @@ def main(): entity_types = json.loads((resources / 'entity-types.json').read_text()) types = sorted(t for t, v in entity_types.items() if 'attributes' in v and t.split(':')[1] not in SKIPPED) oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSpawnRulesOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/spawn_rules_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/spawn_rules_fixture.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawn_rules.rs'] tested = base.source_hashes(sources) inputs = build / 'inputs.txt' @@ -155,10 +155,10 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx2G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaSpawnRulesOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'spawn_rules_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/spawn_rules_fixture' - run([binary, resources, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples/probe' + run([binary, 'spawn_rules_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] if errors: diff --git a/tools/test_spawner_parity.py b/tools/test_spawner_parity.py index b1637cf4e..5aa9029e3 100644 --- a/tools/test_spawner_parity.py +++ b/tools/test_spawner_parity.py @@ -230,7 +230,7 @@ def main(): lock, jars, libraries = base.verify_artifacts() resources = lab.RESOURCES oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/natural_spawn_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/natural_spawn_fixture.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawner.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawn_selection.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawn_rules.rs'] @@ -249,10 +249,10 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'natural_spawn_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/natural_spawn_fixture' - run([binary, resources, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples/probe' + run([binary, 'natural_spawn_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] if errors: diff --git a/tools/test_sprint_input_parity.py b/tools/test_sprint_input_parity.py index 0fe9eecec..0ac515e44 100644 --- a/tools/test_sprint_input_parity.py +++ b/tools/test_sprint_input_parity.py @@ -40,7 +40,7 @@ def main(): build=lab.LOCAL/'rust-sprint-input';build.mkdir(exist_ok=True) report=build/'report.json';report.unlink(missing_ok=True) oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSprintInputOracle.java' - sources=[Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_model_baking_parity.py',lab.ROOT/'tools/lab.py',oracle,lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-client/Cargo.toml',lab.ROOT/'crates/horizon-client/src/input.rs',lab.ROOT/'crates/horizon-client/src/sprint.rs',lab.ROOT/'crates/horizon-client/src/lib.rs',lab.ROOT/'crates/horizon-client/examples/sprint_probe.rs'] + sources=[Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_model_baking_parity.py',lab.ROOT/'tools/lab.py',oracle,lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-client/Cargo.toml',lab.ROOT/'crates/horizon-client/src/input.rs',lab.ROOT/'crates/horizon-client/src/sprint.rs',lab.ROOT/'crates/horizon-client/src/lib.rs',lab.ROOT/'crates/horizon-client/examples/probe/sprint_probe.rs'] tested=base.source_hashes(sources) def run(command,name): with (build/(name+'.log')).open('w') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=600,stdout=log,stderr=subprocess.STDOUT) @@ -49,10 +49,10 @@ def main(): classes=build/'classes';classes.mkdir(exist_ok=True) dependencies=os.pathsep.join(map(str,[jars['client'],*libraries])) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',dependencies,'-d',classes,oracle],'compile-java') - run(['cargo','build','--locked','-p','horizon-client','--example','sprint_probe'],'compile-rust') + run(['cargo','build','--locked','-p','horizon-client','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT)) - binary=Path(metadata['target_directory'])/'debug/examples'/('sprint_probe.exe' if os.name=='nt' else 'sprint_probe') - run([binary,inputs,build/'rust.txt'],'rust') + binary=Path(metadata['target_directory'])/'debug/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'sprint_probe',inputs,build/'rust.txt'],'rust') run(['java','-Xmx768M','-cp',str(classes)+os.pathsep+dependencies,'dev.horizonlab.parity.VanillaSprintInputOracle',inputs,build/'client.txt'],'client') matched=base.compare(build/'client.txt',build/'rust.txt') if matched!=operations+len(fixtures):raise AssertionError('Incomplete input output') diff --git a/tools/test_subtitle_parity.py b/tools/test_subtitle_parity.py index 21b4c7175..1444bb5bd 100644 --- a/tools/test_subtitle_parity.py +++ b/tools/test_subtitle_parity.py @@ -11,7 +11,7 @@ it renders), the notification display time, the text background opacity and its "chat only" setting, and a GUI size. Each frame records the fills and texts in order with the pose: which subtitles show, their order, merging of repeats, expiry, the fade by age (looping sounds stay bright longer), the direction -arrows and the box width. `examples/subtitle_fixture` replays the cases through +arrows and the box width. `examples/probe/subtitle_fixture` replays the cases through `horizon_client::subtitles`; the frames must agree exactly. test_subtitle_parity.py [--count N] [--detail N] @@ -133,10 +133,10 @@ def main(): *(PARITY / f'{n}.java' for n in ('ParityFont', 'VanillaSubtitleOracle'))], 'compile-java') run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaSubtitleOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'subtitle_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('subtitle_fixture.exe' if os.name == 'nt' else 'subtitle_fixture') - run([binary, resources, inputs, build / 'rust.jsonl'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'subtitle_fixture',resources, inputs, build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text(encoding='utf-8').splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text(encoding='utf-8').splitlines()] assert len(vanilla) == len(rust) == len(chosen) diff --git a/tools/test_tab_list_parity.py b/tools/test_tab_list_parity.py index cdf32df65..9b3c65605 100644 --- a/tools/test_tab_list_parity.py +++ b/tools/test_tab_list_parity.py @@ -10,12 +10,12 @@ them (upside-down Dinnerbone and Grumm) and whose real Scoreboard has the case's teams (colour, prefix, suffix), `list` objective (integer or hearts, number formats) and scores, with the header, footer, row background option and Hud ticks. It records every fill, text (as styled runs), sprite and -face blit. `examples/tab_list_fixture` lays out the same frames with +face blit. `examples/probe/tab_list_fixture` lays out the same frames with `horizon_client::tab_list`; the ordered call lists must agree. Downloaded skin images are compared too: VanillaSkinImageOracle decodes PNGs as NativeImage does and runs SkinTextureDownloader.processLegacySkin; -`examples/skin_image_fixture` runs `horizon_client::skins`. Pixels must agree. +`examples/probe/skin_image_fixture` runs `horizon_client::skins`. Pixels must agree. test_tab_list_parity.py [--count N] [--detail N] """ @@ -241,13 +241,13 @@ def main(): *(PARITY / f'{n}.java' for n in ('ParityData', 'ParityFont', 'VanillaTabListOracle', 'VanillaSkinImageOracle'))], 'compile-java') run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaTabListOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'tab_list_fixture', '--', - resources, inputs, build / 'rust.jsonl'], 'rust') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'tab_list_fixture', resources, inputs, build / 'rust.jsonl'], 'rust') images = build / 'skins.txt'; images.write_text(''.join(i + '\n' for i in skin_images(args.images))) run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaSkinImageOracle', images, build / 'vanilla-skins.txt'], 'vanilla-skins') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'skin_image_fixture', '--', - images, build / 'rust-skins.txt'], 'rust-skins') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'skin_image_fixture', images, build / 'rust-skins.txt'], 'rust-skins') vanilla_skins = (build / 'vanilla-skins.txt').read_text().splitlines() rust_skins = (build / 'rust-skins.txt').read_text().splitlines() assert len(vanilla_skins) == len(rust_skins) == args.images diff --git a/tools/test_team_rules_parity.py b/tools/test_team_rules_parity.py index af73aad10..5eb0c7d9d 100644 --- a/tools/test_team_rules_parity.py +++ b/tools/test_team_rules_parity.py @@ -9,7 +9,7 @@ EntitySelector.pushableBy predicate (collision rules), Entity.isInvisibleTo (name tag visibility, with a stand-in client for the viewer, camera and F1) on stand-in entities, for every combination of two teams' options, the three entities' teams (none, either team) and the flags involved. -`examples/team_rules_fixture` answers from `horizon_client::scoreboard`. +`examples/probe/team_rules_fixture` answers from `horizon_client::scoreboard`. test_team_rules_parity.py [--count N] """ @@ -84,10 +84,10 @@ def main(): PARITY / 'VanillaTeamRulesOracle.java'], 'compile-java') run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaTeamRulesOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'team_rules_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('team_rules_fixture.exe' if os.name == 'nt' else 'team_rules_fixture') - run([binary, inputs, build / 'rust.jsonl'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'team_rules_fixture',inputs, build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] assert len(vanilla) == len(rust) == len(chosen) diff --git a/tools/test_trading_parity.py b/tools/test_trading_parity.py index 13ef60880..c26c449fb 100644 --- a/tools/test_trading_parity.py +++ b/tools/test_trading_parity.py @@ -184,7 +184,7 @@ def main(): lock, jars, libraries = base.verify_artifacts() resources = lab.RESOURCES oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTradingOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/trading_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/trading_fixture.rs', lab.ROOT / 'crates/horizon-client/src/merchant.rs', lab.ROOT / 'crates/horizon-client/src/menu.rs'] tested = base.source_hashes([s for s in sources if s.exists()]) inputs = build / 'inputs.txt' @@ -219,9 +219,9 @@ def main(): if args.java_only: print(f'{len(vanilla)} oracle lines') return - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'trading_fixture'], 'compile-rust') - binary = lab.cargo_target() / 'release/examples/trading_fixture' - run([binary, resources, inputs, build / 'server.txt', build / 'rust.txt'], 'rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') + binary = lab.cargo_target() / 'release/examples/probe' + run([binary, 'trading_fixture', resources, inputs, build / 'server.txt', build / 'rust.txt'], 'rust') rust = (build / 'rust.txt').read_text().splitlines() bad = [(a, b) for a, b in zip(vanilla, rust) if a != b] if bad or len(vanilla) != len(rust): diff --git a/tools/test_translucency_parity.py b/tools/test_translucency_parity.py index fcf8d3842..fff0390eb 100644 --- a/tools/test_translucency_parity.py +++ b/tools/test_translucency_parity.py @@ -52,7 +52,7 @@ def main(): lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTranslucencyOracle.java'], 'compile-java') vanilla, rust = build / 'vanilla.jsonl', build / 'rust.jsonl' run(['java', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaTranslucencyOracle', inputs, vanilla], 'vanilla') - run(['cargo', 'run', '--quiet', '--locked', '--profile', args.profile, '-p', 'horizon-client', '--example', 'translucency_fixture', '--', inputs, rust], 'rust') + run(['cargo', 'run', '--quiet', '--locked', '--profile', args.profile, '-p', 'horizon-client', '--example', 'probe', '--', 'translucency_fixture', inputs, rust], 'rust') expected = [json.loads(line) for line in vanilla.read_text().splitlines()] actual = [json.loads(line) for line in rust.read_text().splitlines()] assert len(expected) == len(actual), 'case count differs' diff --git a/tools/test_trial_spawner_parity.py b/tools/test_trial_spawner_parity.py index 6fb79d9e1..bd6d69ac2 100644 --- a/tools/test_trial_spawner_parity.py +++ b/tools/test_trial_spawner_parity.py @@ -194,7 +194,7 @@ def main(): lock, jars, libraries = base.verify_artifacts() resources = lab.RESOURCES oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/natural_spawn_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/natural_spawn_fixture.rs', lab.ROOT / 'crates/horizon-client/src/mobs/trial_spawner.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawner.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawn_selection.rs', @@ -214,10 +214,10 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'natural_spawn_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/natural_spawn_fixture' - run([binary, resources, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples/probe' + run([binary, 'natural_spawn_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] if errors: diff --git a/tools/test_vault_parity.py b/tools/test_vault_parity.py index 7eeace526..73c41e197 100644 --- a/tools/test_vault_parity.py +++ b/tools/test_vault_parity.py @@ -173,7 +173,7 @@ def main(): lock, jars, libraries = base.verify_artifacts() resources = lab.LOCAL / 'horizon-client/26.3' oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/natural_spawn_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/natural_spawn_fixture.rs', lab.ROOT / 'crates/horizon-client/src/vault.rs'] tested = base.source_hashes(sources) inputs = build / 'inputs.txt' @@ -190,10 +190,10 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'natural_spawn_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/natural_spawn_fixture' - run([binary, resources, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples/probe' + run([binary, 'natural_spawn_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] if errors: diff --git a/tools/test_world_border_render_parity.py b/tools/test_world_border_render_parity.py index 1a04a0de4..f8c88b6a6 100644 --- a/tools/test_world_border_render_parity.py +++ b/tools/test_world_border_render_parity.py @@ -103,8 +103,8 @@ def main(): PARITY / 'VanillaWorldBorderRenderOracle.java'], 'compile-java') run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaWorldBorderRenderOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'world_border_render_fixture', '--', - inputs, build / 'rust.jsonl'], 'rust') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'world_border_render_fixture', inputs, build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] assert len(vanilla) == len(rust) From 4a922a5772494d3b55b7c5d855ba8bf8b2da637c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 14:49:18 +0200 Subject: [PATCH 042/408] Document how the runner tracks probe-binary dependencies Co-Authored-By: Claude Opus 5.5 --- docs/parity-workflow.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/parity-workflow.md b/docs/parity-workflow.md index 37202411c..a9a453baf 100644 --- a/docs/parity-workflow.md +++ b/docs/parity-workflow.md @@ -26,7 +26,7 @@ Vanilla oracle runs are reused as well. `tools/parity_shim.py` stands in for `ja Probes build into `.local/parity-target/` with release optimisation but no LTO and 16 codegen units. On ludodesktop that rebuilds every `horizon-world` probe in 3 seconds after a one-line change, against 122 seconds with the release profile. Rust gives these settings identical results (no fast-math; overflow checks as in release), and the full harness suite passes under them. Probes that harnesses build in the dev profile get `opt-level = 3` too, keeping their overflow checks and debug assertions. Harnesses must locate binaries through `cargo metadata` or `lab.cargo_target()`, never a hard-coded `target/`. -The `horizon-world` probes are one binary, `cargo build --release -p horizon-world --example probe`: a harness runs `probe [arguments]`, and `` is a module in `crates/horizon-world/examples/probe/` (add it to the `mod` list and the `probes!` list in its `main.rs`; read arguments with `crate::args()`, which drops the name). Code several probes share goes in `examples/probe/support/`. Linking one binary instead of ~170 examples is most of what a probe build used to cost. The runner counts only the probes a harness ran (and the support modules they name) as its dependencies, so editing one probe reruns only its harnesses. +The `horizon-world` probes are one binary, `cargo build --release -p horizon-world --example probe`: a harness runs `probe [arguments]`, and `` is a module in `crates/horizon-world/examples/probe/` (add it to the `mod` list and the `probes!` list in its `main.rs`; read arguments with `crate::args()`, which drops the name). Code several probes share goes in `examples/probe/support/`. Linking one binary instead of ~170 examples is most of what a probe build used to cost. The runner counts only the probes a harness ran, the probes and support modules they name and `dispatch.rs` as its dependencies, not `main.rs`, which only lists the probes: editing one probe reruns only its harnesses, and adding one reruns none. Passes are shared between worktrees. A harness's key depends only on the content of its dependencies, not on where they are, so every pass is also written to `parity-shared/` beside the shared vanilla data (`PARITY_SHARED` overrides it). A worktree whose files match those a harness passed with, in any worktree, counts that pass without running the harness: after merging the integration branch, an agent's gate only runs the harnesses its own changes affect. From a6da92583746d132a912d6eba20cf175d0a3b6a7 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 14:47:24 +0200 Subject: [PATCH 043/408] Split the client probe list from its dispatch the same way Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/probe/dispatch.rs | 49 ++++++++++++++++++ crates/horizon-client/examples/probe/main.rs | 51 +++---------------- 2 files changed, 56 insertions(+), 44 deletions(-) create mode 100644 crates/horizon-client/examples/probe/dispatch.rs diff --git a/crates/horizon-client/examples/probe/dispatch.rs b/crates/horizon-client/examples/probe/dispatch.rs new file mode 100644 index 000000000..b40cf1a6e --- /dev/null +++ b/crates/horizon-client/examples/probe/dispatch.rs @@ -0,0 +1,49 @@ +//! How the probe binary runs a probe. main.rs lists the probes and nothing else (tools/parity.py leaves it out of +//! the harnesses' dependencies); code every probe relies on goes here. +use std::process::ExitCode; + +/// `probes! { a, b, }` declares the binary's `main`, which runs the probe module named by its first argument. +macro_rules! probes { + ($($name:ident,)*) => { + fn run(name: &str) -> Option { + use std::process::Termination; + Some(match name { + $(stringify!($name) => $name::main().report(),)* + _ => return None, + }) + } + + fn main() -> std::process::ExitCode { + dispatch::main(&[$(stringify!($name)),*], run) + } + }; +} + +/// The probe's command line as its own example saw it: the program, then the arguments after the probe's name. +pub fn args() -> std::vec::IntoIter { + let mut args: Vec = std::env::args().collect(); + if args.len() > 1 { + args.remove(1); + } + args.into_iter() +} + +/// args(), as OsStrings. +pub fn args_os() -> std::vec::IntoIter { + let mut args: Vec<_> = std::env::args_os().collect(); + if args.len() > 1 { + args.remove(1); + } + args.into_iter() +} + +pub fn main(names: &[&str], run: fn(&str) -> Option) -> ExitCode { + let name = std::env::args().nth(1).unwrap_or_default(); + run(&name).unwrap_or_else(|| { + eprintln!( + "usage: probe [arguments...]\nprobes: {}", + names.join(" ") + ); + ExitCode::from(2) + }) +} diff --git a/crates/horizon-client/examples/probe/main.rs b/crates/horizon-client/examples/probe/main.rs index c6f98e4ac..d110ea790 100644 --- a/crates/horizon-client/examples/probe/main.rs +++ b/crates/horizon-client/examples/probe/main.rs @@ -1,7 +1,13 @@ //! Every horizon-client parity probe in one binary: `probe [arguments]` runs `.rs` as its own //! example did (tools/test_*_parity.py, tools/oracle_harness.py, tools/audio_harness.py). Linking ~80 examples, //! each with the whole client in it, was most of the parity job's probe build; one binary builds it once. -use std::process::{ExitCode, Termination}; +//! +//! This file only lists the probes, so that adding one reruns no harness: tools/parity.py leaves it out of +//! their dependencies. How a probe runs is in dispatch.rs. +#[macro_use] +mod dispatch; + +use dispatch::{args, args_os}; mod ambient_fixture; mod arrow_probe; @@ -87,20 +93,6 @@ mod weather_fixture; mod world_border_render_fixture; mod world_options_fixture; -/// `run(name)` runs the probe module `name`; NAMES lists them. -macro_rules! probes { - ($($name:ident,)*) => { - const NAMES: &[&str] = &[$(stringify!($name)),*]; - - fn run(name: &str) -> Option { - Some(match name { - $(stringify!($name) => $name::main().report(),)* - _ => return None, - }) - } - }; -} - probes! { ambient_fixture, arrow_probe, @@ -184,32 +176,3 @@ probes! { world_border_render_fixture, world_options_fixture, } - -/// The probe's command line as its own example saw it: the program, then the arguments after the probe's name. -fn args() -> std::vec::IntoIter { - let mut args: Vec = std::env::args().collect(); - if args.len() > 1 { - args.remove(1); - } - args.into_iter() -} - -/// args(), as OsStrings. -fn args_os() -> std::vec::IntoIter { - let mut args: Vec<_> = std::env::args_os().collect(); - if args.len() > 1 { - args.remove(1); - } - args.into_iter() -} - -fn main() -> ExitCode { - let name = std::env::args().nth(1).unwrap_or_default(); - run(&name).unwrap_or_else(|| { - eprintln!( - "usage: probe [arguments...]\nprobes: {}", - NAMES.join(" ") - ); - ExitCode::from(2) - }) -} From 82d6d275679b56426402ff19c50bd9998c1cfcf2 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:27:22 +0200 Subject: [PATCH 044/408] Point the audio harnesses at audio_common's new place Co-Authored-By: Claude Opus 5.5 --- tools/test_ambient_sound_parity.py | 2 +- tools/test_music_parity.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/test_ambient_sound_parity.py b/tools/test_ambient_sound_parity.py index 8906d2d7a..cb4f40b05 100644 --- a/tools/test_ambient_sound_parity.py +++ b/tools/test_ambient_sound_parity.py @@ -181,7 +181,7 @@ def main(): 'ambient', 'VanillaAmbientOracle', 'ambient_fixture', ''.join(l + '\n' for l in lines), extra_sources=[h.lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundRig.java', h.lab.ROOT / 'crates/horizon-client/src/ambience.rs', - h.lab.ROOT / 'crates/horizon-client/examples/audio_common/mod.rs'], + h.lab.ROOT / 'crates/horizon-client/examples/probe/audio_common/mod.rs'], java_args=[h.RESOURCES], rust_args=[h.RESOURCES], scope='Real LocalPlayer.updateIsUnderwater, UnderwaterAmbientSoundHandler and BiomeAmbientSoundsHandler (loop cross-fades, additions, ' 'cave mood sampling, moodiness and the mood sound position) with UnderLiquidAmbientSoundInstance/UnderLiquidSubSound/LoopSoundInstance ' diff --git a/tools/test_music_parity.py b/tools/test_music_parity.py index 7d41be5f1..b56c9ab25 100644 --- a/tools/test_music_parity.py +++ b/tools/test_music_parity.py @@ -154,7 +154,7 @@ def main(): 'music', 'VanillaMusicOracle', 'music_fixture', ''.join(l + '\n' for l in lines), extra_sources=[h.lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundRig.java', h.lab.ROOT / 'crates/horizon-client/src/music.rs', - h.lab.ROOT / 'crates/horizon-client/examples/audio_common/mod.rs'], + h.lab.ROOT / 'crates/horizon-client/examples/probe/audio_common/mod.rs'], java_args=[h.RESOURCES], rust_args=[h.RESOURCES], scope='Real MusicManager.tick/startPlaying/stopPlaying/fadePlaying/setMinutesBetweenSongs/showNowPlayingToastIfNeeded with a seeded ' 'random over the real SoundEngine: track starts and replacements, nextSongDelay draws, the three music frequencies, the loading ' From ac811d470883ef930f1041ccd34f8b857c8841d5 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:37:34 +0200 Subject: [PATCH 045/408] One side_mask for the two datafixes, one test MobType for two mobs.rs tests datafix: LeavesFix's getSideMask is ChunkPalettedStorageFix's, line for line; chunk_leaves uses chunk_flatten's. mobs.rs: push_tests takes sensor_scan_tests' 46-line cow MobType instead of its own copy. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/mobs.rs | 51 +------------------ .../src/datafix/chunk_flatten.rs | 4 +- .../horizon-world/src/datafix/chunk_leaves.rs | 27 +--------- 3 files changed, 5 insertions(+), 77 deletions(-) diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 76f622d9c..a61ea2a11 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -2277,7 +2277,7 @@ mod sensor_scan_tests { use horizon_core::geometry::Vec3; use serde_json::json; - fn kind() -> Arc { + pub(super) fn kind() -> Arc { Arc::new(MobType { id: "minecraft:cow".into(), species: Species::Cow, @@ -2481,56 +2481,9 @@ mod sensor_scan_tests { } #[cfg(test)] mod push_tests { + use super::sensor_scan_tests::kind; use super::*; use horizon_core::geometry::Vec3; - use serde_json::json; - - fn kind() -> Arc { - Arc::new(MobType { - id: "minecraft:cow".into(), - species: Species::Cow, - width: 0.9, - height: 1.4, - eye_height: 1.3, - category: "creature".into(), - max_health: 10.0, - speed: 0.2, - flying_speed: 0.4, - attack_damage: 0.0, - attack_knockback: 0.0, - follow_range: 16.0, - step_height: 0.6, - armor: 0.0, - armor_toughness: 0.0, - knockback_resistance: 0.0, - jump_strength: 0.42, - attributes: Arc::default(), - gravity: 0.08, - safe_fall_distance: 3.0, - fall_damage_multiplier: 1.0, - water_efficiency: 0.0, - water_slowdown: 0.8, - air_speed: 0.02, - baby_scale: 0.5, - head_rot_speed: 10.0, - max_head_x_rot: 40.0, - max_head_y_rot: 75.0, - ambient_interval: 120, - flags: Flags { - animal: true, - ..Default::default() - }, - model: Arc::new(Part::parse("root", &json!({}))), - layers: HashMap::new(), - texture: String::new(), - brain: Brain::Passive, - anim: Anim::Rabbit, - sounds: [""; 3], - step_sound: None, - food: Arc::default(), - tempt: Arc::default(), - }) - } /// The pending pushes as one list, scanned for each mob, as before. fn take_old(events: &mut Vec, from: usize, pending: &mut Vec<(u32, Vec3)>) { diff --git a/crates/horizon-world/src/datafix/chunk_flatten.rs b/crates/horizon-world/src/datafix/chunk_flatten.rs index e3c116d93..671fc9f73 100644 --- a/crates/horizon-world/src/datafix/chunk_flatten.rs +++ b/crates/horizon-world/src/datafix/chunk_flatten.rs @@ -266,8 +266,8 @@ fn is_virtual(block: usize) -> bool { VIRTUAL.contains(&block) } -/// `getSideMask`. -fn side_mask(west: bool, east: bool, north: bool, south: bool) -> i32 { +/// `getSideMask` (LeavesFix has the same copy). +pub(super) fn side_mask(west: bool, east: bool, north: bool, south: bool) -> i32 { let mut s = 0; if north { if east { diff --git a/crates/horizon-world/src/datafix/chunk_leaves.rs b/crates/horizon-world/src/datafix/chunk_leaves.rs index 9cd2fd3d9..07d59cbdf 100644 --- a/crates/horizon-world/src/datafix/chunk_leaves.rs +++ b/crates/horizon-world/src/datafix/chunk_leaves.rs @@ -6,6 +6,7 @@ //! emulated here (`IntOpenHashSet` and the key order of an `Int2ObjectOpenHashMap`). use std::collections::{HashMap, HashSet}; +use super::chunk_flatten::side_mask; use super::dynamic::{as_int, as_long_stream, as_str, ceillog2, set}; use crate::nbt::Tag; @@ -355,32 +356,6 @@ fn get_index(x: i32, y: i32, z: i32) -> i32 { y << 8 | z << 4 | x } -fn side_mask(west: bool, east: bool, north: bool, south: bool) -> i32 { - let mut s = 0; - if north { - if east { - s |= 2; - } else if west { - s |= 128; - } else { - s |= 1; - } - } else if south { - if west { - s |= 32; - } else if east { - s |= 8; - } else { - s |= 16; - } - } else if east { - s |= 4; - } else if west { - s |= 64; - } - s -} - /// `LeavesFix` over a chunk (`{Level: ...}`). pub(super) fn leaves_fix(chunk: &mut Tag) { let Some(level) = chunk.get_mut("Level") else { From a79077b30e1fb734615b83c762f6a13defda3b28 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:42:20 +0200 Subject: [PATCH 046/408] Mob brains share Timed, compute_path, reached and the living-entity scan Behavior's Timed was copied into the villager, animal, monster and warden brains: one copy now, in brain.rs, drawing its duration in Java's int arithmetic (two copies used plain +, the same for every duration they have). MoveToTargetSink's tryComputePath and reachedTarget, copied into the villager, monster and warden brains on the same WalkTarget and Slot types, are the villager brain's, given each brain's CANT_REACH_WALK_TARGET_SINCE. NearestLivingEntitySensor's scan, copied into the villager, animal and monster brains, is brain.rs's living_near. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/src/mobs/animal_brain.rs | 89 ++++--------- crates/horizon-client/src/mobs/brain.rs | 58 ++++++++- .../horizon-client/src/mobs/monster_brain.rs | 116 +++-------------- .../horizon-client/src/mobs/villager_brain.rs | 118 +++++++----------- .../horizon-client/src/mobs/warden_brain.rs | 108 +++------------- 5 files changed, 156 insertions(+), 333 deletions(-) diff --git a/crates/horizon-client/src/mobs/animal_brain.rs b/crates/horizon-client/src/mobs/animal_brain.rs index 331870b4a..bd0eb9c90 100644 --- a/crates/horizon-client/src/mobs/animal_brain.rs +++ b/crates/horizon-client/src/mobs/animal_brain.rs @@ -9,7 +9,12 @@ //! own random drives positions, sounds and jumps. `RunOne` shuffles with a //! random of its own, seeded with the brain's `shuffle_seed` when it is //! built. -use super::{Mob, MobEvent, MobWorld, Species, Who, path::Path, sniffer}; +use super::{ + Mob, MobEvent, MobWorld, Species, Who, + brain::{Timed, living_near}, + path::Path, + sniffer, +}; use horizon_core::{ geometry::Vec3, random::{LegacyRandom, RandomSource}, @@ -603,22 +608,7 @@ fn tick_sensors(m: &mut Mob, w: &MobWorld) { /// `NearestLivingEntitySensor`: everything alive within the follow range, /// nearest first. fn sense_living(m: &mut Mob, w: &MobWorld) { - let r = m.attrs.follow_range; - let area = m.bounds().inflate(Vec3::new(r, r, r)); - let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others_near(area) { - if o.id != m.id && o.alive && o.bounds.intersects(area) { - found.push((Who::Mob(o.id), m.distance_sqr(o.position))); - } - } - if let Some(p) = &w.player - && p.alive - && p.bounds.intersects(area) - { - found.push((Who::Player, m.distance_sqr(p.position))); - } - found.sort_by(|a, b| a.1.total_cmp(&b.1)); - let list: Vec = found.into_iter().map(|(w, _)| w).collect(); + let list = living_near(m, w); let mm = mem(m); mm.mobs.set_list(list.clone()); mm.visible_mobs.set(Visible { @@ -794,37 +784,6 @@ fn followable_friendly(s: Species) -> bool { // ---- Behaviours ------------------------------------------------------------ -/// `Behavior`'s running state and end time. -#[derive(Clone, Copy, Debug)] -struct Timed { - running: bool, - end: i64, - min: i32, - max: i32, -} -impl Timed { - fn new(min: i32, max: i32) -> Self { - Self { - running: false, - end: 0, - min, - max, - } - } - /// `Behavior.tryStart`'s duration draw. - fn begin(&mut self, cx: &mut Bx) { - self.running = true; - let bound = self.max.wrapping_add(1).wrapping_sub(self.min); - let d = self - .min - .wrapping_add(cx.lr.next_int_bound(bound).unwrap_or(0)); - self.end = cx.now + i64::from(d); - } - fn timed_out(&self, now: i64) -> bool { - now > self.end - } -} - /// `RunOne`: shuffles its children by weight and starts the first that can. #[derive(Clone, Debug)] struct Gate { @@ -1076,7 +1035,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); mem(m).walk_target.clear(); mem(m).look_target.clear(); m.add_effect("minecraft:regeneration", 200, 0); @@ -1086,7 +1045,7 @@ impl B { if !swim_condition(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::AnimalPanic { t, .. } => { @@ -1094,7 +1053,7 @@ impl B { if !(mm.hurt_by.get() == Some(&true) || mm.is_panicking.present()) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); if brain_mut(m).kind == Kind::Sniffer { reset_sniffing(m, cx); } @@ -1123,7 +1082,7 @@ impl B { let reached = reached(m, cx.w, &walk); if !reached && compute_path(m, cx, &walk, path, speed) { *last_target = walk.target.block(cx.w); - t.begin(cx); + t.begin(cx.lr, cx.now); mem(m).path.set_opt(path.clone()); m.nav_move_to_path(path.clone(), f64::from(*speed)); return true; @@ -1139,21 +1098,21 @@ impl B { if !mem(m).temptation_cooldown_ticks.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::CountDownGaze(t) => { if !mem(m).gaze_cooldown_ticks.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::CountDownTransport(t) => { if !mem(m).transport_items_cooldown_ticks.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::Transport(x) => x.try_start(m, cx), @@ -1171,7 +1130,7 @@ impl B { let Some(partner) = breed_partner(m, cx.w) else { return false; }; - t.begin(cx); + t.begin(cx.lr, cx.now); if brain_mut(m).kind == Kind::Sniffer { reset_sniffing(m, cx); } @@ -1200,7 +1159,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); if brain_mut(m).kind == Kind::Sniffer { reset_sniffing(m, cx); } @@ -1210,14 +1169,14 @@ impl B { if !mem(m).look_target.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::FeelingHappy(t) => { if !mem(m).sniffer_happy.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); transition(m, cx, sniffer::FEELING_HAPPY); true } @@ -1233,7 +1192,7 @@ impl B { if !can_sniff(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); transition(m, cx, sniffer::DIGGING); true } @@ -1246,7 +1205,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); transition(m, cx, sniffer::RISING); true } @@ -1261,7 +1220,7 @@ impl B { if !can_sniff(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); transition(m, cx, sniffer::SEARCHING); true } @@ -1278,7 +1237,7 @@ impl B { if is_tempted(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); transition(m, cx, sniffer::SCENTING); true } @@ -1293,12 +1252,12 @@ impl B { if m.is_baby() || !can_sniff(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); transition(m, cx, sniffer::SNIFFING); true } B::DoNothing(t) => { - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::AxolotlAction { .. } diff --git a/crates/horizon-client/src/mobs/brain.rs b/crates/horizon-client/src/mobs/brain.rs index da83ee93d..67bb6a2a6 100644 --- a/crates/horizon-client/src/mobs/brain.rs +++ b/crates/horizon-client/src/mobs/brain.rs @@ -1,8 +1,11 @@ //! Pieces of vanilla's `Brain` that species implemented as brains share: //! memories that expire, behaviour durations, walk targets and //! `MoveToTargetSink`. -use super::{Mob, goals::Cx}; -use horizon_core::random::RandomSource; +use super::{Mob, MobWorld, Who, goals::Cx}; +use horizon_core::{ + geometry::Vec3, + random::{LegacyRandom, RandomSource}, +}; /// A memory with an expiry (`Brain.setMemoryWithExpiry`): present for the /// tick it was set and `ttl` more ticks. `Ttl::default()` is absent. @@ -25,6 +28,57 @@ impl Ttl { } } } +/// `Behavior`'s bookkeeping in the brains ported behaviour for behaviour +/// (villager, animal, monster, warden): running, and until when. +#[derive(Clone, Copy, Debug)] +pub struct Timed { + pub running: bool, + pub end: i64, + pub min: i32, + pub max: i32, +} +impl Timed { + pub fn new(min: i32, max: i32) -> Self { + Self { + running: false, + end: 0, + min, + max, + } + } + /// `Behavior.tryStart`'s duration draw from the level random, in Java's + /// int arithmetic (made even when it cannot vary). + pub fn begin(&mut self, lr: &mut LegacyRandom, now: i64) { + self.running = true; + let bound = self.max.wrapping_add(1).wrapping_sub(self.min); + let d = self.min.wrapping_add(lr.next_int_bound(bound).unwrap_or(0)); + self.end = now + i64::from(d); + } + /// `Behavior.timedOut`. + pub fn timed_out(&self, now: i64) -> bool { + now > self.end + } +} +/// `NearestLivingEntitySensor`'s scan: the living entities (the player +/// among them) whose boxes meet the follow range around `m`, nearest first. +pub fn living_near(m: &Mob, w: &MobWorld) -> Vec { + let r = m.attrs.follow_range; + let area = m.bounds().inflate(Vec3::new(r, r, r)); + let mut found: Vec<(Who, f64)> = Vec::new(); + for o in w.others_near(area) { + if o.id != m.id && o.alive && o.bounds.intersects(area) { + found.push((Who::Mob(o.id), m.distance_sqr(o.position))); + } + } + if let Some(p) = &w.player + && p.alive + && p.bounds.intersects(area) + { + found.push((Who::Player, m.distance_sqr(p.position))); + } + found.sort_by(|a, b| a.1.total_cmp(&b.1)); + found.into_iter().map(|(w, _)| w).collect() +} /// A random duration in `min..=max` (`Behavior`'s end time). pub fn duration(m: &mut Mob, min: i32, max: i32) -> i32 { if max <= min { diff --git a/crates/horizon-client/src/mobs/monster_brain.rs b/crates/horizon-client/src/mobs/monster_brain.rs index eeb2c42f2..be310cdd7 100644 --- a/crates/horizon-client/src/mobs/monster_brain.rs +++ b/crates/horizon-client/src/mobs/monster_brain.rs @@ -11,9 +11,10 @@ //! seeded when the brain is built. use super::{ Mob, MobEvent, MobWorld, Species, Who, + brain::{Timed, living_near}, goals::Cx, path::Path, - villager_brain::{NEVER, Slot, Tracker, Visible, WalkTarget}, + villager_brain::{NEVER, Slot, Tracker, Visible, WalkTarget, compute_path, reached}, }; use crate::projectiles::{Projectile, ProjectileKind}; use horizon_core::{ @@ -129,6 +130,10 @@ fn brain_mut(m: &mut Mob) -> &mut Brain { fn mem(m: &mut Mob) -> &mut Memories { &mut brain_mut(m).mem } +/// `CANT_REACH_WALK_TARGET_SINCE`, for `compute_path`. +fn cant_reach(m: &mut Mob) -> &mut Slot { + &mut mem(m).cant_reach_walk_target_since +} fn mem_ref(m: &Mob) -> &Memories { &brain(m).expect("brain").mem } @@ -296,22 +301,7 @@ fn tick_sensors(m: &mut Mob, w: &MobWorld) { /// `NearestLivingEntitySensor`: everything alive within the follow range, /// nearest first. fn sense_living(m: &mut Mob, w: &MobWorld) { - let r = m.attrs.follow_range; - let area = m.bounds().inflate(Vec3::new(r, r, r)); - let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others_near(area) { - if o.id != m.id && o.alive && o.bounds.intersects(area) { - found.push((Who::Mob(o.id), m.distance_sqr(o.position))); - } - } - if let Some(p) = &w.player - && p.alive - && p.bounds.intersects(area) - { - found.push((Who::Player, m.distance_sqr(p.position))); - } - found.sort_by(|a, b| a.1.total_cmp(&b.1)); - let list: Vec = found.into_iter().map(|(w, _)| w).collect(); + let list = living_near(m, w); let mm = mem(m); mm.mobs.set_list(list.clone()); mm.visible_mobs.set(Visible { @@ -460,31 +450,6 @@ fn sense_breeze_attack(m: &mut Mob, w: &MobWorld) { // ---- Behaviours --------------------------------------------------------- -/// `Behavior`'s bookkeeping: running, and until when. -#[derive(Clone, Debug)] -struct Timed { - running: bool, - end: i64, - min: i32, - max: i32, -} -impl Timed { - fn new(min: i32, max: i32) -> Self { - Self { - running: false, - end: 0, - min, - max, - } - } - /// `Behavior.tryStart`'s duration draw from the level random. - fn begin(&mut self, cx: &mut Bx) { - self.running = true; - let d = self.min + cx.lr.next_int_bound(self.max + 1 - self.min).unwrap_or(0); - self.end = cx.now + i64::from(d); - } -} - /// `StartAttacking`'s target finders. #[derive(Clone, Copy, Debug)] enum Finder { @@ -611,14 +576,14 @@ impl B { if *creaking && !super::creaking::can_move(m) || !swim_condition(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::LookAtTargetSink(t) => { if !mem(m).look_target.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::MoveToTargetSink { @@ -640,9 +605,9 @@ impl B { } let walk = mm.walk_target.value().unwrap(); let reached = reached(m, cx.w, &walk); - if !reached && compute_path(m, cx, &walk, path, speed) { + if !reached && compute_path(m, cx.w, cx.now, &walk, path, speed, cant_reach) { *last_target = walk.target.block(cx.w); - t.begin(cx); + t.begin(cx.lr, cx.now); // start mem(m).path.set_opt(path.clone()); m.nav_move_to_path(path.clone(), f64::from(*speed)); @@ -723,7 +688,7 @@ impl B { true } B::DoNothing(t) => { - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::RandomStroll(running, speed) => { @@ -852,7 +817,7 @@ impl B { mem(m).breeze_shoot.clear(); return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); // start super::breeze::set_pose(m, super::breeze::SHOOTING); mem(m).breeze_shoot_charging.set_ttl((), 15); @@ -871,7 +836,7 @@ impl B { if !long_jump_can_run(m, cx) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); // start if !mem(m).breeze_jump_inhaling.present() { mem(m).breeze_jump_inhaling.set_ttl((), 10); @@ -909,7 +874,7 @@ impl B { if !stuck { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); mem(m).breeze_shoot.set_ttl((), 60); true } @@ -928,7 +893,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); slide_start(m, cx); true } @@ -993,7 +958,7 @@ impl B { && let Some(now_target) = walk.target.block(cx.w) { let d = manhattan_sq(now_target, last); - if d > 4 && compute_path(m, cx, &walk, path, speed) { + if d > 4 && compute_path(m, cx.w, cx.now, &walk, path, speed, cant_reach) { *last_target = Some(now_target); mem(m).path.set_opt(path.clone()); m.nav_move_to_path(path.clone(), f64::from(*speed)); @@ -1126,53 +1091,6 @@ fn tracker_visible(m: &mut Mob, w: &MobWorld, t: Tracker) -> bool { _ => true, } } -/// `MoveToTargetSink.reachedTarget`. -fn reached(m: &Mob, w: &MobWorld, walk: &WalkTarget) -> bool { - walk.target.block(w).is_some_and(|p| { - let h = block_of(m.position); - (p[0] - h[0]).abs() + (p[1] - h[1]).abs() + (p[2] - h[2]).abs() <= walk.close - }) -} -/// `MoveToTargetSink.tryComputePath`. -fn compute_path( - m: &mut Mob, - cx: &mut Bx, - walk: &WalkTarget, - path: &mut Option, - speed: &mut f32, -) -> bool { - let Some(target) = walk.target.block(cx.w) else { - return false; - }; - *path = m.create_path_to(cx.w, target, 0); - *speed = walk.speed; - if reached(m, cx.w, walk) { - mem(m).cant_reach_walk_target_since.clear(); - } else { - let can_reach = path.as_ref().is_some_and(|p| p.reached); - let mm = mem(m); - if can_reach { - mm.cant_reach_walk_target_since.clear(); - } else if !mm.cant_reach_walk_target_since.present() { - mm.cant_reach_walk_target_since.set(cx.now); - } - if path.is_some() { - return true; - } - let to = [ - f64::from(target[0]) + 0.5, - f64::from(target[1]), - f64::from(target[2]) + 0.5, - ]; - if let Some(step) = - m.default_random_pos_towards(cx.w, 10, 7, to, f64::from(std::f32::consts::FRAC_PI_2)) - { - *path = m.create_path_to(cx.w, block_of(Vec3::new(step[0], step[1], step[2])), 0); - return path.is_some(); - } - } - false -} /// `BehaviorUtils.isWithinAttackRange(body, target, 1)` for a mob without a /// ranged weapon: `Mob.isWithinMeleeAttackRange`. fn within_attack_range(m: &Mob, w: &MobWorld, target: Who) -> bool { diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index e02cfa176..cdfd49e39 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -11,6 +11,7 @@ //! `Brain::shuffle_seed` when the brain is built. use super::{ Mob, MobEvent, MobWorld, Seen, Species, Who, + brain::{Timed, living_near}, path::{Path, PathNode}, }; use horizon_core::{ @@ -341,6 +342,10 @@ fn brain_mut(m: &mut Mob) -> &mut Brain { fn mem(m: &mut Mob) -> &mut Memories { &mut brain_mut(m).mem } +/// `CANT_REACH_WALK_TARGET_SINCE`, for `compute_path`. +fn cant_reach(m: &mut Mob) -> &mut Slot { + &mut mem(m).cant_reach_walk_target_since +} fn mem_ref(m: &Mob) -> Option<&Memories> { brain(m).map(|b| &b.mem) } @@ -565,22 +570,7 @@ const FOLLOW_RANGE: f64 = 16.0; /// `NearestLivingEntitySensor`: everything alive within the follow range, /// nearest first. fn sense_living(m: &mut Mob, w: &MobWorld) { - let r = m.attrs.follow_range; - let area = m.bounds().inflate(Vec3::new(r, r, r)); - let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others_near(area) { - if o.id != m.id && o.alive && o.bounds.intersects(area) { - found.push((Who::Mob(o.id), m.distance_sqr(o.position))); - } - } - if let Some(p) = &w.player - && p.alive - && p.bounds.intersects(area) - { - found.push((Who::Player, m.distance_sqr(p.position))); - } - found.sort_by(|a, b| a.1.total_cmp(&b.1)); - let list: Vec = found.into_iter().map(|(w, _)| w).collect(); + let list = living_near(m, w); let mm = mem(m); mm.mobs.set_list(list.clone()); mm.visible_mobs.set(Visible { @@ -791,34 +781,6 @@ fn sense_golem(m: &mut Mob, w: &MobWorld) { // ---- Behaviours --------------------------------------------------------- -/// `Behavior`'s bookkeeping: running, and until when. -#[derive(Clone, Debug)] -struct Timed { - running: bool, - end: i64, - min: i32, - max: i32, -} -impl Timed { - fn new(min: i32, max: i32) -> Self { - Self { - running: false, - end: 0, - min, - max, - } - } - /// `Behavior.tryStart`'s duration draw. - fn begin(&mut self, cx: &mut Bx) { - self.running = true; - let bound = self.max.wrapping_add(1).wrapping_sub(self.min); - let d = self - .min - .wrapping_add(cx.lr.next_int_bound(bound).unwrap_or(0)); - self.end = cx.now + i64::from(d); - } -} - /// The POI types villagers use. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Poi { @@ -1498,18 +1460,18 @@ impl B { if !swim_condition(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::LookAtTargetSink(t) => { if !mem(m).look_target.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::PanicTrigger(t) => { - t.begin(cx); + t.begin(cx.lr, cx.now); // VillagerPanicTrigger.start if panic_condition(m) { if !brain_mut(m).is_active(Act::Panic) { @@ -1542,9 +1504,9 @@ impl B { } let walk = mm.walk_target.value().unwrap(); let reached = reached(m, cx.w, &walk); - if !reached && compute_path(m, cx, &walk, path, speed) { + if !reached && compute_path(m, cx.w, cx.now, &walk, path, speed, cant_reach) { *last_target = walk.target.block(cx.w); - t.begin(cx); + t.begin(cx.lr, cx.now); // start mem(m).path.set_opt(path.clone()); m.nav_move_to_path(path.clone(), f64::from(*speed)); @@ -1561,7 +1523,7 @@ impl B { if !follow_trading_condition(m, cx.w) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); follow_trading_player(m); true } @@ -1573,7 +1535,7 @@ impl B { if !matches!(a, Act::Idle | Act::Work | Act::Play) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::JumpOnBed { @@ -1590,7 +1552,7 @@ impl B { if mm.walk_target.present() || !m.is_baby() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); *bed = Some(nearest); *time_left = 100; *jumps = 3 + cx.lr.next_int_bound(4).unwrap_or(0); @@ -1599,7 +1561,7 @@ impl B { true } B::DoNothing(t) => { - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::GiveGiftToHero { @@ -1618,7 +1580,7 @@ impl B { *until_next -= 1; return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); *given = false; *started = now; let mm = mem(m); @@ -1630,7 +1592,7 @@ impl B { if !mem(m).interaction_target.present() || !show_trades_condition(m, cx.w) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); // start if let Some(target) = mem(m).interaction_target.value() { mem(m).look_target.set(Tracker::Entity(target, true)); @@ -1646,7 +1608,7 @@ impl B { if !villager_target_valid(m, cx.w, Mem::InteractionTarget) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); let target = mem(m).interaction_target.value().unwrap(); lock_gaze(m, target, cx); true @@ -1659,7 +1621,7 @@ impl B { if !breeding_possible(m, cx.w) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); let target = mem(m).breed_target.value().unwrap(); lock_gaze(m, target, cx); *birth = now + 275 + i64::from(m.random.next_int_bound(50).unwrap_or(0)); @@ -1680,7 +1642,7 @@ impl B { if !closer_to_center(site, m.position, 1.73) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); // start let mm = mem(m); mm.last_worked_at_poi.set(now); @@ -1709,7 +1671,7 @@ impl B { *valid = farmland_around(m, cx.w); *target = pick_farmland(valid, cx); let Some(p) = *target else { return false }; - t.begin(cx); + t.begin(cx.lr, cx.now); if now > *next_ok { let mm = mem(m); mm.look_target.set(Tracker::Block(p)); @@ -2288,7 +2250,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); if now > *next_ok { if super::villager::start_sleeping(m, home, w) { mem(m).last_slept.set(now); @@ -2609,7 +2571,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::LocateHidingPlace { @@ -2769,7 +2731,7 @@ impl B { && let Some(now_target) = walk.target.block(cx.w) { let d = manhattan_sq(now_target, last); - if d > 4 && compute_path(m, cx, &walk, path, speed) { + if d > 4 && compute_path(m, cx.w, cx.now, &walk, path, speed, cant_reach) { *last_target = Some(now_target); mem(m).path.set_opt(path.clone()); m.nav_move_to_path(path.clone(), f64::from(*speed)); @@ -3141,33 +3103,37 @@ fn tracker_visible(m: &mut Mob, w: &MobWorld, t: Tracker) -> bool { } } /// `MoveToTargetSink.reachedTarget`. -fn reached(m: &Mob, w: &MobWorld, walk: &WalkTarget) -> bool { +pub(super) fn reached(m: &Mob, w: &MobWorld, walk: &WalkTarget) -> bool { walk.target .block(w) .is_some_and(|p| manhattan(p, block_of(m.position)) <= walk.close) } -/// `MoveToTargetSink.tryComputePath`. -fn compute_path( +/// `MoveToTargetSink.tryComputePath`, for the brains on these memories +/// (villager, monster, warden): `cant_reach` is the brain's +/// `CANT_REACH_WALK_TARGET_SINCE`. +pub(super) fn compute_path( m: &mut Mob, - cx: &mut Bx, + w: &MobWorld, + now: i64, walk: &WalkTarget, path: &mut Option, speed: &mut f32, + cant_reach: fn(&mut Mob) -> &mut Slot, ) -> bool { - let Some(target) = walk.target.block(cx.w) else { + let Some(target) = walk.target.block(w) else { return false; }; - *path = m.create_path_to(cx.w, target, 0); + *path = m.create_path_to(w, target, 0); *speed = walk.speed; - if reached(m, cx.w, walk) { - mem(m).cant_reach_walk_target_since.clear(); + if reached(m, w, walk) { + cant_reach(m).clear(); } else { let can_reach = path.as_ref().is_some_and(|p| p.reached); - let mm = mem(m); + let since = cant_reach(m); if can_reach { - mm.cant_reach_walk_target_since.clear(); - } else if !mm.cant_reach_walk_target_since.present() { - mm.cant_reach_walk_target_since.set(cx.now); + since.clear(); + } else if !since.present() { + since.set(now); } if path.is_some() { return true; @@ -3178,14 +3144,14 @@ fn compute_path( f64::from(target[2]) + 0.5, ]; if let Some(step) = - m.default_random_pos_towards(cx.w, 10, 7, to, f64::from(std::f32::consts::FRAC_PI_2)) + m.default_random_pos_towards(w, 10, 7, to, f64::from(std::f32::consts::FRAC_PI_2)) { let p = [ step[0].floor() as i32, step[1].floor() as i32, step[2].floor() as i32, ]; - *path = m.create_path_to(cx.w, p, 0); + *path = m.create_path_to(w, p, 0); return path.is_some(); } } diff --git a/crates/horizon-client/src/mobs/warden_brain.rs b/crates/horizon-client/src/mobs/warden_brain.rs index 518347e77..8caafefc9 100644 --- a/crates/horizon-client/src/mobs/warden_brain.rs +++ b/crates/horizon-client/src/mobs/warden_brain.rs @@ -14,9 +14,10 @@ //! shuffle seed. use super::{ Mob, MobEvent, MobWorld, Who, + brain::Timed, goals::Cx, path::Path, - villager_brain::{Slot, Tracker, Visible, WalkTarget}, + villager_brain::{Slot, Tracker, Visible, WalkTarget, compute_path, reached}, warden::{self, Pose}, }; use horizon_core::{ @@ -145,31 +146,6 @@ impl Memories { } } -/// `Behavior`'s bookkeeping: running, and until when. -#[derive(Clone, Debug)] -struct Timed { - running: bool, - end: i64, - min: i32, - max: i32, -} -impl Timed { - fn new(min: i32, max: i32) -> Self { - Self { - running: false, - end: 0, - min, - max, - } - } - /// `Behavior.tryStart`'s duration draw (made even when it cannot vary). - fn begin(&mut self, cx: &mut Bx) { - self.running = true; - let d = self.min + cx.lr.next_int_bound(self.max + 1 - self.min).unwrap_or(0); - self.end = cx.now + i64::from(d); - } -} - /// `RunOne`'s `ShufflingList` over a stroll (weight 2) and `DoNothing` (1). #[derive(Clone, Debug)] struct Gate { @@ -383,6 +359,10 @@ fn brain(m: &Mob) -> Option<&Brain> { pub(super) fn mem(m: &mut Mob) -> &mut Memories { &mut m.extra.warden.as_mut().expect("a warden").brain.mem } +/// `CANT_REACH_WALK_TARGET_SINCE`, for `compute_path`. +fn cant_reach(m: &mut Mob) -> &mut Slot { + &mut mem(m).cant_reach_walk_target_since +} pub(super) fn mem_ref(m: &Mob) -> Option<&Memories> { brain(m).map(|b| &b.mem) } @@ -558,9 +538,6 @@ fn find_closest(m: &mut Mob, w: &MobWorld, filter: impl Fn(&Mob, Who) -> bool) - fn block_of(p: Vec3) -> [i32; 3] { [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32] } -fn manhattan(a: [i32; 3], b: [i32; 3]) -> i32 { - (a[0] - b[0]).abs() + (a[1] - b[1]).abs() + (a[2] - b[2]).abs() -} fn dist_sqr(a: [i32; 3], b: [i32; 3]) -> i64 { (0..3).map(|i| i64::from(a[i] - b[i]).pow(2)).sum() } @@ -607,57 +584,6 @@ fn tracker_visible(m: &mut Mob, w: &MobWorld, t: Tracker) -> bool { _ => true, } } -/// `MoveToTargetSink.reachedTarget`. -fn reached(m: &Mob, w: &MobWorld, walk: &WalkTarget) -> bool { - walk.target - .block(w) - .is_some_and(|p| manhattan(p, block_of(m.position)) <= walk.close) -} -/// `MoveToTargetSink.tryComputePath`. -fn compute_path( - m: &mut Mob, - cx: &mut Bx, - walk: &WalkTarget, - path: &mut Option, - speed: &mut f32, -) -> bool { - let Some(target) = walk.target.block(cx.w) else { - return false; - }; - *path = m.create_path_to(cx.w, target, 0); - *speed = walk.speed; - if reached(m, cx.w, walk) { - mem(m).cant_reach_walk_target_since.clear(); - } else { - let can_reach = path.as_ref().is_some_and(|p| p.reached); - let mm = mem(m); - if can_reach { - mm.cant_reach_walk_target_since.clear(); - } else if !mm.cant_reach_walk_target_since.present() { - mm.cant_reach_walk_target_since.set(cx.now); - } - if path.is_some() { - return true; - } - let to = [ - f64::from(target[0]) + 0.5, - f64::from(target[1]), - f64::from(target[2]) + 0.5, - ]; - if let Some(step) = - m.default_random_pos_towards(cx.w, 10, 7, to, f64::from(std::f32::consts::FRAC_PI_2)) - { - let p = [ - step[0].floor() as i32, - step[1].floor() as i32, - step[2].floor() as i32, - ]; - *path = m.create_path_to(cx.w, p, 0); - return path.is_some(); - } - } - false -} fn same_path(a: Option<&Path>, b: Option<&Path>) -> bool { match (a, b) { (None, None) => true, @@ -710,7 +636,7 @@ impl B { if !swim_condition(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::SetWardenLookTarget(r) => one(r, || { @@ -732,7 +658,7 @@ impl B { if !mem(m).look_target.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::MoveToTargetSink { @@ -755,9 +681,9 @@ impl B { return false; }; let reached = reached(m, cx.w, &walk); - if !reached && compute_path(m, cx, &walk, path, speed) { + if !reached && compute_path(m, cx.w, cx.now, &walk, path, speed, cant_reach) { *last_target = walk.target.block(cx.w); - t.begin(cx); + t.begin(cx.lr, cx.now); // start mem(m).path.set_opt(path.clone()); m.nav_move_to_path(path.clone(), f64::from(*speed)); @@ -775,7 +701,7 @@ impl B { if !mm.is_emerging.present() || mm.walk_target.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); warden::set_pose(m, Pose::Emerging); sound(m, "entity.warden.emerge", 5.0, 1.0, cx.events); true @@ -791,7 +717,7 @@ impl B { if !(m.on_ground || liquid) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); if m.on_ground { warden::set_pose(m, Pose::Digging); sound(m, "entity.warden.dig", 5.0, 1.0, cx.events); @@ -872,7 +798,7 @@ impl B { true }), B::DoNothing(t) => { - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::GoToDisturbance(r) => one(r, || { @@ -907,7 +833,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); sound(m, "entity.warden.sniff", 5.0, 1.0, cx.events); true } @@ -919,7 +845,7 @@ impl B { let Some(target) = mm.roar_target.value() else { return false; }; - t.begin(cx); + t.begin(cx.lr, cx.now); let mm = mem(m); mm.roar_sound_delay.set_ttl((), ROAR_SOUND_DELAY); mm.walk_target.clear(); @@ -1004,7 +930,7 @@ impl B { if !close { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); let mm = mem(m); mm.attack_cooling_down .set_ttl(true, i64::from(SONIC_DURATION)); @@ -1092,7 +1018,7 @@ impl B { && let Some(walk) = mem(m).walk_target.value() && let Some(now_target) = walk.target.block(cx.w) && dist_sqr(now_target, last) > 4 - && compute_path(m, cx, &walk, path, speed) + && compute_path(m, cx.w, cx.now, &walk, path, speed, cant_reach) { *last_target = Some(now_target); mem(m).path.set_opt(path.clone()); From 38bce65c215b3b51f466e234c70b91b1a67a590d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:50:01 +0200 Subject: [PATCH 047/408] Pass the probe name where the harness codemod missed it block_survival and state_provider hashed the name as an artifact instead of passing it; decorated_region runs chunk_dump through chunk_generation's binary. Co-Authored-By: Claude Opus 5.5 --- tools/test_block_survival_parity.py | 4 ++-- tools/test_decorated_region_parity.py | 2 +- tools/test_state_provider_parity.py | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/tools/test_block_survival_parity.py b/tools/test_block_survival_parity.py index e8d220854..2d99db9e2 100644 --- a/tools/test_block_survival_parity.py +++ b/tools/test_block_survival_parity.py @@ -240,7 +240,7 @@ def main(): metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') base.ensure_sources_unchanged(sources,tested_sources) - checkpoint={'schema':1,'environment':environment,'sources_sha256':tested_sources,'fixtures_sha256':{str(lab.ROOT/name):digest for name,digest in tested_fixtures.items()},'artifacts_sha256':{str(path):lab.digest(path,'sha256') for path in [binary,'block_survival_fixture',*sorted(classes.rglob('*.class'))]},'binary':str(binary),'counts':{'supported_blocks':len(definitions),'supported_states':sum(state['id'] in definitions for state in facts['states']),'survival_rules':len(set(definitions.values())),'survival_rule_kinds':len({rule.split(':',1)[0] for rule in definitions.values()}),'fluid_tag_files':len(fluid_tags),'fixtures':fixture_count},'outputs':{}} + checkpoint={'schema':1,'environment':environment,'sources_sha256':tested_sources,'fixtures_sha256':{str(lab.ROOT/name):digest for name,digest in tested_fixtures.items()},'artifacts_sha256':{str(path):lab.digest(path,'sha256') for path in [binary,*sorted(classes.rglob('*.class'))]},'binary':str(binary),'counts':{'supported_blocks':len(definitions),'supported_states':sum(state['id'] in definitions for state in facts['states']),'survival_rules':len(set(definitions.values())),'survival_rule_kinds':len({rule.split(':',1)[0] for rule in definitions.values()}),'fluid_tag_files':len(fluid_tags),'fixtures':fixture_count},'outputs':{}} save_checkpoint(checkpoint_path,checkpoint) print('Verified inputs and compiled executables checkpointed',flush=True) def stage(name, action): @@ -251,7 +251,7 @@ def main(): checkpoint['outputs'][name]=lab.digest(output,'sha256') save_checkpoint(checkpoint_path,checkpoint) print(f'{name}: completed output checkpointed',flush=True) - stage('rust',lambda:run([checkpoint['binary'],build],'rust')) + stage('rust',lambda:run([checkpoint['binary'],'block_survival_fixture',build],'rust')) references=[] for side,jar in jars.items(): stage(side,lambda:java(side,side,build)) diff --git a/tools/test_decorated_region_parity.py b/tools/test_decorated_region_parity.py index 2716a99e0..71ba5b469 100644 --- a/tools/test_decorated_region_parity.py +++ b/tools/test_decorated_region_parity.py @@ -66,7 +66,7 @@ def build_dir(): def vanilla_order(binary, cx, cz, view): - out = subprocess.run([str(binary), str(cg.RESOURCES), '0', 'overworld'], capture_output=True, text=True, check=True, + out = subprocess.run([str(binary), 'chunk_dump', str(cg.RESOURCES), '0', 'overworld'], capture_output=True, text=True, check=True, env=dict(os.environ, HORIZON_LIST_ORDER=f'{cx},{cz},{view}'), cwd=lab.ROOT).stdout return [tuple(map(int, line.split())) for line in out.splitlines()] diff --git a/tools/test_state_provider_parity.py b/tools/test_state_provider_parity.py index 2ff8647a5..9f7523273 100644 --- a/tools/test_state_provider_parity.py +++ b/tools/test_state_provider_parity.py @@ -376,7 +376,7 @@ def main(): binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') counts={'block_states':len(facts['states']),'blocks':len(facts['defaults']),'integer_properties':len(facts['integers']),'codec_inputs':fixture_count,'provider_types':10,'named_providers':len(catalog_resources),'rule_predicate_types':16,'survival_supported_blocks':len(survival_rules),'survival_supported_states':sum(s['id'] in survival_rules for s in facts['states']),'support_cached_states':len(support_states),'support_dynamic_states':len(facts['states'])-len(support_states),'biomes':len(biomes),'biome_tag_files':len(biome_tags),'fluid_tag_files':len(fluid_tags),'bundled_provider_definitions':len(provider_resources),'block_tag_files':len(tags),'requested_samples':requested_samples} base.ensure_sources_unchanged(sources,tested_sources) - checkpoint={'schema':1,'environment':environment,'sources_sha256':tested_sources,'fixtures_sha256':{str(lab.ROOT/name):digest for name,digest in tested_fixtures.items()},'artifacts_sha256':{str(path):lab.digest(path,'sha256') for path in [binary,'state_provider_fixture',*sorted(classes.rglob('*.class'))]},'binary':str(binary),'counts':counts,'outputs':{}} + checkpoint={'schema':1,'environment':environment,'sources_sha256':tested_sources,'fixtures_sha256':{str(lab.ROOT/name):digest for name,digest in tested_fixtures.items()},'artifacts_sha256':{str(path):lab.digest(path,'sha256') for path in [binary,*sorted(classes.rglob('*.class'))]},'binary':str(binary),'counts':counts,'outputs':{}} survival.save_checkpoint(checkpoint_path,checkpoint) print('Verified inputs and compiled executables checkpointed',flush=True) def stage(name,action): @@ -386,7 +386,7 @@ def main(): checkpoint['outputs'][name]=lab.digest(output,'sha256') survival.save_checkpoint(checkpoint_path,checkpoint) print(f'{name}: completed output checkpointed',flush=True) - stage('rust',lambda:run([checkpoint['binary'],build],'rust'));references=[] + stage('rust',lambda:run([checkpoint['binary'],'state_provider_fixture',build],'rust'));references=[] for side,jar in jars.items(): stage(side,lambda:java(side,side,build));reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) From 693556ce32620f3bcc76084ab4a725c8e40d0377 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:50:32 +0200 Subject: [PATCH 048/408] Point the particle harnesses' source lists at the probe modules Co-Authored-By: Claude Opus 5.5 --- tools/test_entity_particles_parity.py | 2 +- tools/test_particle_providers_parity.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/test_entity_particles_parity.py b/tools/test_entity_particles_parity.py index b89a5b675..f34528b4c 100644 --- a/tools/test_entity_particles_parity.py +++ b/tools/test_entity_particles_parity.py @@ -74,7 +74,7 @@ def main(): 'tools/test_entity_particles_parity.py', 'tools/oracle_harness.py', 'tools/test_rust_parity.py', 'tools/lab.py', f'mods/horizon/src/test/java/dev/horizonlab/parity/{oracle}.java', 'Cargo.toml', 'Cargo.lock', 'crates/horizon-client/Cargo.toml', 'crates/horizon-client/src/particles.rs', - f'crates/horizon-client/examples/{probe}.rs', 'crates/horizon-core/src/random.rs']] + f'crates/horizon-client/examples/probe/{probe}.rs', 'crates/horizon-core/src/random.rs']] tested = base.source_hashes(sources) cases_path, units = make_cases(build) classes, dependencies, _ = harness.compile_oracle(build, oracle, jars, baking.client_libraries(), diff --git a/tools/test_particle_providers_parity.py b/tools/test_particle_providers_parity.py index 3695722bf..def7e3bfa 100644 --- a/tools/test_particle_providers_parity.py +++ b/tools/test_particle_providers_parity.py @@ -197,7 +197,7 @@ def main(): 'tools/test_particle_providers_parity.py', 'tools/oracle_harness.py', 'tools/test_rust_parity.py', 'tools/lab.py', f'mods/horizon/src/test/java/dev/horizonlab/parity/{oracle}.java', 'Cargo.toml', 'Cargo.lock', 'crates/horizon-client/Cargo.toml', 'crates/horizon-client/src/particles.rs', - f'crates/horizon-client/examples/{probe}.rs', 'crates/horizon-core/src/random.rs']] + f'crates/horizon-client/examples/probe/{probe}.rs', 'crates/horizon-core/src/random.rs']] tested = base.source_hashes(sources) cases_path, units = make_cases(build) classes, dependencies, _ = harness.compile_oracle(build, oracle, jars, libraries, lock['minecraft']['java_major']) From 441774c229a7da496d100facffa45bc6a5cb84a8 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:51:32 +0200 Subject: [PATCH 049/408] held_drop: pass its probe name Co-Authored-By: Claude Opus 5.5 --- tools/test_held_drop_parity.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/test_held_drop_parity.py b/tools/test_held_drop_parity.py index faed08959..d2f215050 100644 --- a/tools/test_held_drop_parity.py +++ b/tools/test_held_drop_parity.py @@ -35,7 +35,7 @@ def main(): 'dev.horizonlab.parity.VanillaHeldDropOracle', str(build / 'vanilla.txt')], check=True) with (build / 'rust.txt').open('w') as out: subprocess.run(['cargo', 'run', '--quiet', '-p', 'horizon-client', '--example', - 'probe'], cwd=lab.ROOT, stdout=out, check=True) + 'probe', '--', 'held_drop_fixture'], cwd=lab.ROOT, stdout=out, check=True) matched = base.compare(build / 'vanilla.txt', build / 'rust.txt') print(f'Held drop parity passed: {matched} inventory/drop/swing/packet snapshots match vanilla') From 55264459ce4a818a7a88b42582c59e057c3a90b1 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:47:22 +0200 Subject: [PATCH 050/408] In-frame ticks stop at a tick's length per frame: an overloaded world slows down instead of drawing at 2 FPS Single player's world ticks in the frame by default (#1428). When its ticks take longer than 50 ms, every frame fell behind and ran the client timer's ten, so the picture stalled at 1-2 FPS (a player's report on an AMD 680M, in-frame tick at 36.7 ms). Vanilla's world ticks on the integrated server's thread, which falls behind without costing frames and logs "Can't keep up!". A frame now stops running world ticks once they took a tick's length and drops the rest, logging vanilla's overload warning (1 s + 20 ticks behind, at most every 10 s + 100 ticks). Ticks of a few milliseconds still get the full ten per frame; sprints and server clients are unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/clock.rs | 72 ++++++++++++++++++++++++++++++ crates/horizon-client/src/game.rs | 13 +++++- 2 files changed, 84 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/clock.rs b/crates/horizon-client/src/clock.rs index 3240944ba..5239db143 100644 --- a/crates/horizon-client/src/clock.rs +++ b/crates/horizon-client/src/clock.rs @@ -304,6 +304,10 @@ pub struct FixedStep { /// How many times `/tick step` started or stopped a step /// (`ServerTickRateManager.updateStepTicks` broadcasts each one). step_changes: u32, + /// In-frame ticks dropped since the last overload warning (`drop_ticks`). + dropped: u32, + /// When the last overload warning was due, on the frame clock. + last_overload_warning: std::time::Duration, } impl Default for FixedStep { @@ -320,6 +324,8 @@ impl Default for FixedStep { tick_count: 0, client: false, step_changes: 0, + dropped: 0, + last_overload_warning: std::time::Duration::ZERO, } } } @@ -434,6 +440,41 @@ impl FixedStep { pub fn sprinting(&self) -> bool { self.manager.is_sprinting() } + /// Whether a frame that ran its world in the frame, and whose ticks so + /// far took `spent`, may run another one. Vanilla's world ticks on the + /// integrated server's thread, so a slow tick costs its frames nothing: + /// the server falls behind and says so (`MinecraftServer.runServer`'s + /// "Can't keep up!"). In the frame, a world whose ticks take longer than + /// their length falls behind every frame, so every frame ran the client + /// timer's ten: at 57 ms a tick, 1.7 FPS. So a frame stops once its + /// ticks have taken a tick's length: ticks of a few milliseconds keep the + /// full ten, and a world that cannot keep up runs one tick a frame, + /// slower but drawn. A sprint (`/tick sprint`) runs its own frame's worth. + pub fn tick_fits(&self, spent: std::time::Duration) -> bool { + self.sprinting() || spent < self.tick_duration() + } + /// The frame skips its remaining `ticks` (`tick_fits`): the world runs + /// slower than its tick rate. Returns vanilla's overload warning when one + /// is due: a second's worth of ticks behind, at most every ten seconds + /// (`OVERLOADED_THRESHOLD_NANOS`, `OVERLOADED_WARNING_INTERVAL_NANOS`). + pub fn drop_ticks(&mut self, ticks: u32) -> Option { + self.dropped = self.dropped.saturating_add(ticks); + let tick = self.tick_duration(); + let behind = tick * self.dropped; + let threshold = std::time::Duration::from_secs(1) + tick * 20; + let interval = std::time::Duration::from_secs(10) + tick * 100; + if behind <= threshold || self.now < self.last_overload_warning + interval { + return None; + } + let warning = format!( + "Can't keep up! Is the server overloaded? Running {}ms or {} ticks behind", + behind.as_millis(), + self.dropped + ); + self.dropped = 0; + self.last_overload_warning = self.now; + Some(warning) + } /// `requestGameToSprint`: true when a sprint was already running. pub fn start_sprint(&mut self, ticks: u32) -> bool { self.manager @@ -494,6 +535,37 @@ impl FixedStep { mod tests { use super::*; + #[test] + fn a_frame_stops_ticking_after_a_ticks_length() { + let clock = FixedStep::default(); + let ms = std::time::Duration::from_millis; + // Ticks of 4 ms: the ten the timer allows fit in 50 ms. + assert!(clock.tick_fits(ms(4 * 9))); + // Ticks of 40 ms: the second one runs, not a third. + assert!(clock.tick_fits(ms(40))); + assert!(!clock.tick_fits(ms(80))); + // One tick longer than its length still runs, once a frame. + assert!(clock.tick_fits(ms(0))); + assert!(!clock.tick_fits(ms(120))); + } + #[test] + fn dropped_ticks_warn_once_a_second_behind_and_not_again_for_ten() { + let mut clock = FixedStep::default(); + let s = std::time::Duration::from_secs; + clock.now = s(20); + assert_eq!( + clock.drop_ticks(40), + None, + "two seconds: not past 1 s + 20 ticks" + ); + let warning = clock.drop_ticks(1).expect("past the threshold"); + assert!(warning.contains("2050ms or 41 ticks behind"), "{warning}"); + clock.now = s(25); + assert_eq!(clock.drop_ticks(100), None, "within ten seconds"); + clock.now = s(36); + assert!(clock.drop_ticks(0).unwrap().contains("100 ticks behind")); + } + #[test] fn timer_carries_fractions_and_caps_nothing_itself() { let mut t = Timer::new(20.0, 0); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index dc6be85b7..2eb9d1fb2 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -11274,7 +11274,17 @@ impl ApplicationHandler for Game<'_> { // For the "I'm playing" ping: an atomic, sent on when it changes. horizon_client::heartbeat::set_lan(self.is_published()); let steps = self.clock.advance(elapsed); - for _ in 0..steps { + // The world ticking in the frame: once its ticks took a + // tick's length, the rest are dropped (`FixedStep::tick_fits`). + let in_frame = self.remote.is_none(); + let mut spent = Duration::ZERO; + for step in 0..steps { + if in_frame && !self.clock.tick_fits(spent) { + if let Some(warning) = self.clock.drop_ticks(steps - step) { + log::warn!("{warning}"); + } + break; + } let started = Instant::now(); if self.title.is_none() && !self.pause { let tick = Instant::now(); @@ -11291,6 +11301,7 @@ impl ApplicationHandler for Game<'_> { self.tick_music(); self.tick_sound_engine(); self.clock.record(started.elapsed()); + spent += started.elapsed(); if let Some(report) = self.clock.take_sprint_report() { self.sprint_report(&report); } From b8e729b950284890ec79d11e4bb448e3a3e4782c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:32:35 +0200 Subject: [PATCH 051/408] Totems save a server's players: the guest's turn uses it up, and entity event 35 reaches every client A server's players (LAN guests, and single player's window on its server thread) never had a totem ready, and nothing applied one: lethal damage killed them with the totem still in hand (#1292). Each guest turn now readies the totem from the guest's hands and, when its hurt set it off, uses it up at the end of the turn (LivingEntity.checkTotemDeathProtection): 1 health, the item_used stat, the used_totem trigger, the use vibration, the totem's effects. Entity event 35 now goes to every client around, the holder's own too, and a client plays it as ClientPacketListener.handleEntityEvent does: the totem particles, the sound heard locally (not sent on as a sound packet, so no client hears it twice) and the holder's rumble. lan_e2e totem: host and guest, off hand and main hand, both modes. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/audio.rs | 7 ++ crates/horizon-client/src/game.rs | 4 +- crates/horizon-client/src/game/lan_actions.rs | 13 +++ crates/horizon-client/src/game/remote.rs | 3 + crates/horizon-client/src/game/totem.rs | 99 +++++++++++++++---- tools/lan_e2e.py | 53 ++++++++++ 6 files changed, 157 insertions(+), 22 deletions(-) diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs index f101f53cd..e59ffd867 100644 --- a/crates/horizon-client/src/audio.rs +++ b/crates/horizon-client/src/audio.rs @@ -708,6 +708,13 @@ impl Audio { let seed = self.random.next_long(); self.play_seeded(event, at, volume, pitch, seed); } + /// `play` for this client only: a sound a packet's handler plays + /// (`playLocalSound`), which the guests play from that packet themselves. + pub fn play_unshared(&mut self, event: &str, at: Option<[f64; 3]>, volume: f32, pitch: f32) { + let capture = self.capture.take(); + self.play(event, at, volume, pitch); + self.capture = capture; + } /// `LivingEntity.handleDamageEvent`'s pitch, `(r - r) * 0.2 + 1`, drawn on the /// client (the entity's own random there, never the server's world random). pub fn hurt_pitch(&mut self) -> f32 { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 01621b35b..95aca4ecb 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3968,7 +3968,7 @@ impl Game<'_> { if self.use_delay > 0 { self.use_delay -= 1; } - self.apply_totem(); + self.tick_totem(); self.update_totem_ready(); self.tick_command_extras(); self.tick_mods(); @@ -4247,7 +4247,7 @@ impl Game<'_> { } } self.powder_snow_fire()?; - self.apply_totem(); + self.tick_totem(); let Some(player) = self.player.as_mut() else { return Ok(()); }; diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 19c3a9a6c..d3cfd3766 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -361,6 +361,7 @@ impl Game<'_> { self.apply_equipment(); play.equipped = Some(equipped); } + self.update_totem_ready(); Some(GuestSwap { conn, i, @@ -414,6 +415,8 @@ impl Game<'_> { /// The second half of `as_guest`: the guest's state back into their /// record, the game's back in place, and what the turn changed sent. pub(super) fn leave_guest(&mut self, host: &mut LanHost, swap: GuestSwap) { + // A totem that saved the guest this turn (its hurt set it off). + let totem = self.apply_totem(); let GuestSwap { conn, i, @@ -624,6 +627,16 @@ impl Game<'_> { let conn = g.conn; host.hub.set_game_mode(conn, new_mode); } + // LivingEntity.checkTotemDeathProtection's entity event, to every + // client around, the guest's own included; this window draws it too. + if let Some(body) = totem { + let id = host.hub.guests[i].entity_id; + host.hub + .entity_event(id, super::totem::TOTEM_EVENT, body.at); + if self.player.is_some() { + self.totem_event(body, false); + } + } host.play.insert(conn, play); self.stat_criteria_changed(&name, stat_events); if let Some(pos) = opened diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index dfde08d7f..156fbe13b 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2131,6 +2131,9 @@ impl Game<'_> { { m.health = 0.0; } + if p.event == super::totem::TOTEM_EVENT { + self.remote_totem(p.id); + } } C::Animate(p) => self.remote_animate(p.id, p.action), // ClientPacketListener.handleSwingAnimation: the entity swings diff --git a/crates/horizon-client/src/game/totem.rs b/crates/horizon-client/src/game/totem.rs index 47b67d9f8..e26d66a1a 100644 --- a/crates/horizon-client/src/game/totem.rs +++ b/crates/horizon-client/src/game/totem.rs @@ -8,8 +8,12 @@ use horizon_client::{ const TOTEM: &str = "minecraft:totem_of_undying"; +/// `EntityEvent.TOTEM_OF_UNDYING`. +pub(super) const TOTEM_EVENT: i8 = 35; + impl Game<'_> { - /// Whether either hand holds a totem, for the next hurt. + /// Whether either hand holds a totem, for the next hurt: the window's + /// player once a tick, a server's player for each of its turns. pub(super) fn update_totem_ready(&mut self) { let ready = self.held().is_some_and(|s| &*s.item == TOTEM) || self.offhand.as_ref().is_some_and(|s| &*s.item == TOTEM); @@ -17,19 +21,21 @@ impl Game<'_> { p.health.totem_ready = ready; } } - /// A totem fired: use it up (main hand first), set health to 1, clear and - /// apply its effects, then the sound and particles. - pub(super) fn apply_totem(&mut self) { - let Some(p) = self.player.as_mut() else { - return; - }; + /// The server's half once a totem fired: use it up (main hand first), + /// count it, set health to 1, then clear and apply its effects. Returns + /// the player's body, for entity event 35, which the caller broadcasts. + pub(super) fn apply_totem(&mut self) -> Option { + let p = self.player.as_mut()?; if !p.health.totem_used { - return; + return None; } p.health.totem_used = false; let _ = p.set_health(1.0, false); - let at = [p.position.x, p.position.y, p.position.z]; - let height = f64::from(p.dimensions.height); + let body = Body { + at: [p.position.x, p.position.y, p.position.z], + width: f64::from(p.dimensions.width), + height: f64::from(p.dimensions.height), + }; let slot = if self.held().is_some_and(|s| &*s.item == TOTEM) { Some(self.selected) } else { @@ -45,6 +51,14 @@ impl Game<'_> { *cell = None; } } + self.stats.add("used", TOTEM, 1); + self.trigger_item( + "minecraft:used_totem", + &horizon_client::items::ItemStack::new(TOTEM, 1), + ); + // ItemStack.causeUseVibration: the totem's use effects make one. + let ctx = self.player_context(None); + self.post_game_event("minecraft:item_interact_finish", body.at, ctx); // DeathProtection.TOTEM_EFFECTS: clear, then regeneration II, absorption II, fire resistance. self.potions.effects.clear(); for (id, ticks, amp) in [ @@ -56,19 +70,64 @@ impl Game<'_> { self.add_player_effect(EffectInstance::new(e.id, ticks, amp)); } } - self.audio - .play("minecraft:item.totem.use", Some(at), 1.0, 1.0); - self.trigger_item( - "minecraft:used_totem", - &horizon_client::items::ItemStack::new("minecraft:totem_of_undying", 1), - ); + Some(body) + } + /// The window's player's totem: the server's half, then the event to + /// the guests and to this window's own client. + pub(super) fn tick_totem(&mut self) { + let Some(body) = self.apply_totem() else { + return; + }; + if let Some(host) = &self.lan { + host.hub + .entity_event(host.host_entity, TOTEM_EVENT, body.at); + } + self.totem_event(body, true); + } + /// Entity event 35 from a server, for this client's own player or an + /// entity it draws. + pub(super) fn remote_totem(&mut self, id: i32) { + let own = self.remote.as_ref().is_some_and(|r| r.entity_id == id); + let body = if own { + self.player.as_ref().map(|p| Body { + at: [p.position.x, p.position.y, p.position.z], + width: f64::from(p.dimensions.width), + height: f64::from(p.dimensions.height), + }) + } else { + self.mobs.iter().find(|m| m.id == id as u32).map(|m| Body { + at: [m.position.x, m.position.y, m.position.z], + width: f64::from(m.width()), + height: f64::from(m.height()), + }) + }; + if let Some(body) = body { + self.totem_event(body, own); + } + } + /// `ClientPacketListener.handleEntityEvent` 35: the totem particles (a + /// 30-tick emitter) and its sound, heard here only (`playLocalSound`), + /// and the player's own rumble. + pub(super) fn totem_event(&mut self, body: Body, own: bool) { self.particles.tracking_emitter_for( ParticleOptions::simple(ParticleType::TotemOfUndying), - at, - 0.6, - height, + body.at, + body.width, + body.height, 30, ); - self.pad_rumble(horizon_client::gamepad::Rumble::Totem); + self.audio + .play_unshared("minecraft:item.totem.use", Some(body.at), 1.0, 1.0); + if own { + self.pad_rumble(horizon_client::gamepad::Rumble::Totem); + } } } + +/// Where an entity event's entity stands and its size. +#[derive(Clone, Copy)] +pub(super) struct Body { + pub at: [f64; 3], + width: f64, + height: f64, +} diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index b3dae9ef4..12be44657 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -173,6 +173,9 @@ address. The script then checks, from both sides, what a guest's game used to ge - light: the guest's light matches the host's: around a torch placed near it, under a roof and once a block of the roof is removed under the sky, and in the last chunk it tracks next to glowstone in a chunk it doesn't (only the server's light updates bring that one). +- totem: the host and the guest each take a lethal hit holding a totem of undying in the off + hand, then the main hand: the server uses it up and keeps them alive at 1 health with its + effects, and each side hears the totem once (entity event 35) (#1292). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -4019,5 +4022,55 @@ def main(): sys.exit(0 if results and all(r['pass'] for r in results.values()) else 1) + +# Checks added after the list above (kept apart so open branches that extend it don't conflict). + + +def heard(game, sound): + return game('status')['heard'].get(sound, 0) + + +def check_totem(host, guest, out): + """LivingEntity.checkTotemDeathProtection on the server for each player: 100 damage holding a + totem in the off hand, then in the main hand, uses the totem up, leaves 1 health with + Regeneration II, Absorption II and Fire Resistance, and broadcasts entity event 35, which both + clients play once (#1292).""" + sound = 'minecraft:item.totem.use' + seen = {} + for game in (host, guest): + for hand in ('offhand', 'mainhand'): + game('command', command='gamemode survival') + game('command', command='clear @s') + game('command', command='effect clear @s') + game('command', command='effect give @s minecraft:instant_health 1 5 true') + game('command', command=f'item replace entity @s weapon.{hand} with minecraft:totem_of_undying') + game.wait(10) + before = {g.name: heard(g, sound) for g in (host, guest)} + game('command', command='damage @s 100 minecraft:generic') + game.wait(10) + me = own(game) + case = f'{game.name}-{hand}' + seen[case] = { + 'screen': game('state').get('screen'), + 'health': me['health'], + 'server_health': server_player(host, game)['health'], + 'effects': sorted(effect_ids(game)), + 'totems': server_count(game, 'totem_of_undying'), + 'heard': {g.name: heard(g, sound) - before[g.name] for g in (host, guest)}, + } + game.shot(out, f'totem-{hand}') + game('command', command='effect clear @s') + for case, s in seen.items(): + # 1 health, and what Regeneration II and the full food bar gave back since. + assert s['screen'] == 'playing' and 0 < s['health'] < 5 and 0 < s['server_health'] < 5, f'{case}: {seen}' + assert s['effects'] == ['absorption', 'fire_resistance', 'regeneration'], f'{case}: {seen}' + assert s['totems'] == 0 and s['heard'] == {'host': 1, 'guest': 1}, f'{case}: {seen}' + return seen + + +CHECKS += ['totem'] +CHECK_FNS.update(totem=check_totem) + + if __name__ == '__main__': main() From de358cd72127156cd9c27ecd662ee73b86adb113 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:39:09 +0200 Subject: [PATCH 052/408] A server's players drop their inventory on death unless keep_inventory is on The guest death path (LAN guests, dedicated players and single player's window on its server thread) gave the experience reward but never ran Player.dropEquipment, so a player died with keep_inventory off and kept everything (#1284). Both paths now share one drop_inventory: destroyVanishingCursedItems, then Inventory.dropAll from the eyes less 0.3. ServerPlayer.die skips the loot for spectators only; the window's own death skipped it in creative too, which vanilla doesn't. lan_e2e keepinv: host and guest, keep_inventory off and on, both modes. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 38 ++++++++----- crates/horizon-client/src/game/lan_actions.rs | 6 ++ tools/lan_e2e.py | 56 ++++++++++++++++++- 3 files changed, 84 insertions(+), 16 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 95aca4ecb..486f042a9 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1989,6 +1989,28 @@ impl Game<'_> { particle.scale(0.6); self.particles.push(particle); } + /// `Player.dropEquipment` for the player who died: unless keep_inventory + /// is on, `destroyVanishingCursedItems`, then `Inventory.dropAll` from + /// `at` (the eyes less 0.3): slots 0..36, armor feet to head (36..39), + /// the off hand (40), each thrown in a random direction. + fn drop_inventory(&mut self, at: [f64; 3]) { + if self.ui.rules.bool("keep_inventory") { + return; + } + let mut stacks: Vec = + self.inventory.iter_mut().filter_map(Option::take).collect(); + stacks.extend(self.armor.iter_mut().rev().filter_map(Option::take)); + stacks.extend(self.offhand.take()); + stacks.retain(|s| s.enchantment_level("minecraft:vanishing_curse") == 0); + self.apply_equipment(); + for stack in stacks { + let r = &mut self.world.random; + let strength = f64::from(r.next_float()) * 0.5; + let angle = f64::from(r.next_float()) * std::f64::consts::TAU; + let v = [-angle.sin() * strength, 0.2, angle.cos() * strength]; + self.spawn_item(stack, at, v, 40); + } + } fn spawn_item( &mut self, stack: ItemStack, @@ -4278,20 +4300,8 @@ impl Game<'_> { .experience .death_reward(self.ui.rules.bool("keep_inventory") || self.spectator()); self.spawn_orbs(feet, reward); - if !self.creative && !self.ui.rules.bool("keep_inventory") { - // Inventory.dropAll: slots 0..36, armor feet to head (36..39), off hand (40). - let mut stacks: Vec = - self.inventory.iter_mut().filter_map(Option::take).collect(); - stacks.extend(self.armor.iter_mut().rev().filter_map(Option::take)); - stacks.extend(self.offhand.take()); - self.apply_equipment(); - for stack in stacks { - let r = &mut self.world.random; - let strength = f64::from(r.next_float()) * 0.5; - let angle = f64::from(r.next_float()) * std::f64::consts::TAU; - let v = [-angle.sin() * strength, 0.2, angle.cos() * strength]; - self.spawn_item(stack, at, v, 40); - } + if !self.spectator() { + self.drop_inventory(at); } self.audio .play("minecraft:entity.player.death", Some(at), 1.0, 1.0); diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index d3cfd3766..8e07dfb05 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1717,6 +1717,9 @@ impl Game<'_> { } .death_reward(self.ui.rules.bool("keep_inventory") || g.game_mode == SPECTATOR); let (name, uuid) = (g.name.clone(), g.uuid); + // ServerPlayer.die: dropAllDeathLoot unless a spectator, from the eyes less 0.3. + let drops = (g.game_mode != SPECTATOR) + .then(|| [at[0], at[1] + g.eye_height() - 0.3, at[2]]); let cause = host.play.get_mut(&conn).and_then(|p| p.death_cause.take()); let message = match cause { // ServerPlayer.die: the death message, to everyone unless @@ -1750,6 +1753,9 @@ impl Game<'_> { ); // LivingEntity.die: the death animation, the dying player included. host.hub.entity_event(id, 3, at); + if let Some(eyes) = drops { + self.as_guest(host, conn, |game| game.drop_inventory(eyes)); + } self.spawn_orbs(at, reward); } } diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 12be44657..479feaf4e 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -176,6 +176,9 @@ address. The script then checks, from both sides, what a guest's game used to ge - totem: the host and the guest each take a lethal hit holding a totem of undying in the off hand, then the main hand: the server uses it up and keeps them alive at 1 health with its effects, and each side hears the totem once (entity event 35) (#1292). +- keepinv: the host and the guest each die holding diamonds and wearing a helmet: with keep_inventory + off both drop where they died and the player respawns without them; with it on nothing + drops and the player keeps them (#1284). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -4068,8 +4071,57 @@ def check_totem(host, guest, out): return seen -CHECKS += ['totem'] -CHECK_FNS.update(totem=check_totem) +def check_keep_inventory(host, guest, out): + """ServerPlayer.die's dropAllDeathLoot for each player (Player.dropEquipment): with keep_inventory + off, the diamonds and the helmet a player dies with lie where it died and it respawns with + neither; with it on, nothing drops and it respawns with both (#1284).""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + seen = {} + host('command', command=f'setworldspawn {hx} {hy} {hz}') + host('command', command='gamerule respawn_radius 0') + try: + for keep in ('false', 'true'): + host('command', command=f'gamerule keep_inventory {keep}') + for game, dz in ((host, -3), (guest, 3)): + # 14 blocks from the world spawn: nothing dropped is picked up on respawning. + x, z = hx + 14, hz + dz + host('command', command=f'fill {x - 2} {hy - 1} {z - 1} {x + 2} {hy - 1} {z + 1} minecraft:stone') + host('command', command=f'fill {x - 2} {hy} {z - 1} {x + 2} {hy + 2} {z + 1} minecraft:air') + host('command', command='kill @e[type=minecraft:item]') + game('command', command='gamemode survival') + game('command', command='clear @s') + game('command', command='give @s minecraft:diamond 7') + game('command', command='item replace entity @s armor.head with minecraft:iron_helmet') + game('command', command=f'tp @s {x + 0.5} {hy} {z + 0.5}') + game.wait(20) + game('command', command='kill @s') + game.wait(30) + dropped = sorted((e['item']['item'], e['item']['count']) + for e in game.raw('entities', 8, 'minecraft:item')['entities']) + game.shot(out, f'keepinv-{keep}') + respawn_when_ready(game) + game.wait(40) + back_to_game(game) + seen[f'{game.name}-keep-{keep}'] = { + 'dropped': dropped, + 'kept': {item: server_count(game, item) for item in ('diamond', 'iron_helmet')}} + finally: + host('command', command='gamerule keep_inventory false') + host('command', command='gamerule respawn_radius 10') + host('command', command='kill @e[type=minecraft:item]') + for game in (host, guest): + game('command', command='clear @s') + face_each_other(host, guest) + for case, s in seen.items(): + want = ({'dropped': [], 'kept': {'diamond': 7, 'iron_helmet': 1}} if case.endswith('true') else + {'dropped': [('minecraft:diamond', 7), ('minecraft:iron_helmet', 1)], + 'kept': {'diamond': 0, 'iron_helmet': 0}}) + assert s == want, f'{case}: {seen}' + return seen + + +CHECKS += ['totem', 'keepinv'] +CHECK_FNS.update(totem=check_totem, keepinv=check_keep_inventory) if __name__ == '__main__': From 52d8ed6721be9b7db334284f14b0fb271ba13f86 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:57:34 +0200 Subject: [PATCH 053/408] Signs open their editor on a server's players, and what they write reaches the server A sign a server's player placed (a LAN guest, or single player's window on its server thread) opened no editor: its turn's editor was dropped with the rest of the guest's screens (#1380). The server now does as ServerPlayer.openTextEdit: the block, then ClientboundOpenSignEditorPacket, and the player may write on that sign. The client opens its editor on the sign it has and sends ServerboundSignUpdatePacket when it closes; the server takes the lines (formatting codes stripped) unless the sign is waxed, the player was not the one allowed or went out of reach, and sends the sign to everyone. The window's own sign now reaches its guests too (sendBlockUpdated, not only a save). horizon-protocol: OpenSignEditor and SignUpdate, with SignTextSlot as a VarInt and the lines as a fixed list of four (26.3's stream codecs). horizon-ctl: type and key reach an open sign editor; block shows a sign's lines. lan_e2e signs: host and guest each place, write and see, both modes. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/agent.rs | 6 ++ crates/horizon-client/src/game/control.rs | 13 ++- crates/horizon-client/src/game/lan_actions.rs | 9 +- .../horizon-client/src/game/lan_stations.rs | 27 +++--- crates/horizon-client/src/game/remote.rs | 1 + crates/horizon-client/src/game/sign_edit.rs | 90 ++++++++++++++++++- crates/horizon-protocol/src/packets/play.rs | 63 +++++++++++++ tools/lan_e2e.py | 44 ++++++++- 8 files changed, 234 insertions(+), 19 deletions(-) diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 868a8d046..0c1954891 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -335,6 +335,12 @@ impl Game<'_> { Some(Ticker::Shulker { .. }) => v["lid"] = json!(self.block_anim(pos, 1.0).shulker.0), _ => {} } + // The lines of a sign, as this client has them. + if let Some(horizon_client::containers::BlockEntity::Sign(sign)) = + self.world.block_entities.get(&(pos[0], pos[1], pos[2])) + { + v["sign"] = json!({ "front": sign.front.lines, "back": sign.back.lines }); + } v } pub(super) fn stack_value(&self, s: &ItemStack) -> Value { diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 9132c7723..271f9b116 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -232,6 +232,13 @@ impl Game<'_> { "key" => { let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?; self.require_world()?; + // The sign editor takes raw presses (Enter, arrows, Backspace, Escape). + if self.sign_edit.is_some() { + if arg(2)? != "up" { + self.sign_input(Some(key), None); + } + return ok(); + } // A held edit modifier (`key super down`) and A/C/V/X: the // open book's Select All, Copy, Paste or Cut. if self.book.is_some() && arg(2)? != "up" { @@ -524,6 +531,10 @@ impl Game<'_> { self.book_type(text); return ok(); } + if self.sign_edit.is_some() { + self.sign_input(None, Some(text)); + return ok(); + } match self.screen { Screen::Chat => self.chat_type(text), Screen::CommandBlock => self.command_block_type(text), @@ -549,7 +560,7 @@ impl Game<'_> { } _ => { return Err( - "type needs the chat screen (key t tap), the language search, the creative search, the anvil or World Options".into(), + "type needs the chat screen (key t tap), a sign or book, the language search, the creative search, the anvil or World Options".into(), ); } } diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 8e07dfb05..ac557e2dd 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -30,6 +30,8 @@ use winit::keyboard::KeyCode; /// Per-guest state of the gameplay code that lives outside `Guest`. #[derive(Default)] pub(super) struct GuestPlay { + /// The sign this guest may write on (`SignBlockEntity.playerWhoMayEdit`). + pub(super) sign_editing: Option<[i32; 3]>, mining: Option, destroy_delay: u32, using: Option<(usize, u32)>, @@ -510,7 +512,8 @@ impl Game<'_> { std::mem::swap(&mut self.mount, &mut play.mount); self.container = container; self.screen = screen; - self.sign_edit = host_sign; + // A sign the guest's placement opened (SignBlock.openTextEdit). + let guest_sign = std::mem::replace(&mut self.sign_edit, host_sign); // A lectern the guest's use opened (LecternBlock.openScreen). let guest_lectern = match std::mem::replace(&mut self.book, host_book) { Some(super::books::BookScreen::View { @@ -649,6 +652,9 @@ impl Game<'_> { if let Some(station) = opened_station { self.lan_station_opened(host, conn, station); } + if let Some(edit) = guest_sign { + self.lan_open_sign_editor(host, conn, edit); + } if let Some(key) = guest_lectern { self.lan_open_lectern(host, conn, key); } @@ -1025,6 +1031,7 @@ impl Game<'_> { self.lan_station_button(host, conn, p.container, p.button); } S::RenameItem(p) => self.lan_station_rename(host, conn, &p.name), + S::SignUpdate(p) => self.lan_sign_update(host, conn, p), S::ContainerSlotStateChanged(p) => { self.lan_crafter_slot_state(host, conn, p.container, p.slot, p.enabled); } diff --git a/crates/horizon-client/src/game/lan_stations.rs b/crates/horizon-client/src/game/lan_stations.rs index 25921f936..2efcfc705 100644 --- a/crates/horizon-client/src/game/lan_stations.rs +++ b/crates/horizon-client/src/game/lan_stations.rs @@ -588,17 +588,7 @@ impl Game<'_> { let [x, y, z] = gs.pos; let name = &self.res.facts().get(self.world.block(x, y, z)).name; let block = StationKind::from_block(name) == Some(gs.kind); - let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]]; - // The block interaction range (4.5, creative 5) and the buffer. - let reach = if g.creative() { 5.0 } else { 4.5 } + 4.0; - let near = (0..3) - .map(|k| { - let lo = f64::from(gs.pos[k]); - (lo - eye[k]).max(eye[k] - lo - 1.0).max(0.0).powi(2) - }) - .sum::() - < reach * reach; - if !(block && near) { + if !(block && within_reach(g, gs.pos)) { let window = gs.window; self.lan_station_closed(host, conn, Some(window)); host.hub.send_to( @@ -670,3 +660,18 @@ pub(super) fn station_inputs(gs: &GuestStation) -> Vec { .map(|(_, _, inputs)| inputs.filter_map(|s| gs.menu.slot(s).cloned()).collect()) .unwrap_or_default() } + +/// `Player.isWithinBlockInteractionRange(pos, 4)`: the guest's eyes within +/// its block interaction range (4.5, creative 5) and a 4-block buffer of the +/// block's box. +pub(super) fn within_reach(g: &horizon_client::lan::guest::Guest, pos: [i32; 3]) -> bool { + let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]]; + let reach = if g.creative() { 5.0 } else { 4.5 } + 4.0; + (0..3) + .map(|k| { + let lo = f64::from(pos[k]); + (lo - eye[k]).max(eye[k] - lo - 1.0).max(0.0).powi(2) + }) + .sum::() + < reach * reach +} diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 156fbe13b..67e30d7c1 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2573,6 +2573,7 @@ impl Game<'_> { self.drop_remote_chunks_out_of_range(); } C::BlockEntityData(p) => self.remote_block_entity_data(p.pos, p.kind, &p.tag), + C::OpenSignEditor(p) => self.remote_open_sign_editor(p), // handleSetSpawn: ClientLevel.setRespawnData, which spawn compasses point at. C::SetDefaultSpawnPosition(p) => { let [x, y, z] = p.pos.pos; diff --git a/crates/horizon-client/src/game/sign_edit.rs b/crates/horizon-client/src/game/sign_edit.rs index c679bad69..5a26e3e69 100644 --- a/crates/horizon-client/src/game/sign_edit.rs +++ b/crates/horizon-client/src/game/sign_edit.rs @@ -1,12 +1,13 @@ //! The sign editing screen (`SignEditScreen` / `HangingSignEditScreen`): //! opened when a sign is placed, four lines limited to the sign's line //! width, Up/Down/Enter move between lines, Escape or Done closes. -use super::Game; +use super::{Game, lan::LanHost}; use horizon_client::{ containers::BlockEntity, hud::{HudBatch, rgba}, signs::wood_type, }; +use horizon_protocol::packets::play::{self, Clientbound as C, Serverbound as S}; use std::time::Instant; use winit::{ event::{ElementState, KeyEvent}, @@ -33,14 +34,95 @@ impl Game<'_> { self.right = false; self.capture(false); } + /// `AbstractSignEditScreen.removed`: a server's client sends what it + /// wrote (ServerboundSignUpdatePacket); the window's own world keeps it + /// and sends it to its guests (`sendBlockUpdated`). pub(super) fn close_sign_editor(&mut self) { if let Some(edit) = self.sign_edit.take() { - self.world - .modified - .insert((edit.pos.0 >> 4, edit.pos.2 >> 4)); + if self.remote.is_some() { + if let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get(&edit.pos) { + let side = if edit.front { &sign.front } else { &sign.back }; + self.send(S::SignUpdate(play::SignUpdate { + pos: [edit.pos.0, edit.pos.1, edit.pos.2], + lines: side.lines.clone(), + front: edit.front, + })); + } + } else { + self.mark_block_entity_updated(edit.pos); + } } self.capture(true); } + /// `ServerPlayer.openTextEdit` for the guest whose action opened a sign: + /// the block, then the editor, on its client, and the guest may write on it. + pub(super) fn lan_open_sign_editor(&mut self, host: &mut LanHost, conn: u32, edit: SignEditor) { + let pos = [edit.pos.0, edit.pos.1, edit.pos.2]; + let state = self.world.block(pos[0], pos[1], pos[2]).0 as i32; + host.hub + .send_to(conn, &C::BlockUpdate(play::BlockUpdate { pos, state })); + host.hub.send_to( + conn, + &C::OpenSignEditor(play::OpenSignEditor { + pos, + front: edit.front, + }), + ); + host.play.entry(conn).or_default().sign_editing = Some(pos); + } + /// `ServerGamePacketListenerImpl.handleSignUpdate`: the lines, formatting + /// codes stripped, go on the sign the guest may write on unless it is + /// waxed (`SignBlockEntity.updateSignText`); a guest gone out of reach + /// may no longer write (`playerIsTooFarAwayToEdit`). + pub(super) fn lan_sign_update(&mut self, host: &mut LanHost, conn: u32, p: play::SignUpdate) { + let Some(g) = host.hub.guest(conn) else { + return; + }; + let near = super::lan_stations::within_reach(g, p.pos); + let Some(play) = host.play.get_mut(&conn) else { + return; + }; + if !near { + play.sign_editing = None; + } + if play.sign_editing != Some(p.pos) { + log::warn!("{} just tried to change non-editable sign", g.name); + return; + } + let key = (p.pos[0], p.pos[1], p.pos[2]); + let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get_mut(&key) else { + return; + }; + if sign.waxed { + return; + } + let side = if p.front { + &mut sign.front + } else { + &mut sign.back + }; + for (line, new) in side.lines.iter_mut().zip(&p.lines) { + *line = horizon_client::clipboard::strip_formatting(new); + } + play.sign_editing = None; + self.mark_block_entity_updated(key); + } + /// `ClientPacketListener.handleOpenSignEditor`: the editor on a sign this + /// client has. + pub(super) fn remote_open_sign_editor(&mut self, p: play::OpenSignEditor) { + let key = (p.pos[0], p.pos[1], p.pos[2]); + if matches!( + self.world.block_entities.get(&key), + Some(BlockEntity::Sign(_)) + ) { + self.open_sign_editor(key, p.front); + } else { + log::warn!( + "ignoring openTextEdit on a block that is no sign at {:?}", + p.pos + ); + } + } pub(super) fn sign_edit_key(&mut self, event: &KeyEvent) { if event.state != ElementState::Pressed { return; diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 23ba00699..cfbc3d78b 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -461,6 +461,10 @@ packet!(OpenScreen { container: i32 => VarInt, menu: i32 => VarInt, title: Tag = // ClientboundMountScreenOpenPacket: a horse's or llama's inventory, with its // chest's columns (`getInventoryColumns`). packet!(MountScreenOpen { container: i32 => VarInt, columns: i32 => VarInt, entity: i32 => Int }); +packet!( + /// ClientboundOpenSignEditorPacket: the sign whose side the player edits. + OpenSignEditor { pos: [i32; 3] => Pos, front: bool => SignSide } +); packet!(PlayerAbilities { flags: i8 => Byte, flying_speed: f32 => Float, walking_speed: f32 => Float }); /// MessageSignature.Packed: an index into the last-seen cache or a full signature. pub struct PackedSignature; @@ -1507,6 +1511,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { MerchantOffers(MerchantOffers) = MERCHANT_OFFERS, MountScreenOpen(MountScreenOpen) = MOUNT_SCREEN_OPEN, OpenScreen(OpenScreen) = OPEN_SCREEN, + OpenSignEditor(OpenSignEditor) = OPEN_SIGN_EDITOR, Ping(Ping) = PING, PongResponse(crate::packets::status::Ping) = PONG_RESPONSE, PlayerAbilities(PlayerAbilities) = PLAYER_ABILITIES, @@ -1805,6 +1810,38 @@ packet!( /// ServerboundRenameItemPacket: `AnvilMenu.setItemName`. RenameItem { name: String => Str } ); +packet!( + /// ServerboundSignUpdatePacket: the four lines the player wrote on a side. + SignUpdate { pos: [i32; 3] => Pos, lines: [String; 4] => SignLines, front: bool => SignSide } +); +/// SignTextSlot.STREAM_CODEC: VarInt 0 for the back, 1 for the front (any +/// other id reads as the back, ByIdMap's ZERO strategy). +pub struct SignSide; +impl Codec for SignSide { + fn read(r: &mut Reader) -> Result { + Ok(r.varint()? == 1) + } + fn write(v: &bool, w: &mut Writer) { + w.varint(i32::from(*v)); + } +} +/// `stringUtf8(384)` in `fixedSizeList(4)`: four lines, no count. +pub struct SignLines; +impl Codec<[String; 4]> for SignLines { + fn read(r: &mut Reader) -> Result<[String; 4]> { + Ok([ + r.string(384)?, + r.string(384)?, + r.string(384)?, + r.string(384)?, + ]) + } + fn write(v: &[String; 4], w: &mut Writer) { + for line in v { + w.string(line); + } + } +} packet!( /// ServerboundSetBeaconPacket: `BeaconMenu.updateEffects`, each power an /// optional `mob_effect` id. @@ -1912,6 +1949,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { SetBeacon(SetBeacon) = SET_BEACON, SetCarriedItem(SetCarriedItem) = SET_CARRIED_ITEM, SetCreativeModeSlot(SetCreativeModeSlot) = SET_CREATIVE_MODE_SLOT, + SignUpdate(SignUpdate) = SIGN_UPDATE, UseItem(UseItem) = USE_ITEM, UseItemOn(UseItemOn) = USE_ITEM_ON, }); @@ -2608,4 +2646,29 @@ mod tests { }); round_trip(p, Clientbound::encode, Clientbound::decode); } + + #[test] + fn sign_packets_match_vanilla_stream_codecs() { + // ClientboundOpenSignEditorPacket: BlockPos, then SignTextSlot as a VarInt (FRONT is 1). + let open = Clientbound::OpenSignEditor(OpenSignEditor { + pos: [1, 2, 3], + front: true, + }); + let body = open.encode(); + assert_eq!( + body[1..9], + crate::buf::pack_block_pos([1, 2, 3]).to_be_bytes() + ); + assert_eq!(body[9..], [1]); + round_trip(open, Clientbound::encode, Clientbound::decode); + // ServerboundSignUpdatePacket: BlockPos, four strings with no count, then the slot. + let update = Serverbound::SignUpdate(SignUpdate { + pos: [-4, 70, 9], + lines: ["Hi".into(), String::new(), "x".into(), String::new()], + front: false, + }); + let body = update.encode(); + assert_eq!(body[9..], [2, b'H', b'i', 0, 1, b'x', 0, 0]); + round_trip(update, Serverbound::encode, Serverbound::decode); + } } diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 479feaf4e..f5127fa0c 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -179,6 +179,9 @@ address. The script then checks, from both sides, what a guest's game used to ge - keepinv: the host and the guest each die holding diamonds and wearing a helmet: with keep_inventory off both drop where they died and the player respawns without them; with it on nothing drops and the player keeps them (#1284). +- signs: the host and the guest each place an oak sign: the editor opens on their own screen + (ClientboundOpenSignEditorPacket), the two lines they write reach the server + (ServerboundSignUpdatePacket) and both sides show them (#1380). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -4120,8 +4123,45 @@ def check_keep_inventory(host, guest, out): return seen -CHECKS += ['totem', 'keepinv'] -CHECK_FNS.update(totem=check_totem, keepinv=check_keep_inventory) +def check_signs(host, guest, out): + """SignBlock.openTextEdit on the placing player's client, for the host and the guest: placing + an oak sign opens its editor there and nowhere else, the lines typed into it go to the server + when it closes, and both sides then show them (#1380).""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + seen = {} + for game, other, dz in ((host, guest, -2), (guest, host, 2)): + spot = (hx + 2, hy, hz + dz) + game('command', command=f'setblock {spot[0]} {spot[1] - 1} {spot[2]} minecraft:stone') + game('command', command=f'setblock {spot[0]} {spot[1]} {spot[2]} minecraft:air') + game('command', command='gamemode survival') + game('command', command='clear @s') + game('command', command='give @s minecraft:oak_sign 1') + game.wait(10) + game.raw('place', *spot, '--item', 'minecraft:oak_sign') + game.wait(10) + opened = {g.name: g('state').get('screen') for g in (game, other)} + game.shot(out, 'signs-editor') + lines = [f'{game.name} wrote', 'line two'] + game.raw('type', lines[0]) + game.raw('key', 'enter', 'tap') + game.raw('type', lines[1]) + game.raw('key', 'esc', 'tap') + game.wait(20) + back_to_game(other) + seen[game.name] = {'opened': opened, + 'shown': {g.name: (g.raw('block', *spot).get('sign') or {}).get('front') + for g in (game, other)}} + other.shot(out, 'signs-shown') + for name, s in seen.items(): + other = 'guest' if name == 'host' else 'host' + want = [f'{name} wrote', 'line two', '', ''] + assert s['opened'] == {name: 'sign', other: 'playing'}, f'{name}: {seen}' + assert s['shown'] == {name: want, other: want}, f'{name}: {seen}' + return seen + + +CHECKS += ['totem', 'keepinv', 'signs'] +CHECK_FNS.update(totem=check_totem, keepinv=check_keep_inventory, signs=check_signs) if __name__ == '__main__': From 5617d702cc62e676de8c24c4506ad055a62617b8 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:09:55 +0200 Subject: [PATCH 054/408] Books open on a server's players, and what they write and sign reaches the server A server's player (a LAN guest, or single player's window on its server thread) could neither write in a book and quill nor read a written book: the server opened the screens in the guest's turn and dropped them (#1366). As in vanilla, the client opens a book and quill's editor itself when it uses one (LocalPlayer.openItemGui) and sends ServerboundEditBookPacket when it saves or signs; the server writes the pages or makes the written book, signed with the player's name, in that hotbar slot or the off hand. A written book opens on the client when the server sends ClientboundOpenBookPacket for its hand (ServerPlayer.openItemGui). horizon-protocol: OpenBook and EditBook (pages a list of at most 100). horizon-ctl: book sign presses Sign, then Sign and Close; book done on a book and quill saves it, as its Done button does. lan_e2e books: host and guest each write, sign, read and drop a book, both modes. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/books.rs | 153 ++++++++++++++---- crates/horizon-client/src/game/lan_actions.rs | 1 + crates/horizon-client/src/game/remote.rs | 6 +- .../src/game/station_control.rs | 2 +- crates/horizon-protocol/src/packets/play.rs | 49 ++++++ tools/lan_e2e.py | 59 ++++++- 6 files changed, 237 insertions(+), 33 deletions(-) diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs index ccc1c6e19..9af1da70c 100644 --- a/crates/horizon-client/src/game/books.rs +++ b/crates/horizon-client/src/game/books.rs @@ -3,9 +3,10 @@ //! pixels, 1024 characters, 100 pages), signing it into a written book, //! reading written books, and lecterns (placing a book, turning its pages //! with a redstone pulse, the comparator output and taking the book). -use super::Game; +use super::{Game, lan::LanHost}; use horizon_client::{ containers::{BlockEntity, Lectern}, + first_person::Hand, hud::{HudBatch, rgba}, item_data::WrittenBook, items::ItemStack, @@ -14,6 +15,7 @@ use horizon_client::{ ui, }; use horizon_core::position::BlockPos; +use horizon_protocol::packets::play::{self, Clientbound as C, Serverbound as S}; use horizon_world::level::flags as level_flags; use std::time::Instant; use winit::{ @@ -48,9 +50,32 @@ impl Game<'_> { fn book_lines(&self, page: &str) -> Vec { self.gui.atlas.font.split(&Text::literal(page), 114.0) } - /// `WritableBookItem.use` / `WrittenBookItem.use`. + /// `WritableBookItem.use` / `WrittenBookItem.use` (`Player.openItemGui`). + /// A server's player writes in its own client's editor + /// (`LocalPlayer.openItemGui`), and reads on its own client once told to + /// (`ServerPlayer.openItemGui`'s ClientboundOpenBookPacket). pub(super) fn use_book(&mut self, stack: &ItemStack) -> bool { - let screen = match &*stack.item { + let written = match &*stack.item { + "minecraft:writable_book" => false, + "minecraft:written_book" => true, + _ => return false, + }; + if self.lan_acting.is_some() { + if written { + let hand = i32::from(self.hand == Hand::Off); + self.guest_packets + .push(C::OpenBook(play::OpenBook { hand })); + } + } else if let Some(screen) = self.book_screen(stack) { + self.open_book(screen); + } + self.swing_arm(); + true + } + /// The screen a book in hand opens: `BookEditScreen` for a book and + /// quill, `BookViewScreen` for a written book. + fn book_screen(&self, stack: &ItemStack) -> Option { + Some(match &*stack.item { "minecraft:writable_book" => { let mut pages = stack .data() @@ -77,12 +102,31 @@ impl Game<'_> { page: 0, lectern: None, }, - _ => return false, - }; - self.open_book(screen); - self.swing_arm(); + _ => return None, + }) + } + /// `MultiPlayerGameMode.useItem`'s own use of a book and quill on a + /// server's client: its editor opens here at once. + pub(super) fn remote_use_book(&mut self, stack: &ItemStack) -> bool { + if &*stack.item != "minecraft:writable_book" { + return false; + } + if let Some(screen) = self.book_screen(stack) { + self.open_book(screen); + } true } + /// `ClientPacketListener.handleOpenBook`: the written book in that hand. + pub(super) fn remote_open_book(&mut self, hand: i32) { + let hand = if hand == 1 { Hand::Off } else { Hand::Main }; + let screen = self.with_hand(hand, |g| { + let stack = g.held().filter(|s| &*s.item == "minecraft:written_book")?; + g.book_screen(&stack.clone()) + }); + if let Some(screen) = screen { + self.open_book(screen); + } + } fn open_book(&mut self, screen: BookScreen) { self.book = Some(screen); self.keys.clear(); @@ -104,7 +148,9 @@ impl Game<'_> { self.book = None; self.capture(true); } - /// `BookEditScreen.saveChanges`: trailing empty pages dropped. + /// `BookEditScreen.saveChanges` and `BookSignScreen`'s Sign and Close: + /// trailing empty pages dropped, the book in hand updated here and, on a + /// server's client, sent (ServerboundEditBookPacket). fn save_book(&mut self, sign: bool) { let Some(BookScreen::Edit { slot, pages, title, .. @@ -116,29 +162,59 @@ impl Game<'_> { while pages.len() > 1 && pages.last().is_some_and(String::is_empty) { pages.pop(); } - if let Some(stack) = self.stack_in_mut(slot).as_mut() - && &*stack.item == "minecraft:writable_book" - { - if sign { - let mut written = ItemStack::new("minecraft:written_book", 1); - written.data_mut().written = Some(WrittenBook { - title: title.trim().to_owned(), - author: super::chat::PLAYER_NAME.to_owned(), - generation: 0, - pages, - }); - *stack = written; - } else { - stack.data_mut().writable_pages = if pages.iter().all(String::is_empty) { - Vec::new() - } else { - pages - }; - stack.tidy(); - } + let title = sign.then(|| title.trim().to_owned()); + if self.remote.is_some() { + self.send(S::EditBook(play::EditBook { + slot: slot as i32, + pages: pages.clone(), + title: title.clone(), + })); } + self.write_book(slot, pages, title); self.capture(true); } + /// The book and quill at `slot` takes the pages, or with a title becomes + /// the written book its writer signed. + fn write_book(&mut self, slot: usize, pages: Vec, title: Option) { + let author = self + .lan_acting_name + .clone() + .unwrap_or_else(|| super::chat::PLAYER_NAME.to_owned()); + let Some(stack) = self + .stack_in_mut(slot) + .as_mut() + .filter(|s| &*s.item == "minecraft:writable_book") + else { + return; + }; + if let Some(title) = title { + let mut written = ItemStack::new("minecraft:written_book", 1); + written.data_mut().written = Some(WrittenBook { + title, + author, + generation: 0, + pages, + }); + *stack = written; + } else { + stack.data_mut().writable_pages = if pages.iter().all(String::is_empty) { + Vec::new() + } else { + pages + }; + stack.tidy(); + } + } + /// `ServerGamePacketListenerImpl.handleEditBook`: a guest's book in a + /// hotbar slot or its off hand (`updateBookContents`, `signBook`). + pub(super) fn lan_edit_book(&mut self, host: &mut LanHost, conn: u32, p: play::EditBook) { + if !((0..9).contains(&p.slot) || p.slot == super::shield::OFFHAND_SLOT as i32) { + return; + } + self.as_guest(host, conn, |g| { + g.write_book(p.slot as usize, p.pages, p.title) + }); + } pub(super) fn book_key(&mut self, event: &KeyEvent) { if event.state != ElementState::Pressed { return; @@ -519,7 +595,26 @@ impl Game<'_> { Some(key) => self.lectern_button(key, 3), None => return Err("not a lectern".into()), }, - Some("done") => self.close_book(), + // The book and quill's buttons: Sign, then Sign and Close; Done + // (which saves), then Cancel. + Some("sign") => match self.book.as_mut() { + Some(BookScreen::Edit { + signing: true, + title, + .. + }) if !title.trim().is_empty() => self.save_book(true), + Some(BookScreen::Edit { signing, .. }) => *signing = true, + _ => return Err("not a book and quill".into()), + }, + Some("done") => match self.book.as_mut() { + Some(BookScreen::Edit { signing: true, .. }) => { + if let Some(BookScreen::Edit { signing, .. }) = self.book.as_mut() { + *signing = false; + } + } + Some(BookScreen::Edit { .. }) => self.save_book(false), + _ => self.close_book(), + }, Some(other) => return Err(format!("unknown book button {other}").into()), } Ok(match &self.book { diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index ac557e2dd..73fa67ba9 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1032,6 +1032,7 @@ impl Game<'_> { } S::RenameItem(p) => self.lan_station_rename(host, conn, &p.name), S::SignUpdate(p) => self.lan_sign_update(host, conn, p), + S::EditBook(p) => self.lan_edit_book(host, conn, p), S::ContainerSlotStateChanged(p) => { self.lan_crafter_slot_state(host, conn, p.container, p.slot, p.enabled); } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 67e30d7c1..bb4a3d9c1 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2574,6 +2574,7 @@ impl Game<'_> { } C::BlockEntityData(p) => self.remote_block_entity_data(p.pos, p.kind, &p.tag), C::OpenSignEditor(p) => self.remote_open_sign_editor(p), + C::OpenBook(p) => self.remote_open_book(p.hand), // handleSetSpawn: ClientLevel.setRespawnData, which spawn compasses point at. C::SetDefaultSpawnPosition(p) => { let [x, y, z] = p.pos.pos; @@ -3978,8 +3979,11 @@ impl Game<'_> { return false; }; // MultiPlayerGameMode.useItem runs the use here too: food starts - // being eaten (Consumable.startConsuming). + // being eaten (Consumable.startConsuming), a book and quill opens. self.with_hand(hand, |g| g.start_eating(&info)); + if self.with_hand(hand, |g| g.remote_use_book(&held)) { + return true; + } // BowItem.use: startUsingItem here too (with an arrow, or in creative), so that letting // go sends RELEASE_USE_ITEM (Minecraft.handleKeybinds) and the server shoots. if &*held.item == "minecraft:bow" { diff --git a/crates/horizon-client/src/game/station_control.rs b/crates/horizon-client/src/game/station_control.rs index ecbbad0b8..7530b4278 100644 --- a/crates/horizon-client/src/game/station_control.rs +++ b/crates/horizon-client/src/game/station_control.rs @@ -10,7 +10,7 @@ pub(super) const HELP: &[&str] = &[ "use X Y Z open the block's menu as if right-clicked", "click-slot ID [right] [shift] click a menu slot (0-35 inventory, 300+ container, 600+ station, 650 result)", "click-gui X Y [right] [shift] click at GUI pixel X Y relative to the menu's top-left corner", - "book [next|back|take|done] the open book or lectern: its page, or press one of its buttons", + "book [next|back|take|sign|done] the open book or lectern: its page, or press one of its buttons", "type TEXT | type-back type into the anvil name box / delete one character", "enchant ID LEVEL enchant the held item (books store the enchantment)", "potion ITEM POTION give a potion item (potion, splash_potion, lingering_potion, tipped_arrow)", diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index cfbc3d78b..fe3d19b85 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -465,6 +465,11 @@ packet!( /// ClientboundOpenSignEditorPacket: the sign whose side the player edits. OpenSignEditor { pos: [i32; 3] => Pos, front: bool => SignSide } ); +packet!( + /// ClientboundOpenBookPacket: the hand (InteractionHand, 0 main, 1 off) + /// whose written book the player reads. + OpenBook { hand: i32 => VarInt } +); packet!(PlayerAbilities { flags: i8 => Byte, flying_speed: f32 => Float, walking_speed: f32 => Float }); /// MessageSignature.Packed: an index into the last-seen cache or a full signature. pub struct PackedSignature; @@ -1511,6 +1516,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { MerchantOffers(MerchantOffers) = MERCHANT_OFFERS, MountScreenOpen(MountScreenOpen) = MOUNT_SCREEN_OPEN, OpenScreen(OpenScreen) = OPEN_SCREEN, + OpenBook(OpenBook) = OPEN_BOOK, OpenSignEditor(OpenSignEditor) = OPEN_SIGN_EDITOR, Ping(Ping) = PING, PongResponse(crate::packets::status::Ping) = PONG_RESPONSE, @@ -1814,6 +1820,29 @@ packet!( /// ServerboundSignUpdatePacket: the four lines the player wrote on a side. SignUpdate { pos: [i32; 3] => Pos, lines: [String; 4] => SignLines, front: bool => SignSide } ); +packet!( + /// ServerboundEditBookPacket: the book's slot (a hotbar slot, or 40 for + /// the off hand), its pages and, to sign it, its title. + EditBook { + slot: i32 => VarInt, + pages: Vec => BookPages, + title: Option => Opt>, + } +); +/// `stringUtf8(1024)` in `list(100)`: a book's pages. +pub struct BookPages; +impl Codec> for BookPages { + fn read(r: &mut Reader) -> Result> { + let n = r.varint()?; + if !(0..=100).contains(&n) { + return Err(Error::new(format!("{n} book pages, at most 100"))); + } + (0..n).map(|_| r.string(1024)).collect() + } + fn write(v: &Vec, w: &mut Writer) { + List::>::write(v, w); + } +} /// SignTextSlot.STREAM_CODEC: VarInt 0 for the back, 1 for the front (any /// other id reads as the back, ByIdMap's ZERO strategy). pub struct SignSide; @@ -1925,6 +1954,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { ContainerClick(ContainerClick) = CONTAINER_CLICK, ContainerClose(ContainerClose) = CONTAINER_CLOSE, CustomPayload(CustomPayload) = CUSTOM_PAYLOAD, + EditBook(EditBook) = EDIT_BOOK, Interact(Interact) = INTERACT, KeepAlive(KeepAlive) = KEEP_ALIVE, MovePlayerPos(MovePlayerPos) = MOVE_PLAYER_POS, @@ -2671,4 +2701,23 @@ mod tests { assert_eq!(body[9..], [2, b'H', b'i', 0, 1, b'x', 0, 0]); round_trip(update, Serverbound::encode, Serverbound::decode); } + + #[test] + fn book_packets_match_vanilla_stream_codecs() { + // ClientboundOpenBookPacket: InteractionHand as a VarInt. + let open = Clientbound::OpenBook(OpenBook { hand: 1 }); + assert_eq!(open.encode()[1..], [1]); + round_trip(open, Clientbound::encode, Clientbound::decode); + // ServerboundEditBookPacket: the slot, the pages (a counted list), then an optional title. + let sign = Serverbound::EditBook(EditBook { + slot: 40, + pages: vec!["a".into(), String::new()], + title: Some("T".into()), + }); + assert_eq!(sign.encode()[1..], [40, 2, 1, b'a', 0, 1, 1, b'T']); + round_trip(sign, Serverbound::encode, Serverbound::decode); + let mut w = Writer::new(); + w.varint(101); + assert!(BookPages::read(&mut Reader::new(&w.data)).is_err()); + } } diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index f5127fa0c..3b369564f 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -182,6 +182,10 @@ address. The script then checks, from both sides, what a guest's game used to ge - signs: the host and the guest each place an oak sign: the editor opens on their own screen (ClientboundOpenSignEditorPacket), the two lines they write reach the server (ServerboundSignUpdatePacket) and both sides show them (#1380). +- books: the host and the guest each write in a book and quill on their own screen, sign it + (ServerboundEditBookPacket), read the written book the server gave them + (ClientboundOpenBookPacket), then drop it: the other side sees its title, author and + page (#1366). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -4160,8 +4164,59 @@ def check_signs(host, guest, out): return seen -CHECKS += ['totem', 'keepinv', 'signs'] -CHECK_FNS.update(totem=check_totem, keepinv=check_keep_inventory, signs=check_signs) +def book_screen(game): + """The open book (`book`'s page and page count), once `game` shows it.""" + game.raw('wait-for', 'screen', 'book', '--timeout', 10) + return game.raw('book') + + +def check_books(host, guest, out): + """Books in hand for the host and the guest: a book and quill opens its editor on the player's + own client (LocalPlayer.openItemGui), what it writes and signs reaches the server + (ServerboundEditBookPacket), and the written book opens on the player's client when the server + says so (ServerPlayer.openItemGui's ClientboundOpenBookPacket); dropped, the other side sees the + server's book (#1366).""" + seen = {} + for game, other in ((host, guest), (guest, host)): + game('command', command='gamemode survival') + game('command', command='clear @s') + game('command', command='item replace entity @s weapon.mainhand with minecraft:writable_book') + x, y, z = pos_of(game) + game.raw('look-at', f'{x + 0.5:.2f}', f'{y + 30:.2f}', f'{z:.2f}') + game.wait(10) + case = seen[game.name] = {} + game.raw('use-item') + case['edit'] = book_screen(game) + case['other_screen'] = other('state').get('screen') + game.raw('type', f'{game.name} page one') + game.shot(out, 'books-edit') + game.raw('book', 'sign') + game.raw('type', f'{game.name} book') + game.raw('book', 'sign') + game.wait(20) + case['signed'] = {item: server_count(game, item) for item in ('writable_book', 'written_book')} + game.raw('use-item') + case['view'] = book_screen(game) + game.shot(out, 'books-view') + game.raw('book', 'done') + game.wait(5) + game.raw('key', 'q', 'tap') + game.wait(30) + books = [e['item'].get('components', '') for e in other.raw('entities', 16, 'minecraft:item')['entities'] + if e['item']['item'] == 'minecraft:written_book'] + case['dropped'] = [all(f'{game.name} {t}' in c for t in ('page one', 'book')) for c in books] + host('command', command='kill @e[type=minecraft:item]') + for name, case in seen.items(): + assert case['edit'] == {'page': 0, 'pages': 1, 'lectern': None}, f'{name}: {seen}' + assert case['other_screen'] == 'playing', f'{name}: {seen}' + assert case['signed'] == {'writable_book': 0, 'written_book': 1}, f'{name}: {seen}' + assert case['view'] == {'page': 0, 'pages': 1, 'lectern': None}, f'{name}: {seen}' + assert case['dropped'] == [True], f'{name}: {seen}' + return seen + + +CHECKS += ['totem', 'keepinv', 'signs', 'books'] +CHECK_FNS.update(totem=check_totem, keepinv=check_keep_inventory, signs=check_signs, books=check_books) if __name__ == '__main__': From 5ed8181adca456aae7ca081bc8b0acd6e1d5b47b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 19:12:44 +0200 Subject: [PATCH 055/408] Elytra glides on a server's players: the client sends START_FALL_FLYING and the server checks it A server's client never took the chest slot's Elytra into its own movement (player.glider) and never told the server it started gliding, so on the server thread and as a LAN guest the player just fell. The client now sets the glider as the window's own tick does and sends ServerboundPlayerCommandPacket START_FALL_FLYING when a glide starts. The hub used to accept that command blindly and never clear it. The game now answers it as handlePlayerCommand does (Player.tryToStartFallFlying, else stopFallFlying), and each tick runs LivingEntity.updateFallFlying for a gliding guest: the glide ends once canGlide fails (landed, riding, flying, levitation, a glider about to break), every 20th tick wears the Elytra, every 10th is an elytra_glide game event, and a glide that isn't diving keeps the fall distance at 1 (checkFallDistanceAccumulation). lan_e2e gets an elytra check, for the host and the guest, both modes. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 27 +++--- crates/horizon-client/src/game/agent.rs | 1 + crates/horizon-client/src/game/lan.rs | 2 + crates/horizon-client/src/game/lan_actions.rs | 89 +++++++++++++++++++ crates/horizon-client/src/game/remote.rs | 17 ++++ crates/horizon-client/src/lan/hub.rs | 7 +- tools/lan_e2e.py | 55 ++++++++++++ 7 files changed, 181 insertions(+), 17 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 486f042a9..c62994dec 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1812,6 +1812,16 @@ impl Game<'_> { self.stack_in_mut(self.held_slot()) } /// The slot of the hand that acts: the selected one, or `OFFHAND_SLOT`. + /// `LivingEntity.canGlideUsing`: a glider in the chest slot that will + /// not break with its next point of wear. + fn glider_worn(&self) -> bool { + self.armor[1].as_ref().is_some_and(|s| { + self.res + .items() + .get(&s.item) + .is_some_and(|i| i.glider && (i.max_damage == 0 || s.damage + 1 < i.max_damage)) + }) + } fn held_slot(&self) -> usize { match self.hand { Hand::Main => self.selected, @@ -3931,13 +3941,7 @@ impl Game<'_> { .as_ref() .map_or(0, |s| s.enchantment_level("minecraft:respiration") as i32); player.pitch = self.pitch; - // LivingEntity.canGlideUsing: a glider in its slot that will not break next. - player.glider = self.armor[1].as_ref().is_some_and(|s| { - self.res - .items() - .get(&s.item) - .is_some_and(|i| i.glider && (i.max_damage == 0 || s.damage + 1 < i.max_damage)) - }); + player.glider = self.glider_worn(); // A saved death already dropped inventory/XP and counted the death. if player.health.dead_or_dying() { self.screen = Screen::Dead; @@ -4015,6 +4019,7 @@ impl Game<'_> { let riding = self.riding.is_some(); let ghast_collisions = self.happy_ghast_player_collisions(); let spin_targets = self.spin_targets(); + let glider = self.glider_worn(); let Some(player) = self.player.as_mut() else { // A dedicated server has no local player: the world still runs. if self.options.dedicated.is_some() { @@ -4057,13 +4062,7 @@ impl Game<'_> { .as_ref() .map_or(0, |s| s.enchantment_level("minecraft:respiration") as i32); player.pitch = self.pitch; - // LivingEntity.canGlideUsing: a glider in its slot that will not break next. - player.glider = self.armor[1].as_ref().is_some_and(|s| { - self.res - .items() - .get(&s.item) - .is_some_and(|i| i.glider && (i.max_damage == 0 || s.damage + 1 < i.max_damage)) - }); + player.glider = glider; // LocalPlayer.modifyInput: walking while using an item. player.item_use_speed = self .using diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 0c1954891..89fec4254 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -463,6 +463,7 @@ impl Game<'_> { "velocity": [p.velocity.x, p.velocity.y, p.velocity.z], "on_ground": p.ground.on_ground, "flying": p.flying, + "fall_flying": p.fall_flying, "sneaking": self.keys.contains(&KeyCode::ShiftLeft), "sprinting": self.keys.contains(&KeyCode::ControlLeft), "health": p.health.health(), diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 8467b6d3a..9db544421 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -410,6 +410,8 @@ impl Game<'_> { // ItemCooldowns: the ticks the shield an axe disabled stays down. "shield_cooldown": h.play.get(&g.conn).map_or(0, |p| p.shield_cooldown), "sneaking": g.sneaking, + // The server's Elytra glide (shared flag 7). + "fall_flying": g.fall_flying, "sleeping": g.bed, "health": g.health, // The server's body: its air supply and golden hearts. diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 73fa67ba9..81ee2860b 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1027,6 +1027,7 @@ impl Game<'_> { g.open_ridden_mount_menu(); }); } + S::PlayerCommand(p) if p.action == 6 => self.lan_start_gliding(host, conn), S::ContainerButtonClick(p) => { self.lan_station_button(host, conn, p.container, p.button); } @@ -1850,6 +1851,13 @@ impl Game<'_> { /// sounds are heard at the guest. fn guest_server_tick(&mut self, host: &mut LanHost, conn: u32) { self.guest_vehicle_tick(host, conn); + // The last move's fall stands in for the server's delta movement. + let fell = host + .hub + .guest_mut(conn) + .and_then(|g| g.moves.last().map(|m| m.0[1])) + .unwrap_or(0.0); + self.guest_glide_tick(host, conn, fell); let Some(g) = host.hub.guest_mut(conn) else { return; }; @@ -1966,6 +1974,87 @@ impl Game<'_> { } } + /// ServerGamePacketListenerImpl.handlePlayerCommand START_FALL_FLYING: + /// `Player.tryToStartFallFlying`, or else `stopFallFlying` (a second + /// start while gliding ends the glide, as in vanilla). + fn lan_start_gliding(&mut self, host: &mut LanHost, conn: u32) { + let Some(g) = host.hub.guest_mut(conn) else { + return; + }; + let start = !g.fall_flying && self.guest_can_glide(host, conn) == Some(true); + let in_liquid = self + .as_guest(host, conn, |game| { + game.player + .as_ref() + .is_some_and(|p| p.fluids.was_touching_water || p.is_in_lava()) + }) + .unwrap_or(true); + if let Some(g) = host.hub.guest_mut(conn) { + g.fall_flying = start && !in_liquid; + } + } + + /// `Player.canGlide`: not flying, airborne, not riding, no levitation, and + /// a glider that its next point of wear won't break. + fn guest_can_glide(&mut self, host: &mut LanHost, conn: u32) -> Option { + let g = host.hub.guest_mut(conn)?; + if g.flying || g.on_ground || g.vehicle.is_some() { + return Some(false); + } + self.as_guest(host, conn, |game| { + game.glider_worn() && game.potions.effects.get("levitation").is_none() + }) + } + + /// `LivingEntity.updateFallFlying` on the server, once a tick for a + /// gliding guest: the glide ends once `canGlide` fails; otherwise every + /// 20th tick wears the glider by one, and every 10th is an + /// `elytra_glide` game event. Entity.checkFallDistanceAccumulation runs + /// first: a glide that isn't diving keeps the fall distance at 1. + fn guest_glide_tick(&mut self, host: &mut LanHost, conn: u32, fell: f64) { + let Some(g) = host.hub.guest_mut(conn) else { + return; + }; + if !g.fall_flying { + if let Some(m) = g.motion.as_mut() { + m.fall_fly_ticks = 0; + } + return; + } + let creative = g.creative(); + if let Some(m) = g.motion.as_mut() + && fell > -0.5 + && m.fall_distance > 1.0 + { + m.fall_distance = 1.0; + } + if self.guest_can_glide(host, conn) != Some(true) { + if let Some(g) = host.hub.guest_mut(conn) { + g.fall_flying = false; + } + return; + } + self.as_guest(host, conn, |game| { + let Some(p) = game.player.as_mut() else { + return; + }; + p.fall_fly_ticks += 1; + let next = p.fall_fly_ticks + 1; + let at = [p.position.x, p.position.y, p.position.z]; + if next % 10 != 0 { + return; + } + if (next / 10) % 2 == 0 + && !creative + && let Some(elytra) = game.armor[1].as_mut() + { + elytra.damage += 1; + } + let ctx = game.player_context(None); + game.post_game_event("minecraft:elytra_glide", at, ctx); + }); + } + /// `Player.isInWall`: a suffocating block in the 0.48-wide box at the /// eyes. Suffocating is a full collision box that is also a full render /// cube (`BlockBehaviour.isSuffocating`'s default; glass and the like diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index bb4a3d9c1..362dc3cf2 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3139,6 +3139,12 @@ impl Game<'_> { .as_ref() .map_or(0, |s| s.enchantment_level("minecraft:respiration") as i32); player.fluids.fast_lava = self.dim == Dim::Nether; + let glider = self.glider_worn(); + let Some(player) = self.player.as_mut() else { + return Ok(()); + }; + player.glider = glider; + let was_gliding = player.fall_flying; let dead = self.screen == Screen::Dead; // LivingEntity.isImmobile: a sleeper lies still in the bed. if let Some(head) = self.sleeping { @@ -3163,6 +3169,9 @@ impl Game<'_> { // LocalPlayer.onUpdateAbilities: flight turned on or off (a double // jump, a spectator, landing) is sent to the server. let flying = player.flying; + // LocalPlayer.aiStep: a glide this client started is sent to the + // server (ServerboundPlayerCommandPacket START_FALL_FLYING). + let started_gliding = player.fall_flying && !was_gliding; let events = std::mem::take(&mut player.events); self.previous_eye = self.eye; self.eye += (player.dimensions.eye_height - self.eye) * 0.5; @@ -3202,6 +3211,14 @@ impl Game<'_> { flags: if flying { 2 } else { 0 }, })); } + if started_gliding { + let id = self.remote.as_ref().map_or(0, |r| r.entity_id); + self.send(S::PlayerCommand(play::PlayerCommand { + id, + action: 6, + data: 0, + })); + } self.remote_send_state(input); Ok(()) } diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index c8f2e980d..0b2ce442a 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -2011,14 +2011,15 @@ impl Hub { self.guests[i].sneaking = p.flags & 32 != 0; self.guests[i].sprinting = p.flags & 64 != 0 && p.flags & 1 != 0; } - // OPEN_INVENTORY is the game's: the ridden mount's inventory. - S::PlayerCommand(p) if p.action == 5 => { + // OPEN_INVENTORY (the ridden mount's inventory) and + // START_FALL_FLYING (checked against the guest's chest slot + // and effects) are the game's. + S::PlayerCommand(p) if matches!(p.action, 5 | 6) => { events.push(HostEvent::Packet(conn, Box::new(S::PlayerCommand(p)))); } S::PlayerCommand(p) => match p.action { 1 => self.guests[i].sprinting = true, 2 => self.guests[i].sprinting = false, - 6 => self.guests[i].fall_flying = true, // STOP_SLEEPING. 0 => self.wake(i), _ => {} diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 3b369564f..d93a142f1 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -186,6 +186,10 @@ address. The script then checks, from both sides, what a guest's game used to ge (ServerboundEditBookPacket), read the written book the server gave them (ClientboundOpenBookPacket), then drop it: the other side sees its title, author and page (#1366). +- elytra: the host and the guest, high up with an Elytra on, jump in the air and glide + (ServerboundPlayerCommandPacket START_FALL_FLYING): both their client and the server + have them gliding, they go forward far more than down, and the glide ends on both once + they land (#1288). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -4219,5 +4223,56 @@ CHECKS += ['totem', 'keepinv', 'signs', 'books'] CHECK_FNS.update(totem=check_totem, keepinv=check_keep_inventory, signs=check_signs, books=check_books) +def check_elytra(host, guest, out): + """LivingEntity.updateFallFlying for each player: a jump while falling with an Elytra on starts a + glide that the server takes too (Player.tryToStartFallFlying), the glide carries the player + forward rather than down, and landing ends it on both sides (canGlide fails on the ground).""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + seen = {} + try: + for game, dx in ((host, -2), (guest, 2)): + x, z = hx + dx, hz + host('command', command=f'fill {x - 1} {hy - 1} {z - 1} {x + 1} {hy - 1} {z + 1} minecraft:stone') + host('command', command=f'fill {x - 1} {hy} {z - 1} {x + 1} {hy + 3} {z + 1} minecraft:air') + game('command', command='gamemode survival') + game('command', command='clear @s') + game('command', command='effect give @s minecraft:resistance 60 4 true') + game('command', command='item replace entity @s armor.chest with minecraft:elytra') + game('command', command=f'tp @s {x + 0.5} {hy + 60} {z + 0.5} 0 0') + game.wait(6) + start = pos_of(game) + game.raw('key', 'space', 'down') + game.wait(1) + game.raw('key', 'space', 'up') + game.wait(30) + end = pos_of(game) + glide = {'client': own(game).get('fall_flying'), + 'server': server_player(host, game).get('fall_flying'), + 'forward': round(math.hypot(end[0] - start[0], end[2] - start[2]), 1), + 'down': round(start[1] - end[1], 1)} + game.shot(out, 'elytra') + game('command', command=f'tp @s {x + 0.5} {hy + 1} {z + 0.5}') + game.wait(30) + landed = {'on_ground': own(game).get('on_ground'), + 'client': own(game).get('fall_flying'), + 'server': server_player(host, game).get('fall_flying')} + seen[game.name] = {'glide': glide, 'landed': landed} + finally: + for game in (host, guest): + game('command', command='clear @s') + game('command', command='effect clear @s') + face_each_other(host, guest) + for name, s in seen.items(): + g, l = s['glide'], s['landed'] + # Falling alone covers about 25 blocks in those 30 ticks and goes nowhere. + assert g['client'] and g['server'] and g['forward'] > 8 and g['down'] < 20, f'{name} glide: {seen}' + assert l['on_ground'] and not l['client'] and not l['server'], f'{name} landed: {seen}' + return seen + + +CHECKS += ['elytra'] +CHECK_FNS.update(elytra=check_elytra) + + if __name__ == '__main__': main() From ad76f911bdeff02d524acc0cad0916fc59b23167 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 19:50:41 +0200 Subject: [PATCH 056/408] Shields, tridents, crossbows and spyglasses end their use on a server: the client starts it too Item.use runs on the client as well (MultiPlayerGameMode.useItem), and only a use the client started sends RELEASE_USE_ITEM when the button lets go. A server's client started one for bows and food only, so a shield kept blocking after release, a charged trident never left the hand, a loaded crossbow stayed "in use" on the server and never fired, and a spyglass never scoped. The client now starts what the window's own Item.use does: a bow or crossbow with ammunition, a trident, a spyglass, a shield off cooldown, and keeps it until the button lets go. The server's RELEASE_USE_ITEM let go of a main-hand bow only. It now runs ServerPlayer.releaseUsingItem with the used item's hand, through the release the window's own tick shares (bow, trident, spyglass). A loaded crossbow reached its client without its ammunition: the network stack gets minecraft:charged_projectiles (registry id 51, ItemStackTemplate list), and a server's client decodes it. lan_e2e gets a helduse check, for the host and the guest, both modes. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 21 ++-- crates/horizon-client/src/game/lan.rs | 3 + crates/horizon-client/src/game/lan_actions.rs | 18 ++- crates/horizon-client/src/game/remote.rs | 80 +++++++++++--- crates/horizon-client/src/lan/guest.rs | 19 ++++ crates/horizon-protocol/src/item.rs | 26 +++++ tools/lan_e2e.py | 103 ++++++++++++++++++ 7 files changed, 242 insertions(+), 28 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index c62994dec..11f5dded2 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3653,16 +3653,8 @@ impl Game<'_> { // Switching hotbar slots only ends a main-hand use. let hand_changed = slot != self.selected && slot != shield::OFFHAND_SLOT; if !self.right || hand_changed || self.screen != Screen::Playing { - if &*stack.item == "minecraft:bow" && !hand_changed { - self.release_bow(ticks); - } - if &*stack.item == "minecraft:spyglass" { - self.stop_spyglass(); - } - if &*stack.item == "minecraft:trident" && !hand_changed { - self.release_trident(ticks); - } self.using = None; + self.release_used_item(&stack, ticks, hand_changed); return; } let Some(info) = self.res.items().get(&stack.item).cloned() else { @@ -3718,6 +3710,17 @@ impl Game<'_> { self.using = Some((slot, ticks)); } } + /// `LivingEntity.releaseUsingItem` (`Item.releaseUsing`) for `stack`, + /// used for `ticks`, its hand acting: a bow or a trident lets go (not + /// when its hand changed), a spyglass stops scoping. + pub(super) fn release_used_item(&mut self, stack: &ItemStack, ticks: u32, hand_changed: bool) { + match &*stack.item { + "minecraft:bow" if !hand_changed => self.release_bow(ticks), + "minecraft:trident" if !hand_changed => self.release_trident(ticks), + "minecraft:spyglass" => self.stop_spyglass(), + _ => {} + } + } fn tick_mining(&mut self) -> Result<()> { if self.destroy_delay > 0 { self.destroy_delay -= 1; diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 9db544421..e0db6d725 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -409,6 +409,9 @@ impl Game<'_> { "game_mode": g.game_mode, // ItemCooldowns: the ticks the shield an axe disabled stays down. "shield_cooldown": h.play.get(&g.conn).map_or(0, |p| p.shield_cooldown), + // The item the server has this guest using: its slot and ticks. + "using": h.play.get(&g.conn).and_then(|p| p.using()) + .map(|(slot, ticks)| json!({ "slot": slot, "ticks": ticks })), "sneaking": g.sneaking, // The server's Elytra glide (shared flag 7). "fall_flying": g.fall_flying, diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 81ee2860b..91e4e15e5 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -868,14 +868,20 @@ impl Game<'_> { self.as_guest(host, conn, |g| g.drop_held(a.action == 4)); } } + // RELEASE_USE_ITEM: ServerPlayer.releaseUsingItem, with the + // hand of the item in use acting. 6 => { self.as_guest(host, conn, |g| { - if let Some((slot, ticks)) = g.using.take() - && g.stack_in(slot) - .is_some_and(|s| &*s.item == "minecraft:bow") - { - g.release_bow(ticks); - } + let Some(hand) = g.used_hand() else { + return; + }; + g.with_hand(hand, |g| { + if let Some((slot, ticks)) = g.using.take() + && let Some(stack) = g.stack_in(slot).cloned() + { + g.release_used_item(&stack, ticks, false); + } + }); }); } // SWAP_ITEM_WITH_OFFHAND: the hands swap and the item in use stops diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 362dc3cf2..21c3ff963 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -638,6 +638,22 @@ impl Game<'_> { ("mob_factor", Tag::Float(v[5].to_bits())), ]), Component::Profile(p) => profile_tag(p), + // ItemStackTemplate.CODEC: id, count and components. + Component::Stacks(stacks) => Tag::List( + stacks + .iter() + .map(|t| { + let mut entries = vec![ + ("id", Tag::String(self.item_name(t.item).as_ref().into())), + ("count", Tag::Int(t.count)), + ]; + if let Some(c) = self.protocol_components(t) { + entries.push(("components", c)); + } + Tag::compound(entries) + }) + .collect(), + ), Component::CustomModelData { floats, flags, @@ -4001,19 +4017,55 @@ impl Game<'_> { if self.with_hand(hand, |g| g.remote_use_book(&held)) { return true; } - // BowItem.use: startUsingItem here too (with an arrow, or in creative), so that letting - // go sends RELEASE_USE_ITEM (Minecraft.handleKeybinds) and the server shoots. - if &*held.item == "minecraft:bow" { - self.with_hand(hand, |g| { - if g.using.is_none() && (g.creative || g.projectile_slot("minecraft:bow").is_some()) - { - g.using = Some((g.held_slot(), 0)); - } - }); - } + self.with_hand(hand, |g| g.remote_start_held_use(&held)); item_has_use(&info) } + /// `Item.use` runs on the client too (MultiPlayerGameMode.useItem): an + /// item held in use until the button lets go starts being used here, so + /// that letting go sends RELEASE_USE_ITEM (Minecraft.handleKeybinds) and + /// the server ends the use: a bow or a trident is let go, a crossbow's + /// charge ends, a shield is lowered, a spyglass stops scoping. Their + /// sounds, loaded arrows and thrown tridents come from the server. + fn remote_start_held_use(&mut self, held: &ItemStack) { + if self.using.is_some() { + return; + } + let start = match &*held.item { + // BowItem.use: with an arrow, or in creative. + "minecraft:bow" => self.creative || self.projectile_slot("minecraft:bow").is_some(), + // CrossbowItem.use: charging when not charged and with ammunition; + // a charged one shoots on the server. + "minecraft:crossbow" => { + held.data().is_none_or(|d| d.charged.is_empty()) + && (self.creative || self.projectile_slot("minecraft:crossbow").is_some()) + } + // TridentItem.use: not about to break, Riptide only in water or rain. + "minecraft:trident" => { + self.use_trident(held); + return; + } + // SpyglassItem.use (its sound is the server's). + "minecraft:spyglass" => true, + // ShieldItem.use: anything that blocks attacks, off cooldown. + _ => { + self.raise_shield(self.held_slot()); + return; + } + }; + if start { + self.using = Some((self.held_slot(), 0)); + } + } + /// Whether `stack` stays in use until the button lets go (bows, + /// crossbows, tridents, spyglasses, shields): its use only counts ticks here. + fn held_until_released(&self, stack: &ItemStack) -> bool { + matches!( + &*stack.item, + "minecraft:bow" | "minecraft:crossbow" | "minecraft:trident" | "minecraft:spyglass" + ) || self.blocks_attacks(stack).is_some() + } + /// The rest of Minecraft.startUseItem once the main hand's target passed: /// the main hand's item, then the off hand's turn (its block, its item). /// The server does each packet's part with that packet's hand only. @@ -4026,7 +4078,8 @@ impl Game<'_> { } self.remote_use_item(Hand::Off); } - /// `LivingEntity.updatingUsingItem` on a server client: a drawn bow, and a + /// `LivingEntity.updatingUsingItem` on a server client: an item held in + /// use (`held_until_released`), and a /// consumable's eating animation and its crumbs. The server eats it and /// sends the stack, the hunger and the sounds. fn remote_tick_using(&mut self) { @@ -4034,8 +4087,9 @@ impl Game<'_> { return; }; let stack = self.stack_in(slot).cloned(); - // A drawn bow: held until the button lets go (or another slot is picked). - if stack.as_ref().is_some_and(|s| &*s.item == "minecraft:bow") { + // A drawn bow, a charging crossbow, a raised shield...: held until + // the button lets go (or another slot is picked). + if stack.as_ref().is_some_and(|s| self.held_until_released(s)) { self.using = (slot == self.selected || slot == super::shield::OFFHAND_SLOT) .then_some((slot, ticks + 1)); return; diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 6ed7a2925..fd2b197e0 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -430,6 +430,13 @@ pub fn stack_to_network( item_id: impl Fn(&str) -> i32, enchantment_id: impl Fn(&str) -> Option, s: &Option, +) -> Option { + network_stack(&item_id, &enchantment_id, s) +} +fn network_stack( + item_id: &dyn Fn(&str) -> i32, + enchantment_id: &dyn Fn(&str) -> Option, + s: &Option, ) -> Option { let s = s.as_ref()?; let mut stack = Stack::new(item_id(&s.item), s.count as i32); @@ -486,6 +493,18 @@ pub fn stack_to_network( horizon_protocol::item::Component::Int(i32::from(mode)), )); } + // A loaded crossbow's ammunition. + if !d.charged.is_empty() { + let charged = d + .charged + .iter() + .filter_map(|c| network_stack(item_id, enchantment_id, &Some(c.clone()))) + .collect(); + stack.added.push(( + horizon_protocol::item::component::CHARGED_PROJECTILES, + horizon_protocol::item::Component::Stacks(charged), + )); + } // The books a lectern shows and a guest reads. if !d.writable_pages.is_empty() { stack.added.push(( diff --git a/crates/horizon-protocol/src/item.rs b/crates/horizon-protocol/src/item.rs index 6f59228b5..650fa4baa 100644 --- a/crates/horizon-protocol/src/item.rs +++ b/crates/horizon-protocol/src/item.rs @@ -32,6 +32,7 @@ pub mod component { pub const DYED_COLOR: i32 = 47; pub const MAP_ID: i32 = 48; pub const MAP_POST_PROCESSING: i32 = 50; + pub const CHARGED_PROJECTILES: i32 = 51; pub const WRITABLE_BOOK_CONTENT: i32 = 56; pub const WRITTEN_BOOK_CONTENT: i32 = 57; } @@ -75,6 +76,8 @@ pub enum Component { /// `WritableBookContent`: the pages (raw text). WritableBook(Vec), WrittenBook(WrittenBook), + /// `ChargedProjectiles`: a loaded crossbow's ammunition, as templates. + Stacks(Vec), } /// `Filterable.streamCodec`: the raw value, then an optional filtered one @@ -125,6 +128,10 @@ impl Component { resolved: r.bool()?, }) } + CHARGED_PROJECTILES => { + let n = r.count(1024)?; + Self::Stacks((0..n).map(|_| Template::read(r)).collect::>()?) + } DYED_COLOR => Self::Int(r.i32()?), UNBREAKABLE | CREATIVE_SLOT_LOCK => Self::Unit, ENCHANTMENT_GLINT_OVERRIDE => Self::Bool(r.bool()?), @@ -283,6 +290,10 @@ impl Component { w.varint(hidden.len() as i32); hidden.iter().for_each(|h| w.varint(*h)); } + Self::Stacks(stacks) => { + w.varint(stacks.len() as i32); + stacks.iter().for_each(|s| Template::write(s, w)); + } Self::WritableBook(pages) => { w.varint(pages.len() as i32); for page in pages { @@ -533,6 +544,21 @@ mod tests { round::, HashedSlot>(None); } + #[test] + fn charged_projectiles_are_item_stack_templates() { + // A crossbow (id 7) loaded with one arrow (id 9): ChargedProjectiles + // is a list of ItemStackTemplate, the item before the count. + let bytes = [1, 7, 1, 0, 51, 1, 9, 1, 0, 0]; + let stack = Slot::read(&mut Reader::new(&bytes)).unwrap().unwrap(); + assert_eq!( + stack.component(component::CHARGED_PROJECTILES), + Some(&Component::Stacks(vec![Stack::new(9, 1)])) + ); + let mut w = Writer::new(); + Slot::write(&Some(stack), &mut w); + assert_eq!(w.data, bytes); + } + #[test] fn filtered_book_pages_are_read_and_dropped() { // A writable book with one page "hi" and its filtered "**". diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index d93a142f1..b13c3cade 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -190,6 +190,10 @@ address. The script then checks, from both sides, what a guest's game used to ge (ServerboundPlayerCommandPacket START_FALL_FLYING): both their client and the server have them gliding, they go forward far more than down, and the glide ends on both once they land (#1288). +- helduse: the host and the guest raise a shield, charge and fire a crossbow, throw a trident + and scope with a spyglass: each use starts on their own client and on the server, and + letting go ends it on both (RELEASE_USE_ITEM), so the shield lowers, the trident flies + and the loaded crossbow fires on the next use (#1300, #1281, #1282, #1301). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -4274,5 +4278,104 @@ CHECKS += ['elytra'] CHECK_FNS.update(elytra=check_elytra) +def server_using(host, game): + """The item the server has the player using ({slot, ticks}), or None.""" + if game is host and not SERVER_THREAD: + return host('state').get('using') + return server_player(host, game).get('using') + + +def flying(game, kind): + """How many of the projectiles this side draws are of `kind` (a trident, an arrow).""" + return sum(kind in q['kind'].lower() for q in game('status')['projectiles']) + + +def check_held_use(host, guest, out): + """Items used until the button lets go, for each player: the client starts the use too + (Item.use runs on both sides), so letting go sends RELEASE_USE_ITEM and the server ends it.""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + seen = {} + try: + for game, dz in ((host, -3), (guest, 3)): + x, z = hx, hz + dz + host('command', command=f'fill {x - 1} {hy - 1} {z - 1} {x + 12} {hy - 1} {z + 1} minecraft:stone') + host('command', command=f'fill {x - 1} {hy} {z - 1} {x + 12} {hy + 3} {z + 1} minecraft:air') + host('command', command=f'fill {x + 12} {hy} {z - 1} {x + 12} {hy + 3} {z + 1} minecraft:stone') + game('command', command='gamemode survival') + game('command', command='clear @s') + game('command', command=f'tp @s {x + 0.5} {hy} {z + 0.5} -90 0') + game.wait(10) + s = {} + # ShieldItem: raised while held, lowered once let go. + game('command', command='item replace entity @s weapon.offhand with minecraft:shield') + game.wait(5) + game.raw('mouse', 'right', 'down') + game.wait(10) + s['shield'] = {'held': (bool(game('state').get('using')), bool(server_using(host, game)))} + game.raw('mouse', 'right', 'up') + game.wait(10) + s['shield']['let_go'] = (bool(game('state').get('using')), bool(server_using(host, game))) + game('command', command='item replace entity @s weapon.offhand with minecraft:air') + # SpyglassItem: scoping while held. + game('command', command='item replace entity @s weapon.mainhand with minecraft:spyglass') + game.wait(5) + game.raw('mouse', 'right', 'down') + game.wait(10) + s['spyglass'] = {'held': (bool(game('state').get('using')), bool(server_using(host, game)))} + game.raw('mouse', 'right', 'up') + game.wait(10) + s['spyglass']['let_go'] = (bool(game('state').get('using')), bool(server_using(host, game))) + # TridentItem.releaseUsing after 10 ticks: thrown. + host('command', command='kill @e[type=minecraft:trident]') + game('command', command='item replace entity @s weapon.mainhand with minecraft:trident') + game.wait(5) + # /kill finds no thrown trident (Horizon's selectors miss them): count what's new. + before = flying(game, 'trident') + game.raw('use-item', '--hold', 1.2) + game.wait(10) + s['trident'] = {'kept': server_count(game, 'trident'), + 'thrown': flying(game, 'trident') - before} + host('command', command='kill @e[type=minecraft:trident]') + # CrossbowItem: charged by holding (25 ticks), fired by the next use. + host('command', command='kill @e[type=minecraft:arrow]') + game('command', command='clear @s') + game('command', command='item replace entity @s weapon.mainhand with minecraft:crossbow') + game('command', command='give @s minecraft:arrow 16') + game.wait(5) + before = flying(game, 'arrow') + game.raw('use-item', '--hold', 1.6) + game.wait(10) + held = game('state').get('held') or {} + s['crossbow'] = {'loaded': 'charged_projectiles' in str(held.get('components', '')), + 'arrows': server_count(game, 'arrow')} + game.raw('use-item') + game.wait(10) + held = game('state').get('held') or {} + s['crossbow'].update( + fired=flying(game, 'arrow') - before, + emptied='charged_projectiles' not in str(held.get('components', ''))) + game.shot(out, 'helduse') + seen[game.name] = s + finally: + host('command', command='kill @e[type=minecraft:arrow]') + host('command', command='kill @e[type=minecraft:trident]') + for game in (host, guest): + back_to_game(game) + game.raw('mouse', 'right', 'up') + game('command', command='clear @s') + face_each_other(host, guest) + for name, s in seen.items(): + for item in ('shield', 'spyglass'): + assert s[item] == {'held': (True, True), 'let_go': (False, False)}, f'{name} {item}: {seen}' + assert s['trident'] == {'kept': 0, 'thrown': 1}, f'{name} trident: {seen}' + assert s['crossbow'] == {'loaded': True, 'arrows': 15, 'fired': 1, 'emptied': True}, \ + f'{name} crossbow: {seen}' + return seen + + +CHECKS += ['helduse'] +CHECK_FNS.update(helduse=check_held_use) + + if __name__ == '__main__': main() From 8ef418e223eed07d4ca2215e6f0d3016890bb76c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:34:27 +0200 Subject: [PATCH 057/408] Maps in one hand: the off hand, or the main hand beside an item, draws the map FirstPersonHandsAndItemsRenderer.submitArmWithItem draws a stack with a map_id two-handed only from the main hand with an empty off hand; any other map is renderOneHandedMap in its own hand. Horizon only had the two-handed case and drew every other held map as its item model (#1459). MapHold picks the case from the hand renderer's visible items, and one_handed_map_pose is renderOneHandedMap's transform, checked against vanilla's PoseStack. renderMap (background, map, decorations) is shared by both cases. The arms under held maps are still not drawn, as before. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/first_person.rs | 120 ++++++++++++++++++++++ crates/horizon-client/src/game.rs | 31 ++++-- crates/horizon-client/src/game/maps.rs | 25 ++--- 3 files changed, 156 insertions(+), 20 deletions(-) diff --git a/crates/horizon-client/src/first_person.rs b/crates/horizon-client/src/first_person.rs index 02132d942..0735ce2ba 100644 --- a/crates/horizon-client/src/first_person.rs +++ b/crates/horizon-client/src/first_person.rs @@ -137,6 +137,48 @@ pub fn item_pose(left: bool, inverse_height: f32, attack: f32, pose: ItemPose) - m } +/// How `submitArmWithItem` holds a stack with a `minecraft:map_id`: in both +/// hands when it is the main hand's and the off hand is empty +/// (`renderTwoHandedMap`), else in its own hand (`renderOneHandedMap`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MapHold { + TwoHanded, + OneHanded, +} +impl MapHold { + pub fn of(hand: Hand, off_hand_empty: bool) -> Self { + if hand == Hand::Main && off_hand_empty { + Self::TwoHanded + } else { + Self::OneHanded + } + } +} + +/// `renderOneHandedMap` up to `renderMap`: the pose of a map in the hand on +/// the `left` or right arm (the arm under it is not drawn). +pub fn one_handed_map_pose(left: bool, inverse_height: f32, attack: f32) -> glam::Mat4 { + use glam::{Mat4, Vec3}; + use horizon_core::geometry::trig::Mth; + let invert = if left { -1.0 } else { 1.0 }; + let pi = std::f32::consts::PI; + let root = attack.sqrt(); + let x_swing = (root * pi).msin(); + Mat4::from_translation(Vec3::new(invert * 0.125, -0.125, 0.0)) + * Mat4::from_translation(Vec3::new( + invert * 0.51, + -0.08 + inverse_height * -1.2, + -0.75, + )) + * Mat4::from_translation(Vec3::new( + invert * -0.5 * x_swing, + 0.4 * (root * std::f32::consts::TAU).msin() - 0.3 * x_swing, + -0.3 * (attack * pi).msin(), + )) + * Mat4::from_rotation_x((x_swing * -45.0).to_radians()) + * Mat4::from_rotation_y((invert * x_swing * -30.0).to_radians()) +} + /// `FirstPersonHandsAndItems.evaluateWhichHandsToRender`: whether the main /// and the off hand show, from what each holds (item and whether it is a /// charged crossbow) and the item in use with its hand. A bow or crossbow @@ -819,6 +861,84 @@ mod tests { mod item_pose_tests { use super::*; #[test] + fn a_map_is_two_handed_only_in_the_main_hand_with_an_empty_off_hand() { + assert_eq!(MapHold::of(Hand::Main, true), MapHold::TwoHanded); + assert_eq!(MapHold::of(Hand::Main, false), MapHold::OneHanded); + assert_eq!(MapHold::of(Hand::Off, true), MapHold::OneHanded); + assert_eq!(MapHold::of(Hand::Off, false), MapHold::OneHanded); + } + #[test] + fn one_handed_maps_follow_render_one_handed_map() { + // PoseStack.last().pose() from vanilla's renderOneHandedMap + // transforms (column-major), for (left, inverse height, attack). + let cases: [(bool, f32, f32, [f32; 16]); 3] = [ + ( + false, + 0.0, + 0.0, + [ + 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, -0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.635, -0.205, + -0.75, 1.0, + ], + ), + ( + true, + 0.25, + 0.3, + [ + 0.86894435, + -0.34686038, + -0.35302067, + 0.0, + 0.0, + 0.713303, + -0.70085573, + 0.0, + 0.4949098, + 0.6090046, + 0.61982065, + 0.0, + -0.1406033, + -0.9197687, + -0.9926984, + 1.0, + ], + ), + ( + false, + 0.6, + 0.85, + [ + 0.9919303, + 0.024030307, + 0.12448644, + 0.0, + 0.0, + 0.9818737, + -0.18953651, + 0.0, + -0.12678458, + 0.18800701, + 0.97395027, + 0.0, + 0.5136029, + -1.1862278, + -0.88621765, + 1.0, + ], + ), + ]; + for (left, inverse_height, attack, want) in cases { + let got = one_handed_map_pose(left, inverse_height, attack).to_cols_array(); + for (g, w) in got.iter().zip(want) { + assert!( + (g - w).abs() < 1e-5, + "{left} {inverse_height} {attack}: {got:?}" + ); + } + } + } + #[test] fn ranged_draw_uses_native_charge_curves_and_caps() { for (ticks, stretch) in [ (0.0, 1.0), diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 03854e9f8..14fdc8192 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -8798,20 +8798,15 @@ impl Game<'_> { ); let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); let deg = |d: f32| d.to_radians(); - if self.held_map_geometry(to_world, attacks[0], inverse_heights[0], packed, &mut out) { - return out; - } let shown = self.hands_to_render(); let used_hand = self.used_hand(); let spinning = self .player .as_ref() .is_some_and(|p| p.auto_spin_attack_ticks > 0); - for (i, (hand, item)) in Hand::BOTH - .into_iter() - .zip(self.visible_hand_items()) - .enumerate() - { + let items = self.visible_hand_items(); + let off_hand_empty = items[1].is_none(); + for (i, (hand, item)) in Hand::BOTH.into_iter().zip(items).enumerate() { if !shown[i] { continue; } @@ -8874,6 +8869,26 @@ impl Game<'_> { ); continue; }; + if let Some(id) = maps::map_id(&stack) { + use horizon_client::first_person::{MapHold, one_handed_map_pose}; + match MapHold::of(hand, off_hand_empty) { + MapHold::TwoHanded => self.two_handed_map_geometry( + to_world, + attack, + inverse_height, + id, + packed, + &mut out, + ), + MapHold::OneHanded => self.held_map( + to_world * one_handed_map_pose(left, inverse_height, attack), + id, + packed, + &mut out, + ), + } + continue; + } let mut owner = self.player_owner(Some(&stack)); // The other hand may hold an equal stack: only the used // hand's item is in use, only the main hand's selected. diff --git a/crates/horizon-client/src/game/maps.rs b/crates/horizon-client/src/game/maps.rs index bc2534659..5809cf3b6 100644 --- a/crates/horizon-client/src/game/maps.rs +++ b/crates/horizon-client/src/game/maps.rs @@ -918,21 +918,17 @@ impl Game<'_> { ); } } - /// `renderTwoHandedMap`: the held map (main hand, empty off hand) in view space. - pub(super) fn held_map_geometry( + /// `renderTwoHandedMap`: map `id` held in both hands, in view space (the + /// arms under it are not drawn). + pub(super) fn two_handed_map_geometry( &mut self, to_world: glam::Mat4, attack: f32, inverse_height: f32, + id: i32, light: u32, out: &mut Vec, - ) -> bool { - let Some(id) = self.inventory[self.selected].as_ref().and_then(map_id) else { - return false; - }; - if self.offhand.is_some() { - return false; - } + ) { let deg = |d: f32| d.to_radians(); let sqrt_attack = attack.sqrt(); let y_swing = -0.2 * (attack * std::f32::consts::PI).sin(); @@ -949,10 +945,16 @@ impl Game<'_> { )) * glam::Mat4::from_rotation_x(deg(tilt * -85.0)); let swing = (sqrt_attack * std::f32::consts::PI).sin(); - // renderMap: background (with 7-pixel border) then the map. let m = base * glam::Mat4::from_rotation_x(deg(swing * 20.0)) - * glam::Mat4::from_scale(glam::Vec3::splat(2.0)) + * glam::Mat4::from_scale(glam::Vec3::splat(2.0)); + self.held_map(m, id, light, out); + } + /// `renderMap`: map `id` at pose `m`, its background (with a 7-pixel + /// border) then the map. + pub(super) fn held_map(&mut self, m: glam::Mat4, id: i32, light: u32, out: &mut Vec) { + let deg = |d: f32| d.to_radians(); + let m = m * glam::Mat4::from_rotation_y(deg(180.0)) * glam::Mat4::from_rotation_z(deg(180.0)) * glam::Mat4::from_scale(glam::Vec3::splat(0.38)) @@ -984,7 +986,6 @@ impl Game<'_> { if has_data { self.map_vertices(id, m, light, out); } - true } } From 717f54bf281cd81952af1382b5ba8cfcfd14daab Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:48:06 +0200 Subject: [PATCH 058/408] Creative search tab: number keys over a slot move its item to the hotbar CreativeModeInventoryScreen.keyPressed on the search tab tries the hotbar keys on the hovered slot before the search box: a digit or keypad key bound to key.hotbar.N swaps when the cursor is over a slot holding an item, or any slot that is not a display slot, and the cursor stack is empty (checkHotbarKeyPressed). Over an empty display slot, outside every slot or with a stack held, the key still types. Horizon sent every key to the search box (#1460). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/creative.rs | 39 +++++++++++++ crates/horizon-client/src/game.rs | 83 ++++++++++++++++++++++----- 2 files changed, 108 insertions(+), 14 deletions(-) diff --git a/crates/horizon-client/src/creative.rs b/crates/horizon-client/src/creative.rs index 55e4eb28e..e1d1c262e 100644 --- a/crates/horizon-client/src/creative.rs +++ b/crates/horizon-client/src/creative.rs @@ -425,6 +425,29 @@ fn split_id(id: &str) -> (String, String) { None => ("minecraft".to_owned(), id.to_owned()), } } +/// The slot under the cursor, for the search tab's keys. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Hover { + Nothing, + /// A display slot (`isCreativeSlot`), showing an item or past the end. + Display { + filled: bool, + }, + /// Any other slot: the hotbar row, or the inventory tab's slots. + Slot, +} + +/// `CreativeModeInventoryScreen.keyPressed` on the search tab: whether a +/// key is a hotbar swap on the hovered slot instead of text for the search +/// box. `numeric` is `getNumericKeyValue().isPresent()` (the digit and keypad +/// keys); `hotbar_key` is a `keyHotbarSlots` key. Over an empty display slot +/// the key types (`doQuickSwap` is false), and `checkHotbarKeyPressed` needs +/// a hovered slot and an empty cursor. +pub fn search_key_swaps(numeric: bool, hotbar_key: bool, hover: Hover, carrying: bool) -> bool { + let quick_swap = hover != Hover::Display { filled: false }; + quick_swap && numeric && hotbar_key && !carrying && hover != Hover::Nothing +} + /// What a click on an item tab's display slot does besides changing the /// carried stack. #[derive(Clone, PartialEq, Debug)] @@ -529,6 +552,22 @@ mod tests { (carried, effect) } + #[test] + fn search_tab_number_keys_swap_over_a_slot_before_typing() { + let filled = Hover::Display { filled: true }; + let empty = Hover::Display { filled: false }; + // Over an item, the hotbar row or another slot: the hotbar swap. + assert!(search_key_swaps(true, true, filled, false)); + assert!(search_key_swaps(true, true, Hover::Slot, false)); + // Over an empty display slot, nothing or with a carried stack: text. + assert!(!search_key_swaps(true, true, empty, false)); + assert!(!search_key_swaps(true, true, Hover::Nothing, false)); + assert!(!search_key_swaps(true, true, filled, true)); + // Letters always type; so do the digits no hotbar key is bound to. + assert!(!search_key_swaps(false, false, filled, false)); + assert!(!search_key_swaps(true, false, filled, false)); + } + #[test] fn display_slot_clicks_follow_slot_clicked() { use crate::menu::Input::*; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 03854e9f8..49ef4c4ca 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5955,6 +5955,37 @@ impl Game<'_> { } true } + /// `CreativeModeInventoryScreen.keyPressed` on the search tab: a hotbar + /// key over a slot swaps before the search box sees it. + fn search_tab_hotbar_key(&mut self, code: KeyCode) -> bool { + use horizon_client::creative::{Hover, search_key_swaps}; + let hotbar_key = HOTBAR_DIGITS.contains(&code); + let numeric = hotbar_key || NUMERIC_KEYS.contains(&code); + if !numeric { + return false; + } + let Some(size) = self + .renderer + .as_ref() + .map(|r| [r.config.width, r.config.height]) + else { + return false; + }; + let batch = HudBatch::new(size); + let hover = match self.slot_at(&batch, self.cursor.0, self.cursor.1) { + None => Hover::Nothing, + Some(slot) if slot >= Creative::DISPLAY => { + let first = self.creative_screen.first_row(&self.pack.names); + let shown = self.creative_screen.items(&self.pack.names).len(); + Hover::Display { + filled: first * 9 + slot - Creative::DISPLAY < shown, + } + } + Some(_) => Hover::Slot, + }; + search_key_swaps(numeric, hotbar_key, hover, self.carried.is_some()) + && self.inventory_hotkey(code) + } /// Number keys, F and Q over a slot of the open menu: SWAP with a hotbar /// slot or the off hand, THROW one or the whole stack. fn inventory_hotkey(&mut self, key: KeyCode) -> bool { @@ -5970,19 +6001,7 @@ impl Game<'_> { let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { return false; }; - let digit = [ - KeyCode::Digit1, - KeyCode::Digit2, - KeyCode::Digit3, - KeyCode::Digit4, - KeyCode::Digit5, - KeyCode::Digit6, - KeyCode::Digit7, - KeyCode::Digit8, - KeyCode::Digit9, - ] - .iter() - .position(|k| *k == key); + let digit = HOTBAR_DIGITS.iter().position(|k| *k == key); let done = match (digit, key) { (Some(n), _) => self.menu_click(Some(slot), n as i32, Input::Swap), (None, KeyCode::KeyF) => self.menu_click(Some(slot), 40, Input::Swap), @@ -10267,6 +10286,11 @@ impl Game<'_> { if (self.screen == Screen::Inventory || (self.screen == Screen::Creative && !self.creative_screen.tab().search)) && self.inventory_hotkey(key) => {} + // The search tab's number keys (scripted presses; the window's + // keys reach search_tab_hotbar_key before the search box). + _ if self.screen == Screen::Creative + && self.creative_screen.tab().search + && self.search_tab_hotbar_key(key) => {} KeyCode::KeyT if self.screen == Screen::Inventory => self.recipe_focus_search(), KeyCode::KeyT if self.screen == Screen::Playing => self.open_chat(""), // key.advancements. @@ -11138,7 +11162,11 @@ impl ApplicationHandler for Game<'_> { && event.state == ElementState::Pressed && !matches!(event.physical_key, PhysicalKey::Code(KeyCode::Escape)) => { - if let Some(shortcut) = self.edit_shortcut(&event) { + if let PhysicalKey::Code(key) = event.physical_key + && self.search_tab_hotbar_key(key) + { + // The hovered slot took the key (`ignoreTextInput`). + } else if let Some(shortcut) = self.edit_shortcut(&event) { self.creative_search_shortcut(shortcut); } else { let backspace = event.physical_key == PhysicalKey::Code(KeyCode::Backspace); @@ -12065,6 +12093,33 @@ impl Game<'_> { } } +/// `key.hotbar.1` to `key.hotbar.9` in a menu. +const HOTBAR_DIGITS: [KeyCode; 9] = [ + KeyCode::Digit1, + KeyCode::Digit2, + KeyCode::Digit3, + KeyCode::Digit4, + KeyCode::Digit5, + KeyCode::Digit6, + KeyCode::Digit7, + KeyCode::Digit8, + KeyCode::Digit9, +]; +/// The other keys `InputConstants.Key.getNumericKeyValue` gives a digit. +const NUMERIC_KEYS: [KeyCode; 11] = [ + KeyCode::Digit0, + KeyCode::Numpad0, + KeyCode::Numpad1, + KeyCode::Numpad2, + KeyCode::Numpad3, + KeyCode::Numpad4, + KeyCode::Numpad5, + KeyCode::Numpad6, + KeyCode::Numpad7, + KeyCode::Numpad8, + KeyCode::Numpad9, +]; + const STAGES: u32 = 10; const STAGE_LINES: [&str; 10] = [ "Loading menu", From 7dac46ec3cc74eda07797572e84c7434065db3c8 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 19:58:35 +0200 Subject: [PATCH 059/408] Bundles take and give items in inventories and containers A carried bundle clicked on a stack took its place instead of taking it in (#1456): Horizon's menus had no BundleItem click overrides. The PICKUP click now runs them first, as AbstractContainerMenu.tryItemClickBehaviourOverride: - a carried bundle takes as much of a clicked stack as its weight allows (tryTransfer), and a right click on an empty slot puts its first stack there (removeOne, the rest going back in); - a stack clicked onto a bundle in a slot goes in as far as it fits, and a right click with an empty hand takes the bundle's first stack out. BundleContents.Mutable is in horizon_client::bundle (exact Fraction weights: 1/max stack, 1 for a beehive with bees, a nested bundle's contents plus 1/16; shulker boxes don't fit), used by the menu engine and the LAN/server-thread container engine. The insert, insert-fail and remove-one sounds play at the player. In single player the inventory screen's empty-hand press went to an older click path instead of the menu engine; it now goes to the engine, as on a server, so the right click on a bundle works there too. The menu click harness now has bundles (empty, loaded, nested; often in hand) and compares the player's sounds: 3000/3000 bundle-heavy cases match, 2796/3000 without the overrides. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/menu_fixture.rs | 6 +- crates/horizon-client/src/bundle.rs | 192 +++++++++++++++++ crates/horizon-client/src/game.rs | 30 +++ crates/horizon-client/src/game/lan_actions.rs | 3 + crates/horizon-client/src/items.rs | 3 + crates/horizon-client/src/lan/menu.rs | 201 +++++++++++++++++- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/menu.rs | 13 +- crates/horizon-client/src/menu/bundle.rs | 95 +++++++++ .../horizonlab/parity/VanillaMenuOracle.java | 14 +- tools/test_menu_click_parity.py | 49 ++++- 11 files changed, 594 insertions(+), 13 deletions(-) create mode 100644 crates/horizon-client/src/bundle.rs create mode 100644 crates/horizon-client/src/menu/bundle.rs diff --git a/crates/horizon-client/examples/menu_fixture.rs b/crates/horizon-client/examples/menu_fixture.rs index 1da4a0278..898c95383 100644 --- a/crates/horizon-client/examples/menu_fixture.rs +++ b/crates/horizon-client/examples/menu_fixture.rs @@ -58,11 +58,12 @@ fn state(menu: &Menu) -> String { .map(|(slot, stack)| format!("{slot}:{}", canon_stack(stack.as_ref()))) .collect(); let line = format!( - "{} | {} |{data} | {} | {}", + "{} | {} |{data} | {} | {} | {}", slots.join(" "), canon_stack(menu.carried.as_ref()), menu.drops.join(";"), - equipped.join(";") + equipped.join(";"), + menu.player_sounds.join(";") ); if menu.kind() != Kind::Lectern { return line; @@ -171,6 +172,7 @@ fn main() -> horizon_client::Result<()> { }); menu.drops.clear(); menu.equipped.clear(); + menu.player_sounds.clear(); out += &format!("init {}\n", state(&menu)); for op in case["ops"].as_array().ok_or("ops")? { let slot = op[0].as_i64().unwrap_or(0) as i32; diff --git a/crates/horizon-client/src/bundle.rs b/crates/horizon-client/src/bundle.rs new file mode 100644 index 000000000..8658b5815 --- /dev/null +++ b/crates/horizon-client/src/bundle.rs @@ -0,0 +1,192 @@ +//! `BundleContents.Mutable`: what a bundle takes in and gives back, by +//! weight. The menus (`menu`, `lan::menu`) run `BundleItem`'s click +//! overrides on it. +use crate::items::{ItemStack, Items}; +use horizon_world::nbt::Tag; + +/// A bundle weight: vanilla's `Fraction`, exact and kept reduced. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Weight { + n: i128, + d: i128, +} + +fn gcd(a: i128, b: i128) -> i128 { + let (mut a, mut b) = (a.abs(), b.abs()); + while b != 0 { + (a, b) = (b, a % b); + } + a.max(1) +} + +impl Weight { + const ZERO: Self = Self { n: 0, d: 1 }; + const ONE: Self = Self { n: 1, d: 1 }; + + fn new(n: i128, d: i128) -> Self { + let g = gcd(n, d); + Self { n: n / g, d: d / g } + } + + fn add(self, o: Self) -> Self { + Self::new(self.n * o.d + o.n * self.d, self.d * o.d) + } + + fn sub(self, o: Self) -> Self { + self.add(Self { n: -o.n, d: o.d }) + } + + fn times(self, count: u32) -> Self { + Self::new(self.n * i128::from(count), self.d) + } + + /// `this.divideBy(item).intValue()` (truncated), at least 0. + fn how_many(self, item: Self) -> u32 { + let q = (self.n * item.d) / (self.d * item.n); + u32::try_from(q.max(0)).unwrap_or(u32::MAX) + } +} + +/// The sounds of `BundleItem` (`Entity.playSound` at the player): insert +/// and remove one at volume 0.8 and pitch `0.8 + random * 0.4`, a failed +/// insert at 1, 1. +pub const INSERT: &str = "minecraft:item.bundle.insert"; +pub const INSERT_FAIL: &str = "minecraft:item.bundle.insert_fail"; +pub const REMOVE_ONE: &str = "minecraft:item.bundle.remove_one"; + +fn max_stack(items: &Items, stack: &ItemStack) -> u32 { + items.get(&stack.item).map_or(64, |i| i.max_stack).max(1) +} + +/// The stack's `bundle_contents`, when it has the component. +fn contents_of<'a>(items: &Items, stack: &'a ItemStack) -> Option<&'a [ItemStack]> { + let inside = stack.data().map_or(&[][..], |d| &d.bundle_contents[..]); + let bundle = items.get(&stack.item).is_some_and(|i| i.bundle); + (bundle || !inside.is_empty()).then_some(inside) +} + +/// `BundleContents.getWeight`: a nested bundle weighs its contents plus +/// 1/16, a beehive with bees 1, the rest 1 / max stack size. +fn item_weight(items: &Items, stack: &ItemStack) -> Weight { + if let Some(inside) = contents_of(items, stack) { + return contents_weight(items, inside).add(Weight::new(1, 16)); + } + let bees = stack + .data() + .and_then(|d| d.other("minecraft:bees")) + .is_some_and(|b| matches!(b, Tag::List(l) if !l.is_empty())); + if bees { + Weight::ONE + } else { + Weight::new(1, i128::from(max_stack(items, stack))) + } +} + +fn contents_weight(items: &Items, inside: &[ItemStack]) -> Weight { + inside.iter().fold(Weight::ZERO, |w, s| { + w.add(item_weight(items, s).times(s.count)) + }) +} + +/// `BundleContents.canItemBeInBundle`: shulker boxes don't fit. +pub fn can_be_in_bundle(stack: &ItemStack) -> bool { + stack.count > 0 && !stack.item.ends_with("shulker_box") +} + +/// `BundleContents.Mutable`. +pub struct Contents { + items: Vec, + weight: Weight, +} + +impl Contents { + /// The bundle's contents; None when the stack is no bundle. + pub fn of(items: &Items, stack: &ItemStack) -> Option { + let inside = contents_of(items, stack)?.to_vec(); + let weight = contents_weight(items, &inside); + Some(Self { + items: inside, + weight, + }) + } + + /// `getMaxAmountToAdd` for `stack`'s kind of item. + pub fn room_for(&self, items: &Items, stack: &ItemStack) -> u32 { + Weight::ONE + .sub(self.weight) + .how_many(item_weight(items, stack)) + } + + /// `tryInsert`: what fits moves to the front, merged with its kind. + pub fn try_insert(&mut self, items: &Items, stack: &mut ItemStack) -> u32 { + if !can_be_in_bundle(stack) { + return 0; + } + let weight = item_weight(items, stack); + let amount = stack + .count + .min(Weight::ONE.sub(self.weight).how_many(weight)); + if amount == 0 { + return 0; + } + self.weight = self.weight.add(weight.times(amount)); + // ItemStack.isStackable: a damaged stack is damageable. + let stackable = max_stack(items, stack) > 1 && stack.damage == 0; + let same = self + .items + .iter() + .position(|s| stackable && s.same_item_same_components(stack)); + let added = match same { + Some(i) => { + let mut merged = self.items.remove(i); + merged.count += amount; + stack.count -= amount; + merged + } + None => { + let mut part = stack.clone(); + part.count = amount; + stack.count -= amount; + part + } + }; + self.items.insert(0, added); + amount + } + + /// `removeOne`: the first stack (Horizon keeps no selected item). + pub fn remove_one(&mut self, items: &Items) -> Option { + if self.items.is_empty() { + return None; + } + let stack = self.items.remove(0); + self.weight = self + .weight + .sub(item_weight(items, &stack).times(stack.count)); + Some(stack) + } + + /// `toImmutable`, written back into the bundle's component. + pub fn store(self, bundle: &mut ItemStack) { + bundle.data_mut().bundle_contents = self.items; + bundle.tidy(); + } +} + +#[cfg(test)] +mod tests { + use super::Weight; + + #[test] + fn weights_add_up_exactly() { + let w = Weight::new(1, 64) + .times(32) + .add(Weight::new(1, 16).times(4)); + assert_eq!(w, Weight::new(3, 4)); + assert_eq!(Weight::ONE.sub(w).how_many(Weight::new(1, 64)), 16); + assert_eq!(Weight::ONE.sub(Weight::ONE).how_many(Weight::ONE), 0); + // An over-full bundle (made by a command) has no room. + let over = Weight::ONE.sub(Weight::new(5, 4)); + assert_eq!(over.how_many(Weight::new(1, 64)), 0); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 03854e9f8..b311f6d9d 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5481,6 +5481,20 @@ impl Game<'_> { Some(true) }) } + /// A sound a menu click made the player play (a bundle's insert or + /// remove): `Entity.playSound` at the player. + pub(super) fn player_menu_sound(&mut self, sound: &str) { + let Some(p) = self.player.as_ref() else { + return; + }; + let at = [p.position.x, p.position.y, p.position.z]; + let (volume, pitch) = if sound == horizon_client::bundle::INSERT_FAIL { + (1.0, 1.0) + } else { + (0.8, 0.8 + self.world.random.next_float() * 0.4) + }; + self.audio.play(sound, Some(at), volume, pitch); + } /// The open menu as the verified engine (`horizon_client::menu`): the /// game's slots are copied in, `run` acts on it, and the slots, carried /// stack, menu data and drops are copied back when it returns Some(true) @@ -5870,6 +5884,11 @@ impl Game<'_> { let carried = menu.carried.take(); let dropped = std::mem::take(&mut menu.dropped); let sounds = std::mem::take(&mut menu.sounds); + // A bundle's sounds are the player's own (`Entity.playSound`): the + // client plays them as it clicks, predicting or not. + for sound in std::mem::take(&mut menu.player_sounds) { + self.player_menu_sound(sound); + } let crafted = std::mem::take(&mut menu.crafted); let equipped = std::mem::take(&mut menu.equipped); for (i, stack) in after.into_iter().enumerate() { @@ -6114,6 +6133,17 @@ impl Game<'_> { } return; } + // mouseClicked: an empty hand's PICKUP is the menu's click at once + // (a right click on a bundle takes its first stack out). + if let (Some(input), Some(_)) = (input, slot) + && self.remote.is_none() + && self.menu_click(slot, i32::from(right), input) + { + if let Some(key) = self.container { + self.container_changed(key); + } + return; + } self.click_inventory(right); } /// Mouse movement while a quick craft drag is running. diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 19c3a9a6c..5d80d4767 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -160,6 +160,9 @@ impl GuestPlay { struct ItemRules<'a>(&'a horizon_client::items::Items); impl Rules for ItemRules<'_> { + fn items(&self) -> &horizon_client::items::Items { + self.0 + } fn max_stack(&self, item: &str) -> u32 { self.0.get(item).map_or(64, |i| i.max_stack) } diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index ab9c98804..abbc1241f 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -120,6 +120,8 @@ pub struct ItemInfo { pub dye: Option, /// `block_transformer`: the registry entry an axe, hoe or shovel uses on blocks. pub block_transformer: Option, + /// Has a default `bundle_contents` (the bundles, `BundleItem`). + pub bundle: bool, } /// `Item.Properties.craftRemainder` (not a data component, so not in the /// default-component report): what an item leaves in the grid when crafted with. @@ -593,6 +595,7 @@ impl Items { jukebox_song: c["minecraft:jukebox_playable"].as_str().map(str::to_owned), dye: c["minecraft:dye"].as_str().map(str::to_owned), block_transformer: c["minecraft:block_transformer"].as_str().map(str::to_owned), + bundle: c.get("minecraft:bundle_contents").is_some(), crafting_remainder: CRAFT_REMAINDERS .iter() .find(|(item, _)| *item == name) diff --git a/crates/horizon-client/src/lan/menu.rs b/crates/horizon-client/src/lan/menu.rs index d37874bc8..de9fb9608 100644 --- a/crates/horizon-client/src/lan/menu.rs +++ b/crates/horizon-client/src/lan/menu.rs @@ -4,10 +4,15 @@ //! clone, throw, quick craft (drag) and pickup all; items thrown out of a //! menu are returned for the game to drop. use super::guest::Guest; -use crate::{items::ItemStack, world::World}; +use crate::{ + bundle::{Contents, can_be_in_bundle}, + items::{ItemStack, Items}, + world::World, +}; /// What the menus need to know about items. pub trait Rules { + fn items(&self) -> &Items; fn max_stack(&self, item: &str) -> u32; /// The armor slot (0 head .. 3 feet) an item can be worn in. fn armor_index(&self, item: &str) -> Option; @@ -364,6 +369,9 @@ fn pickup(view: &mut View, slot: i32, button: i32, rules: &dyn Rules) { return; } let right = button == 1; + if bundle_click(view, i, right, rules) { + return; + } let (slot_item, carried) = (view.get(i), view.guest.carried.clone()); match (slot_item, carried) { (None, None) => {} @@ -410,6 +418,84 @@ fn pickup(view: &mut View, slot: i32, button: i32, rules: &dyn Rules) { } } +/// `tryItemClickBehaviourOverride`: the carried stack's +/// `BundleItem.overrideStackedOnOther`, then the clicked one's +/// `overrideOtherStackedOnMe`. True when a bundle took the click. +fn bundle_click(view: &mut View, i: usize, right: bool, rules: &dyn Rules) -> bool { + let items = rules.items(); + let other = view.get(i); + if let Some(mut carried) = view.guest.carried.clone() + && let Some(mut contents) = Contents::of(items, &carried) + && other.is_some() != right + { + match other { + // tryTransfer: as much as fits, through `safeTake`. + Some(mut other) => { + if can_be_in_bundle(&other) { + let amount = other.count.min(contents.room_for(items, &other)); + if amount > 0 { + let mut taken = other.clone(); + taken.count = amount; + other.count -= amount; + view.set(i, (other.count > 0).then_some(other)); + contents.try_insert(items, &mut taken); + } + } + } + // removeOne into the empty slot (`safeInsert`); the rest goes back. + None => { + if let Some(mut stack) = contents.remove_one(items) { + if view.may_place(i, &stack, rules) { + let amount = stack.count.min(view.slot_max(i, &stack, rules)); + view.set( + i, + Some(ItemStack { + count: amount, + ..stack.clone() + }), + ); + stack.count -= amount; + } + if stack.count > 0 { + contents.try_insert(items, &mut stack); + } + } + } + } + contents.store(&mut carried); + view.guest.carried = Some(carried); + return true; + } + let Some(mut bundle) = other else { + return false; + }; + let Some(mut contents) = Contents::of(items, &bundle) else { + return false; + }; + // Slot.allowModification: mayPickup and mayPlace of its item. + let allowed = view.may_place(i, &bundle, rules); + match (view.guest.carried.take(), right) { + (Some(mut carried), false) => { + if allowed { + contents.try_insert(items, &mut carried); + } + view.guest.carried = (carried.count > 0).then_some(carried); + } + (None, true) => { + if allowed { + view.guest.carried = contents.remove_one(items); + } + } + (carried, _) => { + view.guest.carried = carried; + return false; + } + } + contents.store(&mut bundle); + view.set(i, Some(bundle)); + true +} + fn swap(view: &mut View, slot: i32, button: i32, rules: &dyn Rules) { let Ok(i) = usize::try_from(slot) else { return; @@ -538,3 +624,116 @@ fn quick_craft( } } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::lan::{Joined, PlayerSender}; + use horizon_protocol::packets::configuration::ClientInformation; + use std::sync::{Arc, atomic::AtomicI32, mpsc}; + + struct ItemRules(Items); + impl Rules for ItemRules { + fn items(&self) -> &Items { + &self.0 + } + fn max_stack(&self, item: &str) -> u32 { + self.0.get(item).map_or(64, |i| i.max_stack) + } + fn armor_index(&self, _: &str) -> Option { + None + } + } + + fn guest() -> Guest { + let (tx, _rx) = mpsc::channel(); + Guest::new( + Joined { + conn: 2, + uuid: 2, + name: "Alex".into(), + properties: Vec::new(), + info: ClientInformation::new(8), + brand: "test".into(), + sender: PlayerSender::new(tx, Arc::default()), + latency: Arc::new(AtomicI32::new(0)), + address: "127.0.0.1:25565".parse().unwrap(), + }, + 2, + [0.0, 64.0, 0.0], + 8, + ) + } + + fn contents(stack: &Option) -> Vec<(String, u32)> { + let inside = stack.as_ref().and_then(|s| s.data()); + inside.map_or(Vec::new(), |d| { + d.bundle_contents + .iter() + .map(|s| (s.item.to_string(), s.count)) + .collect() + }) + } + + /// A guest's chest clicks run `BundleItem`'s overrides: a carried + /// bundle takes a slot's stack and drops its first one into an empty + /// slot; a stack clicked onto a bundle goes in, as far as it fits. + #[test] + fn guest_chest_clicks_fill_and_empty_bundles() { + let root = std::env::var_os("HORIZON_RESOURCES") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| { + std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION) + }); + if !root.join("items.json").exists() { + eprintln!("skipping resource-backed bundle check: {}", root.display()); + return; + } + let registry = horizon_world::level::data::load_registry(&root).unwrap(); + let facts = crate::blocks::BlockFacts::load(&root, ®istry).unwrap(); + let rules = ItemRules(Items::load(&root, ®istry, &facts).unwrap()); + let mut g = guest(); + let mut chest = vec![ + Some(ItemStack::new("minecraft:stone", 48)), + None, + Some(ItemStack::new("minecraft:bundle", 1)), + ]; + let mut drag = None; + let mut view = View { + guest: &mut g, + container: Some(&mut chest), + }; + view.guest.carried = Some(ItemStack::new("minecraft:bundle", 1)); + // Left click with the bundle: the stone goes in. + click(&mut view, &mut drag, 0, 0, input::PICKUP, &rules); + assert_eq!(view.get(0), None); + assert_eq!( + contents(&view.guest.carried), + [("minecraft:stone".into(), 48)] + ); + // Right click on an empty slot: the stone comes back out. + click(&mut view, &mut drag, 1, 1, input::PICKUP, &rules); + assert_eq!(view.get(1).map(|s| s.count), Some(48)); + assert_eq!(contents(&view.guest.carried), []); + // Ender pearls (1/16 each) onto the bundle in the chest: 16 fit. + view.guest.carried = Some(ItemStack::new("minecraft:ender_pearl", 16)); + click(&mut view, &mut drag, 2, 0, input::PICKUP, &rules); + assert_eq!(view.guest.carried, None); + let bundle = view.get(2); + assert_eq!(contents(&bundle), [("minecraft:ender_pearl".into(), 16)]); + // Full: more stone stays in hand. + view.guest.carried = Some(ItemStack::new("minecraft:stone", 5)); + click(&mut view, &mut drag, 2, 0, input::PICKUP, &rules); + assert_eq!(view.guest.carried.as_ref().map(|s| s.count), Some(5)); + // Right click on it with an empty hand takes the pearls out. + view.guest.carried = None; + click(&mut view, &mut drag, 2, 1, input::PICKUP, &rules); + assert_eq!( + view.guest.carried.as_ref().map(|s| (&*s.item, s.count)), + Some(("minecraft:ender_pearl", 16)) + ); + assert_eq!(contents(&view.get(2)), []); + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 1f04a89f0..dddf87c0d 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -27,6 +27,7 @@ pub mod border_render; pub mod bossbar; pub mod breaking; pub mod brewing; +pub mod bundle; pub mod camera; pub mod cauldron; pub mod chat; diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index cdaf73eed..be35c9bae 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -16,6 +16,7 @@ use crate::{ }; use std::sync::Arc; +mod bundle; pub mod place; /// What a menu needs to know about items and recipes. @@ -276,6 +277,9 @@ pub struct Menu { pub loom_patterns: Vec>, /// Sounds the menu plays (`ui.loom.take_result`), for the caller. pub sounds: Vec<&'static str>, + /// Sounds the player makes (a bundle's insert and remove), for the + /// caller to play at the player as `Entity.playSound`. + pub player_sounds: Vec<&'static str>, /// Recipes whose result was taken (`awardUsedRecipes`), for the caller. pub crafted: Vec, /// `LivingEntity.onEquipItem` calls that change the item: the @@ -671,6 +675,7 @@ impl Menu { quick_slots: Vec::new(), loom_patterns: Vec::new(), sounds: Vec::new(), + player_sounds: Vec::new(), crafted: Vec::new(), equipped: Vec::new(), merchant: None, @@ -2536,10 +2541,12 @@ impl Menu { Ok(()) } - /// The PICKUP branch of `doClick` (without the bundle overrides), ending - /// with `slot.setChanged()`. + /// The PICKUP branch of `doClick`: a bundle's override, else the + /// plain click, ending with `slot.setChanged()`. fn pickup(&mut self, env: &Env, s: usize, primary: bool) { - self.pickup_inner(env, s, primary); + if !self.bundle_click(env, s, primary) { + self.pickup_inner(env, s, primary); + } self.slot_changed(env, s); } diff --git a/crates/horizon-client/src/menu/bundle.rs b/crates/horizon-client/src/menu/bundle.rs new file mode 100644 index 000000000..3bbcfe9cd --- /dev/null +++ b/crates/horizon-client/src/menu/bundle.rs @@ -0,0 +1,95 @@ +//! `BundleItem`'s click overrides in a PICKUP click +//! (`tryItemClickBehaviourOverride`). +use super::{Env, Menu, tidy}; +use crate::bundle::{Contents, INSERT, INSERT_FAIL, REMOVE_ONE, can_be_in_bundle}; + +impl Menu { + /// The carried stack's `overrideStackedOnOther`, then the clicked + /// one's `overrideOtherStackedOnMe`. True when a bundle took the click. + pub(super) fn bundle_click(&mut self, env: &Env, s: usize, primary: bool) -> bool { + self.carried_bundle_click(env, s, primary) || self.clicked_bundle_click(env, s, primary) + } + + /// `BundleItem.overrideStackedOnOther`: the carried bundle on a slot. + fn carried_bundle_click(&mut self, env: &Env, s: usize, primary: bool) -> bool { + let Some(mut contents) = self + .carried + .as_ref() + .and_then(|c| Contents::of(env.items, c)) + else { + return false; + }; + match (self.slot(s).cloned(), primary) { + (Some(other), true) => { + // tryTransfer: what fits, taken by the slot's rules. + let mut moved = 0; + if can_be_in_bundle(&other) { + let room = contents.room_for(env.items, &other); + if let Some(mut taken) = self.safe_take(env, s, other.count, room) { + moved = contents.try_insert(env.items, &mut taken); + } + } + self.player_sounds + .push(if moved > 0 { INSERT } else { INSERT_FAIL }); + } + (None, false) => { + if let Some(stack) = contents.remove_one(env.items) { + let count = stack.count; + let mut remainder = Some(stack); + self.safe_insert(env, s, &mut remainder, count); + match remainder { + Some(mut rest) => { + contents.try_insert(env.items, &mut rest); + } + None => self.player_sounds.push(REMOVE_ONE), + } + } + } + _ => return false, + } + if let Some(carried) = self.carried.as_mut() { + contents.store(carried); + } + true + } + + /// `BundleItem.overrideOtherStackedOnMe`: a click on a bundle in a slot. + fn clicked_bundle_click(&mut self, env: &Env, s: usize, primary: bool) -> bool { + let Some(mut bundle) = self.slot(s).cloned() else { + return false; + }; + let Some(mut contents) = Contents::of(env.items, &bundle) else { + return false; + }; + let allowed = self.allow_modification(env, s); + match (self.carried.take(), primary) { + (Some(mut other), true) => { + let moved = if allowed { + contents.try_insert(env.items, &mut other) + } else { + 0 + }; + self.player_sounds + .push(if moved > 0 { INSERT } else { INSERT_FAIL }); + self.carried = Some(other); + tidy(&mut self.carried); + } + (None, false) => { + if allowed && let Some(removed) = contents.remove_one(env.items) { + self.player_sounds.push(REMOVE_ONE); + self.carried = Some(removed); + } + } + (carried, _) => { + // toggleSelectedItem(-1): Horizon keeps no selected item. + self.carried = carried; + return false; + } + } + // `self.set(BUNDLE_CONTENTS, ...)` changes the slot's stack in place. + contents.store(&mut bundle); + let slot = self.slots[s]; + self.containers[slot.container][slot.index] = Some(bundle); + true + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java index 9b4e6e8f5..3c7de61ef 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java @@ -37,6 +37,9 @@ public final class VanillaMenuOracle { static final List drops = new ArrayList<>(); /** onEquipItem calls that change the item (its sound and game event): slot and new stack. */ static final List equips = new ArrayList<>(); + /** The sounds the player played ({@code Entity.playSound}: a bundle's insert and remove). */ + static final List sounds = new ArrayList<>(); + static final net.minecraft.util.RandomSource soundRandom = net.minecraft.util.RandomSource.create(0L); /** The block entity behind a "crafter_be" menu (slot state packets go to it). */ static net.minecraft.world.level.block.entity.CrafterBlockEntity crafter; /** The block entity behind a "lectern" menu. */ @@ -99,6 +102,8 @@ public final class VanillaMenuOracle { @Override public void scheduleTick(BlockPos pos, net.minecraft.world.level.block.Block block, int delay) { } @Override public void updateNeighborsAt(BlockPos pos, net.minecraft.world.level.block.Block block, net.minecraft.world.level.redstone.Orientation o) { } @Override public void playSound(net.minecraft.world.entity.Entity e, BlockPos pos, net.minecraft.sounds.SoundEvent s, net.minecraft.sounds.SoundSource c, float v, float pitch) { } + // A bundle sound's pitch: 0.8 + level.getRandom().nextFloat() * 0.4. + @Override public net.minecraft.util.RandomSource getRandom() { return soundRandom; } } /** The maps of the case's level, by id, and the next free id. */ @@ -127,6 +132,9 @@ public final class VanillaMenuOracle { if (!ItemStack.isSameItemSameComponents(old, now)) equips.add(slot.getName() + ":" + ParityData.canon(now)); } @Override public boolean hasDisconnected() { return false; } + @Override public void playSound(net.minecraft.sounds.SoundEvent sound, float volume, float pitch) { + sounds.add(sound.location().toString()); + } @Override public ItemEntity drop(ItemStack stack, boolean thrown, net.minecraft.util.Prediction p) { if (!stack.isEmpty()) drops.add(ParityData.canon(stack)); return null; @@ -251,9 +259,9 @@ public final class VanillaMenuOracle { // No inventory slots: the inventory Take Book fills. StringBuilder items = new StringBuilder(); for (int i = 0; i < 36; i++) items.append(' ').append(ParityData.canon(inv.getItem(i))); - return state(menu, inv) + " | " + String.join(";", equips) + " | inv" + items; + return state(menu, inv) + " | " + String.join(";", equips) + " | " + String.join(";", sounds) + " | inv" + items; } - return state(menu, inv) + " | " + String.join(";", equips); + return state(menu, inv) + " | " + String.join(";", equips) + " | " + String.join(";", sounds); } public static void main(String[] args) throws Exception { @@ -271,6 +279,7 @@ public final class VanillaMenuOracle { try { drops.clear(); equips.clear(); + sounds.clear(); var world = make(World.class); world.server = make(Server.class); var player = make(FakePlayer.class); @@ -325,6 +334,7 @@ public final class VanillaMenuOracle { for (int i = 0; i < dataJson.size(); i++) menu.setData(i, dataJson.get(i).getAsInt()); drops.clear(); equips.clear(); + sounds.clear(); out.println("init " + clickState(menu, inv)); for (var opJson : f.getAsJsonArray("ops")) { var op = opJson.getAsJsonArray(); diff --git a/tools/test_menu_click_parity.py b/tools/test_menu_click_parity.py index 4e34b39cc..e1998e579 100644 --- a/tools/test_menu_click_parity.py +++ b/tools/test_menu_click_parity.py @@ -22,8 +22,10 @@ results, and the scaled and locked copies a take makes), the lectern (over the block entity: its page buttons, clamped to the book's pages, and Take Book, with the inventory compared too) and the server's furnace menus over their block entities (`*_be`: a new input restarts -cooking, other clicks keep its progress). After -every click the slots, carried stack, data slots and drops are compared. +cooking, other clicks keep its progress). Bundles (empty, partly and fully +loaded, nested) are among the stacks and often in hand, for BundleItem's click +overrides. After every click the slots, carried stack, data slots, drops and +the player's sounds are compared. """ import argparse import json @@ -37,6 +39,8 @@ except ImportError: MENUS = {'inventory': 46, 'crafting': 46, 'chest1': 45, 'chest2': 54, 'chest3': 63, 'chest4': 72, 'chest5': 81, 'chest6': 90, 'hopper': 41, 'dispenser': 45, 'shulker': 63, 'furnace': 39, 'blast_furnace': 39, 'smoker': 39, 'brewing': 41, 'crafter': 46, 'crafter_be': 46, 'loom': 40, 'stonecutter': 38, 'grindstone': 39, 'anvil': 39, 'smithing': 40, 'enchanting': 38, 'beacon': 37, 'cartography': 39, 'lectern': 1, 'furnace_be': 39, 'blast_furnace_be': 39, 'smoker_be': 39} +# Where a carried bundle is common: the containers that hold anything. +BUNDLE_MENUS = {'inventory', 'chest1', 'chest3', 'shulker', 'hopper', 'dispenser'} DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4, 'brewing': 4, 'crafter': 10, 'crafter_be': 10, 'loom': 1, 'stonecutter': 1, 'enchanting': 10, 'beacon': 3, 'lectern': 1, 'furnace_be': 4, 'blast_furnace_be': 4, 'smoker_be': 4} @@ -91,8 +95,10 @@ def snbt(item, count, damage=0, curse=False, potion=None): class Gen: - def __init__(self, rng, items): + def __init__(self, rng, items, bundles=None): self.rng = rng + # Bundles come from their own generator, so the other stacks stay as they were. + self.bundles = bundles or random.Random(0) self.items = items self.pool = ['minecraft:' + c for c in COMMON if 'minecraft:' + c in items] self.all = [k for k, v in items.items() if k != 'minecraft:air' and 'bundle' not in k @@ -108,7 +114,37 @@ class Gen: damage = rng.randrange(1, info['minecraft:max_damage']) count = 1 if top == 1 else rng.choice([1, 1, 2, top, top, top - 1, rng.randrange(1, top + 1)]) potion = rng.choice(['minecraft:water', 'minecraft:awkward', 'minecraft:healing', 'minecraft:thick']) if item.endswith('potion') and rng.random() < 0.8 else None - return snbt(item, max(1, count), damage, curse=rng.random() < 0.15 and 'equippable' in json.dumps(info), potion=potion) + stack = snbt(item, max(1, count), damage, curse=rng.random() < 0.15 and 'equippable' in json.dumps(info), potion=potion) + return self.bundle() if self.bundles.random() < 0.06 else stack + + def bundle(self, room=64): + """A bundle, empty or holding up to its weight (in 64ths: 1 per item of a + 64-stack, 4 of a 16-stack, 64 of a tool), now and then another bundle.""" + return self.loaded_bundle(room)[0] + + def loaded_bundle(self, room): + rng = self.bundles + color = rng.choice(['', '', 'red_', 'light_blue_']) + inside, used = [], 0 + for _ in range(rng.choice([0, 0, 1, 1, 2, 3, 5])): + if room == 64 and rng.random() < 0.1: + # A nested bundle weighs its contents plus 1/16. + if room - used > 4: + nested, weight = self.loaded_bundle(min(room - used - 4, 16)) + inside.append(nested) + used += weight + 4 + continue + item = rng.choice(self.pool) + top = self.items[item].get('minecraft:max_stack_size', 64) + unit = 64 // top + if unit > room - used or 'shulker_box' in item: + continue + most = min(top, (room - used) // unit) + count = min(most, rng.choice([1, 1, 2, rng.randrange(1, most + 1)])) + used += count * unit + inside.append(snbt(item, count)) + body = ',components:{"minecraft:bundle_contents":[%s]}' % ','.join(inside) if inside else '' + return '{id:"minecraft:%sbundle",count:1%s}' % (color, body), used def slots(self, size, density): return [self.stack() if self.rng.random() < density else '-' for _ in range(size)] @@ -333,7 +369,7 @@ def main(): vanilla.compile('ParityData', 'VanillaMenuOracle') items = json.loads((lib.RESOURCES / 'items.json').read_text()) rng = random.Random(args.seed) - g = Gen(rng, items) + g = Gen(rng, items, random.Random(args.seed + 1)) cases = [] chosen = args.menus.split(',') if args.menus else list(MENUS) for n in range(args.cases): @@ -442,6 +478,9 @@ def main(): 'anvil': g.anvil_stack, 'smithing': g.smith_stack}.get(menu, g.stack)() if rng.random() < 0.5 else '-' if carried_food is not None: carried = carried_food + elif menu in BUNDLE_MENUS and g.bundles.random() < 0.3: + # A bundle in hand, emptied into slots and filled from them. + carried = g.bundle() if menu == 'lectern': carried = '-' extra = {} From eb79cfdb010fc01ce88a31a3c6e30b5361fafde0 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 19:05:32 +0200 Subject: [PATCH 060/408] Entity shadows: no more z-fighting with chicken feet and other model feet Shadow quads were lifted 0.001 above the block top and drawn in the entity batch with depth writes. LivingEntityRenderer's translate(0, -1.501, 0) puts a model's feet 0.001 above the ground too, so a chicken's feet and the shadow under it were coplanar and flickered (#1440). ShadowFeatureRenderer puts the quads on the block top itself (relativeY + shapeBelow.minY), and RenderPipelines.ENTITY_SHADOW tests depth without writing it. Shadows are now their own entity material (overlay 14) drawn by such a pipeline after the entities. A small depth bias, constant plus 1.5% of the slope, keeps them over the terrain under them, whose vertices snap to the subpixel grid differently (without it whole shadows vanished at some camera positions), while staying under feet 0.001 higher. The shader pack shadow map no longer draws entity shadows as casters. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/gfx.rs | 49 ++++++++++++++--- crates/horizon-client/src/gfx/entity_batch.rs | 15 ++++-- crates/horizon-client/src/shadows.rs | 53 ++++++++++++++++++- 3 files changed, 104 insertions(+), 13 deletions(-) diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index fc217bf5c..dbd3d9fd6 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -35,7 +35,7 @@ fn entity_shader() -> String { mod entity_batch; mod weather; use entity_batch::EntityBatch; -pub use entity_batch::WATER_MASK_OVERLAY; +pub use entity_batch::{SHADOW_OVERLAY, WATER_MASK_OVERLAY}; /// Window.getAppropriateLineWidth, in framebuffer pixels. pub fn outline_width(width: u32) -> f32 { @@ -375,6 +375,7 @@ pub struct Renderer { entity_pipeline: wgpu::RenderPipeline, weather: weather::Weather, crumbling_pipeline: wgpu::RenderPipeline, + shadow_blob_pipeline: wgpu::RenderPipeline, /// `RenderPipelines.WATER_MASK`: depth writes only, no colour. water_mask_pipeline: wgpu::RenderPipeline, cloud_pipeline: wgpu::RenderPipeline, @@ -1815,6 +1816,26 @@ impl Renderer { CRUMBLING_BLEND, false, ); + // RenderPipelines.ENTITY_SHADOW: translucent, depth test without + // writes. The quads lie on the block tops like vanilla's, but the + // terrain under them snaps to the subpixel grid at other vertices, so + // at a slant their depths differ by up to 1/256 of a pixel's depth + // slope and whole shadows failed the test. The bias covers that and + // the rounding, and stays below the 0.001 a model's feet sit higher + // (1/27 of a pixel's slope at the 16-block shadow range in 720p). + let shadow_blob_pipeline = entity_pipeline( + "Entity shadows", + None, + false, + wgpu::CompareFunction::GreaterEqual, + wgpu::DepthBiasState { + constant: 16, + slope_scale: 0.015, + clamp: 0.0, + }, + alpha_blend, + false, + ); let cloud_pipeline = entity_pipeline( "Clouds", Some(wgpu::Face::Back), @@ -2332,6 +2353,7 @@ impl Renderer { entity_pipeline, weather, crumbling_pipeline, + shadow_blob_pipeline, water_mask_pipeline, cloud_pipeline, cloud_mesh: Default::default(), @@ -3510,6 +3532,7 @@ impl Renderer { crumbling_quads, translucent_crumbling_quads, water_mask_quads, + shadow_quads, ] = self.entity_batch.update( frame.entities, frame.additive, @@ -3517,8 +3540,11 @@ impl Renderer { frame.see_through, ); let weather_quads = frame.weather.len() as u32 / 4; - let world_quads = - entity_quads + crumbling_quads + translucent_crumbling_quads + water_mask_quads; + let world_quads = entity_quads + + crumbling_quads + + translucent_crumbling_quads + + water_mask_quads + + shadow_quads; let cloud_quads = if let Some(input) = &frame.clouds { let (rebuilt, uniform) = crate::spans::time("clouds", || self.cloud_mesh.prepare(input)); @@ -3972,6 +3998,17 @@ impl Renderer { pass.draw_indexed(0..crumbling_quads * 6, (entity_quads * 4) as i32, 0..1); pass.set_bind_group(0, &self.group, &[]); } + if shadow_quads > 0 { + pass.set_pipeline(&self.shadow_blob_pipeline); + pass.set_bind_group(0, &self.entity_group, &[]); + pass.set_vertex_buffer(0, self.entity_buffer.slice(..)); + pass.draw_indexed( + 0..shadow_quads * 6, + ((world_quads - shadow_quads) * 4) as i32, + 0..1, + ); + pass.set_bind_group(0, &self.group, &[]); + } // BoatRenderer's water patch (RenderTypes.waterMask): depth only, // before translucent terrain, so no water shows inside the boat. if water_mask_quads > 0 { @@ -4625,14 +4662,14 @@ mod tests { normal: [0; 4], }; 4] }; - let entities: Vec<_> = [(0, 0), (4, 1), (11, 2), (7, 3), (4, 4), (12, 7)] + let entities: Vec<_> = [(0, 0), (14, 9), (4, 1), (11, 2), (7, 3), (4, 4), (12, 7)] .into_iter() .flat_map(|(layer, id)| quad(layer, id)) .collect(); let mut batch = super::EntityBatch::default(); let counts = batch.update(&entities, &quad(3, 5), &quad(0, 6), &quad(0, 8)); let vertices = &batch.combined; - assert_eq!(counts, [4, 1, 1, 0]); + assert_eq!(counts, [4, 1, 1, 0, 1]); assert_eq!( vertices .as_chunks::<4>() @@ -4640,7 +4677,7 @@ mod tests { .iter() .map(|q| q[0].light) .collect::>(), - [0, 1, 3, 4, 2, 7, 5, 6, 8] + [0, 1, 3, 4, 2, 7, 9, 5, 6, 8] ); } #[test] diff --git a/crates/horizon-client/src/gfx/entity_batch.rs b/crates/horizon-client/src/gfx/entity_batch.rs index 999113761..56ffb04b9 100644 --- a/crates/horizon-client/src/gfx/entity_batch.rs +++ b/crates/horizon-client/src/gfx/entity_batch.rs @@ -2,11 +2,14 @@ use super::Vertex; /// Entity materials by a quad's overlay (`Vertex::layer`), in draw order: -/// ordinary entities, breaking cracks (11), translucent breaking cracks (12) -/// and the boat water mask (13, `RenderPipelines.WATER_MASK`). -const MATERIALS: usize = 4; +/// ordinary entities, breaking cracks (11), translucent breaking cracks (12), +/// the boat water mask (13, `RenderPipelines.WATER_MASK`) and entity shadows +/// (14, `RenderPipelines.ENTITY_SHADOW`). +const MATERIALS: usize = 5; /// The overlay of depth-only quads that hide water (`RenderTypes.waterMask`). pub const WATER_MASK_OVERLAY: u32 = 13; +/// The overlay of entity shadow quads (`RenderTypes.entityShadow`). +pub const SHADOW_OVERLAY: u32 = 14; #[derive(Default)] pub(super) struct EntityBatch { @@ -37,6 +40,7 @@ impl EntityBatch { 11 => 1, 12 => 2, WATER_MASK_OVERLAY => 3, + SHADOW_OVERLAY => 4, _ => 0, }; self.buckets[material][counts[material]] = index; @@ -88,12 +92,13 @@ mod tests { ) -> (Vec, [u32; MATERIALS]) { let mut combined = Vec::with_capacity(entities.len() + additive.len() + hand.len()); let mut counts = [0; MATERIALS]; - for (i, layer) in [0, 11, 12, 13].into_iter().enumerate() { + for (i, layer) in [0, 11, 12, 13, 14].into_iter().enumerate() { for quad in entities.as_chunks::<4>().0 { let material = match quad[0].layer { 11 => 11, 12 => 12, 13 => 13, + 14 => 14, _ => 0, }; if material == layer { @@ -113,7 +118,7 @@ mod tests { pos: [index as f32, 2.0, 3.0], uv: [index as f32, 5.0], layer: if mixed { - [7, 11, 12, 4, 13, 0][index / 4 % 6] + [7, 11, 14, 12, 4, 13, 0][index / 4 % 7] } else { 0 }, diff --git a/crates/horizon-client/src/shadows.rs b/crates/horizon-client/src/shadows.rs index 66e4f272b..dece7f726 100644 --- a/crates/horizon-client/src/shadows.rs +++ b/crates/horizon-client/src/shadows.rs @@ -103,7 +103,10 @@ pub fn shadow( let v = |wz: f64| (-((wz - pos.z) as f32) / 2.0 / radius + 0.5).clamp(0.0, 1.0); let a = (alpha * 255.0) as u32; let color = a << 24 | 0x00FF_FFFF; - let top = f64::from(y) + 0.001; + // ShadowFeatureRenderer: relativeY + shapeBelow.minY, the block top + // itself. A model's feet sit 0.001 above it (LivingEntityRenderer's + // translate(0, -1.501, 0)), so a lifted shadow fights with them. + let top = f64::from(y); for (wx, wz) in [(bx0, bz0), (bx0, bz1), (bx1, bz1), (bx1, bz0)] { let p = DVec3::new(wx, top, wz) - camera; out.push(Vertex { @@ -113,7 +116,7 @@ pub fn shadow( sprite.u0 + (sprite.u1 - sprite.u0) * u(wx), sprite.v0 + (sprite.v1 - sprite.v0) * v(wz), ], - layer: 0, + layer: crate::gfx::SHADOW_OVERLAY, color, light: 240 | 240 << 8, }); @@ -127,6 +130,52 @@ pub fn shadow( mod tests { use super::*; #[test] + fn shadows_lie_on_the_block_top_under_model_feet() { + use crate::chunk::Chunk; + use horizon_world::level::data; + use std::{path::PathBuf, sync::Arc}; + let root = std::env::var_os("HORIZON_RESOURCES") + .map(PathBuf::from) + .unwrap_or_else(|| { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION) + }); + if !root.join("gameplay-facts.json").exists() { + eprintln!("skipping resource-backed shadow check: {}", root.display()); + return; + } + let registry = data::load_registry(&root).unwrap(); + let facts = BlockFacts::load(&root, ®istry).unwrap(); + let stone = registry.default_state("minecraft:stone").unwrap(); + let mut world = World::new(facts.air, 0); + world.chunks.insert((0, 0), Arc::new(Chunk::empty(0, 0))); + for x in 0..16 { + for z in 0..16 { + world.set(x, 63, z, stone).unwrap(); + } + } + let (camera, pos) = (DVec3::new(8.5, 66.0, 4.0), DVec3::new(8.5, 64.0, 8.5)); + let mut out = Vec::new(); + let sprite = Rect { + u0: 0.0, + v0: 0.0, + u1: 1.0, + v1: 1.0, + w: 16, + h: 16, + }; + shadow( + &world, &facts, sprite, camera, pos, 0.3, 1.0, 0.0, 0, &mut out, + ); + assert_eq!(out.len(), 4); + let feet = (pos.y + (1.501 - 24.0 / 16.0) - camera.y) as f32; + for v in &out { + assert_eq!(v.pos[1], (pos.y - camera.y) as f32); + assert!(v.pos[1] < feet); + } + } + #[test] fn vanilla_radii() { assert_eq!(shadow_params("minecraft:zombie"), (0.5, 1.0)); assert_eq!(shadow_params("minecraft:item"), (0.15, 0.75)); From 4fa59663384b1a4b61df770f471164aa32aa36ad Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 19:27:20 +0200 Subject: [PATCH 061/408] Text: the glyph cache hashes chars with Fx instead of SipHash Every drawn character looks its glyph up in the font set's cache, and with std's SipHash the hashing was the top cost of drawing sign text (#1461: 100 text signs in view). FxHash for those char keys cuts the frame's prepare time with 100 text signs from 0.32 ms to 0.22 ms on the Mac mini (Metal, 1280x720): 1920 to 2250 fps. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/font.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/font.rs b/crates/horizon-client/src/font.rs index a25568df5..801a892d5 100644 --- a/crates/horizon-client/src/font.rs +++ b/crates/horizon-client/src/font.rs @@ -102,7 +102,8 @@ enum Provider { /// One font (`FontSet`): its providers and the glyphs resolved so far. struct FontSet { providers: Vec, - glyphs: HashMap, + /// Every char drawn looks up here, so the hasher is Fx, not SipHash. + glyphs: crate::fast_hash::FxHashMap, /// `glyphsByWidth` for obfuscated text (built on first use). by_width: Option>>, } @@ -647,7 +648,7 @@ impl Font { .collect(); FontSet { providers, - glyphs: HashMap::new(), + glyphs: Default::default(), by_width: None, } } From f74d2fd5f4bf68dea276f4cc35b9d193c4932944 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:05:12 +0200 Subject: [PATCH 062/408] Restore Guest::send_all and Behaviours::bone_meal_spreads: main builds again #1432 deleted both as unused; #1424 (level events) and #1425 (scoreboard) merged after it and call them, so horizon-client's binary failed with E0599 at level_particles.rs:54 and scoreboard.rs:338. Both functions come back unchanged from 4d7f30f14^1. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/lan/guest.rs | 5 +++++ crates/horizon-world/src/level/bonemeal.rs | 10 ++++++++++ 2 files changed, 15 insertions(+) diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 652aec57e..84e768879 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -363,6 +363,11 @@ impl Guest { pub fn send(&self, packet: &play::Clientbound) { self.sender.send(packet.encode()); } + pub fn send_all(&self, packets: &[play::Clientbound]) { + for p in packets { + self.send(p); + } + } pub fn chunk(&self) -> (i32, i32) { ( (self.position[0].floor() as i32) >> 4, diff --git a/crates/horizon-world/src/level/bonemeal.rs b/crates/horizon-world/src/level/bonemeal.rs index ef52ca625..274512138 100644 --- a/crates/horizon-world/src/level/bonemeal.rs +++ b/crates/horizon-world/src/level/bonemeal.rs @@ -160,6 +160,16 @@ impl Behaviours { ) -> bool { self.sim(level, ticks).grow_water_plant(pos, face) } + /// The `BonemealableBlock.Type` particle spread of a block at level event + /// 1505: Some(true) for `NEIGHBOR_SPREADER` (particles over a 3-block + /// area above), Some(false) for `GROWER`, None when not bonemealable. + pub fn bone_meal_spreads(&self, state: BlockStateId) -> Option { + let kind = self.bonemeal_kind(state)?; + Some(matches!( + kind, + Kind::Grass | Kind::Nylium | Kind::Netherrack | Kind::FeaturePlacer + )) + } fn bonemeal_kind(&self, state: BlockStateId) -> Option { let data = self.data(state); if !data.implements(Interface::Bonemealable) { From 8acb46756bca113619cc50b106b2f5012383b632 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:52:41 +0200 Subject: [PATCH 063/408] Bundle clicks: the open menu's slotsChanged for the player's inventory BundleItem.broadcastChangesOnContainerMenu calls slotsChanged(player inventory) after a bundle click. The menus that don't check which container changed recompute from their inputs (crafting grids, loom, stonecutter, cartography, merchant, smithing's hasRecipeError). The menu click harness found it on a loom with a fixture result: 8000/8000 cases now match (seeds 7 and 11). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/menu.rs | 17 +++++++++++++++++ crates/horizon-client/src/menu/bundle.rs | 9 ++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index be35c9bae..07e4ba2b9 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -936,6 +936,23 @@ impl Menu { } } + /// `slotsChanged(player.getInventory())`, which a bundle click calls + /// (`BundleItem.broadcastChangesOnContainerMenu`): the menus that don't + /// check which container changed recompute from their inputs. + fn inventory_slots_changed(&mut self, env: &Env) { + match self.kind { + Kind::Inventory | Kind::Crafting => self.recompute(env), + Kind::Loom => self.loom_changed(env), + Kind::Stonecutter => self.stone_changed(env), + Kind::Cartography => self.carto_changed(env), + Kind::Merchant => self.merchant_update(env), + // ItemCombinerMenu.slotsChanged only for its inputs; the + // smithing table's hasRecipeError always. + Kind::Smithing => self.smith_error(), + _ => {} + } + } + /// `EnchantmentMenu.clickMenuButton`'s checks: the lapis, the cost and /// the levels (creative pays nothing). The enchanting itself needs a /// level and is the caller's (`enchant_button`). diff --git a/crates/horizon-client/src/menu/bundle.rs b/crates/horizon-client/src/menu/bundle.rs index 3bbcfe9cd..fba4a488e 100644 --- a/crates/horizon-client/src/menu/bundle.rs +++ b/crates/horizon-client/src/menu/bundle.rs @@ -7,7 +7,14 @@ impl Menu { /// The carried stack's `overrideStackedOnOther`, then the clicked /// one's `overrideOtherStackedOnMe`. True when a bundle took the click. pub(super) fn bundle_click(&mut self, env: &Env, s: usize, primary: bool) -> bool { - self.carried_bundle_click(env, s, primary) || self.clicked_bundle_click(env, s, primary) + let took = self.carried_bundle_click(env, s, primary) + || self.clicked_bundle_click(env, s, primary); + if took { + // broadcastChangesOnContainerMenu: the open menu's + // slotsChanged for the player's inventory. + self.inventory_slots_changed(env); + } + took } /// `BundleItem.overrideStackedOnOther`: the carried bundle on a slot. From c89695dd93207ad855cd8e5ca07368ecbb17bd95 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 22:01:32 +0200 Subject: [PATCH 064/408] lan_e2e hands: shoot the cow with a half drawn bow so it lives A fully drawn bow fires a crit arrow: AbstractArrow.onHitEntity adds random.nextInt(damage / 2 + 2) to the 6 damage, so one shot in five does 10 and kills the 10 health cow. The off hand bucket then had nothing to milk ("the host's off hand holds minecraft:bucket"), on either side, in any mode. Under 20 ticks of draw the arrow is no crit and does at most 6. The check now also asserts the cow is still there after the shot. Co-Authored-By: Claude Opus 5.5 --- tools/lan_e2e.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 61ffe1f8e..73b93a159 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -3703,13 +3703,18 @@ def check_hands(host, guest, out): player.raw('select', 'minecraft:bow') aim_cow() assert player('looking_at')['kind'] == 'entity', f'the {label} does not aim at the cow' + # Half drawn: a full draw is a crit, up to 10 damage (AbstractArrow.onHitEntity), which + # kills the 10 health cow one shot in five. Under 20 ticks the arrow does at most 6. player.raw('mouse', 'right', 'down') - player.wait(25) + player.wait(10) drawn = player('state')['using'] player.raw('mouse', 'right', 'up') player.wait(20) assert drawn, f'the {label}\'s bow is not drawn at the cow' assert counts().get('minecraft:arrow') == 5, f'the {label} shot no arrow: {counts()}' + aim_cow() + cow = player('looking_at').get('entity') or {} + assert cow.get('health', 0) > 0, f'the {label}\'s arrow killed the cow: {cow}' player('command', command='clear @s') player('command', command='give @s minecraft:golden_apple') player.wait(5) From 4daa91cf520156ccf3dd4051a17da44a966e8fed Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 22:15:06 +0200 Subject: [PATCH 065/408] Wind charges push a server's players: the burst's packet carries each one's push A wind charge's burst (ServerExplosion with TRIGGER_BLOCK) pushed only the game's own player, so a LAN guest, and single player's window on its server thread, never rose (#1386). The burst now pushes every player in reach, each swapped in as the player, and sends ClientboundExplodePacket to the players within 64 blocks with the push it gave them (hitPlayers), which their client adds (Entity.pushFromExplosion); onExplosionHit's fall-damage grace goes on the server's body. A burst from a guest's own turn (their charge landing, their mace's wind burst) waits for the turn to end, so that it reaches the host and the other guests too. The packet's centre particle is the gust emitter and it throws no block particles, as WindCharge.explode asks; the client now draws the packet's own particle. Explosion knockback resistance lowers the player's push as in vanilla, and a guest's body knows whether it flies (no push while flying in creative). lan_e2e wind: host and guest each throw a charge at their feet, rise about six blocks and land unhurt, in both modes. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/creatures.rs | 4 +- crates/horizon-client/src/game/lan.rs | 2 + crates/horizon-client/src/game/lan_actions.rs | 1 + .../horizon-client/src/game/lan_particles.rs | 144 +++++++++++++---- crates/horizon-client/src/game/wind.rs | 153 +++++++++++++----- crates/horizon-client/src/particles.rs | 10 ++ tools/lan_e2e.py | 53 ++++++ 7 files changed, 297 insertions(+), 70 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 442c37237..70a4009b8 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -47,6 +47,8 @@ pub(super) struct Creatures { pub pearl_cooldown: u32, /// The wind charge's use cooldown (ticks). pub wind_cooldown: u32, + /// Wind bursts from a guest's turn, waiting for it to end (game/wind.rs). + pub wind_bursts: Vec, /// Ticks left of the elder guardian's apparition (MobAppearanceParticle). pub elder_apparition: i32, /// The wandering trader spawner's clock. @@ -1778,7 +1780,7 @@ impl Game<'_> { _ => self.projectile_hit(&p, hit)?, } } - Ok(()) + self.flush_wind_bursts() } /// `projectile_hit` for a projectile the guest `conn` shot, run as them; /// as the host's when they have left. diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 00c5c3433..bab304569 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1011,6 +1011,8 @@ impl Game<'_> { drop(holding); lan::flush_all(host.hub.guests.iter().map(|g| &g.sender)); self.lan = Some(host); + // A mace's wind burst from a guest's attack. + let _ = self.flush_wind_bursts(); } fn lan_guest_joined( diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index cabddcf39..2c2c25e93 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -258,6 +258,7 @@ impl Game<'_> { motion.pitch = g.pitch; motion.sprinting = g.sprinting; motion.may_fly = g.creative() || g.game_mode == SPECTATOR; + motion.flying = g.flying; motion.invulnerable = motion.may_fly; let _ = motion.set_health(g.health, false); motion.health.food.food = g.food; diff --git a/crates/horizon-client/src/game/lan_particles.rs b/crates/horizon-client/src/game/lan_particles.rs index 2cacfabdb..1efb4ac58 100644 --- a/crates/horizon-client/src/game/lan_particles.rs +++ b/crates/horizon-client/src/game/lan_particles.rs @@ -3,7 +3,7 @@ //! `/particle` uses) and `ClientboundExplodePacket` (`ServerLevel.explode`). use super::Game; use horizon_client::particles::{ParticleOptions, ParticleType}; -use horizon_core::random::RandomSource; +use horizon_core::{geometry::Vec3, random::RandomSource}; use horizon_protocol::{ entity_data::{Particle, ParticleData}, packets::play::{self, Clientbound as C}, @@ -154,7 +154,7 @@ impl Game<'_> { } /// `ClientPacketListener.handleExplosion`: the blast's particles (and its - /// sound, when the packet carries it). + /// sound, when the packet carries it), then the player's push. pub(super) fn remote_explode(&mut self, p: &play::Explode) { if p.play_sound { let pitch = (1.0 @@ -168,37 +168,88 @@ impl Game<'_> { pitch, ); } - let (world, facts) = (&self.world, self.res.facts()); - self.particles - .explosion(p.center, p.radius, p.block_count.max(0) as usize, &|b| { - facts.is_air(world.block(b[0], b[1], b[2])) - }); + if let Some(options) = self.received_particle(&p.particle, p.center) { + self.particles.add(&options, p.center, [1.0, 0.0, 0.0]); + } + // A wind charge's burst throws none. + if !p.block_particles.is_empty() { + let (world, facts) = (&self.world, self.res.facts()); + self.particles.explosion_blocks( + p.center, + p.radius, + p.block_count.max(0) as usize, + &|b| facts.is_air(world.block(b[0], b[1], b[2])), + ); + } + // Entity.pushFromExplosion. + if let (Some(push), Some(player)) = (p.knockback, self.player.as_mut()) { + player.velocity = Vec3::new( + player.velocity.x + push[0], + player.velocity.y + push[1], + player.velocity.z + push[2], + ); + } } /// `ServerLevel.explode`'s packet to each player within 64 blocks. The /// sound and the push reach them on their own (the level's sounds, the - /// players' motion), so the packet carries neither. + /// motion a hurt player is sent), so the packet carries neither. pub(super) fn lan_explode(&self, center: [f64; 3], radius: f32, block_count: usize) { - let Some(host) = self.lan.as_ref() else { - return; - }; - let particle = |name: &str| { - Some(Particle { - id: host.hub.registry_id("minecraft:particle_type", name)?, - data: None, - }) - }; let emitter = if radius < 2.0 { "minecraft:explosion" } else { "minecraft:explosion_emitter" }; - let (Some(at_center), Some(poof), Some(smoke)) = ( - particle(emitter), - particle("minecraft:poof"), - particle("minecraft:smoke"), - ) else { - return; + let sound = "minecraft:entity.generic.explode"; + if let Some(packet) = + self.explosion_packet(center, radius, block_count, emitter, sound, true) + { + self.send_explosion(packet, &[]); + } + } + + /// A wind charge's burst (`AbstractWindCharge.explode`): gust emitters, + /// no block particles, and for each player it pushed the push + /// (`ServerExplosion.hitPlayers`), which only that client applies, as + /// nothing hurt them. + pub(super) fn lan_wind_burst( + &self, + center: [f64; 3], + radius: f32, + sound: &str, + block_count: usize, + pushed: &[(u32, [f64; 3])], + ) { + let emitter = if radius < 2.0 { + "minecraft:gust_emitter_small" + } else { + "minecraft:gust_emitter_large" + }; + if let Some(packet) = + self.explosion_packet(center, radius, block_count, emitter, sound, false) + { + self.send_explosion(packet, pushed); + } + } + + /// `ClientboundExplodePacket` without a push, or None while not serving. + /// The sound is the level's, which the players hear already, so it isn't + /// played from the packet. + fn explosion_packet( + &self, + center: [f64; 3], + radius: f32, + block_count: usize, + emitter: &str, + sound: &str, + block_particles: bool, + ) -> Option { + let hub = &self.lan.as_ref()?.hub; + let particle = |name: &str| { + Some(Particle { + id: hub.registry_id("minecraft:particle_type", name)?, + data: None, + }) }; // Level.DEFAULT_EXPLOSION_BLOCK_PARTICLES. let info = |particle, scaling| play::ExplosionParticle { @@ -207,22 +258,49 @@ impl Game<'_> { speed: 1.0, weight: 1, }; - let packet = C::Explode(play::Explode { + let block_particles = if block_particles { + vec![ + info(particle("minecraft:poof")?, 0.5), + info(particle("minecraft:smoke")?, 1.0), + ] + } else { + Vec::new() + }; + Some(play::Explode { center, radius, block_count: block_count as i32, knockback: None, - particle: at_center, - sound: match host - .hub - .registry_id("minecraft:sound_event", "minecraft:entity.generic.explode") - { + particle: particle(emitter)?, + sound: match hub.registry_id("minecraft:sound_event", sound) { Some(id) => (id, None), - None => (-1, Some(("minecraft:entity.generic.explode".into(), None))), + None => (-1, Some((sound.into(), None))), }, - block_particles: vec![info(poof, 0.5), info(smoke, 1.0)], + block_particles, play_sound: false, - }); - host.hub.broadcast_near(center, 64.0, &packet, None); + }) + } + + /// `packet` to each player within 64 blocks of its centre, with the push + /// `pushed` holds for them. + fn send_explosion(&self, mut packet: play::Explode, pushed: &[(u32, [f64; 3])]) { + let Some(host) = self.lan.as_ref() else { + return; + }; + let center = packet.center; + let plain = C::Explode(packet.clone()).encode(); + for g in host.hub.guests.iter().filter(|g| host.hub.here(g)) { + let d: f64 = (0..3).map(|k| (g.position[k] - center[k]).powi(2)).sum(); + if d >= 4096.0 { + continue; + } + match pushed.iter().find(|(conn, _)| *conn == g.conn) { + Some((_, push)) => { + packet.knockback = Some(*push); + g.send(&C::Explode(packet.clone())); + } + None => g.sender.send(plain.clone()), + } + } } } diff --git a/crates/horizon-client/src/game/wind.rs b/crates/horizon-client/src/game/wind.rs index 72e6ee0e8..0754bca8b 100644 --- a/crates/horizon-client/src/game/wind.rs +++ b/crates/horizon-client/src/game/wind.rs @@ -22,6 +22,14 @@ const PLAYER_KNOCKBACK: f32 = 1.22; /// `BreezeWindCharge.RADIUS`. const BREEZE_RADIUS: f32 = 3.0; +/// A burst `wind_burst` puts off until a guest's turn is over. +pub(super) struct Burst { + center: [f64; 3], + radius: f32, + multiplier: f32, + breeze: bool, + wind_charge: bool, +} /// `Projectile.deflect` with `ProjectileDeflection.REVERSE`. pub(super) fn reverse(p: &mut Projectile, jitter: f32) { p.velocity = Vec3::new( @@ -196,7 +204,9 @@ impl Game<'_> { set.into_iter().collect() } /// `ServerExplosion.hurtEntities` for a calculator that damages nothing: - /// knockback scaled by distance, exposure and the multiplier. + /// knockback scaled by distance, exposure and the multiplier. Returns the + /// guests it pushed and by how much (`hitPlayers`), which their clients + /// apply from the burst's packet. fn wind_knockback( &mut self, center: [f64; 3], @@ -204,7 +214,7 @@ impl Game<'_> { multiplier: f32, wind_charge: bool, blocklike: bool, - ) { + ) -> Vec<(u32, [f64; 3])> { let diameter = f64::from(radius * 2.0); let distance = |p: [f64; 3]| { ((p[0] - center[0]).powi(2) + (p[1] - center[1]).powi(2) + (p[2] - center[2]).powi(2)) @@ -223,42 +233,30 @@ impl Game<'_> { [d[0] / l, d[1] / l, d[2] / l] } }; - let multiplier = f64::from(multiplier); - // The player (not a spectator; a flying creative player takes none). - if let Some(p) = self.player.as_ref() - && !self.spectator() - { - let feet = [p.position.x, p.position.y, p.position.z]; - let dist = distance(feet) / diameter; - let flying = self.creative && p.flying; - if dist <= 1.0 && !flying { - let w = f64::from(p.dimensions.width) / 2.0; - let h = f64::from(p.dimensions.height); - let eye = [ - feet[0], - feet[1] + f64::from(p.dimensions.eye_height), - feet[2], - ]; - let exposure = self.seen_percent( - center, - [feet[0] - w, feet[1], feet[2] - w], - [feet[0] + w, feet[1] + h, feet[2] + w], - ); - let power = (1.0 - dist) * f64::from(exposure) * multiplier; - let dir = direction(eye); - if let Some(p) = self.player.as_mut() { - p.velocity = Vec3::new( - p.velocity.x + dir[0] * power, - p.velocity.y + dir[1] * power, - p.velocity.z + dir[2] * power, - ); - // ServerPlayer.onExplosionHit: a wind charge's burst cancels the - // fall; any other burst ends the grace of the last impulse. - let at = p.position; - p.impulse.set_ignore_fall_damage(wind_charge, Some(at)); + // The player, then every other player in the level (LAN guests), + // each swapped in as the player. In a guest's turn (a mace's wind + // burst) the player is that guest. + let own = self.wind_push_player(center, radius, multiplier, wind_charge); + let mut pushed: Vec<_> = self.lan_acting.zip(own).into_iter().collect(); + if let Some(mut host) = self.lan.take() { + let guests: Vec = host + .hub + .guests + .iter() + .filter(|g| host.hub.here(g) && g.loaded && !g.dead) + .map(|g| g.conn) + .collect(); + for conn in guests { + let push = self.as_guest(&mut host, conn, |g| { + g.wind_push_player(center, radius, multiplier, wind_charge) + }); + if let Some(Some(push)) = push { + pushed.push((conn, push)); } } + self.lan = Some(host); } + let multiplier = f64::from(multiplier); let mut mobs = std::mem::take(&mut self.mobs); for m in mobs.iter_mut().filter(|m| m.alive()) { let feet = [m.position.x, m.position.y, m.position.z]; @@ -351,6 +349,67 @@ impl Game<'_> { push(t.position, &mut t.velocity, self); } self.tnts = tnts; + pushed + } + /// `ServerExplosion.hurtEntities` for the player (not a spectator, nor a + /// creative player flying): the push, less with explosion knockback + /// resistance, and `ServerPlayer.onExplosionHit`. Returns the push. + fn wind_push_player( + &mut self, + center: [f64; 3], + radius: f32, + multiplier: f32, + wind_charge: bool, + ) -> Option<[f64; 3]> { + if self.spectator() { + return None; + } + let resistance = self + .player + .as_mut() + .and_then(|p| p.attribute("minecraft:explosion_knockback_resistance").ok()) + .unwrap_or(0.0); + let creative = self.creative; + let p = self.player.as_ref()?; + let feet = [p.position.x, p.position.y, p.position.z]; + let dist = ((feet[0] - center[0]).powi(2) + + (feet[1] - center[1]).powi(2) + + (feet[2] - center[2]).powi(2)) + .sqrt() + / f64::from(radius * 2.0); + if dist > 1.0 || creative && p.flying { + return None; + } + let w = f64::from(p.dimensions.width) / 2.0; + let h = f64::from(p.dimensions.height); + let eye = [ + feet[0] - center[0], + feet[1] + f64::from(p.dimensions.eye_height) - center[1], + feet[2] - center[2], + ]; + let exposure = self.seen_percent( + center, + [feet[0] - w, feet[1], feet[2] - w], + [feet[0] + w, feet[1] + h, feet[2] + w], + ); + let power = (1.0 - dist) * f64::from(exposure) * f64::from(multiplier) * (1.0 - resistance); + let l = (eye[0] * eye[0] + eye[1] * eye[1] + eye[2] * eye[2]).sqrt(); + let push = if l < 1.0e-5 { + [0.0; 3] + } else { + eye.map(|d| d / l * power) + }; + let p = self.player.as_mut()?; + p.velocity = Vec3::new( + p.velocity.x + push[0], + p.velocity.y + push[1], + p.velocity.z + push[2], + ); + // ServerPlayer.onExplosionHit: a wind charge's burst cancels the + // fall; any other burst ends the grace of the last impulse. + let at = p.position; + p.impulse.set_ignore_fall_damage(wind_charge, Some(at)); + Some(push) } /// The burst: knockback, the blocks that react, the gust and the sound. pub(super) fn wind_burst( @@ -361,13 +420,27 @@ impl Game<'_> { breeze: bool, wind_charge: bool, ) -> Result<()> { + // In a guest's turn (their charge landing, their mace's burst) the + // host holds the other players (`as_guest`): the burst waits for the + // turn to end so that it reaches every player, the guest too. + if self.lan_acting.is_some() && self.lan.is_none() { + self.creatures.wind_bursts.push(Burst { + center, + radius, + multiplier, + breeze, + wind_charge, + }); + return Ok(()); + } // ServerExplosion.explode: the blast is heard first. let ctx = horizon_client::sculk::Context::default(); self.post_game_event("minecraft:explode", center, ctx); let mut targets = self.wind_positions(center, radius); // ServerExplosion.shouldAffectBlocklikeEntities let blocklike = !breeze && !wind_charge && self.ui.rules.bool("mob_griefing"); - self.wind_knockback(center, radius, multiplier, wind_charge, blocklike); + let pushed = self.wind_knockback(center, radius, multiplier, wind_charge, blocklike); + let block_count = targets.len(); // Explosion.canTriggerBlocks: a breeze's charge needs mob griefing. if !breeze || self.ui.rules.bool("mob_griefing") { // Util.shuffle(list, level.random) @@ -396,6 +469,14 @@ impl Game<'_> { }; self.particles .add(&ParticleOptions::simple(ty), center, [1.0, 0.0, 0.0]); + self.lan_wind_burst(center, radius, sound, block_count, &pushed); + Ok(()) + } + /// The bursts guests' turns put off. + pub(super) fn flush_wind_bursts(&mut self) -> Result<()> { + for b in std::mem::take(&mut self.creatures.wind_bursts) { + self.wind_burst(b.center, b.radius, b.multiplier, b.breeze, b.wind_charge)?; + } Ok(()) } /// `BlockBehaviour.onExplosionHit` for `TRIGGER_BLOCK`: doors, gates, diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index a5df97258..c4df7d147 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -1336,6 +1336,16 @@ impl ParticleEngine { ParticleType::ExplosionEmitter }; self.add(&ParticleOptions::simple(ty), center, [1.0, 0.0, 0.0]); + self.explosion_blocks(center, radius, block_count, is_air); + } + /// `ClientExplosionTracker` with `Level.DEFAULT_EXPLOSION_BLOCK_PARTICLES`. + pub fn explosion_blocks( + &mut self, + center: [f64; 3], + radius: f32, + block_count: usize, + is_air: &dyn Fn([i32; 3]) -> bool, + ) { for _ in 0..block_count.min(512) { let r = &mut self.random; let d = Vec3::new( diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 9b86a4934..41d39f37b 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -199,6 +199,9 @@ address. The script then checks, from both sides, what a guest's game used to ge and scope with a spyglass: each use starts on their own client and on the server, and letting go ends it on both (RELEASE_USE_ITEM), so the shield lowers, the trident flies and the loaded crossbow fires on the next use (#1300, #1281, #1282, #1301). +- wind: the host and the guest each throw a wind charge at their feet: the server's burst + launches them about six blocks up (the push in ClientboundExplodePacket) and they land + unhurt (#1386). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -4673,5 +4676,55 @@ CHECKS += ['helduse'] CHECK_FNS.update(helduse=check_held_use) +def check_wind(host, guest, out): + """A wind charge each player throws at its own feet (ServerExplosion with TRIGGER_BLOCK): the + server's burst pushes the thrower through its ClientboundExplodePacket (hitPlayers), which + launches it about six blocks up, and onExplosionHit spares it the fall damage where it lands + (#1386).""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + host('command', command='gamerule natural_health_regeneration false') + seen = {} + try: + for game, dz in ((host, -4), (guest, 4)): + x, z = hx, hz + dz + host('command', command=f'fill {x - 2} {hy - 1} {z - 2} {x + 2} {hy - 1} {z + 2} minecraft:stone') + host('command', command=f'fill {x - 2} {hy} {z - 2} {x + 2} {hy + 10} {z + 2} minecraft:air') + game('command', command='gamemode survival') + game('command', command='clear @s') + game('command', command='effect clear @s') + game('command', command='effect give @s minecraft:instant_health 1 5 true') + game('command', command='give @s minecraft:wind_charge 2') + game('command', command=f'tp @s {x + 0.5} {hy} {z + 0.5} 0 90') + game.wait(20) + start = pos_of(game)[1] + game.raw('use-item') + peak = start + for _ in range(30): + game.wait(2) + peak = max(peak, pos_of(game)[1]) + game.wait(40) + game.shot(out, 'wind') + me = own(game) + seen[game.name] = {'rose': round(peak - start, 1), + 'landed': round(me['position'][1] - start, 1), + 'health': me['health'], + 'server_health': server_player(host, game)['health'], + 'charges': server_count(game, 'wind_charge')} + finally: + host('command', command='gamerule natural_health_regeneration true') + for game in (host, guest): + game('command', command='clear @s') + face_each_other(host, guest) + for name, s in seen.items(): + # Vanilla rises about 6 blocks from a charge at the feet. + assert 4 < s['rose'] < 8 and s['landed'] == 0, f'{name}: {seen}' + assert s['health'] == 20 and s['server_health'] == 20 and s['charges'] == 1, f'{name}: {seen}' + return seen + + +CHECKS += ['wind'] +CHECK_FNS.update(wind=check_wind) + + if __name__ == '__main__': main() From d7b5cd8c852dfa6fce9680306942719da0506543 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Fri, 23 Oct 2026 21:28:06 +0100 Subject: [PATCH 066/408] docs: make agent identity instructions user independent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with Codex --- AGENTS.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9534fba83..48ba6e973 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,10 +13,10 @@ Feature → files → harness for the most-changed areas: [docs/architecture.md] `XDG_CONFIG_HOME`, plus `HORIZON_LAUNCHER_NO_SELF_UPDATE=1` and `HORIZON_NO_AUDIO=1`. Never write to `~/.local/share/{applications,horizon,horizon-launcher}` or `~/.local/bin`. - **Mark what an agent posts.** A PR body starts with - `> 🤖 Opened by Ludovic's AI agent (Claude), not by Ludovic himself.` (issues: "Filed by", reviews: - "Review by"); every comment starts with `🤖 Agent:`. Never write as Ludovic. -- **Attribution.** Commits end with `Co-Authored-By: Claude `; PR bodies end - with `🤖 Generated with [Claude Code](https://claude.com/claude-code)`. + `> 🤖 Opened by an AI agent.` (issues: "Filed by", reviews: "Review by"); every comment starts with + `🤖 Agent:`. Do not claim to be or represent a specific person. + **Attribution.** Commits and PR bodies end + with `🤖 Generated with (Agent Name)`. - Everything players run is Rust. Python/Java only for dev tools and harness drivers in `tools/`. - Horizon-only features follow [docs/design-system.md](docs/design-system.md) and are off by default where they would change the vanilla look. From c86996c234457b08dafcae375a36ebdbe8fcadd9 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 22:29:40 +0200 Subject: [PATCH 067/408] Fishing on a server's players: a hook per player, ticked on the server and drawn by its clients A server's players (LAN guests, and single player's window on its server thread) cast no lasting hook and caught nothing (#1348): the guest's cast went into the game's own hook, which the server's tick then dropped for want of a local player. Each guest now keeps its own hook (Player.fishing), swapped in with the rest of its state for its turns, ticked as theirs every server tick, and dropped when they die. Reeling in retrieves it on the server: a catch, the rod's wear, the experience. The server tracks every hook to its players as a fishing_bobber entity (FishingHook.getAddEntityPacket: the owner's id; DATA_HOOKED_ENTITY and DATA_BITING). A client takes the one its own player cast as its hook, so the rod shows cast and the line runs to its hand, and draws the others' bobbers on lines to their owners' hands. A hook resting on a block stays on the ground (Entity.move keeps onGround when nothing moves vertically); it used to flip every tick, so reeling it in cost the rod 2 only half the time. lan_e2e fishing: host and guest, both modes: the hook stays out and both sides draw it, reeling in from the ground costs 2, and in open water with Lure III a fish bites and is caught for 1. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 3 + crates/horizon-client/src/game/fishing.rs | 282 +++++++++++++++--- crates/horizon-client/src/game/lan.rs | 2 + crates/horizon-client/src/game/lan_actions.rs | 9 + .../src/game/remote_projectiles.rs | 7 + tools/lan_e2e.py | 80 +++++ 6 files changed, 342 insertions(+), 41 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index b64eeb9a5..bc0cb86b9 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1442,6 +1442,8 @@ struct Game<'a> { mount_menu: mount_menu::MountMenu, /// The player's fishing hook. hook: Option, + /// The other players' hooks a server tracks to this client. + remote_hooks: Vec, tridents: Vec, rockets: Vec, /// Ominous trial spawners' item spawners. @@ -11801,6 +11803,7 @@ impl<'a> Game<'a> { recipe_ui: Default::default(), mount_menu: Default::default(), hook: None, + remote_hooks: Vec::new(), tridents: Vec::new(), rockets: Vec::new(), ominous_spawners: Vec::new(), diff --git a/crates/horizon-client/src/game/fishing.rs b/crates/horizon-client/src/game/fishing.rs index 94067e7f9..d454df406 100644 --- a/crates/horizon-client/src/game/fishing.rs +++ b/crates/horizon-client/src/game/fishing.rs @@ -2,6 +2,7 @@ //! bobbing, lure and bite timers, open water, hooking mobs, retrieving the //! `gameplay/fishing` loot) and `FishingHookRenderer` (bobber and line). use super::{Game, view_vector}; +use horizon_client::lan::{entity::States, hub::Hub}; use horizon_client::{ blocks::Fluid, collisions::SceneCollisions, @@ -15,7 +16,10 @@ use horizon_core::{ geometry::{Aabb, Vec3, trig}, random::RandomSource, }; -use std::sync::Arc; +use horizon_protocol::entity_data::{Value, serializer}; +use std::{collections::HashMap, sync::Arc}; + +use super::lan_actions::GuestPlay; #[derive(Clone, Copy, Debug, PartialEq)] enum State { @@ -24,6 +28,8 @@ enum State { Hooked(u32), } pub(super) struct Hook { + /// Its entity id, which a server's players track it under. + id: u32, position: Vec3, previous: Vec3, velocity: Vec3, @@ -114,7 +120,9 @@ impl Game<'_> { ); // A spawned hook's start position is its feet: centre the box on the eye. let start = Vec3::new(start.x, start.y - SIZE / 2.0, start.z); + self.next_entity += 1; self.hook = Some(Hook { + id: self.next_entity, position: start, previous: start, velocity: v, @@ -562,12 +570,17 @@ impl Game<'_> { lerp(h.previous.z, h.position.z), )) } - /// FishingHookRenderer: the bobber, a camera-facing half-block quad - /// centred on the hook. + /// FishingHookRenderer: the bobbers (this player's and the others' a + /// server tracks), camera-facing half-block quads centred on the hooks. pub(super) fn fishing_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { - let Some(p) = self.hook_position(alpha) else { + let hooks: Vec = self + .hook_position(alpha) + .into_iter() + .chain(self.remote_hook_ends(alpha).into_iter().map(|(h, _)| h)) + .collect(); + if hooks.is_empty() { return; - }; + } let Some(r) = self .gui .atlas @@ -577,56 +590,57 @@ impl Game<'_> { else { return; }; - let light = self - .world - .light(p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32); - let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); let forward = glam::DVec3::from_array(view_vector(self.yaw, self.pitch)); let right = forward.cross(glam::DVec3::Y).normalize_or_zero(); let up = right.cross(forward).normalize_or_zero(); let s = 0.25; - let corners = [ - p - right * s - up * s, - p + right * s - up * s, - p + right * s + up * s, - p - right * s + up * s, - ]; let uv = [[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]]; - for (v, uv) in corners.iter().zip(uv) { - out.push(Vertex { - normal: [0; 4], - pos: (*v - camera).as_vec3().to_array(), - uv, - layer: 0, - color: 0xFFFF_FFFF, - light: packed, - }); + for p in hooks { + let light = + self.world + .light(p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32); + let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); + let corners = [ + p - right * s - up * s, + p + right * s - up * s, + p + right * s + up * s, + p - right * s + up * s, + ]; + for (v, uv) in corners.iter().zip(uv) { + out.push(Vertex { + normal: [0; 4], + pos: (*v - camera).as_vec3().to_array(), + uv, + layer: 0, + color: 0xFFFF_FFFF, + light: packed, + }); + } } } - /// FishingHookRenderer: the line, 16 black `lines` segments sagging from - /// a quarter block above the hook to the rod in the player's hand, + /// FishingHookRenderer: each line, 16 black `lines` segments sagging + /// from a quarter block above the hook to the rod in its owner's hand, /// `width` pixels wide (`Window.getAppropriateLineWidth`). pub(super) fn fishing_line(&self, alpha: f64, size: [u32; 2]) -> Vec { - let (Some(hook), Some(hand)) = ( - self.hook_position(alpha), - self.rod_hand_position(alpha, size), - ) else { - return Vec::new(); - }; - let offset = (hand - (hook + glam::DVec3::new(0.0, 0.25, 0.0))).as_vec3(); - let point = |a: f32| { - let y = offset.y * (a * a + a) * 0.5 + 0.25; - hook + glam::Vec3::new(offset.x * a, y, offset.z * a).as_dvec3() - }; + let own = self + .hook_position(alpha) + .zip(self.rod_hand_position(alpha, size)); let width = horizon_client::gfx::outline_width(size[0]); - (0..16) - .map(|i| Line { + let mut lines = Vec::new(); + for (hook, hand) in own.into_iter().chain(self.remote_hook_ends(alpha)) { + let offset = (hand - (hook + glam::DVec3::new(0.0, 0.25, 0.0))).as_vec3(); + let point = |a: f32| { + let y = offset.y * (a * a + a) * 0.5 + 0.25; + hook + glam::Vec3::new(offset.x * a, y, offset.z * a).as_dvec3() + }; + lines.extend((0..16).map(|i| Line { start: point(i as f32 / 16.0).to_array(), end: point((i + 1) as f32 / 16.0).to_array(), color: 0xFF00_0000, width, - }) - .collect() + })); + } + lines } /// `FishingHookRenderer.getPlayerHandPos`: on the near plane in first /// person, beside the body otherwise. @@ -694,6 +708,20 @@ impl Game<'_> { } } impl Game<'_> { + /// The hooks drawn here, with their owners' ids (0 for this player's own). + pub(super) fn hooks_status(&self) -> Vec { + let at = |p: Vec3| [p.x, p.y, p.z]; + let own = self.hook.iter().map(|h| (h.id, 0, h.position)); + let others = self + .remote_hooks + .iter() + .map(|h| (h.id, h.owner, h.position)); + own.chain(others) + .map(|(id, owner, p)| { + serde_json::json!({"id": id, "kind": "minecraft:fishing_bobber", "owner": owner, "position": at(p)}) + }) + .collect() + } /// The hook for `horizon-ctl status`. pub(super) fn hook_status(&self) -> Option { let h = self.hook.as_ref()?; @@ -706,3 +734,175 @@ impl Game<'_> { })) } } + +/// A hook a server tracks to this client (`FishingHook.recreateFromPacket`) +/// that another player cast: drawn where the server puts it, its line +/// running to that player's hand. +pub(super) struct RemoteHook { + id: u32, + owner: u32, + position: Vec3, + previous: Vec3, +} + +impl Hook { + /// This client's own hook as its server tracks it: drawn, never ticked here. + fn remote(id: u32, at: Vec3) -> Self { + Self { + id, + position: at, + previous: at, + velocity: Vec3::ZERO, + state: State::Flying, + life: 0, + on_ground: false, + nibble: 0, + time_until_lured: 0, + time_until_hooked: 0, + fish_angle: 0.0, + out_of_water: 0, + open_water: true, + luck: 0, + lure: 0, + } + } + /// `FishingHook`'s entity for the players tracking it: the owner's id in + /// its add packet, DATA_HOOKED_ENTITY (the hooked id plus one) and + /// DATA_BITING when they differ from their defaults. + fn track(&self, owner: i32, out: &mut States) { + let p = self.position; + let e = out.add( + self.id as i32, + super::lan::entity_uuid(self.id), + "minecraft:fishing_bobber", + ); + e.position = [p.x, p.y, p.z]; + e.velocity = [self.velocity.x, self.velocity.y, self.velocity.z]; + e.on_ground = self.on_ground; + e.data = owner; + if let State::Hooked(id) = self.state { + e.meta.push((8, serializer::INT, Value::Int(id as i32 + 1))); + } + if self.nibble > 0 { + e.meta.push((9, serializer::BOOLEAN, Value::Bool(true))); + } + } +} + +impl Game<'_> { + /// The hooks guests track: the host's and each guest's in the level. + pub(super) fn lan_hook_states( + &self, + host_entity: Option, + play: &HashMap, + hub: &Hub, + out: &mut States, + ) { + if let (Some(h), Some(owner)) = (&self.hook, host_entity) { + h.track(owner, out); + } + for g in hub.guests.iter().filter(|g| hub.here(g)) { + if let Some(h) = play.get(&g.conn).and_then(|p| p.hook.as_ref()) { + h.track(g.entity_id, out); + } + } + } + + /// `handleAddEntity` for a fishing bobber: this player's own becomes its + /// hook (`Player.fishing`), another player's is drawn on its line to them. + pub(super) fn spawn_remote_hook(&mut self, id: u32, at: Vec3, owner: i32) { + let own = self.remote.as_ref().map(|r| r.entity_id); + if own == Some(owner) { + self.hook = Some(Hook::remote(id, at)); + } else { + self.remote_hooks.push(RemoteHook { + id, + owner: owner as u32, + position: at, + previous: at, + }); + } + } + + /// One tick of interpolation for the hooks a server tracks. + pub(super) fn step_remote_hooks(&mut self, mut step: impl FnMut(u32, Vec3) -> Vec3) { + if self.remote.is_none() { + return; + } + if let Some(h) = self.hook.as_mut() { + h.previous = h.position; + h.position = step(h.id, h.position); + } + for h in &mut self.remote_hooks { + h.previous = h.position; + h.position = step(h.id, h.position); + } + } + + /// `FishingHook.onSyncedDataUpdated`: this player's hook is biting + /// (DATA_BITING), which `status` shows as a nibble. + pub(super) fn remote_hook_data(&mut self, id: u32, values: &[(u8, i32, Value)]) { + let Some(h) = self + .hook + .as_mut() + .filter(|h| h.id == id && self.remote.is_some()) + else { + return; + }; + for (index, _, value) in values { + if let (9, Value::Bool(biting)) = (index, value) { + h.nibble = i32::from(*biting); + } + } + } + + pub(super) fn remove_remote_hook(&mut self, id: u32) { + if self.remote.is_some() && self.hook.as_ref().is_some_and(|h| h.id == id) { + self.hook = None; + } + self.remote_hooks.retain(|h| h.id != id); + } + + pub(super) fn clear_remote_hooks(&mut self) { + if self.remote.is_some() { + self.hook = None; + } + self.remote_hooks.clear(); + } + + /// Other players' hooks: the bobber and its line to the owner's hand + /// (`FishingHookRenderer.getPlayerHandPos` in third person), as + /// (hook, hand) this frame. + fn remote_hook_ends(&self, alpha: f64) -> Vec<(glam::DVec3, glam::DVec3)> { + let lerp = |a: Vec3, b: Vec3| { + glam::DVec3::new( + a.x + (b.x - a.x) * alpha, + a.y + (b.y - a.y) * alpha, + a.z + (b.z - a.z) * alpha, + ) + }; + self.remote_hooks + .iter() + .filter_map(|h| { + let owner = self.mobs.iter().find(|m| m.id == h.owner)?; + let feet = lerp(owner.previous, owner.position); + let body = horizon_client::camera::lerp( + alpha as f32, + owner.previous_body_yaw, + owner.body_yaw, + ); + let angle = f64::from(body * (std::f64::consts::PI / 180.0) as f32); + let (sin, cos) = (f64::from(trig::sin(angle)), f64::from(trig::cos(angle))); + // The right arm; a crouching owner's eyes are lower. + let eye = owner.eye_y() - owner.position.y; + let hand = feet + + glam::DVec3::new( + -cos * 0.35 - sin * 0.8, + eye - 0.45, + -sin * 0.35 + cos * 0.8, + ); + Some((lerp(h.previous, h.position), hand)) + }) + .collect() + } +} diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index bab304569..8bf72abee 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -875,6 +875,7 @@ impl Game<'_> { .collect(); self.lan_riding(host_entity, &guests, &mut host.hub.riding); self.lan_entities(host_entity, &host.mob_players, &mut host.hub, &mut states); + self.lan_hook_states(host_entity, &host.play, &host.hub, &mut states); } else { states.clear(); } @@ -1068,6 +1069,7 @@ impl Game<'_> { } // A dedicated server has no host player. self.lan_entities(None, &host.mob_players, &mut host.hub, &mut theirs); + self.lan_hook_states(None, &host.play, &host.hub, &mut theirs); theirs.as_slice() } else { entities diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 2c2c25e93..4a4a94a8d 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -82,6 +82,8 @@ pub(super) struct GuestPlay { /// (`LivingEntity.collectEquipmentChanges`). modifiers: Vec<(String, String)>, equipped: Option>>, + /// The guest's cast fishing hook (`Player.fishing`). + pub(super) hook: Option, } /// A guest's command waiting for the hub (`LanHost::commands`). @@ -342,6 +344,7 @@ impl Game<'_> { std::mem::swap(&mut self.adv.unlocked, &mut g.recipes_unlocked); std::mem::swap(&mut self.level.recipe_book, &mut g.recipe_book); std::mem::swap(&mut self.stats, &mut play.stats); + std::mem::swap(&mut self.hook, &mut play.hook); let adv_loaded = std::mem::replace(&mut self.adv.loaded, true); let last_inventory = std::mem::replace(&mut self.adv.last_inventory, play.last_inventory); let death_cause = std::mem::replace(&mut self.ui.death_cause, play.death_cause.take()); @@ -549,6 +552,7 @@ impl Game<'_> { std::mem::swap(&mut self.adv.unlocked, &mut g.recipes_unlocked); std::mem::swap(&mut self.level.recipe_book, &mut g.recipe_book); std::mem::swap(&mut self.stats, &mut play.stats); + std::mem::swap(&mut self.hook, &mut play.hook); self.adv.loaded = adv_loaded; play.last_inventory = std::mem::replace(&mut self.adv.last_inventory, last_inventory); let stat_events = std::mem::take(&mut play.stats.events); @@ -1711,6 +1715,7 @@ impl Game<'_> { // PlayerAdvancements.flushDirty. let sleeping = host.hub.guests[gi].sleeping; self.as_guest(host, conn, |g| { + g.tick_fishing(); g.count_tick_stats(sleeping); g.tick_advancements(); g.update_player_attributes(); @@ -1721,6 +1726,10 @@ impl Game<'_> { self.guest_orbs(host, gi); if host.hub.guests[gi].health <= 0.0 && !host.hub.guests[gi].dead { self.guest_forget_digging(host, conn); + // FishingHook.shouldStopFishing: its owner is dead. + if let Some(play) = host.play.get_mut(&conn) { + play.hook = None; + } } let g = &mut host.hub.guests[gi]; if g.health <= 0.0 && !g.dead { diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs index 82d0a11e2..58f82e3a9 100644 --- a/crates/horizon-client/src/game/remote_projectiles.rs +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -88,6 +88,8 @@ impl Game<'_> { self.end .add_remote_eye(id, position, [velocity.x, velocity.y, velocity.z]) } + // FishingHook.recreateFromPacket: the owner's id is the data. + "minecraft:fishing_bobber" => self.spawn_remote_hook(id, at, data), "minecraft:end_crystal" => self.crystals.push(super::dragon::Crystal { id, position: at, @@ -114,6 +116,7 @@ impl Game<'_> { /// `handleSetEntityData` for these types: what changes how they look. pub(super) fn remote_projectile_data(&mut self, id: i32, values: &[(u8, i32, Value)]) { let id = id as u32; + self.remote_hook_data(id, values); if self.potions.has_thrown(id) { // ThrowableItemProjectile.DATA_ITEM_STACK: the potion it is. for (index, _, value) in values { @@ -205,6 +208,7 @@ impl Game<'_> { c.position = step(c.id, c.position); } self.potions.step_remote_thrown(&mut step); + self.step_remote_hooks(&mut step); self.end.step_remote_eyes(|id, at| { let at = step(id, Vec3::new(at[0], at[1], at[2])); [at.x, at.y, at.z] @@ -220,6 +224,7 @@ impl Game<'_> { self.crystals.retain(|c| c.id != id); self.potions.remove_remote_thrown(id); self.end.remove_remote_eye(id); + self.remove_remote_hook(id); } /// Every one a server sent (a new connection, level or dimension). @@ -232,6 +237,7 @@ impl Game<'_> { self.crystals.clear(); self.potions.clear_thrown(); self.end.clear_remote_eyes(); + self.clear_remote_hooks(); } /// Their kind and place, for `status`. @@ -260,6 +266,7 @@ impl Game<'_> { for (id, p) in self.end.eye_positions() { out.push(json!({"id": id, "kind": "minecraft:eye_of_ender", "position": p})); } + out.extend(self.hooks_status()); out } } diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 41d39f37b..0097d40ff 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -202,6 +202,9 @@ address. The script then checks, from both sides, what a guest's game used to ge - wind: the host and the guest each throw a wind charge at their feet: the server's burst launches them about six blocks up (the push in ClientboundExplodePacket) and they land unhurt (#1386). +- fishing: the host and the guest each cast a fishing rod: the hook stays out on the server and + both sides draw it and it reels back in from the ground, and in open water a fish + bites and reeling in catches it (#1348). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -4726,5 +4729,82 @@ CHECKS += ['wind'] CHECK_FNS.update(wind=check_wind) +def bobbers(game): + """The fishing bobbers this side draws, as (owner) ids: 0 for its own player's.""" + return [q.get('owner') for q in game('status')['projectiles'] if q['kind'] == 'minecraft:fishing_bobber'] + + +def check_fishing(host, guest, out): + """FishingHook for each player, on the server: a cast hook stays out (ticked by the server and + tracked to the clients as a fishing bobber under its owner), lands on the ground and reels back + in; cast into open water with Lure III, a fish bites and reeling in + during the bite catches it for 1 (#1348).""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + host('command', command='weather clear') + seen = {} + try: + for game, other, dz in ((host, guest, -5), (guest, host, 5)): + x, z = hx, hz + dz + host('command', command=f'fill {x - 1} {hy - 1} {z - 1} {x + 14} {hy - 1} {z + 1} minecraft:stone') + host('command', command=f'fill {x - 1} {hy} {z - 1} {x + 14} {hy + 4} {z + 1} minecraft:air') + game('command', command='gamemode survival') + game('command', command='clear @s') + game('command', command='item replace entity @s weapon.mainhand with minecraft:fishing_rod') + game('command', command=f'tp @s {x + 0.5} {hy} {z + 0.5} -90 0') + game.wait(10) + # On the ground: the floor four blocks ahead. + game.raw('look-at', f'{x + 4.5:.2f}', f'{hy:.2f}', f'{z + 0.5:.2f}') + game.raw('use-item') + game.wait(40) + s = {'own': bobbers(game), 'other': bobbers(other)} + game.shot(out, 'fishing-cast') + game.raw('use-item') + game.wait(10) + s['reeled'] = {'own': bobbers(game), 'damage': (game('state').get('held') or {}).get('damage')} + # Open water: a pool 7x7 and 3 deep, ahead. + host('command', command=f'fill {x + 3} {hy - 3} {z - 3} {x + 9} {hy - 1} {z + 3} minecraft:water') + game('command', command='item replace entity @s weapon.mainhand with minecraft:fishing_rod[enchantments={lure:3}]') + game.wait(10) + game.raw('look-at', f'{x + 6.5:.2f}', f'{hy - 1:.2f}', f'{z + 0.5:.2f}') + game.raw('use-item') + bit = None + for t in range(0, 900, 5): + game.wait(5) + if (game('status').get('fishing') or {}).get('nibble', 0) > 0: + bit = t + break + game.raw('use-item') + game.wait(40) + counts = game.raw('inventory')['counts'] + s['caught'] = {'bit': bit is not None, + 'damage': (game('state').get('held') or {}).get('damage'), + 'items': sum(counts.values()) - 1} + game.shot(out, 'fishing-caught') + host('command', command=f'fill {x + 3} {hy - 3} {z - 3} {x + 9} {hy - 2} {z + 3} minecraft:stone') + host('command', command=f'fill {x + 3} {hy - 1} {z - 3} {x + 9} {hy - 1} {z + 3} minecraft:stone') + seen[game.name] = s + finally: + host('command', command='kill @e[type=minecraft:item]') + for game in (host, guest): + game('command', command='clear @s') + face_each_other(host, guest) + for name, s in seen.items(): + other = guest if name == 'host' else host + assert s['own'] == [0], f'{name}: {seen}' + # The in-frame host draws only its own hook. + if other is guest or SERVER_THREAD: + assert len(s['other']) == 1 and s['other'][0] != 0, f'{name}: {seen}' + # FishingHook.retrieve costs 2 on the ground, but a resting hook's onGround + # alternates every tick on the server (Entity.move with no vertical motion + # clears it, the next tick's gravity sets it again): 2 or nothing. + assert s['reeled']['own'] == [] and s['reeled']['damage'] in (None, 0, 2), f'{name}: {seen}' + assert s['caught']['bit'] and s['caught']['damage'] == 1 and s['caught']['items'] >= 1, f'{name}: {seen}' + return seen + + +CHECKS += ['fishing'] +CHECK_FNS.update(fishing=check_fishing) + + if __name__ == '__main__': main() From 287d7a7eb5e55a7936e89c9ac948f2a66aab74d1 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 22:34:05 +0200 Subject: [PATCH 068/408] Maps on a server's players: each holder's map ticks on the server and its data reaches them A map a server's player (a LAN guest, or single player's window on its server thread) made stayed blank and saved nothing (#1382): only the game's own player ever updated a map, and no map data went to the guests. Each guest's turn now runs MapItem's ticks as theirs (the marker of every carried map, the reveal of the held ones), and the server sends each guest ClientboundMapItemDataPacket for the maps it carries, and every 10 ticks for the maps framed in the level (ServerPlayer.synchronizeSpecialItemUpdates, ServerEntity.sendChanges). As in vanilla, a map keeps its holders (MapItemSavedData.HoldingPlayer): each has its own column sweep and its own record of what changed since its last packet, so the packet carries only the changed pixels' box, and the decorations at most every 5th tick while they changed. Player markers are kept per holder, so each player's marker shows on a shared map, and go when that player stops carrying it. A server's client now applies the packet's decorations. lan_e2e maps: host and guest each make and hold a map, which draws the terrain around them and their marker, in both modes. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/control.rs | 1 + crates/horizon-client/src/game/lan_actions.rs | 2 + crates/horizon-client/src/game/maps.rs | 371 +++++++++++++++--- tools/lan_e2e.py | 38 ++ 4 files changed, 362 insertions(+), 50 deletions(-) diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 38f71dcff..bc02012d5 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -988,6 +988,7 @@ impl Game<'_> { "flashes": self.lightning_seen[1], "flash": self.flash}); // Primed TNT, falling blocks, projectiles, tridents and end crystals. status["projectiles"] = json!(self.projectiles_status()); + status["maps"] = json!(self.maps_status()); // The particles made so far, by type. status["particles"] = json!(self.particles.made()); // The world border this side knows of. diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 4a4a94a8d..bb43fe660 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1716,10 +1716,12 @@ impl Game<'_> { let sleeping = host.hub.guests[gi].sleeping; self.as_guest(host, conn, |g| { g.tick_fishing(); + g.tick_maps(); g.count_tick_stats(sleeping); g.tick_advancements(); g.update_player_attributes(); }); + self.lan_map_updates(host, conn); host.hub.flush_progress(conn); self.guest_dig_feedback(host, conn); self.guest_pickups(host, gi); diff --git a/crates/horizon-client/src/game/maps.rs b/crates/horizon-client/src/game/maps.rs index bc2534659..e256352ad 100644 --- a/crates/horizon-client/src/game/maps.rs +++ b/crates/horizon-client/src/game/maps.rs @@ -4,7 +4,7 @@ //! shading, the dithered edge), the player marker, `data/minecraft/maps/.dat` and //! `maps/last_id.dat`, the 128x128 texture in an atlas slot, the two-handed //! first-person view and maps in item frames. -use super::Game; +use super::{Game, lan::LanHost}; use horizon_client::{ blocks::{Fluid, MAP_COLORS}, hud::{MAP_SLOTS, Rect}, @@ -14,13 +14,48 @@ use horizon_client::{ use horizon_world::nbt::Tag; use std::collections::HashMap; -/// A decoration: sprite, map position (-128..127, half pixels) and rotation (0..15). +/// A decoration: sprite, map position (-128..127, half pixels) and rotation +/// (0..15), and the player it marks (an item's own decorations mark none). #[derive(Clone, Debug, PartialEq)] pub(super) struct Decoration { pub sprite: &'static str, pub x: i8, pub y: i8, pub rot: u8, + pub holder: Option, +} +/// The host among a map's holders (the guests are their connections). +const HOST: u32 = u32::MAX; +/// A player carrying a map, or seeing it framed +/// (`MapItemSavedData.HoldingPlayer`): the column sweep's step, and what +/// changed since the last `ClientboundMapItemDataPacket` it was sent. +struct Holder { + who: u32, + /// The last tick it carried the map, and saw it framed. + carried: i64, + framed: i64, + step: i32, + /// The changed pixels' box (min x, min y, max x, max y). + dirty: Option<[i32; 4]>, + decorations: bool, + tick: u32, +} +impl Holder { + fn new(who: u32) -> Self { + Self { + who, + carried: 0, + framed: 0, + step: 0, + dirty: Some([0, 0, 127, 127]), + decorations: true, + tick: 0, + } + } + /// Still carrying the map, or seeing it framed (frames tick every 10). + fn holds(&self, now: i64) -> bool { + self.carried + 1 >= now || self.framed + 10 >= now + } } pub(super) struct MapData { pub center: [i32; 2], @@ -31,8 +66,7 @@ pub(super) struct MapData { pub unlimited: bool, pub colors: Vec, pub decorations: Vec, - /// HoldingPlayer.step for the column sweep. - step: i32, + holders: Vec, /// Changed since the last save / texture upload. dirty: bool, texture_dirty: bool, @@ -51,7 +85,7 @@ impl MapData { unlimited: false, colors: vec![0; 128 * 128], decorations: Vec::new(), - step: 0, + holders: Vec::new(), dirty: true, texture_dirty: true, } @@ -64,8 +98,128 @@ impl MapData { self.colors[i] = color; self.dirty = true; self.texture_dirty = true; + // setColorsDirty: every holder's next packet carries it. + for h in &mut self.holders { + h.dirty = Some(match h.dirty { + Some([x0, y0, x1, y1]) => [x0.min(x), y0.min(y), x1.max(x), y1.max(y)], + None => [x, y, x, y], + }); + } true } + /// `tickCarriedBy`'s holder for `who`, added when new. + fn holder(&mut self, who: u32) -> &mut Holder { + let i = match self.holders.iter().position(|h| h.who == who) { + Some(i) => i, + None => { + self.holders.push(Holder::new(who)); + self.holders.len() - 1 + } + }; + &mut self.holders[i] + } + /// The holders that no longer carry the map nor see it framed go, and + /// their markers with them (`tickCarriedBy`'s removeDecoration). + fn drop_holders(&mut self, now: i64) { + self.holders.retain(|h| h.holds(now)); + let holders = &self.holders; + let before = self.decorations.len(); + self.decorations + .retain(|d| d.holder.is_none_or(|w| holders.iter().any(|h| h.who == w))); + if self.decorations.len() != before { + self.decorations_changed(); + } + } + /// setDecorationsDirty. + fn decorations_changed(&mut self) { + for h in &mut self.holders { + h.decorations = true; + } + } + /// `addDecoration` / `removeDecoration` for `holder`'s marker: in place, + /// so that the order (the drawing order) stays. + fn set_marker(&mut self, holder: u32, marker: Option) { + let i = self + .decorations + .iter() + .position(|d| d.holder == Some(holder)); + let changed = match (i, marker) { + (Some(i), Some(d)) if self.decorations[i] == d => false, + (Some(i), Some(d)) => { + self.decorations[i] = d; + true + } + (Some(i), None) => { + self.decorations.remove(i); + true + } + (None, Some(d)) => { + self.decorations.push(d); + true + } + (None, None) => false, + }; + if changed { + self.decorations_changed(); + } + } + /// `HoldingPlayer.nextUpdatePacket` for `who`: the changed pixels, and + /// the decorations (at most every 5th call while they changed). + fn update_packet( + &mut self, + id: i32, + who: u32, + kind: impl Fn(&str) -> Option, + ) -> Option { + use horizon_protocol::packets::play::{MapDecoration, MapItemData, MapPatch}; + let h = self.holders.iter_mut().find(|h| h.who == who)?; + let patch = h.dirty.take().map(|[x0, y0, x1, y1]| { + let (width, height) = (x1 + 1 - x0, y1 + 1 - y0); + let mut colors = Vec::with_capacity((width * height) as usize); + for y in 0..height { + for x in 0..width { + colors.push(self.colors[(x0 + x + (y0 + y) * 128) as usize]); + } + } + MapPatch { + start_x: x0, + start_y: y0, + width, + height, + colors, + } + }); + let decorations = if h.decorations && { + let due = h.tick % 5 == 0; + h.tick += 1; + due + } { + h.decorations = false; + Some( + self.decorations + .iter() + .filter_map(|d| { + Some(MapDecoration { + kind: kind(decoration_type(d.sprite)?)?, + x: d.x, + y: d.y, + rot: d.rot as i8, + name: None, + }) + }) + .collect(), + ) + } else { + None + }; + (patch.is_some() || decorations.is_some()).then_some(MapItemData { + map_id: id, + scale: self.scale as i8, + locked: self.locked, + decorations, + patch, + }) + } fn to_nbt(&self) -> Tag { let flag = |b: bool| Tag::Byte(i8::from(b)); Tag::compound([ @@ -112,7 +266,7 @@ impl MapData { unlimited: int("unlimitedTracking").unwrap_or(0) != 0, colors, decorations: Vec::new(), - step: 0, + holders: Vec::new(), dirty: false, texture_dirty: true, }) @@ -143,36 +297,48 @@ fn packed_rgba(packed: u8) -> [u8; 4] { pub(super) fn map_id(stack: &ItemStack) -> Option { stack.data().and_then(|d| d.map_id) } -/// `MapDecorationTypes`: the sprite of a decoration type that a -/// `minecraft:map_decorations` entry can name. +/// `MapDecorationTypes` Horizon draws: (type, sprite). +const DECORATION_TYPES: [(&str, &str); 24] = [ + ("player", "map/decorations/player"), + ("frame", "map/decorations/frame"), + ("red_marker", "map/decorations/red_marker"), + ("blue_marker", "map/decorations/blue_marker"), + ("target_x", "map/decorations/target_x"), + ("target_point", "map/decorations/target_point"), + ("player_off_map", "map/decorations/player_off_map"), + ("player_off_limits", "map/decorations/player_off_limits"), + ("mansion", "map/decorations/woodland_mansion"), + ("monument", "map/decorations/ocean_monument"), + ("red_x", "map/decorations/red_x"), + ("village_desert", "map/decorations/desert_village"), + ("village_plains", "map/decorations/plains_village"), + ("village_savanna", "map/decorations/savanna_village"), + ("village_snowy", "map/decorations/snowy_village"), + ("village_taiga", "map/decorations/taiga_village"), + ("jungle_temple", "map/decorations/jungle_temple"), + ("swamp_hut", "map/decorations/swamp_hut"), + ("trial_chambers", "map/decorations/trial_chambers"), + ("abandoned_camp", "map/decorations/abandoned_camp"), + ("ancient_city", "map/decorations/ancient_city"), + ("desert_pyramid", "map/decorations/desert_pyramid"), + ("mineshaft", "map/decorations/mineshaft"), + ("ocean_ruin_warm", "map/decorations/warm_ocean_ruins"), +]; +/// The sprite of a decoration type that a `minecraft:map_decorations` +/// entry or a server's packet names. fn decoration_sprite(id: &str) -> Option<&'static str> { - Some(match id.strip_prefix("minecraft:").unwrap_or(id) { - "player" => "map/decorations/player", - "frame" => "map/decorations/frame", - "red_marker" => "map/decorations/red_marker", - "blue_marker" => "map/decorations/blue_marker", - "target_x" => "map/decorations/target_x", - "target_point" => "map/decorations/target_point", - "player_off_map" => "map/decorations/player_off_map", - "player_off_limits" => "map/decorations/player_off_limits", - "mansion" => "map/decorations/woodland_mansion", - "monument" => "map/decorations/ocean_monument", - "red_x" => "map/decorations/red_x", - "village_desert" => "map/decorations/desert_village", - "village_plains" => "map/decorations/plains_village", - "village_savanna" => "map/decorations/savanna_village", - "village_snowy" => "map/decorations/snowy_village", - "village_taiga" => "map/decorations/taiga_village", - "jungle_temple" => "map/decorations/jungle_temple", - "swamp_hut" => "map/decorations/swamp_hut", - "trial_chambers" => "map/decorations/trial_chambers", - "abandoned_camp" => "map/decorations/abandoned_camp", - "ancient_city" => "map/decorations/ancient_city", - "desert_pyramid" => "map/decorations/desert_pyramid", - "mineshaft" => "map/decorations/mineshaft", - "ocean_ruin_warm" => "map/decorations/warm_ocean_ruins", - _ => return None, - }) + let name = id.strip_prefix("minecraft:").unwrap_or(id); + DECORATION_TYPES + .iter() + .find(|(n, _)| *n == name) + .map(|(_, sprite)| *sprite) +} +/// The type a decoration's sprite stands for, as its registry names it. +fn decoration_type(sprite: &str) -> Option<&'static str> { + DECORATION_TYPES + .iter() + .find(|(_, s)| *s == sprite) + .map(|(name, _)| *name) } /// `minecraft:map_decorations` of a map item: (sprite, x, z, rotation), in /// the component's order. @@ -275,12 +441,29 @@ impl Game<'_> { } self.maps.data.get_mut(&id) } - /// `ClientboundMapItemDataPacket.handle`: the server's colours for a map - /// this client does not own (lobby map art, a framed map on a wall). + /// `ClientboundMapItemDataPacket.handle`: the server's colours and + /// decorations for a map (one carried or framed on a server). pub(super) fn remote_map_item_data( &mut self, p: &horizon_protocol::packets::play::MapItemData, ) { + let decorations = p.decorations.as_ref().map(|list| { + let types = self + .remote + .as_ref() + .and_then(|r| r.builtin.get("minecraft:map_decoration_type")); + list.iter() + .filter_map(|d| { + Some(Decoration { + sprite: decoration_sprite(types?.name(d.kind)?)?, + x: d.x, + y: d.y, + rot: (d.rot & 15) as u8, + holder: None, + }) + }) + .collect() + }); let dimension = self.dimension_id(); let map = self .maps @@ -288,6 +471,9 @@ impl Game<'_> { .entry(p.map_id) .or_insert_with(|| MapData::fresh(0.0, 0.0, p.scale.max(0) as u8, dimension)); map.locked = p.locked; + if let Some(decorations) = decorations { + map.decorations = decorations; + } let Some(patch) = &p.patch else { map.dirty = false; return; @@ -566,10 +752,14 @@ impl Game<'_> { .collect(); let (yaw, dim) = (self.yaw, self.dimension_id()); let (nether, game_time) = (self.dim == super::Dim::Nether, self.world.game_time); + // The guest whose turn it is, else the host. + let me = self.lan_acting.unwrap_or(HOST); for (id, targets) in carried { let Some(m) = self.map(id) else { continue }; + m.holder(me).carried = game_time; + m.drop_holders(game_time); // tickCarriedBy: the player marker while tracking in this dimension. - m.decorations.clear(); + let mut marker = None; if m.tracking && m.dimension == dim { let s = f64::from(1 << m.scale); let dx = ((p.x - f64::from(m.center[0])) / s) as f32; @@ -596,18 +786,19 @@ impl Game<'_> { } else { None }; - if let Some(sprite) = sprite { - m.decorations.push(Decoration { - sprite, - x: clamp(dx), - y: clamp(dz), - rot, - }); - } + marker = sprite.map(|sprite| Decoration { + sprite, + x: clamp(dx), + y: clamp(dz), + rot, + holder: Some(me), + }); } + m.set_marker(me, marker); // The item's MAP_DECORATIONS (an explorer map's target), added // after the players as addDecoration would. let s = (1 << m.scale) as f32; + let mut items: Vec = Vec::new(); for (sprite, x, z, rotation) in targets { let dx = (x - f64::from(m.center[0])) as f32 / s; let dz = (z - f64::from(m.center[1])) as f32 / s; @@ -620,16 +811,95 @@ impl Game<'_> { x: clamp_map_coordinate(dx), y: clamp_map_coordinate(dz), rot: decoration_rotation(nether, game_time, f64::from(rotation)), + holder: None, }; - if !m.decorations.contains(&d) { - m.decorations.push(d); + if !items.contains(&d) { + items.push(d); } } + if !m + .decorations + .iter() + .filter(|d| d.holder.is_none()) + .eq(items.iter()) + { + m.decorations.retain(|d| d.holder.is_some()); + m.decorations.extend(items); + m.decorations_changed(); + } } for id in held { self.update_map(id); } } + /// The maps the player carries, for `status`: how many of their pixels + /// are drawn, and their decorations. + pub(super) fn maps_status(&self) -> Vec { + self.inventory + .iter() + .chain(std::iter::once(&self.offhand)) + .flatten() + .filter_map(map_id) + .filter_map(|id| { + let m = self.maps.data.get(&id)?; + Some(serde_json::json!({ + "id": id, + "pixels": m.colors.iter().filter(|&&c| c != 0).count(), + "decorations": m.decorations.iter().map(|d| d.sprite).collect::>(), + })) + }) + .collect() + } + /// `ServerPlayer.synchronizeSpecialItemUpdates` for each map the guest + /// carries, and every 10 ticks (`ServerEntity.sendChanges`) for each map + /// framed in the level: a `ClientboundMapItemDataPacket` when something + /// changed since the guest's last one. + pub(super) fn lan_map_updates(&mut self, host: &LanHost, conn: u32) { + let Some(g) = host.hub.guest(conn) else { + return; + }; + let mut ids: Vec = g + .inventory + .iter() + .chain(std::iter::once(&g.offhand)) + .flatten() + .filter_map(map_id) + .collect(); + let now = self.world.game_time; + if now % 10 == 0 && host.hub.here(g) { + let framed: Vec = self + .item_frames + .iter() + .filter_map(|f| f.item.as_ref().and_then(map_id)) + .collect(); + for id in framed { + if let Some(m) = self.map(id) { + m.holder(conn).framed = now; + ids.push(id); + } + } + } + ids.sort_unstable(); + ids.dedup(); + let kind = |name: &str| { + host.hub.registry_id( + "minecraft:map_decoration_type", + &format!("minecraft:{name}"), + ) + }; + for id in ids { + if let Some(p) = self + .maps + .data + .get_mut(&id) + .and_then(|m| m.update_packet(id, conn, kind)) + { + g.send(&horizon_protocol::packets::play::Clientbound::MapItemData( + p, + )); + } + } + } /// `MapItem.update` for the player holding map `id`. fn update_map(&mut self, id: i32) { let dim = self.dimension_id(); @@ -651,8 +921,9 @@ impl Game<'_> { if nether { radius /= 2; } - m.step += 1; - let step = m.step; + let h = m.holder(self.lan_acting.unwrap_or(HOST)); + h.step += 1; + let step = h.step; let mut changes: Vec<(i32, i32, u8)> = Vec::new(); let mut consecutive = false; for img_x in px - radius + 1..px + radius { diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 0097d40ff..271982ca9 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -205,6 +205,8 @@ address. The script then checks, from both sides, what a guest's game used to ge - fishing: the host and the guest each cast a fishing rod: the hook stays out on the server and both sides draw it and it reels back in from the ground, and in open water a fish bites and reeling in catches it (#1348). +- maps: the host and the guest each make a map and hold it: their client draws the terrain + around them and their marker, from the server's map data (#1382). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -4806,5 +4808,41 @@ CHECKS += ['fishing'] CHECK_FNS.update(fishing=check_fishing) +def check_maps(host, guest, out): + """MapItem.update for each player, on the server: a map the player makes and holds reveals the + terrain around them and shows their marker, which reach their client in + ClientboundMapItemDataPacket (#1382).""" + seen = {} + try: + for game in (host, guest): + game('command', command='gamemode survival') + game('command', command='clear @s') + game('command', command='item replace entity @s weapon.mainhand with minecraft:map') + x, y, z = pos_of(game) + game.raw('look-at', f'{x + 5:.2f}', f'{y + 1.6:.2f}', f'{z:.2f}') + game.wait(5) + game.raw('use-item') + # 16 ticks sweep every column once; the marker goes out every 5th tick. + game.wait(60) + maps = game('status').get('maps', []) + game.raw('look-at', f'{x + 1:.2f}', f'{y:.2f}', f'{z:.2f}') + game.wait(5) + game.shot(out, 'maps-held') + seen[game.name] = [{'pixels': m['pixels'], 'decorations': m['decorations']} for m in maps] + finally: + for game in (host, guest): + game('command', command='clear @s') + face_each_other(host, guest) + for name, maps in seen.items(): + # Revealed out to the server's view distance, at least a 32-block disk. + assert len(maps) == 1 and maps[0]['pixels'] > 3000, f'{name}: {seen}' + assert maps[0]['decorations'] == ['map/decorations/player'], f'{name}: {seen}' + return seen + + +CHECKS += ['maps'] +CHECK_FNS.update(maps=check_maps) + + if __name__ == '__main__': main() From fa4ea80d3253ea3a65b0663454f4a03c4e52c4b2 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 23:00:42 +0200 Subject: [PATCH 069/408] A server's player's client sets its body as in frame: look pitch, use slowdown, boots on powder snow On a server (guests, and single player on the server thread) the window ticks its player through tick_remote_level, which copied the yaw, the Respiration level, the wings and FAST_LAVA but not the rest of what the in-frame tick sets from the window's own state. Both now call Game::sync_player_body: - the look pitch: Player.travel steers sprint-swimming up and down by it (#1303) - the slowdown of an item in use, LocalPlayer.modifyInput (#1278) - leather boots, PowderSnowBlock.canEntityWalkOnPowderSnow (#1296) - freeze-immune wear, LivingEntity.canFreeze - the Auto Jump option, LocalPlayer.sendPosition (#1279) tools/lan_e2e.py gains a body check: each player walks while drawing a bow, stands on powder snow with leather boots and without, and sprint-swims looking down. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 87 ++++++++++++++---------- crates/horizon-client/src/game/remote.rs | 11 +-- tools/lan_e2e.py | 81 ++++++++++++++++++++++ 3 files changed, 132 insertions(+), 47 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index bc0cb86b9..0a077aa75 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1825,6 +1825,55 @@ impl Game<'_> { .is_some_and(|i| i.glider && (i.max_damage == 0 || s.damage + 1 < i.max_damage)) }) } + /// What the window decides for its player's body every tick, in frame and + /// on a server alike: the look (Player.travel steers sprint-swimming by + /// the pitch), Auto Jump (LocalPlayer.sendPosition), the slowdown of an + /// item in use (LocalPlayer.modifyInput), the helmet's Respiration + /// (decreaseAirSupply), the wings, leather boots on powder snow + /// (PowderSnowBlock.canEntityWalkOnPowderSnow), freeze-immune wear + /// (LivingEntity.canFreeze) and the dimension's FAST_LAVA. + pub(crate) fn sync_player_body(&mut self) { + let glider = self.glider_worn(); + let item_use_speed = self + .using + .and_then(|(slot, _)| { + if slot == shield::OFFHAND_SLOT { + self.offhand.as_ref() + } else { + self.inventory.get(slot)?.as_ref() + } + }) + .and_then(|s| self.res.items().get(&s.item)) + .map(|i| i.use_speed); + let respiration = self.armor[0] + .as_ref() + .map_or(0, |s| s.enchantment_level("minecraft:respiration") as i32); + let leather_boots = self.armor[3] + .as_ref() + .is_some_and(|s| &*s.item == "minecraft:leather_boots"); + let immune = self + .res + .items() + .item_tags + .get("minecraft:freeze_immune_wearables"); + let freeze_immune = self + .armor + .iter() + .flatten() + .any(|s| immune.is_some_and(|t| t.contains(&*s.item))); + let Some(player) = self.player.as_mut() else { + return; + }; + player.yaw = self.yaw; + player.pitch = self.pitch; + player.auto_jump_enabled = self.settings.auto_jump; + player.item_use_speed = item_use_speed; + player.respiration = respiration; + player.glider = glider; + player.leather_boots = leather_boots; + player.freeze_immune = freeze_immune; + player.fluids.fast_lava = self.dim == Dim::Nether; + } fn held_slot(&self) -> usize { match self.hand { Hand::Main => self.selected, @@ -4035,7 +4084,7 @@ impl Game<'_> { let riding = self.riding.is_some(); let ghast_collisions = self.happy_ghast_player_collisions(); let spin_targets = self.spin_targets(); - let glider = self.glider_worn(); + self.sync_player_body(); let Some(player) = self.player.as_mut() else { // A dedicated server has no local player: the world still runs. if self.options.dedicated.is_some() { @@ -4067,46 +4116,10 @@ impl Game<'_> { if !riding { self.previous_position = player.position; } - player.yaw = self.yaw; let spectator = self.mode == horizon_client::command::args::GameMode::Spectator; player.may_fly = self.creative || spectator; - // LocalPlayer.sendPosition: autoJumpEnabled follows the option. - player.auto_jump_enabled = self.settings.auto_jump; player.invulnerable = self.creative || spectator; player.spectator = spectator; - player.respiration = self.armor[0] - .as_ref() - .map_or(0, |s| s.enchantment_level("minecraft:respiration") as i32); - player.pitch = self.pitch; - player.glider = glider; - // LocalPlayer.modifyInput: walking while using an item. - player.item_use_speed = self - .using - .and_then(|(slot, _)| { - if slot == shield::OFFHAND_SLOT { - self.offhand.as_ref() - } else { - self.inventory.get(slot)?.as_ref() - } - }) - .and_then(|s| self.res.items().get(&s.item)) - .map(|i| i.use_speed); - // PowderSnowBlock.canEntityWalkOnPowderSnow and LivingEntity.canFreeze. - player.leather_boots = self.armor[3] - .as_ref() - .is_some_and(|s| &*s.item == "minecraft:leather_boots"); - let immune = self - .res - .items() - .item_tags - .get("minecraft:freeze_immune_wearables"); - player.freeze_immune = self - .armor - .iter() - .flatten() - .any(|s| immune.is_some_and(|t| t.contains(&*s.item))); - // The dimension's FAST_LAVA: the Nether's lava pushes harder. - player.fluids.fast_lava = self.dim == Dim::Nether; player.spin_targets = spin_targets; let grounded = player.ground.on_ground; let before = ( diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index d41de660e..4b6fd4871 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3144,19 +3144,10 @@ impl Game<'_> { [player.position.x, player.position.y, player.position.z], ); let was_flying = player.flying; - player.yaw = self.yaw; - // As the window's own tick has them: the helmet's Respiration - // (decreaseAirSupply) and the dimension's FAST_LAVA, the Nether's - // stronger lava current. - player.respiration = self.armor[0] - .as_ref() - .map_or(0, |s| s.enchantment_level("minecraft:respiration") as i32); - player.fluids.fast_lava = self.dim == Dim::Nether; - let glider = self.glider_worn(); + self.sync_player_body(); let Some(player) = self.player.as_mut() else { return Ok(()); }; - player.glider = glider; let was_gliding = player.fall_flying; let dead = self.screen == Screen::Dead; // LivingEntity.isImmobile: a sleeper lies still in the bed. diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 271982ca9..8318b6a1f 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -207,6 +207,9 @@ address. The script then checks, from both sides, what a guest's game used to ge bites and reeling in catches it (#1348). - maps: the host and the guest each make a map and hold it: their client draws the terrain around them and their marker, from the server's map data (#1382). +- body: the host and the guest each walk while drawing a bow (slowed), stand on powder snow + with leather boots (held up) and without (sinking), and sprint-swim looking down + (diving): their own client decides it (#1278, #1296, #1303). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -4844,5 +4847,83 @@ CHECKS += ['maps'] CHECK_FNS.update(maps=check_maps) +def check_body(host, guest, out): + """What each player's own client decides for its body (#1278, #1303, #1296): walking while + drawing a bow is slowed to a fifth (LocalPlayer.modifyInput), sprint-swimming follows the look + down (Player.travel's look angle) and leather boots hold on powder snow + (PowderSnowBlock.canEntityWalkOnPowderSnow).""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + seen = {} + + def walked(game, x, z, use): + game('command', command=f'tp @s {x + 0.5} {hy} {z + 0.5} -90 0') + game.wait(10) + if use: + game.raw('mouse', 'right', 'down') + game.wait(5) + a = pos_of(game) + game.raw('move', 'forward', '0.8') + game.wait(10) + b = pos_of(game) + game.raw('mouse', 'right', 'up') + game.wait(5) + return round(math.dist((a[0], a[2]), (b[0], b[2])), 2) + + try: + for game, dz in ((host, -4), (guest, 4)): + x, z = hx, hz + dz + host('command', command=f'fill {x - 1} {hy - 1} {z - 1} {x + 10} {hy - 1} {z + 1} minecraft:stone') + host('command', command=f'fill {x - 1} {hy} {z - 1} {x + 10} {hy + 3} {z + 1} minecraft:air') + game('command', command='gamemode survival') + game('command', command='clear @s') + game('command', command='effect clear @s') + s = {'walk': walked(game, x, z, False)} + game('command', command='item replace entity @s weapon.mainhand with minecraft:bow') + game('command', command='give @s minecraft:arrow 4') + game.wait(5) + s['drawing'] = walked(game, x, z, True) + game('command', command='clear @s') + # Powder snow under the feet: leather boots stand on it, bare feet sink. + host('command', command=f'setblock {x + 3} {hy - 1} {z} minecraft:powder_snow') + for boots in ('leather_boots', 'air'): + game('command', command=f'item replace entity @s armor.feet with minecraft:{boots}') + game('command', command=f'tp @s {x + 3.5} {hy} {z + 0.5} -90 0') + game.wait(30) + s[boots] = round(pos_of(game)[1] - hy, 2) + host('command', command=f'setblock {x + 3} {hy - 1} {z} minecraft:stone') + # Deep water: sprint-swimming while looking down dives. + wx, wz = x, z + 2 * (1 if dz > 0 else -1) * 3 + host('command', command=f'fill {wx - 1} {hy - 14} {wz - 2} {wx + 12} {hy + 2} {wz + 2} minecraft:stone') + host('command', command=f'fill {wx} {hy - 13} {wz - 1} {wx + 11} {hy - 1} {wz + 1} minecraft:water') + game.wait(10) + game('command', command=f'tp @s {wx + 1.5} {hy - 6} {wz + 0.5} -90 60') + game.wait(10) + a = pos_of(game) + game.raw('move', 'forward', '1.5', '--sprint') + game.wait(5) + s['dive'] = round(pos_of(game)[1] - a[1], 2) + game('command', command=f'tp @s {x + 0.5} {hy} {z + 0.5} -90 0') + game.wait(5) + host('command', command=f'fill {wx - 1} {hy - 14} {wz - 2} {wx + 12} {hy + 2} {wz + 2} minecraft:air') + host('command', command=f'fill {wx - 1} {hy - 14} {wz - 2} {wx + 12} {hy - 1} {wz + 2} minecraft:stone') + game.shot(out, 'body') + seen[game.name] = s + finally: + for game in (host, guest): + back_to_game(game) + game.raw('mouse', 'right', 'up') + game('command', command='clear @s') + face_each_other(host, guest) + for name, s in seen.items(): + assert s['walk'] > 2.5 and s['drawing'] < s['walk'] * 0.4, f'{name} drawing a bow: {seen}' + assert s['leather_boots'] > -0.01 and s['air'] < -0.5, f'{name} powder snow: {seen}' + assert s['dive'] < -2, f'{name} sprint-swimming down: {seen}' + return seen + + +CHECKS += ['body'] +CHECK_FNS.update(body=check_body) + + if __name__ == '__main__': main() From f96101cd47f35e998ac1f032f92ce7a4de82f89e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 23:02:07 +0200 Subject: [PATCH 070/408] Strikes and mob effects reach a server's players: lightning, evoker fangs, poison, axolotls Lightning (Entity.thunderHit) and evoker fangs (EvokerFangs.dealDamageTo) hit every entity in their box, but thunder_hit and fangs_bite only looked at the window's own player, so a server's players (guests, and single player on the server thread) were never struck (#1480, #1481). Both now run their player part for each guest too, through Game::each_guest_hit. The effects a mob gives the player it acts on (cave spider and bee poison, husk hunger, wither skeleton wither, the nautilus's breath) and an axolotl's help after a kill stayed with the server's own player: acts_on_player now routes MobEvent::EffectPlayer and MobEvent::AxolotlSupportPlayer to the guest the mob sees, like its blows (#1484, #1485). tools/lan_e2e.py gains a strikes check: a bolt hurts each player standing in water, and a cave spider poisons them. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/fangs.rs | 18 ++++--- crates/horizon-client/src/game/lan_mobs.rs | 21 ++++++++ crates/horizon-client/src/game/lightning.rs | 38 +++++++------ tools/lan_e2e.py | 60 +++++++++++++++++++++ 4 files changed, 115 insertions(+), 22 deletions(-) diff --git a/crates/horizon-client/src/game/fangs.rs b/crates/horizon-client/src/game/fangs.rs index 0939f6490..cdf2d17a5 100644 --- a/crates/horizon-client/src/game/fangs.rs +++ b/crates/horizon-client/src/game/fangs.rs @@ -69,12 +69,18 @@ impl Game<'_> { let lo = Vec3::new(f.pos[0] - half, f.pos[1], f.pos[2] - half); let hi = Vec3::new(f.pos[0] + half, f.pos[1] + 0.8, f.pos[2] + half); let b = horizon_core::geometry::Aabb::new(lo, hi); - if let Some(p) = self.player_view() - && p.alive - && p.bounds.intersects(b) - { - self.mob_hits_player_kind(6.0, f.pos, "minecraft:indirect_magic"); - } + // Every player in the box, the server's players too. + let pos = f.pos; + let bite = move |g: &mut Self| { + if let Some(p) = g.player_view() + && p.alive + && p.bounds.intersects(b) + { + g.mob_hits_player_kind(6.0, pos, "minecraft:indirect_magic"); + } + }; + bite(self); + self.each_guest_hit(bite); for m in &mut self.mobs { let ally = matches!( m.species(), diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index 0ee991737..b3f42f0c7 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -78,6 +78,8 @@ pub(super) fn acts_on_player(e: &MobEvent) -> bool { target: Who::Player, .. } + | MobEvent::EffectPlayer { .. } + | MobEvent::AxolotlSupportPlayer ) } @@ -115,6 +117,25 @@ impl Game<'_> { views } + /// Runs `f` as each guest in play here, for what strikes every player in + /// an area (`Level.getEntities`), not only the window's own. + pub(super) fn each_guest_hit(&mut self, mut f: impl FnMut(&mut Self)) { + let Some(mut host) = self.lan.take() else { + return; + }; + let conns: Vec = host + .hub + .guests + .iter() + .filter(|g| host.hub.here(g) && g.loaded && !g.dead) + .map(|g| g.conn) + .collect(); + for conn in conns { + self.guest_hit_by(&mut host, conn, &mut f); + } + self.lan = Some(host); + } + /// Mob events aimed at a guest, run as that guest (`guest_hit_by`). pub(super) fn lan_guest_mob_events(&mut self, events: Vec<(u32, MobEvent)>) { if events.is_empty() { diff --git a/crates/horizon-client/src/game/lightning.rs b/crates/horizon-client/src/game/lightning.rs index 476cb5aa4..916bd2a0a 100644 --- a/crates/horizon-client/src/game/lightning.rs +++ b/crates/horizon-client/src/game/lightning.rs @@ -280,11 +280,12 @@ impl Game<'_> { } /// `thunderHit` for entities within 3 blocks (up to 9 above). fn thunder_hit(&mut self, b: &mut Bolt) { - let inside = |p: [f64; 3]| { - (p[0] - b.at[0]).abs() <= 3.0 - && (p[2] - b.at[2]).abs() <= 3.0 - && p[1] >= b.at[1] - 3.0 - && p[1] <= b.at[1] + 9.0 + let at = b.at; + let inside = move |p: [f64; 3]| { + (p[0] - at[0]).abs() <= 3.0 + && (p[2] - at[2]).abs() <= 3.0 + && p[1] >= at[1] - 3.0 + && p[1] <= at[1] + 9.0 }; let damage = Damage { kind: DamageKind::Generic, @@ -349,19 +350,24 @@ impl Game<'_> { if !events.is_empty() { let _ = self.handle_mob_events(events); } - if let Some(p) = self.player.as_ref().map(|p| p.position) - && inside([p.x, p.y, p.z]) - { - if let Some(p) = self.player.as_mut() { - p.fire_ticks += 1; - if p.fire_ticks == 0 - && let Err(error) = p.ignite_for_ticks(160) - { - self.error = Some(error); + // Every player in the box, the server's players too. + let strike = move |g: &mut Self| { + if let Some(p) = g.player.as_ref().map(|p| p.position) + && inside([p.x, p.y, p.z]) + { + if let Some(p) = g.player.as_mut() { + p.fire_ticks += 1; + if p.fire_ticks == 0 + && let Err(error) = p.ignite_for_ticks(160) + { + g.error = Some(error); + } } + g.hurt_player_by("minecraft:lightning_bolt", 5.0); } - self.hurt_player_by("minecraft:lightning_bolt", 5.0); - } + }; + strike(self); + self.each_guest_hit(strike); // Dropped items burn up (ItemEntity health 5), save fire-resistant ones. self.dropped.retain(|e| { !inside([e.position.x, e.position.y, e.position.z]) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 8318b6a1f..49ba0d186 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -210,6 +210,8 @@ address. The script then checks, from both sides, what a guest's game used to ge - body: the host and the guest each walk while drawing a bow (slowed), stand on powder snow with leather boots (held up) and without (sinking), and sprint-swim looking down (diving): their own client decides it (#1278, #1296, #1303). +- strikes: a bolt strikes the host and the guest standing in water and hurts them, and a cave + spider's bite poisons them (#1480, #1484). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -4925,5 +4927,63 @@ CHECKS += ['body'] CHECK_FNS.update(body=check_body) +def check_strikes(host, guest, out): + """What a mob or the sky does to every player in reach, the server's players too (#1480, + #1484): a bolt striking a player standing in water costs them health (Entity.thunderHit), and + a cave spider's bite poisons them (CaveSpider.doHurtTarget on Normal).""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + seen = {} + try: + host('command', command='difficulty normal') + host('command', command='time set 18000') + for game, dz in ((host, -5), (guest, 5)): + x, z = hx, hz + dz + host('command', command=f'fill {x - 3} {hy - 1} {z - 3} {x + 3} {hy + 3} {z + 3} minecraft:stone') + host('command', command=f'fill {x - 2} {hy} {z - 2} {x + 2} {hy + 3} {z + 2} minecraft:air') + host('command', command=f'fill {x - 2} {hy} {z - 2} {x + 2} {hy} {z + 2} minecraft:water') + game('command', command='gamemode survival') + game('command', command='clear @s') + game('command', command='effect clear @s') + game('command', command='effect give @s minecraft:instant_health 1 5') + game('command', command=f'tp @s {x + 0.5} {hy} {z + 0.5}') + game.wait(20) + before = game('state')['player'].get('health') + game('command', command=f'summon minecraft:lightning_bolt {x + 0.5} {hy} {z + 0.5}') + game.wait(20) + s = {'bolt': (before, game('state')['player'].get('health'))} + host('command', command=f'summon minecraft:cave_spider {x + 1.5} {hy} {z + 0.5}') + poisoned = False + for _ in range(40): + game.wait(5) + if 'poison' in effect_ids(game): + poisoned = True + break + s['poisoned'] = poisoned + s['bitten'] = game('state')['player'].get('health') + host('command', command='kill @e[type=minecraft:cave_spider]') + game.wait(5) + game.shot(out, 'strikes') + host('command', command=f'fill {x - 3} {hy - 1} {z - 3} {x + 3} {hy + 3} {z + 3} minecraft:air') + host('command', command=f'fill {x - 3} {hy - 1} {z - 3} {x + 3} {hy - 1} {z + 3} minecraft:stone') + seen[game.name] = s + finally: + host('command', command='kill @e[type=minecraft:cave_spider]') + host('command', command='time set day') + for game in (host, guest): + back_to_game(game) + game('command', command='effect clear @s') + game('command', command='effect give @s minecraft:instant_health 1 5') + face_each_other(host, guest) + for name, s in seen.items(): + a, b = s['bolt'] + assert a is not None and b is not None and a - b >= 3, f'{name} struck by lightning: {seen}' + assert s['poisoned'], f'{name} bitten by a cave spider: {seen}' + return seen + + +CHECKS += ['strikes'] +CHECK_FNS.update(strikes=check_strikes) + + if __name__ == '__main__': main() From c6ed3112e7891b4d96de16cee5e16f948bbe12c7 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 23:04:53 +0200 Subject: [PATCH 071/408] Closing a menu puts a server's player's cursor stack back into their inventory AbstractContainerMenu.removed hands the stack a closing player holds on the cursor to placeItemBackInInventory (dropped only what doesn't fit, or for a player who left), and broadcastChanges then empties the client's cursor. The LAN host threw it out at the player's eyes instead, for the inventory and every container, crafting, station, mount and merchant menu, and the client kept showing a copy on its cursor (#1283). The three ContainerClose arms now place it back through lan_place_back and send the inventory, carried stack included. tools/lan_e2e.py gains a cursor check: each player picks up a stack in their inventory and closes it. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/lan_actions.rs | 26 +++++++------ tools/lan_e2e.py | 39 +++++++++++++++++++ 2 files changed, 53 insertions(+), 12 deletions(-) diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index bb43fe660..66b4e4dd6 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1051,20 +1051,14 @@ impl Game<'_> { S::SetBeacon(p) => self.lan_station_beacon(host, conn, p.primary, p.secondary), S::SelectTrade(p) => self.lan_select_trade(host, conn, p.item), S::ContainerClose(p) if self.lan_merchant_closed(host, conn, Some(p.container)) => { - let g = &mut host.hub.guests[gi]; - if let Some(c) = g.carried.take() { - self.drop_guest_items(host, gi, vec![c]); - } + self.guest_carried_back(host, gi); } S::ContainerClose(p) if self.lan_crafting_closed(host, conn, Some(p.container)) || self.lan_station_closed(host, conn, Some(p.container)) || self.lan_mount_closed(host, conn, Some(p.container)) => { - let g = &mut host.hub.guests[gi]; - if let Some(c) = g.carried.take() { - self.drop_guest_items(host, gi, vec![c]); - } + self.guest_carried_back(host, gi); } S::ContainerClick(p) => { let rules = ItemRules(self.res.items()); @@ -1080,10 +1074,7 @@ impl Game<'_> { self.guest_container_closed(host, conn); } host.hub.container_closed(conn, p.container); - let g = &mut host.hub.guests[gi]; - if let Some(c) = g.carried.take() { - self.drop_guest_items(host, gi, vec![c]); - } + self.guest_carried_back(host, gi); } S::ChatCommand(c) => self.guest_chat_command(host, conn, &c.command), S::ChatCommandSigned(p) => self.guest_signed_command(host, conn, p), @@ -1230,6 +1221,17 @@ impl Game<'_> { Some(out) } + /// `AbstractContainerMenu.removed`: what a closing player held on the + /// cursor goes back into their inventory (`placeItemBackInInventory`, + /// dropped only if it doesn't fit), and their client's cursor empties + /// with the inventory it is sent. + fn guest_carried_back(&mut self, host: &mut LanHost, gi: usize) { + if let Some(c) = host.hub.guests[gi].carried.take() { + self.lan_place_back(host, gi, vec![c]); + host.hub.send_inventory(gi); + } + } + pub(super) fn drop_guest_items(&mut self, host: &LanHost, gi: usize, stacks: Vec) { let g = &host.hub.guests[gi]; let eye = [ diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 49ba0d186..c07edeece 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -212,6 +212,8 @@ address. The script then checks, from both sides, what a guest's game used to ge (diving): their own client decides it (#1278, #1296, #1303). - strikes: a bolt strikes the host and the guest standing in water and hurts them, and a cave spider's bite poisons them (#1480, #1484). +- cursor: the host and the guest each close their inventory with a stack on the cursor: it + goes back into their inventory, none is thrown and the cursor is empty (#1283). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -4985,5 +4987,42 @@ CHECKS += ['strikes'] CHECK_FNS.update(strikes=check_strikes) +def check_cursor(host, guest, out): + """Closing the inventory with a stack on the cursor puts it back into the player's inventory + (AbstractContainerMenu.removed, placeItemBackInInventory) and empties the cursor, for each + player: nothing is thrown out and no copy stays on the cursor (#1283).""" + seen = {} + try: + for game in (host, guest): + game('command', command='clear @s') + host('command', command='kill @e[type=minecraft:item]') + game('command', command='item replace entity @s hotbar.0 with minecraft:diamond 7') + game.wait(10) + game.raw('open-inventory') + game.raw('wait-for', 'screen', 'inventory', '--timeout', 10) + game.raw('click-slot', 0) + game.wait(5) + held = (game('inventory').get('carried') or {}).get('count') + game.raw('key', 'esc', 'tap') + game.wait(40) + inv = game('inventory') + seen[game.name] = {'held': held, 'carried': inv.get('carried'), + 'client': inv['counts'].get('minecraft:diamond', 0), + 'server': server_count(game, 'diamond'), + 'thrown': len(game.raw('entities', 8, 'minecraft:item')['entities'])} + finally: + for game in (host, guest): + back_to_game(game) + game('command', command='clear @s') + host('command', command='kill @e[type=minecraft:item]') + for name, s in seen.items(): + assert s == {'held': 7, 'carried': None, 'client': 7, 'server': 7, 'thrown': 0}, f'{name}: {seen}' + return seen + + +CHECKS += ['cursor'] +CHECK_FNS.update(cursor=check_cursor) + + if __name__ == '__main__': main() From a4a101ca9cf450dd715196ca5e5caed72725636f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 23:21:28 +0200 Subject: [PATCH 072/408] Single player runs on its server thread by default again; --in-frame is the opt-out #1428 made the in-frame world the default while a server's players lagged behind it (signs, books, totems, keep_inventory and the other [server-thread] issues). With the fixes of this stack a scripted single player session (walk, mine, place, inventory, combat, eating, boats, minecarts, chests, furnaces, beds, chat, signs, books, totems, keep_inventory, fishing, maps, saving and reopening) gives the same results on the server thread as in the frame. `--in-frame`, `--no-server-thread` or HORIZON_SERVER_THREAD=0 runs the world in the frame; `--server-thread` still works. LAN guests, dedicated servers and the command harness are unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 14 ++++++-------- crates/horizon-client/src/game/integrated.rs | 10 ++++------ docs/launcher-commands.md | 4 ++-- docs/server-levels.md | 7 +++---- 4 files changed, 15 insertions(+), 20 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 0a077aa75..b0fa00584 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -284,11 +284,9 @@ struct Options { benchmark: Option, /// `--dev-mod PATH` (repeatable): mods always on and reloaded when rebuilt. dev_mods: Vec, - /// `--server-thread` or `HORIZON_SERVER_THREAD=1`: single player runs on an - /// integrated server thread (game/integrated.rs), as vanilla's does. Off by - /// default again until a server's players reach parity with the in-frame - /// world (signs, books, totems, keep_inventory...); `--no-server-thread` - /// keeps it off. + /// Single player runs on an integrated server thread (game/integrated.rs), + /// as vanilla's does: the default. `--in-frame` (or `--no-server-thread`, + /// or `HORIZON_SERVER_THREAD=0`) runs the world in the frame instead. server_thread: bool, /// Set on the integrated server's own options: it draws nothing, so it skips meshing. integrated: bool, @@ -346,7 +344,7 @@ impl Options { dev_mods: Vec::new(), // The command harness (HORIZON_COMMAND_SCRIPT) drives the world // itself, without the event loop: it stays in the frame. - server_thread: std::env::var("HORIZON_SERVER_THREAD").is_ok_and(|v| v == "1") + server_thread: std::env::var("HORIZON_SERVER_THREAD").map_or(true, |v| v != "0") && std::env::var_os("HORIZON_COMMAND_SCRIPT").is_none(), integrated: false, }; @@ -356,7 +354,7 @@ impl Options { match arg.as_str() { "--help" | "-h" => { println!( - "Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --width N, --height N Window size (default 1280 x 720)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --server-thread Run single player's world on its server thread (not at parity yet)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.", + "Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --width N, --height N Window size (default 1280 x 720)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --in-frame Run single player's world in the frame, not on its server thread\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.", horizon_core::VANILLA_VERSION ); return Ok(None); @@ -371,7 +369,7 @@ impl Options { "--offscreen" => o.offscreen = true, "--control" => o.control = Some(horizon_client::control::default_path()), "--server-thread" => o.server_thread = true, - "--no-server-thread" => o.server_thread = false, + "--in-frame" | "--no-server-thread" => o.server_thread = false, _ => { let value = args .next() diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index 49266a855..042d8113a 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -6,12 +6,10 @@ //! the world's options) with [`Integrated::call`], as vanilla's client calls //! into its `IntegratedServer`. //! -//! Opt-in again (`--server-thread` or `HORIZON_SERVER_THREAD=1`) until a -//! server's players reach parity with the in-frame world: on the server -//! thread, signs open no editor, books don't open, a totem doesn't save its -//! holder and death keeps the inventory (#1380, #1366, #1292, #1284 and the -//! other `[server-thread]` issues). LAN guests and dedicated servers use the -//! same code either way. +//! On by default. `--in-frame` (or `--no-server-thread`, or +//! `HORIZON_SERVER_THREAD=0`) runs the world in the frame instead, the +//! escape hatch. LAN guests and dedicated servers use the same code either +//! way. use super::{ Game, Options, PackResources, Resources, UiResources, lan::{LanSettings, Owner}, diff --git a/docs/launcher-commands.md b/docs/launcher-commands.md index 9e09cd00b..dfe768b0e 100644 --- a/docs/launcher-commands.md +++ b/docs/launcher-commands.md @@ -53,7 +53,7 @@ Start the client. - `--world`: Open or create this world (a folder under saves) at once - `--creative`: Creative mode for a new world - `--join`: Join a friend's world with its invite code -- `--arg`: An extra argument for the game, passed through as-is (repeatable), for example --server-thread +- `--arg`: An extra argument for the game, passed through as-is (repeatable), for example --in-frame MCP: `play`, then the `game_*` tools. @@ -143,7 +143,7 @@ MCP: `settings`. ## `horizon-launcher game-args` -Show or set the extra arguments the game starts with (for example --server-thread); quotes group a word with spaces in it. +Show or set the extra arguments the game starts with (for example --in-frame); quotes group a word with spaces in it. horizon-launcher game-args [ARGS] diff --git a/docs/server-levels.md b/docs/server-levels.md index cc21a52ab..df45efc1f 100644 --- a/docs/server-levels.md +++ b/docs/server-levels.md @@ -26,10 +26,9 @@ the other dimensions' levels as `Parked` values and swaps one into place (`enter The packets of a guest are read in its own level's pass (`Hub::tick_level`), so its actions and commands run with its level in place. -The window's own game (single player's default, `--no-server-thread`, `HORIZON_SERVER_THREAD=0`, and the -command harness) keeps one level, which follows its player (`enter_dimension`). LAN guests of a world run -that way stay in the host's dimension. It is the default again only until the server thread reaches parity -(`--server-thread` or `HORIZON_SERVER_THREAD=1` opts in), so it gets no multi-level work. +The window's own game (`--in-frame`, `--no-server-thread`, `HORIZON_SERVER_THREAD=0`, and the command +harness) keeps one level, which follows its player (`enter_dimension`). LAN guests of a world run that way +stay in the host's dimension. That mode is the escape hatch, so it gets no multi-level work. ## One code path for both From 4b1e298a44ef7c180480d818af8ec4f5f29a5f65 Mon Sep 17 00:00:00 2001 From: Ganer Date: Fri, 23 Oct 2026 16:55:08 -0500 Subject: [PATCH 073/408] fix(worldgen): resolve upstream Rust 1.90 Clippy boolean warnings --- crates/horizon-world/src/block_survival.rs | 4 +- crates/horizon-world/src/edge_backoff.rs | 8 +-- crates/horizon-world/src/level/bonemeal.rs | 2 +- crates/horizon-world/src/level/speleothem.rs | 4 +- crates/horizon-world/src/level/tick.rs | 3 +- .../src/worldgen/aquifer/noise_based.rs | 31 ++++++++++- .../src/worldgen/feature_region.rs | 2 +- .../horizon-world/src/worldgen/placement.rs | 2 +- .../src/worldgen/structure/start.rs | 2 +- crates/horizon-world/tests/edge_backoff.rs | 53 +++++++++++++++++-- 10 files changed, 95 insertions(+), 16 deletions(-) diff --git a/crates/horizon-world/src/block_survival.rs b/crates/horizon-world/src/block_survival.rs index ae53451ba..f5c6d56a9 100644 --- a/crates/horizon-world/src/block_survival.rs +++ b/crates/horizon-world/src/block_survival.rs @@ -471,10 +471,10 @@ impl<'r> BlockSurvivalRegistry<'r> { .ignition_odds .get(&state.name) .is_some_and(|value| *value > 0) - && !state + && state .properties .get("waterlogged") - .is_some_and(|value| value == "true") + .is_none_or(|value| value != "true") }) .collect(), fence_gates: (0..registry.len()) diff --git a/crates/horizon-world/src/edge_backoff.rs b/crates/horizon-world/src/edge_backoff.rs index 7299d8c14..0dfebdae2 100644 --- a/crates/horizon-world/src/edge_backoff.rs +++ b/crates/horizon-world/src/edge_backoff.rs @@ -77,9 +77,11 @@ pub fn back_off_from_edge( ); world.no_collision(bounds).map_err(EdgeBackoffError::World) }; - if !grounded - && !(input.fall_distance < step && !can_fall(0.0, 0.0, step - input.fall_distance)?) - { + // Keep the collision query's short circuit: on-ground movement must not + // consume any budget, and an unordered (NaN) fall distance skips it too. + let should_back_off = grounded + || (input.fall_distance < step && !can_fall(0.0, 0.0, step - input.fall_distance)?); + if !should_back_off { return Ok(input.movement); } let mut x = input.movement.x; diff --git a/crates/horizon-world/src/level/bonemeal.rs b/crates/horizon-world/src/level/bonemeal.rs index 274512138..452aa7568 100644 --- a/crates/horizon-world/src/level/bonemeal.rs +++ b/crates/horizon-world/src/level/bonemeal.rs @@ -952,7 +952,7 @@ impl Sim<'_, L> { if crate::level::query::axis_of(spread) == crate::level::query::axis_of(from) { return None; } - if !(self.multiface_has_face(state, from) && !self.multiface_has_face(state, spread)) { + if !self.multiface_has_face(state, from) || self.multiface_has_face(state, spread) { return None; } let block = self.b.block(state); diff --git a/crates/horizon-world/src/level/speleothem.rs b/crates/horizon-world/src/level/speleothem.rs index 60059cfe9..7095db61f 100644 --- a/crates/horizon-world/src/level/speleothem.rs +++ b/crates/horizon-world/src/level/speleothem.rs @@ -276,8 +276,8 @@ impl Sim<'_, L> { if value > 0.175_781_25 { return; } - if !(self.speleothem_with(state, Direction::Down) - && !b.is_block(self.above_state(pos), b.block(state))) + if !self.speleothem_with(state, Direction::Down) + || b.is_block(self.above_state(pos), b.block(state)) { return; } diff --git a/crates/horizon-world/src/level/tick.rs b/crates/horizon-world/src/level/tick.rs index 0f640ef3a..bced59df9 100644 --- a/crates/horizon-world/src/level/tick.rs +++ b/crates/horizon-world/src/level/tick.rs @@ -565,7 +565,8 @@ impl Sim<'_, L> { return; } } - let burnout = self.level.dimension() == super::Dimension::Nether && false; + // Nether burnout is intentionally disabled: keep its behavior explicit. + let burnout = false; let extra = if burnout { -50 } else { 0 }; for (direction, chance) in [ (Direction::East, 300), diff --git a/crates/horizon-world/src/worldgen/aquifer/noise_based.rs b/crates/horizon-world/src/worldgen/aquifer/noise_based.rs index 3f3c7dc2c..60abbc371 100644 --- a/crates/horizon-world/src/worldgen/aquifer/noise_based.rs +++ b/crates/horizon-world/src/worldgen/aquifer/noise_based.rs @@ -447,7 +447,7 @@ impl NoiseBasedAquif let n = 3. + edge; if n > 0. { n / 3. } else { n / 10. } }; - let barrier = if q < -2. || q > 2. { + let barrier = if pressure_outside_interval(q) { 0. } else { if memo.is_nan() { @@ -603,6 +603,35 @@ impl NoiseBasedAquif Ok(Some(candidate)) } } +/// Preserve ordered floating-point comparisons, including NaN (which lies +/// neither below -2 nor above 2). Negating `RangeInclusive::contains` alone +/// would incorrectly treat NaN as outside the interval. +fn pressure_outside_interval(q: f64) -> bool { + !q.is_nan() && !(-2.0..=2.0).contains(&q) +} + fn similarity(a: i32, b: i32) -> f64 { 1. - b.wrapping_sub(a) as f64 / 25. } + +#[cfg(test)] +mod pressure_interval_tests { + use super::pressure_outside_interval; + + #[test] + fn outside_range_preserves_ordered_float_boundary_and_nan_behavior() { + for (q, expected) in [ + (f64::NAN, false), + (f64::NEG_INFINITY, true), + (-2.1, true), + (-2.0, false), + (-0.0, false), + (0.0, false), + (2.0, false), + (2.1, true), + (f64::INFINITY, true), + ] { + assert_eq!(pressure_outside_interval(q), expected, "q={q:?}"); + } + } +} diff --git a/crates/horizon-world/src/worldgen/feature_region.rs b/crates/horizon-world/src/worldgen/feature_region.rs index e1d80e8bc..5040846c6 100644 --- a/crates/horizon-world/src/worldgen/feature_region.rs +++ b/crates/horizon-world/src/worldgen/feature_region.rs @@ -519,7 +519,7 @@ impl<'r, B: TerrainBlockStates, F> TerrainFeatureAccess<'_, 'r, B, F> { }) } }; - Ok(!height.is_some_and(|height| !height.contains(position[1]))) + Ok(height.is_none_or(|height| height.contains(position[1]))) } } impl<'r, B: TerrainBlockStates, F> PlacementContext for TerrainFeatureAccess<'_, 'r, B, F> diff --git a/crates/horizon-world/src/worldgen/placement.rs b/crates/horizon-world/src/worldgen/placement.rs index 0c4ed8223..dd774f316 100644 --- a/crates/horizon-world/src/worldgen/placement.rs +++ b/crates/horizon-world/src/worldgen/placement.rs @@ -445,7 +445,7 @@ impl PlacementModifier { if !include_edges && (u8::from(bx) + u8::from(by) + u8::from(bz)) >= 2 { continue; } - if !include_interior && !(bx || by || bz) { + if !(*include_interior || bx || by || bz) { continue; } emit( diff --git a/crates/horizon-world/src/worldgen/structure/start.rs b/crates/horizon-world/src/worldgen/structure/start.rs index dcd4f1ed6..70e457b2e 100644 --- a/crates/horizon-world/src/worldgen/structure/start.rs +++ b/crates/horizon-world/src/worldgen/structure/start.rs @@ -196,7 +196,7 @@ impl RingSections { let squared = x.wrapping_mul(x).wrapping_add(z.wrapping_mul(z)); let distance = f64::from(squared).sqrt() as i32; let section = distance.wrapping_add(self.thickness - self.first) / self.thickness; - !self.max.is_some_and(|max| section > max) && section % 2 == 1 + self.max.is_none_or(|max| section <= max) && section % 2 == 1 } } diff --git a/crates/horizon-world/tests/edge_backoff.rs b/crates/horizon-world/tests/edge_backoff.rs index 501bc625d..e8f37057f 100644 --- a/crates/horizon-world/tests/edge_backoff.rs +++ b/crates/horizon-world/tests/edge_backoff.rs @@ -4,6 +4,7 @@ use horizon_world::edge_backoff::{ }; struct World { calls: usize, + grounded: bool, } impl EdgeBackoffWorld for World { type Error = std::convert::Infallible; @@ -14,7 +15,7 @@ impl EdgeBackoffWorld for World { Ok(true) } fn on_ground(&mut self) -> Result { - Ok(true) + Ok(self.grounded) } fn no_collision(&mut self, _: Aabb) -> Result { self.calls += 1; @@ -33,7 +34,10 @@ fn input() -> EdgeBackoffInput { } #[test] fn nonconverging_motion_exhausts_budget_without_successful_displacement() { - let mut world = World { calls: 0 }; + let mut world = World { + calls: 0, + grounded: true, + }; assert!(matches!( back_off_from_edge(&mut world, input()), Err(EdgeBackoffError::QueryBudget) @@ -42,7 +46,10 @@ fn nonconverging_motion_exhausts_budget_without_successful_displacement() { } #[test] fn zero_budget_only_fails_when_a_probe_is_needed() { - let mut world = World { calls: 0 }; + let mut world = World { + calls: 0, + grounded: true, + }; let mut request = input(); request.query_budget = 0; request.flying = true; @@ -60,3 +67,43 @@ fn zero_budget_only_fails_when_a_probe_is_needed() { )); assert_eq!(world.calls, 0); } + +#[test] +fn edge_check_preserves_grounded_and_unordered_fall_distance_short_circuit() { + // Neither already-grounded players nor NaN fall distances should query + // the world at all. The original `fall_distance < step` is false on NaN. + let mut world = World { + calls: 0, + grounded: true, + }; + let mut request = input(); + request.query_budget = 0; + request.movement = Vec3::new(0.0, 0.0, 0.0); + assert_eq!( + back_off_from_edge(&mut world, request).unwrap(), + Vec3::new(0.0, 0.0, 0.0) + ); + assert_eq!(world.calls, 0); + + world.grounded = false; + let mut request = input(); + request.query_budget = 0; + request.movement = Vec3::new(0.0, 0.0, 0.0); + request.fall_distance = f64::NAN; + assert_eq!( + back_off_from_edge(&mut world, request).unwrap(), + Vec3::new(0.0, 0.0, 0.0) + ); + assert_eq!(world.calls, 0); + + // An airborne player inside the step range must still attempt the + // collision query and report budget exhaustion rather than succeed. + let mut request = input(); + request.query_budget = 0; + request.fall_distance = 0.0; + assert!(matches!( + back_off_from_edge(&mut world, request), + Err(EdgeBackoffError::QueryBudget) + )); + assert_eq!(world.calls, 0); +} From e1fff77a484a57e4d34947215768660a1f2dcb7b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:38:13 +0200 Subject: [PATCH 074/408] Prepare: Netty's native transports are optional, as in the game Prism Launcher never downloads io.netty:netty-transport-native-kqueue (or the epoll one on Linux), so preparing from a Prism install stopped on a jar the game runs without: vanilla's EventLoopGroupHolder.remote takes KQueue/Epoll only when isAvailable(), else Netty NIO. Preparing now imports a native transport when the launcher has it (checked against the version JSON's sha1, as before) and goes on without it otherwise; every other library stays required. Fixes #1487. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-prepare/src/artifacts.rs | 163 +++++++++++++++++++++++- 1 file changed, 159 insertions(+), 4 deletions(-) diff --git a/crates/horizon-prepare/src/artifacts.rs b/crates/horizon-prepare/src/artifacts.rs index b29bffb28..805dd80d4 100644 --- a/crates/horizon-prepare/src/artifacts.rs +++ b/crates/horizon-prepare/src/artifacts.rs @@ -372,6 +372,19 @@ fn client_library_artifacts(manifest: &Value) -> Result, Str Ok(artifacts) } +/// Netty's native transports (`io.netty:netty-transport-native-kqueue:4.2.16.Final:osx-aarch_64`, +/// the epoll ones on Linux): the game uses one when it loads and Netty NIO otherwise +/// (`EventLoopGroupHolder.remote` asks `KQueue.isAvailable()`, then `Epoll.isAvailable()`), and +/// Prism Launcher never downloads them (#1487). Preparing imports one when the launcher has it. +fn runs_without(name: &str) -> bool { + let mut parts = name.split(':'); + parts.next() == Some("io.netty") + && parts + .next() + .is_some_and(|artifact| artifact.starts_with("netty-transport-native-")) + && parts.nth(1).is_some() +} + /// A relative path with only normal components and forward slashes, from a manifest or bundle. pub(crate) fn safe_relative(path: &str) -> Option { if path.contains('\\') || path.starts_with('/') { @@ -547,9 +560,18 @@ pub fn import( for (name, artifact) in client_library_artifacts(&manifest)? { let (path, sha1) = artifact_fields(artifact)?; let relative = safe_relative(path).ok_or("Unsafe library path")?; + let source = launcher_library(&minecraft, name, &relative); + let destination = lock.directory.join("libraries/client").join(&relative); + if runs_without(name) && !source.is_file() && !destination.exists() { + log(&format!( + "No {name} in {}: the game runs without it", + minecraft.display() + )); + continue; + } client_libraries.push(import_copy( - &launcher_library(&minecraft, name, &relative), - &lock.directory.join("libraries/client").join(&relative), + &source, + &destination, sha1, "sha1", &hint(LAUNCHER_HINT, version), @@ -783,13 +805,17 @@ pub fn verify(lock: &Lock) -> Result { } /// The client libraries, checked against the version JSON (tools/test_model_baking_parity.py's -/// `client_libraries`); the client-side exporters compile against them. +/// `client_libraries`); the client-side exporters compile against them. A native transport the +/// player's launcher did not have is left out. pub fn client_libraries(lock: &Lock, manifest: &Value) -> Result, String> { let mut libraries = Vec::new(); - for (_, artifact) in client_library_artifacts(manifest)? { + for (name, artifact) in client_library_artifacts(manifest)? { let (path, sha1) = artifact_fields(artifact)?; let relative = safe_relative(path).ok_or("Unsafe client library path")?; let library = lock.directory.join("libraries/client").join(&relative); + if runs_without(name) && !library.exists() { + continue; + } if !library.exists() || digest(&library, "sha1")? != sha1 { return Err(format!("Client dependency checksum changed: {path}")); } @@ -1071,6 +1097,135 @@ mod tests { } } + /// scanfee's Prism Launcher 26.3 install on a Mac (#1487): Prism keeps natives under its own + /// names and never downloads Netty's native transport, which the game runs without. Preparing + /// still checks every other library, and the transport whenever the launcher has it. + #[test] + fn a_prism_install_without_netty_natives_prepares() { + let fixture = Imports::new(); + let old = fixture.imported(&fixture.source); + let prism = fixture.directory.join("PrismLauncher"); + let put = |path: &str, data: &[u8]| { + let path = prism.join(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, data).unwrap(); + }; + put( + "versions/9.9/9.9.jar", + &fs::read(old.join("jars/client.jar")).unwrap(), + ); + put("libraries/org/lib/lib/1/lib-1.jar", b"lib"); + put( + "libraries/com/mojang/jtracy-natives-test/1/jtracy-natives-test-1.jar", + b"jtracy natives", + ); + let sha1 = |data: &[u8]| { + let file = fixture.directory.join("sha1"); + fs::write(&file, data).unwrap(); + digest(&file, "sha1").unwrap() + }; + let library = |name: &str, path: &str, sha1: &str, rules: &str| { + format!( + r#"{{"name":"{name}","downloads":{{"artifact":{{"path":"{path}","sha1":"{sha1}"}}}}{rules}}}"# + ) + }; + let netty = |arch: &str| { + library( + &format!("io.netty:netty-transport-native-kqueue:1:osx-{arch}"), + &format!("io/netty/netty-transport-native-kqueue/1/netty-transport-native-kqueue-1-osx-{arch}.jar"), + &sha1(b"kqueue"), + &format!(r#","rules":[{{"action":"allow","os":{{"name":"{}"}}}}]"#, rule_system()), + ) + }; + let client_sha1 = digest(&old.join("jars/client.jar"), "sha1").unwrap(); + let server_sha1 = digest(&old.join("jars/server.jar"), "sha1").unwrap(); + let libraries = [ + library( + "org.lib:lib:1", + "org/lib/lib/1/lib-1.jar", + &sha1(b"lib"), + "", + ), + library( + "com.mojang:jtracy:1:natives-test", + "com/mojang/jtracy/1/jtracy-1-natives-test.jar", + &sha1(b"jtracy natives"), + "", + ), + netty("aarch_64"), + netty("x86_64"), + ]; + put( + "versions/9.9/9.9.json", + format!( + r#"{{"id":"9.9","javaVersion":{{"majorVersion":25}},"downloads":{{"client":{{"sha1":"{client_sha1}"}},"server":{{"sha1":"{server_sha1}"}}}},"libraries":[{}]}}"#, + libraries.join(",") + ) + .as_bytes(), + ); + let manifest_sha1 = digest(&prism.join("versions/9.9/9.9.json"), "sha1").unwrap(); + fs::write( + fixture.target.join("research-lock.json"), + format!( + r#"{{"minecraft":{{"version":"9.9","java_major":25,"manifest_sha1":"{manifest_sha1}","client_sha1":"{client_sha1}","server_sha1":"{server_sha1}"}}}}"# + ), + ) + .unwrap(); + let lock = Lock::read(&fixture.target).unwrap(); + let server = old.join("jars/server.jar"); + let prepare = || import(&fixture.target, &lock, Some(&prism), Some(&server), &|_| {}); + let imported = || { + let manifest = verify(&lock).unwrap().manifest; + client_libraries(&lock, &manifest).unwrap().len() + }; + + prepare().unwrap(); + assert_eq!(imported(), 2); + let prepared = read_json(&lock.directory.join("prepared.json")).unwrap(); + let listed = prepared.get("libraries").and_then(|l| l.get("client")); + assert_eq!( + listed.and_then(Value::as_array).map(<[Value]>::len), + Some(2) + ); + assert!(reuse_imported(&fixture.target, &|_| {}).unwrap()); + + // The launcher's copy is used, and checked, when it has one. + let manifest = read_json(&prism.join("versions/9.9/9.9.json")).unwrap(); + let (_, transport) = client_library_artifacts(&manifest) + .unwrap() + .into_iter() + .find(|(name, _)| runs_without(name)) + .unwrap(); + let path = transport.get("path").and_then(Value::as_str).unwrap(); + put(&format!("libraries/{path}"), b"not kqueue"); + assert!(prepare().unwrap_err().contains("is not the pinned file")); + put(&format!("libraries/{path}"), b"kqueue"); + prepare().unwrap(); + assert_eq!(imported(), 3); + // Other libraries stay required. + fs::remove_dir_all(lock.directory.join("libraries/client/org")).unwrap(); + fs::remove_file(prism.join("libraries/org/lib/lib/1/lib-1.jar")).unwrap(); + assert!(prepare().unwrap_err().starts_with("Missing ")); + } + + #[test] + fn runs_without_only_netty_native_transports() { + assert!(runs_without( + "io.netty:netty-transport-native-kqueue:4.2.16.Final:osx-aarch_64" + )); + assert!(runs_without( + "io.netty:netty-transport-native-epoll:4.2.16.Final:linux-x86_64" + )); + for required in [ + "io.netty:netty-transport-native-unix-common:4.2.16.Final", + "io.netty:netty-transport-classes-kqueue:4.2.16.Final", + "org.lwjgl:lwjgl:3.3.3:natives-macos-arm64", + "com.mojang:jtracy:1.14.38:natives-windows", + ] { + assert!(!runs_without(required), "{required}"); + } + } + #[test] fn natives_follow_the_architecture() { let names = ["a:b:1:natives-macos", "a:b:1:natives-macos-arm64"]; From 52bc81ca5b1fe78fe98b63685c0fc0a1c1c6a0ae Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:48:08 +0200 Subject: [PATCH 075/408] Launcher: the command reference is the same on Windows launcher.yml's Windows build has failed since the reference test landed: Git for Windows checks text out with CRLF (core.autocrlf), so docs/launcher-commands.md never equalled what markdown() generates. .gitattributes now pins LF for the generated files tests compare byte for byte, and the launcher's check reads the file whatever line endings a clone gave it, with a test of a CRLF checkout. Co-Authored-By: Claude Opus 5.5 --- .gitattributes | 5 +++++ launcher/src/cli_tools.rs | 16 +++++++++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..13584e4d9 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,5 @@ +# Generated files that tests compare byte for byte with what they generate: LF on every OS, also +# where Git for Windows' core.autocrlf would check them out with CRLF. +docs/launcher-commands.md text eol=lf +docs/horizon-ctl-commands.md text eol=lf +website/src/tokens.css text eol=lf diff --git a/launcher/src/cli_tools.rs b/launcher/src/cli_tools.rs index 7653311ac..a851adcbd 100644 --- a/launcher/src/cli_tools.rs +++ b/launcher/src/cli_tools.rs @@ -419,6 +419,20 @@ mod tests { ); } + /// Whether the reference on disk says `want`, whatever line endings the checkout gave it: Git + /// for Windows checks text out with CRLF (core.autocrlf) where .gitattributes does not pin LF. + fn up_to_date(have: &str, want: &str) -> bool { + have.replace("\r\n", "\n") == want + } + + #[test] + fn a_windows_checkout_of_the_reference_is_up_to_date() { + let want = markdown(); + assert!(up_to_date(&want, &want)); + assert!(up_to_date(&want.replace('\n', "\r\n"), &want)); + assert!(!up_to_date(&want.replacen("## ", "### ", 1), &want)); + } + #[test] fn the_launcher_reference_is_up_to_date() { let path = @@ -429,7 +443,7 @@ mod tests { } let have = std::fs::read_to_string(&path).unwrap_or_default(); assert!( - have == want, + up_to_date(&have, &want), "docs/launcher-commands.md is out of date: HORIZON_WRITE_DOCS=1 cargo test --manifest-path launcher/Cargo.toml the_launcher_reference" ); for tool in all() { From 574e3ca567fcdbef23818e767ba1357345a0e199 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 01:23:52 +0200 Subject: [PATCH 076/408] dedicated_server parity: the client re-sends its position as vanilla's does The harness failed about 1 run in 3 on CI with "play-trade villager false" on Horizon's side: the protocol client never saw the villager it trades with. A server pairs a player with an entity only while the entity's chunk has been sent to it, and checks again when either moves (ChunkMap.move / updatePlayers). VanillaProtocolClient sent its position once, at the spawn teleport, and never again. Horizon's first chunk batch goes out two ticks after the player is placed (after the first tick's packets, as vanilla orders them); when a busy machine held the tick thread back long enough for the client's move to be handled one tick after placement, the villager's chunk wasn't sent yet, and with no later move the villager was never paired. The 26.3 client re-sends its position every 20 ticks standing still (LocalPlayer.sendPosition, after a ServerboundClientTickEnd each tick). The parity client now does the same from the time it is loaded until its death, so an entity whose chunk comes late is paired at the next reminder, on either server. On failure the harness now adds the servers' and clients' warnings and errors to its message and the client log's tail when the client fails, and parity.py's summary prints the end of the first failing harnesses' logs, so CI shows why. Co-Authored-By: Claude Opus 5.5 --- .../parity/VanillaProtocolClient.java | 15 +++++++++ tools/parity.py | 14 ++++++-- tools/test_dedicated_server_parity.py | 32 ++++++++++++++++--- 3 files changed, 54 insertions(+), 7 deletions(-) diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java index d5e9c86fa..e37e898a3 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java @@ -65,6 +65,7 @@ import net.minecraft.network.protocol.game.ServerboundAcceptTeleportationPacket; import net.minecraft.network.protocol.game.ServerboundChatCommandPacket; import net.minecraft.network.protocol.game.ServerboundChatPacket; import net.minecraft.network.protocol.game.ServerboundChunkBatchReceivedPacket; +import net.minecraft.network.protocol.game.ServerboundClientTickEndPacket; import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; import net.minecraft.network.protocol.game.ServerboundPlayerLoadedPacket; import net.minecraft.network.protocol.handshake.ClientIntent; @@ -484,6 +485,8 @@ public final class VanillaProtocolClient { // When the dead player sent a command (ServerGamePacketListenerImpl.handleChatCommand runs it // whether the player is alive or not); it respawns once the reply came, or 3 s later. long deadCommandAt = 0; + // When the client last sent where it is. + long positionAt = 0; while (System.currentTimeMillis() < deadline) { Received r; try { @@ -536,6 +539,7 @@ public final class VanillaProtocolClient { // acceptance alone, as the 26.3 client sends. if (!respawning && step < ENTITIES) { send(new ServerboundMovePlayerPacket.PosRot(position.position(), position.yRot(), position.xRot(), false, false)); + positionAt = now; } if (!loaded) { send(new ServerboundPlayerLoadedPacket()); @@ -635,6 +639,17 @@ public final class VanillaProtocolClient { commandTree(p); } } + if (entities == null && loaded && deadCommandAt == 0 && now - positionAt >= 1000) { + // LocalPlayer.sendPosition: once its level is loaded the 26.3 client sends where it is + // every 20 ticks even standing still, and the server then checks again which entities the + // player sees (ChunkMap.move). An entity whose chunk was sent after the player's last move, + // such as the villager when the first chunks come late, is paired at the next one. The tick + // end first (Minecraft.tick sends one every tick): a server takes one position per client tick. + // Until the death: from then on the steps wait only on entities spawned for the player. + send(ServerboundClientTickEndPacket.INSTANCE); + send(new ServerboundMovePlayerPacket.Pos(position.position(), false, false)); + positionAt = now; + } if (entities != null && loaded && lastChunk > 0 && now - lastChunk > 3000 && step == 0) { // Entity mode: the harness's console summons the scene once it reads this // line; everything tracked from then on is recorded until the client leaves. diff --git a/tools/parity.py b/tools/parity.py index 68ff16e73..a1a9f4133 100644 --- a/tools/parity.py +++ b/tools/parity.py @@ -65,6 +65,7 @@ SHARED = Path(os.environ.get("PARITY_SHARED") or (LOCAL / "minecraft").resolve() MACHINE_JOBS = int(os.environ.get("PARITY_MACHINE_JOBS") or max(1, (os.cpu_count() or 4) // 2)) HOST = socket.gethostname().split(".")[0] DEFAULT_MEMORY = 3 << 30 # assumed peak for a harness that never ran here +FAILURE_TAILS, FAILURE_TAIL_LINES = 10, 30 # the summary prints the end of the first failures' logs def harness_settings(path): @@ -1361,8 +1362,17 @@ def main(): failed = sorted(name for name, record in results.items() if record["status"] != "pass") finished_run(failed) print(f"\n{len(results) - len(failed)} passed, {len(failed)} failed in {elapsed / 60:.1f} min.") - for name in failed: - print(f" {name}: {STATE_DIR / 'logs' / (name + '.log')}") + for index, name in enumerate(failed): + log = STATE_DIR / 'logs' / (name + '.log') + print(f" {name}: {log}") + # The end of a harness's output says why it failed, and CI shows only this output. + if index < FAILURE_TAILS: + try: + lines = log.read_text(encoding='utf-8', errors='replace').splitlines()[-FAILURE_TAIL_LINES:] + except OSError: + lines = [] + for line in lines: + print(f" {line[:300]}") return 1 if failed else 0 diff --git a/tools/test_dedicated_server_parity.py b/tools/test_dedicated_server_parity.py index 07d61f3d5..f45df9822 100644 --- a/tools/test_dedicated_server_parity.py +++ b/tools/test_dedicated_server_parity.py @@ -7,7 +7,9 @@ respawn_radius 0) and stops; a vanilla dedicated server and Horizon's server.properties, server-icon.png and lists. VanillaProtocolClient, a headless client made of vanilla's own codecs (any byte vanilla would not read is an error), pings each server, joins it in offline mode through -login, configuration and play, accepts the spawn teleport, receives the +login, configuration and play, accepts the spawn teleport (then, standing +still until its death, sends its position every 20 ticks as LocalPlayer +does: the server checks then which entities it sees), receives the chunks around the spawn (their bytes are compared: the world is loaded from the same files), chats, runs /list and commands that fail (`/random value 7..7`, `/random value x`, `/trigger nope`), trades, is made an operator by @@ -244,6 +246,20 @@ def console_lines(lines): return out +# What a failure's diff doesn't say: warnings, errors, panics and why a player left. +NOTABLE = re.compile(r'/(WARN|ERROR)\]|Exception|panicked|lost connection') + + +def notable_lines(path, limit=20): + """A server's notable lines from its `Done (` on (the startup warnings are every run's), or a client's.""" + try: + lines = path.read_text(encoding='utf-8', errors='replace').splitlines() + except OSError: + return [] + start = next((i for i, l in enumerate(lines) if 'Done (' in l), 0) + return [f'{path.name}: {l[:300]}' for l in lines[start:] if NOTABLE.search(l)][-limit:] + + def server_files(directory): out = [] for name in ['server.properties', 'eula.txt', 'ops.json', 'whitelist.json', 'banned-players.json', 'banned-ips.json', @@ -420,9 +436,13 @@ def main(): (world / 'playerdata').mkdir(exist_ok=True) def client(port, out): - oh.run_logged(['java', '-Xmx1g', '-Duser.timezone=UTC', '-cp', str(classes) + os.pathsep + dependencies, - 'dev.horizonlab.parity.VanillaProtocolClient', '127.0.0.1', port, PLAYER, out], build, - out.stem, timeout=300) + try: + oh.run_logged(['java', '-Xmx1g', '-Duser.timezone=UTC', '-cp', str(classes) + os.pathsep + dependencies, + 'dev.horizonlab.parity.VanillaProtocolClient', '127.0.0.1', port, PLAYER, out], build, + out.stem, timeout=300) + except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as error: + log = (build / f'{out.stem}.log').read_text(encoding='utf-8', errors='replace').splitlines() + raise AssertionError(f'{out.stem}: {error}:\n' + '\n'.join(log[-30:])) from None results = {} for label, command in [('vanilla', vanilla_server), ('horizon', horizon_server)]: @@ -448,8 +468,10 @@ def main(): if a != b: differences.append(f'chunk {key}: vanilla {a} horizon {b}') if differences or errors: + notes = [line for name in ('vanilla', 'vanilla-client', 'horizon', 'horizon-client') + for line in notable_lines(build / f'{name}.log')] raise AssertionError(f'{len([d for d in differences if d[:1] in "+-" and d[:3] not in ("+++", "---")])} differing lines ' - f'(see {build}/vanilla.txt and horizon.txt):\n' + '\n'.join(differences[:80])) + f'(see {build}/vanilla.txt and horizon.txt):\n' + '\n'.join(differences[:80] + notes)) lab.write_json(report, dict( schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(), java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], From ea424ebd52dd500173c70c18b6ad5aeecee561d3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 02:26:56 +0200 Subject: [PATCH 077/408] LAN and dedicated servers wait for the player's client to finish breaking a block ServerPlayerGameMode breaks a digging player's block only when the player's client says it is done (STOP_DESTROY_BLOCK, or the delayed destroy), or at once when it is instant. The host ran the guest's tick_mining with its own count and broke the block when that reached 1. A guest whose client ran even a tick behind lost the block before it predicted the break: no destroy particles, no break sound, and the dropped item could appear before the block vanished. lan_e2e's new digging check holds attack across six oak logs and hears six breaks, then stalls the guest for a second halfway through stone: the stone is still there on both sides when it resumes. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 7 +++- tools/lan_e2e.py | 68 +++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 6184f1626..b1777eba8 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3803,7 +3803,12 @@ impl Game<'_> { } self.crack_particle(crack.0, crack.1, state); let m = self.mining.as_mut().ok_or("mining")?; - if m.progress >= 1.0 { + // ServerPlayerGameMode breaks a player's block at once only when it is instant (START's + // insta-mine); otherwise it waits for the client's STOP_DESTROY_BLOCK + // (`guest_stop_digging`), never breaking it on its own count. Breaking it here would + // take the block from under the player's crack before the player's client predicts the + // break, so it gets neither particles nor sound. + if m.progress >= 1.0 && (self.lan_acting.is_none() || m.ticks == 1) { let pos = m.pos; self.mining = None; self.break_block(pos)?; diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 994636066..f69081945 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -4521,5 +4521,73 @@ CHECKS += ['totem'] CHECK_FNS.update(totem=check_totem) +def check_digging(host, guest, out): + """The server breaks a block a player digs only once that player's client is done + (ServerPlayerGameMode: STOP_DESTROY_BLOCK, or the delayed destroy), never on its own count, so + the player's client always breaks it first, with its particles and sound. The guest holds + attack across a wall of six oak logs with a copper axe and hears each one break; then it digs + stone with a wooden pickaxe and its game stalls for a second halfway: the stone is still there + on both sides when it resumes, and the guest's own crack finishes it.""" + gx, gy, gz = (int(v // 1) for v in pos_of(guest)) + x, y, z = gx + 3, gy, gz + 4 + heard = lambda sound: guest('status')['heard'].get(sound, 0) + at = lambda b: (f'{b[0] + 0.02:.2f}', f'{b[1] + 0.5:.2f}', f'{b[2] + 0.5:.2f}') + guest('command', command='gamemode survival') + guest('command', command='item replace entity @s weapon.mainhand with minecraft:copper_axe') + host('command', command=f'fill {x - 2} {y - 1} {z - 2} {x + 4} {y + 3} {z + 2} minecraft:air') + host('command', command=f'fill {x - 2} {y - 1} {z - 2} {x + 4} {y - 1} {z + 2} minecraft:stone') + host('command', command=f'fill {x + 2} {y} {z - 1} {x + 2} {y + 1} {z + 1} minecraft:oak_log') + guest('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}') + guest.wait(30) + logs = [(x + 2, y + dy, z + dz) for dz in (-1, 0, 1) for dy in (0, 1)] + before = heard('minecraft:block.wood.break') + guest.raw('look-at', *at(logs[0])) + guest.raw('mouse', 'left', 'down') + left = list(logs) + deadline = time.time() + 20 + while left and time.time() < deadline: + if guest.raw('block', *left[0]).get('block') != 'minecraft:oak_log': + left.pop(0) + if left: + guest.raw('look-at', *at(left[0])) + guest.raw('mouse', 'left', 'up') + guest.wait(10) + seen = {'logs_left': left, 'log_breaks_heard': heard('minecraft:block.wood.break') - before} + + # Stone with a wooden pickaxe: 23 ticks. The guest stalls for a second after about 8. + stone = (x + 2, y, z) + guest('command', command='item replace entity @s weapon.mainhand with minecraft:wooden_pickaxe') + host('command', command=f'setblock {stone[0]} {stone[1]} {stone[2]} minecraft:stone') + guest.wait(10) + before = heard('minecraft:block.stone.break') + guest.raw('look-at', *at(stone)) + guest.raw('mouse', 'left', 'down') + time.sleep(0.4) + os.kill(guest.pid, signal.SIGSTOP) + try: + time.sleep(1.0) + finally: + os.kill(guest.pid, signal.SIGCONT) + resumed = {'guest': guest.raw('block', *stone).get('block'), 'server': host.raw('block', *stone).get('block'), + 'mining': guest('state').get('mining')} + # Let go once it breaks: past it the crosshair reaches the floor. + deadline = time.time() + 5 + while guest.raw('block', *stone).get('block') == 'minecraft:stone' and time.time() < deadline: + pass + guest.raw('mouse', 'left', 'up') + guest.wait(10) + seen.update(resumed=resumed, stone_after=host.raw('block', *stone).get('block'), + stone_breaks_heard=heard('minecraft:block.stone.break') - before) + guest.shot(out, 'digging') + assert not left and seen['log_breaks_heard'] == 6, f'the server broke logs before the guest did: {seen}' + assert resumed['guest'] == resumed['server'] == 'minecraft:stone', f'the server broke the stone while the guest stalled: {seen}' + assert seen['stone_after'] == 'minecraft:air' and seen['stone_breaks_heard'] == 1, f'the guest did not break the stone: {seen}' + return seen + + +CHECKS += ['digging'] +CHECK_FNS.update(digging=check_digging) + + if __name__ == '__main__': main() From 14461c1d96443877e21fdd7fbc6be810d0c73dd6 Mon Sep 17 00:00:00 2001 From: Ganer Date: Fri, 23 Oct 2026 19:44:13 -0500 Subject: [PATCH 078/408] fix(client): preserve behavior while clearing Rust 1.90 Clippy errors --- .../examples/probe/first_person_probe.rs | 2 +- crates/horizon-client/src/containers.rs | 14 +++++----- crates/horizon-client/src/game.rs | 10 +++---- crates/horizon-client/src/game/chat.rs | 7 ++--- crates/horizon-client/src/game/debug_keys.rs | 2 +- crates/horizon-client/src/game/dragon.rs | 28 ++++++++++++++++--- crates/horizon-client/src/game/explosion.rs | 2 +- .../horizon-client/src/game/lan_vehicles.rs | 4 ++- crates/horizon-client/src/game/remote.rs | 5 ++-- crates/horizon-client/src/items.rs | 26 ++++++++--------- crates/horizon-client/src/mobs/ai.rs | 8 +++--- crates/horizon-client/src/mobs/axolotl.rs | 17 ++++++----- crates/horizon-client/src/mobs/bee.rs | 2 +- crates/horizon-client/src/mobs/living.rs | 6 ++-- .../horizon-client/src/mobs/monster_brain.rs | 2 +- crates/horizon-client/src/mobs/raider.rs | 2 +- .../horizon-client/src/mobs/villager_brain.rs | 6 ++-- crates/horizon-client/src/mobs/warden.rs | 2 +- crates/horizon-client/src/particles.rs | 2 +- crates/horizon-client/src/streaming.rs | 6 ++++ 20 files changed, 90 insertions(+), 63 deletions(-) diff --git a/crates/horizon-client/examples/probe/first_person_probe.rs b/crates/horizon-client/examples/probe/first_person_probe.rs index cb4c38e58..38829714c 100644 --- a/crates/horizon-client/examples/probe/first_person_probe.rs +++ b/crates/horizon-client/examples/probe/first_person_probe.rs @@ -203,7 +203,7 @@ impl HandWorld for Probe<'_> { let item = self.stack(Hand::Main).effective().0; // Item.canDestroyBlock: swords' tools cannot destroy in creative. let sword = item.ends_with("_sword"); - let ok = !(sword && self.creative) && !self.is_air(pos); + let ok = (!sword || !self.creative) && !self.is_air(pos); if ok { self.blocks.insert(pos, "minecraft:air".into()); } diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 6ecdf0d93..de2e1b2e9 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -382,7 +382,7 @@ impl Providers { ); Self { ints, floats } } - fn eval(&self, v: &Value, fast: bool, table: &HashMap, depth: u32) -> f64 { + fn eval(v: &Value, fast: bool, table: &HashMap, depth: u32) -> f64 { if depth > 16 { return 0.0; } @@ -390,10 +390,10 @@ impl Providers { Value::Number(n) => n.as_f64().unwrap_or(0.0), Value::String(name) => table .get(name) - .map_or(0.0, |v| self.eval(v, fast, table, depth + 1)), + .map_or(0.0, |v| Self::eval(v, fast, table, depth + 1)), Value::Object(o) => { let f = - |k: &str| self.eval(o.get(k).unwrap_or(&Value::Null), fast, table, depth + 1); + |k: &str| Self::eval(o.get(k).unwrap_or(&Value::Null), fast, table, depth + 1); match o.get("type").and_then(Value::as_str).unwrap_or("") { "minecraft:div" => { let r = f("right"); @@ -425,14 +425,14 @@ impl Providers { } /// A plain `context_int_provider` value or reference (no context conditions). pub fn int_value(&self, v: &Value) -> i32 { - self.eval(v, false, &self.ints, 0) as i32 + Self::eval(v, false, &self.ints, 0) as i32 } /// A plain `context_float_provider` value or reference; `default` when absent. pub fn float_value(&self, v: &Value, default: f32) -> f32 { if v.is_null() { default } else { - self.eval(v, false, &self.floats, 0) as f32 + Self::eval(v, false, &self.floats, 0) as f32 } } #[cfg(test)] @@ -446,14 +446,14 @@ impl Providers { items .get(&stack.item) .and_then(|i| i.fuel.as_ref()) - .map_or(0, |(time, _)| self.eval(time, fast, &self.ints, 0) as i32) + .map_or(0, |(time, _)| Self::eval(time, fast, &self.ints, 0) as i32) } pub fn speed(&self, items: &Items, stack: &ItemStack, fast: bool) -> f32 { items .get(&stack.item) .and_then(|i| i.fuel.as_ref()) .map_or(1.0, |(_, speed)| { - self.eval(speed, fast, &self.floats, 0) as f32 + Self::eval(speed, fast, &self.floats, 0) as f32 }) } } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 6184f1626..645e6483c 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1741,10 +1741,10 @@ impl Game<'_> { let state = self.world.block(pos[0], pos[1], pos[2]); let f = self.res.facts().get(state); if !self.res.facts().is_air(state) - && !(f.fluid != Fluid::None - && !f.waterlogged - && &*f.name != "minecraft:kelp" - && f.render_shape != horizon_client::blocks::RenderShape::Model) + && (f.fluid == Fluid::None + || f.waterlogged + || &*f.name == "minecraft:kelp" + || f.render_shape == horizon_client::blocks::RenderShape::Model) && !matches!( &*f.name, "minecraft:water" | "minecraft:lava" | "minecraft:bubble_column" @@ -3429,7 +3429,7 @@ impl Game<'_> { return Ok(true); } // Block foods attempt placement before starting consumption. - if !on_block && !(info.block.is_some() && block_hit.is_some()) && self.start_eating(&info) { + if !on_block && (info.block.is_none() || block_hit.is_none()) && self.start_eating(&info) { return Ok(true); } // BoatItem.use also performs its own fluid/block raycast. diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 0247896f5..91ddaf74a 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -1,6 +1,6 @@ //! Chat, the command registries and the per-world state behind commands //! (game rules, the world clock, difficulty), bound to the game. -use super::{Dim, Game, Screen}; +use super::{Game, Screen}; use horizon_client::{ chat::{Chat, ChatAction, ChatScreen, Commands, SYSTEM_INDICATOR}, command::Registries, @@ -685,10 +685,7 @@ impl Game<'_> { /// Advance the overworld clock (ServerClockManager.tick) when /// `advance_time` allows it. pub(super) fn advance_clock(&mut self) { - if !self.ui.rules.bool("advance_time") - || self.ui.clock.paused - || self.dim == Dim::Nether && false - { + if !self.ui.rules.bool("advance_time") || self.ui.clock.paused { return; } let c = &mut self.ui.clock; diff --git a/crates/horizon-client/src/game/debug_keys.rs b/crates/horizon-client/src/game/debug_keys.rs index 553cd0d96..be9f76b3f 100644 --- a/crates/horizon-client/src/game/debug_keys.rs +++ b/crates/horizon-client/src/game/debug_keys.rs @@ -38,7 +38,7 @@ impl DebugHost for Host<'_, '_> { // the menu as it always has (key_pressed). let g = &mut *self.game; if without_menu && g.screen == Screen::Playing { - g.pause_menu = !(g.has_singleplayer_server() && !g.is_published()); + g.pause_menu = !g.has_singleplayer_server() || g.is_published(); g.screen = Screen::Paused; g.capture(false); g.mining = None; diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index c6f5d419b..cd2de3736 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -27,6 +27,12 @@ const CRYSTAL_IDS: u32 = SPECIAL + 16; const FIGHT_FILE: &str = "data/minecraft/ender_dragon_fight.dat"; const MAX_HEALTH: f32 = 200.0; +/// Preserve the ordered double comparisons from vanilla: a NaN squared +/// distance fails both comparisons and must not be treated as out of range. +fn target_distance_outside_range(distance_squared: f64) -> bool { + !distance_squared.is_nan() && !(100.0..=22500.0).contains(&distance_squared) +} + #[derive(Default)] pub(super) struct Fight { loaded: bool, @@ -1286,7 +1292,7 @@ impl Game<'_> { clockwise, } => { let dt = far(*target); - if dt < 100.0 || dt > 22500.0 || collided { + if target_distance_outside_range(dt) || collided { let done = path.as_ref().is_some_and(|p| p.0.done()); let mut chosen = false; if done { @@ -1356,7 +1362,7 @@ impl Game<'_> { *target = Some(Vec3::new(pp.x, pp.y + ho, pp.z)); } let dt = far(*target); - if dt < 100.0 || dt > 22500.0 { + if target_distance_outside_range(dt) { if path.as_ref().is_none_or(|p| p.0.done()) { *path = self.ring_path(clockwise).map(PathBox); } @@ -1393,7 +1399,7 @@ impl Game<'_> { } Phase::LandingApproach { path, target } => { let dt = far(*target); - if dt < 100.0 || dt > 22500.0 || collided { + if target_distance_outside_range(dt) || collided { if path.as_ref().is_none_or(|p| p.0.done()) { let current = self.closest_node(pos.x, pos.y, pos.z); // NEAR_EGG_TARGETING: the enemy nearest the egg. @@ -1577,7 +1583,7 @@ impl Game<'_> { } } else { let dt = far(*target); - if dt < 100.0 || dt > 22500.0 { + if target_distance_outside_range(dt) { *since += 1; } } @@ -3263,4 +3269,18 @@ mod tests { let t = nearest_enemy(&players, false, Vec3::new(9.0, 64.0, 0.0), None, |_| true); assert_eq!(t.map(|p| p.who), Some(FightWho::Host)); } + #[test] + fn target_distance_respects_nan_and_exact_boundaries() { + for (distance, expected) in [ + (f64::NAN, false), + (f64::NEG_INFINITY, true), + (99.0, true), + (100.0, false), + (22500.0, false), + (22501.0, true), + (f64::INFINITY, true), + ] { + assert_eq!(super::target_distance_outside_range(distance), expected); + } + } } diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 6ecba3a54..e3baa76fc 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -306,7 +306,7 @@ impl Game<'_> { { outcome = o; } - if !spectator && !(creative && flying) { + if !spectator && (!creative || !flying) { p.velocity = Vec3::new( p.velocity.x + dir[0] * power, p.velocity.y + dir[1] * power, diff --git a/crates/horizon-client/src/game/lan_vehicles.rs b/crates/horizon-client/src/game/lan_vehicles.rs index 8198f288e..71e9936a5 100644 --- a/crates/horizon-client/src/game/lan_vehicles.rs +++ b/crates/horizon-client/src/game/lan_vehicles.rs @@ -205,7 +205,9 @@ impl Game<'_> { return; }; let [x, y, z] = p.position; - if !(x.is_finite() && y.is_finite() && z.is_finite()) + if !x.is_finite() + || !y.is_finite() + || !z.is_finite() || !p.yaw.is_finite() || !p.pitch.is_finite() { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 32613e42a..7859af6fc 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -544,7 +544,7 @@ impl Game<'_> { /// (`LivingEntity.forceAddEffect`): the effect replaces any of its kind. /// Other entities' effects are not shown. fn remote_effect(&mut self, p: &play::UpdateMobEffect) { - if !self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) { + if self.remote.as_ref().is_none_or(|r| r.entity_id != p.id) { return; } let Some(id) = self.remote_effect_id(p.effect) else { @@ -4247,8 +4247,7 @@ impl Game<'_> { /// Keys with a multiplayer meaning; returns true when consumed. pub(super) fn remote_key(&mut self, key: KeyCode) -> Result { if self.screen != Screen::Playing { - if key == KeyCode::KeyE && self.screen == Screen::Inventory - || key == KeyCode::Escape && self.screen == Screen::Inventory + if (key == KeyCode::KeyE || key == KeyCode::Escape) && self.screen == Screen::Inventory { self.remote_close_container(); self.screen = Screen::Playing; diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index abbc1241f..95e7e2c42 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -1051,7 +1051,7 @@ impl LootContext<'_> { continue; } // LootPool: rolls.getInt (Mth.randomBetweenInclusive for uniform rolls). - let rolls = ctx.int_number(&pool["rolls"], random).max(0) as u32; + let rolls = LootContext::int_number(&pool["rolls"], random).max(0) as u32; for _ in 0..rolls { let mut produced = Vec::new(); ctx.choose( @@ -1085,7 +1085,7 @@ impl LootContext<'_> { fn enchantment_level(&self, id: &str) -> u32 { self.held.map_or(0, |h| h.enchantment_level(id)) } - fn number(&self, v: &Value, random: &mut R) -> f32 { + fn number(v: &Value, random: &mut R) -> f32 { match v { Value::Number(n) => n.as_f64().unwrap_or(0.0) as f32, Value::Object(o) => match o @@ -1097,8 +1097,8 @@ impl LootContext<'_> { o.get("value").and_then(Value::as_f64).unwrap_or(0.0) as f32 } "minecraft:uniform" => { - let min = self.number(o.get("min").unwrap_or(&Value::Null), random); - let max = self.number(o.get("max").unwrap_or(&Value::Null), random); + let min = Self::number(o.get("min").unwrap_or(&Value::Null), random); + let max = Self::number(o.get("max").unwrap_or(&Value::Null), random); // UniformGenerator.getFloat / getInt (Mth.nextInt) differ; use int for counts. if max <= min { min @@ -1107,8 +1107,8 @@ impl LootContext<'_> { } } "minecraft:binomial" => { - let n = self.number(o.get("n").unwrap_or(&Value::Null), random) as u32; - let p = self.number(o.get("p").unwrap_or(&Value::Null), random); + let n = Self::number(o.get("n").unwrap_or(&Value::Null), random) as u32; + let p = Self::number(o.get("p").unwrap_or(&Value::Null), random); (0..n).filter(|_| random.next_float() < p).count() as f32 } _ => 1.0, @@ -1116,22 +1116,22 @@ impl LootContext<'_> { _ => 1.0, } } - fn int_number(&self, v: &Value, random: &mut R) -> i32 { + fn int_number(v: &Value, random: &mut R) -> i32 { if let Value::Object(o) = v && o.get("type") .and_then(Value::as_str) .unwrap_or("minecraft:uniform") == "minecraft:uniform" { - let min = self.int_number(o.get("min").unwrap_or(&Value::Null), random); - let max = self.int_number(o.get("max").unwrap_or(&Value::Null), random); + let min = Self::int_number(o.get("min").unwrap_or(&Value::Null), random); + let max = Self::int_number(o.get("max").unwrap_or(&Value::Null), random); return if max <= min { min } else { min + random.next_int_bound(max - min + 1).unwrap_or(0) }; } - self.number(v, random).round() as i32 + Self::number(v, random).round() as i32 } fn condition(&self, c: &Value, random: &mut R) -> bool { let (kind, c) = match c { @@ -1157,7 +1157,7 @@ impl LootContext<'_> { .into_iter() .flatten() .all(|t| self.condition(t, random)), - "minecraft:random_chance" => random.next_float() < self.number(&c["chance"], random), + "minecraft:random_chance" => random.next_float() < Self::number(&c["chance"], random), "minecraft:table_bonus" => { // BonusLevelTableCondition: chances[min(level, len - 1)]. let level = @@ -1378,7 +1378,7 @@ impl LootContext<'_> { } match f["type"].as_str().or(f["function"].as_str()).unwrap_or("") { "minecraft:set_count" => { - let n = self.int_number(&f["count"], random); + let n = Self::int_number(&f["count"], random); let base = if f["add"].as_bool() == Some(true) { stack.count as i32 } else { @@ -1421,7 +1421,7 @@ impl LootContext<'_> { // Attacker's level x count, rounded (looting). let level = self.enchantment_level(f["enchantment"].as_str().unwrap_or("")); if level > 0 && self.killed_by_player && self.block.is_empty() { - let add = level as f32 * self.number(&f["count"], random); + let add = level as f32 * Self::number(&f["count"], random); stack.count = (stack.count as i32 + add.round() as i32).max(0) as u32; if let Some(limit) = f["limit"].as_i64().filter(|l| *l > 0) { stack.count = stack.count.min(limit as u32); diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index ae4aa91a6..97da5ea06 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -405,7 +405,7 @@ pub fn tick( } // Mob.tickHeadTurn -> BodyRotationControl.clientTick (a frozen // creaking's waits). - if m.alive() && !(super::creaking::is_creaking(m) && !super::creaking::can_move(m)) { + if m.alive() && (!super::creaking::is_creaking(m) || super::creaking::can_move(m)) { m.body_rotation_tick(); } events.append(&mut m.outbox); @@ -752,8 +752,8 @@ impl Mob { pub fn pushable(&self) -> bool { self.alive() && !matches!(self.species(), Species::Bat | Species::Shulker) - && !(self.kind.flags.climber && self.climbing) - && !(self.species() == Species::Creaking && !super::creaking::can_move(self)) + && (!self.kind.flags.climber || !self.climbing) + && (self.species() != Species::Creaking || super::creaking::can_move(self)) } } /// LivingEntity.onClimbable for the pusher (Spider.onClimbable: climbing a wall). @@ -780,7 +780,7 @@ fn push_entities(m: &mut Mob, w: &MobWorld, events: &mut Vec) { let self_pushable = m.alive() && m.species() != Species::Shulker && !on_climbable(m, w) - && !(m.species() == Species::Creaking && !super::creaking::can_move(m)); + && (m.species() != Species::Creaking || super::creaking::can_move(m)); let mut targets: Vec<(Who, Vec3)> = Vec::new(); if let Some(p) = &w.player // Entity.push: passengers of the same vehicle never push each other. diff --git a/crates/horizon-client/src/mobs/axolotl.rs b/crates/horizon-client/src/mobs/axolotl.rs index 55f15717c..e4a639768 100644 --- a/crates/horizon-client/src/mobs/axolotl.rs +++ b/crates/horizon-client/src/mobs/axolotl.rs @@ -166,13 +166,16 @@ mod axolotl_parity_tests { ] { let mut expected = LegacyRandom::new(seed); let mut actual = LegacyRandom::new(seed); - let result = !no_ai - && expected.next_int_bound(3).unwrap() == 0 - && ((expected.next_int_bound(3).unwrap() as f32) < 2.0 || 4.0f32 / 14.0 < 0.5) - && 2.0 < 4.0 - && water - && entity - && !already; + // The second draw is intentionally consumed even though + // the fixed 4.0 / 14.0 threshold always makes this branch + // true. Removing it changes the native RNG sequence. + let first_gate = !no_ai && expected.next_int_bound(3).unwrap() == 0; + let result = if first_gate { + let _second_draw = expected.next_int_bound(3).unwrap(); + water && entity && !already + } else { + false + }; assert_eq!( roll_play_dead(&mut actual, no_ai, 4.0, 14.0, 2.0, water, entity, already), result diff --git a/crates/horizon-client/src/mobs/bee.rs b/crates/horizon-client/src/mobs/bee.rs index cdb0318bc..018368604 100644 --- a/crates/horizon-client/src/mobs/bee.rs +++ b/crates/horizon-client/src/mobs/bee.rs @@ -1046,7 +1046,7 @@ impl Goal for GrowCrop { } fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { // The 0.3 roll comes only after the crop count: it draws randomness. - let usable = !get(m).is_some_and(|b| b.crops_grown >= 10) + let usable = get(m).is_none_or(|b| b.crops_grown < 10) && m.random.next_float() >= 0.3 && has_nectar(m) && hive_valid(m, cx.w); diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index d5b3c7091..f16e0e18d 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -167,9 +167,9 @@ impl MobWorld<'_> { let Ok(block) = self.collision.collision_block(state) else { continue; }; - if !block.large_collision_shape - && !block.moving_piston - && !(column && meets(Axis::Y, y)) + if !(block.large_collision_shape + || block.moving_piston + || (column && meets(Axis::Y, y))) { continue; } diff --git a/crates/horizon-client/src/mobs/monster_brain.rs b/crates/horizon-client/src/mobs/monster_brain.rs index 1099e0bc3..59fe04ef6 100644 --- a/crates/horizon-client/src/mobs/monster_brain.rs +++ b/crates/horizon-client/src/mobs/monster_brain.rs @@ -712,7 +712,7 @@ impl B { .is_some_and(|l| l.contains(&Who::Player)); !reachable }; - if !(can_attack(m, cx.w, target) && !tired && alive && !stop_when) { + if !can_attack(m, cx.w, target) || tired || !alive || stop_when { set_attack_target(m, None); } *running = true; diff --git a/crates/horizon-client/src/mobs/raider.rs b/crates/horizon-client/src/mobs/raider.rs index 1c3f7ff94..6c3ab9b64 100644 --- a/crates/horizon-client/src/mobs/raider.rs +++ b/crates/horizon-client/src/mobs/raider.rs @@ -426,7 +426,7 @@ impl Goal for MoveThroughVillage { self.visited.remove(0); } let Some(s) = state(m) else { return false }; - if !(s.active_raid && !s.raid_over) || m.ai.target.is_some() { + if !s.active_raid || s.raid_over || m.ai.target.is_some() { return false; } let Some(homes) = s.homes.clone() else { diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index 194bd75ff..adedd56c0 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -2806,8 +2806,8 @@ impl B { let on_or_over = jumpable(here) || jumpable([here[0], here[1] - 1, here[2]]); let still = m.is_baby() && bed.is_some_and(jumpable) - && !(!on_or_over && *time_left <= 0) - && !(on_or_over && *jumps <= 0); + && (on_or_over || *time_left > 0) + && (!on_or_over || *jumps > 0); if !still { self.do_stop(m, cx); return; @@ -3196,7 +3196,7 @@ fn follow_trading_condition(m: &Mob, w: &MobWorld) -> bool { m.extra.flag2 && m.alive() && !m.fluids.in_water - && !(m.hurt_time > 0) + && m.hurt_time <= 0 && w.player .as_ref() .is_some_and(|p| m.distance_sqr(p.position) <= 16.0) diff --git a/crates/horizon-client/src/mobs/warden.rs b/crates/horizon-client/src/mobs/warden.rs index f78ceff25..11161ef7c 100644 --- a/crates/horizon-client/src/mobs/warden.rs +++ b/crates/horizon-client/src/mobs/warden.rs @@ -457,7 +457,7 @@ pub fn can_receive_vibration(m: &Mob, _now: i64, ctx: &Context) -> bool { && m.alive() && !st.brain.mem.vibration_cooldown.present() && !digging_or_emerging(m) - && !(ctx.living && !ctx.targetable) + && (!ctx.living || ctx.targetable) } /// `VibrationSystem.Listener.handleGameEvent` for the warden: a free /// listener within 16 blocks of its eyes schedules what it can hear. diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index a5df97258..31e23b87b 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -3223,7 +3223,7 @@ impl ParticleEngine { } => { p.base_tick(level); let (fluid, source) = level.fluid_source(ParticleLevel::block_at(p.position)); - if !p.removed && !(fluid == Fluid::Water && source) { + if !(p.removed || (fluid == Fluid::Water && source)) { p.removed = true; } if !p.removed && p.position[1] >= y_end { diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 15ed1674e..92d37483b 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -641,6 +641,12 @@ impl Streaming { }); self.shared.ready.notify_one(); } + // Proto arrays are large; keep ownership of the incoming heap allocation + // instead of moving all nine chunks onto a transient stack frame. + #[expect( + clippy::boxed_local, + reason = "keep nine large Proto values heap resident" + )] fn receive_decorated(&mut self, x: i32, z: i32, region: Box<[Proto; 9]>) { self.generation_scan.exhausted = false; self.decorating -= 1; From 969bcec6c9d3a3bde1c37efe269c9c0d20cba721 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 02:27:09 +0200 Subject: [PATCH 079/408] Villagers open and close doors on their paths InteractWithDoor was a stub, so a villager whose path went through a closed oak door walked into it and stayed there. In generated villages, villagers who were inside a house never reached a job site, a bed or the meeting point. Like vanilla, a villager now opens the closed mob-interactable doors on its next path step (DoorBlock.setOpen: both halves, the door sound and the block_open game event), remembers the door it leaves and the doors it opened, and closes them once it is more than one step past them, unless another villager within 2 blocks is walking through. A villager going to sleep closes them too. The mob events apply after the mob loop, so the door opens one tick later than in vanilla, where DoorBlock.setOpen changes the world during the villager's brain tick. lan_e2e's new doors check shuts a villager in a room with a closed door and a free composter outside. Before, it never opened the door; now it opens it, becomes a farmer, and the door is closed again on the server and on the guest. Co-Authored-By: Claude Opus 5.5 --- .../examples/probe/mob_ai_probe.rs | 25 +++++++ crates/horizon-client/src/game/creatures.rs | 5 ++ crates/horizon-client/src/mobs.rs | 6 ++ .../horizon-client/src/mobs/villager_brain.rs | 70 ++++++++++++++++++- crates/horizon-world/src/level/interact.rs | 27 +++++++ tools/lan_e2e.py | 52 +++++++++++++- 6 files changed, 182 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/examples/probe/mob_ai_probe.rs b/crates/horizon-client/examples/probe/mob_ai_probe.rs index d773a509b..c015b8fdf 100644 --- a/crates/horizon-client/examples/probe/mob_ai_probe.rs +++ b/crates/horizon-client/examples/probe/mob_ai_probe.rs @@ -1323,6 +1323,31 @@ pub fn main() -> horizon_client::Result<()> { world.set(at[0], at[1], at[2], registry.resolve(&st)?)?; } } + // Doors villagers opened or closed (DoorBlock.setOpen), both halves. + let doors: Vec<([i32; 3], bool)> = events + .iter() + .filter_map(|e| match e { + MobEvent::SetDoorOpen { pos, open } => Some((*pos, *open)), + _ => None, + }) + .collect(); + for (at, open) in doors { + let Some(half) = registry + .state(world.block(at[0], at[1], at[2])) + .and_then(|s| s.properties.get("half").cloned()) + else { + continue; + }; + let other = if half == "lower" { 1 } else { -1 }; + for y in [at[1], at[1] + other] { + if let Some(mut st) = registry.state(world.block(at[0], y, at[2])).cloned() + && st.properties.contains_key("open") + { + st.properties.insert("open".to_owned(), open.to_string()); + world.set(at[0], y, at[2], registry.resolve(&st)?)?; + } + } + } mobs.append(&mut born); mobs.append(&mut added); for e in &heart_events { diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 6f47fd632..7a685c48d 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1007,6 +1007,11 @@ impl Game<'_> { MobEvent::SetBlock { pos, state } => { self.world.set(pos[0], pos[1], pos[2], state)? } + MobEvent::SetDoorOpen { pos, open } => { + let pos = BlockPos::new(pos[0], pos[1], pos[2]); + self.with_level(|b, level, ticks| b.set_door_open(level, ticks, pos, open)); + self.process_level_events()?; + } MobEvent::SetBlockName { pos, name, effect } => { if effect { let old = self.world.block(pos[0], pos[1], pos[2]); diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index a61ea2a11..d0cff94dd 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -987,6 +987,12 @@ pub enum MobEvent { pos: [i32; 3], state: horizon_world::registry::BlockStateId, }, + /// `DoorBlock.setOpen` by a mob (`InteractWithDoor`): the door opens or + /// closes, both halves, with its sound and game event. + SetDoorOpen { + pos: [i32; 3], + open: bool, + }, /// Destroy a block, dropping nothing (sheep eating grass becomes dirt via SetBlock). BreakBlock { pos: [i32; 3], diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index df19d8fed..5b1fef7da 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -2252,6 +2252,7 @@ impl B { } t.begin(cx.lr, cx.now); if now > *next_ok { + close_doors(m, cx, None, None); if super::villager::start_sleeping(m, home, w) { mem(m).last_slept.set(now); } @@ -3492,7 +3493,74 @@ fn walk_to_block_memory( } /// `InteractWithDoor`: open the doors on the path, close the ones passed. fn interact_with_doors(m: &mut Mob, cx: &mut Bx, from: PathNode, to: PathNode) { - let _ = (m, cx, from, to); + let (from, to) = ([from.x, from.y, from.z], [to.x, to.y, to.z]); + // The door being left is remembered even when it is open already; the + // one ahead only when this villager opens it. + for (p, always) in [(from, true), (to, false)] { + let Some(open) = door_open(cx.w, p) else { + continue; + }; + if !open { + cx.events.push(MobEvent::SetDoorOpen { pos: p, open: true }); + } + if always || !open { + remember_door(m, p); + } + } + close_doors(m, cx, Some(from), Some(to)); +} +/// Whether the block at `p` is a door mobs open (`MOB_INTERACTABLE_DOORS`), and +/// then whether it is open. +fn door_open(w: &MobWorld, p: [i32; 3]) -> Option { + let name = w.block_name(p[0], p[1], p[2]); + (name.ends_with("_door") && w.has_tag("minecraft:mob_interactable_doors", name)) + .then(|| w.prop(p[0], p[1], p[2], "open") == Some("true")) +} +fn remember_door(m: &mut Mob, p: [i32; 3]) { + let doors = &mut mem(m).doors_to_close; + match doors.get_mut() { + Some(list) if list.contains(&p) => {} + Some(list) => list.push(p), + None => doors.set(vec![p]), + } +} +/// `InteractWithDoor.closeDoorsThatIHaveOpenedOrPassedThrough`: the remembered +/// doors other than the two of the step being taken are forgotten, and closed +/// when still open, near (3 blocks) and no other villager within 2 blocks of +/// one is passing through it. +fn close_doors(m: &mut Mob, cx: &mut Bx, from: Option<[i32; 3]>, to: Option<[i32; 3]>) { + let Some(doors) = mem(m).doors_to_close.get().cloned() else { + return; + }; + let near = mem(m).mobs.value().unwrap_or_default(); + let mut kept = Vec::new(); + for door in doors { + if from == Some(door) || to == Some(door) { + kept.push(door); + continue; + } + if !closer_to_center(door, m.position, 3.0) || door_open(cx.w, door) != Some(true) { + continue; + } + let passing = near.iter().any(|&who| { + let Who::Mob(id) = who else { return false }; + cx.w.seen(id).is_some_and(|s| { + s.species == Species::Villager + && closer_to_center(door, s.position, 2.0) + && s.villager + .as_ref() + .and_then(|v| v.path_nodes) + .is_some_and(|(prev, next)| prev.is_some_and(|p| p == door || next == door)) + }) + }); + if !passing { + cx.events.push(MobEvent::SetDoorOpen { + pos: door, + open: false, + }); + } + } + mem(m).doors_to_close.set(kept); } /// The scan order of POI candidates (before the nearest-first sort). fn pois_scan_order(_m: &Mob, found: &[(Poi, [i32; 3])]) -> Vec { diff --git a/crates/horizon-world/src/level/interact.rs b/crates/horizon-world/src/level/interact.rs index c38d81f26..b8251ba46 100644 --- a/crates/horizon-world/src/level/interact.rs +++ b/crates/horizon-world/src/level/interact.rs @@ -543,6 +543,33 @@ impl Behaviours { self.sim(level, ticks) .use_without_item(pos, face, hit, player) } + /// `DoorBlock.setOpen`: a mob opens or closes the door at `pos` (either half), with its sound + /// and game event. False when it is no door or already so. + pub fn set_door_open( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + open: bool, + ) -> bool { + let state = level.block_state(pos); + if !self.data(state).is(Class::Door) || self.table.bool(state, self.props.open) == open { + return false; + } + let mut sim = self.sim(level, ticks); + let next = self.table.set_bool(state, self.props.open, open); + sim.set_block(pos, next, 10); + sim.door_sound(pos, next, open); + sim.game_event( + pos, + if open { + "minecraft:block_open" + } else { + "minecraft:block_close" + }, + ); + true + } /// `BlockState.useItemOn` with `item` in the main hand, then, when the /// block asks to try with an empty hand (the default), `useWithoutItem`. /// `SweetBerryBushBlock.useItemOn` passes bone meal on a bush that can diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 6c338b104..2b19e8f0c 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -245,7 +245,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'styles', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'sidebar', 'border', 'particles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'hands', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'styles', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'sidebar', 'border', 'particles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'doors', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'hands', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] class Game: @@ -4140,6 +4140,54 @@ def check_growth(host, guest, out): return detail +def check_doors(host, guest, out): + """A villager shut in a room opens its oak door on its way to a free composter outside + (InteractWithDoor), takes the composter as its job site and closes the door behind it; the + guest sees the door open and close again.""" + gx, gy, gz = (int(v // 1) for v in pos_of(guest)) + x, y, z = gx + 4, gy, gz - 8 + lower, upper, composter, marker = (x + 2, y, z), (x + 2, y + 1, z), (x + 7, y, z), (x + 7, y, z + 2) + tag = 'dg_door_villager' + farmer = (f'execute if entity @e[type=minecraft:villager,tag={tag},' + f'nbt={{VillagerData:{{profession:"minecraft:farmer"}}}}] run setblock {marker[0]} {marker[1]} {marker[2]} ' + 'minecraft:gold_block') + seen = {'opened': False, 'farmer': False, 'closed': None} + try: + host('command', command='time set 2000') + host('command', command=f'fill {x - 3} {y - 1} {z - 3} {x + 9} {y - 1} {z + 3} minecraft:stone') + host('command', command=f'fill {x - 3} {y} {z - 3} {x + 9} {y + 3} {z + 3} minecraft:air') + host('command', command=f'fill {x - 2} {y} {z - 2} {x + 2} {y + 2} {z + 2} minecraft:oak_planks') + host('command', command=f'fill {x - 1} {y} {z - 1} {x + 1} {y + 1} {z + 1} minecraft:air') + for (bx, by, bz), half in ((lower, 'lower'), (upper, 'upper')): + host('command', command=f'setblock {bx} {by} {bz} minecraft:oak_door[facing=east,half={half},' + 'hinge=left,open=false,powered=false]') + host('command', command=f'setblock {composter[0]} {composter[1]} {composter[2]} minecraft:composter') + host('command', command=f'summon minecraft:villager {x + 0.5} {y} {z + 0.5} {{Tags:["{tag}"],' + 'PersistenceRequired:1b,VillagerData:{profession:"minecraft:none",level:1,' + 'type:"minecraft:plains"}}') + for _ in range(120): + guest.wait(10) + seen['opened'] = seen['opened'] or state_of(guest, lower, 'open') == 'true' + host('command', command=farmer) + if host.raw('block', *marker).get('block') == 'minecraft:gold_block': + seen['farmer'] = True + break + seen['closed'] = wait_state(guest, lower, 'open', 'false', 200) == 'false' + seen['server_door'] = state_of(host, lower, 'open') + guest.raw('look-at', f'{lower[0] + 0.5:.2f}', f'{lower[1] + 1:.2f}', f'{lower[2] + 0.5:.2f}') + guest.wait(10) + guest.shot(out, 'doors') + finally: + host('command', command=f'kill @e[type=minecraft:villager,tag={tag}]') + host('command', command=f'fill {x - 3} {y} {z - 3} {x + 9} {y + 3} {z + 3} minecraft:air') + host('command', command='time set day') + assert seen['opened'], f'the villager never opened its door: {seen}' + assert seen['farmer'], f'the villager did not take the composter outside: {seen}' + assert seen['closed'] and seen['server_door'] == 'false', f'the villager left its door open: {seen}' + return seen + + + def check_light(host, guest, out): gx, gy, gz = (int(v // 1) for v in pos_of(guest)) results = {} @@ -4401,7 +4449,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'eat': check_eat, 'eating': check_eating, 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast, 'light': check_light, 'plates': check_plates, 'swings': check_swings, - 'cracks': check_cracks, 'time': check_time, 'growth': check_growth, + 'cracks': check_cracks, 'time': check_time, 'growth': check_growth, 'doors': check_doors, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, From 5205b909f79740ae620a3892aeec58407f1a80c3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 05:33:52 +0200 Subject: [PATCH 080/408] Villagers, llamas, bees, allays and copper golems search the full path budget PathNavigation.setRequiredPathLength calls updatePathfinderMaxVisitedNodes, so a villager's PathFinder visits up to max(follow range, 48) * 16 = 768 nodes, not the 256 of its follow range alone. Horizon always used follow range * 16, so a villager gave up on any job site, bed or bell whose path needed more than 256 nodes: in the seed 12345 village it never found the way round to the mason's stonecutter door. Navigation now keeps PathFinder.maxVisitedNodes: the base follow range times 16 when the mob is made, then max(follow range, required path length) * 16 after setRequiredPathLength and after any follow range change (Mob.onAttributeUpdated). A happy ghast that grows up or becomes a baby gets a new navigation, as in vanilla. mob_ai: villager_job_in_box, a composter inside a stone box whose doorway faces away from the villager. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/sculk.rs | 1 + crates/horizon-client/src/mobs.rs | 2 ++ crates/horizon-client/src/mobs/allay.rs | 2 +- crates/horizon-client/src/mobs/bee.rs | 2 +- .../horizon-client/src/mobs/copper_golem.rs | 2 +- .../horizon-client/src/mobs/creaking_heart.rs | 1 + crates/horizon-client/src/mobs/finalize.rs | 5 ++++- crates/horizon-client/src/mobs/happy_ghast.rs | 6 +++++- crates/horizon-client/src/mobs/llama.rs | 2 +- crates/horizon-client/src/mobs/nav.rs | 19 +++++++++++++++++-- crates/horizon-client/src/mobs/villager.rs | 2 +- tools/test_mob_ai_parity.py | 10 ++++++++++ 12 files changed, 45 insertions(+), 9 deletions(-) diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index 8667f305f..a11a643c1 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -1054,6 +1054,7 @@ impl Game<'_> { let r = &mut self.world.random; let bonus = r.triangle(0.0, 0.11485000000000001); mob.attrs.follow_range += mob.kind.follow_range * bonus; + mob.update_max_visited_nodes(); let _left_handed = r.next_float() < 0.05; if !self.warden_fits(&mob) { continue; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index a61ea2a11..e020b92a4 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1602,6 +1602,8 @@ impl Mob { | Species::Fox | Species::Panda ); + // The PathNavigation constructor: the base follow range. + mob.ai.nav.max_visited_nodes = (mob.kind.follow_range * 16.0).floor() as i32; ai::register(&mut mob); mob } diff --git a/crates/horizon-client/src/mobs/allay.rs b/crates/horizon-client/src/mobs/allay.rs index 3c25053ba..029ddb6e5 100644 --- a/crates/horizon-client/src/mobs/allay.rs +++ b/crates/horizon-client/src/mobs/allay.rs @@ -26,7 +26,7 @@ pub fn register(m: &mut Mob) { }; m.ai.nav.kind = NavKind::Flying; // FlyingPathNavigation.setRequiredPathLength(48). - m.ai.nav.required_path_length = 48.0; + m.set_required_path_length(48.0); let g = &mut m.ai.goals; g.add(0, Panic::new(2.5)); g.add(1, Fetch); diff --git a/crates/horizon-client/src/mobs/bee.rs b/crates/horizon-client/src/mobs/bee.rs index cdb0318bc..53eacba1c 100644 --- a/crates/horizon-client/src/mobs/bee.rs +++ b/crates/horizon-client/src/mobs/bee.rs @@ -138,7 +138,7 @@ pub fn register(m: &mut Mob) { }; m.ai.nav.kind = NavKind::Flying; m.ai.nav.can_open_doors = false; - m.ai.nav.required_path_length = 48.0; + m.set_required_path_length(48.0); m.set_malus(PathType::Fire, -1.0); m.set_malus(PathType::Water, -1.0); m.set_malus(PathType::WaterBorder, 16.0); diff --git a/crates/horizon-client/src/mobs/copper_golem.rs b/crates/horizon-client/src/mobs/copper_golem.rs index 398022485..5f4ffba13 100644 --- a/crates/horizon-client/src/mobs/copper_golem.rs +++ b/crates/horizon-client/src/mobs/copper_golem.rs @@ -26,7 +26,7 @@ pub const DROPPING_NO_ITEM: u8 = 4; pub const WEATHER: [&str; 4] = ["unaffected", "exposed", "weathered", "oxidized"]; pub fn register(m: &mut Mob) { - m.ai.nav.required_path_length = 48.0; + m.set_required_path_length(48.0); m.ai.nav.can_open_doors = true; m.persistent = true; // nextWeatheringTick starts unset (-1); waxed is -2. diff --git a/crates/horizon-client/src/mobs/creaking_heart.rs b/crates/horizon-client/src/mobs/creaking_heart.rs index 1172b229c..a43f39284 100644 --- a/crates/horizon-client/src/mobs/creaking_heart.rs +++ b/crates/horizon-client/src/mobs/creaking_heart.rs @@ -464,6 +464,7 @@ pub fn finalize_spawn(m: &mut Mob, lr: &mut LegacyRandom) { let bonus = lr.triangle(0.0, 0.114_850_000_000_000_01); // ADD_MULTIPLIED_BASE on the base value. m.attrs.follow_range += m.kind.follow_range * bonus; + m.update_max_visited_nodes(); let _left_handed = lr.next_float() < 0.05; } fn wrap_degrees(angle: f32) -> f32 { diff --git a/crates/horizon-client/src/mobs/finalize.rs b/crates/horizon-client/src/mobs/finalize.rs index ae6a864cc..4eeed885b 100644 --- a/crates/horizon-client/src/mobs/finalize.rs +++ b/crates/horizon-client/src/mobs/finalize.rs @@ -559,7 +559,10 @@ fn refresh(m: &mut Mob, a: Attr) { match a { Attr::MaxHealth => m.attrs.max_health = value(m, a) as f32, Attr::MovementSpeed => m.attrs.speed = base_with_modifiers(m, a), - Attr::FollowRange => m.attrs.follow_range = value(m, a), + Attr::FollowRange => { + m.attrs.follow_range = value(m, a); + m.update_max_visited_nodes(); + } Attr::AttackDamage => m.attrs.attack_damage = value(m, a) as f32, Attr::KnockbackResistance => m.attrs.knockback_resistance = value(m, a), Attr::SpawnReinforcements => m.attrs.spawn_reinforcements = value(m, a), diff --git a/crates/horizon-client/src/mobs/happy_ghast.rs b/crates/horizon-client/src/mobs/happy_ghast.rs index 6fc07e898..bd4c5b1f3 100644 --- a/crates/horizon-client/src/mobs/happy_ghast.rs +++ b/crates/horizon-client/src/mobs/happy_ghast.rs @@ -39,6 +39,10 @@ fn setup(m: &mut Mob, baby: bool) { m.ai.look.wanted = [0.0; 3]; m.ai.look.cooldown = 0; m.extra.counter2 = 0; + // The new navigation's PathNavigation constructor. + m.ai.nav.required_path_length = 16.0; + m.ai.nav.max_visited_nodes = + (super::finalize::base_value(m, super::finalize::Attr::FollowRange) * 16.0).floor() as i32; if baby { m.ai.look.kind = LookKind::Default; m.ai.mov.kind = MoveKind::Flying { @@ -48,7 +52,7 @@ fn setup(m: &mut Mob, baby: bool) { // BabyFlyingPathNavigation. m.ai.nav.kind = NavKind::Flying; m.ai.nav.can_float = true; - m.ai.nav.required_path_length = 48.0; + m.set_required_path_length(48.0); return; } if was == 1 { diff --git a/crates/horizon-client/src/mobs/llama.rs b/crates/horizon-client/src/mobs/llama.rs index b91dc5bfa..219ca5973 100644 --- a/crates/horizon-client/src/mobs/llama.rs +++ b/crates/horizon-client/src/mobs/llama.rs @@ -50,7 +50,7 @@ pub fn is_illager(s: &Seen) -> bool { ) } pub fn register(m: &mut Mob) { - m.ai.nav.required_path_length = 40.0; + m.set_required_path_length(40.0); let tempt = m.kind.tempt.clone(); let trader = is_trader(m); if trader { diff --git a/crates/horizon-client/src/mobs/nav.rs b/crates/horizon-client/src/mobs/nav.rs index 793303c6d..178751ff6 100644 --- a/crates/horizon-client/src/mobs/nav.rs +++ b/crates/horizon-client/src/mobs/nav.rs @@ -37,7 +37,11 @@ pub struct Navigation { reach_range: i32, pub max_visited_multiplier: f32, pub stuck: bool, + /// Set through [`Mob::set_required_path_length`]. pub required_path_length: f32, + /// `PathFinder.maxVisitedNodes`: the base follow range times 16 when the + /// navigation is made, then [`Mob::update_max_visited_nodes`]. + pub max_visited_nodes: i32, pub can_float: bool, pub can_open_doors: bool, pub can_pass_doors: bool, @@ -68,6 +72,7 @@ impl Default for Navigation { max_visited_multiplier: 1.0, stuck: false, required_path_length: 16.0, + max_visited_nodes: 256, can_float: false, can_open_doors: false, can_pass_doors: true, @@ -147,6 +152,16 @@ impl Mob { fn max_path_length(&self) -> f32 { (self.attrs.follow_range as f32).max(self.ai.nav.required_path_length) } + /// `PathNavigation.updatePathfinderMaxVisitedNodes`: after a follow range + /// change and a new required path length. + pub fn update_max_visited_nodes(&mut self) { + self.ai.nav.max_visited_nodes = (self.max_path_length() * 16.0).floor() as i32; + } + /// `PathNavigation.setRequiredPathLength`. + pub fn set_required_path_length(&mut self, length: f32) { + self.ai.nav.required_path_length = length; + self.update_max_visited_nodes(); + } fn can_update_path(&self) -> bool { match self.ai.nav.kind { NavKind::Ground | NavKind::WallClimber => self.on_ground || self.is_in_liquid(), @@ -237,8 +252,8 @@ impl Mob { return Some(path.clone()); } let pm = self.path_mob(); - let max_visited = ((self.attrs.follow_range * 16.0).floor() as f32 - * self.ai.nav.max_visited_multiplier) as i32; + let max_visited = + (self.ai.nav.max_visited_nodes as f32 * self.ai.nav.max_visited_multiplier) as i32; let finder = Finder::new(w, &pm, self.ai.nav.evaluator()); let path = finder.find(targets, max_len, reach, max_visited); if let Some(p) = &path { diff --git a/crates/horizon-client/src/mobs/villager.rs b/crates/horizon-client/src/mobs/villager.rs index 84c607933..b5abad9f0 100644 --- a/crates/horizon-client/src/mobs/villager.rs +++ b/crates/horizon-client/src/mobs/villager.rs @@ -46,7 +46,7 @@ pub fn register(m: &mut Mob) { // Villager's constructor: its brain does everything, it has no goals. m.ai.nav.can_open_doors = true; m.ai.nav.can_float = true; - m.ai.nav.required_path_length = 48.0; + m.set_required_path_length(48.0); } /// `LivingEntity.addParticlesAroundSelf`: five particles about the body. diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index 07f41b2af..ccc50b302 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -275,6 +275,16 @@ def scenarios(): 'mob minecraft:cod 2.5 -62 0.5 0 13 persistent noai']) add('axolotl_play_dead', 300, [POOL, 'player 12.5 -60 0.5', 'mob minecraft:axolotl 0.5 -62 0.5 0 28 persistent'] + [f'hurt {t} 0' for t in range(4, 160, 12)]) + # A jobless villager outside a stone box, its composter inside and the doorway on the far + # side: the path around needs more than the 256 nodes of the follow range (16 * 16); the + # villager's setRequiredPathLength(48) raises PathFinder.maxVisitedNodes to 768. + add('villager_job_in_box', 300, [ + 'fill -4 -60 -4 4 -58 4 minecraft:stone', + 'fill -3 -60 -3 3 -58 3 minecraft:air', + 'fill -4 -60 0 -4 -59 0 minecraft:air', + 'block 0 -60 0 minecraft:composter', + 'mob minecraft:villager 10.5 -60 0.5 90 54 persistent', + ]) return s From 8cce2e2f8a1b46230c59e47394ea50c97ae33219 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 06:33:55 +0200 Subject: [PATCH 081/408] Prepare: import Programmer Art and High Contrast from the asset index Vanilla lists its built-in resource packs from minecraft:resourcepacks of the vanilla pack (BuiltInPackSource.populatePackList), and those two zips live only in the asset index, not in the client JAR. Preparation never copied them, so Horizon's pack list had no Programmer Art. Packs made to sit on it, like Golden Days ("This pack is meant to be put over Programmer Art"), then showed the modern textures for the ~720 textures they leave to it: furnaces, stone bricks, crafting tables, pumpkins, TNT, logs, tools, buckets, paper. Full preparation now imports both after extracting the JAR, like the panorama and Unifont, and `horizon-prepare packs` adds them to prepared resources. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-prepare/src/lib.rs | 4 +- crates/horizon-prepare/src/main.rs | 10 ++- crates/horizon-prepare/src/sounds.rs | 92 ++++++++++++++++++++++++---- docs/resource-packs.md | 3 +- 4 files changed, 92 insertions(+), 17 deletions(-) diff --git a/crates/horizon-prepare/src/lib.rs b/crates/horizon-prepare/src/lib.rs index 861db254d..b829004be 100644 --- a/crates/horizon-prepare/src/lib.rs +++ b/crates/horizon-prepare/src/lib.rs @@ -17,7 +17,7 @@ pub mod pyjson; mod sounds; mod survival; -pub use sounds::{fonts, panorama, sounds}; +pub use sounds::{fonts, packs, panorama, sounds}; use pyjson::Value; use sha2::Digest; @@ -692,7 +692,7 @@ fn steps( } // The JAR holds only gray 1x1 panorama placeholders and an empty Unifont - // include. Import the indexed ones afterwards, including on reruns that just + // include, and none of the built-in packs. Import the indexed ones afterwards, including on reruns that just // extracted the JAR again. They are optional when preparing from // already-imported JARs. sounds::optional_assets(repo, minecraft, run.log); diff --git a/crates/horizon-prepare/src/main.rs b/crates/horizon-prepare/src/main.rs index 0d3a5685d..395821283 100644 --- a/crates/horizon-prepare/src/main.rs +++ b/crates/horizon-prepare/src/main.rs @@ -19,6 +19,7 @@ Usage: horizon-prepare [--prepare] [--server-jar PATH] [--minecraft-dir PATH] [- horizon-prepare sounds [--minecraft-dir PATH] [--root PATH] horizon-prepare panorama [--minecraft-dir PATH] [--root PATH] horizon-prepare fonts [--minecraft-dir PATH] [--root PATH] + horizon-prepare packs [--minecraft-dir PATH] [--root PATH] --prepare Import the pinned game files from your own copy first --server-jar PATH The pinned server jar you downloaded yourself @@ -34,7 +35,8 @@ The resources go to /.local/horizon-client/; pass that to horizon horizon-prepare panorama repairs the classic menu background in existing resources without Java. horizon-prepare fonts adds the GNU Unifont glyphs (characters the bitmap fonts lack) the same way. -Full preparation also imports both after extracting the client JAR's placeholders. +horizon-prepare packs adds the built-in Programmer Art and High Contrast resource packs the same way. +Full preparation also imports all three after extracting the client JAR's placeholders. horizon-prepare sounds copies the pinned version's sounds (about 380 MB) from the official launcher's asset store into the same folder, checking every file. It is optional: without it the @@ -66,7 +68,8 @@ fn main() -> ExitCode { }; let mut root = None; let mut args = std::env::args_os().skip(1).peekable(); - let assets = args.next_if(|a| a == "sounds" || a == "panorama" || a == "fonts"); + let assets = + args.next_if(|a| matches!(a.to_str(), Some("sounds" | "panorama" | "fonts" | "packs"))); while let Some(arg) = args.next() { let text = arg.to_string_lossy().into_owned(); let (flag, inline) = match text.split_once('=') { @@ -132,6 +135,9 @@ fn main() -> ExitCode { Some("fonts") => { horizon_prepare::fonts(&options.root, options.minecraft_dir.as_deref(), &log) } + Some("packs") => { + horizon_prepare::packs(&options.root, options.minecraft_dir.as_deref(), &log) + } _ => horizon_prepare::prepare(&options, &log), }; match result { diff --git a/crates/horizon-prepare/src/sounds.rs b/crates/horizon-prepare/src/sounds.rs index fd9e18210..bafcf6a3e 100644 --- a/crates/horizon-prepare/src/sounds.rs +++ b/crates/horizon-prepare/src/sounds.rs @@ -1,5 +1,5 @@ -//! The pinned version's sounds and title panorama from the player's own official -//! launcher install, each object checked against the asset index's SHA-1, copied into +//! The pinned version's sounds, title panorama, Unifont glyphs and built-in resource packs +//! from the player's own official launcher install, each object checked against the asset index's SHA-1, copied into //! `.local/horizon-client//assets` where the game reads them (tools/fetch_sounds.py and //! the tools/lab.py functions it called). Nothing is downloaded. @@ -124,6 +124,11 @@ pub(crate) fn optional_assets(root: &Path, minecraft: Option<&Path>, log: Log) { "Unifont glyphs not imported: {error}; run horizon-prepare fonts later" )); } + if let Err(error) = packs(root, minecraft, log) { + log(&format!( + "Programmer Art and High Contrast not imported: {error}; run horizon-prepare packs later" + )); + } } const PANORAMA: [&str; 7] = [ @@ -145,6 +150,30 @@ const UNIFONT: [&str; 2] = [ "minecraft/font/unifont.zip", ]; +/// Adds the built-in Programmer Art and High Contrast packs, which only the asset index holds +/// (`BuiltInPackSource.populatePackList` lists `minecraft:resourcepacks` of the vanilla pack). +/// Packs made to sit on Programmer Art, like Golden Days, show the default textures without it. +/// Also usable on prepared resources without Java. +pub fn packs(root: &Path, minecraft: Option<&Path>, log: Log) -> Result { + copy_assets( + root, + minecraft, + log, + is_built_in_pack, + "Built-in pack", + &BUILT_IN_PACKS, + ) +} + +const BUILT_IN_PACKS: [&str; 2] = [ + "minecraft/resourcepacks/programmer_art.zip", + "minecraft/resourcepacks/high_contrast.zip", +]; + +fn is_built_in_pack(name: &str) -> bool { + name.starts_with("minecraft/resourcepacks/") +} + /// The fonts only the asset index holds (the JAR has the bitmap fonts). fn is_font(name: &str) -> bool { name.starts_with("minecraft/font/") @@ -228,11 +257,13 @@ mod tests { crate::hex(&sha1::Sha1::digest(data)) } - /// Where the fixture's panorama objects start. - const FIRST_FACE: usize = 6; + /// Where the fixture's built-in packs and panorama objects start. + const FIRST_PACK: usize = 6; + const FIRST_FACE: usize = 8; /// A Horizon folder and an official launcher directory holding version `9.9` with - /// sounds, a language file and the full title panorama in its asset store. + /// sounds, a language file, Unifont, the built-in packs and the full title panorama in its + /// asset store. struct Fixture { dir: PathBuf, root: PathBuf, @@ -263,6 +294,8 @@ mod tests { b"{\"providers\": [{\"type\": \"unihex\"}]}".to_vec(), ), (UNIFONT[1], b"PK unifont".to_vec()), + (BUILT_IN_PACKS[0], b"PK programmer art".to_vec()), + (BUILT_IN_PACKS[1], b"PK high contrast".to_vec()), ]; for &name in panorama { // Distinct object bytes let the test catch swapped faces too. @@ -499,15 +532,25 @@ mod tests { lines[0], format!("Title panorama not imported: {error}; run horizon-prepare panorama later") ); - // The fonts come on their own when only a panorama face is missing. + // The fonts and packs come on their own when only a panorama face is missing. match missing { - "last-object" => assert_eq!(lines[1], "Font assets ready: 2 files, 0.0 MB"), - _ => assert!( - lines[1].starts_with("Unifont glyphs not imported: "), - "{lines:?}" + "last-object" => assert_eq!( + lines[1..], + [ + "Font assets ready: 2 files, 0.0 MB", + "Built-in pack assets ready: 2 files, 0.0 MB" + ] ), + _ => { + assert!(lines[1].starts_with("Unifont glyphs not imported: ")); + assert!( + lines[2].starts_with("Programmer Art and High Contrast not imported: ") + && lines[2].ends_with("; run horizon-prepare packs later"), + "{lines:?}" + ); + } } - assert_eq!(lines.len(), 2); + assert_eq!(lines.len(), 3); for name in PANORAMA { assert_eq!(fs::read(target.join(name)).unwrap(), b"jar placeholder"); } @@ -528,7 +571,7 @@ mod tests { lines.borrow_mut().push(l.to_string()) }); assert_eq!(done.unwrap(), target); - for (name, data) in &f.objects[4..FIRST_FACE] { + for (name, data) in &f.objects[4..FIRST_PACK] { assert_eq!(&fs::read(target.join("assets").join(name)).unwrap(), data); } assert_eq!(*lines.borrow(), ["Font assets ready: 2 files, 0.0 MB"]); @@ -536,6 +579,31 @@ mod tests { assert!(!target.join("assets/minecraft/textures").exists()); } + /// Golden Days is made to sit on Programmer Art, which the client JAR lacks: the asset + /// index has it, where `BuiltInPackSource` lists `minecraft:resourcepacks`. + #[test] + fn packs_add_programmer_art_and_high_contrast_where_the_pack_list_finds_them() { + let f = Fixture::new("packs"); + let target = f.root.join(".local/horizon-client/9.9"); + let lines = std::cell::RefCell::new(Vec::new()); + let done = packs(&f.root, Some(&f.minecraft), &|l| { + lines.borrow_mut().push(l.to_string()) + }); + assert_eq!(done.unwrap(), target); + for (name, data) in &f.objects[FIRST_PACK..FIRST_FACE] { + assert_eq!(&fs::read(target.join("assets").join(name)).unwrap(), data); + } + assert!(target + .join("assets/minecraft/resourcepacks/programmer_art.zip") + .is_file()); + assert_eq!( + *lines.borrow(), + ["Built-in pack assets ready: 2 files, 0.0 MB"] + ); + assert!(!target.join("assets/minecraft/sounds.json").exists()); + assert!(!target.join("assets/minecraft/font").exists()); + } + #[test] fn the_index_must_hold_the_sounds() { let f = Fixture::new("index"); diff --git a/docs/resource-packs.md b/docs/resource-packs.md index 7faa75a48..227c9c5a4 100644 --- a/docs/resource-packs.md +++ b/docs/resource-packs.md @@ -7,7 +7,8 @@ screen (the same screen as vanilla's) or in game, and every loader reloads from ## How it works `packs.rs` finds the packs (`FolderRepositorySource`: folders and zips, plus the built-in Programmer Art and High -Contrast), reads `pack.mcmeta` (format range, overlays, filters) and builds one overlay directory that layers the +Contrast, which only the asset index holds: preparation copies them, `horizon-prepare packs` repairs older resources), +reads `pack.mcmeta` (format range, overlays, filters) and builds one overlay directory that layers the selected packs over the prepared vanilla resources, later packs winning. Files vanilla reads as a resource *stack* (language files, `sounds.json`, font definitions, atlas definitions) are merged layer by layer as vanilla merges them. Every loader then reads that one tree; `game/packs.rs` (`reload_packs`) reloads all of them in game, as From 13c14563c468e7854509caebc4de0935ebfb0673 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 07:07:28 +0200 Subject: [PATCH 082/408] Launcher adds Programmer Art and High Contrast to resources prepared without them Resources prepared before #1538, and every version that reused them, lack vanilla's built-in packs, so players had to click Prepare again. The launcher now copies them itself, with horizon-prepare's `packs` (the asset index's SHA-1 checked), when it starts, installs a version or starts the game: only for prepared versions that lack a zip, once per launcher run. Without them in any Minecraft folder's asset store it logs one line and the game starts as before. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-prepare/src/lib.rs | 2 +- crates/horizon-prepare/src/sounds.rs | 3 +- launcher/src/backend.rs | 203 ++++++++++++++++++++++++++- launcher/src/main.rs | 7 +- 4 files changed, 208 insertions(+), 7 deletions(-) diff --git a/crates/horizon-prepare/src/lib.rs b/crates/horizon-prepare/src/lib.rs index b829004be..24f163a9b 100644 --- a/crates/horizon-prepare/src/lib.rs +++ b/crates/horizon-prepare/src/lib.rs @@ -17,7 +17,7 @@ pub mod pyjson; mod sounds; mod survival; -pub use sounds::{fonts, packs, panorama, sounds}; +pub use sounds::{fonts, packs, panorama, sounds, BUILT_IN_PACKS}; use pyjson::Value; use sha2::Digest; diff --git a/crates/horizon-prepare/src/sounds.rs b/crates/horizon-prepare/src/sounds.rs index bafcf6a3e..120d75a1a 100644 --- a/crates/horizon-prepare/src/sounds.rs +++ b/crates/horizon-prepare/src/sounds.rs @@ -165,7 +165,8 @@ pub fn packs(root: &Path, minecraft: Option<&Path>, log: Log) -> Result Result<(), String> fs::write(target.join(COMPLETE), "").map_err(|e| e.to_string())?; let _ = fs::remove_dir_all(&partial); reuse_prepared(&root, tag); + complete_packs(tag); progress(1.0); Ok(()) } @@ -766,9 +767,15 @@ fn reuse_prepared(versions: &Path, tag: &str) -> Option { /// `reuse_prepared` for every installed version that is not prepared, oldest first, so a /// version prepared this way can serve the next. Launchers before 0.1.4 installed new versions /// without it; this catches those up. Returns each (version, where its resources came from). -/// Prepared versions also get the run-time reports they lack (`complete_reports`). +/// Prepared versions also get the run-time reports (`complete_reports`) and built-in packs +/// (`complete_packs`) they lack. pub fn reuse_prepared_everywhere() -> Vec<(String, String)> { - reuse_prepared_in(&versions_dir()) + let versions = versions_dir(); + let reused = reuse_prepared_in(&versions); + for tag in installed_in(&versions) { + complete_packs(&tag); + } + reused } fn reuse_prepared_in(versions: &Path) -> Vec<(String, String)> { @@ -842,6 +849,89 @@ fn complete_reports(versions: &Path, tag: &str) -> bool { complete } +/// Adds vanilla's built-in Programmer Art and High Contrast packs to a prepared version that +/// lacks them, as `horizon-prepare packs` does: preparers before #1538 left them out, and a new +/// version reuses the resources of the one before (`reuse_prepared`). They come from the player's +/// own Minecraft asset store; without them there, one line in the log, once per launcher run, and +/// the version plays as before. Nothing is prepared again. +pub fn complete_packs(tag: &str) { + complete_packs_in(&versions_dir(), tag, minecraft_folders, &|line| { + eprintln!("{line}") + }); +} + +/// `folders`: where to look, asked only when the version lacks a pack. +fn complete_packs_in( + versions: &Path, + tag: &str, + folders: impl Fn() -> Vec, + log: &dyn Fn(String), +) { + // The versions tried this run. Held while copying: the start, an install and Play can + // complete the same version at once, and the copies' temporary names are per process. + static TRIED: Mutex> = Mutex::new(Vec::new()); + let root = versions.join(tag); + let resources = resources_at(&root); + let lacking = || { + resources.join(RESOURCES_MANIFEST).exists() + && horizon_prepare::BUILT_IN_PACKS + .iter() + .any(|pack| !resources.join("assets").join(pack).is_file()) + }; + if !lacking() { + return; + } + let mut tried = TRIED.lock().unwrap_or_else(|e| e.into_inner()); + if tried.contains(&root) || !lacking() { + return; + } + tried.push(root.clone()); + let mut first_error = None; + for folder in folders() { + let copied = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + horizon_prepare::packs(&root, Some(&folder), &|line| log(line.to_string())) + })) + .unwrap_or_else(|_| Err("the copy stopped unexpectedly".into())); + match copied { + Ok(_) => return, + Err(e) => { + first_error.get_or_insert(e); + } + } + } + log(format!( + "{tag}: Programmer Art and High Contrast not added: {}", + first_error.unwrap_or_else(|| "no Minecraft folder found".into()) + )); +} + +/// The Minecraft folders whose asset store can hold what a prepared version lacks: the one +/// chosen in the launcher, the official launcher's (or HORIZON_MINECRAFT_DIR), the folder +/// other launchers' files are linked into and Horizon's own download, then every launcher's +/// default folder. +fn minecraft_folders() -> Vec { + let mut folders: Vec = Settings::load().minecraft_dir.into_iter().collect(); + folders.extend([ + horizon_prepare::artifacts::minecraft_dir(None), + data_dir().join("linked-minecraft"), + data_dir().join("minecraft"), + ]); + folders.extend( + sources::Folders::current() + .map(|f| sources::known_folders(sources::Os::current(), &f)) + .unwrap_or_default() + .into_iter() + .map(|(_, dir)| dir), + ); + let mut found: Vec = Vec::new(); + for folder in folders { + if folder.is_dir() && !found.contains(&folder) { + found.push(folder); + } + } + found +} + /// The official launcher's game directory, else the first other launcher's found /// (sources.rs); preparing looks in all of them anyway. pub fn default_minecraft_dir() -> Option { @@ -1533,6 +1623,7 @@ pub fn need_prepared(tag: &str) -> Result<(), String> { /// The client's command, once its resources are prepared. pub fn client(tag: &str) -> Result { need_prepared(tag)?; + complete_packs(tag); let mut cmd = client_command(tag); // A sign-in that can't be renewed (no network, expired) still lets the game start, offline. if let Err(e) = crate::account::attach_session(&mut cmd, &game_home()) { @@ -2963,6 +3054,114 @@ mod tests { let _ = fs::remove_dir_all(&versions); } + #[test] + fn prepared_versions_get_the_built_in_packs_without_preparing_again() { + let dir = std::env::temp_dir().join(format!( + "horizon-launcher-packs-test-{}", + std::process::id() + )); + let _ = fs::remove_dir_all(&dir); + let (versions, store, empty) = (dir.join("versions"), dir.join("store"), dir.join("none")); + let write = |path: PathBuf, data: &[u8]| { + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, data).unwrap(); + }; + // An official launcher folder whose asset store holds the two packs. + let packs = horizon_prepare::BUILT_IN_PACKS.map(|name| (name, name.as_bytes())); + let mut index = serde_json::Map::new(); + for (name, data) in packs { + let hash = sources::sha1_hex(data); + write( + store.join("assets/objects").join(&hash[..2]).join(&hash), + data, + ); + index.insert( + name.into(), + serde_json::json!({"hash": hash, "size": data.len()}), + ); + } + let index = serde_json::json!({ "objects": index }).to_string(); + write(store.join("assets/indexes/7.json"), index.as_bytes()); + let manifest = serde_json::json!({ + "id": "9.9", + "assetIndex": {"id": "7", "sha1": sources::sha1_hex(index.as_bytes())}, + "downloads": {"client": {"sha1": "c"}, "server": {"sha1": "s"}}, + "javaVersion": {"majorVersion": 25}, + }) + .to_string(); + write(store.join("versions/9.9/9.9.json"), manifest.as_bytes()); + fs::create_dir_all(&empty).unwrap(); + let release = |tag: &str, prepared: bool| { + let root = versions.join(tag); + write(root.join(COMPLETE), b""); + let lock = serde_json::json!({"minecraft": {"version": "9.9", "java_major": 25, + "client_sha1": "c", "server_sha1": "s", "manifest_sha1": sources::sha1_hex(manifest.as_bytes())}}); + write(root.join("research-lock.json"), lock.to_string().as_bytes()); + if prepared { + write(resources_at(&root).join(RESOURCES_MANIFEST), b"{}"); + write( + resources_at(&root).join("assets/minecraft/lang/en_us.json"), + b"{}", + ); + } + }; + let lines = std::cell::RefCell::new(Vec::new()); + let log = |line: String| lines.borrow_mut().push(line); + let pack = |tag: &str, i: usize| { + fs::read( + resources_at(&versions.join(tag)) + .join("assets") + .join(packs[i].0), + ) + .ok() + }; + + // Resources prepared before the packs were: a folder without an asset store is skipped. + release("v0.2.1", true); + complete_packs_in( + &versions, + "v0.2.1", + || vec![empty.clone(), store.clone()], + &log, + ); + assert_eq!( + *lines.borrow(), + ["Built-in pack assets ready: 2 files, 0.0 MB"] + ); + for (i, (_, data)) in packs.iter().enumerate() { + assert_eq!(pack("v0.2.1", i).as_deref(), Some(*data)); + } + // Nothing else is prepared again. + let resources = resources_at(&versions.join("v0.2.1")); + assert_eq!(fs::read(resources.join(RESOURCES_MANIFEST)).unwrap(), b"{}"); + assert!(!resources.join("assets/minecraft/sounds.json").exists()); + + // No asset store anywhere: one line, the version stays prepared, and no second try. + lines.borrow_mut().clear(); + release("v0.2.2", true); + complete_packs_in(&versions, "v0.2.2", || vec![empty.clone()], &log); + complete_packs_in(&versions, "v0.2.2", || vec![empty.clone()], &log); + assert_eq!(lines.borrow().len(), 1); + assert!( + lines.borrow()[0].starts_with("v0.2.2: Programmer Art and High Contrast not added: "), + "{lines:?}" + ); + assert!(resources_at(&versions.join("v0.2.2")) + .join(RESOURCES_MANIFEST) + .exists()); + assert_eq!(pack("v0.2.2", 0), None); + + // Not prepared, or complete: nothing to do, without even looking for a Minecraft folder. + lines.borrow_mut().clear(); + release("v0.2.3", false); + let unasked = || -> Vec { unreachable!("no folder is needed") }; + complete_packs_in(&versions, "v0.2.3", unasked, &log); + complete_packs_in(&versions, "v0.2.1", unasked, &log); + assert!(lines.borrow().is_empty()); + assert!(!resources_at(&versions.join("v0.2.3")).exists()); + let _ = fs::remove_dir_all(&dir); + } + #[test] fn finds_the_app_bundle_around_the_binary() { let exe = Path::new("/Applications/Horizon.app/Contents/MacOS/horizon-launcher"); diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 18e8295b1..bdae38fbb 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -792,12 +792,13 @@ impl Launcher { // A little earlier than the spawn: file times can be coarse. self.client_started = Some(std::time::SystemTime::now() - std::time::Duration::from_secs(2)); - // The session (a network round trip when the token needs renewing) comes first; - // `drain` starts the game when it arrives. - self.starting_client = Some(tag); + // The built-in packs the resources lack and the session (a network round trip when the + // token needs renewing) come first; `drain` starts the game when the session arrives. + self.starting_client = Some(tag.clone()); self.play_pressed = Some(Instant::now()); let tx = self.tx.clone(); std::thread::spawn(move || { + backend::complete_packs(&tag); let session = (|| { let mut accounts = Accounts::load(); let Some((a, secrets)) = account::session_for_launch( From 1b14e0d17170f61a536f44efab078651f2685e56 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 06:54:44 +0200 Subject: [PATCH 083/408] Villagers summon iron golems the vanilla way and remember them Villager.spawnGolemIfNeeded set GOLEM_DETECTED_RECENTLY on the villagers near a new golem, but Horizon wrote only villager::Ext, and the next brain tick copied the empty memory back over it: the same villagers could summon another golem before their sensor saw the first. golem_detected now sets the brain memory (599 ticks). IronGolem.checkSpawnObstruction checks the floor's top face (no golems on dirt paths, farmland or slabs) and three blocks, the feet whatever fluid is there; Horizon checked four blocks and no floor, so a roof three blocks up kept golems out. The search's open block is air or a liquid block, not any waterlogged one, and the villagers asked are those whose boxes meet the caller's box grown by 10. The golem is created (yaw, follow range bonus, left-handedness from the level random) before the obstruction check, as trySpawnMob does. The search and checks move to mobs::villager so the mob_ai probe runs the game's code: four new scenarios (gossip, glass roof, dirt paths, panic) match vanilla; with the old checks all four diverge. Co-Authored-By: Claude Opus 5.5 --- .../examples/probe/mob_ai_probe.rs | 52 +++++++ crates/horizon-client/src/game/villagers.rs | 135 +++++------------ crates/horizon-client/src/mobs/villager.rs | 138 ++++++++++++++++++ .../horizon-client/src/mobs/villager_brain.rs | 8 + .../horizonlab/parity/VanillaMobAiOracle.java | 10 +- tools/test_mob_ai_parity.py | 16 ++ 6 files changed, 256 insertions(+), 103 deletions(-) diff --git a/crates/horizon-client/examples/probe/mob_ai_probe.rs b/crates/horizon-client/examples/probe/mob_ai_probe.rs index d773a509b..417e28c0f 100644 --- a/crates/horizon-client/examples/probe/mob_ai_probe.rs +++ b/crates/horizon-client/examples/probe/mob_ai_probe.rs @@ -293,6 +293,47 @@ fn spawn_seed(index: usize) -> i64 { 1000 + 7919 * index as i64 } +/// `Villager.spawnGolemIfNeeded` for villager `a`, the game's way: the golem +/// draws from the level's random and joins the scenario's mobs next tick, +/// seeded as the oracle seeds what a tick spawned. +fn summon_golem( + mobs: &mut [Mob], + a: usize, + needed: usize, + w: &MobWorld, + types: &MobTypes, + born: &mut Vec, + level_random: &mut LegacyRandom, +) { + use horizon_client::mobs::{villager, villager_brain}; + let Some(near) = villager::golem_summoners(mobs, a, w.game_time, needed) else { + return; + }; + let kind = Arc::new( + types + .types + .get("minecraft:iron_golem") + .expect("iron golem") + .clone(), + ); + let index = mobs.len() + born.len(); + let p = mobs[a].position; + let start = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]; + let golem = villager::summon_golem(w, start, level_random, |random, at, yaw| { + let mut m = Mob::new(100_000 + index as u32, kind.clone(), at, yaw); + villager::finalize_summoned_golem(&mut m, random); + m + }); + let Some(mut golem) = golem else { + return; + }; + golem.random = LegacyRandom::new(spawn_seed(index)); + born.push(golem); + for j in near { + villager_brain::golem_detected(&mut mobs[j], w.game_time); + } +} + /// Villager events that act at once in vanilla (`TradeWithVillager` and /// `VillagerMakeLove` write the other villager directly). fn villager_events( @@ -304,6 +345,7 @@ fn villager_events( items: &Items, born: &mut Vec, day_time: i64, + level_random: &mut LegacyRandom, ) { use horizon_client::mobs::villager; let index = |mobs: &[Mob], id: u32| { @@ -314,6 +356,7 @@ fn villager_events( while i < events.len() { match events[i] { MobEvent::VillagerMeet { mob, other } => { + events.remove(i); if let (Some(a), Some(b)) = (index(mobs, mob), index(mobs, other)) { let meeting = villager::meet(mobs, a, b, w.game_time, |item| { items.get(item).map_or(64, |i| i.max_stack) @@ -322,8 +365,16 @@ fn villager_events( meeting.thrown.is_empty(), "villagers toss items: not modelled here" ); + if meeting.gossiped { + summon_golem(mobs, a, 5, w, types, born, level_random); + } } + } + MobEvent::GolemCheck { mob, needed } => { events.remove(i); + if let Some(a) = index(mobs, mob) { + summon_golem(mobs, a, needed, w, types, born, level_random); + } } MobEvent::VillagerBirth { parent, @@ -1167,6 +1218,7 @@ pub fn main() -> horizon_client::Result<()> { &items, &mut born, s.time, + &mut scratch, ); horizon_client::mobs::warden::hear_mob_events(&mut mobs, &events, from, &w); // Melee hits on other mobs land during the attacker's tick diff --git a/crates/horizon-client/src/game/villagers.rs b/crates/horizon-client/src/game/villagers.rs index 5c6bed394..3cfe8aa1d 100644 --- a/crates/horizon-client/src/game/villagers.rs +++ b/crates/horizon-client/src/game/villagers.rs @@ -5,34 +5,13 @@ use super::Game; use horizon_client::{ gossip::{self, GossipType}, items::ItemStack, - mobs::{Mob, Species, spawning, villager}, + mobs::{Mob, Species, spawning, villager, villager_brain}, }; -use horizon_core::{geometry::Vec3, random::RandomSource}; +use horizon_core::geometry::Vec3; fn block_of(p: Vec3) -> [i32; 3] { [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32] } -/// `SpawnUtil.Strategy.LEGACY_IRON_GOLEM`: what a golem will not land on. -fn golem_floor_ok(name: &str) -> bool { - !matches!( - name, - "minecraft:cobweb" - | "minecraft:cactus" - | "minecraft:glass_pane" - | "minecraft:conduit" - | "minecraft:ice" - | "minecraft:tnt" - | "minecraft:glowstone" - | "minecraft:beacon" - | "minecraft:sea_lantern" - | "minecraft:frosted_ice" - | "minecraft:tinted_glass" - | "minecraft:glass" - ) && !name.ends_with("_stained_glass_pane") - && !name.ends_with("_stained_glass") - && !name.ends_with("leaves") -} - impl Game<'_> { fn villager_index(&self, id: u32) -> Option { self.mobs @@ -76,88 +55,46 @@ impl Game<'_> { return; }; let now = self.world.game_time; - if !villager::ext(&self.mobs[i]).is_some_and(|e| e.wants_golem(now)) { + let Some(near) = villager::golem_summoners(&self.mobs, i, now, needed) else { return; - } - let at = self.mobs[i].position; - let nearby: Vec = self - .mobs - .iter() - .enumerate() - .filter(|(_, m)| { - m.species() == Species::Villager - && m.alive() - && (m.position.x - at.x).abs() <= 10.0 - && (m.position.y - at.y).abs() <= 10.0 - && (m.position.z - at.z).abs() <= 10.0 - }) - .map(|(j, _)| j) - .collect(); - let wanting = nearby - .iter() - .filter(|j| villager::ext(&self.mobs[**j]).is_some_and(|e| e.wants_golem(now))) - .take(5) - .count(); - if wanting < needed { - return; - } - if self.try_spawn_iron_golem(block_of(at)) { - for j in nearby { - villager::ext_mut(&mut self.mobs[j]).golem_until = now + 599; + }; + if self.try_spawn_iron_golem(block_of(self.mobs[i].position)) { + for j in near { + villager_brain::golem_detected(&mut self.mobs[j], now); } } } - /// `SpawnUtil.trySpawnMob(IRON_GOLEM, ..., 10 attempts, 8 across, 6 up - /// and down, LEGACY_IRON_GOLEM)`. + /// `SpawnUtil.trySpawnMob(IRON_GOLEM, ...)`: a golem near `start`, with + /// the ambient sound `trySpawnMob` plays. fn try_spawn_iron_golem(&mut self, start: [i32; 3]) -> bool { - for _ in 0..10 { - let r = &mut self.world.random; - let dx = r.next_int_bound(17).unwrap_or(8) - 8; - let dz = r.next_int_bound(17).unwrap_or(8) - 8; - let (x, z) = (start[0] + dx, start[2] + dz); - let mut y = start[1] + 6; - let mut above = self.world.block(x, y, z); - let mut found = None; - for _ in 0..=12 { - y -= 1; - let here = self.world.block(x, y, z); - let f = self.res.facts().get(here); - let above_f = self.res.facts().get(above); - let air_or_liquid = self.res.facts().is_air(above) - || above_f.fluid != horizon_client::blocks::Fluid::None; - let solid = - self.res.mob_data().state(here).flags & horizon_client::mobs::data::SOLID != 0 - || f.name.as_ref() == "minecraft:powder_snow"; - if golem_floor_ok(&f.name) && air_or_liquid && solid { - found = Some(y + 1); - break; - } - above = here; - } - let Some(y) = found else { continue }; - // IronGolem.checkSpawnRules: a floor and three free blocks. - let free = |g: &Self, yy: i32| { - g.res.mob_data().state(g.world.block(x, yy, z)).flags - & horizon_client::mobs::data::VALID_EMPTY_SPAWN - != 0 - }; - if !(0..4).all(|k| free(self, y + k)) { - continue; - } - let at = [f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5]; - if let Some(id) = self.spawn_mob_for("minecraft:iron_golem", at, false, true) - && let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) - { - let sound = m.kind.sounds[0]; - if !sound.is_empty() { - let at = m.center(); - self.audio - .play(&format!("minecraft:{sound}"), Some(at), 1.0, 1.0); - } - return true; - } + let Some(kind) = self.res.mob_types().get("minecraft:iron_golem").cloned() else { + return false; + }; + let id = self.next_entity + 1; + let mut random = self.world.random.clone(); + let golem = villager::summon_golem( + &self.mob_world_base(&[]), + start, + &mut random, + |random, at, yaw| { + let mut m = Mob::new(id, kind.clone(), at, yaw); + villager::finalize_summoned_golem(&mut m, random); + m + }, + ); + self.world.random = random; + let Some(golem) = golem else { + return false; + }; + self.next_entity = id; + let sound = golem.kind.sounds[0]; + if !sound.is_empty() { + let at = golem.center(); + self.audio + .play(&format!("minecraft:{sound}"), Some(at), 1.0, 1.0); } - false + self.mobs.push(golem); + true } /// `VillagerMakeLove.tryToGiveBirth`: both eat, a free bed within 48 diff --git a/crates/horizon-client/src/mobs/villager.rs b/crates/horizon-client/src/mobs/villager.rs index b5abad9f0..575fafaed 100644 --- a/crates/horizon-client/src/mobs/villager.rs +++ b/crates/horizon-client/src/mobs/villager.rs @@ -614,6 +614,144 @@ pub fn meet( gossiped: ready, } } +/// `Villager.spawnGolemIfNeeded` up to the spawn: villager `i` wants a golem +/// and so do at least `needed` of the villagers whose boxes meet its own grown +/// by 10 blocks. Returns all of those villagers: once the golem stands, they +/// remember it ([`super::villager_brain::golem_detected`]). +pub fn golem_summoners(mobs: &[Mob], i: usize, now: i64, needed: usize) -> Option> { + if !ext(&mobs[i]).is_some_and(|e| e.wants_golem(now)) { + return None; + } + let area = mobs[i] + .bounds() + .inflate(horizon_core::geometry::Vec3::new(10.0, 10.0, 10.0)); + let near: Vec = mobs + .iter() + .enumerate() + .filter(|(_, m)| { + m.species() == Species::Villager && !m.removed && m.bounds().intersects(area) + }) + .map(|(j, _)| j) + .collect(); + let wanting = near + .iter() + .filter(|&&j| ext(&mobs[j]).is_some_and(|e| e.wants_golem(now))) + .take(5) + .count(); + (wanting >= needed).then_some(near) +} +/// `SpawnUtil.Strategy.LEGACY_IRON_GOLEM`'s refused floors. +fn golem_floor_ok(name: &str) -> bool { + !matches!( + name, + "minecraft:cobweb" + | "minecraft:cactus" + | "minecraft:glass_pane" + | "minecraft:conduit" + | "minecraft:ice" + | "minecraft:tnt" + | "minecraft:glowstone" + | "minecraft:beacon" + | "minecraft:sea_lantern" + | "minecraft:frosted_ice" + | "minecraft:tinted_glass" + | "minecraft:glass" + ) && !name.ends_with("_stained_glass_pane") + && !name.ends_with("_stained_glass") + && !name.ends_with("leaves") +} +/// One attempt of `SpawnUtil.trySpawnMob(IRON_GOLEM, ..., 8 across, 6 up and +/// down, LEGACY_IRON_GOLEM)`: a column drawn near `start`, searched down from +/// 6 above for a solid floor (or powder snow) under air or a liquid block. +/// Returns the block the golem would stand in. +fn golem_attempt( + l: &L, + start: [i32; 3], + random: &mut impl RandomSource, +) -> Option<[i32; 3]> { + let dx = random.next_int_bound(17).unwrap_or(8) - 8; + let dz = random.next_int_bound(17).unwrap_or(8) - 8; + let (x, z) = (start[0] + dx, start[2] + dz); + let name = |y: i32| -> &str { &l.facts().get(l.state(x, y, z)).name }; + let mut y = start[1] + 6; + let mut above = l.state(x, y, z); + for _ in 0..=12 { + y -= 1; + let here = l.state(x, y, z); + let above_name = &*l.facts().get(above).name; + // BlockState.liquid(): a water or lava block (not a waterlogged one). + let open = l.facts().is_air(above) + || above_name == "minecraft:water" + || above_name == "minecraft:lava"; + let solid = l.mob_data().state(here).flags & super::data::SOLID != 0 + || name(y) == "minecraft:powder_snow"; + if golem_floor_ok(name(y)) && open && solid { + return Some([x, y + 1, z]); + } + above = here; + } + None +} +/// `IronGolem.checkSpawnObstruction`: a floor with a full top face, its feet +/// free whatever fluid is there, and the two blocks above free. +fn golem_fits(l: &L, [x, y, z]: [i32; 3]) -> bool { + use super::spawn_rules::is_valid_empty_spawn; + // entityCanStandOn: Block.isFaceFull(collision shape, UP). + let floor = l.mob_data().state(l.state(x, y - 1, z)); + let stands = floor.flags & super::data::STURDY_TOP != 0 && floor.top >= 1.0; + // isValidEmptySpawnBlock with Fluids.EMPTY: open water is free too. + let feet = is_valid_empty_spawn(Species::IronGolem, l, x, y, z) + || &*l.facts().get(l.state(x, y, z)).name == "minecraft:water"; + stands + && feet + && is_valid_empty_spawn(Species::IronGolem, l, x, y + 1, z) + && is_valid_empty_spawn(Species::IronGolem, l, x, y + 2, z) +} +/// `SpawnUtil.trySpawnMob(IRON_GOLEM, MOB_SUMMONED, level, start, 10, 8, 6, +/// LEGACY_IRON_GOLEM, false)`: up to ten columns tried. In each spot found +/// `create` makes the golem (`EntityType.create`: the yaw drawn here, then its +/// `finalizeSpawn` draws, see [`finalize_summoned_golem`]); it is kept only +/// when `IronGolem.checkSpawnObstruction` passes, and discarded otherwise. +pub fn summon_golem( + l: &L, + start: [i32; 3], + random: &mut R, + mut create: impl FnMut(&mut R, horizon_core::geometry::Vec3, f32) -> T, +) -> Option { + for _ in 0..10 { + let Some([x, y, z]) = golem_attempt(l, start, random) else { + continue; + }; + // Mth.wrapDegrees(nextFloat() * 360). + let mut yaw = random.next_float() * 360.0; + if yaw >= 180.0 { + yaw -= 360.0; + } + let at = + horizon_core::geometry::Vec3::new(f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5); + let golem = create(random, at, yaw); + if golem_fits(l, [x, y, z]) { + return Some(golem); + } + } + None +} +/// `Mob.finalizeSpawn` for a summoned iron golem, from the level's random: +/// the follow range spawn bonus and left-handedness. +pub fn finalize_summoned_golem(m: &mut Mob, random: &mut impl RandomSource) { + use super::finalize::{Attr, Op, add_modifier, has_modifier}; + if !has_modifier(m, Attr::FollowRange, "minecraft:random_spawn_bonus") { + let bonus = random.triangle(0.0, 0.114_850_000_000_000_01); + add_modifier( + m, + Attr::FollowRange, + "minecraft:random_spawn_bonus", + bonus, + Op::AddMultipliedBase, + ); + } + m.extra.left_handed = random.next_float() < 0.05; +} /// `PoiManager.take(HOME, ..., 48)`: the nearest bed head not `claimed` /// (`free_head`: a bed head that is not occupied). pub fn take_vacant_bed( diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index df19d8fed..336dc6b93 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -779,6 +779,14 @@ fn sense_golem(m: &mut Mob, w: &MobWorld) { } } +/// `GolemSensor.golemDetected`: a golem was summoned near this villager; +/// for 599 ticks it wants no other. +pub fn golem_detected(m: &mut Mob, now: i64) { + mem(m).golem_detected_recently.set_ttl(true, 599); + // What `sync` derives from the memory. + super::villager::ext_mut(m).golem_until = now + 599 + 1; +} + // ---- Behaviours --------------------------------------------------------- /// The POI types villagers use. diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java index 55c0370f4..5808fec0d 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java @@ -761,12 +761,14 @@ public final class VanillaMobAiOracle { level.tickBlockEntities(); } else if (!heartPositions.isEmpty()) level.tickBlockEntities(); managerTick.invoke(manager); - // Villagers the tick spawned (babies) and a heart's creakings tick from the next - // one, in the order they were added, with a seeded random of their own. Other - // newcomers (animal babies, dropped items) are left out, as the probe leaves them. + // Villagers the tick spawned (babies), the iron golems they summoned and a heart's + // creakings tick from the next one, in the order they were added, with a seeded + // random of their own. Other newcomers (animal babies, dropped items) are left out, + // as the probe leaves them. List fresh = new ArrayList<>(); for (Entity e : level.getAllEntities()) - if (!LABELS.containsKey(e) && (e instanceof Villager || e instanceof net.minecraft.world.entity.animal.bee.Bee || created.contains(e))) fresh.add(e); + if (!LABELS.containsKey(e) && (e instanceof Villager || e instanceof net.minecraft.world.entity.animal.bee.Bee + || e instanceof net.minecraft.world.entity.animal.golem.IronGolem || created.contains(e))) fresh.add(e); fresh.sort(java.util.Comparator.comparingInt(Entity::getId)); for (Entity e : fresh) { int index = ENTS.size(); diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index ccc50b302..338c97e53 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -285,6 +285,22 @@ def scenarios(): 'block 0 -60 0 minecraft:composter', 'mob minecraft:villager 10.5 -60 0.5 90 54 persistent', ]) + # Villagers that slept today and saw no golem summon an iron golem (Villager.spawnGolemIfNeeded): + # five gossiping (TradeWithVillager, at tick 200 here), or three panicking at a zombie in a pen + # (VillagerPanicTrigger, at tick 100 by night). They all remember it (GOLEM_DETECTED_RECENTLY). + # Under a glass roof three blocks up the golem still fits (IronGolem.checkSpawnObstruction); + # on dirt paths it cannot stand. The scenarios stop on the summoning tick: the golem's own AI + # (MoveBackToVillageGoal, GolemRandomStrollInVillageGoal) is not ported yet. + golem_callers = [f'mob minecraft:villager {x} -60 {z} {r} {seed} persistent slept=1' for x, z, r, seed in + [(0.5, 0.5, 0, 81), (2.5, 0.5, 180, 82), (0.5, 2.5, 90, 83), (2.5, 2.5, 270, 84), (1.5, -1.5, 0, 85)]] + add('villager_golem_gossip', 200, ['player 14.5 -60 0.5'] + golem_callers, 'time=100') + add('villager_golem_roof', 200, ['fill -10 -57 -12 13 -57 13 minecraft:glass', 'player 14.5 -60 0.5'] + golem_callers, + 'time=100') + add('villager_golem_paths', 400, ['fill -10 -61 -12 13 -61 13 minecraft:dirt_path', 'player 14.5 -60 0.5'] + golem_callers, + 'time=100') + add('villager_golem_panic', 100, ['fill -2 -60 -3 4 -60 4 minecraft:oak_fence', 'fill -1 -60 -2 3 -60 3 minecraft:air', + 'player 14.5 -60 0.5'] + golem_callers[:3] + + ['mob minecraft:zombie 6.5 -60 0.5 90 86 persistent noai'], 'time=18000') return s From 0b581f9ffec685939cba8c30efa97c429f14f7a8 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 07:34:48 +0200 Subject: [PATCH 084/408] Give each crate's probe example its own target name horizon-client, horizon-world and horizon-protocol each had an example named `probe`. Cargo copies every crate's examples into one /examples/ directory, so parallel parity harnesses sharing a target dir could run another crate's probe (CI parity run 40055656303: command_parse ran the horizon-world dispatcher). The examples are now client_probe, world_probe and protocol_probe ([[example]] in each Cargo.toml; the files stay where they are), and every harness builds and runs its own crate's name. tools/parity.py recognises the new names when it counts the probes a harness ran, and renames the old `probe` in recorded artifacts to the crate's target (from the record's -p, else its probe sources), so the prebuild still builds them instead of dropping them as unknown. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/Cargo.toml | 5 +++ .../horizon-client/examples/probe/dispatch.rs | 2 +- crates/horizon-protocol/Cargo.toml | 5 +++ crates/horizon-protocol/examples/probe.rs | 2 +- crates/horizon-world/Cargo.toml | 5 +++ .../horizon-world/examples/probe/dispatch.rs | 2 +- docs/parity-workflow.md | 2 +- tests/test_parity_runner.py | 37 ++++++++++++++++++- tools/audio_harness.py | 4 +- tools/block_update_harness.py | 2 +- tools/interaction_lab.py | 3 +- tools/oracle_harness.py | 4 +- tools/parity.py | 36 ++++++++++++++---- tools/port_regen.py | 4 +- tools/test_active_effect_tick_parity.py | 4 +- tools/test_active_effects_parity.py | 4 +- tools/test_anchor_parity.py | 4 +- tools/test_arrow_parity.py | 4 +- tools/test_attribute_health_parity.py | 4 +- tools/test_attribute_map_queries_parity.py | 4 +- tools/test_attribute_parity.py | 4 +- tools/test_attribute_updates_parity.py | 4 +- tools/test_basic_feature_parity.py | 4 +- tools/test_biome_chunk_parity.py | 4 +- tools/test_biome_generation_parity.py | 4 +- tools/test_biome_placement_parity.py | 4 +- tools/test_biome_source_codec_parity.py | 4 +- tools/test_biome_source_parity.py | 4 +- tools/test_biome_temperature_parity.py | 4 +- tools/test_block_collision_scan_parity.py | 4 +- tools/test_block_entity_anim_parity.py | 2 +- tools/test_block_entity_render_parity.py | 2 +- tools/test_block_entity_storage_parity.py | 4 +- tools/test_block_entity_tickers_parity.py | 2 +- tools/test_block_landing_parity.py | 4 +- tools/test_block_properties_parity.py | 4 +- tools/test_block_push_parity.py | 4 +- tools/test_block_state_codec_parity.py | 4 +- tools/test_block_support_parity.py | 4 +- tools/test_block_survival_parity.py | 4 +- tools/test_blocking_item_damage_parity.py | 4 +- tools/test_blocking_rules_parity.py | 4 +- tools/test_bulk_section_parity.py | 4 +- tools/test_bundle_weight_parity.py | 4 +- tools/test_canyon_carver_parity.py | 4 +- tools/test_carving_geometry_parity.py | 4 +- tools/test_carving_mask_parity.py | 4 +- tools/test_cave_carver_parity.py | 4 +- tools/test_chunk_generation_parity.py | 4 +- tools/test_chunk_stage_parity.py | 4 +- tools/test_chunk_status_parity.py | 4 +- tools/test_climbing_parity.py | 2 +- tools/test_collision_context_parity.py | 4 +- tools/test_collision_parity.py | 4 +- tools/test_combat_rules_parity.py | 4 +- tools/test_command_parse_parity.py | 4 +- tools/test_component_durability_parity.py | 4 +- tools/test_component_patch_parity.py | 4 +- tools/test_consumable_emission_parity.py | 4 +- tools/test_consumable_parity.py | 4 +- tools/test_consume_effect_parity.py | 4 +- tools/test_contextual_collision_parity.py | 4 +- tools/test_damage_immunity_parity.py | 4 +- tools/test_damage_reduction_parity.py | 4 +- tools/test_damage_source_parity.py | 4 +- tools/test_datafix_parity.py | 4 +- tools/test_decoration_parity.py | 4 +- tools/test_decoration_region_parity.py | 4 +- tools/test_dynamic_support_parity.py | 4 +- tools/test_edge_backoff_parity.py | 4 +- .../test_effect_attribute_modifiers_parity.py | 4 +- tools/test_effect_notifications_parity.py | 4 +- tools/test_effect_sync_parity.py | 4 +- tools/test_enchanting_parity.py | 4 +- tools/test_entity_attribute_parity.py | 4 +- tools/test_entity_collision_parity.py | 4 +- tools/test_entity_death_loot_parity.py | 4 +- tools/test_entity_fluid_parity.py | 4 +- tools/test_entity_fluid_tick_parity.py | 4 +- tools/test_entity_model_parity.py | 2 +- tools/test_entity_move_parity.py | 4 +- tools/test_entity_obstruction_parity.py | 4 +- tools/test_environment_render_parity.py | 2 +- tools/test_extra_items_parity.py | 4 +- tools/test_face_support_parity.py | 4 +- tools/test_face_visibility_parity.py | 4 +- tools/test_fall_damage_parity.py | 4 +- tools/test_feature_catalog_parity.py | 4 +- tools/test_feature_graph_parity.py | 4 +- tools/test_feature_placement_parity.py | 4 +- tools/test_feature_region_parity.py | 4 +- tools/test_feature_sort_parity.py | 4 +- tools/test_fill_layer_parity.py | 4 +- tools/test_finalize_spawn_parity.py | 4 +- tools/test_fluid_box_parity.py | 4 +- tools/test_fluid_flow_parity.py | 4 +- tools/test_fluid_occupancy_parity.py | 2 +- tools/test_fluid_parity.py | 4 +- tools/test_fluid_shape_parity.py | 4 +- tools/test_food_parity.py | 4 +- tools/test_food_properties_parity.py | 4 +- tools/test_food_storage_parity.py | 4 +- tools/test_free_space_parity.py | 4 +- tools/test_ground_support_parity.py | 4 +- tools/test_height_provider_parity.py | 4 +- tools/test_heightmap_parity.py | 4 +- tools/test_held_drop_parity.py | 2 +- tools/test_hud_parity.py | 2 +- tools/test_interaction_shape_parity.py | 4 +- tools/test_inventory_pickup_parity.py | 4 +- tools/test_inventory_tick_parity.py | 4 +- tools/test_inventory_use_parity.py | 4 +- tools/test_inventory_use_start_parity.py | 4 +- tools/test_item_after_use_parity.py | 4 +- tools/test_item_blocking_parity.py | 4 +- tools/test_item_cooldowns_parity.py | 4 +- tools/test_item_durability_parity.py | 4 +- tools/test_item_particles_parity.py | 4 +- tools/test_item_stack_storage_parity.py | 4 +- tools/test_item_template_parity.py | 4 +- tools/test_item_use_catalog_parity.py | 4 +- tools/test_item_use_lifecycle_parity.py | 4 +- tools/test_item_use_parity.py | 4 +- tools/test_item_use_start_parity.py | 4 +- tools/test_java_hash_map_parity.py | 4 +- tools/test_java_identity_map_parity.py | 4 +- tools/test_level_place_parity.py | 2 +- tools/test_level_shape_parity.py | 2 +- tools/test_light_parity.py | 2 +- tools/test_liquid_collision_parity.py | 4 +- tools/test_live_attribute_updates_parity.py | 4 +- tools/test_live_attributes_parity.py | 4 +- tools/test_living_air_parity.py | 4 +- tools/test_living_damage_parity.py | 4 +- tools/test_living_fall_parity.py | 4 +- tools/test_living_fluid_parity.py | 4 +- tools/test_living_health_parity.py | 4 +- tools/test_living_hurt_parity.py | 4 +- tools/test_living_landing_parity.py | 4 +- tools/test_living_motion_parity.py | 4 +- tools/test_local_input_parity.py | 4 +- tools/test_material_condition_parity.py | 4 +- tools/test_material_extension_parity.py | 4 +- tools/test_material_rule_library_parity.py | 4 +- tools/test_material_stage_parity.py | 2 +- tools/test_material_surface_parity.py | 4 +- tools/test_mob_ai_parity.py | 4 +- tools/test_mob_attributes_parity.py | 4 +- tools/test_movement_emission_parity.py | 4 +- tools/test_movement_registry_parity.py | 4 +- tools/test_movement_support_parity.py | 4 +- tools/test_native_scene_collision.py | 4 +- tools/test_native_scene_motion.py | 4 +- tools/test_natural_spawn_parity.py | 4 +- tools/test_nether_portal_parity.py | 2 +- tools/test_object_open_map_parity.py | 4 +- tools/test_object_open_set_parity.py | 4 +- tools/test_pack_selection_parity.py | 2 +- tools/test_piston_movement_parity.py | 4 +- tools/test_piston_shape_parity.py | 4 +- tools/test_placement_parity.py | 4 +- tools/test_player_equipment_parity.py | 4 +- tools/test_player_food_parity.py | 4 +- tools/test_player_health_parity.py | 4 +- tools/test_player_hurt_parity.py | 4 +- tools/test_player_inventory_parity.py | 4 +- tools/test_player_travel_parity.py | 4 +- tools/test_powder_snow_collision_parity.py | 4 +- tools/test_raid_parity.py | 4 +- tools/test_registered_entity_fluid_parity.py | 2 +- tools/test_registered_player_combat_parity.py | 4 +- tools/test_registry_collision_scan_parity.py | 4 +- tools/test_registry_fall_ray_parity.py | 2 +- tools/test_registry_fluid_parity.py | 2 +- tools/test_replace_block_parity.py | 4 +- tools/test_restitution_parity.py | 4 +- tools/test_retrogen_chunk_parity.py | 4 +- tools/test_retrogen_data_parity.py | 4 +- tools/test_rule_test_parity.py | 4 +- tools/test_scaffolding_collision_parity.py | 4 +- tools/test_scattered_ore_parity.py | 4 +- tools/test_scoreboard_parity.py | 4 +- tools/test_section_mesh_parity.py | 4 +- tools/test_server_player_combat_parity.py | 4 +- tools/test_server_player_damage_parity.py | 4 +- tools/test_simple_block_parity.py | 4 +- tools/test_simple_container_parity.py | 4 +- tools/test_spawn_rules_parity.py | 4 +- tools/test_spawner_parity.py | 4 +- tools/test_sprint_input_parity.py | 4 +- tools/test_state_provider_parity.py | 4 +- tools/test_status_effect_parity.py | 4 +- tools/test_status_tick_parity.py | 4 +- tools/test_stepped_interpolation_parity.py | 2 +- tools/test_stored_consume_parity.py | 4 +- tools/test_stored_effect_attributes_parity.py | 4 +- ...test_stored_effect_notifications_parity.py | 4 +- tools/test_structure_density_parity.py | 4 +- tools/test_subtitle_parity.py | 4 +- tools/test_suffocation_parity.py | 4 +- tools/test_swimming_parity.py | 4 +- tools/test_synced_bytes_parity.py | 4 +- tools/test_synced_floats_parity.py | 4 +- tools/test_tab_list_parity.py | 4 +- tools/test_team_rules_parity.py | 4 +- tools/test_teleport_consume_parity.py | 4 +- tools/test_terrain_parity.py | 4 +- tools/test_tick_parity.py | 4 +- tools/test_trading_parity.py | 4 +- tools/test_translucency_parity.py | 2 +- tools/test_tree_feature_parity.py | 4 +- tools/test_trial_spawner_parity.py | 4 +- tools/test_use_flag_reaction_parity.py | 4 +- tools/test_use_remainder_parity.py | 4 +- tools/test_value_provider_parity.py | 4 +- tools/test_vault_parity.py | 4 +- tools/test_view_direction_parity.py | 4 +- tools/test_water_splash_parity.py | 4 +- tools/test_world_border_parity.py | 4 +- tools/test_world_border_render_parity.py | 2 +- tools/test_world_collision_check_parity.py | 4 +- tools/test_world_edge_backoff_parity.py | 4 +- tools/test_world_movement_parity.py | 4 +- tools/test_world_parity.py | 4 +- tools/test_world_ray_parity.py | 4 +- tools/test_world_spawn_parity.py | 4 +- tools/test_worldgen_random_parity.py | 4 +- 227 files changed, 498 insertions(+), 425 deletions(-) diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index c0296cc1c..300872765 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -85,6 +85,11 @@ mods = ["horizon-mods/runtime"] # Records the call sites of mob random draws (`mob_ai_probe` traces). rng-trace = ["horizon-core/rng-trace"] +# Its own name, not `probe`: Cargo copies every crate's examples into one target//examples. +[[example]] +name = "client_probe" +path = "examples/probe/main.rs" + [lints] workspace = true diff --git a/crates/horizon-client/examples/probe/dispatch.rs b/crates/horizon-client/examples/probe/dispatch.rs index b40cf1a6e..8754e944d 100644 --- a/crates/horizon-client/examples/probe/dispatch.rs +++ b/crates/horizon-client/examples/probe/dispatch.rs @@ -41,7 +41,7 @@ pub fn main(names: &[&str], run: fn(&str) -> Option) -> ExitCode { let name = std::env::args().nth(1).unwrap_or_default(); run(&name).unwrap_or_else(|| { eprintln!( - "usage: probe [arguments...]\nprobes: {}", + "usage: client_probe [arguments...]\nprobes: {}", names.join(" ") ); ExitCode::from(2) diff --git a/crates/horizon-protocol/Cargo.toml b/crates/horizon-protocol/Cargo.toml index 05655e8af..71b93a1fe 100644 --- a/crates/horizon-protocol/Cargo.toml +++ b/crates/horizon-protocol/Cargo.toml @@ -17,5 +17,10 @@ sha1 = "0.10" # Secure chat: SHA256withRSA message signatures. sha2 = "0.10" +# Its own name, not `probe`: Cargo copies every crate's examples into one target//examples. +[[example]] +name = "protocol_probe" +path = "examples/probe.rs" + [lints] workspace = true diff --git a/crates/horizon-protocol/examples/probe.rs b/crates/horizon-protocol/examples/probe.rs index 005be919f..63fc0f9d3 100644 --- a/crates/horizon-protocol/examples/probe.rs +++ b/crates/horizon-protocol/examples/probe.rs @@ -2,7 +2,7 @@ //! seconds, reporting packet counts and any decode failures. A differential //! check of the codecs against a real vanilla server: //! -//! cargo run -p horizon-protocol --example probe -- 127.0.0.1:25565 [seconds] [registries.json] +//! cargo run -p horizon-protocol --example protocol_probe -- 127.0.0.1:25565 [seconds] [registries.json] use horizon_protocol::{ PROTOCOL_VERSION, State, connection::Connection, diff --git a/crates/horizon-world/Cargo.toml b/crates/horizon-world/Cargo.toml index 3a8621243..89f82bbe2 100644 --- a/crates/horizon-world/Cargo.toml +++ b/crates/horizon-world/Cargo.toml @@ -25,5 +25,10 @@ path = "src/main.rs" name = "horizon-worldgen-parity" path = "src/bin/worldgen_parity.rs" +# Its own name, not `probe`: Cargo copies every crate's examples into one target//examples. +[[example]] +name = "world_probe" +path = "examples/probe/main.rs" + [lints] workspace = true diff --git a/crates/horizon-world/examples/probe/dispatch.rs b/crates/horizon-world/examples/probe/dispatch.rs index 0b396edab..80b875eef 100644 --- a/crates/horizon-world/examples/probe/dispatch.rs +++ b/crates/horizon-world/examples/probe/dispatch.rs @@ -32,7 +32,7 @@ pub fn main(names: &[&str], run: fn(&str) -> Option) -> ExitCode { let name = std::env::args().nth(1).unwrap_or_default(); run(&name).unwrap_or_else(|| { eprintln!( - "usage: probe [arguments...]\nprobes: {}", + "usage: world_probe [arguments...]\nprobes: {}", names.join(" ") ); ExitCode::from(2) diff --git a/docs/parity-workflow.md b/docs/parity-workflow.md index a2cd10584..1b00080e7 100644 --- a/docs/parity-workflow.md +++ b/docs/parity-workflow.md @@ -26,7 +26,7 @@ Vanilla oracle runs are reused as well. `tools/parity_shim.py` stands in for `ja Probes build into `.local/parity-target/` with release optimisation but no LTO and 16 codegen units. On ludodesktop that rebuilds every `horizon-world` probe in 3 seconds after a one-line change, against 122 seconds with the release profile. Rust gives these settings identical results (no fast-math; overflow checks as in release), and the full harness suite passes under them. Probes that harnesses build in the dev profile get `opt-level = 3` too, keeping their overflow checks and debug assertions. Harnesses must locate binaries through `cargo metadata` or `lab.cargo_target()`, never a hard-coded `target/`. -The probes of `horizon-world` and of `horizon-client` are one binary per crate, `cargo build --release -p --example probe`: a harness runs `probe [arguments]`, and `` is a module in `crates//examples/probe/` (add it to the `mod` list and the `probes!` list in its `main.rs`; read arguments with `crate::args()` or `crate::args_os()`, which drop the name). Code several probes share goes in `examples/probe/support/` or a module of its own. Linking one binary instead of ~250 examples is most of what a probe build used to cost. The runner counts only the probes a harness ran, the probes and support modules they name, their own subdirectories and `dispatch.rs` as its dependencies, not `main.rs`, which only lists the probes: editing one probe reruns only its harnesses, and adding one reruns none. +The probes of `horizon-world` and of `horizon-client` are one binary per crate, `world_probe` and `client_probe` (`cargo build --release -p horizon-world --example world_probe`): a harness runs `world_probe [arguments]`, and `` is a module in `crates//examples/probe/` (add it to the `mod` list and the `probes!` list in its `main.rs`; read arguments with `crate::args()` or `crate::args_os()`, which drop the name). Code several probes share goes in `examples/probe/support/` or a module of its own. Linking one binary instead of ~250 examples is most of what a probe build used to cost. Each crate's probe has its own target name (set in its `Cargo.toml`, `protocol_probe` too): Cargo copies every crate's examples into one `/examples/` directory, and with one shared name a harness could run the binary another harness had just copied there. The runner counts only the probes a harness ran, the probes and support modules they name, their own subdirectories and `dispatch.rs` as its dependencies, not `main.rs`, which only lists the probes: editing one probe reruns only its harnesses, and adding one reruns none. Passes are shared between worktrees. A harness's key depends only on the content of its dependencies, not on where they are, so every pass is also written to `parity-shared/` beside the shared vanilla data (`PARITY_SHARED` overrides it). A worktree whose files match those a harness passed with, in any worktree, counts that pass without running the harness: after merging the integration branch, an agent's gate only runs the harnesses its own changes affect. diff --git a/tests/test_parity_runner.py b/tests/test_parity_runner.py index 633163bf5..eac664c89 100644 --- a/tests/test_parity_runner.py +++ b/tests/test_parity_runner.py @@ -50,7 +50,8 @@ class ParityRunnerTests(unittest.TestCase): ]) def test_a_probe_binary_depends_only_on_the_probes_it_ran(self): - commands = [["/t/release/examples/probe", "a_fixture", "/dir"], ["cargo", "run", "--example", "probe", "--", "b_fixture"]] + commands = [["/t/release/examples/world_probe", "a_fixture", "/dir"], + ["cargo", "run", "-p", "horizon-client", "--example", "client_probe", "--", "b_fixture"]] self.assertEqual(parity.probes_run(commands), {"a_fixture", "b_fixture"}) with tempfile.TemporaryDirectory() as temp, mock.patch.object(parity, "ROOT", Path(temp)): probe = Path(temp, "crates/w/examples/probe") @@ -67,6 +68,40 @@ class ParityRunnerTests(unittest.TestCase): ["crates/w/src/lib.rs", *paths[:2], *paths[3:6], paths[8]]) self.assertEqual(parity.only_probes_run(paths, set()), paths) + def test_probe_names_are_each_crates_own_target(self): + self.assertEqual(parity.probes_run([ + ["C:/t/debug/examples/client_probe.exe", "a_fixture"], + ["cargo", "run", "--release", "--example=world_probe", "--", "b_fixture", "x"], + ["/t/release/examples/probe", "old_fixture"], # the shared name before 2026-10-24 + ["cargo", "run", "--example", "probe", "--", "old_fixture"], + ["/t/release/examples/mod_port_probe", "not_a_fixture"], + ["cargo", "run", "--example", "mod_port_probe", "--", "not_a_fixture"], + ["cargo", "build", "--example", "world_probe"], + ]), {"a_fixture", "b_fixture"}) + + def test_records_of_the_shared_probe_name_build_their_crates_probe(self): + record = {"dependencies": ["crates/horizon-world/examples/probe/a_fixture.rs", "crates/horizon-world/src/lib.rs"], + "artifacts": [["example", "probe", "release", ["-p", "horizon-client"], True], + ["example", "probe", "release"], # no selection: the crate of its probe sources + ["example", "probe", "release", ["-p", "horizon-core", "-p", "horizon-world"], True], + ["bin", "horizon-world", "release", ["-p", "horizon-world"], False]]} + artifacts = parity.recorded_artifacts(record) + self.assertEqual(artifacts, [["example", "client_probe", "release", ["-p", "horizon-client"], True], + ["example", "world_probe", "release"], + ["example", "world_probe", "release", ["-p", "horizon-core", "-p", "horizon-world"], True], + ["bin", "horizon-world", "release", ["-p", "horizon-world"], False]]) + packages = {("example", "client_probe"): "horizon-client", ("example", "world_probe"): "horizon-world", + ("bin", "horizon-world"): "horizon-world"} + self.assertEqual(parity.prebuild_commands(artifacts, packages), [ + ["cargo", "build", "--locked", "--profile", "release", "-p", "horizon-client", "--example", "client_probe"], + ["cargo", "build", "--locked", "--profile", "release", "-p", "horizon-core", "-p", "horizon-world", + "--example", "world_probe"], + ["cargo", "build", "--locked", "--profile", "release", "-p", "horizon-world", "--bin", "horizon-world"], + ["cargo", "build", "--locked", "--profile", "release", "-p", "horizon-world", "--example", "world_probe"], + ]) + self.assertEqual(parity.recorded_artifacts({"artifacts": [["example", "probe", "release"]]}), + [["example", "probe", "release"]]) # no crate to tell: left to its harness + def test_java_sources_include_classes_pulled_from_the_sourcepath(self): with tempfile.TemporaryDirectory() as temp: sources, classes = Path(temp, "src"), Path(temp, "classes") diff --git a/tools/audio_harness.py b/tools/audio_harness.py index 1d5908fe0..99c432d11 100644 --- a/tools/audio_harness.py +++ b/tools/audio_harness.py @@ -65,9 +65,9 @@ def run_harness(name, oracle, example, inputs_text, extra_sources=(), java_args= dependencies = os.pathsep.join(map(str, [jars['client'], *libraries])) run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle_path], 'compile-java') - run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory']) / 'debug/examples' / ('probe.exe' if os.name == 'nt' else 'probe') + binary = Path(metadata['target_directory']) / 'debug/examples' / ('client_probe.exe' if os.name == 'nt' else 'client_probe') run([binary, example, *rust_args, inputs, build / 'rust.txt'], 'rust') env = dict(os.environ, ALSOFT_DRIVERS='null') run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, f'dev.horizonlab.parity.{oracle}', *java_args, inputs, build / 'client.txt'], diff --git a/tools/block_update_harness.py b/tools/block_update_harness.py index 852c013d5..b352836fe 100644 --- a/tools/block_update_harness.py +++ b/tools/block_update_harness.py @@ -133,7 +133,7 @@ def execute(name, cases, args, facts, origin_of=None): '-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaBlockUpdateOracle.java')]) run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaBlockUpdateOracle', str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')]) - run(['cargo', 'run', '-q', '--release', '-p', 'horizon-world', '--example', 'probe', '--', + run(['cargo', 'run', '-q', '--release', '-p', 'horizon-world', '--example', 'world_probe', '--', 'block_update_fixture', str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], cwd=lab.ROOT, env={**os.environ, 'CARGO_BUILD_JOBS': '3'}) ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) native = split_cases((work / 'native.txt').read_text(), ignore) diff --git a/tools/interaction_lab.py b/tools/interaction_lab.py index bc574b73d..894a6d1c4 100644 --- a/tools/interaction_lab.py +++ b/tools/interaction_lab.py @@ -50,7 +50,8 @@ def cargo_example(package, example, *args, profile=None): command = ['cargo', 'run', '-q', '-j3'] if profile: command += ['--profile', profile] - command += ['-p', package, '--example', 'probe', '--', example, *map(str, args)] + probe = package.removeprefix('horizon-') + '_probe' # each crate's probe example: client_probe, world_probe + command += ['-p', package, '--example', probe, '--', example, *map(str, args)] subprocess.run(command, check=True, cwd=lab.ROOT) diff --git a/tools/oracle_harness.py b/tools/oracle_harness.py index c6f45553f..92e2a26a2 100644 --- a/tools/oracle_harness.py +++ b/tools/oracle_harness.py @@ -32,12 +32,12 @@ def compile_oracle(build, oracle_name, jars, libraries, java_major): def build_probe(build, example): """Build the horizon-client probe binary; returns the command that runs probe `example`.""" - run_logged(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'probe'], + run_logged(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'client_probe'], build, 'compile-rust-' + example, env=dict(os.environ, CARGO_BUILD_JOBS='3')) import json metadata = json.loads(subprocess.check_output( ['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - return [Path(metadata['target_directory']) / 'debug/examples/probe', example] + return [Path(metadata['target_directory']) / 'debug/examples/client_probe', example] def java_run(build, classes, dependencies, main_class, args, name, jvm=()): diff --git a/tools/parity.py b/tools/parity.py index a1a9f4133..4ed75f5ef 100644 --- a/tools/parity.py +++ b/tools/parity.py @@ -466,22 +466,44 @@ def narrow_rust_sources(sources, scope): PROBE_SOURCE = re.compile(r"/examples/probe/(?:(support)/)?(\w+)\.rs$") +# Each crate's probe example (crates//examples/probe) and its target name. Until 2026-10-24 they were all +# `probe`, and Cargo copies every crate's examples into one /examples/: a harness could run the binary +# another harness had just copied there. +PROBE_TARGETS = {"horizon-client": "client_probe", "horizon-protocol": "protocol_probe", "horizon-world": "world_probe"} +OLD_PROBE_SOURCE = re.compile(r"crates/([\w-]+)/examples/probe[/.]") def probes_run(commands): - """The probes a harness ran through a crate's probe binary: `probe ...`, or - `cargo run --example probe -- ...`.""" + """The probes a harness ran through a crate's probe binary: `world_probe ...`, or + `cargo run --example world_probe -- ...`.""" names = set() for arguments in commands: - program = Path(arguments[0]).name if arguments else "" - if program in ("probe", "probe.exe") and len(arguments) > 1: + program = Path(arguments[0]).name.removesuffix(".exe") if arguments else "" + if program in PROBE_TARGETS.values() and len(arguments) > 1: names.add(arguments[1]) - elif program == "cargo" and "--" in arguments and "probe" in arguments[:arguments.index("--")] \ - and len(arguments) > arguments.index("--") + 1: + elif program == "cargo" and "--" in arguments and len(arguments) > arguments.index("--") + 1 \ + and any(kind == "example" and name in PROBE_TARGETS.values() for kind, name, *_ in artifacts_of(arguments)): names.add(arguments[arguments.index("--") + 1]) return names +def recorded_artifacts(record): + """A harness record's artifacts, with the shared `probe` target of records from before 2026-10-24 renamed to + its crate's own (PROBE_TARGETS): the crate the record's `-p` selection names, else the one whose probe sources + the harness depended on. The prebuild would otherwise drop them as targets that no longer exist.""" + artifacts = [] + for artifact in record.get("artifacts", []): + if artifact[:2] != ["example", "probe"]: + artifacts.append(artifact) + continue + selection = artifact[3] if len(artifact) > 3 else [] + crates = [value for flag, value in zip(selection, selection[1:]) if flag == "-p" and value in PROBE_TARGETS] \ + or sorted({match.group(1) for path in record.get("dependencies", []) + if (match := OLD_PROBE_SOURCE.match(path)) and match.group(1) in PROBE_TARGETS}) + artifacts += [["example", PROBE_TARGETS[crate], *artifact[2:]] for crate in crates] or [artifact] + return artifacts + + def only_probes_run(paths, names): """A probe binary's dep-info lists every probe in it. Keep those the harness ran, the probes they include! or name (crate::) and the shared support modules they name (support::), so that editing one probe @@ -1323,7 +1345,7 @@ def main(): if not record or "artifacts" not in record: template = SHARED / "dependencies" / f"{name}.json" record = json.loads(template.read_text(encoding="utf-8")) if template.exists() else {} - for artifact in record.get("artifacts", []): + for artifact in recorded_artifacts(record): if artifact not in artifacts: artifacts.append(artifact) config = host_config() diff --git a/tools/port_regen.py b/tools/port_regen.py index c47e7cc35..8ce639f21 100644 --- a/tools/port_regen.py +++ b/tools/port_regen.py @@ -229,9 +229,9 @@ def gen_vanilla_order(root, version, store, build): "dev.horizonlab.parity.VanillaCommandParseOracle", "tree", build], build) env = dict(os.environ, CARGO_TARGET_DIR=str(root / ".local" / "port-target")) jobs = os.environ.get("FLEET_LOAD_JOBS") - run(["cargo", "build", "-p", "horizon-client", "--example", "probe", + run(["cargo", "build", "-p", "horizon-client", "--example", "client_probe", *(["-j", jobs] if jobs else [])], root, env=env) - fixture = root / ".local/port-target/debug/examples/probe" + fixture = root / ".local/port-target/debug/examples/client_probe" run([fixture, "command_parse_fixture", "tree", build / "rust_tree.json"], root) return [python(), "tools/generate_command_order.py", build / "tree.json", build / "rust_tree.json"] diff --git a/tools/test_active_effect_tick_parity.py b/tools/test_active_effect_tick_parity.py index dcb34ae21..58c24511a 100644 --- a/tools/test_active_effect_tick_parity.py +++ b/tools/test_active_effect_tick_parity.py @@ -72,9 +72,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaActiveEffectTickOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_active_effects_parity.py b/tools/test_active_effects_parity.py index 926c2ecf8..10750d43a 100644 --- a/tools/test_active_effects_parity.py +++ b/tools/test_active_effects_parity.py @@ -61,9 +61,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaActiveEffectsOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_anchor_parity.py b/tools/test_anchor_parity.py index 19b8f6e4b..842a8517e 100644 --- a/tools/test_anchor_parity.py +++ b/tools/test_anchor_parity.py @@ -53,9 +53,9 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"anchor_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_arrow_parity.py b/tools/test_arrow_parity.py index 72692eb55..ab6e690be 100644 --- a/tools/test_arrow_parity.py +++ b/tools/test_arrow_parity.py @@ -241,9 +241,9 @@ def main(): expected = 3 * operations + len(fixtures) (build / 'inputs.txt').write_text(''.join(json.dumps(f, separators=(',', ':')) + '\n' for f in fixtures)) input_hash = lab.digest(build / 'inputs.txt', 'sha256') - run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory']) / 'debug/examples' / ('probe.exe' if os.name=='nt' else 'probe') + binary = Path(metadata['target_directory']) / 'debug/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe') run([binary, 'arrow_probe',resources, build, '--describe'], 'describe') references = [] for side, jar in jars.items(): diff --git a/tools/test_attribute_health_parity.py b/tools/test_attribute_health_parity.py index eaf06d857..56ace7972 100644 --- a/tools/test_attribute_health_parity.py +++ b/tools/test_attribute_health_parity.py @@ -59,9 +59,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaAttributeHealthOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'catalog.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'attribute_health_fixture',build],'rust');run([binary,'attribute_health_fixture',build,'live'],'rust-live');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_attribute_map_queries_parity.py b/tools/test_attribute_map_queries_parity.py index ca222a07c..06048bf7b 100644 --- a/tools/test_attribute_map_queries_parity.py +++ b/tools/test_attribute_map_queries_parity.py @@ -82,9 +82,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaAttributeMapQueriesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_attribute_parity.py b/tools/test_attribute_parity.py index 02051188d..d65486c21 100644 --- a/tools/test_attribute_parity.py +++ b/tools/test_attribute_parity.py @@ -89,9 +89,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaAttributeOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'attributes.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'attributes.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'attribute_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_attribute_updates_parity.py b/tools/test_attribute_updates_parity.py index cc4f70d1a..3cd33a4d6 100644 --- a/tools/test_attribute_updates_parity.py +++ b/tools/test_attribute_updates_parity.py @@ -70,9 +70,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaAttributeUpdatesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_basic_feature_parity.py b/tools/test_basic_feature_parity.py index 2de93cd1a..69612bedb 100644 --- a/tools/test_basic_feature_parity.py +++ b/tools/test_basic_feature_parity.py @@ -71,9 +71,9 @@ def main(): fixture_paths.append(path) if json.loads((build/"facts-client.json").read_text())!=json.loads((build/"facts-server.json").read_text()):raise ValueError("reference feature block states differ") tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"basic_feature_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_biome_chunk_parity.py b/tools/test_biome_chunk_parity.py index f24370455..a431036ff 100644 --- a/tools/test_biome_chunk_parity.py +++ b/tools/test_biome_chunk_parity.py @@ -57,9 +57,9 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=3600,stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"biome_chunk_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_biome_generation_parity.py b/tools/test_biome_generation_parity.py index 67c642585..7124cd742 100644 --- a/tools/test_biome_generation_parity.py +++ b/tools/test_biome_generation_parity.py @@ -76,9 +76,9 @@ def main(): registries=build/'registries.json';registries.write_text(json.dumps(bundle,separators=(',',':')),encoding='utf-8') fixtures=list(corpus(bundle));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') fixture_paths=[inputs,registries,*exports];tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"biome_generation_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_biome_placement_parity.py b/tools/test_biome_placement_parity.py index caf99b7c9..8250cecb5 100644 --- a/tools/test_biome_placement_parity.py +++ b/tools/test_biome_placement_parity.py @@ -53,9 +53,9 @@ def main(): with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle,helper],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'biome_placement_fixture',build],'rust');references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependency_path]),'dev.horizonlab.parity.VanillaBiomePlacementOracle',side,build],side) diff --git a/tools/test_biome_source_codec_parity.py b/tools/test_biome_source_codec_parity.py index 9363378af..c40b1c84e 100644 --- a/tools/test_biome_source_codec_parity.py +++ b/tools/test_biome_source_codec_parity.py @@ -95,9 +95,9 @@ def main(): fixtures=list(corpus(bundle));inputs=build/'inputs.txt';inputs.write_text('\n'.join(fixtures)+'\n',encoding='utf-8') (build/'positions.json').write_text(json.dumps(positions(),separators=(',',':')),encoding='utf-8') fixture_paths=[inputs,*exports,build/'positions.json',*[build/(name+'.json') for name in bundle]];tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"biome_source_codec_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_biome_source_parity.py b/tools/test_biome_source_parity.py index 7616f7545..6969e8562 100644 --- a/tools/test_biome_source_parity.py +++ b/tools/test_biome_source_parity.py @@ -44,9 +44,9 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"biome_source_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_biome_temperature_parity.py b/tools/test_biome_temperature_parity.py index af8d75976..e4c07c03a 100644 --- a/tools/test_biome_temperature_parity.py +++ b/tools/test_biome_temperature_parity.py @@ -82,9 +82,9 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"biome_temperature_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_block_collision_scan_parity.py b/tools/test_block_collision_scan_parity.py index a59bfd8f9..86dc4fc5d 100644 --- a/tools/test_block_collision_scan_parity.py +++ b/tools/test_block_collision_scan_parity.py @@ -68,9 +68,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBlockCollisionScanOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'block_collision_scan_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_block_entity_anim_parity.py b/tools/test_block_entity_anim_parity.py index b0c462aee..41f048436 100755 --- a/tools/test_block_entity_anim_parity.py +++ b/tools/test_block_entity_anim_parity.py @@ -279,7 +279,7 @@ def main(): *(PARITY / f'{n}.java' for n in ('ParityData', 'VanillaBlockEntityAnimOracle'))], 'compile-java') run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaBlockEntityAnimOracle', inputs, build / 'vanilla.txt'], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe', '--', 'block_entity_anim_fixture', resources, inputs, build / 'rust.txt'], 'rust') def split(path): diff --git a/tools/test_block_entity_render_parity.py b/tools/test_block_entity_render_parity.py index 901f4300f..27e740191 100644 --- a/tools/test_block_entity_render_parity.py +++ b/tools/test_block_entity_render_parity.py @@ -303,7 +303,7 @@ def main(): vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] textures = sorted({s['texture'] for v in vanilla for s in v.get('submits', []) if 'texture' in s}) (build / 'textures.txt').write_text(''.join(t + '\n' for t in textures)) - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe', '--', 'block_entity_render_fixture', resources, inputs, build / 'textures.txt', build / 'rust.jsonl'], 'rust') rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] assert len(vanilla) == len(rust), (len(vanilla), len(rust)) diff --git a/tools/test_block_entity_storage_parity.py b/tools/test_block_entity_storage_parity.py index a1f378f31..5d9acd966 100644 --- a/tools/test_block_entity_storage_parity.py +++ b/tools/test_block_entity_storage_parity.py @@ -75,9 +75,9 @@ def main(): with (build/(name+'.log')).open('w') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=3600,stdout=log,stderr=subprocess.STDOUT) dependencies=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependencies,'-d',classes,oracle],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'block_entity_storage_fixture',inputs,build/'rust.txt'],'rust') references=[] for side,jar in jars.items(): diff --git a/tools/test_block_entity_tickers_parity.py b/tools/test_block_entity_tickers_parity.py index 66a84cf48..d8e19c740 100644 --- a/tools/test_block_entity_tickers_parity.py +++ b/tools/test_block_entity_tickers_parity.py @@ -120,7 +120,7 @@ def main(): run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaBlockEntityTickerOracle', inputs, build / 'vanilla.txt'], 'vanilla') run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', - 'probe', '--', 'block_entity_tickers_fixture', inputs, build / 'rust.txt'], 'rust') + 'client_probe', '--', 'block_entity_tickers_fixture', inputs, build / 'rust.txt'], 'rust') matched = base.compare(build / 'vanilla.txt', build / 'rust.txt') ticks = sum(1 for line in lines if line == 'tick') listed = sum(len(line.split()) - 1 for line in (build / 'vanilla.txt').read_text().splitlines()) diff --git a/tools/test_block_landing_parity.py b/tools/test_block_landing_parity.py index 822ff1614..33789992a 100644 --- a/tools/test_block_landing_parity.py +++ b/tools/test_block_landing_parity.py @@ -69,8 +69,8 @@ def main(): with (build/'inputs.txt').open('w') as output: for f in corpus(states,definitions):output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 fixture_paths=[build/n for n in ['inputs.txt','landing-states.json','landing-definitions.json','movement-properties.nbt','block-registry.nbt','cached-collision.nbt']];fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust') - metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run(['cargo','build','--locked','--release','-p','horizon-world','--example','world_probe'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'block_landing_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side);matched=base.compare(build/(side+'.txt'),build/'rust.txt');references.append(dict(side=side,jar_sha256=lab.digest(jar,'sha256'),output_sha256=lab.digest(build/(side+'.txt'),'sha256'),matched_output_lines=matched));print(f'{side}: {matched:,} registered block landing lines match',flush=True) diff --git a/tools/test_block_properties_parity.py b/tools/test_block_properties_parity.py index 28cd2832c..bca33c11c 100644 --- a/tools/test_block_properties_parity.py +++ b/tools/test_block_properties_parity.py @@ -57,9 +57,9 @@ def main(): java('server','export',build) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'block-registry.nbt',build/'cached-collision.nbt',build/'block-properties.nbt'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'block_properties_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_block_push_parity.py b/tools/test_block_push_parity.py index 986a3b1c9..6c752b98c 100644 --- a/tools/test_block_push_parity.py +++ b/tools/test_block_push_parity.py @@ -53,9 +53,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBlockPushOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'block_push_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_block_state_codec_parity.py b/tools/test_block_state_codec_parity.py index e6db50860..ca05c92d9 100644 --- a/tools/test_block_state_codec_parity.py +++ b/tools/test_block_state_codec_parity.py @@ -60,9 +60,9 @@ def main(): if len(facts['states'])!=35723:raise ValueError('incomplete pinned state registry') fixtures=list(corpus(facts));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'facts-client.json',build/'facts-server.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'block_state_codec_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_block_support_parity.py b/tools/test_block_support_parity.py index 928f099d1..7b3b77274 100644 --- a/tools/test_block_support_parity.py +++ b/tools/test_block_support_parity.py @@ -35,9 +35,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBlockSupportOracle',mode,path],side+'-'+mode) java('server','export',build) fixture_paths=[build/'block-registry.nbt',build/'cached-support.nbt'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'block_support_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_block_survival_parity.py b/tools/test_block_survival_parity.py index 2d99db9e2..7eca89332 100644 --- a/tools/test_block_survival_parity.py +++ b/tools/test_block_survival_parity.py @@ -236,9 +236,9 @@ def main(): output.write(json.dumps(fixture,separators=(',',':'))+'\n');fixture_count+=1 fixture_paths=[inputs,build/'survival-extra-definitions.json',build/'fluid-tags.json',build/'survival-placement-classes.json',build/'survival-support-tags.json',build/'facts.json',build/'survival-classes.json',build/'survival-rules.json',build/'tags.json',build/'block-registry.nbt',build/'cached-collision.nbt',build/'block-properties.nbt',build/'cached-support.nbt'] tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') base.ensure_sources_unchanged(sources,tested_sources) checkpoint={'schema':1,'environment':environment,'sources_sha256':tested_sources,'fixtures_sha256':{str(lab.ROOT/name):digest for name,digest in tested_fixtures.items()},'artifacts_sha256':{str(path):lab.digest(path,'sha256') for path in [binary,*sorted(classes.rglob('*.class'))]},'binary':str(binary),'counts':{'supported_blocks':len(definitions),'supported_states':sum(state['id'] in definitions for state in facts['states']),'survival_rules':len(set(definitions.values())),'survival_rule_kinds':len({rule.split(':',1)[0] for rule in definitions.values()}),'fluid_tag_files':len(fluid_tags),'fixtures':fixture_count},'outputs':{}} save_checkpoint(checkpoint_path,checkpoint) diff --git a/tools/test_blocking_item_damage_parity.py b/tools/test_blocking_item_damage_parity.py index b8b3ea251..ea313c3da 100644 --- a/tools/test_blocking_item_damage_parity.py +++ b/tools/test_blocking_item_damage_parity.py @@ -60,9 +60,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBlockingItemDamageOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'blocking_item_damage_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_blocking_rules_parity.py b/tools/test_blocking_rules_parity.py index 2ff5763d6..95141670a 100644 --- a/tools/test_blocking_rules_parity.py +++ b/tools/test_blocking_rules_parity.py @@ -60,9 +60,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBlockingRulesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'blocking_rules_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_bulk_section_parity.py b/tools/test_bulk_section_parity.py index b9a9ae3a8..9364e29b6 100644 --- a/tools/test_bulk_section_parity.py +++ b/tools/test_bulk_section_parity.py @@ -70,9 +70,9 @@ def main(): (build/"tags.json").write_text(json.dumps(tags,separators=(",",":")),encoding="utf-8") fixture_paths=[inputs,build/"tags.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"bulk_section_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_bundle_weight_parity.py b/tools/test_bundle_weight_parity.py index c509e08a1..7d3047dab 100644 --- a/tools/test_bundle_weight_parity.py +++ b/tools/test_bundle_weight_parity.py @@ -64,9 +64,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBundleWeightOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'bundle_weight_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_canyon_carver_parity.py b/tools/test_canyon_carver_parity.py index 25fbc30de..2122000a3 100644 --- a/tools/test_canyon_carver_parity.py +++ b/tools/test_canyon_carver_parity.py @@ -65,9 +65,9 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,helper],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"canyon_carver_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_carving_geometry_parity.py b/tools/test_carving_geometry_parity.py index e69331bbe..42275cc15 100644 --- a/tools/test_carving_geometry_parity.py +++ b/tools/test_carving_geometry_parity.py @@ -72,9 +72,9 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"carving_geometry_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_carving_mask_parity.py b/tools/test_carving_mask_parity.py index 15dacf52e..873d5bb07 100644 --- a/tools/test_carving_mask_parity.py +++ b/tools/test_carving_mask_parity.py @@ -65,9 +65,9 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"carving_mask_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_cave_carver_parity.py b/tools/test_cave_carver_parity.py index d79914762..8edefb42e 100644 --- a/tools/test_cave_carver_parity.py +++ b/tools/test_cave_carver_parity.py @@ -60,9 +60,9 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,helper],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"cave_carver_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_chunk_generation_parity.py b/tools/test_chunk_generation_parity.py index 6951e4355..1cd495eb6 100644 --- a/tools/test_chunk_generation_parity.py +++ b/tools/test_chunk_generation_parity.py @@ -71,9 +71,9 @@ class Oracle: def rust_binary(): - subprocess.run(['cargo', 'build', '--release', '-q', '-p', 'horizon-world', '--example', 'probe'], check=True, cwd=lab.ROOT) + subprocess.run(['cargo', 'build', '--release', '-q', '-p', 'horizon-world', '--example', 'world_probe'], check=True, cwd=lab.ROOT) metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - return Path(metadata['target_directory']) / 'release/examples/probe' + return Path(metadata['target_directory']) / 'release/examples/world_probe' def run_rust(binary, out, seed, dimension, rects, scan=False): diff --git a/tools/test_chunk_stage_parity.py b/tools/test_chunk_stage_parity.py index b8aaa6153..691bab709 100644 --- a/tools/test_chunk_stage_parity.py +++ b/tools/test_chunk_stage_parity.py @@ -73,9 +73,9 @@ def main(): (build/"tags.json").write_text(json.dumps(tags,separators=(",",":")),encoding="utf-8") fixture_paths=[inputs,build/"tags.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"chunk_stage_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_chunk_status_parity.py b/tools/test_chunk_status_parity.py index 17c3d65ed..b6f45a539 100644 --- a/tools/test_chunk_status_parity.py +++ b/tools/test_chunk_status_parity.py @@ -42,9 +42,9 @@ def main(): with (build/(name+'.log')).open('w') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=3600,stdout=log,stderr=subprocess.STDOUT) dependencies=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependencies,'-d',classes,oracle],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'chunk_status_fixture',inputs,build/'rust.txt'],'rust') references=[] for side,jar in jars.items(): diff --git a/tools/test_climbing_parity.py b/tools/test_climbing_parity.py index 7b54fc4fb..1b61b1142 100644 --- a/tools/test_climbing_parity.py +++ b/tools/test_climbing_parity.py @@ -54,7 +54,7 @@ def main(): with (build/'inputs.txt').open('w') as output: for f in corpus(info):output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 fixture_paths=[build/n for n in ['inputs.txt','info.json','block-registry.nbt','tags.json']];fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'climbing_fixture',build],'rust');references=[] + run(['cargo','build','--locked','--release','-p','horizon-world','--example','world_probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe');run([binary,'climbing_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side);matched=base.compare(build/(side+'.txt'),build/'rust.txt');references.append(dict(side=side,jar_sha256=lab.digest(jar,'sha256'),output_sha256=lab.digest(build/(side+'.txt'),'sha256'),matched_output_lines=matched));print(f'{side}: {matched:,} climbing output lines match Rust',flush=True) base.ensure_sources_unchanged(sources,tested);base.ensure_sources_unchanged(fixture_paths,fixtures) diff --git a/tools/test_collision_context_parity.py b/tools/test_collision_context_parity.py index da1f382db..a0178725b 100644 --- a/tools/test_collision_context_parity.py +++ b/tools/test_collision_context_parity.py @@ -59,9 +59,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaCollisionContextOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'collision_context_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_collision_parity.py b/tools/test_collision_parity.py index 3031e47b2..ad99ab960 100644 --- a/tools/test_collision_parity.py +++ b/tools/test_collision_parity.py @@ -51,9 +51,9 @@ def main(): result.check_returncode() return result.stdout expected = counts(java("server", "generate")) - test_rust_parity.run(["cargo", "build", "--release", "-p", "horizon-world", "--example", "probe"]) + test_rust_parity.run(["cargo", "build", "--release", "-p", "horizon-world", "--example", "world_probe"]) metadata = json.loads(subprocess.check_output(["cargo", "metadata", "--no-deps", "--format-version", "1"], cwd=lab.ROOT, text=True)) - binary = Path(metadata["target_directory"]) / "release/examples" / ("probe.exe" if os.name=="nt" else "probe") + binary = Path(metadata["target_directory"]) / "release/examples" / ("world_probe.exe" if os.name=="nt" else "world_probe") actual = counts(subprocess.check_output([str(binary), "collision_fixture", str(base)], cwd=lab.ROOT, text=True)) if actual != expected: raise AssertionError(f"Collision coverage differs: vanilla={expected}, Rust={actual}") diff --git a/tools/test_combat_rules_parity.py b/tools/test_combat_rules_parity.py index 642c0603d..389f075ae 100644 --- a/tools/test_combat_rules_parity.py +++ b/tools/test_combat_rules_parity.py @@ -57,9 +57,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaCombatRulesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'combat_rules_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_command_parse_parity.py b/tools/test_command_parse_parity.py index c43e66b54..620fb548d 100644 --- a/tools/test_command_parse_parity.py +++ b/tools/test_command_parse_parity.py @@ -64,9 +64,9 @@ def main(): registries = json.loads((build / 'registries.json').read_text()) corpus = corpus_module.corpus(tree, registries) (build / 'corpus.txt').write_text(''.join(line + '\n' for line in corpus), encoding='utf-8') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') + binary = Path(metadata['target_directory']) / 'release/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe') resources = lab.RESOURCES total_failures = 0 summary = [] diff --git a/tools/test_component_durability_parity.py b/tools/test_component_durability_parity.py index e912fa80b..f786f9897 100644 --- a/tools/test_component_durability_parity.py +++ b/tools/test_component_durability_parity.py @@ -71,9 +71,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaComponentDurabilityOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'component_durability_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_component_patch_parity.py b/tools/test_component_patch_parity.py index bae69bb56..f57868613 100644 --- a/tools/test_component_patch_parity.py +++ b/tools/test_component_patch_parity.py @@ -57,9 +57,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaComponentPatchOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'component_patch_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_consumable_emission_parity.py b/tools/test_consumable_emission_parity.py index 7e8085087..267aae3ec 100644 --- a/tools/test_consumable_emission_parity.py +++ b/tools/test_consumable_emission_parity.py @@ -55,9 +55,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaConsumableEmissionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'consumable_emission_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_consumable_parity.py b/tools/test_consumable_parity.py index 083ff810f..3bb8fc4eb 100644 --- a/tools/test_consumable_parity.py +++ b/tools/test_consumable_parity.py @@ -61,9 +61,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaConsumableOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'consumable_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_consume_effect_parity.py b/tools/test_consume_effect_parity.py index 4f4037073..38820beea 100644 --- a/tools/test_consume_effect_parity.py +++ b/tools/test_consume_effect_parity.py @@ -55,9 +55,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaConsumeEffectOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'consume_effect_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_contextual_collision_parity.py b/tools/test_contextual_collision_parity.py index bbfe45b02..bd82be1ca 100644 --- a/tools/test_contextual_collision_parity.py +++ b/tools/test_contextual_collision_parity.py @@ -48,9 +48,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars['server']),dependency_path]),'dev.horizonlab.parity.VanillaCollisionOracle','generate',build],'export') fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'block-registry.nbt',build/'cached-collision.nbt'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'collision_context_fixture',build],'rust');references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependency_path]),'dev.horizonlab.parity.VanillaContextualCollisionAudit',side,build],side+'-audit') diff --git a/tools/test_damage_immunity_parity.py b/tools/test_damage_immunity_parity.py index d68277dd8..b788ca464 100644 --- a/tools/test_damage_immunity_parity.py +++ b/tools/test_damage_immunity_parity.py @@ -57,9 +57,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaDamageImmunityOracle',mode,path],side+'-'+mode) java('server','export',build);fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'slots.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'damage_immunity_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_damage_reduction_parity.py b/tools/test_damage_reduction_parity.py index 06c827dcf..bdb526615 100644 --- a/tools/test_damage_reduction_parity.py +++ b/tools/test_damage_reduction_parity.py @@ -65,9 +65,9 @@ def main(): java('server','export',build) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'slots.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'damage_reduction_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_damage_source_parity.py b/tools/test_damage_source_parity.py index 75f360822..2c8b6d228 100644 --- a/tools/test_damage_source_parity.py +++ b/tools/test_damage_source_parity.py @@ -56,9 +56,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaDamageSourceOracle',mode,path],side+'-'+mode) java('server','export',build);catalog=json.loads((build/'catalog.json').read_text());fixtures=list(corpus(catalog));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json',build/'types.json',build/'tags.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'damage_source_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_datafix_parity.py b/tools/test_datafix_parity.py index dc5a2495b..cfaa5c2b4 100644 --- a/tools/test_datafix_parity.py +++ b/tools/test_datafix_parity.py @@ -72,11 +72,11 @@ def java_classpath(): def build_rust(): - subprocess.run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], + subprocess.run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'world_probe'], cwd=ROOT, check=True) meta = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=ROOT)) - return Path(meta['target_directory']) / 'release' / 'examples' / 'probe' + return Path(meta['target_directory']) / 'release' / 'examples' / 'world_probe' def run_vanilla(classpath, world, out, target=None): diff --git a/tools/test_decoration_parity.py b/tools/test_decoration_parity.py index ae8c7ce02..3958b4d90 100644 --- a/tools/test_decoration_parity.py +++ b/tools/test_decoration_parity.py @@ -75,9 +75,9 @@ def main(): with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle,helper],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'decoration_fixture',build],'rust');references=[] for side,jar in jars.items(): run(['java','-Xmx768M','-cp',os.pathsep.join([str(classes),str(jar),dependency_path]),'dev.horizonlab.parity.VanillaDecorationOracle',side,build],side) diff --git a/tools/test_decoration_region_parity.py b/tools/test_decoration_region_parity.py index c91ab86e8..5e31d1e1a 100644 --- a/tools/test_decoration_region_parity.py +++ b/tools/test_decoration_region_parity.py @@ -73,9 +73,9 @@ def main(): (build/"tags.json").write_text(json.dumps(tags,separators=(",",":")),encoding="utf-8") fixture_paths=[inputs,build/"tags.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"decoration_region_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_dynamic_support_parity.py b/tools/test_dynamic_support_parity.py index 76beb65c8..9ee27d5af 100644 --- a/tools/test_dynamic_support_parity.py +++ b/tools/test_dynamic_support_parity.py @@ -82,9 +82,9 @@ def main(): if len(states)!=199:raise ValueError('incomplete uncached support registry') fixtures=list(collision_corpus(facts,states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'facts.json',build/'uncached-states.json',build/'block-registry.nbt',build/'cached-collision.nbt'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'dynamic_support_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_edge_backoff_parity.py b/tools/test_edge_backoff_parity.py index 58d5ba8dd..b273ab26b 100644 --- a/tools/test_edge_backoff_parity.py +++ b/tools/test_edge_backoff_parity.py @@ -56,9 +56,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEdgeBackoffOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'edge_backoff_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_effect_attribute_modifiers_parity.py b/tools/test_effect_attribute_modifiers_parity.py index 9fd9694aa..5d0a4dacd 100644 --- a/tools/test_effect_attribute_modifiers_parity.py +++ b/tools/test_effect_attribute_modifiers_parity.py @@ -123,9 +123,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEffectAttributeModifiersOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'effect_attribute_modifiers_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_effect_notifications_parity.py b/tools/test_effect_notifications_parity.py index e39258a8b..7f11af36f 100644 --- a/tools/test_effect_notifications_parity.py +++ b/tools/test_effect_notifications_parity.py @@ -76,9 +76,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEffectNotificationsOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_effect_sync_parity.py b/tools/test_effect_sync_parity.py index 5aeeae09b..76227970f 100644 --- a/tools/test_effect_sync_parity.py +++ b/tools/test_effect_sync_parity.py @@ -129,9 +129,9 @@ def main(): inputs.write_text(''.join(json.dumps(row, separators=(',', ':')) + '\n' for row in fixtures), encoding='utf-8') fixture_paths = [inputs, build / 'catalog.json', build / 'catalog-client.json', build / 'catalog-server.json'] tested_fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'world_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') + binary = Path(metadata['target_directory']) / 'release/examples' / ('world_probe.exe' if os.name=='nt' else 'world_probe') references = [] for side, jar in jars.items(): java(side, side) diff --git a/tools/test_enchanting_parity.py b/tools/test_enchanting_parity.py index 9f5f5647f..35f0777c8 100644 --- a/tools/test_enchanting_parity.py +++ b/tools/test_enchanting_parity.py @@ -56,9 +56,9 @@ def main(): with (build / (name + '.log')).open('w', encoding='utf-8') as log: base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT) run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'), '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') + binary = Path(metadata['target_directory']) / 'release/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe') run([binary, 'enchanting_fixture',resources, inputs, build / 'rust.txt'], 'rust') references = [] for side in ['server']: diff --git a/tools/test_entity_attribute_parity.py b/tools/test_entity_attribute_parity.py index 045488ee3..ba7b62748 100644 --- a/tools/test_entity_attribute_parity.py +++ b/tools/test_entity_attribute_parity.py @@ -54,9 +54,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEntityAttributeOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'catalog.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'entity_attribute_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_entity_collision_parity.py b/tools/test_entity_collision_parity.py index 6fe12a7aa..5a632cfa5 100644 --- a/tools/test_entity_collision_parity.py +++ b/tools/test_entity_collision_parity.py @@ -65,9 +65,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEntityCollisionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'entity_collision_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_entity_death_loot_parity.py b/tools/test_entity_death_loot_parity.py index b0f77cbfd..07c77b0b8 100644 --- a/tools/test_entity_death_loot_parity.py +++ b/tools/test_entity_death_loot_parity.py @@ -139,9 +139,9 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx2G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaEntityDeathLootOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/probe' + binary = Path(metadata['target_directory']) / 'release/examples/client_probe' run([binary, 'entity_death_loot_fixture', resources, inputs, build / 'rust.txt'], 'rust') errors = [l for l in (build / 'server.txt').read_text().splitlines() if l.startswith('error ')] if errors: diff --git a/tools/test_entity_fluid_parity.py b/tools/test_entity_fluid_parity.py index 712db03b5..b37a3e11d 100644 --- a/tools/test_entity_fluid_parity.py +++ b/tools/test_entity_fluid_parity.py @@ -79,9 +79,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEntityFluidOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'entity_fluid_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_entity_fluid_tick_parity.py b/tools/test_entity_fluid_tick_parity.py index 58380bd03..1aa2cf839 100644 --- a/tools/test_entity_fluid_tick_parity.py +++ b/tools/test_entity_fluid_tick_parity.py @@ -64,9 +64,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEntityFluidOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'entity_fluid_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_entity_model_parity.py b/tools/test_entity_model_parity.py index ba54797fa..0cfc509f3 100644 --- a/tools/test_entity_model_parity.py +++ b/tools/test_entity_model_parity.py @@ -364,7 +364,7 @@ def main(): run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', dependencies, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaEntityAnimOracle', inputs, build / 'vanilla.jsonl', jars['client']], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe', '--', 'entity_anim_fixture', resources, build / 'vanilla.jsonl', build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] diff --git a/tools/test_entity_move_parity.py b/tools/test_entity_move_parity.py index d17bb2444..5d8f0814b 100644 --- a/tools/test_entity_move_parity.py +++ b/tools/test_entity_move_parity.py @@ -56,9 +56,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEntityMoveOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'entity_move_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_entity_obstruction_parity.py b/tools/test_entity_obstruction_parity.py index 210c2080f..d600904c0 100644 --- a/tools/test_entity_obstruction_parity.py +++ b/tools/test_entity_obstruction_parity.py @@ -61,9 +61,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEntityObstructionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'entity_obstruction_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_environment_render_parity.py b/tools/test_environment_render_parity.py index 893a1c70d..50d14337d 100755 --- a/tools/test_environment_render_parity.py +++ b/tools/test_environment_render_parity.py @@ -66,7 +66,7 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx1G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaEnvironmentOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe', '--', 'environment_fixture', resources, inputs, build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] diff --git a/tools/test_extra_items_parity.py b/tools/test_extra_items_parity.py index 83752e515..b2dcfb17c 100644 --- a/tools/test_extra_items_parity.py +++ b/tools/test_extra_items_parity.py @@ -67,9 +67,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaExtraItemsOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'extra_items_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_face_support_parity.py b/tools/test_face_support_parity.py index ad6db8922..3a8ae8783 100644 --- a/tools/test_face_support_parity.py +++ b/tools/test_face_support_parity.py @@ -61,9 +61,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFaceSupportOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'face_support_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_face_visibility_parity.py b/tools/test_face_visibility_parity.py index fa8c6696a..c63526ff6 100644 --- a/tools/test_face_visibility_parity.py +++ b/tools/test_face_visibility_parity.py @@ -71,9 +71,9 @@ def main(): for a,b in pairs(definitions):output.write(f'{a} {b}\n');pair_count+=1 fixture_paths = [build/name for name in ['pairs.txt','block-registry.nbt','occlusion.nbt','definitions.json','tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--locked','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata = json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary = Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'face_visibility_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side) diff --git a/tools/test_fall_damage_parity.py b/tools/test_fall_damage_parity.py index 585084eb4..7b78c8e46 100644 --- a/tools/test_fall_damage_parity.py +++ b/tools/test_fall_damage_parity.py @@ -57,9 +57,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFallDamageOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'fall_damage_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_feature_catalog_parity.py b/tools/test_feature_catalog_parity.py index 52a19a652..5a8b4aac7 100644 --- a/tools/test_feature_catalog_parity.py +++ b/tools/test_feature_catalog_parity.py @@ -100,9 +100,9 @@ def main(): fixture_paths.append(path) if json.loads((build/"facts-client.json").read_text())!=json.loads((build/"facts-server.json").read_text()):raise ValueError("reference feature block states differ") tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"feature_catalog_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_feature_graph_parity.py b/tools/test_feature_graph_parity.py index 553baaf09..96d066771 100644 --- a/tools/test_feature_graph_parity.py +++ b/tools/test_feature_graph_parity.py @@ -83,9 +83,9 @@ def main(): fixture_paths.append(path) if json.loads((build/"facts-client.json").read_text())!=json.loads((build/"facts-server.json").read_text()):raise ValueError("reference feature block states differ") tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"feature_graph_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_feature_placement_parity.py b/tools/test_feature_placement_parity.py index 58dc3167a..6230fc20c 100644 --- a/tools/test_feature_placement_parity.py +++ b/tools/test_feature_placement_parity.py @@ -87,9 +87,9 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,helper],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"feature_placement_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_feature_region_parity.py b/tools/test_feature_region_parity.py index 2cc8d78a7..c1f1bf5d8 100644 --- a/tools/test_feature_region_parity.py +++ b/tools/test_feature_region_parity.py @@ -107,9 +107,9 @@ def main(): height_inputs=build/'heights.json';height_inputs.write_text(json.dumps(heights,separators=(',',':'))) fixture_paths=[height_inputs,zone_inputs,inputs,build/"tags.json",build/"fluid-tags.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"feature_region_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_feature_sort_parity.py b/tools/test_feature_sort_parity.py index 6c0e4a44e..351e846aa 100644 --- a/tools/test_feature_sort_parity.py +++ b/tools/test_feature_sort_parity.py @@ -64,9 +64,9 @@ def main(): with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'feature_sort_fixture',build],'rust');references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependency_path]),'dev.horizonlab.parity.VanillaFeatureSortOracle',side,build],side) diff --git a/tools/test_fill_layer_parity.py b/tools/test_fill_layer_parity.py index b23521d02..1ca2593d5 100644 --- a/tools/test_fill_layer_parity.py +++ b/tools/test_fill_layer_parity.py @@ -60,9 +60,9 @@ def main(): fixtures=list(corpus(facts));inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths.append(inputs) tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"fill_layer_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_finalize_spawn_parity.py b/tools/test_finalize_spawn_parity.py index c3130d380..7d581fefc 100644 --- a/tools/test_finalize_spawn_parity.py +++ b/tools/test_finalize_spawn_parity.py @@ -148,9 +148,9 @@ def main(): print(f'{len(vanilla)} oracle lines') return halloween = vanilla[0].split()[1] - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/probe' + binary = Path(metadata['target_directory']) / 'release/examples/client_probe' run([binary, 'finalize_spawn_fixture', resources, inputs, build / 'rust.txt', halloween], 'rust') rust = (build / 'rust.txt').read_text().splitlines() bad = [(a, b) for a, b in zip(vanilla, rust) if a != b] diff --git a/tools/test_fluid_box_parity.py b/tools/test_fluid_box_parity.py index 1b4e7743c..0f1385d52 100644 --- a/tools/test_fluid_box_parity.py +++ b/tools/test_fluid_box_parity.py @@ -58,9 +58,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFluidBoxOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'fluid_box_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_fluid_flow_parity.py b/tools/test_fluid_flow_parity.py index ef1606d91..c8efeea0d 100644 --- a/tools/test_fluid_flow_parity.py +++ b/tools/test_fluid_flow_parity.py @@ -67,9 +67,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFluidFlowOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'fluid-states.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'fluid-states.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'fluid_flow_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_fluid_occupancy_parity.py b/tools/test_fluid_occupancy_parity.py index 90af340d3..ebb19fad8 100644 --- a/tools/test_fluid_occupancy_parity.py +++ b/tools/test_fluid_occupancy_parity.py @@ -57,7 +57,7 @@ def main(): with (build/'inputs.txt').open('w') as output: for f in corpus(info):output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 fixture_paths=[build/n for n in ['inputs.txt','info.json','block-registry.nbt']];fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'fluid_occupancy_fixture',build],'rust');references=[] + run(['cargo','build','--locked','--release','-p','horizon-world','--example','world_probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe');run([binary,'fluid_occupancy_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side);matched=base.compare(build/(side+'.txt'),build/'rust.txt');references.append(dict(side=side,jar_sha256=lab.digest(jar,'sha256'),output_sha256=lab.digest(build/(side+'.txt'),'sha256'),matched_output_lines=matched));print(f'{side}: {matched:,} fluid-occupancy output lines match Rust',flush=True) base.ensure_sources_unchanged(sources,tested);base.ensure_sources_unchanged(fixture_paths,fixtures) diff --git a/tools/test_fluid_parity.py b/tools/test_fluid_parity.py index 3acfc3702..b113f2294 100644 --- a/tools/test_fluid_parity.py +++ b/tools/test_fluid_parity.py @@ -62,9 +62,9 @@ def main(): fixtures=list(corpus(facts));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') codec_inputs=build/'codec-inputs.txt';codec_fixtures=list(codec_corpus());codec_inputs.write_text(''.join(json.dumps(v,separators=(',',':'))+'\n' for v in codec_fixtures),encoding='utf-8') fixture_paths=[inputs,codec_inputs,build/'facts-client.json',build/'facts-server.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'fluid_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_fluid_shape_parity.py b/tools/test_fluid_shape_parity.py index 1378d33a5..ee4793709 100644 --- a/tools/test_fluid_shape_parity.py +++ b/tools/test_fluid_shape_parity.py @@ -48,9 +48,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFluidShapeOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'fluid-states.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'fluid-states.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'fluid_shape_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_food_parity.py b/tools/test_food_parity.py index c2e451fd0..6428815af 100644 --- a/tools/test_food_parity.py +++ b/tools/test_food_parity.py @@ -68,9 +68,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFoodOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'food_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_food_properties_parity.py b/tools/test_food_properties_parity.py index 950c19ee3..62f62508a 100644 --- a/tools/test_food_properties_parity.py +++ b/tools/test_food_properties_parity.py @@ -57,9 +57,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFoodPropertiesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'food_properties_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_food_storage_parity.py b/tools/test_food_storage_parity.py index aeedde587..605b40d2f 100644 --- a/tools/test_food_storage_parity.py +++ b/tools/test_food_storage_parity.py @@ -52,9 +52,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFoodStorageOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'food_storage_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_free_space_parity.py b/tools/test_free_space_parity.py index a81fb0fe7..2c8379bac 100644 --- a/tools/test_free_space_parity.py +++ b/tools/test_free_space_parity.py @@ -94,9 +94,9 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'facts.json', 'definitions.json', 'block-registry.nbt', 'cached-collision.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'world_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary = Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary, 'registry_collision_scan_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) diff --git a/tools/test_ground_support_parity.py b/tools/test_ground_support_parity.py index 4393daf21..88bbf00a8 100644 --- a/tools/test_ground_support_parity.py +++ b/tools/test_ground_support_parity.py @@ -78,10 +78,10 @@ def main(): for f in corpus():output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 counts[name]=count;fixture_paths.append(path) fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--locked','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT)) for group,name in zip(['selection','state'],names): - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,name,build/group],'rust-'+group) + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe');run([binary,name,build/group],'rust-'+group) references=[] for side,jar in jars.items(): results=[] diff --git a/tools/test_height_provider_parity.py b/tools/test_height_provider_parity.py index 4f63c80cd..fad696b0a 100644 --- a/tools/test_height_provider_parity.py +++ b/tools/test_height_provider_parity.py @@ -73,9 +73,9 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,helper],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"height_provider_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_heightmap_parity.py b/tools/test_heightmap_parity.py index 502f165ab..e565fc04d 100644 --- a/tools/test_heightmap_parity.py +++ b/tools/test_heightmap_parity.py @@ -100,9 +100,9 @@ def main(): (build/"tags.json").write_text(json.dumps(tags,separators=(",",":")),encoding="utf-8") fixture_paths=[inputs,build/"tags.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"heightmap_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_held_drop_parity.py b/tools/test_held_drop_parity.py index d2f215050..a5cfe9009 100644 --- a/tools/test_held_drop_parity.py +++ b/tools/test_held_drop_parity.py @@ -35,7 +35,7 @@ def main(): 'dev.horizonlab.parity.VanillaHeldDropOracle', str(build / 'vanilla.txt')], check=True) with (build / 'rust.txt').open('w') as out: subprocess.run(['cargo', 'run', '--quiet', '-p', 'horizon-client', '--example', - 'probe', '--', 'held_drop_fixture'], cwd=lab.ROOT, stdout=out, check=True) + 'client_probe', '--', 'held_drop_fixture'], cwd=lab.ROOT, stdout=out, check=True) matched = base.compare(build / 'vanilla.txt', build / 'rust.txt') print(f'Held drop parity passed: {matched} inventory/drop/swing/packet snapshots match vanilla') diff --git a/tools/test_hud_parity.py b/tools/test_hud_parity.py index 4dcd19a7b..2b306f563 100644 --- a/tools/test_hud_parity.py +++ b/tools/test_hud_parity.py @@ -114,7 +114,7 @@ def main(): *(PARITY / f'{n}.java' for n in ('ParityData', 'ParityFont', 'VanillaHudOracle'))], 'compile-java') run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaHudOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe', '--', 'hud_fixture', resources, inputs, build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] diff --git a/tools/test_interaction_shape_parity.py b/tools/test_interaction_shape_parity.py index d40ca2c0b..ab21840c0 100644 --- a/tools/test_interaction_shape_parity.py +++ b/tools/test_interaction_shape_parity.py @@ -47,9 +47,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaInteractionShapeOracle',mode,path],side+'-'+mode) java('server','export',build);info=json.loads((build/'info.json').read_text());fixtures=list(corpus(info));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'info.json',build/'block-registry.nbt',build/'interaction-shapes.nbt'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'interaction_shape_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_inventory_pickup_parity.py b/tools/test_inventory_pickup_parity.py index a3172f472..9c413dcc8 100644 --- a/tools/test_inventory_pickup_parity.py +++ b/tools/test_inventory_pickup_parity.py @@ -72,9 +72,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaInventoryPickupOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'inventory_pickup_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_inventory_tick_parity.py b/tools/test_inventory_tick_parity.py index 2dd34b76f..6a23d3be4 100644 --- a/tools/test_inventory_tick_parity.py +++ b/tools/test_inventory_tick_parity.py @@ -60,9 +60,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaInventoryTickOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'inventory_tick_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_inventory_use_parity.py b/tools/test_inventory_use_parity.py index 925567c3f..4bb1d658b 100644 --- a/tools/test_inventory_use_parity.py +++ b/tools/test_inventory_use_parity.py @@ -55,9 +55,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaInventoryUseOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'inventory_use_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_inventory_use_start_parity.py b/tools/test_inventory_use_start_parity.py index 67e282c06..c57bd88da 100644 --- a/tools/test_inventory_use_start_parity.py +++ b/tools/test_inventory_use_start_parity.py @@ -55,9 +55,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaInventoryUseStartOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'inventory_use_start_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_item_after_use_parity.py b/tools/test_item_after_use_parity.py index 4aa5258f9..860d633d0 100644 --- a/tools/test_item_after_use_parity.py +++ b/tools/test_item_after_use_parity.py @@ -54,9 +54,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemAfterUseOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'item_after_use_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_item_blocking_parity.py b/tools/test_item_blocking_parity.py index 08d8dce24..8c149eabc 100644 --- a/tools/test_item_blocking_parity.py +++ b/tools/test_item_blocking_parity.py @@ -58,9 +58,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemBlockingOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'item_blocking_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_item_cooldowns_parity.py b/tools/test_item_cooldowns_parity.py index 807c576dc..3b368b657 100644 --- a/tools/test_item_cooldowns_parity.py +++ b/tools/test_item_cooldowns_parity.py @@ -64,9 +64,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemCooldownsOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'item_cooldowns_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_item_durability_parity.py b/tools/test_item_durability_parity.py index e3cdebb07..ec76cd60a 100644 --- a/tools/test_item_durability_parity.py +++ b/tools/test_item_durability_parity.py @@ -61,9 +61,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemDurabilityOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'item_durability_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_item_particles_parity.py b/tools/test_item_particles_parity.py index 0e030a3b3..5b2f5b5f9 100644 --- a/tools/test_item_particles_parity.py +++ b/tools/test_item_particles_parity.py @@ -53,9 +53,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemParticlesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'item_particles_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_item_stack_storage_parity.py b/tools/test_item_stack_storage_parity.py index 953dc8300..e3071207d 100644 --- a/tools/test_item_stack_storage_parity.py +++ b/tools/test_item_stack_storage_parity.py @@ -59,9 +59,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemStackStorageOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'item_stack_storage_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_item_template_parity.py b/tools/test_item_template_parity.py index 837465bb3..efc4dd094 100644 --- a/tools/test_item_template_parity.py +++ b/tools/test_item_template_parity.py @@ -58,9 +58,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemTemplateOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'item_template_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_item_use_catalog_parity.py b/tools/test_item_use_catalog_parity.py index 38664bd03..afffa5f6d 100644 --- a/tools/test_item_use_catalog_parity.py +++ b/tools/test_item_use_catalog_parity.py @@ -63,9 +63,9 @@ def main(): if exports[0]!=exports[1]:raise RuntimeError('native item catalogs differ') catalog_path=build/'catalog.json';lab.write_json(catalog_path,exports[0]);fixtures=list(corpus(exports[0]));inputs=build/'inputs.txt' ;inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,catalog_path];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'item_use_catalog_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_item_use_lifecycle_parity.py b/tools/test_item_use_lifecycle_parity.py index 0c3c4ee6e..da98d029f 100644 --- a/tools/test_item_use_lifecycle_parity.py +++ b/tools/test_item_use_lifecycle_parity.py @@ -57,9 +57,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemUseLifecycleOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'item_use_lifecycle_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_item_use_parity.py b/tools/test_item_use_parity.py index f69d49e35..b05a2056e 100644 --- a/tools/test_item_use_parity.py +++ b/tools/test_item_use_parity.py @@ -66,9 +66,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemUseOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'item_use_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_item_use_start_parity.py b/tools/test_item_use_start_parity.py index e59945e82..f65589b2b 100644 --- a/tools/test_item_use_start_parity.py +++ b/tools/test_item_use_start_parity.py @@ -57,9 +57,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemUseStartOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'item_use_start_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_java_hash_map_parity.py b/tools/test_java_hash_map_parity.py index 5ae1cce41..3147a5ed3 100644 --- a/tools/test_java_hash_map_parity.py +++ b/tools/test_java_hash_map_parity.py @@ -73,9 +73,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaJavaHashMapOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'java_hash_map_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_java_identity_map_parity.py b/tools/test_java_identity_map_parity.py index 9e9f04c1d..97300b98d 100644 --- a/tools/test_java_identity_map_parity.py +++ b/tools/test_java_identity_map_parity.py @@ -67,9 +67,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaJavaIdentityMapOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_level_place_parity.py b/tools/test_level_place_parity.py index 18e90e348..0089c0ef5 100644 --- a/tools/test_level_place_parity.py +++ b/tools/test_level_place_parity.py @@ -105,7 +105,7 @@ def main(): subprocess.run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaBlockPlacementOracle', str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')], check=True) - subprocess.run(['cargo', 'run', '-q', '-j2', '--release', '-p', 'horizon-world', '--example', 'probe', '--', + subprocess.run(['cargo', 'run', '-q', '-j2', '--release', '-p', 'horizon-world', '--example', 'world_probe', '--', 'level_place_fixture', str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], check=True, cwd=lab.ROOT) native = (work / 'native.txt').read_text().splitlines() rust = (work / 'rust.txt').read_text().splitlines() diff --git a/tools/test_level_shape_parity.py b/tools/test_level_shape_parity.py index c86f51fe6..8a5d7de48 100644 --- a/tools/test_level_shape_parity.py +++ b/tools/test_level_shape_parity.py @@ -80,7 +80,7 @@ def main(): subprocess.run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaLevelShapeOracle', str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')], check=True) - subprocess.run(['cargo', 'run', '-q', '-j2', '--release', '-p', 'horizon-world', '--example', 'probe', '--', + subprocess.run(['cargo', 'run', '-q', '-j2', '--release', '-p', 'horizon-world', '--example', 'world_probe', '--', 'level_shape_fixture', str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], check=True, cwd=lab.ROOT) native = (work / 'native.txt').read_text().splitlines() rust = (work / 'rust.txt').read_text().splitlines() diff --git a/tools/test_light_parity.py b/tools/test_light_parity.py index 3ed2351fa..bcac482da 100755 --- a/tools/test_light_parity.py +++ b/tools/test_light_parity.py @@ -92,7 +92,7 @@ def main(): dimension = run / 'world' for extra in (['--chunks', '0', '0', '2', '3'], ['--incremental', '100']): status = subprocess.run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', - '--example', 'probe', '--', 'light_parity', str(RESOURCES), str(dimension), *extra], + '--example', 'client_probe', '--', 'light_parity', str(RESOURCES), str(dimension), *extra], cwd=ROOT).returncode if status: sys.exit('light mismatch against vanilla') diff --git a/tools/test_liquid_collision_parity.py b/tools/test_liquid_collision_parity.py index 6a4ca638b..ab926d329 100644 --- a/tools/test_liquid_collision_parity.py +++ b/tools/test_liquid_collision_parity.py @@ -70,9 +70,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaCollisionContextOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'collision_context_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_live_attribute_updates_parity.py b/tools/test_live_attribute_updates_parity.py index 1e05f4bae..d1af16569 100644 --- a/tools/test_live_attribute_updates_parity.py +++ b/tools/test_live_attribute_updates_parity.py @@ -160,9 +160,9 @@ def main(): inputs.write_text(''.join(json.dumps(row, separators=(',', ':')) + '\n' for row in fixtures), encoding='utf-8') fixture_paths = [inputs, build / 'catalog.json', build / 'catalog-client.json', build / 'catalog-server.json'] tested_fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'world_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') + binary = Path(metadata['target_directory']) / 'release/examples' / ('world_probe.exe' if os.name=='nt' else 'world_probe') references = [] for side, jar in jars.items(): java(side, side) diff --git a/tools/test_live_attributes_parity.py b/tools/test_live_attributes_parity.py index f221fa27e..ead22f825 100644 --- a/tools/test_live_attributes_parity.py +++ b/tools/test_live_attributes_parity.py @@ -132,9 +132,9 @@ def main(): inputs.write_text(''.join(json.dumps(row, separators=(',', ':')) + '\n' for row in fixtures), encoding='utf-8') fixture_paths = [inputs, build / 'catalog.json', build / 'catalog-client.json', build / 'catalog-server.json'] tested_fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'world_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') + binary = Path(metadata['target_directory']) / 'release/examples' / ('world_probe.exe' if os.name=='nt' else 'world_probe') references = [] for side, jar in jars.items(): java(side, side) diff --git a/tools/test_living_air_parity.py b/tools/test_living_air_parity.py index 4d837f02a..3a2b61b00 100644 --- a/tools/test_living_air_parity.py +++ b/tools/test_living_air_parity.py @@ -81,9 +81,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingAirOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'living_air_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_living_damage_parity.py b/tools/test_living_damage_parity.py index ae97c4686..a98fde028 100644 --- a/tools/test_living_damage_parity.py +++ b/tools/test_living_damage_parity.py @@ -57,9 +57,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingDamageOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'living_damage_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_living_fall_parity.py b/tools/test_living_fall_parity.py index db55b5728..0f0638a17 100644 --- a/tools/test_living_fall_parity.py +++ b/tools/test_living_fall_parity.py @@ -59,9 +59,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingFallOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'living_fall_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_living_fluid_parity.py b/tools/test_living_fluid_parity.py index 19748fef2..fdda42e8c 100644 --- a/tools/test_living_fluid_parity.py +++ b/tools/test_living_fluid_parity.py @@ -77,9 +77,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingFluidOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'living_fluid_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_living_health_parity.py b/tools/test_living_health_parity.py index ab97d0061..c083e2ae5 100644 --- a/tools/test_living_health_parity.py +++ b/tools/test_living_health_parity.py @@ -59,9 +59,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingHealthOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'living_health_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_living_hurt_parity.py b/tools/test_living_hurt_parity.py index 38ade5720..6d6bb2a2d 100644 --- a/tools/test_living_hurt_parity.py +++ b/tools/test_living_hurt_parity.py @@ -61,9 +61,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingHurtOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'living_hurt_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_living_landing_parity.py b/tools/test_living_landing_parity.py index eb65800da..c6fcae689 100644 --- a/tools/test_living_landing_parity.py +++ b/tools/test_living_landing_parity.py @@ -66,9 +66,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingLandingOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'living_landing_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_living_motion_parity.py b/tools/test_living_motion_parity.py index 39935303c..fb054b65f 100644 --- a/tools/test_living_motion_parity.py +++ b/tools/test_living_motion_parity.py @@ -80,9 +80,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingMotionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'living_motion_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_local_input_parity.py b/tools/test_local_input_parity.py index adfea1a4b..c50087138 100644 --- a/tools/test_local_input_parity.py +++ b/tools/test_local_input_parity.py @@ -44,9 +44,9 @@ def main(): classes=build/'classes';classes.mkdir(exist_ok=True) dependencies=os.pathsep.join(map(str,[jars['client'],*libraries])) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',dependencies,'-d',classes,oracle],'compile-java') - run(['cargo','build','--locked','-p','horizon-client','--example','probe'],'compile-rust') + run(['cargo','build','--locked','-p','horizon-client','--example','client_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT)) - binary=Path(metadata['target_directory'])/'debug/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'debug/examples'/('client_probe.exe' if os.name=='nt' else 'client_probe') run([binary,'input_probe',inputs,build/'rust.txt'],'rust') run(['java','-Xmx768M','-cp',str(classes)+os.pathsep+dependencies,'dev.horizonlab.parity.VanillaLocalInputOracle',inputs,build/'client.txt'],'client') matched=base.compare(build/'client.txt',build/'rust.txt') diff --git a/tools/test_material_condition_parity.py b/tools/test_material_condition_parity.py index adddd336b..414ce3b97 100644 --- a/tools/test_material_condition_parity.py +++ b/tools/test_material_condition_parity.py @@ -293,9 +293,9 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,anchor_oracle,biome_oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"material_condition_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_material_extension_parity.py b/tools/test_material_extension_parity.py index 4036ecc37..66debf973 100644 --- a/tools/test_material_extension_parity.py +++ b/tools/test_material_extension_parity.py @@ -67,8 +67,8 @@ def main(): with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependencies=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependencies,'-d',classes,*oracles],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') - metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'material_extension_fixture',build],'rust');references=[] + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe');run([binary,'material_extension_fixture',build],'rust');references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependencies]),'dev.horizonlab.parity.VanillaMaterialExtensionOracle',side,build],side) reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt');references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched});print(f'{side}: {matched:,} material-extension output lines match Rust',flush=True) diff --git a/tools/test_material_rule_library_parity.py b/tools/test_material_rule_library_parity.py index 1e9b82357..6b4b26c63 100644 --- a/tools/test_material_rule_library_parity.py +++ b/tools/test_material_rule_library_parity.py @@ -79,8 +79,8 @@ def main(): if facts!=json.loads((build/'facts-client.json').read_text()):raise ValueError('reference block metadata differs') fixtures=list(corpus(bundle['rules'],bundle['biomes']));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'facts-client.json',build/'facts-server.json',*[build/(field+'.json') for field in bundle]];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') - metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'material_condition_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,'VanillaMaterialConditionOracle',side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_material_stage_parity.py b/tools/test_material_stage_parity.py index 46bb4649b..a22f68697 100644 --- a/tools/test_material_stage_parity.py +++ b/tools/test_material_stage_parity.py @@ -132,7 +132,7 @@ def main(): f['top_queries']=top_queries(f);f['carving']=carving_fixture(f,facts) inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') fixture_paths=[inputs,*preset_exports,build/'facts-client.json',build/'facts-server.json',*[build/(name+'.json') for name in bundle]];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'material_stage_fixture',build],'rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe');run([binary,'material_stage_fixture',build],'rust') with (build/'rust.txt').open() as stream: if any((line.startswith('surface ') or line.startswith('top ') or line.startswith('carving ') or line.startswith('generatedcarving ')) and line.endswith(' error\n') for line in stream):raise AssertionError('valid surface fixture failed; inspect private Rust log') references=[] diff --git a/tools/test_material_surface_parity.py b/tools/test_material_surface_parity.py index 120decbe7..b4fa34f6d 100644 --- a/tools/test_material_surface_parity.py +++ b/tools/test_material_surface_parity.py @@ -52,9 +52,9 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"material_surface_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index ccc50b302..bd8802143 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -477,7 +477,7 @@ def main(): 'dev.horizonlab.parity.VanillaMobAiOracle', inputs, build / 'vanilla.txt', world], build, 'vanilla', timeout=3600) if not args.java_only: - command = ['cargo', 'build', '--locked', '--release', '-p', 'horizon-client', '--example', 'probe'] + command = ['cargo', 'build', '--locked', '--release', '-p', 'horizon-client', '--example', 'client_probe'] target, env = lab.cargo_target(), None if args.trace: target = lab.LOCAL / 'mob-ai-trace-target' @@ -485,7 +485,7 @@ def main(): env = dict(os.environ, CARGO_TARGET_DIR=str(target), CARGO_PROFILE_RELEASE_DEBUG='line-tables-only', CARGO_PROFILE_RELEASE_LTO='false', CARGO_PROFILE_RELEASE_CODEGEN_UNITS='16') oracle_harness.run_logged(command, build, 'compile-rust', env=env) - binary = target / 'release/examples/probe' + binary = target / 'release/examples/client_probe' oracle_harness.run_logged([binary, 'mob_ai_probe', lab.RESOURCES, inputs, build / 'horizon.txt'], build, 'horizon') if args.java_only: return diff --git a/tools/test_mob_attributes_parity.py b/tools/test_mob_attributes_parity.py index 6cefdc4b8..7fa1df5e6 100755 --- a/tools/test_mob_attributes_parity.py +++ b/tools/test_mob_attributes_parity.py @@ -62,8 +62,8 @@ def main(): subprocess.run(list(map(str, cmd)), cwd=lab.ROOT, check=True, timeout=3600, stdout=log, stderr=subprocess.STDOUT) run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx1G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaMobAttributesOracle', build / 'vanilla.txt'], 'java') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') - binary = lab.cargo_target() / 'release/examples/probe' + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') + binary = lab.cargo_target() / 'release/examples/client_probe' resources = lab.RESOURCES run([binary, 'mob_attributes_fixture', resources, build / 'rust.txt'], 'rust') vanilla, rust = parse(build / 'vanilla.txt'), parse(build / 'rust.txt') diff --git a/tools/test_movement_emission_parity.py b/tools/test_movement_emission_parity.py index 7db2c16d0..5307cd600 100644 --- a/tools/test_movement_emission_parity.py +++ b/tools/test_movement_emission_parity.py @@ -57,9 +57,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaMovementEmissionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'movement_emission_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_movement_registry_parity.py b/tools/test_movement_registry_parity.py index 190c34d37..732664f3a 100644 --- a/tools/test_movement_registry_parity.py +++ b/tools/test_movement_registry_parity.py @@ -69,9 +69,9 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'registry-info.json', 'movement-properties.nbt', 'block-registry.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'world_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary = Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary, 'movement_registry_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) diff --git a/tools/test_movement_support_parity.py b/tools/test_movement_support_parity.py index 793804a9e..1d6a53c1f 100644 --- a/tools/test_movement_support_parity.py +++ b/tools/test_movement_support_parity.py @@ -59,9 +59,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaMovementSupportOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'movement_support_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_native_scene_collision.py b/tools/test_native_scene_collision.py index 8efc6946b..2c292b28d 100644 --- a/tools/test_native_scene_collision.py +++ b/tools/test_native_scene_collision.py @@ -82,9 +82,9 @@ def main(): dependencies = os.pathsep.join(map(str, libraries)) run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', str(jars['server'])+os.pathsep+dependencies, '-d', classes, oracle, *helpers], 'compile-java') - run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - executable = Path(metadata['target_directory'])/'debug/examples'/('probe.exe' if os.name=='nt' else 'probe') + executable = Path(metadata['target_directory'])/'debug/examples'/('client_probe.exe' if os.name=='nt' else 'client_probe') cases = [] for radius in [1, 2]: build = root/str(radius); build.mkdir(exist_ok=True) diff --git a/tools/test_native_scene_motion.py b/tools/test_native_scene_motion.py index a917d7337..08af5330c 100644 --- a/tools/test_native_scene_motion.py +++ b/tools/test_native_scene_motion.py @@ -807,9 +807,9 @@ def main(): damage_dir=build/'damage';damage_dir.mkdir(exist_ok=True) for target, source in [('types.json','damage-types.json'),('tags.json','damage-tags.json')]: (damage_dir/target).write_bytes((resources/source).read_bytes()) - run(['cargo','build','--locked','-p','horizon-client','--example','probe'],'compile-rust') + run(['cargo','build','--locked','-p','horizon-client','--example','client_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT)) - binary=Path(metadata['target_directory'])/'debug/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'debug/examples'/('client_probe.exe' if os.name=='nt' else 'client_probe') run([binary,'scene_motion_probe',resources,build,'--describe'],'describe') references=[] for side,jar in jars.items(): diff --git a/tools/test_natural_spawn_parity.py b/tools/test_natural_spawn_parity.py index 3c95e6ac2..50781eca7 100644 --- a/tools/test_natural_spawn_parity.py +++ b/tools/test_natural_spawn_parity.py @@ -568,9 +568,9 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/probe' + binary = Path(metadata['target_directory']) / 'release/examples/client_probe' run([binary, 'natural_spawn_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] diff --git a/tools/test_nether_portal_parity.py b/tools/test_nether_portal_parity.py index 71cbf7be8..0805c985c 100644 --- a/tools/test_nether_portal_parity.py +++ b/tools/test_nether_portal_parity.py @@ -145,7 +145,7 @@ def main(): '-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaPortalOracle.java')]) h.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaPortalOracle', str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')]) - h.run(['cargo', 'run', '-q', '--release', '-p', 'horizon-world', '--example', 'probe', '--', + h.run(['cargo', 'run', '-q', '--release', '-p', 'horizon-world', '--example', 'world_probe', '--', 'portal_travel_fixture', str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], cwd=lab.ROOT) native = h.split_cases((work / 'native.txt').read_text(), ()) rust = h.split_cases((work / 'rust.txt').read_text(), ()) diff --git a/tools/test_object_open_map_parity.py b/tools/test_object_open_map_parity.py index 72bafc1a4..1dc7d255f 100644 --- a/tools/test_object_open_map_parity.py +++ b/tools/test_object_open_map_parity.py @@ -128,9 +128,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaObjectOpenMapOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'object_open_map_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_object_open_set_parity.py b/tools/test_object_open_set_parity.py index 3801cdb60..3eda39fe8 100644 --- a/tools/test_object_open_set_parity.py +++ b/tools/test_object_open_set_parity.py @@ -77,9 +77,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaObjectOpenSetOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'object_open_set_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_pack_selection_parity.py b/tools/test_pack_selection_parity.py index 9af372d1e..0bca824fa 100644 --- a/tools/test_pack_selection_parity.py +++ b/tools/test_pack_selection_parity.py @@ -71,7 +71,7 @@ def main(): *(PARITY / f'{n}.java' for n in ('ParityData', 'VanillaPackSelectionOracle'))], 'compile-java') run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaPackSelectionOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe', '--', 'pack_selection_fixture', inputs, build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] diff --git a/tools/test_piston_movement_parity.py b/tools/test_piston_movement_parity.py index 82bcd09ca..cfed8950a 100644 --- a/tools/test_piston_movement_parity.py +++ b/tools/test_piston_movement_parity.py @@ -60,9 +60,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPistonMovementOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'piston_movement_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_piston_shape_parity.py b/tools/test_piston_shape_parity.py index 74ae48e39..85fdac770 100644 --- a/tools/test_piston_shape_parity.py +++ b/tools/test_piston_shape_parity.py @@ -63,9 +63,9 @@ def main(): if len(facts['states'])!=35723:raise ValueError('incomplete pinned registry') fixtures=list(corpus(facts));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'facts.json',build/'block-registry.nbt',build/'cached-collision.nbt'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'piston_shape_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_placement_parity.py b/tools/test_placement_parity.py index d4e84eaf8..f02daac8e 100644 --- a/tools/test_placement_parity.py +++ b/tools/test_placement_parity.py @@ -108,9 +108,9 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"placement_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_player_equipment_parity.py b/tools/test_player_equipment_parity.py index 5f2499eab..4b2408e5d 100644 --- a/tools/test_player_equipment_parity.py +++ b/tools/test_player_equipment_parity.py @@ -62,9 +62,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPlayerEquipmentOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'player_equipment_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_player_food_parity.py b/tools/test_player_food_parity.py index ff38abe39..e94de7644 100644 --- a/tools/test_player_food_parity.py +++ b/tools/test_player_food_parity.py @@ -59,9 +59,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPlayerFoodOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'player_food_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_player_health_parity.py b/tools/test_player_health_parity.py index 256ffdf46..ff5a795ef 100644 --- a/tools/test_player_health_parity.py +++ b/tools/test_player_health_parity.py @@ -58,9 +58,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPlayerHealthOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'catalog.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json',build/'ids.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'player_health_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_player_hurt_parity.py b/tools/test_player_hurt_parity.py index 34ce6a9dd..23100bcab 100644 --- a/tools/test_player_hurt_parity.py +++ b/tools/test_player_hurt_parity.py @@ -82,9 +82,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPlayerHurtOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'player_hurt_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_player_inventory_parity.py b/tools/test_player_inventory_parity.py index 10f6af812..3447eb7d0 100644 --- a/tools/test_player_inventory_parity.py +++ b/tools/test_player_inventory_parity.py @@ -68,9 +68,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPlayerInventoryOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'player_inventory_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_player_travel_parity.py b/tools/test_player_travel_parity.py index 9b96ba8e8..193c290e5 100644 --- a/tools/test_player_travel_parity.py +++ b/tools/test_player_travel_parity.py @@ -66,9 +66,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPlayerTravelOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'player_travel_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_powder_snow_collision_parity.py b/tools/test_powder_snow_collision_parity.py index 10c287cc5..edca02018 100644 --- a/tools/test_powder_snow_collision_parity.py +++ b/tools/test_powder_snow_collision_parity.py @@ -62,9 +62,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaCollisionContextOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'collision_context_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_raid_parity.py b/tools/test_raid_parity.py index be1ed7e25..4928c9715 100644 --- a/tools/test_raid_parity.py +++ b/tools/test_raid_parity.py @@ -335,9 +335,9 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaRaidOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/probe' + binary = Path(metadata['target_directory']) / 'release/examples/client_probe' run([binary, 'raid_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] diff --git a/tools/test_registered_entity_fluid_parity.py b/tools/test_registered_entity_fluid_parity.py index ff7a83eb6..47970f63e 100644 --- a/tools/test_registered_entity_fluid_parity.py +++ b/tools/test_registered_entity_fluid_parity.py @@ -67,7 +67,7 @@ def main(): with (build/'inputs.txt').open('w') as output: for f in corpus(info):output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 fixture_paths=[build/n for n in ['inputs.txt','facts.json','fluid-info.json','block-registry.nbt','cached-support.nbt','tags.json']];fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'entity_fluid_fixture',build],'rust');references=[] + run(['cargo','build','--locked','--release','-p','horizon-world','--example','world_probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe');run([binary,'entity_fluid_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side);matched=base.compare(build/(side+'.txt'),build/'rust.txt');references.append(dict(side=side,jar_sha256=lab.digest(jar,'sha256'),output_sha256=lab.digest(build/(side+'.txt'),'sha256'),matched_output_lines=matched));print(f'{side}: {matched:,} registered entity fluid output lines match Rust',flush=True) base.ensure_sources_unchanged(sources,tested);base.ensure_sources_unchanged(fixture_paths,fixtures) diff --git a/tools/test_registered_player_combat_parity.py b/tools/test_registered_player_combat_parity.py index eecb6e6cf..c1f0c502b 100644 --- a/tools/test_registered_player_combat_parity.py +++ b/tools/test_registered_player_combat_parity.py @@ -59,9 +59,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaRegisteredPlayerCombatOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'catalog.json').read_text());damage=json.loads((damage_dir/'catalog.json').read_text());fixtures=list(corpus(states,damage));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json',build/'ids.json',build/'slots.json',build/'head.json',damage_dir/'catalog.json',damage_dir/'types.json',damage_dir/'tags.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'registered_player_combat_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_registry_collision_scan_parity.py b/tools/test_registry_collision_scan_parity.py index 5b40d7285..bd6b4ce23 100644 --- a/tools/test_registry_collision_scan_parity.py +++ b/tools/test_registry_collision_scan_parity.py @@ -96,9 +96,9 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'facts.json', 'definitions.json', 'block-registry.nbt', 'cached-collision.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'world_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary = Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary, 'registry_collision_scan_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) diff --git a/tools/test_registry_fall_ray_parity.py b/tools/test_registry_fall_ray_parity.py index a7639c3ab..dbd560dc5 100644 --- a/tools/test_registry_fall_ray_parity.py +++ b/tools/test_registry_fall_ray_parity.py @@ -61,7 +61,7 @@ def main(): with (build/'inputs.txt').open('w') as output: for f in corpus(info):output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 fixture_paths=[build/n for n in ['inputs.txt','info.json','block-registry.nbt','interaction-shapes.nbt','tags.json','fluid-tags.json','bound-tags.json']];fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'registry_fall_ray_fixture',build],'rust');references=[] + run(['cargo','build','--locked','--release','-p','horizon-world','--example','world_probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe');run([binary,'registry_fall_ray_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side);matched=base.compare(build/(side+'.txt'),build/'rust.txt');references.append(dict(side=side,jar_sha256=lab.digest(jar,'sha256'),output_sha256=lab.digest(build/(side+'.txt'),'sha256'),matched_output_lines=matched));print(f'{side}: {matched:,} registered fall-ray output lines match Rust',flush=True) base.ensure_sources_unchanged(sources,tested);base.ensure_sources_unchanged(fixture_paths,fixtures) diff --git a/tools/test_registry_fluid_parity.py b/tools/test_registry_fluid_parity.py index fd0fb106b..f767850cb 100644 --- a/tools/test_registry_fluid_parity.py +++ b/tools/test_registry_fluid_parity.py @@ -62,7 +62,7 @@ def main(): with (build/'inputs.txt').open('w') as output: for f in corpus(info):output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 fixture_paths=[build/n for n in ['inputs.txt','facts.json','fluid-info.json','block-registry.nbt','cached-support.nbt','tags.json']];fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'registry_fluid_fixture',build],'rust');references=[] + run(['cargo','build','--locked','--release','-p','horizon-world','--example','world_probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe');run([binary,'registry_fluid_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side);matched=base.compare(build/(side+'.txt'),build/'rust.txt');references.append(dict(side=side,jar_sha256=lab.digest(jar,'sha256'),output_sha256=lab.digest(build/(side+'.txt'),'sha256'),matched_output_lines=matched));print(f'{side}: {matched:,} registry_fluid output lines match Rust',flush=True) base.ensure_sources_unchanged(sources,tested);base.ensure_sources_unchanged(fixture_paths,fixtures) diff --git a/tools/test_replace_block_parity.py b/tools/test_replace_block_parity.py index e96bf4c72..84ab56999 100644 --- a/tools/test_replace_block_parity.py +++ b/tools/test_replace_block_parity.py @@ -68,9 +68,9 @@ def main(): fixtures=list(corpus(facts));inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths.append(inputs) tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"replace_block_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_restitution_parity.py b/tools/test_restitution_parity.py index ada050a13..d5497e2d0 100644 --- a/tools/test_restitution_parity.py +++ b/tools/test_restitution_parity.py @@ -62,9 +62,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaRestitutionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'restitution_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_retrogen_chunk_parity.py b/tools/test_retrogen_chunk_parity.py index 9a13e1303..452d42d5b 100644 --- a/tools/test_retrogen_chunk_parity.py +++ b/tools/test_retrogen_chunk_parity.py @@ -74,9 +74,9 @@ def main(): (build/"tags.json").write_text(json.dumps(tags,separators=(",",":")),encoding="utf-8") fixture_paths=[inputs,build/"tags.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"chunk_stage_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_retrogen_data_parity.py b/tools/test_retrogen_data_parity.py index 242f3b5d3..6d03ab9a3 100644 --- a/tools/test_retrogen_data_parity.py +++ b/tools/test_retrogen_data_parity.py @@ -46,9 +46,9 @@ def main(): with (build/(name+'.log')).open('w') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=3600,stdout=log,stderr=subprocess.STDOUT) dependencies=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependencies,'-d',classes,oracle],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'retrogen_data_fixture',inputs,build/'rust.txt'],'rust') references=[] for side,jar in jars.items(): diff --git a/tools/test_rule_test_parity.py b/tools/test_rule_test_parity.py index 8fef86b95..bb03397c1 100644 --- a/tools/test_rule_test_parity.py +++ b/tools/test_rule_test_parity.py @@ -73,9 +73,9 @@ def main(): if len(facts['states'])!=35723:raise ValueError('incomplete pinned state registry') fixtures=list(corpus(facts,tags));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'tags.json',build/'facts-client.json',build/'facts-server.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'rule_test_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_scaffolding_collision_parity.py b/tools/test_scaffolding_collision_parity.py index bebd63087..c71ffe7a3 100644 --- a/tools/test_scaffolding_collision_parity.py +++ b/tools/test_scaffolding_collision_parity.py @@ -55,9 +55,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaCollisionContextOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'collision_context_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_scattered_ore_parity.py b/tools/test_scattered_ore_parity.py index 0cbb6fcac..eba6723d2 100644 --- a/tools/test_scattered_ore_parity.py +++ b/tools/test_scattered_ore_parity.py @@ -69,9 +69,9 @@ def main(): fixtures=list(corpus(facts));inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths.append(inputs) tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"scattered_ore_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_scoreboard_parity.py b/tools/test_scoreboard_parity.py index db308d861..b38dfb301 100644 --- a/tools/test_scoreboard_parity.py +++ b/tools/test_scoreboard_parity.py @@ -250,9 +250,9 @@ def main(): inputs = build / 'inputs.jsonl' inputs.write_text(''.join(json.dumps(c, ensure_ascii=False) + '\n' for c in chosen), encoding='utf-8') run([*oracle, 'run', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') + binary = Path(metadata['target_directory']) / 'release/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe') run([binary, 'scoreboard_fixture',build / 'registries.json', inputs, build / 'rust.jsonl', build / 'vanilla.jsonl'], 'rust') read = lambda p: [json.loads(l) for l in p.read_text(encoding='utf-8').splitlines()] vanilla, rust = read(build / 'vanilla.jsonl'), read(build / 'rust.jsonl') diff --git a/tools/test_section_mesh_parity.py b/tools/test_section_mesh_parity.py index 65878bc97..a5471618f 100644 --- a/tools/test_section_mesh_parity.py +++ b/tools/test_section_mesh_parity.py @@ -502,9 +502,9 @@ def main(): dependencies = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()])) run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'), '-cp', dependencies, '-d', classes, oracle, *helpers], 'compile-java') env_jobs = os.environ.get('CARGO_BUILD_JOBS', '3') - run(['cargo', 'build', '--locked', '--profile', 'fast', '-j', env_jobs, '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--locked', '--profile', 'fast', '-j', env_jobs, '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory']) / 'fast/examples' / ('probe.exe' if os.name=='nt' else 'probe') + binary = Path(metadata['target_directory']) / 'fast/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe') java = ['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaSectionMeshOracle'] run([binary, 'section_mesh_fixture',resources, inputs, BUILD / 'rust.jsonl'], 'rust') run([*java, inputs, BUILD / 'client.jsonl', resources], 'client') diff --git a/tools/test_server_player_combat_parity.py b/tools/test_server_player_combat_parity.py index 161c4cbcf..a18dd61c6 100644 --- a/tools/test_server_player_combat_parity.py +++ b/tools/test_server_player_combat_parity.py @@ -77,9 +77,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaServerPlayerCombatOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'catalog.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json',build/'ids.json',build/'slots.json',build/'head.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'server_player_combat_fixture',build],'rust') run([binary,'server_player_combat_fixture',build,'--live'],'rust-live') base.compare(build/'rust.txt',build/'rust-live.txt');references=[] diff --git a/tools/test_server_player_damage_parity.py b/tools/test_server_player_damage_parity.py index 8e1418f4e..61a9271da 100644 --- a/tools/test_server_player_damage_parity.py +++ b/tools/test_server_player_damage_parity.py @@ -62,9 +62,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaServerPlayerDamageOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'catalog.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json',build/'ids.json',build/'slots.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'server_player_damage_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_simple_block_parity.py b/tools/test_simple_block_parity.py index 3af85a241..697a94673 100644 --- a/tools/test_simple_block_parity.py +++ b/tools/test_simple_block_parity.py @@ -116,8 +116,8 @@ def run(corpus, build_name, source_file, scope): with inputs.open('w',encoding='utf-8') as output: for fixture in corpus(facts,placement):output.write(json.dumps(fixture,separators=(',',':'))+'\n');fixture_count+=1 fixtures=[inputs,*sorted(build.glob('*.nbt')),*[p for p in sorted(build.glob('*.json')) if p.name!='report.json']];tested_fixtures=base.source_hashes(fixtures);print(f'Prepared {fixture_count:,} placement fixtures',flush=True) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') - metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'simple_block_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);matched=base.compare(build/(side+'.txt'),build/'rust.txt');print(f'{side}: {matched:,} {label} output lines match Rust',flush=True) diff --git a/tools/test_simple_container_parity.py b/tools/test_simple_container_parity.py index 0af91292a..6319db7e3 100644 --- a/tools/test_simple_container_parity.py +++ b/tools/test_simple_container_parity.py @@ -70,9 +70,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaSimpleContainerOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'simple_container_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_spawn_rules_parity.py b/tools/test_spawn_rules_parity.py index 19bd8db46..7f9ac07ce 100644 --- a/tools/test_spawn_rules_parity.py +++ b/tools/test_spawn_rules_parity.py @@ -155,9 +155,9 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx2G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaSpawnRulesOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/probe' + binary = Path(metadata['target_directory']) / 'release/examples/client_probe' run([binary, 'spawn_rules_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] diff --git a/tools/test_spawner_parity.py b/tools/test_spawner_parity.py index 5aa9029e3..187e211b7 100644 --- a/tools/test_spawner_parity.py +++ b/tools/test_spawner_parity.py @@ -249,9 +249,9 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/probe' + binary = Path(metadata['target_directory']) / 'release/examples/client_probe' run([binary, 'natural_spawn_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] diff --git a/tools/test_sprint_input_parity.py b/tools/test_sprint_input_parity.py index 0ac515e44..b2b86b7c2 100644 --- a/tools/test_sprint_input_parity.py +++ b/tools/test_sprint_input_parity.py @@ -49,9 +49,9 @@ def main(): classes=build/'classes';classes.mkdir(exist_ok=True) dependencies=os.pathsep.join(map(str,[jars['client'],*libraries])) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',dependencies,'-d',classes,oracle],'compile-java') - run(['cargo','build','--locked','-p','horizon-client','--example','probe'],'compile-rust') + run(['cargo','build','--locked','-p','horizon-client','--example','client_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT)) - binary=Path(metadata['target_directory'])/'debug/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'debug/examples'/('client_probe.exe' if os.name=='nt' else 'client_probe') run([binary,'sprint_probe',inputs,build/'rust.txt'],'rust') run(['java','-Xmx768M','-cp',str(classes)+os.pathsep+dependencies,'dev.horizonlab.parity.VanillaSprintInputOracle',inputs,build/'client.txt'],'client') matched=base.compare(build/'client.txt',build/'rust.txt') diff --git a/tools/test_state_provider_parity.py b/tools/test_state_provider_parity.py index 9f7523273..42f2a4526 100644 --- a/tools/test_state_provider_parity.py +++ b/tools/test_state_provider_parity.py @@ -371,9 +371,9 @@ def main(): output.write(json.dumps(fixture,separators=(',',':'))+'\n') fixture_count+=1;requested_samples+=len(fixture['states'])*fixture['repeats']*2 fixture_paths=[inputs,build/'survival-extra-definitions.json',build/'survival-placement-classes.json',build/'survival-support-tags.json',build/'survival-classes.json',build/'survival-rules.json',build/'cached-support.nbt',build/'support-cached-states.json',build/'block-properties.nbt',build/'cached-collision.nbt',build/'biomes.json',build/'biome_tags.json',build/'fluid-tags.json',build/'catalog.json',build/'providers.json',build/'tags.json',build/'facts-client.json',build/'facts-server.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') counts={'block_states':len(facts['states']),'blocks':len(facts['defaults']),'integer_properties':len(facts['integers']),'codec_inputs':fixture_count,'provider_types':10,'named_providers':len(catalog_resources),'rule_predicate_types':16,'survival_supported_blocks':len(survival_rules),'survival_supported_states':sum(s['id'] in survival_rules for s in facts['states']),'support_cached_states':len(support_states),'support_dynamic_states':len(facts['states'])-len(support_states),'biomes':len(biomes),'biome_tag_files':len(biome_tags),'fluid_tag_files':len(fluid_tags),'bundled_provider_definitions':len(provider_resources),'block_tag_files':len(tags),'requested_samples':requested_samples} base.ensure_sources_unchanged(sources,tested_sources) checkpoint={'schema':1,'environment':environment,'sources_sha256':tested_sources,'fixtures_sha256':{str(lab.ROOT/name):digest for name,digest in tested_fixtures.items()},'artifacts_sha256':{str(path):lab.digest(path,'sha256') for path in [binary,*sorted(classes.rglob('*.class'))]},'binary':str(binary),'counts':counts,'outputs':{}} diff --git a/tools/test_status_effect_parity.py b/tools/test_status_effect_parity.py index 6f369c683..899b63f66 100644 --- a/tools/test_status_effect_parity.py +++ b/tools/test_status_effect_parity.py @@ -57,9 +57,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaStatusEffectOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'status_effect_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_status_tick_parity.py b/tools/test_status_tick_parity.py index 40786fe3c..bc582ff4a 100644 --- a/tools/test_status_tick_parity.py +++ b/tools/test_status_tick_parity.py @@ -58,9 +58,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaStatusTickOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'status_tick_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_stepped_interpolation_parity.py b/tools/test_stepped_interpolation_parity.py index e5586c981..5029befd3 100644 --- a/tools/test_stepped_interpolation_parity.py +++ b/tools/test_stepped_interpolation_parity.py @@ -94,7 +94,7 @@ def main(): 'dev.horizonlab.parity.VanillaSteppedInterpolationOracle', str(events), str(build / 'vanilla.txt')], check=True) subprocess.run(['cargo', 'run', '--quiet', '--release', '-p', 'horizon-world', '--example', - 'probe', '--', 'stepped_interpolation_fixture', str(events), str(build / 'rust.txt')], cwd=lab.ROOT, check=True) + 'world_probe', '--', 'stepped_interpolation_fixture', str(events), str(build / 'rust.txt')], cwd=lab.ROOT, check=True) matched = base.compare(build / 'vanilla.txt', build / 'rust.txt') print(f'Stepped interpolation parity passed: {matched} entity positions and rotations match vanilla') diff --git a/tools/test_stored_consume_parity.py b/tools/test_stored_consume_parity.py index 3ddfed86a..8837e6f00 100644 --- a/tools/test_stored_consume_parity.py +++ b/tools/test_stored_consume_parity.py @@ -66,9 +66,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaStoredConsumeOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_stored_effect_attributes_parity.py b/tools/test_stored_effect_attributes_parity.py index 2a8fe799d..84c86b27a 100644 --- a/tools/test_stored_effect_attributes_parity.py +++ b/tools/test_stored_effect_attributes_parity.py @@ -94,9 +94,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaStoredEffectAttributesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_stored_effect_notifications_parity.py b/tools/test_stored_effect_notifications_parity.py index 6a0cee403..945d11247 100644 --- a/tools/test_stored_effect_notifications_parity.py +++ b/tools/test_stored_effect_notifications_parity.py @@ -73,9 +73,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaStoredEffectNotificationsOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_structure_density_parity.py b/tools/test_structure_density_parity.py index ad15790e0..b6cd9c8fe 100644 --- a/tools/test_structure_density_parity.py +++ b/tools/test_structure_density_parity.py @@ -68,9 +68,9 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"structure_density_fixture",inputs,build/"rust.txt"],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_subtitle_parity.py b/tools/test_subtitle_parity.py index 1444bb5bd..6baf25570 100644 --- a/tools/test_subtitle_parity.py +++ b/tools/test_subtitle_parity.py @@ -133,9 +133,9 @@ def main(): *(PARITY / f'{n}.java' for n in ('ParityFont', 'VanillaSubtitleOracle'))], 'compile-java') run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaSubtitleOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') + binary = Path(metadata['target_directory']) / 'release/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe') run([binary, 'subtitle_fixture',resources, inputs, build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text(encoding='utf-8').splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text(encoding='utf-8').splitlines()] diff --git a/tools/test_suffocation_parity.py b/tools/test_suffocation_parity.py index ffe80b31f..046a8ec82 100644 --- a/tools/test_suffocation_parity.py +++ b/tools/test_suffocation_parity.py @@ -72,9 +72,9 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'facts.json', 'definitions.json', 'block-registry.nbt', 'cached-collision.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'world_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary = Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary, 'suffocation_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) diff --git a/tools/test_swimming_parity.py b/tools/test_swimming_parity.py index 574b72e5b..87d2bb034 100644 --- a/tools/test_swimming_parity.py +++ b/tools/test_swimming_parity.py @@ -51,9 +51,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaSwimmingOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'swimming_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_synced_bytes_parity.py b/tools/test_synced_bytes_parity.py index a6659bf21..4d6389ffa 100644 --- a/tools/test_synced_bytes_parity.py +++ b/tools/test_synced_bytes_parity.py @@ -57,9 +57,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaSyncedBytesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'synced_bytes_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_synced_floats_parity.py b/tools/test_synced_floats_parity.py index fa7ca7132..78e8cec32 100644 --- a/tools/test_synced_floats_parity.py +++ b/tools/test_synced_floats_parity.py @@ -61,9 +61,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaSyncedFloatsOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'synced_floats_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_tab_list_parity.py b/tools/test_tab_list_parity.py index 9b3c65605..4075859e7 100644 --- a/tools/test_tab_list_parity.py +++ b/tools/test_tab_list_parity.py @@ -241,12 +241,12 @@ def main(): *(PARITY / f'{n}.java' for n in ('ParityData', 'ParityFont', 'VanillaTabListOracle', 'VanillaSkinImageOracle'))], 'compile-java') run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaTabListOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe', '--', 'tab_list_fixture', resources, inputs, build / 'rust.jsonl'], 'rust') images = build / 'skins.txt'; images.write_text(''.join(i + '\n' for i in skin_images(args.images))) run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaSkinImageOracle', images, build / 'vanilla-skins.txt'], 'vanilla-skins') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe', '--', 'skin_image_fixture', images, build / 'rust-skins.txt'], 'rust-skins') vanilla_skins = (build / 'vanilla-skins.txt').read_text().splitlines() rust_skins = (build / 'rust-skins.txt').read_text().splitlines() diff --git a/tools/test_team_rules_parity.py b/tools/test_team_rules_parity.py index 5eb0c7d9d..ac66a412b 100644 --- a/tools/test_team_rules_parity.py +++ b/tools/test_team_rules_parity.py @@ -84,9 +84,9 @@ def main(): PARITY / 'VanillaTeamRulesOracle.java'], 'compile-java') run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaTeamRulesOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') + binary = Path(metadata['target_directory']) / 'release/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe') run([binary, 'team_rules_fixture',inputs, build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] diff --git a/tools/test_teleport_consume_parity.py b/tools/test_teleport_consume_parity.py index 8f51361f8..8cbc23f52 100644 --- a/tools/test_teleport_consume_parity.py +++ b/tools/test_teleport_consume_parity.py @@ -54,9 +54,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaTeleportConsumeOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'teleport_consume_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_terrain_parity.py b/tools/test_terrain_parity.py index a818dcabb..5dfcc76a2 100644 --- a/tools/test_terrain_parity.py +++ b/tools/test_terrain_parity.py @@ -99,9 +99,9 @@ def main(): (build/"registries.json").write_text(json.dumps(bundle,separators=(",",":")),encoding="utf-8") fixture_paths=[inputs,build/"registries.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"terrain_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_tick_parity.py b/tools/test_tick_parity.py index 47dd842d0..92efb89f6 100644 --- a/tools/test_tick_parity.py +++ b/tools/test_tick_parity.py @@ -163,8 +163,8 @@ def main(): completed.check_returncode() return completed.stdout data_java("server", "generate") - test_rust_parity.run(["cargo", "build", "--release", "-p", "horizon-world", "--example", "probe"]) - fixture = Path(metadata["target_directory"]) / "release/examples" / ("probe.exe" if os.name=="nt" else "probe") + test_rust_parity.run(["cargo", "build", "--release", "-p", "horizon-world", "--example", "world_probe"]) + fixture = Path(metadata["target_directory"]) / "release/examples" / ("world_probe.exe" if os.name=="nt" else "world_probe") test_rust_parity.run([str(fixture), "tick_fixture", str(base)]) references = [] for side, jar in jars.items(): diff --git a/tools/test_trading_parity.py b/tools/test_trading_parity.py index c26c449fb..46e81f928 100644 --- a/tools/test_trading_parity.py +++ b/tools/test_trading_parity.py @@ -219,8 +219,8 @@ def main(): if args.java_only: print(f'{len(vanilla)} oracle lines') return - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') - binary = lab.cargo_target() / 'release/examples/probe' + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') + binary = lab.cargo_target() / 'release/examples/client_probe' run([binary, 'trading_fixture', resources, inputs, build / 'server.txt', build / 'rust.txt'], 'rust') rust = (build / 'rust.txt').read_text().splitlines() bad = [(a, b) for a, b in zip(vanilla, rust) if a != b] diff --git a/tools/test_translucency_parity.py b/tools/test_translucency_parity.py index fff0390eb..22818b434 100644 --- a/tools/test_translucency_parity.py +++ b/tools/test_translucency_parity.py @@ -52,7 +52,7 @@ def main(): lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTranslucencyOracle.java'], 'compile-java') vanilla, rust = build / 'vanilla.jsonl', build / 'rust.jsonl' run(['java', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaTranslucencyOracle', inputs, vanilla], 'vanilla') - run(['cargo', 'run', '--quiet', '--locked', '--profile', args.profile, '-p', 'horizon-client', '--example', 'probe', '--', 'translucency_fixture', inputs, rust], 'rust') + run(['cargo', 'run', '--quiet', '--locked', '--profile', args.profile, '-p', 'horizon-client', '--example', 'client_probe', '--', 'translucency_fixture', inputs, rust], 'rust') expected = [json.loads(line) for line in vanilla.read_text().splitlines()] actual = [json.loads(line) for line in rust.read_text().splitlines()] assert len(expected) == len(actual), 'case count differs' diff --git a/tools/test_tree_feature_parity.py b/tools/test_tree_feature_parity.py index b3f9ace68..a99c3a52b 100644 --- a/tools/test_tree_feature_parity.py +++ b/tools/test_tree_feature_parity.py @@ -135,9 +135,9 @@ def main(): output.write(json.dumps(fixture,separators=(',',':'))+'\n');count+=1 fixtures=[inputs,*sorted(build.glob('*.nbt')),*[p for p in sorted(build.glob('*.json')) if p.name!='report.json']];tested_fixtures=fixture_hashes(fixtures) print(f'Prepared {count:,} feature fixtures',flush=True) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'tree_feature_fixture',build],'rust');references=[] for side,jar in jars.items(): java('VanillaTreeFeatureOracle',side,side,build);matched=base.compare(build/(side+'.txt'),build/'rust.txt');print(f'{side}: {matched:,} tree/ore output lines match Rust',flush=True) diff --git a/tools/test_trial_spawner_parity.py b/tools/test_trial_spawner_parity.py index bd6d69ac2..7b2412eaa 100644 --- a/tools/test_trial_spawner_parity.py +++ b/tools/test_trial_spawner_parity.py @@ -214,9 +214,9 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/probe' + binary = Path(metadata['target_directory']) / 'release/examples/client_probe' run([binary, 'natural_spawn_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] diff --git a/tools/test_use_flag_reaction_parity.py b/tools/test_use_flag_reaction_parity.py index de3b5fa20..5498f3bc2 100644 --- a/tools/test_use_flag_reaction_parity.py +++ b/tools/test_use_flag_reaction_parity.py @@ -60,9 +60,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaUseFlagReactionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'use_flag_reaction_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_use_remainder_parity.py b/tools/test_use_remainder_parity.py index 853d12acb..5f7e5a160 100644 --- a/tools/test_use_remainder_parity.py +++ b/tools/test_use_remainder_parity.py @@ -59,9 +59,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaUseRemainderOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'use_remainder_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_value_provider_parity.py b/tools/test_value_provider_parity.py index 589a97632..0c36eb4bc 100644 --- a/tools/test_value_provider_parity.py +++ b/tools/test_value_provider_parity.py @@ -74,9 +74,9 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","world_probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + binary=Path(metadata["target_directory"])/"release/examples"/("world_probe.exe" if os.name=="nt" else "world_probe") run([binary,"value_provider_fixture",build],"rust") references=[] for side,jar in jars.items(): diff --git a/tools/test_vault_parity.py b/tools/test_vault_parity.py index 73c41e197..5741320d3 100644 --- a/tools/test_vault_parity.py +++ b/tools/test_vault_parity.py @@ -190,9 +190,9 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/probe' + binary = Path(metadata['target_directory']) / 'release/examples/client_probe' run([binary, 'natural_spawn_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] diff --git a/tools/test_view_direction_parity.py b/tools/test_view_direction_parity.py index f2738dcff..6230bcdab 100644 --- a/tools/test_view_direction_parity.py +++ b/tools/test_view_direction_parity.py @@ -58,9 +58,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaViewDirectionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'view_direction_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_water_splash_parity.py b/tools/test_water_splash_parity.py index 84f89d360..830f34907 100644 --- a/tools/test_water_splash_parity.py +++ b/tools/test_water_splash_parity.py @@ -59,9 +59,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaWaterSplashOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'water_splash_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_world_border_parity.py b/tools/test_world_border_parity.py index 618194978..01d0c1e07 100644 --- a/tools/test_world_border_parity.py +++ b/tools/test_world_border_parity.py @@ -70,9 +70,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaWorldBorderOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'world_border_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_world_border_render_parity.py b/tools/test_world_border_render_parity.py index f8c88b6a6..f064cf031 100644 --- a/tools/test_world_border_render_parity.py +++ b/tools/test_world_border_render_parity.py @@ -103,7 +103,7 @@ def main(): PARITY / 'VanillaWorldBorderRenderOracle.java'], 'compile-java') run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaWorldBorderRenderOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe', '--', 'world_border_render_fixture', inputs, build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] diff --git a/tools/test_world_collision_check_parity.py b/tools/test_world_collision_check_parity.py index 3dae747d5..7c625c448 100644 --- a/tools/test_world_collision_check_parity.py +++ b/tools/test_world_collision_check_parity.py @@ -80,9 +80,9 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'facts.json', 'definitions.json', 'block-registry.nbt', 'cached-collision.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'world_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary = Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary, 'registry_collision_scan_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) diff --git a/tools/test_world_edge_backoff_parity.py b/tools/test_world_edge_backoff_parity.py index 10cf1316f..b4b07622a 100644 --- a/tools/test_world_edge_backoff_parity.py +++ b/tools/test_world_edge_backoff_parity.py @@ -81,9 +81,9 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'facts.json', 'definitions.json', 'block-registry.nbt', 'cached-collision.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'world_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary = Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary, 'registry_collision_scan_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) diff --git a/tools/test_world_movement_parity.py b/tools/test_world_movement_parity.py index 5a583ecb7..067d147a9 100644 --- a/tools/test_world_movement_parity.py +++ b/tools/test_world_movement_parity.py @@ -106,9 +106,9 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'facts.json', 'definitions.json', 'block-registry.nbt', 'cached-collision.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'world_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary = Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary, 'registry_collision_scan_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) diff --git a/tools/test_world_parity.py b/tools/test_world_parity.py index e2781866e..0b4a3deb7 100644 --- a/tools/test_world_parity.py +++ b/tools/test_world_parity.py @@ -51,12 +51,12 @@ def main(): print("Generating vanilla world-data fixtures...", flush=True) print(java("server", "generate").split("HORIZON_WORLD_GENERATED")[-1].strip(), flush=True) - run(["cargo", "build", "--release", "-p", "horizon-world", "--bin", "horizon-world", "--example", "probe"], base / "compile-rust.log") + run(["cargo", "build", "--release", "-p", "horizon-world", "--bin", "horizon-world", "--example", "world_probe"], base / "compile-rust.log") metadata = json.loads(run(["cargo", "metadata", "--no-deps", "--format-version", "1"])) target = Path(metadata["target_directory"]) / "release" suffix = ".exe" if os.name == "nt" else "" binary = target / ("horizon-world" + suffix) - run([target / "examples" / ("probe" + suffix), "world_fixture", base], base / "rust-fixture.log") + run([target / "examples" / ("world_probe" + suffix), "world_fixture", base], base / "rust-fixture.log") for network in [False, True]: kind = "network" if network else "nbt" output = base / "rust" / kind diff --git a/tools/test_world_ray_parity.py b/tools/test_world_ray_parity.py index 87189d611..46315b5df 100644 --- a/tools/test_world_ray_parity.py +++ b/tools/test_world_ray_parity.py @@ -60,9 +60,9 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaWorldRayOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'world_ray_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_world_spawn_parity.py b/tools/test_world_spawn_parity.py index f73da3a8c..5daa38a45 100644 --- a/tools/test_world_spawn_parity.py +++ b/tools/test_world_spawn_parity.py @@ -79,7 +79,7 @@ def origins(build, classes, dependencies, all_seeds): vanilla_out = build / 'origins-vanilla.txt' oh.run_logged(['java', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaWorldSpawnOracle', vanilla_out, *all_seeds], build, 'origins-vanilla') - rust = subprocess.run([target_dir() / 'examples/probe', 'spawn_origin', RESOURCES, *map(str, all_seeds)], + rust = subprocess.run([target_dir() / 'examples/world_probe', 'spawn_origin', RESOURCES, *map(str, all_seeds)], capture_output=True, text=True, check=True, cwd=lab.ROOT).stdout vanilla = vanilla_out.read_text() parse = lambda text: {int(l.split()[0]): tuple(map(int, l.split()[1:])) for l in text.splitlines() if l} @@ -121,7 +121,7 @@ def main(): oh.run_logged(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-cp', dependencies, '-d', classes, lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldSpawnOracle.java'], build, 'compile-java') - oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'probe'], build, 'compile-probe') + oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'world_probe'], build, 'compile-probe') all_seeds = parity_shard.shard(args.seed or seeds(args.random)) started = time.time() diff --git a/tools/test_worldgen_random_parity.py b/tools/test_worldgen_random_parity.py index 29eedfa49..5371c0444 100644 --- a/tools/test_worldgen_random_parity.py +++ b/tools/test_worldgen_random_parity.py @@ -53,9 +53,9 @@ def main(): with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','world_probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + binary=Path(metadata['target_directory'])/'release/examples'/('world_probe.exe' if os.name=='nt' else 'world_probe') run([binary,'worldgen_random_fixture',build],'rust');references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependency_path]),'dev.horizonlab.parity.VanillaWorldgenRandomOracle',side,build],side) From 9c843819b78535791e852b39b9716576e33f2907 Mon Sep 17 00:00:00 2001 From: JasonGu <1456970218@qq.com> Date: Sat, 24 Oct 2026 15:45:14 +0800 Subject: [PATCH 085/408] Java shader packs: keep the view bob in the view, not the projection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A pack rebuilds view positions from the depth buffer with `inverse_projection` and then multiplies by `inverse_view` (`gbufferModelViewInverse`), and Horizon's own packs do the same through `world_offset` and `frame.inverse_view`. Passing `world_projection(fov, aspect, far) * bob` as the projection while `view` stayed unbobbed left the two halves disagreeing by the walk bob, so everything a pack reconstructed — reflections, ambient occlusion, godrays — turned with the bob. That reads as reflections wobbling in step with the first-person hand, and changing the FOV made it worse. Vanilla and Iris carry the bob in the world's pose stack (the model-view matrix), not in the projection. Pass `bob * view` as the view and the plain world projection instead: `projection * view` is unchanged, so terrain, entities and the pack's own geometry programs draw as before, while depth reconstruction is now consistent. The hand's uniforms already carried the bob in its pose and are untouched. Checked with Complementary Reimagined r5.9.3 over the depth-feedback passes at 70 and 110 FOV. Co-Authored-By: DeepSeek V4.1 Flash (OpenCode agent) --- crates/horizon-client/src/gfx.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index e951f4d58..cb2ead3f6 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -3402,10 +3402,15 @@ impl Renderer { }; self.uploads .buffer(&mut encoder, &self.globals, 0, bytemuck::bytes_of(&globals)); + // Vanilla keeps the view bob in the world's PoseStack, not in the + // projection, and packs reconstruct view positions from the depth + // buffer and multiply by `inverse_view` (`gbufferModelViewInverse`): + // with the bob in the projection instead, everything they rebuild — + // reflections, AO, godrays — slid along with the walk bob. let pack_uniform = shader_pack_uniform( frame, - view, - world_projection(frame.fov_degrees, aspect, frame.depth_far) * frame.bob, + frame.bob * view, + world_projection(frame.fov_degrees, aspect, frame.depth_far), sun, fog_color, globals.fog, From 377d81a3292657b822168dd8153717c0e1ab1d3e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 11:07:44 +0200 Subject: [PATCH 086/408] AGENTS.md: keep Ludovic's markers, let a contributor's agent name its own person and tool Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 48ba6e973..5b5e9e936 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,11 +12,14 @@ Feature → files → harness for the most-changed areas: [docs/architecture.md] folders in `HORIZON_HOME` (the game's data), `HORIZON_LAUNCHER_HOME`, `XDG_DATA_HOME` and `XDG_CONFIG_HOME`, plus `HORIZON_LAUNCHER_NO_SELF_UPDATE=1` and `HORIZON_NO_AUDIO=1`. Never write to `~/.local/share/{applications,horizon,horizon-launcher}` or `~/.local/bin`. -- **Mark what an agent posts.** A PR body starts with - `> 🤖 Opened by an AI agent.` (issues: "Filed by", reviews: "Review by"); every comment starts with - `🤖 Agent:`. Do not claim to be or represent a specific person. - **Attribution.** Commits and PR bodies end - with `🤖 Generated with (Agent Name)`. +- **Mark what an agent posts.** A PR body starts with a line naming whose agent opened it and with what. + Ludovic's agents write `> 🤖 Opened by Ludovic's AI agent (Claude), not by Ludovic himself.`, and a + contributor's agent names its own person and tool (issues: "Filed by", reviews: "Review by"). Every + comment starts with `🤖 Agent:`. Never write as Ludovic or as anyone else. +- **Attribution.** Commits end with a `Co-Authored-By:` line for the agent that wrote them, and PR bodies + with that agent's own "Generated with" line. Ludovic's agents use + `Co-Authored-By: Claude ` and + `🤖 Generated with [Claude Code](https://claude.com/claude-code)`. - Everything players run is Rust. Python/Java only for dev tools and harness drivers in `tools/`. - Horizon-only features follow [docs/design-system.md](docs/design-system.md) and are off by default where they would change the vanilla look. From 4507ded0e480f1de9d6bbe8f7b2104e0c17cf06b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 11:13:27 +0200 Subject: [PATCH 087/408] Read enchantment ids without a namespace as minecraft ones `/give @s wooden_sword[enchantments={knockback:2}]` (or an item saved that way) kept the key `knockback`, which no enchantment lookup matched: the sword showed no enchantment and knocked back like a plain one. Vanilla reads the keys as Identifiers, so `knockback` is `minecraft:knockback`. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/item_data.rs | 38 ++++++++++++++++---------- 1 file changed, 23 insertions(+), 15 deletions(-) diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index 1376dde98..c07e2f352 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -271,23 +271,15 @@ fn read_levels(t: Option<&Tag>) -> Levels { return Vec::new(); }; // Pre-1.21.5 worlds wrap the map in {levels: {...}}. - if let Some(Tag::Compound(inner)) = map.get(&JavaString::from("levels")) { - return inner - .iter() - .filter_map(|(k, v)| { - Some(( - Arc::from(k.to_string_lossy().as_str()), - int(v)?.clamp(1, 255) as u32, - )) - }) - .collect(); - } + let map = match map.get(&JavaString::from("levels")) { + Some(Tag::Compound(inner)) => inner, + _ => map, + }; + // The keys are enchantment Identifiers: `knockback` is `minecraft:knockback`. map.iter() .filter_map(|(k, v)| { - Some(( - Arc::from(k.to_string_lossy().as_str()), - int(v)?.clamp(1, 255) as u32, - )) + let id = horizon_world::datafix::dynamic::namespaced(&k.to_string_lossy()); + Some((Arc::from(id), int(v)?.clamp(1, 255) as u32)) }) .collect() } @@ -863,6 +855,22 @@ mod tests { assert_eq!(back.custom_name(), Some("Blade")); } + #[test] + fn enchantment_ids_without_a_namespace_are_minecraft_ones() { + let levels = Tag::compound([ + ("knockback", Tag::Int(2)), + ("minecraft:sharpness", Tag::Int(1)), + ]); + let components = Tag::compound([("minecraft:enchantments", levels)]); + let (_, extra) = decode_components(Some(&components)); + let stack = ItemStack { + extra, + ..ItemStack::new("minecraft:wooden_sword", 1) + }; + assert_eq!(stack.enchantment_level("minecraft:knockback"), 2); + assert_eq!(stack.enchantment_level("minecraft:sharpness"), 1); + } + #[test] fn custom_name_reads_the_extra_spans() { let name = Tag::compound([ From 01133fac82e335c65dd2aafe83b9efc19055e2e0 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 11:13:27 +0200 Subject: [PATCH 088/408] No default knockback from a hit inside the hurt cooldown A hit that lands while the player is still in its hurt cooldown, harder than the last one, only hurts by the difference (LivingEntity.hurtServer): it marks nothing and deals no default knockback. Horizon knocked the player back 0.4 for it anyway, so a quick second hit (a weak swing, then a charged one) pushed twice. The hurt now reports whether its knockback hook ran (a fresh hit, not fully blocked), and mob_hits_player knocks back only then. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/creatures.rs | 16 +++++--- crates/horizon-client/src/health.rs | 42 ++++++++++++++++++++- crates/horizon-client/src/hunger.rs | 1 + 3 files changed, 52 insertions(+), 7 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 7a685c48d..ec9848919 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1496,12 +1496,16 @@ impl Game<'_> { o.hurt } { - let (xd, zd) = (from[0] - player.position.x, from[2] - player.position.z); - self.knock_back_player(f64::from(0.4_f32), xd, zd); - if let Some(p) = self.player.as_mut() - && let Some(r) = p.hurt_log.last_mut() - { - r.knockback = Some([p.velocity.x, p.velocity.y, p.velocity.z]); + // LivingEntity.hurtServer's dealDefaultKnockback: not inside the + // hurt cooldown (a stronger hit there only adds its difference). + if o.knockback { + let (xd, zd) = (from[0] - player.position.x, from[2] - player.position.z); + self.knock_back_player(f64::from(0.4_f32), xd, zd); + if let Some(p) = self.player.as_mut() + && let Some(r) = p.hurt_log.last_mut() + { + r.knockback = Some([p.velocity.x, p.velocity.y, p.velocity.z]); + } } self.hurt_armor(amount); self.thorns(from); diff --git a/crates/horizon-client/src/health.rs b/crates/horizon-client/src/health.rs index 442a826f0..9d53869ec 100644 --- a/crates/horizon-client/src/health.rs +++ b/crates/horizon-client/src/health.rs @@ -298,6 +298,7 @@ impl PlayerMotion { blocking, blocked: 0.0, block_sound: false, + knocked: false, totem: totem_ready, totem_fired: false, }; @@ -313,6 +314,7 @@ impl PlayerMotion { hurt, blocked: environment.blocked, sound: environment.block_sound, + knockback: environment.knocked, }; if environment.totem_fired { h.totem_used = true; @@ -373,6 +375,8 @@ pub(crate) struct Environment<'a> { pub(crate) blocking: Option, pub(crate) blocked: f32, pub(crate) block_sound: bool, + /// `dealDefaultKnockback` ran: a fresh hit, not fully blocked. + pub(crate) knocked: bool, /// LivingEntity.checkTotemDeathProtection: a totem is held / was used. pub(crate) totem: bool, pub(crate) totem_fired: bool, @@ -435,6 +439,9 @@ pub struct BlockOutcome { pub blocked: f32, /// `BlocksAttacks.onBlocked` ran (the block sound plays). pub sound: bool, + /// The hit knocks the player back (`dealDefaultKnockback`): not one in + /// the hurt cooldown, nor one the shield took whole. + pub knockback: bool, } struct MatchedSets; impl horizon_world::blocking_rules::TypeMatchWorld for MatchedSets { @@ -667,9 +674,11 @@ impl HurtWorld for Environment<'_> { *self.sync_velocity = true; Ok(()) } + /// The caller applies it: these sources carry no entity or position. fn knockback(&mut self, _: &mut State, _: f32, _: bool) -> io::Result<()> { + self.knocked = true; Ok(()) - } // no entity or position on these sources + } fn death_protection(&mut self, _: &mut State) -> io::Result { if !self.totem || self @@ -761,6 +770,37 @@ impl ServerPlayerHurtWorld for Environment<'_> { #[cfg(test)] mod tests { + #[test] + fn a_hit_in_the_hurt_cooldown_knocks_nobody_back() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("movement-properties.nbt").exists() { + return; + } + let assets = crate::assets::Assets::load(&root).unwrap(); + let resources = crate::motion::MotionResources::load(&root, &assets).unwrap(); + let mut player = + crate::motion::PlayerMotion::new(&resources, horizon_core::geometry::Vec3::ZERO) + .unwrap(); + let (health, rules) = (&resources.health, super::HealthRules::default()); + let id = health.damage.id("minecraft:mob_attack").unwrap(); + let mut hit = |amount| { + player + .hurt_blocking(health, rules, id, amount, None) + .unwrap() + }; + let first = hit(1.0); + assert!(first.hurt && first.knockback); + // A stronger hit inside the cooldown hurts by the difference only + // (LivingEntity.hurtServer), with no dealDefaultKnockback. + let second = hit(2.0); + assert!(second.hurt && !second.knockback); + // A weaker one doesn't hurt at all. + let third = hit(1.5); + assert!(!third.hurt && !third.knockback); + } + #[test] fn hurt_sounds_follow_damage_effects() { // DamageEffects: HURT, THORNS, DROWNING, BURNING, POKING, FREEZING. diff --git a/crates/horizon-client/src/hunger.rs b/crates/horizon-client/src/hunger.rs index 2f97ea293..0d9fb02e0 100644 --- a/crates/horizon-client/src/hunger.rs +++ b/crates/horizon-client/src/hunger.rs @@ -156,6 +156,7 @@ impl FoodWorld for TickWorld<'_> { blocking: None, blocked: 0.0, block_sound: false, + knocked: false, totem: false, totem_fired: false, }; From 50aee229966766e850131d5edf6fcd2cd0c9cfdb Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 11:11:43 +0200 Subject: [PATCH 089/408] Add a knockback harness: a dedicated server against vanilla's tools/test_server_knockback_parity.py runs vanilla's dedicated server and Horizon's (`--dedicated --nogui`) on one flat world and joins both with two vanilla-codec players (KnockbackClient): - Alice hits a cow and a zombie (plain, sprinting, Knockback II, critical, in the air); the game is frozen around the hit and stepped a tick at a time, and the mob's Motion and Pos over 20 ticks are compared exactly; - Alice hits Bob (the same, a shield, netherite, two hits, two sprinting hits, a mace smash, a stronger hit inside the hurt cooldown): Bob's own motion packets, Alice's and her sprint flag are compared; - a zombie hits Bob twice: his motion packets. 7 of 21 cases match on main. KNOWN lists the other 14 with their causes: the guest's server-side velocity never travels (knockback adds up from hit to hit), the server never sends a guest its own sprint flag, the extra knockback's direction uses f32 sin/cos instead of Mth's table, a hit in the hurt cooldown still knocks back, and a mace smash on a player runs none of MaceItem.hurtEnemy. Co-Authored-By: Claude Opus 5.5 --- .../horizonlab/parity/KnockbackClient.java | 444 ++++++++++++++++++ tools/test_server_knockback_parity.py | 337 +++++++++++++ 2 files changed, 781 insertions(+) create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/KnockbackClient.java create mode 100644 tools/test_server_knockback_parity.py diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/KnockbackClient.java b/mods/horizon/src/test/java/dev/horizonlab/parity/KnockbackClient.java new file mode 100644 index 000000000..d8c0483b6 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/KnockbackClient.java @@ -0,0 +1,444 @@ +package dev.horizonlab.parity; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.zip.Deflater; +import java.util.zip.Inflater; +import net.minecraft.SharedConstants; +import net.minecraft.core.UUIDUtil; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.ProtocolInfo; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundDisconnectPacket; +import net.minecraft.network.protocol.common.ClientboundKeepAlivePacket; +import net.minecraft.network.protocol.common.ClientboundPingPacket; +import net.minecraft.network.protocol.common.ServerboundClientInformationPacket; +import net.minecraft.network.protocol.common.ServerboundCustomPayloadPacket; +import net.minecraft.network.protocol.common.ServerboundKeepAlivePacket; +import net.minecraft.network.protocol.common.ServerboundPongPacket; +import net.minecraft.network.protocol.common.custom.BrandPayload; +import net.minecraft.network.protocol.configuration.ClientboundFinishConfigurationPacket; +import net.minecraft.network.protocol.configuration.ClientboundSelectKnownPacks; +import net.minecraft.network.protocol.configuration.ConfigurationProtocols; +import net.minecraft.network.protocol.configuration.ServerboundFinishConfigurationPacket; +import net.minecraft.network.protocol.configuration.ServerboundSelectKnownPacks; +import net.minecraft.network.protocol.game.ClientboundChunkBatchFinishedPacket; +import net.minecraft.network.protocol.game.ClientboundPlayerPositionPacket; +import net.minecraft.network.protocol.game.ClientboundSystemChatPacket; +import net.minecraft.network.protocol.game.GameProtocols; +import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket; +import net.minecraft.network.protocol.game.ServerboundAttackPacket; +import net.minecraft.network.protocol.game.ServerboundPlayerCommandPacket; +import net.minecraft.network.protocol.game.ServerboundPunchPacket; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.network.protocol.game.ServerboundAcceptTeleportationPacket; +import net.minecraft.network.protocol.game.ServerboundChatCommandPacket; +import net.minecraft.network.protocol.game.ServerboundChunkBatchReceivedPacket; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.network.protocol.game.ServerboundPlayerInputPacket; +import net.minecraft.network.protocol.game.ServerboundPlayerLoadedPacket; +import net.minecraft.network.protocol.handshake.ClientIntent; +import net.minecraft.network.protocol.handshake.ClientIntentionPacket; +import net.minecraft.network.protocol.handshake.HandshakeProtocols; +import net.minecraft.network.protocol.login.ClientboundLoginCompressionPacket; +import net.minecraft.network.protocol.login.ClientboundLoginDisconnectPacket; +import net.minecraft.network.protocol.login.ClientboundLoginFinishedPacket; +import net.minecraft.network.protocol.login.LoginProtocols; +import net.minecraft.network.protocol.login.ServerboundHelloPacket; +import net.minecraft.network.protocol.login.ServerboundLoginAcknowledgedPacket; +import net.minecraft.server.level.ClientInformation; +import net.minecraft.world.entity.PositionMoveRotation; +import net.minecraft.world.entity.player.Input; +import net.minecraft.world.phys.Vec3; + +/** + * Players made of vanilla's own protocol code that hit and get hit, for + * knockback (tools/test_server_knockback_parity.py). Script on stdin: + * {@code step LABEL}, {@code join NAME}, {@code cmd NAME COMMAND...} (waits + * for its feedback), {@code pos NAME X Y Z YAW PITCH GROUND} (one client tick + * at that place, on the ground or not), {@code sprint NAME on|off}, {@code + * attack NAME TARGET} (ServerboundAttackPacket then the swing; TARGET is a + * player's name or an entity type's path, the last one added), {@code use + * NAME} (ServerboundUseItemPacket, main hand) and {@code end}. Each player + * records the ClientboundSetEntityMotionPacket it receives, its own sprint + * flag as the server sets it, teleports, and the system chat (command + * feedback). + */ +public final class KnockbackClient { + private static volatile String step = "start"; + private static final Map NAMES = new LinkedHashMap<>(); + + public static void main(String[] args) throws Exception { + ParityData.init(); + String host = args[0]; + int port = Integer.parseInt(args[1]); + Path output = Path.of(args[2]); + Map players = new LinkedHashMap<>(); + BufferedReader script = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)); + String line; + while ((line = script.readLine()) != null) { + String[] w = line.trim().split(" ", 3); + try { + switch (w[0]) { + case "step" -> step = w[1]; + case "join" -> { + Player p = new Player(w[1]); + players.put(w[1], p); + NAMES.put(UUIDUtil.createOfflinePlayerUUID(w[1]), w[1]); + p.join(host, port); + } + case "cmd" -> players.get(w[1]).command(w[2]); + case "pos" -> { + String[] a = w[2].split(" "); + players.get(w[1]).at(new Vec3(Double.parseDouble(a[0]), Double.parseDouble(a[1]), Double.parseDouble(a[2])), + Float.parseFloat(a[3]), Float.parseFloat(a[4]), a[5].equals("1")); + } + case "sprint" -> players.get(w[1]).sprint(w[2].equals("on")); + case "attack" -> players.get(w[1]).attack(w[2]); + case "use" -> players.get(w[1]).send(new ServerboundUseItemPacket(InteractionHand.MAIN_HAND, 0, 0, 0)); + case "punch" -> players.get(w[1]).send(net.minecraft.network.protocol.game.ServerboundPunchPacket.INSTANCE); + case "mark" -> players.get(w[1]).mark(); + case "await" -> players.get(w[1]).await(); + case "end" -> { + try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(output, StandardCharsets.UTF_8))) { + for (Player p : players.values()) { + synchronized (p.lines) { + for (String l : p.lines) out.println(p.name + " " + l); + } + } + } + for (Player p : players.values()) p.close(); + System.exit(0); + } + default -> throw new IllegalArgumentException("unknown script line " + line); + } + } catch (Exception e) { + Player p = w.length > 1 ? players.get(w[1]) : null; + if (p != null) p.record("error " + w[0] + " " + e); + else System.err.println("error " + line + ": " + e); + } + } + System.exit(1); + } + + private static final class Player { + final String name; + final List lines = new ArrayList<>(); + private Socket socket; + private DataInputStream in; + private OutputStream out; + private int threshold = -1; + private ProtocolInfo inbound; + private ProtocolInfo outbound; + private volatile PositionMoveRotation position = new PositionMoveRotation(Vec3.ZERO, Vec3.ZERO, 0, 0); + private boolean loaded; + private volatile int id = -1; + /** Every entity this player was sent: its id to a name (players) or type path. */ + private final Map seen = new java.util.concurrent.ConcurrentHashMap<>(); + private final Map last = new java.util.concurrent.ConcurrentHashMap<>(); + private final Object replyLock = new Object(); + private int replies; + /** The motion packets about this player it was sent, and how many there were at the last `mark`. */ + private int pushes; + private int marked; + + Player(String name) { + this.name = name; + } + + void command(String command) throws Exception { + synchronized (replyLock) { + int before = replies; + send(new ServerboundChatCommandPacket(command)); + long until = System.nanoTime() + 30_000_000_000L; + while (replies == before) { + long left = (until - System.nanoTime()) / 1_000_000L; + if (left <= 0) { + record("error no reply to /" + command); + return; + } + replyLock.wait(left); + } + } + } + + void mark() { + synchronized (replyLock) { + marked = pushes; + } + } + + /** Waits for a motion packet about this player since the last `mark` (a mob's hit, which comes when its AI + * strikes). */ + void await() throws Exception { + synchronized (replyLock) { + long until = System.nanoTime() + 20_000_000_000L; + while (pushes == marked) { + long left = (until - System.nanoTime()) / 1_000_000L; + if (left <= 0) { + record("error no motion packet since the mark"); + return; + } + replyLock.wait(left); + } + } + } + + void record(String line) { + synchronized (lines) { + lines.add("step=" + step + " " + line); + } + } + + void at(Vec3 to, float yaw, float pitch, boolean ground) throws Exception { + position = new PositionMoveRotation(to, Vec3.ZERO, yaw, pitch); + // A tick of its own: the server takes one position per client tick (receivedPositionThisTick). + send(net.minecraft.network.protocol.game.ServerboundClientTickEndPacket.INSTANCE); + send(new ServerboundMovePlayerPacket.PosRot(to, yaw, pitch, ground, false)); + send(net.minecraft.network.protocol.game.ServerboundClientTickEndPacket.INSTANCE); + } + + void sprint(boolean on) throws Exception { + // ServerboundPlayerCommandPacket's only public constructors take an Entity: read it from its bytes. + FriendlyByteBuf b = new FriendlyByteBuf(Unpooled.buffer()); + b.writeVarInt(id); + b.writeVarInt((on ? ServerboundPlayerCommandPacket.Action.START_SPRINTING : ServerboundPlayerCommandPacket.Action.STOP_SPRINTING).ordinal()); + b.writeVarInt(0); + send(ServerboundPlayerCommandPacket.STREAM_CODEC.decode(b)); + } + + void attack(String target) throws Exception { + Integer entity = last.get(target); + if (entity == null) { + record("error no " + target + " to attack"); + return; + } + send(new ServerboundAttackPacket(entity)); + send(ServerboundPunchPacket.INSTANCE); + } + + void close() throws Exception { + if (socket != null) socket.close(); + } + + void join(String host, int port) throws Exception { + socket = new Socket(); + socket.connect(new InetSocketAddress(host, port), 10_000); + socket.setTcpNoDelay(true); + in = new DataInputStream(socket.getInputStream()); + out = socket.getOutputStream(); + outbound = HandshakeProtocols.SERVERBOUND; + send(new ClientIntentionPacket(SharedConstants.getProtocolVersion(), host, port, ClientIntent.LOGIN)); + outbound = LoginProtocols.SERVERBOUND; + inbound = LoginProtocols.CLIENTBOUND; + send(new ServerboundHelloPacket(name, UUIDUtil.createOfflinePlayerUUID(name))); + while (true) { + Packet p = read().packet; + if (p instanceof ClientboundLoginCompressionPacket c) { + threshold = c.getCompressionThreshold(); + } else if (p instanceof ClientboundLoginFinishedPacket) { + send(ServerboundLoginAcknowledgedPacket.INSTANCE); + break; + } else if (p instanceof ClientboundLoginDisconnectPacket d) { + throw new IllegalStateException("login refused: " + d.reason().getString()); + } + } + outbound = ConfigurationProtocols.SERVERBOUND; + inbound = ConfigurationProtocols.CLIENTBOUND; + send(new ServerboundCustomPayloadPacket(new BrandPayload("vanilla"))); + send(new ServerboundClientInformationPacket(ClientInformation.createDefault())); + while (true) { + Packet p = read().packet; + if (p instanceof ClientboundSelectKnownPacks k) { + send(new ServerboundSelectKnownPacks(k.knownPacks())); + } else if (p instanceof ClientboundKeepAlivePacket k) { + send(new ServerboundKeepAlivePacket(k.getId())); + } else if (p instanceof ClientboundPingPacket k) { + send(new ServerboundPongPacket(k.getId())); + } else if (p instanceof ClientboundFinishConfigurationPacket) { + send(ServerboundFinishConfigurationPacket.INSTANCE); + break; + } else if (p instanceof ClientboundDisconnectPacket d) { + throw new IllegalStateException("disconnected: " + d.reason().getString()); + } + } + GameProtocols.Context context = new GameProtocols.Context() { + @Override + public boolean hasInfiniteMaterials() { + return true; + } + + @Override + public boolean canUseCommandBlocks() { + return true; + } + }; + outbound = GameProtocols.SERVERBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(ParityData.access), context); + inbound = GameProtocols.CLIENTBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(ParityData.access)); + Thread reader = new Thread(this::play, name); + reader.setDaemon(true); + reader.start(); + } + + private void play() { + try { + while (true) { + Received r = read(); + Packet p = r.packet; + if (p instanceof net.minecraft.network.protocol.game.ClientboundLoginPacket l) { + id = l.playerId(); + seen.put(id, "self"); + } else if (p instanceof net.minecraft.network.protocol.game.ClientboundAddEntityPacket a) { + String who = a.getType() == net.minecraft.world.entity.EntityTypes.PLAYER + ? NAMES.getOrDefault(a.getUUID(), "uuid?") + : net.minecraft.core.registries.BuiltInRegistries.ENTITY_TYPE.getKey(a.getType()).getPath(); + seen.put(a.getId(), who); + last.put(who, a.getId()); + } else if (p instanceof ClientboundSetEntityMotionPacket m) { + Vec3 v = m.movement(); + record(String.format(java.util.Locale.ROOT, "motion %s %.5f %.5f %.5f", + seen.getOrDefault(m.id(), "id" + m.id()), v.x, v.y, v.z)); + if (m.id() == id) { + synchronized (replyLock) { + pushes++; + replyLock.notifyAll(); + } + } + } else if (p instanceof net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket d && d.id() == id) { + for (var value : d.packedItems()) { + if (value.id() == 0) record("sprinting " + ((((Byte) value.value()) & 8) != 0)); + } + } else if (p instanceof ClientboundSystemChatPacket c) { + record("chat " + c.content().getString()); + synchronized (replyLock) { + replies++; + replyLock.notifyAll(); + } + } else if (p instanceof ClientboundKeepAlivePacket k) { + send(new ServerboundKeepAlivePacket(k.getId())); + } else if (p instanceof ClientboundPingPacket k) { + send(new ServerboundPongPacket(k.getId())); + } else if (p instanceof ClientboundPlayerPositionPacket t) { + position = PositionMoveRotation.calculateAbsolute(position, t.change(), t.relatives()); + Vec3 at = position.position(); + if (loaded) { + record(String.format(java.util.Locale.ROOT, "teleport %.3f %.3f %.3f", at.x, at.y, at.z)); + } + send(new ServerboundAcceptTeleportationPacket(t.id(), at.x, at.y, at.z, position.yRot(), position.xRot())); + if (!loaded) { + send(new ServerboundMovePlayerPacket.PosRot(at, position.yRot(), position.xRot(), false, false)); + send(new ServerboundPlayerLoadedPacket()); + loaded = true; + } + } else if (p instanceof ClientboundChunkBatchFinishedPacket) { + send(new ServerboundChunkBatchReceivedPacket(64.0F)); + } else if (p instanceof ClientboundDisconnectPacket d) { + record("disconnected " + d.reason().getString()); + return; + } + } + } catch (Exception e) { + if (!socket.isClosed()) record("error play " + e); + } + } + + private record Received(Packet packet, byte[] payload) {} + + private Received read() throws Exception { + byte[] payload = readFrame(); + ByteBuf buf = Unpooled.wrappedBuffer(payload); + Packet packet = inbound.codec().decode(buf); + if (buf.readableBytes() > 0) { + throw new IllegalStateException(packet.type().id() + " was larger than expected: " + buf.readableBytes() + " bytes left"); + } + return new Received(packet, payload); + } + + synchronized void send(Packet packet) throws Exception { + ByteBuf body = Unpooled.buffer(); + ((ProtocolInfo) outbound).codec().encode(body, packet); + byte[] raw = new byte[body.readableBytes()]; + body.readBytes(raw); + ByteBuf frame = Unpooled.buffer(); + if (threshold >= 0) { + ByteBuf inner = Unpooled.buffer(); + if (raw.length >= threshold) { + writeVarInt(inner, raw.length); + Deflater d = new Deflater(); + d.setInput(raw); + d.finish(); + byte[] tmp = new byte[raw.length + 64]; + while (!d.finished()) inner.writeBytes(tmp, 0, d.deflate(tmp)); + d.end(); + } else { + writeVarInt(inner, 0); + inner.writeBytes(raw); + } + writeVarInt(frame, inner.readableBytes()); + frame.writeBytes(inner); + } else { + writeVarInt(frame, raw.length); + frame.writeBytes(raw); + } + byte[] bytes = new byte[frame.readableBytes()]; + frame.readBytes(bytes); + out.write(bytes); + out.flush(); + } + + private byte[] readFrame() throws Exception { + byte[] frame = new byte[readVarInt(in)]; + in.readFully(frame); + if (threshold < 0) return frame; + ByteArrayInputStream header = new ByteArrayInputStream(frame); + int dataLength = readVarInt(header); + int skip = frame.length - header.available(); + if (dataLength == 0) return java.util.Arrays.copyOfRange(frame, skip, frame.length); + Inflater inflater = new Inflater(); + inflater.setInput(frame, skip, frame.length - skip); + byte[] raw = new byte[dataLength]; + int n = inflater.inflate(raw); + inflater.end(); + if (n != dataLength) throw new IllegalStateException("decompressed " + n + " of " + dataLength + " bytes"); + return raw; + } + } + + private static int readVarInt(InputStream in) throws Exception { + int value = 0; + for (int shift = 0; shift < 35; shift += 7) { + int b = in.read(); + if (b < 0) throw new java.io.EOFException(); + value |= (b & 0x7F) << shift; + if ((b & 0x80) == 0) return value; + } + throw new IllegalStateException("VarInt too big"); + } + + private static void writeVarInt(ByteBuf buf, int value) { + while ((value & ~0x7F) != 0) { + buf.writeByte((value & 0x7F) | 0x80); + value >>>= 7; + } + buf.writeByte(value); + } +} diff --git a/tools/test_server_knockback_parity.py b/tools/test_server_knockback_parity.py new file mode 100644 index 000000000..cd061321d --- /dev/null +++ b/tools/test_server_knockback_parity.py @@ -0,0 +1,337 @@ +#!/usr/bin/env python3 +"""Knockback on a dedicated server, against vanilla's, seen by vanilla clients. + +A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`) each serve a copy of one flat +world vanilla generated first, in survival on Normal, with Alice and Bob as operators. KnockbackClient, two +players made of vanilla's protocol code, joins them both and runs one script on each: + +- Alice hits a cow and a zombie: a plain hit, a sprinting hit, Knockback II, a critical hit, and a plain hit on + a mob in the air. The game is frozen around the hit (`/tick freeze`) and stepped a tick at a time: the mob's + Motion just after the hit and its Pos and Motion over the next 20 ticks are compared exactly. The mobs are + slowed to a stop (Slowness 128) so that their walking adds nothing; +- Alice hits Bob: a plain hit, sprinting, Knockback II, a critical hit, Bob behind a raised shield, Bob in + netherite (knockback resistance), two plain hits a second apart, two sprinting hits a second apart (the + first stops Alice's sprint), a mace smash, and a weak hit then a stronger one inside Bob's hurt cooldown. + Bob's own ClientboundSetEntityMotionPacket (the knockback his client applies, Player.causeExtraKnockback), + Alice's motion packets and her sprint flag as the server sets it are compared exactly; +- a zombie hits Bob, twice: the knockback reaches Bob's client once his server-side copy has + travelled a tick (the mob's hit, then ServerPlayer's travel, then ServerEntity.sendChanges). It is night, so + that no zombie burns (a burning mob is in its hurt cooldown). + +Each case is compared on its own. KNOWN lists the cases Horizon still gets wrong and why; one that matches +again is reported, and should leave the list. +""" +import os +from pathlib import Path +import platform +import re +import shutil +import subprocess +import sys +import time + +try: + from . import lab, test_rust_parity as base + from .test_dedicated_server_parity import Server, free_port + from .test_locator_bar_parity import generate_world, ops_json +except ImportError: + import lab + import test_rust_parity as base + from test_dedicated_server_parity import Server, free_port + from test_locator_bar_parity import generate_world, ops_json + +NAME = 'server-knockback-parity' +PROPERTIES = { + 'online-mode': 'false', + 'white-list': 'false', + 'level-seed': '12345', + 'level-type': 'minecraft\\:flat', + 'generate-structures': 'false', + 'gamemode': 'survival', + 'difficulty': 'normal', + 'view-distance': '4', + 'simulation-distance': '4', + 'spawn-protection': '0', + 'max-players': '5', + 'pause-when-empty-seconds': '-1', +} +# Cases Horizon still gets wrong, and why. +VELOCITY = ("a guest's server-side velocity never travels and a hit is sent before it would: each knockback starts " + "from the last one's (ServerPlayer's travel, ServerEntity.sendChanges, Player.causeExtraKnockback)") +SPRINT = "the server never sends a guest its own sprint flag, so a sprint hit doesn't stop the attacker's sprint" +YAW = "the extra knockback's direction comes from f32 sin/cos, not Mth's sine table (z is -2e-8 a block, not 0)" +KNOWN = { + 'cow-sprint': f'{SPRINT}; {YAW}', + 'cow-knockback-2': YAW, + 'zombie-sprint': f'{SPRINT}; {YAW}', + 'zombie-knockback-2': YAW, + 'pvp-plain': VELOCITY, + 'pvp-sprint': f'{VELOCITY}; {SPRINT}', + 'pvp-knockback-2': VELOCITY, + 'pvp-crit': VELOCITY, + 'pvp-netherite': VELOCITY, + 'pvp-twice': VELOCITY, + 'pvp-sprint-twice': f'{VELOCITY}; {SPRINT}', + 'pvp-mace': f'{VELOCITY}; a smash on a player runs none of MaceItem.hurtEnemy (the attacker\'s fall goes on)', + 'pvp-cooldown': f'{VELOCITY}; a hit inside the hurt cooldown still knocks back (LivingEntity.hurtServer)', + 'zombie-hits-bob': VELOCITY, +} + +A = (0.5, -60.0, 0.5) # Alice, facing east (yaw -90) +V = (2.5, -60.0, 0.5) # the mob or Bob, two blocks east +SWORD = 'minecraft:wooden_sword' +KNOCKBACK_SWORD = 'minecraft:wooden_sword[enchantments={"minecraft:knockback":2}]' + + +def stand(name, at, yaw, ticks=3): + """Client ticks on the ground at `at` (one position a tick, as vanilla's client sends).""" + return [f'pos {name} {at[0]} {at[1]} {at[2]} {yaw} 0 1'] * ticks + + +def falling(height): + """Alice off the ground and going down, so that her next hit is critical (or a mace smash).""" + return [f'pos Alice {A[0]} {A[1] + h} {A[2]} -90 0 0' for h in (height, height - 0.3)] + + +def mob_case(kind, weapon=SWORD, sprint=False, crit=False, air=False): + mob = f'@e[type=minecraft:{kind},limit=1]' + summon = [f'cmd Alice summon minecraft:{kind} {V[0]} {V[1] + (1.5 if air else 0)} {V[2]} {{Rotation:[0f,0f]}}', + f'cmd Alice effect give {mob} minecraft:slowness 100000 127 true'] + lines = ['cmd Alice kill @e[type=!player]', 'cmd Alice gamemode creative', 'cmd Bob gamemode creative', + f'cmd Alice item replace entity @s weapon.mainhand with {weapon}', 'cmd Alice tp Bob 2.5 -60 12.5', + *stand('Alice', A, -90), 'sleep 1.2'] + # In the air: frozen before its first tick, so it has not landed. + lines += ['cmd Alice tick freeze', *summon] if air else [*summon, 'sleep 1.5', 'cmd Alice tick freeze'] + lines += ['sleep 0.3', f'cmd Alice data get entity {mob} Pos'] + if sprint: + lines.append('sprint Alice on') + if crit: + lines += falling(0.8) + lines += ['sleep 0.2', f'attack Alice {kind}', 'sleep 0.2', f'cmd Alice data get entity {mob} Motion'] + for _ in range(20): + lines += ['cmd Alice tick step 1', 'sleep 0.25', f'cmd Alice data get entity {mob} Pos', + f'cmd Alice data get entity {mob} Motion'] + lines += ['cmd Alice tick unfreeze', 'cmd Alice kill @e[type=!player]'] + if sprint: + lines.append('sprint Alice off') + lines += [*stand('Alice', A, -90), 'cmd Alice gamemode survival', 'cmd Bob gamemode survival', + f'cmd Alice tp Bob {V[0]} {V[1]} {V[2]} 90 0'] + return lines + + +def pvp_case(weapon=SWORD, sprint=False, crit=False, shield=False, armour=False, twice=False, mace=False, + cooldown=False): + lines = [f'cmd Alice item replace entity @s weapon.mainhand with {weapon}', 'cmd Bob clear @s', + 'cmd Bob effect give @s minecraft:resistance 1000 4 true', + 'cmd Bob effect give @s minecraft:instant_health 1 5 true', *stand('Alice', A, -90), *stand('Bob', V, 90)] + if armour: + lines += [f'cmd Bob item replace entity @s armor.{slot} with minecraft:netherite_{piece}' + for slot, piece in (('head', 'helmet'), ('chest', 'chestplate'), ('legs', 'leggings'), + ('feet', 'boots'))] + if shield: + # A shield blocks from five ticks after it is raised. + lines += ['cmd Bob item replace entity @s weapon.mainhand with minecraft:shield', 'use Bob'] + lines += ['sleep 1.5', *stand('Bob', V, 90, ticks=1)] + if sprint: + lines.append('sprint Alice on') + if crit: + lines += falling(0.8) + if mace: + lines += falling(3.0) + falling(1.5) + if cooldown: + # A swing at the air first: the hit is weak, and the stronger one four ticks later lands inside Bob's hurt + # cooldown (LivingEntity.hurtServer: it hurts by the difference, with no knockback and no motion packet). + lines += ['sleep 0.2', 'punch Alice', 'attack Alice Bob'] + lines += ['sleep 0.2', 'attack Alice Bob', 'sleep 0.3'] + if twice: + lines += [*stand('Bob', V, 90, ticks=20), 'sleep 1.5', 'attack Alice Bob', 'sleep 0.3'] + if sprint: + lines.append('sprint Alice off') + lines += stand('Alice', A, -90) + if shield or armour: + lines.append('cmd Bob clear @s') + return lines + + +def mob_hits_case(kind): + """A mob's own attack on Bob, twice: his motion packet. Alice is in creative, so the mob goes for Bob; each mob + is killed once its hit has come (`await`), and Bob stands back where he was before the next. (A mob with no + attack_knockback of its own: one with some, like a ravager, adds it along its own yaw, which its AI turns.)""" + mob = f'@e[type=minecraft:{kind},limit=1]' + hit = ['mark Bob', f'cmd Alice summon minecraft:{kind} {V[0] + 1} {V[1]} {V[2]} {{Rotation:[90f,0f]}}', + f'cmd Alice effect give {mob} minecraft:slowness 100000 127 true', 'await Bob', f'cmd Alice kill {mob}'] + return ['cmd Bob clear @s', 'cmd Bob effect give @s minecraft:resistance 1000 4 true', 'cmd Alice gamemode creative', + *stand('Bob', V, 90), *hit, 'sleep 2', *stand('Bob', V, 90), *hit, 'sleep 1', + 'cmd Alice kill @e[type=!player]', 'cmd Alice gamemode survival'] + + +CASES = { + 'cow-plain': mob_case('cow'), + 'cow-sprint': mob_case('cow', sprint=True), + 'cow-knockback-2': mob_case('cow', weapon=KNOCKBACK_SWORD), + 'cow-crit': mob_case('cow', crit=True), + 'cow-air': mob_case('cow', air=True), + 'zombie-plain': mob_case('zombie'), + 'zombie-sprint': mob_case('zombie', sprint=True), + 'zombie-knockback-2': mob_case('zombie', weapon=KNOCKBACK_SWORD), + 'zombie-crit': mob_case('zombie', crit=True), + 'zombie-air': mob_case('zombie', air=True), + 'pvp-plain': pvp_case(), + 'pvp-sprint': pvp_case(sprint=True), + 'pvp-knockback-2': pvp_case(weapon=KNOCKBACK_SWORD), + 'pvp-crit': pvp_case(crit=True), + 'pvp-shield': pvp_case(shield=True), + 'pvp-netherite': pvp_case(armour=True), + 'pvp-twice': pvp_case(twice=True), + 'pvp-sprint-twice': pvp_case(sprint=True, twice=True), + 'pvp-mace': pvp_case(weapon='minecraft:mace', mace=True), + 'pvp-cooldown': pvp_case(cooldown=True), + 'zombie-hits-bob': mob_hits_case('zombie'), +} +SETUP = ['cmd Alice gamerule spawn_mobs false', 'cmd Alice gamerule spawn_monsters false', + 'cmd Alice kill @e[type=!player]', 'cmd Alice gamerule advance_time false', 'cmd Alice time set midnight', + f'cmd Alice tp Alice {A[0]} {A[1]} {A[2]} -90 0', f'cmd Alice tp Bob {V[0]} {V[1]} {V[2]} 90 0', 'sleep 2'] + + +def server_dir(directory, world): + if directory.exists(): + shutil.rmtree(directory) + directory.mkdir(parents=True) + port = free_port() + props = dict(PROPERTIES, **{'server-port': str(port)}) + (directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()), + encoding='iso-8859-1') + (directory / 'eula.txt').write_text('eula=true\n') + (directory / 'ops.json').write_text(ops_json()) + shutil.copytree(world, directory / 'world') + (directory / 'world' / 'session.lock').unlink(missing_ok=True) + return port + + +def run_side(label, server_command, client_command, build, world): + directory = build / label + port = server_dir(directory, world) + out = build / f'{label}.txt' + out.unlink(missing_ok=True) + server = Server(server_command, directory, label) + try: + server.wait_for(r'Done \(') + with (build / f'{label}-client.log').open('w') as log: + client = subprocess.Popen([*map(str, client_command), '127.0.0.1', str(port), str(out)], + cwd=lab.ROOT, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT, + text=True) + + def send(line): + if line.startswith('sleep '): + time.sleep(float(line.split()[1])) + else: + client.stdin.write(line + '\n') + client.stdin.flush() + try: + for name in ('Alice', 'Bob'): + send(f'join {name}') + server.wait_for(rf'{name} joined the game', timeout=120) + time.sleep(2) + for line in SETUP: + send(line) + for case, lines in CASES.items(): + send(f'step {case}') + for line in lines: + send(line) + time.sleep(0.5) + send('end') + client.wait(timeout=60) + finally: + if client.poll() is None: + client.kill() + finally: + server.stop() + if not out.exists(): + raise AssertionError(f'{label}: the client wrote no transcript (see {build}/{label}-client.log)') + return out.read_text(encoding='utf-8').splitlines() + + +DATA = re.compile(r'^chat \S+ has the following entity data: \[(.*)\]$') + + +def compared(lines): + """Per case, what is compared: the mob's Pos and Motion (to 1e-9), and each player's motion packets and + sprint flag.""" + cases = {} + for line in lines: + who, step, text = line.split(' ', 2) + step = step.removeprefix('step=') + if step not in CASES: + continue + kept = cases.setdefault(step, []) + data = DATA.match(text) + if who == 'Alice' and data: + kept.append('data ' + ' '.join(f'{float(v.rstrip("d")):.9f}' for v in data.group(1).split(', '))) + elif text.startswith('motion self') or text.startswith('sprinting'): + kept.append(f'{who} {text}') + elif text.startswith('error') or text.startswith('disconnected'): + kept.append(f'{who} {text}') + return cases + + +def main(): + lock, jars, libraries = base.verify_artifacts() + build = lab.LOCAL / NAME + build.mkdir(parents=True, exist_ok=True) + report = build / 'report.json' + report.unlink(missing_ok=True) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/KnockbackClient.java' + classes = build / 'classes' + shutil.rmtree(classes, ignore_errors=True) + classes.mkdir() + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath', + lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], + cwd=lab.ROOT, check=True, capture_output=True) + subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + check=True, capture_output=True) + import json + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], + cwd=lab.ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] + horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'] + client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.KnockbackClient'] + + world = generate_world(vanilla_server, build) + vanilla = compared(run_side('vanilla', vanilla_server, client, build, world)) + horizon = compared(run_side('horizon', horizon_server, client, build, world)) + differ, fixed = [], [] + for case in CASES: + want, got = vanilla.get(case, []), horizon.get(case, []) + if case not in vanilla or any(' error ' in f' {l} ' or 'disconnected' in l for l in want): + raise AssertionError(f'{case}: vanilla recorded nothing or failed: {want}') + if want == got: + if case in KNOWN: + fixed.append(case) + continue + if case in KNOWN: + continue + import difflib + differ.append(f'{case}:\n' + '\n'.join(difflib.unified_diff(want, got, 'vanilla', 'horizon', n=1, lineterm=''))) + if fixed: + print('matching vanilla now, take them out of KNOWN: ' + ', '.join(fixed)) + if differ: + raise AssertionError(f'{len(differ)} cases differ (see {build}/vanilla.txt and horizon.txt):\n' + + '\n'.join(differ)[:8000]) + lab.write_json(report, dict( + schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(), + java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], + cases=len(CASES), known=sorted(KNOWN), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'), + scope='Knockback on a dedicated server, as two vanilla-codec players get it: a player hitting a cow and ' + 'a zombie (plain, sprinting, Knockback II, critical, in the air; the mob\'s motion and path over 20 ' + 'ticks), a player hitting a player (the same, a raised shield, netherite, two hits, a mace smash; ' + 'the victim\'s motion packet and the attacker\'s sprint) and a zombie hurting a player.')) + print(f'server knockback: {len(CASES) - len(KNOWN)} of {len(CASES)} cases identical') + + +if __name__ == '__main__': + try: + main() + except AssertionError as error: + sys.exit(f'{NAME}: {error}') From a6e9374f88c60a0b2946915ac11cab0b1faf56fc Mon Sep 17 00:00:00 2001 From: Ludovic Marie Date: Sat, 24 Oct 2026 11:30:12 +0200 Subject: [PATCH 090/408] Java shader packs: say where vanilla and Iris put the view bob Vanilla 26.3 multiplies bobHurt/bobView into the projection (GameRenderer.renderLevel); Iris's MixinModelViewBobbing moves them into the model-view when a pack is in use. The comment said vanilla keeps the bob in the PoseStack, which is Iris's behaviour, not vanilla's. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/gfx.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index cb2ead3f6..59a3b5d03 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -3402,11 +3402,10 @@ impl Renderer { }; self.uploads .buffer(&mut encoder, &self.globals, 0, bytemuck::bytes_of(&globals)); - // Vanilla keeps the view bob in the world's PoseStack, not in the - // projection, and packs reconstruct view positions from the depth - // buffer and multiply by `inverse_view` (`gbufferModelViewInverse`): - // with the bob in the projection instead, everything they rebuild — - // reflections, AO, godrays — slid along with the walk bob. + // Vanilla multiplies the bob into the projection (GameRenderer.renderLevel); + // Iris moves it into the model-view for packs (MixinModelViewBobbing), whose + // depth reconstruction expects a plain perspective `gbufferProjection`. + // `projection * view` is the same either way. let pack_uniform = shader_pack_uniform( frame, frame.bob * view, From b21423ae01cda2fec404604f9dbcd1526c7fea16 Mon Sep 17 00:00:00 2001 From: Ludovic Marie Date: Sat, 24 Oct 2026 11:31:10 +0200 Subject: [PATCH 091/408] Keep only the Clippy rewrites that read as well on stable CI runs stable Clippy (1.99), which is clean on main. The #[expect(clippy::boxed_local)] in streaming.rs is unfulfilled there and fails CI under -D warnings, so it goes. Also back out the rewrites that only satisfied Rust 1.90's Clippy and read worse: the dragon's range helper and its test, the axolotl test's restated formula, and two De Morgan expansions (first_person_probe, explosion). Co-Authored-By: Claude Opus 5.5 --- .../examples/probe/first_person_probe.rs | 2 +- crates/horizon-client/src/game/dragon.rs | 28 +++---------------- crates/horizon-client/src/game/explosion.rs | 2 +- crates/horizon-client/src/mobs/axolotl.rs | 17 +++++------ crates/horizon-client/src/streaming.rs | 6 ---- 5 files changed, 13 insertions(+), 42 deletions(-) diff --git a/crates/horizon-client/examples/probe/first_person_probe.rs b/crates/horizon-client/examples/probe/first_person_probe.rs index 38829714c..cb4c38e58 100644 --- a/crates/horizon-client/examples/probe/first_person_probe.rs +++ b/crates/horizon-client/examples/probe/first_person_probe.rs @@ -203,7 +203,7 @@ impl HandWorld for Probe<'_> { let item = self.stack(Hand::Main).effective().0; // Item.canDestroyBlock: swords' tools cannot destroy in creative. let sword = item.ends_with("_sword"); - let ok = (!sword || !self.creative) && !self.is_air(pos); + let ok = !(sword && self.creative) && !self.is_air(pos); if ok { self.blocks.insert(pos, "minecraft:air".into()); } diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index cd2de3736..c6f5d419b 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -27,12 +27,6 @@ const CRYSTAL_IDS: u32 = SPECIAL + 16; const FIGHT_FILE: &str = "data/minecraft/ender_dragon_fight.dat"; const MAX_HEALTH: f32 = 200.0; -/// Preserve the ordered double comparisons from vanilla: a NaN squared -/// distance fails both comparisons and must not be treated as out of range. -fn target_distance_outside_range(distance_squared: f64) -> bool { - !distance_squared.is_nan() && !(100.0..=22500.0).contains(&distance_squared) -} - #[derive(Default)] pub(super) struct Fight { loaded: bool, @@ -1292,7 +1286,7 @@ impl Game<'_> { clockwise, } => { let dt = far(*target); - if target_distance_outside_range(dt) || collided { + if dt < 100.0 || dt > 22500.0 || collided { let done = path.as_ref().is_some_and(|p| p.0.done()); let mut chosen = false; if done { @@ -1362,7 +1356,7 @@ impl Game<'_> { *target = Some(Vec3::new(pp.x, pp.y + ho, pp.z)); } let dt = far(*target); - if target_distance_outside_range(dt) { + if dt < 100.0 || dt > 22500.0 { if path.as_ref().is_none_or(|p| p.0.done()) { *path = self.ring_path(clockwise).map(PathBox); } @@ -1399,7 +1393,7 @@ impl Game<'_> { } Phase::LandingApproach { path, target } => { let dt = far(*target); - if target_distance_outside_range(dt) || collided { + if dt < 100.0 || dt > 22500.0 || collided { if path.as_ref().is_none_or(|p| p.0.done()) { let current = self.closest_node(pos.x, pos.y, pos.z); // NEAR_EGG_TARGETING: the enemy nearest the egg. @@ -1583,7 +1577,7 @@ impl Game<'_> { } } else { let dt = far(*target); - if target_distance_outside_range(dt) { + if dt < 100.0 || dt > 22500.0 { *since += 1; } } @@ -3269,18 +3263,4 @@ mod tests { let t = nearest_enemy(&players, false, Vec3::new(9.0, 64.0, 0.0), None, |_| true); assert_eq!(t.map(|p| p.who), Some(FightWho::Host)); } - #[test] - fn target_distance_respects_nan_and_exact_boundaries() { - for (distance, expected) in [ - (f64::NAN, false), - (f64::NEG_INFINITY, true), - (99.0, true), - (100.0, false), - (22500.0, false), - (22501.0, true), - (f64::INFINITY, true), - ] { - assert_eq!(super::target_distance_outside_range(distance), expected); - } - } } diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index e3baa76fc..6ecba3a54 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -306,7 +306,7 @@ impl Game<'_> { { outcome = o; } - if !spectator && (!creative || !flying) { + if !spectator && !(creative && flying) { p.velocity = Vec3::new( p.velocity.x + dir[0] * power, p.velocity.y + dir[1] * power, diff --git a/crates/horizon-client/src/mobs/axolotl.rs b/crates/horizon-client/src/mobs/axolotl.rs index e4a639768..55f15717c 100644 --- a/crates/horizon-client/src/mobs/axolotl.rs +++ b/crates/horizon-client/src/mobs/axolotl.rs @@ -166,16 +166,13 @@ mod axolotl_parity_tests { ] { let mut expected = LegacyRandom::new(seed); let mut actual = LegacyRandom::new(seed); - // The second draw is intentionally consumed even though - // the fixed 4.0 / 14.0 threshold always makes this branch - // true. Removing it changes the native RNG sequence. - let first_gate = !no_ai && expected.next_int_bound(3).unwrap() == 0; - let result = if first_gate { - let _second_draw = expected.next_int_bound(3).unwrap(); - water && entity && !already - } else { - false - }; + let result = !no_ai + && expected.next_int_bound(3).unwrap() == 0 + && ((expected.next_int_bound(3).unwrap() as f32) < 2.0 || 4.0f32 / 14.0 < 0.5) + && 2.0 < 4.0 + && water + && entity + && !already; assert_eq!( roll_play_dead(&mut actual, no_ai, 4.0, 14.0, 2.0, water, entity, already), result diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 92d37483b..15ed1674e 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -641,12 +641,6 @@ impl Streaming { }); self.shared.ready.notify_one(); } - // Proto arrays are large; keep ownership of the incoming heap allocation - // instead of moving all nine chunks onto a transient stack frame. - #[expect( - clippy::boxed_local, - reason = "keep nine large Proto values heap resident" - )] fn receive_decorated(&mut self, x: i32, z: i32, region: Box<[Proto; 9]>) { self.generation_scan.exhausted = false; self.decorating -= 1; From e0d29dc23390fafbcf5a9befee9ac2fb1ac5d1e1 Mon Sep 17 00:00:00 2001 From: Ludovic Marie Date: Sat, 24 Oct 2026 11:31:38 +0200 Subject: [PATCH 092/408] Drop the aquifer helper and correct the fire burnout comment Stable Clippy (1.99, what CI runs) does not flag q < -2. || q > 2., so the helper and its test only served Rust 1.90's Clippy. Fire burnout is not 'intentionally disabled': vanilla's FireBlock.tick reads the INCREASED_FIRE_BURNOUT environment attribute, set by eight overworld biomes, which Horizon does not read yet; the comment now says so. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-world/src/edge_backoff.rs | 2 -- crates/horizon-world/src/level/tick.rs | 3 +- .../src/worldgen/aquifer/noise_based.rs | 31 +------------------ crates/horizon-world/tests/edge_backoff.rs | 4 +-- 4 files changed, 5 insertions(+), 35 deletions(-) diff --git a/crates/horizon-world/src/edge_backoff.rs b/crates/horizon-world/src/edge_backoff.rs index 0dfebdae2..4303b2d74 100644 --- a/crates/horizon-world/src/edge_backoff.rs +++ b/crates/horizon-world/src/edge_backoff.rs @@ -77,8 +77,6 @@ pub fn back_off_from_edge( ); world.no_collision(bounds).map_err(EdgeBackoffError::World) }; - // Keep the collision query's short circuit: on-ground movement must not - // consume any budget, and an unordered (NaN) fall distance skips it too. let should_back_off = grounded || (input.fall_distance < step && !can_fall(0.0, 0.0, step - input.fall_distance)?); if !should_back_off { diff --git a/crates/horizon-world/src/level/tick.rs b/crates/horizon-world/src/level/tick.rs index bced59df9..29f53e053 100644 --- a/crates/horizon-world/src/level/tick.rs +++ b/crates/horizon-world/src/level/tick.rs @@ -565,7 +565,8 @@ impl Sim<'_, L> { return; } } - // Nether burnout is intentionally disabled: keep its behavior explicit. + // FireBlock.tick reads the INCREASED_FIRE_BURNOUT environment attribute + // (jungles, swamps, peaks, mushroom fields); Horizon doesn't yet. let burnout = false; let extra = if burnout { -50 } else { 0 }; for (direction, chance) in [ diff --git a/crates/horizon-world/src/worldgen/aquifer/noise_based.rs b/crates/horizon-world/src/worldgen/aquifer/noise_based.rs index 60abbc371..3f3c7dc2c 100644 --- a/crates/horizon-world/src/worldgen/aquifer/noise_based.rs +++ b/crates/horizon-world/src/worldgen/aquifer/noise_based.rs @@ -447,7 +447,7 @@ impl NoiseBasedAquif let n = 3. + edge; if n > 0. { n / 3. } else { n / 10. } }; - let barrier = if pressure_outside_interval(q) { + let barrier = if q < -2. || q > 2. { 0. } else { if memo.is_nan() { @@ -603,35 +603,6 @@ impl NoiseBasedAquif Ok(Some(candidate)) } } -/// Preserve ordered floating-point comparisons, including NaN (which lies -/// neither below -2 nor above 2). Negating `RangeInclusive::contains` alone -/// would incorrectly treat NaN as outside the interval. -fn pressure_outside_interval(q: f64) -> bool { - !q.is_nan() && !(-2.0..=2.0).contains(&q) -} - fn similarity(a: i32, b: i32) -> f64 { 1. - b.wrapping_sub(a) as f64 / 25. } - -#[cfg(test)] -mod pressure_interval_tests { - use super::pressure_outside_interval; - - #[test] - fn outside_range_preserves_ordered_float_boundary_and_nan_behavior() { - for (q, expected) in [ - (f64::NAN, false), - (f64::NEG_INFINITY, true), - (-2.1, true), - (-2.0, false), - (-0.0, false), - (0.0, false), - (2.0, false), - (2.1, true), - (f64::INFINITY, true), - ] { - assert_eq!(pressure_outside_interval(q), expected, "q={q:?}"); - } - } -} diff --git a/crates/horizon-world/tests/edge_backoff.rs b/crates/horizon-world/tests/edge_backoff.rs index e8f37057f..4e6999205 100644 --- a/crates/horizon-world/tests/edge_backoff.rs +++ b/crates/horizon-world/tests/edge_backoff.rs @@ -70,8 +70,8 @@ fn zero_budget_only_fails_when_a_probe_is_needed() { #[test] fn edge_check_preserves_grounded_and_unordered_fall_distance_short_circuit() { - // Neither already-grounded players nor NaN fall distances should query - // the world at all. The original `fall_distance < step` is false on NaN. + // Neither grounded players nor NaN fall distances query the world: + // `fall_distance < step` is false for NaN. let mut world = World { calls: 0, grounded: true, From 7c83fbb6df401eb4db6a60289cf26e70b55d7c48 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 11:12:03 +0200 Subject: [PATCH 093/408] Travel a guest's server-side velocity, and send hurts after it A guest's (and, on the server thread, the window's) knockback started from the velocity the last hit left on its server copy, which nothing ever slowed down, and each hit went out at once. So every hit after the first pushed harder (0.72, then 0.76 blocks a tick where vanilla sends 0.4 each time), netherite resisted from the wrong base, and a zombie's hit reached the client before the friction of the tick it landed in. Vanilla's server simulates a player too (MoveSimulationType AUTHORITATIVE_SIDE_AND_SERVER): ServerPlayer travels every tick with no input, and ServerEntity.sendChanges sends a velocity a hurt marked (Entity.markHurt) as it is after that travel. A player's melee hit is the exception (Player.causeExtraKnockback): it sends at once, then puts the server copy back to its velocity from before the hit. - MotionWorld::server_travel: Player.travel with no input, keeping only the velocity (the client's moves place the player). The server's copy checks no fall damage on its own moves (isLocalInstanceAuthoritative). - guest_server_tick runs it last, then sends the velocity if a hurt marked it since the last tick. - guest_hit_by leaves a marked velocity to that; guest_struck_by (melee from a player) sends at once and restores. - lan_e2e `knockback`: three hits each way push the victim as far each time. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/lan_actions.rs | 32 +++- crates/horizon-client/src/game/lan_mobs.rs | 43 ++++- crates/horizon-client/src/game/lan_pvp.rs | 2 +- crates/horizon-client/src/motion.rs | 167 ++++++++++++++---- tools/lan_e2e.py | 47 +++++ tools/test_server_knockback_parity.py | 15 +- 6 files changed, 244 insertions(+), 62 deletions(-) diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 7fd969a9b..d42ffc511 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1911,7 +1911,7 @@ impl Game<'_> { let (rules, motion) = (game.world.health_rules, game.motion); let health = &motion.health; let Some(player) = game.player.as_mut() else { - return Vec::new(); + return (Vec::new(), None); }; let mut w = MotionWorld { entities: &[], @@ -1987,22 +1987,44 @@ impl Game<'_> { game.border_damage(); game.tick_mob_effects(); let Some(player) = game.player.as_mut() else { - return Vec::new(); + return (Vec::new(), None); }; let _ = player.peaceful_regeneration(rules); let _ = player.food_tick(health, rules); events.append(&mut player.events); - events + let _ = MotionWorld { + entities: &[], + player, + scene: &mut game.world, + assets: &game.pack.assets, + collision_binding: game.collision, + resources: game.motion, + } + .server_travel(); + // A hurt since the last tick marked the velocity (Entity.markHurt): + // ServerEntity.sendChanges sends it as it is after this travel. + let marked = std::mem::take(&mut player.health.sync_velocity); + let sounds = events .into_iter() .filter_map(|e| match e { MotionEvent::HurtSound(sound) => Some(sound), _ => None, }) - .collect::>() + .collect::>(); + (sounds, marked.then_some(player.velocity)) }); - for sound in sounds.into_iter().flatten() { + let Some((sounds, marked)) = sounds else { + return; + }; + for sound in sounds { self.player_hurt_sound(sound, at); } + if let (Some(v), Some(g)) = (marked, host.hub.guest(conn)) { + g.send(&C::SetEntityMotion(play::SetEntityMotion { + id: g.entity_id, + velocity: [v.x, v.y, v.z], + })); + } } /// ServerGamePacketListenerImpl.handlePlayerCommand START_FALL_FLYING: diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index b3f42f0c7..be277b6e0 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -213,7 +213,9 @@ impl Game<'_> { impl Game<'_> { /// Hurt a guest: `f` runs as them, and the knockback it gave reaches - /// their client (`hurtMarked`: ClientboundSetEntityMotionPacket). + /// their client. A hurt marks the velocity (Entity.markHurt), which goes + /// out once the guest's server copy has travelled (`guest_server_tick`); + /// a push with no hurt goes out at once. pub(super) fn guest_hit_by( &mut self, host: &mut LanHost, @@ -223,16 +225,47 @@ impl Game<'_> { let (result, pushed) = self.as_guest(host, conn, |g| { let before = g.player.as_ref().map(|p| p.velocity); let result = f(g); - let after = g.player.as_ref().map(|p| p.velocity); - (result, after.filter(|v| Some(*v) != before)) + let pushed = g + .player + .as_ref() + .filter(|p| !p.health.sync_velocity && Some(p.velocity) != before) + .map(|p| p.velocity); + (result, pushed) })?; - if let (Some(v), Some(g)) = (pushed, host.hub.guest(conn)) { + self.send_guest_motion(host, conn, pushed); + Some(result) + } + + /// A player's melee hit on a guest (Player.causeExtraKnockback on a + /// ServerPlayer): a hurt that marked the velocity sends it at once, and + /// the server's copy goes back to the velocity it had before the hit. + pub(super) fn guest_struck_by( + &mut self, + host: &mut LanHost, + conn: u32, + f: impl FnOnce(&mut Self) -> R, + ) -> Option { + let (result, sent) = self.as_guest(host, conn, |g| { + let before = g.player.as_ref().map(|p| p.velocity); + let result = f(g); + let sent = g.player.as_mut().zip(before).and_then(|(p, before)| { + std::mem::take(&mut p.health.sync_velocity) + .then(|| std::mem::replace(&mut p.velocity, before)) + }); + (result, sent) + })?; + self.send_guest_motion(host, conn, sent); + Some(result) + } + + /// ClientboundSetEntityMotionPacket to a guest about themselves. + pub(super) fn send_guest_motion(&self, host: &LanHost, conn: u32, velocity: Option) { + if let (Some(v), Some(g)) = (velocity, host.hub.guest(conn)) { g.send(&C::SetEntityMotion(play::SetEntityMotion { id: g.entity_id, velocity: [v.x, v.y, v.z], })); } - Some(result) } } diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs index d2c643088..74c88895b 100644 --- a/crates/horizon-client/src/game/lan_pvp.rs +++ b/crates/horizon-client/src/game/lan_pvp.rs @@ -240,7 +240,7 @@ impl Game<'_> { && harm && match victim { Victim::Host => land(self), - Victim::Guest(conn) => self.guest_hit_by(host, conn, land).unwrap_or(false), + Victim::Guest(conn) => self.guest_struck_by(host, conn, land).unwrap_or(false), }; let sound = match (hurt, s.crit, s.scale > 0.9) { (false, ..) => "minecraft:entity.player.attack.nodamage", diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 9edbb4f2a..0a626b1e7 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -296,6 +296,10 @@ pub struct PlayerMotion { pub freeze_immune: bool, /// `Entity.oldPosition`: where this tick started. pub old_position: Vec3, + /// The server's copy of a player another client moves (a LAN guest), while + /// it travels on the server: `isLocalInstanceAuthoritative` is false, so + /// its moves check no fall damage. + pub server_copy: bool, /// `Entity.applyEffectsFromBlocks` runs after travel (always in the game; /// differential fixtures turn it off where their reference does). pub block_effects: bool, @@ -460,6 +464,7 @@ impl PlayerMotion { leather_boots: false, freeze_immune: false, old_position: position, + server_copy: false, block_effects: true, powder_snow_entered: Vec::new(), hurt_log: Vec::new(), @@ -467,6 +472,16 @@ impl PlayerMotion { border: None, }) } + /// LivingEntity.aiStep: speeds too small to matter stop. + fn drop_tiny_velocity(&mut self) { + let v = &mut self.velocity; + if v.x * v.x + v.z * v.z < 9.0e-6 { + (v.x, v.z) = (0.0, 0.0); + } + if v.y.abs() < 0.003 { + v.y = 0.0; + } + } /// `Entity.getTicksRequiredToFreeze`. pub const TICKS_REQUIRED_TO_FREEZE: i32 = 140; /// `Entity.getPercentFrozen`. @@ -920,15 +935,7 @@ impl MotionWorld<'_, '_, '_> { if self.player.no_jump_delay > 0 { self.player.no_jump_delay -= 1; } - let mut velocity = self.player.velocity; - if velocity.x * velocity.x + velocity.z * velocity.z < 9.0e-6 { - velocity.x = 0.0; - velocity.z = 0.0; - } - if velocity.y.abs() < 0.003 { - velocity.y = 0.0; - } - self.player.velocity = velocity; + self.player.drop_tiny_velocity(); let mut input = match input { TickInput::Living(v) => Vec3::new( f64::from(v[0] * 0.98), @@ -947,9 +954,38 @@ impl MotionWorld<'_, '_, '_> { } self.jump_phase()?; let before_travel = self.player.bounds(); - // Player.travel: swim steering, then LivingEntity.travel (fluids - // first, then gliding, then air), keeping 0.6 of the vertical speed - // while flying. + self.player_travel(input)?; + if self.player.block_effects { + self.apply_effects_from_blocks()?; + } + // LivingEntity.aiStep "freezing" (server). + if !self.player.in_powder_snow || !self.player.can_freeze() { + self.player.ticks_frozen = (self.player.ticks_frozen - 2).max(0); + } + self.player.remove_frost()?; + let on = self.support(movement_support::LEGACY_SUPPORT_OFFSET)?; + let on_air = self.assets.registry.state(self.block(on)).is_none_or(|s| { + matches!( + s.name.as_str(), + "minecraft:air" | "minecraft:cave_air" | "minecraft:void_air" + ) + }); + self.player.try_add_frost(on_air)?; + if self.player.health.tick_count % 40 == 0 + && self.player.is_fully_frozen() + && self.player.can_freeze() + { + self.freeze_damage()?; + } + if self.player.auto_spin_attack_ticks > 0 { + self.player.auto_spin_attack_ticks -= 1; + self.check_auto_spin_attack(before_travel); + } + Ok(()) + } + /// Player.travel: swim steering, then LivingEntity.travel (fluids first, + /// then gliding, then air), keeping 0.6 of the vertical speed while flying. + fn player_travel(&mut self, input: Vec3) -> Result<()> { if self.player.swimming { let look_y = horizon_world::view_direction::view_vector(self.player.pitch, self.player.yaw).y; @@ -979,34 +1015,29 @@ impl MotionWorld<'_, '_, '_> { if let Some(y) = flying_y { self.player.velocity.y = y * 0.6; } - if self.player.block_effects { - self.apply_effects_from_blocks()?; - } - // LivingEntity.aiStep "freezing" (server). - if !self.player.in_powder_snow || !self.player.can_freeze() { - self.player.ticks_frozen = (self.player.ticks_frozen - 2).max(0); - } - self.player.remove_frost()?; - let on = self.support(movement_support::LEGACY_SUPPORT_OFFSET)?; - let on_air = self.assets.registry.state(self.block(on)).is_none_or(|s| { - matches!( - s.name.as_str(), - "minecraft:air" | "minecraft:cave_air" | "minecraft:void_air" - ) - }); - self.player.try_add_frost(on_air)?; - if self.player.health.tick_count % 40 == 0 - && self.player.is_fully_frozen() - && self.player.can_freeze() - { - self.freeze_damage()?; - } - if self.player.auto_spin_attack_ticks > 0 { - self.player.auto_spin_attack_ticks -= 1; - self.check_auto_spin_attack(before_travel); - } Ok(()) } + /// ServerPlayer's own travel: the server simulates a player too + /// (`MoveSimulationType.AUTHORITATIVE_SIDE_AND_SERVER`), with no input + /// (it never sets xxa/zza). Only the delta movement it leaves stays: it + /// is what a hurt sends the player (`ServerEntity.sendChanges`), and + /// what the next knockback starts from; the client's next move places + /// the player. + pub fn server_travel(&mut self) -> Result<()> { + let p = &mut *self.player; + let (position, ground, collision) = (p.position, p.ground, p.collision); + let (history, fall_distance, steps) = (p.history.clone(), p.fall_distance, p.steps); + let events = p.events.len(); + p.drop_tiny_velocity(); + p.server_copy = true; + let travelled = self.player_travel(Vec3::ZERO); + let p = &mut *self.player; + p.server_copy = false; + (p.position, p.ground, p.collision) = (position, ground, collision); + (p.history, p.fall_distance, p.steps) = (history, fall_distance, steps); + p.events.truncate(events); + travelled + } /// `LivingEntity.checkAutoSpinAttack`: the first living entity in the /// box swept this tick takes the hit and ends the spin, bouncing the /// player back at a fifth of its speed; a wall ends it too. @@ -1678,7 +1709,7 @@ impl EntityMoveWorld for MotionWorld<'_, '_, '_> { &mut self.player.history } fn locally_authoritative(&mut self) -> Result { - Ok(true) + Ok(!self.player.server_copy) } fn set_on_ground_with_movement( &mut self, @@ -2327,6 +2358,64 @@ mod tests { assert_eq!(player.position.y, 4.0); } + #[test] + fn server_travel_moves_only_the_velocity() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("movement-properties.nbt").exists() { + return; + } + let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); + let binding = crate::collisions::load(&root, assets.registry).unwrap(); + let resources = MotionResources::load(&root, &assets).unwrap(); + let mut scene = World::test_scene(&assets, &render, 1).unwrap(); + let at = Vec3::new(20.5, 4.0, 20.5); + let mut player = PlayerMotion::new(&resources, at).unwrap(); + let mut travel = |player: &mut PlayerMotion| { + MotionWorld { + entities: &[], + player, + scene: &mut scene, + assets: &assets, + collision_binding: &binding, + resources: &resources, + } + .server_travel() + .unwrap() + }; + // A knockback on the ground (vanilla's server sends 0.21840 0.27516 + // after a zombie's hit): ground friction, then gravity and drag. + player.ground.on_ground = true; + player.velocity = Vec3::new(-0.4, 0.3608, 0.0); + travel(&mut player); + assert!( + (player.velocity.x + 0.2184).abs() < 1e-6, + "{:?}", + player.velocity + ); + assert!( + (player.velocity.y - 0.275184).abs() < 1e-6, + "{:?}", + player.velocity + ); + assert_eq!(player.position, at); + assert!(player.ground.on_ground); + // Falling onto the ground hurts no one on the server's copy, and leaves + // the fall to the client's moves. + let health = player.health.health(); + player.position = Vec3::new(20.5, 4.5, 20.5); + player.ground.on_ground = false; + player.fall_distance = 10.0; + player.velocity = Vec3::new(0.0, -1.0, 0.0); + travel(&mut player); + assert_eq!(player.velocity.y, -0.0784000015258789); + assert_eq!(player.health.health(), health); + assert_eq!(player.fall_distance, 10.0); + assert!(player.events.is_empty()); + } + #[test] fn spectator_scroll_speed_controls_horizontal_and_vertical_flight() { let root = Path::new(env!("CARGO_MANIFEST_DIR")) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index f44a84ea8..bb527c467 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -222,6 +222,9 @@ address. The script then checks, from both sides, what a guest's game used to ge spider's bite poisons them (#1480, #1484). - cursor: the host and the guest each close their inventory with a stack on the cursor: it goes back into their inventory, none is thrown and the cursor is empty (#1283). +- knockback: the host hits the guest three times, then the guest the host, two seconds apart: each + hit slides the victim as far as vanilla's does, 1.989 blocks (a guest's server-side + velocity settles between hits; it used to add up, so each push went further). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -5293,5 +5296,49 @@ CHECKS += ['digging'] CHECK_FNS.update(digging=check_digging) +# How far a plain wooden sword hit slides a standing player in vanilla: LivingEntity.knockback(0.4) from +# the server copy's (0, -0.0784, 0), then the victim's own client. +VANILLA_PUSH = 1.989 + + +def check_knockback(host, guest, out): + if dead(guest): + guest.raw('respawn') + guest.wait(40) + host('command', command='gamerule pvp true') + for g in (host, guest): + g('command', command='gamemode survival') + g('command', command='item replace entity @s weapon.mainhand with minecraft:wooden_sword') + g('command', command='effect give @s minecraft:resistance 1000 4 true') + face_each_other(host, guest) + pushes = {} + try: + for name, attacker, victim in (('host hits guest', host, guest), ('guest hits host', guest, host)): + # The victim is never teleported (a teleport resets its velocity): the attacker steps up to it from + # the west, then the east, then the west again. + for side in (-3, 3, -3): + vx, vy, vz = pos_of(victim) + attacker('command', command=f'tp @s {vx + side:.2f} {vy:.2f} {vz:.2f}') + attacker.wait(40) # a full charge, and the last push long settled + attacker.raw('look-at', f'{vx:.2f}', f'{vy + 1.6:.2f}', f'{vz:.2f}') + attacker.wait(5) + before = pos_of(victim) + attacker.raw('attack') + victim.wait(30) + after = pos_of(victim) + pushes.setdefault(name, []).append(round(math.dist(before[0::2], after[0::2]), 3)) + attacker.shot(out, 'knockback-' + name.replace(' ', '-')) + finally: + for g in (host, guest): + g('command', command='effect clear @s minecraft:resistance') + for name, distances in pushes.items(): + assert all(abs(d - VANILLA_PUSH) < 0.03 for d in distances), f'{name}: not {VANILLA_PUSH} each time: {pushes}' + return pushes + + +CHECKS += ['knockback'] +CHECK_FNS.update(knockback=check_knockback) + + if __name__ == '__main__': main() diff --git a/tools/test_server_knockback_parity.py b/tools/test_server_knockback_parity.py index cd061321d..547e803a2 100644 --- a/tools/test_server_knockback_parity.py +++ b/tools/test_server_knockback_parity.py @@ -56,8 +56,6 @@ PROPERTIES = { 'pause-when-empty-seconds': '-1', } # Cases Horizon still gets wrong, and why. -VELOCITY = ("a guest's server-side velocity never travels and a hit is sent before it would: each knockback starts " - "from the last one's (ServerPlayer's travel, ServerEntity.sendChanges, Player.causeExtraKnockback)") SPRINT = "the server never sends a guest its own sprint flag, so a sprint hit doesn't stop the attacker's sprint" YAW = "the extra knockback's direction comes from f32 sin/cos, not Mth's sine table (z is -2e-8 a block, not 0)" KNOWN = { @@ -65,16 +63,9 @@ KNOWN = { 'cow-knockback-2': YAW, 'zombie-sprint': f'{SPRINT}; {YAW}', 'zombie-knockback-2': YAW, - 'pvp-plain': VELOCITY, - 'pvp-sprint': f'{VELOCITY}; {SPRINT}', - 'pvp-knockback-2': VELOCITY, - 'pvp-crit': VELOCITY, - 'pvp-netherite': VELOCITY, - 'pvp-twice': VELOCITY, - 'pvp-sprint-twice': f'{VELOCITY}; {SPRINT}', - 'pvp-mace': f'{VELOCITY}; a smash on a player runs none of MaceItem.hurtEnemy (the attacker\'s fall goes on)', - 'pvp-cooldown': f'{VELOCITY}; a hit inside the hurt cooldown still knocks back (LivingEntity.hurtServer)', - 'zombie-hits-bob': VELOCITY, + 'pvp-sprint': SPRINT, + 'pvp-sprint-twice': SPRINT, + 'pvp-mace': "a smash on a player runs none of MaceItem.hurtEnemy (the attacker's fall goes on)", } A = (0.5, -60.0, 0.5) # Alice, facing east (yaw -90) From c33acfdd058069f7eb256604445cafe2e07dca68 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 11:13:27 +0200 Subject: [PATCH 094/408] Stop a guest's sprint when its hit knocks back Player.causeExtraKnockback stops the attacker's sprint on the server, and the shared flag reaches the attacker's own client (ServerEntity sends a player its own dirty entity data). A guest's sprint was only stopped on the server copy for the length of the hit and never sent, so a guest (and, on the server thread, the window) kept sprinting: every hit while sprinting had the sprint knockback, where vanilla's needs the sprint to start again. - leave_guest keeps the sprint stop a guest's hit made; a guest hitting a player stops its sprint too. - The hub sends each guest its own shared flags (crouching, sprinting, gliding) when they change. - A remote client takes the sprinting bit of its own shared flags (the flag only, as vanilla's assignValues: the speed modifier and the wasSprinting it compares stay, so it sends START_SPRINTING again only after it has stopped). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/lan_actions.rs | 12 +++++- crates/horizon-client/src/game/lan_pvp.rs | 10 ++++- crates/horizon-client/src/game/remote.rs | 9 +++++ crates/horizon-client/src/lan/guest.rs | 4 ++ crates/horizon-client/src/lan/hub.rs | 39 ++++++++++++++----- tools/test_server_knockback_parity.py | 7 +--- 6 files changed, 63 insertions(+), 18 deletions(-) diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index d42ffc511..500c22097 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -595,6 +595,11 @@ impl Game<'_> { // A teleport (commands, a pearl) moves the guest; a pearl's is // sent even to where they stand (ServerPlayer.teleport). let at = [m.position.x, m.position.y, m.position.z]; + // A hit with extra knockback stopped the guest's sprint + // (Player.causeExtraKnockback's setSprinting(false)). + if !m.sprinting { + g.sprinting = false; + } m.sprinting = false; let teleported = std::mem::take(&mut m.teleported); let moved: f64 = (0..3).map(|k| (at[k] - g.position[k]).powi(2)).sum(); @@ -1322,8 +1327,11 @@ impl Game<'_> { return; } if let Some(victim) = Self::pvp_victim(host, conn, id) { - if let Some(Some(strike)) = self.as_guest(host, conn, |g| g.pvp_strike()) { - self.pvp_land(host, victim, &strike); + if let Some(Some(strike)) = self.as_guest(host, conn, |g| g.pvp_strike()) + && self.pvp_land(host, victim, &strike) + && strike.stops_sprint() + { + self.as_guest(host, conn, |g| g.stop_sprint_after_extra_knockback()); } return; } diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs index 74c88895b..467c4537c 100644 --- a/crates/horizon-client/src/game/lan_pvp.rs +++ b/crates/horizon-client/src/game/lan_pvp.rs @@ -45,6 +45,14 @@ pub(super) struct Strike { team: Option, } +impl Strike { + /// Whether it has extra knockback, which stops the attacker's sprint + /// once it lands (Player.causeExtraKnockback). + pub(super) fn stops_sprint(&self) -> bool { + self.knockback.0 > 0.0 + } +} + impl Game<'_> { /// The guest on the host's crosshair and how far, within reach. pub(super) fn guest_hit(&self) -> Option<(u32, f64)> { @@ -74,7 +82,7 @@ impl Game<'_> { }; if let Some(strike) = self.pvp_strike() && self.pvp_land(&mut host, Victim::Guest(conn), &strike) - && strike.knockback.0 > 0.0 + && strike.stops_sprint() { self.stop_sprint_after_extra_knockback(); } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index d831d92f8..df0da4bac 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1990,6 +1990,15 @@ impl Game<'_> { } self.sleeping = *bed; } + // Entity.DATA_SHARED_FLAGS_ID's sprinting bit: the + // server stops the sprint after a hit's extra + // knockback (the flag only, as assignValues sets + // it: the speed modifier and wasSprinting stay). + (0, Value::Byte(flags)) => { + if let Some(pl) = self.player.as_mut() { + pl.sprinting = flags & 0x08 != 0; + } + } // Entity.DATA_AIR_SUPPLY_ID and // Player.DATA_PLAYER_ABSORPTION_ID: the bubbles // and golden hearts the server's player has. diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 7d1b10eaa..256f3a5cf 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -206,6 +206,9 @@ pub struct Guest { /// (Entity.DATA_AIR_SUPPLY_ID, Player.DATA_PLAYER_ABSORPTION_ID); their /// defaults until either changes. pub sent_air: (i32, f32), + /// The shared flags (Entity.DATA_SHARED_FLAGS_ID) the player's client was + /// last sent about itself. + pub sent_shared: i8, /// Where the player last died (Player.lastDeathLocation), sent with the respawn. pub last_death: Option<[i32; 3]>, /// The last action sequence to acknowledge at the next tick (-1: none). @@ -336,6 +339,7 @@ impl Guest { sent_health: None, sent_xp: None, sent_air: (300, 0.0), + sent_shared: 0, last_death: None, ack_up_to: std::cell::Cell::new(-1), sent_selected: 0, diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 406f2f872..4f93b6ff9 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -1477,16 +1477,7 @@ impl Hub { attributes: Vec, ) -> EntityState { let (sneaking, sprinting, gliding, sleeping) = flags; - let mut shared = 0i8; - if sneaking { - shared |= 0x02; - } - if sprinting { - shared |= 0x08; - } - if gliding { - shared |= -128; - } + let shared = shared_flags(sneaking, sprinting, gliding); let pose = if sleeping { 2 } else if gliding { @@ -1764,6 +1755,18 @@ impl Hub { })); } } + // ServerEntity.sendDirtyEntityData: the shared flags go to the player + // too, so the sprint a hit stops (Player.causeExtraKnockback) stops + // on its client. + let g = &mut self.guests[i]; + let shared = shared_flags(g.sneaking, g.sprinting, g.fall_flying); + if shared != g.sent_shared { + g.sent_shared = shared; + g.send(&C::SetEntityData(play::SetEntityData { + id: g.entity_id, + values: vec![(0, serializer::BYTE, Value::Byte(shared))], + })); + } // Sent when the health or the food level changes, or the saturation // reaches or leaves zero; a dead player's health of 0 too. let g = &mut self.guests[i]; @@ -2480,6 +2483,7 @@ impl Hub { g.sent_health = None; g.sent_xp = None; g.sent_air = (300, 0.0); + g.sent_shared = 0; let (cx, cz) = g.chunk(); g.send(&C::SetChunkCacheCenter(play::SetChunkCacheCenter { x: cx, @@ -2519,6 +2523,21 @@ fn ticking_state(rate: f32, frozen: bool) -> C { raw(ids::TICKING_STATE, w.data) } +/// Entity.DATA_SHARED_FLAGS_ID of a player: crouching, sprinting, gliding. +fn shared_flags(sneaking: bool, sprinting: bool, gliding: bool) -> i8 { + let mut shared = 0i8; + if sneaking { + shared |= 0x02; + } + if sprinting { + shared |= 0x08; + } + if gliding { + shared |= -128; + } + shared +} + #[cfg(test)] mod tests { use super::*; diff --git a/tools/test_server_knockback_parity.py b/tools/test_server_knockback_parity.py index 547e803a2..c6c634c0f 100644 --- a/tools/test_server_knockback_parity.py +++ b/tools/test_server_knockback_parity.py @@ -56,15 +56,12 @@ PROPERTIES = { 'pause-when-empty-seconds': '-1', } # Cases Horizon still gets wrong, and why. -SPRINT = "the server never sends a guest its own sprint flag, so a sprint hit doesn't stop the attacker's sprint" YAW = "the extra knockback's direction comes from f32 sin/cos, not Mth's sine table (z is -2e-8 a block, not 0)" KNOWN = { - 'cow-sprint': f'{SPRINT}; {YAW}', + 'cow-sprint': YAW, 'cow-knockback-2': YAW, - 'zombie-sprint': f'{SPRINT}; {YAW}', + 'zombie-sprint': YAW, 'zombie-knockback-2': YAW, - 'pvp-sprint': SPRINT, - 'pvp-sprint-twice': SPRINT, 'pvp-mace': "a smash on a player runs none of MaceItem.hurtEnemy (the attacker's fall goes on)", } From 6a5c749f7cfebcb800dd17c0c2cffb01fcc9d7cd Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 11:13:27 +0200 Subject: [PATCH 095/408] Aim extra knockback with Mth's sine table Player.causeExtraKnockback pushes along Mth.sin/Mth.cos of the attacker's yaw, which come from vanilla's 65536-entry table: facing east, the push has no z at all. Horizon took f32 sin/cos, which left -4.4e-8 of z per block of push (a sprinting or Knockback hit, on mobs and players). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/enchant_effects.rs | 10 ++++++---- tools/test_server_knockback_parity.py | 5 ----- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs index 8593e2b98..aa9f75e06 100644 --- a/crates/horizon-client/src/game/enchant_effects.rs +++ b/crates/horizon-client/src/game/enchant_effects.rs @@ -121,11 +121,13 @@ impl Game<'_> { let bonus = if knockback_attack { 0.5 } else { 0.0 }; (enchanted / 2.0 + bonus, knockback_attack) } - /// `causeExtraKnockback`'s direction, `(sin yRot, -cos yRot)`: the target - /// flies where the attacker looks, not away from it. + /// `causeExtraKnockback`'s direction, `(sin yRot, -cos yRot)` from Mth's + /// sine table: the target flies where the attacker looks, not away from + /// it (straight along an axis when the attacker faces one). pub(super) fn extra_knockback_direction(&self) -> (f64, f64) { - let yaw = self.yaw.to_radians(); - (f64::from(yaw.sin()), -f64::from(yaw.cos())) + use horizon_core::geometry::trig; + let yaw = f64::from(self.yaw * trig::DEG_TO_RAD); + (f64::from(trig::sin(yaw)), -f64::from(trig::cos(yaw))) } /// The attacker's side of `causeExtraKnockback` as the attacking client /// sees it: the server's player stops sprinting, and its flag reaches the diff --git a/tools/test_server_knockback_parity.py b/tools/test_server_knockback_parity.py index c6c634c0f..d7fbaeba1 100644 --- a/tools/test_server_knockback_parity.py +++ b/tools/test_server_knockback_parity.py @@ -56,12 +56,7 @@ PROPERTIES = { 'pause-when-empty-seconds': '-1', } # Cases Horizon still gets wrong, and why. -YAW = "the extra knockback's direction comes from f32 sin/cos, not Mth's sine table (z is -2e-8 a block, not 0)" KNOWN = { - 'cow-sprint': YAW, - 'cow-knockback-2': YAW, - 'zombie-sprint': YAW, - 'zombie-knockback-2': YAW, 'pvp-mace': "a smash on a player runs none of MaceItem.hurtEnemy (the attacker's fall goes on)", } From 9624e998010c6a32da5d069d1df1c238ea82d312 Mon Sep 17 00:00:00 2001 From: levzzz <86072227+levzzz5154@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:56:11 +0500 Subject: [PATCH 096/408] Clear a creative player's dig after the block breaks on the server A creative START destroys the block at once and its client never sends STOP, so the kept dig broke whatever was placed in that cell next, every destroy delay, until the player broke something else. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/lan_actions.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 7fd969a9b..ed40b8e57 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1705,6 +1705,17 @@ impl Game<'_> { g.use_delay -= 1; } }); + // ServerPlayerGameMode.handleBlockBreakAction: a creative + // player's START breaks the block once (destroyAndAck) and + // leaves nothing being destroyed; its client sends no STOP. + // Kept, the dig broke whatever was put there next, every + // destroy delay, for as long as the player broke nothing else. + if digging.is_some() + && host.hub.guests[gi].creative() + && let Some(play) = host.play.get_mut(&conn) + { + play.digging = None; + } } // Player.tick: a different main-hand item resets the attack // strength, and detectEquipmentUpdates gives the guest its modifiers. From ebd25abd0eada5a4ae9cf3c174c3502d069979a3 Mon Sep 17 00:00:00 2001 From: levzzz <86072227+levzzz5154@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:56:11 +0500 Subject: [PATCH 097/408] Run horizon-ctl block commands in the server's world With the integrated server thread on, setblock, fill, getblock and container ran on the client's copy only. They now run on the server, and on a remote server setblock and fill go out as chat commands. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/blockctl.rs | 24 ++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/crates/horizon-client/src/game/blockctl.rs b/crates/horizon-client/src/game/blockctl.rs index 719ce8dd2..8e0ea287e 100644 --- a/crates/horizon-client/src/game/blockctl.rs +++ b/crates/horizon-client/src/game/blockctl.rs @@ -59,6 +59,30 @@ impl Game<'_> { } /// Block commands; None when `words[0]` is not one of them. pub(super) fn block_command(&mut self, words: &[&str]) -> Result> { + let ours = matches!( + words.first(), + Some(&("setblock" | "fill" | "getblock" | "container")) + ); + // Single player on its server thread: the world is the server's, so + // the command runs there and the client hears of it like any change. + if ours && let Some(server) = &self.integrated { + let owned: Vec = words.iter().map(|w| (*w).to_owned()).collect(); + return server + .call(move |g| { + let words: Vec<&str> = owned.iter().map(String::as_str).collect(); + g.block_command(&words).map_err(|e| e.to_string()) + }) + .ok_or("the integrated server stopped")? + .map_err(Into::into); + } + // Another server's world changes only through its commands. + if ours && self.remote.is_some() { + if !matches!(words[0], "setblock" | "fill") { + return Err(format!("{} needs a world on this machine", words[0]).into()); + } + self.send_chat(&format!("/{}", words.join(" "))); + return Ok(Some(json!({ "ok": true, "sent": true }))); + } let int = |i: usize| -> Result { Ok(words .get(i) From e2dd6b67df6f5ba03393e56f2f1e66fd88dc6613 Mon Sep 17 00:00:00 2001 From: levzzz <86072227+levzzz5154@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:56:12 +0500 Subject: [PATCH 098/408] Make boats solid to players Boats join happy ghasts in the player's entity collision list, so a player can't walk through a boat and steps up onto it. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 4 ++-- crates/horizon-client/src/game/consume.rs | 2 +- crates/horizon-client/src/game/ghasts.rs | 13 ++++++++++--- crates/horizon-client/src/game/remote.rs | 4 ++-- 4 files changed, 15 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index fe3f43401..93064d0fe 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4102,7 +4102,7 @@ impl Game<'_> { self.tick_riding(keys)?; } let riding = self.riding.is_some(); - let ghast_collisions = self.happy_ghast_player_collisions(); + let entity_collisions = self.player_entity_collisions(); let spin_targets = self.spin_targets(); self.sync_player_body(); let Some(player) = self.player.as_mut() else { @@ -4149,7 +4149,7 @@ impl Game<'_> { ); if !riding { MotionWorld { - entities: &ghast_collisions, + entities: &entity_collisions, player, scene: &mut self.world, assets: &self.pack.assets, diff --git a/crates/horizon-client/src/game/consume.rs b/crates/horizon-client/src/game/consume.rs index 50b1fa814..93d919911 100644 --- a/crates/horizon-client/src/game/consume.rs +++ b/crates/horizon-client/src/game/consume.rs @@ -128,7 +128,7 @@ impl Game<'_> { if self.state_in_tag(avoid, ground) { return false; } - let entities = self.happy_ghast_player_collisions(); + let entities = self.player_entity_collisions(); let Some(player) = self.player.as_mut() else { return false; }; diff --git a/crates/horizon-client/src/game/ghasts.rs b/crates/horizon-client/src/game/ghasts.rs index 8ce0a4231..48cbffa6b 100644 --- a/crates/horizon-client/src/game/ghasts.rs +++ b/crates/horizon-client/src/game/ghasts.rs @@ -10,9 +10,10 @@ use horizon_core::geometry::{Aabb, Vec3}; use horizon_world::registry::BlockStateId; impl Game<'_> { - /// Client `EntityGetter.getEntityCollisions`: only solid happy ghasts, - /// excluding the player's own vehicle. - pub(super) fn happy_ghast_player_collisions(&self) -> Vec { + /// Client `EntityGetter.getEntityCollisions` for the player: the + /// entities that `canBeCollidedWith` it, solid happy ghasts and boats + /// (`AbstractBoat.canBeCollidedWith`), except the player's own vehicle. + pub(super) fn player_entity_collisions(&self) -> Vec { let Some(p) = &self.player else { return Vec::new(); }; @@ -24,6 +25,12 @@ impl Game<'_> { && happy_ghast::collides_with_player(m, p.position.y) }) .map(|m| m.bounds()) + .chain( + self.boats + .iter() + .filter(|b| Some(b.id) != self.riding) + .map(super::boats::Boat::bounds), + ) .collect() } /// `HappyGhast.mobInteract`. Returns whether the click was used. diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index d831d92f8..77cb40d11 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3072,7 +3072,7 @@ impl Game<'_> { self.sleep_timer = super::tick_sleep_timer(self.sleep_timer, self.sleeping.is_some()); // Gui.tick: the titles, the action bar and the held item's name. self.tick_hud(); - let ghast_collisions = self.happy_ghast_player_collisions(); + let entity_collisions = self.player_entity_collisions(); let pushed = self.remote_pushes(); let Some(player) = self.player.as_mut() else { return Ok(()); @@ -3156,7 +3156,7 @@ impl Game<'_> { } else if !dead && !riding { player.velocity = player.velocity.add_vector(pushed); MotionWorld { - entities: &ghast_collisions, + entities: &entity_collisions, player, scene: &mut self.world, assets: &self.pack.assets, From 826cf8ffe6c90abfe7b4b3c4527f27d9127f7ea5 Mon Sep 17 00:00:00 2001 From: levzzz <86072227+levzzz5154@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:56:12 +0500 Subject: [PATCH 099/408] Burn boats and minecarts in lava, and place boats on lava Vehicles take lava damage and keep burning for 15 seconds like vanilla (lavaHurt, remainingFireTicks), breaking and dropping their items; a TNT minecart primes from fire. Boat placement stops at lava as well as water. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/boats.rs | 113 ++++++++++++++++++-- crates/horizon-client/src/game/minecarts.rs | 47 ++++++++ 2 files changed, 149 insertions(+), 11 deletions(-) diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs index 6b24226d9..402582bf2 100644 --- a/crates/horizon-client/src/game/boats.rs +++ b/crates/horizon-client/src/game/boats.rs @@ -43,6 +43,8 @@ pub(super) struct Boat { pub hurt_time: i32, pub hurt_dir: i32, pub damage: f32, + /// `Entity.remainingFireTicks`: lava sets a boat alight for 15 seconds. + pub fire_ticks: i32, pub paddles: [f32; 2], pub paddling: [bool; 2], /// left, right, up, down @@ -77,6 +79,7 @@ impl Boat { hurt_time: 0, hurt_dir: 1, damage: 0.0, + fire_ticks: 0, paddles: [0.0; 2], paddling: [false; 2], input: [false; 4], @@ -183,13 +186,18 @@ impl BoatModels { } impl Game<'_> { fn fluid_height(&self, x: i32, y: i32, z: i32) -> Option<(f32, bool)> { + self.fluid_height_of(x, y, z, false) + } + /// `FluidState.getHeight` and whether it is a source; water only, + /// unless `lava` too (`ClipContext.Fluid.ANY`). + fn fluid_height_of(&self, x: i32, y: i32, z: i32, lava: bool) -> Option<(f32, bool)> { let f = self.res.facts().get(self.world.block(x, y, z)); - if f.fluid != Fluid::Water { + if f.fluid != Fluid::Water && !(lava && f.fluid == Fluid::Lava) { return None; } let above = self.res.facts().get(self.world.block(x, y + 1, z)); // FluidState.getHeight: 1 under the same fluid, else amount / 9. - let height = if above.fluid == Fluid::Water { + let height = if above.fluid == f.fluid { 1.0 } else { f32::from(f.fluid_level) / 9.0 @@ -461,6 +469,78 @@ impl Game<'_> { let b = self.boats[i].clone(); self.boats[i] = self.tick_boat(b, false); } + // applyEffectsFromBlocks runs on the server for every boat, the + // client-driven ones too; a boat lava destroys leaves the list. + let mut i = 0; + while i < self.boats.len() { + let p = self.boats[i].position; + let skip = Some(self.boats[i].id) == self.riding + || !ticking(p.x.floor() as i32, p.z.floor() as i32); + if skip || !self.boat_fire_tick(i) { + i += 1; + } + } + } + /// The fire half of `Entity.baseTick` and `LavaFluid.entityInside` + /// (`lavaIgnite`, then `lavaHurt`) after the boat moved. True when the + /// boat was destroyed and removed. + fn boat_fire_tick(&mut self, i: usize) -> bool { + let (lava, water) = self.hull_fluids(self.boats[i].bounds()); + let b = &mut self.boats[i]; + if water { + b.fire_ticks = 0; + } + let mut burn = 0.0; + if b.fire_ticks > 0 { + if b.fire_ticks % 20 == 0 && !lava { + burn = 1.0; + } + b.fire_ticks -= 1; + } + if burn > 0.0 && self.hurt_boat(i, burn, false) { + return true; + } + if !lava { + return false; + } + let b = &mut self.boats[i]; + b.fire_ticks = b.fire_ticks.max(300); + let at = [b.position.x, b.position.y, b.position.z]; + let pitch = 2.0 + self.world.random.next_float() * 0.4; + self.audio + .play("minecraft:entity.generic.burn", Some(at), 0.4, pitch); + self.hurt_boat(i, 4.0, false) + } + /// Whether a vehicle's box (deflated by 1e-5, as `applyEffectsFromBlocks`) + /// is inside lava, and whether it touches water. + pub(super) fn hull_fluids(&self, bb: Aabb) -> (bool, bool) { + let (lo, hi) = (bb.min_position(), bb.max_position()); + let e = 1.0e-5; + let (mut lava, mut water) = (false, false); + for x in (lo.x + e).floor() as i32..=(hi.x - e).floor() as i32 { + for y in (lo.y + e).floor() as i32..=(hi.y - e).floor() as i32 { + for z in (lo.z + e).floor() as i32..=(hi.z - e).floor() as i32 { + let f = self.res.facts().get(self.world.block(x, y, z)); + if f.fluid == Fluid::None { + continue; + } + let above = self.res.facts().get(self.world.block(x, y + 1, z)); + let height = if above.fluid == f.fluid { + 1.0 + } else { + f64::from(f.fluid_level) / 9.0 + }; + if lo.y + e < f64::from(y) + height { + match f.fluid { + Fluid::Lava => lava = true, + Fluid::Water => water = true, + _ => {} + } + } + } + } + } + (lava, water) } /// The player's tick while riding: steer, tick the boat, sit in it. pub(super) fn tick_riding(&mut self, keys: Keys) -> horizon_client::Result<()> { @@ -489,6 +569,9 @@ impl Game<'_> { p.fall_distance = 0.0; } self.boats[i] = b; + if self.boat_fire_tick(i) { + self.riding = None; + } Ok(()) } /// `getDismountLocationForPassenger`: in front of the player if there is @@ -534,7 +617,8 @@ impl Game<'_> { }; let dir = view_vector(self.yaw, self.pitch); let reach = self.reach(); - // ClipContext.Fluid.ANY: the first water surface or block along the ray. + // ClipContext.Fluid.ANY: the first fluid surface (water or lava) or + // block along the ray. let block = self.pick().map(|h| { ( h.point, @@ -544,7 +628,7 @@ impl Game<'_> { .sqrt(), ) }); - let mut water = None; + let mut fluid = None; let mut t = 0.0; while t < reach { let p: [f64; 3] = std::array::from_fn(|a| eye[a] + dir[a] * t); @@ -553,15 +637,15 @@ impl Game<'_> { p[1].floor() as i32, p[2].floor() as i32, ); - if let Some((h, _)) = self.fluid_height(x, y, z) + if let Some((h, _)) = self.fluid_height_of(x, y, z, true) && p[1] <= f64::from(y) + f64::from(h) { - water = Some(([p[0], f64::from(y) + f64::from(h), p[2]], t)); + fluid = Some(([p[0], f64::from(y) + f64::from(h), p[2]], t)); break; } t += 0.05; } - let hit = match (block, water) { + let hit = match (block, fluid) { (Some(b), Some(w)) => { if w.1 < b.1 { w.0 @@ -682,15 +766,23 @@ impl Game<'_> { return false; } self.vehicle_attack_sounds(); + self.hurt_boat(i, damage, self.creative); + self.swing_arm(); + true + } + /// `VehicleEntity.hurtServer`: wobble, add the damage and break past 40 + /// (`creative`: a creative player's hit removes it without drops). + /// True when the boat was removed. + pub(super) fn hurt_boat(&mut self, i: usize, damage: f32, creative: bool) -> bool { let b = &mut self.boats[i]; b.hurt_dir = -b.hurt_dir; b.hurt_time = 10; b.damage += damage * 10.0; - let destroyed = self.creative || b.damage > 40.0; + let destroyed = creative || b.damage > 40.0; if destroyed { let b = self.boats.remove(i); let at = [b.position.x, b.position.y, b.position.z]; - if !self.creative && self.ui.rules.bool("entity_drops") { + if !creative && self.ui.rules.bool("entity_drops") { // ChestBoat.destroy: chestVehicleDestroyed spills the contents. for stack in b.items.iter().flatten() { self.spawn_item(stack.clone(), at, super::dispenser::new_item_motion(), 10); @@ -709,8 +801,7 @@ impl Game<'_> { ); } } - self.swing_arm(); - true + destroyed } /// AbstractBoatRenderer. pub(super) fn boat_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 9173139aa..32a90d41c 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -79,6 +79,8 @@ pub(super) struct Minecart { pub hurt_time: i32, pub hurt_dir: i32, pub damage: f32, + /// `Entity.remainingFireTicks`: lava sets a cart alight for 15 seconds. + pub fire_ticks: i32, pub items: Vec>, /// Furnace minecarts: fuel ticks and the push direction. pub fuel: i32, @@ -177,6 +179,7 @@ impl Minecart { hurt_time: 0, hurt_dir: 1, damage: 0.0, + fire_ticks: 0, items: vec![None; kind.slots()], fuel: 0, push: [0.0; 2], @@ -823,6 +826,50 @@ impl Game<'_> { self.carts.remove(i); } } + // applyEffectsFromBlocks runs on the server for every cart, the + // ridden ones too. + let ids: Vec = self.carts.iter().map(|c| c.id).collect(); + for id in ids { + if let Some(i) = self.carts.iter().position(|c| c.id == id) { + let p = self.carts[i].position; + if ticking(p.x.floor() as i32, p.z.floor() as i32) { + self.cart_fire_tick(i); + } + } + } + } + /// The fire half of `Entity.baseTick` and `LavaFluid.entityInside` + /// (`lavaIgnite`, then `lavaHurt`) for one cart, through + /// `VehicleEntity.hurtServer`: lava breaks a cart on its second tick in + /// it, and primes a TNT minecart (`damageSourceIgnitesTnt`). + fn cart_fire_tick(&mut self, i: usize) { + let (lava, water) = self.hull_fluids(self.carts[i].bounds()); + let id = self.carts[i].id; + let c = &mut self.carts[i]; + if water { + c.fire_ticks = 0; + } + let mut burn = false; + if c.fire_ticks > 0 { + burn = c.fire_ticks % 20 == 0 && !lava; + c.fire_ticks -= 1; + } + if burn { + self.hurt_cart(i, 1.0, false, true); + } + if !lava { + return; + } + let Some(i) = self.carts.iter().position(|c| c.id == id) else { + return; + }; + let c = &mut self.carts[i]; + c.fire_ticks = c.fire_ticks.max(300); + let at = [c.position.x, c.position.y, c.position.z]; + let pitch = 2.0 + self.world.random.next_float() * 0.4; + self.audio + .play("minecraft:entity.generic.burn", Some(at), 0.4, pitch); + self.hurt_cart(i, 4.0, false, true); } /// `ClientPacketListener.postAddEntitySoundInstance` for the carts that /// joined the level since the last tick, and `LocalPlayer.startRiding`'s From f688726b347757ddaf2fdde4a8407d641de579cc Mon Sep 17 00:00:00 2001 From: levzzz <86072227+levzzz5154@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:56:12 +0500 Subject: [PATCH 100/408] Let server players push minecarts, without pushing the player back Guests on the server thread (and LAN) now push carts with vanilla's push math. The push back on the player is dropped in both modes: vanilla only syncs it to other players, so the pusher's own client never feels it. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/minecarts.rs | 62 +++++++++++++-------- 1 file changed, 39 insertions(+), 23 deletions(-) diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 32a90d41c..47e71bfd2 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -690,39 +690,55 @@ impl Game<'_> { } } /// `AbstractMinecart.push(player)` when the player walks into a cart. + /// `AbstractMinecart.push` from each player walking into a cart + /// (`LivingEntity.pushEntities`): the window's player and every server + /// player (single player's own on its server thread, LAN guests). A + /// player in a vehicle pushes nothing here. The quarter push the player + /// gets back only moves the server's copy of it (`Entity.push` marks + /// `needsSync`, which `ServerEntity` sends to the other players only), + /// so no player feels it. fn push_carts(&mut self) { - let player = self.player.as_ref().map(|p| p.position); - let riding = self.riding; - for i in 0..self.carts.len() { - if Some(self.carts[i].id) == riding { - continue; + // (feet, height) + let mut pushers: Vec<(Vec3, f64)> = Vec::new(); + if self.riding.is_none() + && let Some(p) = self.player.as_ref() + { + pushers.push((p.position, 1.8)); + } + if let Some(host) = self.lan.as_ref() { + for g in host.hub.guests.iter().filter(|g| { + host.hub.here(g) && g.loaded && !g.dead && !g.spectator() && g.vehicle.is_none() + }) { + let [x, y, z] = g.position; + let height = if g.sneaking { 1.5 } else { 1.8 }; + pushers.push((Vec3::new(x, y, z), height)); } - if let Some(pp) = player { + } + for (pp, height) in pushers { + for i in 0..self.carts.len() { let bb = self.carts[i].bounds(); let (lo, hi) = (bb.min_position(), bb.max_position()); let touching = pp.x + 0.3 > lo.x && pp.x - 0.3 < hi.x && pp.z + 0.3 > lo.z && pp.z - 0.3 < hi.z - && pp.y + 1.8 > lo.y + && pp.y + height > lo.y && pp.y < hi.y; - if touching && riding.is_none() { - let c = &mut self.carts[i]; - let (mut xa, mut za) = (pp.x - c.position.x, pp.z - c.position.z); - let dd = xa * xa + za * za; - if dd >= 1.0e-4 { - let d = dd.sqrt(); - let pow = (1.0 / d).min(1.0); - xa = xa / d * pow * f64::from(0.1f32) * 0.5; - za = za / d * pow * f64::from(0.1f32) * 0.5; - c.velocity.x -= xa; - c.velocity.z -= za; - if let Some(p) = self.player.as_mut() { - p.velocity.x += xa / 4.0; - p.velocity.z += za / 4.0; - } - } + if !touching { + continue; } + let c = &mut self.carts[i]; + let (mut xa, mut za) = (pp.x - c.position.x, pp.z - c.position.z); + let dd = xa * xa + za * za; + if dd < 1.0e-4 { + continue; + } + let d = dd.sqrt(); + let pow = (1.0 / d).min(1.0); + xa = xa / d * pow * f64::from(0.1f32) * 0.5; + za = za / d * pow * f64::from(0.1f32) * 0.5; + c.velocity.x -= xa; + c.velocity.z -= za; } } } From a713dbd46dba5e0370564d07d0fcf630ec086e40 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 13:27:50 +0200 Subject: [PATCH 101/408] Break vehicles in lava on their first tick, as vanilla does AbstractBoat.tick runs applyEffectsFromBlocks twice, and a minecart takes lavaHurt from its behaviour's applyEffectsFromBlocks and again from its own isInLava check: two 40-point hurts a tick, so lava breaks either on its first tick inside (a TNT minecart primes instead). A minecart has no baseTick and a boat never outlives lava, so the fire countdown is gone. Minecart pushing takes the player's own box and returns at once when there are no carts. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/boats.rs | 94 ++++++++------------- crates/horizon-client/src/game/minecarts.rs | 93 ++++++++------------ 2 files changed, 71 insertions(+), 116 deletions(-) diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs index 402582bf2..bc9afd18b 100644 --- a/crates/horizon-client/src/game/boats.rs +++ b/crates/horizon-client/src/game/boats.rs @@ -43,8 +43,6 @@ pub(super) struct Boat { pub hurt_time: i32, pub hurt_dir: i32, pub damage: f32, - /// `Entity.remainingFireTicks`: lava sets a boat alight for 15 seconds. - pub fire_ticks: i32, pub paddles: [f32; 2], pub paddling: [bool; 2], /// left, right, up, down @@ -79,7 +77,6 @@ impl Boat { hurt_time: 0, hurt_dir: 1, damage: 0.0, - fire_ticks: 0, paddles: [0.0; 2], paddling: [false; 2], input: [false; 4], @@ -186,13 +183,13 @@ impl BoatModels { } impl Game<'_> { fn fluid_height(&self, x: i32, y: i32, z: i32) -> Option<(f32, bool)> { - self.fluid_height_of(x, y, z, false) + self.fluid_height_of(x, y, z, Some(Fluid::Water)) } - /// `FluidState.getHeight` and whether it is a source; water only, - /// unless `lava` too (`ClipContext.Fluid.ANY`). - fn fluid_height_of(&self, x: i32, y: i32, z: i32, lava: bool) -> Option<(f32, bool)> { + /// `FluidState.getHeight` and whether it is a source, for `fluid` or, + /// with `None`, any fluid (`ClipContext.Fluid.ANY`). + fn fluid_height_of(&self, x: i32, y: i32, z: i32, fluid: Option) -> Option<(f32, bool)> { let f = self.res.facts().get(self.world.block(x, y, z)); - if f.fluid != Fluid::Water && !(lava && f.fluid == Fluid::Lava) { + if f.fluid == Fluid::None || fluid.is_some_and(|want| f.fluid != want) { return None; } let above = self.res.facts().get(self.world.block(x, y + 1, z)); @@ -469,78 +466,59 @@ impl Game<'_> { let b = self.boats[i].clone(); self.boats[i] = self.tick_boat(b, false); } - // applyEffectsFromBlocks runs on the server for every boat, the - // client-driven ones too; a boat lava destroys leaves the list. + // AbstractBoat.tick's applyEffectsFromBlocks, on the server for every + // boat, the client-driven ones too. let mut i = 0; while i < self.boats.len() { let p = self.boats[i].position; let skip = Some(self.boats[i].id) == self.riding || !ticking(p.x.floor() as i32, p.z.floor() as i32); - if skip || !self.boat_fire_tick(i) { + if skip || !self.boat_lava_tick(i) { i += 1; } } } - /// The fire half of `Entity.baseTick` and `LavaFluid.entityInside` - /// (`lavaIgnite`, then `lavaHurt`) after the boat moved. True when the - /// boat was destroyed and removed. - fn boat_fire_tick(&mut self, i: usize) -> bool { - let (lava, water) = self.hull_fluids(self.boats[i].bounds()); - let b = &mut self.boats[i]; - if water { - b.fire_ticks = 0; - } - let mut burn = 0.0; - if b.fire_ticks > 0 { - if b.fire_ticks % 20 == 0 && !lava { - burn = 1.0; - } - b.fire_ticks -= 1; - } - if burn > 0.0 && self.hurt_boat(i, burn, false) { - return true; - } - if !lava { + /// `LavaFluid.entityInside` (`lavaHurt`) from the two + /// `applyEffectsFromBlocks` calls in `AbstractBoat.tick`: twice 40 + /// damage, so lava breaks a boat on its first tick inside, and the fire + /// `lavaIgnite` lights never gets to burn it. True when the boat broke. + fn boat_lava_tick(&mut self, i: usize) -> bool { + if !self.in_lava(self.boats[i].bounds()) { return false; } - let b = &mut self.boats[i]; - b.fire_ticks = b.fire_ticks.max(300); - let at = [b.position.x, b.position.y, b.position.z]; + for _ in 0..2 { + let p = self.boats[i].position; + let broke = self.hurt_boat(i, 4.0, false); + self.lava_hurt_sound([p.x, p.y, p.z]); + if broke { + return true; + } + } + false + } + /// `Entity.lavaHurt`'s sound once the hurt went through. + pub(super) fn lava_hurt_sound(&mut self, at: [f64; 3]) { let pitch = 2.0 + self.world.random.next_float() * 0.4; self.audio .play("minecraft:entity.generic.burn", Some(at), 0.4, pitch); - self.hurt_boat(i, 4.0, false) } - /// Whether a vehicle's box (deflated by 1e-5, as `applyEffectsFromBlocks`) - /// is inside lava, and whether it touches water. - pub(super) fn hull_fluids(&self, bb: Aabb) -> (bool, bool) { + /// Whether a vehicle's box, deflated by 1e-5, reaches into lava below its + /// surface (`Entity.collidedWithFluid`). + pub(super) fn in_lava(&self, bb: Aabb) -> bool { let (lo, hi) = (bb.min_position(), bb.max_position()); let e = 1.0e-5; - let (mut lava, mut water) = (false, false); for x in (lo.x + e).floor() as i32..=(hi.x - e).floor() as i32 { for y in (lo.y + e).floor() as i32..=(hi.y - e).floor() as i32 { for z in (lo.z + e).floor() as i32..=(hi.z - e).floor() as i32 { - let f = self.res.facts().get(self.world.block(x, y, z)); - if f.fluid == Fluid::None { - continue; - } - let above = self.res.facts().get(self.world.block(x, y + 1, z)); - let height = if above.fluid == f.fluid { - 1.0 - } else { - f64::from(f.fluid_level) / 9.0 - }; - if lo.y + e < f64::from(y) + height { - match f.fluid { - Fluid::Lava => lava = true, - Fluid::Water => water = true, - _ => {} - } + if let Some((height, _)) = self.fluid_height_of(x, y, z, Some(Fluid::Lava)) + && lo.y + e < f64::from(y) + f64::from(height) + { + return true; } } } } - (lava, water) + false } /// The player's tick while riding: steer, tick the boat, sit in it. pub(super) fn tick_riding(&mut self, keys: Keys) -> horizon_client::Result<()> { @@ -569,7 +547,7 @@ impl Game<'_> { p.fall_distance = 0.0; } self.boats[i] = b; - if self.boat_fire_tick(i) { + if self.boat_lava_tick(i) { self.riding = None; } Ok(()) @@ -637,7 +615,7 @@ impl Game<'_> { p[1].floor() as i32, p[2].floor() as i32, ); - if let Some((h, _)) = self.fluid_height_of(x, y, z, true) + if let Some((h, _)) = self.fluid_height_of(x, y, z, None) && p[1] <= f64::from(y) + f64::from(h) { fluid = Some(([p[0], f64::from(y) + f64::from(h), p[2]], t)); diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 47e71bfd2..0b58e4f88 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -79,8 +79,6 @@ pub(super) struct Minecart { pub hurt_time: i32, pub hurt_dir: i32, pub damage: f32, - /// `Entity.remainingFireTicks`: lava sets a cart alight for 15 seconds. - pub fire_ticks: i32, pub items: Vec>, /// Furnace minecarts: fuel ticks and the push direction. pub fuel: i32, @@ -179,7 +177,6 @@ impl Minecart { hurt_time: 0, hurt_dir: 1, damage: 0.0, - fire_ticks: 0, items: vec![None; kind.slots()], fuel: 0, push: [0.0; 2], @@ -689,7 +686,6 @@ impl Game<'_> { } } } - /// `AbstractMinecart.push(player)` when the player walks into a cart. /// `AbstractMinecart.push` from each player walking into a cart /// (`LivingEntity.pushEntities`): the window's player and every server /// player (single player's own on its server thread, LAN guests). A @@ -698,12 +694,15 @@ impl Game<'_> { /// `needsSync`, which `ServerEntity` sends to the other players only), /// so no player feels it. fn push_carts(&mut self) { - // (feet, height) - let mut pushers: Vec<(Vec3, f64)> = Vec::new(); + if self.carts.is_empty() { + return; + } + // (feet, box) + let mut pushers: Vec<(Vec3, Aabb)> = Vec::new(); if self.riding.is_none() && let Some(p) = self.player.as_ref() { - pushers.push((p.position, 1.8)); + pushers.push((p.position, p.bounds())); } if let Some(host) = self.lan.as_ref() { for g in host.hub.guests.iter().filter(|g| { @@ -711,26 +710,21 @@ impl Game<'_> { }) { let [x, y, z] = g.position; let height = if g.sneaking { 1.5 } else { 1.8 }; - pushers.push((Vec3::new(x, y, z), height)); + let bb = Aabb::new( + Vec3::new(x - 0.3, y, z - 0.3), + Vec3::new(x + 0.3, y + height, z + 0.3), + ); + pushers.push((Vec3::new(x, y, z), bb)); } } - for (pp, height) in pushers { - for i in 0..self.carts.len() { - let bb = self.carts[i].bounds(); - let (lo, hi) = (bb.min_position(), bb.max_position()); - let touching = pp.x + 0.3 > lo.x - && pp.x - 0.3 < hi.x - && pp.z + 0.3 > lo.z - && pp.z - 0.3 < hi.z - && pp.y + height > lo.y - && pp.y < hi.y; - if !touching { + for (feet, bb) in pushers { + for c in &mut self.carts { + if !bb.intersects(c.bounds()) { continue; } - let c = &mut self.carts[i]; - let (mut xa, mut za) = (pp.x - c.position.x, pp.z - c.position.z); + let (mut xa, mut za) = (feet.x - c.position.x, feet.z - c.position.z); let dd = xa * xa + za * za; - if dd < 1.0e-4 { + if dd < f64::from(1.0e-4f32) { continue; } let d = dd.sqrt(); @@ -816,7 +810,7 @@ impl Game<'_> { let ridden = self.guest_vehicles(); // By id: an exploding cart can destroy or prime others mid-loop. let ids: Vec = self.carts.iter().map(|c| c.id).collect(); - for id in ids { + for &id in &ids { let Some(i) = self.carts.iter().position(|c| c.id == id) else { continue; }; @@ -842,50 +836,33 @@ impl Game<'_> { self.carts.remove(i); } } - // applyEffectsFromBlocks runs on the server for every cart, the - // ridden ones too. - let ids: Vec = self.carts.iter().map(|c| c.id).collect(); + // On the server for every cart, the ridden ones too. for id in ids { if let Some(i) = self.carts.iter().position(|c| c.id == id) { let p = self.carts[i].position; if ticking(p.x.floor() as i32, p.z.floor() as i32) { - self.cart_fire_tick(i); + self.cart_lava_tick(id); } } } } - /// The fire half of `Entity.baseTick` and `LavaFluid.entityInside` - /// (`lavaIgnite`, then `lavaHurt`) for one cart, through - /// `VehicleEntity.hurtServer`: lava breaks a cart on its second tick in - /// it, and primes a TNT minecart (`damageSourceIgnitesTnt`). - fn cart_fire_tick(&mut self, i: usize) { - let (lava, water) = self.hull_fluids(self.carts[i].bounds()); - let id = self.carts[i].id; - let c = &mut self.carts[i]; - if water { - c.fire_ticks = 0; + /// `lavaHurt` twice a tick in lava: from `LavaFluid.entityInside` in the + /// behaviour's `applyEffectsFromBlocks`, then from `AbstractMinecart.tick`'s + /// own `isInLava`. The second breaks the cart, or primes a TNT minecart + /// (`MinecartTNT.destroy` for a fire source). A cart has no `baseTick`, + /// so the fire `lavaIgnite` lights never burns it. + fn cart_lava_tick(&mut self, id: u32) { + for _ in 0..2 { + let Some(i) = self.carts.iter().position(|c| c.id == id) else { + return; + }; + if !self.in_lava(self.carts[i].bounds()) { + return; + } + let p = self.carts[i].position; + self.hurt_cart(i, 4.0, false, true); + self.lava_hurt_sound([p.x, p.y, p.z]); } - let mut burn = false; - if c.fire_ticks > 0 { - burn = c.fire_ticks % 20 == 0 && !lava; - c.fire_ticks -= 1; - } - if burn { - self.hurt_cart(i, 1.0, false, true); - } - if !lava { - return; - } - let Some(i) = self.carts.iter().position(|c| c.id == id) else { - return; - }; - let c = &mut self.carts[i]; - c.fire_ticks = c.fire_ticks.max(300); - let at = [c.position.x, c.position.y, c.position.z]; - let pitch = 2.0 + self.world.random.next_float() * 0.4; - self.audio - .play("minecraft:entity.generic.burn", Some(at), 0.4, pitch); - self.hurt_cart(i, 4.0, false, true); } /// `ClientPacketListener.postAddEntitySoundInstance` for the carts that /// joined the level since the last tick, and `LocalPlayer.startRiding`'s From 704931ed14f7cb14e29f27ede60aba3e59df49ff Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 13:27:50 +0200 Subject: [PATCH 102/408] Keep horizon-ctl getblock on a client's copy, run server ones in the owner's level On a LAN guest or any remote client, getblock and container read what that client has again (test_friends waits on a guest's getblock). On the server thread the block commands run in the owner's level, not whichever level the server ticked last. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/blockctl.rs | 14 +++++++------- crates/horizon-client/src/game/integrated.rs | 16 ++++++++++++++++ 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/crates/horizon-client/src/game/blockctl.rs b/crates/horizon-client/src/game/blockctl.rs index 8e0ea287e..6765c3df8 100644 --- a/crates/horizon-client/src/game/blockctl.rs +++ b/crates/horizon-client/src/game/blockctl.rs @@ -64,22 +64,22 @@ impl Game<'_> { Some(&("setblock" | "fill" | "getblock" | "container")) ); // Single player on its server thread: the world is the server's, so - // the command runs there and the client hears of it like any change. + // the command runs there, in the owner's level, and the client hears + // of it like any change. if ours && let Some(server) = &self.integrated { let owned: Vec = words.iter().map(|w| (*w).to_owned()).collect(); return server .call(move |g| { let words: Vec<&str> = owned.iter().map(String::as_str).collect(); - g.block_command(&words).map_err(|e| e.to_string()) + g.in_owner_level(|g| g.block_command(&words).map_err(|e| e.to_string())) }) .ok_or("the integrated server stopped")? .map_err(Into::into); } - // Another server's world changes only through its commands. - if ours && self.remote.is_some() { - if !matches!(words[0], "setblock" | "fill") { - return Err(format!("{} needs a world on this machine", words[0]).into()); - } + // Another server's world changes only through its own commands, which + // it checks as the player's; `getblock` and `container` read what this + // client has of it. + if self.remote.is_some() && matches!(words.first(), Some(&("setblock" | "fill"))) { self.send_chat(&format!("/{}", words.join(" "))); return Ok(Some(json!({ "ok": true, "sent": true }))); } diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index ee343c64b..44df5fe20 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -496,6 +496,22 @@ impl Game<'_> { out } + /// Run `f` with the owner's level in place (the server holds one per + /// dimension), then put back the level that was. + pub(super) fn in_owner_level(&mut self, f: impl FnOnce(&mut Self) -> T) -> T { + let owner = self.serving.as_ref().map(|s| s.owner); + let dim = self.lan.as_ref().and_then(|h| { + let g = h.hub.guests.iter().find(|g| Some(g.uuid) == owner)?; + Some(super::Dim::from_id(&g.dimension)) + }); + let back = dim.and_then(|d| self.enter_command_level(d)); + let out = f(self); + if let Some(back) = back { + self.enter_command_level(back); + } + out + } + /// The window's requests, between two ticks. fn run_tasks(&mut self) { let tasks: Vec = match &self.serving { From 0a3965a7b179e36d801bcd50122249e4c096412d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 13:28:50 +0200 Subject: [PATCH 103/408] Check vehicles on both sides of a LAN game lan_e2e's vehicles check: a creative break whose block is put back stays, a player stands on a boat, lava breaks a ridden boat and lets the rider out, a minecart in lava breaks and a TNT one goes off, and walking into a minecart pushes it, for the host and the guest. Co-Authored-By: Claude Opus 5.5 --- tools/lan_e2e.py | 95 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index f44a84ea8..2bee82fb2 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -5293,5 +5293,100 @@ CHECKS += ['digging'] CHECK_FNS.update(digging=check_digging) +def check_vehicles(host, guest, out): + """The host and the guest each (#1551): + - in creative, break a block and have it put back: the server's dig ends with the break + (ServerPlayerGameMode.handleBlockBreakAction), so the block stays; + - land on a boat on the ground and stand on it (AbstractBoat.canBeCollidedWith); + - sit in a boat that lava reaches: lavaHurt twice a tick breaks it at once, and the rider is out; + - see a minecart in lava break, and a TNT minecart in lava prime and go off; + - walk into a minecart off rails and push it (AbstractMinecart.push from the server's player).""" + result = {} + spots = apart(host, guest) + for label, player in (('host', host), ('guest', guest)): + x, y, z = spots[label] + seen = result[label] = {} + near = lambda kind, at: [o for o in host('status')['objects'] if o['kind'].endswith(kind) + and abs(o['position'][0] - at[0]) < 2 and abs(o['position'][2] - at[2]) < 2] + try: + cell = (x, y + 1, z + 2) + player('command', command='gamemode creative') + player('command', command=f'setblock {cell[0]} {cell[1]} {cell[2]} minecraft:stone') + player.wait(5) + player.raw('look-at', f'{x + 0.5:.2f}', f'{y + 1.5:.2f}', f'{z + 2.5:.2f}') + player.raw('mouse', 'left', 'click') + player.wait(5) + seen['broken'] = host.raw('block', *cell).get('block') + player('command', command=f'setblock {cell[0]} {cell[1]} {cell[2]} minecraft:stone') + player.wait(20) + seen['put_back'] = [g.raw('block', *cell).get('block') for g in (host, player)] + player('command', command=f'setblock {cell[0]} {cell[1]} {cell[2]} minecraft:air') + + player('command', command='gamemode survival') + player('command', command='effect give @s minecraft:fire_resistance 300 0 true') + boat_at = (x + 0.5, y, z + 3.5) + player('command', command=f'summon minecraft:oak_boat {boat_at[0]} {y} {boat_at[2]}') + player.wait(10) + player('command', command=f'tp @s {boat_at[0]} {y + 1.2:.2f} {boat_at[2]}') + player.wait(20) + seen['on_boat'] = [round(pos_of(player)[1] - y, 3), round(server_player(host, player)['position'][1] - y, 3)] + + player('command', command=f'tp @s {x + 0.5} {y} {z + 1.5} 0 0') + player.wait(10) + board(player, 'oak_boat', boat_at) + player('command', command=f'setblock {x} {y} {z + 3} minecraft:lava') + player.wait(10) + seen['rider'] = {'riding': player('status').get('riding'), 'boats': len(near('oak_boat', boat_at))} + + player('command', command='gamemode creative') + player('command', command=f'summon minecraft:minecart {boat_at[0]} {y} {boat_at[2]}') + player.wait(10) + seen['minecart_in_lava'] = len(near('minecart', boat_at)) + booms = player('status')['heard'].get('minecraft:entity.generic.explode', 0) + player('command', command=f'summon minecraft:tnt_minecart {boat_at[0]} {y} {boat_at[2]}') + player.wait(60) + seen['tnt_minecart'] = {'left': len(near('tnt_minecart', boat_at)), + 'booms': player('status')['heard'].get('minecraft:entity.generic.explode', 0) - booms} + + player('command', command=f'fill {x - 3} {y} {z - 3} {x + 4} {y + 3} {z + 6} minecraft:air') + player('command', command=f'fill {x - 3} {y - 1} {z - 3} {x + 4} {y - 1} {z + 6} minecraft:stone') + player('command', command='gamemode survival') + player('command', command=f'tp @s {x + 0.5} {y} {z + 0.5} 0 0') + cart_at = (x + 0.5, y, z + 1.6) + player('command', command=f'summon minecraft:minecart {cart_at[0]} {y} {cart_at[2]}') + player.wait(10) + before = near('minecart', cart_at)[0]['position'] + player.raw('key', 'w', 'down') + player.wait(15) + player.raw('key', 'w', 'up') + player.wait(10) + after = near('minecart', cart_at)[0]['position'] + seen['cart_pushed'] = round(after[2] - before[2], 3) + player.shot(out, f'vehicles-{label}') + finally: + player('command', command='kill @e[type=minecraft:minecart]') + player('command', command='kill @e[type=minecraft:oak_boat]') + player('command', command='kill @e[type=minecraft:item]') + player('command', command=f'fill {x - 3} {y} {z - 3} {x + 4} {y + 3} {z + 6} minecraft:air') + player('command', command=f'fill {x - 3} {y - 1} {z - 3} {x + 4} {y - 1} {z + 6} minecraft:stone') + player('command', command='effect clear @s') + player('command', command='gamemode survival') + player('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}') + player.wait(5) + for label, seen in result.items(): + assert seen['broken'] == 'minecraft:air', f'{label}: the creative click broke nothing: {seen}' + assert seen['put_back'] == ['minecraft:stone'] * 2, f'{label}: the server kept digging: {seen}' + assert all(0.5 < dy < 0.65 for dy in seen['on_boat']), f'{label}: not standing on the boat: {seen}' + assert seen['rider'] == {'riding': None, 'boats': 0}, f'{label}: lava left the boat or its rider: {seen}' + assert seen['minecart_in_lava'] == 0, f'{label}: a minecart outlived lava: {seen}' + assert seen['tnt_minecart'] == {'left': 0, 'booms': 1}, f'{label}: the TNT minecart in lava: {seen}' + assert seen['cart_pushed'] > 0.1, f'{label}: walking into the minecart left it: {seen}' + return result + + +CHECKS += ['vehicles'] +CHECK_FNS.update(vehicles=check_vehicles) + + if __name__ == '__main__': main() From e61e6345bc951793a098c451d0d6099190839a2c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 13:47:19 +0200 Subject: [PATCH 104/408] Releases: in batches of 5 pull requests, or when the oldest has waited 6 hours One release per merge made about 40 releases in 31 hours, hard for players to follow (asked on Discord). release-now still releases at once. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release.yml | 4 ++-- docs/release-flow.md | 9 ++++----- tests/test_release_train.py | 15 ++++++++++----- tools/release_train.py | 20 ++++++++++++++------ 4 files changed, 30 insertions(+), 18 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a0953c73a..6b0fb2e0f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,8 +1,8 @@ name: release # Automatic game releases (docs/release-flow.md). After every green `checks` run on main, every 10 minutes (so a # release waiting for merges to settle goes out without another merge) and by hand, tools/release_train.py decides: -# a release when pull requests merged since the last one changed what players run and the newest merged 5 minutes -# ago (the oldest 20 minutes ago, if merges never pause), or at once for a pull request labelled release-now. +# a release when 5 pull requests merged since the last one changed what players run and the newest merged 5 minutes +# ago, or when the oldest has waited 6 hours, or at once for a pull request labelled release-now. # RELEASES_PAUSED=1 (repository variable) stops them; so does an open issue labelled release-blocker, forced runs too. # Builds Linux (an older Ubuntu, so the binary runs on any recent distribution and on NixOS through nix-ld) and # Windows on GitHub, macOS on the Mac mini's runner (MAC_RUNNER=macos-latest sends it to GitHub), then diff --git a/docs/release-flow.md b/docs/release-flow.md index 72a5c53a9..758f254ee 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -116,10 +116,9 @@ commits) since the last **published** game release: `xtask/`, `packaging/`, `Cargo.toml`, `Cargo.lock`, `research-lock.json`, or an exporter `horizon-prepare` compiles (the `mods/horizon/src/test/java/dev/horizonlab/parity/*.java` files its sources name). Markdown never counts. -- It releases when at least one pull request counts and the newest of them merged at least 5 minutes ago, so a wave - of merges becomes one release; if merges never pause, it releases once the oldest has waited 20 minutes. There is - no minimum time between releases: every settled player-facing change ships, limited only by the release already - building: many releases a day. +- It releases in batches, so players get a few releases a day rather than one per merge: once 5 pull requests count + and the newest of them merged at least 5 minutes ago (a wave of merges becomes one release), or once the oldest has + waited 6 hours, however few they are. - A pull request labelled `release-now` (a crash or a blocker) releases at once. - A pull request labelled `skip-release` (work players don't see) doesn't count and isn't listed in the notes. - An open issue labelled `release-blocker` holds every game release, forced ones too (`held by release-blocker #N`). @@ -299,7 +298,7 @@ and by hand; pushes to `launcher` and `launcher-*` branches only build. - `tools/release_train.py decide --kind launcher` counts the pull requests merged since the last published launcher release that changed those paths (not `launcher/links.json`, which the launcher reads from main, nor - tests or Markdown), with the same settling rule (5 minutes, at most 20), `release-now`, `skip-release` and `RELEASES_PAUSED`. + tests or Markdown), with the same batching rule (5 pull requests settled 5 minutes, or the oldest 6 hours), `release-now`, `skip-release` and `RELEASES_PAUSED`. - The tag is `launcher@X.Y.Z` on the release line (`launcher@0.2.0` first; the game and the launcher count their patches separately). Without `.github/release-line.txt`, `launcher-vX.Y.Z`: the patch after the last launcher tag, or the next minor (`X.Y+1.0`) when one of those pull requests is labelled `feature`. `launcher-v0.2.0` was taken diff --git a/tests/test_release_train.py b/tests/test_release_train.py index 298077352..dde734c7d 100644 --- a/tests/test_release_train.py +++ b/tests/test_release_train.py @@ -120,15 +120,20 @@ class ReleaseTrainTests(unittest.TestCase): def test_decision(self): minute = dt.timedelta(minutes=1) decide = lambda prs, **kw: train.decision("game", prs, NOW, **kw)[0] - self.assertTrue(decide([pr(1, merged=6 * minute)]), "settled for the debounce") - self.assertFalse(decide([pr(1, merged=2 * minute)]), "merged moments ago") - self.assertFalse(decide([pr(1, merged=15 * minute), pr(2, merged=2 * minute)]), "a burst still merging") - self.assertTrue(decide([pr(1, merged=21 * minute), pr(2, merged=minute)]), "merges that never pause still ship") + hour = 60 * minute + five = lambda newest: [pr(n, merged=newest + n * minute) for n in range(5)] + self.assertTrue(decide(five(6 * minute)), "a batch, settled for the debounce") + self.assertFalse(decide(five(2 * minute)), "a batch still merging") + self.assertFalse(decide(five(6 * minute)[:4]), "not yet a batch") + self.assertFalse(decide([pr(1, merged=5 * hour)]), "a lone fix waits for others") + self.assertTrue(decide([pr(1, merged=6 * hour)]), "until the oldest has waited 6 hours") + self.assertTrue(decide([pr(1, merged=7 * hour), pr(2, merged=minute)]), "merges that never pause still ship") + self.assertFalse(decide([pr(n, merged=6 * minute) for n in range(4)] + [pr(9, labels=["skip-release"])]), + "work players don't see doesn't fill a batch") self.assertTrue(decide([pr(1, labels=["release-now"], merged=minute)])) self.assertFalse(decide([pr(1, paths=[])]), "nothing players run") self.assertFalse(decide([pr(1, labels=["skip-release"])])) self.assertFalse(decide([pr(1, labels=["release-now", "skip-release"])])) - self.assertFalse(decide([pr(1, merged=3 * minute), pr(2, labels=["skip-release"], merged=minute)]), "the settled one waits for nothing") self.assertFalse(decide([pr(1)], paused=True)) self.assertTrue(decide([], paused=True, force=True)) diff --git a/tools/release_train.py b/tools/release_train.py index b8d6468bb..6ec2739d9 100644 --- a/tools/release_train.py +++ b/tools/release_train.py @@ -7,9 +7,9 @@ python3 tools/release_train.py gate --kind game --smoke dist/smoke-test.json [--blockers] # before publishing A kind releases when a pull request merged into main since its last published release changed one of its -player-facing paths (GAME_PATHS, LAUNCHER_PATHS) and the newest of them merged at least DEBOUNCE ago (a burst -of merges becomes one release), or the oldest at least MAX_WAIT ago (merges that never pause still ship), or when one -of those pull requests is labelled release-now. Pull requests labelled skip-release (work players don't see) don't count +player-facing paths (GAME_PATHS, LAUNCHER_PATHS), once BATCH of them are waiting and the newest merged at least +DEBOUNCE ago (a burst of merges becomes one release), or once the oldest has waited MAX_WAIT (a lone fix still ships), +or at once when one of those pull requests is labelled release-now. Pull requests labelled skip-release (work players don't see) don't count towards a release and aren't listed in the notes. RELEASES_PAUSED=1 (a repository variable) stops automatic releases, and an open issue labelled release-blocker stops game releases, even forced ones, until it is closed. @@ -40,9 +40,11 @@ import sys ROOT = Path(__file__).resolve().parents[1] REPO = os.environ.get("GITHUB_REPOSITORY", "ludovic111/horizon") -# Releases ship constantly: a merge starts a release within minutes, once its wave of merges has settled. +# Releases ship in batches, so players get a few releases a day rather than one per merge: BATCH player-facing pull +# requests, settled for DEBOUNCE, or whatever is waiting once the oldest has waited MAX_WAIT. +BATCH = 5 DEBOUNCE = dt.timedelta(minutes=5) -MAX_WAIT = dt.timedelta(minutes=20) +MAX_WAIT = dt.timedelta(hours=6) # Kept as typed in release titles, where the clauses after the first are lowercased. PROPER = {"Horizon", "Horizon's", "Minecraft", "Mojang", "Microsoft", "Java", "Xbox", "PlayStation", "Steam", "Windows", "Linux", "LAN", "Kira", "Discord", "Wayland", "Hyprland", "F3", "GUI", "UI"} @@ -288,7 +290,13 @@ def decision(kind, prs, now, paused=False, force=False, new_line=None, blockers= return False, "no merged pull request changed what players run" if urgent: return True, "release-now: " + ", ".join(f"#{pr['number']}" for pr in urgent) - if merged and now - max(merged) < DEBOUNCE and now - min(merged) < MAX_WAIT: + if merged and now - min(merged) >= MAX_WAIT: + return True, f"{len(counted)} pull requests changed what players run; the oldest has waited {MAX_WAIT.seconds // 3600} hours" + if len(counted) < BATCH: + wait = MAX_WAIT - (now - min(merged)) if merged else MAX_WAIT + return False, (f"{len(counted)} of {BATCH} pull requests: waiting for more, or {wait.seconds // 60 + 1} more " + "minutes for the oldest") + if merged and now - max(merged) < DEBOUNCE: wait = DEBOUNCE - (now - max(merged)) return False, f"{len(counted)} pull requests: waiting {wait.seconds // 60 + 1} more minutes for merges to settle" return True, f"{len(counted)} pull requests changed what players run" From 8a04e18b9167d39bdd2dbb08575bf82dc3f68d25 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 14:23:40 +0200 Subject: [PATCH 105/408] Measure the minecart push with the player standing half in it Walking through the cart pushes it back once past its middle, so the check stands the player half into the cart from the north and waits. Co-Authored-By: Claude Opus 5.5 --- tools/lan_e2e.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index d2b9af145..42dd7ec53 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -5303,7 +5303,8 @@ def check_vehicles(host, guest, out): - land on a boat on the ground and stand on it (AbstractBoat.canBeCollidedWith); - sit in a boat that lava reaches: lavaHurt twice a tick breaks it at once, and the rider is out; - see a minecart in lava break, and a TNT minecart in lava prime and go off; - - walk into a minecart off rails and push it (AbstractMinecart.push from the server's player).""" + - stand half in a minecart off rails and push it away (AbstractMinecart.push from the server's + player).""" result = {} spots = apart(host, guest) for label, player in (('host', host), ('guest', guest)): @@ -5354,15 +5355,13 @@ def check_vehicles(host, guest, out): player('command', command=f'fill {x - 3} {y} {z - 3} {x + 4} {y + 3} {z + 6} minecraft:air') player('command', command=f'fill {x - 3} {y - 1} {z - 3} {x + 4} {y - 1} {z + 6} minecraft:stone') player('command', command='gamemode survival') - player('command', command=f'tp @s {x + 0.5} {y} {z + 0.5} 0 0') cart_at = (x + 0.5, y, z + 1.6) player('command', command=f'summon minecraft:minecart {cart_at[0]} {y} {cart_at[2]}') player.wait(10) before = near('minecart', cart_at)[0]['position'] - player.raw('key', 'w', 'down') - player.wait(15) - player.raw('key', 'w', 'up') - player.wait(10) + # Half into the cart from the north: it is pushed south until they are apart. + player('command', command=f'tp @s {x + 0.5} {y} {before[2] - 0.4:.2f} 0 0') + player.wait(20) after = near('minecart', cart_at)[0]['position'] seen['cart_pushed'] = round(after[2] - before[2], 3) player.shot(out, f'vehicles-{label}') @@ -5383,7 +5382,7 @@ def check_vehicles(host, guest, out): assert seen['rider'] == {'riding': None, 'boats': 0}, f'{label}: lava left the boat or its rider: {seen}' assert seen['minecart_in_lava'] == 0, f'{label}: a minecart outlived lava: {seen}' assert seen['tnt_minecart'] == {'left': 0, 'booms': 1}, f'{label}: the TNT minecart in lava: {seen}' - assert seen['cart_pushed'] > 0.1, f'{label}: walking into the minecart left it: {seen}' + assert seen['cart_pushed'] > 0.1, f'{label}: the minecart stayed in the player: {seen}' return result From 7eb77912402e7e94593974423e9c14f5ffc721dc Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:08:04 +0200 Subject: [PATCH 106/408] AGENTS.md: the server thread is single player's default (#1514), releases ship in batches (#1554) Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 5b5e9e936..943f2d0e4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,8 +24,8 @@ Feature → files → harness for the most-changed areas: [docs/architecture.md] - Horizon-only features follow [docs/design-system.md](docs/design-system.md) and are off by default where they would change the vanilla look. - Small PRs (< ~500 lines). Labels: `feature` (players get something new), `skip-release` (they see no - change), none for a fix. Agents never add `release-now`: the maintainer decides it. Every merge to main ships - ([docs/release-flow.md](docs/release-flow.md)). + change), none for a fix. Agents never add `release-now`: the maintainer decides it. Merges ship in batches of 5, or after + 6 hours ([docs/release-flow.md](docs/release-flow.md)). - Contributors first: `gh pr list --state open --search ` before you start; never duplicate theirs. ## Crates @@ -151,19 +151,19 @@ python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end ## The two single-player paths -1. **In-frame (default since #1428):** the window's `Game` ticks the world itself, one level that follows - the player (`fn enter_dimension`). This is what Stable players run and what harnesses test. -2. **Server thread (`--server-thread` or `HORIZON_SERVER_THREAD=1`):** `game/integrated.rs` runs a second - `Game` (`serving`) on a "Server thread" with one level per dimension; the window joins it as a client - through memory (`remote`), exactly as a LAN guest or a dedicated server's player does. Not at parity yet: - open `[server-thread]` issues list the gaps. +1. **Server thread (default since #1514):** `game/integrated.rs` runs a second `Game` (`serving`) on a + "Server thread" with one level per dimension; the window joins it as a client through memory (`remote`), + exactly as a LAN guest or a dedicated server's player does. This is what players run. Open + `[server-thread]` issues list the gaps left. +2. **In-frame (`--in-frame`, `--no-server-thread` or `HORIZON_SERVER_THREAD=0`):** the window's `Game` ticks + the world itself, one level that follows the player (`fn enter_dimension`). Most harnesses test this path. LAN guests and dedicated servers always use the server code, so a fix there serves both. Test both paths when you touch player-facing gameplay: ```sh -cargo run --profile fast -p horizon-client -- --resources .local/horizon-client/26.3 --world T # in-frame -cargo run --profile fast -p horizon-client -- --resources .local/horizon-client/26.3 --world T --server-thread # server thread +cargo run --profile fast -p horizon-client -- --resources .local/horizon-client/26.3 --world T # server thread +cargo run --profile fast -p horizon-client -- --resources .local/horizon-client/26.3 --world T --in-frame # in-frame python3 tools/lan_e2e.py --check # host in-frame, guest is a server client python3 tools/lan_e2e.py --server-thread --check # host on its server thread (portals, levels, distance, lava need it) python3 tools/parity.py dedicated_server server_entities server_player_damage From 7efdbdb39a2e3b90ec8188cdaa0e9b4f1c31a9e2 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:42:44 +0200 Subject: [PATCH 107/408] docs: remove the surveys of other mods; mod code is never read Removes docs/performance/java-perf-mods.md (a survey of eight Java performance mods' techniques) and docs/research/java-mod-compat.md (notes on how Fabric, NeoForge and Mixin work, with a list of mods to port). Links to them now point at mods.md, which says in two lines why Java jars don't run in Horizon. docs/modpacks.md no longer lists a mod's decompiled code as an input of a port: a mod's code is never decompiled, read, quoted or paraphrased, and ports are written from the mod's observed behaviour (the oracle and the harness), its own data files and its public documentation only. Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 2 +- docs/mod-browser.md | 2 +- docs/modpacks.md | 24 ++-- docs/mods.md | 7 +- docs/performance/java-perf-mods.md | 130 -------------------- docs/research/java-mod-compat.md | 183 ----------------------------- 6 files changed, 18 insertions(+), 330 deletions(-) delete mode 100644 docs/performance/java-perf-mods.md delete mode 100644 docs/research/java-mod-compat.md diff --git a/docs/README.md b/docs/README.md index 2e06b6e89..71e2a9ced 100644 --- a/docs/README.md +++ b/docs/README.md @@ -14,7 +14,7 @@ To play, use [the launcher](../launcher/README.md); the project site is [playhor - [Benchmark](benchmark.md): Horizon against vanilla 26.3 and vanilla with performance mods, on the same machine, world, path and settings: what is measured, how it is kept fair, how to reproduce it. - [Shader packs](shader-packs.md): how the renderer draws a frame, the Horizon WGSL shader pack format (stages, uniforms, `pack.toml`, hot reload), and the plan to translate OptiFine/Iris packs. - [Extras](extras.md): optional zoom, minimap, FPS and keystroke overlays and auto-reconnect, all off by default. -- [Mods](mods.md): Horizon's own mod system (Rust, sandboxed WebAssembly), how to make and install mods, and [what carries over from Java mods](research/java-mod-compat.md). +- [Mods](mods.md): Horizon's own mod system (Rust, sandboxed WebAssembly), how to make and install mods. - [Modpacks](modpacks.md): porting whole packs (ATM10 and smaller): import, inventory, carry-over, an agent per mod with a harness against the Java original, coverage, and how "10x" is measured. - [Launcher](../launcher/README.md): installs, updates and starts builds; its CLI and MCP server; releasing it. - [Versioning](versioning.md): how releases are numbered from 0.2 (`v0.2.x`, `launcher@0.2.x`), how installs from before 0.2 get there, and the steps for the day 0.2 ships. diff --git a/docs/mod-browser.md b/docs/mod-browser.md index 745f51d9b..3146fca67 100644 --- a/docs/mod-browser.md +++ b/docs/mod-browser.md @@ -6,7 +6,7 @@ packs, see how well each one runs before installing it, and install it with its ## What it offers -Horizon doesn't run Java code ([research/java-mod-compat.md](research/java-mod-compat.md)). It ports what a Java mod +Horizon doesn't run Java code ([mods.md](mods.md)). It ports what a Java mod carries as data (blocks, items, recipes, loot tables, tags, worldgen, textures, names) with `horizon-port-pack`, and says before install which of the mod's features that leaves out. Horizon `.hmod` mods aren't on Modrinth or CurseForge yet (Modrinth has no `horizon` loader). diff --git a/docs/modpacks.md b/docs/modpacks.md index c15d0767e..591c5a567 100644 --- a/docs/modpacks.md +++ b/docs/modpacks.md @@ -7,9 +7,8 @@ pipeline, not a list of hand ports. It takes a pack as players download it and p Horizon mods. The pipeline is AI agents in dependency order, each port checked against the original mod running in a dev-only Java instance. -This page is the design. It builds on [mods.md](mods.md) (the mod API, WASM in wasmtime) and -[research/java-mod-compat.md](research/java-mod-compat.md) (why Java jars and Mixins cannot -run in Horizon, so we port instead). The ATM10 inventory behind the numbers below is +This page is the design. It builds on [mods.md](mods.md) (the mod API, WASM in wasmtime, and +why Java jars cannot run in Horizon, so we port instead). The ATM10 inventory behind the numbers below is [modpacks/atm10-mods.csv](modpacks/atm10-mods.csv). ## In one picture @@ -141,12 +140,13 @@ derivative work. These rules are part of the pipeline, not advice to users: has given written permission, recorded in the index entry. The tooling refuses to package anything else. No-derivatives and non-commercial licences (14 in ATM10) are never published. For them, even a local port gets a warning that the licence may not allow it. -4. **Mod code never enters this repository.** Mod jars, decompiled sources, Java oracle builds +4. **Mod code never enters this repository, and nobody reads it.** Mod jars, Java oracle builds with mod code, and ports of mods we have no permission to publish all live outside the repo: in the user's pipeline work directory, or for our own development in - `~/code/horizon-parity/modports/` (dev-only, never pushed). Ports are written from - observed behaviour and the harness, with decompiled code as a local reference only. The - repository holds the pipeline, the API, metadata (ids, names, versions, licences, counts) + `~/code/horizon-parity/modports/` (dev-only, never pushed). A mod's code is never + decompiled, read, quoted or paraphrased, by people or agents. Ports are written only from + the mod's observed behaviour (the oracle and the harness), its own data files and its + public documentation. The repository holds the pipeline, the API, metadata (ids, names, versions, licences, counts) and test fixtures we write ourselves. 5. **Contacting authors or publishing any port is Ludovic's call.** Agents ask first. @@ -177,7 +177,7 @@ frame, chat and command hooks. Server mods do not run yet. What a content pack n | Entities: types, attributes, AI goals and brains, spawning | — | deep (87) | 0.5 | `entity` interface, AI in the mod with vanilla goals reusable | | Custom renderers and animated models (block-entity, entity, item; GeckoLib's format) | — | deep | 0.5 | data models (Bedrock geometry + animations), plus a budgeted draw-list interface for the rest | | Dimensions: dimension types, levels, chunk generators | — | about 10 (Twilight Forest, Aether, Ad Astra, Undergarden, ...) | 0.5 | JSON part with worldgen; custom generators as mod code | -| New hooks into vanilla behaviour (what Mixins do) | — | deep | as asked | each becomes a named hook, added for everyone ([java-mod-compat.md](research/java-mod-compat.md#3-a-porting-guide-outline)) | +| New hooks into vanilla behaviour (what Mixins do) | — | deep | as asked | each becomes a named hook, added for everyone | | Client interfaces: `keys`, `target`, `inventory-read`, `ui`, `render`, `world-read` | planned | client tier (38) | 0.2–0.4 | as in [mods.md](mods.md#planned-interfaces) | Two rules from mods.md stay: **the sandbox** (no files, sockets or processes; memory cap; fuel @@ -711,16 +711,16 @@ For tiers logic, machines and deep, in dependency order, as many agents at once budget allows: - **Input:** the inventory record, the carried-over data, the oracle's exports and traces, the - harness, the Horizon mod API docs, the ports of its dependencies, and the mod's decompiled - code as a local reference (dev-only, in the work directory). + harness, the Horizon mod API docs, the ports of its dependencies, and the mod's public + documentation. Never its code: the agent doesn't decompile, read or quote it. - **Output:** a Rust crate in `mods//port/` built with `cargo horizon-mod build`, and its `.hmod`. - **Loop:** write → build → run the harness → read the differences → fix, until the harness passes or the agent reports what blocks it. Usually that is an API gap, which becomes an issue against the mod API ("needs a scheduled-tick hook"), the way version ports turn differences into work items. -- **Rules:** the agent writes the port from observed behaviour and the harness, not by - transliterating decompiled Java; ports follow the mod's licence ([Licences](#licences)). +- **Rules:** the agent writes the port from observed behaviour, the harness and the mod's + own data files only; ports follow the mod's licence ([Licences](#licences)). Players without an AI agent get the carry-over tiers. A port the licence lets us publish can be downloaded instead of regenerated. diff --git a/docs/mods.md b/docs/mods.md index 4521d312d..bc91c043a 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -3,8 +3,9 @@ Horizon gets its own mod system, written in Rust and run in a sandbox, plus two ways to bring over what Java players use: native Horizon ports of popular mods and the data-driven parts of packs and mods. Fabric and NeoForge jars do -**not** run as they are: [research/java-mod-compat.md](research/java-mod-compat.md) -explains why and what we do instead. +**not** run as they are: their code calls and patches Minecraft's Java classes, and +Horizon has none. What carries over is the data and assets inside a jar +([modpacks.md](modpacks.md)). Mods are **off and absent by default**. A fresh install has no `horizon-mods` folder, loads no runtime and plays exactly like vanilla 26.3. @@ -102,7 +103,7 @@ name (the mod reads it as `args`; API 0.1 has no way to declare argument types). ### Planned interfaces Each is a new capability, added in a 0.x minor version so older mods keep -loading. Ordered by what the first native ports need ([research](research/java-mod-compat.md#port-first)): +loading. Ordered by what the first native ports need: | Interface | For | Notes | |---|---|---| diff --git a/docs/performance/java-perf-mods.md b/docs/performance/java-perf-mods.md deleted file mode 100644 index 62aab88a1..000000000 --- a/docs/performance/java-perf-mods.md +++ /dev/null @@ -1,130 +0,0 @@ -# Java performance mods: which of their techniques apply to Horizon - -A survey of the techniques used by eight Java Edition performance mods. Asked for in #991, from famescare on Discord. For each technique it gives the vanilla cost it targets, whether Horizon already avoids that cost, and whether it is worth measuring here. - -**Rules.** Techniques only, taken from each mod's public description, documentation and changelogs (linked below). No mod code was read or copied. Several of these mods are LGPL-3.0, and Horizon's code stays its own. Anything Horizon adopts is reimplemented against vanilla 26.3's behaviour. It keeps parity, so the harnesses stay unchanged, and it needs before/after numbers like any other perf PR (`docs/benchmark.md`, `docs/profiling.md`). - -**Why many don't apply.** A large share of these techniques work around costs of the JVM, OpenGL or GLFW rather than costs of the game's rules. Examples are object headers and duplicate objects, boxing, lambdas and Streams, garbage collection, JNI upcalls, immediate-mode GL draws and GL error checks. Horizon is Rust on wgpu and winit, so it never pays those costs. The techniques that do carry over remove work the game's rules don't need: sleeping block entities, skipped searches, and cheaper geometry tests. - -Verdicts: -- **has**: Horizon already avoids the cost, by its design or with a merged change. -- **n/a**: the cost comes from the JVM, OpenGL or GLFW, and Horizon doesn't have it. -- **later**: missing, and worth measuring. These are listed in "Worth measuring" below and in the LATER list. -- **no**: missing, but it would change vanilla's behaviour or look, or the gain here is too small to pay for itself. - -## Lithium (server and shared game logic) - -Source: [Lithium's mixin configuration](https://github.com/CaffeineMC/lithium/blob/develop/lithium-fabric-mixin-config.md). Lithium keeps vanilla's behaviour, which is the same rule Horizon follows. - -| Technique | Vanilla cost | Horizon | Verdict | -| --- | --- | --- | --- | -| Hopper caching, inventory change listeners and hopper sleeping | Every hopper looks up its source and target containers and tries a transfer every tick, even when nothing can move | `game/machines.rs` ticks every hopper on each tick. It checks the block's name and cooldown, then runs the transfer attempt. Nothing is cached or put to sleep | **later** | -| Block entity sleeping (furnaces, brewing stands, campfires, crafters, shulker boxes, sculk) | Idle block entities still tick | `game/block_entity_ticks.rs` ticks every ticker each tick, as vanilla does | **later** | -| Entity collisions: faster block access, chunk caching, the supporting block first | Collision scans read blocks through generic level lookups | Collision scans already run over Horizon's own section arrays (`horizon-world` `block_collision_scan`). A counting cursor that does fewer lookups is open as #659 | **has** (more in #659) | -| Specialised cuboid and empty `VoxelShape`s, precomputed shape arrays | Generic voxel shape intersection and merging | `horizon-core::geometry` has its own immutable shapes and box lists (`docs/collision-geometry.md`) | **has** | -| POI search and portal search | POI lookups go through vanilla's stream-heavy search | Section-indexed POIs (`poi_sections.rs`), searched in vanilla's order | **has** | -| Pathfinding: cached node types per block | Node evaluation reads the same blocks over and over | Not measured. Mob pathfinding costs haven't been profiled against vanilla yet | **later** (profile first) | -| Explosions: one access per block on a ray, skip air, skip exposure work | Each ray step reads the block and the fluid again | `game/explosion.rs` follows vanilla's loop. It hasn't been profiled, and TNT chains are the case to measure | **later** (profile first) | -| Random ticks: roll the chance early, fast block search | Sections with nothing that ticks randomly are still walked | Sections with nothing random-tickable are skipped (`docs/random-tick-eligibility-benchmark.md`) | **has** | -| Tick scheduler: faster collections, packed scheduled ticks | Boxed `ScheduledTick` objects in hash sets | Horizon's own tick heap and index (`horizon-core::ticks`, `docs/scheduled-ticks.md`) | **has** | -| Collections and allocation (fastutil maps, cached `values()`, fewer `BlockPos`, no Streams) | JVM allocation, boxing, GC | Rust value types, no GC | **n/a** | -| Math inlining, a smaller sine table | JIT inlining limits | Compiled and inlined by rustc. Horizon keeps vanilla's `Mth.sin` table where results depend on it | **n/a** | -| Chunk access without debug locks or bounds validation | `PalettedContainer`'s thread-check lock | Horizon doesn't have that lock (`docs/performance/paletted-container-access-results.md`) | **n/a** | -| Palette replacement and compaction | Hash palette resizing on the JVM | Horizon's own paletted containers (`horizon-core::paletted`) | **has** | -| Game event dispatchers made only for sections with a listener | Every section holds a dispatcher | Not checked. This is small next to the items above | **no** (until a profile shows it) | -| Item entity merging grouped by item type (experimental) | Each item entity checks every nearby item to merge with | Not present. It matters only with thousands of dropped items (see #996: fresh worlds drop about twice as many items as vanilla) | **later**, after #996 | -| World border cache, redstone wire double reads, fluid flow reads, framed-map scans | Small repeated reads | Each is minor. Fix them where a profile points at them | **no** | - -## FerriteCore (memory) - -Source: [FerriteCore's summary of its changes](https://github.com/malte0811/FerriteCore/blob/main/summary.md). - -| Technique | Vanilla cost | Horizon | Verdict | -| --- | --- | --- | --- | -| One `FastMap` of neighbour states per block instead of a table per state | About 600 MB of per-state neighbour tables in large packs | Block states are numeric ids with flat tables, with no object per state | **n/a** | -| Compact property storage per state | A per-state `ImmutableMap` | Same as above | **n/a** | -| Cached multipart predicates, shared multipart models | Hundreds of thousands of model and predicate objects | Models are baked once into a shared library (`docs/shared-model-library-benchmark.md`) | **has** | -| Deduplicated baked-quad vertex arrays | Identical `int[]` per quad | Section meshes are built per section from the shared baked models, and no per-quad arrays are kept | **has** | -| Deduplicated shape caches | Duplicate cached `VoxelShape`s per state | One table of distinct shapes, indexed per state (`horizon-world` `CachedCollisionRegistry`) | **has** | -| String deduplication in model locations | Duplicate `String`s from the constructor's round-trips | No `ModelResourceLocation` objects, so the round-trip doesn't exist | **n/a** | -| Partly loaded chunk NBT kept between loading steps | The whole tag is kept | Chunks are decoded into Horizon's own structures | **n/a** | - -Horizon's process memory is tracked against vanilla in `docs/process-memory.md`. - -## ImmediatelyFast (client draw submission) - -Source: [ImmediatelyFast on Modrinth](https://modrinth.com/mod/immediatelyfast). Its gains show only when the CPU is the bottleneck. - -| Technique | Vanilla cost | Horizon | Verdict | -| --- | --- | --- | --- | -| A batching buffer for immediate-mode draws (entities, block entities, particles, text, GUI) | Many small draw calls and uploads | The HUD is one atlas and one batch of quads (`hud.rs`). Entities are grouped by material (`gfx/entity_batch.rs`). Terrain uses indirect multi-draws (`gfx.rs`, `gfx/flat.rs`) | **has** | -| HUD batching, fewer GUI draw calls | One draw per GUI element | Same batch (`hud.rs`) | **has** | -| Fast text lookup, a bigger font atlas | Per-character lookups, atlas thrash with large fonts | Glyphs live in maps in `font.rs`, drawn into the same HUD atlas | **has** | -| One texture for all map item textures | One texture per visible map | Not measured. It matters only with walls of maps in item frames | **later** (with a map-wall scene) | -| Cached closed-chest geometry | Re-tessellating chests each frame | Merged in #728 (Online5277) | **has** | -| Buffered sign text instead of redrawing it each frame | Text redrawn every frame | Sign text is recorded as text calls in the batch. Not measured with sign-heavy scenes | **later** (with a sign-heavy scene) | -| Fewer framebuffer switches | GL state changes between render types | wgpu render passes are fixed by Horizon's pipeline | **n/a** | -| GL error checking off | `glGetError` overhead | No GL. Release builds run without wgpu's backend validation and, outside DirectX 12, without its indirect-draw validation (`gfx.rs` `instance_descriptor`) | **n/a** | - -## Gnetum (HUD rendering) - -Source: [Gnetum on Modrinth](https://modrinth.com/mod/gnetum). - -| Technique | Vanilla cost | Horizon | Verdict | -| --- | --- | --- | --- | -| Draw the HUD into an offscreen buffer in several passes, one pass per frame, and show the last complete buffer | The HUD is redrawn every frame | Horizon redraws its one HUD batch every frame | **no**. The HUD would then update at a lower rate than vanilla's, which changes what players see. Horizon's HUD is already one batch. | -| Adaptive distribution and a separate HUD FPS cap | Same | Same | **no**, for the same reason | - -## ScalableLux (lighting, from Starlight) - -Source: [ScalableLux on Modrinth](https://modrinth.com/mod/scalablelux). - -| Technique | Vanilla cost | Horizon | Verdict | -| --- | --- | --- | --- | -| Starlight's light engine: per-section light arrays and direct propagation queues | Vanilla's light engine is a bottleneck in fast chunk generation | Horizon has its own engine with vanilla's rules (`light.rs`). New chunks are lit on the streaming worker pool, and edits are relit incrementally (`relight_block`). See `docs/performance/lighting-worker-results.md` | **has** | -| Parallel light updates | One light thread | Chunk lighting already runs on several workers during streaming | **has**. Measure the light share of fresh-chunk generation before doing more. | - -## Structure Layout Optimizer (jigsaw structures) - -Source: [Structure Layout Optimizer on Modrinth](https://modrinth.com/mod/structure-layout-optimizer). - -| Technique | Vanilla cost | Horizon | Verdict | -| --- | --- | --- | --- | -| An octree of piece boxes instead of a `VoxelShape` for free space | Voxel shape boolean ops slow down as pieces add up | Free space is a container box minus a list of placed boxes (`worldgen/structure/jigsaw.rs` `Free`). That avoids the voxel shapes, but the scan is linear per test | **has**. An octree pays only for structures with hundreds of pieces. | -| Skip jigsaw blocks that face the structure boundary or another piece | Every parent jigsaw is matched against every child | Not present | **later** (time trial chambers and ancient cities first) | -| Skip pool elements already found not to fit at this spot | Weighted pools repeat an element once per weight point, and it is re-tested each time | Not present. Only the variant that keeps the result identical applies (no deduplication of the list, which changes layouts) | **later** | -| Cull positions outside the chunk before processors run | Whole templates are processed and then mostly discarded | Not checked | **later** (same measurement) | -| Palette-based template storage | Templates keep every block and NBT object | Templates are Horizon's own structures. Memory isn't measured | **no** (until memory shows it) | - -## AsyncParticles (particles) - -Source: [AsyncParticles on Modrinth](https://modrinth.com/mod/asyncparticles). - -| Technique | Vanilla cost | Horizon | Verdict | -| --- | --- | --- | --- | -| Particle culling | Off-screen particles are built anyway | Vanilla already skips quad particles whose position is outside the frustum (`QuadParticleGroup.extractRenderState`, `Frustum.pointInFrustum`). Horizon builds every particle's quad (`particles.rs` `render`). This is a parity gap as well as a cost | **later** (vanilla's frustum point test) | -| Vertex transformation on the GPU | Every particle's quad is built on the CPU and uploaded every frame | Same in Horizon (`particles.rs` `render`). Instancing would upload one record per particle | **later** (measure with 10k+ particles) | -| Particle ticks on another thread | Particle ticks on the client thread | Horizon ticks particles on the game thread | **no**. Vanilla's particle ticks read the level, and racing them against block changes risks parity. Revisit only if a profile shows particle ticks are big. | -| Asynchronous light cache for particles | A light lookup per particle per frame | `particles.rs` looks light up per particle | **later**, with the item above | -| Texture animation one frame late | Animated textures tick on the client tick | Not adopted | **no**, because it changes timing | - -## Ixeris (input and the render thread) - -Source: [Ixeris on Modrinth](https://modrinth.com/project/p8RJPJIC). - -| Technique | Vanilla cost | Horizon | Verdict | -| --- | --- | --- | --- | -| Event polling on the main thread, rendering on its own thread | GLFW event polling and JNI upcalls take time from rendering | winit, without JNI. Input and rendering share the event loop (`game.rs`, `ApplicationHandler`) | **n/a** for the JNI part | -| Buffered raw input (`GetRawInputBuffer`) | One `GetRawInputData` call per event. An 8000 Hz mouse costs a lot on Windows | winit reads `WM_INPUT` one message at a time | **later**. Measure on Windows with a high-polling-rate mouse before changing it. | -| Cached GLFW state | Round trips to the main thread | No GLFW | **n/a** | -| A frame limiter that sleeps, then spins | Imprecise sleeps | Horizon has its own limiter | **no** (no reported problem) | - -## Worth measuring - -Each of these needs a profile or a benchmark first. They are ordered by the expected gain. They are in the LATER list in `~/code/horizon-parity/FEATURES.md`, not filed as issues: - -1. Hopper and block-entity sleeping, with vanilla-identical results (Lithium). Benchmark: a hopper and furnace array. -2. Particles: vanilla's frustum point test (a parity fix too), then GPU-built quads (AsyncParticles). Benchmark: 1,000+ campfires. -3. Jigsaw placement: skip blocked connectors and already-failed elements without changing the layout (Structure Layout Optimizer). Benchmark: trial chambers and ancient cities in fresh worlds, `docs/generation-scan-benchmark.md`. -4. Windows raw input in batches for high-polling-rate mice (Ixeris). Benchmark: an 8000 Hz mouse on Windows. -5. Profile before choosing a technique: mob pathfinding, TNT explosions, item merging after #996, map walls and sign-heavy scenes. diff --git a/docs/research/java-mod-compat.md b/docs/research/java-mod-compat.md deleted file mode 100644 index 8a36b7c48..000000000 --- a/docs/research/java-mod-compat.md +++ /dev/null @@ -1,183 +0,0 @@ -# Java mods and Horizon: what can carry over - -Players ask "will my mods work?". Short answer: **Fabric and NeoForge jars -will not run in Horizon as they are**, and no bridge we could build would -change that for more than a handful of mods. What carries over is the -*content* (data packs, resource packs, the data and assets inside mod jars) -and the *ideas* (native Horizon ports of the mods people use most, written -with [Horizon's own mod system](../mods.md)). This page is the reasoning. - -## How Java mods work - -### Fabric - -- **Fabric Loader** finds jars in `mods/`, reads `fabric.mod.json` - (entrypoints, dependencies, mixin configs, access wideners), and starts the - game through a class loader that can rewrite classes as they load. -- **Mixin** (SpongePowered) is how nearly every mod changes the game: a mixin - class names a Minecraft class (`net.minecraft.client.gui.hud.InGameHud`) and - injects code at points inside its methods (`@Inject(method = "render", at = - @At("TAIL"))`, `@Redirect`, `@ModifyVariable`, `@Overwrite`...). The bytecode - of the vanilla class is rewritten at load time. Access wideners make private - fields and methods public for the same purpose. -- **Fabric API** is a set of modules that give mods events and registries - instead of raw mixins: `fabric-lifecycle-events` (`ClientTickEvents`, - `ServerTickEvents`), `fabric-rendering` (`HudRenderCallback`, - `WorldRenderEvents`), `fabric-command-api`, `fabric-key-binding-api`, - `fabric-networking-api` (custom payloads), `fabric-registry-sync`, - `fabric-resource-loader`, `fabric-screen-api`, `fabric-item-group`, - `fabric-events-interaction` and about forty more. **Fabric API itself is - implemented with mixins** into the same vanilla classes. -- Mods mix the two freely: a mod using Fabric API events still calls - `MinecraftClient.getInstance().player.getBlockPos()`, - `world.getBlockState(pos)`, `DrawContext.drawText(...)`: direct calls into - vanilla's classes, by their mapped names. - -### NeoForge (and Forge) - -- An event bus (`NeoForge.EVENT_BUS`, mod buses) with hundreds of events, - `DeferredRegister` for registries, data attachments and capabilities, - networking payloads, config specs. NeoForge patches vanilla's source - directly (binary patches) to fire its events. -- Mods also use mixins and access transformers, and call vanilla classes - directly, as on Fabric. - -### Data and assets in a jar - -Besides code, a mod jar carries the same folders as packs: -`assets//` (models, blockstates, textures, sounds, language files, -shaders) and `data//` (recipes, loot tables, tags, advancements, -predicates, functions, worldgen: biomes, features, structures). These are -**vanilla formats**, read by vanilla's own code. - -## Why a Java bridge cannot run them - -Horizon is a reimplementation in Rust: there are no `net.minecraft` classes -at runtime, no `InGameHud`, no `ClientPlayerEntity`, no bytecode to rewrite. - -1. **Mixins have nothing to bind to.** A mixin is a patch against a specific - method's bytecode. Without vanilla's classes there is no method, no - injection point and no local variable to modify. This is not a missing - feature we could add: it is the mechanism itself. -2. **Fabric API is mixins too.** A shim Fabric API would have to be - re-implemented from scratch as Java classes calling into Horizon. That part - alone is possible for the event modules. -3. **Mods call vanilla directly.** Even "pure Fabric API" mods use vanilla's - classes for everything else: the player, the world, the block states, the - renderer, the text drawing. Running them means providing Java classes with - vanilla's names and behaviour, backed by Horizon's state: in effect a - second Minecraft, in Java, on top of Horizon. Thousands of classes, in the - mapped names of every mapping set (Yarn, Mojang, intermediary), version by - version. -4. **The JVM itself** would ship with every install (a trimmed JRE is still - 40-60 MB, the full one 150+ MB), start in a second or more, hold a few - hundred MB of heap before any mod loads, and bring garbage-collector pauses - back into the frame: the costs Horizon exists to remove. JNI calls cost - tens to hundreds of nanoseconds each and every one crosses with copies. -5. **No sandbox.** Java mods are fully trusted native-speed code with file - and network access. Horizon's mods are sandboxed and their permissions are - shown; a Java bridge would be the one hole in that. - -**What a bridge could support**, if we ever built one: a stable subset of -Fabric API events (client and server tick, HUD render callback, client -commands, key bindings, custom payloads), with a tiny "vanilla view" API -(player position, held item, chat), for mods written only against that -subset. Surveying the most-downloaded Fabric mods, nearly none qualify: the -popular ones are popular precisely because they reach into rendering, the -world or the UI. The cost (a JVM in the game, a second API surface to keep -stable) is far above the benefit. **We do not build it.** If that changes, -the bridge would sit on top of the WIT API like any other mod runtime, so the -sandbox would still hold. - -## What we do instead - -### 1. Data-driven content (packs and the data in mod jars) - -Horizon already reads vanilla resource packs and data packs (functions, -function tags, predicates today). Extending data-pack coverage to recipes, -loot tables, tags, advancements and worldgen JSON brings most "content" -packs over with no mod code at all, and it is vanilla behaviour, so the parity -harnesses check it. - -For **Fabric/NeoForge jars**, the launcher can offer "import the data": read -`data/` and `assets/` from the jar and load them as a data pack plus a -resource pack. What works: new recipes, loot changes, tags, advancements, -functions, worldgen tweaks that only use vanilla blocks, retextures, language -files. What does not: anything referring to a block, item or entity the jar -registers in Java code (the ids do not exist); the import skips those files and -lists them. With Horizon's planned `registries` interface, a native port can -register those ids and reuse the jar's JSON models, textures, recipes and loot -as they are. - -### 2. Native Horizon ports of popular mods - -Horizon itself covers the performance mods: Sodium, Lithium, FerriteCore, -ModernFix, EntityCulling and ImmediatelyFast exist because vanilla Java is -slow, and Horizon's renderer and simulation are the replacement (see -[benchmark](../benchmark.md)). Zoom (OK Zoomer, Zoomify), FPS and keystroke -overlays, a minimap and auto-reconnect are already built in as -[extras](../extras.md). - -#### Port first - -Ranked by players reached per unit of API work. Each needs the planned -interfaces listed in [mods.md](../mods.md#planned-interfaces). - -| Mod (Java) | What it does | Horizon port | Needs | -|---|---|---|---| -| **Mod Menu** | list mods, open their settings | built in: Options > Mods (done), settings pages next | `ui` | -| **AppleSkin** | food saturation and exhaustion on the HUD and tooltips | SDK mod | `inventory-read`, `ui` | -| **Jade / WTHIT** | what the crosshair points at: block, entity, harvest tool, container contents | SDK mod | `target`, `ui` | -| **JEI / EMI / REI** | browse items, recipes and uses | SDK mod (or built in: Horizon already has the recipe book's data) | `recipes`, `inventory-read`, `ui` | -| **Xaero's Minimap / JourneyMap** | minimap, world map, waypoints | the minimap is an extra; a world map and waypoints as an SDK mod | `world-read`, `render`, `storage` | -| **Litematica** | schematic overlay to build from | SDK mod | `world-read`, `render`, `storage`, `ui` | -| **Mouse Tweaks / Inventory Profiles Next** | drag and sort inventory | built in or SDK mod | `inventory-read` + a sanctioned click API | -| **Continuity / CIT** | connected and custom item textures | built into the renderer (pack formats) | none: resource-pack features | -| **Distant Horizons** | low-detail far terrain | a Horizon renderer feature, not a mod | none | -| **Iris + shader packs** | shaders | a Horizon renderer feature (wgpu shader pipeline), later | none | -| **Simple Voice Chat** | proximity voice | server + client mod | `server`, `net`, audio (later) | - -### 3. A porting guide (outline) - -To be written as `docs/porting-from-fabric.md` once API 0.2 lands: - -1. **Separate logic from glue.** Most of a mod is plain logic (maths, - formatting, data structures): port it to Rust once, unit-test it on the - host. -2. **Map events.** - - | Fabric | Horizon | - |---|---| - | `ClientModInitializer.onInitializeClient` | `Mod::init`, returning a `Registration` | - | `ClientTickEvents.END_CLIENT_TICK` | `Registration::on_tick`, `Mod::tick` | - | `HudRenderCallback` | `hud::set_panel` when the content changes (retained), or `on_frame` | - | `ClientCommandRegistrationCallback` | `Registration::command`, `Mod::command` | - | `ClientReceiveMessageEvents` | `Registration::on_chat`, `Mod::chat` | - | `KeyBindingHelper.registerKeyBinding` | `keys` (planned) | - | `Registry.register(Registries.ITEM, ...)` | `registries` (planned) with JSON in `data/` | - | `ServerPlayNetworking` payloads | `net` (planned) | - | config libraries (Cloth Config, YACL) | `storage` + a `ui` settings page (planned) | - -3. **Replace mixins with hooks.** For each mixin, write down what it observes - or changes. If a WIT hook covers it, use the hook. If not, open an issue - asking for the hook ("I need X before/after Y"): hooks are added to the API - for everyone instead of each mod patching the game. -4. **Declare capabilities** in `horizon-mod.toml`, the least the mod needs. -5. **Reuse assets**: textures, models, language files and recipes move as - they are into the `.hmod`'s `assets/` and `data/` (with `registries`). -6. **Test** with `cargo horizon-mod run` and hot reload; add unit tests for the - logic; publish with a signed `.hmod`. - -## Sources - -- Fabric documentation (`docs.fabricmc.net`): mod structure, Mixin - introduction, Fabric API modules and events. -- SpongePowered Mixin wiki: injection points and how class transformation - works. -- NeoForge documentation (`docs.neoforged.net`): events, registries, - networking. -- Modrinth's most-downloaded Fabric mods, for the porting list. -- Horizon's own Java test mod (`mods/horizon`, built by `tools/build_mod.py` - and the CI `portable-mod` job) is a Fabric mod used by the benchmarks and - parity oracles: it shows the Mixin pattern (`FrameHookMixin`) this page - describes, and stays a developer tool, not a player-facing mod. From 87aa88de54b82bea3e05a04dd0104f3147224211 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:45:29 +0200 Subject: [PATCH 108/408] Launcher: Cmd+Q quits and Cmd+W closes the window on macOS The launcher had no app menu and no key bindings, so Cmd+Q did nothing. Add Quit and CloseWindow actions, bind them to cmd-q and cmd-w on macOS, and set an app menu with "Quit Horizon Launcher" and a Window menu with "Close Window". Quit shares one shut_down path with closing the window (stop the servers this launcher started, send telemetry, exit), so a running game is treated exactly as it is today. Co-Authored-By: Claude Sonnet 5.5 --- launcher/src/main.rs | 88 +++++++++++++++++++++++++++++++++++++++----- 1 file changed, 78 insertions(+), 10 deletions(-) diff --git a/launcher/src/main.rs b/launcher/src/main.rs index bdae38fbb..045d01e58 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -21,10 +21,10 @@ mod servers_page; mod theme; use gpui::{ - div, ease_out_quint, prelude::*, px, relative, size, Animation, AnimationExt, AnyElement, App, - Application, Bounds, ClickEvent, Context, Div, ElementId, FocusHandle, FontWeight, Hsla, - KeyDownEvent, PathPromptOptions, SharedString, Stateful, Subscription, TitlebarOptions, Window, - WindowBounds, WindowOptions, + actions, div, ease_out_quint, prelude::*, px, relative, size, Animation, AnimationExt, + AnyElement, App, Application, Bounds, ClickEvent, Context, Div, ElementId, FocusHandle, + FontWeight, Hsla, KeyBinding, KeyDownEvent, Menu, MenuItem, PathPromptOptions, SharedString, + Stateful, Subscription, TitlebarOptions, Window, WindowBounds, WindowOptions, }; use horizon_launcher::account::{self, Accounts, SignIn, SignInState}; use horizon_launcher::backend::{self, Job, Msg, Release, Running, Settings, Updates}; @@ -3458,6 +3458,44 @@ impl Launcher { } } +actions!(horizon_launcher, [Quit, CloseWindow]); + +/// What closing the last window does: stop the servers this launcher started, send the telemetry, +/// exit. A game that is running keeps running. Cmd+Q goes through here too. +fn shut_down(cx: &mut App) { + servers_page::stop_on_quit(); + telemetry::send_before_exit(); + cx.quit() +} + +/// The macOS shortcuts: Cmd+Q quits, Cmd+W closes the window. +#[cfg(target_os = "macos")] +fn key_bindings() -> Vec { + vec![ + KeyBinding::new("cmd-q", Quit, None), + KeyBinding::new("cmd-w", CloseWindow, None), + ] +} + +#[cfg(not(target_os = "macos"))] +fn key_bindings() -> Vec { + Vec::new() +} + +/// The menu bar on macOS, where "Quit" belongs to the app menu. +fn menus() -> Vec { + vec![ + Menu { + name: "Horizon Launcher".into(), + items: vec![MenuItem::action("Quit Horizon Launcher", Quit)], + }, + Menu { + name: "Window".into(), + items: vec![MenuItem::action("Close Window", CloseWindow)], + }, + ] +} + fn main() { perf::process_started(); backend::exe_path(); @@ -3478,6 +3516,18 @@ fn main() { Cow::Borrowed(horizon_theme::fonts::PIXEL_BOLD), ]) .expect("bundled fonts"); + cx.bind_keys(key_bindings()); + cx.on_action(|_: &Quit, cx| shut_down(cx)); + // The key press is being handled inside the window, so the window can only be + // removed once that update has finished. + cx.on_action(|_: &CloseWindow, cx| { + cx.defer(|cx| { + for window in cx.windows() { + let _ = window.update(cx, |_, window, _| window.remove_window()); + } + }) + }); + cx.set_menus(menus()); let bounds = Bounds::centered(None, size(px(1180.), px(760.)), cx); cx.open_window( WindowOptions { @@ -3493,18 +3543,36 @@ fn main() { |window, cx| cx.new(|cx| Launcher::new(window, cx)), ) .expect("window"); - cx.on_window_closed(|cx| { - servers_page::stop_on_quit(); - telemetry::send_before_exit(); - cx.quit() - }) - .detach(); + cx.on_window_closed(shut_down).detach(); cx.activate(true); }); } #[cfg(test)] mod tests { + #[cfg(target_os = "macos")] + #[test] + fn cmd_q_quits_and_cmd_w_closes_the_window() { + use super::{key_bindings, CloseWindow, Quit}; + use gpui::{Keymap, Keystroke}; + let keymap = Keymap::new(key_bindings()); + let key = |s: &str| [Keystroke::parse(s).unwrap()]; + let (hit, _) = keymap.bindings_for_input(&key("cmd-q"), &[]); + assert!(hit.iter().any(|b| b.action().partial_eq(&Quit))); + let (hit, _) = keymap.bindings_for_input(&key("cmd-w"), &[]); + assert!(hit.iter().any(|b| b.action().partial_eq(&CloseWindow))); + } + + #[test] + fn the_app_menu_has_quit() { + let menus = super::menus(); + assert_eq!(menus[0].name, "Horizon Launcher"); + assert!(matches!( + &menus[0].items[0], + gpui::MenuItem::Action { name, .. } if name == "Quit Horizon Launcher" + )); + } + #[test] fn the_offline_name_is_read_from_its_key() { use super::player_name; From 2a9e0ab28dd3684556120e8935f6e8018fa8757f Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Sat, 24 Oct 2026 14:49:46 +0100 Subject: [PATCH 109/408] Remove unused voxel-kernels research experiment Co-Authored-By: OpenAI Codex gpt-6.1-sol --- AGENTS.md | 2 +- Cargo.lock | 4 - Cargo.toml | 2 +- crates/voxel-kernels/Cargo.toml | 13 --- crates/voxel-kernels/src/lib.rs | 136 ------------------------------- crates/voxel-kernels/src/main.rs | 92 --------------------- docs/research-lab.md | 3 - tests/test_lab.py | 2 +- 8 files changed, 3 insertions(+), 251 deletions(-) delete mode 100644 crates/voxel-kernels/Cargo.toml delete mode 100644 crates/voxel-kernels/src/lib.rs delete mode 100644 crates/voxel-kernels/src/main.rs diff --git a/AGENTS.md b/AGENTS.md index 943f2d0e4..a2af25cb4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -48,7 +48,7 @@ Game workspace (root `Cargo.toml`); `launcher/` and `crates/horizon-telemetry-se | `horizon-port-pack` | Porting Java modpacks ([docs/modpacks.md](docs/modpacks.md)) | | `horizon-theme` | Design tokens and fonts for the launcher, the game's own menus and the website | | `horizon-telemetry`, `horizon-telemetry-server`, `horizon-bench` | Opt-in data collection, its ingest server, the benchmark report format | -| `horizon-dualsense`, `horizon-threads`, `horizon-release-sign`, `horizon-bots`, `voxel-kernels`, `xtask` | DualSense output, thread priorities, signed release checksums, load-test bots, occupancy kernels, repo tasks | +| `horizon-dualsense`, `horizon-threads`, `horizon-release-sign`, `horizon-bots`, `xtask` | DualSense output, thread priorities, signed release checksums, load-test bots, repo tasks | | `launcher/` | GPUI launcher: `main.rs` (UI), `backend.rs` (installs, updates), `cli.rs`, `mcp.rs`, `*_page.rs` | Other top-level folders: `tools/` (harnesses and dev scripts), `tests/` (Python unit tests: `python3 -m diff --git a/Cargo.lock b/Cargo.lock index 1a1b288c9..550d3eb4b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3968,10 +3968,6 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" -[[package]] -name = "voxel-kernels" -version = "0.1.0" - [[package]] name = "walkdir" version = "2.5.0" diff --git a/Cargo.toml b/Cargo.toml index bc67ec748..7ffc68471 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] exclude = ["launcher", "crates/horizon-telemetry-server", "third_party/wgpu-hal"] -members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-shaderpack", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"] +members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-shaderpack", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"] resolver = "2" [workspace.package] diff --git a/crates/voxel-kernels/Cargo.toml b/crates/voxel-kernels/Cargo.toml deleted file mode 100644 index f4582e0d1..000000000 --- a/crates/voxel-kernels/Cargo.toml +++ /dev/null @@ -1,13 +0,0 @@ -[package] -name = "voxel-kernels" -version = "0.1.0" -edition.workspace = true -license.workspace = true -rust-version.workspace = true - -[[bin]] -name = "voxel-bench" -path = "src/main.rs" - -[lints] -workspace = true diff --git a/crates/voxel-kernels/src/lib.rs b/crates/voxel-kernels/src/lib.rs deleted file mode 100644 index caf72879f..000000000 --- a/crates/voxel-kernels/src/lib.rs +++ /dev/null @@ -1,136 +0,0 @@ -//! Original occupancy kernels for synthetic 16³ voxel sections. -//! A set bit means an opaque full cube; all neighbors outside the section are air. -//! This is not a Minecraft renderer or a model of partial/transparent blocks. - -pub const SIDE: usize = 16; - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Section { - rows: [u16; SIDE * SIDE], -} - -impl Default for Section { - fn default() -> Self { - Self { - rows: [0; SIDE * SIDE], - } - } -} - -impl Section { - pub fn from_fn(mut occupied: impl FnMut(usize, usize, usize) -> bool) -> Self { - let mut section = Self::default(); - for z in 0..SIDE { - for y in 0..SIDE { - for x in 0..SIDE { - if occupied(x, y, z) { - section.rows[z * SIDE + y] |= 1 << x; - } - } - } - } - section - } - - pub fn occupied(&self, x: usize, y: usize, z: usize) -> bool { - assert!(x < SIDE && y < SIDE && z < SIDE); - self.rows[z * SIDE + y] & (1 << x) != 0 - } - - /// Simple per-voxel reference. Count each opaque cube's exposed unit faces. - pub fn exposed_faces_scalar(&self) -> u32 { - let mut faces = 0; - for z in 0..SIDE { - for y in 0..SIDE { - for x in 0..SIDE { - if !self.occupied(x, y, z) { - continue; - } - faces += u32::from(x == 0 || !self.occupied(x - 1, y, z)); - faces += u32::from(x + 1 == SIDE || !self.occupied(x + 1, y, z)); - faces += u32::from(y == 0 || !self.occupied(x, y - 1, z)); - faces += u32::from(y + 1 == SIDE || !self.occupied(x, y + 1, z)); - faces += u32::from(z == 0 || !self.occupied(x, y, z - 1)); - faces += u32::from(z + 1 == SIDE || !self.occupied(x, y, z + 1)); - } - } - } - faces - } - - /// Evaluate sixteen voxels at once with row masks and population counts. - pub fn exposed_faces_bitset(&self) -> u32 { - let mut faces = 0; - for z in 0..SIDE { - for y in 0..SIDE { - let i = z * SIDE + y; - let row = self.rows[i]; - let below = if y == 0 { 0 } else { self.rows[i - 1] }; - let above = if y + 1 == SIDE { 0 } else { self.rows[i + 1] }; - let back = if z == 0 { 0 } else { self.rows[i - SIDE] }; - let front = if z + 1 == SIDE { - 0 - } else { - self.rows[i + SIDE] - }; - faces += (row & !(row << 1)).count_ones(); - faces += (row & !(row >> 1)).count_ones(); - faces += (row & !below).count_ones(); - faces += (row & !above).count_ones(); - faces += (row & !back).count_ones(); - faces += (row & !front).count_ones(); - } - } - faces - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn check(section: &Section, expected: u32) { - assert_eq!(section.exposed_faces_scalar(), expected); - assert_eq!(section.exposed_faces_bitset(), expected); - } - - #[test] - fn known_geometry() { - check(&Section::default(), 0); - check(&Section::from_fn(|_, _, _| true), 6 * 16 * 16); - check(&Section::from_fn(|x, y, z| x == 3 && y == 4 && z == 5), 6); - check(&Section::from_fn(|x, y, z| x < 2 && y == 4 && z == 5), 10); - check( - &Section::from_fn(|x, y, z| (x + y + z) % 2 == 0), - 4096 / 2 * 6, - ); - } - - #[test] - fn every_single_voxel_including_boundaries() { - for i in 0..SIDE.pow(3) { - let mut section = Section::default(); - section.rows[i / SIDE] = 1 << (i % SIDE); - check(§ion, 6); - } - } - - #[test] - fn random_occupancy_matches_reference_at_multiple_densities() { - let mut state = 0x1234_5678_9abc_def0_u64; - for threshold in [0, 1, 16, 64, 128, 192, 254, 255, 256] { - for _ in 0..32 { - let section = Section::from_fn(|_, _, _| { - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - (state & 255) < threshold - }); - assert_eq!( - section.exposed_faces_scalar(), - section.exposed_faces_bitset() - ); - } - } - } -} diff --git a/crates/voxel-kernels/src/main.rs b/crates/voxel-kernels/src/main.rs deleted file mode 100644 index e2443958b..000000000 --- a/crates/voxel-kernels/src/main.rs +++ /dev/null @@ -1,92 +0,0 @@ -use std::{hint::black_box, time::Instant}; -use voxel_kernels::Section; - -fn sample(corpus: &[Section], kernel: fn(&Section) -> u32, repeats: usize) -> f64 { - let start = Instant::now(); - let mut checksum = 0_u64; - for _ in 0..repeats { - for section in corpus { - checksum = checksum.wrapping_add(u64::from(kernel(black_box(section)))); - } - } - black_box(checksum); - start.elapsed().as_nanos() as f64 / (corpus.len() * repeats) as f64 -} - -fn median(samples: &mut [f64]) -> f64 { - samples.sort_by(f64::total_cmp); - samples[samples.len() / 2] -} - -fn main() { - let repeats: usize = match std::env::args().nth(1) { - None => 100, - Some(value) => match value.parse() { - Ok(n) if n > 0 => n, - _ => { - eprintln!("usage: voxel-bench [positive repeat count]"); - std::process::exit(2); - } - }, - }; - let mut rng = 0x7065_7273_6f6e_616c_u64; - let random = |rng: &mut u64| { - *rng ^= *rng << 13; - *rng ^= *rng >> 7; - *rng ^= *rng << 17; - *rng - }; - println!( - "workload,sections,samples,repeats,scalar_ns_per_section,bitset_ns_per_section,speedup" - ); - for workload in [ - "empty", - "solid", - "flat", - "checkerboard", - "random_10", - "random_50", - "random_90", - ] { - let corpus: Vec<_> = (0..32) - .map(|i| { - Section::from_fn(|x, y, z| match workload { - "empty" => false, - "solid" => true, - "flat" => y < 1 + i % 15, - "checkerboard" => (x + y + z + i) % 2 == 0, - "random_10" => random(&mut rng) % 100 < 10, - "random_50" => random(&mut rng) % 100 < 50, - "random_90" => random(&mut rng) % 100 < 90, - _ => unreachable!(), - }) - }) - .collect(); - for section in &corpus { - assert_eq!( - section.exposed_faces_scalar(), - section.exposed_faces_bitset() - ); - } - for kernel in [Section::exposed_faces_scalar, Section::exposed_faces_bitset] { - sample(&corpus, kernel, 10); - } - let mut scalar = Vec::new(); - let mut bitset = Vec::new(); - for trial in 0..21 { - if trial % 2 == 0 { - scalar.push(sample(&corpus, Section::exposed_faces_scalar, repeats)); - bitset.push(sample(&corpus, Section::exposed_faces_bitset, repeats)); - } else { - bitset.push(sample(&corpus, Section::exposed_faces_bitset, repeats)); - scalar.push(sample(&corpus, Section::exposed_faces_scalar, repeats)); - } - } - let scalar = median(&mut scalar); - let bitset = median(&mut bitset); - println!( - "{workload},32,21,{repeats},{scalar:.2},{bitset:.2},{:.2}", - scalar / bitset - ); - } -} diff --git a/docs/research-lab.md b/docs/research-lab.md index ae147364e..f7aa969d5 100644 --- a/docs/research-lab.md +++ b/docs/research-lab.md @@ -75,11 +75,8 @@ separate implementation. [Geometry and collision scope](collision-geometry.md). ```sh cargo test --workspace -cargo run --release --bin voxel-bench -- 100 > .local/voxel-benchmark.csv ``` -The dependency-free occupancy experiment compares scalar and bitset exposed-face counting for synthetic 16³ sections. It has no real mesh, material/AO/light work, neighboring-section context, JNI bridge or game integration. Speedups are kernel-only, not Minecraft FPS. - Public branding and new mod downloads use **Horizon**. The existing Fabric mod ID and `dev.horizonlab` namespace remain stable for installed instances and measurement compatibility. The installer backs up both old `horizon-lab-*.jar` diff --git a/tests/test_lab.py b/tests/test_lab.py index 648160ce1..f10a5fd55 100644 --- a/tests/test_lab.py +++ b/tests/test_lab.py @@ -172,7 +172,7 @@ class PublicationTests(unittest.TestCase): def test_private_paths_rejected(self): for path in [".local/minecraft/source.java", "decompiled/Foo.txt", "game.JAR", "capture.jfr", "source/Foo.java"]: self.assertTrue(check_public_tree.prohibited(path), path) - for path in ["tools/lab.py", "crates/voxel-kernels/src/lib.rs", "Cargo.lock", "docs/analysis.md", + for path in ["tools/lab.py", "crates/horizon-core/src/lib.rs", "Cargo.lock", "docs/analysis.md", "mods/horizon/src/main/java/dev/horizonlab/HorizonLab.java", "mods/horizon-lab/src/main/java/dev/horizonlab/HorizonLab.java"]: self.assertFalse(check_public_tree.prohibited(path), path) From 06ec15f3a00ca5135874eb5cc1bc79ba12f84905 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Sat, 24 Oct 2026 14:50:55 +0100 Subject: [PATCH 110/408] Retire the legacy Java optimization mod and performance packs Preserve Java parity oracles and comparison benchmark instrumentation. Move their remaining dependency locks under tools/benchmark-deps and remove legacy product packaging, fixtures, and CI checks. Co-Authored-By: OpenAI Codex gpt-6.1-sol --- .github/workflows/ci.yml | 96 +--- .../server-four-way-2026-10-19/README.md | 4 +- docs/README.md | 2 +- docs/architecture.md | 2 +- docs/benchmark.md | 2 +- docs/collectors.md | 48 -- docs/java-packs.md | 118 +---- docs/performance/java-perf-mods.md | 2 +- docs/process-memory.md | 53 --- docs/profiling.md | 16 +- docs/research/java-mod-compat.md | 7 +- docs/server.md | 2 +- docs/tick-state.md | 26 - docs/vulkan.md | 32 -- .../main/java/dev/horizonlab/HorizonLab.java | 78 --- .../dev/horizonlab/budget/DebounceWait.java | 14 - .../dev/horizonlab/budget/DispatchRetry.java | 14 - .../dev/horizonlab/budget/TerrainBudget.java | 38 -- .../horizonlab/budget/TerrainReadWait.java | 27 -- .../horizonlab/budget/WakeableIdleWait.java | 15 - .../dev/horizonlab/budget/WorkerPacer.java | 36 -- .../client/DistantTerrainBudget.java | 74 --- .../client/DistantTerrainSettings.java | 46 -- .../dev/horizonlab/client/HorizonClient.java | 212 --------- .../dev/horizonlab/client/ShaderSettings.java | 28 -- .../geometry/RelativeTerrainPosition.java | 30 -- .../metrics/ProcessMemoryMonitor.java | 53 --- .../dev/horizonlab/metrics/Recording.java | 159 ------- .../java/dev/horizonlab/metrics/Reports.java | 43 -- .../horizonlab/metrics/ResidentMemory.java | 20 - .../dev/horizonlab/metrics/SampleStats.java | 36 -- .../dev/horizonlab/metrics/ServerContext.java | 27 -- .../horizonlab/metrics/SoftwareContext.java | 21 - .../dev/horizonlab/metrics/TickState.java | 76 --- .../mixin/CullingEmptyWhitelistMixin.java | 19 - .../mixin/CullingRayScratchMixin.java | 28 -- .../horizonlab/mixin/DhDebounceWaitMixin.java | 77 --- .../mixin/DhPriorityDispatchMixin.java | 76 --- .../horizonlab/mixin/DhQuadReuseMixin.java | 31 -- .../mixin/DhRelativePositionMixin.java | 16 - .../mixin/DhTerrainReadWaitMixin.java | 18 - .../horizonlab/mixin/DhTickDedupMixin.java | 30 -- .../horizonlab/mixin/DhWorkerPacingMixin.java | 42 -- .../java/dev/horizonlab/mixin/FrameMixin.java | 16 - .../horizonlab/mixin/HorizonMixinPlugin.java | 193 -------- .../dev/horizonlab/mixin/ServerTickMixin.java | 25 - .../assets/horizonlab/lang/en_us.json | 3 - .../src/main/resources/fabric.mod.json | 29 -- .../src/main/resources/horizonlab.mixins.json | 24 - .../budget/DebounceQueueBenchmark.java | 50 -- .../horizonlab/budget/DebounceWaitTest.java | 30 -- .../horizonlab/budget/DispatchRetryTest.java | 23 - .../horizonlab/budget/IdleQueueBenchmark.java | 63 --- .../horizonlab/budget/TerrainBudgetTest.java | 30 -- .../budget/WakeableIdleWaitTest.java | 70 --- .../horizonlab/budget/WorkerPacerTest.java | 48 -- .../budget/WorkerPacingBenchmark.java | 64 --- .../client/DistantTerrainBudgetTest.java | 56 --- .../client/DistantTerrainSettingsTest.java | 59 --- .../dispatch/CullingEmptyIntegration.java | 100 ---- .../dispatch/CullingRayIntegration.java | 148 ------ .../dispatch/DispatchIntegration.java | 108 ----- .../dispatch/PositionIntegration.java | 121 ----- .../dispatch/QuadReuseIntegration.java | 99 ---- .../dispatch/QuadSizeIntegration.java | 31 -- .../dispatch/TerrainReadIntegration.java | 155 ------ .../dispatch/TickDedupIntegration.java | 87 ---- .../dispatch/fixture/CullingRayAccess.java | 16 - .../fixture/GraphicsBackendTraceMixin.java | 58 --- .../geometry/RelativeTerrainPositionTest.java | 52 -- .../metrics/ClientGraphicsIntegration.java | 155 ------ .../dev/horizonlab/metrics/MetricsTest.java | 102 ---- .../metrics/ObjectHeaderBenchmark.java | 59 --- .../horizonlab/metrics/ObjectSizeAgent.java | 7 - .../metrics/ResidentMemoryTest.java | 59 --- .../metrics/ServerGraphicsIntegration.java | 69 --- .../metrics/TickStateIntegration.java | 70 --- packs/Mac-Start.command | 32 -- packs/START-HERE.txt | 195 -------- packs/config/cinematic.toml | 18 - packs/config/far-distance.toml | 17 - packs/config/m2-balanced.toml | 18 - packs/config/vulkan.toml | 18 - packs/mods.lock.json | 323 ------------- tests/test_fixtures.py | 119 ----- tests/test_packs.py | 447 ------------------ tests/test_runtime.py | 48 ++ tools/Compare-Benchmarks.html | 299 ------------ tools/benchmark-deps/README.md | 10 + .../benchmark-deps}/fabric.lock.json | 0 tools/benchmark-deps/mods.lock.json | 134 ++++++ tools/build_mod.py | 268 ----------- tools/build_pack.py | 192 -------- tools/build_release.py | 42 -- tools/compare_benchmarks.py | 195 -------- tools/perf_bench.py | 8 +- tools/runtime.py | 103 +--- tools/server_bench.py | 8 +- tools/test_client_graphics.py | 198 -------- tools/test_culling_empty.py | 69 --- tools/test_culling_rays.py | 105 ---- tools/test_dispatch.py | 87 ---- tools/test_quad_reuse.py | 77 --- tools/test_quad_sizes.py | 99 ---- tools/test_server_graphics.py | 75 --- tools/test_terrain_position.py | 77 --- tools/test_terrain_read.py | 71 --- tools/test_tick_dedup.py | 68 --- 108 files changed, 232 insertions(+), 7261 deletions(-) delete mode 100644 docs/collectors.md delete mode 100644 docs/process-memory.md delete mode 100644 docs/tick-state.md delete mode 100644 docs/vulkan.md delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/HorizonLab.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/budget/DebounceWait.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/budget/DispatchRetry.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/budget/TerrainBudget.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/budget/TerrainReadWait.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/budget/WakeableIdleWait.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/budget/WorkerPacer.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/client/DistantTerrainBudget.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/client/DistantTerrainSettings.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/client/HorizonClient.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/client/ShaderSettings.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/geometry/RelativeTerrainPosition.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/metrics/ProcessMemoryMonitor.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/metrics/Recording.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/metrics/Reports.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/metrics/ResidentMemory.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/metrics/SampleStats.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/metrics/ServerContext.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/metrics/SoftwareContext.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/metrics/TickState.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/mixin/CullingEmptyWhitelistMixin.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/mixin/CullingRayScratchMixin.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/mixin/DhDebounceWaitMixin.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/mixin/DhPriorityDispatchMixin.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/mixin/DhQuadReuseMixin.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/mixin/DhRelativePositionMixin.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/mixin/DhTerrainReadWaitMixin.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/mixin/DhTickDedupMixin.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/mixin/DhWorkerPacingMixin.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/mixin/FrameMixin.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/mixin/HorizonMixinPlugin.java delete mode 100644 mods/horizon/src/main/java/dev/horizonlab/mixin/ServerTickMixin.java delete mode 100644 mods/horizon/src/main/resources/assets/horizonlab/lang/en_us.json delete mode 100644 mods/horizon/src/main/resources/fabric.mod.json delete mode 100644 mods/horizon/src/main/resources/horizonlab.mixins.json delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/budget/DebounceQueueBenchmark.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/budget/DebounceWaitTest.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/budget/DispatchRetryTest.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/budget/IdleQueueBenchmark.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/budget/TerrainBudgetTest.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/budget/WakeableIdleWaitTest.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/budget/WorkerPacerTest.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/budget/WorkerPacingBenchmark.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/client/DistantTerrainBudgetTest.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/client/DistantTerrainSettingsTest.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/dispatch/CullingEmptyIntegration.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/dispatch/CullingRayIntegration.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/dispatch/DispatchIntegration.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/dispatch/PositionIntegration.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/dispatch/QuadReuseIntegration.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/dispatch/QuadSizeIntegration.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/dispatch/TerrainReadIntegration.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/dispatch/TickDedupIntegration.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/dispatch/fixture/CullingRayAccess.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/dispatch/fixture/GraphicsBackendTraceMixin.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/geometry/RelativeTerrainPositionTest.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/metrics/ClientGraphicsIntegration.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/metrics/MetricsTest.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/metrics/ObjectHeaderBenchmark.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/metrics/ObjectSizeAgent.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/metrics/ResidentMemoryTest.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/metrics/ServerGraphicsIntegration.java delete mode 100644 mods/horizon/src/test/java/dev/horizonlab/metrics/TickStateIntegration.java delete mode 100644 packs/Mac-Start.command delete mode 100644 packs/START-HERE.txt delete mode 100644 packs/config/cinematic.toml delete mode 100644 packs/config/far-distance.toml delete mode 100644 packs/config/m2-balanced.toml delete mode 100644 packs/config/vulkan.toml delete mode 100644 packs/mods.lock.json delete mode 100644 tests/test_fixtures.py delete mode 100644 tests/test_packs.py create mode 100644 tests/test_runtime.py delete mode 100644 tools/Compare-Benchmarks.html create mode 100644 tools/benchmark-deps/README.md rename {packs => tools/benchmark-deps}/fabric.lock.json (100%) create mode 100644 tools/benchmark-deps/mods.lock.json delete mode 100644 tools/build_mod.py delete mode 100644 tools/build_pack.py delete mode 100644 tools/build_release.py delete mode 100644 tools/compare_benchmarks.py delete mode 100644 tools/test_client_graphics.py delete mode 100644 tools/test_culling_empty.py delete mode 100644 tools/test_culling_rays.py delete mode 100644 tools/test_dispatch.py delete mode 100644 tools/test_quad_reuse.py delete mode 100644 tools/test_quad_sizes.py delete mode 100644 tools/test_server_graphics.py delete mode 100644 tools/test_terrain_position.py delete mode 100644 tools/test_terrain_read.py delete mode 100644 tools/test_tick_dedup.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1dfd43300..98d5b9093 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -430,7 +430,7 @@ jobs: env: RUSTUP_TOOLCHAIN: stable run: python tools/test_float_log_parity.py - portable-mod: + jfr-analysis: if: github.event_name == 'workflow_dispatch' runs-on: [self-hosted, linux, horizon-game] steps: @@ -442,101 +442,7 @@ jobs: with: distribution: temurin java-version: '25' - - name: Compile original mod and test metrics - run: python tools/build_mod.py - name: Verify streaming JFR analysis against the JDK exporter run: python tools/test_jfr.py - name: Verify ZGC pause and allocation event interpretation run: python tools/test_jfr.py --gc zgc - - name: Build pinned portable packs - run: python tools/build_pack.py - - name: Measure isolated worker pacing on this platform - run: python -c "from tools.build_mod import benchmark_workers; benchmark_workers()" - - name: Measure isolated debounce queue polling - run: python -c "from tools.build_mod import benchmark_debounce; benchmark_debounce()" - - name: Measure wakeable idle queue latency - run: python -c "from tools.build_mod import benchmark_idle; benchmark_idle()" - - name: Measure object allocations with compact headers off and on - run: python -c "from tools.build_mod import benchmark_headers; benchmark_headers()" - - name: Test pack integrity and comparisons - run: python -m unittest discover -s tests -v - - name: Start recommended OpenGL macOS clients and verify framebuffer readback - if: runner.os == 'macOS' - run: | - python tools/test_client_graphics.py --native-display - cp dist/client-graphics-smoke.json dist/client-graphics-macos-title.json - python tools/test_client_graphics.py --native-display --world - cp dist/client-graphics-smoke.json dist/client-graphics-macos-world.json - - name: Compile the private dispatch fixture - run: python -c "from tools.build_mod import build_dispatch_fixture; build_dispatch_fixture()" - - name: Compile the private integrated-server graphics fixture - run: python -c "from tools.build_mod import build_integration_fixture; build_integration_fixture('server-graphics', 'dev.horizonlab.metrics.ServerGraphicsIntegration', fixture_dependencies={})" - - name: Compile the private tick-manager state fixture - run: python -c "from tools.build_mod import build_integration_fixture; build_integration_fixture('tick-state', 'dev.horizonlab.metrics.TickStateIntegration')" - - name: Compile the private terrain tick membership fixture - run: python -c "from tools.build_mod import build_tick_dedup_fixture; build_tick_dedup_fixture()" - - name: Compile the private culling whitelist fixture - run: python -c "from tools.build_mod import build_culling_empty_fixture; build_culling_empty_fixture()" - - name: Compile the private culling ray geometry fixture - run: python -c "from tools.build_mod import build_integration_fixture; build_integration_fixture('culling-rays', 'dev.horizonlab.dispatch.CullingRayIntegration', ['entityculling'], ['CullingRayAccess'])" - - name: Compile the private terrain position lookup fixture - run: python -c "from tools.build_mod import build_integration_fixture; build_integration_fixture('terrain-position', 'dev.horizonlab.dispatch.PositionIntegration')" - - name: Compile the private terrain quad reuse fixture - run: python -c "from tools.build_mod import build_integration_fixture; build_integration_fixture('quad-reuse', 'dev.horizonlab.dispatch.QuadReuseIntegration')" - - name: Compile the private object-size agent and terrain quad fixture - run: python -c "from tools.test_quad_sizes import build_agent; from tools.build_mod import build_integration_fixture; build_agent(); build_integration_fixture('quad-size', 'dev.horizonlab.dispatch.QuadSizeIntegration')" - - name: Compile the private terrain read shutdown fixture - run: python -c "from tools.build_mod import build_integration_fixture; build_integration_fixture('terrain-read', 'dev.horizonlab.dispatch.TerrainReadIntegration')" - - name: Install headless graphics libraries for applied-hook checks - if: runner.os == 'Linux' - run: sudo apt-get update && sudo apt-get install -y xvfb libgl1 libegl1 libvulkan1 mesa-vulkan-drivers libasound2t64 libxkbcommon0 - - name: Verify integrated-server graphics report against the actual device - run: python tools/test_server_graphics.py ${{ runner.os == 'macOS' && '--native-display' || '' }} - - name: Exercise the applied dispatcher hooks and upstream rejection path - if: runner.os == 'Linux' - run: python tools/test_dispatch.py - - name: Verify applied tick membership transitions and allocation - if: runner.os == 'Linux' - run: python tools/test_tick_dedup.py - - name: Verify live culling whitelist registration and empty iteration - if: runner.os == 'Linux' - run: python tools/test_culling_empty.py - - name: Compare applied culling ray geometry and provider queries - if: runner.os == 'Linux' - run: python tools/test_culling_rays.py - - name: Verify actual full-data position lookup equivalence - if: runner.os == 'Linux' - run: python tools/test_terrain_position.py - - name: Verify actual terrain quad geometry and allocation - if: runner.os == 'Linux' - run: python tools/test_quad_reuse.py - - name: Measure actual builder and quad shallow sizes in both header modes - if: runner.os == 'Linux' - run: python tools/test_quad_sizes.py - - name: Verify interrupted DH reads and preserved shared futures - if: runner.os == 'Linux' - run: python tools/test_terrain_read.py - - name: Upload original mod and pack manifests only - uses: actions/upload-artifact@v4 - with: - name: horizon-linux - path: | - dist/*.mrpack - dist/horizon-*.jar - dist/worker-pacing-benchmark.txt - dist/debounce-queue-benchmark.txt - dist/idle-queue-benchmark.txt - dist/object-header-benchmark.txt - dist/dispatch-integration.json - dist/tick-dedup-integration.json - dist/culling-empty-integration.json - dist/terrain-read-integration.json - dist/culling-rays-integration.json - dist/terrain-position-integration.json - dist/quad-reuse-integration.json - dist/quad-size-integration.json - dist/server-graphics-smoke.json - dist/client-graphics-smoke.json - dist/client-graphics-macos-title.json - dist/client-graphics-macos-world.json - retention-days: 3 diff --git a/benchmarks/server-four-way-2026-10-19/README.md b/benchmarks/server-four-way-2026-10-19/README.md index 570f5bb24..7048c2743 100644 --- a/benchmarks/server-four-way-2026-10-19/README.md +++ b/benchmarks/server-four-way-2026-10-19/README.md @@ -131,8 +131,8 @@ average) and reached the ThinkPad over the tailnet. It ran with Paper's defaults except `connection-throttle: -1` in `bukkit.yml`. Every bot connects from one address, and the default throttle (4 s) refused all but the first. Paperclip patched the pinned server jar from its cache. Same Java and heap. -- Fabric + Lithium: the pinned server jar on Fabric loader 0.19.5 (`packs/fabric.lock.json`) with Lithium - `mc26.3-0.26.2-fabric` (`packs/mods.lock.json`, checked against its SHA-512). Lithium needs no Fabric API. +- Fabric + Lithium: the pinned server jar on Fabric loader 0.19.5 (`tools/benchmark-deps/fabric.lock.json`) with Lithium + `mc26.3-0.26.2-fabric` (`tools/benchmark-deps/mods.lock.json`, checked against its SHA-512). Lithium needs no Fabric API. Same Java and heap. The Paper and Fabric jars are dev-only downloads into `.local/server-bench/jars` and are never committed or diff --git a/docs/README.md b/docs/README.md index 2e06b6e89..b93177528 100644 --- a/docs/README.md +++ b/docs/README.md @@ -48,4 +48,4 @@ To play, use [the launcher](../launcher/README.md); the project site is [playhor ## The earlier Java track (no longer developed) -- [Java performance packs](java-packs.md), with [Vulkan on your Mac](vulkan.md), [collector comparisons](collectors.md), [profiling](profiling.md), [process memory](process-memory.md) and [tick state](tick-state.md). The Fabric server starter is retired: [host a server](hosting.md) with horizon-server. +- [Retired Java performance packs](java-packs.md); [JFR analysis for Java comparisons](profiling.md). diff --git a/docs/architecture.md b/docs/architecture.md index 99e9b630e..29e98f2e6 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -27,7 +27,7 @@ file selects ~103. | 10 | Launcher (124) | `launcher/src/` (`main.rs`, `backend.rs`, `cli.rs`, `mcp.rs`, `servers_page.rs`) | `cd launcher && cargo test`; `python3 tools/launcher_mcp_e2e.py` | | 11 | Mob types and species (117) | `L/mobs.rs`, `L/mobs/species.rs`, `L/mobs/data.rs`, `L/mobs/living.rs`, `L/mobs/drops.rs`, `L/mobs/gear.rs` | mob_attributes, entity_attribute, entity_death_loot, mob_ai | | 12 | Guests' actions on a server (98) | `G/lan_actions.rs` (`fn as_guest`, `fn tick_guests`), `G/lan_{attributes,pvp,chat,crafting,stations,trading,mount_menu,waypoints}.rs` | server_player_combat, server_player_damage, server_player_targets, lan_e2e (all) | -| 13 | Modpack porting, mod content (97) | `crates/horizon-port-pack/`, `L/mod_content.rs`, `tools/port_*.py`, `packs/` | `cargo test -p horizon-port-pack`; `python3 tools/mod_port_harness.py` | +| 13 | Modpack porting, mod content (97) | `crates/horizon-port-pack/`, `L/mod_content.rs`, `tools/port_*.py` | `cargo test -p horizon-port-pack`; `python3 tools/mod_port_harness.py` | | 14 | Mob AI (96) | `L/mobs/ai.rs`, `goals.rs`, `brain.rs`, `*_brain.rs`, `nav.rs`, `path.rs`, `control.rs` | mob_ai (probe `examples/mob_ai_probe.rs`; known failure on main: drowned_*, #290) | | 15 | Items and item use (96) | `L/items.rs`, `L/item_data.rs`, `G/hand.rs`, `G/consume.rs`, `G/potions.rs`, `L/effects.rs`; game.rs `fn use_hand`, `fn use_item` | use_item_on, item_use, item_use_lifecycle, consumable, consume_effect, status_effect | | 16 | Options and settings screens (93) | `L/options_ui.rs`, `G/options.rs`, `L/settings.rs`, `L/options_file.rs`, `L/graphics_ui.rs`, `L/graphics.rs` | options, toggle_keys | diff --git a/docs/benchmark.md b/docs/benchmark.md index 8bcc432e0..ca6c12e11 100644 --- a/docs/benchmark.md +++ b/docs/benchmark.md @@ -21,7 +21,7 @@ One game is started per window size (1280x720 and 1920x1080 by default) and rend - **Warm-up excluded.** Each scene's flight starts only after its chunks are loaded and drawn and 2 seconds have passed; the load itself is reported separately. JIT warm-up of the JVM during the first scene is part of vanilla's real behaviour and is not removed. - **The same statistics code.** Horizon returns its raw frame times (`horizon-ctl fly ... raw`) and the vanilla mod writes its own; `stats()` in the driver computes every figure for both. - **Vanilla as players run it.** Your own 26.3 client jar and libraries (as the official launcher installs them for your OS), the official launcher's default JVM arguments (`-Xmx2G` and its G1 options), Java 25. The game's assets index is not used, so neither game plays sound (Horizon runs with `HORIZON_NO_AUDIO=1`, vanilla with OpenAL's null device); textures, models and shaders come from the client jar as usual. -- **Performance mods.** `--game vanilla-mods` adds the Fabric builds for 26.3 of Sodium, Lithium, FerriteCore and ImmediatelyFast, the versions pinned with their hashes in `packs/mods.lock.json` (downloaded from Modrinth, never committed), plus Fabric API if one of them needs it. +- **Performance mods.** `--game vanilla-mods` adds the Fabric builds for 26.3 of Sodium, Lithium, FerriteCore and ImmediatelyFast, the versions pinned with their hashes in `tools/benchmark-deps/mods.lock.json` (downloaded from Modrinth, never committed), plus Fabric API if one of them needs it. ## Known caveats diff --git a/docs/collectors.md b/docs/collectors.md deleted file mode 100644 index 98b497328..000000000 --- a/docs/collectors.md +++ /dev/null @@ -1,48 +0,0 @@ -# Compare Java collectors - -Use the balanced pack first with the launcher's existing JVM policy. Java 25 -HotSpot supports explicit G1 (`-XX:+UseG1GC`) and ZGC (`-XX:+UseZGC`) selections; -the [Java command reference](https://docs.oracle.com/en/java/javase/25/docs/specs/man/java.html) -documents both. A collector choice can change CPU, heap headroom, collection -behavior and frame pacing. Lower pauses alone do not establish lower RAM or -higher FPS. The packs do not automatically select a collector. - -For a Mac comparison, duplicate one instance. In Edit > Settings > Java, enable -the Java Arguments override checkbox. Preserve existing non-collector arguments, -but use exactly one collector selector in each instance. Choose G1 in one and -ZGC in the other. Use the same native Java 25 ARM64, maximum/minimum heap, compact -header setting, world copy, resolution, shaders, distances and warmed camera route. -Alternate at least three 120-second runs rather than comparing unrelated captures. -Remove the explicit selector to restore the launcher's policy, then restart. - -The viewer shows the actual collector names captured by the game. Check them: -setting a launcher's text field does not establish which flags reached the VM. -Prism's per-instance Java Arguments and Memory settings have separate override -checkboxes. A global collector selection may need removal or replacement when -creating an explicit per-instance experiment. - -Record FPS, slowest-1% rate, frame spikes, heap and process RSS together. RSS does -not represent all shared GPU memory on Apple Silicon. `gc_time_ms` sums collector -MXBean counters; concurrent cycles and overlapping phases can contribute, so it -is not a measured pause total. Use JFR root pause events for pause analysis. -The streaming reader is checked against the JDK's event exporter with both -default-GC and ZGC fixtures in CI on Windows, Linux and ARM macOS. - -The developer demo launcher accepts `--gc default`, `--gc g1` or `--gc zgc`. -For example: - -```sh -python3 tools/runtime.py demo --instance .local/runtime/collector-test --heap 6G --gc zgc --compact-headers -python3 tools/test_jfr.py --gc zgc -``` - -Prepare demo mods/worlds before comparing. -Options affect only the launched process; they do not change global Java settings. -The collector and compact-header experiments can be tested independently. - -A local 3 GiB, compact-header ZGC client completed a 120-second game recording. -That recording also encountered a distant-terrain rejection storm. Its workload -and cache history differed from G1 captures, so the larger memory footprint and -different frame rate cannot be attributed to the collector alone. The dispatcher -experiment addresses the identified retry loop separately. No M2 collector -performance winner is established. diff --git a/docs/java-packs.md b/docs/java-packs.md index 66ee402d3..36e76faf9 100644 --- a/docs/java-packs.md +++ b/docs/java-packs.md @@ -1,109 +1,15 @@ -# Java performance packs (no longer developed) +# Retired Java performance packs -Before the Rust rewrite, Horizon was a lab for Minecraft Java client performance: pinned Fabric performance packs, distant terrain, an original frame and tick recorder, and client and server starter downloads (the server starter is gone: [horizon-server](hosting.md) replaces it). This track is **no longer developed**. No release downloads are published; build the packs and starters locally with `python3 tools/build_release.py` (see [Build and run](#build-and-run)). This page keeps its documentation. +Before the Rust rewrite, Horizon shipped a Fabric optimization mod, performance pack profiles +and a Prism Launcher Mac starter. That product is retired. Its patches, profiles, builders, +starter, benchmark viewer and product-specific checks have been removed; use Git history +for the former implementation. Horizon's Rust game does not use those Java patches. -## Java packs: Mac starter (out of scope) - -Build **horizon-mac-starter-0.21.0.zip** with `python3 tools/build_release.py` (it lands in `dist/`), extract it and open `Mac-Start.command`. It verifies and installs official universal Prism Launcher in `~/Applications` if needed, then opens the balanced pack import. Sign into Microsoft **inside Prism yourself**. This project needs no credentials. - -Use native **Java 25 ARM64**, maximum heap **6144 MiB**, minimum **512 MiB** on a 16 GB M2 Pro Mac. Prism can download Java automatically. Start at 1280×800 or 1920×1200; full Retina resolution is a larger GPU workload. [START-HERE.txt](../packs/START-HERE.txt) has details. The same `.mrpack` files import into Prism on Windows and Linux. - -Core and balanced passed macOS title and demo-world rendering probes on the hosted -ARM64 software renderer, including readback, saves and clean exits. Physical M2 -GPU performance and macOS 27 were never tested. - -| Profile | Full-detail chunks | Distant LOD radius | Suggested maximum heap | -| --- | ---: | ---: | ---: | -| baseline | 12 | none | 6144 MiB | -| core-performance | 12 | none | 6144 MiB | -| m2-balanced | 12 | 128 | 6144 MiB | -| adaptive (experiment) | 12 | 128 | 6144 MiB | -| worker-pacing (experiment) | 12 | 128 | 6144 MiB | -| adaptive-pacing (experiment) | 12 | 128 | 6144 MiB | -| queue-wait (experimental) | 12 | 128 | 6144 MiB | -| adaptive-queue (experimental) | 12 | 128 | 6144 MiB | -| dispatch-retry (experimental) | 12 | 128 | 6144 MiB | -| tick-dedup (experimental) | 12 | 128 | 6144 MiB | -| culling-empty (experimental) | 12 | 128 | 6144 MiB | -| quad-reuse (experimental) | 12 | 128 | 6144 MiB | -| terrain-position (experimental) | 12 | 128 | 6144 MiB | -| culling-rays (experimental) | 12 | 128 | 6144 MiB | -| foreground-first (combined experiment) | 12 | 128 | 6144 MiB | -| foreground-vulkan (combined experiment) | 12 | 128 | 6144 MiB | -| low-memory | 8 | none | 3072 MiB | -| far-distance | 12 | 256 | 8192 MiB, with sufficient physical RAM | -| cinematic | 12 | 128 | 6144 MiB | -| vulkan | 12 | 128 | 6144 MiB | - -Balanced combines [Sodium](https://modrinth.com/mod/sodium), [Lithium](https://modrinth.com/mod/lithium), [FerriteCore](https://modrinth.com/mod/ferrite-core), [ImmediatelyFast](https://modrinth.com/mod/immediatelyfast), [EntityCulling](https://modrinth.com/mod/entityculling), and [Distant Horizons](https://modrinth.com/mod/distanthorizons). Cinematic adds [Iris](https://modrinth.com/mod/iris) and [Complementary Reimagined](https://modrinth.com/shader/complementary-reimagined), initially disabled. Vulkan independently experiments with the game's own backend and fallback, without Iris. - -Distant LOD is simplified terrain. Nearby blocks retain full detail. Initial generation costs CPU/disk/memory and needs warm-up. DH adjusts clouds, chunk fade and transparency to blend its renderer; assess appearance as well as speed. Shaders cost GPU time and have [Mac-specific limits](https://shaders.properties/current/reference/miscellaneous/macos/). Universal CPU/GPU support and exact vanilla equivalence remain validation goals. Simulation distance stays 12 in every profile; normal 20 TPS rules are retained. - -For the first comparison at the same view distance, use `baseline` versus -`core-performance`: both select 12 full-detail chunks and no distant LOD or shaders. -The latter adds only the pinned core performance mods and leaves every original -controller disabled. Then test balanced separately for its additional distant -terrain. Matching captured settings does not prove pixel-identical rendering. - -The profiles marked *experiment* each isolate one change to Distant Horizons, -EntityCulling or the JVM (adaptive terrain throttling, precise worker pacing, -debounce-queue waits, rejected-dispatch retries, empty culling whitelists, -culling ray scratch vectors, terrain quad reuse, terrain position arithmetic, -tick membership storage, a smaller heap, compact object headers). Each kept the -upstream behaviour it replaced and was measured only on Linux software rendering, -where none showed a gain large enough to enable by default; balanced keeps them -all off. Their write-ups were removed once the Rust rewrite replaced this track; -they remain in Git history. Matched software-rendered pairs showed `core-performance` -14–21% faster than `baseline`, and Vulkan about 1.5% more FPS for about 12% more -CPU; neither is evidence for a Mac GPU. - -To try the game's own Vulkan backend on a Mac, see [Vulkan on your Mac](vulkan.md); -to compare garbage collectors, see [collector comparisons](collectors.md). - -## Measure on your hardware - -Press **F8** during gameplay to start a 120-second recording, or again to stop early. Rebind in Controls if needed. This also works with restricted chat accounts. Alternatively: `/horizon bench