From c77863f16314af2f891ee50c770b4ce158197cf4 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 12:08:30 +0200 Subject: [PATCH] Armour trims on worn armour (player, LAN guests, armour stands) EquipmentLayerRenderer's trim layer: the pattern's textures/trims/entity//.png recoloured from its base palette (palette metadata section) to the material's palette, or to the equipment asset's trim_overrides palette (iron armour with an iron trim uses trim/iron_darker), as PalettedTextureManager does. Each texture is made once, on first use, into one of 32 atlas trim slots (least recently drawn reused), and drawn over the armour layer on the player, on the guests a LAN host sees and on armour stands. Fixes #337 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 4 + .../horizon-client/src/game/armor_stands.rs | 181 ++++++++- crates/horizon-client/src/game/lan.rs | 7 +- crates/horizon-client/src/game/packs.rs | 1 + crates/horizon-client/src/hud.rs | 15 +- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/trims.rs | 354 ++++++++++++++++++ 7 files changed, 553 insertions(+), 10 deletions(-) create mode 100644 crates/horizon-client/src/trims.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2df6aa9b0..e6ccccaab 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1372,6 +1372,8 @@ struct Game<'a> { /// (least recently shown first). skin_downloads: horizon_client::skins::Downloader, skin_slots: Vec<(String, usize)>, + /// Atlas trim slots in use: (sprite name, slot), least recently drawn first. + trim_slots: Vec<(String, usize)>, cart_models: minecarts::CartModels, /// The boat the player rides. riding: Option, @@ -6278,6 +6280,7 @@ impl Game<'_> { mut out: Vec, ) -> Vec { self.prepare_entity_culling(camera); + self.prepare_trims(); let fire_yaw = if self.camera_type == perspective::CameraType::ThirdPersonFront { self.yaw + 180.0 } else { @@ -11439,6 +11442,7 @@ impl<'a> Game<'a> { .join("assets/skins"), ), skin_slots: Vec::new(), + trim_slots: Vec::new(), cart_models: prepared.cart_models, riding: None, ender_items: vec![None; 27], diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index 9f174c5ef..121287c4c 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -8,12 +8,13 @@ use horizon_client::{ items::ItemStack, mesher::Vertex, mobs::{Mob, Part, anim::Poses}, + trims::{TrimOverride, TrimRegistry, TrimTexture}, }; use horizon_core::{ geometry::{Aabb, Vec3}, random::RandomSource, }; -use std::{collections::HashMap, sync::Arc}; +use std::{collections::HashMap, path::PathBuf, sync::Arc}; /// Armor stand models and the humanoid layers of every equipment asset. pub(super) struct ArmorStandAssets { @@ -25,6 +26,11 @@ pub(super) struct ArmorStandAssets { pub player: HashMap<&'static str, Part>, /// asset id -> layer kind (humanoid / humanoid_leggings) -> (texture, undyed colour). pub equipment: HashMap)>>, + /// asset id -> `trim_overrides`. + pub trim_overrides: HashMap>, + pub trims: TrimRegistry, + /// The resources the trim textures are made from. + pub root: PathBuf, } impl ArmorStandAssets { pub fn load( @@ -48,6 +54,7 @@ impl ArmorStandAssets { player.insert("elytra", part); } let mut equipment = HashMap::new(); + let mut trim_overrides = HashMap::new(); if let Ok(entries) = std::fs::read_dir(root.join("assets/minecraft/equipment")) { for e in entries.flatten() { let path = e.path(); @@ -76,6 +83,7 @@ impl ArmorStandAssets { ); } } + trim_overrides.insert(format!("minecraft:{name}"), TrimOverride::list(&v)); equipment.insert(format!("minecraft:{name}"), kinds); } } @@ -85,30 +93,67 @@ impl ArmorStandAssets { layers, player, equipment, + trim_overrides, + trims: TrimRegistry::load(root), + root: root.to_owned(), } } + /// Trim data of reloaded resources (the models stay). + pub fn reload_trims(&mut self, root: &std::path::Path) { + let fresh = Self::load(root, None); + self.trim_overrides = fresh.trim_overrides; + self.trims = fresh.trims; + self.root = fresh.root; + } + /// `TrimTextureKey`: the trim texture of `stack` on its humanoid + /// layer (`humanoid` or `humanoid_leggings`), if it has a trim. + fn trim_texture(&self, asset: &str, kind: &str, stack: &ItemStack) -> Option { + let (material, pattern) = stack.extra.as_ref()?.trim.as_ref()?; + let overrides = self + .trim_overrides + .get(asset) + .map_or(&[][..], Vec::as_slice); + TrimTexture::resolve(&self.trims, overrides, material, pattern, kind) + } } impl Game<'_> { /// `HumanoidArmorLayer` for the player: (model, texture rect, colour) of /// each worn piece, head to feet. pub(super) fn player_armor_layers(&self) -> Vec<(&Part, [f32; 4], u32)> { - self.armor_layers(self.armor.each_ref().map(|s| s.as_ref().map(|s| &*s.item))) + self.stack_armor_layers(&self.armor) + } + /// `HumanoidArmorLayer` for worn stacks (head to feet), trims included. + pub(super) fn stack_armor_layers( + &self, + armor: &[Option; 4], + ) -> Vec<(&Part, [f32; 4], u32)> { + self.armor_layers( + armor + .each_ref() + .map(|s| s.as_ref().map(|s| (&*s.item, Some(s)))), + ) } /// `HumanoidArmorLayer` for another player's model: the armour it wears /// (`extra.head` .. `extra.feet`). pub(super) fn worn_armor_layers(&self, m: &Mob) -> Vec<(&Part, [f32; 4], u32)> { let e = &m.extra; - self.armor_layers([&e.head, &e.chest, &e.legs, &e.feet].map(|s| s.as_deref())) + self.armor_layers( + [&e.head, &e.chest, &e.legs, &e.feet].map(|s| s.as_deref().map(|i| (i, None))), + ) } - /// The layers of the armour items `worn`, head to feet. - fn armor_layers(&self, worn: [Option<&str>; 4]) -> Vec<(&Part, [f32; 4], u32)> { + /// The layers of the armour items `worn` (with their stacks when known, + /// for trims), head to feet. + fn armor_layers( + &self, + worn: [Option<(&str, Option<&ItemStack>)>; 4], + ) -> Vec<(&Part, [f32; 4], u32)> { let assets = &self.armor_stand_assets; let mut out = Vec::new(); for (item, layer) in worn .into_iter() .zip(["helmet", "chestplate", "leggings", "boots"]) { - let Some(item) = item else { + let Some((item, stack)) = item else { continue; }; let Some(asset) = self @@ -138,9 +183,117 @@ impl Game<'_> { 0xFF00_0000 | (c & 0xFF) << 16 | (c & 0xFF00) | (c >> 16) & 0xFF }); out.push((part, [r.u0, r.v0, r.u1, r.v1], color)); + // EquipmentLayerRenderer: the trim layer over the armour. + if let Some(r) = stack + .and_then(|s| assets.trim_texture(&asset, kind, s)) + .and_then(|t| self.gui.atlas.sprites.get(&t.sprite())) + { + out.push((part, [r.u0, r.v0, r.u1, r.v1], 0xFFFF_FFFF)); + } } out } + /// `PalettedTextureManager.getOrPrepare` for the trims drawn this frame + /// (the player's armour and the armour stands'): each generated texture + /// goes into an atlas trim slot, a free one, else the least recently + /// drawn. + pub(super) fn prepare_trims(&mut self) { + use horizon_client::hud::TRIM_SLOTS; + let assets = &self.armor_stand_assets; + let items = self.res.items(); + let mut wanted: Vec = Vec::new(); + let guests = self.lan.iter().flat_map(|host| host.hub.guests.iter()); + let stacks = self + .armor + .iter() + .chain(guests.flat_map(|g| g.armor.iter())) + .zip( + ["helmet", "chestplate", "leggings", "boots"] + .into_iter() + .cycle(), + ) + .chain(self.armor_stands.iter().flat_map(|a| { + [5usize, 4, 3, 2] + .map(|slot| &a.equipment[slot]) + .into_iter() + .zip(["helmet", "chestplate", "leggings", "boots"]) + })); + for (stack, layer) in stacks { + let Some(stack) = stack.as_ref().filter(|s| s.extra.is_some()) else { + continue; + }; + let Some(asset) = items + .get(&stack.item) + .and_then(|i| i.equip_asset.as_deref()) + else { + continue; + }; + let kind = if layer == "leggings" { + "humanoid_leggings" + } else { + "humanoid" + }; + if let Some(t) = assets.trim_texture(asset, kind, stack) + && !wanted.contains(&t) + { + wanted.push(t); + } + } + for t in wanted { + let name = t.sprite(); + // Entries the atlas no longer has (rebuilt by a resource reload) are free. + let sprites = &self.gui.atlas.sprites; + self.trim_slots.retain(|(n, _)| sprites.contains_key(n)); + if let Some(i) = self.trim_slots.iter().position(|e| e.0 == name) { + let e = self.trim_slots.remove(i); + self.trim_slots.push(e); + continue; + } + let Some((w, h, rgba)) = t.generate(&self.armor_stand_assets.root) else { + continue; + }; + let used: Vec = self.trim_slots.iter().map(|e| e.1).collect(); + let slot = match (0..TRIM_SLOTS).find(|i| !used.contains(i)) { + Some(free) => free, + None => { + let (old, slot) = self.trim_slots.remove(0); + self.gui.atlas.sprites.remove(&old); + slot + } + }; + let Some(area) = self + .gui + .atlas + .sprites + .get(&format!("horizon/trim{slot}")) + .copied() + else { + continue; + }; + if w > area.w || h > area.h { + continue; + } + let (aw, ah) = (self.gui.atlas.width as f32, self.gui.atlas.height as f32); + let (x, y) = ((area.u0 * aw).round(), (area.v0 * ah).round()); + self.map_patches.push(horizon_client::font::Patch { + x: x as u32, + y: y as u32, + width: w, + height: h, + rgba, + }); + let rect = horizon_client::hud::Rect { + u0: area.u0, + v0: area.v0, + u1: (x + w as f32) / aw, + v1: (y + h as f32) / ah, + w, + h, + }; + self.gui.atlas.sprites.insert(name.clone(), rect); + self.trim_slots.push((name, slot)); + } + } /// `ArmorStandItem.useOn`. pub(super) fn place_armor_stand(&mut self, hit: &super::Hit, stack: &ItemStack) -> bool { if &*stack.item != "minecraft:armor_stand" || hit.face == [0, -1, 0] { @@ -560,6 +713,22 @@ impl Game<'_> { 0, out, ); + // EquipmentLayerRenderer: the trim layer over the armour. + if let Some(trim) = assets + .trim_texture(&asset, kind, stack) + .and_then(|t| uv_of(&t.sprite())) + { + horizon_client::mobs::render::draw( + part, + base, + &layer_poses, + trim, + 0xFFFF_FFFF, + packed, + 0, + out, + ); + } } self.cull_entity_vertices(out, entity_start); } diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index f9ea1262b..4fb99e2e9 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1253,7 +1253,7 @@ impl Game<'_> { }; let atlas = &self.gui.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); - for m in host.models.values() { + for (conn, m) in &host.models { let entity_start = out.len(); let light = self.world.light( m.position.x.floor() as i32, @@ -1268,7 +1268,10 @@ impl Game<'_> { &lookup, packed, self.res.mob_data(), - &self.worn_armor_layers(m), + &host.hub.guest(*conn).map_or_else( + || self.worn_armor_layers(m), + |g| self.stack_armor_layers(&g.armor), + ), out, ); self.held_item_geometry(m, camera, alpha, packed, true, out); diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index ac08385a0..e635b46d2 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -171,6 +171,7 @@ impl Game<'_> { } }; // Everything loaded: switch over. + self.armor_stand_assets.reload_trims(root); self.random_tick_sections.clear(); self.portals.sections.clear(); self.options.resources = root.to_path_buf(); diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 0cc99b07b..69d642246 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -38,6 +38,9 @@ pub const MINIMAP_SPRITE: &str = "horizon/minimap"; pub const SKIN_SLOTS: usize = 32; /// Reused by the visible rows of the classic world selector. pub const WORLD_ICON_SLOTS: usize = 32; +/// Atlas slots for armour trim textures made at run time (`trims`), each the +/// size of the largest trim texture. +pub const TRIM_SLOTS: usize = 32; pub fn decode(path: &Path) -> Result<(u32, u32, Vec)> { decode_bytes(&fs::read(path)?) } @@ -159,7 +162,7 @@ impl HudAtlas { } /// Empty slots written at run time: map textures (game/maps.rs), the /// minimap, downloaded skins, world icons and the Horizon menu text. - fn slots(images: &mut Vec) { + fn slots(images: &mut Vec, trim: (u32, u32)) { for i in 0..MAP_SLOTS { images.push((format!("horizon/map{i}"), 128, 128, vec![0; 128 * 128 * 4])); } @@ -174,6 +177,14 @@ impl HudAtlas { for i in 0..SKIN_SLOTS { images.push((format!("horizon/skin{i}"), 64, 64, vec![0; 64 * 64 * 4])); } + for i in 0..TRIM_SLOTS { + images.push(( + format!("horizon/trim{i}"), + trim.0, + trim.1, + vec![0; (trim.0 * trim.1 * 4) as usize], + )); + } for i in 0..WORLD_ICON_SLOTS { images.push(( format!("horizon/world-icon{i}"), @@ -256,7 +267,7 @@ impl HudAtlas { } images.push(("horizon/white".into(), 4, 4, vec![255; 64])); if full { - Self::slots(&mut images); + Self::slots(&mut images, crate::trims::slot_size(root)); } images.sort_by(|a, b| b.2.cmp(&a.2).then(b.1.cmp(&a.1))); let width = 4096u32; diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 7a69de4aa..b12981533 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -179,6 +179,7 @@ pub mod ticket_levels; pub mod title; pub mod title_edition; pub mod toasts; +pub mod trims; pub mod ui; pub mod ui_theme; pub mod vanillagen; diff --git a/crates/horizon-client/src/trims.rs b/crates/horizon-client/src/trims.rs new file mode 100644 index 000000000..e53aeed72 --- /dev/null +++ b/crates/horizon-client/src/trims.rs @@ -0,0 +1,354 @@ +//! Armour trims on worn armour: `EquipmentLayerRenderer`'s trim layer. A +//! trim's texture is `textures/trims/entity//.png` recoloured +//! by `PalettedTextureManager`: every pixel whose colour is in the texture's +//! base palette (its `palette` metadata section, `trim_base`) takes the colour +//! at the same index of the material's palette (`textures/palettes/trim/*`), +//! unless the equipment asset's `trim_overrides` pick another texture or +//! palette (iron armour with an iron trim uses `trim/iron_darker`). +use horizon_assets::palette::apply_palette; +use serde_json::Value; +use std::{collections::HashMap, fs, path::Path}; + +/// An RGBA image: width, height, pixels. +pub type Image = (u32, u32, Vec); + +/// `minecraft:` added to an identifier without a namespace. +fn qualified(id: &str) -> String { + if id.contains(':') { + id.to_owned() + } else { + format!("minecraft:{id}") + } +} + +/// `assets///` of an identifier. +fn asset_path(root: &Path, folder: &str, id: &str, suffix: &str) -> std::path::PathBuf { + let id = qualified(id); + let (namespace, path) = id.split_once(':').unwrap_or(("minecraft", &id)); + root.join("assets") + .join(namespace) + .join(folder) + .join(format!("{path}{suffix}")) +} + +/// `EquipmentClientInfo.TrimOverride`: when the trim matches (`when`'s +/// material and pattern, each optional), use `texture` instead of the +/// pattern's asset id and `palette` (none when absent) as the palette. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct TrimOverride { + pub material: Option, + pub pattern: Option, + pub texture: Option, + pub palette: Option, +} +impl TrimOverride { + /// An equipment asset's `trim_overrides` list. + pub fn list(equipment: &Value) -> Vec { + let Some(list) = equipment.get("trim_overrides").and_then(Value::as_array) else { + return Vec::new(); + }; + let id = |v: &Value, key: &str| v.get(key).and_then(Value::as_str).map(qualified); + list.iter() + .filter_map(|o| { + let when = o.get("when")?; + Some(Self { + material: id(when, "material"), + pattern: id(when, "pattern"), + texture: id(o, "texture"), + palette: id(o, "palette"), + }) + }) + .collect() + } + /// `TrimPredicate.matches`. + fn matches(&self, material: &str, pattern: &str) -> bool { + self.material.as_deref().is_none_or(|m| m == material) + && self.pattern.as_deref().is_none_or(|p| p == pattern) + } +} + +/// The `trim_pattern` (asset id) and `trim_material` (palette id) registries. +#[derive(Clone, Debug, Default)] +pub struct TrimRegistry { + patterns: HashMap, + materials: HashMap, +} +impl TrimRegistry { + /// Every `data//trim_pattern` and `trim_material` entry. + pub fn load(root: &Path) -> Self { + let mut out = Self::default(); + let Ok(namespaces) = fs::read_dir(root.join("data")) else { + return out; + }; + for ns in namespaces.flatten() { + let namespace = ns.file_name().to_string_lossy().into_owned(); + for (folder, key, map) in [ + ("trim_pattern", "asset_id", &mut out.patterns), + ("trim_material", "palette_id", &mut out.materials), + ] { + let Ok(files) = fs::read_dir(ns.path().join(folder)) else { + continue; + }; + for f in files.flatten() { + let path = f.path(); + if path.extension().is_none_or(|e| e != "json") { + continue; + } + let Some(value) = fs::read(&path) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + else { + continue; + }; + if let Some(v) = value.get(key).and_then(Value::as_str) { + let name = path.file_stem().unwrap_or_default().to_string_lossy(); + map.insert(format!("{namespace}:{name}"), qualified(v)); + } + } + } + } + out + } + #[cfg(test)] + fn of(patterns: &[(&str, &str)], materials: &[(&str, &str)]) -> Self { + let map = |l: &[(&str, &str)]| { + l.iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect() + }; + Self { + patterns: map(patterns), + materials: map(materials), + } + } +} + +/// The texture and palette of one trim layer. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct TrimTexture { + /// `:trims/entity//`, under `textures/`. + pub texture: String, + /// The target palette under `textures/palettes/`; none draws the + /// texture's own colours. + pub palette: Option, +} +impl TrimTexture { + /// `TrimTextureKey.getOrPrepareTexture`: the trim (`material`, + /// `pattern` registry ids) on the `layer` (`humanoid`, + /// `humanoid_leggings`...) of an equipment asset with `overrides`. + pub fn resolve( + registry: &TrimRegistry, + overrides: &[TrimOverride], + material: &str, + pattern: &str, + layer: &str, + ) -> Option { + let (material, pattern) = (qualified(material), qualified(pattern)); + let mut texture = registry.patterns.get(&pattern)?.clone(); + let mut palette = Some(registry.materials.get(&material)?.clone()); + if let Some(o) = overrides.iter().find(|o| o.matches(&material, &pattern)) { + if let Some(t) = &o.texture { + texture.clone_from(t); + } + palette.clone_from(&o.palette); + } + let (namespace, path) = texture.split_once(':')?; + Some(Self { + texture: format!("{namespace}:trims/entity/{layer}/{path}"), + palette, + }) + } + /// The atlas sprite name the generated texture is stored under. + pub fn sprite(&self) -> String { + format!( + "horizon/trim/{}/{}", + self.texture, + self.palette.as_deref().unwrap_or("-") + ) + } + /// `PalettedTextureManager.prepareSlot`: the texture with its base + /// palette's colours swapped for the target palette's (`PaletteMapping`; + /// unchanged when a palette is missing or the sizes differ). None when + /// the texture itself is missing. + pub fn generate(&self, root: &Path) -> Option { + let path = asset_path(root, "textures", &self.texture, ".png"); + let (w, h, pixels) = crate::hud::decode(&path).ok()?; + let Some(palette) = &self.palette else { + return Some((w, h, pixels)); + }; + let base = fs::read(path.with_extension("png.mcmeta")) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + .and_then(|m| { + m.get("palette")? + .get("base_palette")? + .as_str() + .map(str::to_owned) + }); + let load = |id: &str| { + crate::hud::decode(&asset_path(root, "textures/palettes", id, ".png")) + .ok() + .map(|(_, _, p)| argb(&p)) + }; + let mut mapped = argb(&pixels); + if let (Some(key), Some(target)) = (base.as_deref().and_then(load), load(palette)) { + // Different sizes: PaletteMapping.NONE, the texture as it is. + let _ = apply_palette(&mut mapped, &key, &target); + } + let out = mapped + .iter() + .flat_map(|p| { + let [a, r, g, b] = p.to_be_bytes(); + [r, g, b, a] + }) + .collect(); + Some((w, h, out)) + } +} + +fn argb(rgba: &[u8]) -> Vec { + rgba.as_chunks::<4>() + .0 + .iter() + .map(|p| u32::from_be_bytes([p[3], p[0], p[1], p[2]])) + .collect() +} + +/// The largest trim texture of the resources (the size of the atlas's trim +/// slots), at least vanilla's 64x32. +pub fn slot_size(root: &Path) -> (u32, u32) { + let mut size = (64, 32); + let Ok(namespaces) = fs::read_dir(root.join("assets")) else { + return size; + }; + for ns in namespaces.flatten() { + let Ok(layers) = fs::read_dir(ns.path().join("textures/trims/entity")) else { + continue; + }; + for layer in layers.flatten() { + for f in fs::read_dir(layer.path()).into_iter().flatten().flatten() { + let path = f.path(); + if path.extension().is_some_and(|e| e == "png") + && let Some((w, h)) = png_size(&path) + { + size = (size.0.max(w.min(512)), size.1.max(h.min(512))); + } + } + } + } + size +} + +/// The width and height in a PNG's IHDR chunk. +fn png_size(path: &Path) -> Option<(u32, u32)> { + use std::io::Read; + let mut head = [0u8; 24]; + fs::File::open(path).ok()?.read_exact(&mut head).ok()?; + let be = |i: usize| u32::from_be_bytes(head[i..i + 4].try_into().unwrap()); + (&head[12..16] == b"IHDR").then(|| (be(16), be(20))) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn registry() -> TrimRegistry { + TrimRegistry::of( + &[("minecraft:coast", "minecraft:coast")], + &[ + ("minecraft:iron", "minecraft:trim/iron"), + ("minecraft:gold", "minecraft:trim/gold"), + ], + ) + } + + #[test] + fn material_palette_and_layer_folder() { + let t = TrimTexture::resolve( + ®istry(), + &[], + "minecraft:gold", + "minecraft:coast", + "humanoid_leggings", + ) + .unwrap(); + assert_eq!(t.texture, "minecraft:trims/entity/humanoid_leggings/coast"); + assert_eq!(t.palette.as_deref(), Some("minecraft:trim/gold")); + // Unknown registry entries draw nothing. + assert!( + TrimTexture::resolve( + ®istry(), + &[], + "minecraft:wood", + "minecraft:coast", + "humanoid" + ) + .is_none() + ); + } + + #[test] + fn equipment_overrides_pick_the_darker_palette() { + let iron = serde_json::json!({"trim_overrides": [ + {"palette": "minecraft:trim/iron_darker", "when": {"material": "minecraft:iron"}}, + ]}); + let overrides = TrimOverride::list(&iron); + let resolve = + |m| TrimTexture::resolve(®istry(), &overrides, m, "coast", "humanoid").unwrap(); + assert_eq!( + resolve("iron").palette.as_deref(), + Some("minecraft:trim/iron_darker") + ); + assert_eq!( + resolve("gold").palette.as_deref(), + Some("minecraft:trim/gold") + ); + // An override without a palette leaves the texture's own colours. + let plain = TrimOverride::list(&serde_json::json!({"trim_overrides": [ + {"texture": "minecraft:other", "when": {"pattern": "minecraft:coast"}}, + ]})); + let t = TrimTexture::resolve(®istry(), &plain, "gold", "coast", "humanoid").unwrap(); + assert_eq!(t.texture, "minecraft:trims/entity/humanoid/other"); + assert_eq!(t.palette, None); + } + + #[test] + fn vanilla_trims_are_recoloured() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); + if !root.join("assets/minecraft/textures/trims").is_dir() { + return; + } + let registry = TrimRegistry::load(&root); + let t = TrimTexture::resolve( + ®istry, + &[], + "minecraft:gold", + "minecraft:coast", + "humanoid", + ) + .unwrap(); + let (w, h, gold) = t.generate(&root).unwrap(); + assert_eq!((w, h), (64, 32)); + let plain = TrimTexture { + palette: None, + ..t.clone() + }; + let (_, _, grey) = plain.generate(&root).unwrap(); + // Every opaque pixel of the grey pattern takes a gold palette colour. + let gold_palette = argb( + &crate::hud::decode(&root.join("assets/minecraft/textures/palettes/trim/gold.png")) + .unwrap() + .2, + ); + let mut opaque = 0; + for (g, c) in grey.chunks(4).zip(gold.chunks(4)) { + if g[3] != 0 { + opaque += 1; + let c = u32::from_be_bytes([0xFF, c[0], c[1], c[2]]); + assert!(gold_palette.contains(&c), "{c:08x}"); + } + } + assert!(opaque > 0); + assert_eq!(slot_size(&root), (64, 32)); + } +}