From fb954f7d7f80b107b4b3dfa76dd02c738bb40dc4 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:29:51 +0200 Subject: [PATCH 01/13] Load saved light and test it against vanilla Chunks saved with isLightOn now read their SkyLight and BlockLight arrays back like vanilla instead of being relit: a missing sky layer repeats the bottom layer of the section above it, and a missing block layer is dark. Such chunks skip the light job, mesh as soon as their neighbours are lit, and only relight when a freshly generated neighbour arrives. tools/test_light_parity.py builds a scene of slabs, stairs, snow, trapdoors, lanterns, leaves and lava in a vanilla world, edits it, and requires every saved light value and every incremental relight to match Horizon's engine. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/chunk.rs | 3 + crates/horizon-client/src/save.rs | 104 ++++++++++++++++++++++++- crates/horizon-client/src/streaming.rs | 15 +++- tools/test_light_parity.py | 100 ++++++++++++++++++++++++ 4 files changed, 220 insertions(+), 2 deletions(-) create mode 100755 tools/test_light_parity.py diff --git a/crates/horizon-client/src/chunk.rs b/crates/horizon-client/src/chunk.rs index e1332b159..d5e65655c 100644 --- a/crates/horizon-client/src/chunk.rs +++ b/crates/horizon-client/src/chunk.rs @@ -94,6 +94,8 @@ pub struct Chunk { /// Highest non-air, light-blocking-or-fluid Y per column (MOTION_BLOCKING-like), for rain/sky. pub heights: Arc<[i16; 256]>, pub lit: bool, + /// Light read from a save with `isLightOn`: no light job is needed. + pub light_loaded: bool, /// Newly generated (not loaded from a save): eligible for generation-time spawns. pub fresh: bool, /// Block entities read from a save, moved into the world on arrival. @@ -120,6 +122,7 @@ impl Chunk { biomes: Arc::new(vec![0; 16 * (HEIGHT as usize / 4)]), heights: Arc::new([MIN_Y as i16; 256]), lit: false, + light_loaded: false, fresh: false, block_entities: Vec::new(), structure_refs: Vec::new(), diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index bcca25e8a..83e93e8e1 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -901,6 +901,60 @@ pub fn decode_with( Some(chunk) } +/// Read the stored `SkyLight`/`BlockLight` layers of a chunk saved with +/// `isLightOn` (`SerializableChunkData.read` + `ThreadedLevelLightEngine`), +/// so it needs no relighting. A missing sky layer repeats the bottom layer of +/// the section above it (15 above the highest stored one); a missing block +/// layer is dark. +pub fn load_light(tag: &Tag, chunk: &mut Chunk, sky_light: bool) { + if tag.get("isLightOn") != Some(&Tag::Byte(1)) { + return; + } + let Some(Tag::List(sections)) = tag.get("sections") else { + return; + }; + let mut layers: Vec<(Option<&[u8]>, Option<&[u8]>)> = vec![(None, None); SECTIONS]; + for section in sections { + let Some(y) = number(section.get("Y")) else { + continue; + }; + let si = y as i32 - (MIN_Y >> 4); + if !(0..SECTIONS as i32).contains(&si) { + continue; + } + let layer = |name: &str| match section.get(name) { + Some(Tag::ByteArray(a)) if a.len() == 2048 => Some(&a[..]), + _ => None, + }; + layers[si as usize] = (layer("SkyLight"), layer("BlockLight")); + } + let sky_default = if sky_light { 15u8 } else { 0 }; + // Sky nibbles of the section above's bottom layer, going down. + let mut above: [u8; 256] = [sky_default; 256]; + for si in (0..SECTIONS).rev() { + let (sky, block) = layers[si]; + let mut data = Box::new([0u8; 4096]); + let nibble = |a: &[u8], i: usize| (a[i >> 1] >> ((i & 1) * 4)) & 15; + for (i, packed) in data.iter_mut().enumerate() { + let s = match sky { + Some(a) if sky_light => nibble(a, i), + _ => above[i & 255], + }; + let b = block.map_or(0, |a| nibble(a, i)); + *packed = s << 4 | b; + } + for (i, a) in above.iter_mut().enumerate() { + *a = data[i] >> 4; + } + let mut section = (*chunk.sections[si]).clone(); + section.light = Light::Full(data); + section.compact(); + chunk.sections[si] = Arc::new(section); + } + chunk.lit = true; + chunk.light_loaded = true; +} + type RegionCache = Mutex>>>>; /// One dimension folder (`dimensions/minecraft/`). Region files are /// read lazily by worker threads. @@ -951,7 +1005,9 @@ impl SaveDir { pub fn load(&self, x: i32, z: i32, registry: &BlockRegistry, biomes: &Biomes) -> Option { let root = self.read_record("region", x, z)?; let tables = self.tables.get().map(|t| &**t); - decode_with(&root, registry, biomes, tables) + let mut chunk = decode_with(&root, registry, biomes, tables)?; + load_light(&root.tag, &mut chunk, self.sky_light); + Some(chunk) } /// Entities saved for a chunk (`entities/`; older chunks may still keep /// them in the chunk's own `entities` list). @@ -2016,6 +2072,52 @@ mod tests { assert_eq!(nibbles(&light, true)[0], 0x5F); } #[test] + fn stored_light_loads_with_vanilla_defaults() { + let mut sky = vec![0u8; 2048]; + sky[0] = 0x5A; // x=0 -> 10, x=1 -> 5 + let section = |y: i8, entries: Vec<(&str, Tag)>| { + let mut all = vec![("Y", Tag::Byte(y))]; + all.extend(entries); + Tag::compound(all) + }; + let tag = Tag::compound([ + ("isLightOn", Tag::Byte(1)), + ( + "sections", + Tag::List(vec![ + section( + -4, + vec![ + ("SkyLight", Tag::ByteArray(sky)), + ("BlockLight", Tag::ByteArray(vec![0x21; 2048])), + ], + ), + // No sky layer: repeats the bottom layer of the section above. + section(-3, vec![]), + ]), + ), + ]); + let mut chunk = Chunk::empty(0, 0); + load_light(&tag, &mut chunk, true); + assert!(chunk.lit && chunk.light_loaded); + let at = |c: &Chunk, si: usize, i: usize| c.sections[si].light(i); + assert_eq!(at(&chunk, 0, 0), 0xA1, "stored sky 10, block 1"); + assert_eq!(at(&chunk, 0, 1), 0x52, "stored sky 5, block 2"); + // Section -3 has no layers; above it (-2..) sky defaults to 15. + assert_eq!(at(&chunk, 1, 0), 0xF0); + assert_eq!(at(&chunk, SECTIONS - 1, 5), 0xF0); + let mut dark = Chunk::empty(0, 0); + load_light(&tag, &mut dark, false); + assert_eq!(at(&dark, 1, 0), 0x00, "no skylight dimension"); + let mut unlit = Chunk::empty(0, 0); + load_light( + &Tag::compound([("isLightOn", Tag::Byte(0))]), + &mut unlit, + true, + ); + assert!(!unlit.lit && !unlit.light_loaded); + } + #[test] fn level_round_trips_through_the_vanilla_files() { let dir = std::env::temp_dir().join(format!("horizon-level-{}", std::process::id())); let _ = fs::remove_dir_all(&dir); diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 6fd8a64bd..c43e82e69 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -329,10 +329,23 @@ impl Streaming { self.decorated.insert(key); if self.in_range(key.0, key.1, 2) { self.generated_total += 1; + // A chunk saved with its light needs no light job; its + // unlit neighbours still light themselves from it. + let loaded = chunk.light_loaded; world.chunks.insert(key, Arc::new(chunk)); + if loaded { + self.lit.insert(key); + for sy in 0..SECTIONS as i32 { + world.dirty_sections.insert((key.0, sy, key.1)); + } + } for dz in -1..=1 { for dx in -1..=1 { - world.dirty_light.insert((key.0 + dx, key.1 + dz)); + let n = (key.0 + dx, key.1 + dz); + if !loaded || world.chunks.get(&n).is_some_and(|c| !c.light_loaded) + { + world.dirty_light.insert(n); + } } } } diff --git a/tools/test_light_parity.py b/tools/test_light_parity.py new file mode 100755 index 000000000..3e42acd5c --- /dev/null +++ b/tools/test_light_parity.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""Compare Horizon's light engine with the vanilla 26.3 server. + +Builds a scene of slabs, stairs, snow layers, trapdoors, lanterns, glass, +leaves, water and glowstone in a fresh vanilla world, lets the vanilla light +engine settle, stops the server so the SkyLight/BlockLight arrays are saved, +then relights every saved chunk with `examples/light_parity` and requires every +value to agree. The example also replays block edits through the incremental +`light::relight` and checks them against a full relight. + + test_light_parity.py [--seed N] [--keep] +""" +import argparse +import shutil +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +LOCAL = ROOT / '.local' +RESOURCES = LOCAL / 'horizon-client' / '26.3' +SERVER = LOCAL / 'minecraft' / '26.3' / 'jars' / 'server.jar' + +# Absolute coordinates well above the terrain, inside force-loaded chunks. +SCENE = [ + 'forceload add 0 0 63 63', + 'sleep 6', + # Closed room with a bottom-slab roof and a glowstone lamp. + 'fill 2 170 2 20 175 20 stone hollow', + 'fill 2 176 2 20 176 20 stone_slab[type=bottom]', + 'setblock 10 171 10 glowstone', + # Stairs, top and bottom; snow layers; trapdoors; lanterns; water. + 'fill 4 171 4 4 171 18 oak_stairs[facing=east,half=top]', + 'fill 6 171 4 6 171 18 stone_brick_stairs[facing=north,half=bottom,shape=inner_left]', + 'fill 12 171 4 18 171 6 snow[layers=3]', + 'fill 12 172 8 18 172 8 oak_trapdoor[half=bottom,open=false]', + 'fill 12 173 12 18 173 12 oak_trapdoor[half=top,open=true,facing=north]', + 'setblock 14 171 14 lantern', + 'setblock 15 175 15 soul_lantern[hanging=true]', + 'fill 8 171 16 9 172 17 water', + # Open-air structures: sky light through slabs, stairs and leaves. + 'fill 24 170 24 46 170 46 stone', + 'fill 26 171 26 44 171 26 stone_slab[type=top]', + 'fill 26 171 28 44 171 28 stone_slab[type=bottom]', + 'fill 26 172 30 44 172 30 oak_leaves[persistent=true]', + 'fill 26 171 32 30 171 40 glass', + 'fill 32 171 32 36 171 40 oak_stairs[facing=south,half=bottom]', + 'fill 38 171 32 38 175 40 stone_brick_wall', + 'fill 40 171 32 44 171 40 dirt_path', + 'fill 40 172 34 44 172 34 daylight_detector', + 'fill 24 180 50 46 180 50 stone_slab[type=double]', + 'fill 24 178 52 46 178 52 oak_stairs[facing=west,half=top]', + 'setblock 30 171 44 torch', + 'setblock 34 171 44 campfire', + 'setblock 38 171 44 sea_lantern', + 'setblock 42 171 44 lava', + 'sleep 10', + # Edits after the first lighting pass, so vanilla updates incrementally. + 'setblock 10 171 10 air', + 'setblock 10 176 10 air', + 'setblock 30 171 26 air', + 'fill 26 172 30 30 172 30 air', + # Vanilla saves a chunk only when its blocks changed, so light that + # reached an untouched chunk later is stale on disk: mark every compared + # chunk (0..2, 0..3) as edited so it is written at shutdown. + *[f'setblock {x * 16 + 8} 169 {z * 16 + 8} stone' for x in range(3) for z in range(4)], + 'sleep 8', +] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--seed', default='4242') + parser.add_argument('--keep', action='store_true') + args = parser.parse_args() + run = LOCAL / 'rust-light-parity' + shutil.rmtree(run, ignore_errors=True) + run.mkdir(parents=True) + command = [sys.executable, str(ROOT / 'tools' / 'vanilla_world_check.py'), '--jar', str(SERVER), + '--dir', str(run), '--world', 'world', '--seed', args.seed, '--wait-after', '8'] + for step in SCENE: + command += ['--command', step] + if subprocess.run(command).returncode: + sys.exit('vanilla server reported problems') + dimension = run / 'world' / 'dimensions' / 'minecraft' / 'overworld' + if not (dimension / 'region').is_dir(): + dimension = run / 'world' + for extra in (['--chunks', '0', '0', '2', '3'], ['--incremental', '100']): + status = subprocess.run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', + '--example', 'light_parity', '--', str(RESOURCES), str(dimension), *extra], + cwd=ROOT).returncode + if status: + sys.exit('light mismatch against vanilla') + print('light parity ok') + if not args.keep: + shutil.rmtree(run, ignore_errors=True) + + +if __name__ == '__main__': + main() From 19336564d2bd782186b62674d55c04d343835cf0 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:40:31 +0200 Subject: [PATCH 02/13] Add the loom and banner patterns The loom now opens its menu: a banner, a dye and an optional pattern item go in, the 32 plain patterns (or the one the pattern item provides) show in a scrolling 4x4 grid with hover names, picking one previews the result banner and the result slot gives a banner with one more layer, using up one banner and one dye. Banners with six layers show the error state and give nothing. Shift-click routes banners, dyes and pattern items to the right slots. Banner layers are stored in the banner_patterns item component, in a new banner block entity (saved to chunks), and carry over when a banner is placed or dropped. Placed banners draw all their pattern layers, banner and shield icons are drawn as the vanilla 3D models with their patterns, a held banner is shown in the first-person hand, and tooltips list the layers. Banner duplication and shield decoration crafting recipes work, and crafting now returns item remainders such as buckets. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/banner.rs | 313 +++++++++++++ .../horizon-client/src/block_entity_render.rs | 17 +- crates/horizon-client/src/containers.rs | 24 +- crates/horizon-client/src/crafting.rs | 197 +++++++++ crates/horizon-client/src/game.rs | 54 ++- crates/horizon-client/src/game/banners.rs | 222 ++++++++++ crates/horizon-client/src/game/loom.rs | 415 ++++++++++++++++++ crates/horizon-client/src/game/minecarts.rs | 1 + crates/horizon-client/src/game/shield.rs | 76 +++- crates/horizon-client/src/game/stations.rs | 50 ++- crates/horizon-client/src/game/storage.rs | 4 + crates/horizon-client/src/item_data.rs | 33 ++ crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/save.rs | 41 +- crates/horizon-client/src/stations.rs | 2 + 15 files changed, 1411 insertions(+), 39 deletions(-) create mode 100644 crates/horizon-client/src/banner.rs create mode 100644 crates/horizon-client/src/game/banners.rs create mode 100644 crates/horizon-client/src/game/loom.rs diff --git a/crates/horizon-client/src/banner.rs b/crates/horizon-client/src/banner.rs new file mode 100644 index 000000000..d2bc33fba --- /dev/null +++ b/crates/horizon-client/src/banner.rs @@ -0,0 +1,313 @@ +//! Banner patterns: the `banner_pattern` registry and its tags, the +//! `banner_patterns` layers carried by banner items, shields and placed +//! banners, and the loom rules of `LoomMenu` (selectable patterns, the +//! six-layer limit and the result stack). +use crate::{block_entity_render::DYES, item_data, items::ItemStack, items::Items}; +use horizon_world::nbt::Tag; +use serde_json::Value; +use std::{collections::HashMap, fs, path::Path, sync::Arc}; + +/// `BannerPatternLayers.Layer`: a pattern id and the dye name it is painted in. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BannerLayer { + pub pattern: Arc, + pub color: Arc, +} +impl BannerLayer { + pub fn new(pattern: &str, color: &str) -> Self { + Self { + pattern: Arc::from(pattern), + color: Arc::from(color), + } + } +} + +/// Layers a loom may stack on a banner (`LoomMenu`'s `hasMaxPatterns`). +pub const MAX_LAYERS: usize = 6; + +/// One `banner_pattern` registry entry. +#[derive(Clone, Debug)] +pub struct Pattern { + pub id: Arc, + /// `asset_id` path, the texture under `entity/banner` and `entity/shield`. + pub asset: String, + pub translation_key: String, +} + +/// The pattern registry, its tags and the item components the loom reads. +#[derive(Default)] +pub struct Banners { + patterns: Vec, + /// `#minecraft:no_item_required`, in tag order. + no_item_required: Vec>, + /// Item -> `dye` component. + dyes: HashMap, Arc>, + /// Item -> `provides_banner_patterns`, in tag order. + provided: HashMap, Vec>>, +} + +fn read_tag(root: &Path, name: &str, depth: u32) -> Vec> { + if depth > 8 { + return Vec::new(); + } + let path = root.join(format!( + "data/minecraft/tags/banner_pattern/{}.json", + name.trim_start_matches("minecraft:") + )); + let Some(v) = fs::read(path) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + else { + return Vec::new(); + }; + let mut out = Vec::new(); + for value in v["values"].as_array().into_iter().flatten() { + let Some(s) = value.as_str().or_else(|| value["id"].as_str()) else { + continue; + }; + match s.strip_prefix('#') { + Some(tag) => out.extend(read_tag(root, tag, depth + 1)), + None => out.push(Arc::from(s)), + } + } + out +} + +impl Banners { + pub fn load(root: &Path) -> Self { + let mut banners = Self::default(); + let mut files: Vec<_> = fs::read_dir(root.join("data/minecraft/banner_pattern")) + .into_iter() + .flatten() + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|e| e == "json")) + .collect(); + files.sort(); + for path in files { + let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else { + continue; + }; + let Some(v) = fs::read(&path) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + else { + continue; + }; + let asset = v["asset_id"] + .as_str() + .unwrap_or(stem) + .trim_start_matches("minecraft:") + .to_owned(); + banners.patterns.push(Pattern { + id: Arc::from(format!("minecraft:{stem}").as_str()), + asset, + translation_key: v["translation_key"].as_str().unwrap_or_default().to_owned(), + }); + } + banners.no_item_required = read_tag(root, "no_item_required", 0); + if let Some(raw) = fs::read(root.join("items.json")).ok().and_then(|b| { + serde_json::from_slice::>(&b).ok() + }) { + for (item, c) in raw { + let id: Arc = Arc::from(item.as_str()); + if let Some(dye) = c["minecraft:dye"].as_str() { + banners.dyes.insert(id.clone(), Arc::from(dye)); + } + match &c["minecraft:provides_banner_patterns"] { + Value::String(tag) if tag.starts_with('#') => { + banners.provided.insert(id, read_tag(root, &tag[1..], 0)); + } + Value::String(single) => { + banners + .provided + .insert(id, vec![Arc::from(single.as_str())]); + } + _ => {} + } + } + } + banners + } + pub fn pattern(&self, id: &str) -> Option<&Pattern> { + self.patterns.iter().find(|p| &*p.id == id) + } + /// `Sheets.getBannerSprite` texture name of a pattern. + pub fn banner_texture(&self, id: &str) -> String { + match self.pattern(id) { + Some(p) => format!("entity/banner/{}", p.asset), + None => format!("entity/banner/{}", id.trim_start_matches("minecraft:")), + } + } + /// `Sheets.getShieldSprite` texture name of a pattern. + pub fn shield_texture(&self, id: &str) -> String { + match self.pattern(id) { + Some(p) => format!("entity/shield/{}", p.asset), + None => format!("entity/shield/{}", id.trim_start_matches("minecraft:")), + } + } + /// `BannerPatternLayers.Layer.description` translation key. + pub fn layer_key(&self, layer: &BannerLayer) -> String { + let base = self.pattern(&layer.pattern).map_or_else( + || { + format!( + "block.minecraft.banner.{}", + layer.pattern.trim_start_matches("minecraft:") + ) + }, + |p| p.translation_key.clone(), + ); + format!("{base}.{}", layer.color) + } + /// `LoomMenu.isDyeItem`: the dye colour of a loom dye. + pub fn loom_dye(&self, items: &Items, stack: &ItemStack) -> Option> { + let tagged = items + .item_tags + .get("minecraft:loom_dyes") + .is_some_and(|t| t.contains(&*stack.item)); + tagged + .then(|| self.dyes.get(&stack.item).cloned()) + .flatten() + } + /// `LoomMenu.isPatternItem`. + pub fn is_pattern_item(&self, items: &Items, stack: &ItemStack) -> bool { + items + .item_tags + .get("minecraft:loom_patterns") + .is_some_and(|t| t.contains(&*stack.item)) + && self.provided.contains_key(&stack.item) + } + /// `LoomMenu.getSelectablePatterns`. + pub fn selectable(&self, pattern_item: Option<&ItemStack>) -> Vec> { + match pattern_item { + None => self.no_item_required.clone(), + Some(stack) => self.provided.get(&stack.item).cloned().unwrap_or_default(), + } + } +} + +/// `BannerItem`: a banner's dye colour from its item id. +pub fn banner_color(item: &str) -> Option<&'static str> { + let name = item.strip_prefix("minecraft:")?.strip_suffix("_banner")?; + DYES.iter().map(|d| d.0).find(|d| *d == name) +} +/// `DyeColor.getTextureDiffuseColor` (RGB) by dye name. +pub fn dye_rgb(name: &str) -> u32 { + DYES.iter().find(|d| d.0 == name).map_or(0xFFFFFF, |d| d.1) +} +/// The layers of a banner or shield stack. +pub fn layers(stack: &ItemStack) -> &[BannerLayer] { + stack.data().map_or(&[], |d| &d.banner_patterns) +} +/// `LoomMenu.setupResultSlot`: one banner with the pattern added in the dye colour. +pub fn loom_result(banner: &ItemStack, dye: &str, pattern: &str) -> ItemStack { + let mut result = ItemStack { + count: 1, + ..banner.clone() + }; + result + .data_mut() + .banner_patterns + .push(BannerLayer::new(pattern, dye)); + result +} +/// Whether the banner already carries the loom's limit. +pub fn has_max_layers(banner: &ItemStack) -> bool { + layers(banner).len() >= MAX_LAYERS +} + +/// The `banner_patterns` NBT list of layers. +pub fn layers_to_nbt(layers: &[BannerLayer]) -> Tag { + Tag::List( + layers + .iter() + .map(|l| { + Tag::compound([ + ("pattern", Tag::String((&*l.pattern).into())), + ("color", Tag::String((&*l.color).into())), + ]) + }) + .collect(), + ) +} +pub fn layers_from_nbt(tag: Option<&Tag>) -> Vec { + let Some(Tag::List(list)) = tag else { + return Vec::new(); + }; + list.iter() + .filter_map(|e| { + let text = |k: &str| match e.get(k) { + Some(Tag::String(s)) => Some(s.to_string_lossy()), + _ => None, + }; + let pattern = text("pattern")?; + let color = text("color")?; + Some(BannerLayer::new( + &if pattern.contains(':') { + pattern + } else { + format!("minecraft:{pattern}") + }, + &color, + )) + }) + .collect() +} +/// Keeps `item_data` linked: the `StackData` fields the banner code reads. +pub fn set_layers(stack: &mut ItemStack, layers: Vec) { + let data: &mut item_data::StackData = stack.data_mut(); + data.banner_patterns = layers; + stack.tidy(); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn banners() -> Banners { + let mut b = Banners { + no_item_required: vec![Arc::from("minecraft:stripe_top")], + ..Default::default() + }; + b.provided.insert( + Arc::from("minecraft:flower_banner_pattern"), + vec![Arc::from("minecraft:flower")], + ); + b + } + #[test] + fn selectable_follow_the_pattern_item() { + let b = banners(); + assert_eq!(b.selectable(None).len(), 1); + let item = ItemStack::new("minecraft:flower_banner_pattern", 1); + assert_eq!(&*b.selectable(Some(&item))[0], "minecraft:flower"); + } + #[test] + fn banner_colour_comes_from_the_item() { + assert_eq!( + banner_color("minecraft:light_gray_banner"), + Some("light_gray") + ); + assert_eq!(banner_color("minecraft:white_banner"), Some("white")); + assert_eq!(banner_color("minecraft:white_wool"), None); + } + #[test] + fn loom_adds_a_layer_up_to_the_limit() { + let mut banner = ItemStack::new("minecraft:white_banner", 3); + for i in 0..MAX_LAYERS { + assert!(!has_max_layers(&banner)); + banner = loom_result(&banner, "red", "minecraft:cross"); + assert_eq!(banner.count, 1); + assert_eq!(layers(&banner).len(), i + 1); + } + assert!(has_max_layers(&banner)); + } + #[test] + fn layers_round_trip_through_nbt() { + let l = vec![ + BannerLayer::new("minecraft:flower", "red"), + BannerLayer::new("minecraft:border", "black"), + ]; + assert_eq!(layers_from_nbt(Some(&layers_to_nbt(&l))), l); + } +} diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 5869f6de0..8114542b0 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -700,6 +700,8 @@ pub struct Scene<'a> { pub lid: &'a dyn Fn([i32; 3]) -> f32, /// Sign block-entity data at a position. pub sign: &'a dyn Fn([i32; 3]) -> Option<&'a crate::signs::SignData>, + /// Banner layers at a position: pattern texture and RGB tint, bottom first. + pub banner: &'a dyn Fn([i32; 3]) -> Vec<(String, u32)>, /// Font glyph cell and advance. pub glyph: &'a dyn Fn(char) -> Option<(Rect, f32)>, } @@ -773,6 +775,13 @@ impl BlockEntityRenderer { random: LegacyRandom::new(0x5EED_B00C), } } + /// The standing banner's pole-and-bar and flag models (`BannerRenderer.submitSpecial`). + pub fn banner_models(&self) -> Option<(&ModelPart, &ModelPart)> { + Some(( + self.models.get("standing_banner")?, + self.models.get("standing_banner_flag")?, + )) + } fn kind(&self, state: u32) -> &Kind { self.kinds.get(state as usize).unwrap_or(&Kind::None) } @@ -993,10 +1002,16 @@ impl BlockEntityRenderer { draw_part(main, "root", m, &none, paint, out); draw_part(flag, "root", m, &wave, paint, out); } - // BannerRenderer.submitPatterns: the base pattern layer in the dye colour. + // BannerRenderer.submitPatterns: the base pattern layer in the dye colour, + // then up to 16 pattern layers in order. if let Some(paint) = paint("entity/banner/base", *color, packed) { draw_part(flag, "root", m, &wave, paint, out); } + for (texture, tint) in (scene.banner)(pos).iter().take(16) { + if let Some(paint) = paint(texture, *tint, packed) { + draw_part(flag, "root", m, &wave, paint, out); + } + } } Kind::Skull { kind, diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 6d999c9a8..431eac25f 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -58,6 +58,13 @@ pub enum BlockEntity { Beacon(Box), /// `LecternBlockEntity`: the book and the open page. Lectern(Lectern), + /// `BannerBlockEntity`: the pattern layers. + Banner(Banner), +} +#[derive(Clone, Debug, Default)] +pub struct Banner { + pub layers: Vec, + pub name: Option, } #[derive(Clone, Debug, Default)] pub struct Lectern { @@ -104,6 +111,9 @@ impl BlockEntity { if name == "minecraft:lectern" { return Some(Self::Lectern(Lectern::default())); } + if name.ends_with("_banner") { + return Some(Self::Banner(Banner::default())); + } if name == "minecraft:beacon" { return Some(Self::Beacon(Box::new(Beacon { last_check_y: i32::MIN / 2, @@ -155,6 +165,7 @@ impl BlockEntity { Self::Jukebox(_) => "minecraft:jukebox", Self::Beacon(_) => "minecraft:beacon", Self::Lectern(_) => "minecraft:lectern", + Self::Banner(_) => "minecraft:banner", } } pub fn contents(&self) -> Vec { @@ -166,6 +177,7 @@ impl BlockEntity { Self::Jukebox(j) => j.record.iter().cloned().collect(), Self::Beacon(_) => Vec::new(), Self::Lectern(l) => l.book.iter().cloned().collect(), + Self::Banner(_) => Vec::new(), } } pub fn slots(&self) -> &[Option] { @@ -173,7 +185,11 @@ impl BlockEntity { Self::Chest(items) => items, Self::Furnace(f) => &f.items, Self::Brewing(b) => &b.items, - Self::Sign(_) | Self::Jukebox(_) | Self::Beacon(_) | Self::Lectern(_) => &[], + Self::Sign(_) + | Self::Jukebox(_) + | Self::Beacon(_) + | Self::Lectern(_) + | Self::Banner(_) => &[], } } pub fn slots_mut(&mut self) -> &mut [Option] { @@ -181,7 +197,11 @@ impl BlockEntity { Self::Chest(items) => items, Self::Furnace(f) => &mut f.items, Self::Brewing(b) => &mut b.items, - Self::Sign(_) | Self::Jukebox(_) | Self::Beacon(_) | Self::Lectern(_) => &mut [], + Self::Sign(_) + | Self::Jukebox(_) + | Self::Beacon(_) + | Self::Lectern(_) + | Self::Banner(_) => &mut [], } } } diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index ecf8f9bd6..7994d0bd7 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -53,6 +53,96 @@ pub enum Recipe { ingredients: Vec, result: ItemStack, }, + /// `BannerDuplicateRecipe` and `ShieldDecorationRecipe`. + Special(Special), +} +/// The banner-copying custom recipes. +#[derive(Clone, Debug)] +pub enum Special { + /// A patterned banner and a blank one of the same colour copy the patterns. + BannerDuplicate { banner: Ingredient, result: String }, + /// A banner decorates an undecorated shield. + ShieldDecoration { + banner: Ingredient, + target: Ingredient, + result: String, + }, +} +impl Special { + /// `matches` + `assemble` over the non-empty stacks of the grid. + fn assemble(&self, stacks: &[&ItemStack]) -> Option { + use crate::banner; + if stacks.len() != 2 { + return None; + } + match self { + Self::BannerDuplicate { + banner: ing, + result, + } => { + let color = banner::banner_color(&stacks[0].item)?; + let mut source = None; + let mut target = false; + for s in stacks { + if !ing.test(s) || banner::banner_color(&s.item)? != color { + return None; + } + let layers = banner::layers(s).len(); + if layers > banner::MAX_LAYERS { + return None; + } + if layers > 0 { + if source.is_some() { + return None; + } + source = Some(*s); + } else { + if target { + return None; + } + target = true; + } + } + let source = source.filter(|_| target)?; + // TransmuteRecipe.createWithOriginalComponents: the source's components. + Some(ItemStack { + item: Arc::from(result.as_str()), + count: 1, + ..(*source).clone() + }) + } + Self::ShieldDecoration { + banner: ing, + target: tgt, + result, + } => { + let (mut patterned, mut clear) = (None, None); + for s in stacks { + if ing.test(s) && banner::banner_color(&s.item).is_some() { + if patterned.is_some() { + return None; + } + patterned = Some(*s); + } else { + if !tgt.test(s) || clear.is_some() || !banner::layers(s).is_empty() { + return None; + } + clear = Some(*s); + } + } + let (banner_stack, shield) = (patterned?, clear?); + let mut out = ItemStack { + item: Arc::from(result.as_str()), + count: 1, + ..shield.clone() + }; + let data = out.data_mut(); + data.banner_patterns = banner::layers(banner_stack).to_vec(); + data.base_color = banner::banner_color(&banner_stack.item).map(Arc::from); + Some(out) + } + } + } } #[derive(Clone, Debug)] pub struct Cooking { @@ -145,6 +235,36 @@ impl Recipes { )); } } + "minecraft:crafting_special_bannerduplicate" => { + if let (Some(banner), Some(id)) = ( + Ingredient::parse(&v["banner"], items), + v["result"]["id"].as_str(), + ) { + crafting.push(( + name, + Recipe::Special(Special::BannerDuplicate { + banner, + result: id.to_owned(), + }), + )); + } + } + "minecraft:crafting_special_shielddecoration" => { + if let (Some(banner), Some(target), Some(id)) = ( + Ingredient::parse(&v["banner"], items), + Ingredient::parse(&v["target"], items), + v["result"]["id"].as_str(), + ) { + crafting.push(( + name, + Recipe::Special(Special::ShieldDecoration { + banner, + target, + result: id.to_owned(), + }), + )); + } + } kind @ ("minecraft:smelting" | "minecraft:blasting" | "minecraft:smoking" @@ -189,6 +309,12 @@ impl Recipes { let cell = |x: usize, y: usize| grid[(y0 + y) * size + x0 + x].as_ref(); for (_, recipe) in &self.crafting { match recipe { + Recipe::Special(special) => { + let stacks: Vec<&ItemStack> = grid.iter().flatten().collect(); + if let Some(result) = special.assemble(&stacks) { + return Some(result); + } + } Recipe::Shaped { width, height, @@ -242,9 +368,80 @@ impl Recipes { } None } + /// `Recipe.getRemainingItems` per grid cell: an item's crafting remainder + /// (buckets, bottles), and the patterned banner a duplicate keeps. + pub fn remainders( + &self, + items: &Items, + grid: &[Option], + result: &ItemStack, + ) -> Vec> { + grid.iter() + .map(|cell| { + let s = cell.as_ref()?; + if let Some(rem) = items.get(&s.item).and_then(|i| i.remainder.as_deref()) { + return Some(ItemStack::new(rem, 1)); + } + (result.item.ends_with("_banner") && !crate::banner::layers(s).is_empty()).then( + || ItemStack { + count: 1, + ..s.clone() + }, + ) + }) + .collect() + } pub fn cook(&self, kind: &str, input: &ItemStack) -> Option<&Cooking> { self.cooking .iter() .find(|c| c.kind == kind && c.ingredient.test(input)) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::banner::BannerLayer; + + fn ingredient(items: &[&str]) -> Ingredient { + Ingredient(items.iter().map(|s| (*s).to_owned()).collect()) + } + fn patterned(item: &str) -> ItemStack { + let mut s = ItemStack::new(item, 1); + s.data_mut().banner_patterns = vec![BannerLayer::new("minecraft:cross", "red")]; + s + } + #[test] + fn banner_duplicate_copies_the_patterns_of_the_same_colour() { + let recipe = Special::BannerDuplicate { + banner: ingredient(&["minecraft:white_banner"]), + result: "minecraft:white_banner".into(), + }; + let source = patterned("minecraft:white_banner"); + let blank = ItemStack::new("minecraft:white_banner", 1); + let out = recipe.assemble(&[&source, &blank]).expect("copy"); + assert_eq!(out.data().unwrap().banner_patterns.len(), 1); + // Two blanks, or two patterned banners, do not match. + assert!(recipe.assemble(&[&blank, &blank]).is_none()); + assert!(recipe.assemble(&[&source, &source]).is_none()); + // Another colour is not in the recipe's ingredient. + let other = ItemStack::new("minecraft:red_banner", 1); + assert!(recipe.assemble(&[&source, &other]).is_none()); + } + #[test] + fn shield_decoration_needs_a_bare_shield() { + let recipe = Special::ShieldDecoration { + banner: ingredient(&["minecraft:red_banner"]), + target: ingredient(&["minecraft:shield"]), + result: "minecraft:shield".into(), + }; + let banner = patterned("minecraft:red_banner"); + let shield = ItemStack::new("minecraft:shield", 1); + let out = recipe.assemble(&[&banner, &shield]).expect("decorated"); + let data = out.data().unwrap(); + assert_eq!(data.base_color.as_deref(), Some("red")); + assert_eq!(data.banner_patterns.len(), 1); + // A shield that already has patterns cannot be decorated again. + assert!(recipe.assemble(&[&banner, &out]).is_none()); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 66925932c..d5e5a8de4 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4,6 +4,7 @@ mod advancements; mod advancements_screen; mod allays; mod armor_stands; +mod banners; mod beacon; mod blockctl; mod boats; @@ -28,6 +29,7 @@ mod game_mode; mod growth; mod jukebox; mod lightning; +mod loom; mod machines; mod maps; mod minecarts; @@ -607,6 +609,8 @@ struct Game<'a> { ender_open: Option<(i32, i32, i32)>, /// Contents of broken shulker boxes waiting for their dropped item. pending_shulker: HashMap<[i32; 3], Vec<(u8, ItemStack)>>, + /// Layers of broken banners waiting for their dropped item. + pending_banner: HashMap<[i32; 3], horizon_client::containers::Banner>, /// The player's fishing hook. hook: Option, tridents: Vec, @@ -977,6 +981,7 @@ impl Game<'_> { /// Block.popResource fn pop_resource(&mut self, pos: [i32; 3], mut stack: ItemStack) { self.attach_shulker_contents(pos, &mut stack); + self.attach_banner_layers(pos, &mut stack); let r = &mut self.world.random; let mut offset = || f64::from(r.next_float()) * 0.5 - 0.25; let p = [ @@ -1808,6 +1813,7 @@ impl Game<'_> { .block_entities .insert((target[0], target[1], target[2]), entity); self.fill_placed_box(target, &stack); + self.fill_placed_banner(target, &stack); if sign { self.open_sign_editor((target[0], target[1], target[2]), true); } @@ -2653,13 +2659,18 @@ impl Game<'_> { .map(|t| Icon::Flat(t.trim_start_matches("minecraft:").to_owned())) } fn draw_item(&mut self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) { - if &*stack.item == "minecraft:shield" { - shield::draw_shield_icon(batch, &self.res.atlas, x, y); - return; - } - let icon = self.icon(&stack.item); + // Special-model items: the shield and banners draw their own 3D icon. + let banner = if &*stack.item == "minecraft:shield" { + let passes = shield::shield_passes(&self.res.stations.banners, stack); + shield::draw_shield_icon(batch, &self.res.atlas, x, y, &passes); + true + } else { + self.draw_banner_icon(batch, stack, x, y) + }; + let icon = if banner { None } else { self.icon(&stack.item) }; let atlas = &self.res.atlas; match icon { + None if banner => {} Some(Icon::Flat(name)) => batch.sprite_scaled(atlas, &name, x, y, 16.0, 16.0, u32::MAX), Some(Icon::Cube { top, @@ -3040,7 +3051,8 @@ impl Game<'_> { BlockEntity::Sign(_) | BlockEntity::Jukebox(_) | BlockEntity::Beacon(_) - | BlockEntity::Lectern(_), + | BlockEntity::Lectern(_) + | BlockEntity::Banner(_), ) => {} None => { v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i)); @@ -3265,7 +3277,8 @@ impl Game<'_> { BlockEntity::Sign(_) | BlockEntity::Jukebox(_) | BlockEntity::Beacon(_) - | BlockEntity::Lectern(_), + | BlockEntity::Lectern(_) + | BlockEntity::Banner(_), ) => {} None => { let texture = if self.craft_size == 3 { @@ -3453,6 +3466,12 @@ impl Game<'_> { let mut crafted = 0; while let Some(result) = self.craft_result() { let made = (result.item.clone(), result.count); + let cells = self.craft_size * self.craft_size; + let remainders = self.res.recipes.remainders( + &self.res.items, + &self.craft_grid[..cells], + &result, + ); if shift { if self.give(result).is_some() { break; @@ -3477,6 +3496,14 @@ impl Game<'_> { } } } + for (i, rest) in remainders.into_iter().enumerate() { + let Some(rest) = rest else { continue }; + match &mut self.craft_grid[i] { + cell @ None => *cell = Some(rest), + Some(c) if c.same_item_same_components(&rest) => c.count += rest.count, + _ => self.give_or_drop(rest), + } + } crafted += 1; self.stats.add("crafted", &made.0, made.1 as i32); if !shift || crafted >= 64 { @@ -3867,6 +3894,7 @@ impl Game<'_> { Some(BlockEntity::Sign(sign)) => Some(sign), _ => None, }, + banner: &|p| self.banner_layers_at(p), glyph: &|c| self.res.atlas.glyph(c), }; self.res @@ -5760,6 +5788,10 @@ impl Game<'_> { } first(&d["model"]) }); + if item.ends_with("_banner") { + // The banner item model is a special renderer over this base model. + current = Some("minecraft:item/template_banner".to_owned()); + } for _ in 0..16 { let Some(m) = current.take() else { break }; let path = m.trim_start_matches("minecraft:").to_owned(); @@ -5906,6 +5938,9 @@ impl Game<'_> { * glam::Mat4::from_quat(glam::Quat::from_euler(glam::EulerRot::XYZ, deg(rot[0]), deg(rot[1]), deg(rot[2]))) * glam::Mat4::from_scale(glam::Vec3::from(scale)) * glam::Mat4::from_translation(glam::Vec3::splat(-0.5)); + if self.held_banner_geometry(m, &stack, packed, &mut out) { + return out; + } let atlas = &self.res.atlas; let quad = |corners: [glam::Vec3; 4], name: &str, @@ -7033,6 +7068,9 @@ impl ApplicationHandler for Game<'_> { if self.screen == Screen::Advancements { self.advancements_drag(); } + if self.screen == Screen::Inventory { + self.loom_drag(); + } if self.dragging && self.screen == Screen::Options { let _ = b; self.options_drag()?; @@ -7164,6 +7202,7 @@ impl ApplicationHandler for Game<'_> { self.container_changed(key); } } + Screen::Inventory => self.loom_release(), Screen::Chat if pressed && button == MouseButton::Left => self.chat_click(), Screen::Creative if pressed => { self.click_creative(button == MouseButton::Right); @@ -7665,6 +7704,7 @@ pub fn run() -> Result<()> { ender_items: vec![None; 27], ender_open: None, pending_shulker: HashMap::new(), + pending_banner: HashMap::new(), hook: None, tridents: Vec::new(), rockets: Vec::new(), diff --git a/crates/horizon-client/src/game/banners.rs b/crates/horizon-client/src/game/banners.rs new file mode 100644 index 000000000..b9f701a0c --- /dev/null +++ b/crates/horizon-client/src/game/banners.rs @@ -0,0 +1,222 @@ +//! Placed banners (`BannerBlockEntity`): the pattern layers move from the +//! banner item to the block when placed and back to the dropped item when +//! broken (`copy_components` in the banner loot tables). +use super::Game; +use glam::{EulerRot, Mat4, Quat, Vec3}; +use horizon_client::{ + banner::{self, BannerLayer}, + block_entity_render::{Paint, draw_part}, + containers::{Banner, BlockEntity}, + hud::{HudBatch, rgba}, + items::ItemStack, + mesher::Vertex, +}; + +impl Game<'_> { + /// The pattern textures and tints of the banner at `pos`, bottom first. + pub(super) fn banner_layers_at(&self, pos: [i32; 3]) -> Vec<(String, u32)> { + let Some(BlockEntity::Banner(b)) = self.world.block_entities.get(&(pos[0], pos[1], pos[2])) + else { + return Vec::new(); + }; + layer_textures(&self.res.stations.banners, &b.layers) + } + /// A placed banner takes the item's layers and name. + pub(super) fn fill_placed_banner(&mut self, pos: [i32; 3], stack: &ItemStack) { + self.pending_banner.remove(&pos); + if !stack.item.ends_with("_banner") { + return; + } + if let Some(BlockEntity::Banner(b)) = + self.world.block_entities.get_mut(&(pos[0], pos[1], pos[2])) + { + b.layers = banner::layers(stack).to_vec(); + b.name = stack.custom_name().map(str::to_owned); + } + } + /// A banner in a slot: `item/template_banner`'s `gui` transform on the + /// banner model (pole, bar and flag with every layer), flat-lit and + /// depth-sorted. False when the stack is not a banner. + pub(super) fn draw_banner_icon( + &self, + batch: &mut HudBatch, + stack: &ItemStack, + x: f32, + y: f32, + ) -> bool { + let Some(base) = banner::banner_color(&stack.item) else { + return false; + }; + let Some((main, flag)) = self.res.block_entity_render.banner_models() else { + return true; + }; + let banners = &self.res.stations.banners; + let sprites = &self.res.atlas.sprites; + // display.gui, then the item's special transformation (a banner is + // modelled upside down and 2/3 size around the block centre). + let m = Mat4::from_translation(Vec3::new(0.0, -3.25 / 16.0, 0.0)) + * Mat4::from_quat(Quat::from_euler( + EulerRot::XYZ, + 30f32.to_radians(), + 20f32.to_radians(), + 0.0, + )) + * Mat4::from_scale(Vec3::splat(0.5325)) + * Mat4::from_translation(Vec3::new(0.0, -0.5, 0.0)) + * Mat4::from_scale(Vec3::new(2.0 / 3.0, -2.0 / 3.0, -2.0 / 3.0)); + let wave = |name: &str, p: &mut [f32; 9]| { + if name == "flag" { + p[3] = (-0.0125 + 0.01) * std::f32::consts::PI; + } + }; + let none = |_: &str, _: &mut [f32; 9]| {}; + let mut passes: Vec<(&str, u32, bool, String)> = vec![ + ("entity/banner/banner_base", 0xFFFFFF, true, String::new()), + ( + "entity/banner/base", + banner::dye_rgb(base), + false, + String::new(), + ), + ]; + for layer in banner::layers(stack).iter().take(16) { + passes.push(( + "", + banner::dye_rgb(&layer.color), + false, + banners.banner_texture(&layer.pattern), + )); + } + // (depth, pass, screen corners, uv, colour) + let mut faces: Vec<(f32, usize, [[f32; 2]; 4], [[f32; 2]; 4], u32)> = Vec::new(); + for (index, (fixed, tint, with_pole, dynamic)) in passes.iter().enumerate() { + let name = if fixed.is_empty() { + dynamic.as_str() + } else { + fixed + }; + let Some(sprite) = sprites.get(name).copied() else { + continue; + }; + let paint = Paint { + sprite, + tint: 0xFFFFFF, + light: 0, + lights: (Vec3::ZERO, Vec3::ZERO), + }; + let mut verts: Vec = Vec::new(); + if *with_pole { + draw_part(main, "root", m, &none, paint, &mut verts); + } + draw_part(flag, "root", m, &wave, paint, &mut verts); + for quad in verts.as_chunks::<4>().0 { + let p = |i: usize| Vec3::from(quad[i].pos); + let normal = (p(1) - p(0)).cross(p(2) - p(0)).normalize_or_zero(); + // Faces turned away from the viewer are culled. + if normal.z <= 0.0 { + continue; + } + let depth = (0..4).map(|i| p(i).z).sum::() / 4.0; + let shade = (0.6 + 0.4 * normal.z).min(1.0); + let c = |s: u32| (((tint >> s) & 255) as f32 * shade) as u8; + faces.push(( + depth, + index, + std::array::from_fn(|i| { + [ + x + 8.0 + quad[i].pos[0] * 16.0, + y + 8.0 - quad[i].pos[1] * 16.0, + ] + }), + std::array::from_fn(|i| quad[i].uv), + rgba(c(16), c(8), c(0), 255), + )); + } + } + faces.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1))); + for (_, _, corners, uv, color) in faces { + batch.quad(corners, uv, color); + } + true + } + /// A banner in the first-person hand: the standing banner model under the + /// item's `firstperson_righthand` transform (`m`) and its special + /// transformation. False when the stack is not a banner. + pub(super) fn held_banner_geometry( + &self, + m: Mat4, + stack: &ItemStack, + packed: u32, + out: &mut Vec, + ) -> bool { + let Some(base) = banner::banner_color(&stack.item) else { + return false; + }; + let Some((main, flag)) = self.res.block_entity_render.banner_models() else { + return true; + }; + let m = m + * Mat4::from_translation(Vec3::new(0.5, 0.0, 0.5)) + * Mat4::from_scale(Vec3::new(2.0 / 3.0, -2.0 / 3.0, -2.0 / 3.0)); + let wave = |name: &str, p: &mut [f32; 9]| { + if name == "flag" { + p[3] = (-0.0125 + 0.01) * std::f32::consts::PI; + } + }; + let none = |_: &str, _: &mut [f32; 9]| {}; + let lights = horizon_client::block_entity_render::diffuse_lights(false); + let sprites = &self.res.atlas.sprites; + let paint = |name: &str, tint: u32| { + sprites.get(name).map(|&sprite| Paint { + sprite, + tint, + light: packed, + lights, + }) + }; + if let Some(p) = paint("entity/banner/banner_base", 0xFFFFFF) { + draw_part(main, "root", m, &none, p, out); + draw_part(flag, "root", m, &wave, p, out); + } + if let Some(p) = paint("entity/banner/base", banner::dye_rgb(base)) { + draw_part(flag, "root", m, &wave, p, out); + } + for layer in banner::layers(stack).iter().take(16) { + let texture = self.res.stations.banners.banner_texture(&layer.pattern); + if let Some(p) = paint(&texture, banner::dye_rgb(&layer.color)) { + draw_part(flag, "root", m, &wave, p, out); + } + } + true + } + /// The layers a banner dropped at `pos` carries. + pub(super) fn attach_banner_layers(&mut self, pos: [i32; 3], stack: &mut ItemStack) { + if !stack.item.ends_with("_banner") { + return; + } + if let Some(Banner { layers, name }) = self.pending_banner.remove(&pos) { + let data = stack.data_mut(); + data.banner_patterns = layers; + if name.is_some() { + data.custom_name = name; + } + stack.tidy(); + } + } +} + +/// Texture names and tints of banner layers (`Sheets.getBannerSprite`). +pub(super) fn layer_textures( + banners: &banner::Banners, + layers: &[BannerLayer], +) -> Vec<(String, u32)> { + layers + .iter() + .map(|l| { + ( + banners.banner_texture(&l.pattern), + banner::dye_rgb(&l.color), + ) + }) + .collect() +} diff --git a/crates/horizon-client/src/game/loom.rs b/crates/horizon-client/src/game/loom.rs new file mode 100644 index 000000000..39663c298 --- /dev/null +++ b/crates/horizon-client/src/game/loom.rs @@ -0,0 +1,415 @@ +//! The loom (`LoomMenu`, `LoomScreen`): stacking banner patterns onto a +//! banner with a dye (and a pattern item for the special patterns), the +//! six-layer limit, the scrolling pattern list and the banner preview. +use super::{ + Game, + stations::{INPUT, Station}, +}; +use horizon_client::{ + banner::{self, BannerLayer}, + hud::{HudBatch, Rect, rgba}, + items::ItemStack, +}; +use std::sync::Arc; + +/// Per-menu loom state: `selectablePatterns`, the selected index and the +/// screen's scroller. +#[derive(Default)] +pub(super) struct LoomState { + pub(super) patterns: Vec>, + pub(super) selected: Option, + /// `displayPatterns`: the pattern buttons are shown. + pub(super) display: bool, + pub(super) has_max: bool, + pub(super) scroll: f32, + pub(super) start_row: usize, + pub(super) scrolling: bool, +} +impl LoomState { + fn total_rows(&self) -> usize { + self.patterns.len().div_ceil(4) + } + fn offscreen_rows(&self) -> i32 { + self.total_rows() as i32 - 4 + } + fn scroll_active(&self) -> bool { + self.display && self.patterns.len() > 16 + } + /// `startRow` for a scroller position. + fn row_for(&self, offs: f32) -> usize { + ((offs * self.offscreen_rows() as f32 + 0.5) as i32).max(0) as usize + } +} + +const BUTTON: f32 = 14.0; + +fn inside(p: (f32, f32), x: f32, y: f32, w: f32, h: f32) -> bool { + p.0 >= x && p.1 >= y && p.0 < x + w && p.1 < y + h +} +/// A sub-rectangle of a sprite given in texels. +fn sub_rect(r: Rect, [x, y, w, h]: [f32; 4]) -> Rect { + let (du, dv) = ((r.u1 - r.u0) / r.w as f32, (r.v1 - r.v0) / r.h as f32); + Rect { + u0: r.u0 + x * du, + v0: r.v0 + y * dv, + u1: r.u0 + (x + w) * du, + v1: r.v0 + (y + h) * dv, + w: w as u32, + h: h as u32, + } +} +/// A dye's tint as a HUD vertex colour. +pub(super) fn dye_color(name: &str) -> u32 { + let c = banner::dye_rgb(name); + rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, 255) +} + +impl Game<'_> { + /// `LoomMenu.slotsChanged` and the screen's `containerChanged`. + pub(super) fn loom_changed(&self, s: &mut Station) { + let banners = &self.res.stations.banners; + let items = &self.res.items; + let (banner_in, dye_in) = (s.inputs[0].as_ref(), s.inputs[1].as_ref()); + let l = &mut s.loom; + let mut result = None; + if let (Some(banner_stack), Some(dye_stack)) = (banner_in, dye_in) { + let valid = l.selected.is_some_and(|i| i < l.patterns.len()); + let previous = std::mem::take(&mut l.patterns); + l.patterns = banners.selectable(s.inputs[2].as_ref()); + let shown = if l.patterns.len() == 1 { + l.selected = Some(0); + Some(l.patterns[0].clone()) + } else if !valid { + l.selected = None; + None + } else { + let value = previous[l.selected.unwrap_or(0)].clone(); + match l.patterns.iter().position(|p| *p == value) { + Some(i) => { + l.selected = Some(i); + Some(value) + } + None => { + l.selected = None; + None + } + } + }; + l.has_max = banner::has_max_layers(banner_stack); + if let Some(pattern) = shown { + if l.has_max { + l.selected = None; + } else if let Some(dye) = banners.loom_dye(items, dye_stack) { + result = Some(banner::loom_result(banner_stack, &dye, &pattern)); + } + } + l.display = !l.has_max && !l.patterns.is_empty(); + } else { + l.patterns.clear(); + l.selected = None; + l.has_max = banner_in.is_some_and(banner::has_max_layers); + l.display = false; + } + if l.start_row >= l.total_rows() { + l.start_row = 0; + l.scroll = 0.0; + } + s.result = result; + } + /// The loom slots' `mayPlace`. + pub(super) fn loom_slot_rules(&self, input: usize, stack: &ItemStack) -> (bool, u32) { + let banners = &self.res.stations.banners; + let ok = match input { + 0 => stack.item.ends_with("_banner"), + 1 => banners.loom_dye(&self.res.items, stack).is_some(), + _ => banners.is_pattern_item(&self.res.items, stack), + }; + (ok, 64) + } + /// The result slot's `onTake`: one banner and one dye are used up. + pub(super) fn loom_taken(&mut self, s: &mut Station) { + for slot in &mut s.inputs[..2] { + if let Some(x) = slot.as_mut() { + x.count -= 1; + if x.count == 0 { + *slot = None; + } + } + } + if s.inputs[0].is_none() || s.inputs[1].is_none() { + s.loom.selected = None; + } + if s.last_sound != self.ticks { + s.last_sound = self.ticks; + let pos = s.pos; + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + self.audio + .play("minecraft:ui.loom.take_result", Some(at), 1.0, 1.0); + } + } + /// `LoomMenu.quickMoveStack` from an inventory slot. + pub(super) fn loom_quick_move(&mut self, slot: usize, stack: &mut ItemStack) -> bool { + let banners = &self.res.stations.banners; + let items = &self.res.items; + let target = if stack.item.ends_with("_banner") { + Some(INPUT) + } else if banners.loom_dye(items, stack).is_some() { + Some(INPUT + 1) + } else if banners.is_pattern_item(items, stack) { + Some(INPUT + 2) + } else { + None + }; + match target { + Some(t) => self.move_to(stack, &[t], false), + None if (9..36).contains(&slot) => { + let hotbar: Vec = (0..9).collect(); + self.move_to(stack, &hotbar, false) + } + None if slot < 9 => { + let main: Vec = (9..36).collect(); + self.move_to(stack, &main, false) + } + None => false, + } + } + /// A left click inside the loom's pattern grid or scroller. + pub(super) fn loom_click(&mut self, local: (f32, f32)) -> bool { + let Some(s) = self.station.as_ref() else { + return false; + }; + let l = &s.loom; + if !l.display { + return false; + } + for row in 0..4 { + for column in 0..4 { + let index = (row + l.start_row) * 4 + column; + let (x, y) = (60.0 + column as f32 * BUTTON, 13.0 + row as f32 * BUTTON); + if index < l.patterns.len() && inside(local, x, y, BUTTON, BUTTON) { + if let Some(s) = self.station.as_mut() { + s.loom.selected = Some(index); + } + self.audio + .play("minecraft:ui.loom.select_pattern", None, 1.0, 1.0); + self.station_changed(); + return true; + } + } + } + if inside(local, 119.0, 9.0, 12.0, 56.0) + && let Some(s) = self.station.as_mut() + { + s.loom.scrolling = true; + return true; + } + false + } + /// `LoomScreen.mouseDragged` on the scroller. + pub(super) fn loom_drag(&mut self) { + let Some(size) = self + .renderer + .as_ref() + .map(|r| [r.config.width, r.config.height]) + else { + return; + }; + let (_, oy) = self.inventory_origin(&HudBatch::new(size)); + let cursor_y = self.cursor.1; + let Some(l) = self.station.as_mut().map(|s| &mut s.loom) else { + return; + }; + if l.scrolling && l.display && l.offscreen_rows() > 0 { + let top = oy + 13.0; + l.scroll = ((cursor_y - top - 7.5) / (56.0 - 15.0)).clamp(0.0, 1.0); + l.start_row = l.row_for(l.scroll); + } + } + pub(super) fn loom_release(&mut self) { + if let Some(s) = self.station.as_mut() { + s.loom.scrolling = false; + } + } + /// `LoomScreen.mouseScrolled`. + pub(super) fn loom_scroll(&mut self, d: f32) { + let Some(l) = self.station.as_mut().map(|s| &mut s.loom) else { + return; + }; + let offscreen = l.offscreen_rows(); + if l.display && offscreen > 0 { + l.scroll = (l.scroll - d / offscreen as f32).clamp(0.0, 1.0); + l.start_row = l.row_for(l.scroll); + } + } + /// A banner flag's front face (`BannerFlagModel`, 20x40 texels at (1, 1)) + /// drawn flat: the cloth, the base colour and every layer. + pub(super) fn draw_flag( + &self, + batch: &mut HudBatch, + rect: [f32; 4], + base: &str, + layers: &[BannerLayer], + ) { + let banners = &self.res.stations.banners; + let mut paint = |name: &str, color: u32| { + if let Some(r) = self.res.atlas.sprites.get(name).copied() { + let uv = sub_rect(r, [1.0, 1.0, 20.0, 40.0]); + batch.rect_uv(rect[0], rect[1], rect[2], rect[3], uv, color); + } + }; + paint("entity/banner/banner_base", u32::MAX); + paint("entity/banner/base", dye_color(base)); + for layer in layers.iter().take(16) { + paint( + &banners.banner_texture(&layer.pattern), + dye_color(&layer.color), + ); + } + } + /// `LoomScreen.extractBackground` after the background; returns the + /// pattern name tooltip of the hovered button. + pub(super) fn draw_loom( + &mut self, + batch: &mut HudBatch, + ox: f32, + oy: f32, + local: (f32, f32), + ) -> Option> { + let s = self.station.as_ref()?; + let l = &s.loom; + let atlas = &self.res.atlas; + for (i, icon) in ["banner", "dye", "banner_pattern"].iter().enumerate() { + if s.inputs[i].is_none() { + let pos = [(13.0, 26.0), (33.0, 26.0), (23.0, 45.0)][i]; + batch.sprite( + atlas, + &format!("gui/sprites/container/slot/{icon}"), + ox + pos.0, + oy + pos.1, + ); + } + } + let scroller = if l.scroll_active() { + "scroller" + } else { + "scroller_disabled" + }; + batch.sprite( + atlas, + &format!("gui/sprites/container/loom/{scroller}"), + ox + 119.0, + oy + 13.0 + (41.0 * l.scroll).floor(), + ); + let result = s.result.clone(); + let (display, has_max, start_row, selected) = + (l.display, l.has_max, l.start_row, l.selected); + let patterns = l.patterns.clone(); + let dye = s.inputs[1] + .as_ref() + .and_then(|d| self.res.stations.banners.loom_dye(&self.res.items, d)) + .unwrap_or_else(|| Arc::from("white")); + if let Some(result) = result.filter(|_| !has_max) + && let Some(base) = banner::banner_color(&result.item) + { + self.draw_flag( + batch, + [ox + 141.0, oy + 8.0, 20.0, 40.0], + base, + banner::layers(&result), + ); + } else if has_max { + batch.sprite( + &self.res.atlas, + "gui/sprites/container/loom/error", + ox + 138.0, + oy + 52.0, + ); + } + let mut tooltip = None; + if display { + let atlas = &self.res.atlas; + for row in 0..4 { + for column in 0..4 { + let index = (row + start_row) * 4 + column; + let Some(pattern) = patterns.get(index) else { + return tooltip; + }; + let (x, y) = (60.0 + column as f32 * BUTTON, 13.0 + row as f32 * BUTTON); + let hover = inside(local, x, y, BUTTON, BUTTON); + let sprite = if selected == Some(index) { + "pattern_selected" + } else if hover { + let key = self + .res + .stations + .banners + .layer_key(&BannerLayer::new(pattern, &dye)); + tooltip = Some(vec![(self.translate(&key, &key), u32::MAX)]); + "pattern_highlighted" + } else { + "pattern" + }; + batch.sprite( + atlas, + &format!("gui/sprites/container/loom/{sprite}"), + ox + x, + oy + y, + ); + // extractBannerOnButton: a 5x10 grey cloth with the pattern. + batch.fill( + atlas, + ox + x + 4.0, + oy + y + 2.0, + 5.0, + 10.0, + dye_color("gray"), + ); + let texture = self.res.stations.banners.banner_texture(pattern); + if let Some(r) = atlas.sprites.get(&texture).copied() { + let uv = sub_rect(r, [0.0, 1.0, 21.0, 40.0]); + batch.rect_uv(ox + x + 4.0, oy + y + 2.0, 5.0, 10.0, uv, u32::MAX); + } + } + } + } + tooltip + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn scroller_rows_follow_the_offset() { + let l = LoomState { + patterns: (0..40) + .map(|i| Arc::from(format!("p{i}").as_str())) + .collect(), + display: true, + ..Default::default() + }; + // 40 patterns = 10 rows, 6 off screen. + assert_eq!(l.offscreen_rows(), 6); + assert!(l.scroll_active()); + assert_eq!(l.row_for(0.0), 0); + assert_eq!(l.row_for(1.0), 6); + assert_eq!(l.row_for(0.5), 3); + } + #[test] + fn few_patterns_do_not_scroll() { + let l = LoomState { + patterns: (0..16) + .map(|i| Arc::from(format!("p{i}").as_str())) + .collect(), + display: true, + ..Default::default() + }; + assert!(!l.scroll_active()); + assert_eq!(l.offscreen_rows(), 0); + } +} diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 259758994..9f201dc8a 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -1238,6 +1238,7 @@ impl Game<'_> { nether: self.dim == super::Dim::Nether, lid: &lid, sign: &|_| None, + banner: &|_| Vec::new(), glyph: &|c| self.res.atlas.glyph(c), }; self.res diff --git a/crates/horizon-client/src/game/shield.rs b/crates/horizon-client/src/game/shield.rs index eade37109..7857c047e 100644 --- a/crates/horizon-client/src/game/shield.rs +++ b/crates/horizon-client/src/game/shield.rs @@ -252,14 +252,8 @@ pub(super) fn draw_shield_icon( atlas: &horizon_client::hud::HudAtlas, x: f32, y: f32, + passes: &[(String, u32)], ) { - let Some(r) = atlas - .sprites - .get("entity/shield/shield_base_nopattern") - .copied() - else { - return; - }; // display.gui: rotation [15, -25, -5], translation [2, 3, 0], scale 0.65. let (sx, cx) = 15f32.to_radians().sin_cos(); let (sy, cy) = (-25f32).to_radians().sin_cos(); @@ -282,15 +276,9 @@ pub(super) fn draw_shield_icon( qz, ] }; - let tex = |u: f32, v: f32| { - [ - r.u0 + (r.u1 - r.u0) * u / 64.0, - r.v0 + (r.v1 - r.v0) * v / 64.0, - ] - }; // ShieldModel: plate texOffs(0, 0) box(-6, -11, -2, 12, 22, 1) and // handle texOffs(26, 0) box(-1, -3, -1, 2, 6, 6). - let mut faces: Vec<(f32, [[f32; 2]; 4], [[f32; 2]; 4], u32)> = Vec::new(); + let mut faces: Vec<(f32, [[f32; 2]; 4], [[f32; 2]; 4], f32)> = Vec::new(); for (tu, tv, from, size) in [ (0.0, 0.0, [-6.0, -11.0, -2.0], [12.0, 22.0, 1.0]), (26.0, 0.0, [-1.0, -3.0, -1.0], [2.0, 6.0, 6.0]), @@ -324,16 +312,64 @@ pub(super) fn draw_shield_icon( } let p = verts.map(place); let depth = p.iter().map(|q| q[2]).sum::() / 4.0; - let uv = [tex(c, b), tex(a, b), tex(a, e), tex(c, e)]; + let texels = [[c, b], [a, b], [a, e], [c, e]]; // Flat item lighting: faces toward the viewer are brightest. let shade = (0.6 + 0.4 * normal[2]).min(1.0); - let s = (shade * 255.0) as u8; - let color = horizon_client::hud::rgba(s, s, s, 255); - faces.push((depth, p.map(|q| [q[0], q[1]]), uv, color)); + faces.push((depth, p.map(|q| [q[0], q[1]]), texels, shade)); } } - faces.sort_by(|a, b| a.0.total_cmp(&b.0)); - for (_, p, uv, color) in faces { + // Every pass redraws the same boxes; equal depths keep the pass order. + let mut quads = Vec::new(); + for (index, (name, tint)) in passes.iter().enumerate() { + let Some(r) = atlas.sprites.get(name).copied() else { + continue; + }; + for (depth, p, texels, shade) in &faces { + let uv = texels.map(|[u, v]| { + [ + r.u0 + (r.u1 - r.u0) * u / 64.0, + r.v0 + (r.v1 - r.v0) * v / 64.0, + ] + }); + let c = |s: u32| (((tint >> s) & 255) as f32 * shade) as u8; + quads.push(( + *depth, + index, + *p, + uv, + horizon_client::hud::rgba(c(16), c(8), c(0), 255), + )); + } + } + quads.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1))); + for (_, _, p, uv, color) in quads { batch.quad(p, uv, color); } } +/// The textures a shield draws: the plain or patterned base, then the +/// banner layers (`ShieldSpecialRenderer.submit`). +pub(super) fn shield_passes( + banners: &horizon_client::banner::Banners, + stack: &ItemStack, +) -> Vec<(String, u32)> { + let data = stack.data(); + let layers = data.map_or(&[][..], |d| &d.banner_patterns[..]); + let base = data.and_then(|d| d.base_color.as_deref()); + if layers.is_empty() && base.is_none() { + return vec![("entity/shield/shield_base_nopattern".into(), 0xFFFFFF)]; + } + let mut passes = vec![ + ("entity/shield/shield_base".into(), 0xFFFFFF), + ( + "entity/shield/base".into(), + horizon_client::banner::dye_rgb(base.unwrap_or("white")), + ), + ]; + for layer in layers.iter().take(16) { + passes.push(( + banners.shield_texture(&layer.pattern), + horizon_client::banner::dye_rgb(&layer.color), + )); + } + passes +} diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index eb6f8c24d..e2771daba 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -32,6 +32,8 @@ pub(super) enum Kind { Beacon, /// The cartography table (game/cartography.rs). Cartography, + /// The loom (game/loom.rs). + Loom, } impl Kind { fn from_block(name: &str) -> Option { @@ -45,12 +47,13 @@ impl Kind { "minecraft:stonecutter" => Self::Stonecutter, "minecraft:beacon" => Self::Beacon, "minecraft:cartography_table" => Self::Cartography, + "minecraft:loom" => Self::Loom, _ => return None, }) } fn inputs(self) -> usize { match self { - Self::Smithing => 3, + Self::Smithing | Self::Loom => 3, Self::Stonecutter | Self::Beacon => 1, _ => 2, } @@ -65,6 +68,7 @@ impl Kind { Self::Merchant => "gui/container/villager", Self::Beacon => "gui/container/beacon", Self::Cartography => "gui/container/cartography_table", + Self::Loom => "gui/container/loom", } } fn title_key(self) -> &'static str { @@ -77,6 +81,7 @@ impl Kind { Self::Merchant => "merchant.trades", Self::Beacon => "container.beacon", Self::Cartography => "container.cartography_table", + Self::Loom => "container.loom", } } /// (titleLabelX, titleLabelY). @@ -85,7 +90,7 @@ impl Kind { Self::Anvil => (60.0, 6.0), Self::Smithing => (44.0, 15.0), Self::Stonecutter => (8.0, 5.0), - Self::Cartography => (8.0, 4.0), + Self::Cartography | Self::Loom => (8.0, 4.0), _ => (8.0, 6.0), } } @@ -99,6 +104,7 @@ impl Kind { Self::Merchant => &[(86.0, 37.0), (112.0, 37.0)], Self::Beacon => &[(109.0, 110.0)], Self::Cartography => &[(15.0, 15.0), (15.0, 52.0)], + Self::Loom => &[(13.0, 26.0), (33.0, 26.0), (23.0, 45.0)], }; table[i.min(table.len() - 1)] } @@ -112,6 +118,7 @@ impl Kind { Self::Merchant => Some((170.0, 37.0)), Self::Beacon => None, Self::Cartography => Some((145.0, 39.0)), + Self::Loom => Some((143.0, 57.0)), } } } @@ -133,11 +140,13 @@ pub(super) struct Station { input_item: Option>, /// Anvil: the input the rename box was last filled from. anvil_last: Option, - last_sound: u64, + pub(super) last_sound: u64, /// Villager trading state. pub(super) merchant: Option>, /// Beacon menu: the selected primary and secondary power (EFFECTS index). pub(super) beacon: [Option; 2], + /// The loom's patterns, selection and scroller (game/loom.rs). + pub(super) loom: super::loom::LoomState, } impl Station { fn new(kind: Kind, pos: [i32; 3]) -> Self { @@ -158,6 +167,7 @@ impl Station { last_sound: 0, merchant: None, beacon: [None; 2], + loom: Default::default(), } } pub(super) fn new_kind(kind: Kind, pos: [i32; 3]) -> Self { @@ -437,6 +447,7 @@ impl Game<'_> { Kind::Merchant => super::trading::update(&mut s, items), Kind::Beacon => {} Kind::Cartography => s.result = self.cartography_result(&s), + Kind::Loom => self.loom_changed(&mut s), Kind::Stonecutter => { let item = s.inputs[0].as_ref().map(|i| i.item.clone()); if item != s.input_item { @@ -498,6 +509,7 @@ impl Game<'_> { match s.kind { Kind::Enchanting if i == 0 => (true, 1), Kind::Beacon => (super::beacon::is_payment(&stack.item), 1), + Kind::Loom => self.loom_slot_rules(i, stack), Kind::Cartography if i == 0 => (super::maps::map_id(stack).is_some(), 64), Kind::Cartography => ( matches!( @@ -565,7 +577,12 @@ impl Game<'_> { self.carried = new_carried; } /// `moveItemStackTo` over `targets` (menu order), merging first, then empty slots. - fn move_to(&mut self, stack: &mut ItemStack, targets: &[usize], reverse: bool) -> bool { + pub(super) fn move_to( + &mut self, + stack: &mut ItemStack, + targets: &[usize], + reverse: bool, + ) -> bool { let order: Vec = if reverse { targets.iter().rev().copied().collect() } else { @@ -614,8 +631,12 @@ impl Game<'_> { return false; }; let player = Self::player_slots(); + let loom = self.station.as_ref().is_some_and(|s| s.kind == Kind::Loom); let moved = if (300..305).contains(&slot) || slot >= INPUT { - self.move_to(&mut stack, &player, true) + // LoomMenu moves into the inventory front to back, the others back to front. + self.move_to(&mut stack, &player, !loom) + } else if loom { + self.loom_quick_move(slot, &mut stack) } else if self.brewing_open() { // BrewingStandMenu.quickMoveStack: fuel, ingredient, bottles, then the other half. let data = self.data(); @@ -673,7 +694,7 @@ impl Game<'_> { moved = self.move_to(&mut stack, &[INPUT, INPUT + 1], false); } } - Some(Kind::Merchant) => {} + Some(Kind::Merchant | Kind::Loom) => {} Some(Kind::Beacon) => { // BeaconMenu.quickMoveStack: one payment item into the empty slot. if super::beacon::is_payment(&stack.item) { @@ -713,7 +734,7 @@ impl Game<'_> { ]; self.audio.play(sound, Some(at), volume, pitch); } - fn give_or_drop(&mut self, stack: ItemStack) { + pub(super) fn give_or_drop(&mut self, stack: ItemStack) { if let Some(rest) = self.give(stack) && let Some(eye) = self.eye_position() { @@ -860,6 +881,7 @@ impl Game<'_> { self.cartography_taken(pos); } } + Kind::Loom => self.loom_taken(&mut s), Kind::Enchanting => {} } self.station = Some(s); @@ -991,6 +1013,9 @@ impl Game<'_> { if kind == Kind::Merchant && !right && self.merchant_click(local) { return true; } + if kind == Kind::Loom && !right && self.loom_click(local) { + return true; + } if kind == Kind::Beacon && !right && self.beacon_click(local) { return true; } @@ -1065,6 +1090,7 @@ impl Game<'_> { } pub(super) fn station_scroll(&mut self, d: f32) { self.merchant_scroll(d); + self.loom_scroll(d); let Some(s) = self.station.as_mut() else { return; }; @@ -1308,6 +1334,9 @@ impl Game<'_> { if kind == Kind::Cartography { self.draw_cartography(batch, ox, oy); } + if kind == Kind::Loom { + tooltip = self.draw_loom(batch, ox, oy, local); + } let atlas = &self.res.atlas; let s = self.station.as_ref().expect("open station"); let has_input = s.inputs.iter().any(Option::is_some); @@ -1598,7 +1627,7 @@ impl Game<'_> { } } } - Kind::Merchant | Kind::Beacon | Kind::Cartography => {} + Kind::Merchant | Kind::Beacon | Kind::Cartography | Kind::Loom => {} Kind::Stonecutter => { let display = s.inputs[0].is_some() && !s.recipes.is_empty(); let active = display && s.recipes.len() > 12; @@ -1799,6 +1828,11 @@ impl Game<'_> { }, )); } + // BannerPatternLayers.addToTooltip: up to six layer names. + for layer in horizon_client::banner::layers(stack).iter().take(6) { + let key = self.res.stations.banners.layer_key(layer); + lines.push((self.translate(&key, &key), rgba(170, 170, 170, 255))); + } if let Some(info) = self.res.items.get(&stack.item) && info.max_damage > 0 && stack.damage > 0 diff --git a/crates/horizon-client/src/game/storage.rs b/crates/horizon-client/src/game/storage.rs index 4d161514f..78c002d1a 100644 --- a/crates/horizon-client/src/game/storage.rs +++ b/crates/horizon-client/src/game/storage.rs @@ -11,6 +11,10 @@ impl Game<'_> { /// Block-entity contents on removal: shulker boxes keep theirs for the /// dropped box (`copy_components`), other containers spill them. pub(super) fn release_contents(&mut self, pos: [i32; 3], entity: BlockEntity, block: &str) { + if let BlockEntity::Banner(banner) = entity { + self.pending_banner.insert(pos, banner); + return; + } if is_shulker_box(block) { if let BlockEntity::Chest(items) = entity { let kept = items diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index d7643d3dd..792373e7a 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -35,6 +35,10 @@ pub struct StackData { pub writable_pages: Vec, /// `minecraft:written_book_content`. pub written: Option, + /// `minecraft:banner_patterns` (banners and shields). + pub banner_patterns: Vec, + /// `minecraft:base_color` (a shield's dye). + pub base_color: Option>, } /// `WrittenBookContent` with the pages as plain text. #[derive(Clone, Debug, Default, PartialEq)] @@ -267,6 +271,15 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option { if let Some(id) = d.map_id { entries.push(("minecraft:map_id", Tag::Int(id))); } + if !d.banner_patterns.is_empty() { + entries.push(( + "minecraft:banner_patterns", + crate::banner::layers_to_nbt(&d.banner_patterns), + )); + } + if let Some(color) = &d.base_color { + entries.push(("minecraft:base_color", Tag::String((&**color).into()))); + } // Filterable values are saved as {raw: ..}. let raw = |t: Tag| Tag::compound([("raw", t)]); if !d.writable_pages.is_empty() { @@ -371,6 +384,11 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option { + if !b.layers.is_empty() { + entries.push(("patterns", crate::banner::layers_to_nbt(&b.layers))); + } + if let Some(name) = &b.name { + entries.push(("CustomName", string(name))); + } + } } Tag::compound(entries) } @@ -428,6 +436,15 @@ fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers: }; return Some((pos, BlockEntity::Lectern(lectern))); } + if id == "minecraft:banner" { + return Some(( + pos, + BlockEntity::Banner(crate::containers::Banner { + layers: crate::banner::layers_from_nbt(tag.get("patterns")), + name: text(tag.get("CustomName")), + }), + )); + } if id == "minecraft:beacon" { let beacon = crate::containers::Beacon { levels: int("Levels").unwrap_or(0), @@ -474,7 +491,10 @@ fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers: }; } BlockEntity::Sign(sign) => sign.decode(tag), - BlockEntity::Jukebox(_) | BlockEntity::Beacon(_) | BlockEntity::Lectern(_) => {} + BlockEntity::Jukebox(_) + | BlockEntity::Beacon(_) + | BlockEntity::Lectern(_) + | BlockEntity::Banner(_) => {} } Some((pos, entity)) } @@ -1993,6 +2013,25 @@ impl ChunkGenerator for Persistent { #[cfg(test)] mod tests { + #[test] + fn banner_block_entity_round_trips() { + let banner = crate::containers::Banner { + layers: vec![crate::banner::BannerLayer::new("minecraft:creeper", "lime")], + name: Some("Flag".into()), + }; + let tag = encode_block_entity( + (1, 2, 3), + &crate::containers::BlockEntity::Banner(banner.clone()), + "minecraft:red_banner", + ); + let (pos, back) = decode_block_entity(&tag).expect("banner"); + assert_eq!(pos, (1, 2, 3)); + let crate::containers::BlockEntity::Banner(back) = back else { + panic!("not a banner"); + }; + assert_eq!(back.layers, banner.layers); + assert_eq!(back.name, banner.name); + } use super::*; #[test] diff --git a/crates/horizon-client/src/stations.rs b/crates/horizon-client/src/stations.rs index 8fd6f85d7..eee0a7442 100644 --- a/crates/horizon-client/src/stations.rs +++ b/crates/horizon-client/src/stations.rs @@ -18,6 +18,7 @@ pub struct StationData { pub recipes: StationRecipes, pub brewing: crate::brewing::Brewing, pub trades: crate::merchant::Trades, + pub banners: crate::banner::Banners, } impl StationData { pub fn load(root: &Path, items: &Items) -> Self { @@ -26,6 +27,7 @@ impl StationData { recipes: StationRecipes::load(root, items), brewing: crate::brewing::Brewing::load(root, items), trades: crate::merchant::Trades::load(root), + banners: crate::banner::Banners::load(root), } } } From f9eaae5a4679a31ab1f301674f072d9bc64ae29c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:48:23 +0200 Subject: [PATCH 03/13] Add the crafter The crafter block now works: right-clicking opens its menu with the 3x3 grid, the recipe result preview and the powered arrow, and clicking an empty slot disables or re-enables it (with the button click sound and the lighter disabled slot art), while shift-click moves stacks between the grid and the inventory. When powered, it crafts after four ticks using the grid's recipe, plays the craft or fail sound, shows the crafting state for six ticks, pushes the result and any remainders into the container in front (or shoots them out with white smoke), uses up one of each ingredient and fires the crafters-crafting-crafters advancement. Its comparator signal counts filled and disabled slots, hoppers fill its smallest stacks first and skip disabled slots, and its items, disabled slots, powered flag and animation ticks are saved with the chunk. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/containers.rs | 58 +++ crates/horizon-client/src/crafting.rs | 12 +- crates/horizon-client/src/game.rs | 23 +- crates/horizon-client/src/game/machines.rs | 21 + .../src/game/machines/crafter.rs | 432 ++++++++++++++++++ crates/horizon-client/src/game/stations.rs | 14 +- crates/horizon-client/src/save.rs | 51 +++ 7 files changed, 597 insertions(+), 14 deletions(-) create mode 100644 crates/horizon-client/src/game/machines/crafter.rs diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 431eac25f..d128b1a25 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -60,6 +60,56 @@ pub enum BlockEntity { Lectern(Lectern), /// `BannerBlockEntity`: the pattern layers. Banner(Banner), + /// `CrafterBlockEntity`. + Crafter(Crafter), +} +/// `CrafterBlockEntity`: nine slots that can be disabled, the powered flag +/// and the ticks left in the crafting animation. +#[derive(Clone, Debug, Default)] +pub struct Crafter { + pub items: [Option; 9], + pub disabled: [bool; 9], + pub triggered: bool, + pub crafting_ticks: i32, +} +impl Crafter { + /// `slotCanBeDisabled`: only empty slots. + pub fn slot_can_be_disabled(&self, slot: usize) -> bool { + slot < 9 && self.items[slot].is_none() + } + /// `setSlotState`. + pub fn set_slot_state(&mut self, slot: usize, enabled: bool) { + if self.slot_can_be_disabled(slot) { + self.disabled[slot] = !enabled; + } + } + /// `getRedstoneSignal`: filled or disabled slots. + pub fn redstone_signal(&self) -> i32 { + (0..9) + .filter(|&i| self.items[i].is_some() || self.disabled[i]) + .count() as i32 + } + /// `canPlaceItem`: a hopper fills the smallest stacks first. + pub fn can_place(&self, slot: usize, stack: &ItemStack, max_stack: u32) -> bool { + if slot >= 9 || self.disabled[slot] { + return false; + } + let Some(current) = &self.items[slot] else { + return true; + }; + if current.count >= max_stack { + return false; + } + !(slot + 1..9).any(|i| { + !self.disabled[i] + && match &self.items[i] { + None => true, + Some(other) => { + other.count < current.count && other.same_item_same_components(stack) + } + } + }) + } } #[derive(Clone, Debug, Default)] pub struct Banner { @@ -111,6 +161,9 @@ impl BlockEntity { if name == "minecraft:lectern" { return Some(Self::Lectern(Lectern::default())); } + if name == "minecraft:crafter" { + return Some(Self::Crafter(Crafter::default())); + } if name.ends_with("_banner") { return Some(Self::Banner(Banner::default())); } @@ -145,6 +198,7 @@ impl BlockEntity { "minecraft:blast_furnace" => "minecraft:blast_furnace", "minecraft:smoker" => "minecraft:smoker", n if n.ends_with("shulker_box") => "minecraft:shulker_box", + "minecraft:crafter" => "minecraft:crafter", _ => return None, }) } @@ -166,6 +220,7 @@ impl BlockEntity { Self::Beacon(_) => "minecraft:beacon", Self::Lectern(_) => "minecraft:lectern", Self::Banner(_) => "minecraft:banner", + Self::Crafter(_) => "minecraft:crafter", } } pub fn contents(&self) -> Vec { @@ -178,6 +233,7 @@ impl BlockEntity { Self::Beacon(_) => Vec::new(), Self::Lectern(l) => l.book.iter().cloned().collect(), Self::Banner(_) => Vec::new(), + Self::Crafter(c) => c.items.iter().flatten().cloned().collect(), } } pub fn slots(&self) -> &[Option] { @@ -190,6 +246,7 @@ impl BlockEntity { | Self::Beacon(_) | Self::Lectern(_) | Self::Banner(_) => &[], + Self::Crafter(c) => &c.items, } } pub fn slots_mut(&mut self) -> &mut [Option] { @@ -202,6 +259,7 @@ impl BlockEntity { | Self::Beacon(_) | Self::Lectern(_) | Self::Banner(_) => &mut [], + Self::Crafter(c) => &mut c.items, } } } diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index 7994d0bd7..c20f0bce9 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -289,6 +289,10 @@ impl Recipes { } /// Match a `size`x`size` grid (row-major) against the crafting recipes. pub fn craft(&self, grid: &[Option], size: usize) -> Option { + self.find(grid, size).map(|(_, result)| result) + } + /// `craft` with the matched recipe's id (the file name without namespace). + pub fn find(&self, grid: &[Option], size: usize) -> Option<(&str, ItemStack)> { // Trim to the occupied bounding box. let occupied: Vec<(usize, usize)> = (0..size * size) .filter(|&i| grid[i].is_some()) @@ -307,12 +311,12 @@ impl Recipes { ); let (w, h) = (x1 - x0 + 1, y1 - y0 + 1); let cell = |x: usize, y: usize| grid[(y0 + y) * size + x0 + x].as_ref(); - for (_, recipe) in &self.crafting { + for (name, recipe) in &self.crafting { match recipe { Recipe::Special(special) => { let stacks: Vec<&ItemStack> = grid.iter().flatten().collect(); if let Some(result) = special.assemble(&stacks) { - return Some(result); + return Some((name, result)); } } Recipe::Shaped { @@ -337,7 +341,7 @@ impl Recipes { }) }; if matches(false) || matches(true) { - return Some(result.clone()); + return Some((name, result.clone())); } } Recipe::Shapeless { @@ -361,7 +365,7 @@ impl Recipes { } }); if ok { - return Some(result.clone()); + return Some((name, result.clone())); } } } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index d5e5a8de4..02a649329 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3047,6 +3047,7 @@ impl Game<'_> { Some(BlockEntity::Chest(items)) => v.extend((0..items.len()).map(|i| 300 + i)), Some(BlockEntity::Furnace(_)) => v.extend(300..303), Some(BlockEntity::Brewing(_)) => v.extend(300..305), + Some(BlockEntity::Crafter(_)) => v.extend(300..310), Some( BlockEntity::Sign(_) | BlockEntity::Jukebox(_) @@ -3069,6 +3070,7 @@ impl Game<'_> { if let Some(p) = self .station_slot_position(i) .or_else(|| self.machine_slot_position(i)) + .or_else(|| self.crafter_slot_position(i)) { return p; } @@ -3148,6 +3150,14 @@ impl Game<'_> { &mut self.inventory[i] } } + /// What a slot shows: the crafting result slots are computed. + fn slot_view(&mut self, i: usize) -> Option { + match i { + 200 => self.craft_result(), + 309 => self.crafter_result(), + _ => self.slot_mut(i).clone(), + } + } fn craft_result(&self) -> Option { let n = self.craft_size; let grid: Vec> = (0..n * n).map(|i| self.craft_grid[i].clone()).collect(); @@ -3273,6 +3283,7 @@ impl Game<'_> { } } Some(BlockEntity::Brewing(_)) => {} + Some(BlockEntity::Crafter(_)) => self.draw_crafter_screen(batch, ox, oy), Some( BlockEntity::Sign(_) | BlockEntity::Jukebox(_) @@ -3328,11 +3339,7 @@ impl Game<'_> { oy + sy, ); } - let stack = if i == 200 { - self.craft_result() - } else { - self.slot_mut(i).clone() - }; + let stack = self.slot_view(i); if let Some(stack) = stack { self.draw_item(batch, &stack, ox + sx, oy + sy); } @@ -3421,6 +3428,11 @@ impl Game<'_> { let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { return; }; + let held_shift = + self.keys.contains(&KeyCode::ShiftLeft) || self.keys.contains(&KeyCode::ShiftRight); + if self.crafter_click(slot, held_shift) { + return; + } if let Some(c) = &self.carried && self.refuses(slot, c) { @@ -4335,6 +4347,7 @@ impl Game<'_> { } fn tick_block_entities(&mut self) -> Result<()> { self.tick_hoppers()?; + self.tick_crafters(); self.tick_jukeboxes(); self.tick_beacons(); // ChestLidController: 0.1 per tick towards open/closed. diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index 835056c09..353865c6f 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -3,6 +3,8 @@ //! the vanilla dispense behaviours Horizon has entities for, and container //! comparator signals (`AbstractContainerMenu.getRedstoneSignalFromContainer`). use super::Game; + +mod crafter; use horizon_client::{ Result, containers::BlockEntity, @@ -40,6 +42,8 @@ enum Kind { /// `AbstractFurnaceBlockEntity` (a `WorldlyContainer`). Furnace, Hopper, + /// `CrafterBlockEntity`: disabled slots and the smallest-stack-first rule. + Crafter, } /// A container: one block entity, or a double chest (`CompoundContainer`). @@ -145,6 +149,7 @@ impl Containers<'_> { let name = self.name(state); let kind = match (entity, name) { (BlockEntity::Furnace(_), _) => Kind::Furnace, + (BlockEntity::Crafter(_), _) => Kind::Crafter, (_, "minecraft:hopper") => Kind::Hopper, _ => Kind::Generic, }; @@ -212,6 +217,12 @@ impl Containers<'_> { } /// `Container.canPlaceItem` (+ `canPlaceItemThroughFace` for furnaces). fn can_place(&self, view: &View, slot: usize, stack: &ItemStack) -> bool { + if view.kind == Kind::Crafter { + return match self.world.block_entities.get(&view.parts[0].0) { + Some(BlockEntity::Crafter(c)) => c.can_place(slot, stack, self.max_stack(stack)), + _ => false, + }; + } if view.kind != Kind::Furnace { return true; } @@ -246,6 +257,13 @@ impl Containers<'_> { } /// `AbstractContainerMenu.getRedstoneSignalFromContainer`. fn signal(&self, view: &View) -> i32 { + if view.kind == Kind::Crafter { + // CrafterBlockEntity.getRedstoneSignal: filled or disabled slots. + return match self.world.block_entities.get(&view.parts[0].0) { + Some(BlockEntity::Crafter(c)) => c.redstone_signal(), + _ => 0, + }; + } let mut total = 0.0f32; for i in 0..view.len() { if let Some(s) = self.get(view, i) { @@ -567,6 +585,9 @@ impl Game<'_> { pub(super) fn dispense_from(&mut self, pos: BlockPos, state: BlockStateId) -> Result<()> { let key = (pos.x, pos.y, pos.z); let name = self.res.facts.get(state).name.clone(); + if &*name == "minecraft:crafter" { + return self.crafter_dispense(pos, state); + } let dropper = &*name == "minecraft:dropper"; if !dropper && &*name != "minecraft:dispenser" { return Ok(()); diff --git a/crates/horizon-client/src/game/machines/crafter.rs b/crates/horizon-client/src/game/machines/crafter.rs new file mode 100644 index 000000000..e0315f46f --- /dev/null +++ b/crates/horizon-client/src/game/machines/crafter.rs @@ -0,0 +1,432 @@ +//! The crafter (`CrafterBlock`, `CrafterBlockEntity`, `CrafterMenu`, +//! `CrafterScreen`): redstone-triggered crafting of its 3x3 grid, ejecting +//! the result and remainders into the container in front or as items, the +//! crafting animation ticks, and the menu with its toggleable slots. +use super::*; +use horizon_client::{ + advancements as adv, + containers::Crafter, + hud::{HudBatch, rgba}, + particles::{ParticleOptions, ParticleType}, +}; +use serde_json::Value; + +/// `CrafterBlock`'s crafting animation length. +const CRAFTING_TICKS: i32 = 6; +const RESULT_SLOT: usize = 309; + +fn center(pos: Pos) -> [f64; 3] { + [ + f64::from(pos.0) + 0.5, + f64::from(pos.1) + 0.5, + f64::from(pos.2) + 0.5, + ] +} +/// Whether an advancement condition's `recipes` entry names the recipe. +fn recipe_matches(condition: &Value, id: &str) -> bool { + match condition { + Value::String(s) => s == id, + Value::Array(list) => list.iter().any(|v| v.as_str() == Some(id)), + _ => true, + } +} + +impl Game<'_> { + /// `Level.setBlock` of one boolean property of the block at `pos`. + fn set_bool_prop(&mut self, pos: Pos, key: &str, value: bool, flags: i32) { + let registry = self.res.assets.registry; + let old = self.world.block(pos.0, pos.1, pos.2); + let Some(mut state) = registry.state(old).cloned() else { + return; + }; + if !state.properties.contains_key(key) { + return; + } + state.properties.insert(key.to_owned(), value.to_string()); + let Ok(id) = registry.resolve(&state) else { + return; + }; + self.with_level(|b, level, ticks| { + b.set_block(level, ticks, BlockPos::new(pos.0, pos.1, pos.2), id, flags) + }); + let _ = self.process_level_events(); + } + fn crafter_at(&self, pos: Pos) -> Option<&Crafter> { + match self.world.block_entities.get(&pos)? { + BlockEntity::Crafter(c) => Some(c), + _ => None, + } + } + /// `CrafterBlockEntity.serverTick` for every crafter, and the powered + /// flag following the block state. + pub(in crate::game) fn tick_crafters(&mut self) { + let positions: Vec = self + .world + .block_entities + .iter() + .filter(|(_, e)| matches!(e, BlockEntity::Crafter(_))) + .map(|(p, _)| *p) + .collect(); + for pos in positions { + let state = self.world.block(pos.0, pos.1, pos.2); + let triggered = self.containers().prop(state, "triggered") == Some("true"); + let mut finished = false; + if let Some(BlockEntity::Crafter(c)) = self.world.block_entities.get_mut(&pos) { + c.triggered = triggered; + let remaining = c.crafting_ticks - 1; + if remaining >= 0 { + c.crafting_ticks = remaining; + finished = remaining == 0; + } + } + if finished { + self.set_bool_prop( + pos, + "crafting", + false, + horizon_world::level::flags::UPDATE_ALL, + ); + } + } + } + /// `CrafterBlock.dispenseFrom` (the scheduled tick after a redstone pulse). + pub(super) fn crafter_dispense(&mut self, pos: BlockPos, state: BlockStateId) -> Result<()> { + let key = (pos.x, pos.y, pos.z); + let Some(crafter) = self.crafter_at(key) else { + return Ok(()); + }; + let grid: Vec> = crafter.items.to_vec(); + let found = self + .res + .recipes + .find(&grid, 3) + .map(|(name, result)| (name.to_owned(), result)) + .filter(|(_, result)| result.count > 0); + let Some((recipe, result)) = found else { + // LevelEvent 1050: CRAFTER_FAIL. + self.audio + .play("minecraft:block.crafter.fail", Some(center(key)), 1.0, 1.0); + return Ok(()); + }; + let Some(facing) = self + .containers() + .prop(state, "orientation") + .and_then(|o| o.split('_').next()) + .and_then(dir_from_name) + else { + return Ok(()); + }; + if let Some(BlockEntity::Crafter(c)) = self.world.block_entities.get_mut(&key) { + c.crafting_ticks = CRAFTING_TICKS; + } + self.set_bool_prop( + key, + "crafting", + true, + horizon_world::level::flags::UPDATE_CLIENTS, + ); + let remainders = self.res.recipes.remainders(&self.res.items, &grid, &result); + self.crafter_eject(key, facing, result, &recipe); + for rest in remainders.into_iter().flatten() { + self.crafter_eject(key, facing, rest, &recipe); + } + if let Some(BlockEntity::Crafter(c)) = self.world.block_entities.get_mut(&key) { + for slot in c.items.iter_mut() { + if let Some(s) = slot { + s.count -= 1; + if s.count == 0 { + *slot = None; + } + } + } + } + self.container_changed(key); + Ok(()) + } + /// `CrafterBlock.dispenseItem`: into the container in front, else out as an item. + fn crafter_eject(&mut self, pos: Pos, facing: Direction, stack: ItemStack, recipe: &str) { + let target = offset(pos, facing); + let mut rest = stack; + if let Some(into) = self.containers().view(target, false) { + let one_by_one = self.crafter_at(target).is_some() + || rest.count > self.containers().max_stack(&rest); + while rest.count > 0 { + let before = rest.count; + if one_by_one { + let one = ItemStack { + count: 1, + ..rest.clone() + }; + if self + .add_item(None, &into, one, Some(facing.opposite())) + .is_some() + { + break; + } + rest.count -= 1; + } else { + match self.add_item(None, &into, rest.clone(), Some(facing.opposite())) { + Some(left) => rest = left, + None => rest.count = 0, + } + if rest.count == before { + break; + } + } + } + } + if rest.count == 0 { + return; + } + self.spawn_dispensed(pos, facing, rest, 6); + // LevelEvent 1049 (CRAFTER_CRAFT) and 2010 (white smoke shot out the front). + self.audio + .play("minecraft:block.crafter.craft", Some(center(pos)), 1.0, 1.0); + let s = step(facing); + for _ in 0..10 { + let r = &mut self.world.random; + let pow = r.next_double() * 0.2 + 0.01; + let at = [ + f64::from(pos.0) + + f64::from(s[0]) * 0.6 + + 0.5 + + f64::from(s[0]) * 0.01 + + (r.next_double() - 0.5) * f64::from(s[2]) * 0.5, + f64::from(pos.1) + + f64::from(s[1]) * 0.6 + + 0.5 + + f64::from(s[1]) * 0.01 + + (r.next_double() - 0.5) * f64::from(s[1]) * 0.5, + f64::from(pos.2) + + f64::from(s[2]) * 0.6 + + 0.5 + + f64::from(s[2]) * 0.01 + + (r.next_double() - 0.5) * f64::from(s[0]) * 0.5, + ]; + let v = [ + f64::from(s[0]) * pow + r.next_gaussian() * 0.01, + f64::from(s[1]) * pow + r.next_gaussian() * 0.01, + f64::from(s[2]) * pow + r.next_gaussian() * 0.01, + ]; + self.particles + .add(&ParticleOptions::simple(ParticleType::WhiteSmoke), at, v); + } + // CrafterRecipeCraftedTrigger for players within the 17-block box. + let near = self.eye_position().is_some_and(|e| { + let c = center(pos); + (0..3).all(|i| (e[i] - c[i]).abs() <= 8.5 + 1.0) + }); + if near { + let id = format!("minecraft:{recipe}"); + let me = self.player_entity(); + self.trigger("minecraft:crafter_recipe_crafted", move |c, w| { + let ctx = adv::Entities { + this: Some(&me), + origin: me.position, + tool: None, + block_pos: None, + }; + adv::conditions(&c["player"], &ctx, w) && recipe_matches(&c["recipes"], &id) + }); + } + } + + // ---- the menu ---- + + /// The grid's current recipe result (`CrafterMenu.refreshRecipeResult`). + pub(in crate::game) fn crafter_result(&self) -> Option { + let key = self.container?; + let c = self.crafter_at(key)?; + self.res.recipes.craft(&c.items, 3) + } + fn crafter_open(&self) -> bool { + matches!(self.container_kind(), Some(BlockEntity::Crafter(_))) + } + /// `CrafterMenu` slot layout: the grid at (26, 17), the result at (134, 35). + pub(in crate::game) fn crafter_slot_position(&self, i: usize) -> Option<(f32, f32)> { + if !self.crafter_open() { + return None; + } + match i { + 300..309 => Some(( + 26.0 + ((i - 300) % 3) as f32 * 18.0, + 17.0 + ((i - 300) / 3) as f32 * 18.0, + )), + RESULT_SLOT => Some((134.0, 35.0)), + _ => None, + } + } + /// `CrafterScreen`'s background, title, disabled slots and powered arrow. + pub(in crate::game) fn draw_crafter_screen(&self, batch: &mut HudBatch, ox: f32, oy: f32) { + let Some(c) = self.container.and_then(|k| self.crafter_at(k)) else { + return; + }; + let atlas = &self.res.atlas; + batch.sprite_region( + atlas, + "gui/container/crafter", + [ox, oy, 176.0, 166.0], + 256.0, + 256.0, + ); + let grey = rgba(64, 64, 64, 255); + let title = self.translate("container.crafter", "Crafter"); + let tw = HudBatch::text_width(atlas, &title); + batch.text( + atlas, + &title, + ox + (176.0 - tw) / 2.0, + oy + 6.0, + grey, + false, + ); + batch.text(atlas, "Inventory", ox + 8.0, oy + 72.0, grey, false); + for slot in 0..9 { + if c.disabled[slot] { + let (x, y) = self.crafter_slot_position(300 + slot).unwrap_or_default(); + batch.sprite( + atlas, + "gui/sprites/container/crafter/disabled_slot", + ox + x - 1.0, + oy + y - 1.0, + ); + } + } + let powered = self + .container + .map(|k| self.world.block(k.0, k.1, k.2)) + .is_some_and(|state| self.containers().prop(state, "triggered") == Some("true")); + let arrow = if powered { + "powered_redstone" + } else { + "unpowered_redstone" + }; + batch.sprite( + atlas, + &format!("gui/sprites/container/crafter/{arrow}"), + ox + 97.0, + oy + 35.0, + ); + } + /// `gui.togglable_slot` over an empty, enabled grid slot. + pub(in crate::game) fn crafter_tooltip(&self, slot: usize) -> Option { + let c = self.container.and_then(|k| self.crafter_at(k))?; + let i = slot.checked_sub(300).filter(|i| *i < 9)?; + (self.carried.is_none() && c.items[i].is_none() && !c.disabled[i] && !self.spectator()) + .then(|| self.translate("gui.togglable_slot", "Click to toggle")) + } + /// A click in the crafter menu before the generic handling; true when + /// it was fully handled (the result, shift-clicks). + pub(in crate::game) fn crafter_click(&mut self, slot: usize, shift: bool) -> bool { + if !self.crafter_open() { + return false; + } + if slot == RESULT_SLOT { + return true; + } + if (300..309).contains(&slot) { + // CrafterScreen.slotClicked: toggle an empty slot. + let i = slot - 300; + if !shift && !self.spectator() && self.slot_mut(slot).is_none() { + let carried_empty = self.carried.is_none(); + let key = self.container; + let mut toggled = None; + if let Some(BlockEntity::Crafter(c)) = + key.and_then(|k| self.world.block_entities.get_mut(&k)) + { + if c.disabled[i] { + c.set_slot_state(i, true); + toggled = Some(true); + } else if carried_empty { + c.set_slot_state(i, false); + toggled = Some(false); + } + } + if let Some(enabled) = toggled { + let pitch = if enabled { 1.0 } else { 0.75 }; + self.audio + .play("minecraft:ui.button.click", None, 0.4, pitch); + } + } + } + if shift { + self.crafter_quick_move(slot); + return true; + } + false + } + /// `CrafterMenu.quickMoveStack`. + fn crafter_quick_move(&mut self, slot: usize) { + if slot >= 309 { + return; + } + let Some(mut stack) = self.slot_mut(slot).take() else { + return; + }; + if slot >= 300 { + let player: Vec = (9..36).chain(0..9).collect(); + self.move_to(&mut stack, &player, true); + } else { + let grid: Vec = (300..309).collect(); + self.move_to(&mut stack, &grid, false); + } + if stack.count > 0 { + *self.slot_mut(slot) = Some(stack); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn stack(item: &str, count: u32) -> Option { + Some(ItemStack::new(item, count)) + } + #[test] + fn signal_counts_filled_and_disabled_slots() { + let mut c = Crafter::default(); + assert_eq!(c.redstone_signal(), 0); + c.items[0] = stack("minecraft:stick", 3); + c.set_slot_state(4, false); + assert_eq!(c.redstone_signal(), 2); + // A filled slot cannot be disabled. + c.set_slot_state(0, false); + assert!(!c.disabled[0]); + c.set_slot_state(4, true); + assert_eq!(c.redstone_signal(), 1); + } + #[test] + fn hoppers_fill_the_smaller_stacks_first() { + let mut c = Crafter::default(); + let stick = ItemStack::new("minecraft:stick", 1); + c.items[0] = stack("minecraft:stick", 2); + c.items[1] = stack("minecraft:stick", 1); + // A later empty slot counts as smaller: stacks level out front to back. + assert!(!c.can_place(0, &stick, 64)); + assert!(!c.can_place(1, &stick, 64)); + assert!(c.can_place(2, &stick, 64)); + c.disabled[5] = true; + assert!(!c.can_place(5, &stick, 64)); + // With every later slot at least as big, a slot accepts again. + for i in 2..9 { + c.items[i] = stack("minecraft:stick", 2); + } + assert!(c.can_place(1, &stick, 64)); + // A full stack accepts nothing. + c.items[2] = stack("minecraft:stick", 64); + assert!(!c.can_place(2, &stick, 64)); + } + #[test] + fn recipes_condition_accepts_a_name_or_a_list() { + assert!(recipe_matches( + &serde_json::json!("minecraft:crafter"), + "minecraft:crafter" + )); + assert!(!recipe_matches( + &serde_json::json!(["minecraft:stick"]), + "minecraft:crafter" + )); + assert!(recipe_matches(&Value::Null, "minecraft:crafter")); + } +} diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index e2771daba..d75b84015 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -483,6 +483,12 @@ impl Game<'_> { /// `Slot.mayPlace` and `getMaxStackSize` for station and brewing slots. fn slot_rules(&self, slot: usize, stack: &ItemStack) -> (bool, u32) { let data = self.data(); + if let Some(BlockEntity::Crafter(c)) = self.container_kind() + && (300..309).contains(&slot) + { + // CrafterSlot.mayPlace: not a disabled slot. + return (!c.disabled[slot - 300], 64); + } if (300..305).contains(&slot) { return match slot - 300 { 0..=2 => (data.brewing.is_bottle(stack), 1), @@ -1952,14 +1958,12 @@ impl Game<'_> { let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) else { return; }; - let stack = if slot == 200 { - self.craft_result() - } else { - self.slot_mut(slot).clone() - }; + let stack = self.slot_view(slot); if let Some(stack) = stack { let lines = self.stack_tooltip(&stack); self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1); + } else if let Some(text) = self.crafter_tooltip(slot) { + self.draw_tooltip_lines(batch, &[(text, u32::MAX)], self.cursor.0, self.cursor.1); } } /// Potion items: `layer0` tinted with the potion colour under the bottle diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 9f9893043..6ecac27e3 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -400,6 +400,20 @@ fn encode_block_entity(p: (i32, i32, i32), e: &crate::containers::BlockEntity, b entries.push(("Page", Tag::Int(l.page))); } } + BlockEntity::Crafter(c) => { + entries.push(("Items", encode_items(&c.items))); + entries.push(( + "disabled_slots", + Tag::IntArray( + (0..9) + .filter(|&i| c.disabled[i]) + .map(|i| i as i32) + .collect(), + ), + )); + entries.push(("triggered", Tag::Int(i32::from(c.triggered)))); + entries.push(("crafting_ticks_remaining", Tag::Int(c.crafting_ticks))); + } BlockEntity::Banner(b) => { if !b.layers.is_empty() { entries.push(("patterns", crate::banner::layers_to_nbt(&b.layers))); @@ -491,6 +505,20 @@ fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers: }; } BlockEntity::Sign(sign) => sign.decode(tag), + BlockEntity::Crafter(c) => { + for (slot, item) in decode_items(tag.get("Items"), 9).into_iter().enumerate() { + c.items[slot] = item; + } + if let Some(Tag::IntArray(slots)) = tag.get("disabled_slots") { + for &slot in slots { + if (0..9).contains(&slot) && c.items[slot as usize].is_none() { + c.disabled[slot as usize] = true; + } + } + } + c.triggered = int("triggered").unwrap_or(0) != 0; + c.crafting_ticks = int("crafting_ticks_remaining").unwrap_or(0); + } BlockEntity::Jukebox(_) | BlockEntity::Beacon(_) | BlockEntity::Lectern(_) @@ -2013,6 +2041,29 @@ impl ChunkGenerator for Persistent { #[cfg(test)] mod tests { + #[test] + fn crafter_block_entity_round_trips() { + let mut crafter = crate::containers::Crafter::default(); + crafter.items[2] = Some(crate::items::ItemStack::new("minecraft:stick", 5)); + crafter.disabled[4] = true; + crafter.triggered = true; + crafter.crafting_ticks = 3; + let tag = encode_block_entity( + (7, 8, 9), + &crate::containers::BlockEntity::Crafter(crafter), + "minecraft:crafter", + ); + let (pos, back) = decode_block_entity(&tag).expect("crafter"); + assert_eq!(pos, (7, 8, 9)); + let crate::containers::BlockEntity::Crafter(back) = back else { + panic!("not a crafter"); + }; + assert_eq!(back.items[2].as_ref().map(|s| s.count), Some(5)); + assert!(back.disabled[4] && !back.disabled[3]); + assert!(back.triggered); + assert_eq!(back.crafting_ticks, 3); + assert_eq!(back.redstone_signal(), 2); + } #[test] fn banner_block_entity_round_trips() { let banner = crate::containers::Banner { From 3de8b358ec584893253af531ffcc96e867cdd0ad Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:56:20 +0200 Subject: [PATCH 04/13] Dispense items like vanilla dispensers and droppers Dispensers now follow DispenserBlock's behaviour table: arrows, eggs, snowballs, experience bottles, thrown potions, firework rockets (flying straight until they hit something) and fire charges are shot out with the vanilla power and spread; buckets place or pick up water, lava, powder snow and mobs through the new Behaviours bucket calls; flint and steel, bone meal, TNT, shears (sheep, mooshrooms, bogged, beehives), brushes on armadillos, honeycomb waxing, respawn anchors, glass bottles (water, honey), water potions on mud, boats, minecarts, armor stands, shulker boxes, carved pumpkins (which now build snow and iron golems for players too), wither skulls, spawn eggs and worn equipment on players, armor stands and mobs that may pick up loot. Every dispense plays the vanilla click, fail or launch sound and the smoke puff, and droppers keep the plain drop or container insert. Experience bottles can also be thrown by the player. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/entity_nbt.rs | 3 +- crates/horizon-client/src/game.rs | 3 + crates/horizon-client/src/game/dispenser.rs | 1462 +++++++++++++++++++ crates/horizon-client/src/game/fireworks.rs | 32 +- crates/horizon-client/src/game/golems.rs | 82 ++ crates/horizon-client/src/game/machines.rs | 385 +---- crates/horizon-client/src/game/minecarts.rs | 10 +- crates/horizon-client/src/game/potions.rs | 89 +- crates/horizon-client/src/items.rs | 25 + crates/horizon-client/src/mobs.rs | 2 + crates/horizon-client/src/mobs/spawning.rs | 22 +- crates/horizon-world/src/level/buckets.rs | 146 ++ crates/horizon-world/src/level/fluids.rs | 2 +- crates/horizon-world/src/level/mod.rs | 2 + crates/horizon-world/src/level/tests.rs | 63 + 15 files changed, 1912 insertions(+), 416 deletions(-) create mode 100644 crates/horizon-client/src/game/dispenser.rs create mode 100644 crates/horizon-client/src/game/golems.rs create mode 100644 crates/horizon-world/src/level/buckets.rs diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index a655c2dcd..02ab14543 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -124,7 +124,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { for (key, value) in [ ("AbsorptionAmount", Tag::Float(0)), ("FallFlying", Tag::Byte(0)), - ("CanPickUpLoot", Tag::Byte(0)), + ("CanPickUpLoot", Tag::Byte(i8::from(m.extra.pick_up_loot))), ("LeftHanded", Tag::Byte(0)), ( "Brain", @@ -446,6 +446,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - } m.death_time = number(tag.get("DeathTime")).unwrap_or(0) as i32; m.persistent = flag(tag, "PersistenceRequired"); + m.extra.pick_up_loot = flag(tag, "CanPickUpLoot"); m.custom_name = custom_name(tag); if m.kind.category == "creature" { m.extra.age = number(tag.get("Age")).unwrap_or(0) as i32; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 66925932c..cd921c878 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -15,6 +15,7 @@ mod commands; mod control; mod creatures; mod crossbow; +mod dispenser; mod dragon; mod enchant_effects; mod end; @@ -25,6 +26,7 @@ mod fishing; mod fov; mod frames; mod game_mode; +mod golems; mod growth; mod jukebox; mod lightning; @@ -1830,6 +1832,7 @@ impl Game<'_> { self.stats.add("used", &stack.item, 1); self.trigger_block("minecraft:placed_block", target, &stack); self.check_wither_spawn(target)?; + self.check_golem_spawn(target)?; self.consume_held(); Ok(()) } diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs new file mode 100644 index 000000000..75f39881d --- /dev/null +++ b/crates/horizon-client/src/game/dispenser.rs @@ -0,0 +1,1462 @@ +//! Dispenser behaviours: `DispenserBlock.getDispenseMethod(..).dispense` with +//! every `DispenseItemBehavior` registration of vanilla that Horizon has the +//! entities for. A behaviour returns what is left in the slot and the level +//! event it plays (`DefaultDispenseItemBehavior.dispense` then plays that +//! event and the smoke animation, event 2000). +use super::Game; +use horizon_client::{ + Result, + collisions::SceneCollisions, + containers::BlockEntity, + items::ItemStack, + mobs::{MobEvent, SpawnSetup, Species}, + particles::{ParticleOptions, ParticleType}, + projectiles::{Projectile, ProjectileKind}, +}; +use horizon_core::{ + geometry::{Aabb, Direction, Vec3}, + position::BlockPos, + random::RandomSource, +}; +use horizon_world::{ + fluid::FluidKind, + level::{BucketContent, PlaceContext, PlaceOutcome}, + registry::BlockStateId, +}; + +type Pos = (i32, i32, i32); + +/// The sound event of a plain click, a failed dispense and a launched projectile. +const CLICK: i32 = 1000; +const FAIL: i32 = 1001; +const LAUNCH: i32 = 1002; + +fn step(d: Direction) -> [i32; 3] { + match d { + Direction::Down => [0, -1, 0], + Direction::Up => [0, 1, 0], + Direction::North => [0, 0, -1], + Direction::South => [0, 0, 1], + Direction::West => [-1, 0, 0], + Direction::East => [1, 0, 0], + } +} +fn offset(p: Pos, d: Direction) -> Pos { + let s = step(d); + (p.0 + s[0], p.1 + s[1], p.2 + s[2]) +} +/// `Direction.get3DDataValue`. +fn data_value(d: Direction) -> i32 { + match d { + Direction::Down => 0, + Direction::Up => 1, + Direction::North => 2, + Direction::South => 3, + Direction::West => 4, + Direction::East => 5, + } +} +/// `Direction.toYRot` (vertical directions give 270 through `data2d = -1`). +fn y_rot(d: Direction) -> f32 { + match d { + Direction::South => 0.0, + Direction::West => 90.0, + Direction::North => 180.0, + Direction::East => 270.0, + _ => 270.0, + } +} +fn block_box(p: Pos) -> Aabb { + Aabb::new( + Vec3::new(f64::from(p.0), f64::from(p.1), f64::from(p.2)), + Vec3::new(f64::from(p.0 + 1), f64::from(p.1 + 1), f64::from(p.2 + 1)), + ) +} +fn overlaps(a: Aabb, b: Aabb) -> bool { + let (a0, a1, b0, b1) = ( + a.min_position(), + a.max_position(), + b.min_position(), + b.max_position(), + ); + a0.x < b1.x && b0.x < a1.x && a0.y < b1.y && b0.y < a1.y && a0.z < b1.z && b0.z < a1.z +} +/// `ItemStack.shrink(1)`; the slot is empty at zero. +fn shrink(mut stack: ItemStack) -> Option { + stack.count -= 1; + (stack.count > 0).then_some(stack) +} +/// A dispenser's answer: the slot's new content and the level event played. +type Dispensed = (Option, i32); + +/// Entities `getEntitiesOfClass(.., AABB(pos))` can find. +enum Target { + Player, + Mob(usize), + Stand(usize), +} + +impl Game<'_> { + fn prop(&self, state: BlockStateId, key: &str) -> Option { + self.res + .assets + .registry + .state(state)? + .properties + .get(key) + .cloned() + } + /// The same block with other properties (`withProperty`). + fn with_props(&self, state: BlockStateId, props: &[(&str, &str)]) -> Option { + let mut s = self.res.assets.registry.state(state)?.clone(); + for (k, v) in props { + s.properties.insert((*k).to_owned(), (*v).to_owned()); + } + self.res.assets.registry.resolve(&s).ok() + } + fn block_at(&self, p: Pos) -> BlockStateId { + self.world.block(p.0, p.1, p.2) + } + fn dispenser_block_name(&self, p: Pos) -> std::sync::Arc { + self.res.facts.get(self.block_at(p)).name.clone() + } + fn in_block_tag(&self, tag: &str, block: &str) -> bool { + self.res + .items + .block_tags + .get(tag) + .is_some_and(|s| s.contains(block)) + } + fn water_at(&self, p: Pos) -> bool { + matches!( + self.res.behaviours.fluid_kind(self.block_at(p)), + FluidKind::Water | FluidKind::FlowingWater + ) + } + fn center(p: Pos) -> [f64; 3] { + [ + f64::from(p.0) + 0.5, + f64::from(p.1) + 0.5, + f64::from(p.2) + 0.5, + ] + } + fn pos_of(p: Pos) -> BlockPos { + BlockPos::new(p.0, p.1, p.2) + } + + // ---- level events (LevelEventHandler) ---- + + /// The dispenser level events: 1000 click, 1001 fail, 1002 launch, 1004 + /// firework shoot, 1018 blaze shoot and 2000 smoke shot out of the front. + pub(super) fn dispenser_event(&mut self, id: i32, pos: Pos, data: i32) { + let c = Self::center(pos); + match id { + 1000 => self + .audio + .play("minecraft:block.dispenser.dispense", Some(c), 1.0, 1.0), + 1001 => self + .audio + .play("minecraft:block.dispenser.fail", Some(c), 1.0, 1.2), + 1002 => self + .audio + .play("minecraft:block.dispenser.launch", Some(c), 1.0, 1.2), + 1004 => self + .audio + .play("minecraft:entity.firework_rocket.shoot", Some(c), 1.0, 1.2), + 1018 => { + let r = &mut self.world.random; + let pitch = (r.next_float() - r.next_float()) * 0.2 + 1.0; + self.audio + .play("minecraft:entity.blaze.shoot", Some(c), 2.0, pitch); + } + 2000 => { + let s = match data { + 0 => [0, -1, 0], + 1 => [0, 1, 0], + 2 => [0, 0, -1], + 3 => [0, 0, 1], + 4 => [-1, 0, 0], + _ => [1, 0, 0], + }; + for _ in 0..10 { + let r = self.particles.random(); + let pow = r.next_double() * 0.2 + 0.01; + let (sx, sy, sz) = (f64::from(s[0]), f64::from(s[1]), f64::from(s[2])); + let p = [ + f64::from(pos.0) + + sx * 0.6 + + 0.5 + + sx * 0.01 + + (r.next_double() - 0.5) * sz * 0.5, + f64::from(pos.1) + + sy * 0.6 + + 0.5 + + sy * 0.01 + + (r.next_double() - 0.5) * sy * 0.5, + f64::from(pos.2) + + sz * 0.6 + + 0.5 + + sz * 0.01 + + (r.next_double() - 0.5) * sx * 0.5, + ]; + let v = [ + sx * pow + r.next_gaussian() * 0.01, + sy * pow + r.next_gaussian() * 0.01, + sz * pow + r.next_gaussian() * 0.01, + ]; + self.particles + .add(&ParticleOptions::simple(ParticleType::Smoke), p, v); + } + } + _ => {} + } + } + + // ---- DefaultDispenseItemBehavior ---- + + /// `DispenserBlock.getDispensePosition(source, scale, offset)`. + fn dispense_position(pos: Pos, facing: Direction, scale: f64, offset: [f64; 3]) -> Vec3 { + let s = step(facing); + let c = Self::center(pos); + Vec3::new( + c[0] + scale * f64::from(s[0]) + offset[0], + c[1] + scale * f64::from(s[1]) + offset[1], + c[2] + scale * f64::from(s[2]) + offset[2], + ) + } + /// `DefaultDispenseItemBehavior.spawnItem` at `getDispensePosition`. + pub(super) fn spawn_dispensed( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + accuracy: i32, + ) { + let s = step(facing); + let p = Self::dispense_position(pos, facing, 0.7, [0.0; 3]); + let mut at = [p.x, p.y, p.z]; + at[1] -= if s[1] != 0 { 0.125 } else { 0.156_25 }; + let r = &mut self.world.random; + // new ItemEntity(level, x, y, z, stack): its default motion draws first. + let _ = (r.next_double(), r.next_double()); + let pow = r.next_double() * 0.1 + 0.2; + let spread = 0.017_227_5 * f64::from(accuracy); + let v = [ + r.triangle(f64::from(s[0]) * pow, spread), + r.triangle(0.2, spread), + r.triangle(f64::from(s[2]) * pow, spread), + ]; + self.spawn_item(stack, at, v, 0); + } + /// `DefaultDispenseItemBehavior.execute`: drop one item. + fn default_execute( + &mut self, + pos: Pos, + facing: Direction, + mut stack: ItemStack, + ) -> Option { + let one = ItemStack { + count: 1, + ..stack.clone() + }; + stack.count -= 1; + self.spawn_dispensed(pos, facing, one, 6); + (stack.count > 0).then_some(stack) + } + /// `new DefaultDispenseItemBehavior().dispense(..)` including its events. + pub(super) fn dispense_default( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Option { + let left = self.default_execute(pos, facing, stack); + self.dispenser_event(CLICK, pos, 0); + self.dispenser_event(2000, pos, data_value(facing)); + left + } + /// `DefaultDispenseItemBehavior.consumeWithRemainder`: the remainder goes + /// into the dispenser (`insertItem`) or is dropped. + fn consume_with_remainder( + &mut self, + pos: Pos, + facing: Direction, + mut stack: ItemStack, + remainder: ItemStack, + ) -> Option { + stack.count -= 1; + if stack.count == 0 { + return Some(remainder); + } + let mut rest = remainder; + if let Some(entity) = self.world.block_entities.get_mut(&pos) { + let max = self + .res + .items + .get(&rest.item) + .map_or(64, |i| i.max_stack) + .max(1); + for cell in entity.slots_mut() { + match cell { + None => { + let n = rest.count.min(max); + *cell = Some(ItemStack { + count: n, + ..rest.clone() + }); + rest.count -= n; + } + Some(e) if e.same_item_same_components(&rest) => { + let n = rest.count.min(max.saturating_sub(e.count)); + e.count += n; + rest.count -= n; + } + Some(_) => {} + } + if rest.count == 0 { + break; + } + } + } + if rest.count > 0 { + self.spawn_dispensed(pos, facing, rest, 6); + self.dispenser_event(CLICK, pos, 0); + self.dispenser_event(2000, pos, data_value(facing)); + } + Some(stack) + } + /// `ItemStack.hurtAndBreak(amount)` without an entity. + fn hurt_and_break(&mut self, mut stack: ItemStack, amount: u32) -> Option { + let max = self.res.items.get(&stack.item).map_or(0, |i| i.max_damage); + if max == 0 { + return Some(stack); + } + stack.damage += self.durability_loss(&stack, amount); + if stack.damage >= max { + return shrink(ItemStack { damage: 0, ..stack }); + } + Some(stack) + } + + // ---- the registry ---- + + /// `DispenserBlock.getDispenseMethod(..).dispense(source, stack)`: what the + /// slot holds afterwards. + pub(super) fn dispense_item( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result> { + let item = stack.item.to_string(); + let (left, event) = match item.as_str() { + "minecraft:arrow" + | "minecraft:tipped_arrow" + | "minecraft:spectral_arrow" + | "minecraft:egg" + | "minecraft:blue_egg" + | "minecraft:brown_egg" + | "minecraft:snowball" + | "minecraft:experience_bottle" + | "minecraft:splash_potion" + | "minecraft:lingering_potion" + | "minecraft:firework_rocket" + | "minecraft:fire_charge" => self.dispense_projectile(pos, facing, stack), + "minecraft:armor_stand" => self.dispense_armor_stand(pos, facing, stack), + "minecraft:chest" => self.dispense_chest(pos, facing, stack), + "minecraft:lava_bucket" + | "minecraft:water_bucket" + | "minecraft:powder_snow_bucket" + | "minecraft:salmon_bucket" + | "minecraft:cod_bucket" + | "minecraft:pufferfish_bucket" + | "minecraft:tropical_fish_bucket" + | "minecraft:axolotl_bucket" + | "minecraft:tadpole_bucket" => self.dispense_filled_bucket(pos, facing, stack)?, + "minecraft:bucket" => self.dispense_empty_bucket(pos, facing, stack)?, + "minecraft:flint_and_steel" => self.dispense_flint_and_steel(pos, facing, stack)?, + "minecraft:bone_meal" => self.dispense_bone_meal(pos, facing, stack)?, + "minecraft:tnt" => self.dispense_tnt(pos, facing, stack), + "minecraft:wither_skeleton_skull" => self.dispense_wither_skull(pos, facing, stack)?, + "minecraft:carved_pumpkin" => self.dispense_carved_pumpkin(pos, facing, stack)?, + "minecraft:glass_bottle" => self.dispense_glass_bottle(pos, facing, stack)?, + "minecraft:glowstone" => self.dispense_glowstone(pos, facing, stack)?, + "minecraft:shears" => self.dispense_shears(pos, facing, stack)?, + "minecraft:brush" => self.dispense_brush(pos, facing, stack), + "minecraft:honeycomb" => self.dispense_honeycomb(pos, facing, stack)?, + "minecraft:potion" => self.dispense_potion(pos, facing, stack)?, + _ if item.ends_with("shulker_box") => self.dispense_shulker_box(pos, facing, stack)?, + _ if super::boats::boat_wood(&item).is_some() => self.dispense_boat(pos, facing, stack), + _ if super::minecarts::CartKind::from_id(&item).is_some() => { + self.dispense_minecart(pos, facing, stack) + } + _ => self.dispense_default_method(pos, facing, stack), + }; + self.dispenser_event(event, pos, 0); + self.dispenser_event(2000, pos, data_value(facing)); + Ok(left) + } + /// `DispenserBlock.getDefaultDispenseMethod`: equipment, spawn eggs, or a drop. + fn dispense_default_method( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Dispensed { + let equippable = self + .res + .items + .get(&stack.item) + .is_some_and(|i| i.equip_slot.is_some()); + if equippable { + let mut stack = stack; + if self.dispense_equipment(pos, facing, &mut stack) { + return (Some(stack).filter(|s| s.count > 0), CLICK); + } + return (self.default_execute(pos, facing, stack), CLICK); + } + if stack.item.ends_with("_spawn_egg") { + return self.dispense_spawn_egg(pos, facing, stack); + } + (self.default_execute(pos, facing, stack), CLICK) + } + + // ---- entities ---- + + /// Entities whose box overlaps the block at `p`. + fn targets_at(&self, p: Pos) -> Vec { + let block = block_box(p); + let mut out: Vec = self + .mobs + .iter() + .enumerate() + .filter(|(_, m)| m.alive() && overlaps(m.bounds(), block)) + .map(|(i, _)| Target::Mob(i)) + .collect(); + out.extend( + self.armor_stands + .iter() + .enumerate() + .filter(|(_, s)| overlaps(s.bounds(), block)) + .map(|(i, _)| Target::Stand(i)), + ); + if let Some(v) = self.player_view() + && v.alive + && !self.spectator() + && overlaps(v.bounds, block) + { + out.push(Target::Player); + } + out + } + /// The Y offset `EntityType.getYOffset` finds for a box set down into a block. + fn drop_offset(&self, width: f64, height: f64, p: Pos) -> f64 { + let h = width / 2.0; + let (x, z) = (f64::from(p.0) + 0.5, f64::from(p.2) + 0.5); + let y = f64::from(p.1) + 1.0; + let bounds = Aabb::new( + Vec3::new(x - h, y, z - h), + Vec3::new(x + h, y + height, z + h), + ); + let mut scene = SceneCollisions { + world: &self.world, + binding: self.collision, + }; + match scene.resolve(bounds, Vec3::new(0.0, -1.0, 0.0), 0.0, false) { + Ok(moved) => 1.0 + moved.y, + Err(_) => 0.0, + } + } + /// `EntityType.spawn(.., pos, reason, tryMoveDown, false)` for a mob. + fn spawn_mob_at(&mut self, kind: &str, p: Pos, try_move_down: bool) -> Option { + let name = if kind.contains(':') { + kind.to_owned() + } else { + format!("minecraft:{kind}") + }; + let t = self.res.mob_types.get(&name)?.clone(); + let y_off = if try_move_down { + self.drop_offset(t.width, t.height, p) + } else { + 0.0 + }; + let at = [ + f64::from(p.0) + 0.5, + f64::from(p.1) + y_off, + f64::from(p.2) + 0.5, + ]; + self.spawn_mob(&name, at, true) + } + /// `EquipmentDispenseItemBehavior.dispenseEquipment`: the first entity in + /// front that can wear the item gets one of it. + fn dispense_equipment(&mut self, pos: Pos, _facing: Direction, stack: &mut ItemStack) -> bool { + let Some(info) = self.res.items.get(&stack.item) else { + return false; + }; + let (Some(slot), true) = (info.equip_slot.clone(), info.equip_dispensable) else { + return false; + }; + let allowed = info.equip_allowed.clone(); + let sound = info.equip_sound.clone(); + let front = offset(pos, _facing); + let one = ItemStack { + count: 1, + ..stack.clone() + }; + let armor_index = match slot.as_str() { + "head" => Some(0), + "chest" => Some(1), + "legs" => Some(2), + "feet" => Some(3), + _ => None, + }; + let id_allowed = |id: &str| allowed.as_ref().is_none_or(|a| a.contains(id)); + let item: std::sync::Arc = stack.item.clone(); + for target in self.targets_at(front) { + let at = match target { + Target::Player => { + // The player wears armour only. + let Some(i) = armor_index else { continue }; + if !id_allowed("minecraft:player") || self.armor[i].is_some() { + continue; + } + self.armor[i] = Some(one.clone()); + self.apply_equipment(); + self.player_view().map(|v| v.position) + } + Target::Stand(i) => { + let Some(ai) = armor_index else { continue }; + if !id_allowed("minecraft:armor_stand") { + continue; + } + // ArmorStand equipment: mainhand, offhand, feet, legs, chest, head. + let index = 5 - ai; + let stand = &mut self.armor_stands[i]; + if stand.equipment[index].is_some() { + continue; + } + stand.equipment[index] = Some(one.clone()); + Some(stand.position) + } + Target::Mob(i) => { + let m = &mut self.mobs[i]; + if !id_allowed(&m.kind.id) { + continue; + } + let species = m.species(); + let tamed = m.extra.tame; + let equine = matches!( + species, + Species::Horse + | Species::Donkey + | Species::Mule + | Species::SkeletonHorse + | Species::ZombieHorse + | Species::Camel + ); + let slot_free = match (slot.as_str(), armor_index) { + (_, Some(0)) => m.extra.head.is_none(), + (_, Some(1)) => m.extra.chest.is_none(), + (_, Some(2)) => m.extra.legs.is_none(), + (_, Some(3)) => m.extra.feet.is_none(), + ("saddle", _) => !m.extra.saddled, + ("body", _) => species == Species::Horse && m.extra.head.is_none(), + _ => false, + }; + // Mob.canDispenserEquipIntoSlot and the overrides. + let saddle_ok = slot == "saddle" + && (matches!(species, Species::Pig | Species::Strider) || equine && tamed); + let body_ok = slot == "body" && equine && tamed; + if !slot_free || !(m.extra.pick_up_loot || saddle_ok || body_ok) { + continue; + } + if species == Species::Strider && slot == "saddle" && m.is_baby() { + continue; + } + match (slot.as_str(), armor_index) { + (_, Some(0)) => m.extra.head = Some(item.clone()), + (_, Some(1)) => m.extra.chest = Some(item.clone()), + (_, Some(2)) => m.extra.legs = Some(item.clone()), + (_, Some(3)) => m.extra.feet = Some(item.clone()), + ("saddle", _) => m.extra.saddled = true, + _ => m.extra.head = Some(item.clone()), + } + // setGuaranteedDrop / setPersistenceRequired. + m.persistent = true; + Some(m.position) + } + }; + if let (Some(sound), Some(at)) = (sound, at) { + self.audio.play(&sound, Some([at.x, at.y, at.z]), 1.0, 1.0); + } + stack.count -= 1; + return true; + } + false + } + fn dispense_spawn_egg(&mut self, pos: Pos, facing: Direction, stack: ItemStack) -> Dispensed { + let kind = stack.item.trim_end_matches("_spawn_egg").to_owned(); + let front = offset(pos, facing); + if self + .spawn_mob_at(&kind, front, facing != Direction::Up) + .is_none() + { + return (Some(stack), CLICK); + } + (shrink(stack), CLICK) + } + + // ---- ProjectileDispenseBehavior ---- + + fn dispense_projectile(&mut self, pos: Pos, facing: Direction, stack: ItemStack) -> Dispensed { + let item = stack.item.to_string(); + let s = step(facing); + let dir = [f64::from(s[0]), f64::from(s[1]), f64::from(s[2])]; + // ProjectileItem.DispenseConfig per item: position, uncertainty, power, event. + let (at, uncertainty, power, event) = match item.as_str() { + "minecraft:firework_rocket" => ( + Self::dispense_position(pos, facing, 0.500_009_999_999_747_4, [0.0; 3]), + 1.0, + 0.5, + 1004, + ), + "minecraft:fire_charge" => ( + Self::dispense_position(pos, facing, 1.0, [0.0; 3]), + 6.666_666_5, + 1.0, + 1018, + ), + "minecraft:experience_bottle" + | "minecraft:splash_potion" + | "minecraft:lingering_potion" => ( + Self::dispense_position(pos, facing, 0.7, [0.0, 0.1, 0.0]), + 3.0, + 1.375, + LAUNCH, + ), + _ => ( + Self::dispense_position(pos, facing, 0.7, [0.0, 0.1, 0.0]), + 6.0, + 1.1, + LAUNCH, + ), + }; + let one = ItemStack { + count: 1, + ..stack.clone() + }; + match item.as_str() { + "minecraft:experience_bottle" + | "minecraft:splash_potion" + | "minecraft:lingering_potion" => { + let mut shot = Projectile::new(ProjectileKind::Snowball, at, None); + shot.shoot(&mut self.world.random, dir, power, uncertainty); + self.launch_thrown(one, at, shot.velocity); + } + "minecraft:firework_rocket" => { + let mut shot = Projectile::new(ProjectileKind::Snowball, at, None); + shot.shoot(&mut self.world.random, dir, power, uncertainty); + self.launch_dispensed_rocket(at, shot.velocity, &one); + } + _ => { + let kind = match item.as_str() { + "minecraft:arrow" => ProjectileKind::Arrow { + base_damage: 2.0, + critical: false, + effect: None, + }, + "minecraft:spectral_arrow" => ProjectileKind::Arrow { + base_damage: 2.0, + critical: false, + effect: Some(("minecraft:glowing", 200)), + }, + "minecraft:tipped_arrow" => ProjectileKind::Arrow { + base_damage: 2.0, + critical: false, + effect: stack + .potion() + .and_then(horizon_client::brewing::potion) + .and_then(|def| { + def.effects + .iter() + .find(|(id, _, _)| { + !horizon_client::brewing::effect(id) + .is_some_and(|e| e.instant) + }) + .map(|(id, duration, _)| (*id, (duration / 8).max(1))) + }), + }, + "minecraft:fire_charge" => { + // The fireball's own aim is drawn first, then shot along the facing. + let r = &mut self.world.random; + let _ = ( + r.triangle(dir[0], 0.114_85), + r.triangle(dir[1], 0.114_85), + r.triangle(dir[2], 0.114_85), + ); + ProjectileKind::SmallFireball + } + "minecraft:egg" | "minecraft:blue_egg" | "minecraft:brown_egg" => { + ProjectileKind::Egg + } + _ => ProjectileKind::Snowball, + }; + let mut shot = Projectile::new(kind, at, None); + shot.shoot(&mut self.world.random, dir, power, uncertainty); + self.creatures.projectiles.push(shot); + } + } + (shrink(stack), event) + } + + // ---- entities placed by items ---- + + fn dispense_armor_stand(&mut self, pos: Pos, facing: Direction, stack: ItemStack) -> Dispensed { + let front = offset(pos, facing); + let foot = Vec3::new( + f64::from(front.0) + 0.5, + f64::from(front.1), + f64::from(front.2) + 0.5, + ); + self.next_entity += 1; + let stand = + horizon_client::entities::ArmorStand::new(self.next_entity, foot, y_rot(facing)); + self.world.modified.insert((front.0 >> 4, front.2 >> 4)); + self.armor_stands.push(stand); + (shrink(stack), CLICK) + } + /// A tame donkey, mule or llama in front without a chest gets it. + fn dispense_chest(&mut self, pos: Pos, facing: Direction, stack: ItemStack) -> Dispensed { + let front = offset(pos, facing); + for target in self.targets_at(front) { + let Target::Mob(i) = target else { continue }; + let m = &mut self.mobs[i]; + if matches!( + m.species(), + Species::Donkey | Species::Mule | Species::Llama | Species::TraderLlama + ) && m.extra.tame + && !m.extra.chested + { + m.extra.chested = true; + return (shrink(stack), CLICK); + } + } + (self.default_execute(pos, facing, stack), CLICK) + } + /// `BoatDispenseItemBehavior`. + fn dispense_boat(&mut self, pos: Pos, facing: Direction, stack: ItemStack) -> Dispensed { + let Some(wood) = super::boats::boat_wood(&stack.item).map(str::to_owned) else { + return (self.dispense_default(pos, facing, stack), CLICK); + }; + let front = offset(pos, facing); + let s = step(facing); + let c = Self::center(pos); + // Boat width 1.375. + let outside = 0.5625 + 1.375 / 2.0; + let (x, y, z) = ( + c[0] + f64::from(s[0]) * outside, + c[1] + f64::from(s[1]) * f64::from(1.125f32), + c[2] + f64::from(s[2]) * outside, + ); + let below = (front.0, front.1 - 1, front.2); + let y_offset = if self.water_at(front) { + 1.0 + } else if self.res.facts.is_air(self.block_at(front)) && self.water_at(below) { + 0.0 + } else { + return (self.dispense_default(pos, facing, stack), CLICK); + }; + if !self.boat_models.models.contains_key(&wood) { + return (self.dispense_default(pos, facing, stack), CLICK); + } + self.next_entity += 1; + let boat = super::boats::Boat::new( + self.next_entity, + wood.as_str().into(), + Vec3::new(x, y + y_offset, z), + y_rot(facing), + ); + self.world.modified.insert((front.0 >> 4, front.2 >> 4)); + self.boats.push(boat); + (shrink(stack), CLICK) + } + /// `MinecartDispenseItemBehavior`. + fn dispense_minecart(&mut self, pos: Pos, facing: Direction, stack: ItemStack) -> Dispensed { + let Some(kind) = super::minecarts::CartKind::from_id(&stack.item) else { + return (self.dispense_default(pos, facing, stack), CLICK); + }; + let s = step(facing); + let c = Self::center(pos); + let (x, base_y, z) = ( + c[0] + f64::from(s[0]) * 1.125, + c[1].floor() + f64::from(s[1]), + c[2] + f64::from(s[2]) * 1.125, + ); + let front = offset(pos, facing); + let y_offset = if let Some(rail) = self.rail(front.0, front.1, front.2) { + if rail.shape.is_slope() { 0.6 } else { 0.1 } + } else { + if !self.res.facts.is_air(self.block_at(front)) { + return (self.dispense_default(pos, facing, stack), CLICK); + } + let below = (front.0, front.1 - 1, front.2); + let Some(rail) = self.rail(below.0, below.1, below.2) else { + return (self.dispense_default(pos, facing, stack), CLICK); + }; + if facing != Direction::Down && rail.shape.is_slope() { + -0.4 + } else { + -0.9 + } + }; + self.next_entity += 1; + let cart = super::minecarts::Minecart::new( + self.next_entity, + kind, + Vec3::new(x, base_y + y_offset, z), + ); + self.world.modified.insert((front.0 >> 4, front.2 >> 4)); + self.carts.push(cart); + (shrink(stack), CLICK) + } + + // ---- buckets ---- + + /// The filled bucket behaviour: `DispensibleContainerItem.emptyContents`. + fn dispense_filled_bucket( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result { + let item = stack.item.to_string(); + let target = offset(pos, facing); + let (content, sound, mob) = match item.as_str() { + "minecraft:lava_bucket" => ( + BucketContent::Fluid(FluidKind::Lava), + "minecraft:item.bucket.empty_lava", + None, + ), + "minecraft:water_bucket" => ( + BucketContent::Fluid(FluidKind::Water), + "minecraft:item.bucket.empty", + None, + ), + "minecraft:powder_snow_bucket" => ( + BucketContent::Powder, + "minecraft:item.bucket.empty_powder_snow", + None, + ), + "minecraft:axolotl_bucket" => ( + BucketContent::Fluid(FluidKind::Water), + "minecraft:item.bucket.empty_axolotl", + Some("axolotl"), + ), + "minecraft:tadpole_bucket" => ( + BucketContent::Fluid(FluidKind::Water), + "minecraft:item.bucket.empty_tadpole", + Some("tadpole"), + ), + other => ( + BucketContent::Fluid(FluidKind::Water), + "minecraft:item.bucket.empty_fish", + Some(match other { + "minecraft:salmon_bucket" => "salmon", + "minecraft:cod_bucket" => "cod", + "minecraft:pufferfish_bucket" => "pufferfish", + _ => "tropical_fish", + }), + ), + }; + let target_pos = Self::pos_of(target); + let emptied = self + .with_level(|b, level, ticks| b.bucket_empty(level, ticks, target_pos, content, sound)); + self.process_level_events()?; + if !emptied { + return Ok((self.dispense_default(pos, facing, stack), CLICK)); + } + if self.dim == super::Dim::Nether + && matches!(content, BucketContent::Fluid(FluidKind::Water)) + { + // The water evaporates in a cloud of smoke. + let c = Self::center(target); + for _ in 0..8 { + let r = self.particles.random(); + let p = [ + f64::from(target.0) + (r.next_double() * 2.0 - 1.0), + f64::from(target.1) + (r.next_double() * 2.0 - 1.0), + f64::from(target.2) + (r.next_double() * 2.0 - 1.0), + ]; + let _ = c; + self.particles.add( + &ParticleOptions::simple(ParticleType::LargeSmoke), + p, + [0.0; 3], + ); + } + } else if let Some(kind) = mob { + // MobBucketItem.checkExtraContent. + self.spawn_mob_at(kind, target, true); + } + let bucket = ItemStack::new("minecraft:bucket", 1); + Ok(( + self.consume_with_remainder(pos, facing, stack, bucket), + CLICK, + )) + } + /// The empty bucket: `BucketPickup.pickupBlock`. + fn dispense_empty_bucket( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result { + let target = Self::pos_of(offset(pos, facing)); + let picked = self.with_level(|b, level, ticks| b.bucket_pickup(level, ticks, target)); + self.process_level_events()?; + match picked { + Some(filled) => { + let filled = ItemStack::new(filled, 1); + Ok(( + self.consume_with_remainder(pos, facing, stack, filled), + CLICK, + )) + } + None => Ok((self.default_execute(pos, facing, stack), CLICK)), + } + } + + // ---- fire, bone meal and TNT ---- + + fn dispense_flint_and_steel( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result { + let target = offset(pos, facing); + let target_pos = Self::pos_of(target); + let state = self.block_at(target); + let name = self.dispenser_block_name(target); + let mut success = true; + if self.res.facts.is_air(state) { + // BaseFireBlock.canBePlacedAt: a fire that survives, or a portal. + let below = self.dispenser_block_name((target.0, target.1 - 1, target.2)); + let fire_name = if matches!(&*below, "minecraft:soul_sand" | "minecraft:soul_soil") { + "minecraft:soul_fire" + } else { + "minecraft:fire" + }; + let fire = self.res.assets.registry.default_state(fire_name); + if let Some(fire) = fire + && self.with_level(|b, level, ticks| b.can_survive(level, ticks, target_pos, fire)) + { + self.level_set([target.0, target.1, target.2], fire)?; + } else if !self.try_light_portal([target.0, target.1, target.2])? { + // Nothing to light; vanilla still counts it as a success. + } + } else if self.prop(state, "lit").as_deref() == Some("false") + && (name.contains("campfire") || name.contains("candle")) + && self.prop(state, "waterlogged").as_deref() != Some("true") + { + if let Some(lit) = self.with_props(state, &[("lit", "true")]) { + self.level_set([target.0, target.1, target.2], lit)?; + } + } else if &*name == "minecraft:tnt" { + if self.ui.rules.bool("tnt_explodes") { + self.spawn_primed_tnt(target_pos, false); + self.with_level(|b, level, ticks| b.remove_block(level, ticks, target_pos, false)); + self.process_level_events()?; + } else { + success = false; + } + } + let event = if success { CLICK } else { FAIL }; + if success { + return Ok((self.hurt_and_break(stack, 1), event)); + } + Ok((Some(stack), event)) + } + fn dispense_bone_meal( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result { + let target = offset(pos, facing); + let target_pos = Self::pos_of(target); + let grown = self.with_level(|b, level, ticks| { + b.grow_crop(level, ticks, target_pos) + || b.grow_water_plant(level, ticks, target_pos, None) + }); + if grown { + self.level_events + .push(horizon_world::level::LevelEvent::LevelEvent { + id: 1505, + pos: target_pos, + data: 15, + }); + } + self.process_level_events()?; + if grown { + Ok((shrink(stack), CLICK)) + } else { + Ok((Some(stack), FAIL)) + } + } + fn dispense_tnt(&mut self, pos: Pos, facing: Direction, stack: ItemStack) -> Dispensed { + if !self.ui.rules.bool("tnt_explodes") { + return (Some(stack), FAIL); + } + let target = Self::pos_of(offset(pos, facing)); + self.spawn_primed_tnt(target, false); + (shrink(stack), CLICK) + } + + // ---- blocks placed by dispensers ---- + + fn dispense_wither_skull( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result { + let target = offset(pos, facing); + let free = self.res.facts.is_air(self.block_at(target)) + && target.1 >= horizon_client::chunk::MIN_Y + 2 + && self.ui.difficulty != 0 + && self.can_build_wither(target); + if free { + let rotation = match facing { + Direction::Up | Direction::Down => 0, + other => { + // RotationSegment.convertToSegment: opposite 2D data value * 4. + (match other.opposite() { + Direction::South => 0, + Direction::West => 1, + Direction::North => 2, + _ => 3, + }) * 4 + } + }; + let skull = self + .res + .assets + .registry + .default_state("minecraft:wither_skeleton_skull") + .and_then(|s| self.with_props(s, &[("rotation", &rotation.to_string())])); + if let Some(skull) = skull { + self.level_set([target.0, target.1, target.2], skull)?; + if let Some(entity) = BlockEntity::for_block("minecraft:wither_skeleton_skull") { + self.world.block_entities.insert(target, entity); + } + self.check_wither_spawn([target.0, target.1, target.2])?; + return Ok((shrink(stack), CLICK)); + } + } + let mut stack = stack; + let equipped = self.dispense_equipment(pos, facing, &mut stack); + Ok(( + Some(stack).filter(|s| s.count > 0), + if equipped { CLICK } else { FAIL }, + )) + } + /// `WitherSkullBlock.getOrCreateWitherBase().find(level, pos)`: the soul + /// sand T below the row `head` is in. + fn can_build_wither(&self, head: Pos) -> bool { + let soul = |p: Pos| { + matches!( + &*self.dispenser_block_name(p), + "minecraft:soul_sand" | "minecraft:soul_soil" + ) + }; + let air = |p: Pos| self.res.facts.is_air(self.block_at(p)); + for (ax, az) in [(1, 0), (0, 1)] { + for col in 0..3 { + let left = (head.0 - ax * col, head.1, head.2 - az * col); + let at = |c: i32, row: i32| (left.0 + ax * c, left.1 - row, left.2 + az * c); + if (0..3).all(|c| soul(at(c, 1))) + && soul(at(1, 2)) + && air(at(0, 2)) + && air(at(2, 2)) + { + return true; + } + } + } + false + } + fn dispense_carved_pumpkin( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result { + let target = offset(pos, facing); + if self.res.facts.is_air(self.block_at(target)) + && self.can_spawn_golem([target.0, target.1, target.2]) + { + if let Some(pumpkin) = self + .res + .assets + .registry + .default_state("minecraft:carved_pumpkin") + { + self.level_set([target.0, target.1, target.2], pumpkin)?; + self.check_golem_spawn([target.0, target.1, target.2])?; + } + return Ok((shrink(stack), CLICK)); + } + let mut stack = stack; + let equipped = self.dispense_equipment(pos, facing, &mut stack); + Ok(( + Some(stack).filter(|s| s.count > 0), + if equipped { CLICK } else { FAIL }, + )) + } + /// `ShulkerBoxDispenseBehavior`: place it like a `DirectionalPlaceContext`. + fn dispense_shulker_box( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result { + let front = offset(pos, facing); + let below_empty = self + .res + .facts + .is_air(self.block_at((front.0, front.1 - 1, front.2))); + let clicked_face = if below_empty { facing } else { Direction::Up }; + let front_state = self.block_at(front); + if !(self.res.facts.is_air(front_state) || self.res.facts.get(front_state).replaceable) { + return Ok((Some(stack), FAIL)); + } + let ctx = PlaceContext { + clicked_pos: Self::pos_of(front), + face: clicked_face, + hit: Vec3::new( + f64::from(front.0) + 0.5, + f64::from(front.1), + f64::from(front.2) + 0.5, + ), + inside: false, + yaw: y_rot(facing), + pitch: 0.0, + sneaking: false, + item: stack.item.to_string(), + can_use_game_master_blocks: false, + }; + let outcome = self.with_level(|b, level, ticks| b.place_block(level, ticks, &ctx)); + let PlaceOutcome::Placed { pos: placed, state } = outcome else { + self.process_level_events()?; + return Ok((Some(stack), FAIL)); + }; + let target = (placed.x, placed.y, placed.z); + if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) { + self.world.block_entities.insert(target, entity); + self.fill_placed_box([target.0, target.1, target.2], &stack); + } + let sounds = self.res.facts.get(state).sounds.clone(); + self.audio.play( + &sounds.place, + Some(Self::center(target)), + (sounds.volume + 1.0) / 2.0, + sounds.pitch * 0.8, + ); + self.process_level_events()?; + Ok((shrink(stack), CLICK)) + } + + // ---- bottles, glowstone, shears, brush, honeycomb ---- + + fn dispense_glass_bottle( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result { + let target = offset(pos, facing); + let state = self.block_at(target); + let name = self.dispenser_block_name(target); + let honey = self + .prop(state, "honey_level") + .and_then(|v| v.parse::().ok()); + if self.in_block_tag("minecraft:beehives", &name) + && let Some(level) = honey + && level >= 5 + { + // releaseBeesAndResetHoneyLevel (the bees themselves are not modelled). + if let Some(reset) = self.with_props(state, &[("honey_level", "0")]) { + self.level_set([target.0, target.1, target.2], reset)?; + } + let bottle = ItemStack::new("minecraft:honey_bottle", 1); + return Ok(( + self.consume_with_remainder(pos, facing, stack, bottle), + CLICK, + )); + } + if self.water_at(target) { + let water = ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water"); + return Ok(( + self.consume_with_remainder(pos, facing, stack, water), + CLICK, + )); + } + Ok((self.default_execute(pos, facing, stack), FAIL)) + } + fn dispense_glowstone( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result { + let target = offset(pos, facing); + let state = self.block_at(target); + if &*self.dispenser_block_name(target) == "minecraft:respawn_anchor" { + let charge = self + .prop(state, "charges") + .and_then(|v| v.parse::().ok()) + .unwrap_or(0); + if charge != 4 { + if let Some(next) = + self.with_props(state, &[("charges", &(charge + 1).to_string())]) + { + self.level_set([target.0, target.1, target.2], next)?; + } + self.audio.play( + "minecraft:block.respawn_anchor.charge", + Some(Self::center(target)), + 1.0, + 1.0, + ); + return Ok((shrink(stack), CLICK)); + } + return Ok((Some(stack), FAIL)); + } + Ok((self.default_execute(pos, facing, stack), CLICK)) + } + fn dispense_shears( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result { + let target = offset(pos, facing); + let sheared = self.shear_beehive(target)? || self.shear_entity(target)?; + if sheared { + return Ok((self.hurt_and_break(stack, 1), CLICK)); + } + Ok((Some(stack), FAIL)) + } + fn shear_beehive(&mut self, target: Pos) -> Result { + let state = self.block_at(target); + let name = self.dispenser_block_name(target); + let level = self + .prop(state, "honey_level") + .and_then(|v| v.parse::().ok()); + if !self.in_block_tag("minecraft:beehives", &name) || level.is_none_or(|l| l < 5) { + return Ok(false); + } + self.audio.play( + "minecraft:block.beehive.shear", + Some(Self::center(target)), + 1.0, + 1.0, + ); + // BeehiveBlock.dropHoneycomb, then the honey level resets. + self.pop_resource( + [target.0, target.1, target.2], + ItemStack::new("minecraft:honeycomb", 3), + ); + if let Some(reset) = self.with_props(state, &[("honey_level", "0")]) { + self.level_set([target.0, target.1, target.2], reset)?; + } + Ok(true) + } + /// `Shearable.shear` on the first ready entity in the block. + fn shear_entity(&mut self, target: Pos) -> Result { + for t in self.targets_at(target) { + let Target::Mob(i) = t else { continue }; + let m = &self.mobs[i]; + let at = [m.position.x, m.position.y, m.position.z]; + match m.species() { + Species::Sheep if !m.extra.sheared && !m.is_baby() => { + let color = + horizon_client::mobs::render::DYE_NAMES[m.extra.color as usize & 15]; + self.mobs[i].extra.sheared = true; + self.audio + .play("minecraft:entity.sheep.shear", Some(at), 1.0, 1.0); + let stacks = self.res.items.loot_table( + &format!("minecraft:shearing/sheep/{color}"), + false, + None, + &mut self.world.random, + ); + self.drop_sheared(at, stacks); + return Ok(true); + } + Species::Bogged if !m.extra.sheared => { + self.mobs[i].extra.sheared = true; + self.audio + .play("minecraft:entity.bogged.shear", Some(at), 1.0, 1.0); + let stacks = self.res.items.loot_table( + "minecraft:shearing/bogged", + false, + None, + &mut self.world.random, + ); + self.drop_sheared(at, stacks); + return Ok(true); + } + Species::Mooshroom if !m.is_baby() => { + let mushroom = if m.extra.variant == 1 { + "minecraft:brown_mushroom" + } else { + "minecraft:red_mushroom" + }; + let setup = SpawnSetup { + yaw: m.yaw, + persistent: true, + ..Default::default() + }; + self.mobs[i].removed = true; + self.audio + .play("minecraft:entity.mooshroom.shear", Some(at), 1.0, 1.0); + self.handle_mob_events(vec![MobEvent::SpawnKind { + kind: "minecraft:cow".into(), + at, + setup, + }])?; + for _ in 0..5 { + let v = [0.0, 0.2, 0.0]; + self.spawn_item( + ItemStack::new(mushroom, 1), + [at[0], at[1] + 1.0, at[2]], + v, + 10, + ); + } + return Ok(true); + } + _ => {} + } + } + Ok(false) + } + /// The drops of a sheared mob, one entity per item, a block above its feet. + fn drop_sheared(&mut self, at: [f64; 3], stacks: Vec) { + for stack in stacks { + for _ in 0..stack.count { + let r = &mut self.world.random; + let v = [ + f64::from((r.next_float() - r.next_float()) * 0.1), + f64::from(r.next_float() * 0.05), + f64::from((r.next_float() - r.next_float()) * 0.1), + ]; + let one = ItemStack { + count: 1, + ..stack.clone() + }; + self.spawn_item(one, [at[0], at[1] + 1.0, at[2]], v, 10); + } + } + } + /// A brush used on an adult armadillo in front. + fn dispense_brush(&mut self, pos: Pos, facing: Direction, stack: ItemStack) -> Dispensed { + let target = offset(pos, facing); + let armadillo = self.targets_at(target).into_iter().find_map(|t| match t { + Target::Mob(i) if self.mobs[i].species() == Species::Armadillo => Some(i), + _ => None, + }); + let Some(i) = armadillo.filter(|&i| !self.mobs[i].is_baby()) else { + return (Some(stack), FAIL); + }; + let m = &self.mobs[i]; + let at = [m.position.x, m.position.y, m.position.z]; + let drops = self.res.items.loot_table( + "minecraft:brush/armadillo", + false, + None, + &mut self.world.random, + ); + for d in drops { + self.spawn_item(d, [at[0], at[1] + 0.5, at[2]], [0.0, 0.2, 0.0], 10); + } + self.audio + .play("minecraft:entity.armadillo.brush", Some(at), 1.0, 1.0); + (self.hurt_and_break(stack, 16), CLICK) + } + fn dispense_honeycomb( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result { + let target = offset(pos, facing); + let state = self.block_at(target); + let name = self.dispenser_block_name(target); + // HoneycombItem.WAXABLES: each copper block has a waxed twin. + let waxed = name.strip_prefix("minecraft:").and_then(|n| { + if n.starts_with("waxed_") { + return None; + } + let twin = format!("minecraft:waxed_{n}"); + let mut s = self.res.assets.registry.state(state)?.clone(); + self.res.assets.registry.default_state(&twin)?; + s.name = twin; + self.res.assets.registry.resolve(&s).ok() + }); + let Some(waxed) = + waxed.filter(|_| name.contains("copper") || name.contains("lightning_rod")) + else { + return Ok((self.default_execute(pos, facing, stack), CLICK)); + }; + self.level_set([target.0, target.1, target.2], waxed)?; + self.audio.play( + "minecraft:item.honeycomb.wax_on", + Some(Self::center(target)), + 1.0, + 1.0, + ); + Ok((shrink(stack), CLICK)) + } + fn dispense_potion( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result { + let target = offset(pos, facing); + let water = stack.potion() == Some("minecraft:water"); + let name = self.dispenser_block_name(target); + if !water || !self.in_block_tag("minecraft:convertible_to_mud", &name) { + // The inner default behaviour dispenses, then the potion's own + // events play on top. + return Ok((self.dispense_default(pos, facing, stack), CLICK)); + } + for _ in 0..5 { + let r = self.particles.random(); + let p = [ + f64::from(pos.0) + r.next_double(), + f64::from(pos.1 + 1), + f64::from(pos.2) + r.next_double(), + ]; + self.particles + .add(&ParticleOptions::simple(ParticleType::Splash), p, [0.0; 3]); + } + self.audio.play( + "minecraft:item.bottle.empty", + Some(Self::center(pos)), + 1.0, + 1.0, + ); + if let Some(mud) = self.res.assets.registry.default_state("minecraft:mud") { + self.level_set([target.0, target.1, target.2], mud)?; + } + let bottle = ItemStack::new("minecraft:glass_bottle", 1); + Ok(( + self.consume_with_remainder(pos, facing, stack, bottle), + CLICK, + )) + } +} diff --git a/crates/horizon-client/src/game/fireworks.rs b/crates/horizon-client/src/game/fireworks.rs index c021842e8..2bd400d96 100644 --- a/crates/horizon-client/src/game/fireworks.rs +++ b/crates/horizon-client/src/game/fireworks.rs @@ -24,6 +24,9 @@ pub(super) struct Rocket { explosions: Vec, /// Boosting the player (attachedToEntity). attached: bool, + /// `DATA_SHOT_AT_ANGLE` (dispensers): constant velocity, exploding on + /// the first block it hits. + angled: bool, icon: Option, } fn fireworks_of(stack: &ItemStack) -> (u8, Vec) { @@ -52,6 +55,7 @@ impl Game<'_> { lifetime, explosions, attached, + angled: false, icon: Some("item/firework_rocket".into()), } } @@ -73,6 +77,13 @@ impl Game<'_> { self.swing_arm(); true } + /// `FireworkRocketItem.asProjectile` shot out of a dispenser. + pub(super) fn launch_dispensed_rocket(&mut self, at: Vec3, velocity: Vec3, stack: &ItemStack) { + let mut rocket = self.new_rocket(at, stack, false); + rocket.velocity = velocity; + rocket.angled = true; + self.rockets.push(rocket); + } /// `FireworkRocketItem.use` while gliding: a rocket attached to the player. pub(super) fn boost_firework(&mut self, stack: &ItemStack) -> bool { if &*stack.item != "minecraft:firework_rocket" @@ -118,12 +129,23 @@ impl Game<'_> { Vec3::new(r.position.x - h, r.position.y, r.position.z - h), Vec3::new(r.position.x + h, r.position.y + 2.0 * h, r.position.z + h), ); - let wanted = Vec3::new( - r.velocity.x * 1.15, - r.velocity.y + 0.04, - r.velocity.z * 1.15, - ); + let wanted = if r.angled { + r.velocity + } else { + Vec3::new( + r.velocity.x * 1.15, + r.velocity.y + 0.04, + r.velocity.z * 1.15, + ) + }; if let Ok(moved) = scene.resolve(bounds, wanted, 0.0, false) { + let blocked = (moved.x - wanted.x).abs() > 1e-7 + || (moved.y - wanted.y).abs() > 1e-7 + || (moved.z - wanted.z).abs() > 1e-7; + if r.angled && blocked { + // hitTargetOrDeflectSelf: explode on the block. + r.life = r.lifetime; + } let horizontal = (moved.x - wanted.x).abs() > 1e-7 || (moved.z - wanted.z).abs() > 1e-7; r.position = Vec3::new( diff --git a/crates/horizon-client/src/game/golems.rs b/crates/horizon-client/src/game/golems.rs new file mode 100644 index 000000000..7287c51bd --- /dev/null +++ b/crates/horizon-client/src/game/golems.rs @@ -0,0 +1,82 @@ +//! Building golems from blocks (`CarvedPumpkinBlock.trySpawnGolem`): a carved +//! pumpkin or jack o'lantern on two snow blocks makes a snow golem, and on a +//! T of four iron blocks (arms along X or Z, nothing beside the legs) an iron +//! golem. Players placing the pumpkin and dispensers share it. +use super::Game; +use horizon_client::Result; + +impl Game<'_> { + fn golem_block(&self, p: [i32; 3]) -> &str { + let state = self.world.block(p[0], p[1], p[2]); + &self.res.facts.get(state).name + } + fn is_golem_head(&self, p: [i32; 3]) -> bool { + matches!( + self.golem_block(p), + "minecraft:carved_pumpkin" | "minecraft:jack_o_lantern" + ) + } + /// The blocks of the golem whose head is at `head` and its spawn base + /// (`BlockPattern.find`), snow golems first. + fn find_golem(&self, head: [i32; 3]) -> Option<(&'static str, Vec<[i32; 3]>, [i32; 3])> { + let below = |n: i32| [head[0], head[1] - n, head[2]]; + if self.golem_block(below(1)) == "minecraft:snow_block" + && self.golem_block(below(2)) == "minecraft:snow_block" + { + return Some(( + "minecraft:snow_golem", + vec![head, below(1), below(2)], + below(2), + )); + } + for (ax, az) in [(1, 0), (0, 1)] { + let side = |s: i32, row: i32| [head[0] + ax * s, head[1] - row, head[2] + az * s]; + let arms = (-1..=1).all(|s| self.golem_block(side(s, 1)) == "minecraft:iron_block"); + let air = |p: [i32; 3]| self.res.facts.is_air(self.world.block(p[0], p[1], p[2])); + if arms + && self.golem_block(side(0, 2)) == "minecraft:iron_block" + && [-1, 1].iter().all(|&s| air(side(s, 0)) && air(side(s, 2))) + { + let mut blocks = vec![head]; + blocks.extend((-1..=1).map(|s| side(s, 1))); + blocks.push(side(0, 2)); + return Some(("minecraft:iron_golem", blocks, side(0, 2))); + } + } + None + } + /// `CarvedPumpkinBlock.canSpawnGolem`. + pub(super) fn can_spawn_golem(&self, head: [i32; 3]) -> bool { + self.find_golem(head).is_some() + } + /// `CarvedPumpkinBlock.trySpawnGolem`, after a pumpkin was placed. + pub(super) fn check_golem_spawn(&mut self, head: [i32; 3]) -> Result<()> { + if !self.is_golem_head(head) { + return Ok(()); + } + let Some((kind, blocks, base)) = self.find_golem(head) else { + return Ok(()); + }; + for p in blocks { + let state = self.world.block(p[0], p[1], p[2]); + self.destroy_particles(p, state); + self.level_set(p, self.world.air)?; + } + let at = [ + f64::from(base[0]) + 0.5, + f64::from(base[1]) + 0.05, + f64::from(base[2]) + 0.5, + ]; + if let Some(id) = self.spawn_mob(kind, at, false) + && let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) + { + m.yaw = 0.0; + m.body_yaw = 0.0; + m.head_yaw = 0.0; + m.previous_yaw = 0.0; + m.previous_body_yaw = 0.0; + m.previous_head_yaw = 0.0; + } + Ok(()) + } +} diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index 835056c09..1ad1d1cec 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -6,15 +6,10 @@ use super::Game; use horizon_client::{ Result, containers::BlockEntity, - entities::Arrow, items::{ItemStack, Items}, world::World, }; -use horizon_core::{ - geometry::{Direction, Vec3}, - position::BlockPos, - random::{LegacyRandom, RandomSource}, -}; +use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource}; use horizon_world::{level::Behaviours, registry::BlockStateId}; type Pos = (i32, i32, i32); @@ -72,11 +67,6 @@ impl View { } } -thread_local! { - /// Entity-owned randomness (projectile spread), separate from the level random. - static ENTITY_RANDOM: std::cell::RefCell = std::cell::RefCell::new(LegacyRandom::new(0x0d15_7e45)); -} - fn dir_from_name(name: &str) -> Option { Some(match name { "down" => Direction::Down, @@ -585,14 +575,8 @@ impl Game<'_> { odds += 1; } } - let center = [ - f64::from(pos.x) + 0.5, - f64::from(pos.y) + 0.5, - f64::from(pos.z) + 0.5, - ]; let Some(slot) = slot else { - self.audio - .play("minecraft:block.dispenser.fail", Some(center), 1.0, 1.2); + self.dispenser_event(1001, key, 0); return Ok(()); }; let Some(facing) = self @@ -608,7 +592,7 @@ impl Game<'_> { let target = offset(key, facing); let remaining = if dropper { match self.containers().view(target, false) { - None => self.default_dispense(key, facing, stack), + None => self.dispense_default(key, facing, stack), Some(into) => { let one = ItemStack { count: 1, @@ -630,7 +614,7 @@ impl Game<'_> { } } } else { - self.dispense_behaviour(key, facing, stack)? + self.dispense_item(key, facing, stack)? }; if let Some(entry) = self.slot_mut_at(&view, slot) { *entry = remaining; @@ -638,367 +622,6 @@ impl Game<'_> { self.container_changed(key); Ok(()) } - /// `DefaultDispenseItemBehavior.dispense`: drop one item, click and smoke. - fn default_dispense( - &mut self, - pos: Pos, - facing: Direction, - mut stack: ItemStack, - ) -> Option { - let one = ItemStack { - count: 1, - ..stack.clone() - }; - stack.count -= 1; - self.spawn_dispensed(pos, facing, one, 6); - self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0); - (stack.count > 0).then_some(stack) - } - fn dispenser_sound(&mut self, pos: Pos, sound: &str, pitch: f32) { - let center = [ - f64::from(pos.0) + 0.5, - f64::from(pos.1) + 0.5, - f64::from(pos.2) + 0.5, - ]; - self.audio.play(sound, Some(center), 1.0, pitch); - } - /// `DefaultDispenseItemBehavior.spawnItem` at `DispenserBlock.getDispensePosition`. - fn spawn_dispensed(&mut self, pos: Pos, facing: Direction, stack: ItemStack, accuracy: i32) { - let s = step(facing); - let mut at = [ - f64::from(pos.0) + 0.5 + 0.7 * f64::from(s[0]), - f64::from(pos.1) + 0.5 + 0.7 * f64::from(s[1]), - f64::from(pos.2) + 0.5 + 0.7 * f64::from(s[2]), - ]; - at[1] -= if s[1] != 0 { 0.125 } else { 0.156_25 }; - let r = &mut self.world.random; - // new ItemEntity(level, x, y, z, stack): its default motion draws first. - let _ = (r.next_double(), r.next_double()); - let pow = r.next_double() * 0.1 + 0.2; - let spread = 0.017_227_5 * f64::from(accuracy); - let v = [ - r.triangle(f64::from(s[0]) * pow, spread), - r.triangle(0.2, spread), - r.triangle(f64::from(s[2]) * pow, spread), - ]; - self.spawn_item(stack, at, v, 0); - } - /// `DefaultDispenseItemBehavior.consumeWithRemainder`. - fn consume_with_remainder( - &mut self, - pos: Pos, - facing: Direction, - mut stack: ItemStack, - remainder: ItemStack, - ) -> Option { - stack.count -= 1; - if stack.count == 0 { - return Some(remainder); - } - // DispenserBlockEntity.insertItem, then drop what does not fit. - let mut rest = remainder; - if let Some(view) = self.containers().view(pos, false) { - let max = self.containers().max_stack(&rest); - for i in 0..view.len() { - let Some(entry) = self.slot_mut_at(&view, i) else { - continue; - }; - match entry { - None => { - let n = rest.count.min(max); - *entry = Some(ItemStack { - count: n, - ..rest.clone() - }); - rest.count -= n; - } - Some(e) if e.item == rest.item && e.damage == rest.damage => { - let n = rest.count.min(max.saturating_sub(e.count)); - e.count += n; - rest.count -= n; - } - Some(_) => {} - } - if rest.count == 0 { - break; - } - } - } - if rest.count > 0 { - self.spawn_dispensed(pos, facing, rest, 6); - self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0); - } - Some(stack) - } - /// `DispenserBlock.getDispenseMethod(..).dispense(source, stack)`. - fn dispense_behaviour( - &mut self, - pos: Pos, - facing: Direction, - stack: ItemStack, - ) -> Result> { - let target = offset(pos, facing); - let target_pos = BlockPos::new(target.0, target.1, target.2); - let item = stack.item.to_string(); - let result = match item.as_str() { - "minecraft:bone_meal" => { - let grown = self.with_level(|b, level, ticks| { - b.grow_crop(level, ticks, target_pos) - || b.grow_water_plant(level, ticks, target_pos, None) - }); - self.process_level_events()?; - if grown { - self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0); - self.audio.play( - "minecraft:item.bone_meal.use", - Some([ - f64::from(target.0) + 0.5, - f64::from(target.1) + 0.5, - f64::from(target.2) + 0.5, - ]), - 1.0, - 1.0, - ); - Some(ItemStack { - count: stack.count - 1, - ..stack - }) - .filter(|s| s.count > 0) - } else { - self.dispenser_sound(pos, "minecraft:block.dispenser.fail", 1.2); - Some(stack) - } - } - "minecraft:tnt" => { - self.spawn_primed_tnt(target_pos, false); - self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0); - Some(ItemStack { - count: stack.count - 1, - ..stack - }) - .filter(|s| s.count > 0) - } - "minecraft:flint_and_steel" => { - let target_state = self.world.block(target.0, target.1, target.2); - let target_name = self.res.facts.get(target_state).name.clone(); - let fire = self.res.assets.registry.default_state("minecraft:fire"); - let success = if self.res.facts.is_air(target_state) - && let Some(fire) = fire - && self - .with_level(|b, level, ticks| b.can_survive(level, ticks, target_pos, fire)) - { - self.level_set([target.0, target.1, target.2], fire)?; - true - } else if &*target_name == "minecraft:tnt" { - self.spawn_primed_tnt(target_pos, false); - self.with_level(|b, level, ticks| { - b.remove_block(level, ticks, target_pos, false) - }); - self.process_level_events()?; - true - } else if self.containers().prop(target_state, "lit") == Some("false") - && (target_name.contains("campfire") || target_name.contains("candle")) - && self.containers().prop(target_state, "waterlogged") != Some("true") - { - let lit = self - .res - .assets - .registry - .state(target_state) - .cloned() - .and_then(|mut s| { - s.properties.insert("lit".into(), "true".into()); - self.res.assets.registry.resolve(&s).ok() - }); - if let Some(lit) = lit { - self.level_set([target.0, target.1, target.2], lit)?; - } - true - } else { - false - }; - self.dispenser_sound( - pos, - if success { - "minecraft:block.dispenser.dispense" - } else { - "minecraft:block.dispenser.fail" - }, - if success { 1.0 } else { 1.2 }, - ); - let mut stack = stack; - if success { - stack.damage += 1; - let max = self.res.items.get(&stack.item).map_or(0, |i| i.max_damage); - if max > 0 && stack.damage >= max { - return Ok(None); - } - } - Some(stack) - } - "minecraft:water_bucket" | "minecraft:lava_bucket" => { - let fluid = if item == "minecraft:water_bucket" { - "minecraft:water" - } else { - "minecraft:lava" - }; - let target_state = self.world.block(target.0, target.1, target.2); - let f = self.res.facts.get(target_state).clone(); - let waterloggable = item == "minecraft:water_bucket" - && self.containers().prop(target_state, "waterlogged") == Some("false"); - if waterloggable { - let wet = self - .res - .assets - .registry - .state(target_state) - .cloned() - .and_then(|mut s| { - s.properties.insert("waterlogged".into(), "true".into()); - self.res.assets.registry.resolve(&s).ok() - }); - if let Some(wet) = wet { - self.level_set([target.0, target.1, target.2], wet)?; - } - self.consume_with_remainder( - pos, - facing, - stack, - ItemStack { - item: "minecraft:bucket".into(), - count: 1, - damage: 0, - extra: None, - }, - ) - } else if (self.res.facts.is_air(target_state) || f.replaceable) - && !(f.fluid_level == 8 && !f.fluid_falling && &*f.name == fluid) - && let Some(source) = self.res.assets.registry.default_state(fluid) - { - self.level_set([target.0, target.1, target.2], source)?; - let sound = if fluid == "minecraft:water" { - "minecraft:item.bucket.empty" - } else { - "minecraft:item.bucket.empty_lava" - }; - self.audio.play( - sound, - Some([ - f64::from(target.0) + 0.5, - f64::from(target.1) + 0.5, - f64::from(target.2) + 0.5, - ]), - 1.0, - 1.0, - ); - self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0); - self.consume_with_remainder( - pos, - facing, - stack, - ItemStack { - item: "minecraft:bucket".into(), - count: 1, - damage: 0, - extra: None, - }, - ) - } else { - self.default_dispense(pos, facing, stack) - } - } - "minecraft:bucket" => { - let target_state = self.world.block(target.0, target.1, target.2); - let f = self.res.facts.get(target_state).clone(); - let picked = if f.waterlogged - && self.containers().prop(target_state, "waterlogged") == Some("true") - { - let dry = self - .res - .assets - .registry - .state(target_state) - .cloned() - .and_then(|mut s| { - s.properties.insert("waterlogged".into(), "false".into()); - self.res.assets.registry.resolve(&s).ok() - }); - if let Some(dry) = dry { - self.level_set([target.0, target.1, target.2], dry)?; - } - Some("minecraft:water_bucket") - } else if f.fluid_level == 8 - && !f.fluid_falling - && matches!(&*f.name, "minecraft:water" | "minecraft:lava") - { - self.level_set([target.0, target.1, target.2], self.world.air)?; - Some(if &*f.name == "minecraft:water" { - "minecraft:water_bucket" - } else { - "minecraft:lava_bucket" - }) - } else if &*f.name == "minecraft:powder_snow" { - self.level_set([target.0, target.1, target.2], self.world.air)?; - Some("minecraft:powder_snow_bucket") - } else { - None - }; - match picked { - Some(filled) => { - self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0); - self.consume_with_remainder( - pos, - facing, - stack, - ItemStack { - item: filled.into(), - count: 1, - damage: 0, - extra: None, - }, - ) - } - None => self.default_dispense(pos, facing, stack), - } - } - "minecraft:arrow" | "minecraft:spectral_arrow" | "minecraft:tipped_arrow" => { - // ProjectileDispenseBehavior: power 1.1, uncertainty 6, from 0.7 ahead and 0.1 up. - let s = step(facing); - let at = Vec3::new( - f64::from(pos.0) + 0.5 + 0.7 * f64::from(s[0]), - f64::from(pos.1) + 0.5 + 0.7 * f64::from(s[1]) + 0.1, - f64::from(pos.2) + 0.5 + 0.7 * f64::from(s[2]), - ); - let spread = 0.017_227_5 * 6.0; - let v = ENTITY_RANDOM.with(|r| { - let r = &mut *r.borrow_mut(); - [ - (f64::from(s[0]) + r.triangle(0.0, spread)) * 1.1, - (f64::from(s[1]) + r.triangle(0.0, spread)) * 1.1, - (f64::from(s[2]) + r.triangle(0.0, spread)) * 1.1, - ] - }); - self.arrows.push(Arrow { - from_player: true, - critical: false, - position: at, - previous: at, - velocity: Vec3::new(v[0], v[1], v[2]), - stuck: false, - age: 0, - base_damage: 2.0, - }); - self.dispenser_sound(pos, "minecraft:block.dispenser.launch", 1.2); - Some(ItemStack { - count: stack.count - 1, - ..stack - }) - .filter(|s| s.count > 0) - } - _ => self.default_dispense(pos, facing, stack), - }; - Ok(result) - } } // ---- hopper, dispenser and dropper screens ---- diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 259758994..26b085560 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -90,7 +90,7 @@ const SEAT: f64 = 0.1875 - 0.6; pub(super) const CART_KEY_Y: i32 = -100_000; #[derive(Clone, Copy, PartialEq, Eq, Debug)] -enum Shape { +pub(super) enum Shape { NorthSouth, EastWest, AscendingEast, @@ -117,7 +117,7 @@ impl Shape { _ => Self::NorthSouth, } } - fn is_slope(self) -> bool { + pub(super) fn is_slope(self) -> bool { matches!( self, Self::AscendingEast | Self::AscendingWest | Self::AscendingNorth | Self::AscendingSouth @@ -141,9 +141,9 @@ impl Shape { } } } -struct Rail { +pub(super) struct Rail { name: Arc, - shape: Shape, + pub(super) shape: Shape, powered: bool, } impl Minecart { @@ -203,7 +203,7 @@ impl CartModels { } } impl Game<'_> { - fn rail(&self, x: i32, y: i32, z: i32) -> Option { + pub(super) fn rail(&self, x: i32, y: i32, z: i32) -> Option { let state = self.world.block(x, y, z); let name = self.res.facts.get(state).name.clone(); if !matches!( diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index ffa2c86da..53f9afe02 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -19,6 +19,18 @@ pub(super) struct ThrownPotion { velocity: Vec3, age: u32, } +impl Game<'_> { + /// A splash potion, lingering potion or experience bottle in flight (the + /// player's throws and dispensers both end up here). + pub(super) fn launch_thrown(&mut self, stack: ItemStack, position: Vec3, velocity: Vec3) { + self.potions.thrown.push(ThrownPotion { + stack, + position, + velocity, + age: 0, + }); + } +} /// Effects, thrown potions and the attribute modifiers last applied. #[derive(Default)] pub(super) struct PotionState { @@ -46,15 +58,19 @@ impl Game<'_> { } Ok(true) } - "minecraft:splash_potion" | "minecraft:lingering_potion" => { + "minecraft:splash_potion" + | "minecraft:lingering_potion" + | "minecraft:experience_bottle" => { let Some(eye) = self.eye_position() else { return Ok(true); }; let pitch = 0.4 / (self.world.random.next_float() * 0.4 + 0.8); - let sound = if &*stack.item == "minecraft:splash_potion" { - "minecraft:entity.splash_potion.throw" - } else { - "minecraft:entity.lingering_potion.throw" + let (sound, power) = match &*stack.item { + "minecraft:splash_potion" => ("minecraft:entity.splash_potion.throw", 0.5), + "minecraft:experience_bottle" => { + ("minecraft:entity.experience_bottle.throw", 0.7) + } + _ => ("minecraft:entity.lingering_potion.throw", 0.5), }; self.audio.play(sound, Some(eye), 0.5, pitch); // Projectile.shootFromRotation(xRot, yRot, -20, 0.5, 1.0). @@ -74,9 +90,9 @@ impl Game<'_> { let r = &mut self.world.random; let mut jitter = || r.triangle(0.0, 0.0172275); let v = Vec3::new( - (f64::from(dir[0]) / l + jitter()) * 0.5, - (f64::from(dir[1]) / l + jitter()) * 0.5, - (f64::from(dir[2]) / l + jitter()) * 0.5, + (f64::from(dir[0]) / l + jitter()) * power, + (f64::from(dir[1]) / l + jitter()) * power, + (f64::from(dir[2]) / l + jitter()) * power, ); let pv = self.player.as_ref().map_or(Vec3::ZERO, |p| p.velocity); let on_ground = self.player.as_ref().is_some_and(|p| p.ground.on_ground); @@ -85,15 +101,14 @@ impl Game<'_> { v.y + if on_ground { 0.0 } else { pv.y }, v.z + pv.z, ); - self.potions.thrown.push(ThrownPotion { - stack: ItemStack { + self.launch_thrown( + ItemStack { count: 1, ..stack.clone() }, - position: Vec3::new(eye[0], eye[1] - 0.1, eye[2]), - velocity: v, - age: 0, - }); + Vec3::new(eye[0], eye[1] - 0.1, eye[2]), + v, + ); self.swing_arm(); self.consume_held(); Ok(true) @@ -326,19 +341,25 @@ impl Game<'_> { } t.position = next; // ThrowableItemProjectile: drag 0.99 then gravity 0.05. + // ThrownExperienceBottle.getDefaultGravity is 0.07. + let gravity = if &*t.stack.item == "minecraft:experience_bottle" { + 0.07 + } else { + 0.05 + }; t.velocity = Vec3::new( t.velocity.x * 0.99, - t.velocity.y * 0.99 - 0.05, + t.velocity.y * 0.99 - gravity, t.velocity.z * 0.99, ); t.age < 1200 && t.position.y > -128.0 }); // ThrownItemRenderer stand-in: a short-lived sprite of the potion at its position. for t in &thrown { - let sprite = if &*t.stack.item == "minecraft:lingering_potion" { - "item/lingering_potion" - } else { - "item/splash_potion" + let sprite = match &*t.stack.item { + "minecraft:lingering_potion" => "item/lingering_potion", + "minecraft:experience_bottle" => "item/experience_bottle", + _ => "item/splash_potion", }; let mut fixed = horizon_core::random::LegacyRandom::new(0); let mut p = horizon_client::particles::Particle::terrain( @@ -362,6 +383,36 @@ impl Game<'_> { } /// `ThrownSplashPotion.onHitAsPotion` (lingering clouds apply as a weaker splash). fn splash(&mut self, stack: &ItemStack, at: Vec3) { + if &*stack.item == "minecraft:experience_bottle" { + // ThrownExperienceBottle.onHit: the water-coloured splash (level + // event 2002) and 3 to 11 experience. + let pitch = self.world.random.next_float() * 0.1 + 0.9; + self.audio.play( + "minecraft:entity.splash_potion.break", + Some([at.x, at.y, at.z]), + 1.0, + pitch, + ); + for _ in 0..8 { + let v = [ + f64::from(self.world.random.next_float() - 0.5) * 0.3, + 0.2, + f64::from(self.world.random.next_float() - 0.5) * 0.3, + ]; + let p = horizon_client::particles::Particle::terrain( + &mut self.world.random, + [at.x, at.y, at.z], + v, + "item/splash_potion".into(), + 0x38_5DC6, + ); + self.particles.push(p); + } + let r = &mut self.world.random; + let value = 3 + r.next_int_bound(5).unwrap_or(0) + r.next_int_bound(5).unwrap_or(0); + self.spawn_orbs([at.x, at.y, at.z], value as u32); + return; + } let lingering = &*stack.item == "minecraft:lingering_potion"; let event = if lingering { "minecraft:entity.lingering_potion.break" diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index eff648db2..c7eb83aae 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -53,6 +53,10 @@ pub struct ItemInfo { pub glider: bool, /// `equippable.swappable` and `equip_sound`. pub swappable: bool, + /// `equippable.dispensable` (dispensers may put it on an entity). + pub equip_dispensable: bool, + /// `equippable.allowed_entities` resolved to entity type ids; None allows all. + pub equip_allowed: Option>, pub equip_sound: Option, /// `jukebox_playable`: the jukebox song it plays. pub jukebox_song: Option, @@ -251,6 +255,13 @@ pub(crate) fn load_tags(root: &Path, kind: &str) -> Result>, spec: &str) -> HashSet { + match spec.strip_prefix('#') { + Some(tag) => tags.get(tag).cloned().unwrap_or_default(), + None => HashSet::from([spec.to_owned()]), + } +} impl Items { pub fn load(root: &Path, registry: &BlockRegistry, facts: &BlockFacts) -> Result { let raw: BTreeMap = @@ -264,6 +275,7 @@ impl Items { .or_insert(BlockStateId(i as u32)); } } + let entity_tags = load_tags(root, "entity_type")?; let mut items = HashMap::new(); let mut order = Vec::new(); for (name, c) in &raw { @@ -323,6 +335,19 @@ impl Items { swappable: c["minecraft:equippable"]["swappable"] .as_bool() .unwrap_or(true), + equip_dispensable: c["minecraft:equippable"]["dispensable"] + .as_bool() + .unwrap_or(true), + equip_allowed: match &c["minecraft:equippable"]["allowed_entities"] { + Value::String(spec) => Some(entity_spec(&entity_tags, spec)), + Value::Array(list) => Some( + list.iter() + .filter_map(Value::as_str) + .flat_map(|spec| entity_spec(&entity_tags, spec)) + .collect(), + ), + _ => None, + }, equip_sound: c["minecraft:equippable"]["equip_sound"] .as_str() .map(str::to_owned), diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index a15b1e1c6..24dafbf94 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -433,6 +433,8 @@ pub struct Extra { /// Dye colour id (sheep wool, collars). pub color: u8, pub sheared: bool, + /// `Mob.canPickUpLoot` (also lets dispensers equip it). + pub pick_up_loot: bool, pub saddled: bool, pub chested: bool, pub tame: bool, diff --git a/crates/horizon-client/src/mobs/spawning.rs b/crates/horizon-client/src/mobs/spawning.rs index 1138649b2..266d5baa1 100644 --- a/crates/horizon-client/src/mobs/spawning.rs +++ b/crates/horizon-client/src/mobs/spawning.rs @@ -299,7 +299,9 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) { S::Wolf => m.extra.variant = biome.wolf, S::Cat => m.extra.variant = super::tame::cat_variant(m, biome.full_moon), S::Zombie | S::Husk | S::Drowned | S::ZombieVillager => { - // Zombie.finalizeSpawn: 5% babies (normal difficulty). + // Zombie.finalizeSpawn: pick up loot 55% of the time (scaled by + // difficulty), 5% babies (normal difficulty). + m.extra.pick_up_loot = m.random.next_float() < 0.55 * difficulty.special(); if m.random.next_float() < 0.05 { m.extra.age = i32::MIN / 2; } @@ -348,8 +350,14 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) { } // AbstractSkeleton.populateDefaultEquipmentSlots (the bow is given on // registration). - S::Skeleton | S::Stray | S::Bogged | S::Parched => populate_armor(m, difficulty), - S::Pillager => m.extra.main_hand = Some("minecraft:crossbow".into()), + S::Skeleton | S::Stray | S::Bogged | S::Parched => { + populate_armor(m, difficulty); + m.extra.pick_up_loot = m.random.next_float() < 0.55 * difficulty.special(); + } + S::Pillager => { + m.extra.main_hand = Some("minecraft:crossbow".into()); + m.extra.pick_up_loot = true; + } S::Horse | S::Donkey | S::Mule | S::SkeletonHorse | S::ZombieHorse => { super::equine::finalize(m) } @@ -358,6 +366,7 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) { // Piglin.createSpawnWeapon: half crossbows, half golden swords, and // each piece of golden armour one time in ten. S::Piglin if !m.is_baby() => { + m.extra.pick_up_loot = true; for i in 0..4 { if m.random.next_float() < 0.1 { let (slot, piece) = match i { @@ -379,11 +388,16 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) { .into(), ); } - S::PiglinBrute => m.extra.main_hand = Some("minecraft:golden_axe".into()), + S::PiglinBrute => { + m.extra.main_hand = Some("minecraft:golden_axe".into()); + m.extra.pick_up_loot = true; + } S::Vindicator => m.extra.main_hand = Some("minecraft:iron_axe".into()), S::Villager => { m.extra.variant = villager_type(biome); + m.extra.pick_up_loot = true; } + S::Fox | S::Panda | S::Dolphin => m.extra.pick_up_loot = true, S::TropicalFish => super::aquatic::finalize(m), S::Slime | S::MagmaCube => super::cube::finalize(m), _ => {} diff --git a/crates/horizon-world/src/level/buckets.rs b/crates/horizon-world/src/level/buckets.rs new file mode 100644 index 000000000..8fe4907a9 --- /dev/null +++ b/crates/horizon-world/src/level/buckets.rs @@ -0,0 +1,146 @@ +//! Dispenser use of buckets: `BucketPickup.pickupBlock` for an empty bucket and +//! `DispensibleContainerItem.emptyContents` for filled ones (`BucketItem`, +//! `MobBucketItem`, `SolidBucketItem`), both without a player. +use super::{ + Behaviours, Dimension, LevelAccess, Sim, Ticks, + classes::{Class, Interface}, +}; +use crate::{ + fluid::{FluidKind, FluidState}, + registry::BlockStateId, +}; +use horizon_core::{position::BlockPos, random::RandomSource}; +use std::sync::Arc; + +/// What a filled bucket empties into the world. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BucketContent { + /// Water or lava (mob buckets hold water). + Fluid(FluidKind), + /// `SolidBucketItem`: the block placed into an empty space (powder snow). + Powder, +} + +impl Sim<'_, L> { + /// `BucketPickup.pickupBlock(null, level, pos, state)`: the filled bucket + /// that results, None when the block gives nothing. + pub(crate) fn bucket_pickup(&mut self, pos: BlockPos) -> Option<&'static str> { + let b = self.b; + let state = self.state(pos); + let item = if b.instance_of(state, Class::Liquid) { + match b.fluid(state).kind() { + FluidKind::Water | FluidKind::FlowingWater => "minecraft:water_bucket", + FluidKind::Lava | FluidKind::FlowingLava => "minecraft:lava_bucket", + FluidKind::Empty => return None, + } + } else if b.implements(state, Interface::SimpleWaterlogged) + && b.table.has(state, b.props.waterlogged) + { + "minecraft:water_bucket" + } else if b.is_block(state, b.named.powder_snow) { + "minecraft:powder_snow_bucket" + } else { + return None; + }; + self.pickup_block(pos, state).then_some(item) + } + /// `BucketItem.emptyContents(null, level, pos, null)`. `sound` is the + /// bucket's empty sound (mob buckets have their own). + pub(crate) fn bucket_empty( + &mut self, + pos: BlockPos, + content: BucketContent, + sound: &str, + ) -> bool { + let b = self.b; + let fluid = match content { + BucketContent::Powder => { + if self.is_in_valid_bounds(pos) && b.is_air(self.state(pos)) { + let snow = b.table.default_state(b.named.powder_snow); + self.set_block_and_update(pos, snow); + self.game_event(pos, "minecraft:fluid_place"); + self.empty_sound(pos, sound); + return true; + } + return false; + } + BucketContent::Fluid(fluid) => fluid, + }; + let state = self.state(pos); + // canBeReplaced(fluid): replaceable or not solid (portals refuse). + let may_replace = !b.instance_of(state, Class::EndPortal) + && !b.instance_of(state, Class::EndGateway) + && (b.is_replaceable(state) || !b.is_solid(state)); + let liquid_container = self.is_liquid_container(state); + let container = liquid_container && self.can_place_liquid(state, fluid); + let place_liquid = may_replace || container; + if !(b.is_air(state) || place_liquid) { + return false; + } + let water = matches!(fluid, FluidKind::Water | FluidKind::FlowingWater); + if water && self.level.dimension() == Dimension::Nether { + // WATER_EVAPORATES: the water hisses away. + let pitch = 2.6 + (self.random().next_float() - self.random().next_float()) * 0.8; + self.emit(super::LevelEvent::Sound { + pos, + sound: "minecraft:block.fire.extinguish".into(), + volume: 0.5, + pitch, + }); + return true; + } + if liquid_container && water { + self.place_liquid(pos, state, FluidState::new(FluidKind::Water, 8, false)); + self.empty_sound(pos, sound); + return true; + } + if may_replace && !b.instance_of(state, Class::Liquid) { + self.destroy_block(pos, true, super::flags::UPDATE_LIMIT); + } + let source = FluidState::new( + if water { + FluidKind::Water + } else { + FluidKind::Lava + }, + 8, + false, + ); + let legacy: BlockStateId = b.legacy_block(source); + if !self.set_block(pos, legacy, super::flags::UPDATE_ALL_IMMEDIATE) + && !self.fluid_at(pos).is_source() + { + return false; + } + self.empty_sound(pos, sound); + true + } + fn empty_sound(&mut self, pos: BlockPos, sound: &str) { + let sound: Arc = sound.into(); + self.sound(pos, &sound, 1.0, 1.0); + self.game_event(pos, "minecraft:fluid_place"); + } +} + +impl Behaviours { + /// `BucketPickup.pickupBlock` by a dispenser: the filled bucket item. + pub fn bucket_pickup( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + ) -> Option<&'static str> { + self.sim(level, ticks).bucket_pickup(pos) + } + /// `DispensibleContainerItem.emptyContents(null, level, pos, null)`. + pub fn bucket_empty( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + content: BucketContent, + sound: &str, + ) -> bool { + self.sim(level, ticks).bucket_empty(pos, content, sound) + } +} diff --git a/crates/horizon-world/src/level/fluids.rs b/crates/horizon-world/src/level/fluids.rs index d1017fb34..b778f6511 100644 --- a/crates/horizon-world/src/level/fluids.rs +++ b/crates/horizon-world/src/level/fluids.rs @@ -178,7 +178,7 @@ impl Sim<'_, L> { // ---- liquid containers ---- /// `LiquidBlockContainer` membership (`canHoldAnyFluid` first clause). - fn is_liquid_container(&self, state: BlockStateId) -> bool { + pub(super) fn is_liquid_container(&self, state: BlockStateId) -> bool { self.b.implements(state, Interface::LiquidBlockContainer) || self.b.implements(state, Interface::SimpleWaterlogged) } diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 1a066cafc..1a05bbb11 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -101,6 +101,7 @@ pub mod states; pub mod ticks; mod bonemeal; +mod buckets; mod falling; mod feature_world; mod fluids; @@ -126,6 +127,7 @@ mod growth_tests; #[cfg(test)] mod tests; +pub use buckets::BucketContent; pub use data::{BlockData, ItemBinding, ItemKind, Named, Props, PushReaction, StateFacts, Tags}; pub use falling::Landing; pub use interact::{InteractionResult, PlayerContext, PlayerEffect}; diff --git a/crates/horizon-world/src/level/tests.rs b/crates/horizon-world/src/level/tests.rs index c1ffce5a1..28c9ac73d 100644 --- a/crates/horizon-world/src/level/tests.rs +++ b/crates/horizon-world/src/level/tests.rs @@ -917,3 +917,66 @@ fn dripstone_fills_cauldrons() { } assert_eq!(w.name(BlockPos::new(0, 5, 0)), "water_cauldron[level=1]"); } + +#[test] +fn dispenser_buckets_pick_up_and_empty() { + let mut w = world!(); + let at = BlockPos::new(0, 10, 0); + let water = w.id("water", &[("level", "0")]); + w.put(at, water); + let picked = w.b().bucket_pickup(&mut w.level, &mut w.ticks, at); + assert_eq!(picked, Some("minecraft:water_bucket")); + assert_eq!(w.get(at), w.b().air()); + // Flowing water gives nothing. + let flowing = w.id("water", &[("level", "3")]); + w.put(at, flowing); + assert_eq!(w.b().bucket_pickup(&mut w.level, &mut w.ticks, at), None); + // A waterlogged slab is drained and stays a slab. + let slab = w.id("oak_slab", &[("waterlogged", "true")]); + w.put(at, slab); + assert_eq!( + w.b().bucket_pickup(&mut w.level, &mut w.ticks, at), + Some("minecraft:water_bucket") + ); + assert_eq!(w.prop(at, "waterlogged"), "false"); + // Powder snow comes up as its bucket. + let snow = w.id("powder_snow", &[]); + w.put(at, snow); + assert_eq!( + w.b().bucket_pickup(&mut w.level, &mut w.ticks, at), + Some("minecraft:powder_snow_bucket") + ); + // Emptying water into air makes a source; stone refuses. + let sound = "minecraft:item.bucket.empty"; + let content = BucketContent::Fluid(crate::fluid::FluidKind::Water); + assert!( + w.b() + .bucket_empty(&mut w.level, &mut w.ticks, at, content, sound) + ); + assert_eq!(w.name(at), "water[level=0]"); + let stone = w.id("stone", &[]); + w.put(at, stone); + assert!( + !w.b() + .bucket_empty(&mut w.level, &mut w.ticks, at, content, sound) + ); + // Water fills a waterloggable slab instead of replacing it. + let dry = w.id("oak_slab", &[]); + w.put(at, dry); + assert!( + w.b() + .bucket_empty(&mut w.level, &mut w.ticks, at, content, sound) + ); + assert_eq!(w.prop(at, "waterlogged"), "true"); + // Powder snow only goes into empty space. + let air = w.b().air(); + w.put(at, air); + assert!(w.b().bucket_empty( + &mut w.level, + &mut w.ticks, + at, + BucketContent::Powder, + "minecraft:item.bucket.empty_powder_snow" + )); + assert_eq!(w.name(at), "powder_snow[]"); +} From 6b80f9c1aae8b89b9aefeac0fbb4da88a861fcd5 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:08:12 +0200 Subject: [PATCH 05/13] Add the recipe book The inventory, crafting table, furnace, blast furnace and smoker screens get the green recipe book button, which opens the book beside the menu and moves the menu over. The book has the search tab and one tab per category (hidden until it holds a recipe), a search box matching recipe names (or @namespace), the craftable-only toggle, pages of 20 recipe buttons that cycle through the recipes of a group, right-click for the alternatives overlay, and tooltips. Clicking a recipe moves the items from the inventory into the grid (shift fills the biggest stack, clicking again adds one more set), and when items are missing the grid is cleared and the recipe is shown as a ghost over the slots. Which recipes appear comes from the advancement rewards already unlocked; the open and craftable-only settings of each book and the unlocked recipes are saved in the player's recipeBook compound. Recipes now keep their category and group from the data pack. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/crafting.rs | 19 +- crates/horizon-client/src/game.rs | 21 +- crates/horizon-client/src/game/control.rs | 3 + crates/horizon-client/src/game/recipe_book.rs | 1221 +++++++++++++++++ crates/horizon-client/src/game/stations.rs | 5 + crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/recipe_book.rs | 685 +++++++++ crates/horizon-client/src/save.rs | 13 +- 8 files changed, 1965 insertions(+), 3 deletions(-) create mode 100644 crates/horizon-client/src/game/recipe_book.rs create mode 100644 crates/horizon-client/src/recipe_book.rs diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index c20f0bce9..aa434a556 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -146,6 +146,11 @@ impl Special { } #[derive(Clone, Debug)] pub struct Cooking { + /// The recipe's file name (its id without namespace). + pub id: String, + /// `category` (`food`, `blocks`, `misc`) and `group` of the recipe book. + pub category: String, + pub group: String, pub kind: String, pub ingredient: Ingredient, pub result: ItemStack, @@ -155,6 +160,8 @@ pub struct Cooking { pub struct Recipes { pub crafting: Vec<(String, Recipe)>, pub cooking: Vec, + /// `category` and `group` of each crafting recipe, by file name. + pub meta: std::collections::HashMap, } fn result(v: &Value) -> Option { Some(ItemStack { @@ -168,6 +175,7 @@ impl Recipes { pub fn load(root: &Path, items: &Items) -> Result { let mut crafting = Vec::new(); let mut cooking = Vec::new(); + let mut meta = std::collections::HashMap::new(); let mut files: Vec<_> = fs::read_dir(root.join("data/minecraft/recipe"))? .flatten() .map(|e| e.path()) @@ -181,6 +189,8 @@ impl Recipes { .unwrap_or("") .to_owned(); let v: Value = serde_json::from_slice(&fs::read(&path)?)?; + let text = |k: &str| v[k].as_str().unwrap_or("").to_owned(); + meta.insert(name.clone(), (text("category"), text("group"))); match v["type"].as_str().unwrap_or("") { "minecraft:crafting_shaped" => { let pattern: Vec> = v["pattern"] @@ -274,6 +284,9 @@ impl Recipes { result(&v["result"]), ) { cooking.push(Cooking { + id: name, + category: text("category"), + group: text("group"), kind: kind.to_owned(), ingredient, result, @@ -285,7 +298,11 @@ impl Recipes { _ => {} } } - Ok(Self { crafting, cooking }) + Ok(Self { + crafting, + cooking, + meta, + }) } /// Match a `size`x`size` grid (row-major) against the crafting recipes. pub fn craft(&self, grid: &[Option], size: usize) -> Option { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 02a649329..a252164e2 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -44,6 +44,7 @@ mod perspective; mod piglins; mod postprocess; mod potions; +mod recipe_book; mod remote; mod render_control; mod render_tick; @@ -611,6 +612,8 @@ struct Game<'a> { pending_shulker: HashMap<[i32; 3], Vec<(u8, ItemStack)>>, /// Layers of broken banners waiting for their dropped item. pending_banner: HashMap<[i32; 3], horizon_client::containers::Banner>, + /// The recipe book of the open screen (game/recipe_book.rs). + recipe_ui: recipe_book::RecipeUi, /// The player's fishing hook. hook: Option, tridents: Vec, @@ -3028,7 +3031,7 @@ impl Game<'_> { } fn inventory_origin(&self, batch: &HudBatch) -> (f32, f32) { ( - (batch.width - 176.0) / 2.0, + (batch.width - 176.0) / 2.0 + self.recipe_book_shift(batch.width), (batch.height - self.screen_height()) / 2.0, ) } @@ -3344,6 +3347,7 @@ impl Game<'_> { self.draw_item(batch, &stack, ox + sx, oy + sy); } } + self.draw_recipe_book(batch); if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (sx, sy) = self.slot_position(slot); batch.fill( @@ -3362,6 +3366,7 @@ impl Game<'_> { } pub(super) fn close_container(&mut self) { self.close_station(); + self.recipe_ui.reset_screen(); if self.remote.is_some() { return self.remote_close_container(); } @@ -3411,6 +3416,9 @@ impl Game<'_> { self.close_cart_container(); } fn click_inventory(&mut self, right: bool) { + if self.recipe_book_click(right) { + return; + } if self.station_click(right) { return; } @@ -6609,6 +6617,7 @@ impl Game<'_> { self.ender_items = items.clone(); } level.ender_items = self.ender_items.clone(); + level.recipe_book.recipes = self.adv.recipes.iter().cloned().collect(); level.active_effects = self .potions .effects @@ -6843,6 +6852,7 @@ impl Game<'_> { Screen::Advancements => self.close_advancements(), Screen::Chat => self.close_chat(), }, + KeyCode::KeyT if self.screen == Screen::Inventory => self.recipe_focus_search(), KeyCode::KeyT if self.screen == Screen::Playing => self.open_chat(""), // key.advancements. KeyCode::KeyL if self.screen == Screen::Playing => self.open_advancements(false), @@ -7277,6 +7287,14 @@ impl ApplicationHandler for Game<'_> { } self.creative_screen.scroll = 0.0; } + WindowEvent::KeyboardInput { event, .. } + if self.recipe_search_focused() + && event.state == ElementState::Pressed + && !matches!(event.physical_key, PhysicalKey::Code(KeyCode::Escape)) => + { + // The recipe book's search box takes every key but Escape. + self.recipe_key(&event); + } WindowEvent::KeyboardInput { event, .. } if self.station_typing() && event.state == ElementState::Pressed @@ -7718,6 +7736,7 @@ pub fn run() -> Result<()> { ender_open: None, pending_shulker: HashMap::new(), pending_banner: HashMap::new(), + recipe_ui: Default::default(), hook: None, tridents: Vec::new(), rockets: Vec::new(), diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 7c07af665..18d0e6b64 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -293,6 +293,9 @@ impl Game<'_> { match self.screen { Screen::Chat => self.chat_type(text), Screen::Options => self.ui.options.type_text(text), + Screen::Inventory if self.recipe_search_focused() => { + self.recipe_text(Some(text), false) + } _ => { return Err( "type needs the chat screen (key t tap) or the language search".into(), diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs new file mode 100644 index 000000000..d66b23e97 --- /dev/null +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -0,0 +1,1221 @@ +//! The recipe book of the inventory, crafting table and furnace screens +//! (`RecipeBookComponent`): the green book button, the tabs by category, the +//! search box, the craftable filter, the pages of recipe buttons with the +//! alternatives overlay, ghost recipes, and placing a recipe in the grid +//! (`ServerPlaceRecipe`). Which recipes are known comes from the advancement +//! rewards; the open and filter settings are saved with the player. +use super::{Game, Screen}; +use horizon_client::{ + containers::{BlockEntity, FurnaceKind}, + hud::{HudBatch, Rect, rgba}, + items::ItemStack, + recipe_book::{Available, Book, BookType, Collection, Display, Entry, Tab}, + ui::EditBox, +}; +use std::{ + collections::BTreeSet, + hash::{Hash, Hasher}, +}; + +const WIDTH: f32 = 147.0; +const HEIGHT: f32 = 166.0; +/// `RecipeBookComponent.TICKS_TO_SWAP_SLOT`. +const SWAP_TICKS: f32 = 30.0; +/// Widest GUI at which the book sits next to the menu (`widthTooNarrow`). +const NARROW: f32 = 379.0; + +/// A ghost recipe slot: the items it cycles through. +struct Ghost { + slot: usize, + items: Vec, + result: bool, +} +/// The alternatives overlay of a recipe button (`OverlayRecipeComponent`). +struct Overlay { + x: f32, + y: f32, + /// (entry index, craftable) + entries: Vec<(usize, bool)>, +} +/// One recipe button: the collection's recipes shown in the current view. +#[derive(Clone, Default)] +struct Button { + /// (entry index, craftable) + entries: Vec<(usize, bool)>, +} +impl Button { + fn craftable(&self) -> bool { + self.entries.iter().any(|e| e.1) + } +} +#[derive(Default)] +struct View { + /// Visible tabs. + tabs: Vec, + buttons: Vec