From c90cd5f0726ebbdbac0828eb2f76d41e1f52a3dd Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 17:45:09 +0200 Subject: [PATCH] Match vanilla llama caravans, trader llamas, breeding and wolves A lead gives its mob a home at the holder (PathfinderMob.whenLeashedTo) and every random position helper honours homes (generateRandomPos- TowardDirection's lean back and GoalUtils.isRestricted), as the happy ghast's float area now does too. LlamaFollowCaravanGoal keeps 2.1F, a llama's baby and the breeding experience are drawn from the parent's random, wolves run from llamas by strength (WolfAvoidEntityGoal), a growing mob refits its box (fudgePositionAfterSizeChange) and a happy ghast's new controls want nothing. Scenarios can lead mobs. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/mob_ai_probe.rs | 10 ++ crates/horizon-client/src/game/creatures.rs | 24 ++- crates/horizon-client/src/game/dispenser.rs | 2 +- crates/horizon-client/src/game/ghasts.rs | 9 + crates/horizon-client/src/game/leads.rs | 2 +- crates/horizon-client/src/mobs.rs | 13 +- crates/horizon-client/src/mobs/ai.rs | 8 + .../horizon-client/src/mobs/animal_brain.rs | 1 + crates/horizon-client/src/mobs/caravan.rs | 10 +- crates/horizon-client/src/mobs/goals.rs | 156 +++++++++++------- crates/horizon-client/src/mobs/happy_ghast.rs | 24 ++- crates/horizon-client/src/mobs/leash.rs | 23 +++ crates/horizon-client/src/mobs/living.rs | 73 ++++++++ crates/horizon-client/src/mobs/llama.rs | 55 +++++- crates/horizon-client/src/mobs/tame.rs | 64 ++++--- .../horizonlab/parity/VanillaMobAiOracle.java | 11 ++ tools/test_mob_ai_parity.py | 10 ++ 17 files changed, 389 insertions(+), 106 deletions(-) diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 4ae4c152d..8e417b53e 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -244,6 +244,11 @@ fn seen(m: &Mob) -> Seen { .flatten(), profession: m.extra.variant2, xp: horizon_client::mobs::villager::xp(m), + stats: [ + f64::from(m.attrs.max_health), + m.extra.vector[0], + m.attrs.speed, + ], } } @@ -480,6 +485,11 @@ fn main() -> horizon_client::Result<()> { "tame" => m.extra.tame = true, x if x.starts_with("age=") => m.extra.age = x[4..].parse().unwrap(), x if x.starts_with("strength=") => m.extra.variant2 = x[9..].parse().unwrap(), + "leashed" => m.extra.leash = Some(horizon_client::mobs::leash::Holder::Player), + x if x.starts_with("leashto=") => { + let n: u32 = x[8..].parse().unwrap(); + m.extra.leash = Some(horizon_client::mobs::leash::Holder::Mob(100_000 + n)); + } other => panic!("unknown mob flag {other}"), } } diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 4740b523c..553fb4ea3 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -135,6 +135,11 @@ fn seen(m: &Mob, player: Option<[i32; 4]>) -> Seen { .flatten(), profession: m.extra.variant2, xp: horizon_client::mobs::villager::xp(m), + stats: [ + f64::from(m.attrs.max_health), + m.extra.vector[0], + m.attrs.speed, + ], } } impl Game<'_> { @@ -886,7 +891,11 @@ impl Game<'_> { } } }, - MobEvent::Breed { parent, partner } => self.breed(parent, partner), + MobEvent::Breed { + parent, + partner, + llama, + } => self.breed(parent, partner, llama), MobEvent::LockGaze { mob, partner } => { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { horizon_client::mobs::animal_brain::lock_gaze(m, partner); @@ -981,7 +990,12 @@ impl Game<'_> { } } /// Animal.spawnChildFromBreeding - fn breed(&mut self, parent: u32, partner: u32) { + fn breed( + &mut self, + parent: u32, + partner: u32, + llama: Option>, + ) { let Some(p) = self.mobs.iter().find(|m| m.id == parent).cloned() else { return; }; @@ -1034,6 +1048,12 @@ impl Game<'_> { && let Some(child) = self.mobs.iter_mut().find(|m| m.id == id) { child.extra.age = -24000; + // A llama's baby was drawn in the parent's tick, with the + // experience. + if let Some(o) = llama { + horizon_client::mobs::llama::apply_offspring(child, &o); + return; + } if horizon_client::mobs::equine::is_equine(p.species()) { let other = q.clone().unwrap_or_else(|| p.clone()); let mut r = self.world.random.clone(); diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index f6a7e5a58..816b82192 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -1912,7 +1912,7 @@ impl Game<'_> { } // Leashable.dropLeash: a lead item at the leashed entity's feet. let drop = |game: &mut Self, j: usize| { - if game.mobs[j].extra.leash.take().is_some() { + if horizon_client::mobs::leash::remove(&mut game.mobs[j]).is_some() { let at = game.mobs[j].position; game.spawn_at_location(at, 0.0, ItemStack::new("minecraft:lead", 1)); } diff --git a/crates/horizon-client/src/game/ghasts.rs b/crates/horizon-client/src/game/ghasts.rs index c324ecfef..40b4a574d 100644 --- a/crates/horizon-client/src/game/ghasts.rs +++ b/crates/horizon-client/src/game/ghasts.rs @@ -48,6 +48,9 @@ impl Game<'_> { let id = self.mobs[index].id; self.break_leash(id, true, false); let was_empty = self.mobs[index].rider.is_none(); + // addPassenger: the rider is not standing on top, so no still + // timeout. + self.mobs[index].extra.counter = 0; self.yaw = self.mobs[index].yaw; self.riding = Some(id); self.mount.reset_jump(); @@ -62,6 +65,12 @@ impl Game<'_> { } /// Getting off lands on top of it. pub(super) fn dismount_happy_ghast(&mut self, id: u32) { + // removePassenger: held still for half a second, and with no one + // aboard the ghast forgets its home. + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + m.extra.counter = 10; + m.ai.home = None; + } let Some(m) = self.mobs.iter().find(|m| m.id == id) else { return; }; diff --git a/crates/horizon-client/src/game/leads.rs b/crates/horizon-client/src/game/leads.rs index 77ccc9a97..699b362f8 100644 --- a/crates/horizon-client/src/game/leads.rs +++ b/crates/horizon-client/src/game/leads.rs @@ -76,7 +76,7 @@ impl Game<'_> { let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) else { return; }; - if m.extra.leash.take().is_none() { + if horizon_client::mobs::leash::remove(m).is_none() { return; } let at = [m.position.x, m.position.y, m.position.z]; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index e17a29e82..f8b2eb4c2 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -741,6 +741,9 @@ pub enum MobEvent { Breed { parent: u32, partner: u32, + /// A llama's baby, drawn from the parent's random as + /// `Llama.getBreedOffspring` does. + llama: Option>, }, /// Replace a block by name (sheep turning grass to dirt), optionally with /// the destroy effect. @@ -915,9 +918,13 @@ pub struct Seen { /// A villager's `POTENTIAL_JOB_SITE` and `MEETING_POINT`. pub potential_job: Option<[i32; 3]>, pub meeting: Option<[i32; 3]>, - /// A villager's profession (index into `render::PROFESSIONS`) and experience. + /// `variant2`: a villager's profession (index into + /// `render::PROFESSIONS`), a llama's strength. And a villager's experience. pub profession: u8, pub xp: i32, + /// `MAX_HEALTH`, `JUMP_STRENGTH` and `MOVEMENT_SPEED` base values (a + /// horse's breeding stock). + pub stats: [f64; 3], } impl Mob { /// `EntityType.getCategory`'s name. @@ -984,7 +991,9 @@ pub fn apply_brain_events(mobs: &mut [Mob], events: &mut Vec, from: us } // Animal.finalizeSpawnChildFromBreeding: the partner rests and // forgets it at once (the game still makes the baby). - MobEvent::Breed { parent, partner } => { + MobEvent::Breed { + parent, partner, .. + } => { if let Some(m) = mobs.iter_mut().find(|m| m.id == partner) { m.extra.age = 6000; m.extra.in_love = 0; diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index c752f2168..d05fb6c71 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -19,6 +19,9 @@ use horizon_core::{ #[derive(Clone, Debug, Default)] pub struct Ai { + /// `Mob.homePosition` and `homeRadius`: where a restricted mob stays + /// (a lead's holder, a happy ghast's float area). + pub home: Option<([i32; 3], i32)>, pub goals: GoalSelector, pub targets: GoalSelector, pub nav: Navigation, @@ -604,7 +607,12 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: & // AgeableMob.aiStep if m.alive() { if m.extra.age < 0 { + let (bw, bh, _) = m.dims(); m.extra.age += 1; + // setAge at the age boundary: refreshDimensions. + if m.extra.age >= 0 { + m.fudge_position_after_size_change(w, bw, bh); + } } else if m.extra.age > 0 { m.extra.age -= 1; } diff --git a/crates/horizon-client/src/mobs/animal_brain.rs b/crates/horizon-client/src/mobs/animal_brain.rs index 0c7bd6983..c37fa469e 100644 --- a/crates/horizon-client/src/mobs/animal_brain.rs +++ b/crates/horizon-client/src/mobs/animal_brain.rs @@ -1314,6 +1314,7 @@ impl B { cx.events.push(MobEvent::Breed { parent: m.id, partner: id, + llama: None, }); if brain_mut(m).kind == Kind::Sniffer { // Sniffer.spawnChildFromBreeding: the experience diff --git a/crates/horizon-client/src/mobs/caravan.rs b/crates/horizon-client/src/mobs/caravan.rs index 3ba4055a5..15f01d59e 100644 --- a/crates/horizon-client/src/mobs/caravan.rs +++ b/crates/horizon-client/src/mobs/caravan.rs @@ -55,20 +55,21 @@ fn first_is_leashed(cx: &Cx, caravan: u32, leashed: bool, counter: i32) -> bool #[derive(Clone, Debug)] pub struct FollowCaravan { speed: f64, - base_speed: f64, dist_check: i32, } impl FollowCaravan { pub fn new(speed: f64) -> Self { Self { speed, - base_speed: speed, dist_check: 0, } } } impl Goal for FollowCaravan { goal_clone!(); + fn name(&self) -> &'static str { + "LlamaFollowCaravanGoal" + } fn flags(&self) -> u8 { super::goals::MOVE } @@ -158,7 +159,8 @@ impl Goal for FollowCaravan { } fn stop(&mut self, m: &mut Mob, _: &mut Cx) { m.extra.ints[1] = 0; - self.speed = self.base_speed; + // A double 2.1 here, while the llama built it with 2.1F. + self.speed = 2.1; } fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { let caravan = head_of(m); @@ -265,7 +267,7 @@ pub fn trader_llama_tick(m: &mut Mob, w: &MobWorld) { } m.extra.ints[0] = trader.unwrap_or(m.extra.ints[0]) - 1; if m.extra.ints[0] <= 0 { - m.extra.leash = None; + super::leash::remove(m); m.removed = true; } } diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index c984024d0..bee88594f 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -174,6 +174,13 @@ impl GoalSelector { // --- random positions (DefaultRandomPos / LandRandomPos / RandomPos) ------- +/// `Mob.isWithinHome(BlockPos)`. +pub fn within_home(c: [i32; 3], r: i32, p: [i32; 3]) -> bool { + let d = |i: usize| i64::from(c[i] - p[i]); + let r = i64::from(r); + d(0) * d(0) + d(1) * d(1) + d(2) * d(2) < r * r +} + impl Mob { /// PathfinderMob.getWalkTargetValue. pub fn walk_target_value(&self, w: &MobWorld, p: [i32; 3]) -> f32 { @@ -209,17 +216,52 @@ impl Mob { let yt = self.random.next_int_bound(2 * v + 1).unwrap_or(0) - v + fly_height; Some([xt.floor() as i32, yt, zt.floor() as i32]) } - /// RandomPos.generateRandomPosTowardDirection (no home restriction). - fn toward(&mut self, _h: f64, d: [i32; 3]) -> [i32; 3] { + /// RandomPos.generateRandomPosTowardDirection: a mob with a home leans + /// half the distance back toward it. + fn toward(&mut self, h: f64, d: [i32; 3]) -> [i32; 3] { + let (mut xt, mut zt) = (f64::from(d[0]), f64::from(d[2])); + if let Some((c, _)) = self.ai.home + && h > 1.0 + { + if self.position.x > f64::from(c[0]) { + xt -= self.random.next_double() * h / 2.0; + } else { + xt += self.random.next_double() * h / 2.0; + } + if self.position.z > f64::from(c[2]) { + zt -= self.random.next_double() * h / 2.0; + } else { + zt += self.random.next_double() * h / 2.0; + } + } [ - (f64::from(d[0]) + self.position.x).floor() as i32, + (xt + self.position.x).floor() as i32, (f64::from(d[1]) + self.position.y).floor() as i32, - (f64::from(d[2]) + self.position.z).floor() as i32, + (zt + self.position.z).floor() as i32, ] } - fn default_check(&self, w: &MobWorld, p: [i32; 3]) -> bool { + /// `GoalUtils.isRestricted(mobRestricted(mob, h), mob, pos)`: a mob + /// near its home keeps the positions it picks within it. + pub fn restricted(&self, h: f64, p: [i32; 3]) -> bool { + let Some((c, r)) = self.ai.home else { + return false; + }; + let near = { + let d = |i: usize, v: f64| f64::from(c[i]) + 0.5 - v; + let (x, y, z) = ( + d(0, self.position.x), + d(1, self.position.y), + d(2, self.position.z), + ); + let reach = f64::from(r) + h + 1.0; + x * x + y * y + z * z < reach * reach + }; + near && !within_home(c, r, p) + } + fn default_check(&self, w: &MobWorld, h: f64, p: [i32; 3]) -> bool { p[1] >= crate::chunk::MIN_Y && p[1] < 320 + && !self.restricted(h, p) && self.stable_destination(w, p) && self.malus(w.path_type_static(p[0], p[1], p[2])) == 0.0 } @@ -252,7 +294,7 @@ impl Mob { self.pick_best(w, |m| { let d = m.random_direction(h, v); let p = m.toward(f64::from(h), d); - m.default_check(w, p).then_some(p) + m.default_check(w, f64::from(h), p).then_some(p) }) } /// DefaultRandomPos.getPosAway @@ -275,7 +317,7 @@ impl Mob { std::f64::consts::FRAC_PI_2, )?; let p = m.toward(f64::from(h), d); - m.default_check(w, p).then_some(p) + m.default_check(w, f64::from(h), p).then_some(p) }) } /// DefaultRandomPos.getPosTowards @@ -291,7 +333,7 @@ impl Mob { self.pick_best(w, |m| { let d = m.random_direction_within(0.0, f64::from(h), v, 0, xd, zd, max_rad)?; let p = m.toward(f64::from(h), d); - m.default_check(w, p).then_some(p) + m.default_check(w, f64::from(h), p).then_some(p) }) } fn land_up_out_of_solid(&self, w: &MobWorld, mut p: [i32; 3]) -> Option<[i32; 3]> { @@ -304,14 +346,6 @@ impl Mob { let water = w.fluid(p[0], p[1], p[2]) == crate::blocks::Fluid::Water; (!water && self.malus(w.path_type_static(p[0], p[1], p[2])) == 0.0).then_some(p) } - /// The home a mob stays near (`Mob.getHomePosition` / `getHomeRadius`): - /// only happy ghasts keep one here. - fn home(&self) -> Option<([i32; 3], i32)> { - if self.species() != Species::HappyGhast { - return None; - } - self.extra.home.map(|h| (h, self.extra.ints[4])) - } /// `Entity.getViewVector(0)`: `calculateViewVector(xRotO, yRotO)`. pub fn view_vector(&self) -> [f64; 3] { use horizon_core::geometry::trig::Mth; @@ -336,15 +370,6 @@ impl Mob { xd: f64, zd: f64, ) -> Option<[f64; 3]> { - let home = self.home(); - let at = self.position; - let within = |c: [i32; 3], r: f64, p: [f64; 3]| { - let d = |i: usize| f64::from(c[i]) + 0.5 - p[i]; - d(0) * d(0) + d(1) * d(1) + d(2) * d(2) < r * r - }; - // GoalUtils.mobRestricted - let restrict = home - .is_some_and(|(c, r)| within(c, f64::from(r) + f64::from(h) + 1.0, [at.x, at.y, at.z])); self.pick_best(w, |m| { let d = m.random_direction_within( 0.0, @@ -355,39 +380,10 @@ impl Mob { zd, std::f64::consts::FRAC_PI_2, )?; - // RandomPos.generateRandomPosTowardDirection, toward home. - let (mut xt, mut zt) = (f64::from(d[0]), f64::from(d[2])); - if let Some((c, _)) = home - && h > 1 - { - let half = f64::from(h) / 2.0; - if m.position.x > f64::from(c[0]) { - xt -= m.random.next_double() * half; - } else { - xt += m.random.next_double() * half; - } - if m.position.z > f64::from(c[2]) { - zt -= m.random.next_double() * half; - } else { - zt += m.random.next_double() * half; - } - } - let mut p = [ - (xt + m.position.x).floor() as i32, - (f64::from(d[1]) + m.position.y).floor() as i32, - (zt + m.position.z).floor() as i32, - ]; - if p[1] < crate::chunk::MIN_Y || p[1] >= 320 { + let mut p = m.toward(f64::from(h), d); + if p[1] < crate::chunk::MIN_Y || p[1] >= 320 || m.restricted(f64::from(h), p) { return None; } - // GoalUtils.isRestricted: Mob.isWithinHome(BlockPos). - if restrict && let Some((c, r)) = home { - let dd = |i: usize| i64::from(c[i] - p[i]); - let r = i64::from(r); - if dd(0) * dd(0) + dd(1) * dd(1) + dd(2) * dd(2) >= r * r { - return None; - } - } // RandomPos.moveUpOutOfSolid if w.solid(p[0], p[1], p[2]) { p[1] += 1; @@ -403,7 +399,11 @@ impl Mob { self.pick_best(w, |m| { let d = m.random_direction(h, v); let p = m.toward(f64::from(h), d); - if p[1] < crate::chunk::MIN_Y || p[1] >= 320 || !m.stable_destination(w, p) { + if p[1] < crate::chunk::MIN_Y + || p[1] >= 320 + || m.restricted(f64::from(h), p) + || !m.stable_destination(w, p) + { return None; } m.land_up_out_of_solid(w, p) @@ -465,7 +465,11 @@ impl Mob { std::f64::consts::FRAC_PI_2, )?; let p = m.toward(f64::from(h), d); - if p[1] < crate::chunk::MIN_Y || p[1] >= 320 || !m.stable_destination(w, p) { + if p[1] < crate::chunk::MIN_Y + || p[1] >= 320 + || m.restricted(f64::from(h), p) + || !m.stable_destination(w, p) + { return None; } m.land_up_out_of_solid(w, p) @@ -491,7 +495,11 @@ impl Mob { std::f64::consts::FRAC_PI_2, )?; let p = m.toward(f64::from(h), d); - if p[1] < crate::chunk::MIN_Y || p[1] >= 320 || !m.stable_destination(w, p) { + if p[1] < crate::chunk::MIN_Y + || p[1] >= 320 + || m.restricted(f64::from(h), p) + || !m.stable_destination(w, p) + { return None; } m.land_up_out_of_solid(w, p) @@ -1431,6 +1439,8 @@ pub struct AvoidEntity { /// Extra condition on the avoider (e.g. untamed cats only). pub when: Option bool>, from: Vec3, + /// The mob being avoided (`toAvoid`), when it is one. + pub found: Option, } impl AvoidEntity { pub fn new(what: Avoid, max_dist: f32, walk: f64, sprint: f64) -> Self { @@ -1441,6 +1451,7 @@ impl AvoidEntity { sprint, when: None, from: Vec3::ZERO, + found: None, } } pub fn when(mut self, f: fn(&Mob) -> bool) -> Self { @@ -1475,11 +1486,16 @@ impl Goal for AvoidEntity { Avoid::Species(list) => { let id = m.id; let y = m.position.y; - cx.w.nearby(m.position, max, move |s| { - s.id != id && list.contains(&s.species) && (s.position.y - y).abs() <= 3.0 + max - }) - .map(|s| s.position) - .next() + let hit = + cx.w.nearby(m.position, max, move |s| { + s.id != id + && list.contains(&s.species) + && (s.position.y - y).abs() <= 3.0 + max + }) + .map(|s| (s.id, s.position)) + .next(); + self.found = hit.map(|h| h.0); + hit.map(|h| h.1) } }; let Some(from) = found else { return false }; @@ -1716,11 +1732,23 @@ impl Goal for Breed { ); self.love_time += 1; if self.love_time >= reduced(60) && m.distance_sqr(p.position) < 9.0 { + // Llama.getBreedOffspring and finalizeSpawnChildFromBreeding's + // experience, from the parent's random. + let llama = super::llama::is_llama(m.species()).then(|| { + let o = super::llama::breed_offspring(m, &p); + let xp = 1 + m.random.next_int_bound(7).unwrap_or(0); + cx.events.push(MobEvent::Experience { + at: [m.position.x, m.position.y, m.position.z], + amount: xp as u32, + }); + Box::new(o) + }); m.extra.in_love = 0; m.extra.age = 6000; cx.events.push(MobEvent::Breed { parent: m.id, partner: p.id, + llama, }); } } diff --git a/crates/horizon-client/src/mobs/happy_ghast.rs b/crates/horizon-client/src/mobs/happy_ghast.rs index b09383d67..b2b0d2c51 100644 --- a/crates/horizon-client/src/mobs/happy_ghast.rs +++ b/crates/horizon-client/src/mobs/happy_ghast.rs @@ -15,7 +15,7 @@ use horizon_core::{ }; // Happy ghast state: `head` the harness, `scratch[0]` 1 once set up as a -// baby and 2 as an adult, `home` and `ints[4]` the restriction, `counter` +// baby and 2 as an adult, `ai.home` the restriction, `counter` // the end tick of the follow-an-adult range pick. pub const BABY_SCALE: f64 = 0.2375; /// `Attributes.FLYING_SPEED` and the speed `travel` uses (`* 5 / 3`). @@ -33,7 +33,13 @@ fn setup(m: &mut Mob, baby: bool) { m.extra.scratch[0] = if baby { 1 } else { 2 }; m.ai.goals.clear(); m.ai.nav.stop(); + // A new move and look control (nothing wanted) and navigation. m.ai.mov.operation = Operation::Wait; + m.ai.mov.wanted = [0.0; 3]; + m.ai.mov.speed_modifier = 0.0; + m.ai.look.wanted = [0.0; 3]; + m.ai.look.cooldown = 0; + m.extra.counter2 = 0; if baby { m.ai.look.kind = LookKind::Default; m.ai.mov.kind = MoveKind::Flying { @@ -74,8 +80,10 @@ fn restriction_radius(m: &Mob) -> i32 { } /// `Mob.isWithinHome` for the ghast's restriction. fn within_home(m: &Mob, p: Vec3) -> bool { - let Some(h) = m.extra.home else { return true }; - let r = f64::from(m.extra.ints[4]); + let Some((h, r)) = m.ai.home else { + return true; + }; + let r = f64::from(r); let (dx, dy, dz) = ( f64::from(h[0]) + 0.5 - p.x, f64::from(h[1]) + 0.5 - p.y, @@ -507,17 +515,17 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld) { m.position.y.floor() as i32, m.position.z.floor() as i32, ]; - let stale = match m.extra.home { - Some(h) => { + // !hasHome || !home.closerThan(blockPosition, radius + 16) || radius changed + let stale = match m.ai.home { + Some((h, r)) => { (h[0] - here[0]).pow(2) + (h[1] - here[1]).pow(2) + (h[2] - here[2]).pow(2) >= (radius + 16).pow(2) - || radius != m.extra.ints[4] + || radius != r } None => true, }; if stale { - m.extra.home = Some(here); - m.extra.ints[4] = radius; + m.ai.home = Some((here, radius)); } } // continuousHeal: a point every 30 seconds, every second in rain. diff --git a/crates/horizon-client/src/mobs/leash.rs b/crates/horizon-client/src/mobs/leash.rs index cc48bc4d8..b7c5011ba 100644 --- a/crates/horizon-client/src/mobs/leash.rs +++ b/crates/horizon-client/src/mobs/leash.rs @@ -209,6 +209,21 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } return; }; + // PathfinderMob.whenLeashedTo: home is the holder's block, within the + // elastic distance less one. + let elastic = if m.species() == super::Species::HappyGhast { + 10.0 + } else { + ELASTIC + }; + m.ai.home = Some(( + [ + state.position.x.floor() as i32, + state.position.y.floor() as i32, + state.position.z.floor() as i32, + ], + elastic as i32 - 1, + )); let b = m.bounds(); let (lo, hi) = (b.min_position(), b.max_position()); let center = Vec3::new( @@ -265,6 +280,14 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { }; m.extra.leash_spin *= friction; } +/// The lead comes off (`Mob.onLeashRemoved`): no more home. +pub fn remove(m: &mut Mob) -> Option { + let was = m.extra.leash.take(); + if was.is_some() { + m.ai.home = None; + } + was +} /// `PathfinderMob.closeRangeLeashBehaviour`: walk to within two blocks of /// the holder unless panicking. fn close_range(m: &mut Mob, w: &MobWorld, holder: &HolderState) { diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 66b000840..18f8eed89 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -141,6 +141,38 @@ impl MobWorld<'_> { } } impl Mob { + /// `Entity.refreshDimensions` after growing from `old_w` by `old_h`: + /// `fudgePositionAfterSizeChange` moves the mob to the free spot nearest + /// its old centre where the bigger box fits (`findFreePosition`), or + /// failing that, one that fits at the old height. + pub fn fudge_position_after_size_change(&mut self, w: &MobWorld, old_w: f64, old_h: f64) { + let (new_w, new_h, _) = self.dims(); + let small = new_w <= 4.0 && new_h <= 4.0; + if self.age == 0 || self.no_physics() || !small || !(new_w > old_w || new_h > old_h) { + return; + } + let center = Vec3::new( + self.position.x, + self.position.y + old_h / 2.0, + self.position.z, + ); + let dw = (new_w - old_w).max(0.0) + 1.0e-6; + let dh = (new_h - old_h).max(0.0) + 1.0e-6; + let at = |allowed: Aabb, size_y: f64| free_position(w, allowed, center, new_w, size_y); + if let Some(p) = at(Aabb::of_size(center, Vec3::new(dw, dh, dw)), new_h) { + self.position = Vec3::new(p.x, p.y - new_h / 2.0, p.z); + return; + } + if new_w > old_w + && new_h > old_h + && let Some(p) = at(Aabb::of_size(center, Vec3::new(dw, 1.0e-6, dw)), old_h) + { + self.position = Vec3::new(p.x, p.y - old_h / 2.0 + 1.0e-6, p.z); + } + } + fn no_physics(&self) -> bool { + false + } pub fn eye_y(&self) -> f64 { self.position.y + self.eye_height() } @@ -657,3 +689,44 @@ fn fluid_falling(gravity: f64, falling: bool, m: Vec3) -> Vec3 { m } } + +/// `CollisionGetter.findFreePosition`: within `allowed`, the point nearest +/// `preferred` at which a box of the size, centred there, meets no block. +fn free_position( + w: &MobWorld, + allowed: Aabb, + preferred: Vec3, + size_x: f64, + size_y: f64, +) -> Option { + use horizon_core::geometry::{ShapeOp, VoxelShape}; + let allowed_shape = VoxelShape::from_box(allowed).ok()?; + if allowed_shape.is_empty() { + return None; + } + let half = Vec3::new(size_x / 2.0, size_y / 2.0, size_x / 2.0); + let area = allowed.inflate(half); + let (lo, hi) = (area.min_position(), area.max_position()); + let mut collisions = VoxelShape::empty(); + // getBlockCollisions: the block shapes that reach into the area. + for x in (lo.x - 1.0e-7).floor() as i32 - 1..=(hi.x + 1.0e-7).floor() as i32 + 1 { + for y in (lo.y - 1.0e-7).floor() as i32 - 1..=(hi.y + 1.0e-7).floor() as i32 + 1 { + for z in (lo.z - 1.0e-7).floor() as i32 - 1..=(hi.z + 1.0e-7).floor() as i32 + 1 { + let boxes = w.block_collision_boxes(x, y, z); + let touches = boxes.iter().any(|b| { + let (a, c) = (b.min_position(), b.max_position()); + a.x < hi.x && c.x > lo.x && a.y < hi.y && c.y > lo.y && a.z < hi.z && c.z > lo.z + }); + if !touches { + continue; + } + for b in boxes { + let grown = VoxelShape::from_box(b.inflate(half)).ok()?; + collisions = collisions.join(&grown, ShapeOp::OR).ok()?; + } + } + } + } + let free = allowed_shape.join(&collisions, ShapeOp::ONLY_FIRST).ok()?; + free.closest_point(preferred) +} diff --git a/crates/horizon-client/src/mobs/llama.rs b/crates/horizon-client/src/mobs/llama.rs index 4c68ea81f..b91dc5bfa 100644 --- a/crates/horizon-client/src/mobs/llama.rs +++ b/crates/horizon-client/src/mobs/llama.rs @@ -62,7 +62,7 @@ pub fn register(m: &mut Mob) { g.add(1, Panic::new(2.0)); } g.add(1, equine::RunAroundLikeCrazy); - g.add(2, super::caravan::FollowCaravan::new(2.1)); + g.add(2, super::caravan::FollowCaravan::new(f64::from(2.1_f32))); g.add(3, RangedAttack::new(1.25, 40, 40, 20.0, spit)); g.add(3, Panic::new(1.2)); g.add(4, Breed::new(1.0)); @@ -127,6 +127,59 @@ pub fn offspring(child: &mut Mob, a: &Mob, b: &Mob, r: &mut impl RandomSource) { child.persistent = true; } } +/// A llama's baby as `Llama.getBreedOffspring` makes it. +#[derive(Clone, Debug)] +pub struct Offspring { + pub max_health: f32, + pub jump: f64, + pub speed: f64, + pub strength: u8, + pub variant: u8, +} +/// `Llama.getBreedOffspring` with `AbstractHorse.setOffspringAttributes`, +/// drawn from the parent's random with the partner's stock. +pub fn breed_offspring(m: &mut Mob, partner: &Seen) -> Offspring { + // Seen.profession is the partner's strength. + let top = strength(m).max(i32::from(partner.profession)); + let (health, jump, speed, own) = ( + f64::from(m.attrs.max_health), + m.extra.vector[0], + m.attrs.speed, + m.extra.variant, + ); + let r = &mut m.random; + let max_health = equine::offspring(health, partner.stats[0], 15.0, 30.0, r) as f32; + let jump = equine::offspring(jump, partner.stats[1], 0.4, 1.0, r); + let speed = equine::offspring(speed, partner.stats[2], 0.1125, 0.3375, r); + let mut s = r.next_int_bound(top).unwrap_or(0) + 1; + if r.next_float() < 0.03 { + s += 1; + } + let variant = if r.next_boolean() { + own + } else { + partner.variant + }; + Offspring { + max_health, + jump, + speed, + strength: s.clamp(1, 5) as u8, + variant, + } +} +/// The game makes the baby drawn by `breed_offspring`. +pub fn apply_offspring(child: &mut Mob, o: &Offspring) { + child.attrs.max_health = o.max_health; + child.health = o.max_health; + child.extra.vector[0] = o.jump; + child.attrs.speed = o.speed; + child.extra.variant2 = o.strength; + child.extra.variant = o.variant; + if is_trader(child) { + child.persistent = true; + } +} /// `LlamaHurtByTargetGoal`: stops hunting right after a spit. #[derive(Clone, Debug)] struct LlamaHurtBy(HurtByTarget); diff --git a/crates/horizon-client/src/mobs/tame.rs b/crates/horizon-client/src/mobs/tame.rs index c00706b89..4e5e3d290 100644 --- a/crates/horizon-client/src/mobs/tame.rs +++ b/crates/horizon-client/src/mobs/tame.rs @@ -65,7 +65,7 @@ pub fn register(m: &mut Mob) { g.add(1, Float); g.add(1, TamePanic(Panic::new(1.5))); g.add(2, SitWhenOrdered); - g.add(3, AvoidLlamas); + g.add(3, AvoidLlamas::new()); g.add(4, LeapAtTarget::new(0.4)); g.add(5, MeleeAttack::new(1.0, true)); g.add(6, FollowOwner::new(1.0, 10.0, 2.0)); @@ -255,38 +255,56 @@ impl Goal for SitWhenOrdered { } /// `Wolf.WolfAvoidEntityGoal`: untamed wolves flee llamas. #[derive(Clone, Debug)] -struct AvoidLlamas; +struct AvoidLlamas(super::goals::AvoidEntity); +impl AvoidLlamas { + fn new() -> Self { + Self(super::goals::AvoidEntity::new( + super::goals::Avoid::Species(vec![Species::Llama, Species::TraderLlama]), + 24.0, + 1.5, + 1.5, + )) + } +} +/// `Wolf.WolfAvoidEntityGoal`: a wild wolf runs from a llama, the more +/// likely the stronger it is (`strength >= random.nextInt(5)`), and drops +/// its target while it does. impl Goal for AvoidLlamas { goal_clone!(); + fn name(&self) -> &'static str { + "WolfAvoidEntityGoal" + } fn flags(&self) -> u8 { - MOVE + self.0.flags() } fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - if m.extra.tame { + if !self.0.can_use(m, cx) { return false; } - let pos = m.position; - let llama = - cx.w.nearby(pos, 24.0, |s| { - matches!(s.species, Species::Llama | Species::TraderLlama) && s.alive - }) - .map(|s| s.position) - .next(); - let Some(from) = llama else { + // Seen.profession is the llama's strength (`variant2`). + let Some(strength) = self + .0 + .found + .and_then(|id| cx.w.seen(id)) + .map(|s| s.profession) + else { return false; }; - // DefaultRandomPos.getPosAway(16, 7, from). - let away = Vec3::new(pos.x - from.x, 0.0, pos.z - from.z); - let len = (away.x * away.x + away.z * away.z).sqrt().max(1e-6); - let target = [ - pos.x + away.x / len * 16.0, - pos.y, - pos.z + away.z / len * 16.0, - ]; - m.nav_move_to(cx.w, target, 1.5) + !m.extra.tame && i32::from(strength) >= m.random.next_int_bound(5).unwrap_or(0) } - fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { - !m.ai.nav.is_done() + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.0.can_continue(m, cx) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + m.ai.target = None; + self.0.start(m, cx) + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.stop(m, cx) + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + m.ai.target = None; + self.0.tick(m, cx) } } /// `FollowOwnerGoal(speed, startDistance, stopDistance)`. diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java index dd901df50..a844bcdfb 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java @@ -480,6 +480,9 @@ public final class VanillaMobAiOracle { else if (flag.startsWith("age=")) ((AgeableMob) mob).setAge(Integer.parseInt(flag.substring(4))); else if (flag.startsWith("strength=")) method(net.minecraft.world.entity.animal.equine.Llama.class, "setStrength", int.class) .invoke(mob, Integer.parseInt(flag.substring(9))); + else if (flag.equals("leashed") || flag.startsWith("leashto=")) { + // Leashed once every mob exists (below). + } else throw new IllegalArgumentException(flag); } level.addFreshEntity(mob); @@ -493,6 +496,14 @@ public final class VanillaMobAiOracle { brains.add(brain); seeds.add(spec.seed); } + // Leads: to the player ("leashed") or to the n-th mob ("leashto=n"). + for (int i = 0; i < s.mobs.size(); i++) { + for (String flag : s.mobs.get(i).flags) { + if (flag.equals("leashed")) ((net.minecraft.world.entity.Leashable) mobs.get(i)).setLeashedTo(player, true); + else if (flag.startsWith("leashto=")) ((net.minecraft.world.entity.Leashable) mobs.get(i)) + .setLeashedTo(mobs.get(Integer.parseInt(flag.substring(8))), true); + } + } level.getRandom().setSeed(s.levelSeed); SOUNDS.clear(); Method tickTime = method(ServerLevel.class, "tickTime"); diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index ad6b131c4..cad1bc7de 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -113,6 +113,16 @@ def scenarios(): 'mob minecraft:happy_ghast 0.5 -55 0.5 0 98 persistent']) add('ghastling_grows', 200, ['player 8.5 -60 0.5', 'mob minecraft:happy_ghast 0.5 -57 0.5 0 99 persistent age=-40']) + # Llama caravans: two llamas fall in behind one on the player's lead; a wandering trader's two + # llamas on its leads. + add('llama_caravan', 300, ['player 0.5 -60 0.5', + 'mob minecraft:llama 3.5 -60 0.5 0 101 persistent leashed strength=3', + 'mob minecraft:llama 9.5 -60 2.5 0 102 persistent strength=2', + 'mob minecraft:llama 13.5 -60 -1.5 0 103 persistent strength=1']) + add('trader_llamas', 300, ['player 14.5 -60 0.5', + 'mob minecraft:wandering_trader 0.5 -60 0.5 0 104 persistent', + 'mob minecraft:trader_llama 3.5 -60 1.5 0 105 persistent leashto=0 strength=2', + 'mob minecraft:trader_llama 3.5 -60 -1.5 0 106 persistent leashto=0 strength=4']) return s