Save status effects, show thrown potions, test loot enchantments and vanilla data

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-08 15:51:16 +02:00
parent 9a3bf42574
commit 481f427e3a
5 changed files with 145 additions and 1 deletions
+2
View File
@@ -2981,6 +2981,7 @@ impl Game<'_> {
self.particles.clear();
self.orbs.clear();
self.experience = Experience { level: self.level.xp_level, progress: self.level.xp_progress, total: self.level.xp_total };
self.restore_effects();
self.mining = None;
self.container = None;
self.carried = None;
@@ -4175,6 +4176,7 @@ impl Game<'_> {
}
}
level.dimension = self.dim.id().to_owned();
level.active_effects = self.potions.effects.list.iter().map(|e| (format!("minecraft:{}", e.id), e.duration, e.amplifier, e.ambient, e.visible)).collect();
level.write(&self.world_root)?;
self.message = Some(("Saved the game".into(), Instant::now()));
Ok(())
+26 -1
View File
@@ -167,7 +167,9 @@ impl Game<'_> {
}
/// `LivingEntity.tickEffects`, attribute modifiers and the status flags.
pub(super) fn tick_effects(&mut self) {
if self.player.as_ref().is_none_or(|p| p.health.dead_or_dying()) {
let Some(player) = self.player.as_ref() else { return };
if player.health.dead_or_dying() {
// LivingEntity.die → removeAllEffects.
self.potions.effects.clear();
}
for action in self.potions.effects.tick() {
@@ -237,6 +239,18 @@ impl Game<'_> {
t.velocity = Vec3::new(t.velocity.x * 0.99, t.velocity.y * 0.99 - 0.05, t.velocity.z * 0.99);
t.age < 1200 && t.position.y > -128.0
});
// ThrownItemRenderer stand-in: a short-lived sprite of the potion at its position.
for t in &thrown {
let sprite = if &*t.stack.item == "minecraft:lingering_potion" { "item/lingering_potion" } else { "item/splash_potion" };
let mut fixed = horizon_core::random::LegacyRandom::new(0);
let mut p = horizon_client::particles::Particle::terrain(&mut fixed, [t.position.x, t.position.y, t.position.z], [0.0; 3], sprite.into(), 0xFFFFFF);
p.velocity = [0.0; 3];
p.gravity = 0.0;
p.lifetime = 2;
p.size = 0.25;
p.uv = [0.0, 0.0, 1.0, 1.0];
self.particles.push(p);
}
self.potions.thrown = thrown;
for (stack, at) in landed {
self.splash(&stack, at);
@@ -341,6 +355,17 @@ impl Game<'_> {
batch.sprite_scaled(atlas, &format!("mob_effect/{}", e.id), x + 3.0, y + 3.0, 18.0, 18.0, rgba(255, 255, 255, (alpha * 255.0) as u8));
}
}
/// Effects saved in level.dat (`Player.active_effects`).
pub(super) fn restore_effects(&mut self) {
self.potions = PotionState::default();
for (id, duration, amplifier, ambient, _) in self.level.active_effects.clone() {
if let Some(def) = brewing::effect(&id) {
let mut e = EffectInstance::new(def.id, duration, amplifier);
e.ambient = ambient;
self.potions.effects.add(e);
}
}
}
pub(super) fn effects_json(&self) -> serde_json::Value {
serde_json::Value::Array(self.potions.effects.list.iter().map(|e| serde_json::json!({ "id": e.id, "duration": e.duration, "amplifier": e.amplifier })).collect())
}
+47
View File
@@ -604,3 +604,50 @@ impl LootContext<'_> {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn ctx<'a>(items: &'a Items, held: Option<&'a ItemStack>, props: &'a BTreeMap<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());
}
}
+30
View File
@@ -386,6 +386,8 @@ pub struct Level {
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,
@@ -468,6 +470,16 @@ impl Level {
xp_progress: player.map_or(0.0, |p| float(p.get("XpP"))),
xp_total: player.map_or(0, |p| long(p.get("XpTotal")) as i32),
xp_seed: player.map_or(0, |p| long(p.get("XpSeed")) as i32),
active_effects: match player.and_then(|p| p.get("active_effects")) {
Some(Tag::List(list)) => list
.iter()
.filter_map(|e| {
let Some(Tag::String(id)) = e.get("id") else { return None };
Some((id.to_string_lossy(), long(e.get("duration")) as i32, long(e.get("amplifier")) as i32, long(e.get("ambient")) != 0, e.get("show_icon").is_none_or(|v| long(Some(v)) != 0)))
})
.collect(),
_ => Vec::new(),
},
inventory,
inventory_components,
})
@@ -483,6 +495,24 @@ impl Level {
("XpP", Tag::Float(self.xp_progress.to_bits())),
("XpTotal", Tag::Int(self.xp_total)),
("XpSeed", Tag::Int(self.xp_seed)),
(
"active_effects",
Tag::List(
self.active_effects
.iter()
.map(|(id, duration, amplifier, ambient, icon)| {
Tag::compound([
("id", string(id)),
("duration", Tag::Int(*duration)),
("amplifier", Tag::Byte(*amplifier as i8)),
("ambient", Tag::Byte(i8::from(*ambient))),
("show_particles", Tag::Byte(1)),
("show_icon", Tag::Byte(i8::from(*icon))),
])
})
.collect(),
),
),
("playerGameType", Tag::Int(i32::from(self.creative))),
(
"Rotation",
+40
View File
@@ -570,6 +570,46 @@ mod tests {
assert_eq!(increased_repair_cost(3), 7);
}
/// Checks against the prepared vanilla resources when they are present.
#[test]
fn prepared_vanilla_data() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3");
if !root.join("items.json").exists() {
return;
}
let items = Items::tags_only(&root).unwrap();
let data = StationData::load(&root, &items);
let e = &data.enchantments;
assert_eq!(e.list.len(), 43);
assert_eq!(&*e.tag("minecraft:in_enchanting_table")[0], "minecraft:protection");
assert!(!e.compatible("minecraft:fortune", "minecraft:silk_touch"));
assert!(e.is_curse("minecraft:binding_curse"));
assert_eq!(e.full_name("minecraft:sharpness", 5).0, "Sharpness V");
assert_eq!(e.enchantable("minecraft:golden_sword"), 22);
// Brewing: water + nether wart = awkward.
assert_eq!(data.brewing.recipes.len(), 279);
let water = ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water");
let r = data.brewing.find(&water, &ItemStack::new("minecraft:nether_wart", 1)).unwrap();
assert_eq!(r.output.potion(), Some("minecraft:awkward"));
assert!(data.brewing.is_reagent(&ItemStack::new("minecraft:blaze_powder", 1)));
// Smithing: netherite upgrade keeps enchantments.
let mut sword = ItemStack::new("minecraft:diamond_sword", 1);
sword.enchant("minecraft:sharpness", 2);
let out = data
.recipes
.smithing_result(e, Some(&ItemStack::new("minecraft:netherite_upgrade_smithing_template", 1)), Some(&sword), Some(&ItemStack::new("minecraft:netherite_ingot", 1)))
.unwrap();
assert_eq!((&*out.item, out.enchantment_level("minecraft:sharpness")), ("minecraft:netherite_sword", 2));
assert!(data.recipes.stonecutter(&ItemStack::new("minecraft:stone", 1)).len() >= 10);
// Trades: every profession level set yields offers.
let ctx = crate::merchant::TradeContext { items: &items, enchantments: e, variant: "minecraft:plains" };
for p in crate::merchant::PROFESSIONS {
let set = crate::merchant::Trades::set_for(p, 1);
let mut random = crate::merchant::sequence_random(12345, &format!("minecraft:trade_set/{}", set.trim_start_matches("minecraft:")));
assert!(!data.trades.offers_from_set(&ctx, &set, &mut random).is_empty(), "{p}");
}
}
#[test]
fn grindstone_strips_non_curses() {
let e = sample();