Merge remote-tracking branch 'origin/wip/parity-stations' into t3/minecraft-parity
# Conflicts: # crates/horizon-client/src/game.rs # crates/horizon-client/src/save.rs
This commit is contained in:
@@ -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<String> = 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::<Vec<_>>().join(",") }
|
||||
} else {
|
||||
"-".to_owned()
|
||||
};
|
||||
writeln!(out, "{line} {i} {cost} {clue} {applied}")?;
|
||||
}
|
||||
}
|
||||
fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
//! 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.<name>`) 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;
|
||||
}
|
||||
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 {
|
||||
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.<name>` 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<String>) -> 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<String>,
|
||||
pub potions: Option<HashSet<String>>,
|
||||
}
|
||||
impl PotionIngredient {
|
||||
fn parse(v: &Value, items: &Items) -> Self {
|
||||
let mut set = HashSet::new();
|
||||
let add = |s: &str, set: &mut HashSet<String>| 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<BrewingRecipe>,
|
||||
/// `RecipePropertySet.BREWING_REAGENTS`.
|
||||
pub reagents: HashSet<String>,
|
||||
/// Items accepted in the bottle slots (`PotionIngredient.isPotionInput`).
|
||||
pub inputs: HashSet<String>,
|
||||
}
|
||||
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::<Value>(&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<ItemStack>; 5],
|
||||
pub brew_time: i32,
|
||||
pub total_brew_time: i32,
|
||||
pub fuel: i32,
|
||||
pub total_fuel: i32,
|
||||
pub speed: f32,
|
||||
pub ingredient: Option<Arc<str>>,
|
||||
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<ItemStack>,
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,7 @@ pub struct Furnace {
|
||||
pub enum BlockEntity {
|
||||
Chest(Vec<Option<ItemStack>>),
|
||||
Furnace(Furnace),
|
||||
Brewing(Box<crate::brewing::BrewingStand>),
|
||||
}
|
||||
impl BlockEntity {
|
||||
pub fn for_block(name: &str) -> Option<Self> {
|
||||
@@ -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<ItemStack>] {
|
||||
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)
|
||||
@@ -208,7 +227,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;
|
||||
|
||||
@@ -68,6 +68,7 @@ fn result(v: &Value) -> Option<ItemStack> {
|
||||
item: Arc::from(v["id"].as_str()?),
|
||||
count: v["count"].as_u64().unwrap_or(1) as u32,
|
||||
damage: 0,
|
||||
extra: None,
|
||||
})
|
||||
}
|
||||
impl Recipes {
|
||||
|
||||
@@ -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<Box<EffectInstance>>,
|
||||
}
|
||||
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<EffectAction> {
|
||||
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<EffectAction> {
|
||||
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<EffectInstance>,
|
||||
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<i32> {
|
||||
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<EffectAction> {
|
||||
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<EffectInstance>, Vec<EffectAction>) {
|
||||
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<i32>,
|
||||
pub slow_falling: bool,
|
||||
pub levitation: Option<i32>,
|
||||
pub resistance: Option<i32>,
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,702 @@
|
||||
//! 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<str>,
|
||||
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<String>,
|
||||
pub primary: Option<Vec<String>>,
|
||||
pub exclusive: HashSet<Arc<str>>,
|
||||
pub slots: Vec<String>,
|
||||
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<String>,
|
||||
pub glint: bool,
|
||||
pub rarity: String,
|
||||
/// `minecraft:provides_trim_material`.
|
||||
pub trim_material: Option<String>,
|
||||
/// `minecraft:brewing_fuel` present.
|
||||
pub brewing_fuel: bool,
|
||||
}
|
||||
pub struct Enchantments {
|
||||
pub list: Vec<Enchantment>,
|
||||
index: HashMap<Arc<str>, usize>,
|
||||
/// Enchantment tags in vanilla `HolderSet` order (nested tags expanded in place).
|
||||
pub tags: HashMap<String, Vec<Arc<str>>>,
|
||||
pub entity_tags: HashMap<String, HashSet<String>>,
|
||||
pub damage_tags: HashMap<String, HashSet<String>>,
|
||||
pub props: HashMap<Arc<str>, ItemProps>,
|
||||
lang: HashMap<String, String>,
|
||||
}
|
||||
|
||||
fn string_list(v: &Value) -> Vec<String> {
|
||||
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<String, Vec<String>> {
|
||||
fn walk(dir: &Path, base: &Path, out: &mut HashMap<String, Vec<String>>) {
|
||||
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::<Value>(&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<String, Vec<String>>, out: &mut Vec<String>, 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<String, Vec<Arc<str>>> = 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<String, Vec<String>>| -> HashMap<String, HashSet<String>> {
|
||||
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<String, Value> = 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<String, String> = fs::read(root.join("assets/minecraft/lang/en_us.json"))
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice::<HashMap<String, String>>(&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::<BTreeMap<String, Value>>(&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<str>] {
|
||||
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<str>, 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<R: RandomSource>(&self, random: &mut R, 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<str>]) -> Vec<(Arc<str>, 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<R: RandomSource>(&self, random: &mut R, list: &[(Arc<str>, u32)]) -> Option<(Arc<str>, 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<R: RandomSource>(&self, items: &Items, random: &mut R, item: &str, cost: i32, pool: &[Arc<str>]) -> Vec<(Arc<str>, 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<R: RandomSource>(random: &mut R, 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;
|
||||
// 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)
|
||||
} 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<Enchantment> = 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<Arc<str>> = ["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<String, HashSet<String>> = 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<i32> = (0..3).map(|slot| e.enchantment_cost(&mut a, slot, bookcases, "minecraft:diamond_sword")).collect();
|
||||
let bc = bookcases.min(15);
|
||||
let expect: Vec<i32> = (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<String> = 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"));
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,11 @@ mod control;
|
||||
mod end;
|
||||
mod postprocess;
|
||||
mod persist;
|
||||
mod enchant_effects;
|
||||
mod potions;
|
||||
mod station_control;
|
||||
mod stations;
|
||||
mod trading;
|
||||
use horizon_client::{
|
||||
Result,
|
||||
assets::Assets,
|
||||
@@ -291,6 +296,8 @@ pub struct Resources {
|
||||
player_arm: Option<horizon_client::mobs::Part>,
|
||||
/// firstperson_righthand display transforms per item: (rotation, translation, scale).
|
||||
displays: HashMap<String, Option<([f32; 3], [f32; 3], [f32; 3])>>,
|
||||
/// Enchantments, workstation recipes and brewing (game/stations.rs).
|
||||
stations: horizon_client::stations::StationData,
|
||||
}
|
||||
struct Game<'a> {
|
||||
res: &'a mut Resources,
|
||||
@@ -314,6 +321,10 @@ 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<stations::Station>,
|
||||
/// Status effects and thrown potions (game/potions.rs).
|
||||
potions: potions::PotionState,
|
||||
scratch_slot: Option<ItemStack>,
|
||||
mining: Option<Mining>,
|
||||
destroy_delay: u32,
|
||||
@@ -503,8 +514,7 @@ impl Game<'_> {
|
||||
let order: Vec<usize> = 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);
|
||||
@@ -813,11 +823,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;
|
||||
@@ -849,6 +859,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;
|
||||
@@ -882,7 +894,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 });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -905,7 +917,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);
|
||||
@@ -918,14 +930,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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -986,6 +999,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));
|
||||
@@ -1077,6 +1093,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;
|
||||
@@ -1148,13 +1167,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 {
|
||||
@@ -1399,6 +1419,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();
|
||||
@@ -1423,6 +1445,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));
|
||||
@@ -1567,6 +1590,8 @@ 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();
|
||||
let w = HudBatch::text_width(atlas, &text);
|
||||
@@ -1618,6 +1643,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
|
||||
@@ -1757,10 +1783,14 @@ impl Game<'_> {
|
||||
}
|
||||
/// 300.. are the open container's slots.
|
||||
fn slots(&self) -> Vec<usize> {
|
||||
if let Some(v) = self.station_slots() {
|
||||
return v;
|
||||
}
|
||||
let mut v: Vec<usize> = (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);
|
||||
@@ -1773,6 +1803,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 };
|
||||
@@ -1804,6 +1837,9 @@ impl Game<'_> {
|
||||
})
|
||||
}
|
||||
fn slot_mut(&mut self, i: usize) -> &mut Option<ItemStack> {
|
||||
if i >= stations::INPUT {
|
||||
return self.station_slot_mut(i);
|
||||
}
|
||||
if (500..504).contains(&i) {
|
||||
return &mut self.armor[i - 500];
|
||||
}
|
||||
@@ -1826,6 +1862,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;
|
||||
@@ -1872,6 +1911,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);
|
||||
@@ -1901,8 +1941,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<ItemStack> = self.carried.take().into_iter().collect();
|
||||
returned.extend(self.craft_grid.iter_mut().filter_map(Option::take));
|
||||
for stack in returned {
|
||||
@@ -1923,6 +1965,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 };
|
||||
@@ -1988,8 +2033,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;
|
||||
@@ -2035,7 +2079,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;
|
||||
@@ -2458,7 +2502,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);
|
||||
@@ -2469,6 +2513,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
|
||||
@@ -2489,13 +2536,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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2690,6 +2740,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) => {
|
||||
@@ -2933,7 +2984,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)) {
|
||||
@@ -2942,7 +2993,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]));
|
||||
@@ -2969,6 +3020,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;
|
||||
@@ -3291,12 +3343,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<u32> = (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
|
||||
@@ -3360,6 +3414,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
|
||||
@@ -3392,7 +3450,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)
|
||||
@@ -3418,7 +3476,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);
|
||||
}
|
||||
@@ -3432,7 +3490,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);
|
||||
@@ -3558,6 +3616,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;
|
||||
@@ -3588,10 +3649,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()
|
||||
{
|
||||
@@ -4003,7 +4066,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;
|
||||
@@ -4019,7 +4082,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));
|
||||
@@ -4093,7 +4156,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 {
|
||||
@@ -4146,13 +4209,18 @@ 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();
|
||||
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(())
|
||||
@@ -4350,7 +4418,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 });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4474,6 +4542,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;
|
||||
}
|
||||
@@ -4569,6 +4640,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()
|
||||
@@ -4733,7 +4812,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,
|
||||
@@ -4788,6 +4869,8 @@ pub fn run() -> Result<()> {
|
||||
craft_grid: vec![None; 9],
|
||||
craft_size: 2,
|
||||
container: None,
|
||||
station: None,
|
||||
potions: Default::default(),
|
||||
scratch_slot: None,
|
||||
mining: None,
|
||||
destroy_delay: 0,
|
||||
|
||||
@@ -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::<Vec<_>>() }))),
|
||||
"status" => Ok(Some(self.control_status())),
|
||||
"key" => {
|
||||
let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?;
|
||||
@@ -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;
|
||||
@@ -252,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()),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
//! 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<ThrownPotion>,
|
||||
applied: Vec<(&'static str, &'static str, f64, &'static str)>,
|
||||
/// Armor the protection table was computed for.
|
||||
protection_for: Option<Vec<Option<ItemStack>>>,
|
||||
/// 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)>,
|
||||
/// The level's trade-set `RandomSequence`s, by sequence id.
|
||||
pub(super) trade_randoms: std::collections::HashMap<String, horizon_core::random::XoroshiroRandom>,
|
||||
}
|
||||
|
||||
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<bool> {
|
||||
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.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::<f64>().sqrt().max(1e-9);
|
||||
// getMovementToShoot: normalize, add triangle(0, 0.0172275 * uncertainty), scale.
|
||||
let r = &mut self.world.random;
|
||||
let mut jitter = || r.triangle(0.0, 0.0172275);
|
||||
let v = Vec3::new((f64::from(dir[0]) / l + jitter()) * 0.5, (f64::from(dir[1]) / l + jitter()) * 0.5, (f64::from(dir[2]) / l + jitter()) * 0.5);
|
||||
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.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);
|
||||
}
|
||||
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) {
|
||||
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() {
|
||||
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<Option<ItemStack>> = 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
|
||||
});
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
/// `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) * 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));
|
||||
}
|
||||
}
|
||||
/// 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::json!({
|
||||
"active": self.potions.effects.list.iter().map(|e| serde_json::json!({ "id": e.id, "duration": e.duration, "amplifier": e.amplifier })).collect::<Vec<_>>(),
|
||||
"thrown": self.potions.thrown.iter().map(|t| [t.position.x, t.position.y, t.position.z]).collect::<Vec<_>>(),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
//! 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",
|
||||
"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 {
|
||||
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::<Vec<_>>(),
|
||||
"stored_enchantments": s.stored_enchantments().iter().map(|(e, l)| json!([&**e, l])).collect::<Vec<_>>(),
|
||||
"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);
|
||||
}
|
||||
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")?;
|
||||
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<Option<Value>> {
|
||||
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<Value> = 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,
|
||||
})))
|
||||
}
|
||||
"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()
|
||||
}
|
||||
"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();
|
||||
self.screen = Screen::Playing;
|
||||
self.capture(true);
|
||||
ok()
|
||||
}
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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<MerchantOffer>,
|
||||
/// `shopItem` / selection hint, scroll offset, and the active offer.
|
||||
pub(super) shop_item: usize,
|
||||
pub(super) scroll: usize,
|
||||
pub(super) active: Option<usize>,
|
||||
pub(super) future_xp: i32,
|
||||
/// The offer button that keeps focus after a click (drawn highlighted).
|
||||
pub(super) focused: Option<usize>,
|
||||
}
|
||||
/// 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<MerchantOffer> {
|
||||
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<ItemStack> = 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<ItemStack> = 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<ItemStack> = 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<ItemStack> = 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<usize> = (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
|
||||
}
|
||||
}
|
||||
@@ -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<Attributes> for Environment<'_> {
|
||||
Ok(())
|
||||
} // empty equipment
|
||||
fn has_resistance(&mut self) -> io::Result<bool> {
|
||||
Ok(false)
|
||||
Ok(self.status.resistance.is_some())
|
||||
}
|
||||
fn resistance_amplifier(&mut self) -> io::Result<i32> {
|
||||
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<Attributes> for Environment<'_> {
|
||||
Err(io::Error::other("no damage attacker"))
|
||||
}
|
||||
fn damage_protection(&mut self, _: ()) -> io::Result<f32> {
|
||||
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<bool> {
|
||||
Ok(false)
|
||||
Ok(self.status.fire_resistance)
|
||||
}
|
||||
fn sleeping(&mut self, _: &mut State) -> io::Result<bool> {
|
||||
Ok(false)
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -16,6 +16,12 @@ struct Out {
|
||||
return out;
|
||||
}
|
||||
@fragment fn fs_main(in: Out) -> @location(0) vec4<f32> {
|
||||
// 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;
|
||||
|
||||
@@ -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)?;
|
||||
|
||||
@@ -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<str>, 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<String>,
|
||||
/// `minecraft:potion_contents.potion`.
|
||||
pub potion: Option<Arc<str>>,
|
||||
/// `minecraft:trim`: (material, pattern).
|
||||
pub trim: Option<(Arc<str>, Arc<str>)>,
|
||||
}
|
||||
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<str>, u32)] {
|
||||
self.data().map_or(&[], |d| &d.enchantments)
|
||||
}
|
||||
pub fn stored_enchantments(&self) -> &[(Arc<str>, 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<str>, 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<i64> {
|
||||
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<String> {
|
||||
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<String> {
|
||||
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<Tag> {
|
||||
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<Tag> {
|
||||
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<Box<StackData>>) {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -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<String>,
|
||||
/// `equippable.slot` (head, chest, legs, feet, ...).
|
||||
@@ -45,6 +47,8 @@ pub struct ItemStack {
|
||||
pub item: Arc<str>,
|
||||
pub count: u32,
|
||||
pub damage: u32,
|
||||
/// Components beyond count and damage (see `item_data`); None when default.
|
||||
pub extra: Option<Box<crate::item_data::StackData>>,
|
||||
}
|
||||
pub struct Items {
|
||||
pub items: HashMap<Arc<str>, ItemInfo>,
|
||||
@@ -176,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"),
|
||||
@@ -206,6 +211,15 @@ 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<Self> {
|
||||
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<String, HashSet<String>>) -> 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)),
|
||||
@@ -317,6 +331,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,
|
||||
@@ -364,14 +382,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" => {
|
||||
@@ -395,17 +416,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.
|
||||
@@ -438,6 +474,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 +503,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,
|
||||
@@ -515,6 +552,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() {
|
||||
@@ -529,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<String, String>, 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::<u32>()).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::<u32>()).sum();
|
||||
let base: u32 = (0..n).map(|_| ctx(&items, None, &props, "").evaluate(&flesh, &mut random).iter().map(|s| s.count).sum::<u32>()).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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,13 +6,16 @@ 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;
|
||||
pub mod control;
|
||||
pub mod crafting;
|
||||
pub mod enchant;
|
||||
pub mod creative;
|
||||
pub mod collisions;
|
||||
pub mod effects;
|
||||
pub mod entities;
|
||||
pub mod entity_nbt;
|
||||
pub mod environment;
|
||||
@@ -21,9 +24,11 @@ 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;
|
||||
pub mod merchant;
|
||||
pub mod mesher;
|
||||
pub mod mobs;
|
||||
pub mod models;
|
||||
@@ -34,6 +39,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;
|
||||
|
||||
@@ -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<ItemCost>,
|
||||
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<ItemStack> {
|
||||
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<ItemStack>, b: &mut Option<ItemStack>) -> 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<usize>) -> Option<usize> {
|
||||
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<usize>) -> (Option<usize>, Option<ItemStack>) {
|
||||
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<String, Value>,
|
||||
/// villager_trade tags, ordered.
|
||||
pub tags: HashMap<String, Vec<String>>,
|
||||
pub sets: HashMap<String, Value>,
|
||||
}
|
||||
fn walk(dir: &Path, base: &Path, out: &mut HashMap<String, Value>) {
|
||||
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<String, Vec<String>> = 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<String, Vec<String>>, out: &mut Vec<String>, 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<String> {
|
||||
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<R: RandomSource>(&self, ctx: &TradeContext<'_>, set_id: &str, random: &mut R) -> Vec<MerchantOffer> {
|
||||
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<R: RandomSource>(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<R: RandomSource>(ctx: &TradeContext<'_>, t: &Value, random: &mut R) -> Option<MerchantOffer> {
|
||||
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")
|
||||
&& 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<R: RandomSource>(ctx: &TradeContext<'_>, m: &Value, stack: ItemStack, random: &mut R) -> Option<(ItemStack, i32)> {
|
||||
let e = ctx.enchantments;
|
||||
let pool = |options: &Value| -> Vec<Arc<str>> {
|
||||
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<Arc<str>> = 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<u32>) -> 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));
|
||||
}
|
||||
}
|
||||
@@ -152,6 +152,8 @@ pub struct PlayerMotion {
|
||||
pub attributes: LiveAttributes<Box<dyn FnMut() -> 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<Option<i32>> {
|
||||
Ok(None)
|
||||
Ok(self.player.status.levitation)
|
||||
}
|
||||
fn is_client_side(&mut self) -> Result<bool> {
|
||||
Ok(false)
|
||||
@@ -970,10 +973,10 @@ impl LivingMotionWorld for MotionWorld<'_, '_, '_> {
|
||||
)?)
|
||||
}
|
||||
fn has_jump_boost(&mut self) -> Result<bool> {
|
||||
Ok(false)
|
||||
Ok(self.player.status.jump_boost.is_some())
|
||||
}
|
||||
fn jump_boost_amplifier(&mut self) -> Result<i32> {
|
||||
Err("absent jump boost".into())
|
||||
self.player.status.jump_boost.ok_or_else(|| "absent jump boost".into())
|
||||
}
|
||||
fn sprinting(&mut self) -> Result<bool> {
|
||||
Ok(self.player.sprinting)
|
||||
@@ -991,7 +994,7 @@ impl LivingMotionWorld for MotionWorld<'_, '_, '_> {
|
||||
self.player.attribute("minecraft:gravity")
|
||||
}
|
||||
fn has_slow_falling(&mut self) -> Result<bool> {
|
||||
Ok(false)
|
||||
Ok(self.player.status.slow_falling)
|
||||
}
|
||||
fn controlling_passenger_is_player(&mut self) -> Result<bool> {
|
||||
Ok(false)
|
||||
|
||||
@@ -277,6 +277,15 @@ pub fn encode_items(slots: &[Option<crate::items::ItemStack>]) -> Tag {
|
||||
.filter_map(|(i, s)| {
|
||||
let mut entries = vec![("Slot", Tag::Byte(i as i8))];
|
||||
entries.extend(encode_item(s.as_ref()?));
|
||||
let s = s.as_ref()?;
|
||||
let mut entries = vec![
|
||||
("Slot", Tag::Byte(i as i8)),
|
||||
("id", string(&s.item)),
|
||||
("count", Tag::Int(s.count as i32)),
|
||||
];
|
||||
if let Some(components) = crate::item_data::encode_components(s) {
|
||||
entries.push(("components", components));
|
||||
}
|
||||
Some(Tag::compound(entries))
|
||||
})
|
||||
.collect(),
|
||||
@@ -289,6 +298,16 @@ pub fn decode_items(tag: Option<&Tag>, size: usize) -> Vec<Option<crate::items::
|
||||
let slot = number(it.get("Slot")).unwrap_or(0) as u8 as usize;
|
||||
if let Some(cell) = slots.get_mut(slot) {
|
||||
*cell = item_from_nbt(it);
|
||||
let Some(Tag::Byte(slot)) = it.get("Slot") else { continue };
|
||||
let Some(Tag::String(id)) = it.get("id") else { continue };
|
||||
let count = match it.get("count") {
|
||||
Some(Tag::Int(c)) => *c as u32,
|
||||
Some(Tag::Byte(c)) => *c as u32,
|
||||
_ => 1,
|
||||
};
|
||||
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, extra });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -323,6 +342,14 @@ fn encode_block_entity(p: (i32, i32, i32), e: &crate::containers::BlockEntity, b
|
||||
entries.push(("speed_multiplier", Tag::Float(f.speed.to_bits())));
|
||||
entries.push(("RecipesUsed", Tag::Compound(Compound::new())));
|
||||
}
|
||||
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)
|
||||
}
|
||||
@@ -345,6 +372,21 @@ fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers:
|
||||
f.speed = speed as f32;
|
||||
}
|
||||
}
|
||||
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))
|
||||
}
|
||||
@@ -921,6 +963,12 @@ pub struct Level {
|
||||
pub saturation: f32,
|
||||
/// (slot, item, count, damage): 0..36 inventory, 100..103 armor (feet..head), 150 offhand.
|
||||
pub inventory: Vec<(u8, String, u32, u32)>,
|
||||
/// Extra item components of `inventory` entries, by slot.
|
||||
pub inventory_components: HashMap<u8, Box<crate::item_data::StackData>>,
|
||||
/// 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,
|
||||
@@ -1088,6 +1136,71 @@ impl Level {
|
||||
}
|
||||
}
|
||||
self.inventory = inventory;
|
||||
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 };
|
||||
let id = if let Some(Tag::String(s)) = it.get("id") { s.to_string_lossy() } else { continue };
|
||||
let count = long(it.get("count")).max(1) as u32;
|
||||
let damage = it
|
||||
.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));
|
||||
}
|
||||
}
|
||||
let rotation = match player.and_then(|p| p.get("Rotation")) {
|
||||
Some(Tag::List(r)) if r.len() == 2 => [float(r.first()), float(r.get(1))],
|
||||
_ => [0.0; 2],
|
||||
};
|
||||
Some(Self {
|
||||
name: match data.get("LevelName") {
|
||||
Some(Tag::String(s)) => s.to_string_lossy(),
|
||||
_ => "World".into(),
|
||||
},
|
||||
seed: long(data.get("WorldGenSettings").and_then(|w| w.get("seed"))),
|
||||
creative: long(data.get("GameType")) == 1,
|
||||
time: long(data.get("Time")),
|
||||
day_time: long(data.get("DayTime")),
|
||||
spawn: Some([long(data.get("SpawnX")) as f64, long(data.get("SpawnY")) as f64, long(data.get("SpawnZ")) as f64]),
|
||||
position: doubles(player.and_then(|p| p.get("Pos"))),
|
||||
rotation,
|
||||
health: player.map_or(20.0, |p| float(p.get("Health"))),
|
||||
food: player.map_or(20, |p| long(p.get("foodLevel")) as i32),
|
||||
saturation: player.map_or(5.0, |p| float(p.get("foodSaturationLevel"))),
|
||||
dimension: match player.and_then(|p| p.get("Dimension")) {
|
||||
Some(Tag::String(s)) => s.to_string_lossy(),
|
||||
_ => "minecraft:overworld".into(),
|
||||
},
|
||||
weather: crate::world::Weather {
|
||||
clear_time: long(data.get("clearWeatherTime")) as i32,
|
||||
rain_time: long(data.get("rainTime")) as i32,
|
||||
thunder_time: long(data.get("thunderTime")) as i32,
|
||||
raining: long(data.get("raining")) != 0,
|
||||
thundering: long(data.get("thundering")) != 0,
|
||||
rain_level: if long(data.get("raining")) != 0 { (1.0, 1.0) } else { (0.0, 0.0) },
|
||||
thunder_level: if long(data.get("thundering")) != 0 { (1.0, 1.0) } else { (0.0, 0.0) },
|
||||
},
|
||||
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),
|
||||
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,
|
||||
})
|
||||
}
|
||||
/// The player compound: the loaded one with Horizon's state written over it.
|
||||
fn player_tag(&self) -> Tag {
|
||||
@@ -1147,6 +1260,25 @@ impl Level {
|
||||
("XpP", Tag::Float(self.xp_progress.to_bits())),
|
||||
("XpTotal", Tag::Int(self.xp_total)),
|
||||
("SelectedItemSlot", Tag::Int(self.selected_slot)),
|
||||
("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))),
|
||||
("Inventory", Tag::List(inventory)),
|
||||
("abilities", abilities),
|
||||
@@ -1253,6 +1385,23 @@ impl Level {
|
||||
("yaw", Tag::Float(0f32.to_bits())),
|
||||
("pitch", Tag::Float(0f32.to_bits())),
|
||||
]),
|
||||
"Inventory",
|
||||
Tag::List(
|
||||
self.inventory
|
||||
.iter()
|
||||
.map(|(slot, id, count, damage)| {
|
||||
let mut entries = vec![
|
||||
("Slot", Tag::Byte(*slot as i8)),
|
||||
("id", string(id)),
|
||||
("count", Tag::Int(*count 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)
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
),
|
||||
("difficulty_settings", difficulty),
|
||||
("initialized", Tag::Byte(1)),
|
||||
|
||||
@@ -0,0 +1,630 @@
|
||||
//! 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};
|
||||
|
||||
/// Everything the workstation menus read, loaded once with the resources.
|
||||
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),
|
||||
trades: crate::merchant::Trades::load(root),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 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<str>, 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<ItemStack> {
|
||||
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<ItemStack>,
|
||||
/// 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<ItemStack> {
|
||||
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<Smithing>,
|
||||
/// Sorted by recipe id, the registry order vanilla lists them in.
|
||||
pub stonecutting: Vec<Stonecutting>,
|
||||
/// `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::<Value>(&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::<Value>(&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<ItemStack> {
|
||||
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_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 {
|
||||
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);
|
||||
}
|
||||
|
||||
/// 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();
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -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<EnchantmentInstance> list(RandomSource random, int seed, int slot, int cost, ItemStack stack, HolderSet.Named<Enchantment> table) {
|
||||
random.setSeed(seed + slot);
|
||||
List<EnchantmentInstance> 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<EnchantmentInstance> l = list(random, seed, i, costs[i], stack, table);
|
||||
if (!l.isEmpty()) clue = name(l.get(random.nextInt(l.size())));
|
||||
List<EnchantmentInstance> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
Reference in New Issue
Block a user