From 95015b78289edd7ac89c7627efe99e9b21b82819 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 15:51:58 +0200 Subject: [PATCH 1/8] Compare sniffer animation states, happy ghast layers and the llama decor model The entity model harness now drives the sniffer's five keyframe animation states and its search walk, the happy ghast body item, riding and leash holder on its body, harness and ropes layers, and LlamaDecorLayer's model. Co-Authored-By: Claude Opus 5.5 --- .../examples/entity_anim_fixture.rs | 31 +++++++++++++++++-- .../parity/VanillaEntityAnimOracle.java | 10 ++++++ tools/test_entity_model_parity.py | 9 ++++++ 3 files changed, 48 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/examples/entity_anim_fixture.rs b/crates/horizon-client/examples/entity_anim_fixture.rs index 4864a680f..ff779c2a3 100644 --- a/crates/horizon-client/examples/entity_anim_fixture.rs +++ b/crates/horizon-client/examples/entity_anim_fixture.rs @@ -8,7 +8,7 @@ use horizon_client::mobs::{ anim::{self, Poses, State}, aquatic, body_anim as b_anim, equine, guardian, keyframes::AnimationState, - shulker, species, tame, + shulker, sniffer, species, tame, }; use horizon_core::geometry::Vec3; use serde_json::{Value, json}; @@ -173,6 +173,30 @@ fn entity_state(mob: &mut Mob, species: Species, case: &Value) { mob.anim.states[i].started = case[k].as_f64().map(|v| v as f32); } } + Species::Sniffer => { + if flag("isSearching") { + mob.extra.variant = sniffer::SEARCHING; + } + // Sniffer's animation states, in `sniffer::anim`'s order. + for (i, k) in [ + "feelingHappyAnimationState", + "scentingAnimationState", + "sniffingAnimationState", + "diggingAnimationState", + "risingAnimationState", + ] + .into_iter() + .enumerate() + { + mob.anim.states[i].started = case[k].as_f64().map(|v| v as f32); + } + } + Species::HappyGhast => { + mob.extra.head = case["bodyItem"].as_str().map(Into::into); + if flag("isRidden") { + mob.rider = Some(Default::default()); + } + } Species::Witch if flag("isHoldingItem") => { mob.extra.main_hand = Some("minecraft:potion".into()); } @@ -214,7 +238,10 @@ fn main() -> horizon_client::Result<()> { for cut in cuts { base = base.replace(cut, ""); } - let base = base.replace("undead_horse#", "zombie_horse#"); + // LlamaDecorLayer's model animates like the llama. + let base = base + .replace("undead_horse#", "zombie_horse#") + .replace("#decor", "#main"); let base = base.trim_start_matches("cold_").trim_start_matches("warm_"); let Some(def) = species::ALL.iter().find(|d| { d.model == layer diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java index c9e04db44..6d1fe235a 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java @@ -115,6 +115,16 @@ public final class VanillaEntityAnimOracle { else if (t == boolean.class) f.setBoolean(state, value.getAsBoolean()); else if (t.isEnum()) { for (Object c : t.getEnumConstants()) if (((Enum) c).name().equals(value.getAsString())) f.set(state, c); + } else if (t == net.minecraft.world.item.ItemStack.class) { + // value = an item id. The item components are not bound outside a level, so the stack + // carries none: models only test that it is not empty. + var item = net.minecraft.core.registries.BuiltInRegistries.ITEM.wrapAsHolder(net.minecraft.core.registries.BuiltInRegistries.ITEM.getValue( + net.minecraft.resources.Identifier.parse(value.getAsString()))); + var ctor = net.minecraft.world.item.ItemStack.class.getDeclaredConstructor(net.minecraft.core.Holder.class, int.class, + net.minecraft.core.component.PatchedDataComponentMap.class); + ctor.setAccessible(true); + f.set(state, ctor.newInstance(item, 1, new net.minecraft.core.component.PatchedDataComponentMap( + net.minecraft.core.component.DataComponentMap.EMPTY))); } else if (t.getSimpleName().equals("AnimationState")) { // value = age in ticks since start (negative = stopped) var a = (net.minecraft.world.entity.AnimationState) f.get(state); diff --git a/tools/test_entity_model_parity.py b/tools/test_entity_model_parity.py index 9f5d1090a..cfdb2ab07 100644 --- a/tools/test_entity_model_parity.py +++ b/tools/test_entity_model_parity.py @@ -48,6 +48,8 @@ EXTRAS = [ ('minecraft:pillager#main', 'IllagerModel'), ('minecraft:vindicator#main', 'IllagerModel'), ('minecraft:llama#main', 'LlamaModel'), ('minecraft:trader_llama#main', 'LlamaModel'), ('minecraft:llama_baby#main', 'BabyLlamaModel'), ('minecraft:trader_llama_baby#main', 'BabyLlamaModel'), + # LlamaDecorLayer: the carpet and the trader's blanket. + ('minecraft:llama#decor', 'LlamaModel'), ('minecraft:llama_baby#decor', 'BabyLlamaModel'), ('minecraft:donkey#main', 'DonkeyModel'), ('minecraft:mule#main', 'DonkeyModel'), ('minecraft:donkey_baby#main', 'BabyDonkeyModel'), ('minecraft:mule_baby#main', 'BabyDonkeyModel'), ('minecraft:skeleton_horse#main', 'HorseModel'), ('minecraft:zombie_horse#main', 'HorseModel'), @@ -134,6 +136,8 @@ PIGLIN = [{'armPose': pose, 'maxCrossbowChageDuration': 25.0, 'ticksUsingItem': EQUINE = [{'eatAnimation': 0.6}, {'standAnimation': 0.5}, {'eatAnimation': 0.3, 'standAnimation': 0.4, 'feedingAnimation': 0.7}, {'isInWater': T}, {'standAnimation': 1.0, 'eatAnimation': 1.0}] WATER = [{'isInWater': T}, {'isInWater': F}] +GHAST_BODY = [{'bodyItem': 'minecraft:white_harness'}, {'isRidden': T}, {'bodyItem': 'minecraft:red_harness', 'isRidden': T}, + {'isLeashHolder': T, 'bodyItem': 'minecraft:blue_harness'}] SPECIES = { 'horse': EQUINE, 'donkey': EQUINE + [{'hasChest': T}], 'mule': EQUINE + [{'hasChest': T}], 'zombie_horse': EQUINE, 'skeleton_horse': EQUINE, 'iron_golem': [{'attackTicksRemaining': 7.0}, {'offerFlowerTick': 30}, {'attackTicksRemaining': 0.0, 'offerFlowerTick': 0}], @@ -170,6 +174,11 @@ SPECIES = { {'sitAmount': 0.6, 'isEating': T}, {'sitAmount': 1.0, 'isScared': T}, {'sitAmount': 0.3}, {'lieOnBackAmount': 0.5}, {'rollAmount': 0.7}], 'llama': [{'hasChest': T}, {'hasChest': F}], + 'sniffer': [{'isSearching': T}, {'diggingAnimationState': 2}, {'sniffingAnimationState': 5}, {'risingAnimationState': 1}, + {'feelingHappyAnimationState': 3}, {'scentingAnimationState': 0}, {'diggingAnimationState': 50, 'isSearching': T}, + {'feelingHappyAnimationState': 30, 'scentingAnimationState': 20}], + 'happy_ghast': GHAST_BODY, 'happy_ghast_ropes': GHAST_BODY, 'happy_ghast_baby_ropes': GHAST_BODY, + 'happy_ghast_harness': GHAST_BODY, 'happy_ghast_baby_harness': GHAST_BODY, 'trader_llama': [{'hasChest': T}, {'hasChest': F}], 'turtle': [{'isOnLand': T}, {'isOnLand': T, 'isLayingEgg': T}, {'isOnLand': F, 'hasEgg': T}, {'isOnLand': T, 'hasEgg': T}], 'strider': [{'isRidden': T}, {'isRidden': F}], From 0e076c7153f6dc8267df6f1d14e2d667998f273c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 16:17:44 +0200 Subject: [PATCH 2/8] Port the sniffer's and the ghastling's brains SnifferAi and HappyGhastAi as vanilla's Brain runs them: the sensors and their scan rates, the activities and their requirements, and every behaviour (AnimalPanic, MoveToTargetSink, FollowTemptation, AnimalMakeLove, LookAtTargetSink, RunOne and the sniffer's scenting, sniffing, searching, digging, rising and happy states) in availableBehaviorsByPriority order. Adds AirAndWaterRandomPos and the mob AI scenarios for llamas, sniffers and happy ghasts. The brain is not ticked yet. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/creatures.rs | 5 + crates/horizon-client/src/mobs.rs | 9 + .../horizon-client/src/mobs/animal_brain.rs | 1980 +++++++++++++++++ crates/horizon-client/src/mobs/goals.rs | 94 + crates/horizon-client/src/mobs/happy_ghast.rs | 69 +- crates/horizon-client/src/mobs/sniffer.rs | 474 +--- tools/test_mob_ai_parity.py | 21 + 7 files changed, 2138 insertions(+), 514 deletions(-) create mode 100644 crates/horizon-client/src/mobs/animal_brain.rs diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 0d7e34572..1e0751d5b 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -850,6 +850,11 @@ impl Game<'_> { } }, MobEvent::Breed { parent, partner } => self.breed(parent, partner), + MobEvent::BreedTarget { mob, partner } => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { + horizon_client::mobs::animal_brain::set_breed_partner(m, partner); + } + } MobEvent::LeashBreak { mob, drop, sound } => self.break_leash(mob, drop, sound), MobEvent::Vibration { from, to, ticks } => { self.mob_vibration_particle(from, to, ticks) diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index e6dd71e45..34ccac776 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -8,6 +8,7 @@ pub mod ai; pub mod allay; pub mod anim; +pub mod animal_brain; pub mod aquatic; pub mod body_anim; pub mod brain; @@ -537,6 +538,8 @@ pub struct Extra { pub raider: Option>, /// A villager's raid activity and gossip. pub villager: Option>, + /// The sniffer's and the ghastling's brain. + pub animal_brain: Option>, /// The mob this one rides, and the mob riding it (`getVehicle`, `getFirstPassenger`). pub mount: Option, pub rider: Option, @@ -620,6 +623,12 @@ pub struct Mob { #[derive(Clone, Debug)] pub enum MobEvent { Sound(&'static str, [f64; 3], f32, f32), + /// `AnimalMakeLove`: the partner remembers this mob as its breed target + /// and walks to it and looks at it. + BreedTarget { + mob: u32, + partner: u32, + }, /// A sound event id that is not a static string (variant sounds). SoundId(String, [f64; 3], f32, f32), AttackPlayer(f32, [f64; 3]), diff --git a/crates/horizon-client/src/mobs/animal_brain.rs b/crates/horizon-client/src/mobs/animal_brain.rs new file mode 100644 index 000000000..5a724a518 --- /dev/null +++ b/crates/horizon-client/src/mobs/animal_brain.rs @@ -0,0 +1,1980 @@ +//! The `Brain`s of the sniffer (`SnifferAi`) and the ghastling +//! (`HappyGhastAi`), ported behaviour for behaviour: memories that expire, +//! the sensors and their scan rates, the activities and their +//! requirements, and the behaviours of each activity, started and ticked in +//! vanilla's order (priority, then the activity's slot in +//! `Brain.availableBehaviorsByPriority`'s hash map, then insertion order). +//! +//! The level random (`ServerLevel.getRandom`) times behaviours; the mob's +//! own random drives positions, sounds and jumps. `RunOne` shuffles with a +//! random of its own, seeded with the brain's `shuffle_seed` when it is +//! built. +use super::{Mob, MobEvent, MobWorld, Species, Who, path::Path, sniffer}; +use horizon_core::{ + geometry::Vec3, + random::{LegacyRandom, RandomSource}, +}; + +/// `MemorySlot.NEVER_EXPIRE`. +const NEVER: i64 = i64::MAX; + +/// `MemorySlot`: a value and its time to live. +#[derive(Clone, Debug)] +pub struct Slot { + v: Option, + ttl: i64, +} +impl Default for Slot { + fn default() -> Self { + Self { + v: None, + ttl: NEVER, + } + } +} +impl Slot { + fn tick(&mut self) { + if self.v.is_some() && self.ttl != NEVER { + if self.ttl <= 0 { + self.clear(); + } else { + self.ttl -= 1; + } + } + } + pub fn set(&mut self, v: T) { + self.v = Some(v); + self.ttl = NEVER; + } + pub fn set_ttl(&mut self, v: T, ttl: i64) { + self.v = Some(v); + self.ttl = ttl; + } + pub fn set_opt(&mut self, v: Option) { + match v { + Some(v) => self.set(v), + None => self.clear(), + } + } + pub fn clear(&mut self) { + self.v = None; + self.ttl = NEVER; + } + pub fn get(&self) -> Option<&T> { + self.v.as_ref() + } + pub fn present(&self) -> bool { + self.v.is_some() + } +} +impl Slot { + pub fn value(&self) -> Option { + self.v.clone() + } +} +impl Slot> { + /// `Brain.setMemory` of a collection: an empty one erases the memory. + fn set_list(&mut self, v: Vec) { + if v.is_empty() { + self.clear(); + } else { + self.set(v); + } + } +} + +/// `PositionTracker`: an entity (`EntityTracker`: at its eyes or feet, and +/// whether its block is the one at its eyes) or a block (`BlockPosTracker`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Tracker { + Entity { + who: Who, + eye: bool, + block_eye: bool, + }, + Block([i32; 3]), +} +impl Tracker { + fn entity(who: Who, eye: bool) -> Self { + Tracker::Entity { + who, + eye, + block_eye: false, + } + } + /// `currentPosition`. + fn position(&self, w: &MobWorld) -> Option<[f64; 3]> { + match *self { + Tracker::Entity { who, eye, .. } => w.target_info(who).map(|t| { + [ + t.position.x, + if eye { t.eye_y } else { t.position.y }, + t.position.z, + ] + }), + Tracker::Block(p) => Some([ + f64::from(p[0]) + 0.5, + f64::from(p[1]) + 0.5, + f64::from(p[2]) + 0.5, + ]), + } + } + /// `currentBlockPosition`. + fn block(&self, w: &MobWorld) -> Option<[i32; 3]> { + match *self { + Tracker::Entity { who, block_eye, .. } => w.target_info(who).map(|t| { + if block_eye { + block_of(Vec3::new(t.position.x, t.eye_y, t.position.z)) + } else { + block_of(t.position) + } + }), + Tracker::Block(p) => Some(p), + } + } +} +fn block_of(p: Vec3) -> [i32; 3] { + [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32] +} + +/// `WalkTarget`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct WalkTarget { + pub target: Tracker, + pub speed: f32, + pub close: i32, +} +impl WalkTarget { + /// `new WalkTarget(Vec3, ...)`: the block containing the point. + fn point(p: [f64; 3], speed: f32, close: i32) -> Self { + Self { + target: Tracker::Block([ + p[0].floor() as i32, + p[1].floor() as i32, + p[2].floor() as i32, + ]), + speed, + close, + } + } +} + +/// `NearestVisibleLivingEntities`: the nearby entities and a lazily filled +/// cache of `Sensor.isEntityTargetable`. +#[derive(Clone, Debug, Default)] +pub struct Visible { + list: Vec, + cache: Vec<(Who, bool)>, +} + +/// The memories these brains register. +#[derive(Clone, Debug, Default)] +pub struct Memories { + pub mobs: Slot>, + pub visible_mobs: Slot, + pub nearest_players: Slot>, + pub nearest_visible_player: Slot, + pub nearest_visible_targetable_player: Slot, + pub nearest_visible_targetable_players: Slot>, + pub nearest_visible_adult: Slot, + pub walk_target: Slot, + pub look_target: Slot, + pub breed_target: Slot, + pub path: Slot, + /// `HURT_BY`: whether the damage is one of `#panic_causes`. + pub hurt_by: Slot, + pub hurt_by_entity: Slot, + pub cant_reach_walk_target_since: Slot, + pub tempting_player: Slot, + pub temptation_cooldown_ticks: Slot, + pub is_panicking: Slot, + pub sniffer_digging: Slot, + pub sniffer_sniffing_target: Slot<[i32; 3]>, + pub sniffer_happy: Slot, + pub sniff_cooldown: Slot<()>, +} +impl Memories { + fn tick(&mut self) { + self.mobs.tick(); + self.visible_mobs.tick(); + self.nearest_players.tick(); + self.nearest_visible_player.tick(); + self.nearest_visible_targetable_player.tick(); + self.nearest_visible_targetable_players.tick(); + self.nearest_visible_adult.tick(); + self.walk_target.tick(); + self.look_target.tick(); + self.breed_target.tick(); + self.path.tick(); + self.hurt_by.tick(); + self.hurt_by_entity.tick(); + self.cant_reach_walk_target_since.tick(); + self.tempting_player.tick(); + self.temptation_cooldown_ticks.tick(); + self.is_panicking.tick(); + self.sniffer_digging.tick(); + self.sniffer_sniffing_target.tick(); + self.sniffer_happy.tick(); + self.sniff_cooldown.tick(); + } +} + +/// `Activity`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Act { + Core, + Idle, + Sniff, + Dig, + Panic, +} +impl Act { + pub fn name(self) -> &'static str { + match self { + Act::Core => "core", + Act::Idle => "idle", + Act::Sniff => "sniff", + Act::Dig => "dig", + Act::Panic => "panic", + } + } +} + +/// Which brain. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Sniffer, + /// A happy ghast (the brain ticks while it is a ghastling). + Ghastling, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Sensor { + Living, + HurtBy, + Players, + Tempting, + AdultAnyType, +} +impl Kind { + /// `BRAIN_PROVIDER`'s sensors, in order (all scan every 20 ticks). + fn sensors(self) -> &'static [Sensor] { + match self { + Kind::Sniffer => &[ + Sensor::Living, + Sensor::HurtBy, + Sensor::Players, + Sensor::Tempting, + ], + Kind::Ghastling => &[ + Sensor::Living, + Sensor::HurtBy, + Sensor::Tempting, + Sensor::AdultAnyType, + Sensor::Players, + ], + } + } +} + +/// An animal's brain. +#[derive(Clone, Debug)] +pub struct Brain { + pub kind: Kind, + pub mem: Memories, + sensors: Vec<(Sensor, i64)>, + /// The active non-core activity (`CORE` is always active). + pub activity: Act, + list: Vec, +} +#[derive(Clone, Debug)] +struct Entry { + act: Act, + b: B, +} + +fn brain(m: &Mob) -> Option<&Brain> { + m.extra.animal_brain.as_deref() +} +fn brain_mut(m: &mut Mob) -> &mut Brain { + m.extra + .animal_brain + .as_deref_mut() + .expect("the animal brain is built before it is used") +} +fn mem(m: &mut Mob) -> &mut Memories { + &mut brain_mut(m).mem +} +fn mem_ref(m: &Mob) -> Option<&Memories> { + brain(m).map(|b| &b.mem) +} + +/// The brain kind a mob has, if any. +pub fn kind_of(m: &Mob) -> Option { + match m.species() { + Species::Sniffer => Some(Kind::Sniffer), + // Every happy ghast has the brain; only the ghastling's ticks. + Species::HappyGhast => Some(Kind::Ghastling), + _ => None, + } +} + +/// `Brain.Provider.makeBrain`: a new brain whose sensors' first scans are +/// delayed by draws from the mob's random, on its default activity (idle). +/// The gates shuffle with a random seeded with `shuffle_seed`. +pub fn init(m: &mut Mob, shuffle_seed: i64) { + let Some(kind) = kind_of(m) else { return }; + let sensors = kind + .sensors() + .iter() + .map(|s| (*s, i64::from(m.random.next_int_bound(20).unwrap_or(0)))) + .collect(); + let mut b = Brain { + kind, + mem: Memories::default(), + sensors, + activity: Act::Idle, + list: Vec::new(), + }; + b.list = match kind { + Kind::Sniffer => sniffer_package(shuffle_seed), + Kind::Ghastling => ghastling_package(shuffle_seed), + }; + m.extra.animal_brain = Some(Box::new(b)); +} + +/// The happy ghast grew up (`adultGhastSetup`): every running behaviour +/// stops (`Brain.stopAll`) and the memories are cleared; the brain no +/// longer ticks. +pub fn grown_up(m: &mut Mob) { + let Some(b) = m.extra.animal_brain.as_deref_mut() else { + return; + }; + for e in b.list.iter_mut() { + e.b.reset(); + } + b.mem = Memories::default(); + m.nav_stop(); +} + +/// `AnimalMakeLove.start` on the partner's side: it remembers `partner` +/// as its breed target, looks at it and walks to it +/// (`BehaviorUtils.lockGazeAndWalkToEachOther`). +pub fn set_breed_partner(m: &mut Mob, partner: u32) { + if m.extra.animal_brain.is_none() { + return; + } + let who = Who::Mob(partner); + mem(m).breed_target.set(who); + lock_gaze_and_walk(m, who, 1.0, 2); +} + +/// What behaviours read and emit during a brain tick. +pub struct Bx<'a, 'w> { + pub w: &'a MobWorld<'w>, + pub lr: &'a mut LegacyRandom, + pub events: &'a mut Vec, + pub now: i64, +} + +/// `Brain.tick` then `updateActivity` (from `customServerAiStep`). +pub fn tick(m: &mut Mob, w: &MobWorld, lr: &mut LegacyRandom, events: &mut Vec) { + if brain(m).is_none() { + let seed = i64::from(m.id); + init(m, seed); + if brain(m).is_none() { + return; + } + } + // forgetOutdatedMemories + mem(m).tick(); + tick_sensors(m, w); + let mut list = std::mem::take(&mut brain_mut(m).list); + let mut cx = Bx { + w, + lr, + events, + now: w.game_time, + }; + for e in list.iter_mut() { + let active = e.act == Act::Core || e.act == brain_mut(m).activity; + if active && !e.b.running() { + e.b.try_start(m, &mut cx); + } + } + for e in list.iter_mut() { + if e.b.running() { + e.b.tick_or_stop(m, &mut cx); + } + } + brain_mut(m).list = list; + update_activity(m); + m.ai.panicking = is_panicking(m); +} + +/// `SnifferAi.updateActivity` / `HappyGhastAi.updateActivity`: +/// `setActiveActivityToFirstValid`. +fn update_activity(m: &mut Mob) { + let b = brain_mut(m); + let mm = &b.mem; + let order: &[Act] = match b.kind { + Kind::Sniffer => &[Act::Dig, Act::Sniff, Act::Idle], + Kind::Ghastling => &[Act::Panic, Act::Idle], + }; + for &a in order { + let ok = match a { + Act::Dig => { + !mm.is_panicking.present() + && !mm.walk_target.present() + && mm.sniffer_digging.present() + } + Act::Sniff => { + !mm.is_panicking.present() + && mm.sniffer_sniffing_target.present() + && mm.walk_target.present() + } + Act::Idle => b.kind != Kind::Sniffer || !mm.sniffer_digging.present(), + Act::Panic => mm.is_panicking.present(), + Act::Core => true, + }; + if ok { + b.activity = a; + break; + } + } +} + +/// `PathfinderMob.isPanicking` for a mob with this brain. +pub fn is_panicking(m: &Mob) -> bool { + mem_ref(m).is_some_and(|mm| mm.is_panicking.present()) +} +/// `Sniffer.isTempted`. +pub fn is_tempted(m: &Mob) -> bool { + mem_ref(m).is_some_and(|mm| mm.tempting_player.present()) +} +/// The explored positions are the sniffer's `SNIFFER_EXPLORED_POSITIONS`. +const EXPLORED_MAX: usize = 20; + +// ---- Sensors ------------------------------------------------------------ + +fn tick_sensors(m: &mut Mob, w: &MobWorld) { + let n = brain_mut(m).sensors.len(); + for i in 0..n { + let (sensor, fire) = { + let s = &mut brain_mut(m).sensors[i]; + s.1 -= 1; + if s.1 <= 0 { + s.1 = 20; + (s.0, true) + } else { + (s.0, false) + } + }; + if !fire { + continue; + } + match sensor { + Sensor::Living => sense_living(m, w), + Sensor::HurtBy => sense_hurt(m, w), + Sensor::Players => sense_players(m, w), + Sensor::Tempting => sense_tempting(m, w), + Sensor::AdultAnyType => sense_adult(m, w), + } + } +} +/// `NearestLivingEntitySensor`: everything alive within the follow range, +/// nearest first. +fn sense_living(m: &mut Mob, w: &MobWorld) { + let r = m.attrs.follow_range; + let area = m.bounds().inflate(Vec3::new(r, r, r)); + let mut found: Vec<(Who, f64)> = Vec::new(); + for o in w.others { + if o.id != m.id && o.alive && o.bounds.intersects(area) { + found.push((Who::Mob(o.id), m.distance_sqr(o.position))); + } + } + if let Some(p) = &w.player + && p.alive + && p.bounds.intersects(area) + { + found.push((Who::Player, m.distance_sqr(p.position))); + } + found.sort_by(|a, b| a.1.total_cmp(&b.1)); + let list: Vec = found.into_iter().map(|(w, _)| w).collect(); + let mm = mem(m); + mm.mobs.set_list(list.clone()); + mm.visible_mobs.set(Visible { + list, + cache: Vec::new(), + }); +} +/// `Sensor.isEntityTargetable`: `TargetingConditions.forNonCombat()` within +/// the follow range, in sight. +fn targetable(m: &mut Mob, w: &MobWorld, who: Who) -> bool { + let range = m.attrs.follow_range; + match who { + Who::Player => { + // TargetingConditions.forNonCombat(): in range (scaled by the + // player's visibility, at least 2) and in sight. + let Some(p) = &w.player else { return false }; + let visibility = if p.sneaking { 0.8 } else { 1.0 }; + let r = (range * visibility).max(2.0); + p.alive && !p.spectator && m.distance_sqr(p.position) <= r * r && m.sees(w, who) + } + Who::Mob(id) => { + let Some(s) = w.seen(id) else { return false }; + s.alive && m.distance_sqr(s.position) <= range * range && m.sees(w, who) + } + } +} +/// The visible-entities memory's line-of-sight test, cached per memory. +fn visible_test(m: &mut Mob, w: &MobWorld, who: Who) -> bool { + match mem_ref(m).and_then(|mm| mm.visible_mobs.get()) { + Some(v) => { + if let Some(&(_, r)) = v.cache.iter().find(|(k, _)| *k == who) { + return r; + } + } + None => return false, + } + let r = targetable(m, w, who); + if let Some(v) = mem(m).visible_mobs.v.as_mut() { + v.cache.push((who, r)); + } + r +} +/// `NearestVisibleLivingEntities.findClosest`. +fn find_closest(m: &mut Mob, w: &MobWorld, filter: impl Fn(&Mob, Who) -> bool) -> Option { + let list = mem_ref(m)?.visible_mobs.get()?.list.clone(); + list.into_iter() + .find(|&who| filter(m, who) && visible_test(m, w, who)) +} +/// `NearestVisibleLivingEntities.contains(entity)`. +fn visible_contains(m: &mut Mob, w: &MobWorld, who: Who) -> bool { + let listed = mem_ref(m) + .and_then(|mm| mm.visible_mobs.get()) + .is_some_and(|v| v.list.contains(&who)); + listed && visible_test(m, w, who) +} +/// `PlayerSensor`. +fn sense_players(m: &mut Mob, w: &MobWorld) { + let range = m.attrs.follow_range; + let near = w + .player + .as_ref() + .is_some_and(|p| !p.spectator && m.distance_sqr(p.position) < range * range); + let players: Vec = if near { vec![Who::Player] } else { vec![] }; + let visible: Vec = players + .iter() + .copied() + .filter(|&p| targetable(m, w, p)) + .collect(); + let attackable: Vec = visible + .iter() + .copied() + .filter(|_| m.can_target_player(w, range, true)) + .collect(); + let mm = mem(m); + mm.nearest_players.set_list(players); + mm.nearest_visible_player.set_opt(visible.first().copied()); + mm.nearest_visible_targetable_players + .set_list(attackable.clone()); + mm.nearest_visible_targetable_player + .set_opt(attackable.first().copied()); +} +/// `HurtBySensor`: the last damage (forgotten 40 ticks after) and who did it. +fn sense_hurt(m: &mut Mob, w: &MobWorld) { + let age = i64::from(m.age); + let last = m + .last_damage + .as_ref() + .filter(|(_, t)| age - t <= 40) + .map(|(d, _)| (d.attacker, d.causes_panic())); + let mm = mem(m); + if let Some((by, panic)) = last { + mm.hurt_by.set(panic); + if let Some(by) = by { + mm.hurt_by_entity.set(by); + } + } else { + mm.hurt_by.clear(); + } + if let Some(who) = mm.hurt_by_entity.value() + && !w.target_info(who).is_some_and(|t| t.alive) + { + mm.hurt_by_entity.clear(); + } +} +/// `TemptingSensor.forAnimal`: the nearest player within the tempt range +/// holding the animal's food (and not riding it). +fn sense_tempting(m: &mut Mob, w: &MobWorld) { + // Attributes.TEMPT_RANGE: 10 for animals, 16 for the happy ghast. + let range = if m.species() == Species::HappyGhast { + 16.0 + } else { + 10.0 + }; + let food = &m.kind.food; + let holds = |item: &Option>| { + item.as_deref() + .is_some_and(|i| food.iter().any(|f| f.as_str() == i)) + }; + let tempting = w.player.as_ref().is_some_and(|p| { + p.alive + && !p.spectator + && m.distance_sqr(p.position) <= range * range + && (holds(&p.main_hand) || holds(&p.off_hand)) + && m.rider.is_none() + }); + mem(m) + .tempting_player + .set_opt(tempting.then_some(Who::Player)); +} +/// `AdultSensorAnyType`: the nearest visible adult of a followable friendly +/// type. +fn sense_adult(m: &mut Mob, w: &MobWorld) { + if !mem(m).visible_mobs.present() { + return; + } + let found = find_closest(m, w, |_, who| match who { + Who::Mob(id) => w + .seen(id) + .is_some_and(|s| !s.baby && followable_friendly(s.species)), + Who::Player => false, + }); + mem(m).nearest_visible_adult.set_opt(found); +} +/// `#followable_friendly_mobs`. +fn followable_friendly(s: Species) -> bool { + matches!( + s, + Species::Camel + | Species::Cat + | Species::Chicken + | Species::Cow + | Species::Donkey + | Species::Fox + | Species::Goat + | Species::HappyGhast + | Species::Horse + | Species::SkeletonHorse + | Species::Llama + | Species::Mule + | Species::Ocelot + | Species::Panda + | Species::Parrot + | Species::Pig + | Species::PolarBear + | Species::Rabbit + | Species::Sheep + | Species::Sniffer + | Species::Strider + | Species::Villager + | Species::Wolf + ) +} + +// ---- Behaviours ------------------------------------------------------------ + +/// `Behavior`'s running state and end time. +#[derive(Clone, Copy, Debug)] +struct Timed { + running: bool, + end: i64, + min: i32, + max: i32, +} +impl Timed { + fn new(min: i32, max: i32) -> Self { + Self { + running: false, + end: 0, + min, + max, + } + } + /// `Behavior.tryStart`'s duration draw. + fn begin(&mut self, cx: &mut Bx) { + self.running = true; + let bound = self.max.wrapping_add(1).wrapping_sub(self.min); + let d = self + .min + .wrapping_add(cx.lr.next_int_bound(bound).unwrap_or(0)); + self.end = cx.now + i64::from(d); + } + fn timed_out(&self, now: i64) -> bool { + now > self.end + } +} + +/// `RunOne`: shuffles its children by weight and starts the first that can. +#[derive(Clone, Debug)] +struct Gate { + running: bool, + random: LegacyRandom, + kids: Vec<(B, i32, f64)>, +} +impl Gate { + fn run_one(seed: i64, kids: Vec<(B, i32)>) -> Self { + Self { + running: false, + random: LegacyRandom::new(seed), + kids: kids.into_iter().map(|(b, w)| (b, w, 0.0)).collect(), + } + } + fn try_start(&mut self, m: &mut Mob, cx: &mut Bx) -> bool { + self.running = true; + // ShufflingList.shuffle: a fresh weight for each entry in the + // current order, then a stable sort. + for k in &mut self.kids { + let r = self.random.next_float(); + k.2 = -f64::from(r).powf(f64::from(1.0_f32 / k.1 as f32)); + } + self.kids.sort_by(|a, b| a.2.total_cmp(&b.2)); + for k in &mut self.kids { + if !k.0.running() && k.0.try_start(m, cx) { + break; + } + } + true + } + fn tick_or_stop(&mut self, m: &mut Mob, cx: &mut Bx) { + for k in &mut self.kids { + if k.0.running() { + k.0.tick_or_stop(m, cx); + } + } + if !self.kids.iter().any(|k| k.0.running()) { + self.do_stop(m, cx); + } + } + fn do_stop(&mut self, m: &mut Mob, cx: &mut Bx) { + self.running = false; + for k in &mut self.kids { + if k.0.running() { + k.0.do_stop(m, cx); + } + } + } +} + +#[derive(Clone, Debug)] +enum B { + Swim(Timed), + /// `AnimalPanic`: flying (`AirAndWaterRandomPos`) or on land, and + /// whether the sniffer's override resets its sniffing first. + AnimalPanic { + t: Timed, + fly: bool, + }, + MoveToTargetSink { + t: Timed, + cooldown: i32, + path: Option, + last_target: Option<[i32; 3]>, + speed: f32, + }, + CountDownTemptation(Timed), + MakeLove { + t: Timed, + spawn_at: i64, + }, + /// `FollowTemptation` and how close is close enough. + FollowTemptation { + t: Timed, + look_in_the_eyes: bool, + }, + LookAtTargetSink(Timed), + FeelingHappy(Timed), + Digging(Timed), + FinishedDigging(Timed), + Searching(Timed), + Scenting(Timed), + Sniffing(Timed), + DoNothing(Timed), + /// `SetWalkTargetFromLookTarget.create(speed, close)`. + WalkToLookTarget { + running: bool, + speed: f32, + close: i32, + }, + /// `SetEntityLookTarget.create(EntityType.PLAYER, 6)`. + LookAtPlayer(bool), + /// `RandomStroll.stroll` or `RandomStroll.fly`. + Stroll { + running: bool, + fly: bool, + speed: f32, + }, + /// `BabyFollowAdult.create(3..16, 1.1, memory, true)`: the nearest + /// visible player or adult. + FollowAdult { + running: bool, + player: bool, + }, + Gate(Box), +} + +impl B { + fn running(&self) -> bool { + match self { + B::Swim(t) + | B::AnimalPanic { t, .. } + | B::MoveToTargetSink { t, .. } + | B::CountDownTemptation(t) + | B::MakeLove { t, .. } + | B::FollowTemptation { t, .. } + | B::LookAtTargetSink(t) + | B::FeelingHappy(t) + | B::Digging(t) + | B::FinishedDigging(t) + | B::Searching(t) + | B::Scenting(t) + | B::Sniffing(t) + | B::DoNothing(t) => t.running, + B::WalkToLookTarget { running, .. } + | B::LookAtPlayer(running) + | B::Stroll { running, .. } + | B::FollowAdult { running, .. } => *running, + B::Gate(g) => g.running, + } + } + /// Stopped without its stop effects (the memories they would touch are + /// cleared with the rest). + fn reset(&mut self) { + match self { + B::Swim(t) + | B::AnimalPanic { t, .. } + | B::CountDownTemptation(t) + | B::MakeLove { t, .. } + | B::FollowTemptation { t, .. } + | B::LookAtTargetSink(t) + | B::FeelingHappy(t) + | B::Digging(t) + | B::FinishedDigging(t) + | B::Searching(t) + | B::Scenting(t) + | B::Sniffing(t) + | B::DoNothing(t) => t.running = false, + B::MoveToTargetSink { t, path, .. } => { + t.running = false; + *path = None; + } + B::Gate(g) => { + g.running = false; + for k in &mut g.kids { + k.0.reset(); + } + } + _ => self.set_one_shot(false), + } + } + /// A one-shot (`OneShot`) runs only until its first tick. + fn one_shot(&self) -> bool { + matches!( + self, + B::WalkToLookTarget { .. } + | B::LookAtPlayer(_) + | B::Stroll { .. } + | B::FollowAdult { .. } + ) + } + fn set_one_shot(&mut self, on: bool) { + match self { + B::WalkToLookTarget { running, .. } + | B::LookAtPlayer(running) + | B::Stroll { running, .. } + | B::FollowAdult { running, .. } => *running = on, + _ => {} + } + } + + /// `BehaviorControl.tryStart`. + fn try_start(&mut self, m: &mut Mob, cx: &mut Bx) -> bool { + if self.one_shot() { + let ok = self.trigger(m, cx); + if ok { + self.set_one_shot(true); + } + return ok; + } + let now = cx.now; + match self { + B::Gate(g) => g.try_start(m, cx), + B::Swim(t) => { + if !swim_condition(m) { + return false; + } + t.begin(cx); + true + } + B::AnimalPanic { t, .. } => { + let mm = mem(m); + if !(mm.hurt_by.get() == Some(&true) || mm.is_panicking.present()) { + return false; + } + t.begin(cx); + if brain_mut(m).kind == Kind::Sniffer { + reset_sniffing(m, cx); + } + let mm = mem(m); + mm.is_panicking.set(true); + mm.walk_target.clear(); + m.nav_stop(); + true + } + B::MoveToTargetSink { + t, + cooldown, + path, + last_target, + speed, + } => { + let mm = mem(m); + if mm.path.present() || !mm.walk_target.present() { + return false; + } + if *cooldown > 0 { + *cooldown -= 1; + return false; + } + let walk = mm.walk_target.value().unwrap(); + let reached = reached(m, cx.w, &walk); + if !reached && compute_path(m, cx, &walk, path, speed) { + *last_target = walk.target.block(cx.w); + t.begin(cx); + mem(m).path.set_opt(path.clone()); + m.nav_move_to_path(path.clone(), f64::from(*speed)); + return true; + } + let mm = mem(m); + mm.walk_target.clear(); + if reached { + mm.cant_reach_walk_target_since.clear(); + } + false + } + B::CountDownTemptation(t) => { + if !mem(m).temptation_cooldown_ticks.present() { + return false; + } + t.begin(cx); + true + } + B::MakeLove { t, spawn_at } => { + let mm = mem(m); + if !mm.visible_mobs.present() + || mm.breed_target.present() + || mm.is_panicking.present() + { + return false; + } + if m.extra.in_love <= 0 { + return false; + } + let Some(partner) = breed_partner(m, cx.w) else { + return false; + }; + t.begin(cx); + if brain_mut(m).kind == Kind::Sniffer { + reset_sniffing(m, cx); + } + mem(m).breed_target.set(partner); + if let Who::Mob(id) = partner { + cx.events.push(MobEvent::BreedTarget { + mob: id, + partner: m.id, + }); + } + lock_gaze_and_walk(m, partner, 1.0, 2); + *spawn_at = now + 60 + i64::from(m.random.next_int_bound(50).unwrap_or(0)); + true + } + B::FollowTemptation { t, .. } => { + let mm = mem(m); + if mm.temptation_cooldown_ticks.present() + || !mm.tempting_player.present() + || mm.breed_target.present() + || mm.is_panicking.present() + { + return false; + } + t.begin(cx); + if brain_mut(m).kind == Kind::Sniffer { + reset_sniffing(m, cx); + } + true + } + B::LookAtTargetSink(t) => { + if !mem(m).look_target.present() { + return false; + } + t.begin(cx); + true + } + B::FeelingHappy(t) => { + if !mem(m).sniffer_happy.present() { + return false; + } + t.begin(cx); + transition(m, cx, sniffer::FEELING_HAPPY); + true + } + B::Digging(t) => { + let mm = mem(m); + if mm.is_panicking.present() + || mm.walk_target.present() + || !mm.sniffer_digging.present() + || mm.sniff_cooldown.present() + { + return false; + } + if !can_sniff(m) { + return false; + } + t.begin(cx); + transition(m, cx, sniffer::DIGGING); + true + } + B::FinishedDigging(t) => { + let mm = mem(m); + if mm.is_panicking.present() + || mm.walk_target.present() + || !mm.sniffer_digging.present() + || !mm.sniff_cooldown.present() + { + return false; + } + t.begin(cx); + transition(m, cx, sniffer::RISING); + true + } + B::Searching(t) => { + let mm = mem(m); + if !mm.walk_target.present() + || mm.is_panicking.present() + || !mm.sniffer_sniffing_target.present() + { + return false; + } + if !can_sniff(m) { + return false; + } + t.begin(cx); + transition(m, cx, sniffer::SEARCHING); + true + } + B::Scenting(t) => { + let mm = mem(m); + if mm.is_panicking.present() + || mm.sniffer_digging.present() + || mm.sniffer_sniffing_target.present() + || mm.sniffer_happy.present() + || mm.breed_target.present() + { + return false; + } + if is_tempted(m) { + return false; + } + t.begin(cx); + transition(m, cx, sniffer::SCENTING); + true + } + B::Sniffing(t) => { + let mm = mem(m); + if mm.walk_target.present() + || mm.sniffer_sniffing_target.present() + || mm.sniff_cooldown.present() + { + return false; + } + if m.is_baby() || !can_sniff(m) { + return false; + } + t.begin(cx); + transition(m, cx, sniffer::SNIFFING); + true + } + B::DoNothing(t) => { + t.begin(cx); + true + } + B::WalkToLookTarget { .. } + | B::LookAtPlayer(_) + | B::Stroll { .. } + | B::FollowAdult { .. } => unreachable!("one-shots trigger"), + } + } + + /// A one-shot's trigger. + fn trigger(&mut self, m: &mut Mob, cx: &mut Bx) -> bool { + match *self { + B::WalkToLookTarget { speed, close, .. } => { + let mm = mem(m); + if mm.walk_target.present() { + return false; + } + let Some(look) = mm.look_target.value() else { + return false; + }; + mm.walk_target.set(WalkTarget { + target: look, + speed, + close, + }); + true + } + B::LookAtPlayer(_) => { + let mm = mem(m); + if mm.look_target.present() || !mm.visible_mobs.present() { + return false; + } + let w = cx.w; + let found = find_closest(m, w, |m, who| { + who == Who::Player + && w.target_info(who) + .is_some_and(|t| t.position.distance_squared(m.position) <= 36.0) + && m.rider.is_none() + }); + let Some(t) = found else { return false }; + mem(m).look_target.set(Tracker::entity(t, true)); + true + } + B::Stroll { fly, speed, .. } => { + if mem(m).walk_target.present() { + return false; + } + let pos = if fly { + let view = m.view_vector(); + m.air_and_water_random_pos(cx.w, 10, 7, -2, view[0], view[2]) + } else { + m.land_random_pos(cx.w, 10, 7) + }; + mem(m) + .walk_target + .set_opt(pos.map(|p| WalkTarget::point(p, speed, 0))); + true + } + B::FollowAdult { player, .. } => { + let mm = mem(m); + let adult = if player { + mm.nearest_visible_player.value() + } else { + mm.nearest_visible_adult.value() + }; + let Some(adult) = adult else { return false }; + if mm.walk_target.present() || !m.is_baby() { + return false; + } + let Some(at) = cx.w.target_info(adult) else { + return false; + }; + // closerThan(adult, 17) && !closerThan(adult, 3) + let d = m.distance_sqr(at.position); + if !(d < 17.0 * 17.0 && d >= 3.0 * 3.0) { + return false; + } + let mm = mem(m); + mm.walk_target.set(WalkTarget { + target: Tracker::Entity { + who: adult, + eye: true, + block_eye: true, + }, + speed: 1.1, + close: 2, + }); + mm.look_target.set(Tracker::Entity { + who: adult, + eye: true, + block_eye: true, + }); + true + } + _ => false, + } + } + + /// `BehaviorControl.tickOrStop`. + fn tick_or_stop(&mut self, m: &mut Mob, cx: &mut Bx) { + if self.one_shot() { + self.set_one_shot(false); + return; + } + let now = cx.now; + match self { + B::Gate(g) => g.tick_or_stop(m, cx), + B::Swim(t) => { + if t.timed_out(now) || !swim_condition(m) { + self.do_stop(m, cx); + } else if m.random.next_float() < 0.8 { + m.ai.jump = true; + } + } + B::AnimalPanic { t, fly } => { + if t.timed_out(now) { + self.do_stop(m, cx); + return; + } + if m.ai.nav.is_done() { + let pos = panic_pos(m, cx.w, *fly); + if let Some(p) = pos { + mem(m).walk_target.set(WalkTarget::point(p, 2.0, 0)); + } + } + } + B::MoveToTargetSink { + t, + path, + last_target, + speed, + .. + } => { + let still = path.is_some() + && last_target.is_some() + && mem(m) + .walk_target + .value() + .is_some_and(|walk| !m.ai.nav.is_done() && !reached(m, cx.w, &walk)); + if t.timed_out(now) || !still { + self.do_stop(m, cx); + return; + } + let new_path = m.ai.nav.path.clone(); + if !same_path(path.as_ref(), new_path.as_ref()) { + *path = new_path.clone(); + mem(m).path.set_opt(new_path.clone()); + } + if new_path.is_some() + && let Some(last) = *last_target + && let Some(walk) = mem(m).walk_target.value() + && let Some(now_target) = walk.target.block(cx.w) + { + let d = dist_sqr(now_target, last); + if d > 4 && compute_path(m, cx, &walk, path, speed) { + *last_target = Some(now_target); + mem(m).path.set_opt(path.clone()); + m.nav_move_to_path(path.clone(), f64::from(*speed)); + } + } + } + B::CountDownTemptation(_) => { + let v = mem(m).temptation_cooldown_ticks.value(); + match v { + Some(v) if v > 0 => mem(m).temptation_cooldown_ticks.set(v - 1), + _ => self.do_stop(m, cx), + } + } + B::MakeLove { spawn_at, .. } => { + let Some(partner) = mem(m).breed_target.value() else { + self.do_stop(m, cx); + return; + }; + let ok = cx.w.target_info(partner).is_some_and(|t| t.alive) + && can_mate_with(m, cx.w, partner) + && visible_contains(m, cx.w, partner) + && now <= *spawn_at + && !is_panicking(m) + && !partner_panicking(cx.w, partner); + if !ok { + self.do_stop(m, cx); + return; + } + lock_gaze_and_walk(m, partner, 1.0, 2); + if let Some(t) = cx.w.target_info(partner) + && m.distance_sqr(t.position) < 9.0 + && now >= *spawn_at + { + // spawnChildFromBreeding: the egg (or baby), and both + // parents rest (finalizeSpawnChildFromBreeding). + let Who::Mob(id) = partner else { return }; + m.extra.in_love = 0; + m.extra.age = 6000; + cx.events.push(MobEvent::Breed { + parent: m.id, + partner: id, + }); + mem(m).breed_target.clear(); + } + } + B::FollowTemptation { + look_in_the_eyes, .. + } => { + let mm = mem(m); + let still = mm.tempting_player.present() + && !mm.breed_target.present() + && !mm.is_panicking.present(); + if !still { + self.do_stop(m, cx); + return; + } + let eyes = *look_in_the_eyes; + let player = mm.tempting_player.value().unwrap(); + mm.look_target.set(Tracker::entity(player, true)); + let close = follow_temptation_close(m); + let near = + cx.w.target_info(player) + .is_some_and(|t| m.distance_sqr(t.position) < close * close); + let speed = if brain_mut(m).kind == Kind::Sniffer { + 1.25 + } else { + 1.25 + }; + let mm = mem(m); + if near { + mm.walk_target.clear(); + } else { + mm.walk_target.set(WalkTarget { + target: Tracker::Entity { + who: player, + eye: eyes, + block_eye: eyes, + }, + speed, + close: 2, + }); + } + } + B::LookAtTargetSink(t) => { + let visible = match mem(m).look_target.value() { + Some(look) => tracker_visible(m, cx.w, look), + None => false, + }; + if t.timed_out(now) || !visible { + self.do_stop(m, cx); + } else if let Some(at) = mem(m).look_target.value().and_then(|l| l.position(cx.w)) { + m.look_at(at); + } + } + B::FeelingHappy(t) | B::Scenting(t) | B::DoNothing(t) => { + if t.timed_out(now) { + self.do_stop(m, cx); + } + } + B::Digging(t) => { + let ok = + mem(m).sniffer_digging.present() && can_dig(m, cx.w) && m.extra.in_love <= 0; + if t.timed_out(now) || !ok { + self.do_stop(m, cx); + } + } + B::FinishedDigging(t) => { + if t.timed_out(now) || !mem(m).sniffer_digging.present() { + self.do_stop(m, cx); + } + } + B::Searching(t) => { + let still = if !can_sniff(m) { + transition(m, cx, sniffer::IDLING); + false + } else { + let w = cx.w; + let mm = mem(m); + match ( + mm.walk_target.value().and_then(|t| t.target.block(w)), + mm.sniffer_sniffing_target.value(), + ) { + (Some(a), Some(b)) => a == b, + _ => false, + } + }; + if t.timed_out(now) || !still { + self.do_stop(m, cx); + } + } + B::Sniffing(t) => { + if t.timed_out(now) || !can_sniff(m) { + self.do_stop(m, cx); + } + } + B::WalkToLookTarget { .. } + | B::LookAtPlayer(_) + | B::Stroll { .. } + | B::FollowAdult { .. } => {} + } + } + + /// `BehaviorControl.doStop`. + fn do_stop(&mut self, m: &mut Mob, cx: &mut Bx) { + if self.one_shot() { + self.set_one_shot(false); + return; + } + let now = cx.now; + match self { + B::Gate(g) => g.do_stop(m, cx), + B::Swim(t) | B::DoNothing(t) => t.running = false, + B::AnimalPanic { t, .. } => { + t.running = false; + mem(m).is_panicking.clear(); + } + B::MoveToTargetSink { + t, cooldown, path, .. + } => { + t.running = false; + if let Some(walk) = mem(m).walk_target.value() + && !reached(m, cx.w, &walk) + && m.ai.nav.stuck + { + *cooldown = cx.lr.next_int_bound(40).unwrap_or(0); + } + m.nav_stop(); + let mm = mem(m); + mm.walk_target.clear(); + mm.path.clear(); + *path = None; + } + B::CountDownTemptation(t) => { + t.running = false; + mem(m).temptation_cooldown_ticks.clear(); + } + B::MakeLove { t, spawn_at } => { + t.running = false; + let mm = mem(m); + mm.breed_target.clear(); + mm.walk_target.clear(); + mm.look_target.clear(); + *spawn_at = 0; + } + B::FollowTemptation { t, .. } => { + t.running = false; + let mm = mem(m); + mm.temptation_cooldown_ticks.set(100); + mm.walk_target.clear(); + mm.look_target.clear(); + } + B::LookAtTargetSink(t) => { + t.running = false; + mem(m).look_target.clear(); + } + B::FeelingHappy(t) => { + t.running = false; + transition(m, cx, sniffer::IDLING); + mem(m).sniffer_happy.clear(); + } + B::Digging(t) => { + t.running = false; + if t.timed_out(now) { + mem(m).sniff_cooldown.set_ttl((), 9600); + } else { + reset_sniffing(m, cx); + } + } + B::FinishedDigging(t) => { + t.running = false; + let finished = t.timed_out(now); + transition(m, cx, sniffer::IDLING); + if finished { + // onDiggingComplete: storeExploredPosition(getOnPos()). + let p = sniffer::on_pos(m); + m.extra.positions.truncate(EXPLORED_MAX); + m.extra.positions.insert(0, p); + } + let mm = mem(m); + mm.sniffer_digging.clear(); + mm.sniffer_happy.set(true); + } + B::Searching(t) => { + t.running = false; + if can_dig(m, cx.w) && can_sniff(m) { + mem(m).sniffer_digging.set(true); + } + let mm = mem(m); + mm.walk_target.clear(); + mm.sniffer_sniffing_target.clear(); + } + B::Scenting(t) => { + t.running = false; + transition(m, cx, sniffer::IDLING); + } + B::Sniffing(t) => { + t.running = false; + let finished = t.timed_out(now); + transition(m, cx, sniffer::IDLING); + if finished && let Some(p) = dig_position(m, cx.w) { + let mm = mem(m); + mm.sniffer_sniffing_target.set(p); + mm.walk_target.set(WalkTarget { + target: Tracker::Block(p), + speed: 1.25, + close: 0, + }); + } + } + B::WalkToLookTarget { .. } + | B::LookAtPlayer(_) + | B::Stroll { .. } + | B::FollowAdult { .. } => {} + } + } +} + +fn same_path(a: Option<&Path>, b: Option<&Path>) -> bool { + match (a, b) { + (None, None) => true, + (Some(a), Some(b)) => a.nodes == b.nodes && a.target == b.target, + _ => false, + } +} +fn dist_sqr(a: [i32; 3], b: [i32; 3]) -> i64 { + let d = |i: usize| i64::from(a[i] - b[i]); + d(0) * d(0) + d(1) * d(1) + d(2) * d(2) +} +fn manhattan(a: [i32; 3], b: [i32; 3]) -> i32 { + (a[0] - b[0]).abs() + (a[1] - b[1]).abs() + (a[2] - b[2]).abs() +} +/// `Swim`: deeper than the jump threshold, or in lava. +fn swim_condition(m: &Mob) -> bool { + m.fluids.water > m.fluid_jump_threshold() || m.fluids.in_lava +} +/// `PositionTracker.isVisibleBy`. +fn tracker_visible(m: &mut Mob, w: &MobWorld, t: Tracker) -> bool { + match t { + Tracker::Entity { who, .. } => { + w.target_info(who).is_some_and(|i| i.alive) && visible_contains(m, w, who) + } + Tracker::Block(_) => true, + } +} +/// `MoveToTargetSink.reachedTarget`. +fn reached(m: &Mob, w: &MobWorld, walk: &WalkTarget) -> bool { + walk.target + .block(w) + .is_some_and(|p| manhattan(p, block_of(m.position)) <= walk.close) +} +/// `MoveToTargetSink.tryComputePath`. +fn compute_path( + m: &mut Mob, + cx: &mut Bx, + walk: &WalkTarget, + path: &mut Option, + speed: &mut f32, +) -> bool { + let Some(target) = walk.target.block(cx.w) else { + return false; + }; + *path = m.create_path_to(cx.w, target, 0); + *speed = walk.speed; + if reached(m, cx.w, walk) { + mem(m).cant_reach_walk_target_since.clear(); + } else { + let can_reach = path.as_ref().is_some_and(|p| p.reached); + let mm = mem(m); + if can_reach { + mm.cant_reach_walk_target_since.clear(); + } else if !mm.cant_reach_walk_target_since.present() { + mm.cant_reach_walk_target_since.set(cx.now); + } + if path.is_some() { + return true; + } + let to = [ + f64::from(target[0]) + 0.5, + f64::from(target[1]), + f64::from(target[2]) + 0.5, + ]; + if let Some(step) = + m.default_random_pos_towards(cx.w, 10, 7, to, f64::from(std::f32::consts::FRAC_PI_2)) + { + let p = [ + step[0].floor() as i32, + step[1].floor() as i32, + step[2].floor() as i32, + ]; + *path = m.create_path_to(cx.w, p, 0); + return path.is_some(); + } + } + false +} +/// `AnimalPanic.getPanicPos`: on land 5 blocks out and 4 up or down, or +/// for a flyer the air and water around it ahead (water first when burning +/// is not reproduced: no fire reaches these scenarios). +fn panic_pos(m: &mut Mob, w: &MobWorld, fly: bool) -> Option<[f64; 3]> { + if fly { + let view = m.view_vector(); + m.air_and_water_random_pos(w, 5, 4, 0, view[0], view[2]) + } else { + m.land_random_pos(w, 5, 4) + } +} +/// `BehaviorUtils.lockGazeAndWalkToEachOther` (this mob's half; the +/// partner's comes with the breed-target event). +fn lock_gaze_and_walk(m: &mut Mob, partner: Who, speed: f32, close: i32) { + let t = Tracker::entity(partner, true); + let mm = mem(m); + mm.look_target.set(t); + mm.walk_target.set(WalkTarget { + target: t, + speed, + close, + }); +} +/// `FollowTemptation`'s close-enough distance. +fn follow_temptation_close(m: &mut Mob) -> f64 { + match brain_mut(m).kind { + Kind::Sniffer => { + if m.is_baby() { + 2.5 + } else { + 3.5 + } + } + Kind::Ghastling => 3.0, + } +} +fn can_mate_with(m: &Mob, w: &MobWorld, partner: Who) -> bool { + let Who::Mob(id) = partner else { return false }; + let Some(s) = w.seen(id) else { return false }; + s.species == m.species() + && s.in_love + && m.extra.in_love > 0 + && sniffer::can_mate_state(sniffer::state(m)) + && sniffer::can_mate_state(s.variant) +} +fn partner_panicking(_w: &MobWorld, _partner: Who) -> bool { + false +} +/// `AnimalMakeLove.findValidBreedPartner`. +fn breed_partner(m: &mut Mob, w: &MobWorld) -> Option { + find_closest(m, w, |m, who| can_mate_with(m, w, who)) +} + +// ---- The sniffer -------------------------------------------------------- + +/// `Sniffer.transitionTo`: the state and its sound. +fn transition(m: &mut Mob, cx: &mut Bx, to: u8) { + let at = [m.position.x, m.position.y, m.position.z]; + let sound = |name: &'static str, pitch: f32| MobEvent::Sound(name, at, 1.0, pitch); + match to { + sniffer::FEELING_HAPPY => cx.events.push(sound("entity.sniffer.happy", 1.0)), + sniffer::SCENTING => { + let pitch = if m.is_baby() { 1.3 } else { 1.0 }; + cx.events.push(sound("entity.sniffer.scenting", pitch)); + } + sniffer::SNIFFING => cx.events.push(sound("entity.sniffer.sniffing", 1.0)), + // onDiggingStart: the seed drops 120 ticks in. + sniffer::DIGGING => m.extra.ints[3] = m.age as i32 + 120, + sniffer::RISING => cx.events.push(sound("entity.sniffer.digging_stop", 1.0)), + _ => {} + } + sniffer::set_state(m, to); +} +/// `SnifferAi.resetSniffing`. +fn reset_sniffing(m: &mut Mob, cx: &mut Bx) { + let mm = mem(m); + mm.sniffer_digging.clear(); + mm.sniffer_sniffing_target.clear(); + transition(m, cx, sniffer::IDLING); +} +/// `Sniffer.canSniff`. +fn can_sniff(m: &Mob) -> bool { + !is_tempted(m) + && !is_panicking(m) + && !m.fluids.in_water + && m.extra.in_love <= 0 + && m.on_ground + && !m.extra.passenger + && m.extra.leash.is_none() +} +/// `Sniffer.canDig(BlockPos)`: diggable, unexplored and reachable. +fn can_dig_at(m: &mut Mob, w: &MobWorld, p: [i32; 3]) -> bool { + w.has_tag( + "minecraft:sniffer_diggable_block", + w.block_name(p[0], p[1], p[2]), + ) && !m.extra.positions.contains(&p) + && m.create_path_to(w, p, 1).is_some_and(|path| path.reached) +} +/// `Sniffer.canDig()`. +fn can_dig(m: &mut Mob, w: &MobWorld) -> bool { + if is_panicking(m) + || is_tempted(m) + || m.is_baby() + || m.fluids.in_water + || !m.on_ground + || m.extra.passenger + { + return false; + } + let head = sniffer::head_block(m); + can_dig_at(m, w, [head[0], head[1] - 1, head[2]]) +} +/// `Sniffer.calculateDigPosition`: the first of five ever wider land +/// positions whose block below can be dug. +fn dig_position(m: &mut Mob, w: &MobWorld) -> Option<[i32; 3]> { + for idx in 0..5 { + let Some(p) = m.land_random_pos(w, 10 + 2 * idx, 3) else { + continue; + }; + let below = [ + p[0].floor() as i32, + p[1].floor() as i32 - 1, + p[2].floor() as i32, + ]; + if can_dig_at(m, w, below) { + return Some(below); + } + } + None +} + +/// `SnifferAi.getActivities`, in `availableBehaviorsByPriority` order: by +/// priority (`ActivityData.create(CORE, 0, ...)` numbers the core +/// behaviours 0, 1, 2...), then by the activity's bucket in the 16-bucket +/// `HashMap` (core 1, dig 3, idle 5, sniff 6, panic 15), +/// then in insertion order. +fn sniffer_package(seed: i64) -> Vec { + let e = |act: Act, b: B| Entry { act, b }; + let mut l = vec![ + // Priority 0: core, dig, idle, sniff. + e(Act::Core, B::Swim(Timed::new(60, 60))), + e(Act::Dig, B::Digging(Timed::new(160, 180))), + e(Act::Dig, B::FinishedDigging(Timed::new(40, 40))), + e( + Act::Idle, + B::MakeLove { + t: Timed::new(110, 110), + spawn_at: 0, + }, + ), + e(Act::Sniff, B::Searching(Timed::new(600, 600))), + // Priority 1. + e( + Act::Core, + B::AnimalPanic { + t: Timed::new(100, 120), + fly: false, + }, + ), + e( + Act::Idle, + B::FollowTemptation { + t: Timed::new(60, 60), + look_in_the_eyes: false, + }, + ), + // Priority 2. + e(Act::Core, move_to_target_sink(500, 700)), + e(Act::Idle, B::LookAtTargetSink(Timed::new(45, 90))), + // Priority 3. + e(Act::Core, B::CountDownTemptation(Timed::new(60, 60))), + e(Act::Idle, B::FeelingHappy(Timed::new(40, 100))), + ]; + // Priority 4. + l.push(e( + Act::Idle, + B::Gate(Box::new(Gate::run_one( + seed, + vec![ + ( + B::WalkToLookTarget { + running: false, + speed: 1.0, + close: 3, + }, + 2, + ), + (B::Scenting(Timed::new(40, 80)), 1), + (B::Sniffing(Timed::new(40, 80)), 1), + (B::LookAtPlayer(false), 1), + ( + B::Stroll { + running: false, + fly: false, + speed: 1.0, + }, + 1, + ), + (B::DoNothing(Timed::new(5, 20)), 2), + ], + ))), + )); + l +} +/// `HappyGhastAi.getActivities`, in `availableBehaviorsByPriority` order. +fn ghastling_package(seed: i64) -> Vec { + let e = |act: Act, b: B| Entry { act, b }; + vec![ + // Priority 0. + e(Act::Core, B::Swim(Timed::new(60, 60))), + // Priority 1. + e( + Act::Core, + B::AnimalPanic { + t: Timed::new(100, 120), + fly: true, + }, + ), + e( + Act::Idle, + B::FollowTemptation { + t: Timed::new(60, 60), + look_in_the_eyes: true, + }, + ), + // Priority 2. + e(Act::Core, B::LookAtTargetSink(Timed::new(45, 90))), + e( + Act::Idle, + B::FollowAdult { + running: false, + player: true, + }, + ), + // Priority 3. + e(Act::Core, move_to_target_sink(150, 250)), + e( + Act::Idle, + B::FollowAdult { + running: false, + player: false, + }, + ), + // Priority 4. + e(Act::Core, B::CountDownTemptation(Timed::new(60, 60))), + e( + Act::Idle, + B::Gate(Box::new(Gate::run_one( + seed, + vec![ + ( + B::Stroll { + running: false, + fly: true, + speed: 1.0, + }, + 1, + ), + ( + B::WalkToLookTarget { + running: false, + speed: 1.0, + close: 3, + }, + 1, + ), + ], + ))), + ), + ] +} +fn move_to_target_sink(min: i32, max: i32) -> B { + B::MoveToTargetSink { + t: Timed::new(min, max), + cooldown: 0, + path: None, + last_target: None, + speed: 0.0, + } +} + +// ---- Debug output (the mob AI harness) ------------------------------------ + +fn pos(p: [i32; 3]) -> String { + format!("{},{},{}", p[0], p[1], p[2]) +} +fn who(w: Who) -> String { + match w { + Who::Player => "player".into(), + Who::Mob(id) => format!("e{id}"), + } +} +fn tracker(t: Tracker) -> String { + match t { + Tracker::Entity { who: e, .. } => who(e), + Tracker::Block(p) => pos(p), + } +} + +/// The active activities and the memories, as the mob AI oracle prints +/// them. +pub fn describe(m: &Mob) -> Option<(String, String)> { + let b = brain(m)?; + let mut acts = ["core", b.activity.name()]; + acts.sort_unstable(); + let mm = &b.mem; + let mut out: Vec = Vec::new(); + let mut put = |name: &str, value: String, ttl: i64| { + if ttl == NEVER { + out.push(format!("{name}={value}")); + } else { + out.push(format!("{name}={value}@{ttl}")); + } + }; + macro_rules! slot { + ($name:expr, $s:expr, $f:expr) => { + if let Some(v) = $s.get() { + put($name, $f(v), $s.ttl); + } + }; + } + let n = |l: &Vec| format!("n{}", l.len()); + slot!("mobs", mm.mobs, n); + slot!("visible_mobs", mm.visible_mobs, |_: &Visible| { + "NearestVisibleLivingEntities".to_string() + }); + slot!("nearest_players", mm.nearest_players, n); + slot!( + "nearest_visible_player", + mm.nearest_visible_player, + |e: &Who| who(*e) + ); + slot!( + "nearest_visible_targetable_player", + mm.nearest_visible_targetable_player, + |e: &Who| who(*e) + ); + slot!( + "nearest_visible_targetable_players", + mm.nearest_visible_targetable_players, + n + ); + slot!( + "nearest_visible_adult", + mm.nearest_visible_adult, + |e: &Who| who(*e) + ); + slot!("walk_target", mm.walk_target, |t: &WalkTarget| format!( + "{}/{:x}/{}", + tracker(t.target), + t.speed.to_bits(), + t.close + )); + slot!("look_target", mm.look_target, |t: &Tracker| tracker(*t)); + slot!("breed_target", mm.breed_target, |e: &Who| who(*e)); + slot!("path", mm.path, |p: &Path| format!("path{}", pos(p.target))); + slot!("hurt_by", mm.hurt_by, |_: &bool| "DamageSource".to_string()); + slot!("hurt_by_entity", mm.hurt_by_entity, |e: &Who| who(*e)); + slot!( + "cant_reach_walk_target_since", + mm.cant_reach_walk_target_since, + |t: &i64| t.to_string() + ); + slot!("tempting_player", mm.tempting_player, |e: &Who| who(*e)); + slot!( + "temptation_cooldown_ticks", + mm.temptation_cooldown_ticks, + |t: &i32| t.to_string() + ); + slot!("is_panicking", mm.is_panicking, |b: &bool| b.to_string()); + slot!("sniffer_digging", mm.sniffer_digging, |b: &bool| b + .to_string()); + slot!( + "sniffer_sniffing_target", + mm.sniffer_sniffing_target, + |p: &[i32; 3]| pos(*p) + ); + slot!("sniffer_happy", mm.sniffer_happy, |b: &bool| b.to_string()); + slot!("sniff_cooldown", mm.sniff_cooldown, |_: &()| "u" + .to_string()); + if b.kind == Kind::Sniffer && !m.extra.positions.is_empty() { + put( + "sniffer_explored_positions", + format!("n{}", m.extra.positions.len()), + NEVER, + ); + } + out.sort(); + Some((acts.join("|"), out.join(" "))) +} diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index c5439479b..50adf62e5 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -304,6 +304,100 @@ 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; + let to_rad = std::f32::consts::PI / 180.0; + let x = self.previous_head_pitch * to_rad; + let y = -self.previous_yaw * to_rad; + let (y_cos, y_sin, x_cos, x_sin) = (y.mcos(), y.msin(), x.mcos(), x.msin()); + [ + f64::from(y_sin * x_cos), + f64::from(-x_sin), + f64::from(y_cos * x_cos), + ] + } + /// AirAndWaterRandomPos.getPos: within the radians of a direction, kept + /// near home, moved up out of solid blocks and free of path maluses. + pub fn air_and_water_random_pos( + &mut self, + w: &MobWorld, + h: i32, + v: i32, + fly_height: i32, + 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, + f64::from(h), + v, + fly_height, + xd, + 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 { + 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; + while p[1] <= 319 && w.solid(p[0], p[1], p[2]) { + p[1] += 1; + } + } + (m.malus(w.path_type_static(p[0], p[1], p[2])) == 0.0).then_some(p) + }) + } /// LandRandomPos.getPos pub fn land_random_pos(&mut self, w: &MobWorld, h: i32, v: i32) -> Option<[f64; 3]> { self.pick_best(w, |m| { diff --git a/crates/horizon-client/src/mobs/happy_ghast.rs b/crates/horizon-client/src/mobs/happy_ghast.rs index 463d29edf..56d5946f5 100644 --- a/crates/horizon-client/src/mobs/happy_ghast.rs +++ b/crates/horizon-client/src/mobs/happy_ghast.rs @@ -3,10 +3,10 @@ //! ghastling follows players and adults, a harnessed adult can be ridden and //! flown, healing is slow (fast in the rain) and `HappyGhastModel`. use super::{ - Mob, MobEvent, MobWorld, Species, + Mob, MobEvent, MobWorld, anim::{Poses, State}, control::{MoveKind, Operation}, - goals::{Cx, Float, Goal, LOOK, MOVE, Panic, Stroll, Tempt, goal_clone}, + goals::{Cx, Float, Goal, LOOK, MOVE, goal_clone}, nav::NavKind, }; use horizon_core::{ @@ -25,8 +25,11 @@ pub const AIR_SPEED: f32 = 0.05 * 5.0 / 3.0; pub fn register(m: &mut Mob) { setup(m, m.is_baby()); } -/// `adultGhastSetup` and `babyGhastSetup`. +/// `adultGhastSetup` and `babyGhastSetup`: the ghastling flies with a +/// `FlyingMoveControl` and has no goals (its brain drives it); the adult +/// floats with `GhastMoveControl` and three goals, its brain stopped. fn setup(m: &mut Mob, baby: bool) { + let was = m.extra.scratch[0]; m.extra.scratch[0] = if baby { 1 } else { 2 }; m.ai.goals.clear(); m.ai.nav.stop(); @@ -36,20 +39,15 @@ fn setup(m: &mut Mob, baby: bool) { max_turn: 180.0, hovers: true, }; + // BabyFlyingPathNavigation. m.ai.nav.kind = NavKind::Flying; m.ai.nav.can_float = true; m.ai.nav.required_path_length = 48.0; - let tempt = m.kind.food.clone(); - let g = &mut m.ai.goals; - g.add(0, Float); - g.add(0, Panic::new(2.0)); - let mut t = Tempt::new(1.25, tempt, false); - t.stop_distance = 3.0; - g.add(1, t); - g.add(2, FollowAdult::default()); - g.add(4, Stroll::flying(1.0)); return; } + if was == 1 { + super::animal_brain::grown_up(m); + } m.ai.mov.kind = MoveKind::Custom; m.ai.nav.kind = NavKind::Ground; let g = &mut m.ai.goals; @@ -274,53 +272,6 @@ impl Goal for FloatAround { m.ai.mov.set_wanted(t.x, t.y, t.z, 1.0); } } -/// `BabyFollowAdult`: a ghastling drifts toward the nearest player or adult -/// until it is a few blocks away. -#[derive(Clone, Debug, Default)] -struct FollowAdult { - close: f64, -} -impl FollowAdult { - fn target(m: &Mob, cx: &Cx) -> Option { - let player = - cx.w.player - .as_ref() - .filter(|p| p.alive && !p.spectator && m.distance_sqr(p.position) <= 32.0 * 32.0) - .map(|p| p.position); - player.or_else(|| { - cx.w.nearby(m.position, 32.0, |s| { - s.species == Species::HappyGhast && !s.baby - }) - .next() - .map(|s| s.position) - }) - } -} -impl Goal for FollowAdult { - goal_clone!(); - fn flags(&self) -> u8 { - MOVE - } - fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - m.is_baby() - && Self::target(m, cx).is_some_and(|t| { - let close = if self.close > 0.0 { self.close } else { 16.0 }; - m.position.distance_squared(t) > close * close - }) - } - fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - Self::target(m, cx).is_some_and(|t| m.position.distance_squared(t) > 9.0) - } - fn start(&mut self, m: &mut Mob, _: &mut Cx) { - // UniformInt.of(3, 16). - self.close = f64::from(3 + m.random.next_int_bound(14).unwrap_or(0)); - } - fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { - if let Some(t) = Self::target(m, cx) { - m.nav_move_to(cx.w, [t.x, t.y, t.z], 1.1); - } - } -} /// What a rider asks (`getRiddenInput`, `tickRidden`). pub fn ridden(m: &mut Mob) { let Some(r) = m.rider else { return }; diff --git a/crates/horizon-client/src/mobs/sniffer.rs b/crates/horizon-client/src/mobs/sniffer.rs index e8049b2d3..c9954669c 100644 --- a/crates/horizon-client/src/mobs/sniffer.rs +++ b/crates/horizon-client/src/mobs/sniffer.rs @@ -3,13 +3,10 @@ //! digging up a seed, the explored positions, laying eggs when bred, and //! `SnifferModel`'s keyframe animations. use super::{ - Mob, MobEvent, MobWorld, + Mob, MobEvent, anim::{Poses, State}, - brain::{Sink, Ttl, WalkTarget, duration}, - goals::{Breed, Cx, Float, Goal, Panic, Tempt, goal_clone}, keyframes::Animation, }; -use horizon_core::random::RandomSource; use std::collections::HashMap; // Sniffer state: `variant` the state (below), `scratch[0]` the state the @@ -24,15 +21,14 @@ pub const SEARCHING: u8 = 4; pub const DIGGING: u8 = 5; pub const RISING: u8 = 6; -const SNIFF_COOLDOWN: i32 = 9600; /// `Sniffer.getBabyStartAge`. pub const BABY_START_AGE: i32 = -48000; pub fn state(m: &Mob) -> u8 { m.extra.variant } -fn set_state(m: &mut Mob, s: u8) { - m.extra.variant = s; +fn now(m: &Mob) -> i32 { + m.age as i32 } /// `Sniffer.getDefaultDimensions`: lower while digging. pub fn digging(m: &Mob) -> bool { @@ -44,468 +40,36 @@ pub fn register(m: &mut Mob) { m.set_malus(PathType::Water, -1.0); m.set_malus(PathType::OnTopOfPowderSnow, -1.0); m.set_malus(PathType::DamageCautious, -1.0); - let tempt = m.kind.tempt.clone(); - let g = &mut m.ai.goals; - g.add(0, Float); - g.add(0, SnifferPanic(Panic::new(2.0))); - g.add( - 0, - Brain { - walk: None, - sink: Sink::new(500, 700), - look: None, - look_until: 0, - digging: false, - happy: false, - cooldown: Ttl::default(), - sniff_target: None, - run: Run::None, - until: 0, - breed: Breed::new(1.0), - tempt: Tempt::new(1.25, tempt, false), - love_on: false, - tempt_on: false, - }, - ); } -/// The core's `AnimalPanic`, forgetting any sniffing when it starts. -#[derive(Clone, Debug)] -struct SnifferPanic(Panic); -impl Goal for SnifferPanic { - goal_clone!(); - fn flags(&self) -> u8 { - self.0.flags() - } - fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - self.0.can_use(m, cx) - } - 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) { - set_state(m, IDLING); - self.0.start(m, cx) - } - fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { - self.0.stop(m, cx) - } -} -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Run { - None, - Digging, - FinishedDigging, - Searching, - Happy, - Scenting, - Sniffing, - DoNothing, -} -#[derive(Clone, Debug)] -struct Brain { - walk: Option, - sink: Sink, - /// `LOOK_TARGET` and the end of `LookAtTargetSink`'s run (0 when not running). - look: Option<[f64; 3]>, - look_until: i32, - /// `SNIFFER_DIGGING`, `SNIFFER_HAPPY`, `SNIFF_COOLDOWN`, `SNIFFER_SNIFFING_TARGET`. - digging: bool, - happy: bool, - cooldown: Ttl, - sniff_target: Option<[i32; 3]>, - /// The timed behaviour running and when it times out. - run: Run, - until: i32, - breed: Breed, - tempt: Tempt, - love_on: bool, - tempt_on: bool, -} -impl Goal for Brain { - goal_clone!(); - fn flags(&self) -> u8 { - 0 - } - fn can_use(&mut self, _: &mut Mob, _: &mut Cx) -> bool { - true - } - fn every_tick(&self) -> bool { - true - } - fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { - self.brain(m, cx); - } -} -fn now(m: &Mob) -> i32 { - m.age as i32 -} -fn sound(m: &Mob, cx: &mut Cx, name: &'static str, pitch: f32) { - cx.events - .push(MobEvent::Sound(name, m.center(), 1.0, pitch)); +/// `Sniffer.setState`. +pub fn set_state(m: &mut Mob, s: u8) { + m.extra.variant = s; } /// `Sniffer.getOnPos`: the block under its feet. -fn on_pos(m: &Mob) -> [i32; 3] { +pub fn on_pos(m: &Mob) -> [i32; 3] { [ m.position.x.floor() as i32, - (m.position.y - 0.2).floor() as i32, + (m.position.y - f64::from(0.2_f32)).floor() as i32, m.position.z.floor() as i32, ] } -/// `Sniffer.getHeadBlock`: 2.25 blocks ahead of it, a little above its feet. +/// `Sniffer.getHeadBlock`: 2.25 blocks along `getForward()`, at its feet +/// plus 0.2. pub fn head_block(m: &Mob) -> [i32; 3] { - let (yaw, pitch) = (m.yaw.to_radians(), m.head_pitch.to_radians()); - let forward = [ - f64::from(-yaw.sin() * pitch.cos()), - f64::from(-pitch.sin()), - f64::from(yaw.cos() * pitch.cos()), - ]; + use horizon_core::geometry::trig::Mth; + // Vec3.directionFromRotation(xRot, yRot). + let to_rad = std::f32::consts::PI / 180.0; + let y = -m.yaw * to_rad - std::f32::consts::PI; + let x = -m.head_pitch * to_rad; + let (y_cos, y_sin) = (y.mcos(), y.msin()); + let x_cos = -x.mcos(); + let forward = [f64::from(y_sin * x_cos), f64::from(y_cos * x_cos)]; [ (m.position.x + forward[0] * 2.25).floor() as i32, (m.position.y + f64::from(0.2_f32)).floor() as i32, - (m.position.z + forward[2] * 2.25).floor() as i32, + (m.position.z + forward[1] * 2.25).floor() as i32, ] } -impl Brain { - fn tempted(&self) -> bool { - self.tempt_on - } - /// `Sniffer.canSniff`. - fn can_sniff(&self, m: &Mob) -> bool { - !self.tempted() - && !m.ai.panicking - && !m.fluids.in_water - && m.extra.in_love <= 0 - && m.on_ground - && m.rider.is_none() - && m.extra.leash.is_none() - } - /// `Sniffer.canDig(BlockPos)`: diggable, unexplored and reachable. - fn can_dig_at(&self, m: &mut Mob, w: &MobWorld, p: [i32; 3]) -> bool { - w.has_tag( - "minecraft:sniffer_diggable_block", - w.block_name(p[0], p[1], p[2]), - ) && !m.extra.positions.contains(&p) - && m.create_path_to(w, p, 1).is_some_and(|path| path.reached) - } - /// `Sniffer.canDig`. - fn can_dig(&self, m: &mut Mob, w: &MobWorld) -> bool { - if m.ai.panicking - || self.tempted() - || m.is_baby() - || m.fluids.in_water - || !m.on_ground - || m.rider.is_some() - { - return false; - } - let head = head_block(m); - self.can_dig_at(m, w, [head[0], head[1] - 1, head[2]]) - } - /// `Sniffer.calculateDigPosition`. - fn dig_position(&self, m: &mut Mob, w: &MobWorld) -> Option<[i32; 3]> { - for idx in 0..5 { - let Some(p) = m.land_random_pos(w, 10 + 2 * idx, 3) else { - continue; - }; - let below = [ - p[0].floor() as i32, - p[1].floor() as i32 - 1, - p[2].floor() as i32, - ]; - if self.can_dig_at(m, w, below) { - return Some(below); - } - } - None - } - fn transition(&mut self, m: &mut Mob, cx: &mut Cx, to: u8) { - match to { - FEELING_HAPPY => sound(m, cx, "entity.sniffer.happy", 1.0), - SCENTING => { - let pitch = if m.is_baby() { 1.3 } else { 1.0 }; - sound(m, cx, "entity.sniffer.scenting", pitch) - } - SNIFFING => sound(m, cx, "entity.sniffer.sniffing", 1.0), - DIGGING => m.extra.ints[3] = now(m) + 120, - RISING => sound(m, cx, "entity.sniffer.digging_stop", 1.0), - _ => {} - } - set_state(m, to); - } - /// `SnifferAi.resetSniffing`. - fn reset_sniffing(&mut self, m: &mut Mob, cx: &mut Cx) { - self.digging = false; - self.sniff_target = None; - self.transition(m, cx, IDLING); - } - fn brain(&mut self, m: &mut Mob, cx: &mut Cx) { - self.cooldown.tick(); - // Tempted: the tempting player memory while the goal runs. - if m.ai.panicking { - self.walk = None; - self.sink.stop(m, &mut self.walk); - self.love_on = false; - self.tempt_on = false; - } else { - self.start_behaviours(m, cx); - } - self.sink.tick(m, cx, &mut self.walk); - self.tick_running(m, cx); - } - /// `Brain.startEachNonRunningBehavior` for the first valid activity. - fn start_behaviours(&mut self, m: &mut Mob, cx: &mut Cx) { - let n = now(m); - // DIG, SNIFF, IDLE. - let dig = self.digging && self.walk.is_none(); - let sniff = self.sniff_target.is_some() && self.walk.is_some(); - if dig { - if self.run == Run::None && !self.cooldown.present() && self.can_sniff(m) { - self.run = Run::Digging; - self.until = n + duration(m, 160, 180); - self.transition(m, cx, DIGGING); - } - if self.run == Run::None && self.cooldown.present() { - self.run = Run::FinishedDigging; - self.until = n + 40; - self.transition(m, cx, RISING); - } - return; - } - if sniff { - if self.run == Run::None && self.can_sniff(m) { - self.run = Run::Searching; - self.until = n + 600; - self.transition(m, cx, SEARCHING); - } - return; - } - if self.digging { - return; - } - // IDLE: love, tempt, look at the target, feeling happy, one of the rest. - if !self.love_on && !self.tempt_on && self.breed.can_use(m, cx) { - self.reset_sniffing(m, cx); - self.breed.start(m, cx); - self.love_on = true; - } - if !self.love_on && !self.tempt_on && self.tempt.can_use(m, cx) { - self.reset_sniffing(m, cx); - self.tempt.start(m, cx); - self.tempt_on = true; - } - if self.look.is_some() && self.look_until == 0 { - self.look_until = n + duration(m, 45, 90); - } - if self.run == Run::None && self.happy { - self.run = Run::Happy; - self.until = n + duration(m, 40, 100); - self.transition(m, cx, FEELING_HAPPY); - } - if self.run == Run::None { - self.run_one(m, cx); - } - } - /// The idle `RunOne`: a weighted random pick among what can start. - fn run_one(&mut self, m: &mut Mob, cx: &mut Cx) { - let n = now(m); - // (weight, option) - let mut options: Vec<(i32, u8)> = Vec::new(); - if self.look.is_some() && self.walk.is_none() { - options.push((2, 0)); - } - if !self.happy && !self.love_on && !self.tempted() && self.sniff_target.is_none() { - options.push((1, 1)); - } - if self.walk.is_none() - && self.sniff_target.is_none() - && !self.cooldown.present() - && !m.is_baby() - && self.can_sniff(m) - { - options.push((1, 2)); - } - if cx.w.player.as_ref().is_some_and(|p| { - p.alive && !p.creative && m.distance_sqr(p.position) <= 36.0 && !p.spectator - }) { - options.push((1, 3)); - } - if self.walk.is_none() { - options.push((1, 4)); - } - options.push((2, 5)); - let total: i32 = options.iter().map(|o| o.0).sum(); - // A weighted pick from the high bits (`WeightedList.getRandom`). - let mut roll = ((m.random.next_float() * total as f32) as i32).min(total - 1); - let mut pick = options[0].1; - for (w, o) in &options { - if roll < *w { - pick = *o; - break; - } - roll -= w; - } - match pick { - // SetWalkTargetFromLookTarget(1.0, 3). - 0 => { - if let Some(l) = self.look { - self.walk = Some(WalkTarget::new( - [ - l[0].floor() as i32, - l[1].floor() as i32, - l[2].floor() as i32, - ], - 1.0, - 3, - )); - } - } - 1 => { - self.run = Run::Scenting; - self.until = n + duration(m, 40, 80); - self.transition(m, cx, SCENTING); - } - 2 => { - self.run = Run::Sniffing; - self.until = n + duration(m, 40, 80); - self.transition(m, cx, SNIFFING); - } - // SetEntityLookTarget(PLAYER, 6). - 3 => { - if let Some(p) = &cx.w.player { - self.look = Some(p.eye); - self.look_until = 0; - } - } - // RandomStroll.stroll(1.0). - 4 => { - if let Some(p) = m.land_random_pos(cx.w, 10, 7) { - self.walk = Some(WalkTarget::new( - [ - p[0].floor() as i32, - p[1].floor() as i32, - p[2].floor() as i32, - ], - 1.0, - 0, - )); - } - } - _ => { - self.run = Run::DoNothing; - self.until = n + duration(m, 5, 20); - } - } - } - /// `Brain.tickRunningBehaviors`. - fn tick_running(&mut self, m: &mut Mob, cx: &mut Cx) { - let n = now(m); - let timed_out = n > self.until; - // The delegated idle behaviours. - if self.love_on { - if self.breed.can_continue(m, cx) { - self.breed.tick(m, cx); - } else { - self.breed.stop(m, cx); - self.love_on = false; - } - } - if self.tempt_on { - self.tempt.stop_distance = if m.is_baby() { 2.5 } else { 3.5 }; - if self.tempt.can_continue(m, cx) { - self.tempt.tick(m, cx); - } else { - self.tempt.stop(m, cx); - self.tempt_on = false; - } - } - // LookAtTargetSink. - if self.look_until != 0 { - if let Some(l) = self.look - && n <= self.look_until - { - m.look_at(l); - } else { - self.look = None; - self.look_until = 0; - } - } - match self.run { - Run::None => {} - Run::Digging => { - let ok = self.digging && self.can_dig(m, cx.w) && m.extra.in_love <= 0; - if timed_out || !ok { - if timed_out { - self.cooldown.set(SNIFF_COOLDOWN); - } else { - self.reset_sniffing(m, cx); - } - self.run = Run::None; - } - } - Run::FinishedDigging => { - if timed_out || !self.digging { - self.transition(m, cx, IDLING); - // onDiggingComplete: remember the spot when it finished. - if timed_out { - let p = on_pos(m); - m.extra.positions.insert(0, p); - m.extra.positions.truncate(21); - } - self.digging = false; - self.happy = true; - self.run = Run::None; - } - } - Run::Searching => { - let still = if !self.can_sniff(m) { - self.transition(m, cx, IDLING); - false - } else { - match (self.walk, self.sniff_target) { - (Some(w), Some(t)) => w.pos == t, - _ => false, - } - }; - if timed_out || !still { - if self.can_dig(m, cx.w) && self.can_sniff(m) { - self.digging = true; - } - self.sink.stop(m, &mut self.walk); - self.sniff_target = None; - self.run = Run::None; - } - } - Run::Happy => { - if timed_out { - self.transition(m, cx, IDLING); - self.happy = false; - self.run = Run::None; - } - } - Run::Scenting => { - if timed_out { - self.transition(m, cx, IDLING); - self.run = Run::None; - } - } - Run::Sniffing => { - if timed_out || !self.can_sniff(m) { - self.transition(m, cx, IDLING); - if timed_out && let Some(p) = self.dig_position(m, cx.w) { - self.sniff_target = Some(p); - self.walk = Some(WalkTarget::new(p, 1.25, 0)); - } - self.run = Run::None; - } - } - Run::DoNothing => { - if timed_out { - self.run = Run::None; - } - } - } - } -} /// `Sniffer.tick` and `Sniffer.aiStep` additions: the animation states, /// the dropped seed and the water malus. pub fn ai_step(m: &mut Mob, events: &mut Vec) { diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index bee2af785..957605492 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -73,6 +73,27 @@ def scenarios(): 'player 12.5 -60 0.5', 'mob minecraft:villager 0.5 -60 0.5 0 51 persistent', ]) + # Llamas and trader llamas: strolling, looking at the player, a baby following its parent and a + # llama hunting a wolf (LlamaAttackWolfGoal) and spitting at it. + for species, seed in [('llama', 61), ('trader_llama', 62)]: + add(f'{species}_player', 200, ['player 6.5 -60 0.5', f'mob minecraft:{species} 0.5 -60 0.5 0 {seed} persistent']) + add(f'{species}_alone', 200, [f'mob minecraft:{species} 0.5 -60 0.5 90 {seed * 7 + 1} persistent']) + add('llama_family', 200, ['mob minecraft:llama 0.5 -60 0.5 0 63 persistent', + 'mob minecraft:llama 6.5 -60 2.5 0 64 persistent baby']) + add('llama_wolf', 200, ['mob minecraft:llama 0.5 -60 0.5 0 65 persistent', + 'mob minecraft:wolf 8.5 -60 0.5 0 66 persistent']) + # Sniffers on diggable grass: scenting, sniffing, searching and digging. + add('sniffer_player', 400, ['player 8.5 -60 0.5', 'mob minecraft:sniffer 0.5 -60 0.5 0 71 persistent']) + for i, seed in enumerate([72, 73, 74]): + add(f'sniffer_alone_{i}', 600, [f'mob minecraft:sniffer 0.5 -60 0.5 {90 * i} {seed} persistent']) + add('sniffer_baby', 300, ['mob minecraft:sniffer 0.5 -60 0.5 0 75 persistent baby']) + # Happy ghasts float above the grass; ghastlings follow players and adults. + add('happy_ghast_player', 200, ['player 6.5 -60 0.5', 'mob minecraft:happy_ghast 0.5 -55 0.5 0 81 persistent']) + add('happy_ghast_alone', 200, ['mob minecraft:happy_ghast 0.5 -55 0.5 90 82 persistent']) + add('ghastling_player', 200, ['player 8.5 -60 0.5', 'mob minecraft:happy_ghast 0.5 -57 0.5 0 83 persistent baby']) + add('ghastling_alone', 200, ['mob minecraft:happy_ghast 0.5 -57 0.5 0 84 persistent baby']) + add('ghastling_adult', 200, ['mob minecraft:happy_ghast 10.5 -55 0.5 0 85 persistent', + 'mob minecraft:happy_ghast 0.5 -57 0.5 0 86 persistent baby']) return s From 4e871bf22ee70b5c119a289650db2f162f63e886 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 16:29:00 +0200 Subject: [PATCH 3/8] Match vanilla llamas: the horse tail draw and mobs seeing earlier mobs' moves AbstractHorse.aiStep draws a tail swish every tick before the goals run. Mobs now see the mobs ticked before them as they are after their tick (ServerLevel ticks entities one after another), in the game and in the mob AI probe; a baby llama following its parent depended on it. The llama's strength is read raw, as getStrength does. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/mob_ai_probe.rs | 58 ++++++++++--------- crates/horizon-client/src/game/creatures.rs | 24 +++++--- crates/horizon-client/src/mobs/ai.rs | 4 ++ crates/horizon-client/src/mobs/anim.rs | 3 +- crates/horizon-client/src/mobs/llama.rs | 21 ++----- 5 files changed, 58 insertions(+), 52 deletions(-) diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index ab6cce246..261eef40f 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -464,35 +464,41 @@ fn main() -> horizon_client::Result<()> { } for t in 1..=s.ticks { world.game_time += 1; - let snapshot: Vec = mobs.iter().filter(|m| !m.removed).map(seen).collect(); - let w = MobWorld { - world: &world, - registry, - facts: &facts, - collision: &collision, - data: &data, - player: player.clone(), - others: &snapshot, - daylight: (s.time.rem_euclid(24000)) < 12000, - game_time: world.game_time, - day_time: world.day_time, - raining: s.rain, - thundering: s.thunder, - nether: false, - block_tags: &items.block_tags, - biomes: &biomes, - mob_griefing: true, - difficulty: LocalDifficulty::new(2, world.day_time, 0, 0.0), - end: false, - world_seed: 0, - }; + let mut snapshot: Vec = mobs.iter().filter(|m| !m.removed).map(seen).collect(); let mut events = Vec::new(); - for m in &mut mobs { - if m.removed { + for i in 0..mobs.len() { + if mobs[i].removed { continue; } - if !m.tick(&w, &mut scratch, &mut events) { - m.removed = true; + let w = MobWorld { + world: &world, + registry, + facts: &facts, + collision: &collision, + data: &data, + player: player.clone(), + others: &snapshot, + daylight: (s.time.rem_euclid(24000)) < 12000, + game_time: world.game_time, + day_time: world.day_time, + raining: s.rain, + thundering: s.thunder, + nether: false, + block_tags: &items.block_tags, + biomes: &biomes, + mob_griefing: true, + difficulty: LocalDifficulty::new(2, world.day_time, 0, 0.0), + end: false, + world_seed: 0, + }; + if !mobs[i].tick(&w, &mut scratch, &mut events) { + mobs[i].removed = true; + } + // ServerLevel ticks entities one after another: the ones + // after this mob see it as it is now. + if let Some(e) = snapshot.iter_mut().find(|e| e.id == mobs[i].id) { + *e = seen(&mobs[i]); + e.alive &= !mobs[i].removed; } } for (i, m) in mobs.iter().enumerate() { diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 1e0751d5b..cfa159dd4 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -438,26 +438,34 @@ impl Game<'_> { } self.tick_raids(); let uuid = self.level.player_uuid; - let snapshot: Vec = self.mobs.iter().map(|m| seen(m, uuid)).collect(); + let mut snapshot: Vec = self.mobs.iter().map(|m| seen(m, uuid)).collect(); let mut events = Vec::new(); let mut mobs = std::mem::take(&mut self.mobs); let mut dead = Vec::new(); { - let w = self.mob_world_base(&snapshot); let mut scratch = self.world.random.clone(); - mobs.retain_mut(|m| { + let mut keep = Vec::with_capacity(mobs.len()); + for (i, m) in mobs.iter_mut().enumerate() { + let w = self.mob_world_base(&snapshot); if !w .world .loaded(m.position.x.floor() as i32, m.position.z.floor() as i32) { - return !m.hostile() || m.persistent; + keep.push(!m.hostile() || m.persistent); + continue; } - let keep = m.tick(&w, &mut scratch, &mut events); - if !keep && !m.alive() && !m.removed { + let kept = m.tick(&w, &mut scratch, &mut events); + if !kept && !m.alive() && !m.removed { dead.push(m.clone()); } - keep - }); + keep.push(kept); + // ServerLevel ticks entities one after another: the ones + // after this mob see it as it is now. + snapshot[i] = seen(m, uuid); + snapshot[i].alive &= kept; + } + let mut flags = keep.into_iter(); + mobs.retain(|_| flags.next().unwrap_or(true)); push_apart(&mut mobs); } self.mobs.append(&mut mobs); diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 4d5c1307e..2d0a32a80 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -490,6 +490,10 @@ fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } /// LivingEntity.aiStep (and Mob/AgeableMob/Animal additions). fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + // AbstractHorse.aiStep: the tail swishes now and then (moveTail). + if super::equine::is_equine(m.species()) { + let _ = m.random.next_int_bound(200); + } if super::creaking::is_creaking(m) { super::creaking::update(m, w, events); } diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index 27f441adc..b8434d75e 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -464,7 +464,8 @@ pub fn setup( Anim::Sniffer => super::sniffer::anim(m, s, p, w_anims), Anim::HappyGhast => super::happy_ghast::anim(m, s, p), Anim::Nautilus => super::nautilus::anim(m, s, p, w_anims), - Anim::Llama => super::llama::anim(m, s, p), + // body_anim::llama runs first. + Anim::Llama => quadruped(p, s), Anim::Warden => super::warden::anim(m, s, p, w_anims), Anim::Allay => super::allay::anim(m, s, p), Anim::Creaking => super::creaking::anim(m, s, p, w_anims), diff --git a/crates/horizon-client/src/mobs/llama.rs b/crates/horizon-client/src/mobs/llama.rs index fbae29b02..3fc2dc935 100644 --- a/crates/horizon-client/src/mobs/llama.rs +++ b/crates/horizon-client/src/mobs/llama.rs @@ -3,9 +3,7 @@ //! spit ranged attack, hunting wolves (and, for traders, zombies and //! illagers) and `LlamaModel`. use super::{ - Mob, MobEvent, MobWorld, Seen, Species, Who, - anim::{Poses, State}, - equine, + Mob, MobEvent, MobWorld, Seen, Species, Who, equine, goals::{ Breed, Cx, Float, FollowParent, Goal, HurtByTarget, LookAtPlayer, NearestTarget, Panic, Prey, RandomLookAround, Stroll, Tempt, goal_clone, @@ -14,7 +12,6 @@ use super::{ }; use crate::projectiles::{Projectile, ProjectileKind}; use horizon_core::{geometry::Vec3, random::RandomSource}; -use std::f32::consts::PI; pub const VARIANTS: [&str; 4] = ["creamy", "white", "brown", "gray"]; /// `Llama.getMaxTemper`. @@ -29,9 +26,10 @@ pub fn is_llama(s: Species) -> bool { pub fn is_trader(m: &Mob) -> bool { m.species() == Species::TraderLlama } -/// `Llama.getStrength`. +/// `Llama.getStrength`: the stored strength (0 for a llama that was never +/// given one; `setStrength` keeps it within 1 to 5). pub fn strength(m: &Mob) -> i32 { - i32::from(m.extra.variant2).clamp(1, 5) + i32::from(m.extra.variant2) } /// `getInventoryColumns`: a chest holds three rows of `strength` columns. pub fn inventory_columns(m: &Mob) -> i32 { @@ -250,17 +248,6 @@ pub fn decor(m: &Mob) -> Option<(String, String)> { (model.into(), format!("entity/equipment/llama_body/{name}")) }) } -/// `LlamaModel.setupAnim`. -pub fn anim(m: &Mob, s: &State, p: &mut Poses) { - super::anim::quadruped(p, s); - let chest = m.extra.chested && !s.baby; - for part in ["right_chest", "left_chest"] { - if !chest { - p.visible(part, false); - } - } - let _ = PI; -} #[cfg(test)] mod tests { use super::*; From 89c3a155c5133115f5cb877ce24c1526de988eba Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 16:31:58 +0200 Subject: [PATCH 4/8] Play the sniffer's digging and searching sounds on the client side The searching sound and the digging block hit sound are the client's (playSearchingSound, emitDiggingParticles), the digging sound starts with the dig (SnifferSoundInstance), and the egg plop and the breeding experience come from the parent's random in its brain. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/sniffers.rs | 42 ++++++++++++------- .../horizon-client/src/mobs/animal_brain.rs | 15 +++++++ crates/horizon-client/src/mobs/sniffer.rs | 9 +--- 3 files changed, 44 insertions(+), 22 deletions(-) diff --git a/crates/horizon-client/src/game/sniffers.rs b/crates/horizon-client/src/game/sniffers.rs index 683ab733f..61325ede6 100644 --- a/crates/horizon-client/src/game/sniffers.rs +++ b/crates/horizon-client/src/game/sniffers.rs @@ -10,20 +10,19 @@ use horizon_client::{ use horizon_core::random::RandomSource; impl Game<'_> { - /// An egg item at the parent, a plop and some experience. + /// The egg item at the parent (`Sniffer.spawnChildFromBreeding`; the + /// brain already played the plop and dropped the experience). pub(super) fn lay_sniffer_egg(&mut self, parent: &Mob) { let at = [parent.position.x, parent.position.y, parent.position.z]; + // new ItemEntity(level, x, y, z, stack): a little random push. + let vx = self.world.random.next_double() * 0.2 - 0.1; + let vz = self.world.random.next_double() * 0.2 - 0.1; self.spawn_item( ItemStack::new("minecraft:sniffer_egg", 1), at, - [0.0, 0.2, 0.0], + [vx, 0.2, vz], 10, ); - let pitch = (self.world.random.next_float() - self.world.random.next_float()) * 0.2 + 0.5; - self.audio - .play("minecraft:block.sniffer_egg.plop", Some(at), 1.0, pitch); - let xp = 1 + self.world.random.next_int_bound(7).unwrap_or(0) as u32; - self.spawn_orbs(at, xp); } /// A snifflet where the egg was. pub(super) fn hatch_sniffer(&mut self, pos: [i32; 3]) { @@ -42,8 +41,10 @@ impl Game<'_> { m.head_yaw = yaw; } } - /// `Sniffer.emitDiggingParticles`: block dust and the digging sound - /// between the 1.7th and the 6th second of the digging animation. + /// The sniffer's client-side effects: `SnifferSoundInstance` when it + /// starts digging, `Sniffer.emitDiggingParticles` (block dust and the + /// block's hit sound between the 1.7th and the 6th second of the + /// digging animation) and `playSearchingSound`. pub(super) fn tick_sniffer_effects(&mut self) { let Some(camera) = self.player.as_ref().map(|p| p.position) else { return; @@ -52,14 +53,27 @@ impl Game<'_> { let m = &self.mobs[i]; if m.species() != Species::Sniffer || !m.alive() - || !sniffer::digging(m) + || m.silent || m.position.distance_squared(camera) > 32.0 * 32.0 { continue; } + let at = [m.position.x, m.position.y, m.position.z]; + if sniffer::state(m) == sniffer::SEARCHING && m.age.is_multiple_of(20) { + self.audio + .play("minecraft:entity.sniffer.searching", Some(at), 1.0, 1.0); + continue; + } + if !sniffer::digging(m) { + continue; + } let Some(ms) = m.anim.states[3].millis(m.age as f32) else { continue; }; + if ms == 0 { + self.audio + .play("minecraft:entity.sniffer.digging", Some(at), 1.0, 1.0); + } if ms <= 1700 || ms >= 6000 { continue; } @@ -68,19 +82,19 @@ impl Game<'_> { let Some((sprite, tint)) = self.particle_sprite(below) else { continue; }; - let at = [ + let dust = [ f64::from(head[0]) + 0.5, f64::from(head[1]) + 0.5 - f64::from(0.65_f32), f64::from(head[2]) + 0.5, ]; for _ in 0..30 { let particle = - Particle::terrain(&mut self.world.random, at, [0.0; 3], sprite.clone(), tint); + Particle::terrain(&mut self.world.random, dust, [0.0; 3], sprite.clone(), tint); self.particles.push(particle); } if self.mobs[i].age.is_multiple_of(10) { - self.audio - .play("minecraft:entity.sniffer.digging", Some(at), 0.5, 0.5); + let hit = self.res.facts.get(below).sounds.hit.clone(); + self.audio.play(&hit, Some(at), 0.5, 0.5); } } } diff --git a/crates/horizon-client/src/mobs/animal_brain.rs b/crates/horizon-client/src/mobs/animal_brain.rs index 5a724a518..ad2952891 100644 --- a/crates/horizon-client/src/mobs/animal_brain.rs +++ b/crates/horizon-client/src/mobs/animal_brain.rs @@ -1295,6 +1295,21 @@ impl B { parent: m.id, partner: id, }); + if brain_mut(m).kind == Kind::Sniffer { + // Sniffer.spawnChildFromBreeding: the experience + // (finalizeSpawnChildFromBreeding), then the plop, + // both from the parent's random; the game lays the + // egg. + let at = [m.position.x, m.position.y, m.position.z]; + let xp = 1 + m.random.next_int_bound(7).unwrap_or(0); + cx.events.push(MobEvent::Experience { + at, + amount: xp as u32, + }); + let pitch = (m.random.next_float() - m.random.next_float()) * 0.2 + 0.5; + cx.events + .push(MobEvent::Sound("block.sniffer_egg.plop", at, 1.0, pitch)); + } mem(m).breed_target.clear(); } } diff --git a/crates/horizon-client/src/mobs/sniffer.rs b/crates/horizon-client/src/mobs/sniffer.rs index c9954669c..6979171b8 100644 --- a/crates/horizon-client/src/mobs/sniffer.rs +++ b/crates/horizon-client/src/mobs/sniffer.rs @@ -104,14 +104,7 @@ pub fn ai_step(m: &mut Mob, events: &mut Vec) { 1.0, )); } - if current == SEARCHING && m.age.is_multiple_of(20) { - events.push(MobEvent::Sound( - "entity.sniffer.searching", - m.center(), - 1.0, - 1.0, - )); - } + // The searching sound is the client's (`playSearchingSound`). // onPathfindingStart / Done: water only blocks the way while it is dry. let wet = m.fluids.in_water || m.fire_ticks > 0; m.set_malus(PathType::Water, if wet { 0.0 } else { -1.0 }); From 5352b593585b9183b41dea779076005d8b66bd37 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 16:36:44 +0200 Subject: [PATCH 5/8] Tick the sniffer's and the ghastling's brains The level random is passed down to the mob AI step as the integration branch does, the brain runs in customServerAiStep's place, and the mob AI probe builds the brain after seeding the mob and prints its activities and memories. The oracle seeds every GateBehavior's shuffle with the mob's seed (the same change the entity-ai branch makes) so RunOne picks are reproducible. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/mob_ai_probe.rs | 11 +++++- crates/horizon-client/src/mobs.rs | 4 +-- crates/horizon-client/src/mobs/ai.rs | 30 ++++++++++++---- .../horizonlab/parity/VanillaMobAiOracle.java | 36 +++++++++++++++++++ 4 files changed, 72 insertions(+), 9 deletions(-) diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 261eef40f..39d3d7437 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -316,7 +316,11 @@ fn print(out: &mut String, t: i32, i: usize, m: &Mob) { f(m.ai.speed), u8::from(m.ai.jumping) ); - let _ = writeln!(out, "\trng {:x}", m.random.state()); + let _ = write!(out, "\trng {:x}", m.random.state()); + if let Some((acts, mem)) = horizon_client::mobs::animal_brain::describe(m) { + let _ = write!(out, "\tact {acts}\tmem {mem}"); + } + out.push('\n'); } fn main() -> horizon_client::Result<()> { @@ -429,6 +433,11 @@ fn main() -> horizon_client::Result<()> { } } m.random = LegacyRandom::new(spec.seed); + // The oracle seeds the random after the brain is built, then + // delays the sensors again and seeds the gates' shuffles. + if horizon_client::mobs::animal_brain::kind_of(&m).is_some() { + horizon_client::mobs::animal_brain::init(&mut m, spec.seed); + } mobs.push(m); } let player = s.player.map(|p| { diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 34ccac776..5754bfae9 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1173,10 +1173,10 @@ impl Mob { pub fn tick( &mut self, w: &MobWorld, - _random: &mut LegacyRandom, + random: &mut LegacyRandom, events: &mut Vec, ) -> bool { - ai::tick(self, w, events) + ai::tick(self, w, random, events) } pub fn distance_to(&self, p: [f64; 3]) -> f64 { let d = [ diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 2d0a32a80..d1415d73e 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -12,7 +12,10 @@ use super::{ undead, }; use crate::blocks::Fluid; -use horizon_core::{geometry::Vec3, random::RandomSource}; +use horizon_core::{ + geometry::Vec3, + random::{LegacyRandom, RandomSource}, +}; #[derive(Clone, Debug, Default)] pub struct Ai { @@ -264,7 +267,12 @@ fn generic(m: &mut Mob) { } } /// One full entity tick. Returns false when the mob is gone. -pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) -> bool { +pub fn tick( + m: &mut Mob, + w: &MobWorld, + level_random: &mut LegacyRandom, + events: &mut Vec, +) -> bool { if m.removed { return false; } @@ -299,7 +307,7 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) -> bool { return false; } if !m.no_ai { - ai_step(m, w, events); + ai_step(m, w, level_random, events); } // Mob.tickHeadTurn -> BodyRotationControl.clientTick if m.alive() { @@ -489,7 +497,7 @@ fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } } /// LivingEntity.aiStep (and Mob/AgeableMob/Animal additions). -fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { +fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: &mut Vec) { // AbstractHorse.aiStep: the tail swishes now and then (moveTail). if super::equine::is_equine(m.species()) { let _ = m.random.next_int_bound(200); @@ -513,7 +521,7 @@ fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { let immobile = m.species() == Species::Ravager && super::ravager::immobile(m) || super::villager::sleeping(m); if m.alive() && !immobile { - server_ai_step(m, w, events); + server_ai_step(m, w, level_random, events); } else { m.ai.jumping = false; m.ai.xxa = 0.0; @@ -576,7 +584,12 @@ fn sun_burn_tick(m: &mut Mob, w: &MobWorld) -> bool { br > 0.5 && m.random.next_float() * 30.0 < (br - 0.4) * 2.0 && !wet && w.can_see_sky(x, y, z) } /// Mob.serverAiStep -fn server_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { +fn server_ai_step( + m: &mut Mob, + w: &MobWorld, + level_random: &mut LegacyRandom, + events: &mut Vec, +) { m.ai.no_action_time += 1; // A creaking looked at stands still. if super::creaking::is_creaking(m) && !super::creaking::can_move(m) { @@ -605,6 +618,11 @@ fn server_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.ai.targets = targets; m.ai.goals = goals; m.nav_tick(w); + // Sniffer and HappyGhast.customServerAiStep: the brain (a happy ghast's + // only while it is a ghastling), then updateActivity. + if m.species() == Species::Sniffer || m.species() == Species::HappyGhast && m.is_baby() { + super::animal_brain::tick(m, w, level_random, events); + } { let mut cx = Cx { w, events }; custom_server_ai_step(m, &mut cx); 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 ca1b2f299..782c5d698 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java @@ -14,6 +14,7 @@ import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Set; import java.util.UUID; import java.util.function.BooleanSupplier; import net.minecraft.SharedConstants; @@ -65,7 +66,10 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.AgeableMob; import net.minecraft.world.entity.ai.Brain; +import net.minecraft.world.entity.ai.behavior.BehaviorControl; import net.minecraft.world.entity.ai.behavior.BlockPosTracker; +import net.minecraft.world.entity.ai.behavior.GateBehavior; +import net.minecraft.world.entity.ai.behavior.ShufflingList; import net.minecraft.world.entity.ai.behavior.EntityTracker; import net.minecraft.world.entity.ai.control.LookControl; import net.minecraft.world.entity.ai.control.MoveControl; @@ -428,6 +432,8 @@ public final class VanillaMobAiOracle { player.snapTo(s.originX + 5000, -60, s.originZ, 0.0F, 0.0F); } List mobs = new ArrayList<>(); + List> brains = new ArrayList<>(); + List seeds = new ArrayList<>(); int id = 100000; for (MobSpec spec : s.mobs) { EntityType type = BuiltInRegistries.ENTITY_TYPE.getValue(net.minecraft.resources.Identifier.parse(spec.type)); @@ -452,7 +458,10 @@ public final class VanillaMobAiOracle { @SuppressWarnings("unchecked") Map> sensors = (Map>) get(brain, "sensors"); for (Sensor sensor : sensors.values()) sensor.randomlyDelayStart(mob.getRandom()); + seedGates(brain, spec.seed); mobs.add(mob); + brains.add(brain); + seeds.add(spec.seed); } level.getRandom().setSeed(s.levelSeed); SOUNDS.clear(); @@ -474,6 +483,13 @@ public final class VanillaMobAiOracle { TracingRandom.tick = t; TracingRandom.on = tracing(s) && t >= traceFrom() && t <= traceTo(); SOUNDS.clear(); + for (int i = 0; i < mobs.size(); i++) { + // Villager.refreshBrain builds a new brain with new gates: seed those too. + if (mobs.get(i).getBrain() != brains.get(i)) { + brains.set(i, mobs.get(i).getBrain()); + seedGates(brains.get(i), seeds.get(i)); + } + } for (Mob mob : mobs) { if (mob.isRemoved()) continue; mob.checkDespawn(); @@ -491,6 +507,26 @@ public final class VanillaMobAiOracle { out.flush(); } + /** + * Every GateBehavior (RunOne and the gates of TradeWithVillager and VillagerMakeLove) shuffles + * its behaviours with its own ShufflingList random, which RandomSource.create() seeds from the + * clock: give each a LegacyRandomSource seeded with the mob's seed so runs are reproducible. + */ + static void seedGates(Brain brain, long seed) throws Exception { + @SuppressWarnings("unchecked") + Map>>> byPriority = (Map>>>) get(brain, "availableBehaviorsByPriority"); + for (Map>> byActivity : byPriority.values()) + for (Set> behaviors : byActivity.values()) + for (BehaviorControl behavior : behaviors) seedGate(behavior, seed); + } + + static void seedGate(Object behavior, long seed) throws Exception { + if (!(behavior instanceof GateBehavior)) return; + ShufflingList list = (ShufflingList) field(GateBehavior.class, "behaviors").get(behavior); + field(ShufflingList.class, "random").set(list, new net.minecraft.world.level.levelgen.LegacyRandomSource(seed)); + for (Object child : list) seedGate(child, seed); + } + static String who(Entity e) { if (e == null) return "none"; if (e instanceof ServerPlayer) return "player"; From 09a0a0e261496e34aed3b0b89af313e1489e9693 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 16:51:36 +0200 Subject: [PATCH 6/8] Match vanilla happy ghasts and ghastlings The adult's careful GhastMoveControl (the blocks around the destination and swept on the way, #happy_ghast_avoids, fluids), HappyGhastLookControl, HappyGhastFloatGoal, the still timeout of a player standing on top, and getSuitableFlyToPosition returning its first good point. The ghastling flies by its brain with getWalkTargetValue's preference for air just above the ground. Flying travel drags by 0.91F and 0.8F as floats, and a happy ghast swims as fast as it flies. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/mobs/ai.rs | 15 + crates/horizon-client/src/mobs/control.rs | 6 + crates/horizon-client/src/mobs/happy_ghast.rs | 310 ++++++++++++++---- crates/horizon-client/src/mobs/living.rs | 35 +- 4 files changed, 295 insertions(+), 71 deletions(-) diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index d1415d73e..b174d3f1a 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -591,6 +591,10 @@ fn server_ai_step( events: &mut Vec, ) { m.ai.no_action_time += 1; + // A happy ghast set up for its age (ageBoundaryReached runs at once). + if m.species() == Species::HappyGhast { + super::happy_ghast::ensure_setup(m); + } // A creaking looked at stands still. if super::creaking::is_creaking(m) && !super::creaking::can_move(m) { return; @@ -800,6 +804,17 @@ pub fn walk_target_value(m: &Mob, w: &MobWorld, p: [i32; 3]) -> f32 { if family(m.species()) == Family::Guardian && w.fluid(p[0], p[1], p[2]) == Fluid::Water { return 10.0 + light(); } + // HappyGhast.getWalkTargetValue: open air, best just above the ground. + if m.species() == Species::HappyGhast { + let air = |y: i32| w.facts.is_air(w.world.block(p[0], y, p[2])); + return if !air(p[1]) { + 0.0 + } else if air(p[1] - 1) && !air(p[1] - 2) { + 10.0 + } else { + 5.0 + }; + } // AbstractNautilus.getWalkTargetValue: everywhere alike. if matches!(m.species(), Species::Nautilus | Species::ZombieNautilus) { return 0.0; diff --git a/crates/horizon-client/src/mobs/control.rs b/crates/horizon-client/src/mobs/control.rs index 361b1b13a..08f77a30f 100644 --- a/crates/horizon-client/src/mobs/control.rs +++ b/crates/horizon-client/src/mobs/control.rs @@ -88,6 +88,8 @@ pub enum LookKind { SmoothSwimming(f32), /// Look controls that never reset pitch (e.g. ghasts keep their own). Fixed, + /// `HappyGhast.HappyGhastLookControl`. + HappyGhast, } #[derive(Clone, Debug, Default)] pub struct LookControl { @@ -307,8 +309,12 @@ impl Mob { /// LookControl.tick (and SmoothSwimmingLookControl). pub fn look_control_tick(&mut self) { let look = self.ai.look.clone(); + if look.kind == LookKind::HappyGhast { + return super::happy_ghast::look_control(self); + } let (x_d, y_d) = self.look_angles(look.wanted); match look.kind { + LookKind::HappyGhast => {} LookKind::SmoothSwimming(max) => { if look.cooldown > 0 { self.ai.look.cooldown -= 1; diff --git a/crates/horizon-client/src/mobs/happy_ghast.rs b/crates/horizon-client/src/mobs/happy_ghast.rs index 56d5946f5..963915902 100644 --- a/crates/horizon-client/src/mobs/happy_ghast.rs +++ b/crates/horizon-client/src/mobs/happy_ghast.rs @@ -5,7 +5,7 @@ use super::{ Mob, MobEvent, MobWorld, anim::{Poses, State}, - control::{MoveKind, Operation}, + control::{LookKind, MoveKind, Operation}, goals::{Cx, Float, Goal, LOOK, MOVE, goal_clone}, nav::NavKind, }; @@ -35,6 +35,7 @@ fn setup(m: &mut Mob, baby: bool) { m.ai.nav.stop(); m.ai.mov.operation = Operation::Wait; if baby { + m.ai.look.kind = LookKind::Default; m.ai.mov.kind = MoveKind::Flying { max_turn: 180.0, hovers: true, @@ -50,8 +51,9 @@ fn setup(m: &mut Mob, baby: bool) { } m.ai.mov.kind = MoveKind::Custom; m.ai.nav.kind = NavKind::Ground; + m.ai.look.kind = LookKind::HappyGhast; let g = &mut m.ai.goals; - g.add(3, Float); + g.add(3, HappyGhastFloat); g.add(4, GhastTempt::default()); g.add(5, FloatAround { blocks: 16 }); } @@ -81,58 +83,233 @@ fn within_home(m: &Mob, p: Vec3) -> bool { ); dx * dx + dy * dy + dz * dz < r * r } -/// `Ghast.GhastMoveControl` with the careful block checks: a push toward -/// the wanted point every few ticks while the way is clear. +/// `isOnStillTimeout`: a player standing on it (or just off it) holds it +/// still (`serverStillTimeout`, kept in `counter`). +pub fn on_still_timeout(m: &Mob) -> bool { + !m.is_baby() && m.extra.counter > 0 +} +/// `Mob.stopInPlace`. +fn stop_in_place(m: &mut Mob) { + m.ai.nav.stop(); + m.ai.xxa = 0.0; + m.ai.yya = 0.0; + m.ai.zza = 0.0; + m.ai.speed = 0.0; + m.velocity = Vec3::ZERO; +} +/// `Ghast.GhastMoveControl(careful)`: held still on a still timeout, else +/// a push toward the wanted point every 2 to 6 ticks while the way there +/// is clear. pub fn move_control(m: &mut Mob, w: &MobWorld) { + if on_still_timeout(m) { + m.ai.mov.operation = Operation::Wait; + stop_in_place(m); + } if m.ai.mov.operation != Operation::MoveTo { return; } + // floatDuration-- <= 0 + let duration = m.extra.counter2; m.extra.counter2 -= 1; - if m.extra.counter2 > 0 { + if duration > 0 { return; } m.extra.counter2 += m.random.next_int_bound(5).unwrap_or(0) + 2; let [wx, wy, wz] = m.ai.mov.wanted; let travel = Vec3::new(wx - m.position.x, wy - m.position.y, wz - m.position.z); - let len = travel.length(); - if len < 1.0e-6 { - return; - } - let b = m.bounds(); - let steps = len.ceil() as i32; - let clear = (1..=steps).all(|i| { - let f = f64::from(i) / f64::from(steps); - let d = Vec3::new(travel.x * f, travel.y * f, travel.z * f); - let at = Aabb::new( - b.min_position().add_vector(d), - b.max_position().add_vector(d), - ); - w.no_collision(at) && !touches_fluid(w, at) - }); - if clear { - let speed = AIR_SPEED; - m.velocity = m.velocity.add_vector(Vec3::new( - travel.x / len * f64::from(speed), - travel.y / len * f64::from(speed), - travel.z / len * f64::from(speed), - )); + if can_reach(m, w, travel) { + // travel.normalize().scale(FLYING_SPEED * 5 / 3) + let len = (travel.x * travel.x + travel.y * travel.y + travel.z * travel.z).sqrt(); + let unit = if len < f64::from(1.0e-5_f32) { + Vec3::ZERO + } else { + Vec3::new(travel.x / len, travel.y / len, travel.z / len) + }; + let speed = FLYING_SPEED * 5.0 / 3.0; + m.velocity = + m.velocity + .add_vector(Vec3::new(unit.x * speed, unit.y * speed, unit.z * speed)); } else { m.ai.mov.operation = Operation::Wait; } } -/// A careful ghast does not float into water or lava. -fn touches_fluid(w: &MobWorld, b: Aabb) -> bool { - let (lo, hi) = (b.min_position(), b.max_position()); +/// `EntityDimensions.makeBoundingBox` at another position. +fn bounds_at(m: &Mob, p: Vec3) -> Aabb { + let half = f64::from(m.width()) / 2.0; + let h = f64::from(m.height()); + Aabb::new( + Vec3::new(p.x - half, p.y, p.z - half), + Vec3::new(p.x + half, p.y + h, p.z + half), + ) +} +/// `GhastMoveControl.canReach`: every block around the destination box can +/// be crossed, and so can every block the box sweeps through on the way. +fn can_reach(m: &Mob, w: &MobWorld, travel: Vec3) -> bool { + let aabb = m.bounds(); + let dest = aabb.move_by(travel); + let around = dest.inflate(Vec3::new(1.0, 1.0, 1.0)); + let (lo, hi) = (around.min_position(), around.max_position()); for x in lo.x.floor() as i32..=hi.x.floor() as i32 { for y in lo.y.floor() as i32..=hi.y.floor() as i32 { for z in lo.z.floor() as i32..=hi.z.floor() as i32 { - if w.fluid(x, y, z) != crate::blocks::Fluid::None { - return true; + if !traversal_possible(m, w, None, [x, y, z], false, false) { + return false; } } } } - false + let (water, lava) = (m.fluids.in_water, m.fluids.in_lava); + let start = m.position; + let end = start.add_vector(travel); + horizon_core::geometry::sweep_intersected_blocks(start, end, dest, 1 << 22, |p, _| { + let at = [p.x, p.y, p.z]; + let unit = Aabb::new( + Vec3::new(f64::from(at[0]), f64::from(at[1]), f64::from(at[2])), + Vec3::new( + f64::from(at[0]) + 1.0, + f64::from(at[1]) + 1.0, + f64::from(at[2]) + 1.0, + ), + ); + aabb.intersects(unit) || traversal_possible(m, w, Some((start, end)), at, water, lava) + }) + .unwrap_or(false) +} +/// `GhastMoveControl.blockTraversalPossible` for a careful ghast: air, or no +/// collision (along the way when `along` is given), never a +/// `#happy_ghast_avoids` block, and a fluid only where the ghast already is. +fn traversal_possible( + m: &Mob, + w: &MobWorld, + along: Option<(Vec3, Vec3)>, + p: [i32; 3], + through_water: bool, + through_lava: bool, +) -> bool { + let state = w.world.block(p[0], p[1], p[2]); + if w.facts.is_air(state) { + return true; + } + let boxes = w.block_collision_boxes(p[0], p[1], p[2]); + let no_collisions = match along { + Some((from, to)) => !bounds_at(m, from).collided_along_vector(to.subtract(from), &boxes), + None => boxes.is_empty(), + }; + if w.has_tag( + "minecraft:happy_ghast_avoids", + w.block_name(p[0], p[1], p[2]), + ) { + return false; + } + let (fluid, height) = w.fluid_height(p[0], p[1], p[2]); + if fluid != crate::blocks::Fluid::None { + let collided = match along { + None => true, + // collidedWithFluid: the fluid's own height. + Some((from, to)) => { + let fluid_box = Aabb::new( + Vec3::new(f64::from(p[0]), f64::from(p[1]), f64::from(p[2])), + Vec3::new( + f64::from(p[0]) + 1.0, + f64::from(p[1]) + height, + f64::from(p[2]) + 1.0, + ), + ); + bounds_at(m, from).collided_along_vector(to.subtract(from), &[fluid_box]) + } + }; + if collided { + return match fluid { + crate::blocks::Fluid::Water => through_water, + _ => through_lava, + }; + } + } + no_collisions +} +/// `HappyGhast.HappyGhastLookControl`: square to the world on a still +/// timeout, face what it looks at, else face its motion +/// (`Ghast.faceMovementDirection`). +pub fn look_control(m: &mut Mob) { + use horizon_core::geometry::trig; + let to_deg = 180.0_f32 / std::f32::consts::PI; + if on_still_timeout(m) { + // Mth.wrapDegrees90 + let mut close = m.yaw % 90.0; + if close >= 45.0 { + close -= 90.0; + } + if close < -45.0 { + close += 90.0; + } + m.yaw -= close; + m.head_yaw = m.yaw; + } else if m.ai.look.cooldown > 0 { + m.ai.look.cooldown -= 1; + let [wx, _, wz] = m.ai.look.wanted; + m.yaw = -(trig::atan2(wx - m.position.x, wz - m.position.z) as f32) * to_deg; + m.body_yaw = m.yaw; + m.head_yaw = m.body_yaw; + } else if m.ai.target.is_none() { + let v = m.velocity; + m.yaw = -(trig::atan2(v.x, v.z) as f32) * to_deg; + m.body_yaw = m.yaw; + } +} +/// `HappyGhast.tick`'s still timeout: it runs out (after the first three +/// seconds) unless a player stands on top (`scanPlayerAboveGhast`). +pub fn still_tick(m: &mut Mob, w: &MobWorld) { + if m.is_baby() { + m.extra.counter = 0; + return; + } + if m.extra.counter > 0 && m.age > 60 { + m.extra.counter -= 1; + } + if player_above(m, w) { + m.extra.counter = 10; + } +} +/// `scanPlayerAboveGhast`: a player (not one riding a happy ghast) within +/// a block around the top, up to half the ghast's height above it. +pub fn player_above(m: &Mob, w: &MobWorld) -> bool { + let Some(p) = w.player.as_ref().filter(|p| !p.spectator) else { + return false; + }; + if m.rider.is_some() { + return false; + } + let b = m.bounds(); + let (lo, hi) = (b.min_position(), b.max_position()); + let area = Aabb::new( + Vec3::new(lo.x - 1.0, hi.y - f64::from(1.0e-5_f32), lo.z - 1.0), + Vec3::new(hi.x + 1.0, hi.y + (hi.y - lo.y) / 2.0, hi.z + 1.0), + ); + area.contains(p.position) +} +/// `HappyGhastFloatGoal`: a `FloatGoal` off a still timeout. +#[derive(Clone, Debug)] +struct HappyGhastFloat; +impl Goal for HappyGhastFloat { + goal_clone!(); + fn name(&self) -> &'static str { + "HappyGhastFloatGoal" + } + fn flags(&self) -> u8 { + Float.flags() + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + !on_still_timeout(m) && Float.can_use(m, cx) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + Float.can_use(m, cx) + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + Float.tick(m, cx) + } } /// `TemptGoal.ForNonPathfinders`: drift toward a player holding food, or /// food and harnesses for a bare adult. @@ -149,6 +326,9 @@ impl GhastTempt { } impl Goal for GhastTempt { goal_clone!(); + fn name(&self) -> &'static str { + "ForNonPathfinders" + } fn flags(&self) -> u8 { MOVE | LOOK } @@ -225,6 +405,9 @@ impl FloatAround { } impl Goal for FloatAround { goal_clone!(); + fn name(&self) -> &'static str { + "RandomFloatAroundGoal" + } fn flags(&self) -> u8 { MOVE } @@ -240,34 +423,35 @@ impl Goal for FloatAround { fn can_continue(&mut self, _: &mut Mob, _: &mut Cx) -> bool { false } + /// `getSuitableFlyToPosition`: the first of 64 random points within 16 + /// blocks (and home) that is good; failing that, the last point, kept + /// below the motion-blocking surface. fn start(&mut self, m: &mut Mob, cx: &mut Cx) { let c = m.position; - let mut result: Option = None; - for _ in 0..64 { - let r = &mut m.random; - let t = Vec3::new( - c.x + f64::from(r.next_float() * 2.0 - 1.0) * 16.0, - c.y + f64::from(r.next_float() * 2.0 - 1.0) * 16.0, - c.z + f64::from(r.next_float() * 2.0 - 1.0) * 16.0, - ); - result = Some(t); - if within_home(m, t) && self.good(cx.w, t) { - break; - } - result = None; - } - let mut t = result.unwrap_or_else(|| { + let choose = |m: &mut Mob| { let r = &mut m.random; Vec3::new( - c.x + f64::from(r.next_float() * 2.0 - 1.0) * 16.0, - c.y + f64::from(r.next_float() * 2.0 - 1.0) * 16.0, - c.z + f64::from(r.next_float() * 2.0 - 1.0) * 16.0, + c.x + f64::from((r.next_float() * 2.0 - 1.0) * 16.0), + c.y + f64::from((r.next_float() * 2.0 - 1.0) * 16.0), + c.z + f64::from((r.next_float() * 2.0 - 1.0) * 16.0), ) - }); + }; + let mut result: Option = None; + for _ in 0..64 { + let t = choose(m); + result = within_home(m, t).then_some(t); + if let Some(t) = result + && self.good(cx.w, t) + { + m.ai.mov.set_wanted(t.x, t.y, t.z, 1.0); + return; + } + } + let mut t = result.unwrap_or_else(|| choose(m)); let top = cx.w.motion_blocking_height(t.x.floor() as i32, t.z.floor() as i32); if top < t.y.floor() as i32 && top > crate::chunk::MIN_Y { - t.y = c.y - (c.y - t.y).abs(); + t.y = m.position.y - (m.position.y - t.y).abs(); } m.ai.mov.set_wanted(t.x, t.y, t.z, 1.0); } @@ -302,13 +486,17 @@ pub fn ridden(m: &mut Mob) { m.ai.zza = forward * scale; m.ai.mov.operation = Operation::Wait; } -/// `HappyGhast.aiStep`, `tick` and `checkRestriction`: the adult/baby -/// setup at the age boundary, the home, face-the-motion and slow healing. -pub fn ai_step(m: &mut Mob, w: &MobWorld) { +/// The adult or ghastling setup for its age (`ageBoundaryReached`). +pub fn ensure_setup(m: &mut Mob) { let baby = m.is_baby(); if m.extra.scratch[0] != if baby { 1 } else { 2 } { setup(m, baby); } +} +/// `HappyGhast.aiStep`, `tick` and `checkRestriction`: the adult/baby +/// setup at the age boundary, the home, face-the-motion and slow healing. +pub fn ai_step(m: &mut Mob, w: &MobWorld) { + ensure_setup(m); // checkRestriction. if m.extra.leash.is_none() && m.rider.is_none() { let radius = restriction_radius(m); @@ -330,15 +518,6 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld) { m.extra.ints[4] = radius; } } - // LookControl: face where it is going. - if !baby && m.rider.is_none() { - let v = m.velocity; - if m.ai.target.is_none() && v.x * v.x + v.z * v.z > 1.0e-6 { - m.yaw = -(v.x.atan2(v.z) as f32).to_degrees(); - m.body_yaw = m.yaw; - m.head_yaw = m.yaw; - } - } // continuousHeal: a point every 30 seconds, every second in rain. if m.alive() && m.death_time == 0 && m.health < m.attrs.max_health { let (x, y, z) = ( @@ -352,6 +531,7 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld) { m.health = (m.health + 1.0).min(m.attrs.max_health); } } + still_tick(m, w); } /// Sounds: the ghastling has its own. pub fn sounds(m: &Mob) -> [&'static str; 3] { diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 8d294cdcc..1f127838b 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -92,6 +92,22 @@ impl MobWorld<'_> { out.eye_in_water = fluid == Fluid::Water && eye_y < f64::from(ey) + h + 0.111_111_11; out } + /// `BlockState.getCollisionShape(level, pos)` (the empty collision + /// context) as boxes in the world. + pub fn block_collision_boxes(&self, x: i32, y: i32, z: i32) -> Vec { + let mut scene = SceneCollisions { + world: self.world, + binding: self.collision, + }; + let state = self.world.block(x, y, z); + let at = horizon_core::position::BlockPos::new(x, y, z); + let context = horizon_world::collision_context::CollisionContext::empty(false); + let offset = Vec3::new(f64::from(x), f64::from(y), f64::from(z)); + self.collision + .collision_shape_with_context(&mut scene, state, at, &context) + .map(|shape| shape.boxes().iter().map(|b| b.move_by(offset)).collect()) + .unwrap_or_default() + } pub fn no_collision(&self, b: Aabb) -> bool { let mut scene = SceneCollisions { world: self.world, @@ -380,14 +396,21 @@ impl Mob { self.travel_in_air(w, input, events); } } - /// LivingEntity.travelFlying (ghast 0.02, phantom 0.2): no gravity, 0.91 drag. + /// LivingEntity.travelFlying: no gravity, `0.91F` drag in the air, + /// `0.8F` in water and 0.5 in lava. A happy ghast swims as fast as it + /// flies (`HappyGhast.travel`); the others at 0.02. fn travel_flying(&mut self, w: &MobWorld, input: Vec3, events: &mut Vec) { - let (speed, drag) = if self.fluids.in_water { - (0.02, 0.8) - } else if self.fluids.in_lava { - (0.02, 0.5) + let fluid_speed = if self.species() == super::Species::HappyGhast { + self.kind.air_speed } else { - (self.kind.air_speed, 0.91) + 0.02 + }; + let (speed, drag) = if self.fluids.in_water { + (fluid_speed, f64::from(0.8_f32)) + } else if self.fluids.in_lava { + (fluid_speed, 0.5) + } else { + (self.kind.air_speed, f64::from(0.91_f32)) }; self.move_relative(speed, input); self.do_move(w, events); From 8393b8de0f93b510b0f66662e1124a6c1df78b0d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 17:15:34 +0200 Subject: [PATCH 7/8] Match vanilla breeding sniffers and tempted happy ghasts Mobs set each other's brain memories within the tick (the breed target and lockGazeAndWalkToEachOther), the partner rests and forgets at the birth, and an animal in love draws its heart particle randoms. The adult happy ghast's TemptGoal.ForNonPathfinders ticks every other tick and follows creative players. The mob AI scenarios can give the player an item and a mob love, taming, an age or a llama strength. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/mob_ai_probe.rs | 17 +++++++- crates/horizon-client/src/game/creatures.rs | 10 ++++- crates/horizon-client/src/mobs.rs | 39 +++++++++++++++++++ crates/horizon-client/src/mobs/ai.rs | 15 ++++--- .../horizon-client/src/mobs/animal_brain.rs | 20 ++++++++++ crates/horizon-client/src/mobs/happy_ghast.rs | 16 ++++---- .../horizonlab/parity/VanillaMobAiOracle.java | 15 ++++++- tools/test_mob_ai_parity.py | 15 +++++++ 8 files changed, 131 insertions(+), 16 deletions(-) diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 39d3d7437..7d11285be 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -43,6 +43,7 @@ struct Scenario { blocks: Vec>, player: Option<[f64; 3]>, creative: bool, + hand: Option, mobs: Vec, } @@ -79,7 +80,13 @@ fn parse(text: &str) -> Vec { f[2].parse().unwrap(), f[3].parse().unwrap(), ]); - s.creative = f.get(4) == Some(&"creative"); + for x in &f[4..] { + match *x { + "creative" => s.creative = true, + x if x.starts_with("hand=") => s.hand = Some(x[5..].to_owned()), + other => panic!("unknown player option {other}"), + } + } } "mob" => s.mobs.push(MobSpec { kind: f[1].to_owned(), @@ -429,6 +436,10 @@ fn main() -> horizon_client::Result<()> { match flag.as_str() { "persistent" => m.persistent = true, "noai" => m.no_ai = true, + "inlove" => m.extra.in_love = 600, + "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(), other => panic!("unknown mob flag {other}"), } } @@ -453,7 +464,7 @@ fn main() -> horizon_client::Result<()> { creative: s.creative, sneaking: false, look: [0.0, 0.0, 1.0], - main_hand: None, + main_hand: s.hand.as_deref().map(Into::into), off_hand: None, head: None, armor_cover: 0.0, @@ -500,9 +511,11 @@ fn main() -> horizon_client::Result<()> { end: false, world_seed: 0, }; + let from = events.len(); if !mobs[i].tick(&w, &mut scratch, &mut events) { mobs[i].removed = true; } + horizon_client::mobs::apply_brain_events(&mut mobs, &mut events, from); // ServerLevel ticks entities one after another: the ones // after this mob see it as it is now. if let Some(e) = snapshot.iter_mut().find(|e| e.id == mobs[i].id) { diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index cfa159dd4..09f09b2e1 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -445,8 +445,10 @@ impl Game<'_> { { let mut scratch = self.world.random.clone(); let mut keep = Vec::with_capacity(mobs.len()); - for (i, m) in mobs.iter_mut().enumerate() { + for i in 0..mobs.len() { + let from = events.len(); let w = self.mob_world_base(&snapshot); + let m = &mut mobs[i]; if !w .world .loaded(m.position.x.floor() as i32, m.position.z.floor() as i32) @@ -463,6 +465,7 @@ impl Game<'_> { // after this mob see it as it is now. snapshot[i] = seen(m, uuid); snapshot[i].alive &= kept; + horizon_client::mobs::apply_brain_events(&mut mobs, &mut events, from); } let mut flags = keep.into_iter(); mobs.retain(|_| flags.next().unwrap_or(true)); @@ -858,6 +861,11 @@ impl Game<'_> { } }, MobEvent::Breed { parent, partner } => self.breed(parent, partner), + 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); + } + } MobEvent::BreedTarget { mob, partner } => { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { horizon_client::mobs::animal_brain::set_breed_partner(m, partner); diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 5754bfae9..48a578292 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -629,6 +629,12 @@ pub enum MobEvent { mob: u32, partner: u32, }, + /// `BehaviorUtils.lockGazeAndWalkToEachOther`'s other half: the partner + /// looks at this mob and walks to it. + LockGaze { + mob: u32, + partner: u32, + }, /// A sound event id that is not a static string (variant sounds). SoundId(String, [f64; 3], f32, f32), AttackPlayer(f32, [f64; 3]), @@ -886,6 +892,39 @@ pub struct Seen { /// A villager's reputation of the player (`getPlayerReputation`). pub player_rep: i32, } +/// Applies the brain memories a mob's tick set on other mobs (from event +/// index `from` on), at once: vanilla sets them on the other entity during +/// the tick, before the mobs after it tick. +pub fn apply_brain_events(mobs: &mut [Mob], events: &mut Vec, from: usize) { + let mut i = from; + while i < events.len() { + match events[i] { + MobEvent::BreedTarget { mob, partner } => { + if let Some(m) = mobs.iter_mut().find(|m| m.id == mob) { + animal_brain::set_breed_partner(m, partner); + } + events.remove(i); + } + MobEvent::LockGaze { mob, partner } => { + if let Some(m) = mobs.iter_mut().find(|m| m.id == mob) { + animal_brain::lock_gaze(m, partner); + } + events.remove(i); + } + // Animal.finalizeSpawnChildFromBreeding: the partner rests and + // forgets it at once (the game still makes the baby). + 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; + animal_brain::forget_breed_target(m, parent); + } + i += 1; + } + _ => i += 1, + } + } +} /// The player as mobs see it. #[derive(Clone, Debug)] pub struct PlayerView { diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index b174d3f1a..792d61eee 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -552,13 +552,18 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: & if m.extra.in_love > 0 { m.extra.in_love -= 1; if m.extra.in_love % 10 == 0 { + // The heart's speed and getRandomX/Y/Z, drawn even on the server. + let (w, h) = (f64::from(m.width()), f64::from(m.height())); + let r = &mut m.random; + for _ in 0..3 { + let _ = r.next_gaussian(); + } + let x = m.position.x + w * (2.0 * r.next_double() - 1.0); + let y = m.position.y + h * r.next_double() + 0.5; + let z = m.position.z + w * (2.0 * r.next_double() - 1.0); events.push(MobEvent::Particles { kind: "heart", - at: [ - m.position.x, - m.position.y + f64::from(m.height()) + 0.5, - m.position.z, - ], + at: [x, y, z], count: 1, }); } diff --git a/crates/horizon-client/src/mobs/animal_brain.rs b/crates/horizon-client/src/mobs/animal_brain.rs index ad2952891..0c7bd6983 100644 --- a/crates/horizon-client/src/mobs/animal_brain.rs +++ b/crates/horizon-client/src/mobs/animal_brain.rs @@ -369,6 +369,20 @@ pub fn set_breed_partner(m: &mut Mob, partner: u32) { lock_gaze_and_walk(m, who, 1.0, 2); } +/// `AnimalMakeLove.tick` after the birth: the partner forgets this mob. +pub fn forget_breed_target(m: &mut Mob, partner: u32) { + if m.extra.animal_brain.is_some() && mem(m).breed_target.value() == Some(Who::Mob(partner)) { + mem(m).breed_target.clear(); + } +} +/// The partner's half of `lockGazeAndWalkToEachOther`. +pub fn lock_gaze(m: &mut Mob, partner: u32) { + if m.extra.animal_brain.is_none() { + return; + } + lock_gaze_and_walk(m, Who::Mob(partner), 1.0, 2); +} + /// What behaviours read and emit during a brain tick. pub struct Bx<'a, 'w> { pub w: &'a MobWorld<'w>, @@ -1282,6 +1296,12 @@ impl B { return; } lock_gaze_and_walk(m, partner, 1.0, 2); + if let Who::Mob(id) = partner { + cx.events.push(MobEvent::LockGaze { + mob: id, + partner: m.id, + }); + } if let Some(t) = cx.w.target_info(partner) && m.distance_sqr(t.position) < 9.0 && now >= *spawn_at diff --git a/crates/horizon-client/src/mobs/happy_ghast.rs b/crates/horizon-client/src/mobs/happy_ghast.rs index 963915902..b09383d67 100644 --- a/crates/horizon-client/src/mobs/happy_ghast.rs +++ b/crates/horizon-client/src/mobs/happy_ghast.rs @@ -338,22 +338,24 @@ impl Goal for GhastTempt { return false; } let Some(p) = &cx.w.player else { return false }; - // Attributes.TEMPT_RANGE 16. + // getNearestPlayer(TargetingConditions.forNonCombat() + // .ignoreLineOfSight().range(TEMPT_RANGE 16)): creative players too. + let visibility = if p.sneaking { 0.8 } else { 1.0 }; + let range = (16.0_f64 * visibility).max(2.0); p.alive - && !p.creative + && !p.spectator && (Self::wants(m, &p.main_hand) || Self::wants(m, &p.off_hand)) - && m.distance_sqr(p.position) <= 256.0 + && m.distance_sqr(p.position) <= range * range } fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + // stopNavigation: setWait; calmDown = reducedTickDelay(100). m.ai.mov.operation = Operation::Wait; - self.calm_down = 50; - } - fn every_tick(&self) -> bool { - true + self.calm_down = super::goals::reduced(100); } fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { let Some(p) = cx.w.player.clone() else { return }; m.look_at(p.eye); + // stopDistance 7. if m.distance_sqr(p.position) < 49.0 { m.ai.mov.operation = Operation::Wait; } else { 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 782c5d698..d658c1430 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java @@ -155,6 +155,8 @@ public final class VanillaMobAiOracle { List blocks = new ArrayList<>(); double[] player; boolean creative; + /** What the player holds in its main hand (an item id), or null. */ + String hand; List mobs = new ArrayList<>(); long levelSeed = 0; } @@ -185,7 +187,11 @@ public final class VanillaMobAiOracle { case "fill", "block" -> s.blocks.add(f); case "player" -> { s.player = new double[] {Double.parseDouble(f[1]), Double.parseDouble(f[2]), Double.parseDouble(f[3])}; - s.creative = f.length > 4 && f[4].equals("creative"); + for (int i = 4; i < f.length; i++) { + if (f[i].equals("creative")) s.creative = true; + else if (f[i].startsWith("hand=")) s.hand = f[i].substring(5); + else throw new IllegalArgumentException(line); + } } case "mob" -> { MobSpec m = new MobSpec(); @@ -426,6 +432,8 @@ public final class VanillaMobAiOracle { this.getPlayerList().placeNewPlayer(connection, player, cookie); } player.setGameMode(s.creative ? GameType.CREATIVE : GameType.SURVIVAL); + player.setItemInHand(net.minecraft.world.InteractionHand.MAIN_HAND, s.hand == null ? net.minecraft.world.item.ItemStack.EMPTY + : new net.minecraft.world.item.ItemStack(BuiltInRegistries.ITEM.getValue(net.minecraft.resources.Identifier.parse(s.hand)))); player.snapTo(s.player[0], s.player[1], s.player[2], 0.0F, 0.0F); player.setDeltaMovement(Vec3.ZERO); } else if (player != null) { @@ -450,6 +458,11 @@ public final class VanillaMobAiOracle { for (String flag : spec.flags) { if (flag.equals("persistent")) mob.setPersistenceRequired(); else if (flag.equals("noai")) mob.setNoAi(true); + else if (flag.equals("inlove")) ((net.minecraft.world.entity.animal.Animal) mob).setInLoveTime(600); + else if (flag.equals("tame") && mob instanceof net.minecraft.world.entity.animal.equine.AbstractHorse horse) horse.setTamed(true); + 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 throw new IllegalArgumentException(flag); } level.addFreshEntity(mob); diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index 957605492..5c43c123f 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -94,6 +94,21 @@ def scenarios(): add('ghastling_alone', 200, ['mob minecraft:happy_ghast 0.5 -57 0.5 0 84 persistent baby']) add('ghastling_adult', 200, ['mob minecraft:happy_ghast 10.5 -55 0.5 0 85 persistent', 'mob minecraft:happy_ghast 0.5 -57 0.5 0 86 persistent baby']) + # Breeding, temptation and growing up. + add('sniffer_love', 300, ['mob minecraft:sniffer 0.5 -60 0.5 0 91 persistent inlove', + 'mob minecraft:sniffer 4.5 -60 0.5 0 92 persistent inlove']) + add('sniffer_tempted', 200, ['player 7.5 -60 0.5 hand=minecraft:torchflower_seeds', + 'mob minecraft:sniffer 0.5 -60 0.5 0 93 persistent']) + add('llama_love', 300, ['mob minecraft:llama 0.5 -60 0.5 0 94 persistent tame inlove strength=3', + 'mob minecraft:llama 4.5 -60 0.5 0 95 persistent tame inlove strength=2']) + add('llama_tempted', 200, ['player 7.5 -60 0.5 hand=minecraft:hay_block', + 'mob minecraft:llama 0.5 -60 0.5 0 96 persistent']) + add('ghastling_tempted', 200, ['player 8.5 -60 0.5 hand=minecraft:snowball', + 'mob minecraft:happy_ghast 0.5 -57 0.5 0 97 persistent baby']) + add('happy_ghast_tempted', 200, ['player 12.5 -60 0.5 hand=minecraft:snowball', + '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']) return s 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 8/8] 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