From 62fe8a4465d0461d19f1d2fc5f6457a763f05333 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 03:49:13 +0200 Subject: [PATCH 1/3] Add item model definitions, baking and parity harness (WIP) Work in progress on vanilla's item model pipeline in horizon-assets: definition parsing, resolution, generated model baking, special renderers and a differential harness against a Java oracle. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 1 + crates/horizon-assets/Cargo.toml | 3 + .../examples/item_model_fixture.rs | 351 ++++ crates/horizon-assets/src/bake.rs | 34 + crates/horizon-assets/src/item_bake.rs | 299 +++ crates/horizon-assets/src/item_model.rs | 1685 +++++++++++++++++ .../horizon-assets/src/item_model/special.rs | 254 +++ crates/horizon-assets/src/item_model/tests.rs | 1 + crates/horizon-assets/src/lib.rs | 3 + crates/horizon-assets/src/math.rs | 140 ++ crates/horizon-assets/src/resolve.rs | 35 + .../parity/VanillaItemModelOracle.java | 407 ++++ tools/test_item_model_parity.py | 380 ++++ 13 files changed, 3593 insertions(+) create mode 100644 crates/horizon-assets/examples/item_model_fixture.rs create mode 100644 crates/horizon-assets/src/item_bake.rs create mode 100644 crates/horizon-assets/src/item_model.rs create mode 100644 crates/horizon-assets/src/item_model/special.rs create mode 100644 crates/horizon-assets/src/item_model/tests.rs create mode 100644 crates/horizon-assets/src/math.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemModelOracle.java create mode 100644 tools/test_item_model_parity.py diff --git a/Cargo.lock b/Cargo.lock index 8225fdd42..5a8da580f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -672,6 +672,7 @@ name = "horizon-assets" version = "0.1.0" dependencies = [ "horizon-core", + "png", "serde", "serde_json", ] diff --git a/crates/horizon-assets/Cargo.toml b/crates/horizon-assets/Cargo.toml index 1550a1564..892ea0972 100644 --- a/crates/horizon-assets/Cargo.toml +++ b/crates/horizon-assets/Cargo.toml @@ -13,3 +13,6 @@ serde_json = { version = "1.0.151", features = ["raw_value"] } [lints] workspace = true + +[dev-dependencies] +png = "0.18" diff --git a/crates/horizon-assets/examples/item_model_fixture.rs b/crates/horizon-assets/examples/item_model_fixture.rs new file mode 100644 index 000000000..1729abf4c --- /dev/null +++ b/crates/horizon-assets/examples/item_model_fixture.rs @@ -0,0 +1,351 @@ +//! Resolve item stacks into render layers for the differential harness +//! `tools/test_item_model_parity.py`. +use horizon_assets::{ + animation::AnimationMetadata, + item_bake::{BakedItemModel, SpriteLookup, SpriteMask, bake_item_model}, + item_model::*, + math::Mat4, + model::{CuboidModel, Direction}, + resolve::{MISSING_MODEL, ModelLibrary}, +}; +use serde_json::{Value, json}; +use std::{ + cell::RefCell, + collections::BTreeMap, + fs::{self, File}, + io::{BufRead, BufReader, BufWriter, Write}, + path::{Path, PathBuf}, +}; + +fn bits(v: f32) -> u32 { + if v.is_nan() { 0x7fc0_0000 } else { v.to_bits() } +} + +struct Sprites { + root: PathBuf, + cache: RefCell>>, +} +impl SpriteLookup for Sprites { + fn mask(&self, sprite: &str) -> Option { + if let Some(hit) = self.cache.borrow().get(sprite) { + return hit.clone(); + } + let mask = self.load(sprite); + self.cache.borrow_mut().insert(sprite.to_owned(), mask.clone()); + mask + } +} +impl Sprites { + fn load(&self, sprite: &str) -> Option { + let (namespace, path) = sprite.split_once(':')?; + let png = self + .root + .join(format!("assets/{namespace}/textures/{path}.png")); + let mut decoder = png::Decoder::new(BufReader::new(File::open(&png).ok()?)); + decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16); + let mut reader = decoder.read_info().ok()?; + let mut bytes = vec![0; reader.output_buffer_size()?]; + let info = reader.next_frame(&mut bytes).ok()?; + let channels = info.color_type.samples(); + let alpha = |pixel: &[u8]| match info.color_type { + png::ColorType::Rgba => pixel[3], + png::ColorType::GrayscaleAlpha => pixel[1], + _ => 255, + }; + let (iw, ih) = (info.width as usize, info.height as usize); + let pixels: Vec = bytes[..info.buffer_size()] + .chunks_exact(channels) + .map(alpha) + .collect(); + let meta = fs::read_to_string(png.with_extension("png.mcmeta")).ok(); + let animation = meta + .and_then(|m| serde_json::from_str::(&m).ok()) + .and_then(|m| m.get("animation").map(|a| a.to_string())) + .and_then(|a| AnimationMetadata::from_json(&a).ok()); + let (w, h) = match &animation { + Some(a) => { + let [w, h] = a.frame_size(iw as i32, ih as i32); + (w as usize, h as usize) + } + None => (iw, ih), + }; + let columns = iw / w; + let total = columns * (ih / h); + let clip = animation.and_then(|a| a.clip(total as u32).ok().flatten()); + let frame_indices: Vec = match clip { + Some(clip) => { + let mut unique = Vec::new(); + for (index, _) in clip.sequence() { + if !unique.contains(&(*index as usize)) { + unique.push(*index as usize); + } + } + unique + } + None => vec![0], + }; + let frames = frame_indices + .into_iter() + .map(|f| { + let (fx, fy) = (f % columns * w, f / columns * h); + (0..h) + .flat_map(|y| (0..w).map(move |x| (x, y))) + .map(|(x, y)| pixels[(fy + y) * iw + fx + x] == 0) + .collect() + }) + .collect(); + Some(SpriteMask { + width: w, + height: h, + frames, + }) + } +} + +struct Env { + grass: Vec, + local_time: String, + bundle_weight: bool, + prototypes: BTreeMap, +} +impl ItemEnv for Env { + fn grass_color(&self, temperature: f64, downfall: f64) -> i32 { + let rain = downfall * temperature; + let x = ((1.0 - temperature) * 255.0) as i64; + let y = ((1.0 - rain) * 255.0) as i64; + let index = (y << 8 | x) as usize; + self.grass.get(index).copied().unwrap_or(-65281) + } + fn local_time(&self, _: &str, _: &str, _: Option<&str>) -> String { + self.local_time.clone() + } + fn bundle_fullness(&self, stack: &StackView, components: &Components) -> f32 { + // Sum of count / max stack size over the contents, as a double fraction. + let Some(items) = components + .get("minecraft:bundle_contents") + .and_then(Value::as_array) + else { + return 0.0; + }; + let _ = (stack, self.bundle_weight); + let mut total = 0.0f64; + for item in items { + let id = item["id"].as_str().unwrap_or(""); + let count = item["count"].as_i64().unwrap_or(1) as f64; + let max = self + .prototypes + .get(id) + .and_then(|c| c.get("minecraft:max_stack_size")) + .and_then(Value::as_i64) + .unwrap_or(1) as f64; + total += count / max; + } + total as f32 + } +} + +fn main() -> Result<(), Box> { + let args: Vec<_> = std::env::args().collect(); + let root = PathBuf::from(&args[1]); + let prototypes_path = &args[2]; + let mut output = BufWriter::new(File::create(&args[4])?); + + let raw: BTreeMap = + serde_json::from_slice(&fs::read(prototypes_path)?)?; + let mut models = ItemModels { + prototypes: raw, + ..Default::default() + }; + writeln!(output, "{}", json!({"row":"components","names":DATA_COMPONENT_TYPES.to_vec()}))?; + let items_dir = root.join("assets/minecraft/items"); + let mut files: Vec<_> = fs::read_dir(&items_dir)?.collect::>()?; + files.sort_by_key(|f| f.file_name()); + for file in files { + let name = file.file_name().to_string_lossy().into_owned(); + let id = format!("minecraft:{}", name.trim_end_matches(".json")); + let ok = match ClientItem::from_json(&fs::read_to_string(file.path())?) { + Ok(item) => { + models.definitions.insert(id, item); + true + } + Err(_) => false, + }; + writeln!(output, "{}", json!({"row":"decode","name":name,"ok":ok}))?; + } + for line in BufReader::new(File::open(format!("{}.definitions", args[3]))?).lines() { + let row: Value = serde_json::from_str(&line?)?; + let name = row["name"].as_str().unwrap(); + let ok = match ClientItem::from_json(row["json"].as_str().unwrap()) { + Ok(item) => { + models + .definitions + .insert(horizon_assets::item_model::identifier(name)?, item); + true + } + Err(_) => false, + }; + writeln!(output, "{}", json!({"row":"decode","name":name,"ok":ok}))?; + } + + let mut cuboids = BTreeMap::new(); + let models_dir = root.join("assets/minecraft/models"); + let mut stack = vec![models_dir.clone()]; + while let Some(dir) = stack.pop() { + for entry in fs::read_dir(&dir)? { + let path = entry?.path(); + if path.is_dir() { + stack.push(path); + } else if path.extension().is_some_and(|e| e == "json") { + let relative = path.strip_prefix(&models_dir)?.with_extension(""); + let id = format!( + "minecraft:{}", + relative.to_string_lossy().replace('\\', "/") + ); + if let Ok(model) = CuboidModel::from_json(&fs::read_to_string(&path)?) { + cuboids.insert(id, model); + } + } + } + } + let library = ModelLibrary::with_item_generator(cuboids)?; + let sprites = Sprites { + root: root.clone(), + cache: RefCell::default(), + }; + let grass = { + let mut decoder = png::Decoder::new(BufReader::new(File::open( + root.join("assets/minecraft/textures/colormap/grass.png"), + )?)); + decoder.set_transformations(png::Transformations::EXPAND); + let mut reader = decoder.read_info()?; + let mut bytes = vec![0; reader.output_buffer_size().unwrap()]; + let info = reader.next_frame(&mut bytes)?; + let channels = info.color_type.samples(); + bytes[..info.buffer_size()] + .chunks_exact(channels) + .map(|p| { + let a = if channels == 4 { p[3] } else { 255 }; + i32::from_be_bytes([a, p[0], p[1], p[2]]) + }) + .collect() + }; + let mut env = Env { + grass, + local_time: String::new(), + bundle_weight: true, + prototypes: models.prototypes.clone(), + }; + let mut baked_cache: BTreeMap = BTreeMap::new(); + let mut bake = |name: &str| -> BakedItemModel { + baked_cache + .entry(name.to_owned()) + .or_insert_with(|| { + bake_item_model(&library, &sprites, name) + .or_else(|_| bake_item_model(&library, &sprites, MISSING_MODEL)) + .expect("missing model bakes") + }) + .clone() + }; + + for line in BufReader::new(File::open(&args[3])?).lines() { + let row: Value = serde_json::from_str(&line?)?; + let id = row["id"].as_str().unwrap(); + let mut stack = StackView::new( + row["item"].as_str().unwrap(), + row["count"].as_i64().unwrap() as i32, + ); + if let Some(components) = row["components"].as_object() { + for (key, value) in components { + match key.strip_prefix('!') { + Some(removed) => stack.patch.insert(removed.to_owned(), None), + None => stack.patch.insert(key.clone(), Some(value.clone())), + }; + } + } + stack.bundle_selected = row["bundle_selected"].as_i64().unwrap_or(-1) as i32; + env.local_time = row["local_time"].as_str().unwrap_or("").to_owned(); + let context = DisplayContext::by_name(row["context"].as_str().unwrap()).unwrap(); + let owner = row["owner"].as_object().map(|o| { + let derived = &row["derived"]; + OwnerState { + entity_type: o["entity_type"].as_str().unwrap().to_owned(), + main_arm_left: o["main_arm"] == "left", + using_this_item: o["using"].as_bool().unwrap(), + use_item_remaining_ticks: o["remaining"].as_i64().unwrap() as i32, + use_duration: derived["use_duration"].as_i64().unwrap_or(0) as i32, + crossbow_charge_duration: derived["charge_duration"].as_i64().unwrap_or(0) as i32, + ..Default::default() + } + }); + let level = row["dimension"].as_str().map(|d| LevelState { + dimension: d.to_owned(), + ..Default::default() + }); + let ctx = Context { + display: context, + owner: owner.as_ref(), + level: level.as_ref(), + seed: row["seed"].as_i64().unwrap_or(0) as i32, + }; + let resolved = models.resolve(&stack, &ctx, &env); + let mut layers = Vec::new(); + for layer in &resolved.layers { + let (kind, baked, extra) = match &layer.content { + LayerContent::Model { model } => ("model", bake(model), json!({})), + LayerContent::Missing => ("model", bake(MISSING_MODEL), json!({})), + LayerContent::Special { + base, + model, + argument, + } => ( + "special", + bake(base), + json!({"special":model.to_json(),"argument":argument}), + ), + }; + let matrix: Mat4 = baked.layer_matrix(context, &layer.transform); + let mut value = json!({ + "kind":kind, + "tints":layer.tints, + "foil":match layer.foil { FoilType::None=>"none", FoilType::Standard=>"standard", FoilType::Special=>"special" }, + "matrix":matrix.rows().iter().flatten().map(|v| bits(*v)).collect::>(), + "uses_block_light":baked.uses_block_light, + "particle":baked.particle.sprite, + "has_transform":baked.transform(context).is_some(), + }); + if kind == "model" { + value["quads"] = Value::Array( + baked + .quads + .iter() + .map(|q| { + json!({ + "positions":q.positions.map(|v| v.map(bits)), + "uv":q.uv.map(|v| v.map(bits)), + "facing":q.facing.name(), + "tint":q.tint_index, + "sprite":q.material.sprite, + "shade":q.shade_direction_override.map(Direction::name), + "light":q.light_emission, + }) + }) + .collect(), + ); + } + if let (Some(target), Some(source)) = (value.as_object_mut(), extra.as_object()) { + for (k, v) in source { + target.insert(k.clone(), v.clone()); + } + } + layers.push(value); + } + writeln!( + output, + "{}", + json!({"row":"case","id":id,"layers":layers,"oversized":resolved.oversized_in_gui, + "swap":{"play":models.hand_animation_on_swap(&stack),"scale":bits(models.swap_animation_scale(&stack))}}) + )?; + } + let _ = Path::new(""); + Ok(()) +} diff --git a/crates/horizon-assets/src/bake.rs b/crates/horizon-assets/src/bake.rs index 1b48ad7dd..10ad2302d 100644 --- a/crates/horizon-assets/src/bake.rs +++ b/crates/horizon-assets/src/bake.rs @@ -213,6 +213,40 @@ fn bake_elements( } Ok(output) } +/// `FaceBakery.bakeQuad` for a quad with explicit corners and unit-atlas UVs +/// (`uv` in 0..16 texels), as `ItemModelGenerator` builds its layers. +pub fn bake_flat_face( + from: [f32; 3], + to: [f32; 3], + uv: [f32; 4], + direction: Direction, + material: Material, + tint_index: i32, +) -> Result { + let element = Element { + from, + to, + faces: Default::default(), + rotation: None, + shade_direction_override: None, + light_emission: 0, + }; + let face = Face { + cull: None, + tint_index, + texture: String::new(), + uv: Some(uv), + rotation: 0, + }; + bake_face( + &element, + &face, + direction, + None, + material, + BlockModelTransform::new([0; 3], false), + ) +} fn bake_face( element: &Element, face: &Face, diff --git a/crates/horizon-assets/src/item_bake.rs b/crates/horizon-assets/src/item_bake.rs new file mode 100644 index 000000000..3a35d42a4 --- /dev/null +++ b/crates/horizon-assets/src/item_bake.rs @@ -0,0 +1,299 @@ +//! Baking of item models: a cuboid model's quads, or the layer extrusion of +//! `builtin/generated` (`ItemModelGenerator`), with the display transforms +//! and render properties a `CuboidItemModelWrapper` keeps. +use crate::{ + bake::{ModelQuad, bake_block_model, bake_flat_face}, + item_model::DisplayContext, + json::Result, + math::{Mat4, quaternion_xyz}, + model::{Direction, DisplayTransform, GuiLight, ItemTransform, Material}, + resolve::ModelLibrary, +}; +use std::{collections::BTreeSet, f32::consts::PI}; + +pub const MISSING_SPRITE: &str = "minecraft:missingno"; + +/// The alpha of every unique animation frame of a sprite. +#[derive(Clone, Debug, PartialEq)] +pub struct SpriteMask { + pub width: usize, + pub height: usize, + /// `frames[f][y * width + x]` is true for alpha 0. + pub frames: Vec>, +} +impl SpriteMask { + pub fn opaque(width: usize, height: usize) -> Self { + Self { + width, + height, + frames: vec![vec![false; width * height]], + } + } + fn transparent(&self, frame: usize, x: i64, y: i64) -> bool { + if x < 0 || y < 0 || x >= self.width as i64 || y >= self.height as i64 { + return true; + } + self.frames[frame][y as usize * self.width + x as usize] + } +} +/// The sprites of the item and block atlases. +pub trait SpriteLookup { + /// `None` when the sprite is in neither atlas (the missing sprite stands in). + fn mask(&self, sprite: &str) -> Option; +} + +#[derive(Clone, Debug)] +pub struct BakedItemModel { + /// `QuadCollection.getAll`: unculled quads, then north, south, east, + /// west, up and down. + pub quads: Vec, + /// `gui_light: side`. + pub uses_block_light: bool, + pub particle: Material, + /// By [`crate::model::DISPLAY_CONTEXTS`]; `None` is `NO_TRANSFORM`. + pub transforms: [Option; 9], +} + +fn context_index(context: DisplayContext) -> Option { + Some(match context { + DisplayContext::None => return None, + DisplayContext::ThirdPersonLeftHand => 0, + DisplayContext::ThirdPersonRightHand => 1, + DisplayContext::FirstPersonLeftHand => 2, + DisplayContext::FirstPersonRightHand => 3, + DisplayContext::Head => 4, + DisplayContext::Gui => 5, + DisplayContext::Ground => 6, + DisplayContext::Fixed => 7, + DisplayContext::OnShelf => 8, + }) +} +impl BakedItemModel { + /// `ItemTransforms.getTransform`. + pub fn transform(&self, context: DisplayContext) -> Option<&ItemTransform> { + context_index(context).and_then(|i| self.transforms[i].as_ref()) + } + /// `LayerRenderState.applyTransform`: the display transform followed by + /// the item model's own local transformation. + pub fn layer_matrix(&self, context: DisplayContext, local: &Mat4) -> Mat4 { + item_transform_matrix(self.transform(context), context.left_hand()).mul(local) + } +} +/// `ItemTransform.apply` on an identity pose. +pub fn item_transform_matrix(transform: Option<&ItemTransform>, left_hand: bool) -> Mat4 { + let Some(t) = transform else { + return Mat4::IDENTITY.translate([-0.5, -0.5, -0.5]); + }; + let (tx, ry, rz) = if left_hand { + (-t.translation[0], -t.rotation[1], -t.rotation[2]) + } else { + (t.translation[0], t.rotation[1], t.rotation[2]) + }; + let radians = PI / 180.0; + Mat4::IDENTITY + .translate([tx, t.translation[1], t.translation[2]]) + .rotate(quaternion_xyz( + t.rotation[0] * radians, + ry * radians, + rz * radians, + )) + .scale(t.scale) + .translate([-0.5, -0.5, -0.5]) +} + +/// Bake the top geometry of `name` the way `CuboidItemModelWrapper` does. +pub fn bake_item_model( + library: &ModelLibrary, + sprites: &dyn SpriteLookup, + name: &str, +) -> Result { + let model = library + .resolve(name) + .or_else(|_| library.resolve(crate::resolve::MISSING_MODEL))?; + let known = |sprite: &str| sprite == MISSING_SPRITE || sprites.mask(sprite).is_some(); + let material = |m: &Material| { + if known(&m.sprite) { + m.clone() + } else { + Material { + sprite: MISSING_SPRITE.to_owned(), + force_translucent: m.force_translucent, + } + } + }; + let quads = if model.uses_item_generator() { + let mut quads = Vec::new(); + for (layer, slot) in ["layer0", "layer1", "layer2", "layer3", "layer4"] + .into_iter() + .enumerate() + { + let Some(m) = model.material(slot)? else { + break; + }; + let m = material(m); + let mask = if m.sprite == MISSING_SPRITE { + SpriteMask::opaque(16, 16) + } else { + sprites.mask(&m.sprite).unwrap_or_else(|| SpriteMask::opaque(16, 16)) + }; + quads.extend(extrude_layer(&mask, &m, layer as i32)?); + } + quads + } else { + let mut quads = bake_block_model( + &model, + crate::bake::BlockModelTransform::new([0; 3], false), + )?; + for q in &mut quads { + q.material = material(&q.material); + } + // `QuadCollection.Builder.build`: unculled, then each culled direction. + let mut ordered: Vec = quads.iter().filter(|q| q.cull.is_none()).cloned().collect(); + for side in [ + Direction::North, + Direction::South, + Direction::East, + Direction::West, + Direction::Up, + Direction::Down, + ] { + ordered.extend(quads.iter().filter(|q| q.cull == Some(side)).cloned()); + } + ordered + }; + // `resolveParticleMaterial`: a missing `particle` slot is the missing sprite. + let particle = model.material("particle")?.map_or_else( + || Material { + sprite: MISSING_SPRITE.to_owned(), + force_translucent: false, + }, + material, + ); + let transforms = std::array::from_fn(|i| match &model.display.contexts[i] { + DisplayTransform::Explicit(Some(t)) => Some(t.clone()), + _ => None, + }); + Ok(BakedItemModel { + quads, + uses_block_light: model.gui_light == GuiLight::Side, + particle, + transforms, + }) +} +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +enum Side { + Up, + Down, + Left, + Right, +} +impl Side { + fn step(self) -> (i64, i64) { + match self { + Self::Up => (0, 1), + Self::Down => (0, -1), + Self::Left => (1, 0), + Self::Right => (-1, 0), + } + } + fn direction(self) -> Direction { + match self { + Self::Up => Direction::Up, + Self::Down => Direction::Down, + Self::Left => Direction::East, + Self::Right => Direction::West, + } + } +} + +/// `ItemModelGenerator.bakeExtrudedSprite` for one layer: the front and back +/// faces and one thin face per opaque/transparent pixel edge. The native +/// client collects the sides in a hash set, so their order is unspecified; +/// they are emitted sorted by pixel here. +fn extrude_layer(mask: &SpriteMask, material: &Material, layer: i32) -> Result> { + let from = [0.0, 0.0, 7.5]; + let to = [16.0, 16.0, 8.5]; + let mut quads = vec![ + bake_flat_face( + from, + to, + [0.0, 0.0, 16.0, 16.0], + Direction::South, + material.clone(), + layer, + )?, + bake_flat_face( + from, + to, + [16.0, 0.0, 0.0, 16.0], + Direction::North, + material.clone(), + layer, + )?, + ]; + let (width, height) = (mask.width as i64, mask.height as i64); + let mut faces = BTreeSet::new(); + for frame in 0..mask.frames.len() { + for y in 0..height { + for x in 0..width { + if mask.transparent(frame, x, y) { + continue; + } + for side in [Side::Up, Side::Down, Side::Left, Side::Right] { + let (sx, sy) = side.step(); + if mask.transparent(frame, x - sx, y - sy) { + faces.insert((y, x, side)); + } + } + } + } + } + let x_scale = 16.0 / mask.width as f32; + let y_scale = 16.0 / mask.height as f32; + for (y, x, side) in faces { + let (x, y) = (x as f32, y as f32); + let u0 = x + 0.1; + let u1 = x + 1.0 - 0.1; + let (v0, v1) = if matches!(side, Side::Up | Side::Down) { + (y + 0.1, y + 1.0 - 0.1) + } else { + (y + 1.0 - 0.1, y + 0.1) + }; + let (mut start_x, mut start_y, mut end_x, mut end_y) = (x, y, x, y); + match side { + Side::Up => end_x += 1.0, + Side::Down => { + end_x += 1.0; + start_y += 1.0; + end_y += 1.0; + } + Side::Left => end_y += 1.0, + Side::Right => { + start_x += 1.0; + end_x += 1.0; + end_y += 1.0; + } + } + start_x *= x_scale; + end_x *= x_scale; + start_y *= y_scale; + end_y *= y_scale; + start_y = 16.0 - start_y; + end_y = 16.0 - end_y; + let (from, to) = match side { + Side::Up => ([start_x, start_y, 7.5], [end_x, start_y, 8.5]), + Side::Down => ([start_x, end_y, 7.5], [end_x, end_y, 8.5]), + Side::Left => ([start_x, start_y, 7.5], [start_x, end_y, 8.5]), + Side::Right => ([end_x, start_y, 7.5], [end_x, end_y, 8.5]), + }; + quads.push(bake_flat_face( + from, + to, + [u0 * x_scale, v0 * y_scale, u1 * x_scale, v1 * y_scale], + side.direction(), + material.clone(), + layer, + )?); + } + Ok(quads) +} diff --git a/crates/horizon-assets/src/item_model.rs b/crates/horizon-assets/src/item_model.rs new file mode 100644 index 000000000..1f0e775f3 --- /dev/null +++ b/crates/horizon-assets/src/item_model.rs @@ -0,0 +1,1685 @@ +//! The 26.3 client item definitions (`assets//items/*.json`): the model +//! tree (`model`, `composite`, `condition`, `select`, `range_dispatch`, +//! `special`, `bundle/selected_item`, `empty`), its properties and tints, and +//! the resolver that turns one stack into render layers +//! (`ItemModelResolver.updateForTopItem`). +//! +//! Baked geometry lives in [`crate::item_bake`]; this module decides *which* +//! model, tints, foil and transformation each layer gets. +use crate::{ + json::{DecodeError, error as err}, + math::{Mat4, normalize_quaternion, quaternion_from_axis_angle}, +}; +use serde_json::{Map, Value}; +use std::{ + collections::BTreeMap, + sync::{Arc, Mutex}, +}; + +mod special; +pub use special::{SpecialKind, SpecialModel}; + +type Result = std::result::Result; + +/// `BuiltInRegistries.DATA_COMPONENT_TYPE`, which `has_component` and the +/// `component` select validate against (checked by the harness). +pub const DATA_COMPONENT_TYPES: [&str; 122] = [ + "minecraft:additional_trade_cost", + "minecraft:attack_animation", + "minecraft:attack_range", + "minecraft:attribute_modifiers", + "minecraft:axolotl/variant", + "minecraft:banner_patterns", + "minecraft:base_color", + "minecraft:bees", + "minecraft:block_entity_data", + "minecraft:block_state", + "minecraft:block_transformer", + "minecraft:blocks_attacks", + "minecraft:break_sound", + "minecraft:brewing_fuel", + "minecraft:bucket_entity_data", + "minecraft:bundle_contents", + "minecraft:can_break", + "minecraft:can_place_on", + "minecraft:cat/collar", + "minecraft:cat/sound_variant", + "minecraft:cat/variant", + "minecraft:charged_projectiles", + "minecraft:chicken/sound_variant", + "minecraft:chicken/variant", + "minecraft:compostable", + "minecraft:consumable", + "minecraft:container", + "minecraft:container_loot", + "minecraft:cooking_fuel", + "minecraft:cow/sound_variant", + "minecraft:cow/variant", + "minecraft:creative_slot_lock", + "minecraft:cushion/color", + "minecraft:custom_data", + "minecraft:custom_model_data", + "minecraft:custom_name", + "minecraft:damage", + "minecraft:damage_resistant", + "minecraft:damage_type", + "minecraft:death_protection", + "minecraft:debug_stick_state", + "minecraft:dye", + "minecraft:dyed_color", + "minecraft:enchantable", + "minecraft:enchantment_glint_override", + "minecraft:enchantments", + "minecraft:entity_data", + "minecraft:equippable", + "minecraft:firework_explosion", + "minecraft:fireworks", + "minecraft:food", + "minecraft:fox/variant", + "minecraft:frog/variant", + "minecraft:glider", + "minecraft:horse/variant", + "minecraft:instrument", + "minecraft:intangible_projectile", + "minecraft:interact_animation", + "minecraft:item_model", + "minecraft:item_name", + "minecraft:jukebox_playable", + "minecraft:kinetic_weapon", + "minecraft:llama/variant", + "minecraft:lock", + "minecraft:lodestone_tracker", + "minecraft:lore", + "minecraft:map_decorations", + "minecraft:map_id", + "minecraft:map_post_processing", + "minecraft:max_damage", + "minecraft:max_stack_size", + "minecraft:minimum_attack_charge", + "minecraft:mob_visibility", + "minecraft:mooshroom/variant", + "minecraft:note_block_sound", + "minecraft:ominous_bottle_amplifier", + "minecraft:painting/variant", + "minecraft:parrot/variant", + "minecraft:piercing_weapon", + "minecraft:pig/sound_variant", + "minecraft:pig/variant", + "minecraft:pot_decorations", + "minecraft:potion_contents", + "minecraft:potion_duration_scale", + "minecraft:profile", + "minecraft:provides_banner_patterns", + "minecraft:provides_pottery_pattern", + "minecraft:provides_trim_material", + "minecraft:rabbit/variant", + "minecraft:rarity", + "minecraft:recipes", + "minecraft:repair_cost", + "minecraft:repairable", + "minecraft:salmon/size", + "minecraft:sheep/color", + "minecraft:shulker/color", + "minecraft:sign_text_back", + "minecraft:sign_text_front", + "minecraft:stored_enchantments", + "minecraft:sulfur_cube_content", + "minecraft:suspicious_stew_effects", + "minecraft:tool", + "minecraft:tooltip_display", + "minecraft:tooltip_style", + "minecraft:trim", + "minecraft:tropical_fish/base_color", + "minecraft:tropical_fish/pattern", + "minecraft:tropical_fish/pattern_color", + "minecraft:unbreakable", + "minecraft:use_cooldown", + "minecraft:use_effects", + "minecraft:use_remainder", + "minecraft:villager/variant", + "minecraft:villager_food", + "minecraft:waxed", + "minecraft:weapon", + "minecraft:wolf/collar", + "minecraft:wolf/sound_variant", + "minecraft:wolf/variant", + "minecraft:writable_book_content", + "minecraft:written_book_content", + "minecraft:zombie_nautilus/variant", +]; + +// --------------------------------------------------------------------------- +// Display contexts +// --------------------------------------------------------------------------- + +/// `ItemDisplayContext`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum DisplayContext { + None, + ThirdPersonLeftHand, + ThirdPersonRightHand, + FirstPersonLeftHand, + FirstPersonRightHand, + Head, + Gui, + Ground, + Fixed, + OnShelf, +} +impl DisplayContext { + pub const ALL: [Self; 10] = [ + Self::None, + Self::ThirdPersonLeftHand, + Self::ThirdPersonRightHand, + Self::FirstPersonLeftHand, + Self::FirstPersonRightHand, + Self::Head, + Self::Gui, + Self::Ground, + Self::Fixed, + Self::OnShelf, + ]; + pub fn name(self) -> &'static str { + match self { + Self::None => "none", + Self::ThirdPersonLeftHand => "thirdperson_lefthand", + Self::ThirdPersonRightHand => "thirdperson_righthand", + Self::FirstPersonLeftHand => "firstperson_lefthand", + Self::FirstPersonRightHand => "firstperson_righthand", + Self::Head => "head", + Self::Gui => "gui", + Self::Ground => "ground", + Self::Fixed => "fixed", + Self::OnShelf => "on_shelf", + } + } + pub fn by_name(name: &str) -> Option { + Self::ALL.into_iter().find(|c| c.name() == name) + } + /// `ItemDisplayContext.leftHand`. + pub fn left_hand(self) -> bool { + matches!(self, Self::ThirdPersonLeftHand | Self::FirstPersonLeftHand) + } +} + +// --------------------------------------------------------------------------- +// Decoding helpers (DataFixerUpper `JsonOps` semantics) +// --------------------------------------------------------------------------- + +fn object(v: &Value) -> Result<&Map> { + v.as_object().ok_or_else(|| err("expected object")) +} +/// A present, non-null field (`JsonOps` maps `null` to an absent key). +fn get<'a>(m: &'a Map, key: &str) -> Option<&'a Value> { + m.get(key).filter(|v| !v.is_null()) +} +fn required<'a>(m: &'a Map, key: &str) -> Result<&'a Value> { + get(m, key).ok_or_else(|| err(&format!("missing {key}"))) +} +/// `Codec.FLOAT`: numbers, and booleans as 1 and 0. +fn float(v: &Value) -> Result { + match v { + Value::Number(n) => n + .to_string() + .parse() + .or_else(|_| n.as_f64().map(|f| f as f32).ok_or(())) + .map_err(|()| err("invalid float")), + _ => Err(err("expected float")), + } +} +/// `Codec.INT`: `Number.intValue`, truncating toward zero and saturating +/// like a Java narrowing of a double (longs keep their low 32 bits). +fn int(v: &Value) -> Result { + match v { + Value::Number(n) => { + if let Some(i) = n.as_i64() { + Ok(i as i32) + } else if let Some(u) = n.as_u64() { + Ok(u as i32) + } else { + Ok(n.as_f64().ok_or_else(|| err("invalid int"))? as i32) + } + } + _ => Err(err("expected int")), + } +} +fn boolean(v: &Value) -> Result { + v.as_bool().ok_or_else(|| err("expected boolean")) +} +fn string(v: &Value) -> Result { + v.as_str().map(str::to_owned).ok_or_else(|| err("expected string")) +} +fn list(v: &Value) -> Result<&Vec> { + v.as_array().ok_or_else(|| err("expected list")) +} +/// `Identifier.CODEC`: a lowercase `namespace:path`, defaulting the namespace. +pub fn identifier(name: &str) -> Result { + let (namespace, path) = match name.split_once(':') { + Some((n, p)) => (if n.is_empty() { "minecraft" } else { n }, p), + None => ("minecraft", name), + }; + let valid = |c: u8| c.is_ascii_lowercase() || c.is_ascii_digit() || b"_.-".contains(&c); + if path.contains(':') + || !namespace.bytes().all(valid) + || !path.bytes().all(|c| valid(c) || c == b'/') + { + return Err(err("invalid resource identifier")); + } + Ok(format!("{namespace}:{path}")) +} +fn ident(v: &Value) -> Result { + identifier(&string(v)?) +} +fn component_type(v: &Value) -> Result { + let id = ident(v)?; + if DATA_COMPONENT_TYPES.contains(&id.as_str()) { + Ok(id) + } else { + Err(err("unknown data component type")) + } +} +fn vector(v: &Value) -> Result<[f32; N]> { + let values = list(v)?; + if values.len() != N { + return Err(err("wrong vector length")); + } + let mut out = [0.0; N]; + for (o, v) in out.iter_mut().zip(values) { + *o = float(v)?; + } + Ok(out) +} +fn non_negative(v: &Value) -> Result { + let i = int(v)?; + if i < 0 { + return Err(err("value must be non-negative")); + } + Ok(i) +} +/// `ExtraCodecs.RGB_COLOR_CODEC`: an int, or three floats in 0..1. +fn rgb(v: &Value) -> Result { + if v.is_array() { + let [r, g, b] = vector::<3>(v)?; + return Ok(argb(255, channel(r), channel(g), channel(b))); + } + int(v) +} +fn argb(a: i32, r: i32, g: i32, b: i32) -> i32 { + (a & 255) << 24 | (r & 255) << 16 | (g & 255) << 8 | (b & 255) +} +fn opaque(color: i32) -> i32 { + color | (0xFF00_0000u32 as i32) +} + +/// `Transformation.EXTENDED_CODEC`. +fn transformation(v: &Value) -> Result { + if v.is_array() { + return Ok(Mat4::from_row_major(vector::<16>(v)?)); + } + let m = object(v)?; + let quaternion = |v: &Value| -> Result<[f32; 4]> { + if v.is_array() { + return Ok(normalize_quaternion(vector::<4>(v)?)); + } + let o = object(v)?; + Ok(quaternion_from_axis_angle( + float(required(o, "angle")?)?, + vector::<3>(required(o, "axis")?)?, + )) + }; + let translation = vector::<3>(required(m, "translation")?)?; + let left = quaternion(required(m, "left_rotation")?)?; + let scale = vector::<3>(required(m, "scale")?)?; + let right = quaternion(required(m, "right_rotation")?)?; + Ok(Mat4::translation(translation) + .rotate(left) + .scale(scale) + .rotate(right)) +} +fn optional_transformation(m: &Map) -> Result> { + get(m, "transformation").map(transformation).transpose() +} +/// `Mth.floor(float)` as `ARGB.as8BitChannel` uses it. +fn channel(v: f32) -> i32 { + let i = v as i32; + if (i as f32) > v { i - 1 } else { i } +} + +// --------------------------------------------------------------------------- +// The model tree +// --------------------------------------------------------------------------- + +/// One `items/.json` file: a model tree plus the client properties. +#[derive(Clone, Debug)] +pub struct ClientItem { + pub model: ItemModelNode, + pub hand_animation_on_swap: bool, + pub oversized_in_gui: bool, + pub swap_animation_scale: f32, +} +impl ClientItem { + pub const DEFAULT_PROPERTIES: (bool, bool, f32) = (true, false, 1.0); + pub fn from_json(text: &str) -> Result { + let value: Value = serde_json::from_str(text.strip_prefix('\u{feff}').unwrap_or(text))?; + Self::decode(&value) + } + pub fn decode(value: &Value) -> Result { + let m = object(value)?; + Ok(Self { + model: ItemModelNode::decode(required(m, "model")?)?, + hand_animation_on_swap: get(m, "hand_animation_on_swap") + .map_or(Ok(true), boolean)?, + oversized_in_gui: get(m, "oversized_in_gui").map_or(Ok(false), boolean)?, + swap_animation_scale: get(m, "swap_animation_scale").map_or(Ok(1.0), float)?, + }) + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct ModelLeaf { + pub model: String, + pub transformation: Option, + pub tints: Vec, +} +#[derive(Clone, Debug)] +pub enum ItemModelNode { + Empty, + Model(ModelLeaf), + Composite { + models: Vec, + transformation: Option, + }, + Condition { + transformation: Option, + property: ConditionProperty, + on_true: Box, + on_false: Box, + }, + Select { + transformation: Option, + property: SelectProperty, + cases: Vec, + fallback: Option>, + }, + RangeDispatch { + transformation: Option, + property: NumericProperty, + scale: f32, + /// Sorted by threshold (a stable sort, as `bake` does). + entries: Vec<(f32, ItemModelNode)>, + fallback: Option>, + }, + Special { + base: String, + transformation: Option, + model: SpecialModel, + }, + BundleSelectedItem, +} +#[derive(Clone, Debug)] +pub struct SwitchCase { + /// Property values, in their canonical JSON form. + pub values: Vec, + pub model: ItemModelNode, +} + +impl ItemModelNode { + pub fn decode(v: &Value) -> Result { + let m = object(v)?; + let kind = ident(required(m, "type")?)?; + Ok(match kind.as_str() { + "minecraft:empty" => Self::Empty, + "minecraft:model" => Self::Model(ModelLeaf { + model: ident(required(m, "model")?)?, + transformation: optional_transformation(m)?, + tints: match get(m, "tints") { + None => Vec::new(), + Some(t) => list(t)? + .iter() + .map(TintSource::decode) + .collect::>()?, + }, + }), + "minecraft:composite" => Self::Composite { + models: list(required(m, "models")?)? + .iter() + .map(Self::decode) + .collect::>()?, + transformation: optional_transformation(m)?, + }, + "minecraft:condition" => Self::Condition { + transformation: optional_transformation(m)?, + property: ConditionProperty::decode(m)?, + on_true: Box::new(Self::decode(required(m, "on_true")?)?), + on_false: Box::new(Self::decode(required(m, "on_false")?)?), + }, + "minecraft:select" => { + let transformation = optional_transformation(m)?; + let property = SelectProperty::decode(m)?; + let cases = list(required(m, "cases")?)? + .iter() + .map(|c| SwitchCase::decode(&property, c)) + .collect::>>()?; + if cases.is_empty() { + return Err(err("empty case list")); + } + let mut seen: Vec<&Value> = Vec::new(); + for value in cases.iter().flat_map(|c| &c.values) { + if seen.contains(&value) { + return Err(err("duplicate case conditions")); + } + seen.push(value); + } + Self::Select { + transformation, + property, + cases, + fallback: get(m, "fallback") + .map(|f| Self::decode(f).map(Box::new)) + .transpose()?, + } + } + "minecraft:range_dispatch" => { + let mut entries = list(required(m, "entries")?)? + .iter() + .map(|e| { + let e = object(e)?; + Ok(( + float(required(e, "threshold")?)?, + Self::decode(required(e, "model")?)?, + )) + }) + .collect::>>()?; + // `Comparator.comparingDouble`: Double.compare, a total order. + entries.sort_by(|a, b| f64::from(a.0).total_cmp(&f64::from(b.0))); + Self::RangeDispatch { + transformation: optional_transformation(m)?, + property: NumericProperty::decode(m)?, + scale: get(m, "scale").map_or(Ok(1.0), float)?, + entries, + fallback: get(m, "fallback") + .map(|f| Self::decode(f).map(Box::new)) + .transpose()?, + } + } + "minecraft:special" => Self::Special { + base: ident(required(m, "base")?)?, + transformation: optional_transformation(m)?, + model: SpecialModel::decode(required(m, "model")?)?, + }, + "minecraft:bundle/selected_item" => Self::BundleSelectedItem, + _ => return Err(err("unknown item model type")), + }) + } + /// Every model resource id the tree can ask for. + pub fn dependencies(&self, out: &mut Vec) { + match self { + Self::Empty | Self::BundleSelectedItem => {} + Self::Model(leaf) => out.push(leaf.model.clone()), + Self::Composite { models, .. } => models.iter().for_each(|m| m.dependencies(out)), + Self::Condition { + on_true, on_false, .. + } => { + on_true.dependencies(out); + on_false.dependencies(out); + } + Self::Select { + cases, fallback, .. + } => { + cases.iter().for_each(|c| c.model.dependencies(out)); + fallback.iter().for_each(|f| f.dependencies(out)); + } + Self::RangeDispatch { + entries, fallback, .. + } => { + entries.iter().for_each(|(_, m)| m.dependencies(out)); + fallback.iter().for_each(|f| f.dependencies(out)); + } + Self::Special { base, .. } => out.push(base.clone()), + } + } +} +impl SwitchCase { + fn decode(property: &SelectProperty, v: &Value) -> Result { + let m = object(v)?; + let when = required(m, "when")?; + // `compactListCodec`: a list, or one value; the list must not be empty. + let raw: Vec<&Value> = match when { + Value::Array(a) if !a.is_empty() => a.iter().collect(), + Value::Array(_) => return Err(err("list must have contents")), + single => vec![single], + }; + Ok(Self { + values: raw + .into_iter() + .map(|v| property.decode_value(v)) + .collect::>()?, + model: ItemModelNode::decode(required(m, "model")?)?, + }) + } +} + +// --------------------------------------------------------------------------- +// Tint sources +// --------------------------------------------------------------------------- + +#[derive(Clone, Debug, PartialEq)] +pub enum TintSource { + Constant(i32), + CustomModelData { index: i32, default: i32 }, + Dye(i32), + Grass { temperature: f32, downfall: f32 }, + Firework(i32), + Potion(i32), + Team(i32), +} +impl TintSource { + fn decode(v: &Value) -> Result { + let m = object(v)?; + let default = || rgb(required(m, "default")?); + let unit = |v: &Value| -> Result { + let f = float(v)?; + if (0.0..=1.0).contains(&f) { + Ok(f) + } else { + Err(err("value must be within range [0;1]")) + } + }; + Ok(match ident(required(m, "type")?)?.as_str() { + "minecraft:constant" => Self::Constant(opaque(rgb(required(m, "value")?)?)), + "minecraft:custom_model_data" => Self::CustomModelData { + index: get(m, "index").map_or(Ok(0), non_negative)?, + default: default()?, + }, + "minecraft:dye" => Self::Dye(default()?), + "minecraft:grass" => Self::Grass { + temperature: unit(required(m, "temperature")?)?, + downfall: unit(required(m, "downfall")?)?, + }, + "minecraft:firework" => Self::Firework(default()?), + "minecraft:potion" => Self::Potion(default()?), + "minecraft:team" => Self::Team(default()?), + _ => return Err(err("unknown item tint source")), + }) + } +} + +// --------------------------------------------------------------------------- +// Properties +// --------------------------------------------------------------------------- + +#[derive(Clone, Debug, PartialEq)] +pub enum ConditionProperty { + CustomModelData(i32), + UsingItem, + Broken, + Damaged, + FishingRodCast, + HasComponent { component: String, ignore_default: bool }, + BundleHasSelectedItem, + Selected, + Carried, + ExtendedView, + KeybindDown(String), + ViewEntity, + /// A `component` predicate, evaluated by the host. + Component(Value), +} +impl ConditionProperty { + fn decode(m: &Map) -> Result { + Ok(match ident(required(m, "property")?)?.as_str() { + "minecraft:custom_model_data" => { + Self::CustomModelData(get(m, "index").map_or(Ok(0), non_negative)?) + } + "minecraft:using_item" => Self::UsingItem, + "minecraft:broken" => Self::Broken, + "minecraft:damaged" => Self::Damaged, + "minecraft:fishing_rod/cast" => Self::FishingRodCast, + "minecraft:has_component" => Self::HasComponent { + component: component_type(required(m, "component")?)?, + ignore_default: get(m, "ignore_default").map_or(Ok(false), boolean)?, + }, + "minecraft:bundle/has_selected_item" => Self::BundleHasSelectedItem, + "minecraft:selected" => Self::Selected, + "minecraft:carried" => Self::Carried, + "minecraft:extended_view" => Self::ExtendedView, + "minecraft:keybind_down" => Self::KeybindDown(string(required(m, "keybind")?)?), + "minecraft:view_entity" => Self::ViewEntity, + "minecraft:component" => { + let predicate = required(m, "predicate")?; + if object(predicate)?.len() != 1 { + return Err(err("a single component predicate is expected")); + } + Self::Component(predicate.clone()) + } + _ => return Err(err("unknown condition property")), + }) + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum SelectProperty { + CustomModelData(i32), + MainHand, + ChargeType, + TrimMaterial, + BlockState(String), + DisplayContext, + LocalTime { + pattern: String, + locale: String, + time_zone: Option, + }, + ContextEntityType, + ContextDimension, + Component(String), +} +impl SelectProperty { + fn decode(m: &Map) -> Result { + Ok(match ident(required(m, "property")?)?.as_str() { + "minecraft:custom_model_data" => { + Self::CustomModelData(get(m, "index").map_or(Ok(0), non_negative)?) + } + "minecraft:main_hand" => Self::MainHand, + "minecraft:charge_type" => Self::ChargeType, + "minecraft:trim_material" => Self::TrimMaterial, + "minecraft:block_state" => Self::BlockState(string(required(m, "block_state_property")?)?), + "minecraft:display_context" => Self::DisplayContext, + "minecraft:local_time" => Self::LocalTime { + pattern: string(required(m, "pattern")?)?, + locale: get(m, "locale").map_or(Ok(String::new()), string)?, + time_zone: get(m, "time_zone").map(string).transpose()?, + }, + "minecraft:context_entity_type" => Self::ContextEntityType, + "minecraft:context_dimension" => Self::ContextDimension, + "minecraft:component" => Self::Component(component_type(required(m, "component")?)?), + _ => return Err(err("unknown select property")), + }) + } + /// A `when` value in canonical form (identifiers normalised). + fn decode_value(&self, v: &Value) -> Result { + Ok(match self { + Self::CustomModelData(_) | Self::BlockState(_) | Self::LocalTime { .. } => { + Value::String(string(v)?) + } + Self::MainHand => match string(v)?.as_str() { + s @ ("left" | "right") => Value::String(s.to_owned()), + _ => return Err(err("invalid arm")), + }, + Self::ChargeType => match string(v)?.as_str() { + s @ ("none" | "rocket" | "arrow") => Value::String(s.to_owned()), + _ => return Err(err("invalid charge type")), + }, + Self::TrimMaterial | Self::ContextEntityType | Self::ContextDimension => { + Value::String(ident(v)?) + } + Self::DisplayContext => { + let s = string(v)?; + DisplayContext::by_name(&s).ok_or_else(|| err("invalid display context"))?; + Value::String(s) + } + Self::Component(_) => v.clone(), + }) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CompassTarget { + None, + Lodestone, + Spawn, + Recovery, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TimeSource { + Random, + Daytime, + MoonPhase, +} +/// A `NeedleDirectionHelper.Wobbler`. +#[derive(Clone, Copy, Debug, Default)] +pub struct Wobbler { + pub rotation: f32, + pub delta_rotation: f32, + pub last_update_tick: i64, + /// Without wobble the needle jumps straight to its target. + pub target: f32, +} +impl Wobbler { + pub fn should_update(&self, wobble: bool, tick: i64) -> bool { + !wobble || self.last_update_tick != tick + } + pub fn update(&mut self, wobble: bool, factor: f32, tick: i64, target_rotation: f32) { + if !wobble { + self.target = target_rotation; + return; + } + self.last_update_tick = tick; + let temp = positive_modulo(target_rotation - self.rotation + 0.5, 1.0) - 0.5; + self.delta_rotation += temp * 0.1; + self.delta_rotation *= factor; + self.rotation = positive_modulo(self.rotation + self.delta_rotation, 1.0); + } + pub fn value(&self, wobble: bool) -> f32 { + if wobble { self.rotation } else { self.target } + } +} +/// `Mth.positiveModulo(float, float)`. +pub fn positive_modulo(input: f32, modulus: f32) -> f32 { + (input % modulus + modulus) % modulus +} +/// The mutable state a baked `compass` or `time` property keeps. +#[derive(Debug, Default)] +pub struct NeedleState(Mutex<[Wobbler; 2]>); +impl Clone for NeedleState { + fn clone(&self) -> Self { + Self::default() + } +} +impl PartialEq for NeedleState { + fn eq(&self, _: &Self) -> bool { + true + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum NumericProperty { + BundleFullness, + Compass { + wobble: bool, + target: CompassTarget, + state: Arc, + }, + Cooldown, + Count { normalize: bool }, + CrossbowPull, + CustomModelData(i32), + Damage { normalize: bool }, + Time { + wobble: bool, + source: TimeSource, + state: Arc, + }, + UseCycle(f32), + UseDuration { remaining: bool }, +} +impl NumericProperty { + fn decode(m: &Map) -> Result { + let normalize = || get(m, "normalize").map_or(Ok(true), boolean); + Ok(match ident(required(m, "property")?)?.as_str() { + "minecraft:custom_model_data" => { + Self::CustomModelData(get(m, "index").map_or(Ok(0), non_negative)?) + } + "minecraft:bundle/fullness" => Self::BundleFullness, + "minecraft:damage" => Self::Damage { + normalize: normalize()?, + }, + "minecraft:cooldown" => Self::Cooldown, + "minecraft:time" => Self::Time { + wobble: get(m, "wobble").map_or(Ok(true), boolean)?, + source: match string(required(m, "source")?)?.as_str() { + "random" => TimeSource::Random, + "daytime" => TimeSource::Daytime, + "moon_phase" => TimeSource::MoonPhase, + _ => return Err(err("invalid time source")), + }, + state: Arc::default(), + }, + "minecraft:compass" => Self::Compass { + wobble: get(m, "wobble").map_or(Ok(true), boolean)?, + target: match string(required(m, "target")?)?.as_str() { + "none" => CompassTarget::None, + "lodestone" => CompassTarget::Lodestone, + "spawn" => CompassTarget::Spawn, + "recovery" => CompassTarget::Recovery, + _ => return Err(err("invalid compass target")), + }, + state: Arc::default(), + }, + "minecraft:crossbow/pull" => Self::CrossbowPull, + "minecraft:use_cycle" => { + let period = get(m, "period").map_or(Ok(1.0), float)?; + if period.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) { + return Err(err("value must be positive")); + } + Self::UseCycle(period) + } + "minecraft:use_duration" => Self::UseDuration { + remaining: get(m, "remaining").map_or(Ok(false), boolean)?, + }, + "minecraft:count" => Self::Count { + normalize: normalize()?, + }, + _ => return Err(err("unknown range dispatch property")), + }) + } +} + +// --------------------------------------------------------------------------- +// Stacks and the world around them +// --------------------------------------------------------------------------- + +/// The item components a stack carries: a prototype plus an explicit patch +/// (`None` removes a prototype component). +pub type Components = BTreeMap; + +/// An item stack as the resolver reads it. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct StackView { + pub item: String, + pub count: i32, + pub patch: BTreeMap>, + /// `BundleContents.selectedItem`, a runtime-only index (-1: none). + pub bundle_selected: i32, +} +impl StackView { + pub fn new(item: &str, count: i32) -> Self { + Self { + item: item.to_owned(), + count, + patch: BTreeMap::new(), + bundle_selected: -1, + } + } +} + +/// `ArmorTrim`/`LodestoneTracker`-style positions are plain data. +#[derive(Clone, Debug, PartialEq)] +pub struct GlobalPos { + pub dimension: String, + pub pos: [i32; 3], +} +/// The living entity holding the item (`ItemOwner`). +#[derive(Clone, Debug, Default)] +pub struct OwnerState { + pub position: [f64; 3], + pub visual_rotation_y_degrees: f32, + pub entity_type: String, + pub main_arm_left: bool, + /// `isUsingItem() && getUseItem() == stack`. + pub using_this_item: bool, + pub use_item_remaining_ticks: i32, + /// `stack.getUseDuration(owner)`. + pub use_duration: i32, + /// `CrossbowItem.getChargeDuration(stack, owner)`. + pub crossbow_charge_duration: i32, + pub fishing_cast_with_this_item: bool, + pub is_selected: bool, + pub is_carried: bool, + pub is_view_entity: bool, + pub team_color: Option, + /// `ItemCooldowns.getCooldownPercent(stack, 0)`. + pub cooldown_percent: f32, + pub is_local_player: bool, + pub last_death_location: Option, +} +/// The `ClientLevel` an item is drawn in. +#[derive(Clone, Debug, Default)] +pub struct LevelState { + pub dimension: String, + pub game_time: i64, + /// `EnvironmentAttributes.SUN_ANGLE` at the owner, in degrees. + pub sun_angle: f32, + /// `EnvironmentAttributes.MOON_PHASE` index at the owner. + pub moon_phase: i32, + pub respawn: Option, + /// `tickRateManager().runsNormally()`. + pub runs_normally: bool, +} +/// Everything about the surroundings that is not in the stack. +#[derive(Clone, Debug)] +pub struct Context<'a> { + pub display: DisplayContext, + pub owner: Option<&'a OwnerState>, + pub level: Option<&'a LevelState>, + pub seed: i32, +} + +/// Host services the resolver cannot derive from data alone. +pub trait ItemEnv { + /// `PotionContents.getColorOr` for the potion/effects part: the mixed + /// effect colour, or `None` when the contents have no visible effects. + fn potion_effect_color(&self, _potion_contents: &Value) -> Option { + None + } + /// `GrassColor.get(temperature, downfall)`. + fn grass_color(&self, _temperature: f64, _downfall: f64) -> i32 { + -65281 + } + /// `BundleItem.getFullnessDisplay`. + fn bundle_fullness(&self, _stack: &StackView, _components: &Components) -> f32 { + 0.0 + } + /// `ItemStack.getMaxStackSize` when the prototype has no component. + fn component_matches(&self, _stack: &StackView, _predicate: &Value) -> bool { + false + } + fn is_keybind_down(&self, _keybind: &str) -> bool { + false + } + fn has_shift_down(&self) -> bool { + false + } + /// `LocalTime`: the formatted current time for a pattern. + fn local_time(&self, _pattern: &str, _locale: &str, _time_zone: Option<&str>) -> String { + String::new() + } + /// A random float for `time` (random source) and the spinning compass. + fn random_float(&self) -> f32 { + 0.0 + } +} +/// An [`ItemEnv`] with the trait defaults. +pub struct NoEnv; +impl ItemEnv for NoEnv {} + +// --------------------------------------------------------------------------- +// Resolution +// --------------------------------------------------------------------------- + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FoilType { + None, + Standard, + Special, +} +#[derive(Clone, Debug, PartialEq)] +pub enum LayerContent { + /// A cuboid model resource, baked by [`crate::item_bake`]. + Model { model: String }, + /// `MissingItemModel`. + Missing, + Special { + base: String, + model: SpecialModel, + /// What `extractArgument` reads from the stack. + argument: Value, + }, +} +#[derive(Clone, Debug, PartialEq)] +pub struct Layer { + pub content: LayerContent, + pub tints: Vec, + pub foil: FoilType, + pub transform: Mat4, +} +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ResolvedItem { + pub layers: Vec, + pub oversized_in_gui: bool, +} + +/// All item definitions and the default components of every item. +#[derive(Default)] +pub struct ItemModels { + pub definitions: BTreeMap, + pub prototypes: BTreeMap, +} + +impl ItemModels { + pub fn components(&self, stack: &StackView) -> Components { + let mut out = self.prototypes.get(&stack.item).cloned().unwrap_or_default(); + for (key, value) in &stack.patch { + match value { + Some(v) => out.insert(key.clone(), v.clone()), + None => out.remove(key), + }; + } + out + } + /// `ItemModelResolver.updateForTopItem`. + pub fn resolve( + &self, + stack: &StackView, + ctx: &Context, + env: &dyn ItemEnv, + ) -> ResolvedItem { + let mut out = ResolvedItem::default(); + if stack.count > 0 && stack.item != "minecraft:air" { + self.append_layers(&mut out, stack, ctx, env); + } + out + } + /// `ItemModelResolver.appendItemLayers`. + pub fn append_layers( + &self, + out: &mut ResolvedItem, + stack: &StackView, + ctx: &Context, + env: &dyn ItemEnv, + ) { + let components = self.components(stack); + let Some(Value::String(model_id)) = components.get("minecraft:item_model") else { + return; + }; + let id = identifier(model_id).unwrap_or_else(|_| model_id.clone()); + let definition = self.definitions.get(&id); + out.oversized_in_gui = definition.is_some_and(|d| d.oversized_in_gui); + let mut state = Resolve { + models: self, + stack, + components: &components, + ctx, + env, + }; + match definition { + Some(d) => state.node(out, &d.model, &Mat4::IDENTITY), + None => state.missing(out, &Mat4::IDENTITY), + } + } + /// `ItemModelResolver.shouldPlaySwapAnimation`. + pub fn hand_animation_on_swap(&self, stack: &StackView) -> bool { + self.properties(stack).0 + } + /// `ItemModelResolver.swapAnimationScale`. + pub fn swap_animation_scale(&self, stack: &StackView) -> f32 { + self.properties(stack).2 + } + fn properties(&self, stack: &StackView) -> (bool, bool, f32) { + match self.components(stack).get("minecraft:item_model") { + Some(Value::String(id)) => identifier(id) + .ok() + .and_then(|id| self.definitions.get(&id)) + .map_or(ClientItem::DEFAULT_PROPERTIES, |d| { + ( + d.hand_animation_on_swap, + d.oversized_in_gui, + d.swap_animation_scale, + ) + }), + _ => ClientItem::DEFAULT_PROPERTIES, + } + } +} + +struct Resolve<'a> { + models: &'a ItemModels, + stack: &'a StackView, + components: &'a Components, + ctx: &'a Context<'a>, + env: &'a dyn ItemEnv, +} + +fn compose(parent: &Mat4, own: &Option) -> Mat4 { + own.as_ref().map_or(*parent, |t| parent.mul(t)) +} + +impl Resolve<'_> { + fn component(&self, key: &str) -> Option<&Value> { + self.components.get(key) + } + fn has_foil(&self) -> bool { + if let Some(v) = self.component("minecraft:enchantment_glint_override") { + return v.as_bool().unwrap_or(false); + } + let enchanted = self + .component("minecraft:enchantments") + .is_some_and(enchantments_present); + enchanted + || (self.stack.item == "minecraft:compass" + && self.component("minecraft:lodestone_tracker").is_some()) + } + fn damageable(&self) -> bool { + self.component("minecraft:max_damage").is_some() + && self.component("minecraft:unbreakable").is_none() + && self.component("minecraft:damage").is_some() + } + fn max_damage(&self) -> i32 { + self.component("minecraft:max_damage") + .and_then(|v| int(v).ok()) + .unwrap_or(0) + } + fn damage_value(&self) -> i32 { + let d = self + .component("minecraft:damage") + .and_then(|v| int(v).ok()) + .unwrap_or(0); + // `Mth.clamp(int, 0, max)` + if d < 0 { 0 } else { d.min(self.max_damage()) } + } + fn max_stack_size(&self) -> i32 { + self.component("minecraft:max_stack_size") + .and_then(|v| int(v).ok()) + .unwrap_or(1) + } + fn missing(&self, out: &mut ResolvedItem, transform: &Mat4) { + out.layers.push(Layer { + content: LayerContent::Missing, + tints: Vec::new(), + foil: FoilType::None, + transform: *transform, + }); + } + fn node(&mut self, out: &mut ResolvedItem, node: &ItemModelNode, parent: &Mat4) { + match node { + ItemModelNode::Empty => {} + ItemModelNode::Model(leaf) => { + let transform = compose(parent, &leaf.transformation); + let foil = if self.has_foil() { + if matches!(self.stack.item.as_str(), "minecraft:clock") + || self.item_in_compass_tag() + { + FoilType::Special + } else { + FoilType::Standard + } + } else { + FoilType::None + }; + let tints = leaf.tints.iter().map(|t| self.tint(t)).collect(); + out.layers.push(Layer { + content: LayerContent::Model { + model: leaf.model.clone(), + }, + tints, + foil, + transform, + }); + } + ItemModelNode::Composite { + models, + transformation, + } => { + let child = compose(parent, transformation); + for m in models { + self.node(out, m, &child); + } + } + ItemModelNode::Condition { + transformation, + property, + on_true, + on_false, + } => { + let child = compose(parent, transformation); + let chosen = if self.condition(property) { on_true } else { on_false }; + self.node(out, chosen, &child); + } + ItemModelNode::Select { + transformation, + property, + cases, + fallback, + } => { + let child = compose(parent, transformation); + let value = self.select_value(property); + let chosen = value.and_then(|v| { + cases + .iter() + .find(|c| c.values.contains(&v)) + .map(|c| &c.model) + }); + match (chosen, fallback) { + (Some(m), _) => self.node(out, m, &child), + (None, Some(f)) => self.node(out, f, &child), + (None, None) => self.missing(out, &child), + } + } + ItemModelNode::RangeDispatch { + transformation, + property, + scale, + entries, + fallback, + } => { + let child = compose(parent, transformation); + let value = self.numeric(property) * scale; + let chosen = if value.is_nan() { + None + } else { + last_index_less_or_equal(entries, value).map(|i| &entries[i].1) + }; + match (chosen, fallback) { + (Some(m), _) => self.node(out, m, &child), + (None, Some(f)) => self.node(out, f, &child), + (None, None) => self.missing(out, &child), + } + } + ItemModelNode::Special { + base, + transformation, + model, + } => { + let transform = compose(parent, transformation); + out.layers.push(Layer { + content: LayerContent::Special { + base: base.clone(), + model: model.clone(), + argument: model.argument(&|k| self.component(k).cloned()), + }, + tints: Vec::new(), + foil: if self.has_foil() { + FoilType::Standard + } else { + FoilType::None + }, + transform, + }); + } + ItemModelNode::BundleSelectedItem => { + if let Some(selected) = self.bundle_selected() { + self.models.append_layers(out, &selected, self.ctx, self.env); + } + } + } + } + fn item_in_compass_tag(&self) -> bool { + // `ItemTags.COMPASSES`: the compass and the recovery compass. + matches!( + self.stack.item.as_str(), + "minecraft:compass" | "minecraft:recovery_compass" + ) + } + /// `BundleItem.getSelectedItem`: the template at the selected index. + fn bundle_selected(&self) -> Option { + let items = self.component("minecraft:bundle_contents")?.as_array()?; + let template = items.get(usize::try_from(self.stack.bundle_selected).ok()?)?; + stack_from_template(template) + } + fn condition(&self, property: &ConditionProperty) -> bool { + let owner = self.ctx.owner; + match property { + ConditionProperty::CustomModelData(i) => self + .component("minecraft:custom_model_data") + .and_then(|d| custom_data_at(d, "flags", *i)) + .and_then(|v| v.as_bool()) + == Some(true), + ConditionProperty::UsingItem => owner.is_some_and(|o| o.using_this_item), + ConditionProperty::Broken => { + self.damageable() && self.damage_value() >= self.max_damage() - 1 + } + ConditionProperty::Damaged => self.damageable() && self.damage_value() > 0, + ConditionProperty::FishingRodCast => { + owner.is_some_and(|o| o.fishing_cast_with_this_item) + } + ConditionProperty::HasComponent { + component, + ignore_default, + } => { + if *ignore_default { + self.stack.patch.contains_key(component) + } else { + self.components.contains_key(component) + } + } + ConditionProperty::BundleHasSelectedItem => self.bundle_selected().is_some(), + ConditionProperty::Selected => owner.is_some_and(|o| o.is_local_player && o.is_selected), + ConditionProperty::Carried => owner.is_some_and(|o| o.is_local_player && o.is_carried), + ConditionProperty::ExtendedView => { + self.ctx.display == DisplayContext::Gui && self.env.has_shift_down() + } + ConditionProperty::KeybindDown(key) => self.env.is_keybind_down(key), + ConditionProperty::ViewEntity => owner.is_some_and(|o| o.is_view_entity), + ConditionProperty::Component(predicate) => { + self.env.component_matches(self.stack, predicate) + } + } + } + fn select_value(&self, property: &SelectProperty) -> Option { + let owner = self.ctx.owner; + match property { + SelectProperty::CustomModelData(i) => self + .component("minecraft:custom_model_data") + .and_then(|d| custom_data_at(d, "strings", *i)) + .cloned(), + SelectProperty::MainHand => owner.map(|o| { + Value::String(if o.main_arm_left { "left" } else { "right" }.to_owned()) + }), + SelectProperty::ChargeType => { + let projectiles = self + .component("minecraft:charged_projectiles") + .and_then(Value::as_array); + let kind = match projectiles { + None => "none", + Some(p) if p.is_empty() => "none", + Some(p) => { + if p.iter().any(|t| template_id(t) == Some("minecraft:firework_rocket")) { + "rocket" + } else { + "arrow" + } + } + }; + Some(Value::String(kind.to_owned())) + } + SelectProperty::TrimMaterial => { + let material = self.component("minecraft:trim")?.get("material")?.as_str()?; + identifier(material).ok().map(Value::String) + } + SelectProperty::BlockState(name) => self + .component("minecraft:block_state") + .and_then(|v| v.get("properties").or(Some(v))) + .and_then(|p| p.get(name)) + .map(|v| Value::String(v.as_str().map_or_else(|| v.to_string(), str::to_owned))), + SelectProperty::DisplayContext => { + Some(Value::String(self.ctx.display.name().to_owned())) + } + SelectProperty::LocalTime { + pattern, + locale, + time_zone, + } => Some(Value::String(self.env.local_time( + pattern, + locale, + time_zone.as_deref(), + ))), + SelectProperty::ContextEntityType => { + owner.map(|o| Value::String(o.entity_type.clone())) + } + SelectProperty::ContextDimension => self + .ctx + .level + .map(|l| Value::String(l.dimension.clone())), + SelectProperty::Component(component) => self.component(component).cloned(), + } + } + fn numeric(&self, property: &NumericProperty) -> f32 { + let owner = self.ctx.owner; + match property { + NumericProperty::BundleFullness => self.env.bundle_fullness(self.stack, self.components), + NumericProperty::Compass { + wobble, + target, + state, + } => self.compass(*wobble, *target, state), + NumericProperty::Cooldown => owner.map_or(0.0, |o| o.cooldown_percent), + NumericProperty::Count { normalize } => { + let count = self.stack.count as f32; + let max = self.max_stack_size() as f32; + if *normalize { + clamp(count / max, 0.0, 1.0) + } else { + clamp(count, 0.0, max) + } + } + NumericProperty::CrossbowPull => { + let Some(o) = owner else { return 0.0 }; + if self + .component("minecraft:charged_projectiles") + .and_then(Value::as_array) + .is_some_and(|p| !p.is_empty()) + { + return 0.0; + } + (o.use_duration - o.use_item_remaining_ticks) as f32 + / o.crossbow_charge_duration as f32 + } + NumericProperty::CustomModelData(i) => self + .component("minecraft:custom_model_data") + .and_then(|d| custom_data_at(d, "floats", *i)) + .and_then(|v| float(v).ok()) + .unwrap_or(0.0), + NumericProperty::Damage { normalize } => { + let damage = self.damage_value() as f32; + let max = self.max_damage() as f32; + if *normalize { + clamp(damage / max, 0.0, 1.0) + } else { + clamp(damage, 0.0, max) + } + } + NumericProperty::Time { + wobble, + source, + state, + } => self.time(*wobble, *source, state), + NumericProperty::UseCycle(period) => match owner { + Some(o) if o.using_this_item => (o.use_item_remaining_ticks as f32) % period, + _ => 0.0, + }, + NumericProperty::UseDuration { remaining } => match owner { + Some(o) if o.using_this_item => { + if *remaining { + o.use_item_remaining_ticks as f32 + } else { + (o.use_duration - o.use_item_remaining_ticks) as f32 + } + } + _ => 0.0, + }, + } + } + /// `Time.calculate` (through `NeedleDirectionHelper.get`). + fn time(&self, wobble: bool, source: TimeSource, state: &NeedleState) -> f32 { + let (Some(_), Some(level)) = (self.ctx.owner, self.ctx.level) else { + return 0.0; + }; + let target = match source { + TimeSource::Random => self.env.random_float(), + TimeSource::Daytime => level.sun_angle / 360.0, + TimeSource::MoonPhase => level.moon_phase as f32 / 8.0, + }; + let mut wobblers = state.0.lock().unwrap_or_else(|e| e.into_inner()); + let w = &mut wobblers[0]; + if w.should_update(wobble, level.game_time) { + w.update(wobble, 0.9, level.game_time, target); + } + w.value(wobble) + } + /// `CompassAngleState.calculate`. + fn compass(&self, wobble: bool, target: CompassTarget, state: &NeedleState) -> f32 { + let (Some(owner), Some(level)) = (self.ctx.owner, self.ctx.level) else { + return 0.0; + }; + let target_pos: Option = match target { + CompassTarget::None => None, + CompassTarget::Lodestone => self + .component("minecraft:lodestone_tracker") + .and_then(|t| t.get("target")) + .and_then(|t| { + Some(GlobalPos { + dimension: identifier(t.get("dimension")?.as_str()?).ok()?, + pos: { + let p = t.get("pos")?.as_array()?; + [ + int(p.first()?).ok()?, + int(p.get(1)?).ok()?, + int(p.get(2)?).ok()?, + ] + }, + }) + }), + CompassTarget::Spawn => level.respawn.clone(), + CompassTarget::Recovery => owner.last_death_location.clone(), + }; + let valid = target_pos.as_ref().filter(|t| { + t.dimension == level.dimension && { + let c = [ + f64::from(t.pos[0]) + 0.5, + f64::from(t.pos[1]) + 0.5, + f64::from(t.pos[2]) + 0.5, + ]; + let d = [ + c[0] - owner.position[0], + c[1] - owner.position[1], + c[2] - owner.position[2], + ]; + // `distToCenterSqr(position) < 1.0E-5F` + !(d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < f64::from(1.0E-5_f32)) + } + }); + let mut wobblers = state.0.lock().unwrap_or_else(|e| e.into_inner()); + let game_time = level.game_time; + let Some(target) = valid else { + // `getRandomlySpinningRotation` + let no_target = &mut wobblers[1]; + if no_target.should_update(wobble, game_time) { + let r = self.env.random_float(); + no_target.update(wobble, 0.8, game_time, r); + } + let hash = self.ctx.seed.wrapping_mul(1_327_217_883); + let rotation = no_target.value(wobble) + hash as f32 / 2.147_483_6E9; + return positive_modulo(rotation, 1.0); + }; + let center = [ + f64::from(target.pos[0]) + 0.5, + f64::from(target.pos[2]) + 0.5, + ]; + let angle_to_target = ((center[1] - owner.position[2]).atan2(center[0] - owner.position[0]) + / f64::from(std::f32::consts::PI * 2.0)) as f32; + let owner_y = positive_modulo(owner.visual_rotation_y_degrees / 360.0, 1.0); + let rotation = if owner.is_local_player && level.runs_normally { + let w = &mut wobblers[0]; + if w.should_update(wobble, game_time) { + w.update(wobble, 0.8, game_time, 0.5 - (owner_y - 0.25)); + } + angle_to_target + w.value(wobble) + } else { + 0.5 - (owner_y - 0.25 - angle_to_target) + }; + positive_modulo(rotation, 1.0) + } + fn tint(&self, source: &TintSource) -> i32 { + match source { + TintSource::Constant(v) => *v, + TintSource::CustomModelData { index, default } => self + .component("minecraft:custom_model_data") + .and_then(|d| custom_data_at(d, "colors", *index)) + .and_then(|v| rgb(v).ok()) + .map_or(opaque(*default), opaque), + TintSource::Dye(default) => match self.component("minecraft:dyed_color") { + Some(v) => opaque( + rgb(v.get("rgb").unwrap_or(v)).unwrap_or(0), + ), + None => *default, + }, + TintSource::Grass { + temperature, + downfall, + } => self + .env + .grass_color(f64::from(*temperature), f64::from(*downfall)), + TintSource::Firework(default) => { + let colors: Vec = self + .component("minecraft:firework_explosion") + .and_then(|e| e.get("colors")) + .and_then(Value::as_array) + .map(|c| c.iter().filter_map(|v| int(v).ok()).collect()) + .unwrap_or_default(); + match colors.len() { + 0 => *default, + 1 => opaque(colors[0]), + n => { + let n = n as i32; + let sum = |shift: u32| -> i32 { + colors.iter().map(|c| (c >> shift) & 255).sum::() / n + }; + argb(255, sum(16), sum(8), sum(0)) + } + } + } + TintSource::Potion(default) => match self.component("minecraft:potion_contents") { + Some(contents) => { + let custom = contents.get("custom_color").and_then(|c| int(c).ok()); + opaque( + custom + .or_else(|| self.env.potion_effect_color(contents)) + .unwrap_or(*default), + ) + } + None => opaque(*default), + }, + TintSource::Team(default) => opaque( + self.ctx + .owner + .and_then(|o| o.team_color) + .unwrap_or(*default), + ), + } + } +} + +/// `Mth.clamp(float, min, max)` with `Math.min`'s NaN propagation. +fn clamp(v: f32, min: f32, max: f32) -> f32 { + if v < min { min } else { java_min(v, max) } +} +fn java_min(a: f32, b: f32) -> f32 { + if a.is_nan() { + a + } else if b.is_nan() { + b + } else if a == 0.0 && b == 0.0 { + if a.is_sign_negative() { a } else { b } + } else if a < b { + a + } else { + b + } +} +fn enchantments_present(v: &Value) -> bool { + // `ItemEnchantments` is a level map, optionally wrapped as {"levels": {...}}. + let map = v.get("levels").unwrap_or(v); + map.as_object().is_some_and(|m| !m.is_empty()) +} +fn custom_data_at<'a>(data: &'a Value, list: &str, index: i32) -> Option<&'a Value> { + data.get(list)?.as_array()?.get(usize::try_from(index).ok()?) +} +fn template_id(t: &Value) -> Option<&str> { + t.get("id")?.as_str() +} +/// `ItemStackTemplate.create`: id, count and a component patch. +fn stack_from_template(template: &Value) -> Option { + let id = identifier(template.get("id")?.as_str()?).ok()?; + let count = template.get("count").map_or(Some(1), |c| int(c).ok())?; + let mut stack = StackView::new(&id, count); + if let Some(components) = template.get("components").and_then(Value::as_object) { + for (key, value) in components { + match key.strip_prefix('!') { + Some(removed) => { + stack.patch.insert(identifier(removed).ok()?, None); + } + None => { + stack.patch.insert(identifier(key).ok()?, Some(value.clone())); + } + } + } + } + Some(stack) +} + +/// `RangeSelectItemModel.lastIndexLessOrEqual`. +fn last_index_less_or_equal(entries: &[(f32, ItemModelNode)], needle: f32) -> Option { + let haystack: Vec = entries.iter().map(|e| e.0).collect(); + let found = if haystack.len() < 16 { + haystack + .iter() + .position(|h| *h > needle) + .map_or(haystack.len() as i64 - 1, |i| i as i64 - 1) + } else { + match binary_search(&haystack, needle) { + Ok(index) => index as i64, + Err(insertion) => insertion as i64 - 1, + } + }; + usize::try_from(found).ok() +} +/// `Arrays.binarySearch(float[], float)`, including its handling of equal +/// values (-0.0 below 0.0, NaN above everything). +fn binary_search(a: &[f32], key: f32) -> std::result::Result { + let (mut low, mut high) = (0i64, a.len() as i64 - 1); + let bits = |v: f32| -> i32 { + if v.is_nan() { 0x7fc0_0000 } else { v.to_bits() as i32 } + }; + while low <= high { + let mid = (low + high) >> 1; + let value = a[mid as usize]; + if value < key { + low = mid + 1; + } else if value > key { + high = mid - 1; + } else { + let (mid_bits, key_bits) = (bits(value), bits(key)); + if mid_bits == key_bits { + return Ok(mid as usize); + } else if mid_bits < key_bits { + low = mid + 1; + } else { + high = mid - 1; + } + } + } + Err(low as usize) +} + +#[cfg(test)] +mod tests; diff --git a/crates/horizon-assets/src/item_model/special.rs b/crates/horizon-assets/src/item_model/special.rs new file mode 100644 index 000000000..f62122bf2 --- /dev/null +++ b/crates/horizon-assets/src/item_model/special.rs @@ -0,0 +1,254 @@ +//! `special` item models: the block-entity style renderers an item can ask +//! for (`SpecialModelRenderers`), their codec fields and what each reads from +//! the stack (`extractArgument`). +use super::{Result, float, get, ident, object, required, string}; +use crate::json::error as err; +use serde_json::{Map, Value, json}; + +#[derive(Clone, Debug, PartialEq)] +pub enum SpecialKind { + Bell, + Banner { + color: String, + wall: bool, + }, + Book { + open_angle: f32, + page1: f32, + page2: f32, + }, + Conduit, + Chest { + texture: String, + openness: f32, + chest_type: String, + }, + CopperGolemStatue { + texture: String, + pose: String, + }, + DecoratedPot, + EndCube { + effect: String, + }, + Head { + kind: String, + texture: Option, + animation: f32, + }, + PlayerHead, + ShulkerBox { + texture: String, + openness: f32, + }, + Shield, + Trident, +} +#[derive(Clone, Debug, PartialEq)] +pub struct SpecialModel { + pub kind: SpecialKind, +} + +const DYES: [&str; 16] = [ + "white", + "orange", + "magenta", + "light_blue", + "yellow", + "lime", + "pink", + "gray", + "light_gray", + "cyan", + "purple", + "blue", + "brown", + "green", + "red", + "black", +]; +fn one_of(v: &Value, names: &[&str]) -> Result { + let s = string(v)?; + if names.contains(&s.as_str()) { + Ok(s) + } else { + Err(err("invalid enum name")) + } +} + +impl SpecialModel { + pub fn decode(v: &Value) -> Result { + let m = object(v)?; + let float_or = |key: &str, default: f32| get(m, key).map_or(Ok(default), float); + let kind = match ident(required(m, "type")?)?.as_str() { + "minecraft:bell" => SpecialKind::Bell, + "minecraft:banner" => SpecialKind::Banner { + color: one_of(required(m, "color")?, &DYES)?, + wall: match get(m, "attachment") { + None => false, + Some(a) => one_of(a, &["wall", "ground"])? == "wall", + }, + }, + "minecraft:book" => SpecialKind::Book { + open_angle: float(required(m, "open_angle")?)?, + page1: float(required(m, "page1")?)?, + page2: float(required(m, "page2")?)?, + }, + "minecraft:conduit" => SpecialKind::Conduit, + "minecraft:chest" => SpecialKind::Chest { + texture: ident(required(m, "texture")?)?, + openness: float_or("openness", 0.0)?, + chest_type: match get(m, "chest_type") { + None => "single".to_owned(), + Some(t) => one_of(t, &["single", "left", "right"])?, + }, + }, + "minecraft:copper_golem_statue" => SpecialKind::CopperGolemStatue { + texture: ident(required(m, "texture")?)?, + pose: one_of( + required(m, "pose")?, + &["standing", "sitting", "running", "star"], + )?, + }, + "minecraft:decorated_pot" => SpecialKind::DecoratedPot, + "minecraft:end_cube" => SpecialKind::EndCube { + effect: one_of(required(m, "effect")?, &["portal", "gateway"])?, + }, + "minecraft:head" => SpecialKind::Head { + kind: one_of( + required(m, "kind")?, + &[ + "skeleton", + "wither_skeleton", + "player", + "zombie", + "creeper", + "piglin", + "dragon", + ], + )?, + texture: get(m, "texture").map(ident).transpose()?, + animation: float_or("animation", 0.0)?, + }, + "minecraft:player_head" => SpecialKind::PlayerHead, + "minecraft:shulker_box" => SpecialKind::ShulkerBox { + texture: ident(required(m, "texture")?)?, + openness: float_or("openness", 0.0)?, + }, + "minecraft:shield" => SpecialKind::Shield, + "minecraft:trident" => SpecialKind::Trident, + _ => return Err(err("unknown special model type")), + }; + Ok(Self { kind }) + } + /// The codec's encoding: optional fields equal to their default are omitted. + pub fn to_json(&self) -> Value { + let mut m = Map::new(); + let mut put = |k: &str, v: Value| { + m.insert(k.to_owned(), v); + }; + let ty = match &self.kind { + SpecialKind::Bell => "bell", + SpecialKind::Banner { color, wall } => { + put("color", json!(color)); + if *wall { + put("attachment", json!("wall")); + } + "banner" + } + SpecialKind::Book { + open_angle, + page1, + page2, + } => { + put("open_angle", json!(open_angle)); + put("page1", json!(page1)); + put("page2", json!(page2)); + "book" + } + SpecialKind::Conduit => "conduit", + SpecialKind::Chest { + texture, + openness, + chest_type, + } => { + put("texture", json!(texture)); + if *openness != 0.0 { + put("openness", json!(openness)); + } + if chest_type != "single" { + put("chest_type", json!(chest_type)); + } + "chest" + } + SpecialKind::CopperGolemStatue { texture, pose } => { + put("texture", json!(texture)); + put("pose", json!(pose)); + "copper_golem_statue" + } + SpecialKind::DecoratedPot => "decorated_pot", + SpecialKind::EndCube { effect } => { + put("effect", json!(effect)); + "end_cube" + } + SpecialKind::Head { + kind, + texture, + animation, + } => { + put("kind", json!(kind)); + if let Some(t) = texture { + put("texture", json!(t)); + } + if *animation != 0.0 { + put("animation", json!(animation)); + } + "head" + } + SpecialKind::PlayerHead => "player_head", + SpecialKind::ShulkerBox { texture, openness } => { + if texture != "minecraft:shulker" { + put("texture", json!(texture)); + } + if *openness != 0.0 { + put("openness", json!(openness)); + } + "shulker_box" + } + SpecialKind::Shield => "shield", + SpecialKind::Trident => "trident", + }; + m.insert("type".to_owned(), json!(format!("minecraft:{ty}"))); + Value::Object(m) + } + pub fn type_name(&self) -> String { + self.to_json()["type"] + .as_str() + .unwrap_or_default() + .to_owned() + } + /// What `extractArgument` reads: banners their pattern layers, shields + /// their base colour and layers, decorated pots their sherds and player + /// heads their profile. Absent components give `null`. + pub fn argument(&self, component: &dyn Fn(&str) -> Option) -> Value { + match &self.kind { + SpecialKind::Banner { .. } => { + component("minecraft:banner_patterns").unwrap_or(Value::Null) + } + SpecialKind::DecoratedPot => { + component("minecraft:pot_decorations").unwrap_or(Value::Null) + } + SpecialKind::PlayerHead => component("minecraft:profile").unwrap_or(Value::Null), + SpecialKind::Shield => { + let mut m = Map::new(); + for key in ["minecraft:banner_patterns", "minecraft:base_color"] { + if let Some(v) = component(key) { + m.insert(key.to_owned(), v); + } + } + Value::Object(m) + } + _ => Value::Null, + } + } +} diff --git a/crates/horizon-assets/src/item_model/tests.rs b/crates/horizon-assets/src/item_model/tests.rs new file mode 100644 index 000000000..4563e55b7 --- /dev/null +++ b/crates/horizon-assets/src/item_model/tests.rs @@ -0,0 +1 @@ +use super::*; diff --git a/crates/horizon-assets/src/lib.rs b/crates/horizon-assets/src/lib.rs index e52fe3a32..cee09ce5d 100644 --- a/crates/horizon-assets/src/lib.rs +++ b/crates/horizon-assets/src/lib.rs @@ -4,7 +4,10 @@ pub mod animation; pub mod bake; pub mod blockstate; +pub mod item_bake; +pub mod item_model; mod json; +pub mod math; pub mod model; pub mod resolve; diff --git a/crates/horizon-assets/src/math.rs b/crates/horizon-assets/src/math.rs new file mode 100644 index 000000000..1b81c7891 --- /dev/null +++ b/crates/horizon-assets/src/math.rs @@ -0,0 +1,140 @@ +//! Column-major `Matrix4f` arithmetic with the operand order of JOML's +//! default (non-FMA) code paths, for composing item-model transformations. + +/// A JOML `Matrix4f`: `m[column][row]`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Mat4(pub [[f32; 4]; 4]); + +impl Mat4 { + pub const IDENTITY: Self = Self([ + [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.0, 0.0, 0.0, 1.0], + ]); + /// `Matrix4f.translation(x, y, z)`. + pub fn translation(t: [f32; 3]) -> Self { + let mut m = Self::IDENTITY; + m.0[3][..3].copy_from_slice(&t); + m + } + /// `ExtraCodecs.MATRIX4F`: sixteen values in row-major order. + pub fn from_row_major(values: [f32; 16]) -> Self { + let mut m = Self([[0.0; 4]; 4]); + for (i, v) in values.into_iter().enumerate() { + m.0[i & 3][i >> 2] = v; + } + m + } + /// The matrix as `[row][column]` entries, the order `getRowColumn` reads. + pub fn rows(&self) -> [[f32; 4]; 4] { + std::array::from_fn(|r| std::array::from_fn(|c| self.0[c][r])) + } + /// `this * right` (`Matrix4f.mul`). + pub fn mul(&self, right: &Self) -> Self { + let (m, r) = (&self.0, &right.0); + let mut out = [[0.0; 4]; 4]; + for c in 0..4 { + for row in 0..4 { + out[c][row] = m[0][row] * r[c][0] + + m[1][row] * r[c][1] + + m[2][row] * r[c][2] + + m[3][row] * r[c][3]; + } + } + Self(out) + } + /// `Matrix4f.translate(x, y, z)` (`translateGeneric`). + pub fn translate(&self, t: [f32; 3]) -> Self { + let mut out = *self; + for row in 0..4 { + out.0[3][row] = + self.0[0][row] * t[0] + (self.0[1][row] * t[1] + (self.0[2][row] * t[2] + self.0[3][row])); + } + out + } + /// `Matrix4f.scale(x, y, z)`: the first three columns are scaled. + pub fn scale(&self, s: [f32; 3]) -> Self { + let mut out = *self; + for c in 0..3 { + for row in 0..4 { + out.0[c][row] = self.0[c][row] * s[c]; + } + } + out + } + /// `Matrix4f.rotate(Quaternionfc)` (`rotateGeneric`). + pub fn rotate(&self, q: [f32; 4]) -> Self { + let [x, y, z, w] = q; + let (w2, x2, y2, z2) = (w * w, x * x, y * y, z * z); + let (zw, xy, xz, yw, yz, xw) = (z * w, x * y, x * z, y * w, y * z, x * w); + let (dzw, dxy, dxz, dyw, dyz, dxw) = (zw + zw, xy + xy, xz + xz, yw + yw, yz + yz, xw + xw); + let r = [ + [w2 + x2 - z2 - y2, dxy + dzw, dxz - dyw], + [dxy - dzw, y2 - z2 + w2 - x2, dyz + dxw], + [dyw + dxz, dyz - dxw, z2 - y2 - x2 + w2], + ]; + let m = &self.0; + let mut out = *self; + for c in 0..3 { + for row in 0..4 { + out.0[c][row] = m[0][row] * r[c][0] + m[1][row] * r[c][1] + m[2][row] * r[c][2]; + } + } + out + } + pub fn is_finite(&self) -> bool { + self.0.iter().flatten().all(|v| v.is_finite()) + } +} + +/// `Quaternionf.normalize` as the codec applies it to four components. +pub fn normalize_quaternion(q: [f32; 4]) -> [f32; 4] { + let [x, y, z, w] = q; + let inv = 1.0 / (x * x + (y * y + (z * z + w * w))).sqrt(); + [x * inv, y * inv, z * inv, w * inv] +} +/// `Quaternionf.rotationXYZ` from angles in radians. +pub fn quaternion_xyz(x: f32, y: f32, z: f32) -> [f32; 4] { + let half = |a: f32| -> (f32, f32) { + let h = a * 0.5; + ((f64::from(h).sin()) as f32, (f64::from(h).cos()) as f32) + }; + let ((sx, cx), (sy, cy), (sz, cz)) = (half(x), half(y), half(z)); + let (cx_cy, sx_cy, cx_sy, sx_sy) = (cx * cy, sx * cy, cx * sy, sx * sy); + [ + sx_cy * cz + cx_sy * sz, + cx_sy * cz - sx_cy * sz, + cx_cy * sz + sx_sy * cz, + cx_cy * cz - sx_sy * sz, + ] +} +/// `new Quaternionf(new AxisAngle4f(angle, axis))`. +pub fn quaternion_from_axis_angle(angle: f32, axis: [f32; 3]) -> [f32; 4] { + let half = angle * 0.5; + let (sin, cos) = (half.sin(), half.cos()); + let norm = 1.0 / (axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]).sqrt(); + let s = sin * norm; + [axis[0] * s, axis[1] * s, axis[2] * s, cos] +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn composes_in_joml_order() { + let t = Mat4::translation([1.0, 2.0, 3.0]); + let s = Mat4::IDENTITY.scale([2.0, -1.0, 1.0]); + let m = t.mul(&s); + assert_eq!(m.0[0][0], 2.0); + assert_eq!(m.0[1][1], -1.0); + assert_eq!(m.0[3][..3], [1.0, 2.0, 3.0]); + assert_eq!(s.mul(&t).0[3][..3], [2.0, -2.0, 3.0]); + } + #[test] + fn quarter_turn_about_z_rotates_x_into_y() { + let q = quaternion_from_axis_angle(std::f32::consts::FRAC_PI_2, [0.0, 0.0, 1.0]); + let m = Mat4::IDENTITY.rotate(q); + assert!((m.0[0][1] - 1.0).abs() < 1e-6 && m.0[0][0].abs() < 1e-6); + } +} diff --git a/crates/horizon-assets/src/resolve.rs b/crates/horizon-assets/src/resolve.rs index ca601f0cc..6a12744e1 100644 --- a/crates/horizon-assets/src/resolve.rs +++ b/crates/horizon-assets/src/resolve.rs @@ -6,6 +6,8 @@ use std::{ }; pub const MISSING_MODEL: &str = "minecraft:builtin/missing"; +/// `ItemModelGenerator.GENERATED_ITEM_MODEL_ID`. +pub const GENERATED_MODEL: &str = "minecraft:builtin/generated"; /// Decoded models are immutable and their inherited geometry is shared. pub struct ModelLibrary { @@ -21,8 +23,14 @@ pub struct ResolvedCuboidModel { /// Cyclic and dangling aliases are absent from `textures`. pub unresolved_textures: BTreeSet, geometry: Option>, + generated: bool, } impl ResolvedCuboidModel { + /// Whether the top geometry is `builtin/generated`'s layer extrusion + /// (no model closer to the leaf has elements of its own). + pub fn uses_item_generator(&self) -> bool { + self.generated + } pub fn elements(&self) -> &[Option] { self.geometry .as_ref() @@ -39,6 +47,25 @@ impl ResolvedCuboidModel { } } impl ModelLibrary { + /// A library that also knows `builtin/generated`, the parent of every + /// flat item model; the native client registers it as a special model. + pub fn with_item_generator(mut models: BTreeMap) -> Result { + models.insert( + GENERATED_MODEL.to_owned(), + CuboidModel { + parent: None, + ambient_occlusion: None, + gui_light: Some(GuiLight::Front), + textures: BTreeMap::from([( + "particle".to_owned(), + TextureSlot::Reference("layer0".to_owned()), + )]), + elements: None, + display: None, + }, + ); + Self::new(models) + } pub fn new(models: BTreeMap) -> Result { let mut decoded = BTreeMap::new(); for (name, model) in models { @@ -64,12 +91,14 @@ impl ModelLibrary { let mut name = identifier(name)?; let mut visited = BTreeSet::new(); let mut chain = Vec::new(); + let mut names = Vec::new(); loop { if !visited.insert(name.clone()) { return Err(error("cyclic model parent")); } let model = self.models.get(&name).unwrap_or(&self.missing); chain.push(model); + names.push(name.clone()); match &model.parent { Some(parent) => name = parent.clone(), None => break, @@ -87,6 +116,11 @@ impl ModelLibrary { .iter() .find(|m| m.elements.is_some()) .map(|m| Arc::clone(m)); + let generated = chain + .iter() + .zip(&names) + .find(|(m, name)| m.elements.is_some() || *name == GENERATED_MODEL) + .is_some_and(|(_, name)| name == GENERATED_MODEL); let display = ItemTransforms { contexts: std::array::from_fn(|index| { chain @@ -146,6 +180,7 @@ impl ModelLibrary { textures, unresolved_textures, geometry, + generated, }) } } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemModelOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemModelOracle.java new file mode 100644 index 000000000..c5d708b0c --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemModelOracle.java @@ -0,0 +1,407 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import com.mojang.blaze3d.platform.NativeImage; +import com.mojang.serialization.Codec; +import com.mojang.serialization.JsonOps; +import com.mojang.serialization.MapCodec; +import java.io.*; +import java.lang.reflect.*; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.CompletableFuture; +import java.util.stream.*; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.model.geom.EntityModelSet; +import net.minecraft.client.renderer.item.*; +import net.minecraft.client.renderer.item.properties.select.SelectItemModelProperty; +import net.minecraft.client.renderer.special.SpecialModelRenderer; +import net.minecraft.client.renderer.special.SpecialModelRenderers; +import net.minecraft.client.renderer.texture.*; +import net.minecraft.client.resources.metadata.animation.AnimationMetadataSection; +import net.minecraft.client.resources.model.*; +import net.minecraft.client.resources.model.cuboid.*; +import net.minecraft.client.resources.model.geometry.BakedQuad; +import net.minecraft.client.resources.model.sprite.SpriteGetter; +import net.minecraft.client.resources.model.sprite.SpriteId; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.RegistryAccess; +import net.minecraft.core.component.DataComponentType; +import net.minecraft.core.component.DataComponents; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.data.registries.VanillaRegistries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.RegistryOps; +import net.minecraft.util.StrictJsonParser; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.ItemOwner; +import net.minecraft.world.entity.HumanoidArm; +import net.minecraft.world.entity.decoration.ArmorStand; +import net.minecraft.world.item.*; +import net.minecraft.world.item.component.BundleContents; +import net.minecraft.world.level.GrassColor; +import net.minecraft.world.level.Level; +import org.joml.Matrix4f; +import org.joml.Vector3fc; + +/** + * Drives the pinned client's own item pipeline headlessly: the ClientItem codec, + * ModelDiscovery, ModelBakery with real baked item models, ItemModelResolver + * semantics and ItemStackRenderState layers. Sprites are real PNGs in a unit + * atlas; the player skin cache and GPU are never touched. + */ +public final class VanillaItemModelOracle { + private static final Gson JSON = new GsonBuilder().serializeNulls().create(); + private static long bits(float value) { return Integer.toUnsignedLong(Float.floatToIntBits(value)); } + static Map map(Object... values) { + var result = new TreeMap(); + for (int i = 0; i < values.length; i += 2) result.put((String) values[i], values[i + 1]); + return result; + } + + static Path root; + static HolderLookup.Provider registries; + static RegistryOps ops; + static String frozenTime = ""; + static final Identifier BLOCKS = TextureAtlas.LOCATION_BLOCKS, ITEMS = TextureAtlas.LOCATION_ITEMS; + + static final class Sprite extends TextureAtlasSprite { + Sprite(Identifier atlas, SpriteContents contents) { super(atlas, contents, contents.width(), contents.height(), 0, 0, 0); } + } + + /** Sprites loaded on demand from the extracted jar. */ + static final class Regions extends HashMap { + final boolean items; + Regions(boolean items) { this.items = items; } + @Override public TextureAtlasSprite get(Object key) { + var id = (Identifier) key; + boolean itemAtlas = id.getPath().startsWith("item/") || id.getPath().startsWith("trims/"); + if (itemAtlas != items) return null; + return computeIfAbsent(id, k -> load(k, items ? ITEMS : BLOCKS)); + } + } + static TextureAtlasSprite load(Identifier id, Identifier atlas) { + try { + var png = root.resolve("assets").resolve(id.getNamespace()).resolve("textures").resolve(id.getPath() + ".png"); + if (!Files.isRegularFile(png)) return null; + NativeImage image; + try (var in = Files.newInputStream(png)) { image = NativeImage.read(in); } + var mcmeta = png.resolveSibling(png.getFileName() + ".mcmeta"); + Optional animation = Optional.empty(); + if (Files.isRegularFile(mcmeta)) { + var json = JsonParser.parseString(Files.readString(mcmeta)).getAsJsonObject(); + if (json.has("animation")) + animation = Optional.of(AnimationMetadataSection.CODEC.parse(JsonOps.INSTANCE, json.get("animation")).getOrThrow()); + } + var size = animation.map(a -> a.calculateFrameSize(image.getWidth(), image.getHeight())) + .orElse(new net.minecraft.client.resources.metadata.animation.FrameSize(image.getWidth(), image.getHeight())); + return new Sprite(atlas, new SpriteContents(id, size, image, animation, List.of(), Optional.empty())); + } catch (IOException e) { throw new UncheckedIOException(e); } + } + + // --- Tagging of special renderers so the layer carries its codec form. --- + static final class Tagged implements SpecialModelRenderer.Unbaked { + final SpecialModelRenderer.Unbaked delegate; + Tagged(SpecialModelRenderer.Unbaked delegate) { this.delegate = delegate; } + @SuppressWarnings({"unchecked", "rawtypes"}) + public MapCodec> type() { return (MapCodec) delegate.type(); } + public SpecialModelRenderer bake(SpecialModelRenderer.BakingContext context) { + var baked = delegate.bake(context); + if (baked == null) return null; + @SuppressWarnings({"unchecked", "rawtypes"}) JsonElement config = SpecialModelRenderers.CODEC.encodeStart(JsonOps.INSTANCE, (SpecialModelRenderer.Unbaked) delegate).getOrThrow(); + return new TaggedRenderer(baked, config); + } + } + static final class TaggedRenderer implements SpecialModelRenderer { + final SpecialModelRenderer delegate; final JsonElement config; + TaggedRenderer(SpecialModelRenderer delegate, JsonElement config) { this.delegate = delegate; this.config = config; } + public void submit(Object argument, com.mojang.blaze3d.vertex.PoseStack poseStack, net.minecraft.client.renderer.SubmitNodeCollector collector, int light, int overlay, boolean foil, int outline) {} + public void getExtents(java.util.function.Consumer output) { delegate.getExtents(output); } + public Object extractArgument(ItemStack stack) { return new Argument(argument(config.getAsJsonObject().get("type").getAsString(), stack)); } + } + record Argument(JsonElement json) {} + static JsonElement encode(DataComponentType type, ItemStack stack) { + var value = stack.get((DataComponentType) type); + if (value == null) return JsonNull.INSTANCE; + @SuppressWarnings({"unchecked", "rawtypes"}) var result = ((Codec) type.codecOrThrow()).encodeStart(ops, value).getOrThrow(); + return (JsonElement) result; + } + static JsonElement argument(String type, ItemStack stack) { + return switch (type) { + case "minecraft:banner" -> encode(DataComponents.BANNER_PATTERNS, stack); + case "minecraft:decorated_pot" -> encode(DataComponents.POT_DECORATIONS, stack); + case "minecraft:player_head" -> encode(DataComponents.PROFILE, stack); + case "minecraft:shield" -> { + var o = new JsonObject(); + var patterns = encode(DataComponents.BANNER_PATTERNS, stack); + if (!patterns.isJsonNull()) o.add("minecraft:banner_patterns", patterns); + var color = encode(DataComponents.BASE_COLOR, stack); + if (!color.isJsonNull()) o.add("minecraft:base_color", color); + yield o; + } + default -> JsonNull.INSTANCE; + }; + } + /** Stands in for LocalTime so a case can script the formatted time. */ + record FrozenTime(Codec valueCodec) implements SelectItemModelProperty { + public String get(ItemStack s, ClientLevel l, net.minecraft.world.entity.LivingEntity o, int seed, ItemDisplayContext d) { return frozenTime; } + @SuppressWarnings({"unchecked", "rawtypes"}) + public SelectItemModelProperty.Type type() { return net.minecraft.client.renderer.item.properties.select.LocalTime.TYPE; } + } + @SuppressWarnings({"unchecked", "rawtypes"}) + static ItemModel.Unbaked tag(ItemModel.Unbaked u) { + if (u instanceof SpecialModelWrapper.Unbaked s) + return new SpecialModelWrapper.Unbaked(s.base(), s.transformation(), new Tagged(s.specialModel())); + if (u instanceof CompositeModel.Unbaked c) + return new CompositeModel.Unbaked(c.models().stream().map(VanillaItemModelOracle::tag).collect(Collectors.toList()), c.transformation()); + if (u instanceof ConditionalItemModel.Unbaked c) + return new ConditionalItemModel.Unbaked(c.transformation(), c.property(), tag(c.onTrue()), tag(c.onFalse())); + if (u instanceof SelectItemModel.Unbaked s) { + var sw = (SelectItemModel.UnbakedSwitch) s.unbakedSwitch(); + var cases = new ArrayList(); + for (var c : (List) sw.cases()) cases.add(new SelectItemModel.SwitchCase(c.values(), tag(c.model()))); + Object property = sw.property(); + if (property instanceof net.minecraft.client.renderer.item.properties.select.LocalTime) property = new FrozenTime(Codec.STRING); + return new SelectItemModel.Unbaked(s.transformation(), new SelectItemModel.UnbakedSwitch((SelectItemModelProperty) property, cases), s.fallback().map(VanillaItemModelOracle::tag)); + } + if (u instanceof RangeSelectItemModel.Unbaked r) { + var entries = new ArrayList(); + for (var e : r.entries()) entries.add(new RangeSelectItemModel.Entry(e.threshold(), tag(e.model()))); + return new RangeSelectItemModel.Unbaked(r.transformation(), r.property(), r.scale(), entries, r.fallback().map(VanillaItemModelOracle::tag)); + } + return u; + } + + // --- Scripted owner --- + static final class Actor extends ArmorStand { + boolean using; int remaining; ItemStack stack = ItemStack.EMPTY; HumanoidArm arm = HumanoidArm.RIGHT; EntityType kind = EntityTypes.PLAYER; + Actor() { super(null, null); } + @Override public boolean isUsingItem() { return using; } + @Override public ItemStack getUseItem() { return using ? stack : ItemStack.EMPTY; } + @Override public int getUseItemRemainingTicks() { return remaining; } + @Override public HumanoidArm getMainArm() { return arm; } + @Override public net.minecraft.core.Holder.Reference> typeHolder() { return kind.builtInRegistryHolder(); } + } + static Object unsafe; static Method allocate; + @SuppressWarnings("unchecked") static T make(Class type) throws Exception { return (T) allocate.invoke(unsafe, type); } + + static final class Resolver extends ItemModelResolver { + Map models; Map properties; ItemModel missing; + Resolver() { super(null); } + @Override public void appendItemLayers(ItemStackRenderState output, ItemStack item, ItemDisplayContext context, Level level, ItemOwner owner, int seed) { + Identifier id = item.get(DataComponents.ITEM_MODEL); + if (id != null) { + output.setOversizedInGui(properties.getOrDefault(id, ClientItem.Properties.DEFAULT).oversizedInGui()); + models.getOrDefault(id, missing).update(output, item, this, context, level instanceof ClientLevel c ? c : null, owner, seed); + } + } + } + + static Object field(Object target, Class type, String name) throws Exception { + var f = type.getDeclaredField(name); f.setAccessible(true); return f.get(target); + } + static Object quad(BakedQuad q) { + var positions = new long[4][3]; var uvs = new long[4][2]; + for (int i = 0; i < 4; i++) { + var p = q.position(i); positions[i] = new long[]{bits(p.x()), bits(p.y()), bits(p.z())}; + long packed = q.packedUV(i); uvs[i] = new long[]{packed >>> 32, packed & 0xffffffffL}; + } + var info = q.materialInfo(); + return map("positions", positions, "uv", uvs, "facing", q.direction().getName(), "tint", info.tintIndex(), + "sprite", info.sprite().contents().name().toString(), + "shade", info.shadeDirectionOverride() == null ? null : info.shadeDirectionOverride().getName(), "light", info.lightEmission()); + } + static Object matrix(Matrix4f m) { + var rows = new long[16]; + for (int r = 0; r < 4; r++) for (int c = 0; c < 4; c++) rows[r * 4 + c] = bits(m.getRowColumn(r, c)); + return rows; + } + static Object layer(ItemStackRenderState state, Object layer, ItemDisplayContext context) throws Exception { + var type = layer.getClass(); + var out = new TreeMap(); + var special = (SpecialModelRenderer) field(layer, type, "specialRenderer"); + var tints = (it.unimi.dsi.fastutil.ints.IntList) field(layer, type, "tintLayers"); + out.put("tints", tints == null ? new int[0] : tints.toIntArray()); + out.put("foil", ((ItemStackRenderState.FoilType) field(layer, type, "foilType")).name().toLowerCase(Locale.ROOT)); + var pose = new com.mojang.blaze3d.vertex.PoseStack.Pose(); + var apply = type.getDeclaredMethod("applyTransform", com.mojang.blaze3d.vertex.PoseStack.Pose.class); + apply.setAccessible(true); apply.invoke(layer, pose); + out.put("matrix", matrix(pose.pose())); + out.put("uses_block_light", field(layer, type, "usesBlockLight")); + var particle = (net.minecraft.client.resources.model.sprite.Material.Baked) field(layer, type, "particleMaterial"); + out.put("particle", particle == null ? null : particle.sprite().contents().name().toString()); + var transform = (net.minecraft.client.resources.model.cuboid.ItemTransform) field(layer, type, "itemTransform"); + out.put("has_transform", transform != net.minecraft.client.resources.model.cuboid.ItemTransform.NO_TRANSFORM); + if (special instanceof TaggedRenderer tagged) { + out.put("kind", "special"); + out.put("special", tagged.config); + var argument = field(layer, type, "argumentForSpecialRendering"); + out.put("argument", argument instanceof Argument a ? a.json() : JsonNull.INSTANCE); + } else { + var quads = (net.minecraft.client.resources.model.geometry.ItemQuads) field(layer, type, "quads"); + out.put("quads", quads.all().stream().map(VanillaItemModelOracle::quad).toList()); + out.put("kind", "model"); + } + return out; + } + + static Map prototypes = new HashMap<>(); + + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion(); + net.minecraft.server.Bootstrap.bootStrap(); + ItemModels.bootstrap(); + SpecialModelRenderers.bootstrap(); + net.minecraft.client.color.item.ItemTintSources.bootstrap(); + net.minecraft.client.renderer.item.properties.select.SelectItemModelProperties.bootstrap(); + net.minecraft.client.renderer.item.properties.conditional.ConditionalItemModelProperties.bootstrap(); + net.minecraft.client.renderer.item.properties.numeric.RangeSelectItemModelProperties.bootstrap(); + var u = Class.forName("sun.misc.Unsafe"); + var uf = u.getDeclaredField("theUnsafe"); uf.setAccessible(true); unsafe = uf.get(null); + allocate = u.getMethod("allocateInstance", Class.class); + root = Path.of(args[0]); + registries = VanillaRegistries.createWorldLookup(); + ops = RegistryOps.create(JsonOps.INSTANCE, registries); + // Default components come from the prepared export of the vanilla reports. + var defaults = JsonParser.parseString(Files.readString(Path.of(args[3]))).getAsJsonObject(); + for (var item : BuiltInRegistries.ITEM) { + var json = defaults.get(BuiltInRegistries.ITEM.getKey(item).toString()); + var map = json == null ? net.minecraft.core.component.DataComponentMap.EMPTY + : net.minecraft.core.component.DataComponentMap.CODEC.parse(ops, json).getOrThrow(); + item.builtInRegistryHolder().bindComponents(map); + } + + // Grass colour map for the grass tint. + try (var in = Files.newInputStream(root.resolve("assets/minecraft/textures/colormap/grass.png")); var image = NativeImage.read(in)) { + GrassColor.init(image.getPixels()); + } + + // Every model file. + var models = new HashMap(); + try (Stream files = Files.walk(root.resolve("assets/minecraft/models"))) { + for (var file : (Iterable) files.filter(p -> p.toString().endsWith(".json"))::iterator) { + var relative = root.resolve("assets/minecraft/models").relativize(file).toString().replace('\\', '/'); + try (var reader = Files.newBufferedReader(file)) { + models.put(Identifier.withDefaultNamespace(relative.substring(0, relative.length() - 5)), CuboidModel.fromStream(reader)); + } catch (RuntimeException ignored) {} + } + } + // Every item definition. + var output = Files.newBufferedWriter(Path.of(args[2])); + output.write(JSON.toJson(map("row", "components", "names", + BuiltInRegistries.DATA_COMPONENT_TYPE.keySet().stream().map(Identifier::toString).sorted().toList()))); output.newLine(); + var items = new TreeMap(); + try (Stream files = Files.list(root.resolve("assets/minecraft/items"))) { + for (var file : (Iterable) files.sorted()::iterator) { + var name = file.getFileName().toString(); + var id = Identifier.withDefaultNamespace(name.substring(0, name.length() - 5)); + String text = Files.readString(file); + boolean ok = decode(id, text, items); + output.write(JSON.toJson(map("row", "decode", "name", name, "ok", ok))); output.newLine(); + } + } + // Synthetic definitions from the harness. + try (var lines = Files.lines(Path.of(args[1] + ".definitions"))) { + for (var line : (Iterable) lines::iterator) { + var row = JsonParser.parseString(line).getAsJsonObject(); + var id = Identifier.parse(row.get("name").getAsString()); + boolean ok = decode(id, row.get("json").getAsString(), items); + output.write(JSON.toJson(map("row", "decode", "name", row.get("name").getAsString(), "ok", ok))); output.newLine(); + } + } + + var missingModel = MissingCuboidModel.missingModel(); + var discovery = new ModelDiscovery(models, missingModel); + discovery.addSpecialModel(ItemModelGenerator.GENERATED_ITEM_MODEL_ID, new ItemModelGenerator()); + items.values().forEach(info -> discovery.addRoot(info.model())); + var resolved = discovery.resolve(); + var missingSprite = new Sprite(BLOCKS, MissingTextureAtlasSprite.create()); + var blockAtlas = new SpriteLoader.Preparations(16, 16, 0, missingSprite, new Regions(false), CompletableFuture.completedFuture(null)); + var itemAtlas = new SpriteLoader.Preparations(16, 16, 0, missingSprite, new Regions(true), CompletableFuture.completedFuture(null)); + var materials = new net.minecraft.client.resources.model.sprite.MaterialBaker(blockAtlas, itemAtlas); + var dummy = new Sprite(ITEMS, new SpriteContents(Identifier.parse("minecraft:dummy"), new net.minecraft.client.resources.metadata.animation.FrameSize(16, 16), new NativeImage(16, 16, true))); + SpriteGetter sprites = id -> dummy; + var bakery = new ModelBakery(EntityModelSet.vanilla(), sprites, null, Map.of(), tagged(items), resolved, discovery.missingModel()); + var baked = bakery.bakeModels(materials, Runnable::run).join(); + var resolver = new Resolver(); + resolver.models = baked.itemStackModels(); resolver.properties = baked.itemProperties(); resolver.missing = baked.missingModels().item(); + for (var id : items.keySet()) if (!resolver.models.containsKey(id)) { + output.write(JSON.toJson(map("row", "unbaked", "name", id.toString()))); output.newLine(); + } + var state = new ItemStackRenderState(); + + try (var lines = Files.lines(Path.of(args[1]))) { + for (var line : (Iterable) lines::iterator) { + var row = JsonParser.parseString(line).getAsJsonObject(); + var result = new TreeMap(); + result.put("row", "case"); result.put("id", row.get("id").getAsString()); + try { + var stackJson = new JsonObject(); + stackJson.addProperty("id", row.get("item").getAsString()); + stackJson.addProperty("count", row.get("count").getAsInt()); + if (row.has("components")) stackJson.add("components", row.get("components")); + var stack = ItemStack.CODEC.parse(ops, stackJson).getOrThrow(); + if (row.has("bundle_selected") && row.get("bundle_selected").getAsInt() >= 0) { + var contents = stack.get(DataComponents.BUNDLE_CONTENTS); + var mutable = contents.asMutable(); + mutable.toggleSelectedItem(row.get("bundle_selected").getAsInt()); + stack.set(DataComponents.BUNDLE_CONTENTS, mutable.toImmutable()); + } + var context = ItemDisplayContext.CODEC.parse(JsonOps.INSTANCE, row.get("context")).getOrThrow(); + frozenTime = row.has("local_time") ? row.get("local_time").getAsString() : ""; + Actor actor = null; + if (row.has("owner") && !row.get("owner").isJsonNull()) { + var o = row.getAsJsonObject("owner"); + actor = make(Actor.class); + actor.using = o.get("using").getAsBoolean(); + actor.remaining = o.get("remaining").getAsInt(); + actor.stack = stack; + actor.arm = o.get("main_arm").getAsString().equals("left") ? HumanoidArm.LEFT : HumanoidArm.RIGHT; + actor.kind = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(o.get("entity_type").getAsString())); + var derived = new TreeMap(); + derived.put("use_duration", stack.getUseDuration(actor)); + try { derived.put("charge_duration", CrossbowItem.getChargeDuration(stack, actor)); } catch (RuntimeException e) { derived.put("charge_duration", 0); } + result.put("derived", derived); + } + Level level = null; + if (row.has("dimension") && !row.get("dimension").isJsonNull()) { + var dim = net.minecraft.resources.ResourceKey.create(net.minecraft.core.registries.Registries.DIMENSION, Identifier.parse(row.get("dimension").getAsString())); + var clientLevel = make(ClientLevel.class); + var f = Level.class.getDeclaredField("dimension"); f.setAccessible(true); + var offset = (long) u.getMethod("objectFieldOffset", Field.class).invoke(unsafe, f); + u.getMethod("putObject", Object.class, long.class, Object.class).invoke(unsafe, clientLevel, offset, dim); + level = clientLevel; + } + resolver.updateForTopItem(state, stack, context, level, actor, row.has("seed") ? row.get("seed").getAsInt() : 0); + var layersField = ItemStackRenderState.class.getDeclaredField("layers"); layersField.setAccessible(true); + var countField = ItemStackRenderState.class.getDeclaredField("activeLayerCount"); countField.setAccessible(true); + var layers = (Object[]) layersField.get(state); int count = countField.getInt(state); + var list = new ArrayList(); + for (int i = 0; i < count; i++) list.add(layer(state, layers[i], context)); + result.put("layers", list); + result.put("oversized", state.isOversizedInGui()); + result.put("swap", map("play", resolver.shouldPlaySwapAnimation(stack), "scale", bits(resolver.swapAnimationScale(stack)))); + } catch (Throwable e) { + Throwable cause = e; while (cause.getCause() != null) cause = cause.getCause(); + result.put("error", cause.toString()); + } + output.write(JSON.toJson(result)); output.newLine(); + } + } + output.close(); + } + + static Map tagged(Map items) { + var out = new TreeMap(); + items.forEach((id, item) -> out.put(id, new ClientItem(tag(item.model()), item.properties(), item.registrySwapper()))); + return out; + } + static boolean decode(Identifier id, String text, Map items) { + try { + var parsed = ClientItem.CODEC.parse(ops, StrictJsonParser.parse(new StringReader(text))).result(); + parsed.ifPresent(item -> items.put(id, item)); + return parsed.isPresent(); + } catch (Exception e) { return false; } + } +} diff --git a/tools/test_item_model_parity.py b/tools/test_item_model_parity.py new file mode 100644 index 000000000..94c34a80e --- /dev/null +++ b/tools/test_item_model_parity.py @@ -0,0 +1,380 @@ +#!/usr/bin/env python3 +"""Compare item model resolution with the pinned client's own item pipeline. + +The vanilla side (VanillaItemModelOracle) decodes every `items/*.json` with the +client codec, discovers and bakes all models with `ModelBakery` against real +PNG sprites, and resolves stacks through `ItemStackRenderState` layers. The +Rust side (`item_model_fixture`) must pick the same layers, tints, foil, +transformations, special-renderer configurations and baked quads.""" +import json +import os +import platform +import random +import subprocess +import zipfile +from pathlib import Path +try: + from . import lab, test_rust_parity as base, test_model_baking_parity as baking +except ImportError: + import lab, test_rust_parity as base, test_model_baking_parity as baking + +CONTEXTS = ['gui', 'ground', 'fixed', 'head', 'thirdperson_righthand', 'thirdperson_lefthand', + 'firstperson_righthand', 'firstperson_lefthand', 'on_shelf', 'none'] +DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', + 'purple', 'blue', 'brown', 'green', 'red', 'black'] +TRIM_MATERIALS = ['quartz', 'iron', 'netherite', 'redstone', 'copper', 'gold', 'emerald', 'diamond', 'lapis', + 'amethyst', 'resin'] +NEEDED = ('assets/minecraft/items/', 'assets/minecraft/models/', 'assets/minecraft/textures/item/', + 'assets/minecraft/textures/block/', 'assets/minecraft/textures/trims/', + 'assets/minecraft/textures/colormap/') + + +def extract(jar, destination): + marker = destination / '.jar-sha256' + digest = lab.digest(jar, 'sha256') + if marker.exists() and marker.read_text() == digest: + return + destination.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(jar) as archive: + for name in archive.namelist(): + if name.startswith(NEEDED) and not name.endswith('/'): + target = destination / name + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(archive.read(name)) + marker.write_text(digest) + + +def owner(using, remaining, arm='right', entity='minecraft:player'): + return {'using': using, 'remaining': remaining, 'main_arm': arm, 'entity_type': entity} + + +def corpus(prototypes): + """Representative stacks for every registered item.""" + rng = random.Random(0x4954454d) + cases = [] + def add(item, context='gui', count=1, components=None, **extra): + case = {'id': str(len(cases)), 'item': item, 'count': count, 'context': context} + if components: case['components'] = components + case.update(extra) + cases.append(case) + for item, components in prototypes.items(): + stack = components.get('minecraft:max_stack_size', 64) + for context in CONTEXTS: add(item, context) + max_damage = components.get('minecraft:max_damage', 0) + if max_damage: + for damage in sorted({0, 1, max_damage // 2, max_damage - 2, max_damage - 1, max_damage}): + add(item, 'gui', components={'minecraft:damage': damage}) + add(item, 'gui', components={'minecraft:damage': max_damage - 1, 'minecraft:unbreakable': {}}) + add(item, 'gui', components={'!minecraft:max_damage': {}}) + for count in sorted({2, stack // 2, stack}): + if 1 <= count <= stack: add(item, 'gui', count=count) + for color in (0xFF0000, 0x123456, 0xFFFFFF, 0): + add(item, 'gui', components={'minecraft:dyed_color': color}) + for material in TRIM_MATERIALS: + add(item, 'gui', components={'minecraft:trim': {'material': 'minecraft:' + material, 'pattern': 'minecraft:coast'}}) + add(item, 'gui', components={'minecraft:custom_model_data': {'floats': [0.0, 0.5, 1.0, 2.5, 7.0], + 'flags': [True, False, True], 'strings': ['a', 'b', 'c'], 'colors': [0xFF0000, 0x00FF00]}}) + add(item, 'gui', components={'minecraft:custom_model_data': {'floats': [3.0]}}) + for context in ('gui', 'ground', 'head'): + add(item, context, components={'minecraft:enchantments': {'minecraft:sharpness': 1}}) + add(item, 'gui', components={'minecraft:enchantment_glint_override': True}) + add(item, 'gui', components={'minecraft:enchantment_glint_override': False, + 'minecraft:enchantments': {'minecraft:sharpness': 1}}) + add(item, 'gui', components={'minecraft:potion_contents': {'custom_color': 0x00FF7F}}) + add(item, 'gui', components={'minecraft:potion_contents': {'potion': 'minecraft:water'}}) + add(item, 'gui', components={'minecraft:potion_contents': {}}) + for colors in ([], [0xFF0000], [0xFF0000, 0x0000FF], [0x112233, 0x445566, 0x778899]): + add(item, 'gui', components={'minecraft:firework_explosion': {'shape': 'small_ball', 'colors': colors}}) + add(item, 'gui', components={'minecraft:item_model': 'minecraft:diamond'}) + add(item, 'gui', components={'minecraft:item_model': 'minecraft:horizon_unknown'}) + add(item, 'gui', components={'!minecraft:item_model': {}}) + add(item, 'gui', components={'minecraft:item_model': 'minecraft:bundle'}, bundle_selected=0) + for state in ({'honey_level': '0'}, {'honey_level': '5'}, {'light_level': '7'}, {'level': '1'}, + {'age': '3'}, {'powered': 'true'}, {'unknown': 'x'}): + add(item, 'gui', components={'minecraft:block_state': state}) + for projectile in ('minecraft:arrow', 'minecraft:firework_rocket'): + add(item, 'gui', components={'minecraft:charged_projectiles': [{'id': projectile, 'count': 1}]}) + add(item, 'gui', components={'minecraft:charged_projectiles': []}) + add(item, 'gui', components={'minecraft:lodestone_tracker': {}}) + add(item, 'gui', components={'minecraft:lodestone_tracker': {'tracked': True, + 'target': {'dimension': 'minecraft:overworld', 'pos': [1, 2, 3]}}}) + add(item, 'gui', components={'minecraft:banner_patterns': [{'pattern': 'minecraft:circle', 'color': 'red'}, + {'pattern': 'minecraft:border', 'color': 'blue'}]}) + add(item, 'gui', components={'minecraft:base_color': 'green', + 'minecraft:banner_patterns': [{'pattern': 'minecraft:globe', 'color': 'yellow'}]}) + add(item, 'gui', components={'minecraft:pot_decorations': {'back': {'id': 'minecraft:brick'}, + 'left': {'id': 'minecraft:angler_pottery_sherd'}, 'front': {'id': 'minecraft:blade_pottery_sherd'}}}) + add(item, 'gui', components={'minecraft:profile': {'name': 'Notch'}}) + add(item, 'gui', components={'minecraft:bundle_contents': [{'id': 'minecraft:stone', 'count': 3}, + {'id': 'minecraft:diamond_sword', 'count': 1}, + {'id': 'minecraft:dirt', 'count': 20}]}, bundle_selected=1) + add(item, 'gui', components={'minecraft:bundle_contents': [{'id': 'minecraft:stone', 'count': 3}]}, bundle_selected=-1) + for time in ('12-24', '12-25', '12-26', '10-09', ''): + add(item, 'gui', local_time=time) + for dimension in ('minecraft:overworld', 'minecraft:the_nether', 'minecraft:the_end', 'horizon:other'): + add(item, 'gui', dimension=dimension) + for arm in ('left', 'right'): + for entity in ('minecraft:player', 'minecraft:zombie'): + add(item, 'firstperson_righthand', owner=owner(False, 0, arm, entity)) + for remaining in (0, 1, 3, 7, 13, 20, 71000, 71990, 72000): + for context in ('firstperson_righthand', 'thirdperson_righthand'): + add(item, context, owner=owner(True, remaining)) + add(item, 'firstperson_righthand', owner=owner(False, 5)) + # Item definitions with every shape the codec accepts and rejects. + return cases + + +def definitions(): + """Synthetic client item definitions: valid and invalid shapes.""" + model = {'type': 'minecraft:model', 'model': 'minecraft:item/stick'} + other = {'type': 'minecraft:model', 'model': 'minecraft:item/diamond'} + rows = {} + def put(name, definition): + rows['horizon:' + name] = definition if isinstance(definition, str) else json.dumps(definition) + put('plain', {'model': model}) + put('props', {'model': model, 'hand_animation_on_swap': False, 'oversized_in_gui': True, 'swap_animation_scale': 2.5}) + put('no_model', {}) + put('unknown_type', {'model': {'type': 'minecraft:horizon'}}) + put('empty', {'model': {'type': 'minecraft:empty'}}) + put('composite', {'model': {'type': 'minecraft:composite', 'models': [model, other, {'type': 'minecraft:empty'}]}}) + put('composite_empty', {'model': {'type': 'minecraft:composite', 'models': []}}) + put('composite_one', {'model': {'type': 'minecraft:composite', 'models': [model], + 'transformation': [1, 0, 0, 0.5, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]}}) + put('matrix', {'model': dict(model, transformation=[0.5, 0, 0, 1, 0, 0.5, 0, 2, 0, 0, 0.5, 3, 0, 0, 0, 1])}) + put('matrix_short', {'model': dict(model, transformation=[1, 0, 0])}) + quarter = [0.0, 0.0, 0.70710677, 0.70710677] + put('decomposed', {'model': dict(model, transformation={'translation': [1, 2, 3], 'left_rotation': quarter, + 'scale': [1, 2, 3], 'right_rotation': [0, 0.38268343, 0, 0.9238795]})}) + put('axis_angle', {'model': dict(model, transformation={'translation': [0, 0, 0], + 'left_rotation': {'angle': 1.5707964, 'axis': [0, 0, 1]}, 'scale': [1, 1, 1], 'right_rotation': [0, 0, 0, 1]})}) + put('decomposed_partial', {'model': dict(model, transformation={'translation': [0, 0, 0], 'scale': [1, 1, 1]})}) + put('nested_transform', {'model': {'type': 'minecraft:condition', 'property': 'minecraft:damaged', + 'transformation': [2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1], 'on_true': dict(model, transformation=[1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]), 'on_false': other}}) + put('tints', {'model': dict(model, tints=[{'type': 'minecraft:constant', 'value': 0x123456}, + {'type': 'minecraft:constant', 'value': [0.5, 0.25, 1.0]}, + {'type': 'minecraft:dye', 'default': -6265536}, {'type': 'minecraft:grass', 'temperature': 0.5, 'downfall': 1.0}, + {'type': 'minecraft:grass', 'temperature': 0.0, 'downfall': 0.0}, {'type': 'minecraft:grass', 'temperature': 1.0, 'downfall': 0.3}, + {'type': 'minecraft:firework', 'default': 7}, {'type': 'minecraft:potion', 'default': 9}, + {'type': 'minecraft:team', 'default': 11}, + {'type': 'minecraft:custom_model_data', 'index': 1, 'default': 0x0000FF}])}) + put('bad_tint', {'model': dict(model, tints=[{'type': 'minecraft:horizon'}])}) + put('bad_grass', {'model': dict(model, tints=[{'type': 'minecraft:grass', 'temperature': 2.0, 'downfall': 0.0}])}) + put('condition_missing_branch', {'model': {'type': 'minecraft:condition', 'property': 'minecraft:damaged', 'on_true': model}}) + for prop in ('broken', 'damaged', 'using_item', 'selected', 'carried', 'view_entity', 'extended_view', + 'fishing_rod/cast', 'bundle/has_selected_item'): + put('cond_' + prop.replace('/', '_'), {'model': {'type': 'minecraft:condition', 'property': 'minecraft:' + prop, 'on_true': model, 'on_false': other}}) + for index in (0, 1, 3, -1): + put(f'cond_cmd_{index}', {'model': {'type': 'minecraft:condition', 'property': 'minecraft:custom_model_data', 'index': index, 'on_true': model, 'on_false': other}}) + for ignore in (True, False): + for component in ('minecraft:damage', 'minecraft:enchantments', 'minecraft:max_damage', 'minecraft:custom_name', 'minecraft:horizon'): + put(f'cond_has_{ignore}_{component}'.lower().replace(':', '_'), {'model': {'type': 'minecraft:condition', 'property': 'minecraft:has_component', + 'component': component, 'ignore_default': ignore, 'on_true': model, 'on_false': other}}) + select = lambda prop, cases, **extra: {'model': dict({'type': 'minecraft:select', 'property': 'minecraft:' + prop, + 'cases': [{'when': w, 'model': m} for w, m in cases]}, **extra)} + put('select_ctx', select('display_context', [(['gui', 'ground'], model), ('head', other)], fallback={'type': 'minecraft:empty'})) + put('select_ctx_nofallback', select('display_context', [('gui', model)])) + put('select_ctx_bad', select('display_context', [('guii', model)])) + put('select_dup', select('display_context', [('gui', model), (['gui', 'head'], other)])) + put('select_empty_cases', select('display_context', [])) + put('select_empty_when', select('display_context', [([], model)])) + put('select_arm', select('main_hand', [('left', model), ('right', other)])) + put('select_arm_fallback', select('main_hand', [('left', model)], fallback=other)) + put('select_charge', select('charge_type', [('none', model), ('arrow', other), ('rocket', {'type': 'minecraft:empty'})])) + put('select_trim', select('trim_material', [(['minecraft:quartz', 'iron'], model), ('minecraft:gold', other)], fallback={'type': 'minecraft:empty'})) + put('select_state', select('block_state', [('3', model), ('5', other)], block_state_property='honey_level', fallback=model)) + put('select_state_missing_prop', select('block_state', [('3', model)])) + put('select_entity', select('context_entity_type', [('minecraft:player', model), ('zombie', other)], fallback={'type': 'minecraft:empty'})) + put('select_dimension', select('context_dimension', [('minecraft:overworld', model), ('the_nether', other)], fallback={'type': 'minecraft:empty'})) + put('select_cmd', select('custom_model_data', [('a', model), ('c', other)], index=2, fallback={'type': 'minecraft:empty'})) + put('select_time', select('local_time', [('12-25', model)], pattern='MM-dd', fallback=other)) + put('select_time_bad', select('local_time', [('12-25', model)], pattern='Q{', fallback=other)) + put('select_component', select('component', [('minecraft:diamond_sword', model)], component='minecraft:item_model', fallback=other)) + put('select_unknown_prop', select('horizon', [('a', model)])) + ranges = lambda prop, entries, **extra: {'model': dict({'type': 'minecraft:range_dispatch', 'property': 'minecraft:' + prop, + 'entries': [{'threshold': t, 'model': m} for t, m in entries]}, **extra)} + put('range_damage', ranges('damage', [(0.0, model), (0.5, other), (0.99, {'type': 'minecraft:empty'})], fallback={'type': 'minecraft:empty'})) + put('range_damage_raw', ranges('damage', [(0, model), (10, other)], normalize=False)) + put('range_count', ranges('count', [(0.0, model), (0.5, other), (1.0, {'type': 'minecraft:empty'})])) + put('range_count_raw', ranges('count', [(1, model), (32, other)], normalize=False)) + put('range_scale', ranges('damage', [(0, model), (50, other)], scale=100)) + put('range_nofallback', ranges('damage', [(0.4, model)])) + put('range_unsorted', ranges('count', [(0.9, other), (0.1, model), (0.5, {'type': 'minecraft:empty'}), (0.1, other)])) + put('range_many', ranges('count', [(i / 20, model if i % 2 else other) for i in range(20)])) + put('range_cmd', ranges('custom_model_data', [(0, model), (1, other), (2.5, {'type': 'minecraft:empty'})], index=0)) + put('range_cooldown', ranges('cooldown', [(0, model), (0.5, other)])) + put('range_use_duration', ranges('use_duration', [(0, model), (10, other)])) + put('range_use_remaining', ranges('use_duration', [(0, model), (10, other)], remaining=True)) + put('range_cycle', ranges('use_cycle', [(0, model), (2, other)], period=4)) + put('range_cycle_bad', ranges('use_cycle', [(0, model)], period=0)) + put('range_crossbow', ranges('crossbow/pull', [(0, model), (0.5, other)])) + put('range_fullness', ranges('bundle/fullness', [(0, model), (0.5, other)])) + put('range_time', ranges('time', [(0, model)], source='daytime')) + put('range_compass', ranges('compass', [(0, model)], target='spawn')) + put('range_compass_bad', ranges('compass', [(0, model)], target='moon')) + put('range_nan_threshold', ranges('damage', [(float('nan'), model)])) + put('range_no_entries', {'model': {'type': 'minecraft:range_dispatch', 'property': 'minecraft:damage'}}) + for kind, config in [('banner', {'color': 'red'}), ('banner', {'color': 'blue', 'attachment': 'wall'}), + ('banner', {'color': 'pink', 'attachment': 'ground'}), ('banner', {'color': 'nope'}), ('banner', {}), + ('bell', {}), ('book', {'open_angle': 1.0, 'page1': 0.25, 'page2': 0.75}), ('book', {'open_angle': 1.0}), + ('chest', {'texture': 'minecraft:normal'}), ('chest', {'texture': 'christmas', 'openness': 0.5, 'chest_type': 'left'}), + ('chest', {'texture': 'minecraft:normal', 'chest_type': 'triple'}), ('chest', {}), + ('conduit', {}), ('copper_golem_statue', {'texture': 'minecraft:copper', 'pose': 'star'}), + ('copper_golem_statue', {'texture': 'minecraft:copper', 'pose': 'dancing'}), + ('decorated_pot', {}), ('end_cube', {'effect': 'portal'}), ('end_cube', {'effect': 'void'}), + ('head', {'kind': 'dragon'}), ('head', {'kind': 'player', 'texture': 'horizon:custom', 'animation': 1.5}), + ('head', {'kind': 'ghast'}), ('player_head', {}), + ('shulker_box', {}), ('shulker_box', {'texture': 'minecraft:shulker_red', 'openness': 0.25}), + ('shield', {}), ('trident', {}), ('horizon', {})]: + put(f'special_{kind}_{len(rows)}', {'model': {'type': 'minecraft:special', 'base': 'minecraft:item/shield' if kind == 'shield' else 'minecraft:item/template_banner', + 'model': dict(config, type='minecraft:' + kind)}}) + put('special_transformed', {'model': {'type': 'minecraft:special', 'base': 'minecraft:item/trident_in_hand', 'model': {'type': 'minecraft:trident'}, + 'transformation': {'left_rotation': [0, 0, 0, 1], 'right_rotation': [0, 0, 0, 1], 'scale': [1, -1, -1], 'translation': [0, 0, 0]}}}) + put('bundle_selected', {'model': {'type': 'minecraft:composite', 'models': [model, {'type': 'minecraft:bundle/selected_item'}, other]}}) + for pack in ('', '_x'): + put('trailing' + pack, json.dumps({'model': model}) + pack) + put('not_object', '[]') + put('null_model', {'model': None}) + put('number_scale', {'model': model, 'swap_animation_scale': 'x'}) + put('bool_flag_number', {'model': model, 'oversized_in_gui': 1}) + put('bool_flag_string', {'model': model, 'oversized_in_gui': 'true'}) + put('bool_flag_float', {'model': model, 'oversized_in_gui': 0.5}) + put('swap_bool', {'model': model, 'swap_animation_scale': True}) + put('int_float_index', {'model': {'type': 'minecraft:condition', 'property': 'minecraft:custom_model_data', 'index': 1.5, 'on_true': model, 'on_false': other}}) + put('int_bool_index', {'model': {'type': 'minecraft:condition', 'property': 'minecraft:custom_model_data', 'index': True, 'on_true': model, 'on_false': other}}) + put('bool_as_number', {'model': dict({'type': 'minecraft:range_dispatch', 'property': 'minecraft:damage', 'entries': [{'threshold': True, 'model': model}]})}) + return rows + + +def definition_cases(rows): + cases = [] + stacks = [('minecraft:diamond_sword', {'minecraft:damage': 100}, 1), ('minecraft:diamond_sword', {'minecraft:damage': 1560}, 1), + ('minecraft:diamond_sword', {}, 1), ('minecraft:stone', {}, 64), ('minecraft:stone', {}, 17), ('minecraft:stone', {}, 1), + ('minecraft:bow', {}, 1), ('minecraft:leather_helmet', {'minecraft:trim': {'material': 'minecraft:gold', 'pattern': 'minecraft:coast'}}, 1), + ('minecraft:beehive', {'minecraft:block_state': {'honey_level': '3'}}, 1), + ('minecraft:beehive', {'minecraft:block_state': {'honey_level': '5'}}, 1), ('minecraft:crossbow', {}, 1), + ('minecraft:crossbow', {'minecraft:charged_projectiles': [{'id': 'minecraft:arrow', 'count': 1}]}, 1), + ('minecraft:diamond_sword', {'minecraft:custom_model_data': {'floats': [0.0, 1.0, 3.0], 'flags': [True], 'strings': ['a', 'b', 'c']}}, 1), + ('minecraft:diamond_sword', {'minecraft:custom_model_data': {'floats': [2.5], 'flags': [False, True], 'strings': ['x']}}, 1), + ('minecraft:bundle', {'minecraft:bundle_contents': [{'id': 'minecraft:diamond_sword', 'count': 1}, {'id': 'minecraft:stone', 'count': 3}]}, 1), + ('minecraft:bundle', {'minecraft:bundle_contents': []}, 1), + ('minecraft:stone', {'minecraft:enchantments': {'minecraft:sharpness': 1}}, 1), + ('minecraft:stone', {'minecraft:custom_name': '"x"'}, 1)] + for name in rows: + for stack_index, (item, components, count) in enumerate(stacks): + for context in ('gui', 'head', 'firstperson_lefthand', 'ground'): + for owner_state in (None, owner(True, 9), owner(False, 0, 'left', 'minecraft:zombie')): + for dimension in (None, 'minecraft:overworld', 'minecraft:the_nether'): + if dimension and context != 'gui': continue + case = {'id': f'd{len(cases)}', 'item': item, 'count': count, 'context': context, + 'components': dict(components, **{'minecraft:item_model': name})} + if owner_state: case['owner'] = owner_state + if dimension: case['dimension'] = dimension + if 'bundle_contents' in str(components) and count == 1 and 'diamond_sword' in str(components): + case['bundle_selected'] = stack_index % 2 + case['local_time'] = '12-25' if stack_index % 2 else '01-01' + cases.append(case) + return cases + + +import struct +def float_bits(value): + return struct.unpack(' 1000, 'Too few cases compared' + assert skipped * 20 < len(cases), f'Too many cases rejected by vanilla: {skipped}' + report = {'schema': 1, '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(), + 'cases': len(cases), 'compared': compared, 'rejected_by_vanilla': skipped, 'definitions_decoded': decoded, + 'definitions_unbaked': unbaked, 'sources_sha256': tested, + 'scope': 'Actual ClientItem codec, ModelDiscovery, ModelBakery item baking and ItemModelResolver semantics against real sprites in a unit atlas. Every bundled items/*.json and synthetic definitions; every item prototype in every display context with representative components. Layer content, tints, foil, composed transformation matrices (numeric equality), special-renderer codec forms and arguments, baked quads by float bits, render properties. Not covered: GPU rendering, atlas packing, level-dependent needles (see the needle tests), player/keybind/team-based properties that need a live client.'} + lab.write_json(report_path, report) + print(f'Item models: {compared:,} resolved stacks match ({skipped:,} rejected by vanilla, {decoded:,} definitions); {report_path}', flush=True) + + +if __name__ == '__main__': main() From fa3acf58b8dc1b2ce859863756a6df272a2ad37e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 06:04:52 +0200 Subject: [PATCH 2/3] Add pack overlays and filter blocks (WIP) Resource packs now honour pack.mcmeta overlay directories and filter block patterns when layering files over the vanilla resources. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/packs.rs | 211 ++++++++++++++++++--- crates/horizon-client/src/packs/pattern.rs | 142 ++++++++++++++ 2 files changed, 328 insertions(+), 25 deletions(-) create mode 100644 crates/horizon-client/src/packs/pattern.rs diff --git a/crates/horizon-client/src/packs.rs b/crates/horizon-client/src/packs.rs index 9e78a5f13..caf6c13b2 100644 --- a/crates/horizon-client/src/packs.rs +++ b/crates/horizon-client/src/packs.rs @@ -3,7 +3,9 @@ //! and High Contrast packs, `pack.mcmeta` metadata and format compatibility, //! and an overlay resource root that layers the enabled packs over the //! vanilla resources (later packs win), so every loader sees one tree. +mod pattern; use crate::{text::Text, zip::Zip}; +use pattern::Pattern; use std::{ collections::{BTreeMap, BTreeSet}, fs, io, @@ -26,6 +28,30 @@ pub struct Pack { pub title: Text, pub description: Text, pub compatible: bool, + /// Overlay directories active for this game version, in `pack.mcmeta` order. + pub overlays: Vec, + /// `filter.block` entries (namespace and path patterns) hiding resources + /// of the packs below this one. + pub filter: Vec, +} +#[derive(Clone, Debug, Default)] +pub struct Filter { + namespace: Option, + path: Option, +} +impl Filter { + fn blocks(&self, file: &str) -> bool { + let Some(rest) = file.strip_prefix("assets/") else { + return false; + }; + let Some((namespace, path)) = rest.split_once('/') else { + return false; + }; + self.namespace + .as_ref() + .is_none_or(|p| p.is_match(namespace)) + && self.path.as_ref().is_none_or(|p| p.is_match(path)) + } } /// A minimal text component from JSON (strings, `text`, `translate`, arrays). pub fn component(v: &serde_json::Value) -> Text { @@ -102,6 +128,58 @@ pub fn compatible(meta: &serde_json::Value) -> bool { } format_of(&pack["pack_format"]).is_some_and(|f| f.0 == current.0) } +/// Whether an `overlays.entries[]` item applies to the current format +/// (OverlayMetadataSection: `formats` as an int, `[min, max]` or +/// `{min_inclusive, max_inclusive}`, or `min_format`/`max_format`). +fn overlay_applies(entry: &serde_json::Value) -> bool { + let current = RESOURCE_FORMAT; + if let (Some(min), Some(max)) = ( + format_of(&entry["min_format"]), + format_of(&entry["max_format"]), + ) { + return min <= current && current <= (max.0, if max.1 == 0 { i64::MAX } else { max.1 }); + } + let formats = &entry["formats"]; + if let Some(n) = formats.as_i64() { + return n == current.0; + } + if let Some(a) = formats.as_array() { + return match ( + a.first().and_then(|v| v.as_i64()), + a.get(1).and_then(|v| v.as_i64()), + ) { + (Some(lo), Some(hi)) => lo <= current.0 && current.0 <= hi, + _ => false, + }; + } + match ( + formats["min_inclusive"].as_i64(), + formats["max_inclusive"].as_i64(), + ) { + (Some(lo), Some(hi)) => lo <= current.0 && current.0 <= hi, + _ => false, + } +} +fn overlays_of(meta: &serde_json::Value) -> Vec { + meta["overlays"]["entries"] + .as_array() + .into_iter() + .flatten() + .filter(|e| overlay_applies(e)) + .filter_map(|e| e["directory"].as_str().map(str::to_owned)) + .collect() +} +fn filter_of(meta: &serde_json::Value) -> Vec { + meta["filter"]["block"] + .as_array() + .into_iter() + .flatten() + .map(|b| Filter { + namespace: b["namespace"].as_str().and_then(Pattern::new), + path: b["path"].as_str().and_then(Pattern::new), + }) + .collect() +} fn read_meta(source: &Source) -> Option { let bytes = match source { Source::Dir(d) => fs::read(d.join("pack.mcmeta")).ok()?, @@ -116,6 +194,8 @@ fn pack(id: String, title: Text, source: Source) -> Option { title, description: component(&meta["pack"]["description"]), compatible: compatible(&meta), + overlays: overlays_of(&meta), + filter: filter_of(&meta), source, }) } @@ -155,30 +235,44 @@ pub fn discover(resources: &Path, packs_dir: &Path) -> Vec { out.extend(user); out } -/// Files a pack provides under `assets/`. -fn pack_files(source: &Source) -> io::Result>> { +/// A file a pack provides: its path (folder packs) and its name inside the pack. +type Provided = (Option, String); +/// Files a pack provides under `assets/`, keyed by their resource name; active +/// overlay directories are applied after the base, in order, later wins. +fn pack_files(pack: &Pack) -> io::Result> { let mut out = BTreeMap::new(); - match source { + let roots = std::iter::once(String::new()) + .chain(pack.overlays.iter().map(|d| format!("{d}/"))) + .collect::>(); + match &pack.source { Source::Dir(d) => { - let mut stack = vec![d.join("assets")]; - while let Some(dir) = stack.pop() { - let Ok(entries) = fs::read_dir(&dir) else { - continue; - }; - for e in entries.flatten() { - let p = e.path(); - if p.is_dir() { - stack.push(p); - } else if let Ok(rel) = p.strip_prefix(d) { - out.insert(rel.to_string_lossy().replace('\\', "/"), Some(p.clone())); + for root in &roots { + let base = d.join(root.trim_end_matches('/')); + let mut stack = vec![base.join("assets")]; + while let Some(dir) = stack.pop() { + let Ok(entries) = fs::read_dir(&dir) else { + continue; + }; + for e in entries.flatten() { + let p = e.path(); + if p.is_dir() { + stack.push(p); + } else if let Ok(rel) = p.strip_prefix(&base) { + let rel = rel.to_string_lossy().replace('\\', "/"); + out.insert(rel.clone(), (Some(p.clone()), format!("{root}{rel}"))); + } } } } } Source::Zip(z) => { - for name in Zip::open(z)?.names() { - if name.starts_with("assets/") { - out.insert(name.to_owned(), None); + let zip = Zip::open(z)?; + for root in &roots { + let prefix = format!("{root}assets/"); + for name in zip.names() { + if let Some(rest) = name.strip_prefix(&prefix) { + out.insert(format!("assets/{rest}"), (None, name.to_owned())); + } } } } @@ -205,12 +299,16 @@ pub fn build_overlay(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<( } fs::create_dir_all(out)?; // Final owner of every overridden file. - let mut files: BTreeMap)> = BTreeMap::new(); + let mut files: BTreeMap = BTreeMap::new(); for (i, p) in packs.iter().enumerate() { - for (name, path) in pack_files(&p.source)? { - files.insert(name, (i, path)); + // A pack's filter hides what the packs below it provide. + files.retain(|name, _| !p.filter.iter().any(|f| f.blocks(name))); + for (name, provided) in pack_files(p)? { + files.insert(name, (i, provided)); } } + // Vanilla sits below every pack, so filters hide its files too. + let filters: Vec<&Filter> = packs.iter().flat_map(|p| &p.filter).collect(); let touched_dirs: BTreeSet = files .keys() .flat_map(|f| { @@ -233,7 +331,8 @@ pub fn build_overlay(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<( vanilla: &Path, out: &Path, touched: &BTreeSet, - files: &BTreeMap)>, + files: &BTreeMap, + filters: &[&Filter], zips: &[Option], ) -> io::Result<()> { let src = if rel.is_empty() { @@ -265,25 +364,31 @@ pub fn build_overlay(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<( } for name in names { let child = format!("{prefix}{name}"); - if let Some((owner, path)) = files.get(&child) { + if let Some((owner, (path, inner))) = files.get(&child) { let target = out.join(&child); match path { Some(p) => link(p, &target)?, None => { if let Some(Some(z)) = zips.get(*owner) { - fs::write(&target, z.read(&child)?)?; + fs::write(&target, z.read(inner)?)?; } } } + } else if vanilla.join(&child).is_dir() + && (touched.contains(&child) || !filters.is_empty()) + { + mirror(&child, vanilla, out, touched, files, filters, zips)?; } else if touched.contains(&child) { - mirror(&child, vanilla, out, touched, files, zips)?; + mirror(&child, vanilla, out, touched, files, filters, zips)?; + } else if filters.iter().any(|f| f.blocks(&child)) { + // Hidden by a pack's filter. } else { link(&vanilla.join(&child), &out.join(&child))?; } } Ok(()) } - mirror("", vanilla, out, &touched_dirs, &files, &zips) + mirror("", vanilla, out, &touched_dirs, &files, &filters, &zips) } /// The packs to apply for an options.txt `resourcePacks` list (bottom first). pub fn enabled(all: &[Pack], ids: &[String]) -> Vec { @@ -388,4 +493,60 @@ mod tests { assert_eq!(fs::read(out.join("facts.json")).unwrap(), b"[]"); let _ = fs::remove_dir_all(base); } + #[test] + fn overlays_and_filters() { + let v = |s: &str| serde_json::from_str::(s).unwrap(); + let meta = v(r#"{"overlays":{"entries":[ + {"formats":[90,96],"directory":"old"}, + {"formats":{"min_inclusive":97,"max_inclusive":97},"directory":"new"}, + {"min_format":97,"max_format":[97,5],"directory":"also"}, + {"formats":50,"directory":"no"}]}}"#); + assert_eq!(overlays_of(&meta), ["new", "also"]); + let base = std::env::temp_dir().join(format!("horizon-packs-ov-{}", std::process::id())); + let _ = fs::remove_dir_all(&base); + let vanilla = base.join("vanilla"); + fs::create_dir_all(vanilla.join("assets/minecraft/textures/block")).unwrap(); + fs::write( + vanilla.join("assets/minecraft/textures/block/stone.png"), + b"v", + ) + .unwrap(); + fs::write( + vanilla.join("assets/minecraft/textures/block/dirt.png"), + b"v", + ) + .unwrap(); + let dir = base.join("packs/P"); + fs::create_dir_all(dir.join("new/assets/minecraft/textures/block")).unwrap(); + fs::create_dir_all(dir.join("old/assets/minecraft/textures/block")).unwrap(); + fs::write( + dir.join("pack.mcmeta"), + br#"{"pack":{"description":"p","pack_format":97}, + "overlays":{"entries":[{"formats":97,"directory":"new"},{"formats":1,"directory":"old"}]}, + "filter":{"block":[{"path":"textures/block/dirt\\.png"}]}}"#, + ) + .unwrap(); + fs::write( + dir.join("new/assets/minecraft/textures/block/stone.png"), + b"overlay", + ) + .unwrap(); + fs::write( + dir.join("old/assets/minecraft/textures/block/stone.png"), + b"old", + ) + .unwrap(); + let packs = discover(&vanilla, &base.join("packs")); + let out = base.join("overlay"); + build_overlay(&vanilla, &packs, &out).unwrap(); + assert_eq!( + fs::read(out.join("assets/minecraft/textures/block/stone.png")).unwrap(), + b"overlay" + ); + assert!( + !out.join("assets/minecraft/textures/block/dirt.png") + .exists() + ); + let _ = fs::remove_dir_all(base); + } } diff --git a/crates/horizon-client/src/packs/pattern.rs b/crates/horizon-client/src/packs/pattern.rs new file mode 100644 index 000000000..0ddd3b826 --- /dev/null +++ b/crates/horizon-client/src/packs/pattern.rs @@ -0,0 +1,142 @@ +//! A small regular-expression subset for `pack.mcmeta` filter blocks (Java +//! `Pattern.asPredicate()` semantics: an unanchored search). Supports +//! literals, `.`, classes `[a-z_]`/`[^..]`, escapes, `* + ?` quantifiers, +//! `^`/`$` and top-level alternation with `|`. + +#[derive(Clone, Debug)] +enum Atom { + Any, + Lit(char), + Class(Vec<(char, char)>, bool), + Start, + End, +} +#[derive(Clone, Debug)] +struct Item { + atom: Atom, + min: usize, + max: usize, +} +#[derive(Clone, Debug)] +pub struct Pattern(Vec>); + +impl Pattern { + pub fn new(src: &str) -> Option { + let mut alternatives = vec![Vec::new()]; + let chars: Vec = src.chars().collect(); + let mut i = 0; + while i < chars.len() { + let atom = match chars[i] { + '|' => { + alternatives.push(Vec::new()); + i += 1; + continue; + } + '.' => Atom::Any, + '^' => Atom::Start, + '$' => Atom::End, + '\\' => { + i += 1; + match *chars.get(i)? { + 'd' => Atom::Class(vec![('0', '9')], false), + 'w' => { + Atom::Class(vec![('a', 'z'), ('A', 'Z'), ('0', '9'), ('_', '_')], false) + } + c => Atom::Lit(c), + } + } + '[' => { + i += 1; + let negate = chars.get(i) == Some(&'^'); + if negate { + i += 1; + } + let mut ranges = Vec::new(); + loop { + let mut c = *chars.get(i)?; + if c == ']' && !ranges.is_empty() { + break; + } + if c == '\\' { + i += 1; + c = *chars.get(i)?; + } + if chars.get(i + 1) == Some(&'-') + && chars.get(i + 2).is_some_and(|e| *e != ']') + { + ranges.push((c, chars[i + 2])); + i += 3; + } else { + ranges.push((c, c)); + i += 1; + } + } + Atom::Class(ranges, negate) + } + '(' | ')' | '{' | '}' => return None, + c => Atom::Lit(c), + }; + i += 1; + let (min, max) = match chars.get(i) { + Some('*') => (0, usize::MAX), + Some('+') => (1, usize::MAX), + Some('?') => (0, 1), + _ => (1, 1), + }; + if (min, max) != (1, 1) { + i += 1; + } + alternatives.last_mut()?.push(Item { atom, min, max }); + } + Some(Pattern(alternatives)) + } + pub fn is_match(&self, text: &str) -> bool { + let text: Vec = text.chars().collect(); + self.0 + .iter() + .any(|alt| (0..=text.len()).any(|start| run(alt, &text, start))) + } +} +fn one(atom: &Atom, c: char) -> bool { + match atom { + Atom::Any => c != '\n', + Atom::Lit(l) => *l == c, + Atom::Class(r, negate) => r.iter().any(|(lo, hi)| *lo <= c && c <= *hi) != *negate, + Atom::Start | Atom::End => false, + } +} +fn run(items: &[Item], text: &[char], at: usize) -> bool { + let Some((item, rest)) = items.split_first() else { + return true; + }; + match item.atom { + Atom::Start => return at == 0 && run(rest, text, at), + Atom::End => return at == text.len() && run(rest, text, at), + _ => {} + } + let mut count = 0; + while count < item.max && at + count < text.len() && one(&item.atom, text[at + count]) { + count += 1; + } + (item.min..=count).rev().any(|n| run(rest, text, at + n)) +} + +#[cfg(test)] +mod tests { + use super::Pattern; + fn m(p: &str, t: &str) -> bool { + Pattern::new(p).unwrap().is_match(t) + } + #[test] + fn java_find_semantics() { + assert!(m("stone", "minecraft/stone_bricks")); + assert!(!m("^stone$", "stone_bricks")); + assert!(m("^textures/.*\\.png$", "textures/block/a.png")); + assert!(!m("^textures/.*\\.png$", "textures/block/a_png")); + assert!(m("[a-c]+z", "xxabcz")); + assert!(!m("^[^a]+$", "bab")); + assert!(m("dirt|grass", "grass_block")); + assert!(m(".*", "")); + assert!(Pattern::new("(a)").is_none()); + } +} From 302d96eeb1754395cbcfaefba03734999fef1291 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 06:58:17 +0200 Subject: [PATCH 3/3] Fix clippy findings in item models and pack mirroring Rewrote a negated float comparison in the compass wobble check, merged two identical branches in the pack overlay mirroring, and replaced the empty item model test stub with small unit tests so the workspace passes clippy and tests. Co-Authored-By: Claude Sonnet 5.5 --- .../examples/item_model_fixture.rs | 13 +- crates/horizon-assets/src/item_bake.rs | 13 +- crates/horizon-assets/src/item_model.rs | 111 +++++++++++------- crates/horizon-assets/src/item_model/tests.rs | 19 +++ crates/horizon-assets/src/math.rs | 4 +- crates/horizon-client/src/packs.rs | 6 +- 6 files changed, 110 insertions(+), 56 deletions(-) diff --git a/crates/horizon-assets/examples/item_model_fixture.rs b/crates/horizon-assets/examples/item_model_fixture.rs index 1729abf4c..559121782 100644 --- a/crates/horizon-assets/examples/item_model_fixture.rs +++ b/crates/horizon-assets/examples/item_model_fixture.rs @@ -31,7 +31,9 @@ impl SpriteLookup for Sprites { return hit.clone(); } let mask = self.load(sprite); - self.cache.borrow_mut().insert(sprite.to_owned(), mask.clone()); + self.cache + .borrow_mut() + .insert(sprite.to_owned(), mask.clone()); mask } } @@ -150,13 +152,16 @@ fn main() -> Result<(), Box> { let prototypes_path = &args[2]; let mut output = BufWriter::new(File::create(&args[4])?); - let raw: BTreeMap = - serde_json::from_slice(&fs::read(prototypes_path)?)?; + let raw: BTreeMap = serde_json::from_slice(&fs::read(prototypes_path)?)?; let mut models = ItemModels { prototypes: raw, ..Default::default() }; - writeln!(output, "{}", json!({"row":"components","names":DATA_COMPONENT_TYPES.to_vec()}))?; + writeln!( + output, + "{}", + json!({"row":"components","names":DATA_COMPONENT_TYPES.to_vec()}) + )?; let items_dir = root.join("assets/minecraft/items"); let mut files: Vec<_> = fs::read_dir(&items_dir)?.collect::>()?; files.sort_by_key(|f| f.file_name()); diff --git a/crates/horizon-assets/src/item_bake.rs b/crates/horizon-assets/src/item_bake.rs index 3a35d42a4..9afb2fbfb 100644 --- a/crates/horizon-assets/src/item_bake.rs +++ b/crates/horizon-assets/src/item_bake.rs @@ -134,21 +134,22 @@ pub fn bake_item_model( let mask = if m.sprite == MISSING_SPRITE { SpriteMask::opaque(16, 16) } else { - sprites.mask(&m.sprite).unwrap_or_else(|| SpriteMask::opaque(16, 16)) + sprites + .mask(&m.sprite) + .unwrap_or_else(|| SpriteMask::opaque(16, 16)) }; quads.extend(extrude_layer(&mask, &m, layer as i32)?); } quads } else { - let mut quads = bake_block_model( - &model, - crate::bake::BlockModelTransform::new([0; 3], false), - )?; + let mut quads = + bake_block_model(&model, crate::bake::BlockModelTransform::new([0; 3], false))?; for q in &mut quads { q.material = material(&q.material); } // `QuadCollection.Builder.build`: unculled, then each culled direction. - let mut ordered: Vec = quads.iter().filter(|q| q.cull.is_none()).cloned().collect(); + let mut ordered: Vec = + quads.iter().filter(|q| q.cull.is_none()).cloned().collect(); for side in [ Direction::North, Direction::South, diff --git a/crates/horizon-assets/src/item_model.rs b/crates/horizon-assets/src/item_model.rs index 1f0e775f3..d50140be2 100644 --- a/crates/horizon-assets/src/item_model.rs +++ b/crates/horizon-assets/src/item_model.rs @@ -247,7 +247,9 @@ fn boolean(v: &Value) -> Result { v.as_bool().ok_or_else(|| err("expected boolean")) } fn string(v: &Value) -> Result { - v.as_str().map(str::to_owned).ok_or_else(|| err("expected string")) + v.as_str() + .map(str::to_owned) + .ok_or_else(|| err("expected string")) } fn list(v: &Value) -> Result<&Vec> { v.as_array().ok_or_else(|| err("expected list")) @@ -367,8 +369,7 @@ impl ClientItem { let m = object(value)?; Ok(Self { model: ItemModelNode::decode(required(m, "model")?)?, - hand_animation_on_swap: get(m, "hand_animation_on_swap") - .map_or(Ok(true), boolean)?, + hand_animation_on_swap: get(m, "hand_animation_on_swap").map_or(Ok(true), boolean)?, oversized_in_gui: get(m, "oversized_in_gui").map_or(Ok(false), boolean)?, swap_animation_scale: get(m, "swap_animation_scale").map_or(Ok(1.0), float)?, }) @@ -615,7 +616,10 @@ pub enum ConditionProperty { Broken, Damaged, FishingRodCast, - HasComponent { component: String, ignore_default: bool }, + HasComponent { + component: String, + ignore_default: bool, + }, BundleHasSelectedItem, Selected, Carried, @@ -683,7 +687,9 @@ impl SelectProperty { "minecraft:main_hand" => Self::MainHand, "minecraft:charge_type" => Self::ChargeType, "minecraft:trim_material" => Self::TrimMaterial, - "minecraft:block_state" => Self::BlockState(string(required(m, "block_state_property")?)?), + "minecraft:block_state" => { + Self::BlockState(string(required(m, "block_state_property")?)?) + } "minecraft:display_context" => Self::DisplayContext, "minecraft:local_time" => Self::LocalTime { pattern: string(required(m, "pattern")?)?, @@ -791,17 +797,23 @@ pub enum NumericProperty { state: Arc, }, Cooldown, - Count { normalize: bool }, + Count { + normalize: bool, + }, CrossbowPull, CustomModelData(i32), - Damage { normalize: bool }, + Damage { + normalize: bool, + }, Time { wobble: bool, source: TimeSource, state: Arc, }, UseCycle(f32), - UseDuration { remaining: bool }, + UseDuration { + remaining: bool, + }, } impl NumericProperty { fn decode(m: &Map) -> Result { @@ -1018,7 +1030,11 @@ pub struct ItemModels { impl ItemModels { pub fn components(&self, stack: &StackView) -> Components { - let mut out = self.prototypes.get(&stack.item).cloned().unwrap_or_default(); + let mut out = self + .prototypes + .get(&stack.item) + .cloned() + .unwrap_or_default(); for (key, value) in &stack.patch { match value { Some(v) => out.insert(key.clone(), v.clone()), @@ -1028,12 +1044,7 @@ impl ItemModels { out } /// `ItemModelResolver.updateForTopItem`. - pub fn resolve( - &self, - stack: &StackView, - ctx: &Context, - env: &dyn ItemEnv, - ) -> ResolvedItem { + pub fn resolve(&self, stack: &StackView, ctx: &Context, env: &dyn ItemEnv) -> ResolvedItem { let mut out = ResolvedItem::default(); if stack.count > 0 && stack.item != "minecraft:air" { self.append_layers(&mut out, stack, ctx, env); @@ -1192,7 +1203,11 @@ impl Resolve<'_> { on_false, } => { let child = compose(parent, transformation); - let chosen = if self.condition(property) { on_true } else { on_false }; + let chosen = if self.condition(property) { + on_true + } else { + on_false + }; self.node(out, chosen, &child); } ItemModelNode::Select { @@ -1258,7 +1273,8 @@ impl Resolve<'_> { } ItemModelNode::BundleSelectedItem => { if let Some(selected) = self.bundle_selected() { - self.models.append_layers(out, &selected, self.ctx, self.env); + self.models + .append_layers(out, &selected, self.ctx, self.env); } } } @@ -1279,11 +1295,12 @@ impl Resolve<'_> { fn condition(&self, property: &ConditionProperty) -> bool { let owner = self.ctx.owner; match property { - ConditionProperty::CustomModelData(i) => self - .component("minecraft:custom_model_data") - .and_then(|d| custom_data_at(d, "flags", *i)) - .and_then(|v| v.as_bool()) - == Some(true), + ConditionProperty::CustomModelData(i) => { + self.component("minecraft:custom_model_data") + .and_then(|d| custom_data_at(d, "flags", *i)) + .and_then(|v| v.as_bool()) + == Some(true) + } ConditionProperty::UsingItem => owner.is_some_and(|o| o.using_this_item), ConditionProperty::Broken => { self.damageable() && self.damage_value() >= self.max_damage() - 1 @@ -1303,7 +1320,9 @@ impl Resolve<'_> { } } ConditionProperty::BundleHasSelectedItem => self.bundle_selected().is_some(), - ConditionProperty::Selected => owner.is_some_and(|o| o.is_local_player && o.is_selected), + ConditionProperty::Selected => { + owner.is_some_and(|o| o.is_local_player && o.is_selected) + } ConditionProperty::Carried => owner.is_some_and(|o| o.is_local_player && o.is_carried), ConditionProperty::ExtendedView => { self.ctx.display == DisplayContext::Gui && self.env.has_shift_down() @@ -1322,9 +1341,8 @@ impl Resolve<'_> { .component("minecraft:custom_model_data") .and_then(|d| custom_data_at(d, "strings", *i)) .cloned(), - SelectProperty::MainHand => owner.map(|o| { - Value::String(if o.main_arm_left { "left" } else { "right" }.to_owned()) - }), + SelectProperty::MainHand => owner + .map(|o| Value::String(if o.main_arm_left { "left" } else { "right" }.to_owned())), SelectProperty::ChargeType => { let projectiles = self .component("minecraft:charged_projectiles") @@ -1333,7 +1351,9 @@ impl Resolve<'_> { None => "none", Some(p) if p.is_empty() => "none", Some(p) => { - if p.iter().any(|t| template_id(t) == Some("minecraft:firework_rocket")) { + if p.iter() + .any(|t| template_id(t) == Some("minecraft:firework_rocket")) + { "rocket" } else { "arrow" @@ -1343,7 +1363,10 @@ impl Resolve<'_> { Some(Value::String(kind.to_owned())) } SelectProperty::TrimMaterial => { - let material = self.component("minecraft:trim")?.get("material")?.as_str()?; + let material = self + .component("minecraft:trim")? + .get("material")? + .as_str()?; identifier(material).ok().map(Value::String) } SelectProperty::BlockState(name) => self @@ -1366,17 +1389,18 @@ impl Resolve<'_> { SelectProperty::ContextEntityType => { owner.map(|o| Value::String(o.entity_type.clone())) } - SelectProperty::ContextDimension => self - .ctx - .level - .map(|l| Value::String(l.dimension.clone())), + SelectProperty::ContextDimension => { + self.ctx.level.map(|l| Value::String(l.dimension.clone())) + } SelectProperty::Component(component) => self.component(component).cloned(), } } fn numeric(&self, property: &NumericProperty) -> f32 { let owner = self.ctx.owner; match property { - NumericProperty::BundleFullness => self.env.bundle_fullness(self.stack, self.components), + NumericProperty::BundleFullness => { + self.env.bundle_fullness(self.stack, self.components) + } NumericProperty::Compass { wobble, target, @@ -1495,7 +1519,8 @@ impl Resolve<'_> { c[2] - owner.position[2], ]; // `distToCenterSqr(position) < 1.0E-5F` - !(d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < f64::from(1.0E-5_f32)) + let dist = d[0] * d[0] + d[1] * d[1] + d[2] * d[2]; + dist.is_nan() || dist >= f64::from(1.0E-5_f32) } }); let mut wobblers = state.0.lock().unwrap_or_else(|e| e.into_inner()); @@ -1538,9 +1563,7 @@ impl Resolve<'_> { .and_then(|v| rgb(v).ok()) .map_or(opaque(*default), opaque), TintSource::Dye(default) => match self.component("minecraft:dyed_color") { - Some(v) => opaque( - rgb(v.get("rgb").unwrap_or(v)).unwrap_or(0), - ), + Some(v) => opaque(rgb(v.get("rgb").unwrap_or(v)).unwrap_or(0)), None => *default, }, TintSource::Grass { @@ -1612,7 +1635,9 @@ fn enchantments_present(v: &Value) -> bool { map.as_object().is_some_and(|m| !m.is_empty()) } fn custom_data_at<'a>(data: &'a Value, list: &str, index: i32) -> Option<&'a Value> { - data.get(list)?.as_array()?.get(usize::try_from(index).ok()?) + data.get(list)? + .as_array()? + .get(usize::try_from(index).ok()?) } fn template_id(t: &Value) -> Option<&str> { t.get("id")?.as_str() @@ -1629,7 +1654,9 @@ fn stack_from_template(template: &Value) -> Option { stack.patch.insert(identifier(removed).ok()?, None); } None => { - stack.patch.insert(identifier(key).ok()?, Some(value.clone())); + stack + .patch + .insert(identifier(key).ok()?, Some(value.clone())); } } } @@ -1658,7 +1685,11 @@ fn last_index_less_or_equal(entries: &[(f32, ItemModelNode)], needle: f32) -> Op fn binary_search(a: &[f32], key: f32) -> std::result::Result { let (mut low, mut high) = (0i64, a.len() as i64 - 1); let bits = |v: f32| -> i32 { - if v.is_nan() { 0x7fc0_0000 } else { v.to_bits() as i32 } + if v.is_nan() { + 0x7fc0_0000 + } else { + v.to_bits() as i32 + } }; while low <= high { let mid = (low + high) >> 1; diff --git a/crates/horizon-assets/src/item_model/tests.rs b/crates/horizon-assets/src/item_model/tests.rs index 4563e55b7..6f6a2e067 100644 --- a/crates/horizon-assets/src/item_model/tests.rs +++ b/crates/horizon-assets/src/item_model/tests.rs @@ -1 +1,20 @@ use super::*; + +#[test] +fn identifier_adds_default_namespace() { + assert_eq!(identifier("stone").unwrap(), "minecraft:stone"); + assert_eq!(identifier("a:b").unwrap(), "a:b"); +} + +#[test] +fn positive_modulo_wraps_negatives() { + assert!((positive_modulo(-0.25, 1.0) - 0.75).abs() < 1e-6); + assert!((positive_modulo(1.5, 1.0) - 0.5).abs() < 1e-6); +} + +#[test] +fn display_context_names_round_trip() { + for name in ["gui", "ground", "fixed", "head"] { + assert_eq!(DisplayContext::by_name(name).unwrap().name(), name); + } +} diff --git a/crates/horizon-assets/src/math.rs b/crates/horizon-assets/src/math.rs index 1b81c7891..51a2de0e2 100644 --- a/crates/horizon-assets/src/math.rs +++ b/crates/horizon-assets/src/math.rs @@ -48,8 +48,8 @@ impl Mat4 { pub fn translate(&self, t: [f32; 3]) -> Self { let mut out = *self; for row in 0..4 { - out.0[3][row] = - self.0[0][row] * t[0] + (self.0[1][row] * t[1] + (self.0[2][row] * t[2] + self.0[3][row])); + out.0[3][row] = self.0[0][row] * t[0] + + (self.0[1][row] * t[1] + (self.0[2][row] * t[2] + self.0[3][row])); } out } diff --git a/crates/horizon-client/src/packs.rs b/crates/horizon-client/src/packs.rs index caf6c13b2..5e0e35515 100644 --- a/crates/horizon-client/src/packs.rs +++ b/crates/horizon-client/src/packs.rs @@ -374,12 +374,10 @@ pub fn build_overlay(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<( } } } - } else if vanilla.join(&child).is_dir() - && (touched.contains(&child) || !filters.is_empty()) + } else if touched.contains(&child) + || (vanilla.join(&child).is_dir() && !filters.is_empty()) { mirror(&child, vanilla, out, touched, files, filters, zips)?; - } else if touched.contains(&child) { - mirror(&child, vanilla, out, touched, files, filters, zips)?; } else if filters.iter().any(|f| f.blocks(&child)) { // Hidden by a pack's filter. } else {