From 723ec3bb8ad7138ecc014346e828b63a8a617054 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:56:39 +0200 Subject: [PATCH 1/2] Drop entity death loot exactly as vanilla's LivingEntity.die does Entity loot tables now run on the faithful loot engine with an entity context: the victim, the killer and direct attacker, the damage type and its tags, the last player to hurt it and their luck, entity predicates (flags, equipment, components, sheep, cube size, raider captains, vehicles, entity type tags), damage source predicates, killed_by_player, random_chance_with_enchanted_bonus, enchanted_count_increase, furnace_smelt and tag entries. Draws come from the world's random sequence for the table. mobs::drops ports dropAllDeathLoot: Monster loot for babies, equipment drops in EquipmentSlot order with Looting's equipment_drops effect and durability, the fox's mouth item, the wither's star, the charged creeper head hook, horse inventories and chests, and getBaseExperienceReward with the equipment bonus and baby zombie reward, split into orbs. Fixes found on the way: sheep dropped their wool twice, baby monsters dropped nothing, armour bonus experience and the equipment slot order were wrong, hoglins were fire immune, and fishing treasure was unreachable (the hook predicate format changed). tools/test_entity_death_loot_parity.py: 1,578 cases over 87 entity types match vanilla. Co-Authored-By: Claude Opus 5.5 --- .../examples/entity_death_loot_fixture.rs | 266 ++++++++ crates/horizon-client/src/game/creatures.rs | 278 ++++---- crates/horizon-client/src/game/raids.rs | 15 - crates/horizon-client/src/mobs.rs | 4 + crates/horizon-client/src/mobs/drops.rs | 530 +++++++++++++++ crates/horizon-client/src/mobs/species.rs | 1 - crates/horizon-world/src/loot.rs | 617 ++++++++++++++++-- .../parity/VanillaEntityDeathLootOracle.java | 320 +++++++++ tools/test_entity_death_loot_parity.py | 185 ++++++ 9 files changed, 2022 insertions(+), 194 deletions(-) create mode 100644 crates/horizon-client/examples/entity_death_loot_fixture.rs create mode 100644 crates/horizon-client/src/mobs/drops.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityDeathLootOracle.java create mode 100644 tools/test_entity_death_loot_parity.py diff --git a/crates/horizon-client/examples/entity_death_loot_fixture.rs b/crates/horizon-client/examples/entity_death_loot_fixture.rs new file mode 100644 index 000000000..0e6dede38 --- /dev/null +++ b/crates/horizon-client/examples/entity_death_loot_fixture.rs @@ -0,0 +1,266 @@ +//! Entity death drops for differential tests against vanilla +//! (tools/test_entity_death_loot_parity.py): reads the cases of +//! `VanillaEntityDeathLootOracle` and prints what `mobs::drops::die` drops. +//! +//! usage: entity_death_loot_fixture RESOURCES INPUT OUTPUT +use horizon_client::{ + mobs::{ + Mob, MobTypes, Species, cube, drops, gear, raider, render::DYE_NAMES, sulfur_cube, + }, + random_sequences::RandomSequences, +}; +use horizon_core::{geometry::Vec3, random::LegacyRandom}; +use horizon_world::loot::{LootDamage, LootData, LootEntity, LootStack}; +use std::{collections::BTreeMap, fmt::Write as _, fs, path::Path, sync::Arc}; + +/// `id[;enchantment:level...]`. +fn stack(spec: &str) -> LootStack { + let mut parts = spec.split(';'); + let mut s = LootStack { + item: parts.next().unwrap_or("minecraft:air").to_owned(), + count: 1, + damage: 0, + enchantments: Vec::new(), + potion: None, + map: false, + ominous_amplifier: None, + }; + for e in parts { + let (name, level) = e.rsplit_once(':').unwrap_or((e, "1")); + let name = if name.contains(':') { + name.to_owned() + } else { + format!("minecraft:{name}") + }; + s.enchantments.push((name, level.parse().unwrap_or(1))); + } + s +} + +fn line(s: &LootStack) -> String { + let mut out = format!("drop {} {}", s.item, s.count); + if s.damage != 0 { + let _ = write!(out, " damage={}", s.damage); + } + for (e, l) in &s.enchantments { + let _ = write!(out, " ench={e}:{l}"); + } + if let Some(p) = &s.potion { + let _ = write!(out, " potion={p}"); + } + if let Some(a) = s.ominous_amplifier { + let _ = write!(out, " ominous={a}"); + } + out +} + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let root = Path::new( + args.get(1) + .ok_or("usage: entity_death_loot_fixture RESOURCES INPUT OUTPUT")?, + ); + let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; + let types = MobTypes::load(root)?; + let loot = LootData::load(root)?; + let mut out = String::new(); + for raw in input.lines() { + if raw.trim().is_empty() || raw.starts_with('#') { + continue; + } + let mut c = BTreeMap::new(); + let mut name = ""; + for token in raw.split_whitespace() { + match token.split_once('=') { + Some((k, v)) => { + c.insert(k, v); + } + None => name = token, + } + } + let get = |k: &str, d: &'static str| -> String { c.get(k).copied().unwrap_or(d).to_owned() }; + let _ = writeln!(out, "== {name}"); + let Some(kind) = types.types.get(c["type"]) else { + let _ = writeln!(out, "error unsupported {}", c["type"]); + continue; + }; + let kind = Arc::new(kind.clone()); + let world_seed: i64 = get("seed", "0").parse()?; + let kills: i64 = get("kills", "1").parse()?; + let rand: i64 = get("rand", "0").parse()?; + let mut sequences = RandomSequences::default(); + for k in 0..kills { + let _ = writeln!(out, "kill {k}"); + let mut m = Mob::new(1, kind.clone(), Vec3::new(0.5, 64.0, 0.5), 0.0); + // EntityType.create(LOAD) gives no equipment. + for slot in drops::SLOTS { + drops::clear_slot(&mut m, slot); + } + if get("baby", "0") == "1" && drops::can_be_baby(m.species()) { + m.extra.age = -24000; + } + if get("fire", "0") == "1" { + m.fire_ticks = 100; + } + // A cube made with EntityType.create(LOAD) was never sized. + if matches!(m.species(), Species::Slime | Species::MagmaCube) { + m.extra.size = 0; + } + if let Some(size) = c.get("size") { + let size: i32 = size.parse()?; + if m.species() == Species::SulfurCube { + sulfur_cube::set_size(&mut m, size, true); + } else { + cube::set_size(&mut m, size); + } + } + if let Some(color) = c.get("color") { + m.extra.color = DYE_NAMES.iter().position(|d| d == color).unwrap_or(0) as u8; + } + m.extra.sheared = get("sheared", "0") == "1"; + if get("leader", "0") == "1" { + raider::state_mut(&mut m).patrol_leader = true; + } + if get("captain", "0") == "1" { + m.extra.head = Some(Arc::from(raider::BANNER)); + } + let mut chances = [drops::DEFAULT_DROP_CHANCE; 8]; + for (i, slot) in drops::SLOTS.iter().enumerate() { + if let Some(spec) = c.get(slot) { + let s = stack(spec); + let item: Option> = Some(Arc::from(s.item.as_str())); + let index = match *slot { + "mainhand" => { + m.extra.main_hand = item; + Some(gear::MAIN) + } + "offhand" => { + m.extra.off_hand = item; + Some(gear::OFF) + } + "head" => { + m.extra.head = item; + Some(gear::HEAD) + } + "body" if drops::head_is_body(m.species()) => { + m.extra.head = item; + None + } + "saddle" => { + m.set_saddle(Some(horizon_client::items::ItemStack::new(&s.item, 1))); + None + } + "chest" => { + m.extra.chest = item; + Some(gear::CHEST) + } + "legs" => { + m.extra.legs = item; + Some(gear::LEGS) + } + "feet" => { + m.extra.feet = item; + Some(gear::FEET) + } + _ => None, + }; + if let Some(index) = index + && !s.enchantments.is_empty() + { + let levels = s + .enchantments + .iter() + .map(|(e, l)| (Arc::from(e.as_str()), *l as u32)) + .collect(); + gear::set(&mut m, index, levels); + } + } + if let Some(chance) = c.get(format!("chance_{slot}").as_str()) { + chances[i] = chance.parse()?; + } + } + m.extra.drop_chances = Some(Box::new(chances)); + m.random = LegacyRandom::new(rand + k); + // The killer, the last player to hurt the victim and the damage source. + let killer_id = get("killer", "none"); + let weapon = c.get("weapon").map(|w| stack(w)); + let armed = |kind: &str| { + let mut e = LootEntity::new(kind); + if let Some(w) = &weapon { + e.equipment.push(("mainhand".into(), w.clone())); + } + e + }; + let player = (killer_id == "player" || get("pkill", "0") == "1").then(|| { + if killer_id == "player" { + armed("minecraft:player") + } else { + LootEntity::new("minecraft:player") + } + }); + let killer = match killer_id.as_str() { + "player" => player.clone(), + "none" => None, + id => { + let mut e = armed(id); + e.frog_variant = c.get("frog").map(|f| f.to_string()); + e.powered = get("charged", "0") == "1"; + Some(e) + } + }; + let pkill = get("pkill", if killer_id == "player" { "1" } else { "0" }) == "1"; + let projectile = |kind: &str| LootEntity { + kind: kind.to_owned(), + ..LootEntity::default() + }; + let damage = |kind: &str, source: Option, direct: Option| LootDamage { + kind: kind.to_owned(), + source, + direct, + }; + let source = match get("source", "attack").as_str() { + "attack" => match &killer { + None => damage("minecraft:generic", None, None), + Some(k) if k.kind == "minecraft:player" => { + damage("minecraft:player_attack", Some(k.clone()), Some(k.clone())) + } + Some(k) => damage("minecraft:mob_attack", Some(k.clone()), Some(k.clone())), + }, + "arrow" => damage("minecraft:arrow", killer.clone(), Some(projectile("minecraft:arrow"))), + "fireball" => match &killer { + Some(k) => damage("minecraft:fireball", Some(k.clone()), Some(projectile("minecraft:fireball"))), + None => damage( + "minecraft:unattributed_fireball", + Some(projectile("minecraft:fireball")), + Some(projectile("minecraft:fireball")), + ), + }, + "explosion" => match &killer { + Some(k) => damage("minecraft:player_explosion", Some(k.clone()), Some(k.clone())), + None => damage("minecraft:explosion", None, None), + }, + "lightning" => damage("minecraft:lightning_bolt", None, None), + "fire" => damage("minecraft:on_fire", None, None), + _ => damage("minecraft:generic", None, None), + }; + let death = drops::Death { + loot: &loot, + damage: Some(source), + player: player.filter(|_| pkill), + luck: get("luck", "0").parse()?, + vehicle: c.get("vehicle").map(|v| LootEntity::new(v)), + mob_drops: true, + world_seed, + }; + let (items, _) = drops::die(&mut m, &death, &mut sequences); + for d in items { + let _ = match d { + drops::Drop::Item(s) => writeln!(out, "{}", line(&s)), + drops::Drop::Orb(v) => writeln!(out, "orb {v}"), + }; + } + } + } + fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 26c1bf86f..afd148af7 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -739,13 +739,14 @@ impl Game<'_> { /// LivingEntity.die / dropAllDeathLoot. fn mob_died(&mut self, m: &Mob) { let by_player = self.last_hurt_by_player.remove(&m.id) || m.ai.last_hurt_by_player > 0; + let mut dying = m.clone(); // LivingEntity.die: the death is heard, and a sculk catalyst nearby - // takes the experience. + // takes the experience (before the loot is dropped). self.sculk_mob_died(m); let consumed = - self.catalyst_takes_experience([m.position.x, m.position.y, m.position.z], |game| { + self.catalyst_takes_experience([m.position.x, m.position.y, m.position.z], |_| { if by_player { - experience_reward(m, &mut game.world.random) + horizon_client::mobs::drops::base_experience(&mut dying).max(0) as u32 } else { 0 } @@ -760,103 +761,8 @@ impl Game<'_> { self.score_entity_removed(m.id); self.raider_died(m, by_player); self.villager_murdered(m, by_player); - let held = self.held().cloned(); let pos = [m.position.x, m.position.y + 0.5, m.position.z]; - if !m.is_baby() { - let mut drops = self.res.items.entity_drops( - &m.kind.id, - by_player, - held.as_ref(), - &mut self.world.random, - ); - if m.species() == Species::Sheep && !m.extra.sheared { - let color = horizon_client::mobs::render::DYE_NAMES[m.extra.color as usize & 15]; - drops.extend(self.res.items.loot_table( - &format!("minecraft:entities/sheep/{color}"), - by_player, - held.as_ref(), - &mut self.world.random, - )); - } - for d in drops { - if d.count > 0 && &*d.item != "minecraft:air" { - self.spawn_item(d, pos, [0.0, 0.2, 0.0], 10); - } - } - // Saddles, horse armour and chests always drop. - let mut gear: Vec<&str> = Vec::new(); - if let Some(saddle) = m.saddle_item() { - self.spawn_item(saddle, pos, [0.0, 0.2, 0.0], 10); - } - // WitherBoss.dropCustomDeathLoot. - if m.species() == Species::Wither { - gear.push("minecraft:nether_star"); - } - if species_drops_harness(m) - && let Some(h) = m.extra.head.as_deref() - { - gear.push(h); - } - if m.extra.chested && horizon_client::mobs::equine::is_equine(m.species()) { - gear.push("minecraft:chest"); - } - if horizon_client::mobs::equine::is_equine(m.species()) - && let Some(armor) = m.extra.head.as_deref() - { - gear.push(armor); - } - for item in gear { - self.spawn_item(ItemStack::new(item, 1), pos, [0.0, 0.2, 0.0], 10); - } - // AbstractChestedHorse.dropEquipment: the chest contents. - for stack in m.extra.items.clone().into_iter().flatten() { - self.spawn_item(stack, pos, [0.0, 0.2, 0.0], 10); - } - self.raider_death_loot(m, pos); - let worn = if horizon_client::mobs::equine::is_equine(m.species()) { - [None, None, None, None] - } else { - [ - m.extra.head.clone(), - m.extra.chest.clone(), - m.extra.legs.clone(), - m.extra.feet.clone(), - ] - }; - for (index, item) in std::iter::once(m.extra.main_hand.clone()) - .chain(worn) - .enumerate() - { - // Main hand, then head to feet (the enchantment slots). - let slot = if index == 0 { - horizon_client::mobs::gear::MAIN - } else { - horizon_client::mobs::gear::HEAD + index - 1 - }; - // Equipment drop chance 8.5% (+ player kill only). - // Vexes never drop their sword. - if let Some(item) = &item - && by_player - && &**item != horizon_client::mobs::raider::BANNER - && m.species() != Species::Vex - && self.world.random.next_float() < 0.085 - { - let mut stack = ItemStack::new(item, 1); - if let Some(g) = horizon_client::mobs::gear::gear(m) { - for (e, l) in &g.slots[slot] { - stack.enchant(e, *l); - } - } - self.spawn_item(stack, pos, [0.0, 0.2, 0.0], 10); - } - } - } - if by_player && !consumed { - let xp = experience_reward(m, &mut self.world.random); - if xp > 0 { - self.spawn_orbs(pos, xp); - } - } + self.drop_death_loot(&mut dying, by_player, consumed, pos); if m.species() == Species::SulfurCube { self.split_sulfur_cube(m); } @@ -881,6 +787,88 @@ impl Game<'_> { } } } + /// `dropAllDeathLoot` through `mobs::drops`: the entity loot table from the + /// world's random sequence, equipment by drop chance, species extras and + /// the experience orbs, spawned in order. + fn drop_death_loot(&mut self, m: &mut Mob, by_player: bool, consumed: bool, pos: [f64; 3]) { + use horizon_client::mobs::{DamageKind, Who, drops}; + use horizon_world::loot::{LootDamage, LootEntity}; + let Some(loot) = horizon_client::structure_blocks::loot_data(&self.options.resources) else { + return; + }; + let player = || { + let mut e = LootEntity::new("minecraft:player"); + if let Some(held) = self.held() { + e.equipment.push(("mainhand".into(), to_loot(held))); + } + e + }; + let damage = m.last_damage.map(|(d, _)| { + let source = match d.attacker { + Some(Who::Player) => Some(player()), + Some(Who::Mob(id)) => self + .mobs + .iter() + .find(|o| o.id == id) + .map(|o| drops::loot_entity(o, None)), + None => None, + }; + let direct = match d.kind { + DamageKind::Arrow => Some(LootEntity { + kind: "minecraft:arrow".into(), + ..LootEntity::default() + }), + DamageKind::Fireball => Some(LootEntity { + kind: "minecraft:fireball".into(), + ..LootEntity::default() + }), + _ => source.clone(), + }; + let player_source = matches!(d.attacker, Some(Who::Player)); + LootDamage { + kind: damage_type(d.kind, player_source).into(), + source, + direct, + } + }); + let vehicle = m + .extra + .mount + .and_then(|id| self.mobs.iter().find(|o| o.id == id)) + .map(|o| LootEntity::new(&o.kind.id)); + let death = drops::Death { + loot: &loot, + damage, + player: by_player.then(player), + luck: 0.0, + vehicle, + mob_drops: self.ui.rules.bool("mob_drops"), + world_seed: self.level.seed, + }; + let (items, skulls) = drops::die(m, &death, &mut self.rand_sequences); + if skulls + && let Some(Who::Mob(id)) = m.last_damage.and_then(|(d, _)| d.attacker) + && let Some(creeper) = self.mobs.iter_mut().find(|o| o.id == id) + { + // Creeper.droppedSkulls: one head per charged explosion. + creeper.extra.charged = false; + } + let raider = horizon_client::mobs::raider::is_raider(m.species()); + for d in items { + match d { + drops::Drop::Item(stack) => { + let item = if raider && stack.item == horizon_client::mobs::raider::BANNER { + horizon_client::mobs::raider::ominous_banner() + } else { + from_loot(&stack) + }; + self.spawn_item(item, pos, [0.0, 0.2, 0.0], 10); + } + drops::Drop::Orb(value) if !consumed => self.spawn_orbs(pos, value as u32), + drops::Drop::Orb(_) => {} + } + } + } pub(super) fn handle_mob_events(&mut self, events: Vec) -> Result<()> { for e in events { match e { @@ -2614,11 +2602,6 @@ impl Game<'_> { } } } -fn species_drops_harness(m: &Mob) -> bool { - // Body equipment set to drop when killed: a harness, nautilus armour, a - // sulfur cube's swallowed block. - horizon_client::mobs::species::body_slot(m.species()) -} fn eat_sound(s: Species) -> &'static str { match s { Species::Pig => "entity.pig.eat", @@ -2633,37 +2616,66 @@ fn eat_sound(s: Species) -> &'static str { } } /// Mob.getBaseExperienceReward -fn experience_reward(m: &Mob, random: &mut impl RandomSource) -> u32 { - use Species as S; - match m.species() { - S::Blaze | S::Ghast | S::Hoglin | S::Zoglin | S::PiglinBrute | S::Breeze => 10, - S::Slime | S::MagmaCube => m.extra.size.max(1) as u32, - S::Endermite => 3, - S::Bat - | S::Squid - | S::GlowSquid - | S::Cod - | S::Salmon - | S::TropicalFish - | S::Pufferfish - | S::Dolphin => 1 + random.next_int_bound(3).unwrap_or(0) as u32, - S::IronGolem | S::SnowGolem | S::Villager | S::WanderingTrader => 0, - // SulfurCube.getBaseExperienceReward. - S::SulfurCube if m.is_baby() => 0, - S::SulfurCube => 1 + random.next_int_bound(2).unwrap_or(0) as u32, - // Animals in the monster category (Animal.getBaseExperienceReward). - S::CamelHusk | S::ZombieNautilus => 1 + random.next_int_bound(3).unwrap_or(0) as u32, - _ if m.hostile() => { - 5 + if m.extra.main_hand.is_some() { - 1 + random.next_int_bound(3).unwrap_or(0) as u32 - } else { - 0 - } - } - _ if m.is_baby() => 0, - _ => 1 + random.next_int_bound(3).unwrap_or(0) as u32, +/// The damage type id of a Horizon damage kind. +fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static str { + use horizon_client::mobs::DamageKind as K; + match kind { + K::PlayerAttack => "minecraft:player_attack", + K::MobAttack => "minecraft:mob_attack", + K::Arrow => "minecraft:arrow", + K::Thrown => "minecraft:thrown", + K::Fireball => "minecraft:fireball", + K::Explosion if player => "minecraft:player_explosion", + K::Explosion => "minecraft:explosion", + K::Fall => "minecraft:fall", + K::OnFire => "minecraft:on_fire", + K::InFire => "minecraft:in_fire", + K::Lava => "minecraft:lava", + K::Drown => "minecraft:drown", + K::Magic => "minecraft:magic", + K::Sting => "minecraft:sting", + K::Cactus => "minecraft:cactus", + K::Generic => "minecraft:generic", + K::InWall => "minecraft:in_wall", + K::Thorns => "minecraft:thorns", + K::SonicBoom => "minecraft:sonic_boom", } } +/// A Horizon item stack as a loot stack (id, count, damage, enchantments). +fn to_loot(stack: &ItemStack) -> horizon_world::loot::LootStack { + horizon_world::loot::LootStack { + item: stack.item.to_string(), + count: stack.count as i32, + damage: stack.damage as i32, + enchantments: stack + .enchantments() + .iter() + .map(|(e, l)| (e.to_string(), *l as i32)) + .collect(), + potion: None, + map: false, + ominous_amplifier: None, + } +} +/// A generated loot stack as a Horizon item stack. +fn from_loot(stack: &horizon_world::loot::LootStack) -> ItemStack { + let mut item = ItemStack { + item: Arc::from(stack.item.as_str()), + count: stack.count.max(1) as u32, + damage: stack.damage.max(0) as u32, + extra: None, + }; + for (id, level) in &stack.enchantments { + item.enchant(id, (*level).max(0) as u32); + } + if let Some(potion) = &stack.potion { + item = item.with_potion(potion); + } + if let Some(amplifier) = stack.ominous_amplifier.filter(|a| *a > 0) { + item.data_mut().ominous_amplifier = Some(amplifier as u8); + } + item +} /// Entity.push between overlapping mobs (LivingEntity.pushEntities). fn push_apart(mobs: &mut [Mob]) { let n = mobs.len(); diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index 3e2fdad58..91c454ce8 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -921,21 +921,6 @@ impl Game<'_> { } /// A raider's ominous banner (drop chance 2.0: always dropped) and a /// patrol captain's ominous bottle (`entities/pillager`). - pub(super) fn raider_death_loot(&mut self, m: &horizon_client::mobs::Mob, pos: [f64; 3]) { - if !raider::is_raider(m.species()) { - return; - } - if m.extra.head.as_deref() == Some(raider::BANNER) { - self.spawn_item(raider::ominous_banner(), pos, [0.0, 0.2, 0.0], 10); - } - if m.species() == Species::Pillager && raider::is_captain(m) { - let amplifier = self.world.random.next_int_bound(5).unwrap_or(0) as u8; - let amplifier = (amplifier > 0).then_some(amplifier); - let mut bottle = horizon_client::items::ItemStack::new("minecraft:ominous_bottle", 1); - bottle.data_mut().ominous_amplifier = amplifier; - self.spawn_item(bottle, pos, [0.0, 0.2, 0.0], 10); - } - } /// `OminousBottleAmplifier.onConsume`: Bad Omen for 100 minutes at the /// bottle's amplifier, then the dispose sound; the bottle is used up. pub(super) fn drink_ominous_bottle( diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index f46420cad..deda5984a 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -18,6 +18,7 @@ pub mod control; pub mod creaking; pub mod cube; pub mod data; +pub mod drops; pub mod enderman; pub mod equine; pub mod farm; @@ -528,6 +529,9 @@ pub struct Extra { pub trap_time: i32, /// Enchantments on the equipment above. pub gear: Option>, + /// `Mob.dropChances` by `EquipmentSlot` (`drops::SLOTS` order) when set + /// explicitly; None uses the defaults of `drops::drop_chance`. + pub drop_chances: Option>, } #[derive(Clone, Debug)] pub struct Mob { diff --git a/crates/horizon-client/src/mobs/drops.rs b/crates/horizon-client/src/mobs/drops.rs new file mode 100644 index 000000000..42010afd9 --- /dev/null +++ b/crates/horizon-client/src/mobs/drops.rs @@ -0,0 +1,530 @@ +//! What a dying mob leaves behind: `LivingEntity.die`'s drop step. The +//! killer's `killedEntity` hook (a charged creeper's head drop), then +//! `dropAllDeathLoot`: the entity loot table (drawn from the world's random +//! sequence), `Mob.dropCustomDeathLoot` (equipment by drop chance, with the +//! entity random), the species' extra drops and the experience orbs. +use super::{Mob, Species, equine, gear, raider, render::DYE_NAMES, species}; +use crate::random_sequences::RandomSequences; +use horizon_core::random::RandomSource; +use horizon_world::loot::{EntityLootParams, LootDamage, LootData, LootEntity, LootStack}; + +/// `DropChances.DEFAULT_EQUIPMENT_DROP_CHANCE`. +pub const DEFAULT_DROP_CHANCE: f32 = 0.085; +/// `EquipmentSlot.VALUES`. +pub use horizon_world::loot::EQUIPMENT_SLOTS as SLOTS; + +/// One thing a death leaves in the world, in spawn order. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Drop { + Item(LootStack), + /// An experience orb of this value. + Orb(i32), +} + +/// How the mob died. +pub struct Death<'a> { + pub loot: &'a LootData, + /// The killing `DamageSource`. + pub damage: Option, + /// The player who last hurt the mob, when `lastHurtByPlayerMemoryTime > 0`. + pub player: Option, + /// That player's luck. + pub luck: f32, + /// The entity the mob rides. + pub vehicle: Option, + /// The `doMobLoot` game rule. + pub mob_drops: bool, + pub world_seed: i64, +} + +/// `instanceof Monster` (Monster.shouldDropLoot/shouldDropExperience). +pub fn is_monster(s: Species) -> bool { + use Species as S; + matches!( + s, + S::Blaze + | S::Bogged + | S::Breeze + | S::CaveSpider + | S::Creaking + | S::Creeper + | S::Drowned + | S::ElderGuardian + | S::Enderman + | S::Endermite + | S::Evoker + | S::Giant + | S::Guardian + | S::Husk + | S::Illusioner + | S::Parched + | S::Piglin + | S::PiglinBrute + | S::Pillager + | S::Ravager + | S::Silverfish + | S::Skeleton + | S::Spider + | S::Stray + | S::Vex + | S::Vindicator + | S::Warden + | S::Witch + | S::Wither + | S::WitherSkeleton + | S::Zoglin + | S::Zombie + | S::ZombieVillager + | S::ZombifiedPiglin + ) +} +/// `Mob.xpReward` as the constructors set it. +fn xp_reward(m: &Mob) -> i32 { + use Species as S; + match m.species() { + S::Blaze | S::Breeze | S::Guardian | S::ElderGuardian | S::Evoker => 10, + S::Vex | S::Endermite => 3, + S::PiglinBrute | S::Ravager => 20, + S::Wither => 50, + S::Creaking => 0, + // Hoglin.setBaby. + S::Hoglin if m.is_baby() => 3, + S::Ghast | S::Hoglin | S::Phantom | S::Shulker => 5, + // Slime.setSize / MagmaCube.setSize (unsized cubes keep 0). + S::Slime | S::MagmaCube => m.extra.size.max(0), + s if is_monster(s) => 5, + _ => 0, + } +} +fn is_animal(s: Species) -> bool { + use Species as S; + matches!( + s, + S::Armadillo + | S::Axolotl + | S::Bee + | S::Camel + | S::CamelHusk + | S::Cat + | S::Chicken + | S::Cow + | S::Donkey + | S::Fox + | S::Frog + | S::HappyGhast + | S::Goat + | S::Hoglin + | S::Horse + | S::Llama + | S::Mooshroom + | S::Mule + | S::Nautilus + | S::Ocelot + | S::Panda + | S::Parrot + | S::Pig + | S::PolarBear + | S::Rabbit + | S::Sheep + | S::SkeletonHorse + | S::Sniffer + | S::Strider + | S::TraderLlama + | S::Turtle + | S::Wolf + | S::ZombieHorse + | S::ZombieNautilus + ) +} +/// AgeableWaterCreature and WaterAnimal. +fn is_water_creature(s: Species) -> bool { + use Species as S; + matches!( + s, + S::Dolphin + | S::GlowSquid + | S::Squid + | S::Cod + | S::Salmon + | S::Pufferfish + | S::TropicalFish + | S::Tadpole + ) +} +fn zombie_family(s: Species) -> bool { + use Species as S; + matches!( + s, + S::Zombie | S::Husk | S::Drowned | S::ZombieVillager | S::ZombifiedPiglin + ) +} +fn is_raider(s: Species) -> bool { + use Species as S; + matches!( + s, + S::Pillager | S::Vindicator | S::Evoker | S::Illusioner | S::Witch | S::Ravager + ) +} +/// Whether `setBaby(true)` makes the species a baby (AgeableMob and the +/// zombies, minus the species that are never babies). +pub fn can_be_baby(s: Species) -> bool { + use Species as S; + matches!( + s, + S::Armadillo + | S::Axolotl + | S::Bee + | S::Camel + | S::Cat + | S::Chicken + | S::Cow + | S::Dolphin + | S::Donkey + | S::Drowned + | S::Fox + | S::HappyGhast + | S::GlowSquid + | S::Goat + | S::Hoglin + | S::Horse + | S::Husk + | S::Llama + | S::Mooshroom + | S::Mule + | S::Nautilus + | S::Ocelot + | S::Panda + | S::Pig + | S::Piglin + | S::PolarBear + | S::Rabbit + | S::Sheep + | S::SkeletonHorse + | S::Sniffer + | S::Squid + | S::Strider + | S::SulfurCube + | S::TraderLlama + | S::Turtle + | S::Villager + | S::WanderingTrader + | S::Wolf + | S::Zoglin + | S::Zombie + | S::ZombieHorse + | S::ZombieVillager + | S::ZombifiedPiglin + ) +} +/// Whether the species keeps its body armour in `extra.head`. +pub fn head_is_body(s: Species) -> bool { + species::body_slot(s) || equine::is_equine(s) +} + +/// The item a mob has in an `EquipmentSlot` (by name), with its enchantments. +pub fn slot_item(m: &Mob, slot: &str) -> Option { + let body = head_is_body(m.species()); + let (item, index) = match slot { + "mainhand" => (m.extra.main_hand.as_deref(), Some(gear::MAIN)), + "offhand" => (m.extra.off_hand.as_deref(), Some(gear::OFF)), + "head" if !body => (m.extra.head.as_deref(), Some(gear::HEAD)), + "chest" => (m.extra.chest.as_deref(), Some(gear::CHEST)), + "legs" => (m.extra.legs.as_deref(), Some(gear::LEGS)), + "feet" => (m.extra.feet.as_deref(), Some(gear::FEET)), + "body" if body => (m.extra.head.as_deref(), None), + "saddle" => { + let saddle = m.saddle_item()?; + let mut stack = loot_stack(&saddle.item, 1); + stack.damage = saddle.damage as i32; + for (e, l) in saddle.enchantments() { + stack.enchantments.push((e.to_string(), *l as i32)); + } + return Some(stack); + } + _ => (None, None), + }; + let mut stack = loot_stack(item?, 1); + if let (Some(index), Some(g)) = (index, gear::gear(m)) { + for (e, l) in &g.slots[index] { + stack.enchantments.push((e.to_string(), *l as i32)); + } + } + Some(stack) +} +/// `setItemSlot(slot, EMPTY)`. +pub fn clear_slot(m: &mut Mob, slot: &str) { + let body = head_is_body(m.species()); + let index = match slot { + "mainhand" => { + m.extra.main_hand = None; + gear::MAIN + } + "offhand" => { + m.extra.off_hand = None; + gear::OFF + } + "head" if !body => { + m.extra.head = None; + gear::HEAD + } + "chest" => { + m.extra.chest = None; + gear::CHEST + } + "legs" => { + m.extra.legs = None; + gear::LEGS + } + "feet" => { + m.extra.feet = None; + gear::FEET + } + "body" if body => { + m.extra.head = None; + return; + } + "saddle" => { + m.set_saddle(None); + return; + } + _ => return, + }; + if m.extra.gear.is_some() { + gear::set(m, index, Vec::new()); + } +} +fn loot_stack(item: &str, count: i32) -> LootStack { + LootStack { + item: item.to_owned(), + count, + damage: 0, + enchantments: Vec::new(), + potion: None, + map: false, + ominous_amplifier: None, + } +} +/// `Mob.dropChances.byEquipment(slot)`: the recorded chance, or the one the +/// game's spawn and equip paths give (saddles and body armour are put on by +/// `Equippable` and always drop; a captain's banner always drops; a vex +/// never drops its sword). +pub fn drop_chance(m: &Mob, slot: &str) -> f32 { + let index = SLOTS.iter().position(|s| *s == slot).unwrap_or(0); + if let Some(chances) = &m.extra.drop_chances { + return chances[index]; + } + match slot { + "saddle" | "body" => 2.0, + "head" if is_raider(m.species()) && m.extra.head.as_deref() == Some(raider::BANNER) => 2.0, + "mainhand" if m.species() == Species::Vex => 0.0, + _ => DEFAULT_DROP_CHANCE, + } +} +/// The facts loot predicates read about a mob. +pub fn loot_entity(m: &Mob, vehicle: Option) -> LootEntity { + use Species as S; + let s = m.species(); + let mut e = LootEntity::new(&m.kind.id); + e.on_fire = m.fire_ticks > 0 && !m.kind.flags.fire_immune; + e.baby = m.is_baby(); + e.vehicle = vehicle.map(Box::new); + if matches!(s, S::Slime | S::MagmaCube | S::SulfurCube) { + // An unsized cube has the synced default size 1. + e.cube_size = Some(m.extra.size.max(1)); + } + if s == S::Sheep { + e.sheep = Some(( + DYE_NAMES[m.extra.color as usize & 15].to_owned(), + m.extra.sheared, + )); + } + if is_raider(s) { + e.captain = Some(raider::is_captain(m)); + } + if s == S::Frog { + e.frog_variant = Some( + ["minecraft:temperate", "minecraft:warm", "minecraft:cold"] + [usize::from(m.extra.variant).min(2)] + .to_owned(), + ); + } + e.powered = s == S::Creeper && m.extra.charged; + e.equipment = SLOTS + .iter() + .filter_map(|slot| slot_item(m, slot).map(|i| (slot.to_string(), i))) + .collect(); + e +} +/// `ExperienceOrb.getExperienceValue`. +pub fn orb_value(amount: i32) -> i32 { + for v in [2477, 1237, 617, 307, 149, 73, 37, 17, 7, 3] { + if amount >= v { + return v; + } + } + 1 +} + +/// `LivingEntity.die`'s drops for `m` (equipment it loses is removed from +/// it). Returns the drops in spawn order and whether a charged creeper +/// killer dropped a head (`Creeper.droppedSkulls`). +pub fn die(m: &mut Mob, d: &Death, sequences: &mut RandomSequences) -> (Vec, bool) { + let mut out = Vec::new(); + let this = loot_entity(m, d.vehicle.clone()); + let mut skulls = false; + // Creeper.killedEntity: a charged creeper's victim drops its head. + if let Some(source) = d.damage.as_ref().and_then(|x| x.source.as_ref()) + && source.kind == "minecraft:creeper" + && source.powered + && d.mob_drops + { + let params = EntityLootParams { + this: this.clone(), + damage: d.damage.clone(), + player: None, + luck: 0.0, + }; + let items = roll(d, "minecraft:charged_creeper/root", ¶ms, sequences); + skulls = items.iter().any(|i| !i.is_empty()); + out.extend(items.into_iter().filter(|i| !i.is_empty()).map(Drop::Item)); + } + let killed_by_player = d.player.is_some(); + let s = m.species(); + // Fox.dropAllDeathLoot: whatever it holds in its mouth comes out first. + if s == Species::Fox + && let Some(stack) = slot_item(m, "mainhand") + { + out.push(Drop::Item(stack)); + clear_slot(m, "mainhand"); + } + let drops_loot = d.mob_drops && (is_monster(s) || !m.is_baby()); + if drops_loot { + let table = format!("minecraft:entities/{}", m.kind.id.trim_start_matches("minecraft:")); + let params = EntityLootParams { + this: this.clone(), + damage: d.damage.clone(), + player: d.player.clone().filter(|_| killed_by_player), + luck: if killed_by_player { d.luck } else { 0.0 }, + }; + let items = roll(d, &table, ¶ms, sequences); + out.extend(items.into_iter().filter(|i| !i.is_empty()).map(Drop::Item)); + // Mob.dropCustomDeathLoot. + let damage_params = EntityLootParams { + this: this.clone(), + damage: d.damage.clone(), + player: None, + luck: 0.0, + }; + let living_attacker = d + .damage + .as_ref() + .and_then(|x| x.source.as_ref()) + .is_some_and(|a| a.living); + for slot in SLOTS { + let stack = slot_item(m, slot); + let mut chance = drop_chance(m, slot); + if chance == 0.0 { + continue; + } + let preserve = chance > 1.0; + if living_attacker { + chance = d.loot.equipment_drop_chance(&damage_params, chance); + } + let Some(mut stack) = stack else { continue }; + if d.loot.prevents_equipment_drop(&stack) || !(killed_by_player || preserve) { + continue; + } + if m.random.next_float() >= chance { + continue; + } + let max = d.loot.max_damage(&stack.item); + if !preserve && max > 0 { + let inner = m.random.next_int_bound((max - 3).max(1)).unwrap_or(0); + stack.damage = max - m.random.next_int_bound(1 + inner).unwrap_or(0); + } + out.push(Drop::Item(stack)); + clear_slot(m, slot); + } + // WitherBoss.dropCustomDeathLoot. + if s == Species::Wither { + out.push(Drop::Item(loot_stack("minecraft:nether_star", 1))); + } + } + // dropEquipment: AbstractHorse's inventory, then a chested horse's chest. + if equine::is_equine(s) { + for stack in m.extra.items.iter().flatten() { + if stack.count > 0 { + let mut item = loot_stack(&stack.item, stack.count as i32); + item.damage = stack.damage as i32; + out.push(Drop::Item(item)); + } + } + if m.extra.chested { + out.push(Drop::Item(loot_stack("minecraft:chest", 1))); + m.extra.chested = false; + } + } + // dropExperience. + let drops_experience = match s { + Species::Tadpole => false, + Species::Hoglin => true, + s if is_monster(s) => true, + _ => !m.is_baby(), + }; + if killed_by_player && drops_experience && d.mob_drops { + let mut amount = base_experience(m); + while amount > 0 { + let value = orb_value(amount); + amount -= value; + out.push(Drop::Orb(value)); + } + } + (out, skulls) +} +fn roll( + d: &Death, + table: &str, + params: &EntityLootParams, + sequences: &mut RandomSequences, +) -> Vec { + match d.loot.random_sequence(table) { + Some(id) => { + let random = sequences.get(id, d.world_seed); + d.loot.roll_entity(table, random, params) + } + None => Vec::new(), + } +} +/// `getBaseExperienceReward` (no vanilla enchantment changes mob experience). +pub fn base_experience(m: &mut Mob) -> i32 { + use Species as S; + let s = m.species(); + match s { + // Chicken.getBaseExperienceReward. + S::Chicken if m.extra.jockey => 10, + S::SulfurCube if m.is_baby() => 0, + S::SulfurCube => 1 + m.random.next_int_bound(2).unwrap_or(0), + // Hoglin / Piglin: the reward without the equipment bonus. + S::Hoglin | S::Piglin => xp_reward(m), + s if is_animal(s) || is_water_creature(s) => 1 + m.random.next_int_bound(3).unwrap_or(0), + _ => { + let mut reward = xp_reward(m); + // Zombie.getBaseExperienceReward: babies are worth 2.5 times as much. + if zombie_family(s) && m.is_baby() { + reward = (reward as f32 * 2.5) as i32; + } + if reward > 0 { + let mut result = reward; + for slot in SLOTS { + // EquipmentSlot.canIncreaseExperience: all but the saddle. + if slot != "saddle" && slot_item(m, slot).is_some() && drop_chance(m, slot) <= 1.0 { + result += 1 + m.random.next_int_bound(3).unwrap_or(0); + } + } + result + } else { + reward + } + } + } +} diff --git a/crates/horizon-client/src/mobs/species.rs b/crates/horizon-client/src/mobs/species.rs index 9954298b9..899666265 100644 --- a/crates/horizon-client/src/mobs/species.rs +++ b/crates/horizon-client/src/mobs/species.rs @@ -1443,7 +1443,6 @@ impl Def { | S::WitherSkeleton | S::ZombifiedPiglin | S::Zoglin - | S::Hoglin | S::Wither ), burns_in_day: matches!( diff --git a/crates/horizon-world/src/loot.rs b/crates/horizon-world/src/loot.rs index d36b00a79..b863e9659 100644 --- a/crates/horizon-world/src/loot.rs +++ b/crates/horizon-world/src/loot.rs @@ -1,10 +1,13 @@ -//! Container loot: `LootTable.fill` for chest-style loot tables (pools, +//! Loot tables: `LootTable.fill` for chest-style loot tables (pools, //! weighted entries, nested tables, item modifiers and conditions, the -//! stack splitter and the slot shuffle) with vanilla's random draw order. +//! stack splitter and the slot shuffle) and `LootTable.getRandomItems` for +//! entity loot (the victim, its killer, the damage source and the last +//! player to hurt it), with vanilla's random draw order. //! //! Items keep their id, count, damage, enchantments and potion. Exploration //! maps are kept as found (structure search is not run); conditions that -//! need an entity, tool or damage source fail, as they do for containers. +//! need an entity, tool or damage source fail when the context has none, as +//! they do for containers. use horizon_core::random::{LegacyRandom, RandomSource}; use serde_json::Value; use std::{ @@ -41,6 +44,10 @@ impl LootStack { pub fn is_empty(&self) -> bool { self.count <= 0 || self.item == "minecraft:air" } + /// `ItemStack.getCount`: 0 for an empty stack. + pub fn get_count(&self) -> i32 { + if self.is_empty() { 0 } else { self.count } + } } #[derive(Clone, Copy, Debug, Default)] @@ -59,6 +66,10 @@ struct Enchantment { weight: i32, min_cost: (i32, i32), max_cost: (i32, i32), + /// `slots`: the equipment slot groups the enchantment works in. + slots: Vec, + /// `effects` (equipment_drops and others). + effects: Value, } impl Enchantment { fn min_cost(&self, level: i32) -> i32 { @@ -79,6 +90,134 @@ pub struct LootData { enchantments: Vec, /// Raw tag files by (registry, tag id). tags: HashMap<(String, String), Vec>, + /// Smelting recipes in recipe id order: (ingredient, result, result count). + smelting: Vec<(Value, String, i32)>, +} + +/// An entity a loot context names (`this`, `attacker`, `direct_attacker`, +/// `attacking_player`): the facts entity predicates read. +#[derive(Clone, Debug, Default)] +pub struct LootEntity { + /// Entity type id (`minecraft:zombie`). + pub kind: String, + /// A `LivingEntity` (has equipment and enchantment levels). + pub living: bool, + /// `Entity.isOnFire` (fire-immune entities never are). + pub on_fire: bool, + pub baby: bool, + /// The entity it rides (`getVehicle`). + pub vehicle: Option>, + /// `AbstractCubeMob.getSize`. + pub cube_size: Option, + /// A sheep's colour name and whether it is sheared. + pub sheep: Option<(String, bool)>, + /// A raider: whether it is a captain (wears the ominous banner). + pub captain: Option, + /// A frog's variant id (`minecraft:warm`). + pub frog_variant: Option, + /// A charged creeper (`Creeper.isPowered`). + pub powered: bool, + /// Worn and held items by `EquipmentSlot` name (mainhand, offhand, + /// feet, legs, chest, head, body, saddle). + pub equipment: Vec<(String, LootStack)>, +} +impl LootEntity { + pub fn new(kind: &str) -> Self { + Self { + kind: kind.to_owned(), + living: true, + ..Self::default() + } + } + pub fn item(&self, slot: &str) -> Option<&LootStack> { + self.equipment + .iter() + .find(|(s, i)| s == slot && !i.is_empty()) + .map(|(_, i)| i) + } +} +/// A `DamageSource`: its damage type and the entities behind it. +#[derive(Clone, Debug, Default)] +pub struct LootDamage { + /// Damage type id (`minecraft:player_attack`). + pub kind: String, + /// `getEntity`: the attacker (the shooter of a projectile). + pub source: Option, + /// `getDirectEntity`: the projectile, or the attacker itself. + pub direct: Option, +} +/// The parameters of `LivingEntity.dropFromLootTable`. +#[derive(Clone, Debug, Default)] +pub struct EntityLootParams { + pub this: LootEntity, + pub damage: Option, + /// `LAST_DAMAGE_PLAYER`: set when a player killed the entity. + pub player: Option, + /// The killing player's luck. + pub luck: f32, +} +/// `EquipmentSlot.VALUES` order. +pub const EQUIPMENT_SLOTS: [&str; 8] = [ + "mainhand", "offhand", "feet", "legs", "chest", "head", "body", "saddle", +]; +/// `EquipmentSlotGroup.test`. +fn slot_in_group(slot: &str, group: &str) -> bool { + match group { + "any" => true, + "hand" => slot == "mainhand" || slot == "offhand", + "armor" => matches!(slot, "feet" | "legs" | "chest" | "head" | "body"), + _ => slot == group, + } +} +/// `LevelBasedValue.calculate`. +pub fn level_value(v: &Value, level: i32) -> f32 { + match v { + Value::Number(n) => n.as_f64().unwrap_or(0.) as f32, + Value::Object(_) => match v["type"].as_str().unwrap_or("") { + "minecraft:linear" => { + level_value(&v["base"], level) + + level_value(&v["per_level_above_first"], level) * (level - 1) as f32 + } + "minecraft:constant" => level_value(&v["value"], level), + "minecraft:clamped" => { + let value = level_value(&v["value"], level); + let min = v["min"].as_f64().unwrap_or(0.) as f32; + let max = v["max"].as_f64().unwrap_or(0.) as f32; + value.clamp(min, max) + } + "minecraft:fraction" => { + level_value(&v["numerator"], level) / level_value(&v["denominator"], level) + } + "minecraft:levels_squared" => { + (level * level) as f32 + v["added"].as_f64().unwrap_or(0.) as f32 + } + "minecraft:lookup" => { + let values = v["values"].as_array().map_or(&[][..], Vec::as_slice); + match values.get((level - 1).max(0) as usize) { + Some(x) if level >= 1 => x.as_f64().unwrap_or(0.) as f32, + _ => level_value(&v["fallback"], level), + } + } + _ => 0., + }, + _ => 0., + } +} +/// `MinMaxBounds.Ints.matches` (a number or `{min, max}`). +fn int_bounds(v: &Value, value: i32) -> bool { + match v { + Value::Null => true, + Value::Number(n) => n.as_i64() == Some(i64::from(value)), + Value::Object(o) => { + o.get("min") + .and_then(Value::as_i64) + .is_none_or(|m| i64::from(value) >= m) + && o.get("max") + .and_then(Value::as_i64) + .is_none_or(|m| i64::from(value) <= m) + } + _ => false, + } } fn load_dir(dir: &Path, prefix: &str, out: &mut HashMap) -> io::Result<()> { @@ -150,11 +289,25 @@ impl LootData { weight: e["weight"].as_i64().unwrap_or(1) as i32, min_cost: cost(&e["min_cost"]), max_cost: cost(&e["max_cost"]), + slots: e["slots"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect(), + effects: e["effects"].clone(), } }) .collect(); let mut tags = HashMap::new(); - for registry in ["item", "enchantment", "instrument"] { + for registry in [ + "item", + "enchantment", + "instrument", + "entity_type", + "damage_type", + ] { let mut raw = HashMap::new(); load_dir(&data.join("tags").join(registry), "", &mut raw)?; for (name, value) in raw { @@ -162,6 +315,20 @@ impl LootData { tags.insert((registry.to_owned(), name), values); } } + let mut recipes = HashMap::new(); + load_dir(&data.join("recipe"), "", &mut recipes)?; + let mut ids: Vec<&String> = recipes.keys().collect(); + ids.sort(); + let smelting = ids + .into_iter() + .map(|id| &recipes[id]) + .filter(|r| r["type"] == "minecraft:smelting") + .filter_map(|r| { + let result = r["result"]["id"].as_str()?.to_owned(); + let count = r["result"]["count"].as_i64().unwrap_or(1) as i32; + Some((r["ingredient"].clone(), result, count)) + }) + .collect(); Ok(Self { tables, modifiers, @@ -169,11 +336,82 @@ impl LootData { items, enchantments, tags, + smelting, }) } pub fn has_table(&self, table: &str) -> bool { self.tables.contains_key(table) } + /// The table's `random_sequence` (where `getRandomItems` draws from). + pub fn random_sequence(&self, table: &str) -> Option<&str> { + self.tables.get(table)?["random_sequence"].as_str() + } + pub fn max_stack(&self, item: &str) -> i32 { + self.facts(item).max_stack + } + pub fn max_damage(&self, item: &str) -> i32 { + self.facts(item).max_damage + } + /// Whether a registry tag (`entity_type`, `damage_type`, `item`...) holds `id`. + pub fn in_tag(&self, registry: &str, tag: &str, id: &str) -> bool { + self.tag(registry, tag).iter().any(|m| m == id) + } + /// `EnchantmentHelper.getEnchantmentLevel(enchantment, entity)`: the best + /// level on the items in the enchantment's slots. + pub fn enchantment_level(&self, enchantment: &str, entity: &LootEntity) -> i32 { + let Some(e) = self.enchantments.iter().find(|e| e.name == enchantment) else { + return 0; + }; + if !entity.living { + return 0; + } + EQUIPMENT_SLOTS + .iter() + .filter(|slot| e.slots.iter().any(|g| slot_in_group(slot, g))) + .filter_map(|slot| entity.item(slot)) + .map(|stack| item_level(stack, enchantment)) + .max() + .unwrap_or(0) + } + /// Whether an item carries an enchantment with `prevent_equipment_drop`. + pub fn prevents_equipment_drop(&self, stack: &LootStack) -> bool { + stack.enchantments.iter().any(|(name, _)| { + self.enchantments.iter().any(|e| { + &e.name == name && !e.effects["minecraft:prevent_equipment_drop"].is_null() + }) + }) + } + /// `EnchantmentHelper.processEquipmentDropChance`: the victim's and the + /// attacker's `equipment_drops` effects (Looting) applied to `chance`. + pub fn equipment_drop_chance(&self, params: &EntityLootParams, chance: f32) -> f32 { + // Enchantment.damageContext: no luck and no killing player. + let damage_params = EntityLootParams { + this: params.this.clone(), + damage: params.damage.clone(), + player: None, + luck: 0.0, + }; + let mut c = Context { + data: self, + random: LegacyRandom::new(0), + biome: None, + visited: Vec::new(), + luck: 0.0, + open_water: None, + entity: Some(&damage_params), + }; + let mut chance = chance; + c.equipment_drops(¶ms.this, "victim", &mut chance); + if let Some(attacker) = params + .damage + .as_ref() + .and_then(|d| d.source.as_ref()) + .filter(|a| a.living) + { + c.equipment_drops(attacker, "attacker", &mut chance); + } + chance + } /// Tag members in tag order (nested tags expanded in place, duplicates /// dropped). fn tag(&self, registry: &str, name: &str) -> Vec { @@ -246,12 +484,54 @@ impl LootData { visited: Vec::new(), luck, open_water, + entity: None, }; let mut items = Vec::new(); c.table_raw(table, json, &mut |_, stack| items.push(stack)); *random = c.random; items } + /// LootTable.getRandomItems for an entity context: the generated stacks + /// after the stack splitter, in order. `random` is the table's random + /// sequence (or the level random) and is advanced. + pub fn roll_entity( + &self, + table: &str, + random: &mut R, + params: &EntityLootParams, + ) -> Vec { + let Some(json) = self.tables.get(table) else { + return Vec::new(); + }; + let mut c = Context { + data: self, + random: random.clone(), + biome: None, + visited: Vec::new(), + luck: params.luck, + open_water: None, + entity: Some(params), + }; + let mut items = Vec::new(); + c.table_raw(table, json, &mut |c, stack| c.data.split(stack, &mut items)); + *random = c.random; + items + } + /// LootTable.createStackSplitter (every item is enabled). + fn split(&self, stack: LootStack, items: &mut Vec) { + let max = self.facts(&stack.item).max_stack.max(1); + if stack.count < max { + items.push(stack); + } else { + let mut count = stack.count; + while count > 0 { + let mut copy = stack.clone(); + copy.count = max.min(count); + count -= copy.count; + items.push(copy); + } + } + } /// LootTable.fill into an empty container of `slots` slots with /// `RandomSource.create(seed)`; `biome` is the container's biome for /// location checks (None: no origin, checks fail). @@ -273,23 +553,10 @@ impl LootData { visited: Vec::new(), luck: 0.0, open_water: None, + entity: None, }; let mut items = Vec::new(); - c.table_raw(table, json, &mut |c, stack| { - // LootTable.createStackSplitter (every item is enabled). - let max = c.data.facts(&stack.item).max_stack.max(1); - if stack.count < max { - items.push(stack); - } else { - let mut count = stack.count; - while count > 0 { - let mut copy = stack.clone(); - copy.count = max.min(count); - count -= copy.count; - items.push(copy); - } - } - }); + c.table_raw(table, json, &mut |c, stack| c.data.split(stack, &mut items)); let random = &mut c.random; let mut available: Vec = (0..slots).collect(); shuffle(&mut available, random); @@ -302,15 +569,23 @@ impl LootData { } } +/// The level of one enchantment on a stack (its `enchantments` component). +fn item_level(stack: &LootStack, enchantment: &str) -> i32 { + stack + .enchantments + .iter() + .find(|(n, _)| n == enchantment) + .map_or(0, |(_, l)| *l) +} /// Util.shuffle. -fn shuffle(list: &mut [T], random: &mut LegacyRandom) { +fn shuffle(list: &mut [T], random: &mut impl RandomSource) { for i in (2..=list.len()).rev() { let j = random.next_int_bound(i as i32).unwrap_or(0) as usize; list.swap(i - 1, j); } } /// Mth.nextInt. -fn next_int(random: &mut LegacyRandom, min: i32, max: i32) -> i32 { +fn next_int(random: &mut impl RandomSource, min: i32, max: i32) -> i32 { if min >= max { min } else { @@ -353,19 +628,136 @@ fn shuffle_and_split(result: &mut Vec, slots: usize, random: &mut Leg shuffle(result, random); } -struct Context<'a> { +struct Context<'a, R> { data: &'a LootData, - random: LegacyRandom, + random: R, biome: Option<&'a str>, visited: Vec, /// LootContext.getLuck. luck: f32, /// A fishing hook's `is_open_water` for `entity_properties` (None: no entity). open_water: Option, + /// The entity, damage source and killer parameters. + entity: Option<&'a EntityLootParams>, } -type Sink<'s> = dyn FnMut(&mut Context<'_>, LootStack) + 's; +type Sink<'s, R> = dyn FnMut(&mut Context<'_, R>, LootStack) + 's; -impl Context<'_> { +impl Context<'_, R> { + /// A `LootContext.EntityTarget` parameter. + fn target(&self, name: &str) -> Option<&LootEntity> { + let p = self.entity?; + match name { + "this" => Some(&p.this), + "attacker" => p.damage.as_ref()?.source.as_ref(), + "direct_attacker" => p.damage.as_ref()?.direct.as_ref(), + "attacking_player" => p.player.as_ref(), + _ => None, + } + } + /// The `ATTACKING_ENTITY` parameter when it is a living entity. + fn living_attacker(&self) -> Option<&LootEntity> { + self.target("attacker").filter(|a| a.living) + } + /// The `equipment_drops` effects on one entity's equipment + /// (`runIterationOnEquipment`), for the given `enchanted` target. + fn equipment_drops(&mut self, holder: &LootEntity, enchanted: &str, chance: &mut f32) { + let data = self.data; + for slot in EQUIPMENT_SLOTS { + let Some(stack) = holder.item(slot) else { + continue; + }; + for (name, level) in &stack.enchantments { + let Some(e) = data.enchantments.iter().find(|e| &e.name == name) else { + continue; + }; + if !e.slots.iter().any(|g| slot_in_group(slot, g)) { + continue; + } + for effect in e.effects["minecraft:equipment_drops"] + .as_array() + .into_iter() + .flatten() + { + if effect["enchanted"].as_str() != Some(enchanted) + || effect["affected"].as_str().unwrap_or("victim") != "victim" + { + continue; + } + if !effect["requirements"].is_null() && !self.condition(&effect["requirements"]) { + continue; + } + let value = level_value(&effect["effect"]["value"], *level); + *chance = match effect["effect"]["type"].as_str().unwrap_or("") { + "minecraft:add" => *chance + value, + "minecraft:multiply" => *chance * value, + "minecraft:set" => value, + _ => *chance, + }; + } + } + } + } + /// EntityPredicate.matches (false without an entity). + fn entity_matches(&self, p: &Value, e: Option<&LootEntity>) -> bool { + let Some(e) = e else { return false }; + let Some(parts) = p.as_object() else { + return true; + }; + let data = self.data; + parts.iter().all(|(key, v)| match key.as_str() { + "minecraft:entity_type" => match v.as_str() { + Some(s) => match s.strip_prefix('#') { + Some(tag) => data.in_tag("entity_type", tag, &e.kind), + None => s == e.kind, + }, + None => v + .as_array() + .is_some_and(|a| a.iter().any(|x| x.as_str() == Some(&e.kind))), + }, + "minecraft:flags" => v.as_object().into_iter().flatten().all(|(flag, want)| { + let want = want.as_bool().unwrap_or(false); + match flag.as_str() { + "is_on_fire" => e.on_fire == want, + // EntityFlagsPredicate: only living entities have an age. + "is_baby" => !e.living || e.baby == want, + "is_fall_flying" => !e.living || !want, + _ => !want, + } + }), + "minecraft:equipment" => { + e.living + && v.as_object().into_iter().flatten().all(|(slot, item)| { + e.item(slot) + .is_some_and(|stack| self.item_matches(item, stack)) + }) + } + "minecraft:components" => v.as_object().into_iter().flatten().all(|(c, want)| { + match c.as_str() { + "minecraft:sheep/color" => e + .sheep + .as_ref() + .is_some_and(|(color, _)| want.as_str() == Some(color)), + "minecraft:frog/variant" => { + e.frog_variant.is_some() && want.as_str() == e.frog_variant.as_deref() + } + _ => false, + } + }), + "minecraft:type_specific/sheep" => e.sheep.as_ref().is_some_and(|(_, sheared)| { + v["sheared"].as_bool().is_none_or(|w| w == *sheared) + }), + "minecraft:type_specific/cube_mob" => { + e.cube_size.is_some_and(|size| int_bounds(&v["size"], size)) + } + // RaiderPredicate: no raid is running here. + "minecraft:type_specific/raider" => e.captain.is_some_and(|captain| { + !v["has_raid"].as_bool().unwrap_or(false) + && captain == v["is_captain"].as_bool().unwrap_or(false) + }), + "minecraft:vehicle" => self.entity_matches(v, e.vehicle.as_deref()), + _ => false, + }) + } fn int(&mut self, v: &Value) -> i32 { match v { Value::Number(n) => n.as_i64().unwrap_or(0) as i32, @@ -426,16 +818,62 @@ impl Context<'_> { .into_iter() .flatten() .any(|t| self.condition(t)), + "minecraft:entity_properties" if self.entity.is_some() => { + let target = self.target(c["entity"].as_str().unwrap_or("this")); + c["predicate"].is_null() || self.entity_matches(&c["predicate"], target) + } // FishingHookPredicate: the only entity property a hook has. "minecraft:entity_properties" => { - let fishing = &c["predicate"]["type_specific"]; - match (self.open_water, fishing["type"].as_str()) { - (Some(open), Some("minecraft:fishing_hook")) => fishing["in_open_water"] + let predicate = &c["predicate"]; + let fishing = &predicate["minecraft:type_specific/fishing_hook"]; + let only_hook = predicate.as_object().is_some_and(|o| o.len() == 1); + match self.open_water { + Some(open) if only_hook && fishing.is_object() => fishing["in_open_water"] .as_bool() .is_none_or(|want| want == open), _ => false, } } + "minecraft:killed_by_player" => self.entity.is_some_and(|p| p.player.is_some()), + "minecraft:random_chance_with_enchanted_bonus" => { + let level = self.living_attacker().map_or(0, |a| { + data.enchantment_level(c["enchantment"].as_str().unwrap_or(""), a) + }); + let chance = if level > 0 { + level_value(&c["enchanted_chance"], level) + } else { + c["unenchanted_chance"].as_f64().unwrap_or(0.) as f32 + }; + self.random.next_float() < chance + } + // DamageSourcePredicate (false without a damage source). + "minecraft:damage_source_properties" => { + let Some(damage) = self.entity.and_then(|p| p.damage.as_ref()) else { + return false; + }; + let p = &c["predicate"]; + let tags_ok = p["tags"].as_array().into_iter().flatten().all(|t| { + let id = t["id"].as_str().unwrap_or(""); + let has = match id.strip_prefix('#') { + Some(tag) => data.in_tag("damage_type", tag, &damage.kind), + None => id == damage.kind, + }; + has == t["expected"].as_bool().unwrap_or(false) + }); + tags_ok + && (p["direct_entity"].is_null() + || self.entity_matches(&p["direct_entity"], damage.direct.as_ref())) + && (p["source_entity"].is_null() + || self.entity_matches(&p["source_entity"], damage.source.as_ref())) + && p["is_direct"].as_bool().is_none_or(|want| { + let direct = match (&damage.source, &damage.direct) { + (Some(a), Some(b)) => a.kind == b.kind, + (None, None) => true, + _ => false, + }; + direct == want + }) + } "minecraft:random_chance" => { let chance = self.float(&c["chance"]); self.random.next_float() < chance @@ -489,7 +927,7 @@ impl Context<'_> { } "minecraft:set_count" => { let base = if f["add"].as_bool() == Some(true) { - stack.count + stack.get_count() } else { 0 }; @@ -497,12 +935,14 @@ impl Context<'_> { } "minecraft:limit_count" => { let limit = &f["limit"]; + let mut count = stack.get_count(); if let Some(min) = limit["min"].as_i64() { - stack.count = stack.count.max(min as i32); + count = count.max(min as i32); } if let Some(max) = limit["max"].as_i64() { - stack.count = stack.count.min(max as i32); + count = count.min(max as i32); } + stack.count = count; } "minecraft:set_damage" => { let max = data.facts(&stack.item).max_damage; @@ -611,19 +1051,74 @@ impl Context<'_> { stack = self.modify(branch, stack); } "minecraft:discard" => stack.count = 0, + "minecraft:enchanted_count_increase" => { + if let Some(attacker) = self.living_attacker() { + let level = + data.enchantment_level(f["enchantment"].as_str().unwrap_or(""), attacker); + if level != 0 { + let addition = level as f32 * self.float(&f["count"]); + // ItemStack.grow(Math.round(addition)). + stack.count = stack.get_count() + (addition + 0.5).floor() as i32; + let limit = f["limit"].as_i64().unwrap_or(0) as i32; + if limit > 0 && !stack.is_empty() && stack.count > limit { + stack.count = limit; + } + } + } + } + "minecraft:furnace_smelt" => { + if !stack.is_empty() + && let Some((_, result, count)) = data + .smelting + .iter() + .find(|(ingredient, _, _)| data.item_in(&stack.item, ingredient)) + { + let input = if f["use_input_count"].as_bool().unwrap_or(true) { + stack.count + } else { + 1 + }; + let mut smelted = LootStack::new(result); + smelted.count = (input * count).min(data.facts(result).max_stack); + stack = smelted; + } + } // Names, lore, components and other data without random draws. _ => {} } stack } - /// ItemPredicate subset used by filtered modifiers. + /// ItemPredicate subset used by filtered modifiers and equipment. fn item_matches(&self, p: &Value, stack: &LootStack) -> bool { if !p["items"].is_null() && !self.data.item_in(&stack.item, &p["items"]) { return false; } + if !int_bounds(&p["count"], stack.count) { + return false; + } if p["predicates"].get("minecraft:map_id").is_some() && !stack.map { return false; } + // EnchantmentsPredicate: every entry must hold. + if let Some(list) = p["predicates"]["minecraft:enchantments"].as_array() { + let data = self.data; + let ok = list.iter().all(|e| { + let levels = &e["levels"]; + match &e["enchantments"] { + Value::Null => stack + .enchantments + .iter() + .any(|(_, l)| int_bounds(levels, *l)), + set => data.holder_set("enchantment", set).iter().any(|name| { + let level = item_level(stack, name); + level != 0 && int_bounds(levels, level) + }), + } + }); + if !ok { + return false; + } + } true } /// EnchantmentHelper.selectEnchantment. @@ -662,7 +1157,7 @@ impl Context<'_> { if available.is_empty() { return results; } - let pick = |random: &mut LegacyRandom, list: &[(usize, i32)]| -> Option<(usize, i32)> { + let pick = |random: &mut R, list: &[(usize, i32)]| -> Option<(usize, i32)> { let total: i32 = list.iter().map(|&(i, _)| data.enchantments[i].weight).sum(); if total <= 0 { return None; @@ -702,7 +1197,7 @@ impl Context<'_> { .contains(&ea.name) } /// LootTable.getRandomItemsRaw. - fn table_raw(&mut self, name: &str, table: &Value, sink: &mut Sink<'_>) { + fn table_raw(&mut self, name: &str, table: &Value, sink: &mut Sink<'_, R>) { if self.visited.iter().any(|v| v == name) { return; } @@ -729,14 +1224,15 @@ impl Context<'_> { self.visited.pop(); } /// LootPool.addRandomItem. - fn add_random_item(&mut self, pool: &Value, sink: &mut Sink<'_>) { - let mut valid: Vec<&Value> = Vec::new(); + fn add_random_item(&mut self, pool: &Value, sink: &mut Sink<'_, R>) { + let mut valid: Vec> = Vec::new(); for entry in pool["entries"].as_array().into_iter().flatten() { self.expand(entry, &mut valid); } // EntryBase.getWeight: max(floor(weight + quality * luck), 0). let luck = self.luck; - let weight = |e: &Value| { + let weight = |c: &Choice<'_>| { + let e = c.entry; let w = e["weight"].as_i64().unwrap_or(1) as f32 + e["quality"].as_i64().unwrap_or(0) as f32 * luck; w.floor().max(0.0) as i32 @@ -746,21 +1242,21 @@ impl Context<'_> { return; } let chosen = if valid.len() == 1 { - valid[0] + valid.swap_remove(0) } else { let mut index = self.random.next_int_bound(total).unwrap_or(0); - let Some(e) = valid.iter().find(|e| { + let Some(at) = valid.iter().position(|e| { index -= weight(e); index < 0 }) else { return; }; - e + valid.swap_remove(at) }; - self.create(chosen, sink); + self.create(&chosen, sink); } /// LootPoolEntryContainer.expand: the singleton entries that can run. - fn expand<'v>(&mut self, entry: &'v Value, out: &mut Vec<&'v Value>) -> bool { + fn expand<'v>(&mut self, entry: &'v Value, out: &mut Vec>) -> bool { if !entry["condition"].is_null() && !self.condition(&entry["condition"]) { return false; } @@ -783,17 +1279,35 @@ impl Context<'_> { } "minecraft:item" | "minecraft:empty" | "minecraft:loot_table" => { if entry["weight"].as_i64().unwrap_or(1) > 0 { - out.push(entry); + out.push(Choice { entry, item: None }); } true } + // TagEntry: one choice per item when expanded, else one for all. + "minecraft:tag" => { + if entry["expand"].as_bool().unwrap_or(false) { + let items = self.data.holder_set("item", &entry["items"]); + for item in items { + if entry["weight"].as_i64().unwrap_or(1) > 0 { + out.push(Choice { entry, item: Some(item) }); + } + } + true + } else { + if entry["weight"].as_i64().unwrap_or(1) > 0 { + out.push(Choice { entry, item: None }); + } + true + } + } _ => false, } } /// LootPoolEntry.createItemStack with the entry's modifier. - fn create(&mut self, entry: &Value, sink: &mut Sink<'_>) { + fn create(&mut self, choice: &Choice<'_>, sink: &mut Sink<'_, R>) { + let entry = choice.entry; let modifier = &entry["modifier"]; - let mut out = |c: &mut Context<'_>, stack: LootStack| { + let mut out = |c: &mut Context<'_, R>, stack: LootStack| { let stack = c.modify(modifier, stack); sink(c, stack); }; @@ -802,6 +1316,14 @@ impl Context<'_> { let stack = LootStack::new(entry["name"].as_str().unwrap_or("minecraft:air")); out(self, stack); } + "minecraft:tag" => match &choice.item { + Some(item) => out(self, LootStack::new(item)), + None => { + for item in self.data.holder_set("item", &entry["items"]) { + out(self, LootStack::new(&item)); + } + } + }, "minecraft:loot_table" => match &entry["value"] { Value::String(name) => { if let Some(table) = self.data.tables.get(name) { @@ -815,6 +1337,11 @@ impl Context<'_> { } } } +/// A pool entry that can be chosen (an expanded tag entry names its item). +struct Choice<'v> { + entry: &'v Value, + item: Option, +} fn enchant(stack: &mut LootStack, name: &str, level: i32) { match stack.enchantments.iter_mut().find(|(n, _)| n == name) { Some(slot) => slot.1 = level, diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityDeathLootOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityDeathLootOracle.java new file mode 100644 index 000000000..bffe88e56 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityDeathLootOracle.java @@ -0,0 +1,320 @@ +package dev.horizonlab.parity; + +import com.mojang.authlib.GameProfile; +import java.io.PrintWriter; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import java.util.function.Predicate; +import net.minecraft.SharedConstants; +import net.minecraft.core.*; +import net.minecraft.core.component.DataComponents; +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.resources.ResourceKey; +import net.minecraft.server.Bootstrap; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.ReloadableServerRegistries; +import net.minecraft.server.ReloadableServerResources; +import net.minecraft.server.RegistryLayer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.packs.PackType; +import net.minecraft.server.packs.repository.ServerPacksSource; +import net.minecraft.server.packs.resources.MultiPackResourceManager; +import net.minecraft.tags.TagLoader; +import net.minecraft.util.RandomSource; +import net.minecraft.world.DifficultyInstance; +import net.minecraft.world.RandomSequences; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.damagesource.DamageSources; +import net.minecraft.world.entity.*; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.DyeColor; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.entity.EntityTypeTest; +import net.minecraft.world.level.gamerules.GameRules; +import net.minecraft.world.level.levelgen.WorldGenSettings; +import net.minecraft.world.level.levelgen.WorldOptions; +import net.minecraft.world.phys.AABB; + +/** + * Original oracle: entity death drops. Each input line describes a victim, its + * equipment and state, a killer and a damage source; the oracle creates the + * real entities on a stand-in ServerLevel (whose addFreshEntity records the + * spawned item entities and experience orbs) and runs LivingEntity.die's drop + * step: the source entity's killedEntity hook, then dropAllDeathLoot (loot + * table with the world's random sequence, dropCustomDeathLoot with the entity + * random, dropEquipment, dropExperience). Loot table randoms come from a fresh + * RandomSequences per case; each case kills `kills` identical victims in turn. + */ +public final class VanillaEntityDeathLootOracle { + static Object unsafe; + static Method allocate, putObject, objectFieldOffset; + + static Object alloc(Class c) throws Exception { return allocate.invoke(unsafe, c); } + + static void put(Object target, Class owner, String field, Object value) throws Exception { + Field f = owner.getDeclaredField(field); + long offset = (long) objectFieldOffset.invoke(unsafe, f); + putObject.invoke(unsafe, target, offset, value); + } + + static final class Lvl extends ServerLevel { + Lvl() { super(null, null, null, null, null, null, false, 0L, List.of(), false); } + MinecraftServer fake; + RegistryAccess registries; + GameRules rules; + List out; + int next = 1; + @Override public MinecraftServer getServer() { return fake; } + @Override public RegistryAccess registryAccess() { return registries; } + @Override public net.minecraft.world.Difficulty getDifficulty() { return net.minecraft.world.Difficulty.NORMAL; } + @Override public long getGameTime() { return 0L; } + @Override public int getNextEntityId() { return next++; } + @Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags(); } + @Override public GameRules getGameRules() { return rules; } + @Override public boolean addFreshEntity(Entity entity) { + if (entity instanceof ItemEntity item) out.add("drop " + stack(item.getItem())); + else if (entity instanceof ExperienceOrb orb) out.add("orb " + orb.getValue()); + else out.add("entity " + BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType())); + return true; + } + @Override public List getEntities(EntityTypeTest type, AABB bb, Predicate selector) { return new ArrayList<>(); } + net.minecraft.world.attribute.EnvironmentAttributeSystem attributes; + @Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes() { return attributes; } + @Override public int getSeaLevel() { return 63; } + @Override public net.minecraft.world.entity.raid.Raid getRaidAt(BlockPos pos) { return null; } + @Override public net.minecraft.world.level.BlockGetter getChunkForCollisions(int chunkX, int chunkZ) { return null; } + @Override public List getEntityCollisions(Entity source, AABB area) { return List.of(); } + @Override public DifficultyInstance getCurrentDifficultyAt(BlockPos pos) { return new DifficultyInstance(net.minecraft.world.Difficulty.NORMAL, 0L, 0L, 0.0F); } + } + + static final class OraclePlayer extends Player { + OraclePlayer(Level level) { super(level, new GameProfile(new UUID(1L, 2L), "oracle")); } + @Override public GameType gameMode() { return GameType.SURVIVAL; } + @Override public net.minecraft.world.item.component.ResolvableProfile getProfile() { return net.minecraft.world.item.component.ResolvableProfile.createResolved(this.getGameProfile()); } + } + + static String stack(ItemStack stack) { + StringBuilder line = new StringBuilder(BuiltInRegistries.ITEM.getKey(stack.getItem()) + " " + stack.getCount()); + if (stack.getDamageValue() != 0) line.append(" damage=").append(stack.getDamageValue()); + var enchantments = stack.getOrDefault(DataComponents.ENCHANTMENTS, net.minecraft.world.item.enchantment.ItemEnchantments.EMPTY); + for (var e : enchantments.entrySet()) line.append(" ench=").append(e.getKey().unwrapKey().get().identifier()).append(':').append(e.getIntValue()); + var potion = stack.get(DataComponents.POTION_CONTENTS); + if (potion != null && potion.potion().isPresent()) line.append(" potion=").append(potion.potion().get().unwrapKey().get().identifier()); + var ominous = stack.get(DataComponents.OMINOUS_BOTTLE_AMPLIFIER); + if (ominous != null) line.append(" ominous=").append(ominous.value()); + return line.toString(); + } + + static Map parse(String line) { + Map m = new LinkedHashMap<>(); + for (String token : line.trim().split("\\s+")) { + int eq = token.indexOf('='); + if (eq < 0) m.put("name", token); else m.put(token.substring(0, eq), token.substring(eq + 1)); + } + return m; + } + + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe"); + unsafeField.setAccessible(true); + unsafe = unsafeField.get(null); + allocate = unsafe.getClass().getMethod("allocateInstance", Class.class); + putObject = unsafe.getClass().getMethod("putObject", Object.class, long.class, Object.class); + objectFieldOffset = unsafe.getClass().getMethod("objectFieldOffset", Field.class); + + 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(); + var worldLayers = layers.replaceFrom(RegistryLayer.WORLD, world); + var loaded = ReloadableServerRegistries.reload(worldLayers, staticTags, resources, Runnable::run).join(); + HolderLookup.Provider lookup = loaded.lookupWithUpdatedTags(); + var components = BuiltInRegistries.DATA_COMPONENT_INITIALIZERS.build(lookup); + staticTags.forEach(Registry.PendingTags::apply); + components.forEach(net.minecraft.core.component.DataComponentInitializers.PendingComponents::apply); + RegistryAccess access = loaded.layers().compositeAccess(); + + // A server that only answers reloadableRegistries, getRandomSequence and debug subscribers. + MinecraftServer server = (MinecraftServer) alloc(net.minecraft.server.dedicated.DedicatedServer.class); + put(server, MinecraftServer.class, "debugSubscribers", alloc(net.minecraft.util.debug.ServerDebugSubscribers.class)); + ReloadableServerResources managers = (ReloadableServerResources) alloc(ReloadableServerResources.class); + put(managers, ReloadableServerResources.class, "fullRegistryHolder", new ReloadableServerRegistries.Holder(lookup)); + Class holderRecord = Class.forName("net.minecraft.server.MinecraftServer$ReloadableResources"); + Constructor rr = holderRecord.getDeclaredConstructors()[0]; + rr.setAccessible(true); + put(server, MinecraftServer.class, "resources", rr.newInstance(null, managers)); + var recipes = new net.minecraft.world.item.crafting.RecipeManager(lookup); + recipes.finalizeRecipeLoading(net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags()); + put(managers, ReloadableServerResources.class, "recipes", recipes); + put(server, MinecraftServer.class, "scoreboard", new net.minecraft.server.ServerScoreboard(server)); + + Lvl level = (Lvl) alloc(Lvl.class); + level.fake = server; + level.registries = access; + put(level, ServerLevel.class, "server", server); + level.attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().build(); + level.rules = new GameRules(net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags()); + put(level, Level.class, "damageSources", new DamageSources(access)); + put(level, Level.class, "random", RandomSource.create(0L)); + Method dropAll = LivingEntity.class.getDeclaredMethod("dropAllDeathLoot", ServerLevel.class, DamageSource.class); + dropAll.setAccessible(true); + var enchantments = access.lookupOrThrow(Registries.ENCHANTMENT); + + if (args.length > 2 && args[2].equals("facts")) { + // Per-type facts the death step reads (a debugging aid, not compared). + Field xp = Mob.class.getDeclaredField("xpReward"); + xp.setAccessible(true); + try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) { + for (var type : BuiltInRegistries.ENTITY_TYPE) { + Entity e; + try { e = type.create(level, EntitySpawnReason.LOAD); } catch (Throwable t) { continue; } + if (!(e instanceof Mob mob)) continue; + StringBuilder sb = new StringBuilder(BuiltInRegistries.ENTITY_TYPE.getKey(type).toString()); + sb.append(" monster=").append(e instanceof net.minecraft.world.entity.monster.Monster).append(" xp=").append(xp.get(mob)) + .append(" baby=").append(mob.isBaby()).append(" class=").append(e.getClass().getSimpleName()) + .append(" animal=").append(e instanceof net.minecraft.world.entity.animal.Animal) + .append(" agwater=").append(e instanceof net.minecraft.world.entity.animal.AgeableWaterCreature) + .append(" water=").append(e instanceof net.minecraft.world.entity.animal.fish.WaterAnimal) + .append(" ageable=").append(e instanceof AgeableMob); + mob.setBaby(true); + sb.append(" canbaby=").append(mob.isBaby()); + for (EquipmentSlot slot : EquipmentSlot.VALUES) if (mob.getDropChances().byEquipment(slot) != 0.085F) sb.append(' ').append(slot.getName()).append('=').append(mob.getDropChances().byEquipment(slot)); + w.println(sb); + } + } + System.exit(0); + } + List lines = Files.readAllLines(Path.of(args[0])); + try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) { + for (String raw : lines) { + if (raw.isBlank() || raw.startsWith("#")) continue; + Map c = parse(raw); + w.println("== " + c.get("name")); + List out = new ArrayList<>(); + level.out = out; + try { + long worldSeed = Long.parseLong(c.getOrDefault("seed", "0")); + put(server, MinecraftServer.class, "worldGenSettings", new WorldGenSettings(new WorldOptions(worldSeed, false, false), null)); + put(server, MinecraftServer.class, "randomSequences", new RandomSequences()); + int kills = Integer.parseInt(c.getOrDefault("kills", "1")); + long rand = Long.parseLong(c.getOrDefault("rand", "0")); + for (int k = 0; k < kills; k++) { + out.add("kill " + k); + run(level, access, enchantments, c, rand + k, dropAll); + } + } catch (Throwable t) { + Throwable cause = t instanceof InvocationTargetException ite ? ite.getCause() : t; + StringBuilder trace = new StringBuilder("error " + cause); + if (System.getenv("ORACLE_TRACE") != null) for (var frame : cause.getStackTrace()) trace.append("\n at ").append(frame); + out.add(trace.toString()); + } + out.forEach(w::println); + } + } + System.exit(0); + } + + static ItemStack item(HolderLookup.RegistryLookup enchantments, String spec) { + // id[;enchantment:level...] + String[] parts = spec.split(";"); + ItemStack stack = new ItemStack(BuiltInRegistries.ITEM.getValue(Identifier.parse(parts[0]))); + for (int i = 1; i < parts.length; i++) { + int colon = parts[i].lastIndexOf(':'); + String name = parts[i].substring(0, colon); + if (!name.contains(":")) name = "minecraft:" + name; + stack.enchant(enchantments.getOrThrow(ResourceKey.create(Registries.ENCHANTMENT, Identifier.parse(name))), Integer.parseInt(parts[i].substring(colon + 1))); + } + return stack; + } + + static Entity create(Lvl level, String id) { + EntityType type = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(id)); + return type.create(level, EntitySpawnReason.LOAD); + } + + @SuppressWarnings("unchecked") + static void run(Lvl level, RegistryAccess access, HolderLookup.RegistryLookup enchantments, + Map c, long rand, Method dropAll) throws Exception { + LivingEntity victim = (LivingEntity) create(level, c.get("type")); + victim.setPos(0.5, 64.0, 0.5); + if (c.containsKey("baby") && victim instanceof Mob mob) mob.setBaby(c.get("baby").equals("1")); + if (c.getOrDefault("fire", "0").equals("1")) victim.setRemainingFireTicks(100); + if (c.containsKey("size")) victim.getClass().getMethod("setSize", int.class, boolean.class).invoke(victim, Integer.parseInt(c.get("size")), true); + if (c.containsKey("color") && victim instanceof net.minecraft.world.entity.animal.sheep.Sheep sheep) sheep.setColor(DyeColor.byName(c.get("color"), DyeColor.WHITE)); + if (c.getOrDefault("sheared", "0").equals("1") && victim instanceof net.minecraft.world.entity.animal.sheep.Sheep sheep) sheep.setSheared(true); + if (c.getOrDefault("leader", "0").equals("1")) ((net.minecraft.world.entity.monster.PatrollingMonster) victim).setPatrolLeader(true); + if (c.getOrDefault("captain", "0").equals("1")) + victim.setItemSlot(EquipmentSlot.HEAD, net.minecraft.world.entity.raid.Raid.getOminousBannerInstance(access.lookupOrThrow(Registries.BANNER_PATTERN))); + for (EquipmentSlot slot : EquipmentSlot.VALUES) { + String spec = c.get(slot.getName()); + if (spec != null) victim.setItemSlot(slot, item(enchantments, spec)); + String chance = c.get("chance_" + slot.getName()); + if (chance != null && victim instanceof Mob mob) mob.setDropChance(slot, Float.parseFloat(chance)); + } + if (c.containsKey("vehicle")) { + Entity vehicle = create(level, c.get("vehicle")); + vehicle.setPos(0.5, 64.0, 0.5); + if (!victim.startRiding(vehicle, true, false)) throw new IllegalStateException("could not ride"); + } + // Killer and damage source. + Player player = null; + LivingEntity killer = null; + String killerId = c.getOrDefault("killer", "none"); + if (killerId.equals("player") || c.getOrDefault("pkill", "0").equals("1")) { + player = new OraclePlayer(level); + player.setPos(2.5, 64.0, 0.5); + if (c.containsKey("luck")) player.getAttribute(Attributes.LUCK).setBaseValue(Double.parseDouble(c.get("luck"))); + if (killerId.equals("player") && c.containsKey("weapon")) player.setItemSlot(EquipmentSlot.MAINHAND, item(enchantments, c.get("weapon"))); + } + if (killerId.equals("player")) killer = player; + else if (!killerId.equals("none")) { + killer = (LivingEntity) create(level, killerId); + killer.setPos(2.5, 64.0, 0.5); + if (c.containsKey("weapon")) killer.setItemSlot(EquipmentSlot.MAINHAND, item(enchantments, c.get("weapon"))); + if (c.containsKey("frog")) killer.setComponent(DataComponents.FROG_VARIANT, + access.lookupOrThrow(Registries.FROG_VARIANT).getOrThrow(ResourceKey.create(Registries.FROG_VARIANT, Identifier.parse(c.get("frog"))))); + if (c.getOrDefault("charged", "0").equals("1")) { + Field powered = net.minecraft.world.entity.monster.Creeper.class.getDeclaredField("DATA_IS_POWERED"); + powered.setAccessible(true); + killer.getEntityData().set((net.minecraft.network.syncher.EntityDataAccessor) powered.get(null), true); + } + } + if (player != null && c.getOrDefault("pkill", killerId.equals("player") ? "1" : "0").equals("1")) victim.setLastHurtByPlayer(player, 100); + DamageSources sources = level.damageSources(); + DamageSource source = switch (c.getOrDefault("source", "attack")) { + case "attack" -> killer == null ? sources.generic() : killer instanceof Player p ? sources.playerAttack(p) : sources.mobAttack(killer); + case "arrow" -> { + var arrow = new net.minecraft.world.entity.projectile.arrow.Arrow(EntityTypes.ARROW, level); + arrow.setPos(1.5, 64.0, 0.5); + yield sources.arrow(arrow, killer); + } + case "fireball" -> { + var fireball = new net.minecraft.world.entity.projectile.hurtingprojectile.LargeFireball(EntityTypes.FIREBALL, level); + fireball.setPos(1.5, 64.0, 0.5); + yield sources.fireball(fireball, killer); + } + case "explosion" -> sources.explosion(killer, killer); + case "lightning" -> sources.lightningBolt(); + case "fire" -> sources.onFire(); + default -> sources.generic(); + }; + victim.getRandom().setSeed(rand); + Entity sourceEntity = source.getEntity(); + if (sourceEntity == null || sourceEntity.killedEntity(level, victim, source)) dropAll.invoke(victim, level, source); + } +} diff --git a/tools/test_entity_death_loot_parity.py b/tools/test_entity_death_loot_parity.py new file mode 100644 index 000000000..ecbd2c7c8 --- /dev/null +++ b/tools/test_entity_death_loot_parity.py @@ -0,0 +1,185 @@ +#!/usr/bin/env python3 +"""Compare entity death drops (loot tables, equipment drops, experience) with vanilla. + +Java (VanillaEntityDeathLootOracle) builds the real victim, killer and damage +source on a stand-in ServerLevel and runs LivingEntity.die's drop step; Rust +(entity_death_loot_fixture) runs horizon_client::mobs::drops on the same cases. +Every living entity type with a loot table is killed by a player with and +without looting, by nothing, on fire, with a smelting weapon, as a baby, with +luck and with worn equipment, plus each table's special conditions (sheep +colours, cube sizes, frog kills, skeleton and charged creeper kills, fireballs, +lightning, raid captains and vehicles). Loot draws come from the world's random +sequences; several victims are killed in turn per case. +""" +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 + +# Living entity types with an entity loot table that the corpus skips: players +# and stands are not mobs, the dragon dies over 200 ticks, and the giant and +# the copper golem are not Horizon mob types. +SKIPPED = {'player', 'mannequin', 'armor_stand', 'ender_dragon', 'giant', 'copper_golem'} +# Types Horizon keeps body armour for in the head slot: their corpus wears +# body items instead of helmets. +BODY = {'horse', 'donkey', 'mule', 'skeleton_horse', 'zombie_horse', 'camel', 'camel_husk', 'llama', 'trader_llama', + 'happy_ghast', 'nautilus', 'zombie_nautilus', 'sulfur_cube'} +WEAPONS = ['minecraft:iron_sword', 'minecraft:diamond_sword;looting:1', 'minecraft:diamond_sword;looting:2', + 'minecraft:netherite_sword;looting:3', 'minecraft:golden_sword;fire_aspect:2', 'minecraft:diamond_axe;looting:3;fire_aspect:1'] +ARMOUR = {'head': 'minecraft:iron_helmet', 'chest': 'minecraft:chainmail_chestplate', 'legs': 'minecraft:golden_leggings', + 'feet': 'minecraft:diamond_boots', 'mainhand': 'minecraft:iron_sword', 'offhand': 'minecraft:shield'} +DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple', + 'blue', 'brown', 'green', 'red', 'black'] + + +def corpus(types): + rng = random.Random(0x4C4F4F54) + cases = [] + + def add(name, **kv): + kv.setdefault('seed', rng.randrange(-2**63, 2**63)) + kv.setdefault('rand', rng.randrange(-2**47, 2**47)) + cases.append(name + ''.join(f' {k}={v}' for k, v in kv.items())) + for t in types: + n = t.split(':')[1] + add(f'{n}-player', type=t, killer='player', weapon='minecraft:iron_sword', kills=4) + add(f'{n}-none', type=t, source='generic', kills=3) + add(f'{n}-mob', type=t, killer='minecraft:spider', kills=2) + for i, weapon in enumerate(WEAPONS[1:]): + add(f'{n}-weapon{i}', type=t, killer='player', weapon=weapon, kills=4) + add(f'{n}-fire', type=t, killer='player', fire=1, kills=3) + add(f'{n}-fire-nokill', type=t, fire=1, source='fire', kills=2) + add(f'{n}-baby', type=t, killer='player', baby=1, weapon='minecraft:iron_sword;looting:3', kills=3) + add(f'{n}-luck', type=t, killer='player', luck=rng.choice([1, 2, 5]), kills=3) + add(f'{n}-arrow', type=t, killer='player', source='arrow', weapon='minecraft:bow;looting:3', kills=2) + head = 'body' if n in BODY else 'head' + armour = dict(ARMOUR) + if n in BODY: + armour['body'] = armour.pop('head').replace('helmet', 'horse_armor') + add(f'{n}-gear', type=t, killer='player', weapon='minecraft:iron_sword;looting:3', kills=6, **armour) + add(f'{n}-gear-plain', type=t, killer='player', kills=6, mainhand='minecraft:stone_axe', chance_mainhand=0.5, + **{head: 'minecraft:leather_helmet', f'chance_{head}': 2.0}) + add(f'{n}-gear-nokill', type=t, source='generic', kills=4, feet='minecraft:iron_boots', chance_feet=1.0, + **{head: 'minecraft:carved_pumpkin', f'chance_{head}': 2.0}) + add(f'{n}-gear-mob', type=t, killer='minecraft:skeleton', source='arrow', kills=4, feet='minecraft:iron_boots', chance_feet=1.0, + weapon='minecraft:bow;looting:3') + for color in DYES: + add(f'sheep-{color}', type='minecraft:sheep', color=color, killer='player', kills=3) + add(f'sheep-{color}-sheared', type='minecraft:sheep', color=color, sheared=1, killer='player', kills=2) + for cube in ['minecraft:slime', 'minecraft:magma_cube', 'minecraft:sulfur_cube']: + for size in [1, 2, 3, 4]: + add(f'{cube[10:]}-size{size}', type=cube, size=size, killer='player', weapon='minecraft:iron_sword;looting:2', kills=4) + for frog in ['temperate', 'warm', 'cold']: + for size in [1, 2, 4]: + add(f'magma_cube-frog-{frog}-{size}', type='minecraft:magma_cube', size=size, killer='minecraft:frog', frog='minecraft:' + frog, + pkill=rng.choice([0, 1]), kills=3) + add('creeper-skeleton', type='minecraft:creeper', killer='minecraft:skeleton', source='arrow', pkill=1, kills=3) + add('creeper-stray', type='minecraft:creeper', killer='minecraft:stray', source='arrow', kills=2) + for victim in ['zombie', 'skeleton', 'creeper', 'wither_skeleton', 'piglin', 'zombie_villager', 'cow']: + add(f'charged-{victim}', type='minecraft:' + victim, killer='minecraft:creeper', charged=1, source='explosion', kills=2) + add(f'uncharged-{victim}', type='minecraft:' + victim, killer='minecraft:creeper', source='explosion', kills=2) + add('ghast-fireball', type='minecraft:ghast', killer='player', source='fireball', kills=4) + add('ghast-fireball-ghast', type='minecraft:ghast', killer='minecraft:ghast', source='fireball', kills=2) + add('turtle-lightning', type='minecraft:turtle', source='lightning', kills=3) + add('turtle-lightning-player', type='minecraft:turtle', source='lightning', pkill=1, kills=3) + add('pillager-captain', type='minecraft:pillager', captain=1, leader=1, killer='player', kills=3) + add('pillager-captain-none', type='minecraft:pillager', captain=1, leader=1, source='generic', kills=2) + add('pillager-captain-looting', type='minecraft:pillager', captain=1, leader=1, killer='player', + weapon='minecraft:iron_sword;looting:3', kills=4, chance_head=2.0) + add('pillager-banner-only', type='minecraft:pillager', captain=1, killer='player', kills=3) + add('pillager-leader-only', type='minecraft:pillager', leader=1, killer='player', kills=2) + add('vindicator-captain', type='minecraft:vindicator', captain=1, leader=1, killer='player', kills=2) + for animal in ['pig', 'strider', 'horse', 'camel', 'donkey']: + add(f'{animal}-saddle', type='minecraft:' + animal, saddle='minecraft:saddle', chance_saddle=2.0, killer='player', kills=2) + add(f'{animal}-saddle-default', type='minecraft:' + animal, saddle='minecraft:saddle', killer='player', kills=6) + add('zombie-horse', type='minecraft:zombie', vehicle='minecraft:zombie_horse', killer='player', kills=4) + add('zombie-baby-chicken', type='minecraft:zombie', baby=1, vehicle='minecraft:chicken', killer='player', kills=3) + add('zombie-baby-chicken-none', type='minecraft:zombie', baby=1, vehicle='minecraft:chicken', source='generic', kills=2) + add('husk-camel', type='minecraft:husk', vehicle='minecraft:camel_husk', killer='player', kills=3) + for weapon in WEAPONS: + add('wither-' + weapon.split(';')[-1].replace(':', ''), type='minecraft:wither', killer='player', weapon=weapon, kills=2) + return cases + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--prepare', action='store_true') + args = parser.parse_args() + build = lab.LOCAL / 'rust-entity-death-loot-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' + tables = resources / 'data/minecraft/loot_table/entities' + types = sorted('minecraft:' + p.stem for p in tables.glob('*.json') if p.stem not in SKIPPED) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityDeathLootOracle.java' + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/entity_death_loot_fixture.rs', + lab.ROOT / 'crates/horizon-client/src/mobs/drops.rs', lab.ROOT / 'crates/horizon-world/src/loot.rs'] + tested = base.source_hashes(sources) + inputs = build / 'inputs.txt' + cases = corpus(types) + inputs.write_text(''.join(line + '\n' for line in cases), 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', '-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'), + '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') + run(['java', '-Xmx2G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), + 'dev.horizonlab.parity.VanillaEntityDeathLootOracle', inputs, build / 'server.txt'], 'server') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'entity_death_loot_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/entity_death_loot_fixture' + run([binary, resources, inputs, build / 'rust.txt'], 'rust') + errors = [l for l in (build / 'server.txt').read_text().splitlines() if l.startswith('error ')] + if errors: + raise SystemExit(f'oracle errors ({len(errors)}): {errors[:5]}') + try: + matched = base.compare(build / 'server.txt', build / 'rust.txt') + except AssertionError as error: + raise SystemExit(str(error) + explain(build)) from None + base.ensure_sources_unchanged(sources, tested) + lab.write_json(build / 'report.json', { + 'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'cases': len(cases), + 'types': len(types), 'skipped': sorted(SKIPPED), 'matched_output_lines': matched, 'sources_sha256': tested, + 'scope': 'LivingEntity.dropAllDeathLoot after the killer\'s killedEntity hook: entity loot tables under the world random ' + 'sequence, Mob.dropCustomDeathLoot equipment drops and durability, species death loot, experience orbs.'}) + print(f'{len(cases):,} death-drop cases over {len(types)} entity types match vanilla ({matched:,} lines)') + + +def explain(build): + def sections(path): + out, name = {}, None + for line in path.read_text(encoding='utf-8', errors='replace').splitlines(): + if line.startswith('== '): + name = line[3:] + out[name] = [] + elif name is not None: + out[name].append(line) + return out + left, right = sections(build / 'server.txt'), sections(build / 'rust.txt') + bad = [n for n in left if left[n] != right.get(n)] + report = f'\n{len(bad)} differing cases' + for name in bad[:30]: + a, b = left[name], right.get(name, []) + diffs = [(x, y) for x, y in zip(a, b) if x != y][:3] + if len(a) != len(b): + diffs.append((f'<{len(a)} lines>', f'<{len(b)} lines>')) + report += f'\n {name}: {diffs}' + return report + + +if __name__ == '__main__': + main() From e6ef8c502b390fe1b45958750c52423b0cf1f2bb Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:16:57 +0200 Subject: [PATCH 2/2] Check spawn placements and spawn predicates exactly as SpawnPlacements does mobs::spawn_rules ports SpawnPlacements over a SpawnLevel trait the game's MobWorld implements: the placement types with per-type isValidSpawn (leaves, ice, magma for fire-immune types) and isValidEmptySpawnBlock with each type's dangerous and immune blocks, and every registered predicate in vanilla's draw order: the dimension's monster light test and block light limit, thunder, peaceful, spawn reasons, guardians' sky from below water, drowned, bats, ghasts, ocelots, slimes (surface chance and slime chunks), strays under powder snow, striders, turtles, polar bears, tropical fish, nautiluses, silverfish and endermites near players, patrols and the spawnable-on tags. Divergences fixed on the way: nether monsters ignored light, hoglins and piglins had extra checks, slimes spawned outside slime chunks, ocelots and ghasts skipped their odds, bats ignored the surface and their draw order, and several predicates read the wrong blocks. tools/test_spawn_rules_parity.py: 18,669 cases over 87 entity types match. Co-Authored-By: Claude Opus 5.5 --- .../examples/spawn_rules_fixture.rs | 232 +++++++ crates/horizon-client/src/game/creatures.rs | 2 + crates/horizon-client/src/mobs.rs | 5 + crates/horizon-client/src/mobs/spawn_rules.rs | 589 ++++++++++++++++++ crates/horizon-client/src/mobs/spawning.rs | 167 +---- .../parity/VanillaSpawnRulesOracle.java | 204 ++++++ tools/test_spawn_rules_parity.py | 182 ++++++ 7 files changed, 1227 insertions(+), 154 deletions(-) create mode 100644 crates/horizon-client/examples/spawn_rules_fixture.rs create mode 100644 crates/horizon-client/src/mobs/spawn_rules.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSpawnRulesOracle.java create mode 100644 tools/test_spawn_rules_parity.py diff --git a/crates/horizon-client/examples/spawn_rules_fixture.rs b/crates/horizon-client/examples/spawn_rules_fixture.rs new file mode 100644 index 000000000..8e4fff1c3 --- /dev/null +++ b/crates/horizon-client/examples/spawn_rules_fixture.rs @@ -0,0 +1,232 @@ +//! Spawn placement and spawn predicate answers for differential tests against +//! vanilla (tools/test_spawn_rules_parity.py): reads the column-world cases of +//! `VanillaSpawnRulesOracle` and prints `mobs::spawn_rules`' answers. +//! +//! usage: spawn_rules_fixture RESOURCES INPUT OUTPUT +use horizon_client::{ + assets::Assets, + blocks::BlockFacts, + items::Items, + mobs::{ + MobTypes, + data::MobData, + spawn_rules::{self, Dimension, Reason, SpawnLevel}, + }, +}; +use horizon_core::random::{LegacyRandom, RandomSource}; +use horizon_world::{chunk::BlockState, registry::BlockStateId}; +use std::{ + collections::{BTreeMap, HashMap, HashSet}, + fmt::Write as _, + fs, + path::Path, +}; + +struct Column<'a> { + facts: &'a BlockFacts, + data: &'a MobData, + block_tags: &'a HashMap>, + air: BlockStateId, + blocks: HashMap, + x0: i32, + z0: i32, + sky: i32, + light: i32, + darken: i32, + thunder: bool, + sea: i32, + surface: i32, + seed: i64, + peaceful: bool, + dimension: Dimension, + biome: String, + slime: f32, + /// A player position and whether it is survival or adventure. + player: Option<([f64; 3], bool)>, +} +impl SpawnLevel for Column<'_> { + fn state(&self, x: i32, y: i32, z: i32) -> BlockStateId { + if x != self.x0 || z != self.z0 { + return self.air; + } + self.blocks.get(&y).copied().unwrap_or(self.air) + } + fn facts(&self) -> &BlockFacts { + self.facts + } + fn mob_data(&self) -> &MobData { + self.data + } + fn block_tag(&self, tag: &str, block: &str) -> bool { + self.block_tags.get(tag).is_some_and(|s| s.contains(block)) + } + fn biome_tag(&self, tag: &str, _: i32, _: i32, _: i32) -> bool { + self.data + .biome_tags + .get(tag) + .is_some_and(|s| s.contains(&self.biome)) + } + fn sky_light(&self, _: i32, _: i32, _: i32) -> i32 { + self.sky + } + fn block_light(&self, _: i32, _: i32, _: i32) -> i32 { + self.light + } + fn sky_darken(&self) -> i32 { + self.darken + } + fn thundering(&self) -> bool { + self.thunder + } + fn sea_level(&self) -> i32 { + self.sea + } + fn world_surface(&self, _: i32, _: i32) -> i32 { + self.surface + } + fn peaceful(&self) -> bool { + self.peaceful + } + fn dimension(&self) -> Dimension { + self.dimension + } + fn surface_slime_chance(&self, _: i32, _: i32, _: i32) -> f32 { + self.slime + } + fn world_seed(&self) -> i64 { + self.seed + } + fn player_near(&self, x: f64, y: f64, z: f64, distance: f64) -> bool { + self.player.is_some_and(|(p, targetable)| { + let d = (p[0] - x).powi(2) + (p[1] - y).powi(2) + (p[2] - z).powi(2); + targetable && d < distance * distance + }) + } +} + +/// `name[key=value,...]`. +fn parse_state(spec: &str) -> BlockState { + let (name, props) = match spec.split_once('[') { + Some((n, rest)) => (n, rest.trim_end_matches(']')), + None => (spec, ""), + }; + let properties: BTreeMap = props + .split(',') + .filter(|p| !p.is_empty()) + .filter_map(|p| p.split_once('=')) + .map(|(k, v)| (k.to_owned(), v.to_owned())) + .collect(); + BlockState { + name: name.to_owned(), + properties, + } +} + +fn reason(name: &str) -> Reason { + match name { + "chunk_generation" => Reason::ChunkGeneration, + "spawner" => Reason::Spawner, + "trial_spawner" => Reason::TrialSpawner, + "reinforcement" => Reason::Reinforcement, + "patrol" => Reason::Patrol, + "structure" => Reason::Structure, + "event" => Reason::Event, + "command" => Reason::Command, + _ => Reason::Natural, + } +} + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let root = Path::new( + args.get(1) + .ok_or("usage: spawn_rules_fixture RESOURCES INPUT OUTPUT")?, + ); + let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; + let assets = Assets::load(root)?; + let registry = assets.registry; + let facts = BlockFacts::load(root, registry)?; + let data = MobData::load(root, &facts); + let items = Items::tags_only(root)?; + let types = MobTypes::load(root)?; + let mut out = String::new(); + for raw in input.lines() { + if raw.trim().is_empty() { + continue; + } + let mut c = BTreeMap::new(); + let mut name = ""; + for token in raw.split_whitespace() { + match token.split_once('=') { + Some((k, v)) => { + c.insert(k, v); + } + None => name = token, + } + } + let get = |k: &str, d: &'static str| -> String { c.get(k).copied().unwrap_or(d).to_owned() }; + let Some(kind) = types.types.get(c["type"]) else { + let _ = writeln!(out, "{name} error unsupported {}", c["type"]); + continue; + }; + let y: i32 = get("y", "64").parse()?; + let (x0, z0): (i32, i32) = (get("x", "8").parse()?, get("z", "8").parse()?); + let mut blocks = HashMap::new(); + for (k, v) in &c { + if let Some(offset) = k.strip_prefix("at") { + let offset: i32 = offset.parse()?; + blocks.insert(y + offset, registry.resolve(&parse_state(v))?); + } + } + let player = c.get("player").map(|p| { + let f: Vec<&str> = p.split(',').collect(); + let at = |i: usize, base: i32| f64::from(base) + f[i].parse::().unwrap_or(0.0); + let mode = f.get(3).copied().unwrap_or("survival"); + ( + [at(0, x0), at(1, y), at(2, z0)], + mode == "survival" || mode == "adventure", + ) + }); + let level = Column { + facts: &facts, + data: &data, + block_tags: &items.block_tags, + air: facts.air, + blocks, + x0, + z0, + sky: get("sky", "15").parse()?, + light: get("light", "0").parse()?, + darken: get("darken", "0").parse()?, + thunder: get("thunder", "0") == "1", + sea: get("sea", "63").parse()?, + surface: get("surface", "0").parse()?, + seed: get("wseed", "0").parse()?, + peaceful: get("difficulty", "normal") == "peaceful", + dimension: match get("dim", "minecraft:overworld").as_str() { + "minecraft:the_nether" => Dimension::Nether, + "minecraft:the_end" => Dimension::End, + _ => Dimension::Overworld, + }, + biome: get("biome", "minecraft:plains"), + slime: get("slime", "0.0").parse()?, + player, + }; + let mut random = LegacyRandom::new(get("seed", "0").parse()?); + let s = kind.species; + let ok = spawn_rules::is_spawn_position_ok(s, &level, x0, y, z0); + let rules = spawn_rules::check_spawn_rules( + s, + &level, + reason(&get("reason", "natural")), + &mut random, + x0, + y, + z0, + ); + let next = random.next_int_bound(1000).unwrap_or(0); + let _ = writeln!(out, "{name} {ok} {rules} {next}"); + } + fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index afd148af7..8441baaf1 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -467,6 +467,8 @@ impl Game<'_> { block_tags: &self.res.items.block_tags, biomes: &self.res.biomes, mob_griefing: self.ui.rules.bool("mob_griefing"), + end: self.dim == Dim::End, + world_seed: self.level.seed, difficulty: self.local_difficulty( self.player .as_ref() diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index deda5984a..b45da996c 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -47,6 +47,7 @@ pub mod riders; pub mod shulker; pub mod sniffer; pub mod spawning; +pub mod spawn_rules; pub mod species; pub mod sulfur_cube; pub mod tame; @@ -903,6 +904,10 @@ pub struct MobWorld<'a> { pub mob_griefing: bool, /// `getCurrentDifficultyAt` near the player. pub difficulty: spawning::LocalDifficulty, + /// The End (its dimension type's monster spawn light rules). + pub end: bool, + /// The world seed (slime chunks). + pub world_seed: i64, } impl Mob { pub fn new(id: u32, kind: Arc, position: Vec3, yaw: f32) -> Self { diff --git a/crates/horizon-client/src/mobs/spawn_rules.rs b/crates/horizon-client/src/mobs/spawn_rules.rs new file mode 100644 index 000000000..f64918bd4 --- /dev/null +++ b/crates/horizon-client/src/mobs/spawn_rules.rs @@ -0,0 +1,589 @@ +//! `SpawnPlacements`: each entity type's placement type +//! (`SpawnPlacementTypes.isSpawnPositionOk`) and spawn predicate +//! (`checkSpawnRules`), read through [`SpawnLevel`] so the game's world and a +//! differential test world answer the same questions. Random draws follow +//! vanilla's order. +use super::{Species, data}; +use crate::blocks::{BlockFacts, Fluid}; +use horizon_core::random::{RandomSource, slime_chunk_random}; +use horizon_world::registry::BlockStateId; + +/// `EntitySpawnReason`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Reason { + Natural, + ChunkGeneration, + Spawner, + TrialSpawner, + Reinforcement, + Patrol, + Structure, + Event, + Command, + SpawnItemUse, + MobSummoned, + Conversion, + Breeding, + Triggered, + Jockey, + Dispenser, + Bucket, + Load, + DimensionTravel, +} +impl Reason { + pub fn is_spawner(self) -> bool { + matches!(self, Self::Spawner | Self::TrialSpawner) + } + pub fn ignores_light(self) -> bool { + self == Self::TrialSpawner + } +} +/// The dimension type's monster spawn light rules. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Dimension { + Overworld, + Nether, + End, +} +impl Dimension { + /// `monster_spawn_block_light_limit`. + fn block_light_limit(self) -> i32 { + match self { + Self::Nether => 15, + _ => 0, + } + } + /// `monster_spawn_light_level.sample`: uniform 0..=7 in the overworld. + fn light_test(self, random: &mut impl RandomSource) -> i32 { + match self { + Self::Overworld => random.next_int_bound(8).unwrap_or(0), + Self::Nether => 7, + Self::End => 15, + } + } +} + +/// What spawn checks read from a level. +pub trait SpawnLevel { + fn state(&self, x: i32, y: i32, z: i32) -> BlockStateId; + fn facts(&self) -> &BlockFacts; + fn mob_data(&self) -> &data::MobData; + fn block_tag(&self, tag: &str, block: &str) -> bool; + fn biome_tag(&self, tag: &str, x: i32, y: i32, z: i32) -> bool; + /// `getBrightness(LightLayer.SKY / BLOCK)`. + fn sky_light(&self, x: i32, y: i32, z: i32) -> i32; + fn block_light(&self, x: i32, y: i32, z: i32) -> i32; + fn sky_darken(&self) -> i32; + fn thundering(&self) -> bool; + fn sea_level(&self) -> i32; + /// `getHeight(WORLD_SURFACE, x, z)`: above the highest non-air block. + fn world_surface(&self, x: i32, z: i32) -> i32; + fn peaceful(&self) -> bool; + fn dimension(&self) -> Dimension; + /// The `gameplay/surface_slime_spawn_chance` environment attribute. + fn surface_slime_chance(&self, x: i32, y: i32, z: i32) -> f32; + fn world_seed(&self) -> i64; + /// `getNearestPlayer(x, y, z, distance, true) != null`: a survival or + /// adventure player that close. + fn player_near(&self, x: f64, y: f64, z: f64, distance: f64) -> bool; +} + +fn name(l: &L, x: i32, y: i32, z: i32) -> &str { + &l.facts().get(l.state(x, y, z)).name +} +fn fluid(l: &L, x: i32, y: i32, z: i32) -> Fluid { + l.facts().get(l.state(x, y, z)).fluid +} +fn flags(l: &L, x: i32, y: i32, z: i32) -> u16 { + l.mob_data().state(l.state(x, y, z)).flags +} +fn tag(l: &L, tag: &str, x: i32, y: i32, z: i32) -> bool { + l.block_tag(tag, name(l, x, y, z)) +} +/// `getRawBrightness(pos, darkening)`. +fn raw_brightness(l: &L, x: i32, y: i32, z: i32, darkening: i32) -> i32 { + l.block_light(x, y, z).max(l.sky_light(x, y, z) - darkening) +} +fn can_see_sky(l: &L, x: i32, y: i32, z: i32) -> bool { + l.sky_light(x, y, z) >= 15 +} +/// `LevelReader.canSeeSkyFromBelowWater`. +fn can_see_sky_from_below_water(l: &L, x: i32, y: i32, z: i32) -> bool { + let sea = l.sea_level(); + if y >= sea { + return can_see_sky(l, x, y, z); + } + if !can_see_sky(l, x, sea, z) { + return false; + } + ((y + 1)..sea).all(|yy| { + let f = l.facts().get(l.state(x, yy, z)); + f.dampening == 0 || f.fluid != Fluid::None + }) +} + +/// `EntityType.fireImmune`. +pub fn fire_immune(s: Species) -> bool { + use Species as S; + matches!( + s, + S::Blaze + | S::Ghast + | S::MagmaCube + | S::Shulker + | S::Strider + | S::Vex + | S::Warden + | S::Wither + | S::WitherSkeleton + | S::Zoglin + | S::ZombifiedPiglin + ) +} +/// `EntityType.isAllowedInPeaceful`. +pub fn allowed_in_peaceful(s: Species) -> bool { + use Species as S; + !matches!( + s, + S::Blaze + | S::Bogged + | S::Breeze + | S::CaveSpider + | S::Creaking + | S::Creeper + | S::Drowned + | S::ElderGuardian + | S::Enderman + | S::Endermite + | S::Evoker + | S::Ghast + | S::Giant + | S::Guardian + | S::Hoglin + | S::Husk + | S::Illusioner + | S::MagmaCube + | S::Parched + | S::Phantom + | S::PiglinBrute + | S::Pillager + | S::Ravager + | S::Silverfish + | S::Skeleton + | S::Slime + | S::Spider + | S::Stray + | S::Vex + | S::Vindicator + | S::Warden + | S::Witch + | S::Wither + | S::WitherSkeleton + | S::Zoglin + | S::Zombie + | S::ZombieVillager + | S::ZombifiedPiglin + ) +} +/// The block tag an entity type is `immuneTo`. +fn immune_tag(s: Species) -> Option<&'static str> { + use Species as S; + match s { + S::Fox => Some("minecraft:fox_immune_to"), + S::PolarBear => Some("minecraft:polar_bear_immune_to"), + S::SnowGolem => Some("minecraft:snow_golem_immune_to"), + S::Stray => Some("minecraft:stray_immune_to"), + S::Wither => Some("minecraft:wither_immune_to"), + S::WitherSkeleton => Some("minecraft:wither_skeleton_immune_to"), + _ => None, + } +} +/// `BlockState.isValidSpawn(level, pos, type)` for the block at a position. +pub fn is_valid_spawn(s: Species, l: &L, x: i32, y: i32, z: i32) -> bool { + if name(l, x, y, z) == "minecraft:magma_block" { + return fire_immune(s); + } + let bit = match s { + Species::Ocelot | Species::Parrot => data::VALID_SPAWN_LEAVES, + Species::PolarBear => data::VALID_SPAWN_ICE, + _ => data::VALID_SPAWN, + }; + flags(l, x, y, z) & bit != 0 +} +/// `NaturalSpawner.isValidEmptySpawnBlock` for an entity type. +pub fn is_valid_empty_spawn(s: Species, l: &L, x: i32, y: i32, z: i32) -> bool { + // The exported flag is the zombie's answer; only blocks a zombie finds + // dangerous can answer differently for another type. + if flags(l, x, y, z) & data::VALID_EMPTY_SPAWN != 0 { + return true; + } + let f = l.facts().get(l.state(x, y, z)); + let block = &*f.name; + let burning = l.block_tag("minecraft:fire", block) + || block == "minecraft:lava" + || block == "minecraft:magma_block" + || (block == "minecraft:campfire" || block == "minecraft:soul_campfire") && f.emission > 0 + || block == "minecraft:lava_cauldron"; + let other = matches!( + block, + "minecraft:wither_rose" + | "minecraft:sweet_berry_bush" + | "minecraft:cactus" + | "minecraft:powder_snow" + ); + if !burning && !other { + return false; + } + let immune = immune_tag(s).is_some_and(|t| l.block_tag(t, block)); + let dangerous = !immune && (burning && !fire_immune(s) || other); + !dangerous + && !f.full_collision + && f.fluid == Fluid::None + && !l.block_tag("minecraft:prevent_mob_spawning_inside", block) +} +/// `SpawnPlacements.isSpawnPositionOk`. +pub fn is_spawn_position_ok(s: Species, l: &L, x: i32, y: i32, z: i32) -> bool { + let id = format!("minecraft:{}", super::species::def(s).name); + match l.mob_data().placement(&id) { + data::Placement::OnGround => { + is_valid_spawn(s, l, x, y - 1, z) + && is_valid_empty_spawn(s, l, x, y, z) + && is_valid_empty_spawn(s, l, x, y + 1, z) + } + data::Placement::InWater => { + fluid(l, x, y, z) == Fluid::Water && flags(l, x, y + 1, z) & data::REDSTONE_CONDUCTOR == 0 + } + data::Placement::InLava => fluid(l, x, y, z) == Fluid::Lava, + data::Placement::NoRestrictions => true, + } +} +/// `Monster.isDarkEnoughToSpawn`. +pub fn is_dark_enough(l: &L, random: &mut impl RandomSource, x: i32, y: i32, z: i32) -> bool { + if l.sky_light(x, y, z) > random.next_int_bound(32).unwrap_or(0) { + return false; + } + let dim = l.dimension(); + let limit = dim.block_light_limit(); + if limit < 15 && l.block_light(x, y, z) > limit { + return false; + } + let darken = if l.thundering() { 10 } else { l.sky_darken() }; + let brightness = raw_brightness(l, x, y, z, darken); + brightness <= dim.light_test(random) +} +/// `Animal.isBrightEnoughToSpawn`. +fn bright(l: &L, x: i32, y: i32, z: i32) -> bool { + raw_brightness(l, x, y, z, 0) > 8 +} +/// `Mob.checkMobSpawnRules`. +fn mob_rules(s: Species, l: &L, reason: Reason, x: i32, y: i32, z: i32) -> bool { + reason.is_spawner() || is_valid_spawn(s, l, x, y - 1, z) +} +/// `Monster.checkMonsterSpawnRules`. +fn monster_rules( + s: Species, + l: &L, + reason: Reason, + random: &mut impl RandomSource, + x: i32, + y: i32, + z: i32, +) -> bool { + (reason.ignores_light() || is_dark_enough(l, random, x, y, z)) && mob_rules(s, l, reason, x, y, z) +} +/// `Animal.checkAnimalSpawnRules` with the given spawnable-on tag. +fn animal_rules(l: &L, reason: Reason, on: &str, x: i32, y: i32, z: i32) -> bool { + let bright = reason.ignores_light() || bright(l, x, y, z); + tag(l, on, x, y - 1, z) && bright +} +/// `WaterAnimal.checkSurfaceWaterAnimalSpawnRules`. +fn surface_water(l: &L, x: i32, y: i32, z: i32) -> bool { + let sea = l.sea_level(); + y >= sea - 13 + && y <= sea + && fluid(l, x, y - 1, z) == Fluid::Water + && name(l, x, y + 1, z) == "minecraft:water" +} + +/// `SpawnPlacements.checkSpawnRules`. +pub fn check_spawn_rules( + s: Species, + l: &L, + reason: Reason, + random: &mut impl RandomSource, + x: i32, + y: i32, + z: i32, +) -> bool { + use Species as S; + if !allowed_in_peaceful(s) && l.peaceful() { + return false; + } + let below = |l: &L| name(l, x, y - 1, z).to_owned(); + match s { + S::Axolotl => tag(l, "minecraft:axolotls_spawnable_on", x, y - 1, z), + S::Cod | S::Pufferfish | S::Salmon | S::Dolphin | S::Squid => surface_water(l, x, y, z), + S::Drowned => { + if fluid(l, x, y - 1, z) != Fluid::Water && !reason.is_spawner() { + return false; + } + let frequent = l.biome_tag("minecraft:more_frequent_drowned_spawns", x, y, z); + let can_spawn = !l.peaceful() + && (reason.ignores_light() || is_dark_enough(l, random, x, y, z)) + && (reason.is_spawner() || fluid(l, x, y, z) == Fluid::Water); + if !can_spawn || !reason.is_spawner() && reason != Reason::Reinforcement { + if frequent { + random.next_int_bound(15).unwrap_or(1) == 0 && can_spawn + } else { + random.next_int_bound(40).unwrap_or(1) == 0 && y < l.sea_level() - 5 && can_spawn + } + } else { + true + } + } + S::Guardian | S::ElderGuardian => { + (random.next_int_bound(20).unwrap_or(1) == 0 || !can_see_sky_from_below_water(l, x, y, z)) + && !l.peaceful() + && (reason.is_spawner() || fluid(l, x, y, z) == Fluid::Water) + && fluid(l, x, y - 1, z) == Fluid::Water + } + S::TropicalFish => { + fluid(l, x, y - 1, z) == Fluid::Water + && name(l, x, y + 1, z) == "minecraft:water" + && (l.biome_tag("minecraft:allows_tropical_fish_spawns_at_any_height", x, y, z) + || surface_water(l, x, y, z)) + } + S::Armadillo => tag(l, "minecraft:armadillo_spawnable_on", x, y - 1, z) && bright(l, x, y, z), + S::Bat => { + if y >= l.world_surface(x, z) || random.next_boolean() { + return false; + } + if raw_brightness(l, x, y, z, l.sky_darken()) > random.next_int_bound(4).unwrap_or(0) { + return false; + } + tag(l, "minecraft:bats_spawnable_on", x, y - 1, z) && mob_rules(s, l, reason, x, y, z) + } + S::Blaze | S::Breeze | S::Zoglin => mob_rules(s, l, reason, x, y, z), + S::Camel => tag(l, "minecraft:camels_spawnable_on", x, y - 1, z) && bright(l, x, y, z), + S::CamelHusk | S::Husk | S::Parched => { + monster_rules(s, l, reason, random, x, y, z) + && (reason.is_spawner() || can_see_sky(l, x, y, z)) + } + S::Chicken + | S::Cow + | S::Donkey + | S::HappyGhast + | S::Horse + | S::Llama + | S::Mule + | S::Pig + | S::Sheep + | S::Cat + | S::Panda + | S::TraderLlama => animal_rules(l, reason, "minecraft:animals_spawnable_on", x, y, z), + S::Endermite | S::Silverfish => { + if !mob_rules(s, l, reason, x, y, z) { + return false; + } + reason.is_spawner() + || !l.player_near(f64::from(x) + 0.5, f64::from(y) + 0.5, f64::from(z) + 0.5, 5.0) + } + S::IronGolem | S::SnowGolem | S::Villager | S::Phantom | S::Shulker + | S::WanderingTrader => mob_rules(s, l, reason, x, y, z), + S::Frog => tag(l, "minecraft:frogs_spawnable_on", x, y - 1, z) && bright(l, x, y, z), + S::Ghast => { + !l.peaceful() + && random.next_int_bound(20).unwrap_or(1) == 0 + && mob_rules(s, l, reason, x, y, z) + } + S::GlowSquid => { + y <= l.sea_level() - 33 + && raw_brightness(l, x, y, z, 0) == 0 + && name(l, x, y, z) == "minecraft:water" + } + S::Goat => tag(l, "minecraft:goats_spawnable_on", x, y - 1, z) && bright(l, x, y, z), + S::MagmaCube => !l.peaceful(), + S::SulfurCube => true, + S::Mooshroom => tag(l, "minecraft:mooshrooms_spawnable_on", x, y - 1, z) && bright(l, x, y, z), + S::Nautilus => { + let sea = l.sea_level(); + y >= sea - 25 + && y <= sea - 5 + && fluid(l, x, y - 1, z) == Fluid::Water + && name(l, x, y + 1, z) == "minecraft:water" + } + S::Ocelot => random.next_int_bound(3).unwrap_or(0) != 0, + S::Parrot => tag(l, "minecraft:parrots_spawnable_on", x, y - 1, z) && bright(l, x, y, z), + S::Hoglin | S::Piglin => below(l) != "minecraft:nether_wart_block", + S::Pillager => l.block_light(x, y, z) <= 8 && mob_rules(s, l, reason, x, y, z), + S::PolarBear => { + if l.biome_tag("minecraft:polar_bears_spawn_on_alternate_blocks", x, y, z) { + bright(l, x, y, z) + && tag(l, "minecraft:polar_bears_spawnable_on_alternate", x, y - 1, z) + } else { + animal_rules(l, reason, "minecraft:animals_spawnable_on", x, y, z) + } + } + S::Rabbit => tag(l, "minecraft:rabbits_spawnable_on", x, y - 1, z) && bright(l, x, y, z), + S::SkeletonHorse => { + if reason.is_spawner() { + reason.ignores_light() || bright(l, x, y, z) + } else { + animal_rules(l, reason, "minecraft:animals_spawnable_on", x, y, z) + } + } + S::Slime => slime_rules(s, l, reason, random, x, y, z), + S::Stray => { + let mut sky = y + 1; + while name(l, x, sky, z) == "minecraft:powder_snow" { + sky += 1; + } + monster_rules(s, l, reason, random, x, y, z) + && (reason.is_spawner() || can_see_sky(l, x, sky - 1, z)) + } + S::Strider => { + let mut up = y + 1; + while fluid(l, x, up, z) == Fluid::Lava { + up += 1; + } + l.facts().is_air(l.state(x, up, z)) + } + S::Turtle => { + y < l.sea_level() + 4 && tag(l, "minecraft:sand", x, y - 1, z) && bright(l, x, y, z) + } + S::Wolf => tag(l, "minecraft:wolves_spawnable_on", x, y - 1, z) && bright(l, x, y, z), + S::ZombifiedPiglin => !l.peaceful() && below(l) != "minecraft:nether_wart_block", + S::Fox => tag(l, "minecraft:foxes_spawnable_on", x, y - 1, z) && bright(l, x, y, z), + S::Bogged + | S::CaveSpider + | S::Creeper + | S::Enderman + | S::Giant + | S::Skeleton + | S::Spider + | S::Witch + | S::Wither + | S::WitherSkeleton + | S::Creaking + | S::Zombie + | S::ZombieHorse + | S::ZombieVillager + | S::Evoker + | S::Illusioner + | S::Ravager + | S::Vex + | S::Vindicator + | S::Warden => monster_rules(s, l, reason, random, x, y, z), + // Types without a SpawnPlacements registration. + _ => true, + } +} +/// `Slime.checkSlimeSpawnRules`. +fn slime_rules( + s: Species, + l: &L, + reason: Reason, + random: &mut impl RandomSource, + x: i32, + y: i32, + z: i32, +) -> bool { + if l.peaceful() { + return false; + } + if reason.is_spawner() { + return mob_rules(s, l, reason, x, y, z); + } + if l.biome_tag("minecraft:allows_surface_slime_spawns", x, y, z) && y > 50 && y < 70 { + let chance = l.surface_slime_chance(x, y, z); + if random.next_float() < chance + && raw_brightness(l, x, y, z, l.sky_darken()) <= random.next_int_bound(8).unwrap_or(0) + { + return mob_rules(s, l, reason, x, y, z); + } + } + let slime_chunk = slime_chunk_random(x >> 4, z >> 4, l.world_seed(), 987_234_911) + .next_int_bound(10) + .unwrap_or(1) + == 0; + if random.next_int_bound(10).unwrap_or(1) == 0 && slime_chunk && y < 40 { + return mob_rules(s, l, reason, x, y, z); + } + false +} + +impl SpawnLevel for super::MobWorld<'_> { + fn state(&self, x: i32, y: i32, z: i32) -> BlockStateId { + self.world.block(x, y, z) + } + fn facts(&self) -> &BlockFacts { + self.facts + } + fn mob_data(&self) -> &data::MobData { + self.data + } + fn block_tag(&self, tag: &str, block: &str) -> bool { + self.has_tag(tag, block) + } + fn biome_tag(&self, tag: &str, x: i32, y: i32, z: i32) -> bool { + let Some(chunk) = self.world.chunks.get(&(x >> 4, z >> 4)) else { + return false; + }; + let biome = &self.biomes.get(chunk.biome(x, y, z)).name; + self.data + .biome_tags + .get(tag.trim_start_matches('#')) + .is_some_and(|members| members.contains(biome)) + } + fn sky_light(&self, x: i32, y: i32, z: i32) -> i32 { + if self.nether || self.end { + return 0; + } + i32::from(self.world.light(x, y, z) >> 4) + } + fn block_light(&self, x: i32, y: i32, z: i32) -> i32 { + i32::from(self.world.light(x, y, z) & 15) + } + fn sky_darken(&self) -> i32 { + super::MobWorld::sky_darken(self) + } + fn thundering(&self) -> bool { + self.thundering + } + fn sea_level(&self) -> i32 { + if self.nether { 32 } else { 63 } + } + fn world_surface(&self, x: i32, z: i32) -> i32 { + let top = crate::chunk::MIN_Y + crate::chunk::HEIGHT; + (crate::chunk::MIN_Y..top) + .rev() + .find(|&y| !self.facts.is_air(self.world.block(x, y, z))) + .map_or(crate::chunk::MIN_Y, |y| y + 1) + } + fn peaceful(&self) -> bool { + self.difficulty.effective == 0.0 + } + fn dimension(&self) -> Dimension { + if self.nether { + Dimension::Nether + } else if self.end { + Dimension::End + } else { + Dimension::Overworld + } + } + fn surface_slime_chance(&self, _: i32, _: i32, _: i32) -> f32 { + let phase = self.day_time.div_euclid(24000).rem_euclid(8) as usize; + 0.5 * super::spawning::MOON_BRIGHTNESS[phase] + } + fn world_seed(&self) -> i64 { + self.world_seed + } + fn player_near(&self, x: f64, y: f64, z: f64, distance: f64) -> bool { + self.player.as_ref().is_some_and(|p| { + let d = (p.position.x - x).powi(2) + (p.position.y - y).powi(2) + (p.position.z - z).powi(2); + p.alive && !p.creative && !p.spectator && d < distance * distance + }) + } +} diff --git a/crates/horizon-client/src/mobs/spawning.rs b/crates/horizon-client/src/mobs/spawning.rs index 33c4b5dd9..cffe7e03d 100644 --- a/crates/horizon-client/src/mobs/spawning.rs +++ b/crates/horizon-client/src/mobs/spawning.rs @@ -2,8 +2,7 @@ //! species' spawn predicate (`checkAnimalSpawnRules`, `checkMonsterSpawnRules`, //! water animals, bats...), and `finalizeSpawn` (variants, colours, babies, //! equipment). -use super::{Mob, MobWorld, Species, data, farm::Climate}; -use crate::blocks::Fluid; +use super::{Mob, MobWorld, Species, farm::Climate}; use horizon_core::random::RandomSource; /// Biome facts finalizeSpawn and the spawn rules read. @@ -27,44 +26,11 @@ pub struct BiomeFacts { /// `spawns_coral_variant_zombie_nautilus` (the warm ocean). pub coral_nautilus: bool, } -/// SpawnPlacementTypes for the species. +/// `SpawnPlacements.isSpawnPositionOk` for the species. pub fn placement_ok(species: Species, w: &MobWorld, x: i32, y: i32, z: i32) -> bool { - let id = format!("minecraft:{}", super::species::def(species).name); - match w.data.placement(&id) { - data::Placement::OnGround => { - let below = w.data.state(w.world.block(x, y - 1, z)); - let valid = match species { - Species::Ocelot | Species::Parrot => below.flags & data::VALID_SPAWN_LEAVES != 0, - Species::PolarBear => below.flags & data::VALID_SPAWN_ICE != 0, - _ => below.flags & data::VALID_SPAWN != 0, - }; - valid && empty(w, x, y, z) && empty(w, x, y + 1, z) - } - data::Placement::InWater => { - w.fluid(x, y, z) == Fluid::Water - && w.data.state(w.world.block(x, y + 1, z)).flags & data::REDSTONE_CONDUCTOR == 0 - } - data::Placement::InLava => w.fluid(x, y, z) == Fluid::Lava, - data::Placement::NoRestrictions => true, - } + super::spawn_rules::is_spawn_position_ok(species, w, x, y, z) } -fn empty(w: &MobWorld, x: i32, y: i32, z: i32) -> bool { - w.data.state(w.world.block(x, y, z)).flags & data::VALID_EMPTY_SPAWN != 0 -} -/// Monster.isDarkEnoughToSpawn (overworld: sky light vs random(32), block light 0). -pub fn dark_enough(w: &MobWorld, random: &mut impl RandomSource, x: i32, y: i32, z: i32) -> bool { - let light = w.world.light(x, y, z); - let (sky, block) = (i32::from(light >> 4), i32::from(light & 15)); - if sky > random.next_int_bound(32).unwrap_or(0) { - return false; - } - if block > 0 { - return false; - } - let darken = if w.thundering { 10 } else { w.sky_darken() }; - (sky - darken).max(0) <= random.next_int_bound(8).unwrap_or(0) -} -/// The species' checkSpawnRules for natural spawns. +/// `SpawnPlacements.checkSpawnRules` for a natural spawn. pub fn spawn_rules_ok( species: Species, w: &MobWorld, @@ -73,122 +39,15 @@ pub fn spawn_rules_ok( y: i32, z: i32, ) -> bool { - use Species as S; - let below = w.block_name(x, y - 1, z).to_owned(); - let light = w.world.light(x, y, z); - let raw = i32::from(light >> 4).max(i32::from(light & 15)); - match species { - // Guardian.checkGuardianSpawnRules. - S::Guardian | S::ElderGuardian => { - let sky_from_below = || { - let sea = 63; - if y >= sea { - return w.can_see_sky(x, y, z); - } - if !w.can_see_sky(x, sea, z) { - return false; - } - ((y + 1)..sea).all(|yy| { - let f = w.facts.get(w.world.block(x, yy, z)); - !f.full_collision || f.fluid != Fluid::None - }) - }; - (random.next_int_bound(20).unwrap_or(1) == 0 || !sky_from_below()) - && w.fluid(x, y, z) == Fluid::Water - && w.fluid(x, y - 1, z) == Fluid::Water - } - // Animal.checkAnimalSpawnRules: animals_spawnable_on below and bright. - S::Pig - | S::Cow - | S::Sheep - | S::Chicken - | S::Horse - | S::Donkey - | S::Llama - | S::Camel - | S::Wolf - | S::Cat - | S::Fox - | S::Rabbit - | S::Goat - | S::Panda - | S::Armadillo - | S::Mooshroom - | S::Turtle - | S::Frog - | S::Bee => { - let tag = match species { - S::Mooshroom => "minecraft:mooshrooms_spawnable_on", - S::Camel => "minecraft:camels_spawnable_on", - S::Wolf => "minecraft:wolves_spawnable_on", - S::Fox => "minecraft:foxes_spawnable_on", - S::Rabbit => "minecraft:rabbits_spawnable_on", - S::Goat => "minecraft:goats_spawnable_on", - S::Armadillo => "minecraft:armadillo_spawnable_on", - S::Turtle => "minecraft:turtles_spawnable_on", - S::Frog => "minecraft:frogs_spawnable_on", - _ => "minecraft:animals_spawnable_on", - }; - w.has_tag(tag, &below) && raw > 8 - } - S::PolarBear => { - w.has_tag("minecraft:polar_bears_spawnable_on_alternate", &below) - || w.has_tag("minecraft:animals_spawnable_on", &below) && raw > 8 - } - S::Ocelot | S::Parrot => { - (w.has_tag("minecraft:parrots_spawnable_on", &below) - || below.contains("leaves") - || below == "minecraft:grass_block") - && raw > 8 - } - S::Bat => { - // Bat.checkBatSpawnRules: below sea level, dark. - if y >= 63 { - return false; - } - let block = i32::from(light & 15).max(i32::from(light >> 4)); - block <= random.next_int_bound(4).unwrap_or(0) - } - S::Slime => { - // Swamp at night by moon brightness, or slime chunks below y 40. - y < 40 && random.next_int_bound(10).unwrap_or(1) == 0 - } - // GlowSquid.checkGlowSquidSpawnRules: deep, pitch dark water. - S::GlowSquid => y <= 63 - 33 && light == 0 && w.block_name(x, y, z) == "minecraft:water", - S::Squid | S::Cod | S::Salmon | S::TropicalFish | S::Pufferfish | S::Dolphin => { - // WaterAnimal.checkSurfaceWaterAnimalSpawnRules: sea level - 13 ..= sea level. - (50..=63).contains(&y) - && w.fluid(x, y - 1, z) == Fluid::Water - && w.block_name(x, y + 1, z) == "minecraft:water" - } - S::Axolotl => w.block_name(x, y - 1, z) == "minecraft:clay", - S::Strider => w.fluid(x, y, z) == Fluid::Lava, - S::Ghast - | S::MagmaCube - | S::ZombifiedPiglin - | S::Piglin - | S::Hoglin - | S::Blaze - | S::WitherSkeleton - | S::Enderman - if w.nether => - { - !w.block_name(x, y - 1, z).contains("nether_wart_block") || species == S::Ghast - } - // Monster.checkSurfaceMonstersSpawnRules. - S::Husk | S::Stray | S::CamelHusk => { - dark_enough(w, random, x, y, z) && w.can_see_sky(x, y, z) - } - // AbstractNautilus.checkNautilusSpawnRules. - S::Nautilus => super::nautilus::spawn_rules_ok(w, x, y, z), - // SulfurCube.checkSulfurCubeSpawnRules: anywhere it fits. - S::SulfurCube => true, - S::Drowned => w.fluid(x, y, z) == Fluid::Water && dark_enough(w, random, x, y, z), - _ => { - // Monster.checkMonsterSpawnRules - !w.nether && dark_enough(w, random, x, y, z) || w.nether - } - } + super::spawn_rules::check_spawn_rules( + species, + w, + super::spawn_rules::Reason::Natural, + random, + x, + y, + z, + ) } /// Mob.finalizeSpawn for natural, chunk-generation and summoned mobs. /// `DifficultyInstance`: the local difficulty at a position. diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSpawnRulesOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSpawnRulesOracle.java new file mode 100644 index 000000000..c02da47a6 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSpawnRulesOracle.java @@ -0,0 +1,204 @@ +package dev.horizonlab.parity; + +import com.mojang.authlib.GameProfile; +import java.io.PrintWriter; +import java.lang.reflect.*; +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.resources.ResourceKey; +import net.minecraft.server.Bootstrap; +import net.minecraft.server.RegistryLayer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.packs.PackType; +import net.minecraft.server.packs.repository.ServerPacksSource; +import net.minecraft.server.packs.resources.MultiPackResourceManager; +import net.minecraft.tags.TagLoader; +import net.minecraft.util.RandomSource; +import net.minecraft.world.Difficulty; +import net.minecraft.world.entity.*; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.LightLayer; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.border.WorldBorder; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.levelgen.Heightmap; +import net.minecraft.world.level.material.FluidState; + +/** + * Original oracle: SpawnPlacements.isSpawnPositionOk and checkSpawnRules for an + * entity type at a position of a controlled column world. The stand-in + * ServerLevel answers block states from the case (air elsewhere), uniform sky + * and block light, the sky darkening, thunder, difficulty, dimension type, + * biome, sea level, WORLD_SURFACE height, world seed, the surface slime spawn + * chance and an optional nearby player. Each case prints the two answers and + * the next nextInt(1000) of its random, which pins the number of draws. + */ +public final class VanillaSpawnRulesOracle { + static Object unsafe; + static Method allocate, putObject, objectFieldOffset; + + static Object alloc(Class c) throws Exception { return allocate.invoke(unsafe, c); } + + static void put(Object target, Class owner, String field, Object value) throws Exception { + Field f = owner.getDeclaredField(field); + putObject.invoke(unsafe, target, (long) objectFieldOffset.invoke(unsafe, f), value); + } + + static final class Lvl extends ServerLevel { + Lvl() { super(null, null, null, null, null, null, false, 0L, List.of(), false); } + RegistryAccess registries; + Map column = new HashMap<>(); + int x0, z0, sky, block, darken, sea, surface; + boolean thunder; + long seed; + Difficulty difficulty; + DimensionType dimension; + Holder biome; + net.minecraft.world.attribute.EnvironmentAttributeSystem attributes; + List playerList = new ArrayList<>(); + WorldBorder border = new WorldBorder(); + int next = 1; + @Override public RegistryAccess registryAccess() { return registries; } + @Override public Difficulty getDifficulty() { return difficulty; } + @Override public long getGameTime() { return 0L; } + @Override public int getNextEntityId() { return next++; } + @Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags(); } + @Override public BlockState getBlockState(BlockPos pos) { + if (pos.getX() != x0 || pos.getZ() != z0) return Blocks.AIR.defaultBlockState(); + return column.getOrDefault(pos.getY(), Blocks.AIR.defaultBlockState()); + } + @Override public FluidState getFluidState(BlockPos pos) { return getBlockState(pos).getFluidState(); } + @Override public int getBrightness(LightLayer layer, BlockPos pos) { return layer == LightLayer.SKY ? sky : block; } + @Override public int getRawBrightness(BlockPos pos, int darkening) { return Math.max(block, sky - darkening); } + @Override public int getSkyDarken() { return darken; } + @Override public boolean isThundering() { return thunder; } + @Override public int getSeaLevel() { return sea; } + @Override public int getHeight(Heightmap.Types type, int x, int z) { return surface; } + @Override public long getSeed() { return seed; } + @Override public DimensionType dimensionType() { return dimension; } + @Override public Holder getBiome(BlockPos pos) { return biome; } + @Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes() { return attributes; } + @Override public WorldBorder getWorldBorder() { return border; } + @SuppressWarnings({"unchecked", "rawtypes"}) + @Override public List players() { return playerList; } + } + + static final class OraclePlayer extends Player { + final GameType mode; + OraclePlayer(Level level, GameType mode) { super(level, new GameProfile(new UUID(1L, 2L), "oracle")); this.mode = mode; } + @Override public GameType gameMode() { return mode; } + @Override public boolean isCreative() { return mode == GameType.CREATIVE; } + @Override public boolean isSpectator() { return mode == GameType.SPECTATOR; } + @Override public net.minecraft.world.item.component.ResolvableProfile getProfile() { return net.minecraft.world.item.component.ResolvableProfile.createResolved(this.getGameProfile()); } + } + + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe"); + unsafeField.setAccessible(true); + unsafe = unsafeField.get(null); + allocate = unsafe.getClass().getMethod("allocateInstance", Class.class); + putObject = unsafe.getClass().getMethod("putObject", Object.class, long.class, Object.class); + objectFieldOffset = unsafe.getClass().getMethod("objectFieldOffset", Field.class); + 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); + var access = layers.replaceFrom(RegistryLayer.WORLD, world).compositeAccess(); + + Lvl level = (Lvl) alloc(Lvl.class); + level.registries = access; + level.column = new HashMap<>(); + level.playerList = new ArrayList<>(); + level.border = new WorldBorder(); + put(level, Level.class, "random", RandomSource.create(0L)); + var biomes = access.lookupOrThrow(Registries.BIOME); + var dimensions = access.lookupOrThrow(Registries.DIMENSION_TYPE); + var blocks = access.lookupOrThrow(Registries.BLOCK); + + if (args.length > 2 && args[2].equals("facts")) { + try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) { + for (var type : BuiltInRegistries.ENTITY_TYPE) + w.println(BuiltInRegistries.ENTITY_TYPE.getKey(type) + " peaceful=" + type.isAllowedInPeaceful() + " fire_immune=" + type.fireImmune() + + " placement=" + SpawnPlacements.getPlacementType(type) + " heightmap=" + SpawnPlacements.getHeightmapType(type)); + } + System.exit(0); + } + + List lines = Files.readAllLines(Path.of(args[0])); + try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) { + for (String raw : lines) { + if (raw.isBlank()) continue; + Map c = new LinkedHashMap<>(); + for (String token : raw.trim().split("\\s+")) { + int eq = token.indexOf('='); + if (eq < 0) c.put("name", token); else c.put(token.substring(0, eq), token.substring(eq + 1)); + } + try { + int y = Integer.parseInt(c.getOrDefault("y", "64")); + level.x0 = Integer.parseInt(c.getOrDefault("x", "8")); + level.z0 = Integer.parseInt(c.getOrDefault("z", "8")); + level.column.clear(); + for (var e : c.entrySet()) { + if (e.getKey().startsWith("at")) { + int offset = Integer.parseInt(e.getKey().substring(2)); + level.column.put(y + offset, net.minecraft.commands.arguments.blocks.BlockStateParser.parseForBlock(blocks, e.getValue(), false).blockState()); + } + } + level.sky = Integer.parseInt(c.getOrDefault("sky", "15")); + level.block = Integer.parseInt(c.getOrDefault("light", "0")); + level.darken = Integer.parseInt(c.getOrDefault("darken", "0")); + level.thunder = c.getOrDefault("thunder", "0").equals("1"); + level.sea = Integer.parseInt(c.getOrDefault("sea", "63")); + level.surface = Integer.parseInt(c.getOrDefault("surface", "0")); + level.seed = Long.parseLong(c.getOrDefault("wseed", "0")); + level.difficulty = Difficulty.byName(c.getOrDefault("difficulty", "normal")); + level.dimension = dimensions.getOrThrow(ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.parse(c.getOrDefault("dim", "minecraft:overworld")))).value(); + level.biome = biomes.getOrThrow(ResourceKey.create(Registries.BIOME, Identifier.parse(c.getOrDefault("biome", "minecraft:plains")))); + level.attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder() + .addConstantLayer(net.minecraft.world.attribute.EnvironmentAttributeMap.builder() + .set(net.minecraft.world.attribute.EnvironmentAttributes.SURFACE_SLIME_SPAWN_CHANCE, Float.parseFloat(c.getOrDefault("slime", "0.0"))) + .build()) + .build(); + level.playerList.clear(); + if (c.containsKey("player")) { + String[] p = c.get("player").split(","); + Player player = new OraclePlayer(level, GameType.byName(p.length > 3 ? p[3] : "survival")); + player.setPos(level.x0 + Double.parseDouble(p[0]), y + Double.parseDouble(p[1]), level.z0 + Double.parseDouble(p[2])); + level.playerList.add(player); + } + EntityType type = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(c.get("type"))); + EntitySpawnReason reason = EntitySpawnReason.valueOf(c.getOrDefault("reason", "natural").toUpperCase(Locale.ROOT)); + BlockPos pos = new BlockPos(level.x0, y, level.z0); + RandomSource random = RandomSource.create(Long.parseLong(c.getOrDefault("seed", "0"))); + boolean ok = SpawnPlacements.isSpawnPositionOk(type, level, pos); + boolean rules = SpawnPlacements.checkSpawnRules(type, level, reason, pos, random); + w.println(c.get("name") + " " + ok + " " + rules + " " + random.nextInt(1000)); + } catch (Throwable t) { + Throwable cause = t instanceof InvocationTargetException ite ? ite.getCause() : t; + StringBuilder line = new StringBuilder(c.get("name") + " error " + cause); + if (System.getenv("ORACLE_TRACE") != null) for (var frame : cause.getStackTrace()) line.append("\n at ").append(frame); + w.println(line); + } + } + } + System.exit(0); + } +} diff --git a/tools/test_spawn_rules_parity.py b/tools/test_spawn_rules_parity.py new file mode 100644 index 000000000..4050fae46 --- /dev/null +++ b/tools/test_spawn_rules_parity.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""Compare spawn placement checks and spawn predicates with vanilla. + +Java (VanillaSpawnRulesOracle) runs SpawnPlacements.isSpawnPositionOk and +checkSpawnRules on a stand-in ServerLevel holding one column of blocks with +uniform light; Rust (spawn_rules_fixture) runs horizon_client::mobs::spawn_rules +on the same column. Every mob type is tried on surfaces, caves, water, lava, +the nether and the end, dangerous blocks, light levels, thunder, difficulty, +biomes, slime chunks, nearby players and several spawn reasons; each case +also prints the next draw of its random, pinning the number of draws. +""" +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 + +# Living types that are not Horizon mob types or not mobs at all. +SKIPPED = {'player', 'mannequin', 'armor_stand', 'ender_dragon', 'giant', 'copper_golem'} + +SCENARIOS = { + 'grass-day': dict(b=dict(m1='minecraft:grass_block'), sky=15, surface=64), + 'grass-night': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=11, surface=64), + 'grass-dusk': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=7, surface=64), + 'grass-thunder': dict(b=dict(m1='minecraft:grass_block'), sky=15, thunder=1, surface=64), + 'grass-peaceful': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=11, difficulty='peaceful', surface=64), + 'grass-torch': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=11, light=9, surface=64), + 'cave-dark': dict(b=dict(m1='minecraft:stone'), sky=0, y=20, surface=80), + 'cave-lit1': dict(b=dict(m1='minecraft:stone'), sky=0, light=1, y=20, surface=80), + 'cave-lit8': dict(b=dict(m1='minecraft:deepslate'), sky=0, light=8, y=-20, surface=80), + 'cave-lit12': dict(b=dict(m1='minecraft:stone'), sky=0, light=12, y=20, surface=80), + 'cave-dim': dict(b=dict(m1='minecraft:stone'), sky=3, y=40, surface=80), + 'water-surface': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=15, y=60, surface=64, biome='minecraft:ocean'), + 'water-warm': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=15, y=58, surface=64, biome='minecraft:warm_ocean'), + 'water-deep': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=0, y=25, surface=64, biome='minecraft:deep_ocean'), + 'water-deep-lit': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=0, light=3, y=25, surface=64, biome='minecraft:lukewarm_ocean'), + 'water-mid': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=15, y=45, surface=64, biome='minecraft:cold_ocean'), + 'water-roofed': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water', p3='minecraft:stone'), sky=0, y=50, surface=64, biome='minecraft:ocean'), + 'water-river': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=0, y=50, surface=64, biome='minecraft:river', darken=11), + 'water-conductor': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:stone'), sky=15, y=60, surface=64), + 'water-seagrass': dict(b=dict(m1='minecraft:sand', p0='minecraft:water', p1='minecraft:water'), sky=15, y=55, surface=64, biome='minecraft:ocean'), + 'water-clay': dict(b=dict(m1='minecraft:clay', p0='minecraft:water', p1='minecraft:water'), sky=0, y=10, surface=64, biome='minecraft:lush_caves'), + 'lava-nether': dict(b=dict(m1='minecraft:lava', p0='minecraft:lava', p1='minecraft:lava'), sky=0, light=15, y=31, sea=32, dim='minecraft:the_nether', biome='minecraft:basalt_deltas'), + 'lava-open': dict(b=dict(m1='minecraft:lava', p0='minecraft:lava'), sky=0, light=15, y=31, sea=32, dim='minecraft:the_nether', biome='minecraft:nether_wastes'), + 'nether-dark': dict(b=dict(m1='minecraft:netherrack'), sky=0, light=0, y=70, sea=32, dim='minecraft:the_nether', biome='minecraft:nether_wastes'), + 'nether-lit7': dict(b=dict(m1='minecraft:netherrack'), sky=0, light=7, y=70, sea=32, dim='minecraft:the_nether', biome='minecraft:crimson_forest'), + 'nether-lit8': dict(b=dict(m1='minecraft:crimson_nylium'), sky=0, light=8, y=70, sea=32, dim='minecraft:the_nether', biome='minecraft:crimson_forest'), + 'nether-wart': dict(b=dict(m1='minecraft:nether_wart_block'), sky=0, light=0, y=70, sea=32, dim='minecraft:the_nether', biome='minecraft:crimson_forest'), + 'nether-soul': dict(b=dict(m1='minecraft:soul_sand'), sky=0, light=3, y=40, sea=32, dim='minecraft:the_nether', biome='minecraft:soul_sand_valley'), + 'nether-magma': dict(b=dict(m1='minecraft:magma_block'), sky=0, light=3, y=40, sea=32, dim='minecraft:the_nether', biome='minecraft:basalt_deltas'), + 'end': dict(b=dict(m1='minecraft:end_stone'), sky=0, light=0, y=60, dim='minecraft:the_end', biome='minecraft:the_end'), + 'end-lit': dict(b=dict(m1='minecraft:end_stone'), sky=0, light=14, y=60, dim='minecraft:the_end', biome='minecraft:end_highlands'), + 'ice-frozen': dict(b=dict(m1='minecraft:ice'), sky=15, y=63, surface=64, biome='minecraft:frozen_ocean'), + 'ice-plains': dict(b=dict(m1='minecraft:packed_ice'), sky=15, y=64, surface=64, biome='minecraft:snowy_plains'), + 'snow-block': dict(b=dict(m1='minecraft:snow_block'), sky=15, darken=11, y=70, surface=70, biome='minecraft:snowy_plains'), + 'snow-layer': dict(b=dict(m1='minecraft:grass_block[snowy=true]', p0='minecraft:snow'), sky=15, y=70, surface=71, biome='minecraft:snowy_taiga'), + 'powder-snow-stray': dict(b=dict(m1='minecraft:snow_block', p1='minecraft:powder_snow', p2='minecraft:powder_snow'), sky=15, darken=11, y=90, surface=93, biome='minecraft:frozen_peaks'), + 'sand-beach': dict(b=dict(m1='minecraft:sand'), sky=15, y=63, surface=64, biome='minecraft:beach'), + 'sand-desert': dict(b=dict(m1='minecraft:sand'), sky=15, darken=11, y=70, surface=70, biome='minecraft:desert'), + 'red-sand': dict(b=dict(m1='minecraft:red_sand'), sky=15, y=80, surface=80, biome='minecraft:badlands'), + 'leaves-jungle': dict(b=dict(m1='minecraft:jungle_leaves'), sky=15, y=90, surface=90, biome='minecraft:jungle'), + 'grass-jungle': dict(b=dict(m1='minecraft:grass_block'), sky=15, y=70, surface=70, biome='minecraft:jungle'), + 'mycelium': dict(b=dict(m1='minecraft:mycelium'), sky=15, y=70, surface=70, biome='minecraft:mushroom_fields'), + 'podzol': dict(b=dict(m1='minecraft:podzol'), sky=15, y=70, surface=70, biome='minecraft:old_growth_pine_taiga'), + 'mud-swamp': dict(b=dict(m1='minecraft:mud'), sky=15, y=62, surface=62, biome='minecraft:mangrove_swamp'), + 'stone-peaks': dict(b=dict(m1='minecraft:stone'), sky=15, y=160, surface=160, biome='minecraft:jagged_peaks'), + 'coarse-savanna': dict(b=dict(m1='minecraft:coarse_dirt'), sky=15, y=70, surface=70, biome='minecraft:savanna'), + 'slab-bottom': dict(b=dict(m1='minecraft:oak_slab[type=bottom]'), sky=0, y=40, surface=80), + 'slab-top': dict(b=dict(m1='minecraft:oak_slab[type=top]'), sky=0, y=40, surface=80), + 'glass': dict(b=dict(m1='minecraft:glass'), sky=0, y=40, surface=80), + 'glowstone': dict(b=dict(m1='minecraft:glowstone'), sky=0, light=15, y=40, surface=80), + 'fire': dict(b=dict(m1='minecraft:netherrack', p0='minecraft:fire'), sky=0, light=15, y=40, surface=80), + 'soul-fire': dict(b=dict(m1='minecraft:soul_soil', p0='minecraft:soul_fire'), sky=0, light=10, y=40, sea=32, dim='minecraft:the_nether', biome='minecraft:soul_sand_valley'), + 'wither-rose': dict(b=dict(m1='minecraft:grass_block', p0='minecraft:wither_rose'), sky=0, y=40, surface=80), + 'berry-bush': dict(b=dict(m1='minecraft:grass_block', p0='minecraft:sweet_berry_bush'), sky=15, y=70, surface=70, biome='minecraft:taiga'), + 'cactus': dict(b=dict(m1='minecraft:sand', p0='minecraft:cactus'), sky=0, y=70, surface=72, biome='minecraft:desert'), + 'powder-snow-feet': dict(b=dict(m1='minecraft:snow_block', p0='minecraft:powder_snow'), sky=15, darken=11, y=90, surface=91, biome='minecraft:snowy_slopes'), + 'campfire': dict(b=dict(m1='minecraft:stone', p0='minecraft:campfire[lit=true]'), sky=0, light=15, y=40, surface=80), + 'campfire-out': dict(b=dict(m1='minecraft:stone', p0='minecraft:campfire[lit=false]'), sky=0, y=40, surface=80), + 'rail': dict(b=dict(m1='minecraft:stone', p0='minecraft:rail'), sky=0, y=40, surface=80), + 'redstone-torch': dict(b=dict(m1='minecraft:stone', p0='minecraft:redstone_torch'), sky=0, light=7, y=40, surface=80), + 'tall-grass': dict(b=dict(m1='minecraft:grass_block', p0='minecraft:short_grass', p1='minecraft:air'), sky=15, darken=11, y=70, surface=70), + 'low-ceiling': dict(b=dict(m1='minecraft:stone', p1='minecraft:stone'), sky=0, y=40, surface=80), + 'swamp-surface': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=11, y=62, surface=63, biome='minecraft:swamp', slime=0.5), + 'swamp-full-moon': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=4, y=64, surface=65, biome='minecraft:swamp', slime=0.5), + 'swamp-new-moon': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=11, y=63, surface=64, biome='minecraft:swamp', slime=0.0), + 'bat-cave': dict(b=dict(m1='minecraft:stone'), sky=0, y=10, surface=80), + 'bat-surface': dict(b=dict(m1='minecraft:stone'), sky=0, y=79, surface=79), +} +REASONS = ['natural', 'natural', 'natural', 'chunk_generation', 'spawner', 'trial_spawner', 'reinforcement', 'patrol'] + + +def corpus(types): + rng = random.Random(0x5350574E) + cases = [] + for t in types: + n = t.split(':')[1] + for name, s in SCENARIOS.items(): + for k in range(3): + kv = {k2: v for k2, v in s.items() if k2 != 'b'} + kv.setdefault('y', 64) + for key, block in s['b'].items(): + kv['at' + ('-' if key[0] == 'm' else '') + key[1:]] = block + kv['reason'] = REASONS[k] if k == 0 else rng.choice(REASONS) + kv['seed'] = rng.randrange(-2**47, 2**47) + cases.append(f'{n}/{name}/{k} type={t} ' + ' '.join(f'{a}={b}' for a, b in kv.items())) + # Slime chunks: deep caves at many chunk positions and world seeds. + if n in ('slime', 'zombie'): + for k in range(600 if n == 'slime' else 60): + cases.append(f'{n}/slime-chunk/{k} type={t} at-1=minecraft:stone sky=0 y={rng.randrange(-60, 45)} ' + f'x={rng.randrange(-4000, 4000)} z={rng.randrange(-4000, 4000)} wseed={rng.randrange(-2**63, 2**63)} ' + f'seed={rng.randrange(-2**47, 2**47)} reason=natural surface=80') + # Nearby players (silverfish and endermite refuse to spawn next to a targetable one). + for k, player in enumerate(['1,0,1,survival', '1,0,1,creative', '4,0,4,survival', '3,1,3,adventure', '0,4.4,0,survival', + '2,2,2,spectator']): + cases.append(f'{n}/player/{k} type={t} at-1=minecraft:stone sky=0 y=20 surface=80 player={player} ' + f'seed={rng.randrange(-2**47, 2**47)} reason={rng.choice(REASONS)}') + return cases + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--prepare', action='store_true') + args = parser.parse_args() + build = lab.LOCAL / 'rust-spawn-rules-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' + entity_types = json.loads((resources / 'entity-types.json').read_text()) + types = sorted(t for t, v in entity_types.items() if 'attributes' in v and t.split(':')[1] not in SKIPPED) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSpawnRulesOracle.java' + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/spawn_rules_fixture.rs', + lab.ROOT / 'crates/horizon-client/src/mobs/spawn_rules.rs'] + tested = base.source_hashes(sources) + inputs = build / 'inputs.txt' + cases = corpus(types) + inputs.write_text(''.join(line + '\n' for line in cases), 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', '-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'), + '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') + run(['java', '-Xmx2G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), + 'dev.horizonlab.parity.VanillaSpawnRulesOracle', inputs, build / 'server.txt'], 'server') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'spawn_rules_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/spawn_rules_fixture' + run([binary, resources, inputs, build / 'rust.txt'], 'rust') + vanilla = (build / 'server.txt').read_text().splitlines() + errors = [l for l in vanilla if ' error ' in l] + if errors: + raise SystemExit(f'oracle errors ({len(errors)}): {errors[:5]}') + rust = (build / 'rust.txt').read_text().splitlines() + bad = [(a, b) for a, b in zip(vanilla, rust) if a != b] + if bad or len(vanilla) != len(rust): + report = '\n'.join(f' vanilla {a}\n rust {b}' for a, b in bad[:40]) + raise SystemExit(f'{len(bad)} of {len(vanilla)} cases differ (rust {len(rust)} lines):\n{report}') + base.ensure_sources_unchanged(sources, tested) + lab.write_json(build / 'report.json', { + 'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'cases': len(cases), + 'types': len(types), 'scenarios': sorted(SCENARIOS), 'sources_sha256': tested, + 'scope': 'SpawnPlacements.isSpawnPositionOk (placement types, isValidSpawn, isValidEmptySpawnBlock with per-type ' + 'dangerous blocks) and checkSpawnRules (every registered predicate, peaceful, spawn reasons) with the ' + 'random draw count.'}) + print(f'{len(cases):,} spawn rule cases over {len(types)} entity types match vanilla') + + +if __name__ == '__main__': + main()