From 1c7a68da26f928670ff4ff6d606ccb0e3dd9a162 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:17:11 +0200 Subject: [PATCH] Add enchanting, anvil, grindstone, smithing, stonecutter and brewing stand menus Workstation menus follow the vanilla screens: slot layouts, sprites, the enchanting table's seeded offers with clues and galactic names, anvil rename/repair/combine costs, grindstone disenchanting with experience, smithing upgrades and trims, stonecutter recipe buttons, and the brewing stand block entity with data-driven recipes. Item tooltips show rarity, enchantments, potion effects and trims; enchanted items glint. horizon-ctl gains menu commands (use, click-slot, click-gui, type, xp, ...). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/brewing.rs | 432 ++++++ crates/horizon-client/src/containers.rs | 19 + crates/horizon-client/src/game.rs | 51 +- crates/horizon-client/src/game/control.rs | 7 +- .../src/game/station_control.rs | 150 ++ crates/horizon-client/src/game/stations.rs | 1215 +++++++++++++++++ crates/horizon-client/src/items.rs | 3 + crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/save.rs | 23 + crates/horizon-client/src/stations.rs | 12 + 10 files changed, 1906 insertions(+), 7 deletions(-) create mode 100644 crates/horizon-client/src/brewing.rs create mode 100644 crates/horizon-client/src/game/station_control.rs create mode 100644 crates/horizon-client/src/game/stations.rs diff --git a/crates/horizon-client/src/brewing.rs b/crates/horizon-client/src/brewing.rs new file mode 100644 index 000000000..8c809be11 --- /dev/null +++ b/crates/horizon-client/src/brewing.rs @@ -0,0 +1,432 @@ +//! Potions and the brewing stand: the `Potions` / `MobEffects` registries (code +//! in vanilla, ported as tables), data-driven `minecraft:brewing` recipes from +//! `data/minecraft/recipe/brewing`, potion colours and tooltips, and +//! `BrewingStandBlockEntity.serverTick`. +use crate::{ + containers::Providers, + items::{ItemStack, Items}, +}; +use serde_json::Value; +use std::{collections::HashSet, fs, path::Path, sync::Arc}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Category { + Beneficial, + Harmful, + Neutral, +} +/// A `MobEffect`: id (without namespace), colour, category, instantaneous. +#[derive(Clone, Copy, Debug)] +pub struct EffectDef { + pub id: &'static str, + pub color: u32, + pub category: Category, + pub instant: bool, +} +const fn fx(id: &'static str, color: u32, category: Category) -> EffectDef { + EffectDef { id, color, category, instant: false } +} +use Category::{Beneficial as B, Harmful as H, Neutral as N}; +/// `MobEffects` in registration order. +pub const EFFECTS: &[EffectDef] = &[ + fx("speed", 3402751, B), + fx("slowness", 9154528, H), + fx("haste", 14270531, B), + fx("mining_fatigue", 4866583, H), + fx("strength", 16762624, B), + EffectDef { id: "instant_health", color: 16262179, category: B, instant: true }, + EffectDef { id: "instant_damage", color: 11101546, category: H, instant: true }, + fx("jump_boost", 16646020, B), + fx("nausea", 5578058, H), + fx("regeneration", 13458603, B), + fx("resistance", 9520880, B), + fx("fire_resistance", 16750848, B), + fx("water_breathing", 10017472, B), + fx("invisibility", 16185078, B), + fx("blindness", 2039587, H), + fx("night_vision", 12779366, B), + fx("hunger", 5797459, H), + fx("weakness", 4738376, H), + fx("poison", 8889187, H), + fx("wither", 7561558, H), + fx("health_boost", 16284963, B), + fx("absorption", 2445989, B), + EffectDef { id: "saturation", color: 16262179, category: B, instant: true }, + fx("glowing", 9740385, N), + fx("levitation", 13565951, H), + fx("luck", 5882118, B), + fx("unluck", 12624973, H), + fx("slow_falling", 15978425, B), + fx("conduit_power", 1950417, B), + fx("dolphins_grace", 8954814, B), + fx("bad_omen", 745784, N), + fx("hero_of_the_village", 4521796, B), + fx("darkness", 2696993, H), + fx("trial_omen", 1484454, N), + fx("raid_omen", 14565464, N), + fx("wind_charged", 12438015, H), + fx("weaving", 7891290, H), + fx("oozing", 10092451, H), + fx("infested", 9214860, H), + fx("breath_of_the_nautilus", 65518, B), +]; +pub fn effect(id: &str) -> Option<&'static EffectDef> { + let id = id.trim_start_matches("minecraft:"); + EFFECTS.iter().find(|e| e.id == id) +} +/// A `Potion`: id, name suffix (`item.minecraft.potion.effect.`) and +/// effects as (effect, duration ticks, amplifier). +#[derive(Clone, Copy, Debug)] +pub struct PotionDef { + pub id: &'static str, + pub name: &'static str, + pub effects: &'static [(&'static str, i32, i32)], +} +const fn p(id: &'static str, name: &'static str, effects: &'static [(&'static str, i32, i32)]) -> PotionDef { + PotionDef { id, name, effects } +} +/// `Potions` in registration order. +pub const POTIONS: &[PotionDef] = &[ + p("water", "water", &[]), + p("mundane", "mundane", &[]), + p("thick", "thick", &[]), + p("awkward", "awkward", &[]), + p("night_vision", "night_vision", &[("night_vision", 3600, 0)]), + p("long_night_vision", "night_vision", &[("night_vision", 9600, 0)]), + p("invisibility", "invisibility", &[("invisibility", 3600, 0)]), + p("long_invisibility", "invisibility", &[("invisibility", 9600, 0)]), + p("leaping", "leaping", &[("jump_boost", 3600, 0)]), + p("long_leaping", "leaping", &[("jump_boost", 9600, 0)]), + p("strong_leaping", "leaping", &[("jump_boost", 1800, 1)]), + p("fire_resistance", "fire_resistance", &[("fire_resistance", 3600, 0)]), + p("long_fire_resistance", "fire_resistance", &[("fire_resistance", 9600, 0)]), + p("swiftness", "swiftness", &[("speed", 3600, 0)]), + p("long_swiftness", "swiftness", &[("speed", 9600, 0)]), + p("strong_swiftness", "swiftness", &[("speed", 1800, 1)]), + p("slowness", "slowness", &[("slowness", 1800, 0)]), + p("long_slowness", "slowness", &[("slowness", 4800, 0)]), + p("strong_slowness", "slowness", &[("slowness", 400, 3)]), + p("turtle_master", "turtle_master", &[("slowness", 400, 3), ("resistance", 400, 2)]), + p("long_turtle_master", "turtle_master", &[("slowness", 800, 3), ("resistance", 800, 2)]), + p("strong_turtle_master", "turtle_master", &[("slowness", 400, 5), ("resistance", 400, 3)]), + p("water_breathing", "water_breathing", &[("water_breathing", 3600, 0)]), + p("long_water_breathing", "water_breathing", &[("water_breathing", 9600, 0)]), + p("healing", "healing", &[("instant_health", 1, 0)]), + p("strong_healing", "healing", &[("instant_health", 1, 1)]), + p("harming", "harming", &[("instant_damage", 1, 0)]), + p("strong_harming", "harming", &[("instant_damage", 1, 1)]), + p("poison", "poison", &[("poison", 900, 0)]), + p("long_poison", "poison", &[("poison", 1800, 0)]), + p("strong_poison", "poison", &[("poison", 432, 1)]), + p("regeneration", "regeneration", &[("regeneration", 900, 0)]), + p("long_regeneration", "regeneration", &[("regeneration", 1800, 0)]), + p("strong_regeneration", "regeneration", &[("regeneration", 450, 1)]), + p("strength", "strength", &[("strength", 3600, 0)]), + p("long_strength", "strength", &[("strength", 9600, 0)]), + p("strong_strength", "strength", &[("strength", 1800, 1)]), + p("weakness", "weakness", &[("weakness", 1800, 0)]), + p("long_weakness", "weakness", &[("weakness", 4800, 0)]), + p("luck", "luck", &[("luck", 6000, 0)]), + p("slow_falling", "slow_falling", &[("slow_falling", 1800, 0)]), + p("long_slow_falling", "slow_falling", &[("slow_falling", 4800, 0)]), + p("wind_charged", "wind_charged", &[("wind_charged", 3600, 0)]), + p("weaving", "weaving", &[("weaving", 3600, 0)]), + p("oozing", "oozing", &[("oozing", 3600, 0)]), + p("infested", "infested", &[("infested", 3600, 0)]), +]; +pub fn potion(id: &str) -> Option<&'static PotionDef> { + let id = id.trim_start_matches("minecraft:"); + POTIONS.iter().find(|p| p.id == id) +} +/// `PotionContents.BASE_POTION_COLOR` (ARGB -13083194) as RGB. +pub const BASE_POTION_COLOR: u32 = 0x385DC6; +/// `PotionContents.getColor`: amplifier-weighted mix of visible effect colours. +pub fn potion_color(id: Option<&str>) -> u32 { + let Some(def) = id.and_then(potion) else { return BASE_POTION_COLOR }; + let (mut r, mut g, mut b, mut total) = (0u32, 0u32, 0u32, 0u32); + for (e, _, amp) in def.effects { + let Some(e) = effect(e) else { continue }; + let w = *amp as u32 + 1; + r += w * (e.color >> 16 & 255); + g += w * (e.color >> 8 & 255); + b += w * (e.color & 255); + total += w; + } + if total == 0 { BASE_POTION_COLOR } else { (r / total) << 16 | (g / total) << 8 | b / total } +} +/// `MobEffectUtil.formatDuration` at 20 TPS: m:ss or h:mm:ss. +pub fn format_duration(ticks: i32) -> String { + let secs = ticks / 20; + let (h, m, s) = (secs / 3600, secs / 60 % 60, secs % 60); + if h > 0 { format!("{h}:{m:02}:{s:02}") } else { format!("{m}:{s:02}") } +} +/// `item.minecraft.potion.effect.` style translation key for a potion item. +pub fn potion_name_key(item: &str, potion: Option<&str>) -> String { + let prefix = item.trim_start_matches("minecraft:"); + let suffix = potion.and_then(self::potion).map_or("empty", |p| p.name); + format!("item.minecraft.{prefix}.effect.{suffix}") +} +/// Roman amplifier suffix (`potion.potency.N`) and duration lines of a potion. +pub fn tooltip(potion: Option<&str>, scale: f32, translate: &dyn Fn(&str) -> Option) -> Vec<(String, Category)> { + let Some(def) = potion.and_then(self::potion) else { return vec![] }; + if def.effects.is_empty() { + return vec![(translate("effect.none").unwrap_or_else(|| "No Effects".into()), Category::Neutral)]; + } + def.effects + .iter() + .map(|(e, duration, amp)| { + let mut line = translate(&format!("effect.minecraft.{e}")).unwrap_or_else(|| (*e).to_owned()); + if *amp > 0 { + line.push(' '); + line.push_str(&translate(&format!("potion.potency.{amp}")).unwrap_or_else(|| crate::enchant::level_name(*amp as u32 + 1))); + } + let instant = effect(e).is_some_and(|d| d.instant); + let scaled = (*duration as f32 * scale) as i32; + if !instant && scaled > 20 { + line = format!("{line} ({})", format_duration(scaled)); + } + (line, effect(e).map_or(Category::Neutral, |d| d.category)) + }) + .collect() +} + +/// A `PotionIngredient`: item ids plus an optional potion filter. +#[derive(Clone, Debug)] +pub struct PotionIngredient { + pub items: HashSet, + pub potions: Option>, +} +impl PotionIngredient { + fn parse(v: &Value, items: &Items) -> Self { + let mut set = HashSet::new(); + let add = |s: &str, set: &mut HashSet| match s.strip_prefix('#') { + Some(tag) => set.extend(items.item_tags.get(tag).into_iter().flatten().cloned()), + None => { + set.insert(s.to_owned()); + } + }; + match &v["item"] { + Value::String(s) => add(s, &mut set), + Value::Array(a) => a.iter().filter_map(Value::as_str).for_each(|s| add(s, &mut set)), + _ => {} + } + let potions = match &v["potion_contents"]["potions"] { + Value::String(s) => Some([s.clone()].into_iter().collect()), + Value::Array(a) => Some(a.iter().filter_map(|x| x.as_str().map(str::to_owned)).collect()), + _ => None, + }; + Self { items: set, potions } + } + pub fn test(&self, stack: &ItemStack) -> bool { + self.items.contains(&*stack.item) && self.potions.as_ref().is_none_or(|p| stack.potion().is_some_and(|x| p.contains(x))) + } +} +#[derive(Clone, Debug)] +pub struct BrewingRecipe { + pub id: String, + pub input: PotionIngredient, + pub reagent: PotionIngredient, + pub output: ItemStack, +} +pub struct Brewing { + pub recipes: Vec, + /// `RecipePropertySet.BREWING_REAGENTS`. + pub reagents: HashSet, + /// Items accepted in the bottle slots (`PotionIngredient.isPotionInput`). + pub inputs: HashSet, +} +impl Brewing { + pub fn load(root: &Path, items: &Items) -> Self { + let mut files: Vec<_> = fs::read_dir(root.join("data/minecraft/recipe/brewing")).into_iter().flatten().flatten().map(|e| e.path()).collect(); + files.sort(); + let mut recipes = Vec::new(); + for p in files { + let Ok(bytes) = fs::read(&p) else { continue }; + let Ok(v) = serde_json::from_slice::(&bytes) else { continue }; + if v["type"] != "minecraft:brewing" { + continue; + } + let mut output = ItemStack::new(v["output"]["id"].as_str().unwrap_or("minecraft:potion"), v["output"]["count"].as_u64().unwrap_or(1) as u32); + if let Some(potion) = v["output"]["components"]["minecraft:potion_contents"]["potion"].as_str() { + output = output.with_potion(potion); + } + recipes.push(BrewingRecipe { + id: format!("minecraft:brewing/{}", p.file_stem().and_then(|s| s.to_str()).unwrap_or("")), + input: PotionIngredient::parse(&v["input"], items), + reagent: PotionIngredient::parse(&v["reagent"], items), + output, + }); + } + let reagents = recipes.iter().flat_map(|r| r.reagent.items.iter().cloned()).collect(); + let inputs = recipes.iter().flat_map(|r| r.input.items.iter().cloned()).chain(std::iter::once("minecraft:glass_bottle".to_owned())).collect(); + Self { recipes, reagents, inputs } + } + pub fn find(&self, input: &ItemStack, reagent: &ItemStack) -> Option<&BrewingRecipe> { + self.recipes.iter().find(|r| r.input.test(input) && r.reagent.test(reagent)) + } + pub fn is_reagent(&self, stack: &ItemStack) -> bool { + self.reagents.contains(&*stack.item) + } + pub fn is_bottle(&self, stack: &ItemStack) -> bool { + self.inputs.contains(&*stack.item) + } +} + +/// `BrewingStandBlockEntity` state. Slots: 0-2 bottles, 3 ingredient, 4 fuel. +#[derive(Clone, Debug, Default)] +pub struct BrewingStand { + pub items: [Option; 5], + pub brew_time: i32, + pub total_brew_time: i32, + pub fuel: i32, + pub total_fuel: i32, + pub speed: f32, + pub ingredient: Option>, + pub last_bottles: Option<[bool; 3]>, +} +/// What a brewing tick asks the world to do. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct BrewTick { + /// New `has_bottle_0..2` block state values. + pub bottles: Option<[bool; 3]>, + /// Level event 1035 (brew sound). + pub brewed: bool, + /// Remainders dropped at the stand. + pub drops: Vec, +} +impl BrewingStand { + pub fn new() -> Self { + Self { total_brew_time: 400, total_fuel: 20, speed: 1.0, ..Default::default() } + } + fn brewable(&self, brewing: &Brewing) -> bool { + let Some(ingredient) = &self.items[3] else { return false }; + if !brewing.is_reagent(ingredient) { + return false; + } + self.items[..3].iter().flatten().any(|b| brewing.find(b, ingredient).is_some()) + } + /// `BrewingStandBlockEntity.serverTick`. + pub fn tick(&mut self, brewing: &Brewing, items: &Items, providers: &Providers) -> BrewTick { + let mut out = BrewTick::default(); + if self.fuel <= 0 + && let Some(fuel) = self.items[4].as_mut() + && let Some((uses, speed)) = brewing_fuel(items, fuel) + { + self.fuel = providers.int_value(&uses); + self.total_fuel = self.fuel; + self.speed = providers.float_value(&speed, 1.0); + let remainder = items.get(&fuel.item).and_then(|i| i.remainder.clone()); + fuel.count -= 1; + if fuel.count == 0 { + self.items[4] = remainder.map(|r| ItemStack::new(&r, 1)); + } else if let Some(r) = remainder { + out.drops.push(ItemStack::new(&r, 1)); + } + } + let brewable = self.brewable(brewing); + if self.brew_time > 0 { + self.brew_time -= 1; + let same = self.items[3].as_ref().map(|s| s.item.clone()) == self.ingredient; + if self.brew_time == 0 && brewable { + self.brew(brewing, items, &mut out); + } else if !brewable || !same { + self.brew_time = 0; + } + } else if brewable && self.fuel > 0 { + let speed = if self.speed > 0.0 { self.speed } else { 1.0 }; + self.fuel -= 1; + self.brew_time = (400.0 / speed).ceil() as i32; + self.total_brew_time = self.brew_time; + self.ingredient = self.items[3].as_ref().map(|s| s.item.clone()); + } + let bottles = [self.items[0].is_some(), self.items[1].is_some(), self.items[2].is_some()]; + if self.last_bottles != Some(bottles) { + self.last_bottles = Some(bottles); + out.bottles = Some(bottles); + } + out + } + fn brew(&mut self, brewing: &Brewing, items: &Items, out: &mut BrewTick) { + let Some(ingredient) = self.items[3].clone() else { return }; + for slot in 0..3 { + if let Some(input) = &self.items[slot] + && let Some(r) = brewing.find(input, &ingredient) + { + self.items[slot] = Some(r.output.clone()); + } + } + let remainder = items.get(&ingredient.item).and_then(|i| i.remainder.clone()); + if let Some(i) = self.items[3].as_mut() { + i.count -= 1; + if i.count == 0 { + self.items[3] = remainder.map(|r| ItemStack::new(&r, 1)); + } else if let Some(r) = remainder { + out.drops.push(ItemStack::new(&r, 1)); + } + } + out.brewed = true; + } +} +/// The `minecraft:brewing_fuel` providers of an item: (uses, speed_multiplier). +pub fn brewing_fuel(items: &Items, stack: &ItemStack) -> Option<(Value, Value)> { + items.get(&stack.item).and_then(|i| i.brewing_fuel.clone()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn potion_colours_and_names() { + // Swiftness: speed colour 3402751 = 0x33EBFF. + assert_eq!(potion_color(Some("minecraft:swiftness")), 0x33EBFF); + assert_eq!(potion_color(Some("minecraft:water")), BASE_POTION_COLOR); + // Turtle master mixes slowness x4 and resistance x3. + let (s, r) = (9154528u32, 9520880u32); + let mix = |sh: u32| ((s >> sh & 255) * 4 + (r >> sh & 255) * 3) / 7; + assert_eq!(potion_color(Some("minecraft:turtle_master")), mix(16) << 16 | mix(8) << 8 | mix(0)); + assert_eq!(potion_name_key("minecraft:splash_potion", Some("minecraft:long_swiftness")), "item.minecraft.splash_potion.effect.swiftness"); + assert_eq!(format_duration(9600), "8:00"); + assert_eq!(format_duration(450), "0:22"); + let t = tooltip(Some("minecraft:strong_poison"), 1.0, &|_| None); + assert_eq!(t[0].0, "poison II (0:21)"); + assert_eq!(POTIONS.len(), 46); + } + + #[test] + fn brewing_stand_brews_after_400_ticks() { + let mut item_tags = std::collections::HashMap::new(); + item_tags.insert("x".into(), HashSet::new()); + let items = Items::for_tests(item_tags); + let recipe = BrewingRecipe { + id: "awkward".into(), + input: PotionIngredient { items: ["minecraft:potion".to_owned()].into_iter().collect(), potions: Some(["minecraft:water".to_owned()].into_iter().collect()) }, + reagent: PotionIngredient { items: ["minecraft:nether_wart".to_owned()].into_iter().collect(), potions: None }, + output: ItemStack::new("minecraft:potion", 1).with_potion("minecraft:awkward"), + }; + let brewing = Brewing { reagents: ["minecraft:nether_wart".to_owned()].into_iter().collect(), inputs: HashSet::new(), recipes: vec![recipe] }; + let providers = Providers::empty(); + let mut stand = BrewingStand::new(); + stand.fuel = 1; + stand.items[0] = Some(ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water")); + stand.items[2] = Some(ItemStack::new("minecraft:potion", 1).with_potion("minecraft:awkward")); + stand.items[3] = Some(ItemStack::new("minecraft:nether_wart", 2)); + let first = stand.tick(&brewing, &items, &providers); + assert_eq!(first.bottles, Some([true, false, true])); + assert_eq!((stand.brew_time, stand.fuel), (400, 0)); + let mut brewed_at = 0; + for t in 1..=400 { + if stand.tick(&brewing, &items, &providers).brewed { + brewed_at = t; + } + } + assert_eq!(brewed_at, 400); + assert_eq!(stand.items[0].as_ref().unwrap().potion(), Some("minecraft:awkward")); + // The awkward potion had no recipe and stays. + assert_eq!(stand.items[2].as_ref().unwrap().potion(), Some("minecraft:awkward")); + assert_eq!(stand.items[3].as_ref().unwrap().count, 1); + // No fuel left: nothing more brews. + stand.tick(&brewing, &items, &providers); + assert_eq!(stand.brew_time, 0); + } +} diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index e53fb0531..97ead6e39 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -49,6 +49,7 @@ pub struct Furnace { pub enum BlockEntity { Chest(Vec>), Furnace(Furnace), + Brewing(Box), } impl BlockEntity { pub fn for_block(name: &str) -> Option { @@ -63,6 +64,9 @@ impl BlockEntity { speed: 1.0, })); } + if name == "minecraft:brewing_stand" { + return Some(Self::Brewing(Box::new(crate::brewing::BrewingStand::new()))); + } matches!( name, "minecraft:chest" | "minecraft:trapped_chest" | "minecraft:barrel" @@ -72,6 +76,7 @@ impl BlockEntity { pub fn id(&self) -> &'static str { match self { Self::Chest(_) => "minecraft:chest", + Self::Brewing(_) => "minecraft:brewing_stand", Self::Furnace(f) => match f.kind { FurnaceKind::Furnace => "minecraft:furnace", FurnaceKind::BlastFurnace => "minecraft:blast_furnace", @@ -83,12 +88,14 @@ impl BlockEntity { match self { Self::Chest(items) => items.iter().flatten().cloned().collect(), Self::Furnace(f) => f.items.iter().flatten().cloned().collect(), + Self::Brewing(b) => b.items.iter().flatten().cloned().collect(), } } pub fn slots_mut(&mut self) -> &mut [Option] { match self { Self::Chest(items) => items, Self::Furnace(f) => &mut f.items, + Self::Brewing(b) => &mut b.items, } } } @@ -148,6 +155,18 @@ impl Providers { _ => 0.0, } } + /// A plain `context_int_provider` value or reference (no context conditions). + pub fn int_value(&self, v: &Value) -> i32 { + self.eval(v, false, &self.ints, 0) as i32 + } + /// A plain `context_float_provider` value or reference; `default` when absent. + pub fn float_value(&self, v: &Value, default: f32) -> f32 { + if v.is_null() { default } else { self.eval(v, false, &self.floats, 0) as f32 } + } + #[cfg(test)] + pub fn empty() -> Self { + Self { ints: HashMap::new(), floats: HashMap::new() } + } pub fn burn_time(&self, items: &Items, stack: &ItemStack, fast: bool) -> i32 { items .get(&stack.item) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 1e22514fe..536846ddf 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1,6 +1,8 @@ //! The playable game loop: streaming world, player simulation at 20 ticks/s, //! block interaction, inventory and HUD. mod control; +mod station_control; +mod stations; use horizon_client::{ Result, assets::Assets, @@ -287,6 +289,8 @@ pub struct Resources { player_arm: Option, /// firstperson_righthand display transforms per item: (rotation, translation, scale). displays: HashMap>, + /// Enchantments, workstation recipes and brewing (game/stations.rs). + stations: horizon_client::stations::StationData, } struct Game<'a> { res: &'a mut Resources, @@ -310,6 +314,8 @@ struct Game<'a> { craft_size: usize, /// Open container block entity, if any. container: Option<(i32, i32, i32)>, + /// Open workstation menu (enchanting table, anvil, ...). + station: Option, scratch_slot: Option, mining: Option, destroy_delay: u32, @@ -486,8 +492,7 @@ impl Game<'_> { let order: Vec = std::iter::once(self.selected).chain((0..36).filter(|&i| i != self.selected)).collect(); for &i in &order { if let Some(slot) = &mut self.inventory[i] - && slot.item == stack.item - && slot.damage == stack.damage + && slot.same_item_same_components(&stack) && slot.count < max { let moved = (max - slot.count).min(stack.count); @@ -828,6 +833,8 @@ impl Game<'_> { if let Some(sound) = sound { self.audio.play(sound, Some([f64::from(key.0) + 0.5, f64::from(key.1) + 0.5, f64::from(key.2) + 0.5]), 0.5, 1.0); } + } else if self.open_station(pos, &name) { + // Workstation menus: game/stations.rs. } else { self.message = Some((format!("{} is not available yet", name.trim_start_matches("minecraft:").replace('_', " ")), Instant::now())); return; @@ -1392,6 +1399,7 @@ impl Game<'_> { self.bob.1 += (target - self.bob.1) * 0.4; } self.tick_block_entities()?; + self.tick_brewing_stands()?; let facts = &self.res.facts; let world = &self.world; self.particles.retain_mut(|p| p.tick(world, |id| facts.states[id as usize].full_collision)); @@ -1536,6 +1544,7 @@ impl Game<'_> { } None => batch.fill(atlas, x + 2.0, y + 2.0, 12.0, 12.0, rgba(200, 0, 200, 255)), } + self.draw_glint(batch, stack, x, y); if stack.count > 1 { let text = stack.count.to_string(); let w = HudBatch::text_width(atlas, &text); @@ -1726,10 +1735,14 @@ impl Game<'_> { } /// 300.. are the open container's slots. fn slots(&self) -> Vec { + if let Some(v) = self.station_slots() { + return v; + } let mut v: Vec = (0..36).collect(); match self.container_kind() { 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), None => { v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i)); v.push(200); @@ -1742,6 +1755,9 @@ impl Game<'_> { } /// InventoryMenu / CraftingMenu slot layouts. fn slot_position(&self, i: usize) -> (f32, f32) { + if let Some(p) = self.station_slot_position(i) { + return p; + } let table = self.craft_size == 3; // ContainerScreen (3 rows) shifts the player inventory down by one pixel. let shift = if matches!(self.container_kind(), Some(BlockEntity::Chest(_))) { 1.0 } else { 0.0 }; @@ -1773,6 +1789,9 @@ impl Game<'_> { }) } fn slot_mut(&mut self, i: usize) -> &mut Option { + if i >= stations::INPUT { + return self.station_slot_mut(i); + } if (500..504).contains(&i) { return &mut self.armor[i - 500]; } @@ -1795,6 +1814,9 @@ impl Game<'_> { self.res.recipes.craft(&grid, n) } fn draw_inventory(&mut self, batch: &mut HudBatch) { + if self.draw_station(batch) { + return; + } let (ox, oy) = self.inventory_origin(batch); { let atlas = &self.res.atlas; @@ -1841,6 +1863,7 @@ impl Game<'_> { part(batch, "gui/sprites/container/furnace/burn_progress", 0.0, 0.0, w, 16.0, ox + 79.0, oy + 34.0); } } + Some(BlockEntity::Brewing(_)) => {} None => { let texture = if self.craft_size == 3 { "gui/container/crafting_table" } else { "gui/container/inventory" }; part(batch, texture, 0.0, 0.0, 176.0, 166.0, ox, oy); @@ -1870,8 +1893,10 @@ impl Game<'_> { if let Some(stack) = self.carried.clone() { self.draw_item(batch, &stack, self.cursor.0 - 8.0, self.cursor.1 - 8.0); } + self.draw_slot_tooltip(batch); } fn close_container(&mut self) { + self.close_station(); let mut returned: Vec = self.carried.take().into_iter().collect(); returned.extend(self.craft_grid.iter_mut().filter_map(Option::take)); for stack in returned { @@ -1892,6 +1917,9 @@ impl Game<'_> { } } fn click_inventory(&mut self, right: bool) { + if self.station_click(right) { + return; + } let Some(size) = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]) else { return }; let batch = HudBatch::new(size); let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { return }; @@ -1957,8 +1985,7 @@ impl Game<'_> { let mut stack = stack; for i in range.clone() { if let Some(s) = &mut self.inventory[i] - && s.item == stack.item - && s.damage == stack.damage + && s.same_item_same_components(&stack) { let moved = max(&self.res.items, s).saturating_sub(s.count).min(stack.count); s.count += moved; @@ -2004,7 +2031,7 @@ impl Game<'_> { (Some(one), (c.count > 0).then_some(c)) } (Some(c), None) => (Some(c), None), - (Some(mut c), Some(mut s)) if c.item == s.item && c.damage == s.damage => { + (Some(mut c), Some(mut s)) if c.same_item_same_components(&s) => { let room = max(items, &s).saturating_sub(s.count); let moved = if right { 1.min(room).min(c.count) } else { room.min(c.count) }; s.count += moved; @@ -4426,6 +4453,9 @@ impl ApplicationHandler for Game<'_> { let rows = self.creative_screen.rows(&self.res.names).saturating_sub(5).max(1) as f32; self.creative_screen.scroll = (self.creative_screen.scroll - d.signum() / rows).clamp(0.0, 1.0); } + if self.screen == Screen::Inventory && d != 0.0 { + self.station_scroll(d); + } if self.screen == Screen::Playing && d != 0.0 { self.selected = (self.selected as i32 - d.signum() as i32).rem_euclid(9) as usize; } @@ -4520,6 +4550,14 @@ impl ApplicationHandler for Game<'_> { } self.creative_screen.scroll = 0.0; } + WindowEvent::KeyboardInput { event, .. } + if self.station_typing() && event.state == ElementState::Pressed + && !matches!(event.physical_key, PhysicalKey::Code(KeyCode::Escape)) => + { + // The anvil rename box takes every key but Escape (AnvilScreen.keyPressed). + let backspace = event.physical_key == PhysicalKey::Code(KeyCode::Backspace); + self.station_text(event.text.as_deref(), backspace); + } WindowEvent::KeyboardInput { event, .. } if self.title.is_some() => { if event.state == ElementState::Pressed && let Some(title) = self.title.as_mut() @@ -4684,7 +4722,9 @@ pub fn run() -> Result<()> { let audio = Audio::new(&root); let world = World::new(facts.air, 0); let creative = options.creative; + let stations = horizon_client::stations::StationData::load(&root, &items); let mut resources = Resources { + stations, assets, facts, items, @@ -4738,6 +4778,7 @@ pub fn run() -> Result<()> { craft_grid: vec![None; 9], craft_size: 2, container: None, + station: None, scratch_slot: None, mining: None, destroy_delay: 0, diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index f645f4a8f..d5d8b69f0 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -65,7 +65,7 @@ impl Game<'_> { }; let ok = || Ok(Some(json!({ "ok": true }))); match words[0] { - "help" => Ok(Some(json!({ "commands": HELP }))), + "help" => Ok(Some(json!({ "commands": HELP.iter().chain(super::station_control::HELP).collect::>() }))), "status" => Ok(Some(self.control_status())), "key" => { let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?; @@ -253,7 +253,10 @@ impl Game<'_> { event_loop.exit(); ok() } - other => Err(format!("unknown command {other}; try help").into()), + other => match self.station_command(&words)? { + Some(value) => Ok(Some(value)), + None => Err(format!("unknown command {other}; try help").into()), + }, } } diff --git a/crates/horizon-client/src/game/station_control.rs b/crates/horizon-client/src/game/station_control.rs new file mode 100644 index 000000000..feac5f35a --- /dev/null +++ b/crates/horizon-client/src/game/station_control.rs @@ -0,0 +1,150 @@ +//! Control-socket commands for menus and item components, so scripts can +//! drive the workstation screens (`horizon-ctl click-slot 600`, ...). +use super::{Game, Screen}; +use horizon_client::{Result, items::ItemStack}; +use serde_json::{Value, json}; + +pub(super) const HELP: &[&str] = &[ + "xp LEVELS add (or remove) experience levels", + "setblock X Y Z BLOCK place a block's default state (with its block entity)", + "use X Y Z open the block's menu as if right-clicked", + "click-slot ID [right] [shift] click a menu slot (0-35 inventory, 300+ container, 600+ station, 650 result)", + "click-gui X Y [right] [shift] click at GUI pixel X Y relative to the menu's top-left corner", + "type TEXT | type-back type into the anvil name box / delete one character", + "enchant ID LEVEL enchant the held item (books store the enchantment)", + "potion ITEM POTION give a potion item (potion, splash_potion, lingering_potion, tipped_arrow)", + "menu JSON dump of the open menu, carried stack and inventory", + "close close the open menu", +]; +fn id(name: &str) -> String { + if name.contains(':') { name.to_owned() } else { format!("minecraft:{name}") } +} +fn stack_json(s: &ItemStack) -> Value { + json!({ + "item": &*s.item, + "count": s.count, + "damage": s.damage, + "enchantments": s.enchantments().iter().map(|(e, l)| json!([&**e, l])).collect::>(), + "stored_enchantments": s.stored_enchantments().iter().map(|(e, l)| json!([&**e, l])).collect::>(), + "repair_cost": s.repair_cost(), + "custom_name": s.custom_name(), + "potion": s.potion(), + "trim": s.data().and_then(|d| d.trim.as_ref()).map(|(m, p)| json!([&**m, &**p])), + }) +} + +impl Game<'_> { + fn click_at(&mut self, x: f32, y: f32, right: bool, shift: bool) { + use winit::keyboard::KeyCode; + let saved = self.cursor; + self.cursor = (x, y); + let had_shift = self.keys.contains(&KeyCode::ShiftLeft); + if shift { + self.keys.insert(KeyCode::ShiftLeft); + } + self.click_inventory(right); + if shift && !had_shift { + self.keys.remove(&KeyCode::ShiftLeft); + } + let _ = saved; + } + fn gui_origin(&self) -> Result<(f32, f32)> { + let size = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]).ok_or("no renderer yet")?; + Ok(self.inventory_origin(&horizon_client::hud::HudBatch::new(size))) + } + /// Commands not known to control.rs; None when unknown here too. + pub(super) fn station_command(&mut self, words: &[&str]) -> Result> { + let arg = |i: usize| words.get(i).copied().ok_or_else(|| format!("{} needs more arguments", words[0])); + let flag = |name: &str| words.iter().skip(1).any(|w| *w == name); + let ok = || Ok(Some(json!({ "ok": true }))); + match words.first().copied().unwrap_or("") { + "xp" => { + let n: i32 = arg(1)?.parse()?; + self.give_levels(n); + Ok(Some(json!({ "ok": true, "level": self.experience.level }))) + } + "setblock" => { + let pos = [arg(1)?.parse()?, arg(2)?.parse()?, arg(3)?.parse()?]; + let name = id(arg(4)?); + if !self.set_state_named(pos, &name, &[])? { + return Err(format!("cannot place {name}").into()); + } + if let Some(entity) = horizon_client::containers::BlockEntity::for_block(&name) { + self.world.block_entities.insert((pos[0], pos[1], pos[2]), entity); + } + self.world.modified.insert((pos[0] >> 4, pos[2] >> 4)); + ok() + } + "use" => { + let pos = [arg(1)?.parse()?, arg(2)?.parse()?, arg(3)?.parse()?]; + self.open_menu(pos); + Ok(Some(json!({ "ok": true, "station": self.station.as_ref().map(|s| format!("{:?}", s.kind)) }))) + } + "click-slot" => { + let slot: usize = arg(1)?.parse()?; + let (ox, oy) = self.gui_origin()?; + let (sx, sy) = self.slot_position(slot); + self.click_at(ox + sx + 8.0, oy + sy + 8.0, flag("right"), flag("shift")); + ok() + } + "click-gui" => { + let (x, y): (f32, f32) = (arg(1)?.parse()?, arg(2)?.parse()?); + let (ox, oy) = self.gui_origin()?; + self.click_at(ox + x, oy + y, flag("right"), flag("shift")); + ok() + } + "type" => { + let text = words[1..].join(" "); + self.station_text(Some(&text), false); + ok() + } + "type-back" => { + self.station_text(None, true); + ok() + } + "enchant" => { + let e = id(arg(1)?); + let level: u32 = arg(2)?.parse()?; + if self.res.stations.enchantments.get(&e).is_none() { + return Err(format!("unknown enchantment {e}").into()); + } + let held = self.inventory[self.selected].as_mut().ok_or("no held item")?; + held.enchant(&e, level); + self.apply_equipment(); + ok() + } + "potion" => { + let stack = ItemStack::new(&id(arg(1)?), 1).with_potion(&id(arg(2)?)); + let rest = self.give(stack); + Ok(Some(json!({ "ok": rest.is_none() }))) + } + "menu" => { + let slots: Vec = self + .slots() + .into_iter() + .filter_map(|i| { + let s = if i == 200 { self.craft_result() } else { self.slot_mut(i).clone() }; + s.map(|s| json!({ "slot": i, "stack": stack_json(&s) })) + }) + .collect(); + Ok(Some(json!({ + "screen": if self.screen == Screen::Inventory { "inventory" } else { "other" }, + "station": self.station.as_ref().map(|s| format!("{:?}", s.kind)), + "name": self.station.as_ref().map(|s| s.name.clone()), + "info": self.station_info(), + "carried": self.carried.as_ref().map(stack_json), + "level": self.experience.level, + "xp_seed": self.level.xp_seed, + "slots": slots, + }))) + } + "close" => { + self.close_container(); + self.screen = Screen::Playing; + self.capture(true); + ok() + } + _ => Ok(None), + } + } +} diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs new file mode 100644 index 000000000..4eee33ecf --- /dev/null +++ b/crates/horizon-client/src/game/stations.rs @@ -0,0 +1,1215 @@ +//! Workstation menus in the game: enchanting table, anvil, grindstone, +//! smithing table, stonecutter and the brewing stand screen. Layouts, sprites, +//! colours and sounds follow the vanilla screens (`EnchantmentScreen`, +//! `AnvilScreen`, `GrindstoneScreen`, `SmithingScreen`, `StonecutterScreen`, +//! `BrewingStandScreen`); item rules live in `horizon_client::stations`. +use super::{Game, Screen}; +use horizon_client::{ + brewing, + containers::BlockEntity, + enchant::Enchantments, + hud::{HudBatch, rgba}, + items::ItemStack, + stations::{self, AnvilResult, EnchantOffers}, +}; +use horizon_core::random::{LegacyRandom, RandomSource}; +use std::sync::Arc; + +/// Slot ids of the open station: inputs from 600, the result at 650. +pub(super) const INPUT: usize = 600; +pub(super) const RESULT: usize = 650; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum Kind { + Enchanting, + Anvil, + Grindstone, + Smithing, + Stonecutter, +} +impl Kind { + fn from_block(name: &str) -> Option { + Some(match name { + "minecraft:enchanting_table" => Self::Enchanting, + "minecraft:anvil" | "minecraft:chipped_anvil" | "minecraft:damaged_anvil" => Self::Anvil, + "minecraft:grindstone" => Self::Grindstone, + "minecraft:smithing_table" => Self::Smithing, + "minecraft:stonecutter" => Self::Stonecutter, + _ => return None, + }) + } + fn inputs(self) -> usize { + match self { + Self::Smithing => 3, + Self::Stonecutter => 1, + _ => 2, + } + } + fn texture(self) -> &'static str { + match self { + Self::Enchanting => "gui/container/enchanting_table", + Self::Anvil => "gui/container/anvil", + Self::Grindstone => "gui/container/grindstone", + Self::Smithing => "gui/container/smithing", + Self::Stonecutter => "gui/container/stonecutter", + } + } + fn title_key(self) -> &'static str { + match self { + Self::Enchanting => "container.enchant", + Self::Anvil => "container.repair", + Self::Grindstone => "container.grindstone_title", + Self::Smithing => "container.upgrade", + Self::Stonecutter => "container.stonecutter", + } + } + /// (titleLabelX, titleLabelY). + fn title_pos(self) -> (f32, f32) { + match self { + Self::Anvil => (60.0, 6.0), + Self::Smithing => (44.0, 15.0), + Self::Stonecutter => (8.0, 5.0), + _ => (8.0, 6.0), + } + } + fn input_pos(self, i: usize) -> (f32, f32) { + let table: &[(f32, f32)] = match self { + Self::Enchanting => &[(15.0, 47.0), (35.0, 47.0)], + Self::Anvil => &[(27.0, 47.0), (76.0, 47.0)], + Self::Grindstone => &[(49.0, 19.0), (49.0, 40.0)], + Self::Smithing => &[(8.0, 48.0), (26.0, 48.0), (44.0, 48.0)], + Self::Stonecutter => &[(20.0, 33.0)], + }; + table[i.min(table.len() - 1)] + } + fn result_pos(self) -> Option<(f32, f32)> { + match self { + Self::Enchanting => None, + Self::Anvil => Some((134.0, 47.0)), + Self::Grindstone => Some((129.0, 34.0)), + Self::Smithing => Some((98.0, 48.0)), + Self::Stonecutter => Some((143.0, 33.0)), + } + } +} + +pub(super) struct Station { + pub(super) kind: Kind, + pub(super) pos: [i32; 3], + pub(super) inputs: Vec>, + result: Option, + offers: EnchantOffers, + bookcases: i32, + anvil: AnvilResult, + /// Anvil rename box text. + pub(super) name: String, + /// Stonecutter: recipe indices for the input, selection and first shown index. + recipes: Vec, + selected: Option, + start: usize, + input_item: Option>, + /// Anvil: the input the rename box was last filled from. + anvil_last: Option, + last_sound: u64, +} +impl Station { + fn new(kind: Kind, pos: [i32; 3]) -> Self { + Self { + kind, + pos, + inputs: vec![None; kind.inputs()], + result: None, + offers: EnchantOffers::default(), + bookcases: 0, + anvil: AnvilResult::default(), + name: String::new(), + recipes: Vec::new(), + selected: None, + start: 0, + input_item: None, + anvil_last: None, + last_sound: 0, + } + } +} + +/// The 108x19 enchantment button `i` (relative to the GUI origin). +fn enchant_button(i: usize) -> (f32, f32, f32, f32) { + (60.0, 14.0 + 19.0 * i as f32, 108.0, 19.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 +} +/// `EnchantmentNames` word list. +const WORDS: &[&str] = &[ + "the", "elder", "scrolls", "klaatu", "berata", "niktu", "xyzzy", "bless", "curse", "light", "darkness", "fire", "air", "earth", "water", "hot", "dry", "cold", "wet", "ignite", "snuff", "embiggen", "twist", "shorten", "stretch", "fiddle", "destroy", "imbue", "galvanize", "enchant", "free", "limited", "range", "of", "towards", "inside", "sphere", "cube", "self", "other", "ball", "mental", "physical", "grow", "shrink", "demon", "elemental", "spirit", "animal", "creature", "beast", "humanoid", "undead", "fresh", "stale", "phnglui", "mglwnafh", "cthulhu", "rlyeh", "wgahnagl", "fhtagn", "baguette", +]; +const GREY: u32 = 0xFF40_4040; +fn argb(c: i32) -> u32 { + let c = c as u32; + rgba((c >> 16 & 255) as u8, (c >> 8 & 255) as u8, (c & 255) as u8, (c >> 24 & 255) as u8) +} + +impl Game<'_> { + fn data(&self) -> &stations::StationData { + &self.res.stations + } + fn translate(&self, key: &str, fallback: &str) -> String { + self.data().enchantments.translate(key).unwrap_or(fallback).to_owned() + } + fn brewing_open(&self) -> bool { + matches!(self.container_kind(), Some(BlockEntity::Brewing(_))) + } + /// Opens a workstation menu for the block; false when it is not one. + pub(super) fn open_station(&mut self, pos: [i32; 3], name: &str) -> bool { + let Some(kind) = Kind::from_block(name) else { return false }; + if self.level.xp_seed == 0 { + self.level.xp_seed = self.world.random.next_int(); + } + self.station = Some(Station::new(kind, pos)); + self.station_changed(); + true + } + /// `AbstractContainerMenu.clearContainer`: inputs go back to the player. + pub(super) fn close_station(&mut self) { + let Some(station) = self.station.take() else { return }; + for stack in station.inputs.into_iter().flatten() { + if let Some(rest) = self.give(stack) + && let Some(eye) = self.eye_position() + { + self.spawn_item(rest, [eye[0], eye[1] - 0.3, eye[2]], [0.0, 0.1, 0.0], 40); + } + } + } + pub(super) fn station_slots(&self) -> Option> { + let mut v: Vec = (0..36).collect(); + if self.brewing_open() { + v.extend(300..305); + return Some(v); + } + let s = self.station.as_ref()?; + v.extend((0..s.inputs.len()).map(|i| INPUT + i)); + if s.kind.result_pos().is_some() { + v.push(RESULT); + } + Some(v) + } + pub(super) fn station_slot_position(&self, i: usize) -> Option<(f32, f32)> { + if self.brewing_open() && (300..305).contains(&i) { + return Some([(56.0, 51.0), (79.0, 58.0), (102.0, 51.0), (79.0, 17.0), (17.0, 17.0)][i - 300]); + } + let s = self.station.as_ref()?; + match i { + RESULT => s.kind.result_pos(), + _ if i >= INPUT && i < INPUT + s.inputs.len() => Some(s.kind.input_pos(i - INPUT)), + _ => None, + } + } + pub(super) fn station_slot_mut(&mut self, i: usize) -> &mut Option { + match self.station.as_mut() { + Some(s) if i == RESULT => &mut s.result, + Some(s) if i >= INPUT && i < INPUT + s.inputs.len() => &mut s.inputs[i - INPUT], + _ => &mut self.scratch_slot, + } + } + fn count_bookshelves(&self, pos: [i32; 3]) -> i32 { + let tags = &self.res.items.block_tags; + let is = |p: [i32; 3], tag: &str| { + let name = &self.res.facts.get(self.world.block(p[0], p[1], p[2])).name; + tags.get(tag).is_some_and(|t| t.contains(&**name)) + }; + stations::bookshelf_offsets() + .into_iter() + .filter(|o| { + is([pos[0] + o[0], pos[1] + o[1], pos[2] + o[2]], "minecraft:enchantment_power_provider") + && is([pos[0] + o[0] / 2, pos[1] + o[1], pos[2] + o[2] / 2], "minecraft:enchantment_power_transmitter") + }) + .count() as i32 + } + /// The anvil name the menu works with (`AnvilScreen.onNameChanged`). + fn anvil_item_name(&self, s: &Station) -> String { + match &s.inputs[0] { + Some(input) if input.custom_name().is_none() && s.name == self.res.names.item(&input.item) => String::new(), + Some(_) => s.name.clone(), + None => String::new(), + } + } + /// `slotsChanged` / `createResult` for the open station. + pub(super) fn station_changed(&mut self) { + let Some(mut s) = self.station.take() else { return }; + let creative = self.creative; + let data = &self.res.stations; + let items = &self.res.items; + match s.kind { + Kind::Enchanting => { + s.bookcases = self.count_bookshelves(s.pos); + s.offers = stations::enchant_offers(&data.enchantments, items, self.level.xp_seed, s.bookcases, s.inputs[0].as_ref()); + } + Kind::Anvil => { + let name = self.anvil_item_name(&s); + let hover = s.inputs[0].as_ref().map(|i| stations::hover_name(&|id| self.res.names.item(id), i)).unwrap_or_default(); + s.anvil = stations::anvil_result(&data.enchantments, items, s.inputs[0].as_ref(), s.inputs[1].as_ref(), Some(&name), &hover, creative); + s.result = s.anvil.result.clone(); + } + Kind::Grindstone => { + s.result = stations::grindstone_result(&data.enchantments, items, s.inputs[0].as_ref(), s.inputs[1].as_ref()); + } + Kind::Smithing => { + s.result = data.recipes.smithing_result(&data.enchantments, s.inputs[0].as_ref(), s.inputs[1].as_ref(), s.inputs[2].as_ref()); + } + Kind::Stonecutter => { + let item = s.inputs[0].as_ref().map(|i| i.item.clone()); + if item != s.input_item { + s.input_item = item; + s.selected = None; + s.start = 0; + s.recipes = match &s.inputs[0] { + Some(input) => data.recipes.stonecutting.iter().enumerate().filter(|(_, r)| r.input.test(input)).map(|(i, _)| i).collect(), + None => Vec::new(), + }; + } + s.result = match (s.selected, &s.inputs[0]) { + (Some(i), Some(_)) => s.recipes.get(i).map(|&r| data.recipes.stonecutting[r].result.clone()), + _ => None, + }; + } + } + self.station = Some(s); + } + fn max_stack(&self, stack: &ItemStack) -> u32 { + self.res.items.get(&stack.item).map_or(64, |i| i.max_stack) + } + /// `Slot.mayPlace` and `getMaxStackSize` for station and brewing slots. + fn slot_rules(&self, slot: usize, stack: &ItemStack) -> (bool, u32) { + let data = self.data(); + if (300..305).contains(&slot) { + return match slot - 300 { + 0..=2 => (data.brewing.is_bottle(stack), 1), + 3 => (data.brewing.is_reagent(stack), 64), + _ => (self.res.items.get(&stack.item).is_some_and(|i| i.brewing_fuel.is_some()), 64), + }; + } + let Some(s) = self.station.as_ref() else { return (true, 64) }; + if slot < 36 { + return (true, 64); + } + if slot == RESULT { + return (false, 64); + } + let i = slot - INPUT; + match s.kind { + Kind::Enchanting if i == 0 => (true, 1), + Kind::Enchanting => (&*stack.item == "minecraft:lapis_lazuli", 64), + Kind::Grindstone => (stations::grindstone_accepts(&self.res.items, stack), 64), + Kind::Smithing => (data.recipes.smithing_accepts(i, stack), 64), + _ => (true, 64), + } + } + /// `AbstractContainerMenu.doClick` PICKUP on a filtered slot. + fn click_filtered(&mut self, slot: usize, right: bool) { + let carried = self.carried.take(); + let current = self.slot_mut(slot).take(); + let (new_slot, new_carried) = match (carried, current) { + (None, None) => (None, None), + (None, Some(mut s)) => { + let take = if right { s.count.div_ceil(2) } else { s.count }; + s.count -= take; + let taken = ItemStack { count: take, ..s.clone() }; + ((s.count > 0).then_some(s), Some(taken)) + } + (Some(mut c), None) => { + let (ok, cap) = self.slot_rules(slot, &c); + if ok { + let n = if right { 1 } else { c.count }.min(cap.min(self.max_stack(&c))); + let placed = ItemStack { count: n, ..c.clone() }; + c.count -= n; + (Some(placed), (c.count > 0).then_some(c)) + } else { + (None, Some(c)) + } + } + (Some(mut c), Some(mut s)) => { + let (ok, cap) = self.slot_rules(slot, &c); + if ok && c.same_item_same_components(&s) { + let room = cap.min(self.max_stack(&s)).saturating_sub(s.count); + let n = if right { 1 } else { c.count }.min(room); + s.count += n; + c.count -= n; + (Some(s), (c.count > 0).then_some(c)) + } else if ok && c.count <= cap.min(self.max_stack(&c)) { + (Some(c), Some(s)) + } else if c.same_item_same_components(&s) { + let n = s.count.min(self.max_stack(&c).saturating_sub(c.count)); + s.count -= n; + c.count += n; + ((s.count > 0).then_some(s), Some(c)) + } else { + (Some(s), Some(c)) + } + } + }; + *self.slot_mut(slot) = new_slot; + 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 { + let order: Vec = if reverse { targets.iter().rev().copied().collect() } else { targets.to_vec() }; + let start = stack.count; + if self.max_stack(stack) > 1 { + for &t in &order { + if stack.count == 0 { + break; + } + let (_, cap) = self.slot_rules(t, stack); + let max = cap.min(self.max_stack(stack)); + if let Some(s) = self.slot_mut(t).as_mut() + && s.same_item_same_components(stack) + { + let n = max.saturating_sub(s.count).min(stack.count); + s.count += n; + stack.count -= n; + } + } + } + for &t in &order { + if stack.count == 0 { + break; + } + let (ok, cap) = self.slot_rules(t, stack); + if self.slot_mut(t).is_none() && (t < 36 || ok) { + let n = cap.min(self.max_stack(stack)).min(stack.count); + *self.slot_mut(t) = Some(ItemStack { count: n, ..stack.clone() }); + stack.count -= n; + } + } + stack.count != start + } + /// The player inventory in menu order: main rows, then the hotbar. + fn player_slots() -> Vec { + (9..36).chain(0..9).collect() + } + /// `quickMoveStack` for one slot; returns whether anything moved. + fn quick_move(&mut self, slot: usize) -> bool { + let Some(mut stack) = self.slot_mut(slot).take() else { return false }; + let player = Self::player_slots(); + let moved = if (300..305).contains(&slot) || slot >= INPUT { + self.move_to(&mut stack, &player, true) + } else if self.brewing_open() { + // BrewingStandMenu.quickMoveStack: fuel, ingredient, bottles, then the other half. + let data = self.data(); + let fuel = self.res.items.get(&stack.item).is_some_and(|i| i.brewing_fuel.is_some()); + let (reagent, bottle) = (data.brewing.is_reagent(&stack), data.brewing.is_bottle(&stack)); + let mut moved = false; + if fuel { + moved = self.move_to(&mut stack, &[304], false); + } + if !moved && reagent { + moved = self.move_to(&mut stack, &[303], false); + } + if !moved && bottle { + moved = self.move_to(&mut stack, &[300, 301, 302], false); + } + if !moved { + let other: Vec = if slot < 9 { (9..36).collect() } else { (0..9).collect() }; + moved = self.move_to(&mut stack, &other, false); + } + moved + } else { + let kind = self.station.as_ref().map(|s| s.kind); + let mut moved = false; + match kind { + Some(Kind::Enchanting) => { + if &*stack.item == "minecraft:lapis_lazuli" { + moved = self.move_to(&mut stack, &[INPUT + 1], true); + } else if self.station_slot_mut(INPUT).is_none() { + let one = ItemStack { count: 1, ..stack.clone() }; + *self.station_slot_mut(INPUT) = Some(one); + stack.count -= 1; + moved = true; + } + } + Some(Kind::Grindstone) => { + let both = self.station.as_ref().is_some_and(|s| s.inputs.iter().all(Option::is_some)); + if !both { + moved = self.move_to(&mut stack, &[INPUT, INPUT + 1], false); + } + } + Some(Kind::Smithing) | Some(Kind::Anvil) | Some(Kind::Stonecutter) => { + let n = self.station.as_ref().map_or(0, |s| s.inputs.len()); + let inputs: Vec = (0..n).map(|i| INPUT + i).collect(); + moved = self.move_to(&mut stack, &inputs, false); + } + None => {} + } + if !moved { + let other: Vec = if slot < 9 { (9..36).collect() } else { (0..9).collect() }; + moved = self.move_to(&mut stack, &other, false); + } + moved + }; + if stack.count > 0 { + *self.slot_mut(slot) = Some(stack); + } + moved + } + fn play_at(&mut self, sound: &str, pos: [i32; 3], volume: f32, pitch: f32) { + let at = [f64::from(pos[0]) + 0.5, f64::from(pos[1]) + 0.5, f64::from(pos[2]) + 0.5]; + self.audio.play(sound, Some(at), volume, pitch); + } + fn give_or_drop(&mut self, stack: ItemStack) { + if let Some(rest) = self.give(stack) + && let Some(eye) = self.eye_position() + { + self.spawn_item(rest, [eye[0], eye[1] - 0.3, eye[2]], [0.0, 0.1, 0.0], 40); + } + } + /// `Player.giveExperienceLevels`. + pub(super) fn give_levels(&mut self, levels: i32) { + let xp = &mut self.experience; + xp.level = xp.level.saturating_add(levels); + if xp.level < 0 { + xp.level = 0; + xp.progress = 0.0; + xp.total = 0; + } + } + /// Whether the result slot may be taken (`mayPickup`). + fn may_take_result(&self) -> bool { + let Some(s) = self.station.as_ref() else { return false }; + match s.kind { + Kind::Anvil => (self.creative || self.experience.level >= s.anvil.cost) && s.anvil.cost > 0, + _ => true, + } + } + /// The result slot's `onTake`. + fn take_result(&mut self) { + let Some(mut s) = self.station.take() else { return }; + let pos = s.pos; + match s.kind { + Kind::Anvil => { + let cost = s.anvil.cost; + let repair = s.anvil.repair_item_count_cost; + if repair > 0 { + if let Some(a) = s.inputs[1].as_mut() + && a.count > repair + { + a.count -= repair; + } else { + s.inputs[1] = None; + } + } else if !s.anvil.only_renaming { + s.inputs[1] = None; + } + s.inputs[0] = None; + s.name.clear(); + if !self.creative { + self.give_levels(-cost); + } + let pitch = self.world.random.next_float() * 0.1 + 0.9; + if !self.creative && self.world.random.next_float() < 0.12 { + // AnvilBlock.damage + let state = self.world.block(pos[0], pos[1], pos[2]); + let name = self.res.facts.get(state).name.clone(); + let next = match &*name { + "minecraft:anvil" => Some("minecraft:chipped_anvil"), + "minecraft:chipped_anvil" => Some("minecraft:damaged_anvil"), + _ => None, + }; + match next { + Some(next) => { + let _ = self.set_state_named(pos, next, &["facing"]); + self.play_at("minecraft:block.anvil.use", pos, 1.0, pitch); + } + None => { + let _ = self.world.set(pos[0], pos[1], pos[2], self.world.air); + self.world.modified.insert((pos[0] >> 4, pos[2] >> 4)); + self.play_at("minecraft:block.anvil.destroy", pos, 1.0, pitch); + self.station = Some(s); + self.close_station(); + self.screen = Screen::Playing; + self.capture(true); + return; + } + } + } else { + self.play_at("minecraft:block.anvil.use", pos, 1.0, pitch); + } + } + Kind::Grindstone => { + let (a, b) = (s.inputs[0].take(), s.inputs[1].take()); + let mut random = LegacyRandom::new(self.world.random.next_long()); + let xp = stations::grindstone_experience(&self.res.stations.enchantments, &mut random, a.as_ref(), b.as_ref()); + if xp > 0 { + self.spawn_orbs([f64::from(pos[0]) + 0.5, f64::from(pos[1]) + 0.5, f64::from(pos[2]) + 0.5], xp); + } + let pitch = self.world.random.next_float() * 0.1 + 0.9; + self.play_at("minecraft:block.grindstone.use", pos, 1.0, pitch); + } + Kind::Smithing => { + for slot in s.inputs.iter_mut() { + if let Some(x) = slot.as_mut() { + x.count -= 1; + if x.count == 0 { + *slot = None; + } + } + } + let pitch = self.world.random.next_float() * 0.1 + 0.9; + self.play_at("minecraft:block.smithing_table.use", pos, 1.0, pitch); + } + Kind::Stonecutter => { + if let Some(x) = s.inputs[0].as_mut() { + x.count -= 1; + if x.count == 0 { + s.inputs[0] = None; + } + } + if s.last_sound != self.ticks { + s.last_sound = self.ticks; + self.play_at("minecraft:ui.stonecutter.take_result", pos, 1.0, 1.0); + } + } + Kind::Enchanting => {} + } + self.station = Some(s); + self.station_changed(); + } + fn click_result(&mut self, shift: bool) { + loop { + let Some(result) = self.station.as_ref().and_then(|s| s.result.clone()) else { return }; + if !self.may_take_result() { + return; + } + if shift { + let mut stack = result.clone(); + let player = Self::player_slots(); + // Simulate first so nothing is lost when the inventory is full. + let saved: Vec> = self.inventory.clone(); + self.move_to(&mut stack, &player, true); + if stack.count > 0 { + self.inventory = saved; + return; + } + } else { + match &mut self.carried { + None => self.carried = Some(result.clone()), + Some(c) if c.same_item_same_components(&result) && c.count + result.count <= self.res.items.get(&c.item).map_or(64, |i| i.max_stack) => c.count += result.count, + _ => return, + } + } + if let Some(s) = self.station.as_mut() { + s.result = None; + } + self.take_result(); + let again = shift && self.station.as_ref().and_then(|s| s.result.as_ref()).is_some_and(|r| r.item == result.item); + if !again { + return; + } + } + } + /// `EnchantmentMenu.clickMenuButton`. + fn click_enchant(&mut self, button: usize) { + let Some(s) = self.station.as_ref() else { return }; + let cost = s.offers.costs[button]; + let lapis_needed = button as u32 + 1; + let Some(item) = s.inputs[0].clone() else { return }; + let lapis = s.inputs[1].as_ref().map_or(0, |l| l.count); + if lapis < lapis_needed && !self.creative { + return; + } + if cost <= 0 || (self.experience.level < lapis_needed as i32 || self.experience.level < cost) && !self.creative { + return; + } + let Some(enchanted) = stations::apply_enchantment(&self.res.stations.enchantments, &self.res.items, self.level.xp_seed, button, cost, &item) else { return }; + let pos = s.pos; + // Player.onEnchantmentPerformed + self.give_levels(-(lapis_needed as i32)); + self.level.xp_seed = self.world.random.next_int(); + if let Some(s) = self.station.as_mut() { + s.inputs[0] = Some(enchanted); + if !self.creative + && let Some(l) = s.inputs[1].as_mut() + { + l.count -= lapis_needed; + if l.count == 0 { + s.inputs[1] = None; + } + } + } + let pitch = self.world.random.next_float() * 0.1 + 0.9; + self.play_at("minecraft:block.enchantment_table.use", pos, 1.0, pitch); + self.station_changed(); + } + /// Mouse click while a station or the brewing stand is open. True when handled. + pub(super) fn station_click(&mut self, right: bool) -> bool { + if self.station.is_none() && !self.brewing_open() { + return false; + } + let Some(size) = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]) else { return true }; + let batch = HudBatch::new(size); + let (ox, oy) = self.inventory_origin(&batch); + let local = (self.cursor.0 - ox, self.cursor.1 - oy); + let shift = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft) || self.keys.contains(&winit::keyboard::KeyCode::ShiftRight); + if let Some(kind) = self.station.as_ref().map(|s| s.kind) { + if kind == Kind::Enchanting && !right { + for i in 0..3 { + let (x, y, w, h) = enchant_button(i); + if inside(local, x, y, w, h) { + self.click_enchant(i); + return true; + } + } + } + if kind == Kind::Stonecutter + && let Some(s) = self.station.as_ref() + && s.inputs[0].is_some() + { + for index in s.start..(s.start + 12).min(s.recipes.len()) { + let p = index - s.start; + let (x, y) = (52.0 + (p % 4) as f32 * 16.0, 14.0 + (p / 4) as f32 * 18.0); + if inside(local, x, y, 16.0, 18.0) { + if s.selected != Some(index) { + if let Some(st) = self.station.as_mut() { + st.selected = Some(index); + } + self.audio.play("minecraft:ui.stonecutter.select_recipe", None, 1.0, 1.0); + self.station_changed(); + } + return true; + } + } + } + } + let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { return true }; + if slot == RESULT { + self.click_result(shift); + return true; + } + if shift { + self.quick_move(slot); + } else if slot >= INPUT || (300..305).contains(&slot) { + self.click_filtered(slot, right); + } else { + return false; + } + if let Some(key) = self.container { + self.world.modified.insert((key.0 >> 4, key.2 >> 4)); + } + self.station_after_input(); + true + } + /// Recompute after slot changes; the anvil box follows its input item. + fn station_after_input(&mut self) { + let Some(s) = self.station.as_mut() else { return }; + if s.kind == Kind::Anvil && s.inputs[0] != s.anvil_last { + // AnvilScreen.slotChanged: the box shows the new input's name. + s.anvil_last = s.inputs[0].clone(); + s.name = s.inputs[0].as_ref().map(|i| stations::hover_name(&|id| self.res.names.item(id), i)).unwrap_or_default(); + } + self.station_changed(); + } + pub(super) fn station_scroll(&mut self, d: f32) { + let Some(s) = self.station.as_mut() else { return }; + if s.kind != Kind::Stonecutter || s.recipes.len() <= 12 { + return; + } + let rows = s.recipes.len().div_ceil(4) - 3; + let first_row = (s.start / 4) as i32 - d.signum() as i32; + s.start = first_row.clamp(0, rows as i32) as usize * 4; + } + /// Whether keyboard text goes to the anvil rename box. + pub(super) fn station_typing(&self) -> bool { + self.screen == Screen::Inventory && self.station.as_ref().is_some_and(|s| s.kind == Kind::Anvil && s.inputs[0].is_some()) + } + pub(super) fn station_text(&mut self, text: Option<&str>, backspace: bool) { + let Some(s) = self.station.as_mut() else { return }; + if backspace { + s.name.pop(); + } else if let Some(t) = text { + for c in t.chars().filter(|c| !c.is_control()) { + if s.name.chars().count() < 50 { + s.name.push(c); + } + } + } + self.station_changed(); + } + + // ---------------------------------------------------------------- drawing + + fn part(batch: &mut HudBatch, atlas: &horizon_client::hud::HudAtlas, name: &str, src: (f32, f32), size: (f32, f32), dst: (f32, f32)) { + if let Some(mut r) = atlas.sprites.get(name).copied() { + let (du, dv) = ((r.u1 - r.u0) / r.w as f32, (r.v1 - r.v0) / r.h as f32); + r.u0 += src.0 * du; + r.v0 += src.1 * dv; + r.u1 = r.u0 + size.0 * du; + r.v1 = r.v0 + size.1 * dv; + batch.rect_uv(dst.0, dst.1, size.0, size.1, r, u32::MAX); + } + } + /// Text in the Standard Galactic alphabet (`minecraft:alt`), cut to `max` pixels. + fn galactic(&self, batch: &mut HudBatch, text: &str, x: f32, y: f32, max: f32, color: u32) { + let atlas = &self.res.atlas; + let Some(sheet) = atlas.sprites.get("font/ascii_sga").copied() else { + batch.text(atlas, text, x, y, color, false); + return; + }; + let cell = sheet.w / 16; + let (px, py) = ((sheet.u0 * atlas.width as f32) as u32, (sheet.v0 * atlas.height as f32) as u32); + let mut cursor = x; + for ch in text.chars() { + let advance = if ch == ' ' { + 4.0 + } else { + let code = ch as u32; + if !(0x41..=0x5A).contains(&code) && !(0x61..=0x7A).contains(&code) { + continue; + } + let (col, row) = (code % 16, code / 16); + let (cx, cy) = (px + col * cell, py + row * cell); + let mut used = 0; + for dx in (0..cell).rev() { + if (0..cell).any(|dy| atlas.pixels[(((cy + dy) * atlas.width + cx + dx) * 4 + 3) as usize] != 0) { + used = dx + 1; + break; + } + } + let advance = (used as f32 * 8.0 / cell as f32 + 0.5).floor() + 1.0; + if cursor + advance - x > max { + break; + } + let r = horizon_client::hud::Rect { + u0: cx as f32 / atlas.width as f32, + v0: cy as f32 / atlas.height as f32, + u1: (cx + cell) as f32 / atlas.width as f32, + v1: (cy + cell) as f32 / atlas.height as f32, + w: cell, + h: cell, + }; + batch.rect_uv(cursor, y, 8.0, 8.0, r, color); + advance + }; + if cursor + advance - x > max { + break; + } + cursor += advance; + } + } + /// Draws the open station or brewing stand screen; false when none is open. + pub(super) fn draw_station(&mut self, batch: &mut HudBatch) -> bool { + let brewing = self.brewing_open(); + if self.station.is_none() && !brewing { + return false; + } + let (ox, oy) = self.inventory_origin(batch); + let local = (self.cursor.0 - ox, self.cursor.1 - oy); + let mut tooltip: Option> = None; + { + let atlas = &self.res.atlas; + batch.fill(atlas, 0.0, 0.0, batch.width, batch.height, rgba(16, 16, 16, 160)); + } + let inventory_label = self.translate("container.inventory", "Inventory"); + if brewing { + let Some(BlockEntity::Brewing(b)) = self.container_kind() else { return true }; + let (fuel, total_fuel, brew, total_brew) = (b.fuel, b.total_fuel, b.brew_time, b.total_brew_time); + let atlas = &self.res.atlas; + Self::part(batch, atlas, "gui/container/brewing_stand", (0.0, 0.0), (176.0, 166.0), (ox, oy)); + let fuel_len = if total_fuel > 0 { ((18 * fuel + total_fuel - 1) / total_fuel).clamp(0, 18) } else { 0 }; + if fuel_len > 0 { + Self::part(batch, atlas, "gui/sprites/container/brewing_stand/fuel_length", (0.0, 0.0), (fuel_len as f32, 4.0), (ox + 60.0, oy + 44.0)); + } + if brew > 0 && total_brew > 0 { + let len = (28.0 * (1.0 - brew as f32 / total_brew as f32)) as i32; + if len > 0 { + Self::part(batch, atlas, "gui/sprites/container/brewing_stand/brew_progress", (0.0, 0.0), (9.0, len as f32), (ox + 97.0, oy + 16.0)); + } + let bubble = [29, 24, 20, 16, 11, 6, 0][(brew / 2 % 7) as usize] as f32; + if bubble > 0.0 { + Self::part(batch, atlas, "gui/sprites/container/brewing_stand/bubbles", (0.0, 29.0 - bubble), (12.0, bubble), (ox + 63.0, oy + 14.0 + 29.0 - bubble)); + } + } + let title = self.translate("container.brewing", "Brewing Stand"); + 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_label, ox + 8.0, oy + 72.0, GREY, false); + // Empty-slot icons. + for (i, icon) in [(300, "potion"), (301, "potion"), (302, "potion"), (304, "brewing_fuel")] { + if self.slot_mut(i).is_none() { + let (sx, sy) = self.station_slot_position(i).unwrap_or_default(); + batch.sprite(&self.res.atlas, &format!("gui/sprites/container/slot/{icon}"), ox + sx, oy + sy); + } + } + } else if let Some(kind) = self.station.as_ref().map(|s| s.kind) { + let title = self.translate(kind.title_key(), ""); + let atlas = &self.res.atlas; + Self::part(batch, atlas, kind.texture(), (0.0, 0.0), (176.0, 166.0), (ox, oy)); + let (tx, ty) = kind.title_pos(); + batch.text(atlas, &title, ox + tx, oy + ty, GREY, false); + batch.text(atlas, &inventory_label, ox + 8.0, oy + 72.0, GREY, false); + let s = self.station.as_ref().expect("open station"); + let has_input = s.inputs.iter().any(Option::is_some); + match kind { + Kind::Enchanting => { + if s.inputs[1].is_none() { + batch.sprite(atlas, "gui/sprites/container/slot/lapis_lazuli", ox + 35.0, oy + 47.0); + } + let mut names = LegacyRandom::new(i64::from(self.level.xp_seed)); + let gold = s.inputs[1].as_ref().map_or(0, |l| l.count as i32); + let level = self.experience.level; + let offers = s.offers.clone(); + for i in 0..3 { + let (bx, by, bw, bh) = enchant_button(i); + let cost = offers.costs[i]; + if cost == 0 { + batch.sprite_scaled(atlas, "gui/sprites/container/enchanting_table/enchantment_slot_disabled", ox + bx, oy + by, bw, bh, u32::MAX); + continue; + } + let cost_text = cost.to_string(); + let text_width = 86.0 - HudBatch::text_width(atlas, &cost_text); + let count = names.next_int_bound(2).unwrap_or(0) + 3; + let words: Vec<&str> = (0..count).map(|_| WORDS[names.next_int_bound(WORDS.len() as i32).unwrap_or(0) as usize]).collect(); + let message = words.join(" "); + let col: i32; + let disabled = (gold < i as i32 + 1 || level < cost) && !self.creative; + if disabled { + batch.sprite_scaled(atlas, "gui/sprites/container/enchanting_table/enchantment_slot_disabled", ox + bx, oy + by, bw, bh, u32::MAX); + batch.sprite(atlas, &format!("gui/sprites/container/enchanting_table/level_{}_disabled", i + 1), ox + bx + 1.0, oy + by + 1.0); + let c = ((-9937334i32) & 16711422) >> 1; + let msg_color = argb(c | 0xFF00_0000u32 as i32); + self.galactic_deferred(batch, &message, ox + bx + 20.0, oy + by + 2.0, text_width, msg_color); + col = -12550384; + } else { + let hover = inside(local, bx, by, bw, bh); + let sprite = if hover { "enchantment_slot_highlighted" } else { "enchantment_slot" }; + batch.sprite_scaled(atlas, &format!("gui/sprites/container/enchanting_table/{sprite}"), ox + bx, oy + by, bw, bh, u32::MAX); + batch.sprite(atlas, &format!("gui/sprites/container/enchanting_table/level_{}", i + 1), ox + bx + 1.0, oy + by + 1.0); + let msg_color = if hover { -128 } else { -9937334 }; + self.galactic_deferred(batch, &message, ox + bx + 20.0, oy + by + 2.0, text_width, argb(msg_color)); + col = -8323296; + } + let atlas = &self.res.atlas; + let cw = HudBatch::text_width(atlas, &cost_text); + batch.text(atlas, &cost_text, ox + bx + 20.0 + 86.0 - cw, oy + by + 9.0, argb(col), true); + // Tooltip with the clue (EnchantmentScreen.extractRenderState). + if inside(local, bx, by, bw, 17.0) + && let Some((id, l)) = &offers.clues[i] + { + let e = &self.res.stations.enchantments; + let (name, _) = e.full_name(id, *l); + let clue = self.translate("container.enchant.clue", "%s . . . ?").replace("%s", &name); + let mut lines = vec![(clue, u32::MAX)]; + if !self.creative { + lines.push((String::new(), u32::MAX)); + if level < cost { + lines.push((self.translate("container.enchant.level.requirement", "Level Requirement: %s").replace("%s", &cost.to_string()), rgba(255, 85, 85, 255))); + } else { + let n = i + 1; + let lapis = if n == 1 { self.translate("container.enchant.lapis.one", "1 Lapis Lazuli") } else { self.translate("container.enchant.lapis.many", "%s Lapis Lazuli").replace("%s", &n.to_string()) }; + lines.push((lapis, if gold >= n as i32 { rgba(170, 170, 170, 255) } else { rgba(255, 85, 85, 255) })); + let levels = if n == 1 { self.translate("container.enchant.level.one", "1 Enchantment Level") } else { self.translate("container.enchant.level.many", "%s Enchantment Levels").replace("%s", &n.to_string()) }; + lines.push((levels, rgba(170, 170, 170, 255))); + } + } + tooltip = Some(lines); + } + } + } + Kind::Anvil => { + let field = if s.inputs[0].is_some() { "text_field" } else { "text_field_disabled" }; + batch.sprite_scaled(atlas, &format!("gui/sprites/container/anvil/{field}"), ox + 59.0, oy + 20.0, 110.0, 16.0, u32::MAX); + if has_input && s.result.is_none() { + batch.sprite(atlas, "gui/sprites/container/anvil/error", ox + 99.0, oy + 45.0); + } + if s.inputs[0].is_some() { + let blink = if (self.ticks / 6) % 2 == 0 { "_" } else { "" }; + batch.text(atlas, &format!("{}{blink}", s.name), ox + 62.0, oy + 24.0, u32::MAX, true); + } + let cost = s.anvil.cost; + if cost > 0 { + let mut color = argb(-8323296); + let line = if cost >= 40 && !self.creative { + color = argb(-40864); + Some(self.translate("container.repair.expensive", "Too Expensive!")) + } else if s.result.is_none() { + None + } else { + if !self.may_take_result() { + color = argb(-40864); + } + Some(self.translate("container.repair.cost", "Enchantment Cost: %1$s").replace("%1$s", &cost.to_string())) + }; + if let Some(line) = line { + let atlas = &self.res.atlas; + let tw = HudBatch::text_width(atlas, &line); + let tx = 176.0 - 8.0 - tw - 2.0; + batch.fill(atlas, ox + tx - 2.0, oy + 67.0, 176.0 - 8.0 - (tx - 2.0), 12.0, argb(1325400064)); + batch.text(atlas, &line, ox + tx, oy + 69.0, color, true); + } + } + } + Kind::Grindstone => { + if has_input && s.result.is_none() { + batch.sprite(atlas, "gui/sprites/container/grindstone/error", ox + 92.0, oy + 31.0); + } + } + Kind::Smithing => { + let icons = ["smithing_template_netherite_upgrade", "", ""]; + for (i, icon) in icons.iter().enumerate() { + if s.inputs[i].is_none() && !icon.is_empty() { + let (sx, sy) = kind.input_pos(i); + batch.sprite(atlas, &format!("gui/sprites/container/slot/{icon}"), ox + sx, oy + sy); + } + } + if s.inputs.iter().all(Option::is_some) && s.result.is_none() { + batch.sprite(atlas, "gui/sprites/container/smithing/error", ox + 65.0, oy + 46.0); + if inside(local, 65.0, 46.0, 28.0, 21.0) { + tooltip = Some(vec![(self.translate("container.upgrade.error_tooltip", "Item can't be upgraded this way"), u32::MAX)]); + } + } + } + Kind::Stonecutter => { + let display = s.inputs[0].is_some() && !s.recipes.is_empty(); + let active = display && s.recipes.len() > 12; + let rows = s.recipes.len().div_ceil(4).saturating_sub(3).max(1); + let offs = if active { (s.start / 4) as f32 / rows as f32 } else { 0.0 }; + let scroller = if active { "scroller" } else { "scroller_disabled" }; + batch.sprite(atlas, &format!("gui/sprites/container/stonecutter/{scroller}"), ox + 119.0, oy + 15.0 + (41.0 * offs).floor()); + if display { + let (start, selected) = (s.start, s.selected); + let shown: Vec<(usize, ItemStack)> = (start..(start + 12).min(s.recipes.len())).map(|i| (i, self.res.stations.recipes.stonecutting[s.recipes[i]].result.clone())).collect(); + for (index, result) in shown { + let p = index - start; + let (x, y) = (52.0 + (p % 4) as f32 * 16.0, 14.0 + (p / 4) as f32 * 18.0 + 2.0); + let hover = inside(local, x, y, 16.0, 18.0); + let sprite = if Some(index) == selected { "recipe_selected" } else if hover { "recipe_highlighted" } else { "recipe" }; + batch.sprite_scaled(&self.res.atlas, &format!("gui/sprites/container/stonecutter/{sprite}"), ox + x, oy + y - 1.0, 16.0, 18.0, u32::MAX); + self.draw_item(batch, &result, ox + x, oy + y); + if hover { + tooltip = Some(self.stack_tooltip(&result)); + } + } + } + } + } + } + for i in self.station_slots().unwrap_or_default() { + let Some((sx, sy)) = self.slot_position_any(i) else { continue }; + let stack = self.slot_mut(i).clone(); + if let Some(stack) = stack { + self.draw_item(batch, &stack, ox + sx, oy + sy); + } + } + if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { + let (sx, sy) = self.slot_position(slot); + batch.fill(&self.res.atlas, ox + sx, oy + sy, 16.0, 16.0, rgba(255, 255, 255, 128)); + if self.carried.is_none() + && tooltip.is_none() + && let Some(stack) = self.slot_mut(slot).clone() + { + tooltip = Some(self.stack_tooltip(&stack)); + } + } + if let Some(stack) = self.carried.clone() { + self.draw_item(batch, &stack, self.cursor.0 - 8.0, self.cursor.1 - 8.0); + } else if let Some(lines) = tooltip { + self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1); + } + true + } + fn galactic_deferred(&self, batch: &mut HudBatch, text: &str, x: f32, y: f32, max: f32, color: u32) { + self.galactic(batch, text, x, y, max, color); + } + fn slot_position_any(&self, i: usize) -> Option<(f32, f32)> { + self.station_slot_position(i).or_else(|| (i < 36).then(|| self.slot_position(i))) + } + + // ---------------------------------------------------------------- tooltips + + /// `ItemStack.getTooltipLines` subset: name in rarity colour, potion + /// effects, enchantments (gray, curses red), stored enchantments, trims. + pub(super) fn stack_tooltip(&self, stack: &ItemStack) -> Vec<(String, u32)> { + let e: &Enchantments = &self.res.stations.enchantments; + let props = e.props(&stack.item); + let mut rarity = props.map_or("common", |p| p.rarity.as_str()); + if !stack.enchantments().is_empty() { + rarity = match rarity { + "common" | "uncommon" => "rare", + "rare" => "epic", + r => r, + }; + } + let color = match rarity { + "uncommon" => rgba(255, 255, 85, 255), + "rare" => rgba(85, 255, 255, 255), + "epic" => rgba(255, 85, 255, 255), + _ => u32::MAX, + }; + let name = if let Some(n) = stack.custom_name() { + n.to_owned() + } else if stack.data().and_then(|d| d.potion.as_ref()).is_some() || stack.item.ends_with("potion") || &*stack.item == "minecraft:tipped_arrow" { + let key = brewing::potion_name_key(&stack.item, stack.potion()); + e.translate(&key).map_or_else(|| self.res.names.item(&stack.item), str::to_owned) + } else { + self.res.names.item(&stack.item) + }; + let mut lines = vec![(name, color)]; + if stack.item.ends_with("potion") || &*stack.item == "minecraft:tipped_arrow" { + let scale = match &*stack.item { + "minecraft:lingering_potion" => 0.25, + "minecraft:tipped_arrow" => 0.125, + _ => 1.0, + }; + for (line, cat) in brewing::tooltip(stack.potion(), scale, &|k| e.translate(k).map(str::to_owned)) { + let c = match cat { + brewing::Category::Beneficial => rgba(85, 85, 255, 255), + brewing::Category::Harmful => rgba(255, 85, 85, 255), + brewing::Category::Neutral => rgba(170, 170, 170, 255), + }; + lines.push((line, c)); + } + } + if let Some((material, pattern)) = stack.data().and_then(|d| d.trim.clone()) { + lines.push((e.translate("item.minecraft.smithing_template.upgrade").unwrap_or("Upgrade:").to_owned(), rgba(170, 170, 170, 255))); + let short = |s: &str| s.trim_start_matches("minecraft:").to_owned(); + let p = e.translate(&format!("trim_pattern.minecraft.{}", short(&pattern))).map_or_else(|| short(&pattern), str::to_owned); + let m = e.translate(&format!("trim_material.minecraft.{}", short(&material))).map_or_else(|| short(&material), str::to_owned); + lines.push((format!(" {p}"), rgba(170, 170, 170, 255))); + lines.push((format!(" {m}"), rgba(170, 170, 170, 255))); + } + for (text, curse) in e.tooltip(stack.stored_enchantments()).into_iter().chain(e.tooltip(stack.enchantments())) { + lines.push((text, if curse { rgba(255, 85, 85, 255) } else { rgba(170, 170, 170, 255) })); + } + if let Some(info) = self.res.items.get(&stack.item) + && info.max_damage > 0 + && stack.damage > 0 + && self.options_advanced_tooltips() + { + lines.push((format!("Durability: {} / {}", info.max_damage - stack.damage, info.max_damage), u32::MAX)); + } + lines + } + /// Menu state for the control socket. + pub(super) fn station_info(&self) -> serde_json::Value { + let Some(s) = self.station.as_ref() else { + return match self.container_kind() { + Some(BlockEntity::Brewing(b)) => serde_json::json!({ "brew_time": b.brew_time, "fuel": b.fuel }), + _ => serde_json::Value::Null, + }; + }; + let recipes = &self.res.stations.recipes.stonecutting; + serde_json::json!({ + "costs": s.offers.costs, + "clues": s.offers.clues.iter().map(|c| c.as_ref().map(|(e, l)| format!("{e} {l}"))).collect::>(), + "bookcases": s.bookcases, + "anvil_cost": s.anvil.cost, + "result": s.result.as_ref().map(|r| format!("{} x{}", r.item, r.count)), + "recipes": s.recipes.iter().map(|&i| recipes[i].id.clone()).collect::>(), + "selected": s.selected, + }) + } + fn options_advanced_tooltips(&self) -> bool { + false + } + /// `TooltipRenderUtil`: dark box with the purple border, first line spaced. + pub(super) fn draw_tooltip_lines(&self, batch: &mut HudBatch, lines: &[(String, u32)], x: f32, y: f32) { + if lines.is_empty() { + return; + } + let atlas = &self.res.atlas; + let w = lines.iter().map(|(t, _)| HudBatch::text_width(atlas, t)).fold(0.0, f32::max); + let h = if lines.len() == 1 { 8.0 } else { 8.0 + 2.0 + (lines.len() - 1) as f32 * 10.0 }; + let mut x = x + 12.0; + let mut y = y - 12.0; + if x + w > batch.width - 4.0 { + x = (x - 28.0 - w).max(4.0); + } + if y + h + 3.0 > batch.height { + y = batch.height - h - 3.0; + } + y = y.max(4.0); + batch.fill(atlas, x - 3.0, y - 4.0, w + 6.0, 1.0, rgba(16, 0, 16, 240)); + batch.fill(atlas, x - 3.0, y + h + 3.0, w + 6.0, 1.0, rgba(16, 0, 16, 240)); + batch.fill(atlas, x - 4.0, y - 3.0, w + 8.0, h + 6.0, rgba(16, 0, 16, 240)); + batch.fill(atlas, x - 3.0, y - 3.0, w + 6.0, 1.0, rgba(80, 0, 255, 80)); + batch.fill(atlas, x - 3.0, y + h + 2.0, w + 6.0, 1.0, rgba(40, 0, 127, 80)); + batch.fill(atlas, x - 3.0, y - 2.0, 1.0, h + 4.0, rgba(60, 0, 190, 80)); + batch.fill(atlas, x + w + 2.0, y - 2.0, 1.0, h + 4.0, rgba(60, 0, 190, 80)); + let mut ty = y; + for (i, (text, color)) in lines.iter().enumerate() { + batch.text(atlas, text, x, ty, *color, true); + ty += if i == 0 { 12.0 } else { 10.0 }; + } + } + /// Hovered-slot tooltip on the plain inventory, crafting and container screens. + pub(super) fn draw_slot_tooltip(&mut self, batch: &mut HudBatch) { + if self.carried.is_some() { + return; + } + 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() }; + if let Some(stack) = stack { + let lines = self.stack_tooltip(&stack); + self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1); + } + } + /// The enchantment glint over an item icon: a shimmering purple tint. + pub(super) fn draw_glint(&self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) { + if !self.res.stations.enchantments.has_glint(stack) { + return; + } + let phase = (self.started.elapsed().as_secs_f32() * 0.8).fract(); + let alpha = (105.0 + 45.0 * (phase * std::f32::consts::TAU).sin()) as u8; + let color = rgba(170, 80, 255, alpha); + match self.res.icons.get(&*stack.item).cloned().flatten() { + Some(super::Icon::Flat(name)) => batch.sprite_scaled(&self.res.atlas, &name, x, y, 16.0, 16.0, color), + Some(super::Icon::Cube { .. }) => batch.fill(&self.res.atlas, x + 1.0, y + 1.0, 14.0, 14.0, rgba(150, 70, 255, alpha / 2)), + None => {} + } + // A bright band sweeping diagonally, clipped to the 16x16 cell. + let band = phase * 32.0 - 8.0; + for i in 0..16 { + let bx = band + i as f32 * 0.5 - 4.0; + if (0.0..15.0).contains(&bx) { + batch.fill(&self.res.atlas, x + bx, y + i as f32, 1.0, 1.0, rgba(200, 150, 255, alpha / 2)); + } + } + } + + // ---------------------------------------------------------------- brewing stand + + /// Ticks every brewing stand (`BrewingStandBlockEntity.serverTick`). + pub(super) fn tick_brewing_stands(&mut self) -> horizon_client::Result<()> { + let mut changes = Vec::new(); + for (pos, entity) in self.world.block_entities.iter_mut() { + if let BlockEntity::Brewing(b) = entity { + let out = b.tick(&self.res.stations.brewing, &self.res.items, &self.res.providers); + if out != brewing::BrewTick::default() { + changes.push((*pos, out)); + } + } + } + for ((x, y, z), out) in changes { + self.world.modified.insert((x >> 4, z >> 4)); + if out.brewed { + self.play_at("minecraft:block.brewing_stand.brew", [x, y, z], 1.0, 1.0); + } + for d in out.drops { + self.pop_resource([x, y, z], d); + } + if let Some(bottles) = out.bottles { + let state = self.world.block(x, y, z); + if let Some(mut s) = self.res.assets.registry.state(state).cloned() + && AsRef::::as_ref(&s.name) == "minecraft:brewing_stand" + { + for (i, has) in bottles.iter().enumerate() { + s.properties.insert(format!("has_bottle_{i}"), has.to_string()); + } + if let Ok(id) = self.res.assets.registry.resolve(&s) { + self.world.set(x, y, z, id)?; + } + } + } + } + Ok(()) + } +} diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 45aea62db..da184a553 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -33,6 +33,8 @@ pub struct ItemInfo { pub attack_speed: f32, /// `cooking_fuel`: burn-time and speed-multiplier provider references. pub fuel: Option<(Value, Value)>, + /// `brewing_fuel`: uses and speed-multiplier provider references. + pub brewing_fuel: Option<(Value, Value)>, /// Item left behind after crafting/fuel use (e.g. bucket). pub remainder: Option, /// `equippable.slot` (head, chest, legs, feet, ...). @@ -178,6 +180,7 @@ impl Items { }) .collect(), fuel: c.get("minecraft:cooking_fuel").map(|f| (f["burn_time"].clone(), f["speed_multiplier"].clone())), + brewing_fuel: c.get("minecraft:brewing_fuel").map(|f| (f["uses"].clone(), f["speed_multiplier"].clone())), remainder: c["minecraft:use_remainder"]["id"].as_str().or(c["minecraft:crafting_remainder"]["id"].as_str()).or(c["minecraft:crafting_remainder"].as_str()).map(str::to_owned), attack_damage: modifier("minecraft:attack_damage"), attack_speed: modifier("minecraft:attack_speed"), diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index ece00a7ee..ebd9b2da3 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -6,6 +6,7 @@ pub mod attribute_updates; pub mod audio; pub mod biome; pub mod blocks; +pub mod brewing; pub mod chunk; pub mod clock; pub mod containers; diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 6c82a1b28..ccdd5ca82 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -107,6 +107,14 @@ fn encode_block_entity(p: (i32, i32, i32), e: &crate::containers::BlockEntity) - entries.push(("cooking_time_spent", Tag::Short(f.cooking_timer as i16))); entries.push(("cooking_total_time", Tag::Short(f.cooking_total as i16))); } + BlockEntity::Brewing(b) => { + entries.push(("Items", encode_items(&b.items))); + entries.push(("BrewTime", Tag::Int(b.brew_time))); + entries.push(("total_brew_time", Tag::Int(b.total_brew_time))); + entries.push(("Fuel", Tag::Int(b.fuel))); + entries.push(("total_fuel", Tag::Int(b.total_fuel))); + entries.push(("speed_multiplier", Tag::Float(b.speed.to_bits()))); + } } Tag::compound(entries) } @@ -131,6 +139,21 @@ fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers: f.cooking_timer = int("cooking_time_spent").unwrap_or(0); f.cooking_total = int("cooking_total_time").unwrap_or(200); } + BlockEntity::Brewing(b) => { + let items = decode_items(tag.get("Items"), 5); + b.items = [items[0].clone(), items[1].clone(), items[2].clone(), items[3].clone(), items[4].clone()]; + b.brew_time = int("BrewTime").unwrap_or(0); + b.total_brew_time = int("total_brew_time").unwrap_or(400); + if b.brew_time > 0 { + b.ingredient = b.items[3].as_ref().map(|s| s.item.clone()); + } + b.fuel = int("Fuel").unwrap_or(0); + b.total_fuel = int("total_fuel").unwrap_or(20); + b.speed = match tag.get("speed_multiplier") { + Some(Tag::Float(f)) => f32::from_bits(*f), + _ => 1.0, + }; + } } Some((pos, entity)) } diff --git a/crates/horizon-client/src/stations.rs b/crates/horizon-client/src/stations.rs index 9eabd9df8..d5495722d 100644 --- a/crates/horizon-client/src/stations.rs +++ b/crates/horizon-client/src/stations.rs @@ -12,6 +12,18 @@ use horizon_core::random::{LegacyRandom, RandomSource}; use serde_json::Value; use std::{collections::HashSet, fs, path::Path, sync::Arc}; +/// Everything the workstation menus read, loaded once with the resources. +pub struct StationData { + pub enchantments: Enchantments, + pub recipes: StationRecipes, + pub brewing: crate::brewing::Brewing, +} +impl StationData { + pub fn load(root: &Path, items: &Items) -> Self { + Self { enchantments: Enchantments::load(root), recipes: StationRecipes::load(root, items), brewing: crate::brewing::Brewing::load(root, items) } + } +} + // ---------------------------------------------------------------- enchanting /// `EnchantingTableBlock.BOOKSHELF_OFFSETS`: the 5x5 ring two blocks out, two high.