From 9d624d01751fc5ec2fcca5d4761af0af7ba80bd1 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:03:28 +0200 Subject: [PATCH 1/9] Add item components (enchantments, name, potion, trim) and the enchantment registry Item stacks carry vanilla's extra components, saved in chunk and player NBT. The enchantment registry loads from the data pack with ordered tags, the EnchantmentHelper cost/selection rules, value effects and level-based values, and the anvil, grindstone, smithing and stonecutter result rules. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/containers.rs | 2 +- crates/horizon-client/src/crafting.rs | 1 + crates/horizon-client/src/enchant.rs | 700 ++++++++++++++++++++++ crates/horizon-client/src/game.rs | 28 +- crates/horizon-client/src/game/control.rs | 1 + crates/horizon-client/src/item_data.rs | 261 ++++++++ crates/horizon-client/src/items.rs | 10 +- crates/horizon-client/src/lib.rs | 3 + crates/horizon-client/src/save.rs | 26 +- crates/horizon-client/src/stations.rs | 572 ++++++++++++++++++ 10 files changed, 1581 insertions(+), 23 deletions(-) create mode 100644 crates/horizon-client/src/enchant.rs create mode 100644 crates/horizon-client/src/item_data.rs create mode 100644 crates/horizon-client/src/stations.rs diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 2eed1860c..e53fb0531 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -208,7 +208,7 @@ impl Furnace { let item = f.item.clone(); f.count -= 1; if f.count == 0 { - self.items[1] = remainder(&item).map(|r| ItemStack { item: Arc::from(r), count: 1, damage: 0 }); + self.items[1] = remainder(&item).map(|r| ItemStack { item: Arc::from(r), count: 1, damage: 0, extra: None }); } } lit = true; diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index 6d2c876b3..ba8ddb74e 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -68,6 +68,7 @@ fn result(v: &Value) -> Option { item: Arc::from(v["id"].as_str()?), count: v["count"].as_u64().unwrap_or(1) as u32, damage: 0, + extra: None, }) } impl Recipes { diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-client/src/enchant.rs new file mode 100644 index 000000000..0204e951e --- /dev/null +++ b/crates/horizon-client/src/enchant.rs @@ -0,0 +1,700 @@ +//! Data-driven enchantments (`data/minecraft/enchantment/*.json`): the +//! registry, ordered enchantment tags, `EnchantmentHelper` selection and cost +//! rules used by the enchanting table, display names, and evaluation of the +//! value/attribute effect components (`LevelBasedValue`, `EnchantmentValueEffect` +//! and the loot-condition subset that enchantment requirements use). +use crate::items::{ItemStack, Items}; +use horizon_core::random::{LegacyRandom, RandomSource}; +use serde_json::Value; +use std::{ + collections::{BTreeMap, HashMap, HashSet}, + fs, + path::Path, + sync::Arc, +}; + +/// `Enchantment.Cost`: base + per_level_above_first * (level - 1). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Cost { + pub base: i32, + pub per_level: i32, +} +impl Cost { + fn parse(v: &Value) -> Self { + Self { base: v["base"].as_i64().unwrap_or(1) as i32, per_level: v["per_level_above_first"].as_i64().unwrap_or(0) as i32 } + } + pub fn calculate(self, level: u32) -> i32 { + self.base + self.per_level * (level as i32 - 1) + } +} +#[derive(Clone, Debug)] +pub struct Enchantment { + pub id: Arc, + pub description: String, + pub max_level: u32, + pub weight: u32, + pub anvil_cost: u32, + pub min_cost: Cost, + pub max_cost: Cost, + /// `supported_items` / `primary_items`: item ids or `#tags`. + pub supported: Vec, + pub primary: Option>, + pub exclusive: HashSet>, + pub slots: Vec, + pub effects: Value, +} +/// Item components the enchanting, anvil and smithing rules read. +#[derive(Clone, Debug, Default)] +pub struct ItemProps { + /// `minecraft:enchantable.value`. + pub enchantable: u32, + /// `minecraft:repairable.items` (ids or a `#tag`). + pub repairable: Vec, + pub glint: bool, + pub rarity: String, + /// `minecraft:provides_trim_material`. + pub trim_material: Option, + /// `minecraft:brewing_fuel` present. + pub brewing_fuel: bool, +} +pub struct Enchantments { + pub list: Vec, + index: HashMap, usize>, + /// Enchantment tags in vanilla `HolderSet` order (nested tags expanded in place). + pub tags: HashMap>>, + pub entity_tags: HashMap>, + pub damage_tags: HashMap>, + pub props: HashMap, ItemProps>, + lang: HashMap, +} + +fn string_list(v: &Value) -> Vec { + match v { + Value::String(s) => vec![s.clone()], + Value::Array(a) => a.iter().filter_map(|e| e.as_str().map(str::to_owned)).collect(), + _ => vec![], + } +} +fn read_tag_dir(dir: &Path) -> HashMap> { + fn walk(dir: &Path, base: &Path, out: &mut HashMap>) { + let Ok(entries) = fs::read_dir(dir) else { return }; + for e in entries.flatten() { + let p = e.path(); + if p.is_dir() { + walk(&p, base, out); + } else if p.extension().is_some_and(|x| x == "json") + && let Ok(rel) = p.strip_prefix(base) + && let Ok(bytes) = fs::read(&p) + && let Ok(v) = serde_json::from_slice::(&bytes) + { + let name = format!("minecraft:{}", rel.with_extension("").to_string_lossy().replace('\\', "/")); + let values = v["values"].as_array().into_iter().flatten().filter_map(|e| e.as_str().or_else(|| e["id"].as_str()).map(str::to_owned)).collect(); + out.insert(name, values); + } + } + } + let mut out = HashMap::new(); + walk(dir, dir, &mut out); + out +} +/// Expand a tag keeping first-seen order (`TagLoader` builds a linked set). +fn expand_ordered(name: &str, raw: &HashMap>, out: &mut Vec, depth: u32) { + if depth > 16 { + return; + } + for v in raw.get(name).into_iter().flatten() { + match v.strip_prefix('#') { + Some(t) => expand_ordered(t, raw, out, depth + 1), + None if !out.contains(v) => out.push(v.clone()), + None => {} + } + } +} +/// Roman numerals as in `enchantment.level.N` (falls back to the number). +pub fn level_name(level: u32) -> String { + const NAMES: [&str; 10] = ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"]; + NAMES.get(level.wrapping_sub(1) as usize).map_or_else(|| level.to_string(), |s| (*s).to_owned()) +} + +impl Enchantments { + pub fn load(root: &Path) -> Self { + let data = root.join("data/minecraft"); + let raw_tags = read_tag_dir(&data.join("tags/enchantment")); + let tags: HashMap>> = raw_tags + .keys() + .map(|k| { + let mut v = Vec::new(); + expand_ordered(k, &raw_tags, &mut v, 0); + (k.clone(), v.into_iter().map(|s| Arc::from(s.as_str())).collect()) + }) + .collect(); + let unordered = |raw: HashMap>| -> HashMap> { + raw.keys() + .map(|k| { + let mut v = Vec::new(); + expand_ordered(k, &raw, &mut v, 0); + (k.clone(), v.into_iter().collect()) + }) + .collect() + }; + let entity_tags = unordered(read_tag_dir(&data.join("tags/entity_type"))); + let damage_tags = unordered(read_tag_dir(&data.join("tags/damage_type"))); + // The registry lists entries sorted by id, like the data-pack loader. + let mut files: BTreeMap = BTreeMap::new(); + if let Ok(entries) = fs::read_dir(data.join("enchantment")) { + for e in entries.flatten() { + let p = e.path(); + if let (Some(stem), Ok(bytes)) = (p.file_stem().and_then(|s| s.to_str()), fs::read(&p)) + && let Ok(v) = serde_json::from_slice(&bytes) + { + files.insert(format!("minecraft:{stem}"), v); + } + } + } + let lang: HashMap = fs::read(root.join("assets/minecraft/lang/en_us.json")) + .ok() + .and_then(|b| serde_json::from_slice::>(&b).ok()) + .unwrap_or_default() + .into_iter() + .filter(|(k, _)| k.starts_with("enchantment.") || k.starts_with("effect.") || k.starts_with("item.minecraft.potion") || k.starts_with("item.minecraft.splash_potion") || k.starts_with("item.minecraft.lingering_potion") || k.starts_with("item.minecraft.tipped_arrow") || k.starts_with("trim_") || k.starts_with("potion.") || k.starts_with("container.") || k.starts_with("merchant.") || k.starts_with("entity.minecraft.villager")) + .collect(); + let mut list = Vec::new(); + for (id, v) in &files { + let exclusive = match &v["exclusive_set"] { + Value::String(s) if s.starts_with('#') => tags.get(&s[1..]).cloned().unwrap_or_default(), + other => string_list(other).into_iter().map(|s| Arc::from(s.as_str())).collect(), + }; + let key = v["description"]["translate"].as_str().unwrap_or(""); + list.push(Enchantment { + id: Arc::from(id.as_str()), + description: lang.get(key).cloned().unwrap_or_else(|| id.trim_start_matches("minecraft:").replace('_', " ")), + max_level: v["max_level"].as_u64().unwrap_or(1) as u32, + weight: v["weight"].as_u64().unwrap_or(1) as u32, + anvil_cost: v["anvil_cost"].as_u64().unwrap_or(0) as u32, + min_cost: Cost::parse(&v["min_cost"]), + max_cost: Cost::parse(&v["max_cost"]), + supported: string_list(&v["supported_items"]), + primary: v.get("primary_items").map(string_list), + exclusive: exclusive.into_iter().collect(), + slots: string_list(&v["slots"]), + effects: v["effects"].clone(), + }); + } + let index = list.iter().enumerate().map(|(i, e)| (e.id.clone(), i)).collect(); + let mut props = HashMap::new(); + if let Ok(bytes) = fs::read(root.join("items.json")) + && let Ok(raw) = serde_json::from_slice::>(&bytes) + { + for (id, c) in raw { + props.insert( + Arc::from(id.as_str()), + ItemProps { + enchantable: c["minecraft:enchantable"]["value"].as_u64().unwrap_or(0) as u32, + repairable: string_list(&c["minecraft:repairable"]["items"]), + glint: c["minecraft:enchantment_glint_override"].as_bool().unwrap_or(false), + rarity: c["minecraft:rarity"].as_str().unwrap_or("common").to_owned(), + trim_material: c["minecraft:provides_trim_material"].as_str().map(str::to_owned), + brewing_fuel: c.get("minecraft:brewing_fuel").is_some(), + }, + ); + } + } + Self { list, index, tags, entity_tags, damage_tags, props, lang } + } + pub fn get(&self, id: &str) -> Option<&Enchantment> { + self.index.get(id).map(|&i| &self.list[i]) + } + pub fn tag(&self, name: &str) -> &[Arc] { + self.tags.get(name.trim_start_matches('#')).map_or(&[], Vec::as_slice) + } + pub fn in_tag(&self, name: &str, id: &str) -> bool { + self.tag(name).iter().any(|e| &**e == id) + } + pub fn is_curse(&self, id: &str) -> bool { + self.in_tag("minecraft:curse", id) + } + pub fn translate(&self, key: &str) -> Option<&str> { + self.lang.get(key).map(String::as_str) + } + pub fn props(&self, item: &str) -> Option<&ItemProps> { + self.props.get(item) + } + pub fn enchantable(&self, item: &str) -> u32 { + self.props(item).map_or(0, |p| p.enchantable) + } + /// Whether `item` matches an id / `#tag` list. + pub fn item_in(items: &Items, specs: &[String], item: &str) -> bool { + specs.iter().any(|s| match s.strip_prefix('#') { + Some(tag) => items.item_tags.get(tag).is_some_and(|t| t.contains(item)), + None => s == item, + }) + } + /// `Enchantment.canEnchant` / `isSupportedItem`. + pub fn can_enchant(&self, items: &Items, id: &str, item: &str) -> bool { + self.get(id).is_some_and(|e| Self::item_in(items, &e.supported, item)) + } + /// `Enchantment.isPrimaryItem`. + pub fn is_primary(&self, items: &Items, e: &Enchantment, item: &str) -> bool { + Self::item_in(items, &e.supported, item) && e.primary.as_ref().is_none_or(|p| Self::item_in(items, p, item)) + } + /// `Enchantment.areCompatible`. + pub fn compatible(&self, a: &str, b: &str) -> bool { + if a == b { + return false; + } + let excl = |x: &str, y: &str| self.get(x).is_some_and(|e| e.exclusive.contains(y)); + !excl(a, b) && !excl(b, a) + } + /// `Enchantment.getFullname` as plain text and whether it is a curse (red). + pub fn full_name(&self, id: &str, level: u32) -> (String, bool) { + let Some(e) = self.get(id) else { return (format!("{id} {}", level_name(level)), false) }; + let mut name = e.description.clone(); + if level != 1 || e.max_level != 1 { + name.push(' '); + name.push_str(self.lang.get(&format!("enchantment.level.{level}")).map_or(&level_name(level), |s| s)); + } + (name, self.is_curse(id)) + } + /// Tooltip lines for a level list, in `#tooltip_order` then remaining order. + pub fn tooltip(&self, levels: &[(Arc, u32)]) -> Vec<(String, bool)> { + let order = self.tag("minecraft:tooltip_order"); + let mut out = Vec::new(); + for id in order { + if let Some((_, l)) = levels.iter().find(|(e, _)| e == id) { + out.push(self.full_name(id, *l)); + } + } + for (id, l) in levels { + if !order.contains(id) { + out.push(self.full_name(id, *l)); + } + } + out + } + /// Whether a stack draws the enchantment glint. + pub fn has_glint(&self, stack: &ItemStack) -> bool { + stack.has_any_enchantments() || self.props(&stack.item).is_some_and(|p| p.glint) + } + + // ---- Enchanting table (EnchantmentHelper) ---- + + /// `EnchantmentHelper.getEnchantmentCost`. + pub fn enchantment_cost(&self, random: &mut LegacyRandom, slot: usize, bookcases: i32, item: &str) -> i32 { + if self.enchantable(item) == 0 { + return 0; + } + let bookcases = bookcases.min(15); + let selected = next_int(random, 8) + 1 + (bookcases >> 1) + next_int(random, bookcases + 1); + match slot { + 0 => (selected / 3).max(1), + 1 => selected * 2 / 3 + 1, + _ => selected.max(bookcases * 2), + } + } + /// `EnchantmentHelper.getAvailableEnchantmentResults`. + pub fn available_results(&self, items: &Items, value: i32, item: &str, pool: &[Arc]) -> Vec<(Arc, u32)> { + let book = item == "minecraft:book"; + let mut out = Vec::new(); + for id in pool { + let Some(e) = self.get(id) else { continue }; + if !(book || self.is_primary(items, e, item)) { + continue; + } + for level in (1..=e.max_level).rev() { + if value >= e.min_cost.calculate(level) && value <= e.max_cost.calculate(level) { + out.push((e.id.clone(), level)); + break; + } + } + } + out + } + fn weighted(&self, random: &mut LegacyRandom, list: &[(Arc, u32)]) -> Option<(Arc, u32)> { + let total: i32 = list.iter().map(|(id, _)| self.get(id).map_or(0, |e| e.weight as i32)).sum(); + if total <= 0 { + return None; + } + let mut index = next_int(random, total); + for (id, l) in list { + index -= self.get(id).map_or(0, |e| e.weight as i32); + if index < 0 { + return Some((id.clone(), *l)); + } + } + None + } + /// `EnchantmentHelper.selectEnchantment`. + pub fn select(&self, items: &Items, random: &mut LegacyRandom, item: &str, cost: i32, pool: &[Arc]) -> Vec<(Arc, u32)> { + let mut results = Vec::new(); + let value = self.enchantable(item) as i32; + if value == 0 { + return results; + } + let mut cost = cost + 1 + next_int(random, value / 4 + 1) + next_int(random, value / 4 + 1); + let span = (random.next_float() + random.next_float() - 1.0) * 0.15; + cost = ((cost as f32 + cost as f32 * span).round() as i32).max(1); + let mut available = self.available_results(items, cost, item, pool); + if !available.is_empty() { + if let Some(first) = self.weighted(random, &available) { + results.push(first); + } + while next_int(random, 50) <= cost { + if let Some((last, _)) = results.last() { + let last = last.clone(); + available.retain(|(e, _)| self.compatible(&last, e)); + } + if available.is_empty() { + break; + } + if let Some(next) = self.weighted(random, &available) { + results.push(next); + } + cost /= 2; + } + } + results + } + + // ---- Effect components ---- + + /// Run `component` value effects of every enchantment on `stack` over `value`. + pub fn modify_value(&self, stack: Option<&ItemStack>, component: &str, ctx: &EffectContext<'_>, random: &mut LegacyRandom, value: f32) -> f32 { + let Some(stack) = stack else { return value }; + let mut value = value; + for (id, level) in stack.enchantments() { + value = self.modify_value_with(id, *level, component, ctx, random, value); + } + value + } + pub fn modify_value_with(&self, id: &str, level: u32, component: &str, ctx: &EffectContext<'_>, random: &mut LegacyRandom, mut value: f32) -> f32 { + let Some(e) = self.get(id) else { return value }; + for effect in e.effects[component].as_array().into_iter().flatten() { + if let Some(req) = effect.get("requirements") + && !self.condition(req, level, ctx, random) + { + continue; + } + value = apply_value_effect(&effect["effect"], level, random, value); + } + value + } + /// Whether `stack` has any enchantment providing `component`. + pub fn has_component(&self, stack: &ItemStack, component: &str) -> bool { + stack.enchantments().iter().any(|(id, _)| self.get(id).is_some_and(|e| e.effects.get(component).is_some())) + } + /// The highest level among enchantments on `stack` that have `component`. + pub fn component_level(&self, stack: &ItemStack, component: &str) -> u32 { + stack.enchantments().iter().filter(|(id, _)| self.get(id).is_some_and(|e| e.effects.get(component).is_some())).map(|(_, l)| *l).max().unwrap_or(0) + } + /// `minecraft:attributes` contributions of `stack`: (attribute, id, amount, operation). + pub fn attributes(&self, stack: &ItemStack) -> Vec<(String, String, f64, String)> { + let mut out = Vec::new(); + for (id, level) in stack.enchantments() { + let Some(e) = self.get(id) else { continue }; + for a in e.effects["minecraft:attributes"].as_array().into_iter().flatten() { + out.push(( + a["attribute"].as_str().unwrap_or("").to_owned(), + format!("{}.{}", a["id"].as_str().unwrap_or(""), level), + f64::from(level_value(&a["amount"], *level)), + a["operation"].as_str().unwrap_or("add_value").to_owned(), + )); + } + } + out + } + /// Sum of `add_value` amounts of one attribute from enchantments on `stack`. + pub fn attribute_add(&self, stack: Option<&ItemStack>, attribute: &str) -> f64 { + stack.map_or(0.0, |s| self.attributes(s).iter().filter(|a| a.0 == attribute && a.3 == "add_value").map(|a| a.2).sum()) + } + fn entity_matches(&self, spec: &Value, entity: Option<&str>) -> bool { + let Some(entity) = entity else { return false }; + match spec.as_str() { + Some(s) => match s.strip_prefix('#') { + Some(tag) => self.entity_tags.get(tag).is_some_and(|t| t.contains(entity)), + None => s == entity, + }, + None => string_list(spec).iter().any(|s| s == entity), + } + } + /// The loot-condition subset enchantment `requirements` use. + pub fn condition(&self, c: &Value, level: u32, ctx: &EffectContext<'_>, random: &mut LegacyRandom) -> bool { + match c["type"].as_str().or(c["condition"].as_str()).unwrap_or("") { + "minecraft:inverted" => !self.condition(&c["term"], level, ctx, random), + "minecraft:all_of" => c["terms"].as_array().into_iter().flatten().all(|t| self.condition(t, level, ctx, random)), + "minecraft:any_of" => c["terms"].as_array().into_iter().flatten().any(|t| self.condition(t, level, ctx, random)), + "minecraft:match_tool" => { + let Some(tool) = ctx.tool else { return false }; + let items = &c["predicate"]["items"]; + if items.is_null() { + return true; + } + string_list(items).iter().any(|s| match s.strip_prefix('#') { + Some(tag) => ctx.items.is_some_and(|i| i.item_tags.get(tag).is_some_and(|t| t.contains(tool))), + None => s == tool, + }) + } + "minecraft:damage_source_properties" => { + let p = &c["predicate"]; + if let Some(direct) = p["is_direct"].as_bool() + && direct != ctx.is_direct + { + return false; + } + p["tags"].as_array().into_iter().flatten().all(|t| { + let tag = t["id"].as_str().unwrap_or("").trim_start_matches('#'); + let has = ctx.damage_type.is_some_and(|d| self.damage_tags.get(tag).is_some_and(|s| s.contains(d))); + has == t["expected"].as_bool().unwrap_or(true) + }) + } + "minecraft:entity_properties" => { + let entity = match c["entity"].as_str().unwrap_or("this") { + "this" => ctx.this, + "attacker" => ctx.attacker, + "direct_attacker" => ctx.direct_attacker, + _ => None, + }; + let spec = &c["predicate"]["minecraft:entity_type"]; + let spec = if spec.is_null() { &c["predicate"]["type"] } else { spec }; + spec.is_null() && entity.is_some() || self.entity_matches(spec, entity) + } + "minecraft:random_chance" => { + let chance = match &c["chance"] { + Value::Object(o) if o.get("type").and_then(Value::as_str) == Some("minecraft:enchantment_level") => level_value(&c["chance"]["amount"], level), + v => v.as_f64().map_or_else(|| level_value(v, level), |f| f as f32), + }; + random.next_float() < chance + } + _ => false, + } + } +} +/// What enchantment requirement predicates can see. +#[derive(Clone, Copy, Default)] +pub struct EffectContext<'a> { + pub items: Option<&'a Items>, + /// The tool for `match_tool` (the enchanted item, or the ammo for ammo_use). + pub tool: Option<&'a str>, + /// Damage type id (e.g. `minecraft:fall`). + pub damage_type: Option<&'a str>, + pub is_direct: bool, + /// Entity type ids: the victim/user ("this"), attacker and direct attacker. + pub this: Option<&'a str>, + pub attacker: Option<&'a str>, + pub direct_attacker: Option<&'a str>, +} +fn next_int(random: &mut LegacyRandom, bound: i32) -> i32 { + random.next_int_bound(bound.max(1)).unwrap_or(0) +} +/// `LevelBasedValue.calculate`. +pub fn level_value(v: &Value, level: u32) -> f32 { + let l = level as f32; + match v { + Value::Number(n) => n.as_f64().unwrap_or(0.0) as f32, + Value::Object(o) => { + let f = |k: &str| o.get(k).and_then(Value::as_f64).unwrap_or(0.0) as f32; + match o.get("type").and_then(Value::as_str).unwrap_or("") { + "minecraft:linear" => f("base") + f("per_level_above_first") * (l - 1.0), + "minecraft:levels_squared" => l * l + f("added"), + "minecraft:clamped" => level_value(&o["value"], level).clamp(f("min"), f("max")), + "minecraft:fraction" => { + let d = level_value(&o["denominator"], level); + if d == 0.0 { 0.0 } else { level_value(&o["numerator"], level) / d } + } + "minecraft:exponent" => level_value(&o["base"], level).powf(level_value(&o["power"], level)), + "minecraft:lookup" => { + let values = o.get("values").and_then(Value::as_array); + match values.and_then(|a| a.get(level as usize - 1)) { + Some(v) => v.as_f64().unwrap_or(0.0) as f32, + None => level_value(&o["fallback"], level), + } + } + _ => f("value"), + } + } + _ => 0.0, + } +} +/// `EnchantmentValueEffect.process`. +pub fn apply_value_effect(effect: &Value, level: u32, random: &mut LegacyRandom, value: f32) -> f32 { + match effect["type"].as_str().unwrap_or("") { + "minecraft:add" => value + level_value(&effect["value"], level), + "minecraft:multiply" => value * level_value(&effect["factor"], level), + "minecraft:set" => level_value(&effect["value"], level), + "minecraft:remove_binomial" => { + let p = level_value(&effect["chance"], level); + let n = value; + let removed = if !(n <= 128.0) && !(n * p < 20.0) && !(n * (1.0 - p) < 20.0) { + let miu = (f64::from(n) * f64::from(p)).floor(); + let sigma = (f64::from(n) * f64::from(p) * f64::from(1.0 - p)).sqrt(); + ((miu + random.next_gaussian() * sigma).round() as i32).clamp(0, n as i32) + } else { + let mut d = 0; + for _ in 0..n as i32 { + if random.next_float() < p { + d += 1; + } + } + d + }; + n - removed as f32 + } + "minecraft:all_of" => effect["effects"].as_array().into_iter().flatten().fold(value, |v, e| apply_value_effect(e, level, random, v)), + _ => value, + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use serde_json::json; + + /// A small registry built from literal JSON matching the vanilla files. + pub fn sample() -> Enchantments { + let defs = [ + ("minecraft:sharpness", json!({"anvil_cost":1,"exclusive_set":"#minecraft:exclusive_set/damage","max_cost":{"base":21,"per_level_above_first":11},"max_level":5,"min_cost":{"base":1,"per_level_above_first":11},"primary_items":"#minecraft:enchantable/melee_weapon","supported_items":"#minecraft:enchantable/sharp_weapon","weight":10,"slots":["mainhand"],"effects":{"minecraft:damage":[{"effect":{"type":"minecraft:add","value":{"type":"minecraft:linear","base":1.0,"per_level_above_first":0.5}}}]}})), + ("minecraft:smite", json!({"anvil_cost":2,"exclusive_set":"#minecraft:exclusive_set/damage","max_cost":{"base":25,"per_level_above_first":8},"max_level":5,"min_cost":{"base":5,"per_level_above_first":8},"primary_items":"#minecraft:enchantable/melee_weapon","supported_items":"#minecraft:enchantable/weapon","weight":5,"effects":{"minecraft:damage":[{"effect":{"type":"minecraft:add","value":{"type":"minecraft:linear","base":2.5,"per_level_above_first":2.5}},"requirements":{"type":"minecraft:entity_properties","entity":"this","predicate":{"minecraft:entity_type":"#minecraft:sensitive_to_smite"}}}]}})), + ("minecraft:unbreaking", json!({"anvil_cost":2,"max_cost":{"base":55,"per_level_above_first":8},"max_level":3,"min_cost":{"base":5,"per_level_above_first":8},"supported_items":"#minecraft:enchantable/durability","weight":5,"effects":{"minecraft:item_damage":[{"effect":{"type":"minecraft:remove_binomial","chance":{"type":"minecraft:fraction","denominator":{"type":"minecraft:linear","base":2.0,"per_level_above_first":1.0},"numerator":{"type":"minecraft:linear","base":1.0,"per_level_above_first":1.0}}}}]}})), + ("minecraft:mending", json!({"anvil_cost":4,"max_cost":{"base":75,"per_level_above_first":25},"max_level":1,"min_cost":{"base":25,"per_level_above_first":25},"supported_items":"#minecraft:enchantable/durability","weight":2})), + ("minecraft:feather_falling", json!({"anvil_cost":2,"max_cost":{"base":11,"per_level_above_first":6},"max_level":4,"min_cost":{"base":5,"per_level_above_first":6},"supported_items":"#minecraft:enchantable/foot_armor","weight":5,"effects":{"minecraft:damage_protection":[{"effect":{"type":"minecraft:add","value":{"type":"minecraft:linear","base":3.0,"per_level_above_first":3.0}},"requirements":{"type":"minecraft:damage_source_properties","predicate":{"tags":[{"expected":true,"id":"#minecraft:is_fall"},{"expected":false,"id":"#minecraft:bypasses_invulnerability"}]}}}]}})), + ]; + let list: Vec = defs + .iter() + .map(|(id, v)| Enchantment { + id: Arc::from(*id), + description: id.trim_start_matches("minecraft:").into(), + max_level: v["max_level"].as_u64().unwrap() as u32, + weight: v["weight"].as_u64().unwrap() as u32, + anvil_cost: v["anvil_cost"].as_u64().unwrap() as u32, + min_cost: Cost::parse(&v["min_cost"]), + max_cost: Cost::parse(&v["max_cost"]), + supported: string_list(&v["supported_items"]), + primary: v.get("primary_items").map(string_list), + exclusive: if v["exclusive_set"].is_null() { HashSet::new() } else { [Arc::from("minecraft:sharpness"), Arc::from("minecraft:smite")].into_iter().collect() }, + slots: vec![], + effects: v["effects"].clone(), + }) + .collect(); + let index = list.iter().enumerate().map(|(i, e)| (e.id.clone(), i)).collect(); + let pool: Vec> = ["minecraft:feather_falling", "minecraft:sharpness", "minecraft:smite", "minecraft:unbreaking", "minecraft:mending"].iter().map(|s| Arc::from(*s)).collect(); + let mut tags = HashMap::new(); + tags.insert("minecraft:in_enchanting_table".to_owned(), pool[..4].to_vec()); + tags.insert("minecraft:tooltip_order".to_owned(), vec![Arc::from("minecraft:sharpness"), Arc::from("minecraft:unbreaking")]); + let mut entity_tags = HashMap::new(); + entity_tags.insert("minecraft:sensitive_to_smite".to_owned(), ["minecraft:zombie".to_owned()].into_iter().collect()); + let mut damage_tags = HashMap::new(); + damage_tags.insert("minecraft:is_fall".to_owned(), ["minecraft:fall".to_owned()].into_iter().collect()); + let mut props = HashMap::new(); + for (item, value) in [("minecraft:diamond_sword", 10), ("minecraft:iron_sword", 14), ("minecraft:book", 1), ("minecraft:iron_boots", 9)] { + props.insert(Arc::from(item), ItemProps { enchantable: value, ..Default::default() }); + } + Enchantments { list, index, tags, entity_tags, damage_tags, props, lang: HashMap::new() } + } + pub fn sample_items() -> Items { + let mut item_tags: HashMap> = HashMap::new(); + let swords = ["minecraft:diamond_sword", "minecraft:iron_sword"]; + for tag in ["enchantable/melee_weapon", "enchantable/sharp_weapon", "enchantable/weapon", "enchantable/durability"] { + item_tags.insert(format!("minecraft:{tag}"), swords.iter().map(|s| (*s).to_owned()).collect()); + } + item_tags.get_mut("minecraft:enchantable/durability").unwrap().insert("minecraft:iron_boots".into()); + item_tags.insert("minecraft:enchantable/foot_armor".into(), ["minecraft:iron_boots".to_owned()].into_iter().collect()); + Items::for_tests(item_tags) + } + + #[test] + fn level_based_values() { + assert_eq!(level_value(&json!({"type":"minecraft:linear","base":1.0,"per_level_above_first":0.5}), 5), 3.0); + assert_eq!(level_value(&json!({"type":"minecraft:levels_squared","added":1.0}), 3), 10.0); + assert_eq!(level_value(&json!({"type":"minecraft:fraction","numerator":{"type":"minecraft:linear","base":1.0,"per_level_above_first":1.0},"denominator":{"type":"minecraft:linear","base":2.0,"per_level_above_first":1.0}}), 3), 0.75); + assert_eq!(level_name(4), "IV"); + assert_eq!(Cost { base: 1, per_level: 11 }.calculate(5), 45); + } + + #[test] + fn enchanting_cost_matches_vanilla_formula() { + let e = sample(); + // Replays EnchantmentHelper.getEnchantmentCost draws by hand. + for seed in [0i64, 1, 42, -7, 123456] { + for bookcases in [0, 5, 15, 20] { + let mut a = LegacyRandom::new(seed); + let mut b = LegacyRandom::new(seed); + let costs: Vec = (0..3).map(|slot| e.enchantment_cost(&mut a, slot, bookcases, "minecraft:diamond_sword")).collect(); + let bc = bookcases.min(15); + let expect: Vec = (0..3) + .map(|slot| { + let s = b.next_int_bound(8).unwrap() + 1 + (bc >> 1) + b.next_int_bound(bc + 1).unwrap(); + match slot { + 0 => (s / 3).max(1), + 1 => s * 2 / 3 + 1, + _ => s.max(bc * 2), + } + }) + .collect(); + assert_eq!(costs, expect); + assert!(costs[2] <= 30); + } + } + assert_eq!(e.enchantment_cost(&mut LegacyRandom::new(0), 0, 15, "minecraft:stick"), 0); + } + + #[test] + fn selection_respects_costs_and_exclusivity() { + let e = sample(); + let items = sample_items(); + let pool = e.tag("minecraft:in_enchanting_table").to_vec(); + for seed in 0..200 { + let mut r = LegacyRandom::new(seed); + let picked = e.select(&items, &mut r, "minecraft:diamond_sword", 30, &pool); + assert!(!picked.is_empty()); + let has = |id: &str| picked.iter().any(|(p, _)| &**p == id); + assert!(!(has("minecraft:sharpness") && has("minecraft:smite")), "{picked:?}"); + assert!(!has("minecraft:feather_falling")); + for (id, l) in &picked { + assert!(*l >= 1 && *l <= e.get(id).unwrap().max_level); + } + } + // Books accept every enchantment in the pool. + let mut r = LegacyRandom::new(3); + let available = e.available_results(&items, 20, "minecraft:book", &pool); + assert!(available.iter().any(|(id, _)| &**id == "minecraft:feather_falling")); + assert!(e.select(&items, &mut r, "minecraft:stick", 30, &pool).is_empty()); + } + + #[test] + fn value_effects_and_requirements() { + let e = sample(); + let items = sample_items(); + let mut sword = ItemStack::new("minecraft:diamond_sword", 1); + sword.enchant("minecraft:sharpness", 5); + let mut r = LegacyRandom::new(1); + let ctx = EffectContext { items: Some(&items), this: Some("minecraft:zombie"), ..Default::default() }; + assert_eq!(e.modify_value(Some(&sword), "minecraft:damage", &ctx, &mut r, 0.0), 3.0); + let mut smite = ItemStack::new("minecraft:diamond_sword", 1); + smite.enchant("minecraft:smite", 2); + assert_eq!(e.modify_value(Some(&smite), "minecraft:damage", &ctx, &mut r, 0.0), 5.0); + let pig = EffectContext { this: Some("minecraft:pig"), ..ctx }; + assert_eq!(e.modify_value(Some(&smite), "minecraft:damage", &pig, &mut r, 0.0), 0.0); + let mut boots = ItemStack::new("minecraft:iron_boots", 1); + boots.enchant("minecraft:feather_falling", 4); + let fall = EffectContext { damage_type: Some("minecraft:fall"), ..Default::default() }; + assert_eq!(e.modify_value(Some(&boots), "minecraft:damage_protection", &fall, &mut r, 0.0), 12.0); + let lava = EffectContext { damage_type: Some("minecraft:lava"), ..Default::default() }; + assert_eq!(e.modify_value(Some(&boots), "minecraft:damage_protection", &lava, &mut r, 0.0), 0.0); + // Unbreaking III keeps about 1/4 of durability hits. + let mut tool = ItemStack::new("minecraft:diamond_sword", 1); + tool.enchant("minecraft:unbreaking", 3); + let kept: f32 = (0..4000).map(|_| e.modify_value(Some(&tool), "minecraft:item_damage", &ctx, &mut r, 1.0)).sum(); + assert!((800.0..1200.0).contains(&kept), "{kept}"); + } + + #[test] + fn names_and_tooltip_order() { + let e = sample(); + assert_eq!(e.full_name("minecraft:mending", 1).0, "mending"); + assert_eq!(e.full_name("minecraft:sharpness", 1).0, "sharpness I"); + let levels = vec![(Arc::from("minecraft:unbreaking"), 3), (Arc::from("minecraft:mending"), 1), (Arc::from("minecraft:sharpness"), 2)]; + let lines: Vec = e.tooltip(&levels).into_iter().map(|l| l.0).collect(); + assert_eq!(lines, ["sharpness II", "unbreaking III", "mending"]); + assert!(!e.compatible("minecraft:sharpness", "minecraft:smite")); + assert!(e.compatible("minecraft:sharpness", "minecraft:unbreaking")); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 6f6b063aa..1e22514fe 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -792,11 +792,11 @@ impl Game<'_> { PlayerEffect::OpenMenu => self.open_menu([pos.x, pos.y, pos.z]), PlayerEffect::Sleep => self.try_sleep([pos.x, pos.y, pos.z]), PlayerEffect::GiveItem(item) => { - if let Some(rest) = self.give(ItemStack { item, count: 1, damage: 0 }) { + if let Some(rest) = self.give(ItemStack { item, count: 1, damage: 0, extra: None }) { self.pop_resource([pos.x, pos.y, pos.z], rest); } } - PlayerEffect::DropItem(item) => self.pop_resource([pos.x, pos.y + 1, pos.z], ItemStack { item, count: 1, damage: 0 }), + PlayerEffect::DropItem(item) => self.pop_resource([pos.x, pos.y + 1, pos.z], ItemStack { item, count: 1, damage: 0, extra: None }), PlayerEffect::EatCake => { if let Some(p) = self.player.as_mut() { let food = &mut p.health.food; @@ -861,7 +861,7 @@ impl Game<'_> { if matches!(landing, Landing::Broken) { let item = self.res.facts.get(state).item.clone(); if &*item != "minecraft:air" { - self.pop_resource(pos, ItemStack { item, count: 1, damage: 0 }); + self.pop_resource(pos, ItemStack { item, count: 1, damage: 0, extra: None }); } } } @@ -2895,7 +2895,7 @@ impl Game<'_> { let mut inventory = vec![None; 36]; self.armor = [None, None, None, None]; for (slot, id, count, damage) in &level.inventory { - let stack = ItemStack { item: Arc::from(id.as_str()), count: *count, damage: *damage }; + let stack = ItemStack { item: Arc::from(id.as_str()), count: *count, damage: *damage, extra: level.inventory_components.get(slot).cloned() }; if (100..104).contains(slot) { self.armor[usize::from(103 - slot)] = Some(stack); } else if let Some(cell) = inventory.get_mut(usize::from(*slot)) { @@ -2904,7 +2904,7 @@ impl Game<'_> { } if self.creative && level.inventory.is_empty() && level.position.is_none() { for (i, name) in ["minecraft:grass_block", "minecraft:stone", "minecraft:oak_planks", "minecraft:glass", "minecraft:torch", "minecraft:oak_log", "minecraft:chest", "minecraft:furnace", "minecraft:diamond_pickaxe"].iter().enumerate() { - inventory[i] = Some(ItemStack { item: Arc::from(*name), count: 1, damage: 0 }); + inventory[i] = Some(ItemStack { item: Arc::from(*name), count: 1, damage: 0, extra: None }); } } let (yaw, pitch) = self.options.look.unwrap_or((level.rotation[0], level.rotation[1])); @@ -3350,7 +3350,7 @@ impl Game<'_> { self.audio.play(sound, Some(at(hit.pos)), 1.0, 1.0); if !self.creative { self.consume_held(); - let filled = ItemStack { item: Arc::from(filled), count: 1, damage: 0 }; + let filled = ItemStack { item: Arc::from(filled), count: 1, damage: 0, extra: None }; if self.inventory[self.selected].is_none() { self.inventory[self.selected] = Some(filled); } else if let Some(rest) = self.give(filled) @@ -3376,7 +3376,7 @@ impl Game<'_> { let sound = if item == "water_bucket" { "minecraft:item.bucket.empty" } else { "minecraft:item.bucket.empty_lava" }; self.audio.play(sound, Some(at(target)), 1.0, 1.0); if !self.creative { - self.inventory[self.selected] = Some(ItemStack { item: Arc::from("minecraft:bucket"), count: 1, damage: 0 }); + self.inventory[self.selected] = Some(ItemStack { item: Arc::from("minecraft:bucket"), count: 1, damage: 0, extra: None }); } return Ok(true); } @@ -3390,7 +3390,7 @@ impl Game<'_> { if let Some(result) = result { self.set_state_named(hit.pos, result, &[])?; if name == "rooted_dirt" { - self.pop_resource([hit.pos[0], hit.pos[1] - 1, hit.pos[2]], ItemStack { item: Arc::from("minecraft:hanging_roots"), count: 1, damage: 0 }); + self.pop_resource([hit.pos[0], hit.pos[1] - 1, hit.pos[2]], ItemStack { item: Arc::from("minecraft:hanging_roots"), count: 1, damage: 0, extra: None }); } self.audio.play("minecraft:item.hoe.till", Some(at(hit.pos)), 1.0, 1.0); self.damage_held(1); @@ -3961,7 +3961,7 @@ impl Game<'_> { batch.sprite(&self.res.atlas, &tab_sprite(&tab, true), ox + tx, oy + ty); for t in &tabs { let (tx, ty) = Creative::tab_position(t); - let stack = ItemStack { item: Arc::from(t.icon.as_str()), count: 1, damage: 0 }; + let stack = ItemStack { item: Arc::from(t.icon.as_str()), count: 1, damage: 0, extra: None }; self.draw_item(batch, &stack, ox + tx + 5.0, oy + ty + if t.top { 9.0 } else { 7.0 }); } let atlas = &self.res.atlas; @@ -3977,7 +3977,7 @@ impl Game<'_> { for c in 0..9 { let Some(item) = items.get((first + r) * 9 + c) else { continue }; let (x, y) = (ox + 9.0 + c as f32 * 18.0, oy + 18.0 + r as f32 * 18.0); - let stack = ItemStack { item: Arc::from(item.as_str()), count: 1, damage: 0 }; + let stack = ItemStack { item: Arc::from(item.as_str()), count: 1, damage: 0, extra: None }; self.draw_item(batch, &stack, x, y); if self.cursor.0 >= x && self.cursor.0 < x + 16.0 && self.cursor.1 >= y && self.cursor.1 < y + 16.0 { batch.fill(&self.res.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); @@ -4051,7 +4051,7 @@ impl Game<'_> { } let Some(item) = items.get((first + r) * 9 + c) else { return }; let max = self.res.items.get(item).map_or(64, |i| i.max_stack); - let stack = ItemStack { item: Arc::from(item.as_str()), count: if right { 1 } else { max }, damage: 0 }; + let stack = ItemStack { item: Arc::from(item.as_str()), count: if right { 1 } else { max }, damage: 0, extra: None }; if shift { let _ = self.give(stack); } else { @@ -4102,10 +4102,14 @@ impl Game<'_> { .enumerate() .filter_map(|(i, s)| s.as_ref().map(|s| (i as u8, s.item.to_string(), s.count, s.damage))) .collect(); + level.inventory_components = self.inventory.iter().enumerate().filter_map(|(i, s)| Some((i as u8, s.as_ref()?.extra.clone()?))).collect(); // Vanilla stores armor in slots 100 (feet) to 103 (head). for (i, s) in self.armor.iter().enumerate() { if let Some(s) = s { level.inventory.push((103 - i as u8, s.item.to_string(), s.count, s.damage)); + if let Some(extra) = s.extra.clone() { + level.inventory_components.insert(103 - i as u8, extra); + } } } level.dimension = self.dim.id().to_owned(); @@ -4299,7 +4303,7 @@ impl Game<'_> { let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); let item = self.res.facts.get(state).item.clone(); if &*item != "minecraft:air" { - self.inventory[self.selected] = Some(ItemStack { item, count: 1, damage: 0 }); + self.inventory[self.selected] = Some(ItemStack { item, count: 1, damage: 0, extra: None }); } } } diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index f6b2bdcc6..f645f4a8f 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -174,6 +174,7 @@ impl Game<'_> { item: item.as_str().into(), count: n, damage: 0, + extra: None, }) .map_or(0, |r| r.count); given += n - rest; diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs new file mode 100644 index 000000000..7eb995762 --- /dev/null +++ b/crates/horizon-client/src/item_data.rs @@ -0,0 +1,261 @@ +//! Item stack components beyond count and damage: enchantments, stored +//! (book) enchantments, `repair_cost`, `custom_name`, `potion_contents` and +//! `trim`, with their NBT form in vanilla's `components` compound. +use crate::items::ItemStack; +use horizon_world::nbt::{JavaString, Tag}; +use std::sync::Arc; + +/// Enchantment id and level, in insertion order. +pub type Levels = Vec<(Arc, u32)>; + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct StackData { + /// `minecraft:enchantments`. + pub enchantments: Levels, + /// `minecraft:stored_enchantments` (enchanted books). + pub stored_enchantments: Levels, + /// `minecraft:repair_cost` (anvil prior-work penalty). + pub repair_cost: u32, + /// `minecraft:custom_name` as plain text. + pub custom_name: Option, + /// `minecraft:potion_contents.potion`. + pub potion: Option>, + /// `minecraft:trim`: (material, pattern). + pub trim: Option<(Arc, Arc)>, +} +impl StackData { + pub fn is_empty(&self) -> bool { + *self == Self::default() + } +} + +impl ItemStack { + pub fn new(item: &str, count: u32) -> Self { + Self { item: Arc::from(item), count, damage: 0, extra: None } + } + pub fn data(&self) -> Option<&StackData> { + self.extra.as_deref() + } + pub fn data_mut(&mut self) -> &mut StackData { + self.extra.get_or_insert_with(Box::default) + } + /// Drops an all-default component box so equal stacks compare equal. + pub fn tidy(&mut self) { + if self.extra.as_ref().is_some_and(|d| d.is_empty()) { + self.extra = None; + } + } + pub fn enchantments(&self) -> &[(Arc, u32)] { + self.data().map_or(&[], |d| &d.enchantments) + } + pub fn stored_enchantments(&self) -> &[(Arc, u32)] { + self.data().map_or(&[], |d| &d.stored_enchantments) + } + /// `EnchantmentHelper.getItemEnchantmentLevel` (0 when absent). + pub fn enchantment_level(&self, id: &str) -> u32 { + self.enchantments().iter().find(|(e, _)| &**e == id).map_or(0, |(_, l)| *l) + } + /// The component an anvil/grindstone works on: stored for books. + pub fn crafting_enchantments(&self) -> &[(Arc, u32)] { + if &*self.item == "minecraft:enchanted_book" { self.stored_enchantments() } else { self.enchantments() } + } + pub fn set_crafting_enchantments(&mut self, levels: Levels) { + if &*self.item == "minecraft:enchanted_book" { + self.data_mut().stored_enchantments = levels; + } else { + self.data_mut().enchantments = levels; + } + self.tidy(); + } + /// `ItemStack.enchant`: upgrade to the higher level. + pub fn enchant(&mut self, id: &str, level: u32) { + let book = &*self.item == "minecraft:enchanted_book"; + let data = self.data_mut(); + let list = if book { &mut data.stored_enchantments } else { &mut data.enchantments }; + upgrade(list, id, level); + } + pub fn has_any_enchantments(&self) -> bool { + !self.enchantments().is_empty() || !self.stored_enchantments().is_empty() + } + pub fn repair_cost(&self) -> u32 { + self.data().map_or(0, |d| d.repair_cost) + } + pub fn custom_name(&self) -> Option<&str> { + self.data().and_then(|d| d.custom_name.as_deref()) + } + pub fn potion(&self) -> Option<&str> { + self.data().and_then(|d| d.potion.as_deref()) + } + pub fn with_potion(mut self, potion: &str) -> Self { + self.data_mut().potion = Some(Arc::from(potion)); + self + } + /// `ItemStack.isSameItemSameComponents`. + pub fn same_item_same_components(&self, other: &Self) -> bool { + self.item == other.item && self.damage == other.damage && self.data() == other.data() + } + /// `ItemStack.transmuteCopy`: another item keeping every component. + pub fn transmute(&self, item: &str, count: u32) -> Self { + let mut stack = Self { item: Arc::from(item), count, ..self.clone() }; + stack.tidy(); + stack + } +} +/// `ItemEnchantments.Mutable.upgrade`. +pub fn upgrade(list: &mut Levels, id: &str, level: u32) { + if level == 0 { + return; + } + match list.iter_mut().find(|(e, _)| &**e == id) { + Some((_, l)) => *l = (*l).max(level), + None => list.push((Arc::from(id), level)), + } +} +/// `ItemEnchantments.Mutable.set` (level 0 removes). +pub fn set_level(list: &mut Levels, id: &str, level: u32) { + if level == 0 { + list.retain(|(e, _)| &**e != id); + } else { + match list.iter_mut().find(|(e, _)| &**e == id) { + Some((_, l)) => *l = level, + None => list.push((Arc::from(id), level)), + } + } +} + +fn levels_tag(levels: &Levels) -> Tag { + Tag::compound(levels.iter().map(|(id, l)| (&**id, Tag::Int(*l as i32)))) +} +fn int(t: &Tag) -> Option { + match t { + Tag::Byte(v) => Some(i64::from(*v)), + Tag::Short(v) => Some(i64::from(*v)), + Tag::Int(v) => Some(i64::from(*v)), + Tag::Long(v) => Some(*v), + _ => None, + } +} +fn string(t: &Tag) -> Option { + match t { + Tag::String(s) => Some(s.to_string_lossy()), + _ => None, + } +} +fn read_levels(t: Option<&Tag>) -> Levels { + let Some(Tag::Compound(map)) = t else { return Vec::new() }; + // Pre-1.21.5 worlds wrap the map in {levels: {...}}. + if let Some(Tag::Compound(inner)) = map.get(&JavaString::from("levels")) { + return inner.iter().filter_map(|(k, v)| Some((Arc::from(k.to_string_lossy().as_str()), int(v)?.clamp(1, 255) as u32))).collect(); + } + map.iter().filter_map(|(k, v)| Some((Arc::from(k.to_string_lossy().as_str()), int(v)?.clamp(1, 255) as u32))).collect() +} +/// A text component as stored by vanilla: a plain string or `{"text": ...}`. +fn read_text(t: &Tag) -> Option { + match t { + Tag::String(s) => Some(s.to_string_lossy()), + Tag::Compound(_) => t.get("text").and_then(string), + _ => None, + } +} + +/// The `components` compound for a stack, or None when every component is default. +pub fn encode_components(stack: &ItemStack) -> Option { + components_tag(stack.damage, stack.data()) +} +/// `encode_components` from the damage value and extra components. +pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option { + let mut entries: Vec<(&str, Tag)> = Vec::new(); + if damage > 0 { + entries.push(("minecraft:damage", Tag::Int(damage as i32))); + } + if let Some(d) = data { + if !d.enchantments.is_empty() { + entries.push(("minecraft:enchantments", levels_tag(&d.enchantments))); + } + if !d.stored_enchantments.is_empty() { + entries.push(("minecraft:stored_enchantments", levels_tag(&d.stored_enchantments))); + } + if d.repair_cost > 0 { + entries.push(("minecraft:repair_cost", Tag::Int(d.repair_cost as i32))); + } + if let Some(name) = &d.custom_name { + entries.push(("minecraft:custom_name", Tag::String(name.as_str().into()))); + } + if let Some(potion) = &d.potion { + entries.push(("minecraft:potion_contents", Tag::compound([("potion", Tag::String((&**potion).into()))]))); + } + if let Some((material, pattern)) = &d.trim { + entries.push(( + "minecraft:trim", + Tag::compound([("material", Tag::String((&**material).into())), ("pattern", Tag::String((&**pattern).into()))]), + )); + } + } + (!entries.is_empty()).then(|| Tag::compound(entries)) +} +/// Damage and extra components from a stack's `components` compound. +pub fn decode_components(components: Option<&Tag>) -> (u32, Option>) { + let Some(c) = components else { return (0, None) }; + let damage = c.get("minecraft:damage").and_then(int).unwrap_or(0).max(0) as u32; + let potion = match c.get("minecraft:potion_contents") { + Some(Tag::String(s)) => Some(Arc::from(s.to_string_lossy().as_str())), + Some(t) => t.get("potion").and_then(string).map(|s| Arc::from(s.as_str())), + None => None, + }; + let data = StackData { + enchantments: read_levels(c.get("minecraft:enchantments")), + stored_enchantments: read_levels(c.get("minecraft:stored_enchantments")), + repair_cost: c.get("minecraft:repair_cost").and_then(int).unwrap_or(0).max(0) as u32, + custom_name: c.get("minecraft:custom_name").and_then(read_text), + potion, + trim: c.get("minecraft:trim").and_then(|t| { + Some((Arc::from(t.get("material").and_then(string)?.as_str()), Arc::from(t.get("pattern").and_then(string)?.as_str()))) + }), + }; + (damage, (!data.is_empty()).then(|| Box::new(data))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn components_round_trip() { + let mut stack = ItemStack::new("minecraft:diamond_sword", 1); + stack.damage = 12; + stack.enchant("minecraft:sharpness", 3); + stack.enchant("minecraft:unbreaking", 2); + stack.data_mut().repair_cost = 3; + stack.data_mut().custom_name = Some("Blade".into()); + let tag = encode_components(&stack).expect("components"); + let (damage, extra) = decode_components(Some(&tag)); + assert_eq!(damage, 12); + let back = ItemStack { damage, extra, ..ItemStack::new("minecraft:diamond_sword", 1) }; + assert_eq!(back.enchantment_level("minecraft:sharpness"), 3); + assert_eq!(back.enchantment_level("minecraft:unbreaking"), 2); + assert_eq!(back.repair_cost(), 3); + assert_eq!(back.custom_name(), Some("Blade")); + } + + #[test] + fn plain_stacks_have_no_components() { + let stack = ItemStack::new("minecraft:stone", 64); + assert!(encode_components(&stack).is_none()); + let mut named = stack.clone(); + named.data_mut(); + named.tidy(); + assert_eq!(named, stack); + } + + #[test] + fn books_store_enchantments() { + let mut book = ItemStack::new("minecraft:enchanted_book", 1); + book.enchant("minecraft:mending", 1); + assert!(book.enchantments().is_empty()); + assert_eq!(book.stored_enchantments().len(), 1); + upgrade(&mut book.data_mut().stored_enchantments, "minecraft:mending", 1); + assert_eq!(book.crafting_enchantments()[0].1, 1); + let book = ItemStack::new("minecraft:book", 1).transmute("minecraft:enchanted_book", 1); + assert!(book.extra.is_none()); + } +} diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 3caf4b445..45aea62db 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -45,6 +45,8 @@ pub struct ItemStack { pub item: Arc, pub count: u32, pub damage: u32, + /// Components beyond count and damage (see `item_data`); None when default. + pub extra: Option>, } pub struct Items { pub items: HashMap, ItemInfo>, @@ -206,6 +208,11 @@ impl Items { pub fn get(&self, id: &str) -> Option<&ItemInfo> { self.items.get(id) } + /// An item table with only tags, for unit tests of item rules. + #[cfg(test)] + pub fn for_tests(item_tags: HashMap>) -> Self { + Self { items: HashMap::new(), order: Vec::new(), block_tags: HashMap::new(), item_tags, loot: HashMap::new() } + } fn block_matches(&self, spec: &str, block: &str) -> bool { match spec.strip_prefix('#') { Some(tag) => self.block_tags.get(tag).is_some_and(|s| s.contains(block)), @@ -438,6 +445,7 @@ impl LootContext<'_> { item: Arc::from(e["name"].as_str().unwrap_or("minecraft:air")), count: 1, damage: 0, + extra: None, }, e["modifier"].clone(), )); @@ -466,7 +474,7 @@ impl LootContext<'_> { true } "minecraft:empty" => { - out.push((e["weight"].as_i64().unwrap_or(1) as i32, ItemStack { item: Arc::from("minecraft:air"), count: 0, damage: 0 }, Value::Null)); + out.push((e["weight"].as_i64().unwrap_or(1) as i32, ItemStack { item: Arc::from("minecraft:air"), count: 0, damage: 0, extra: None }, Value::Null)); true } _ => false, diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 00265cade..ece00a7ee 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -11,6 +11,7 @@ pub mod clock; pub mod containers; pub mod control; pub mod crafting; +pub mod enchant; pub mod creative; pub mod collisions; pub mod entities; @@ -20,6 +21,7 @@ pub mod health; pub mod hud; pub mod hunger; pub mod input; +pub mod item_data; pub mod items; pub mod landing; pub mod light; @@ -33,6 +35,7 @@ pub mod save; pub mod settings; pub mod sprint; pub mod sprites; +pub mod stations; pub mod streaming; pub mod testgen; pub mod title; diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 6997be4f8..6c82a1b28 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -62,8 +62,8 @@ fn encode_items(slots: &[Option]) -> Tag { ("id", string(&s.item)), ("count", Tag::Int(s.count as i32)), ]; - if s.damage > 0 { - entries.push(("components", Tag::compound([("minecraft:damage", Tag::Int(s.damage as i32))]))); + if let Some(components) = crate::item_data::encode_components(s) { + entries.push(("components", components)); } Some(Tag::compound(entries)) }) @@ -81,12 +81,9 @@ fn decode_items(tag: Option<&Tag>, size: usize) -> Vec *c as u32, _ => 1, }; - let damage = match it.get("components").and_then(|c| c.get("minecraft:damage")) { - Some(Tag::Int(d)) => *d as u32, - _ => 0, - }; + let (damage, extra) = crate::item_data::decode_components(it.get("components")); if let Some(cell) = slots.get_mut(*slot as u8 as usize) { - *cell = Some(crate::items::ItemStack { item: Arc::from(id.to_string_lossy().as_str()), count, damage }); + *cell = Some(crate::items::ItemStack { item: Arc::from(id.to_string_lossy().as_str()), count, damage, extra }); } } } @@ -362,6 +359,10 @@ pub struct Level { pub food: i32, pub saturation: f32, pub inventory: Vec<(u8, String, u32, u32)>, + /// Extra item components of `inventory` entries, by slot. + pub inventory_components: HashMap>, + /// Player.XpSeed: the enchanting table seed. + pub xp_seed: i32, pub xp_level: i32, pub xp_progress: f32, pub xp_total: i32, @@ -392,6 +393,7 @@ impl Level { let player = data.get("Player"); let float = |t: Option<&Tag>| if let Some(Tag::Float(b)) = t { f32::from_bits(*b) } else { 0.0 }; let mut inventory = Vec::new(); + let mut inventory_components = HashMap::new(); if let Some(Tag::List(items)) = player.and_then(|p| p.get("Inventory")) { for it in items { let slot = if let Some(Tag::Byte(s)) = it.get("Slot") { *s as u8 } else { continue }; @@ -401,6 +403,9 @@ impl Level { .get("components") .and_then(|c| c.get("minecraft:damage")) .map_or(0, |d| long(Some(d)) as u32); + if let (_, Some(extra)) = crate::item_data::decode_components(it.get("components")) { + inventory_components.insert(slot, extra); + } inventory.push((slot, id, count, damage)); } } @@ -439,7 +444,9 @@ impl Level { xp_level: player.map_or(0, |p| long(p.get("XpLevel")) as i32), xp_progress: player.map_or(0.0, |p| float(p.get("XpP"))), xp_total: player.map_or(0, |p| long(p.get("XpTotal")) as i32), + xp_seed: player.map_or(0, |p| long(p.get("XpSeed")) as i32), inventory, + inventory_components, }) } pub fn write(&self, dir: &Path) -> Result<()> { @@ -452,6 +459,7 @@ impl Level { ("XpLevel", Tag::Int(self.xp_level)), ("XpP", Tag::Float(self.xp_progress.to_bits())), ("XpTotal", Tag::Int(self.xp_total)), + ("XpSeed", Tag::Int(self.xp_seed)), ("playerGameType", Tag::Int(i32::from(self.creative))), ( "Rotation", @@ -468,8 +476,8 @@ impl Level { ("id", string(id)), ("count", Tag::Int(*count as i32)), ]; - if *damage > 0 { - entries.push(("components", Tag::compound([("minecraft:damage", Tag::Int(*damage as i32))]))); + if let Some(components) = crate::item_data::components_tag(*damage, self.inventory_components.get(slot).map(|d| &**d)) { + entries.push(("components", components)); } Tag::compound(entries) }) diff --git a/crates/horizon-client/src/stations.rs b/crates/horizon-client/src/stations.rs new file mode 100644 index 000000000..9eabd9df8 --- /dev/null +++ b/crates/horizon-client/src/stations.rs @@ -0,0 +1,572 @@ +//! Result rules of the workstation menus, ported from vanilla's +//! `EnchantmentMenu`, `AnvilMenu`, `GrindstoneMenu`, `SmithingMenu` (with +//! `SmithingTransformRecipe` / `SmithingTrimRecipe`) and `StonecutterMenu`. +//! Rendering and clicks live in the game; this module is pure item logic. +use crate::{ + crafting::Ingredient, + enchant::Enchantments, + item_data::{self, Levels}, + items::{ItemStack, Items}, +}; +use horizon_core::random::{LegacyRandom, RandomSource}; +use serde_json::Value; +use std::{collections::HashSet, fs, path::Path, sync::Arc}; + +// ---------------------------------------------------------------- enchanting + +/// `EnchantingTableBlock.BOOKSHELF_OFFSETS`: the 5x5 ring two blocks out, two high. +pub fn bookshelf_offsets() -> Vec<[i32; 3]> { + let mut v = Vec::new(); + for x in -2i32..=2 { + for z in -2i32..=2 { + if x.abs() == 2 || z.abs() == 2 { + for y in 0..=1 { + v.push([x, y, z]); + } + } + } + } + v +} +/// The three offers of `EnchantmentMenu.slotsChanged`. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct EnchantOffers { + pub costs: [i32; 3], + /// Shown clue: enchantment and level (`enchantClue` / `levelClue`). + pub clues: [Option<(Arc, u32)>; 3], +} +/// `EnchantmentMenu.getEnchantmentList`. +pub fn enchantment_list(e: &Enchantments, items: &Items, seed: i32, slot: usize, cost: i32, item: &str) -> Levels { + let mut random = LegacyRandom::new(i64::from(seed.wrapping_add(slot as i32))); + let pool = e.tag("minecraft:in_enchanting_table").to_vec(); + let mut list = e.select(items, &mut random, item, cost, &pool); + if item == "minecraft:book" && list.len() > 1 { + let i = random.next_int_bound(list.len() as i32).unwrap_or(0) as usize; + list.remove(i); + } + list +} +/// `EnchantmentMenu.slotsChanged` for an enchantable item. +pub fn enchant_offers(e: &Enchantments, items: &Items, seed: i32, bookcases: i32, stack: Option<&ItemStack>) -> EnchantOffers { + let mut offers = EnchantOffers::default(); + let Some(stack) = stack else { return offers }; + // ItemStack.isEnchantable: enchantable component and no enchantments yet. + if e.enchantable(&stack.item) == 0 || !stack.enchantments().is_empty() { + return offers; + } + let mut random = LegacyRandom::new(i64::from(seed)); + for i in 0..3 { + offers.costs[i] = e.enchantment_cost(&mut random, i, bookcases, &stack.item); + if offers.costs[i] < i as i32 + 1 { + offers.costs[i] = 0; + } + } + for i in 0..3 { + if offers.costs[i] > 0 { + // getEnchantmentList reseeds the menu random; the clue draws continue from it. + let mut list_random = LegacyRandom::new(i64::from(seed.wrapping_add(i as i32))); + let pool = e.tag("minecraft:in_enchanting_table").to_vec(); + let mut list = e.select(items, &mut list_random, &stack.item, offers.costs[i], &pool); + if &*stack.item == "minecraft:book" && list.len() > 1 { + let r = list_random.next_int_bound(list.len() as i32).unwrap_or(0) as usize; + list.remove(r); + } + if !list.is_empty() { + let pick = list_random.next_int_bound(list.len() as i32).unwrap_or(0) as usize; + offers.clues[i] = Some(list[pick].clone()); + } + } + } + offers +} +/// `EnchantmentMenu.clickMenuButton` result: the enchanted item, or None. +pub fn apply_enchantment(e: &Enchantments, items: &Items, seed: i32, slot: usize, cost: i32, stack: &ItemStack) -> Option { + let list = enchantment_list(e, items, seed, slot, cost, &stack.item); + if list.is_empty() { + return None; + } + let mut out = if &*stack.item == "minecraft:book" { stack.transmute("minecraft:enchanted_book", stack.count) } else { stack.clone() }; + for (id, level) in list { + out.enchant(&id, level); + } + Some(out) +} + +// ---------------------------------------------------------------- anvil + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct AnvilResult { + pub result: Option, + /// Level cost (the `cost` data slot). + pub cost: i32, + /// Material items consumed from the second slot on take. + pub repair_item_count_cost: u32, + pub only_renaming: bool, +} +pub fn is_damageable(items: &Items, stack: &ItemStack) -> bool { + items.get(&stack.item).is_some_and(|i| i.max_damage > 0) +} +fn max_damage(items: &Items, stack: &ItemStack) -> i32 { + items.get(&stack.item).map_or(0, |i| i.max_damage as i32) +} +/// `ItemStack.isValidRepairItem`. +pub fn is_valid_repair_item(e: &Enchantments, items: &Items, stack: &ItemStack, material: &ItemStack) -> bool { + e.props(&stack.item).is_some_and(|p| Enchantments::item_in(items, &p.repairable, &material.item)) +} +/// `AnvilMenu.calculateIncreasedRepairCost`. +pub fn increased_repair_cost(cost: u32) -> u32 { + (u64::from(cost) * 2 + 1).min(i32::MAX as u64) as u32 +} +/// The display name the rename box starts with (`getHoverName`). +pub fn hover_name(names: &dyn Fn(&str) -> String, stack: &ItemStack) -> String { + stack.custom_name().map_or_else(|| names(&stack.item), str::to_owned) +} +/// `AnvilMenu.createResult`. `name` is the rename box text (None = untouched). +pub fn anvil_result( + e: &Enchantments, + items: &Items, + input: Option<&ItemStack>, + addition: Option<&ItemStack>, + name: Option<&str>, + hover_name: &str, + creative: bool, +) -> AnvilResult { + let fail = AnvilResult::default(); + let Some(input) = input else { return fail }; + // EnchantmentHelper.canStoreEnchantments: enchantable or enchanted book... every + // item with an enchantments component, which is all of them in 26.3. + let mut result = input.clone(); + let mut enchantments: Levels = input.crafting_enchantments().to_vec(); + let mut price: i64 = 0; + let tax: i64 = i64::from(input.repair_cost()) + i64::from(addition.map_or(0, ItemStack::repair_cost)); + let mut repair_item_count_cost = 0; + let mut naming_cost = 0; + if let Some(addition) = addition { + // addition.has(STORED_ENCHANTMENTS): only enchanted books carry that component. + let using_book = &*addition.item == "minecraft:enchanted_book"; + if is_damageable(items, &result) && is_valid_repair_item(e, items, input, addition) { + let max = max_damage(items, &result); + let mut repair = (result.damage as i32).min(max / 4); + if repair <= 0 { + return fail; + } + let mut count = 0; + while repair > 0 && count < addition.count { + result.damage = (result.damage as i32 - repair) as u32; + price += 1; + repair = (result.damage as i32).min(max / 4); + count += 1; + } + repair_item_count_cost = count; + } else { + if !using_book && (result.item != addition.item || !is_damageable(items, &result)) { + return fail; + } + if is_damageable(items, &result) && !using_book { + let max = max_damage(items, &result); + let remaining1 = max - input.damage as i32; + let remaining2 = max_damage(items, addition) - addition.damage as i32; + let additional = remaining2 + max * 12 / 100; + let remaining = remaining1 + additional; + let damage = (max - remaining).max(0); + if damage < result.damage as i32 { + result.damage = damage as u32; + price += 2; + } + } + let mut any_compatible = false; + let mut any_incompatible = false; + for (id, level) in addition.crafting_enchantments() { + let current = enchantments.iter().find(|(x, _)| x == id).map_or(0, |(_, l)| *l); + let mut level = if current == *level { level + 1 } else { (*level).max(current) }; + let Some(def) = e.get(id) else { continue }; + let mut compatible = e.can_enchant(items, id, &input.item); + if creative || &*input.item == "minecraft:enchanted_book" { + compatible = true; + } + for (other, _) in &enchantments { + if other != id && !e.compatible(id, other) { + compatible = false; + price += 1; + } + } + if !compatible { + any_incompatible = true; + } else { + any_compatible = true; + level = level.min(def.max_level); + item_data::set_level(&mut enchantments, id, level); + let mut fee = def.anvil_cost as i64; + if using_book { + fee = (fee / 2).max(1); + } + price += fee * i64::from(level); + if input.count > 1 { + price = 40; + } + } + } + if any_incompatible && !any_compatible { + return fail; + } + } + } + match name { + Some(n) if !n.trim().is_empty() => { + if n != hover_name { + naming_cost = 1; + price += 1; + result.data_mut().custom_name = Some(n.to_owned()); + } + } + _ => { + if input.custom_name().is_some() { + naming_cost = 1; + price += 1; + result.data_mut().custom_name = None; + } + } + } + let mut cost = if price <= 0 { 0 } else { (tax + price).clamp(0, i64::from(i32::MAX)) as i32 }; + let mut out = (price > 0).then_some(result); + let mut only_renaming = false; + if naming_cost == price && naming_cost > 0 { + if cost >= 40 { + cost = 39; + } + only_renaming = true; + } + if cost >= 40 && !creative { + out = None; + } + if let Some(r) = out.as_mut() { + let mut base = r.repair_cost().max(addition.map_or(0, ItemStack::repair_cost)); + if naming_cost != price || naming_cost == 0 { + base = increased_repair_cost(base); + } + r.data_mut().repair_cost = base; + r.set_crafting_enchantments(enchantments); + r.tidy(); + } + AnvilResult { result: out, cost, repair_item_count_cost, only_renaming } +} + +// ---------------------------------------------------------------- grindstone + +/// `GrindstoneMenu` slot filter: damageable or enchanted. +pub fn grindstone_accepts(items: &Items, stack: &ItemStack) -> bool { + is_damageable(items, stack) || stack.has_any_enchantments() +} +fn remove_non_curses(e: &Enchantments, mut item: ItemStack) -> ItemStack { + let kept: Levels = item.crafting_enchantments().iter().filter(|(id, _)| e.is_curse(id)).cloned().collect(); + let n = kept.len(); + item.set_crafting_enchantments(kept); + if &*item.item == "minecraft:enchanted_book" && item.stored_enchantments().is_empty() { + item = item.transmute("minecraft:book", item.count); + } + let mut cost = 0; + for _ in 0..n { + cost = increased_repair_cost(cost); + } + item.data_mut().repair_cost = cost; + item.tidy(); + item +} +/// `GrindstoneMenu.computeResult`. +pub fn grindstone_result(e: &Enchantments, items: &Items, input: Option<&ItemStack>, additional: Option<&ItemStack>) -> Option { + if input.is_none() && additional.is_none() { + return None; + } + if input.is_some_and(|s| s.count > 1) || additional.is_some_and(|s| s.count > 1) { + return None; + } + match (input, additional) { + (Some(a), Some(b)) => { + if a.item != b.item { + return None; + } + let durability = max_damage(items, a).max(max_damage(items, b)); + let remaining = (max_damage(items, a) - a.damage as i32) + (max_damage(items, b) - b.damage as i32) + durability * 5 / 100; + let mut count = 1; + if !is_damageable(items, a) { + let stack_max = items.get(&a.item).map_or(64, |i| i.max_stack); + if stack_max < 2 || a != b { + return None; + } + count = 2; + } + let mut out = ItemStack { count, ..a.clone() }; + if is_damageable(items, &out) { + out.damage = (durability - remaining).max(0) as u32; + } + // mergeEnchantsFrom + let mut levels = out.crafting_enchantments().to_vec(); + for (id, l) in b.crafting_enchantments() { + if !e.is_curse(id) || !levels.iter().any(|(x, _)| x == id) { + item_data::upgrade(&mut levels, id, *l); + } + } + out.set_crafting_enchantments(levels); + Some(remove_non_curses(e, out)) + } + (Some(s), None) | (None, Some(s)) => s.has_any_enchantments().then(|| remove_non_curses(e, s.clone())), + (None, None) => None, + } +} +/// Experience from the grindstone result slot's `getExperienceAmount`. +pub fn grindstone_experience(e: &Enchantments, random: &mut LegacyRandom, input: Option<&ItemStack>, additional: Option<&ItemStack>) -> u32 { + let from = |s: Option<&ItemStack>| -> i32 { + s.map_or(0, |s| { + s.crafting_enchantments().iter().filter(|(id, _)| !e.is_curse(id)).map(|(id, l)| e.get(id).map_or(0, |d| d.min_cost.calculate(*l))).sum() + }) + }; + let amount = from(input) + from(additional); + if amount > 0 { + let half = (f64::from(amount) / 2.0).ceil() as i32; + (half + random.next_int_bound(half).unwrap_or(0)) as u32 + } else { + 0 + } +} + +// ---------------------------------------------------------------- smithing & stonecutting + +#[derive(Clone, Debug)] +pub enum Smithing { + Transform { template: Ingredient, base: Ingredient, addition: Ingredient, result: String }, + Trim { template: Ingredient, base: Ingredient, addition: Ingredient, pattern: String }, +} +#[derive(Clone, Debug)] +pub struct Stonecutting { + pub id: String, + pub input: Ingredient, + pub result: ItemStack, +} +pub struct StationRecipes { + pub smithing: Vec, + /// Sorted by recipe id, the registry order vanilla lists them in. + pub stonecutting: Vec, + /// `trim_material` registry: id -> (asset name, description). + pub trim_materials: Vec<(String, String)>, +} +fn ingredient(v: &Value, items: &Items) -> Ingredient { + let mut set = HashSet::new(); + for s in match v { + Value::String(s) => vec![s.clone()], + Value::Array(a) => a.iter().filter_map(|x| x.as_str().map(str::to_owned)).collect(), + _ => vec![], + } { + match s.strip_prefix('#') { + Some(tag) => set.extend(items.item_tags.get(tag).into_iter().flatten().cloned()), + None => { + set.insert(s); + } + } + } + Ingredient(set) +} +impl StationRecipes { + pub fn load(root: &Path, items: &Items) -> Self { + let mut files: Vec<_> = fs::read_dir(root.join("data/minecraft/recipe")).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e == "json")).collect(); + files.sort(); + let mut smithing = Vec::new(); + let mut stonecutting = Vec::new(); + for p in files { + let Ok(bytes) = fs::read(&p) else { continue }; + let Ok(v) = serde_json::from_slice::(&bytes) else { continue }; + let id = format!("minecraft:{}", p.file_stem().and_then(|s| s.to_str()).unwrap_or("")); + match v["type"].as_str().unwrap_or("") { + "minecraft:smithing_transform" => smithing.push(Smithing::Transform { + template: ingredient(&v["template"], items), + base: ingredient(&v["base"], items), + addition: ingredient(&v["addition"], items), + result: v["result"]["id"].as_str().unwrap_or("minecraft:air").to_owned(), + }), + "minecraft:smithing_trim" => smithing.push(Smithing::Trim { + template: ingredient(&v["template"], items), + base: ingredient(&v["base"], items), + addition: ingredient(&v["addition"], items), + pattern: v["pattern"].as_str().unwrap_or("").to_owned(), + }), + "minecraft:stonecutting" => stonecutting.push(Stonecutting { + id, + input: ingredient(&v["ingredient"], items), + result: ItemStack::new(v["result"]["id"].as_str().unwrap_or("minecraft:air"), v["result"]["count"].as_u64().unwrap_or(1) as u32), + }), + _ => {} + } + } + let mut trim_materials = Vec::new(); + let mut tm: Vec<_> = fs::read_dir(root.join("data/minecraft/trim_material")).into_iter().flatten().flatten().map(|e| e.path()).collect(); + tm.sort(); + for p in tm { + if let Ok(bytes) = fs::read(&p) + && let Ok(v) = serde_json::from_slice::(&bytes) + { + let id = format!("minecraft:{}", p.file_stem().and_then(|s| s.to_str()).unwrap_or("")); + trim_materials.push((id, v["description"]["translate"].as_str().unwrap_or("").to_owned())); + } + } + Self { smithing, stonecutting, trim_materials } + } + /// Recipes whose input accepts `stack`, in display order. + pub fn stonecutter(&self, stack: &ItemStack) -> Vec<&Stonecutting> { + self.stonecutting.iter().filter(|r| r.input.test(stack)).collect() + } + fn slot_ok(&self, slot: usize, stack: &ItemStack) -> bool { + self.smithing.iter().any(|r| { + let (t, b, a) = match r { + Smithing::Transform { template, base, addition, .. } | Smithing::Trim { template, base, addition, .. } => (template, base, addition), + }; + [t, b, a][slot].test(stack) + }) + } + /// `RecipePropertySet` SMITHING_TEMPLATE / BASE / ADDITION. + pub fn smithing_accepts(&self, slot: usize, stack: &ItemStack) -> bool { + slot < 3 && self.slot_ok(slot, stack) + } + /// `SmithingMenu.createResult`. + pub fn smithing_result(&self, e: &Enchantments, template: Option<&ItemStack>, base: Option<&ItemStack>, addition: Option<&ItemStack>) -> Option { + let (template, base, addition) = (template?, base?, addition?); + for r in &self.smithing { + match r { + Smithing::Transform { template: t, base: b, addition: a, result } => { + if t.test(template) && b.test(base) && a.test(addition) { + // SmithingTransformRecipe: transmute the base keeping its components. + return Some(base.transmute(result, 1)); + } + } + Smithing::Trim { template: t, base: b, addition: a, pattern } => { + if t.test(template) && b.test(base) && a.test(addition) { + let material = e.props(&addition.item)?.trim_material.clone()?; + let trim = (Arc::from(material.as_str()), Arc::from(pattern.as_str())); + if base.data().and_then(|d| d.trim.as_ref()) == Some(&trim) { + return None; + } + let mut out = ItemStack { count: 1, ..base.clone() }; + out.data_mut().trim = Some(trim); + return Some(out); + } + } + } + } + None + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::enchant::tests::{sample, sample_items}; + + fn sword(ench: &[(&str, u32)]) -> ItemStack { + let mut s = ItemStack::new("minecraft:diamond_sword", 1); + for (id, l) in ench { + s.enchant(id, *l); + } + s + } + fn book(ench: &[(&str, u32)]) -> ItemStack { + let mut s = ItemStack::new("minecraft:enchanted_book", 1); + for (id, l) in ench { + s.enchant(id, *l); + } + s + } + + #[test] + fn bookshelf_ring_has_32_positions() { + let o = bookshelf_offsets(); + assert_eq!(o.len(), 32); + assert!(o.contains(&[-2, 0, -2]) && o.contains(&[2, 1, 0]) && !o.contains(&[1, 0, 1])); + } + + #[test] + fn enchant_offers_are_deterministic_per_seed() { + let e = sample(); + let items = sample_items(); + let s = ItemStack::new("minecraft:diamond_sword", 1); + let a = enchant_offers(&e, &items, 1234, 15, Some(&s)); + let b = enchant_offers(&e, &items, 1234, 15, Some(&s)); + assert_eq!(a, b); + assert!(a.costs[2] >= 30 && a.costs[2] <= 30, "{a:?}"); + assert!(a.costs[0] >= 1 && a.costs[0] <= a.costs[2]); + // The clue is the first offer's random pick from the same list. + for slot in 0..3 { + let list = enchantment_list(&e, &items, 1234, slot, a.costs[slot], "minecraft:diamond_sword"); + let clue = a.clues[slot].clone().unwrap(); + assert!(list.contains(&clue)); + let applied = apply_enchantment(&e, &items, 1234, slot, a.costs[slot], &s).unwrap(); + assert_eq!(applied.enchantments(), &list[..]); + } + // Already enchanted items are not enchantable. + assert_eq!(enchant_offers(&e, &items, 1234, 15, Some(&sword(&[("minecraft:sharpness", 1)]))).costs, [0, 0, 0]); + let books = apply_enchantment(&e, &items, 99, 2, 30, &ItemStack::new("minecraft:book", 1)).unwrap(); + assert_eq!(&*books.item, "minecraft:enchanted_book"); + assert!(!books.stored_enchantments().is_empty()); + } + + #[test] + fn anvil_combines_and_charges_like_vanilla() { + let e = sample(); + let items = sample_items(); + // Sharpness II + Sharpness II book = Sharpness III; book fee 1/2 -> max(1, 0) = 1 per level. + let r = anvil_result(&e, &items, Some(&sword(&[("minecraft:sharpness", 2)])), Some(&book(&[("minecraft:sharpness", 2)])), None, "Diamond Sword", false); + let out = r.result.unwrap(); + assert_eq!(out.enchantment_level("minecraft:sharpness"), 3); + assert_eq!(r.cost, 3); + assert_eq!(out.repair_cost(), 1); + // Incompatible only: no result. + let r = anvil_result(&e, &items, Some(&sword(&[("minecraft:sharpness", 1)])), Some(&book(&[("minecraft:smite", 1)])), None, "Diamond Sword", false); + assert!(r.result.is_none()); + // Max level clamps: V + V stays V. + let r = anvil_result(&e, &items, Some(&sword(&[("minecraft:sharpness", 5)])), Some(&book(&[("minecraft:sharpness", 5)])), None, "x", false); + assert_eq!(r.result.unwrap().enchantment_level("minecraft:sharpness"), 5); + assert_eq!(r.cost, 5); + } + + #[test] + fn anvil_rename_and_prior_work() { + let e = sample(); + let items = sample_items(); + let mut s = sword(&[]); + s.data_mut().repair_cost = 7; + let r = anvil_result(&e, &items, Some(&s), None, Some("Excalibur"), "Diamond Sword", false); + assert_eq!(r.cost, 8); + assert!(r.only_renaming); + let out = r.result.unwrap(); + assert_eq!(out.custom_name(), Some("Excalibur")); + // Renaming alone does not raise the penalty. + assert_eq!(out.repair_cost(), 7); + // Same name: nothing to do. + assert!(anvil_result(&e, &items, Some(&s), None, Some("Diamond Sword"), "Diamond Sword", false).result.is_none()); + // Too expensive at 40+ unless creative; rename-only caps at 39. + s.data_mut().repair_cost = 63; + let r = anvil_result(&e, &items, Some(&s), None, Some("A"), "Diamond Sword", false); + assert_eq!(r.cost, 39); + assert!(r.result.is_some()); + let r = anvil_result(&e, &items, Some(&s), Some(&book(&[("minecraft:unbreaking", 1)])), None, "Diamond Sword", false); + assert!(r.cost >= 40 && r.result.is_none()); + assert!(anvil_result(&e, &items, Some(&s), Some(&book(&[("minecraft:unbreaking", 1)])), None, "Diamond Sword", true).result.is_some()); + assert_eq!(increased_repair_cost(0), 1); + assert_eq!(increased_repair_cost(3), 7); + } + + #[test] + fn grindstone_strips_non_curses() { + let e = sample(); + let items = sample_items(); + let s = sword(&[("minecraft:sharpness", 3)]); + let out = grindstone_result(&e, &items, Some(&s), None).unwrap(); + assert!(out.enchantments().is_empty()); + assert_eq!(out.repair_cost(), 0); + assert!(out.extra.is_none()); + let b = grindstone_result(&e, &items, None, Some(&book(&[("minecraft:mending", 1)]))).unwrap(); + assert_eq!(&*b.item, "minecraft:book"); + assert!(grindstone_result(&e, &items, Some(&sword(&[])), None).is_none()); + let mut r = LegacyRandom::new(5); + // min cost of Sharpness III = 23; ceil(23/2)=12 -> 12..23. + let xp = grindstone_experience(&e, &mut r, Some(&s), None); + assert!((12..24).contains(&xp)); + } +} 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 2/9] 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. From 7d26eca09afae6be111e7565a638af074dbb4729 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:22:01 +0200 Subject: [PATCH 3/9] Draw potion icons with their colour and a masked enchantment glint Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 1 + .../src/game/station_control.rs | 2 +- crates/horizon-client/src/game/stations.rs | 59 ++++++++++++++----- crates/horizon-client/src/hud.wgsl | 6 ++ 4 files changed, 53 insertions(+), 15 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 536846ddf..f462aeaf2 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1544,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_potion_layers(batch, stack, x, y); self.draw_glint(batch, stack, x, y); if stack.count > 1 { let text = stack.count.to_string(); diff --git a/crates/horizon-client/src/game/station_control.rs b/crates/horizon-client/src/game/station_control.rs index feac5f35a..fdb8b7955 100644 --- a/crates/horizon-client/src/game/station_control.rs +++ b/crates/horizon-client/src/game/station_control.rs @@ -46,7 +46,7 @@ impl Game<'_> { if shift && !had_shift { self.keys.remove(&KeyCode::ShiftLeft); } - let _ = saved; + self.cursor = 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")?; diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index 4eee33ecf..49e6319ac 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -976,7 +976,8 @@ impl Game<'_> { 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(); + // graphics.item: the icon only, without the count. + let shown: Vec<(usize, ItemStack)> = (start..(start + 12).min(s.recipes.len())).map(|i| (i, ItemStack { count: 1, ..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); @@ -1152,26 +1153,56 @@ impl Game<'_> { self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1); } } + /// Potion items: `layer0` tinted with the potion colour under the bottle + /// (`minecraft:potion` item tint source). + pub(super) fn draw_potion_layers(&self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) { + let (overlay, base) = match &*stack.item { + "minecraft:potion" => ("item/potion_overlay", "item/potion"), + "minecraft:splash_potion" => ("item/potion_overlay", "item/splash_potion"), + "minecraft:lingering_potion" => ("item/potion_overlay", "item/lingering_potion"), + "minecraft:tipped_arrow" => ("item/tipped_arrow_head", "item/tipped_arrow_base"), + _ => return, + }; + let c = brewing::potion_color(stack.potion()); + let atlas = &self.res.atlas; + batch.sprite_scaled(atlas, overlay, x, y, 16.0, 16.0, rgba((c >> 16 & 255) as u8, (c >> 8 & 255) as u8, (c & 255) as u8, 255)); + batch.sprite_scaled(atlas, base, x, y, 16.0, 16.0, u32::MAX); + } /// 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); + // ItemRenderer glint: the enchanted_glint texture scrolls diagonally over the + // item's shape. Approximated with a grid of item-texture quads whose vertex + // colours carry a purple base tint plus a moving bright band. + let t = self.started.elapsed().as_secs_f32(); + let glint = |gx: f32, gy: f32| -> u32 { + let d = ((gx + gy) / 32.0 - t * 0.35).rem_euclid(1.0); + let band = (1.0 - (d - 0.5).abs() * 6.0).max(0.0); + let a = 45.0 + 110.0 * band; + rgba((170.0 + 70.0 * band) as u8, (90.0 + 110.0 * band) as u8, 255, a as u8) + }; 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)); + Some(super::Icon::Flat(name)) => { + let Some(r) = self.res.atlas.sprites.get(&name).copied() else { return }; + const N: usize = 4; + let cell = 16.0 / N as f32; + let (du, dv) = ((r.u1 - r.u0) / N as f32, (r.v1 - r.v0) / N as f32); + for row in 0..N { + for col in 0..N { + let (x0, y0) = (col as f32 * cell, row as f32 * cell); + let (u0, v0) = (r.u0 + du * col as f32, r.v0 + dv * row as f32); + let corners = [(x0, y0, u0, v0), (x0 + cell, y0, u0 + du, v0), (x0 + cell, y0 + cell, u0 + du, v0 + dv), (x0, y0 + cell, u0, v0 + dv)]; + for i in [0usize, 1, 2, 0, 2, 3] { + let (cx, cy, u, v) = corners[i]; + batch.vertices.push(horizon_client::hud::HudVertex { pos: [x + cx, y + cy], uv: [u + 2.0, v], color: glint(cx, cy) }); + } + } + } } + Some(super::Icon::Cube { .. }) => batch.fill(&self.res.atlas, x + 1.0, y + 1.0, 14.0, 14.0, glint(8.0, 8.0) & 0x7FFF_FFFF), + None => {} } } diff --git a/crates/horizon-client/src/hud.wgsl b/crates/horizon-client/src/hud.wgsl index d455db179..ab7c4642a 100644 --- a/crates/horizon-client/src/hud.wgsl +++ b/crates/horizon-client/src/hud.wgsl @@ -16,6 +16,12 @@ struct Out { return out; } @fragment fn fs_main(in: Out) -> @location(0) vec4 { + // u >= 2: flat vertex colour masked by the texture's alpha (enchantment glint). + if in.uv.x >= 2.0 { + let m = textureSample(atlas, atlas_sampler, in.uv - vec2(2.0, 0.0)).a * in.color.a; + if m < 0.004 { discard; } + return vec4(in.color.rgb, m); + } let c = textureSample(atlas, atlas_sampler, in.uv) * in.color; if c.a < 0.004 { discard; } return c; From 61c803095ed6df87fd7447351c9920f2a8a6a0f4 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:30:45 +0200 Subject: [PATCH 4/9] Apply status effects and enchantment effects in gameplay Potions can be drunk, thrown (splash/lingering) and filled from water; effects tick like MobEffectInstance (hidden effects, periodic heal/poison/ wither/hunger), drive movement (jump boost, slow falling, levitation, speed/slowness modifiers), damage (resistance, fire resistance) and mining (haste/fatigue), and show as HUD icons. Enchantments affect gameplay from their data components: efficiency, aqua affinity, unbreaking, sharpness/ smite/bane, knockback, fire aspect, power, infinity, protection family and feather falling, thorns, mending, armor attributes, and fortune/silk touch/ looting in loot tables. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/effects.rs | 303 +++++++++++++++ crates/horizon-client/src/game.rs | 70 +++- .../src/game/enchant_effects.rs | 221 +++++++++++ crates/horizon-client/src/game/potions.rs | 345 ++++++++++++++++++ .../src/game/station_control.rs | 14 + crates/horizon-client/src/game/stations.rs | 6 +- crates/horizon-client/src/health.rs | 13 +- crates/horizon-client/src/hud.rs | 1 + crates/horizon-client/src/hunger.rs | 1 + crates/horizon-client/src/items.rs | 70 +++- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/motion.rs | 11 +- 12 files changed, 1019 insertions(+), 37 deletions(-) create mode 100644 crates/horizon-client/src/effects.rs create mode 100644 crates/horizon-client/src/game/enchant_effects.rs create mode 100644 crates/horizon-client/src/game/potions.rs diff --git a/crates/horizon-client/src/effects.rs b/crates/horizon-client/src/effects.rs new file mode 100644 index 000000000..25a899c52 --- /dev/null +++ b/crates/horizon-client/src/effects.rs @@ -0,0 +1,303 @@ +//! Player status effects (`MobEffectInstance` / `LivingEntity.activeEffects`): +//! add/update with hidden effects, per-tick application of the periodic +//! effects (regeneration, poison, wither, hunger, saturation, instant +//! effects), and the derived flags the movement and damage code read. +use crate::brewing; + +#[derive(Clone, Debug, PartialEq)] +pub struct EffectInstance { + /// Effect id without namespace (`speed`, `poison`, ...). + pub id: &'static str, + /// Remaining ticks; -1 is infinite. + pub duration: i32, + pub amplifier: i32, + pub ambient: bool, + pub visible: bool, + pub hidden: Option>, +} +impl EffectInstance { + pub fn new(id: &'static str, duration: i32, amplifier: i32) -> Self { + Self { id, duration, amplifier: amplifier.clamp(0, 255), ambient: false, visible: true, hidden: None } + } + fn infinite(&self) -> bool { + self.duration == -1 + } + fn shorter_than(&self, other: &Self) -> bool { + !self.infinite() && (self.duration < other.duration || other.infinite()) + } + /// `MobEffectInstance.update`. + pub fn update(&mut self, take: &Self) -> bool { + let mut changed = false; + if take.amplifier > self.amplifier { + if take.shorter_than(self) { + let previous = self.hidden.take(); + let mut copy = self.clone(); + copy.hidden = previous; + self.hidden = Some(Box::new(copy)); + } + self.amplifier = take.amplifier; + self.duration = take.duration; + changed = true; + } else if self.shorter_than(take) { + if take.amplifier == self.amplifier { + self.duration = take.duration; + changed = true; + } else if let Some(h) = self.hidden.as_mut() { + h.update(take); + } else { + self.hidden = Some(Box::new(EffectInstance { hidden: None, ..take.clone() })); + } + } + if !take.ambient && self.ambient || changed { + self.ambient = take.ambient; + changed = true; + } + if take.visible != self.visible { + self.visible = take.visible; + changed = true; + } + changed + } + fn tick_down(&mut self) { + if let Some(h) = self.hidden.as_mut() { + h.tick_down(); + } + if !self.infinite() { + self.duration -= 1; + } + } + fn downgrade(&mut self) { + if self.duration == 0 + && let Some(h) = self.hidden.take() + { + let h = *h; + self.duration = h.duration; + self.amplifier = h.amplifier; + self.ambient = h.ambient; + self.visible = h.visible; + self.hidden = h.hidden; + } + } +} +/// What an effect tick asks the game to do to the player. +#[derive(Clone, Debug, PartialEq)] +pub enum EffectAction { + Heal(f32), + /// Damage with a damage type id (`minecraft:magic`, `minecraft:wither`). + Hurt(&'static str, f32), + Exhaust(f32), + /// FoodData.eat(nutrition, saturation modifier). + Eat(i32, f32), +} +/// `shouldApplyEffectTickThisTick` + `applyEffectTick` for the periodic effects. +fn periodic(id: &str, tick: i32, amp: i32) -> Option { + let every = |base: i32| { + let interval = base >> amp; + interval <= 0 || tick % interval == 0 + }; + match id { + "regeneration" if every(50) => Some(EffectAction::Heal(1.0)), + "poison" if every(25) => Some(EffectAction::Hurt("minecraft:magic", 1.0)), + "wither" if every(40) => Some(EffectAction::Hurt("minecraft:wither", 1.0)), + "hunger" => Some(EffectAction::Exhaust(0.005 * (amp + 1) as f32)), + "saturation" if tick >= 1 => Some(EffectAction::Eat(amp + 1, 1.0)), + "instant_health" if tick >= 1 => Some(EffectAction::Heal((4 << amp.min(30)) as f32)), + "instant_damage" if tick >= 1 => Some(EffectAction::Hurt("minecraft:magic", (6 << amp.min(30)) as f32)), + _ => None, + } +} +/// `InstantenousMobEffect.applyInstantenousEffect` (potions apply these directly). +pub fn instant(id: &str, amp: i32, scale: f64) -> Option { + match id { + "instant_health" => Some(EffectAction::Heal((scale * f64::from(4 << amp.min(30))) as i32 as f32)), + "instant_damage" => Some(EffectAction::Hurt("minecraft:magic", (scale * f64::from(6 << amp.min(30))) as i32 as f32)), + "saturation" => Some(EffectAction::Eat(amp + 1, 1.0)), + _ => None, + } +} +#[derive(Clone, Debug, Default)] +pub struct PlayerEffects { + pub list: Vec, + pub tick_count: i32, +} +impl PlayerEffects { + pub fn get(&self, id: &str) -> Option<&EffectInstance> { + self.list.iter().find(|e| e.id == id) + } + pub fn amplifier(&self, id: &str) -> Option { + self.get(id).map(|e| e.amplifier) + } + /// `LivingEntity.addEffect`; returns whether anything changed. + pub fn add(&mut self, effect: EffectInstance) -> bool { + match self.list.iter_mut().find(|e| e.id == effect.id) { + Some(existing) => existing.update(&effect), + None => { + self.list.push(effect); + true + } + } + } + pub fn clear(&mut self) { + self.list.clear(); + } + /// `LivingEntity.tickEffects` (server part): actions to apply, in order. + pub fn tick(&mut self) -> Vec { + self.tick_count = self.tick_count.wrapping_add(1); + let mut actions = Vec::new(); + let tick_count = self.tick_count; + self.list.retain_mut(|e| { + if !(e.infinite() || e.duration > 0) { + return false; + } + let t = if e.infinite() { tick_count } else { e.duration }; + if let Some(a) = periodic(e.id, t, e.amplifier) { + actions.push(a); + } + e.tick_down(); + e.downgrade(); + e.infinite() || e.duration > 0 + }); + actions + } + /// Effects applied by drinking a potion (`PotionContents.applyToLivingEntity`). + pub fn potion_effects(potion: Option<&str>, scale: f32) -> (Vec, Vec) { + let mut lasting = Vec::new(); + let mut now = Vec::new(); + if let Some(def) = potion.and_then(brewing::potion) { + for (id, duration, amp) in def.effects { + let id = brewing::effect(id).map_or("speed", |e| e.id); + if brewing::effect(id).is_some_and(|e| e.instant) { + now.extend(instant(id, *amp, 1.0)); + } else { + // withScaledDuration: max(floor(d * scale), 1). + let d = ((*duration as f32) * scale).floor() as i32; + lasting.push(EffectInstance::new(id, d.max(1), *amp)); + } + } + } + (lasting, now) + } + /// Flags for movement and damage code. + pub fn status(&self) -> StatusFlags { + StatusFlags { + jump_boost: self.amplifier("jump_boost"), + slow_falling: self.get("slow_falling").is_some(), + levitation: self.amplifier("levitation"), + resistance: self.amplifier("resistance"), + fire_resistance: self.get("fire_resistance").is_some(), + water_breathing: self.get("water_breathing").is_some() || self.get("conduit_power").is_some(), + protection: Vec::new(), + } + } + /// Attribute modifiers of active effects: (attribute, id, amount, operation). + pub fn modifiers(&self) -> Vec<(&'static str, &'static str, f64, &'static str)> { + let mut out = Vec::new(); + for e in &self.list { + let level = f64::from(e.amplifier + 1); + let m = match e.id { + "speed" => Some(("minecraft:movement_speed", "minecraft:effect.speed", 0.2, "add_multiplied_total")), + "slowness" => Some(("minecraft:movement_speed", "minecraft:effect.slowness", -0.15, "add_multiplied_total")), + "haste" => Some(("minecraft:attack_speed", "minecraft:effect.haste", 0.1, "add_multiplied_total")), + "mining_fatigue" => Some(("minecraft:attack_speed", "minecraft:effect.mining_fatigue", -0.1, "add_multiplied_total")), + "strength" => Some(("minecraft:attack_damage", "minecraft:effect.strength", 3.0, "add_value")), + "weakness" => Some(("minecraft:attack_damage", "minecraft:effect.weakness", -4.0, "add_value")), + "jump_boost" => Some(("minecraft:safe_fall_distance", "minecraft:effect.jump_boost", 1.0, "add_value")), + "health_boost" => Some(("minecraft:max_health", "minecraft:effect.health_boost", 4.0, "add_value")), + "luck" => Some(("minecraft:luck", "minecraft:effect.luck", 1.0, "add_value")), + "unluck" => Some(("minecraft:luck", "minecraft:effect.unluck", -1.0, "add_value")), + _ => None, + }; + if let Some((a, id, amount, op)) = m { + out.push((a, id, amount * level, op)); + } + } + out + } + /// `Player.getDestroySpeed` effect factors (haste/conduit, mining fatigue). + pub fn mining_speed_factor(&self) -> f32 { + let mut f = 1.0; + let haste = self.amplifier("haste").max(self.amplifier("conduit_power")); + if let Some(a) = haste { + f *= 1.0 + (a + 1) as f32 * 0.2; + } + if let Some(a) = self.amplifier("mining_fatigue") { + f *= match a { + 0 => 0.3, + 1 => 0.09, + 2 => 0.0027, + _ => 8.1e-4, + }; + } + f + } +} +/// Effect and equipment facts the movement and damage kernels query. +#[derive(Clone, Debug, Default)] +pub struct StatusFlags { + pub jump_boost: Option, + pub slow_falling: bool, + pub levitation: Option, + pub resistance: Option, + pub fire_resistance: bool, + pub water_breathing: bool, + /// Armor enchantment protection per damage type id (`EnchantmentHelper.getDamageProtection`). + pub protection: Vec<(String, f32)>, +} +impl StatusFlags { + pub fn protection(&self, damage_type: &str) -> f32 { + self.protection.iter().find(|(t, _)| *t == damage_type).map_or(0.0, |(_, p)| *p) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn update_keeps_stronger_and_hides_longer() { + let mut fx = PlayerEffects::default(); + fx.add(EffectInstance::new("speed", 9600, 0)); + // A stronger but shorter effect takes over and hides the long one. + fx.add(EffectInstance::new("speed", 1800, 1)); + let e = fx.get("speed").unwrap(); + assert_eq!((e.amplifier, e.duration), (1, 1800)); + assert_eq!(e.hidden.as_ref().map(|h| (h.amplifier, h.duration)), Some((0, 9600))); + for _ in 0..1800 { + fx.tick(); + } + let e = fx.get("speed").unwrap(); + assert_eq!((e.amplifier, e.duration), (0, 7800)); + // Weaker and shorter: ignored. + assert!(!fx.add(EffectInstance::new("speed", 100, 0))); + } + + #[test] + fn regeneration_and_poison_intervals() { + let mut fx = PlayerEffects::default(); + fx.add(EffectInstance::new("regeneration", 900, 0)); + let heals = (0..900).flat_map(|_| fx.tick()).filter(|a| *a == EffectAction::Heal(1.0)).count(); + // Duration 900..1 divisible by 50: 18 heals. + assert_eq!(heals, 18); + assert!(fx.get("regeneration").is_none()); + let mut fx = PlayerEffects::default(); + fx.add(EffectInstance::new("poison", 432, 1)); + let hurts = (0..432).flat_map(|_| fx.tick()).filter(|a| matches!(a, EffectAction::Hurt(..))).count(); + // Interval 25 >> 1 = 12: 432/12 = 36 hits. + assert_eq!(hurts, 36); + } + + #[test] + fn potions_split_instant_and_lasting() { + let (lasting, now) = PlayerEffects::potion_effects(Some("minecraft:strong_healing"), 1.0); + assert!(lasting.is_empty()); + assert_eq!(now, vec![EffectAction::Heal(8.0)]); + let (lasting, _) = PlayerEffects::potion_effects(Some("minecraft:long_swiftness"), 0.25); + assert_eq!((lasting[0].id, lasting[0].duration), ("speed", 2400)); + let (lasting, _) = PlayerEffects::potion_effects(Some("minecraft:turtle_master"), 1.0); + assert_eq!(lasting.len(), 2); + let mut fx = PlayerEffects::default(); + fx.add(EffectInstance::new("haste", 100, 1)); + assert!((fx.mining_speed_factor() - 1.4).abs() < 1e-6); + assert_eq!(fx.modifiers().len(), 1); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index f462aeaf2..23b38e6ed 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 enchant_effects; +mod potions; mod station_control; mod stations; use horizon_client::{ @@ -316,6 +318,8 @@ struct Game<'a> { container: Option<(i32, i32, i32)>, /// Open workstation menu (enchanting table, anvil, ...). station: Option, + /// Status effects and thrown potions (game/potions.rs). + potions: potions::PotionState, scratch_slot: Option, mining: Option, destroy_delay: u32, @@ -891,7 +895,7 @@ impl Game<'_> { held.as_ref(), &mut self.world.random, ); - let silk = false; + let silk = held.as_ref().is_some_and(|h| h.enchantment_level("minecraft:silk_touch") > 0); for d in drops { if &*d.item != "minecraft:air" { self.pop_resource(pos, d); @@ -904,14 +908,15 @@ impl Game<'_> { } // Tools lose durability on blocks with nonzero hardness. if facts.hardness > 0.0 - && let Some(stack) = self.inventory[self.selected].as_mut() - && let Some(info) = self.res.items.get(&stack.item) - && info.max_damage > 0 - && !info.tool.is_empty() + && let Some(stack) = self.inventory[self.selected].clone() + && let Some(max) = self.res.items.get(&stack.item).filter(|i| i.max_damage > 0 && !i.tool.is_empty()).map(|i| i.max_damage) { - stack.damage += 1; - if stack.damage >= info.max_damage { - self.inventory[self.selected] = None; + let loss = self.durability_loss(&stack, 1); + if let Some(stack) = self.inventory[self.selected].as_mut() { + stack.damage += loss; + if stack.damage >= max { + self.inventory[self.selected] = None; + } } } } @@ -972,6 +977,9 @@ impl Game<'_> { } let Some(stack) = self.held().cloned() else { return Ok(()) }; let Some(info) = self.res.items.get(&stack.item).cloned() else { return Ok(()) }; + if self.use_potion_item(&stack)? { + return Ok(()); + } if &*stack.item == "minecraft:bow" { if self.using.is_none() { self.using = Some((self.selected, 0)); @@ -1060,6 +1068,9 @@ impl Game<'_> { self.using = None; return; }; + if self.tick_drinking(slot, ticks, &stack) { + return; + } if &*stack.item == "minecraft:bow" { self.using = Some((slot, ticks + 1)); return; @@ -1131,13 +1142,14 @@ impl Game<'_> { // Player.getDestroySpeed / BlockBehaviour.getDestroyProgress. let held = self.held(); let mut speed = self.res.items.mining_speed(held, &facts.name); + speed = self.modify_destroy_speed(speed); let player = self.player.as_ref().ok_or("no player")?; if !player.ground.on_ground { speed /= 5.0; } let eye = self.eye_position().unwrap_or_default(); if self.res.facts.get(self.world.block(eye[0].floor() as i32, eye[1].floor() as i32, eye[2].floor() as i32)).fluid == Fluid::Water { - speed /= 5.0; + speed *= self.submerged_mining_speed(); } let harvest = !facts.requires_tool || self.res.items.correct_for_drops(held, &facts.name); let progress = if facts.hardness == 0.0 { @@ -1378,6 +1390,8 @@ impl Game<'_> { self.screen = Screen::Dead; self.capture(false); } + self.tick_effects(); + self.tick_burning(); self.tick_using(); self.tick_mining()?; self.tick_items(); @@ -1597,6 +1611,7 @@ impl Game<'_> { self.draw_item(&mut batch, &stack, w / 2.0 - 90.0 + i as f32 * 20.0 + 2.0, h - 19.0); } } + self.draw_effect_icons(&mut batch); let atlas = &self.res.atlas; if !self.creative && let Some(p) = &self.player @@ -2451,7 +2466,7 @@ impl Game<'_> { } let held = self.held().cloned(); let modifiers = held.as_ref().and_then(|h| self.res.items.get(&h.item)).map(|i| (i.attack_damage, i.attack_speed)).unwrap_or((0.0, 0.0)); - let damage = 1.0 + modifiers.0; + let damage = 1.0 + modifiers.0 + self.effect_attack_bonus(); let speed = (4.0 + modifiers.1).max(0.1); let delay = 20.0 / speed; let scale = ((self.attack_ticks as f32 + 0.5) / delay).clamp(0.0, 1.0); @@ -2462,6 +2477,9 @@ impl Game<'_> { if crit { amount *= 1.5; } + // Enchantment damage (sharpness, smite, bane) scaled by the attack strength. + let target_kind = self.mobs[index].kind.id.clone(); + amount += self.enchant_damage_bonus(&format!("minecraft:{}", target_kind.trim_start_matches("minecraft:"))) * scale; self.attack_ticks = 0; if let Some(p) = self.player.as_mut() && !self.creative @@ -2482,13 +2500,16 @@ impl Game<'_> { let event = format!("minecraft:{}", kind.sounds[if dead { 2 } else { 1 }]); let pitch = (self.world.random.next_float() - self.world.random.next_float()) * 0.2 + 1.0; self.audio.play(&event, Some(center), 1.0, pitch); - if let Some(stack) = self.inventory[self.selected].as_mut() - && let Some(info) = self.res.items.get(&stack.item) - && info.max_damage > 0 + self.post_attack(index); + if let Some(stack) = self.inventory[self.selected].clone() + && let Some(max) = self.res.items.get(&stack.item).filter(|i| i.max_damage > 0).map(|i| i.max_damage) { - stack.damage += 1; - if stack.damage >= info.max_damage { - self.inventory[self.selected] = None; + let loss = self.durability_loss(&stack, 1); + if let Some(stack) = self.inventory[self.selected].as_mut() { + stack.damage += loss; + if stack.damage >= max { + self.inventory[self.selected] = None; + } } } } @@ -2682,6 +2703,7 @@ impl Game<'_> { let at = [player.position.x, player.position.y, player.position.z]; self.audio.play("minecraft:entity.player.hurt", Some(at), 1.0, 1.0); self.hurt_armor(amount); + self.thorns(from); } } MobEvent::Shoot(from, target) => { @@ -3277,12 +3299,14 @@ impl Game<'_> { } } } + self.apply_enchantment_attributes(); } /// Inventory.hurtArmor: each piece loses max(1, damage / 4) durability. fn hurt_armor(&mut self, damage: f32) { let amount = ((damage / 4.0) as u32).max(1); let mut broke = false; - for slot in &mut self.armor { + let losses: Vec = (0..4).map(|i| self.armor[i].clone().map_or(amount, |s| self.durability_loss(&s, amount))).collect(); + for (slot, amount) in self.armor.iter_mut().zip(losses) { if let Some(stack) = slot.as_mut() && let Some(info) = self.res.items.get(&stack.item) && info.max_damage > 0 @@ -3346,6 +3370,10 @@ impl Game<'_> { if self.creative { return; } + let amount = match self.inventory[self.selected].clone() { + Some(held) => self.durability_loss(&held, amount), + None => amount, + }; if let Some(stack) = self.inventory[self.selected].as_mut() && let Some(info) = self.res.items.get(&stack.item) && info.max_damage > 0 @@ -3544,6 +3572,9 @@ impl Game<'_> { }); } self.orbs = orbs; + if gained > 0 { + gained = self.mending(gained); + } if gained > 0 { let at = self.eye_position(); let pitch = (self.world.random.next_float() - self.world.random.next_float()) * 0.35 + 0.9; @@ -3574,10 +3605,12 @@ impl Game<'_> { let speed = f64::from(power) * 3.0; let v = [(dir[0] + jitter()) * speed, (dir[1] + jitter()) * speed, (dir[2] + jitter()) * speed]; let p = Vec3::new(eye[0], eye[1] - 0.1, eye[2]); - self.arrows.push(Arrow { from_player: true, critical: power >= 1.0, position: p, previous: p, velocity: Vec3::new(v[0], v[1], v[2]), stuck: false, age: 0, base_damage: 2.0 }); + let (power_bonus, infinity) = self.bow_enchantments(); + self.arrows.push(Arrow { from_player: true, critical: power >= 1.0, position: p, previous: p, velocity: Vec3::new(v[0], v[1], v[2]), stuck: false, age: 0, base_damage: 2.0 + power_bonus }); let pitch = 1.0 / (self.world.random.next_float() * 0.4 + 1.2) + power * 0.5; self.audio.play("minecraft:entity.arrow.shoot", Some(eye), 1.0, pitch); if !self.creative + && !infinity && let Some(i) = arrow_slot && let Some(s) = self.inventory[i].as_mut() { @@ -4780,6 +4813,7 @@ pub fn run() -> Result<()> { craft_size: 2, container: None, station: None, + potions: Default::default(), scratch_slot: None, mining: None, destroy_delay: 0, diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs new file mode 100644 index 000000000..a562c2953 --- /dev/null +++ b/crates/horizon-client/src/game/enchant_effects.rs @@ -0,0 +1,221 @@ +//! Enchantment effects on gameplay, read from the data-driven effect +//! components: efficiency and aqua affinity (`Player.getDestroySpeed`), +//! unbreaking (`minecraft:item_damage`), sharpness/smite/bane and power +//! (`minecraft:damage`), knockback, fire aspect, infinity (`minecraft:ammo_use`), +//! thorns (`minecraft:post_attack`), mending (`minecraft:repair_with_xp`) and +//! the armor attribute effects (respiration, depth strider, ...). +use super::Game; +use horizon_client::{enchant::EffectContext, items::ItemStack}; +use horizon_core::{geometry::Vec3, random::RandomSource}; + +impl Game<'_> { + /// `Player.getDestroySpeed` after the tool speed: mining efficiency, haste + /// and mining fatigue. + pub(super) fn modify_destroy_speed(&self, mut speed: f32) -> f32 { + if speed > 1.0 { + let held = self.inventory[self.selected].as_ref(); + speed += self.res.stations.enchantments.attribute_add(held, "minecraft:mining_efficiency") as f32; + } + speed * self.potions.effects.mining_speed_factor() + } + /// `Attributes.SUBMERGED_MINING_SPEED` (0.2, raised by aqua affinity). + pub(super) fn submerged_mining_speed(&self) -> f32 { + let mut total = 0.0; + for stack in self.armor.iter().flatten() { + for (attr, _, amount, op) in self.res.stations.enchantments.attributes(stack) { + if attr == "minecraft:submerged_mining_speed" && op == "add_multiplied_total" { + total += amount; + } + } + } + (0.2 * (1.0 + total)) as f32 + } + /// `EnchantmentHelper.processDurabilityChange` (unbreaking) for `amount` points. + pub(super) fn durability_loss(&mut self, stack: &ItemStack, amount: u32) -> u32 { + let e = &self.res.stations.enchantments; + if !e.has_component(stack, "minecraft:item_damage") { + return amount; + } + let ctx = EffectContext { tool: Some(&stack.item), items: Some(&self.res.items), ..Default::default() }; + e.modify_value(Some(stack), "minecraft:item_damage", &ctx, &mut self.world.random, amount as f32).max(0.0) as u32 + } + /// `getEnchantedDamage - base`: damage bonus of the held weapon against a mob type. + pub(super) fn enchant_damage_bonus(&mut self, target: &str) -> f32 { + let Some(held) = self.inventory[self.selected].clone() else { return 0.0 }; + let ctx = EffectContext { this: Some(target), attacker: Some("minecraft:player"), direct_attacker: Some("minecraft:player"), is_direct: true, damage_type: Some("minecraft:player_attack"), items: Some(&self.res.items), ..Default::default() }; + self.res.stations.enchantments.modify_value(Some(&held), "minecraft:damage", &ctx, &mut self.world.random, 0.0) + } + /// Strength / weakness on the attack damage attribute. + pub(super) fn effect_attack_bonus(&self) -> f32 { + let fx = &self.potions.effects; + fx.amplifier("strength").map_or(0.0, |a| 3.0 * (a + 1) as f32) - fx.amplifier("weakness").map_or(0.0, |a| 4.0 * (a + 1) as f32) + } + /// After a successful melee hit: knockback enchantment and fire aspect. + pub(super) fn post_attack(&mut self, mob: usize) { + let Some(held) = self.inventory[self.selected].clone() else { return }; + let Some(m) = self.mobs.get(mob) else { return }; + let kind = m.kind.id.clone(); + let ctx = EffectContext { this: Some(&kind), attacker: Some("minecraft:player"), direct_attacker: Some("minecraft:player"), is_direct: true, items: Some(&self.res.items), ..Default::default() }; + let knockback = self.res.stations.enchantments.modify_value(Some(&held), "minecraft:knockback", &ctx, &mut self.world.random, 0.0); + if knockback > 0.0 { + // LivingEntity.knockback(strength * 0.5, sin(yRot), -cos(yRot)). + let strength = f64::from(knockback) * 0.5; + let (s, c) = (f64::from(self.yaw.to_radians().sin()), f64::from(self.yaw.to_radians().cos())); + let (dx, dz) = (s, -c); + let l = (dx * dx + dz * dz).sqrt().max(1e-5); + let m = &mut self.mobs[mob]; + let v = m.velocity; + m.velocity = Vec3::new(v.x / 2.0 - dx / l * strength, if m.on_ground { (v.y / 2.0 + strength).min(0.4) } else { v.y }, v.z / 2.0 - dz / l * strength); + } + // minecraft:post_attack ignite effects of the attacker's weapon (fire aspect). + let mut ignite = 0.0f32; + for (id, level) in held.enchantments() { + let Some(def) = self.res.stations.enchantments.get(id) else { continue }; + for effect in def.effects["minecraft:post_attack"].as_array().into_iter().flatten() { + if effect["enchanted"] == "attacker" && effect["affected"] == "victim" && effect["effect"]["type"] == "minecraft:ignite" { + let mut random = self.world.random.clone(); + let ok = effect.get("requirements").is_none_or(|r| self.res.stations.enchantments.condition(r, *level, &ctx, &mut random)); + self.world.random = random; + if ok { + ignite = ignite.max(horizon_client::enchant::level_value(&effect["effect"]["duration"], *level)); + } + } + } + } + if ignite > 0.0 { + // Entity.igniteForSeconds; mobs burn for 1 damage per second. + let id = self.mobs[mob].id; + self.potions.burning.retain(|(m, _)| *m != id); + self.potions.burning.push((id, (ignite * 20.0) as i32)); + } + } + /// Burning mobs (fire aspect): one damage every 20 ticks, flame particles. + pub(super) fn tick_burning(&mut self) { + let mut burning = std::mem::take(&mut self.potions.burning); + burning.retain_mut(|(id, ticks)| { + *ticks -= 1; + let Some(m) = self.mobs.iter_mut().find(|m| m.id == *id && m.alive()) else { return false }; + if *ticks % 20 == 0 { + let at = [m.position.x, m.position.y, m.position.z]; + if m.hurt(1.0, None, &mut self.world.random) { + self.last_hurt_by_player.insert(*id); + let _ = at; + } + } + *ticks > 0 + }); + self.potions.burning = burning; + } + /// Thorns on worn armor when a mob at `from` hits the player. + pub(super) fn thorns(&mut self, from: [f64; 3]) { + let attacker = self + .mobs + .iter() + .enumerate() + .filter(|(_, m)| m.alive()) + .min_by(|a, b| { + let d = |m: &horizon_client::mobs::Mob| (m.position.x - from[0]).powi(2) + (m.position.y - from[1]).powi(2) + (m.position.z - from[2]).powi(2); + d(a.1).total_cmp(&d(b.1)) + }) + .map(|(i, _)| i); + let Some(attacker) = attacker else { return }; + for slot in 0..4 { + let Some(stack) = self.armor[slot].clone() else { continue }; + let level = stack.enchantment_level("minecraft:thorns"); + if level == 0 { + continue; + } + let Some(def) = self.res.stations.enchantments.get("minecraft:thorns") else { continue }; + let effect = def.effects["minecraft:post_attack"][0].clone(); + let ctx = EffectContext { items: Some(&self.res.items), ..Default::default() }; + let mut random = self.world.random.clone(); + let ok = self.res.stations.enchantments.condition(&effect["requirements"], level, &ctx, &mut random); + self.world.random = random; + if !ok { + continue; + } + // DamageEntity(min 1, max 5) and ChangeItemDamage(2). + let damage = 1.0 + self.world.random.next_float() * 4.0; + let center = { + let m = &mut self.mobs[attacker]; + m.hurt(damage, None, &mut self.world.random); + [m.position.x, m.position.y, m.position.z] + }; + self.audio.play("minecraft:enchant.thorns.hit", Some(center), 1.0, 1.0); + if let Some(s) = self.armor[slot].as_mut() { + s.damage += 2; + if self.res.items.get(&s.item).is_some_and(|i| s.damage >= i.max_damage) { + self.armor[slot] = None; + } + } + } + } + /// `ExperienceOrb.repairPlayerItems`: returns the experience left over. + pub(super) fn mending(&mut self, amount: u32) -> u32 { + let mut amount = amount; + loop { + // EnchantmentHelper.getRandomItemWith(REPAIR_WITH_XP, damaged): held and armor. + let mut candidates: Vec<(bool, usize)> = Vec::new(); + if let Some(s) = &self.inventory[self.selected] + && s.damage > 0 + && s.enchantment_level("minecraft:mending") > 0 + { + candidates.push((false, self.selected)); + } + for (i, s) in self.armor.iter().enumerate() { + if let Some(s) = s + && s.damage > 0 + && s.enchantment_level("minecraft:mending") > 0 + { + candidates.push((true, i)); + } + } + if candidates.is_empty() { + return amount; + } + let (armor, i) = candidates[self.world.random.next_int_bound(candidates.len() as i32).unwrap_or(0) as usize]; + let stack = if armor { self.armor[i].clone() } else { self.inventory[i].clone() }; + let Some(stack) = stack else { return amount }; + let ctx = EffectContext { items: Some(&self.res.items), ..Default::default() }; + let to_repair_xp = self.res.stations.enchantments.modify_value(Some(&stack), "minecraft:repair_with_xp", &ctx, &mut self.world.random, amount as f32) as u32; + let repaired = to_repair_xp.min(stack.damage); + let slot = if armor { &mut self.armor[i] } else { &mut self.inventory[i] }; + if let Some(s) = slot.as_mut() { + s.damage -= repaired; + } + if repaired == 0 || to_repair_xp == 0 { + return 0; + } + let remaining = amount.saturating_sub(repaired * amount / to_repair_xp); + if remaining == 0 { + return 0; + } + amount = remaining; + } + } + /// Bow enchantments at release: (extra base damage, infinity keeps the arrow). + pub(super) fn bow_enchantments(&mut self) -> (f64, bool) { + let Some(bow) = self.inventory[self.selected].clone() else { return (0.0, false) }; + let e = &self.res.stations.enchantments; + let ctx = EffectContext { direct_attacker: Some("minecraft:arrow"), attacker: Some("minecraft:player"), items: Some(&self.res.items), ..Default::default() }; + let power = e.modify_value(Some(&bow), "minecraft:damage", &ctx, &mut self.world.random, 0.0); + let ammo_ctx = EffectContext { tool: Some("minecraft:arrow"), items: Some(&self.res.items), ..Default::default() }; + let infinity = e.has_component(&bow, "minecraft:ammo_use") && e.modify_value(Some(&bow), "minecraft:ammo_use", &ammo_ctx, &mut self.world.random, 1.0) == 0.0; + (f64::from(power), infinity) + } + /// Enchantment attribute modifiers of worn armor (respiration, depth strider...). + pub(super) fn apply_enchantment_attributes(&mut self) { + let mut wanted: Vec<(String, String, f64, String)> = Vec::new(); + for stack in self.armor.iter().flatten() { + wanted.extend(self.res.stations.enchantments.attributes(stack)); + } + let Some(p) = self.player.as_mut() else { return }; + for (attr, id, _, op) in std::mem::take(&mut self.potions.enchant_modifiers) { + let _ = p.set_modifier(&attr, &id, 0.0, &op, false); + } + for (attr, id, amount, op) in &wanted { + let _ = p.set_modifier(attr, id, *amount, op, true); + } + self.potions.enchant_modifiers = wanted; + } +} diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs new file mode 100644 index 000000000..d2ccb344c --- /dev/null +++ b/crates/horizon-client/src/game/potions.rs @@ -0,0 +1,345 @@ +//! Potions and status effects in the game: drinking (`PotionItem` via +//! `Consumable`), throwing splash/lingering potions (`ThrownSplashPotion`), +//! filling glass bottles (`BottleItem`), the per-tick effect application, +//! effect attribute modifiers and the HUD effect icons (`Hud.extractEffects`). +use super::{Game, Screen}; +use horizon_client::{ + brewing, + effects::{EffectAction, EffectInstance, PlayerEffects}, + hud::{HudBatch, rgba}, + items::ItemStack, +}; +use horizon_core::{geometry::Vec3, random::RandomSource}; + +/// A thrown splash or lingering potion in flight. +#[derive(Clone, Debug)] +pub(super) struct ThrownPotion { + stack: ItemStack, + position: Vec3, + velocity: Vec3, + age: u32, +} +/// Effects, thrown potions and the attribute modifiers last applied. +#[derive(Default)] +pub(super) struct PotionState { + pub(super) effects: PlayerEffects, + thrown: Vec, + applied: Vec<(&'static str, &'static str, f64, &'static str)>, + /// Armor the protection table was computed for. + protection_for: Option>>, + /// Mobs set on fire by fire aspect: (mob id, ticks left). + pub(super) burning: Vec<(u32, i32)>, + /// Enchantment attribute modifiers on the player: (attribute, id, amount, operation). + pub(super) enchant_modifiers: Vec<(String, String, f64, String)>, +} + +impl Game<'_> { + /// Right-click with a potion, splash/lingering potion or glass bottle. + pub(super) fn use_potion_item(&mut self, stack: &ItemStack) -> horizon_client::Result { + match &*stack.item { + "minecraft:potion" => { + if self.using.is_none() { + self.using = Some((self.selected, 0)); + } + Ok(true) + } + "minecraft:splash_potion" | "minecraft:lingering_potion" => { + 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" }; + self.audio.play(sound, Some(eye), 0.5, pitch); + // Projectile.shootFromRotation(xRot, yRot, -20, 0.5, 1.0). + let (yaw, pitch) = (self.yaw.to_radians(), (self.pitch - 20.0).to_radians()); + let dir = [-yaw.sin() * pitch.cos(), -pitch.sin(), yaw.cos() * pitch.cos()]; + let r = &mut self.world.random; + let mut jitter = || f64::from(r.next_float() + r.next_float() - 1.0) * 0.0075; + let v = Vec3::new((f64::from(dir[0]) + jitter()) * 0.5, (f64::from(dir[1]) + jitter()) * 0.5, (f64::from(dir[2]) + jitter()) * 0.5); + 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); + let v = Vec3::new(v.x + pv.x, v.y + if on_ground { 0.0 } else { pv.y }, v.z + pv.z); + self.potions.thrown.push(ThrownPotion { stack: ItemStack { count: 1, ..stack.clone() }, position: Vec3::new(eye[0], eye[1] - 0.1, eye[2]), velocity: v, age: 0 }); + self.swing_arm(); + self.consume_held(); + Ok(true) + } + "minecraft:glass_bottle" => { + let Some(hit) = self.pick_fluid() else { return Ok(false) }; + let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); + if self.res.facts.get(state).fluid != horizon_client::blocks::Fluid::Water { + return Ok(false); + } + let at = [f64::from(hit.pos[0]) + 0.5, f64::from(hit.pos[1]) + 0.5, f64::from(hit.pos[2]) + 0.5]; + self.audio.play("minecraft:item.bottle.fill", Some(at), 1.0, 1.0); + let water = ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water"); + self.fill_held(water); + Ok(true) + } + _ => Ok(false), + } + } + /// `ItemUtils.createFilledResult`: replace one of the held stack. + fn fill_held(&mut self, filled: ItemStack) { + if self.creative { + let _ = self.give(filled); + return; + } + self.consume_held(); + if self.inventory[self.selected].is_none() { + self.inventory[self.selected] = Some(filled); + } else if let Some(rest) = self.give(filled) + && let Some(eye) = self.eye_position() + { + self.spawn_item(rest, eye, [0.0, 0.1, 0.0], 40); + } + } + /// Drinking a potion while right-click is held; true when handled. + pub(super) fn tick_drinking(&mut self, slot: usize, ticks: u32, stack: &ItemStack) -> bool { + if &*stack.item != "minecraft:potion" { + return false; + } + let ticks = ticks + 1; + let remaining = 32u32.saturating_sub(ticks); + let eye = self.eye_position().unwrap_or_default(); + // Consumable.emitParticlesAndSounds: the drink sound every 4 ticks near the end. + if remaining <= 25 && remaining % 4 == 0 { + let pitch = self.world.random.next_float() * 0.1 + 0.9; + self.audio.play("minecraft:entity.generic.drink", Some(eye), 0.5, pitch); + } + if ticks < 32 { + self.using = Some((slot, ticks)); + return true; + } + self.using = None; + let (lasting, now) = PlayerEffects::potion_effects(stack.potion(), 1.0); + for e in lasting { + self.potions.effects.add(e); + } + for a in now { + self.apply_effect_action(a); + } + if !self.creative { + if let Some(s) = self.inventory[slot].as_mut() { + s.count -= 1; + if s.count == 0 { + self.inventory[slot] = None; + } + } + let bottle = ItemStack::new("minecraft:glass_bottle", 1); + if self.inventory[slot].is_none() { + self.inventory[slot] = Some(bottle); + } else if let Some(rest) = self.give(bottle) { + self.spawn_item(rest, eye, [0.0, 0.1, 0.0], 40); + } + } + true + } + fn apply_effect_action(&mut self, action: EffectAction) { + let creative = self.creative; + let rules = self.world.health_rules; + let Some(p) = self.player.as_mut() else { return }; + match action { + EffectAction::Heal(amount) => { + let max = p.attribute("minecraft:max_health").unwrap_or(20.0) as f32; + let h = p.health.health(); + if h > 0.0 { + let _ = p.set_health((h + amount).min(max), false); + } + } + EffectAction::Hurt(source, amount) => { + if creative { + return; + } + if let Some(id) = self.motion.health.damage.id(source) { + let _ = p.hurt(&self.motion.health, rules, id, amount); + } + } + EffectAction::Exhaust(amount) => { + p.health.food.exhaustion = (p.health.food.exhaustion + amount).min(40.0); + } + EffectAction::Eat(nutrition, saturation) => { + let food = &mut p.health.food; + food.food = (food.food + nutrition).clamp(0, 20); + food.saturation = (food.saturation + nutrition as f32 * saturation * 2.0).clamp(0.0, food.food as f32); + } + } + } + /// `LivingEntity.tickEffects`, attribute modifiers and the status flags. + pub(super) fn tick_effects(&mut self) { + if self.player.as_ref().is_none_or(|p| p.health.dead_or_dying()) { + self.potions.effects.clear(); + } + for action in self.potions.effects.tick() { + self.apply_effect_action(action); + } + let modifiers = self.potions.effects.modifiers(); + if modifiers != self.potions.applied + && let Some(p) = self.player.as_mut() + { + for (attr, id, _, op) in &self.potions.applied { + let _ = p.set_modifier(attr, id, 0.0, op, false); + } + for (attr, id, amount, op) in &modifiers { + let _ = p.set_modifier(attr, id, *amount, op, true); + } + self.potions.applied = modifiers; + } + // EnchantmentHelper.getDamageProtection per damage type, recomputed on armor change. + let armor: Vec> = self.armor.to_vec(); + if self.potions.protection_for.as_ref() != Some(&armor) { + let mut table = Vec::new(); + let e = &self.res.stations.enchantments; + let mut random = horizon_core::random::LegacyRandom::new(0); + for (_, def) in self.motion.health.damage.entries() { + let ctx = horizon_client::enchant::EffectContext { items: Some(&self.res.items), damage_type: Some(&def.name), this: Some("minecraft:player"), ..Default::default() }; + let total: f32 = armor.iter().flatten().map(|s| e.modify_value(Some(s), "minecraft:damage_protection", &ctx, &mut random, 0.0)).sum(); + if total > 0.0 { + table.push((def.name.clone(), total)); + } + } + self.potions.protection_for = Some(armor); + if let Some(p) = self.player.as_mut() { + p.status.protection = table; + } + } + let mut status = self.potions.effects.status(); + if let Some(p) = self.player.as_mut() { + status.protection = std::mem::take(&mut p.status.protection); + p.status = status; + } + self.tick_thrown_potions(); + } + fn tick_thrown_potions(&mut self) { + let mut thrown = std::mem::take(&mut self.potions.thrown); + let mut landed = Vec::new(); + thrown.retain_mut(|t| { + t.age += 1; + let next = Vec3::new(t.position.x + t.velocity.x, t.position.y + t.velocity.y, t.position.z + t.velocity.z); + // Hit a block along the step (sampled), a mob, or fell out of the world. + let steps = 4; + let mut hit = None; + for i in 1..=steps { + let f = f64::from(i) / f64::from(steps); + let p = Vec3::new(t.position.x + t.velocity.x * f, t.position.y + t.velocity.y * f, t.position.z + t.velocity.z * f); + let state = self.world.block(p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32); + if self.res.facts.get(state).full_collision || self.mobs.iter().any(|m| m.alive() && (m.position.x - p.x).abs() < m.kind.width / 2.0 + 0.125 && (m.position.z - p.z).abs() < m.kind.width / 2.0 + 0.125 && p.y >= m.position.y && p.y <= m.position.y + m.kind.height) { + hit = Some(p); + break; + } + } + if let Some(p) = hit { + landed.push((t.stack.clone(), p)); + return false; + } + t.position = next; + // ThrowableItemProjectile: drag 0.99 then gravity 0.05. + t.velocity = Vec3::new(t.velocity.x * 0.99, t.velocity.y * 0.99 - 0.05, t.velocity.z * 0.99); + t.age < 1200 && t.position.y > -128.0 + }); + self.potions.thrown = thrown; + for (stack, at) in landed { + self.splash(&stack, at); + } + } + /// `ThrownSplashPotion.onHitAsPotion` (lingering clouds apply as a weaker splash). + fn splash(&mut self, stack: &ItemStack, at: Vec3) { + let lingering = &*stack.item == "minecraft:lingering_potion"; + let event = if lingering { "minecraft:entity.lingering_potion.break" } else { "minecraft:entity.splash_potion.break" }; + let pitch = self.world.random.next_float() * 0.1 + 0.9; + self.audio.play(event, Some([at.x, at.y, at.z]), 1.0, pitch); + let color = brewing::potion_color(stack.potion()); + 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(), color); + self.particles.push(p); + } + let scale = if lingering { 0.25 } else { 1.0 }; + let Some(def) = stack.potion().and_then(brewing::potion) else { return }; + // The player. + if let Some(p) = self.player.as_ref() { + let center = Vec3::new(p.position.x, p.position.y + f64::from(p.dimensions.height) / 2.0, p.position.z); + let d2 = (center.x - at.x).powi(2) + (center.y - at.y).powi(2) + (center.z - at.z).powi(2); + if d2 < 16.0 && (center.y - at.y).abs() <= 2.0 + f64::from(p.dimensions.height) { + let intensity = 1.0 - d2.sqrt() / 4.0; + for (id, duration, amp) in def.effects { + let instant = brewing::effect(id).is_some_and(|e| e.instant); + if instant { + if let Some(a) = horizon_client::effects::instant(id, *amp, intensity) { + self.apply_effect_action(a); + } + } else { + let d = (intensity * f64::from(*duration) * f64::from(scale) + 0.5) as i32; + if d > 20 + && let Some(e) = brewing::effect(id) + { + self.potions.effects.add(EffectInstance::new(e.id, d, *amp)); + } + } + } + } + } + // Mobs take the instant effects (undead invert healing and harming). + let undead = &self.res.stations.enchantments.entity_tags; + let mut hits = Vec::new(); + for (i, m) in self.mobs.iter().enumerate() { + let d2 = (m.position.x - at.x).powi(2) + (m.position.y + m.kind.height / 2.0 - at.y).powi(2) + (m.position.z - at.z).powi(2); + if m.alive() && d2 < 16.0 { + let inverted = undead.get("minecraft:inverted_healing_and_harm").is_some_and(|t| t.contains(&m.kind.id)); + hits.push((i, 1.0 - d2.sqrt() / 4.0, inverted)); + } + } + for (i, intensity, inverted) in hits { + for (id, _, amp) in def.effects { + let harm = match *id { + "instant_damage" => !inverted, + "instant_health" => inverted, + _ => continue, + }; + let m = &mut self.mobs[i]; + if harm { + m.hurt((intensity * f64::from(6 << amp)) as i32 as f32, Some([at.x, at.y, at.z]), &mut self.world.random); + } else { + m.health = (m.health + (intensity * f64::from(4 << amp)) as i32 as f32).min(m.kind.max_health); + } + } + } + } + /// `Hud.extractEffects`: icons top-right, beneficial row then harmful row. + pub(super) fn draw_effect_icons(&self, batch: &mut HudBatch) { + if self.screen != Screen::Playing || self.potions.effects.list.is_empty() { + return; + } + let mut list: Vec<&EffectInstance> = self.potions.effects.list.iter().collect(); + let color = |e: &EffectInstance| brewing::effect(e.id).map_or(0, |d| d.color); + list.sort_by(|a, b| (a.ambient, a.duration == -1, a.duration, color(a)).cmp(&(b.ambient, b.duration == -1, b.duration, color(b))).reverse()); + let (mut good, mut bad) = (0, 0); + let atlas = &self.res.atlas; + for e in list { + let beneficial = brewing::effect(e.id).is_some_and(|d| d.category == brewing::Category::Beneficial); + let mut x = batch.width; + let mut y = 1.0; + if beneficial { + good += 1; + x -= 25.0 * good as f32; + } else { + bad += 1; + x -= 25.0 * bad as f32; + y += 26.0; + } + let mut alpha = 1.0f32; + if e.ambient { + batch.sprite(atlas, "gui/sprites/hud/effect_background_ambient", x, y); + } else { + batch.sprite(atlas, "gui/sprites/hud/effect_background", x, y); + if e.duration != -1 && e.duration <= 200 { + let d = e.duration as f32; + let used = 10.0 - (e.duration / 20) as f32; + alpha = ((d / 10.0 / 5.0 * 0.5).clamp(0.0, 0.5) + (d * std::f32::consts::PI / 5.0).cos() * (used / 10.0 * 0.25).clamp(0.0, 0.25)).clamp(0.0, 1.0); + } + } + batch.sprite_scaled(atlas, &format!("mob_effect/{}", e.id), x + 3.0, y + 3.0, 18.0, 18.0, rgba(255, 255, 255, (alpha * 255.0) as u8)); + } + } + pub(super) fn effects_json(&self) -> serde_json::Value { + serde_json::Value::Array(self.potions.effects.list.iter().map(|e| serde_json::json!({ "id": e.id, "duration": e.duration, "amplifier": e.amplifier })).collect()) + } +} diff --git a/crates/horizon-client/src/game/station_control.rs b/crates/horizon-client/src/game/station_control.rs index fdb8b7955..a7a71c2b4 100644 --- a/crates/horizon-client/src/game/station_control.rs +++ b/crates/horizon-client/src/game/station_control.rs @@ -14,6 +14,8 @@ pub(super) const HELP: &[&str] = &[ "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", + "effect ID SECONDS [AMPLIFIER] give a status effect (effect clear removes all)", + "effects list active status effects", "close close the open menu", ]; fn id(name: &str) -> String { @@ -138,6 +140,18 @@ impl Game<'_> { "slots": slots, }))) } + "effect" => { + if arg(1)? == "clear" { + self.potions.effects.clear(); + return ok(); + } + let def = horizon_client::brewing::effect(arg(1)?).ok_or("unknown effect")?; + let seconds: i32 = arg(2)?.parse()?; + let amp: i32 = words.get(3).map_or(Ok(0), |a| a.parse())?; + self.potions.effects.add(horizon_client::effects::EffectInstance::new(def.id, seconds * 20, amp)); + ok() + } + "effects" => Ok(Some(json!({ "effects": self.effects_json(), "health": self.player.as_ref().map(|p| p.health.health()) }))), "close" => { self.close_container(); self.screen = Screen::Playing; diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index 49e6319ac..3b0169ab3 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -174,11 +174,7 @@ impl Game<'_> { 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); - } + self.give_or_drop(stack); } } pub(super) fn station_slots(&self) -> Option> { diff --git a/crates/horizon-client/src/health.rs b/crates/horizon-client/src/health.rs index fedb8db09..e4bf7b96b 100644 --- a/crates/horizon-client/src/health.rs +++ b/crates/horizon-client/src/health.rs @@ -229,6 +229,7 @@ impl PlayerMotion { dead: &mut h.dead, sync_velocity: &mut h.sync_velocity, game_time: h.game_time, + status: self.status.clone(), }; Ok(ServerPlayerCombat::new( &mut self.attributes, @@ -264,6 +265,8 @@ pub(crate) struct Environment<'a> { pub(crate) dead: &'a mut bool, pub(crate) sync_velocity: &'a mut bool, pub(crate) game_time: i64, + /// Resistance, fire resistance and armor protection (effects.rs). + pub(crate) status: crate::effects::StatusFlags, } impl Environment<'_> { fn event(&mut self, event: HealthEvent) { @@ -310,10 +313,10 @@ impl ServerDamageEnvironment for Environment<'_> { Ok(()) } // empty equipment fn has_resistance(&mut self) -> io::Result { - Ok(false) + Ok(self.status.resistance.is_some()) } fn resistance_amplifier(&mut self) -> io::Result { - Err(io::Error::other("no resistance effect")) + self.status.resistance.ok_or_else(|| io::Error::other("no resistance effect")) } fn award_resisted(&mut self, value: i32) -> io::Result<()> { self.stat("resisted", value) @@ -325,8 +328,8 @@ impl ServerDamageEnvironment for Environment<'_> { Err(io::Error::other("no damage attacker")) } fn damage_protection(&mut self, _: ()) -> io::Result { - Ok(0.0) - } // empty equipment + Ok(self.status.protection(&self.source.definition().name)) + } fn award_self(&mut self, stat: DamageStat, value: i32) -> io::Result<()> { self.stat( match stat { @@ -426,7 +429,7 @@ impl HurtWorld for Environment<'_> { Ok(self.source.hurt_tag(tag)) } fn fire_resistance(&mut self, _: &mut State) -> io::Result { - Ok(false) + Ok(self.status.fire_resistance) } fn sleeping(&mut self, _: &mut State) -> io::Result { Ok(false) diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index fa6a0f20e..1182844d1 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -72,6 +72,7 @@ impl HudAtlas { walk(&textures.join("misc"), &mut files); walk(&textures.join("entity"), &mut files); walk(&textures.join("particle"), &mut files); + walk(&textures.join("mob_effect"), &mut files); files.retain(|p| { let s = p.to_string_lossy(); (!s.contains("title/background") || s.contains("panorama_")) && !s.contains("realms") && !s.contains("presets") diff --git a/crates/horizon-client/src/hunger.rs b/crates/horizon-client/src/hunger.rs index 1a70d975b..531bc12b6 100644 --- a/crates/horizon-client/src/hunger.rs +++ b/crates/horizon-client/src/hunger.rs @@ -134,6 +134,7 @@ impl FoodWorld for TickWorld<'_> { dead: self.dead, sync_velocity: self.sync_velocity, game_time: self.game_time, + status: Default::default(), }; ServerPlayerCombat::new(self.attributes, self.data, food, self.ids, &mut environment)? .hurt(self.hurt, amount)?; diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index da184a553..10284d4c3 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -327,6 +327,10 @@ struct LootContext<'a> { killed_by_player: bool, } impl LootContext<'_> { + /// Level of an enchantment on the tool / killer's weapon. + fn enchantment_level(&self, id: &str) -> u32 { + self.held.map_or(0, |h| h.enchantment_level(id)) + } fn number(&self, v: &Value, random: &mut LegacyRandom) -> f32 { match v { Value::Number(n) => n.as_f64().unwrap_or(0.0) as f32, @@ -374,14 +378,17 @@ impl LootContext<'_> { }; match kind { "minecraft:survives_explosion" => true, - "minecraft:tool/can_silk_touch" => false, + "minecraft:tool/can_silk_touch" => self.enchantment_level("minecraft:silk_touch") > 0, "minecraft:tool/can_shear" => self.held.is_some_and(|h| &*h.item == "minecraft:shears"), "minecraft:inverted" => !self.condition(&c["term"], random), "minecraft:any_of" => c["terms"].as_array().into_iter().flatten().any(|t| self.condition(t, random)), "minecraft:all_of" => c["terms"].as_array().into_iter().flatten().all(|t| self.condition(t, random)), "minecraft:random_chance" => random.next_float() < self.number(&c["chance"], random), "minecraft:table_bonus" => { - let chance = c["chances"][0].as_f64().unwrap_or(0.0) as f32; + // BonusLevelTableCondition: chances[min(level, len - 1)]. + let level = self.enchantment_level(c["enchantment"].as_str().unwrap_or("")) as usize; + let chances = c["chances"].as_array().map_or(&[][..], Vec::as_slice); + let chance = chances.get(level.min(chances.len().saturating_sub(1))).and_then(Value::as_f64).unwrap_or(0.0) as f32; random.next_float() < chance } "minecraft:match_block" | "minecraft:block_state_property" => { @@ -405,17 +412,32 @@ impl LootContext<'_> { } "minecraft:match_tool" => { let items = &c["predicate"]["items"]; - match (self.held, items) { + let items_ok = match (self.held, items) { + (_, Value::Null) => self.held.is_some(), (Some(h), Value::String(s)) => match s.strip_prefix('#') { Some(tag) => self.items.item_tags.get(tag).is_some_and(|t| t.contains(&*h.item)), None => **s == *h.item, }, _ => false, - } + }; + // ItemPredicate "minecraft:enchantments": each entry needs a level in range. + let enchants_ok = c["predicate"]["predicates"]["minecraft:enchantments"].as_array().into_iter().flatten().all(|e| { + let level = self.enchantment_level(e["enchantments"].as_str().unwrap_or("")); + let min = e["levels"]["min"].as_u64().unwrap_or(1) as u32; + let max = e["levels"]["max"].as_u64().map_or(u32::MAX, |m| m as u32); + level >= min.max(1) && level <= max + }); + items_ok && enchants_ok } "minecraft:killed_by_player" => self.killed_by_player, "minecraft:random_chance_with_enchanted_bonus" => { - random.next_float() < c["unenchanted_chance"].as_f64().unwrap_or(0.0) as f32 + let level = if self.killed_by_player && self.block.is_empty() { self.enchantment_level(c["enchantment"].as_str().unwrap_or("")) } else { 0 }; + let chance = if level > 0 { + crate::enchant::level_value(&c["enchanted_chance"], level) + } else { + c["unenchanted_chance"].as_f64().unwrap_or(0.0) as f32 + }; + random.next_float() < chance } // Entity flags, equipment and damage-source predicates: none hold // for an unenchanted player kill without fire or lightning. @@ -526,6 +548,44 @@ impl LootContext<'_> { let base = if f["add"].as_bool() == Some(true) { stack.count as i32 } else { 0 }; stack.count = (base + n).max(0) as u32; } + "minecraft:apply_bonus" => { + let level = self.enchantment_level(f["enchantment"].as_str().unwrap_or("")) as i32; + let count = stack.count as i32; + let params = &f["parameters"]; + stack.count = match f["formula"].as_str().unwrap_or("") { + "minecraft:ore_drops" if level > 0 => { + let bonus = (random.next_int_bound(level + 2).unwrap_or(0) - 1).max(0); + count * (bonus + 1) + } + "minecraft:uniform_bonus_count" => { + let multiplier = params["bonusMultiplier"].as_i64().unwrap_or(1) as i32; + count + random.next_int_bound(multiplier * level + 1).unwrap_or(0) + } + "minecraft:binomial_with_bonus_count" => { + let (extra, p) = (params["extra"].as_i64().unwrap_or(0) as i32, params["probability"].as_f64().unwrap_or(0.0) as f32); + let mut n = count; + for _ in 0..level + extra { + if random.next_float() < p { + n += 1; + } + } + n + } + _ => count, + } + .max(0) as u32; + } + "minecraft:enchanted_count_increase" => { + // Attacker's level x count, rounded (looting). + let level = self.enchantment_level(f["enchantment"].as_str().unwrap_or("")); + if level > 0 && self.killed_by_player && self.block.is_empty() { + let add = level as f32 * self.number(&f["count"], random); + stack.count = (stack.count as i32 + add.round() as i32).max(0) as u32; + if let Some(limit) = f["limit"].as_i64().filter(|l| *l > 0) { + stack.count = stack.count.min(limit as u32); + } + } + } "minecraft:limit_count" => { let limit = &f["limit"]; if let Some(min) = limit["min"].as_i64() { diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index ebd9b2da3..f2db3d27f 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -15,6 +15,7 @@ pub mod crafting; pub mod enchant; pub mod creative; pub mod collisions; +pub mod effects; pub mod entities; pub mod environment; pub mod gfx; diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index fb5a835b9..948dbf49d 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -152,6 +152,8 @@ pub struct PlayerMotion { pub attributes: LiveAttributes i32>>, pub impulse: ImpulseContext, pub health: crate::health::PlayerHealth, + /// Status effects and armor protection seen by movement and damage. + pub status: crate::effects::StatusFlags, } fn attribute_error(error: impl std::fmt::Debug) -> io::Error { io::Error::other(format!("movement attribute: {error:?}")) @@ -189,6 +191,7 @@ impl PlayerMotion { .map_err(attribute_error)?; Ok(Self { health: crate::health::PlayerHealth::new(&resources.health, &mut attributes)?, + status: crate::effects::StatusFlags::default(), impulse: ImpulseContext::default(), position, velocity: Vec3::ZERO, @@ -920,7 +923,7 @@ impl LivingAirWorld for MotionWorld<'_, '_, '_> { Ok(false) } fn levitation_amplifier(&mut self) -> Result> { - Ok(None) + Ok(self.player.status.levitation) } fn is_client_side(&mut self) -> Result { Ok(false) @@ -970,10 +973,10 @@ impl LivingMotionWorld for MotionWorld<'_, '_, '_> { )?) } fn has_jump_boost(&mut self) -> Result { - Ok(false) + Ok(self.player.status.jump_boost.is_some()) } fn jump_boost_amplifier(&mut self) -> Result { - Err("absent jump boost".into()) + self.player.status.jump_boost.ok_or_else(|| "absent jump boost".into()) } fn sprinting(&mut self) -> Result { Ok(self.player.sprinting) @@ -991,7 +994,7 @@ impl LivingMotionWorld for MotionWorld<'_, '_, '_> { self.player.attribute("minecraft:gravity") } fn has_slow_falling(&mut self) -> Result { - Ok(false) + Ok(self.player.status.slow_falling) } fn controlling_passenger_is_player(&mut self) -> Result { Ok(false) From 708451f28d89ae1c07a1ced3e67ef75c0447e3e4 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:39:08 +0200 Subject: [PATCH 5/9] Add villager trading: data-driven offers, merchant pricing and the trading menu Offers come from the trade_set/villager_trade registries through each set's RandomSequence (world seed + sequence id), with merchant predicates, enchant_with_levels/enchant_randomly/filtered/set_potion modifiers and the additional trade cost. MerchantOffer pricing (demand, price multiplier, special price), payment matching and stock follow vanilla; the trading menu matches MerchantScreen and levels the merchant up with new offers. horizon-ctl 'trade PROFESSION [LEVEL]' opens it until villagers exist. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/enchant.rs | 8 +- crates/horizon-client/src/game.rs | 1 + crates/horizon-client/src/game/potions.rs | 2 + .../src/game/station_control.rs | 11 + crates/horizon-client/src/game/stations.rs | 28 +- crates/horizon-client/src/game/trading.rs | 311 ++++++++++++ crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/merchant.rs | 466 ++++++++++++++++++ crates/horizon-client/src/stations.rs | 8 +- 9 files changed, 830 insertions(+), 6 deletions(-) create mode 100644 crates/horizon-client/src/game/trading.rs create mode 100644 crates/horizon-client/src/merchant.rs diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-client/src/enchant.rs index 0204e951e..3fbe56fd6 100644 --- a/crates/horizon-client/src/enchant.rs +++ b/crates/horizon-client/src/enchant.rs @@ -279,7 +279,7 @@ impl Enchantments { // ---- Enchanting table (EnchantmentHelper) ---- /// `EnchantmentHelper.getEnchantmentCost`. - pub fn enchantment_cost(&self, random: &mut LegacyRandom, slot: usize, bookcases: i32, item: &str) -> i32 { + pub fn enchantment_cost(&self, random: &mut R, slot: usize, bookcases: i32, item: &str) -> i32 { if self.enchantable(item) == 0 { return 0; } @@ -309,7 +309,7 @@ impl Enchantments { } out } - fn weighted(&self, random: &mut LegacyRandom, list: &[(Arc, u32)]) -> Option<(Arc, u32)> { + fn weighted(&self, random: &mut R, list: &[(Arc, u32)]) -> Option<(Arc, u32)> { let total: i32 = list.iter().map(|(id, _)| self.get(id).map_or(0, |e| e.weight as i32)).sum(); if total <= 0 { return None; @@ -324,7 +324,7 @@ impl Enchantments { None } /// `EnchantmentHelper.selectEnchantment`. - pub fn select(&self, items: &Items, random: &mut LegacyRandom, item: &str, cost: i32, pool: &[Arc]) -> Vec<(Arc, u32)> { + pub fn select(&self, items: &Items, random: &mut R, item: &str, cost: i32, pool: &[Arc]) -> Vec<(Arc, u32)> { let mut results = Vec::new(); let value = self.enchantable(item) as i32; if value == 0 { @@ -482,7 +482,7 @@ pub struct EffectContext<'a> { pub attacker: Option<&'a str>, pub direct_attacker: Option<&'a str>, } -fn next_int(random: &mut LegacyRandom, bound: i32) -> i32 { +fn next_int(random: &mut R, bound: i32) -> i32 { random.next_int_bound(bound.max(1)).unwrap_or(0) } /// `LevelBasedValue.calculate`. diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 23b38e6ed..17e4ffd73 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5,6 +5,7 @@ mod enchant_effects; mod potions; mod station_control; mod stations; +mod trading; use horizon_client::{ Result, assets::Assets, diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index d2ccb344c..cd7297be5 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -31,6 +31,8 @@ pub(super) struct PotionState { pub(super) burning: Vec<(u32, i32)>, /// Enchantment attribute modifiers on the player: (attribute, id, amount, operation). pub(super) enchant_modifiers: Vec<(String, String, f64, String)>, + /// The level's trade-set `RandomSequence`s, by sequence id. + pub(super) trade_randoms: std::collections::HashMap, } impl Game<'_> { diff --git a/crates/horizon-client/src/game/station_control.rs b/crates/horizon-client/src/game/station_control.rs index a7a71c2b4..a30e15b52 100644 --- a/crates/horizon-client/src/game/station_control.rs +++ b/crates/horizon-client/src/game/station_control.rs @@ -16,6 +16,7 @@ pub(super) const HELP: &[&str] = &[ "menu JSON dump of the open menu, carried stack and inventory", "effect ID SECONDS [AMPLIFIER] give a status effect (effect clear removes all)", "effects list active status effects", + "trade PROFESSION [LEVEL] [TYPE] open a villager trading menu (offers from the world's trade sequences)", "close close the open menu", ]; fn id(name: &str) -> String { @@ -151,6 +152,16 @@ impl Game<'_> { self.potions.effects.add(horizon_client::effects::EffectInstance::new(def.id, seconds * 20, amp)); ok() } + "trade" => { + let profession = arg(1)?.trim_start_matches("minecraft:").to_owned(); + if !horizon_client::merchant::PROFESSIONS.contains(&profession.as_str()) { + return Err(format!("unknown profession {profession}").into()); + } + let level: i32 = words.get(2).map_or(Ok(1), |l| l.parse())?; + let variant = id(words.get(3).copied().unwrap_or("plains")); + self.open_merchant(&profession, &variant, level); + ok() + } "effects" => Ok(Some(json!({ "effects": self.effects_json(), "health": self.player.as_ref().map(|p| p.health.health()) }))), "close" => { self.close_container(); diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index 3b0169ab3..d9c1b507f 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -26,6 +26,8 @@ pub(super) enum Kind { Grindstone, Smithing, Stonecutter, + /// Villager trading (game/trading.rs). + Merchant, } impl Kind { fn from_block(name: &str) -> Option { @@ -52,6 +54,7 @@ impl Kind { Self::Grindstone => "gui/container/grindstone", Self::Smithing => "gui/container/smithing", Self::Stonecutter => "gui/container/stonecutter", + Self::Merchant => "gui/container/villager", } } fn title_key(self) -> &'static str { @@ -61,6 +64,7 @@ impl Kind { Self::Grindstone => "container.grindstone_title", Self::Smithing => "container.upgrade", Self::Stonecutter => "container.stonecutter", + Self::Merchant => "merchant.trades", } } /// (titleLabelX, titleLabelY). @@ -79,6 +83,7 @@ impl Kind { 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)], + Self::Merchant => &[(86.0, 37.0), (112.0, 37.0)], }; table[i.min(table.len() - 1)] } @@ -89,6 +94,7 @@ impl Kind { Self::Grindstone => Some((129.0, 34.0)), Self::Smithing => Some((98.0, 48.0)), Self::Stonecutter => Some((143.0, 33.0)), + Self::Merchant => Some((170.0, 37.0)), } } } @@ -97,7 +103,7 @@ pub(super) struct Station { pub(super) kind: Kind, pub(super) pos: [i32; 3], pub(super) inputs: Vec>, - result: Option, + pub(super) result: Option, offers: EnchantOffers, bookcases: i32, anvil: AnvilResult, @@ -111,6 +117,8 @@ pub(super) struct Station { /// Anvil: the input the rename box was last filled from. anvil_last: Option, last_sound: u64, + /// Villager trading state. + pub(super) merchant: Option>, } impl Station { fn new(kind: Kind, pos: [i32; 3]) -> Self { @@ -129,8 +137,12 @@ impl Station { input_item: None, anvil_last: None, last_sound: 0, + merchant: None, } } + pub(super) fn new_kind(kind: Kind, pos: [i32; 3]) -> Self { + Self::new(kind, pos) + } } /// The 108x19 enchantment button `i` (relative to the GUI origin). @@ -195,6 +207,9 @@ impl Game<'_> { 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()?; + if s.kind == Kind::Merchant && i < 36 { + return Some(super::trading::inventory_slot(i)); + } match i { RESULT => s.kind.result_pos(), _ if i >= INPUT && i < INPUT + s.inputs.len() => Some(s.kind.input_pos(i - INPUT)), @@ -253,6 +268,7 @@ impl Game<'_> { 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::Merchant => super::trading::update(&mut s, items), Kind::Stonecutter => { let item = s.inputs[0].as_ref().map(|i| i.item.clone()); if item != s.input_item { @@ -430,6 +446,7 @@ impl Game<'_> { moved = self.move_to(&mut stack, &[INPUT, INPUT + 1], false); } } + Some(Kind::Merchant) => {} 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(); @@ -565,6 +582,7 @@ impl Game<'_> { self.play_at("minecraft:ui.stonecutter.take_result", pos, 1.0, 1.0); } } + Kind::Merchant => self.merchant_take(&mut s), Kind::Enchanting => {} } self.station = Some(s); @@ -647,6 +665,9 @@ impl Game<'_> { 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::Merchant && !right && self.merchant_click(local) { + return true; + } if kind == Kind::Enchanting && !right { for i in 0..3 { let (x, y, w, h) = enchant_button(i); @@ -705,6 +726,7 @@ impl Game<'_> { self.station_changed(); } pub(super) fn station_scroll(&mut self, d: f32) { + self.merchant_scroll(d); let Some(s) = self.station.as_mut() else { return }; if s.kind != Kind::Stonecutter || s.recipes.len() <= 12 { return; @@ -793,6 +815,9 @@ impl Game<'_> { } /// Draws the open station or brewing stand screen; false when none is open. pub(super) fn draw_station(&mut self, batch: &mut HudBatch) -> bool { + if self.station.as_ref().is_some_and(|s| s.kind == Kind::Merchant) { + return self.draw_merchant(batch); + } let brewing = self.brewing_open(); if self.station.is_none() && !brewing { return false; @@ -963,6 +988,7 @@ impl Game<'_> { } } } + Kind::Merchant => {} Kind::Stonecutter => { let display = s.inputs[0].is_some() && !s.recipes.is_empty(); let active = display && s.recipes.len() > 12; diff --git a/crates/horizon-client/src/game/trading.rs b/crates/horizon-client/src/game/trading.rs new file mode 100644 index 000000000..a2eb6e261 --- /dev/null +++ b/crates/horizon-client/src/game/trading.rs @@ -0,0 +1,311 @@ +//! The merchant (villager trading) menu: `MerchantMenu` / `MerchantScreen` +//! layout (276x166, drawn 50 px left of the usual 176-wide origin), offer +//! buttons, payment slots, the result slot's `onTake`, villager experience and +//! level-ups with new offers from the next trade set. +use super::{ + Game, + stations::{INPUT, Kind, RESULT, Station}, +}; +use horizon_client::{ + hud::{HudBatch, rgba}, + items::ItemStack, + merchant::{self, MerchantOffer, TradeContext}, +}; +use horizon_core::random::RandomSource; + +/// The merchant screen is 100 px wider than the 176-px menus it shares an origin with. +const SHIFT: f32 = -50.0; +const GREY: u32 = 0xFF40_4040; + +pub(super) struct MerchantState { + pub(super) profession: String, + pub(super) variant: String, + pub(super) level: i32, + pub(super) xp: i32, + pub(super) offers: Vec, + /// `shopItem` / selection hint, scroll offset, and the active offer. + pub(super) shop_item: usize, + pub(super) scroll: usize, + pub(super) active: Option, + pub(super) future_xp: i32, + /// The offer button that keeps focus after a click (drawn highlighted). + pub(super) focused: Option, +} +/// Player inventory slot positions in `MerchantMenu` (x from 108). +pub(super) fn inventory_slot(i: usize) -> (f32, f32) { + match i { + 0..9 => (108.0 + SHIFT + i as f32 * 18.0, 142.0), + _ => (108.0 + SHIFT + ((i - 9) % 9) as f32 * 18.0, 84.0 + ((i - 9) / 9) as f32 * 18.0), + } +} +/// `MerchantContainer.updateSellItem`. +pub(super) fn update(s: &mut Station, items: &horizon_client::items::Items) { + let Some(m) = s.merchant.as_mut() else { return }; + let (active, result) = merchant::sell_item(&m.offers, items, s.inputs[0].as_ref(), s.inputs[1].as_ref(), Some(m.shop_item)); + m.active = active; + m.future_xp = if result.is_some() { active.map_or(0, |i| m.offers[i].xp) } else { 0 }; + s.result = result; +} + +impl Game<'_> { + /// Offers a villager of `profession` gets on reaching `level`. + fn new_offers(&mut self, profession: &str, variant: &str, level: i32) -> Vec { + let set = merchant::Trades::set_for(profession, level); + let sequence = format!("minecraft:trade_set/{}", set.trim_start_matches("minecraft:")); + let random = self.potions.trade_randoms.entry(sequence.clone()).or_insert_with(|| merchant::sequence_random(self.level.seed, &sequence)); + let ctx = TradeContext { items: &self.res.items, enchantments: &self.res.stations.enchantments, variant }; + self.res.stations.trades.offers_from_set(&ctx, &set, random) + } + /// Opens a merchant menu for a villager (or a generated one for tests). + pub(super) fn open_merchant(&mut self, profession: &str, variant: &str, level: i32) { + let mut offers = Vec::new(); + for l in 1..=level.clamp(1, 5) { + offers.extend(self.new_offers(profession, variant, l)); + } + let mut s = Station::new_kind(Kind::Merchant, [0, 0, 0]); + s.merchant = Some(Box::new(MerchantState { + profession: profession.trim_start_matches("minecraft:").to_owned(), + variant: variant.to_owned(), + level: level.clamp(1, 5), + xp: merchant::min_xp(level.clamp(1, 5)), + offers, + shop_item: 0, + scroll: 0, + active: None, + future_xp: 0, + focused: None, + })); + self.station = Some(s); + self.screen = super::Screen::Inventory; + self.capture(false); + self.right = false; + } + /// `MerchantResultSlot.onTake` and `Villager.notifyTrade` / `rewardTradeXp`. + pub(super) fn merchant_take(&mut self, s: &mut Station) { + let items = &self.res.items; + let Some(m) = s.merchant.as_mut() else { return }; + let Some(i) = m.active else { return }; + let offer = m.offers[i].clone(); + let (mut a, mut b) = (s.inputs[0].take(), s.inputs[1].take()); + let took = offer.take(items, &mut a, &mut b) || offer.take(items, &mut b, &mut a); + s.inputs[0] = a; + s.inputs[1] = b; + if !took { + return; + } + m.offers[i].uses += 1; + let mut pop = 3 + self.world.random.next_int_bound(4).unwrap_or(0); + m.xp += offer.xp; + let level_up = merchant::can_level_up(m.level) && m.xp >= merchant::max_xp(m.level); + let at = self.player.as_ref().map(|p| [p.position.x, p.position.y + 0.5, p.position.z]); + self.audio.play("minecraft:entity.villager.yes", at, 1.0, 1.0); + if level_up { + let (profession, variant, level) = (m.profession.clone(), m.variant.clone(), m.level + 1); + m.level = level; + let more = self.new_offers(&profession, &variant, level); + if let Some(m) = s.merchant.as_mut() { + m.offers.extend(more); + } + pop += 5; + } + if offer.reward_exp + && let Some(at) = at + { + self.spawn_orbs(at, pop as u32); + } + } + /// `MerchantMenu.tryMoveItems`: return payment, then fill it for the selected offer. + fn try_move_items(&mut self, index: usize) { + let Some(s) = self.station.as_mut() else { return }; + let returned: Vec = s.inputs.iter_mut().filter_map(Option::take).collect(); + for stack in returned { + if let Some(rest) = self.give(stack) + && let Some(eye) = self.eye_position() + { + self.spawn_item(rest, eye, [0.0, 0.1, 0.0], 40); + } + } + let Some(offer) = self.station.as_ref().and_then(|s| s.merchant.as_ref()).and_then(|m| m.offers.get(index)).cloned() else { return }; + let wants = [Some(offer.cost_a(&self.res.items)), offer.cost_b()]; + for (slot, want) in wants.into_iter().enumerate() { + let Some(want) = want else { continue }; + let max = self.res.items.get(&want.item).map_or(64, |i| i.max_stack); + let mut gathered: Option = None; + for i in (9..36).chain(0..9) { + let Some(s) = self.inventory[i].as_mut() else { continue }; + if !s.same_item_same_components(&ItemStack { count: s.count, ..want.clone() }) { + continue; + } + let have = gathered.as_ref().map_or(0, |g| g.count); + let n = s.count.min(max - have); + if n == 0 { + break; + } + s.count -= n; + let taken = ItemStack { count: n, ..s.clone() }; + if s.count == 0 { + self.inventory[i] = None; + } + match gathered.as_mut() { + Some(g) => g.count += n, + None => gathered = Some(taken), + } + } + if let Some(st) = self.station.as_mut() { + st.inputs[slot] = gathered; + } + } + } + /// Clicks on the offer list; true when one was hit. + pub(super) fn merchant_click(&mut self, local: (f32, f32)) -> bool { + let Some(m) = self.station.as_ref().and_then(|s| s.merchant.as_ref()) else { return false }; + for i in 0..7 { + let (x, y) = (5.0 + SHIFT, 18.0 + 20.0 * i as f32); + if local.0 >= x && local.0 < x + 88.0 && local.1 >= y && local.1 < y + 20.0 && i + m.scroll < m.offers.len() { + let index = i + m.scroll; + if let Some(m) = self.station.as_mut().and_then(|s| s.merchant.as_mut()) { + m.shop_item = index; + m.focused = Some(i); + } + self.audio.play("minecraft:ui.button.click", None, 0.25, 1.0); + self.try_move_items(index); + self.station_changed(); + return true; + } + } + false + } + pub(super) fn merchant_scroll(&mut self, d: f32) { + let Some(m) = self.station.as_mut().and_then(|s| s.merchant.as_mut()) else { return }; + if m.offers.len() > 7 { + let max = m.offers.len() - 7; + m.scroll = (m.scroll as i32 - d.signum() as i32).clamp(0, max as i32) as usize; + } + } + /// `MerchantScreen` rendering. + pub(super) fn draw_merchant(&mut self, batch: &mut HudBatch) -> bool { + let (ox, oy) = self.inventory_origin(batch); + let local = (self.cursor.0 - ox, self.cursor.1 - oy); + let Some(m) = self.station.as_ref().and_then(|s| s.merchant.as_ref()) else { return false }; + let (profession, level, xp, scroll, shop, future, focused) = (m.profession.clone(), m.level, m.xp, m.scroll, m.shop_item, m.future_xp, m.focused); + let offers = m.offers.clone(); + let costs: Vec = offers.iter().map(|o| o.cost_a(&self.res.items)).collect(); + let atlas = &self.res.atlas; + batch.fill(atlas, 0.0, 0.0, batch.width, batch.height, rgba(16, 16, 16, 160)); + if let Some(mut r) = atlas.sprites.get("gui/container/villager").copied() { + let (du, dv) = ((r.u1 - r.u0) / r.w as f32, (r.v1 - r.v0) / r.h as f32); + r.u1 = r.u0 + 276.0 * du; + r.v1 = r.v0 + 166.0 * dv; + batch.rect_uv(ox + SHIFT, oy, 276.0, 166.0, r, u32::MAX); + } + let e = &self.res.stations.enchantments; + let tr = |k: &str, f: &str| e.translate(k).unwrap_or(f).to_owned(); + let name = tr(&format!("entity.minecraft.villager.{profession}"), &profession); + let title = tr("merchant.title", "%s - %s").replacen("%s", &name, 1).replacen("%s", &tr(&format!("merchant.level.{level}"), ""), 1); + let tw = HudBatch::text_width(atlas, &title); + batch.text(atlas, &title, ox + SHIFT + (49.0 + 138.0 - (tw / 2.0).floor()), oy + 6.0, GREY, false); + let trades = tr("merchant.trades", "Trades"); + let tw = HudBatch::text_width(atlas, &trades); + batch.text(atlas, &trades, ox + SHIFT + 5.0 - (tw / 2.0).floor() + 48.0, oy + 6.0, GREY, false); + batch.text(atlas, &tr("container.inventory", "Inventory"), ox + SHIFT + 107.0, oy + 72.0, GREY, false); + if offers.get(shop).is_some_and(MerchantOffer::out_of_stock) { + batch.sprite(atlas, "gui/sprites/container/villager/out_of_stock", ox + SHIFT + 182.0, oy + 35.0); + } + // Experience bar (levels 1-4). + if level < 5 { + batch.sprite(atlas, "gui/sprites/container/villager/experience_bar_background", ox + SHIFT + 136.0, oy + 16.0); + let min = merchant::min_xp(level); + if xp >= min && merchant::can_level_up(level) { + let mult = 102.0 / (merchant::max_xp(level) - min) as f32; + let w = ((mult * (xp - min) as f32).floor()).min(102.0); + batch.sprite_part(atlas, "gui/sprites/container/villager/experience_bar_current", ox + SHIFT + 136.0, oy + 16.0, w / 102.0); + if future > 0 { + let fw = (future as f32 * mult).floor().min(102.0 - w); + if let Some(mut r) = atlas.sprites.get("gui/sprites/container/villager/experience_bar_result").copied() { + let du = (r.u1 - r.u0) / r.w as f32; + r.u0 += w * du; + r.u1 = r.u0 + fw * du; + batch.rect_uv(ox + SHIFT + 136.0 + w, oy + 16.0, fw, 5.0, r, u32::MAX); + } + } + } + } + // Scroller. + let steps = offers.len() as i32 + 1 - 7; + if steps > 1 { + let left = 139 - (27 + (steps - 1) * 139 / steps); + let step = 1 + left / steps + 139 / steps; + let mut y = (scroll as i32 * step).min(113); + if scroll as i32 == steps - 1 { + y = 113; + } + batch.sprite(atlas, "gui/sprites/container/villager/scroller", ox + SHIFT + 94.0, oy + 18.0 + y as f32); + } else { + batch.sprite(atlas, "gui/sprites/container/villager/scroller_disabled", ox + SHIFT + 94.0, oy + 18.0); + } + // Offer buttons. + let mut tooltip: Option = None; + for (row, (index, offer)) in offers.iter().enumerate().skip(scroll).take(7).enumerate() { + let (bx, by) = (ox + SHIFT + 5.0, oy + 18.0 + 20.0 * row as f32); + let hover = local.0 >= 5.0 + SHIFT && local.0 < 93.0 + SHIFT && local.1 >= 18.0 + 20.0 * row as f32 && local.1 < 38.0 + 20.0 * row as f32; + let sprite = if hover || focused == Some(row) { "gui/sprites/widget/button_highlighted" } else { "gui/sprites/widget/button" }; + batch.sprite_scaled(&self.res.atlas, sprite, bx, by, 88.0, 20.0, u32::MAX); + let y = oy + 16.0 + 1.0 + 20.0 * row as f32 + 2.0; + let base = offer.base_cost_a.stack.clone(); + let cost_a = costs[index].clone(); + let x = ox + SHIFT + 10.0; + if base.count == cost_a.count { + self.draw_item(batch, &cost_a, x, y); + } else { + // Discounted: the base price struck through, then the new price. + self.draw_item(batch, &ItemStack { count: 1, ..cost_a.clone() }, x, y); + let atlas = &self.res.atlas; + let t = base.count.to_string(); + batch.text(atlas, &t, x + 17.0 - HudBatch::text_width(atlas, &t), y + 9.0, u32::MAX, true); + let t = cost_a.count.to_string(); + batch.text(atlas, &t, x + 14.0 + 17.0 - HudBatch::text_width(atlas, &t), y + 9.0, u32::MAX, true); + batch.sprite(atlas, "gui/sprites/container/villager/discount_strikethrough", x + 7.0, y + 12.0); + } + if let Some(b) = offer.cost_b() { + self.draw_item(batch, &b, ox + SHIFT + 40.0, y); + } + let arrow = if offer.out_of_stock() { "trade_arrow_out_of_stock" } else { "trade_arrow" }; + batch.sprite(&self.res.atlas, &format!("gui/sprites/container/villager/{arrow}"), ox + SHIFT + 60.0, y + 3.0); + self.draw_item(batch, &offer.result, ox + SHIFT + 73.0, y); + if hover && self.carried.is_none() { + let rel = local.0 - (5.0 + SHIFT); + tooltip = if rel < 20.0 { + Some(cost_a) + } else if rel > 30.0 && rel < 50.0 { + offer.cost_b() + } else if rel > 65.0 { + Some(offer.result.clone()) + } else { + None + }; + } + } + // Slots, hover highlight, carried stack, tooltip. + let slots: Vec = (0..36).chain([INPUT, INPUT + 1, RESULT]).collect(); + for i in slots { + let (sx, sy) = self.slot_position(i); + if let Some(stack) = self.slot_mut(i).clone() { + 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() { + tooltip = self.slot_mut(slot).clone(); + } + } + 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(stack) = tooltip { + let lines = self.stack_tooltip(&stack); + self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1); + } + true + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index f2db3d27f..990c7e7f0 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -27,6 +27,7 @@ pub mod item_data; pub mod items; pub mod landing; pub mod light; +pub mod merchant; pub mod mesher; pub mod mobs; pub mod models; diff --git a/crates/horizon-client/src/merchant.rs b/crates/horizon-client/src/merchant.rs new file mode 100644 index 000000000..8c52a1c42 --- /dev/null +++ b/crates/horizon-client/src/merchant.rs @@ -0,0 +1,466 @@ +//! Villager trading: the data-driven `trade_set` / `villager_trade` registries, +//! offer generation (`AbstractVillager.addOffersFromTradeSet` with each +//! set's `RandomSequence`), `MerchantOffer` pricing, demand and stock, and the +//! `VillagerData` level thresholds. The villager entity itself is not part of +//! this module; anything that can trade calls [`Merchant`]. +use crate::{ + enchant::Enchantments, + items::{ItemStack, Items}, +}; +use horizon_core::random::{RandomSource, XoroshiroRandom, mix_stafford13, seed_from_hash}; +use serde_json::Value; +use std::{collections::HashMap, fs, path::Path, sync::Arc}; + +/// `VillagerData.NEXT_LEVEL_XP_THRESHOLDS`. +pub const LEVEL_XP: [i32; 5] = [0, 10, 70, 150, 250]; +pub fn can_level_up(level: i32) -> bool { + (1..5).contains(&level) +} +pub fn min_xp(level: i32) -> i32 { + if can_level_up(level) { LEVEL_XP[level as usize - 1] } else { 0 } +} +pub fn max_xp(level: i32) -> i32 { + if can_level_up(level) { LEVEL_XP[level as usize] } else { 0 } +} +/// The professions with trades, as in `VillagerProfession`. +pub const PROFESSIONS: &[&str] = &[ + "armorer", "butcher", "cartographer", "cleric", "farmer", "fisherman", "fletcher", "leatherworker", "librarian", "mason", "shepherd", "toolsmith", "weaponsmith", +]; + +/// An `ItemCost`: item and count (component predicates are not used by the +/// 26.3 trade data except for one exact match, kept as the stack's data). +#[derive(Clone, Debug, PartialEq)] +pub struct ItemCost { + pub stack: ItemStack, +} +impl ItemCost { + pub fn test(&self, s: &ItemStack) -> bool { + s.item == self.stack.item && (self.stack.extra.is_none() || s.data() == self.stack.data()) + } +} +#[derive(Clone, Debug, PartialEq)] +pub struct MerchantOffer { + pub base_cost_a: ItemCost, + pub cost_b: Option, + pub result: ItemStack, + pub uses: i32, + pub max_uses: i32, + pub reward_exp: bool, + pub special_price_diff: i32, + pub demand: i32, + pub price_multiplier: f32, + pub xp: i32, +} +impl MerchantOffer { + fn max_stack(items: &Items, s: &ItemStack) -> u32 { + items.get(&s.item).map_or(64, |i| i.max_stack) + } + /// `getModifiedCostCount` for cost A. + pub fn cost_a_count(&self, items: &Items) -> u32 { + let base = self.base_cost_a.stack.count as i32; + let demand_diff = ((base as f32 * self.demand as f32 * self.price_multiplier).floor() as i32).max(0); + (base + demand_diff + self.special_price_diff).clamp(1, Self::max_stack(items, &self.base_cost_a.stack) as i32) as u32 + } + pub fn cost_a(&self, items: &Items) -> ItemStack { + ItemStack { count: self.cost_a_count(items), ..self.base_cost_a.stack.clone() } + } + pub fn cost_b(&self) -> Option { + self.cost_b.as_ref().map(|c| c.stack.clone()) + } + pub fn out_of_stock(&self) -> bool { + self.uses >= self.max_uses + } + /// `MerchantOffer.updateDemand` (on restock). + pub fn update_demand(&mut self) { + self.demand = self.demand + self.uses - (self.max_uses - self.uses); + } + /// `satisfiedBy(buyA, buyB)`. + pub fn satisfied_by(&self, items: &Items, a: Option<&ItemStack>, b: Option<&ItemStack>) -> bool { + let Some(a) = a else { return false }; + if !self.base_cost_a.test(a) || a.count < self.cost_a_count(items) { + return false; + } + match (&self.cost_b, b) { + (None, b) => b.is_none(), + (Some(c), Some(b)) => c.test(b) && b.count >= c.stack.count, + (Some(_), None) => false, + } + } + /// `MerchantOffer.take`: consume the payment; false when not satisfied. + pub fn take(&self, items: &Items, a: &mut Option, b: &mut Option) -> bool { + if !self.satisfied_by(items, a.as_ref(), b.as_ref()) { + return false; + } + let n = self.cost_a_count(items); + if let Some(s) = a.as_mut() { + s.count -= n; + if s.count == 0 { + *a = None; + } + } + if let (Some(c), Some(s)) = (&self.cost_b, b.as_mut()) { + s.count -= c.stack.count; + if s.count == 0 { + *b = None; + } + } + true + } +} +/// `MerchantOffers.getRecipeFor`: the hinted offer if it fits, else the first that does. +pub fn recipe_for(offers: &[MerchantOffer], items: &Items, a: Option<&ItemStack>, b: Option<&ItemStack>, hint: Option) -> Option { + if let Some(h) = hint + && offers.get(h).is_some_and(|o| o.satisfied_by(items, a, b)) + { + return Some(h); + } + offers.iter().position(|o| o.satisfied_by(items, a, b)) +} +/// `MerchantContainer.updateSellItem`: (active offer, result). +pub fn sell_item(offers: &[MerchantOffer], items: &Items, a: Option<&ItemStack>, b: Option<&ItemStack>, hint: Option) -> (Option, Option) { + let (a, b) = if a.is_none() { (b, None) } else { (a, b) }; + if a.is_none() { + return (None, None); + } + let mut found = recipe_for(offers, items, a, b, hint); + let mut active = found; + if found.is_none_or(|i| offers[i].out_of_stock()) { + active = found; + found = recipe_for(offers, items, b, a, hint); + } + match found { + Some(i) if !offers[i].out_of_stock() => (Some(i), Some(offers[i].result.clone())), + _ => (active, None), + } +} + +/// `RandomSequence(worldSeed ^ salt, id)` with the default salt 0. +pub fn sequence_random(world_seed: i64, id: &str) -> XoroshiroRandom { + const SILVER: u64 = 0x6a09_e667_f3bc_c909; + const GOLDEN: u64 = 0x9e37_79b9_7f4a_7c15; + let lo = world_seed as u64 ^ SILVER; + let hi = lo.wrapping_add(GOLDEN); + let key = seed_from_hash(id); + XoroshiroRandom::from_state(mix_stafford13(lo ^ key[0]), mix_stafford13(hi ^ key[1])) +} + +/// The trade registries. +pub struct Trades { + pub trades: HashMap, + /// villager_trade tags, ordered. + pub tags: HashMap>, + pub sets: HashMap, +} +fn walk(dir: &Path, base: &Path, out: &mut HashMap) { + let Ok(entries) = fs::read_dir(dir) else { return }; + for e in entries.flatten() { + let p = e.path(); + if p.is_dir() { + walk(&p, base, out); + } else if p.extension().is_some_and(|x| x == "json") + && let Ok(rel) = p.strip_prefix(base) + && let Ok(bytes) = fs::read(&p) + && let Ok(v) = serde_json::from_slice(&bytes) + { + out.insert(format!("minecraft:{}", rel.with_extension("").to_string_lossy().replace('\\', "/")), v); + } + } +} +impl Trades { + pub fn load(root: &Path) -> Self { + let data = root.join("data/minecraft"); + let (mut trades, mut raw_tags, mut sets) = (HashMap::new(), HashMap::new(), HashMap::new()); + walk(&data.join("villager_trade"), &data.join("villager_trade"), &mut trades); + walk(&data.join("tags/villager_trade"), &data.join("tags/villager_trade"), &mut raw_tags); + walk(&data.join("trade_set"), &data.join("trade_set"), &mut sets); + let raw: HashMap> = raw_tags + .into_iter() + .map(|(k, v)| (k, v["values"].as_array().into_iter().flatten().filter_map(|e| e.as_str().map(str::to_owned)).collect())) + .collect(); + fn expand(name: &str, raw: &HashMap>, out: &mut Vec, depth: u32) { + for v in raw.get(name).into_iter().flatten() { + match v.strip_prefix('#') { + Some(t) if depth < 16 => expand(t, raw, out, depth + 1), + Some(_) => {} + None if !out.contains(v) => out.push(v.clone()), + None => {} + } + } + } + let tags = raw + .keys() + .map(|k| { + let mut v = Vec::new(); + expand(k, &raw, &mut v, 0); + (k.clone(), v) + }) + .collect(); + Self { trades, tags, sets } + } + /// `VillagerProfession.getTrades(level)`. + pub fn set_for(profession: &str, level: i32) -> String { + format!("minecraft:{}/level_{level}", profession.trim_start_matches("minecraft:")) + } + fn trade_list(&self, spec: &Value) -> Vec { + match spec { + Value::String(s) => match s.strip_prefix('#') { + Some(tag) => self.tags.get(tag).cloned().unwrap_or_default(), + None => vec![s.clone()], + }, + Value::Array(a) => a.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect(), + _ => vec![], + } + } + /// `AbstractVillager.addOffersFromTradeSet`. + pub fn offers_from_set(&self, ctx: &TradeContext<'_>, set_id: &str, random: &mut R) -> Vec { + let Some(set) = self.sets.get(set_id) else { return vec![] }; + let mut potential = self.trade_list(&set["trades"]); + let amount = int_provider(&set["amount"], random); + let duplicates = set["allow_duplicates"].as_bool().unwrap_or(false); + let mut out = Vec::new(); + while (out.len() as i32) < amount && !potential.is_empty() { + let roll = random.next_int_bound(potential.len() as i32).unwrap_or(0) as usize; + let id = if duplicates { potential[roll].clone() } else { potential.remove(roll) }; + match self.trades.get(&id).and_then(|t| offer_from(ctx, t, random)) { + Some(o) => out.push(o), + None if duplicates => { + potential.remove(roll); + } + None => {} + } + } + out + } +} +/// What a villager trade's loot context provides. +pub struct TradeContext<'a> { + pub items: &'a Items, + pub enchantments: &'a Enchantments, + /// Villager type (`minecraft:plains`, ...), for `merchant_predicate`. + pub variant: &'a str, +} +fn int_provider(v: &Value, random: &mut R) -> i32 { + match v { + Value::Number(n) => n.as_i64().unwrap_or(0) as i32, + Value::Object(o) => match o.get("type").and_then(Value::as_str).unwrap_or("") { + "minecraft:uniform" => { + let (min, max) = (o["min"].as_i64().unwrap_or(0) as i32, o["max"].as_i64().unwrap_or(0) as i32); + if min >= max { min } else { min + random.next_int_bound(max - min + 1).unwrap_or(0) } + } + "minecraft:constant" => o["value"].as_i64().unwrap_or(0) as i32, + _ => o.get("value").and_then(Value::as_i64).unwrap_or(0) as i32, + }, + _ => 0, + } +} +fn cost(items: &Items, v: &Value, additional: i32) -> ItemCost { + let id = v["id"].as_str().unwrap_or("minecraft:air"); + let max = items.get(id).map_or(64, |i| i.max_stack) as i32; + let count = (v["count"].as_i64().unwrap_or(1) as i32 + additional).clamp(0, max); + ItemCost { stack: ItemStack::new(id, count as u32) } +} +fn variant_ok(pred: &Value, variant: &str) -> bool { + match &pred["predicate"]["minecraft:predicates"]["minecraft:villager/variant"] { + Value::String(s) => s == variant, + Value::Array(a) => a.iter().any(|x| x.as_str() == Some(variant)), + _ => true, + } +} +/// `VillagerTrade.getOffer`. +pub fn offer_from(ctx: &TradeContext<'_>, t: &Value, random: &mut R) -> Option { + if let Some(p) = t.get("merchant_predicate") + && !variant_ok(p, ctx.variant) + { + return None; + } + let gives = &t["gives"]; + let mut result = ItemStack::new(gives["id"].as_str()?, gives["count"].as_u64().unwrap_or(1) as u32); + let mut additional = 0; + let modifiers: Vec<&Value> = match &t["given_item_modifier"] { + Value::Array(a) => a.iter().collect(), + v @ Value::Object(_) => vec![v], + _ => vec![], + }; + for m in modifiers { + let (stack, extra) = apply_modifier(ctx, m, result, random)?; + result = stack; + additional += extra; + } + if let Some(Value::String(tag)) = t.get("double_trade_price_enchantments") { + if result.stored_enchantments().iter().any(|(e, _)| ctx.enchantments.in_tag(tag, e)) { + additional *= 2; + } + } + let a = cost(ctx.items, &t["wants"], additional); + if a.stack.count < 1 { + return None; + } + let b = t.get("additional_wants").map(|w| cost(ctx.items, w, 0)); + if b.as_ref().is_some_and(|b| b.stack.count < 1) { + return None; + } + Some(MerchantOffer { + base_cost_a: a, + cost_b: b, + result, + uses: 0, + max_uses: (t["max_uses"].as_i64().unwrap_or(4) as i32).max(1), + reward_exp: true, + special_price_diff: 0, + demand: 0, + price_multiplier: (t["reputation_discount"].as_f64().unwrap_or(0.0) as f32).max(0.0), + xp: (t["xp"].as_i64().unwrap_or(1) as i32).max(0), + }) +} +/// The loot functions trades use; None discards the offer. +fn apply_modifier(ctx: &TradeContext<'_>, m: &Value, stack: ItemStack, random: &mut R) -> Option<(ItemStack, i32)> { + let e = ctx.enchantments; + let pool = |options: &Value| -> Vec> { + match options { + Value::String(s) if s.starts_with('#') => e.tag(s).to_vec(), + Value::String(s) => vec![Arc::from(s.as_str())], + Value::Array(a) => a.iter().filter_map(|x| x.as_str().map(Arc::from)).collect(), + _ => e.list.iter().map(|x| x.id.clone()).collect(), + } + }; + match m["type"].as_str().or(m["function"].as_str()).unwrap_or("") { + "minecraft:enchant_with_levels" => { + let levels = int_provider(&m["levels"], random); + // EnchantmentHelper.enchantItem on the loot context's random. + let chosen = e.select(ctx.items, random, &stack.item, levels, &pool(&m["options"])); + let mut out = if &*stack.item == "minecraft:book" { ItemStack::new("minecraft:enchanted_book", stack.count) } else { stack }; + for (id, l) in chosen { + out.enchant(&id, l); + } + let extra = if m["include_additional_cost_component"].as_bool().unwrap_or(false) && levels > 0 { levels } else { 0 }; + Some((out, extra)) + } + "minecraft:enchant_randomly" => { + let book = &*stack.item == "minecraft:book"; + let only_compatible = m["only_compatible"].as_bool().unwrap_or(true); + let options: Vec> = pool(&m["options"]).into_iter().filter(|id| book || !only_compatible || e.can_enchant(ctx.items, id, &stack.item)).collect(); + if options.is_empty() { + return Some((stack, 0)); + } + let id = options[random.next_int_bound(options.len() as i32).unwrap_or(0) as usize].clone(); + let max = e.get(&id).map_or(1, |d| d.max_level) as i32; + let level = if max <= 1 { 1 } else { 1 + random.next_int_bound(max).unwrap_or(0) }; + let mut out = if book { ItemStack::new("minecraft:enchanted_book", 1) } else { stack }; + out.enchant(&id, level as u32); + let extra = if m["include_additional_cost_component"].as_bool().unwrap_or(false) { + 2 + random.next_int_bound(5 + level * 10).unwrap_or(0) + 3 * level + } else { + 0 + }; + Some((out, extra)) + } + "minecraft:filtered" => { + let filter = &m["item_filter"]; + let item_ok = filter["items"].as_str().is_none_or(|i| i == &*stack.item); + let needs = |key: &str, have: bool| filter["predicates"][key].as_array().is_none_or(|_| have); + let ok = item_ok && needs("minecraft:enchantments", !stack.enchantments().is_empty()) && needs("minecraft:stored_enchantments", !stack.stored_enchantments().is_empty()); + if ok { + Some((stack, 0)) + } else if m["on_fail"]["type"] == "minecraft:discard" { + None + } else { + Some((stack, 0)) + } + } + "minecraft:set_potion" => Some((stack.with_potion(m["id"].as_str().unwrap_or("minecraft:water")), 0)), + "minecraft:discard" => None, + // Dyes, stew effects, random potions and exploration maps keep the plain item. + _ => Some((stack, 0)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn items() -> Items { + Items::for_tests(HashMap::new()) + } + fn offer(cost: u32, b: Option) -> MerchantOffer { + MerchantOffer { + base_cost_a: ItemCost { stack: ItemStack::new("minecraft:emerald", cost) }, + cost_b: b.map(|n| ItemCost { stack: ItemStack::new("minecraft:book", n) }), + result: ItemStack::new("minecraft:iron_boots", 1), + uses: 0, + max_uses: 12, + reward_exp: true, + special_price_diff: 0, + demand: 0, + price_multiplier: 0.2, + xp: 1, + } + } + + #[test] + fn demand_raises_prices() { + let items = items(); + let mut o = offer(4, None); + assert_eq!(o.cost_a_count(&items), 4); + o.uses = 12; + o.update_demand(); + assert_eq!(o.demand, 12); + // 4 + floor(4 * 12 * 0.2) = 13. + assert_eq!(o.cost_a_count(&items), 13); + o.special_price_diff = -20; + assert_eq!(o.cost_a_count(&items), 1); + } + + #[test] + fn payment_and_selection() { + let items = items(); + let offers = vec![offer(5, None), offer(1, Some(1))]; + let mut a = Some(ItemStack::new("minecraft:emerald", 6)); + let mut b = None; + assert_eq!(sell_item(&offers, &items, a.as_ref(), b.as_ref(), None).0, Some(0)); + assert!(offers[0].take(&items, &mut a, &mut b)); + assert_eq!(a.as_ref().unwrap().count, 1); + // Payment in the second slot only still matches (A and B swap). + let book = Some(ItemStack::new("minecraft:book", 1)); + let (i, r) = sell_item(&offers, &items, None, Some(&ItemStack::new("minecraft:emerald", 5)), None); + assert_eq!((i, r.map(|r| r.item)), (Some(0), Some(Arc::from("minecraft:iron_boots")))); + assert_eq!(sell_item(&offers, &items, a.as_ref(), book.as_ref(), Some(1)).0, Some(1)); + let mut out = offers[0].clone(); + out.uses = 12; + assert_eq!(sell_item(&[out], &items, Some(&ItemStack::new("minecraft:emerald", 5)), None, None).1, None); + } + + #[test] + fn sequence_random_is_stable() { + let mut a = sequence_random(12345, "minecraft:trade_set/armorer/level_1"); + let mut b = sequence_random(12345, "minecraft:trade_set/armorer/level_1"); + let mut c = sequence_random(12345, "minecraft:trade_set/butcher/level_1"); + let (x, y, z) = (a.next_long(), b.next_long(), c.next_long()); + assert_eq!(x, y); + assert_ne!(x, z); + assert_eq!(min_xp(2), 10); + assert_eq!(max_xp(2), 70); + assert!(!can_level_up(5)); + } + + #[test] + fn offers_follow_the_trade_data() { + let items = items(); + let e = crate::enchant::tests::sample(); + let mut trades = HashMap::new(); + trades.insert("minecraft:t/boots".into(), json!({"gives":{"id":"minecraft:iron_boots"},"max_uses":12,"reputation_discount":0.2,"wants":{"count":4,"id":"minecraft:emerald"}})); + trades.insert("minecraft:t/helmet".into(), json!({"gives":{"id":"minecraft:iron_helmet"},"max_uses":12,"reputation_discount":0.2,"wants":{"count":5,"id":"minecraft:emerald"}})); + trades.insert("minecraft:t/desert".into(), json!({"gives":{"id":"minecraft:sand"},"wants":{"id":"minecraft:emerald"},"merchant_predicate":{"entity":"this","predicate":{"minecraft:predicates":{"minecraft:villager/variant":"minecraft:desert"}},"type":"minecraft:entity_properties"}})); + let mut tags = HashMap::new(); + tags.insert("minecraft:t/level_1".into(), vec!["minecraft:t/boots".into(), "minecraft:t/helmet".into(), "minecraft:t/desert".into()]); + let mut sets = HashMap::new(); + sets.insert("minecraft:t/level_1".into(), json!({"amount": 5, "trades": "#minecraft:t/level_1"})); + let t = Trades { trades, tags, sets }; + let ctx = TradeContext { items: &items, enchantments: &e, variant: "minecraft:plains" }; + let offers = t.offers_from_set(&ctx, "minecraft:t/level_1", &mut sequence_random(1, "x")); + // The desert-only trade is skipped for a plains villager; no duplicates. + assert_eq!(offers.len(), 2); + assert_ne!(offers[0].result.item, offers[1].result.item); + assert!(offers.iter().all(|o| o.max_uses == 12 && (o.price_multiplier - 0.2).abs() < 1e-6)); + } +} diff --git a/crates/horizon-client/src/stations.rs b/crates/horizon-client/src/stations.rs index d5495722d..f0cca1156 100644 --- a/crates/horizon-client/src/stations.rs +++ b/crates/horizon-client/src/stations.rs @@ -17,10 +17,16 @@ pub struct StationData { pub enchantments: Enchantments, pub recipes: StationRecipes, pub brewing: crate::brewing::Brewing, + pub trades: crate::merchant::Trades, } 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) } + Self { + enchantments: Enchantments::load(root), + recipes: StationRecipes::load(root, items), + brewing: crate::brewing::Brewing::load(root, items), + trades: crate::merchant::Trades::load(root), + } } } From 1861320d75ca136607ccb6c8d6a41626422a7f23 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:41:41 +0200 Subject: [PATCH 6/9] Tidy clippy findings in the station modules Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/brewing.rs | 5 ++++- crates/horizon-client/src/enchant.rs | 4 +++- crates/horizon-client/src/game/potions.rs | 4 ++-- crates/horizon-client/src/game/stations.rs | 11 +++++------ crates/horizon-client/src/merchant.rs | 8 ++++---- crates/horizon-client/src/stations.rs | 2 +- 6 files changed, 19 insertions(+), 15 deletions(-) diff --git a/crates/horizon-client/src/brewing.rs b/crates/horizon-client/src/brewing.rs index 8c809be11..13bdb826b 100644 --- a/crates/horizon-client/src/brewing.rs +++ b/crates/horizon-client/src/brewing.rs @@ -152,7 +152,10 @@ pub fn potion_color(id: Option<&str>) -> u32 { b += w * (e.color & 255); total += w; } - if total == 0 { BASE_POTION_COLOR } else { (r / total) << 16 | (g / total) << 8 | b / total } + match (r.checked_div(total), g.checked_div(total), b.checked_div(total)) { + (Some(r), Some(g), Some(b)) => (r << 16) | (g << 8) | b, + _ => BASE_POTION_COLOR, + } } /// `MobEffectUtil.formatDuration` at 20 TPS: m:ss or h:mm:ss. pub fn format_duration(ticks: i32) -> String { diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-client/src/enchant.rs index 3fbe56fd6..e10a5ab4d 100644 --- a/crates/horizon-client/src/enchant.rs +++ b/crates/horizon-client/src/enchant.rs @@ -523,7 +523,9 @@ pub fn apply_value_effect(effect: &Value, level: u32, random: &mut LegacyRandom, "minecraft:remove_binomial" => { let p = level_value(&effect["chance"], level); let n = value; - let removed = if !(n <= 128.0) && !(n * p < 20.0) && !(n * (1.0 - p) < 20.0) { + // Normal approximation for large counts (written as vanilla's negated tests). + let large = n > 128.0 && n * p >= 20.0 && n * (1.0 - p) >= 20.0; + let removed = if large { let miu = (f64::from(n) * f64::from(p)).floor(); let sigma = (f64::from(n) * f64::from(p) * f64::from(1.0 - p)).sqrt(); ((miu + random.next_gaussian() * sigma).round() as i32).clamp(0, n as i32) diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index cd7297be5..c19c89870 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -103,7 +103,7 @@ impl Game<'_> { let remaining = 32u32.saturating_sub(ticks); let eye = self.eye_position().unwrap_or_default(); // Consumable.emitParticlesAndSounds: the drink sound every 4 ticks near the end. - if remaining <= 25 && remaining % 4 == 0 { + if remaining <= 25 && remaining.is_multiple_of(4) { let pitch = self.world.random.next_float() * 0.1 + 0.9; self.audio.play("minecraft:entity.generic.drink", Some(eye), 0.5, pitch); } @@ -269,7 +269,7 @@ impl Game<'_> { self.apply_effect_action(a); } } else { - let d = (intensity * f64::from(*duration) * f64::from(scale) + 0.5) as i32; + let d = (intensity * f64::from(*duration) * scale + 0.5) as i32; if d > 20 && let Some(e) = brewing::effect(id) { diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index d9c1b507f..e85e4d83c 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -890,15 +890,14 @@ impl Game<'_> { 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 { + let col: i32 = 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; + -12550384 } else { let hover = inside(local, bx, by, bw, bh); let sprite = if hover { "enchantment_slot_highlighted" } else { "enchantment_slot" }; @@ -906,8 +905,8 @@ impl Game<'_> { 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; - } + -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); @@ -942,7 +941,7 @@ impl Game<'_> { 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 { "" }; + let blink = if (self.ticks / 6).is_multiple_of(2) { "_" } else { "" }; batch.text(atlas, &format!("{}{blink}", s.name), ox + 62.0, oy + 24.0, u32::MAX, true); } let cost = s.anvil.cost; diff --git a/crates/horizon-client/src/merchant.rs b/crates/horizon-client/src/merchant.rs index 8c52a1c42..d8fa86a07 100644 --- a/crates/horizon-client/src/merchant.rs +++ b/crates/horizon-client/src/merchant.rs @@ -286,10 +286,10 @@ pub fn offer_from(ctx: &TradeContext<'_>, t: &Value, random: &m result = stack; additional += extra; } - if let Some(Value::String(tag)) = t.get("double_trade_price_enchantments") { - if result.stored_enchantments().iter().any(|(e, _)| ctx.enchantments.in_tag(tag, e)) { - additional *= 2; - } + if let Some(Value::String(tag)) = t.get("double_trade_price_enchantments") + && result.stored_enchantments().iter().any(|(e, _)| ctx.enchantments.in_tag(tag, e)) + { + additional *= 2; } let a = cost(ctx.items, &t["wants"], additional); if a.stack.count < 1 { diff --git a/crates/horizon-client/src/stations.rs b/crates/horizon-client/src/stations.rs index f0cca1156..6a659f605 100644 --- a/crates/horizon-client/src/stations.rs +++ b/crates/horizon-client/src/stations.rs @@ -507,7 +507,7 @@ mod tests { let a = enchant_offers(&e, &items, 1234, 15, Some(&s)); let b = enchant_offers(&e, &items, 1234, 15, Some(&s)); assert_eq!(a, b); - assert!(a.costs[2] >= 30 && a.costs[2] <= 30, "{a:?}"); + assert_eq!(a.costs[2], 30, "{a:?}"); assert!(a.costs[0] >= 1 && a.costs[0] <= a.costs[2]); // The clue is the first offer's random pick from the same list. for slot in 0..3 { From 9a3bf425747da00b20189b8601b82b1226933a2e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:47:03 +0200 Subject: [PATCH 7/9] Add a differential test of enchanting-table offers against vanilla A Java oracle loads the vanilla data pack's enchantment registry, binds item components and replays EnchantmentMenu's cost, clue and enchantment selection draws; tools/test_enchanting_parity.py compares it with the Rust stations module for every enchantable item and the book over 32 seeds and 7 bookshelf counts (51,744 lines match). Co-Authored-By: Claude Opus 5.5 --- .../examples/enchanting_fixture.rs | 35 +++++++ crates/horizon-client/src/items.rs | 4 + .../parity/VanillaEnchantingOracle.java | 92 +++++++++++++++++++ tools/test_enchanting_parity.py | 79 ++++++++++++++++ 4 files changed, 210 insertions(+) create mode 100644 crates/horizon-client/examples/enchanting_fixture.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEnchantingOracle.java create mode 100644 tools/test_enchanting_parity.py diff --git a/crates/horizon-client/examples/enchanting_fixture.rs b/crates/horizon-client/examples/enchanting_fixture.rs new file mode 100644 index 000000000..cd82cad48 --- /dev/null +++ b/crates/horizon-client/examples/enchanting_fixture.rs @@ -0,0 +1,35 @@ +//! Enchanting-table offers for differential tests against vanilla +//! (tools/test_enchanting_parity.py): reads "seed bookcases item" lines and +//! prints costs, clues and applied enchantments in the oracle's format. +//! +//! usage: enchanting_fixture RESOURCES INPUT OUTPUT +use horizon_client::{enchant::Enchantments, items::{ItemStack, Items}, stations}; +use std::{fmt::Write as _, fs, path::Path}; + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let root = Path::new(args.get(1).ok_or("usage: enchanting_fixture RESOURCES INPUT OUTPUT")?); + let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; + let items = Items::tags_only(root)?; + let e = Enchantments::load(root); + let mut out = String::new(); + for line in input.lines() { + let f: Vec<&str> = line.split(' ').collect(); + let (seed, bookcases, item): (i32, i32, &str) = (f[0].parse()?, f[1].parse()?, f[2]); + let stack = ItemStack::new(item, 1); + let offers = stations::enchant_offers(&e, &items, seed, bookcases, Some(&stack)); + for i in 0..3 { + let cost = offers.costs[i]; + let clue = offers.clues[i].as_ref().map_or("-".to_owned(), |(id, l)| format!("{id}:{l}")); + let applied = if cost > 0 { + let list = stations::enchantment_list(&e, &items, seed, i, cost, item); + if list.is_empty() { "-".to_owned() } else { list.iter().map(|(id, l)| format!("{id}:{l}")).collect::>().join(",") } + } else { + "-".to_owned() + }; + writeln!(out, "{line} {i} {cost} {clue} {applied}")?; + } + } + fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 10284d4c3..abbf4c5b6 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -211,6 +211,10 @@ impl Items { pub fn get(&self, id: &str) -> Option<&ItemInfo> { self.items.get(id) } + /// Only the block and item tags, for tools that need tag membership. + pub fn tags_only(root: &Path) -> Result { + Ok(Self { items: HashMap::new(), order: Vec::new(), block_tags: load_tags(root, "block")?, item_tags: load_tags(root, "item")?, loot: HashMap::new() }) + } /// An item table with only tags, for unit tests of item rules. #[cfg(test)] pub fn for_tests(item_tags: HashMap>) -> Self { diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEnchantingOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEnchantingOracle.java new file mode 100644 index 000000000..7bd1b8db3 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEnchantingOracle.java @@ -0,0 +1,92 @@ +package dev.horizonlab.parity; + +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.SharedConstants; +import net.minecraft.core.*; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.RegistryDataLoader; +import net.minecraft.server.Bootstrap; +import net.minecraft.server.RegistryLayer; +import net.minecraft.server.packs.PackType; +import net.minecraft.server.packs.repository.ServerPacksSource; +import net.minecraft.server.packs.resources.MultiPackResourceManager; +import net.minecraft.tags.EnchantmentTags; +import net.minecraft.tags.TagLoader; +import net.minecraft.util.RandomSource; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.enchantment.Enchantment; +import net.minecraft.world.item.enchantment.EnchantmentHelper; +import net.minecraft.world.item.enchantment.EnchantmentInstance; + +/** + * Original oracle: loads the vanilla data pack's enchantment registry and + * replays the enchanting table offer computation (EnchantmentMenu.slotsChanged + * and getEnchantmentList) through EnchantmentHelper for fixture lines + * "seed bookcases item", printing costs, clues and the enchantments applied. + */ +public final class VanillaEnchantingOracle { + private static String name(EnchantmentInstance e) { + return e.enchantment().unwrapKey().get().identifier() + ":" + e.level(); + } + + private static List list(RandomSource random, int seed, int slot, int cost, ItemStack stack, HolderSet.Named table) { + random.setSeed(seed + slot); + List list = EnchantmentHelper.selectEnchantment(random, stack, cost, table.stream()); + if (stack.is(Items.BOOK) && list.size() > 1) { + list.remove(random.nextInt(list.size())); + } + return list; + } + + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + Path in = Path.of(args[0]), out = Path.of(args[1]); + var repo = ServerPacksSource.createVanillaTrustedRepository(); + repo.reload(); + repo.setSelected(List.of("vanilla")); + var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected()); + var layers = RegistryLayer.createRegistryAccess(); + var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC)); + var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags); + RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join(); + staticTags.forEach(Registry.PendingTags::apply); + RegistryAccess access = layers.replaceFrom(RegistryLayer.WORLD, world).compositeAccess(); + // Bind default item components (enchantable values) as server reloads do. + BuiltInRegistries.DATA_COMPONENT_INITIALIZERS.build(access).forEach(p -> p.apply()); + var table = world.lookupOrThrow(Registries.ENCHANTMENT).get(EnchantmentTags.IN_ENCHANTING_TABLE).orElseThrow(); + RandomSource random = RandomSource.create(0L); + try (var w = new PrintWriter(Files.newBufferedWriter(out, StandardCharsets.UTF_8))) { + for (String line : Files.readAllLines(in, StandardCharsets.UTF_8)) { + String[] f = line.split(" "); + int seed = Integer.parseInt(f[0]), bookcases = Integer.parseInt(f[1]); + ItemStack stack = new ItemStack(BuiltInRegistries.ITEM.getValue(Identifier.parse(f[2]))); + int[] costs = new int[3]; + random.setSeed(seed); + for (int i = 0; i < 3; i++) { + costs[i] = EnchantmentHelper.getEnchantmentCost(random, i, bookcases, stack); + if (costs[i] < i + 1) costs[i] = 0; + } + for (int i = 0; i < 3; i++) { + String clue = "-"; + String applied = "-"; + if (costs[i] > 0) { + List l = list(random, seed, i, costs[i], stack, table); + if (!l.isEmpty()) clue = name(l.get(random.nextInt(l.size()))); + List again = list(RandomSource.create(0L), seed, i, costs[i], stack, table); + StringBuilder sb = new StringBuilder(); + for (var e : again) sb.append(sb.length() == 0 ? "" : ",").append(name(e)); + if (sb.length() > 0) applied = sb.toString(); + } + w.println(line + " " + i + " " + costs[i] + " " + clue + " " + applied); + } + } + } + } +} diff --git a/tools/test_enchanting_parity.py b/tools/test_enchanting_parity.py new file mode 100644 index 000000000..4cfda596a --- /dev/null +++ b/tools/test_enchanting_parity.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +"""Compare enchanting-table offers (costs, clues, applied enchantments) with vanilla. + +Java loads the vanilla data pack's enchantment registry and runs +EnchantmentHelper as EnchantmentMenu does; Rust runs horizon_client::stations +on the prepared resources. Every enchantable item and the book are tested +across seeds and bookshelf counts. +""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + + +def corpus(items): + rng = random.Random(0x454E4348414E54) + seeds = [-2147483648, -1, 0, 1, 2147483647, *[rng.randrange(-2**31, 2**31) for _ in range(27)]] + for item in items: + for seed in seeds: + for bookcases in [0, 1, 4, 8, 12, 15, 30]: + yield f"{seed} {bookcases} {item}" + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--prepare', action='store_true') + args = parser.parse_args() + build = lab.LOCAL / 'agents/stations/enchanting-parity' + build.mkdir(parents=True, exist_ok=True) + if args.prepare: + lab.prepare() + lock, jars, libraries = base.verify_artifacts() + resources = lab.LOCAL / 'horizon-client/26.3' + catalog = json.loads((resources / 'items.json').read_text()) + items = sorted(k for k, v in catalog.items() if 'minecraft:enchantable' in v) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEnchantingOracle.java' + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/enchanting_fixture.rs', + *sorted((lab.ROOT / 'crates/horizon-client/src').glob('*.rs'))] + tested = base.source_hashes(sources) + inputs = build / 'inputs.txt' + fixtures = list(corpus(items)) + inputs.write_text(''.join(line + '\n' for line in fixtures), encoding='utf-8') + classes = build / 'classes' + classes.mkdir(exist_ok=True) + deps = os.pathsep.join(map(str, libraries)) + + def run(command, name): + with (build / (name + '.log')).open('w', encoding='utf-8') as log: + base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT) + run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'enchanting_fixture'], 'compile-rust') + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release/examples' / ('enchanting_fixture.exe' if os.name == 'nt' else 'enchanting_fixture') + run([binary, resources, inputs, build / 'rust.txt'], 'rust') + references = [] + for side in ['server']: + run(['java', '-Xmx1G', '-cp', os.pathsep.join([str(classes), str(jars[side]), deps]), 'dev.horizonlab.parity.VanillaEnchantingOracle', inputs, build / f'{side}.txt'], side) + matched = base.compare(build / f'{side}.txt', build / 'rust.txt') + references.append({'side': side, 'jar_sha256': lab.digest(jars[side], 'sha256'), 'matched_output_lines': matched}) + print(f'{side}: {matched:,} enchanting offer lines match Rust', flush=True) + base.ensure_sources_unchanged(sources, tested) + report = {'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'fixtures': len(fixtures), + 'items': len(items), 'references': references, 'sources_sha256': tested, + 'scope': 'EnchantmentHelper.getEnchantmentCost / selectEnchantment on the data-driven enchantment registry and ' + '#in_enchanting_table, EnchantmentMenu clue draws and book removal, for every enchantable item and the book.'} + lab.write_json(build / 'report.json', report) + print(f'Enchanting parity passed: {build / "report.json"}') + + +if __name__ == '__main__': + main() From 481f427e3ab3936f5dd55cd543a06aec2e97b326 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:51:16 +0200 Subject: [PATCH 8/9] Save status effects, show thrown potions, test loot enchantments and vanilla data Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 2 + crates/horizon-client/src/game/potions.rs | 27 ++++++++++++- crates/horizon-client/src/items.rs | 47 +++++++++++++++++++++++ crates/horizon-client/src/save.rs | 30 +++++++++++++++ crates/horizon-client/src/stations.rs | 40 +++++++++++++++++++ 5 files changed, 145 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 17e4ffd73..698146896 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2981,6 +2981,7 @@ impl Game<'_> { self.particles.clear(); self.orbs.clear(); self.experience = Experience { level: self.level.xp_level, progress: self.level.xp_progress, total: self.level.xp_total }; + self.restore_effects(); self.mining = None; self.container = None; self.carried = None; @@ -4175,6 +4176,7 @@ impl Game<'_> { } } level.dimension = self.dim.id().to_owned(); + level.active_effects = self.potions.effects.list.iter().map(|e| (format!("minecraft:{}", e.id), e.duration, e.amplifier, e.ambient, e.visible)).collect(); level.write(&self.world_root)?; self.message = Some(("Saved the game".into(), Instant::now())); Ok(()) diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index c19c89870..34d3a3699 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -167,7 +167,9 @@ impl Game<'_> { } /// `LivingEntity.tickEffects`, attribute modifiers and the status flags. pub(super) fn tick_effects(&mut self) { - if self.player.as_ref().is_none_or(|p| p.health.dead_or_dying()) { + let Some(player) = self.player.as_ref() else { return }; + if player.health.dead_or_dying() { + // LivingEntity.die → removeAllEffects. self.potions.effects.clear(); } for action in self.potions.effects.tick() { @@ -237,6 +239,18 @@ impl Game<'_> { t.velocity = Vec3::new(t.velocity.x * 0.99, t.velocity.y * 0.99 - 0.05, 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 mut fixed = horizon_core::random::LegacyRandom::new(0); + let mut p = horizon_client::particles::Particle::terrain(&mut fixed, [t.position.x, t.position.y, t.position.z], [0.0; 3], sprite.into(), 0xFFFFFF); + p.velocity = [0.0; 3]; + p.gravity = 0.0; + p.lifetime = 2; + p.size = 0.25; + p.uv = [0.0, 0.0, 1.0, 1.0]; + self.particles.push(p); + } self.potions.thrown = thrown; for (stack, at) in landed { self.splash(&stack, at); @@ -341,6 +355,17 @@ impl Game<'_> { batch.sprite_scaled(atlas, &format!("mob_effect/{}", e.id), x + 3.0, y + 3.0, 18.0, 18.0, rgba(255, 255, 255, (alpha * 255.0) as u8)); } } + /// Effects saved in level.dat (`Player.active_effects`). + pub(super) fn restore_effects(&mut self) { + self.potions = PotionState::default(); + for (id, duration, amplifier, ambient, _) in self.level.active_effects.clone() { + if let Some(def) = brewing::effect(&id) { + let mut e = EffectInstance::new(def.id, duration, amplifier); + e.ambient = ambient; + self.potions.effects.add(e); + } + } + } pub(super) fn effects_json(&self) -> serde_json::Value { serde_json::Value::Array(self.potions.effects.list.iter().map(|e| serde_json::json!({ "id": e.id, "duration": e.duration, "amplifier": e.amplifier })).collect()) } diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index abbf4c5b6..e5b448113 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -604,3 +604,50 @@ impl LootContext<'_> { } } } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn ctx<'a>(items: &'a Items, held: Option<&'a ItemStack>, props: &'a BTreeMap, block: &'a str) -> LootContext<'a> { + LootContext { items, block, properties: props, held, killed_by_player: block.is_empty() } + } + + #[test] + fn fortune_silk_touch_and_looting() { + let items = Items::for_tests(HashMap::new()); + let props = BTreeMap::new(); + let mut pick = ItemStack::new("minecraft:diamond_pickaxe", 1); + pick.enchant("minecraft:fortune", 3); + let ore = json!({"pools":[{"rolls":1,"entries":[{"type":"minecraft:alternatives","children":[ + {"type":"minecraft:item","condition":"minecraft:tool/can_silk_touch","name":"minecraft:diamond_ore"}, + {"type":"minecraft:item","name":"minecraft:diamond","modifier":[{"type":"minecraft:apply_bonus","enchantment":"minecraft:fortune","formula":"minecraft:ore_drops"}]}]}]}]}); + let mut random = LegacyRandom::new(7); + let n = 20000; + let total: u32 = (0..n).map(|_| ctx(&items, Some(&pick), &props, "minecraft:diamond_ore").evaluate(&ore, &mut random).iter().map(|s| s.count).sum::()).sum(); + // Fortune III ore drops average (1 + 1 + 2 + 3 + 4) / 5 = 2.2 diamonds. + let mean = f64::from(total) / f64::from(n); + assert!((mean - 2.2).abs() < 0.05, "{mean}"); + let mut silk = ItemStack::new("minecraft:diamond_pickaxe", 1); + silk.enchant("minecraft:silk_touch", 1); + let drops = ctx(&items, Some(&silk), &props, "minecraft:diamond_ore").evaluate(&ore, &mut random); + assert_eq!(&*drops[0].item, "minecraft:diamond_ore"); + let plain = ItemStack::new("minecraft:diamond_pickaxe", 1); + let drops = ctx(&items, Some(&plain), &props, "minecraft:diamond_ore").evaluate(&ore, &mut random); + assert_eq!((&*drops[0].item, drops[0].count), ("minecraft:diamond", 1)); + // Looting III adds level x uniform(0, 1) on player kills. + let flesh = json!({"pools":[{"rolls":1,"entries":[{"type":"minecraft:item","name":"minecraft:rotten_flesh","modifier":[ + {"type":"minecraft:set_count","count":{"type":"minecraft:uniform","min":0.0,"max":2.0}}, + {"type":"minecraft:enchanted_count_increase","count":{"type":"minecraft:uniform","min":0.0,"max":1.0},"enchantment":"minecraft:looting"}]}]}]}); + let mut sword = ItemStack::new("minecraft:iron_sword", 1); + sword.enchant("minecraft:looting", 3); + let looted: u32 = (0..n).map(|_| ctx(&items, Some(&sword), &props, "").evaluate(&flesh, &mut random).iter().map(|s| s.count).sum::()).sum(); + let base: u32 = (0..n).map(|_| ctx(&items, None, &props, "").evaluate(&flesh, &mut random).iter().map(|s| s.count).sum::()).sum(); + assert!(f64::from(looted) / f64::from(n) > f64::from(base) / f64::from(n) + 1.0); + // Table bonus uses the chance for the tool's level. + let leaves = json!({"pools":[{"rolls":1,"conditions":[{"type":"minecraft:table_bonus","enchantment":"minecraft:fortune","chances":[0.0,0.0,0.0,1.0]}],"entries":[{"type":"minecraft:item","name":"minecraft:apple"}]}]}); + assert_eq!(ctx(&items, Some(&pick), &props, "minecraft:oak_leaves").evaluate(&leaves, &mut random).len(), 1); + assert!(ctx(&items, Some(&plain), &props, "minecraft:oak_leaves").evaluate(&leaves, &mut random).is_empty()); + } +} diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index ccdd5ca82..12a1a6989 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -386,6 +386,8 @@ pub struct Level { pub inventory_components: HashMap>, /// Player.XpSeed: the enchanting table seed. pub xp_seed: i32, + /// Player.active_effects: (id, duration, amplifier, ambient, show_icon). + pub active_effects: Vec<(String, i32, i32, bool, bool)>, pub xp_level: i32, pub xp_progress: f32, pub xp_total: i32, @@ -468,6 +470,16 @@ impl Level { xp_progress: player.map_or(0.0, |p| float(p.get("XpP"))), xp_total: player.map_or(0, |p| long(p.get("XpTotal")) as i32), xp_seed: player.map_or(0, |p| long(p.get("XpSeed")) as i32), + active_effects: match player.and_then(|p| p.get("active_effects")) { + Some(Tag::List(list)) => list + .iter() + .filter_map(|e| { + let Some(Tag::String(id)) = e.get("id") else { return None }; + Some((id.to_string_lossy(), long(e.get("duration")) as i32, long(e.get("amplifier")) as i32, long(e.get("ambient")) != 0, e.get("show_icon").is_none_or(|v| long(Some(v)) != 0))) + }) + .collect(), + _ => Vec::new(), + }, inventory, inventory_components, }) @@ -483,6 +495,24 @@ impl Level { ("XpP", Tag::Float(self.xp_progress.to_bits())), ("XpTotal", Tag::Int(self.xp_total)), ("XpSeed", Tag::Int(self.xp_seed)), + ( + "active_effects", + Tag::List( + self.active_effects + .iter() + .map(|(id, duration, amplifier, ambient, icon)| { + Tag::compound([ + ("id", string(id)), + ("duration", Tag::Int(*duration)), + ("amplifier", Tag::Byte(*amplifier as i8)), + ("ambient", Tag::Byte(i8::from(*ambient))), + ("show_particles", Tag::Byte(1)), + ("show_icon", Tag::Byte(i8::from(*icon))), + ]) + }) + .collect(), + ), + ), ("playerGameType", Tag::Int(i32::from(self.creative))), ( "Rotation", diff --git a/crates/horizon-client/src/stations.rs b/crates/horizon-client/src/stations.rs index 6a659f605..393e796e4 100644 --- a/crates/horizon-client/src/stations.rs +++ b/crates/horizon-client/src/stations.rs @@ -570,6 +570,46 @@ mod tests { assert_eq!(increased_repair_cost(3), 7); } + /// Checks against the prepared vanilla resources when they are present. + #[test] + fn prepared_vanilla_data() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); + if !root.join("items.json").exists() { + return; + } + let items = Items::tags_only(&root).unwrap(); + let data = StationData::load(&root, &items); + let e = &data.enchantments; + assert_eq!(e.list.len(), 43); + assert_eq!(&*e.tag("minecraft:in_enchanting_table")[0], "minecraft:protection"); + assert!(!e.compatible("minecraft:fortune", "minecraft:silk_touch")); + assert!(e.is_curse("minecraft:binding_curse")); + assert_eq!(e.full_name("minecraft:sharpness", 5).0, "Sharpness V"); + assert_eq!(e.enchantable("minecraft:golden_sword"), 22); + // Brewing: water + nether wart = awkward. + assert_eq!(data.brewing.recipes.len(), 279); + let water = ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water"); + let r = data.brewing.find(&water, &ItemStack::new("minecraft:nether_wart", 1)).unwrap(); + assert_eq!(r.output.potion(), Some("minecraft:awkward")); + assert!(data.brewing.is_reagent(&ItemStack::new("minecraft:blaze_powder", 1))); + // Smithing: netherite upgrade keeps enchantments. + let mut sword = ItemStack::new("minecraft:diamond_sword", 1); + sword.enchant("minecraft:sharpness", 2); + let out = data + .recipes + .smithing_result(e, Some(&ItemStack::new("minecraft:netherite_upgrade_smithing_template", 1)), Some(&sword), Some(&ItemStack::new("minecraft:netherite_ingot", 1))) + .unwrap(); + assert_eq!((&*out.item, out.enchantment_level("minecraft:sharpness")), ("minecraft:netherite_sword", 2)); + assert!(data.recipes.stonecutter(&ItemStack::new("minecraft:stone", 1)).len() >= 10); + // Trades: every profession level set yields offers. + let ctx = crate::merchant::TradeContext { items: &items, enchantments: e, variant: "minecraft:plains" }; + for p in crate::merchant::PROFESSIONS { + let set = crate::merchant::Trades::set_for(p, 1); + let mut random = crate::merchant::sequence_random(12345, &format!("minecraft:trade_set/{}", set.trim_start_matches("minecraft:"))); + assert!(!data.trades.offers_from_set(&ctx, &set, &mut random).is_empty(), "{p}"); + } + } + #[test] fn grindstone_strips_non_curses() { let e = sample(); From 9e3f4276fe50be0c3fe4962f8031bb3324fbc2df Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:53:14 +0200 Subject: [PATCH 9/9] Throw potions with vanilla's shootFromRotation spread Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/potions.rs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 34d3a3699..a75409681 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -51,11 +51,13 @@ impl Game<'_> { let sound = if &*stack.item == "minecraft:splash_potion" { "minecraft:entity.splash_potion.throw" } else { "minecraft:entity.lingering_potion.throw" }; self.audio.play(sound, Some(eye), 0.5, pitch); // Projectile.shootFromRotation(xRot, yRot, -20, 0.5, 1.0). - let (yaw, pitch) = (self.yaw.to_radians(), (self.pitch - 20.0).to_radians()); - let dir = [-yaw.sin() * pitch.cos(), -pitch.sin(), yaw.cos() * pitch.cos()]; + let (yaw, pitch) = (self.yaw.to_radians(), self.pitch.to_radians()); + let dir = [-yaw.sin() * pitch.cos(), -(self.pitch - 20.0).to_radians().sin(), yaw.cos() * pitch.cos()]; + let l = dir.iter().map(|c| f64::from(*c).powi(2)).sum::().sqrt().max(1e-9); + // getMovementToShoot: normalize, add triangle(0, 0.0172275 * uncertainty), scale. let r = &mut self.world.random; - let mut jitter = || f64::from(r.next_float() + r.next_float() - 1.0) * 0.0075; - let v = Vec3::new((f64::from(dir[0]) + jitter()) * 0.5, (f64::from(dir[1]) + jitter()) * 0.5, (f64::from(dir[2]) + jitter()) * 0.5); + 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); 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); let v = Vec3::new(v.x + pv.x, v.y + if on_ground { 0.0 } else { pv.y }, v.z + pv.z); @@ -367,6 +369,9 @@ impl Game<'_> { } } pub(super) fn effects_json(&self) -> serde_json::Value { - serde_json::Value::Array(self.potions.effects.list.iter().map(|e| serde_json::json!({ "id": e.id, "duration": e.duration, "amplifier": e.amplifier })).collect()) + serde_json::json!({ + "active": self.potions.effects.list.iter().map(|e| serde_json::json!({ "id": e.id, "duration": e.duration, "amplifier": e.amplifier })).collect::>(), + "thrown": self.potions.thrown.iter().map(|t| [t.position.x, t.position.y, t.position.z]).collect::>(), + }) } }