From d4144d33b4657d7bb1f62ee26e6bc194856bdc4a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 11 Oct 2026 18:24:38 +0200 Subject: [PATCH 1/7] Match vanilla zombie turtle-egg goal, entity pushing and raider goal order Zombies (and husks, drowned, zombie villagers, zombified piglins) now register ZombieAttackTurtleEggGoal first, as vanilla does, so their goal selector draws the same random numbers. LivingEntity.pushEntities runs in aiStep against the player and other mobs, with pushes to other mobs applied at once as Entity.push does (replacing the post-tick push_apart). Spider target goals check the light before their random interval, LookAtPlayerGoal uses the non-combat targeting conditions, raiders register the PatrollingMonster/Raider goals before their own, and the witch runs its aiStep (heal cooldown, drinking, particle roll) before super.aiStep with NearestHealableRaiderTargetGoal's nextBoolean. The mob AI oracle's player is now a fully loaded, hurtable client: its connection starts with a 60-tick load timer and 26.3 moved the hurt cooldown to damageCooldownTime, both of which only ServerPlayer.tick counts down, so whether mobs could hurt the player depended on the scenario order. The probe reports the player's hurt sound, and an rng-trace feature records the call sites of Horizon's mob random draws next to the oracle's trace. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/Cargo.toml | 4 + .../horizon-client/examples/mob_ai_probe.rs | 55 ++++++- crates/horizon-client/src/game/creatures.rs | 45 +----- crates/horizon-client/src/mobs.rs | 31 ++++ crates/horizon-client/src/mobs/ai.rs | 93 ++++++++++- crates/horizon-client/src/mobs/goals.rs | 42 ++++- crates/horizon-client/src/mobs/hostile.rs | 4 +- crates/horizon-client/src/mobs/illager.rs | 15 +- crates/horizon-client/src/mobs/raider.rs | 12 +- crates/horizon-client/src/mobs/undead.rs | 146 ++++++++++++++++++ crates/horizon-client/src/mobs/witch.rs | 88 ++++++++--- crates/horizon-core/Cargo.toml | 4 + crates/horizon-core/src/random.rs | 48 +++++- .../horizonlab/parity/VanillaMobAiOracle.java | 6 + tools/test_mob_ai_parity.py | 17 +- 15 files changed, 523 insertions(+), 87 deletions(-) diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 3b2335ab5..8f0ad3b98 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -23,5 +23,9 @@ cpal = "0.16" symphonia = { version = "0.5", default-features = false, features = ["ogg", "vorbis"] } miniz_oxide = "0.8" +[features] +# Records the call sites of mob random draws (`mob_ai_probe` traces). +rng-trace = ["horizon-core/rng-trace"] + [lints] workspace = true diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index ab6cce246..f28ee853c 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -221,6 +221,27 @@ fn seen(m: &Mob) -> Seen { hurt_by: m.ai.last_hurt_by.map(|w| (w, m.ai.last_hurt_by_time)), active_raid: horizon_client::mobs::raider::has_active_raid(m), player_rep: 0, + pushable: m.pushable(), + } +} + +/// Whether an event hurts the scenario's player (survival, normal difficulty, +/// no armour, made hurtable again every tick by the oracle). +fn player_hurt(player: Option<&PlayerView>, e: &MobEvent) -> bool { + let Some(p) = player.filter(|p| !p.creative) else { + return false; + }; + match e { + MobEvent::AttackPlayer(amount, _) | MobEvent::DamagePlayer { amount, .. } => *amount > 0.0, + // ServerExplosion.hurtEntities: within twice the radius every hit does damage. + MobEvent::Explode(at, radius) => { + let d = Vec3::new(at[0], at[1], at[2]) + .distance_squared(p.position) + .sqrt(); + let r = 2.0 * f64::from(*radius); + d / r <= 1.0 && d != 0.0 + } + _ => false, } } @@ -487,14 +508,34 @@ fn main() -> horizon_client::Result<()> { world_seed: 0, }; let mut events = Vec::new(); - for m in &mut mobs { + #[allow(unused_mut)] // filled only with the rng-trace feature + let mut traces: Vec = Vec::new(); + let mut pushes = Vec::new(); + for (i, m) in mobs.iter_mut().enumerate() { if m.removed { continue; } - if !m.tick(&w, &mut scratch, &mut events) { + horizon_client::mobs::apply_mob_pushes(m, &mut pushes); + let from = events.len(); + #[cfg(feature = "rng-trace")] + horizon_core::random::trace::set(true); + let alive = m.tick(&w, &mut scratch, &mut events); + #[cfg(feature = "rng-trace")] + { + horizon_core::random::trace::set(false); + for line in horizon_core::random::trace::take() { + traces.push(format!("{t} trace {i} {line}")); + } + } + horizon_client::mobs::take_mob_pushes(&mut events, from, &mut pushes); + let _ = i; + if !alive { m.removed = true; } } + for m in &mut mobs { + horizon_client::mobs::apply_mob_pushes(m, &mut pushes); + } for (i, m) in mobs.iter().enumerate() { print(&mut out, t, i, m); } @@ -508,8 +549,18 @@ fn main() -> horizon_client::Result<()> { ); } else if let MobEvent::SoundId(name, _, volume, pitch) = e { let _ = writeln!(out, "{t} sound {name} {} {}", f(*volume), f(*pitch)); + } else if player_hurt(player.as_ref(), e) { + // The oracle's survival player, healed and made hurtable every tick, + // takes the damage (LivingEntity.playHurtSound). + let _ = writeln!( + out, + "{t} sound minecraft:entity.player.hurt 3f800000 3f800000" + ); } } + for line in traces { + let _ = writeln!(out, "{line}"); + } } } fs::write(&args[2], out)?; diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 0d7e34572..bceb78131 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -127,6 +127,7 @@ fn seen(m: &Mob, player: Option<[i32; 4]>) -> Seen { } _ => 0, }, + pushable: m.pushable(), } } impl Game<'_> { @@ -445,6 +446,7 @@ impl Game<'_> { { let w = self.mob_world_base(&snapshot); let mut scratch = self.world.random.clone(); + let mut pushes = Vec::new(); mobs.retain_mut(|m| { if !w .world @@ -452,13 +454,18 @@ impl Game<'_> { { return !m.hostile() || m.persistent; } + horizon_client::mobs::apply_mob_pushes(m, &mut pushes); + let from = events.len(); let keep = m.tick(&w, &mut scratch, &mut events); + horizon_client::mobs::take_mob_pushes(&mut events, from, &mut pushes); if !keep && !m.alive() && !m.removed { dead.push(m.clone()); } keep }); - push_apart(&mut mobs); + for m in &mut mobs { + horizon_client::mobs::apply_mob_pushes(m, &mut pushes); + } } self.mobs.append(&mut mobs); self.sync_riders(); @@ -2421,42 +2428,6 @@ fn from_loot(stack: &horizon_world::loot::LootStack) -> ItemStack { } item } -/// Entity.push between overlapping mobs (LivingEntity.pushEntities). -fn push_apart(mobs: &mut [Mob]) { - let n = mobs.len(); - for i in 0..n { - if !mobs[i].alive() { - continue; - } - let bi = mobs[i].bounds(); - for j in (i + 1)..n { - if !mobs[j].alive() || !bi.intersects(mobs[j].bounds()) { - continue; - } - // A rider and its vehicle do not push each other. - if mobs[i].extra.mount == Some(mobs[j].id) || mobs[j].extra.mount == Some(mobs[i].id) { - continue; - } - let (dx, dz) = ( - mobs[j].position.x - mobs[i].position.x, - mobs[j].position.z - mobs[i].position.z, - ); - let mut dd = dx.abs().max(dz.abs()); - if dd >= 0.01 { - dd = dd.sqrt(); - let (mut xa, mut za) = (dx / dd, dz / dd); - let inv = (1.0 / dd).min(1.0); - xa *= inv * 0.05; - za *= inv * 0.05; - mobs[i].velocity.x -= xa; - mobs[i].velocity.z -= za; - mobs[j].velocity.x += xa; - mobs[j].velocity.z += za; - } - } - } -} - impl Game<'_> { /// The rest of `NetherPortalBlock.randomTick` after a won roll: with a /// player close enough for spawning, a zombified piglin spawns on the block diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index a80d29b83..fc0d15a0f 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -876,6 +876,37 @@ pub struct Seen { pub active_raid: bool, /// A villager's reputation of the player (`getPlayerReputation`). pub player_rep: i32, + /// `isPushable` and pushed by others (`Entity.push(Entity)` moves it). + pub pushable: bool, +} +/// `Entity.push` on other mobs acts at once in vanilla: a mob ticking later +/// moves with it this tick. Takes the `Push` events aimed at mobs out of +/// `events[from..]` into `pending`, which the caller adds to each mob's +/// velocity before its tick (and to every mob once all have ticked). +pub fn take_mob_pushes(events: &mut Vec, from: usize, pending: &mut Vec<(u32, Vec3)>) { + let mut i = from; + while i < events.len() { + if let MobEvent::Push { + target: Who::Mob(id), + velocity, + } = events[i] + { + pending.push((id, Vec3::new(velocity[0], velocity[1], velocity[2]))); + events.remove(i); + } else { + i += 1; + } + } +} +/// Adds the pending pushes aimed at `m` to its velocity, in push order. +pub fn apply_mob_pushes(m: &mut Mob, pending: &mut Vec<(u32, Vec3)>) { + pending.retain(|(id, v)| { + if *id != m.id { + return true; + } + m.velocity = Vec3::new(m.velocity.x + v.x, m.velocity.y + v.y, m.velocity.z + v.z); + false + }); } /// The player as mobs see it. #[derive(Clone, Debug)] diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index be23ad75b..f001a360a 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -158,6 +158,8 @@ pub fn family(s: Species) -> Family { } } pub fn register(m: &mut Mob) { + // Raider subclasses call super.registerGoals() first. + super::raider::register(m); match family(m.species()) { Family::Farm => farm::register(m), Family::Undead => undead::register(m), @@ -201,7 +203,6 @@ pub fn register(m: &mut Mob) { Family::Creaking => super::creaking::register(m), Family::Nautilus => super::nautilus::register(m), } - super::raider::register(m); } /// Mob.tick additions that run before the entity tick (creeper fuse, puffing). fn pre_tick(m: &mut Mob, events: &mut Vec) { @@ -486,6 +487,13 @@ 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) { + // Witch.aiStep runs before super.aiStep(). + if m.species() == Species::Witch { + let far = m + .target_info(w) + .is_some_and(|t| t.position.distance_squared(m.position) > 121.0); + super::witch::ai_step(m, events, far); + } if super::creaking::is_creaking(m) { super::creaking::update(m, w, events); } @@ -518,6 +526,7 @@ fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { f64::from(m.ai.zza), ); m.travel(w, input, events); + push_entities(m, w, events); // Spider.tick: climbing while pressed against a wall. if m.kind.flags.climber { m.climbing = m.horizontal_collision; @@ -554,6 +563,82 @@ fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } species_ai_step(m, w, events); } +impl Mob { + /// LivingEntity.isPushable (and the push it takes from `Entity.push(Entity)`): + /// bats and shulkers are never moved by others. + pub fn pushable(&self) -> bool { + self.alive() + && !matches!(self.species(), Species::Bat | Species::Shulker) + && !(self.kind.flags.climber && self.climbing) + && !(self.species() == Species::Creaking && !super::creaking::can_move(self)) + } +} +/// LivingEntity.onClimbable for the pusher (Spider.onClimbable: climbing a wall). +fn on_climbable(m: &Mob, w: &MobWorld) -> bool { + if m.kind.flags.climber { + return m.climbing; + } + let (x, y, z) = ( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ); + w.has_tag("minecraft:climbable", w.block_name(x, y, z)) +} +/// LivingEntity.pushEntities: every pushable entity overlapping the box is +/// pushed apart from this one (`doPush(e)` = `e.push(this)`); pushes of other +/// mobs are `Push` events their tick picks up. +fn push_entities(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + if m.species() == Species::Bat { + return; + } + let bounds = m.bounds(); + // The pusher's own isPushable, checked by `e.push(this)` before moving it. + let self_pushable = m.alive() + && m.species() != Species::Shulker + && !on_climbable(m, w) + && !(m.species() == Species::Creaking && !super::creaking::can_move(m)); + let mut targets: Vec<(Who, Vec3)> = Vec::new(); + if let Some(p) = &w.player + && p.alive + && !p.spectator + && p.bounds.intersects(bounds) + { + targets.push((Who::Player, p.position)); + } + for o in w.others { + if o.id != m.id && o.alive && o.pushable && o.bounds.intersects(bounds) { + targets.push((Who::Mob(o.id), o.position)); + } + } + // Cramming (maxEntityCramming 24). + if targets.len() > 23 { + let _ = m.random.next_int_bound(4); + } + for (who, at) in targets { + // Entity.push(Entity) with `this` the other entity. + let (mut xa, mut za) = (m.position.x - at.x, m.position.z - at.z); + let mut dd = xa.abs().max(za.abs()); + if dd < f64::from(0.01_f32) { + continue; + } + dd = dd.sqrt(); + xa /= dd; + za /= dd; + let pow = (1.0 / dd).min(1.0); + xa *= pow; + za *= pow; + xa *= f64::from(0.05_f32); + za *= f64::from(0.05_f32); + events.push(MobEvent::Push { + target: who, + velocity: [-xa, 0.0, -za], + }); + if self_pushable { + m.velocity = Vec3::new(m.velocity.x + xa, m.velocity.y, m.velocity.z + za); + } + } +} fn sun_burn_tick(m: &mut Mob, w: &MobWorld) -> bool { if !w.daylight || w.nether { return false; @@ -632,12 +717,6 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { aquatic::ai_step(m, w, events); } match m.species() { - Species::Witch => { - let far = m - .target_info(w) - .is_some_and(|t| t.position.distance_squared(m.position) > 121.0); - super::witch::ai_step(m, events, far) - } Species::Enderman => super::enderman::ai_step(m, w, events), Species::Wolf => super::tame::ai_step(m, w, events), Species::Cat => super::tame::cat_ai_step(m, events), diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index c5439479b..b1c7ecb26 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -397,9 +397,22 @@ impl Mob { /// creative, within range scaled by visibility, optionally visible. pub fn can_target_player(&mut self, w: &MobWorld, range: f64, check_sight: bool) -> bool { let Some(p) = &w.player else { return false }; - if !p.alive || p.creative { + if p.creative { return false; } + self.player_in_range(w, range, check_sight) + } + /// TargetingConditions.forNonCombat().range(range).test for the player + /// (seen by anyone, within range scaled by visibility, in sight). + pub fn can_see_player(&mut self, w: &MobWorld, range: f64) -> bool { + self.player_in_range(w, range, true) + } + fn player_in_range(&mut self, w: &MobWorld, range: f64, check_sight: bool) -> bool { + let Some(p) = &w.player else { return false }; + if !p.alive || p.spectator { + return false; + } + // LivingEntity.getVisibilityPercent let mut visibility = 1.0; if p.sneaking { visibility *= 0.8; @@ -660,8 +673,8 @@ impl Goal for LookAtPlayer { if m.random.next_float() >= self.probability { return false; } - let Some(p) = &cx.w.player else { return false }; - p.alive && m.distance_sqr(p.position) <= f64::from(self.range * self.range) + // level.getNearestPlayer(forNonCombat().range(lookDistance)). + m.can_see_player(cx.w, f64::from(self.range)) } fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { let Some(p) = &cx.w.player else { return false }; @@ -918,8 +931,11 @@ pub struct NearestTarget { pub must_see: bool, pub must_reach: bool, pub interval: i32, - /// Extra condition on the attacker (e.g. spiders only at night). + /// Extra condition on the attacker, checked after the random interval. pub when: Option bool>, + /// A condition checked before anything else, by subclasses overriding + /// `canUse` (SpiderTargetGoal: only in the dark). + pub gate: Option bool>, found: Option, target_goal: TargetState, } @@ -947,6 +963,7 @@ impl NearestTarget { must_reach: false, interval: reduced(10), when: None, + gate: None, found: None, target_goal: TargetState { unseen_memory: 60, @@ -977,6 +994,10 @@ impl NearestTarget { self.when = Some(f); self } + pub fn gate(mut self, f: fn(&Mob, &MobWorld) -> bool) -> Self { + self.gate = Some(f); + self + } } /// TargetGoal.canContinueToUse pub fn target_continue(st: &mut TargetState, must_see: bool, m: &mut Mob, cx: &mut Cx) -> bool { @@ -1009,6 +1030,11 @@ impl Goal for NearestTarget { TARGET } fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if let Some(f) = self.gate + && !f(m, cx.w) + { + return false; + } if self.interval > 0 && m.random.next_int_bound(self.interval).unwrap_or(1) != 0 { return false; } @@ -1828,7 +1854,7 @@ impl MoveToBlock { self.find_nearest(m, w, valid) } /// `MoveToBlockGoal.findNearestBlock`: rings outward, alternating heights. - fn find_nearest( + pub fn find_nearest( &mut self, m: &Mob, w: &MobWorld, @@ -1881,6 +1907,10 @@ impl MoveToBlock { } /// `MoveToBlockGoal.tick` (accepted distance 1 from the block above). pub fn tick(&mut self, m: &mut Mob, w: &MobWorld) { + self.tick_within(m, w, 1.0); + } + /// `MoveToBlockGoal.tick` with the goal's `acceptedDistance`. + pub fn tick_within(&mut self, m: &mut Mob, w: &MobWorld, accepted: f64) { let t = [ f64::from(self.block[0]) + 0.5, f64::from(self.block[1] + 1) + 0.5, @@ -1889,7 +1919,7 @@ impl MoveToBlock { let d2 = (m.position.x - t[0]).powi(2) + (m.position.y - t[1]).powi(2) + (m.position.z - t[2]).powi(2); - if d2 >= 1.0 { + if d2 >= accepted * accepted { self.reached = false; self.try_ticks += 1; if self.try_ticks % 40 == 0 { diff --git a/crates/horizon-client/src/mobs/hostile.rs b/crates/horizon-client/src/mobs/hostile.rs index 18f5d7333..403eaa3c7 100644 --- a/crates/horizon-client/src/mobs/hostile.rs +++ b/crates/horizon-client/src/mobs/hostile.rs @@ -47,10 +47,10 @@ pub fn register(m: &mut Mob) { g.add(6, RandomLookAround::default()); m.ai.targets.add(1, HurtByTarget::new()); m.ai.targets - .add(2, NearestTarget::player(true).when(dark_enough)); + .add(2, NearestTarget::player(true).gate(dark_enough)); m.ai.targets.add( 3, - NearestTarget::species(&[S::IronGolem], true).when(dark_enough), + NearestTarget::species(&[S::IronGolem], true).gate(dark_enough), ); m.ai.nav.kind = super::nav::NavKind::WallClimber; } diff --git a/crates/horizon-client/src/mobs/illager.rs b/crates/horizon-client/src/mobs/illager.rs index 761230398..f2879887c 100644 --- a/crates/horizon-client/src/mobs/illager.rs +++ b/crates/horizon-client/src/mobs/illager.rs @@ -48,17 +48,30 @@ fn targets(m: &mut Mob, villagers_seen: bool) { m.ai.targets .add(3, NearestTarget::species(&[Species::IronGolem], true)); } +/// `AvoidEntityGoal<>(this, Creaking.class, 8.0F, walk, sprint)`. +fn avoid_creaking(walk: f64, sprint: f64) -> super::goals::AvoidEntity { + super::goals::AvoidEntity::new( + super::goals::Avoid::Species(vec![Species::Creaking]), + 8.0, + walk, + sprint, + ) +} pub fn register_pillager(m: &mut Mob) { let g = &mut m.ai.goals; g.add(0, Float); + g.add(1, avoid_creaking(1.0, 1.2)); + g.add(2, super::raider::HoldGroundAttack::new(10.0)); g.add(3, CrossbowAttack::new(1.0, 8.0)); g.add(8, Stroll::new(0.6)); - g.add(9, LookAtPlayer::new(15.0)); + g.add(9, LookAtPlayer::new(15.0).probability(1.0)); targets(m, false); } pub fn register_vindicator(m: &mut Mob) { let g = &mut m.ai.goals; g.add(0, Float); + g.add(1, avoid_creaking(1.0, 1.2)); + g.add(4, super::raider::HoldGroundAttack::new(10.0)); g.add(5, MeleeAttack::new(1.0, false)); g.add(8, Stroll::new(0.6)); g.add(9, LookAtPlayer::new(3.0)); diff --git a/crates/horizon-client/src/mobs/raider.rs b/crates/horizon-client/src/mobs/raider.rs index e75464fc4..64f268bc0 100644 --- a/crates/horizon-client/src/mobs/raider.rs +++ b/crates/horizon-client/src/mobs/raider.rs @@ -80,24 +80,18 @@ pub fn is_captain(m: &Mob) -> bool { m.extra.head.as_deref() == Some(BANNER) && state(m).is_some_and(|s| s.patrol_leader) } +/// `PatrollingMonster.registerGoals` then `Raider.registerGoals`: the goals +/// every raider registers before its own. pub fn register(m: &mut Mob) { if !is_raider(m.species()) { return; } m.extra.raider = Some(Box::default()); - let species = m.species(); + m.ai.goals.add(4, LongDistancePatrol::new(0.7, 0.595)); m.ai.goals.add(1, ObtainBanner); m.ai.goals.add(3, PathfindToRaid); m.ai.goals.add(4, MoveThroughVillage::new(1.05, 1.0)); m.ai.goals.add(5, Celebration); - m.ai.goals.add(4, LongDistancePatrol::new(0.7, 0.595)); - // The illagers hold their ground in a patrol (Witch and Ravager do not). - if matches!(species, Species::Pillager | Species::Vindicator) { - m.ai.goals.add( - if species == Species::Pillager { 2 } else { 4 }, - HoldGroundAttack::new(10.0), - ); - } } /// `Raid.getOminousBannerInstance`. diff --git a/crates/horizon-client/src/mobs/undead.rs b/crates/horizon-client/src/mobs/undead.rs index c126ebb12..4d2886a00 100644 --- a/crates/horizon-client/src/mobs/undead.rs +++ b/crates/horizon-client/src/mobs/undead.rs @@ -15,6 +15,7 @@ pub fn register(m: &mut Mob) { match m.species() { S::Zombie | S::Husk | S::ZombieVillager => { let g = &mut m.ai.goals; + g.add(4, AttackTurtleEgg::default()); g.add(8, LookAtPlayer::new(8.0)); g.add(8, RandomLookAround::default()); g.add(3, MeleeAttack::new(1.0, false).zombie()); @@ -476,3 +477,148 @@ impl Goal for DrownedGoToWater { m.nav_move_to(cx.w, self.wanted, 1.0); } } + +/// `Zombie.ZombieAttackTurtleEggGoal` (a `RemoveBlockGoal` on turtle eggs): +/// walk to a turtle egg within 24 blocks and trample it. +#[derive(Clone, Debug)] +pub struct AttackTurtleEgg { + base: super::goals::MoveToBlock, + since_reached: i32, +} +impl Default for AttackTurtleEgg { + fn default() -> Self { + Self { + base: super::goals::MoveToBlock::new(1.0, 24, 3), + since_reached: 0, + } + } +} +/// RemoveBlockGoal.isValidTarget: the block with two air blocks above, in a loaded chunk. +fn turtle_egg_target(w: &super::MobWorld, p: [i32; 3]) -> bool { + w.world.loaded(p[0], p[2]) + && w.block_name(p[0], p[1], p[2]) == "minecraft:turtle_egg" + && w.facts.is_air(w.world.block(p[0], p[1] + 1, p[2])) + && w.facts.is_air(w.world.block(p[0], p[1] + 2, p[2])) +} +impl Goal for AttackTurtleEgg { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | super::goals::JUMP + } + fn every_tick(&self) -> bool { + true + } + /// RemoveBlockGoal.canUse + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if !cx.w.mob_griefing { + return false; + } + if self.base.next_start > 0 { + self.base.next_start -= 1; + return false; + } + if self.base.find_nearest(m, cx.w, turtle_egg_target) { + self.base.next_start = super::goals::reduced(20); + return true; + } + // MoveToBlockGoal.nextStartTick + self.base.next_start = + super::goals::reduced(200 + m.random.next_int_bound(200).unwrap_or(0)); + false + } + fn can_continue(&mut self, _m: &mut Mob, cx: &mut Cx) -> bool { + self.base.can_continue(cx.w, turtle_egg_target) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.base.start(m, cx.w); + self.since_reached = 0; + } + fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) { + m.fall_distance = 1.0; + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + self.base.tick_within(m, cx.w, 1.14); + let at = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + let egg = |p: [i32; 3]| cx.w.block_name(p[0], p[1], p[2]) == "minecraft:turtle_egg"; + let eat = [ + at, + [at[0], at[1] - 1, at[2]], + [at[0] - 1, at[1], at[2]], + [at[0] + 1, at[1], at[2]], + [at[0], at[1], at[2] - 1], + [at[0], at[1], at[2] + 1], + [at[0], at[1] - 2, at[2]], + ] + .into_iter() + .find(|p| egg(*p)); + let Some(eat) = eat.filter(|_| self.base.reached) else { + return; + }; + let center = [ + f64::from(eat[0]) + 0.5, + f64::from(eat[1]) + 0.7, + f64::from(eat[2]) + 0.5, + ]; + if self.since_reached > 0 { + m.velocity.y = 0.3; + // The egg crumb particles' spread. + for _ in 0..3 { + m.random.next_float(); + } + cx.events.push(MobEvent::Particles { + kind: "item_egg", + at: center, + count: 3, + }); + } + if self.since_reached % 2 == 0 { + m.velocity.y = -0.3; + if self.since_reached % 6 == 0 { + let pitch = 0.9 + m.random.next_float() * 0.2; + let b = self.base.block; + cx.events.push(MobEvent::Sound( + "entity.zombie.destroy_egg", + [ + f64::from(b[0]) + 0.5, + f64::from(b[1]) + 0.5, + f64::from(b[2]) + 0.5, + ], + 0.5, + pitch, + )); + } + } + if self.since_reached > 60 { + cx.events.push(MobEvent::BreakBlock { + pos: eat, + drop: false, + }); + for _ in 0..20 { + m.random.next_gaussian(); + m.random.next_gaussian(); + m.random.next_gaussian(); + } + cx.events.push(MobEvent::Particles { + kind: "poof", + at: [center[0], f64::from(eat[1]), center[2]], + count: 20, + }); + // The break sound's pitch draws from the level random. + cx.events.push(MobEvent::Sound( + "block.turtle_egg.break", + [ + f64::from(eat[0]) + 0.5, + f64::from(eat[1]) + 0.5, + f64::from(eat[2]) + 0.5, + ], + 0.7, + 1.0, + )); + } + self.since_reached += 1; + } +} diff --git a/crates/horizon-client/src/mobs/witch.rs b/crates/horizon-client/src/mobs/witch.rs index 32fea42c4..0995d64e6 100644 --- a/crates/horizon-client/src/mobs/witch.rs +++ b/crates/horizon-client/src/mobs/witch.rs @@ -20,20 +20,56 @@ pub fn register(m: &mut Mob) { g.add(3, LookAtPlayer::new(8.0)); g.add(3, RandomLookAround::default()); m.ai.targets.add(1, HurtByTarget::new()); - // NearestHealableRaiderTargetGoal: in a raid, go and heal the other raiders. + m.ai.targets.add(2, HealRaiders::default()); + // NearestAttackableWitchTargetGoal: only while not healing raiders. m.ai.targets.add( - 2, - NearestTarget::new( - super::goals::Prey::Filter(|s| { - super::raider::is_raider(s.species) && s.species != Species::Witch - }), - true, - ) - .interval(1) - .when(|m, _| super::raider::has_active_raid(m)), + 3, + NearestTarget::player(true) + .interval(10) + .gate(|m, _| m.extra.counter2 <= 0), ); - m.ai.targets - .add(3, NearestTarget::player(true).interval(10)); +} +/// `NearestHealableRaiderTargetGoal`: in a raid, target another raider to +/// heal, then wait 10 seconds (the cooldown lives in `extra.counter2`). +#[derive(Clone, Debug)] +struct HealRaiders(NearestTarget); +impl Default for HealRaiders { + fn default() -> Self { + Self( + NearestTarget::new( + super::goals::Prey::Filter(|s| { + super::raider::is_raider(s.species) && s.species != Species::Witch + }), + true, + ) + .interval(0), + ) + } +} +impl Goal for HealRaiders { + goal_clone!(); + fn flags(&self) -> u8 { + self.0.flags() + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if m.extra.counter2 > 0 || !m.random.next_boolean() { + return false; + } + if !super::raider::has_active_raid(m) { + return false; + } + 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) { + m.extra.counter2 = super::goals::reduced(200); + self.0.start(m, cx); + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.stop(m, cx); + } } /// The callback a ranged mob uses to fire (`RangedAttackMob.performRangedAttack`). pub type Fire = fn(&mut Mob, Who, f32, &mut Cx); @@ -123,15 +159,20 @@ impl Goal for RangedAttack { /// Witch.performRangedAttack: harming by default, slowness at range, poison /// on healthy targets, weakness up close. fn witch_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) { - if m.extra.using_item > 0 { + // isDrinkingPotion + if m.extra.flag { return; } let Some(t) = cx.w.target_info(who) else { return; }; - let xd = t.position.x - m.position.x; - let yd = t.eye_y - 1.1 - m.position.y; - let zd = t.position.z - m.position.z; + let motion = match who { + Who::Player => cx.w.player.as_ref().map_or(Vec3::ZERO, |p| p.velocity), + Who::Mob(id) => cx.w.seen(id).map_or(Vec3::ZERO, |s| s.velocity), + }; + let xd = t.position.x + motion.x - m.position.x; + let yd = t.eye_y - f64::from(1.1_f32) - m.position.y; + let zd = t.position.z + motion.z - m.position.z; let dist = (xd * xd + zd * zd).sqrt(); let health = if t.is_player { 20.0 @@ -194,14 +235,23 @@ fn witch_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) { pitch, )); } -/// Witch.aiStep: drink water breathing, fire resistance, healing or swiftness. +/// Witch.aiStep before `super.aiStep()`: the healing cooldown, then drink +/// water breathing, fire resistance, healing or swiftness. pub fn ai_step(m: &mut Mob, cx_events: &mut Vec, target_far: bool) { if !m.alive() { return; } - if m.extra.using_item > 0 { + // healRaidersGoal.decrementCooldown (the attack goal's canAttack reads it). + m.extra.counter2 -= 1; + drink(m, cx_events, target_far); + // The angry-witch particles (entity event 15). + let _ = m.random.next_float(); +} +fn drink(m: &mut Mob, cx_events: &mut Vec, target_far: bool) { + if m.extra.flag { + // `usingTime-- <= 0` m.extra.using_item -= 1; - if m.extra.using_item <= 0 { + if m.extra.using_item < 0 { m.extra.using_item = 0; if let Some(potion) = m.extra.main_hand.take() { match potion.as_ref() { diff --git a/crates/horizon-core/Cargo.toml b/crates/horizon-core/Cargo.toml index 8925532b1..655472a35 100644 --- a/crates/horizon-core/Cargo.toml +++ b/crates/horizon-core/Cargo.toml @@ -6,6 +6,10 @@ license.workspace = true rust-version.workspace = true description = "Horizon simulation foundations for the pinned vanilla Java Edition target" +[features] +# Records the call sites of LegacyRandom draws (mob AI parity debugging). +rng-trace = [] + [[bin]] name = "horizon-parity" path = "src/bin/parity.rs" diff --git a/crates/horizon-core/src/random.rs b/crates/horizon-core/src/random.rs index 9b2b570e4..89de3e1f1 100644 --- a/crates/horizon-core/src/random.rs +++ b/crates/horizon-core/src/random.rs @@ -9,6 +9,49 @@ pub use positional::{ }; pub use worldgen::{WorldgenPositional, WorldgenRandom, WorldgenSource, slime_chunk_random}; +/// Call sites of `LegacyRandom` draws, recorded while switched on (the +/// counterpart of the mob AI oracle's `TracingRandom`). +#[cfg(feature = "rng-trace")] +pub mod trace { + use std::cell::{Cell, RefCell}; + thread_local! { + static ON: Cell = const { Cell::new(false) }; + static LOG: RefCell> = const { RefCell::new(Vec::new()) }; + } + pub fn set(on: bool) { + ON.with(|c| c.set(on)); + } + /// The draws recorded since the last call, as `bits=value: frames`. + pub fn take() -> Vec { + LOG.with(|l| std::mem::take(&mut *l.borrow_mut())) + } + pub(super) fn record(bits: u32, value: i32) { + if !ON.with(Cell::get) { + return; + } + let text = std::backtrace::Backtrace::force_capture().to_string(); + let mut line = format!("{bits}={value:x}:"); + let mut name = ""; + let mut n = 0; + for raw in text.lines() { + let raw = raw.trim(); + match raw.strip_prefix("at ") { + Some(at) if at.contains("horizon-client/src/") && n < 7 => { + let file = at.rsplit('/').next().unwrap_or(at); + let file = file.rsplit_once(':').map_or(file, |(f, _)| f); + let short = name.split('<').next().unwrap_or(name); + let short = short.rsplit("::").next().unwrap_or(short); + line.push_str(&format!(" {short}@{file}")); + n += 1; + } + Some(_) => {} + None => name = raw.split_once(": ").map_or("", |(_, f)| f), + } + } + LOG.with(|l| l.borrow_mut().push(line)); + } +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct InvalidBound; @@ -85,7 +128,10 @@ impl LegacyRandom { fn bits(&mut self, count: u32) -> i32 { self.state = self.state.wrapping_mul(Self::MULTIPLIER).wrapping_add(11) & Self::MASK; - (self.state >> (48 - count)) as i32 + let value = (self.state >> (48 - count)) as i32; + #[cfg(feature = "rng-trace")] + trace::record(count, value); + value } } 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..30a94811b 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java @@ -420,6 +420,10 @@ public final class VanillaMobAiOracle { Connection connection = new Connection(PacketFlow.SERVERBOUND); new EmbeddedChannel(connection); this.getPlayerList().placeNewPlayer(connection, player, cookie); + // A client that has finished loading: otherwise the player stays invulnerable + // until 60 of the server ticks between scenarios have passed, so whether mobs can + // hurt it would depend on the scenario order. + method(player.connection.getClass(), "markClientLoaded").invoke(player.connection); } player.setGameMode(s.creative ? GameType.CREATIVE : GameType.SURVIVAL); player.snapTo(s.player[0], s.player[1], s.player[2], 0.0F, 0.0F); @@ -467,6 +471,8 @@ public final class VanillaMobAiOracle { if (player != null && s.player != null) { player.setHealth(player.getMaxHealth()); player.setInvulnerableTime(0); + // The hurt cooldown (only ServerPlayer.tick counts it down). + field(LivingEntity.class, "damageCooldownTime").setInt(player, 0); player.hurtTime = 0; player.snapTo(s.player[0], s.player[1], s.player[2], 0.0F, 0.0F); player.setDeltaMovement(Vec3.ZERO); diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index bee2af785..4214da235 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -200,6 +200,9 @@ def compare(vanilla, rust, fields=None): f'horizon {draws(prev_r, (b or {}).get("rng"))})') for line in [x for x in v.get('trace', {}).get(t, []) if x.split(' ', 1)[0] == str(mob)][:40]: report.append(' vanilla ' + line) + # Present when the probe is built with the rng-trace feature (see --trace). + for line in [x for x in r.get('trace', {}).get(t, []) if x.split(' ', 1)[0] == str(mob)][:40]: + report.append(' horizon ' + line) report.extend(' ' + d for d in diffs[:12]) if first is not None: clean = False @@ -221,6 +224,8 @@ def main(): parser.add_argument('--java-only', action='store_true') parser.add_argument('--rust-only', action='store_true', help='reuse the last vanilla output') parser.add_argument('--report-only', action='store_true', help='print divergences without failing') + parser.add_argument('--trace', action='store_true', + help="also trace Horizon's mob random draws (rng-trace probe with line tables)") args = parser.parse_args() build = lab.LOCAL / 'mob-ai-parity' build.mkdir(parents=True, exist_ok=True) @@ -235,9 +240,15 @@ def main(): 'dev.horizonlab.parity.VanillaMobAiOracle', inputs, build / 'vanilla.txt'], build, 'vanilla', timeout=3600) if not args.java_only: - oracle_harness.run_logged(['cargo', 'build', '--locked', '--release', '-p', 'horizon-client', '--example', 'mob_ai_probe'], - build, 'compile-rust') - binary = lab.cargo_target() / 'release/examples/mob_ai_probe' + command = ['cargo', 'build', '--locked', '--release', '-p', 'horizon-client', '--example', 'mob_ai_probe'] + target, env = lab.cargo_target(), None + if args.trace: + target = lab.LOCAL / 'mob-ai-trace-target' + command += ['--features', 'rng-trace'] + env = dict(os.environ, CARGO_TARGET_DIR=str(target), CARGO_PROFILE_RELEASE_DEBUG='line-tables-only', + CARGO_PROFILE_RELEASE_LTO='false', CARGO_PROFILE_RELEASE_CODEGEN_UNITS='16') + oracle_harness.run_logged(command, build, 'compile-rust', env=env) + binary = target / 'release/examples/mob_ai_probe' oracle_harness.run_logged([binary, lab.ROOT / '.local/horizon-client/26.3', inputs, build / 'horizon.txt'], build, 'horizon') if args.java_only: return From d2c91b513b96c59826cd5d51094b942e3af5c912 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 11 Oct 2026 18:56:36 +0200 Subject: [PATCH 2/7] Match vanilla drowned AI, skeleton weapon goals, trader look goals and monster idle time Drowned register Zombie's goals and then Drowned.addBehaviourGoals (go to water, trident and melee attacks with okTarget, go to beach, swim up, RandomStrollGoal) with DrownedMoveControl, Drowned.travelInWater and AmphibiousPathNavigation. Skeletons get their bow from finalizeSpawn and pick the bow goal or the AbstractSkeleton$1 melee goal from the held item, as reassessWeaponGoal does. Monster.aiStep adds 2 to noActionTime in bright light (raiders always), which stops RandomStrollGoal; LookAtPlayerGoal supports Mob.class targets and InteractGoal, used by the wandering trader (with vanilla's AvoidEntityGoal order), illagers, ravagers and vexes. Entities below the world take 4 damage a tick instead of vanishing, water travel uses the 0.8F/0.6F/0.3F float constants, and MobWorld carries the level's sea level. The oracle refreshes the player's water state after placing it (it is never ticked, so isInWater kept the previous scenario's value) and keeps its world under the harness build directory, deleting it before halting instead of leaving /tmp/horizon-mob-ai* behind. The probe reports KILLED removals. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/mob_ai_probe.rs | 8 +- crates/horizon-client/src/entity_nbt.rs | 4 +- crates/horizon-client/src/game/creatures.rs | 2 + crates/horizon-client/src/mobs.rs | 6 + crates/horizon-client/src/mobs/ai.rs | 59 ++- crates/horizon-client/src/mobs/control.rs | 2 +- crates/horizon-client/src/mobs/goals.rs | 111 ++++- crates/horizon-client/src/mobs/illager.rs | 6 +- crates/horizon-client/src/mobs/illusioner.rs | 2 +- crates/horizon-client/src/mobs/living.rs | 12 +- crates/horizon-client/src/mobs/ravager.rs | 1 + crates/horizon-client/src/mobs/spawn_rules.rs | 2 +- crates/horizon-client/src/mobs/spawning.rs | 9 +- crates/horizon-client/src/mobs/trader.rs | 6 +- crates/horizon-client/src/mobs/undead.rs | 421 ++++++++++++++++-- crates/horizon-client/src/mobs/vex.rs | 1 + ...unk-aiworld-2026-10-11_16.47.20-server.txt | 96 ++++ .../horizonlab/parity/VanillaMobAiOracle.java | 17 +- tools/test_mob_ai_parity.py | 6 +- 19 files changed, 694 insertions(+), 77 deletions(-) create mode 100644 debug/chunk-aiworld-2026-10-11_16.47.20-server.txt diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index f28ee853c..7058d448f 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -142,6 +142,8 @@ fn goal_name(m: &Mob, name: &str) -> String { let vanilla = match name { "Float" => "FloatGoal", "Stroll" => "WaterAvoidingRandomStrollGoal", + "RandomStroll" => "RandomStrollGoal", + "RandomSwimming" => "RandomSwimmingGoal", "LookAtPlayer" => "LookAtPlayerGoal", "RandomLookAround" => "RandomLookAroundGoal", "HurtByTarget" => "HurtByTargetGoal", @@ -248,7 +250,9 @@ fn player_hurt(player: Option<&PlayerView>, e: &MobEvent) -> bool { fn print(out: &mut String, t: i32, i: usize, m: &Mob) { let _ = write!(out, "{t} {i}"); if m.removed { - let _ = writeln!(out, " removed DISCARDED"); + // Entity.RemovalReason: the end of the death animation, else a discard. + let reason = if m.alive() { "DISCARDED" } else { "KILLED" }; + let _ = writeln!(out, " removed {reason}"); return; } let p = m.position; @@ -506,6 +510,8 @@ fn main() -> horizon_client::Result<()> { difficulty: LocalDifficulty::new(2, world.day_time, 0, 0.0), end: false, world_seed: 0, + // FlatLevelSource.getSeaLevel. + sea_level: -63, }; let mut events = Vec::new(); #[allow(unused_mut)] // filled only with the rng-trace feature diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index b38fb8469..1dfe273e7 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -407,7 +407,9 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { } // Skeletons are spawned holding a bow (finalizeSpawn); a mob loaded // from NBT keeps only its saved equipment. - "minecraft:skeleton" | "minecraft:stray" | "minecraft:bogged" if raw.is_none() => { + "minecraft:skeleton" | "minecraft:stray" | "minecraft:bogged" + if raw.is_none() && m.extra.main_hand.as_deref() == Some("minecraft:bow") => + { map.entry("equipment".into()).or_insert_with(|| { Tag::compound([( "mainhand", diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index bceb78131..38c56d408 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -366,6 +366,7 @@ impl Game<'_> { mob_griefing: self.ui.rules.bool("mob_griefing"), end: self.dim == Dim::End, world_seed: self.level.seed, + sea_level: if self.dim == Dim::Nether { 32 } else { 63 }, difficulty: self.local_difficulty( self.player .as_ref() @@ -2391,6 +2392,7 @@ fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static K::InWall => "minecraft:in_wall", K::Thorns => "minecraft:thorns", K::SonicBoom => "minecraft:sonic_boom", + K::OutOfWorld => "minecraft:out_of_world", } } /// A Horizon item stack as a loot stack (id, count, damage, enchantments). diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index fc0d15a0f..efd9bc88a 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -359,6 +359,8 @@ pub enum DamageKind { InWall, Thorns, SonicBoom, + /// `fell_out_of_world`: below the world's floor. + OutOfWorld, } /// A damage source: its type, the attacking entity and where it came from. #[derive(Clone, Copy, Debug)] @@ -414,6 +416,7 @@ impl Damage { | DamageKind::InWall | DamageKind::Generic | DamageKind::SonicBoom + | DamageKind::OutOfWorld ) } pub fn is_fire(&self) -> bool { @@ -436,6 +439,7 @@ impl Damage { | DamageKind::Cactus | DamageKind::Generic | DamageKind::InWall + | DamageKind::OutOfWorld ) } pub fn is_projectile(&self) -> bool { @@ -960,6 +964,8 @@ pub struct MobWorld<'a> { pub end: bool, /// The world seed (slime chunks). pub world_seed: i64, + /// `Level.getSeaLevel` (63 in the overworld, -63 in a flat world). + pub sea_level: i32, } impl Mob { pub fn new(id: u32, kind: Arc, position: Vec3, yaw: f32) -> Self { diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index f001a360a..180fcfe0a 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -221,6 +221,9 @@ fn pre_tick(m: &mut Mob, events: &mut Vec) { } /// Move controls implemented by the species (MoveKind::Custom). pub fn custom_move_control(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + if m.species() == Species::Drowned { + return undead::drowned_move_control(m, w); + } if m.species() == Species::Ghast { return super::nether::ghast_move_control(m, w); } @@ -264,6 +267,47 @@ fn generic(m: &mut Mob) { g.add(7, RandomLookAround::default()); } } +/// Subclasses of `net.minecraft.world.entity.monster.Monster`. +pub fn is_monster(s: Species) -> bool { + use Species as S; + matches!( + s, + S::Zombie + | S::Husk + | S::Drowned + | S::ZombieVillager + | S::ZombifiedPiglin + | S::Giant + | S::Skeleton + | S::Stray + | S::Bogged + | S::Parched + | S::WitherSkeleton + | S::Creeper + | S::Spider + | S::CaveSpider + | S::Enderman + | S::Endermite + | S::Silverfish + | S::Witch + | S::Pillager + | S::Vindicator + | S::Evoker + | S::Illusioner + | S::Ravager + | S::Vex + | S::Piglin + | S::PiglinBrute + | S::Zoglin + | S::Blaze + | S::Guardian + | S::ElderGuardian + | S::Breeze + | S::Creaking + | S::Warden + | S::Wither + ) +} /// One full entity tick. Returns false when the mob is gone. pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) -> bool { if m.removed { @@ -310,7 +354,7 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) -> bool { m.update_walk_animation(); m.anim.end_tick(m.ai.swinging); tick_swing(m); - m.position.y > -128.0 + true } /// LivingEntity.updateSwingTime (6-tick swing duration). fn tick_swing(m: &mut Mob) { @@ -355,6 +399,10 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.fire_ticks -= 1; } } + // Entity.checkBelowWorld: LivingEntity.onBelowWorld hurts 4 a tick. + if m.position.y < f64::from(crate::chunk::MIN_Y - 64) { + m.damage(4.0, Damage::of(DamageKind::OutOfWorld)); + } if m.alive() { // LivingEntity.baseTick: suffocation inside full blocks. let (ex, ey, ez) = ( @@ -494,6 +542,12 @@ fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { .is_some_and(|t| t.position.distance_squared(m.position) > 121.0); super::witch::ai_step(m, events, far); } + // Monster.aiStep: updateNoActionTime (Raider: always +2). + if is_monster(m.species()) + && (super::raider::is_raider(m.species()) || super::hostile::mob_brightness(m, w) > 0.5) + { + m.ai.no_action_time += 2; + } if super::creaking::is_creaking(m) { super::creaking::update(m, w, events); } @@ -1014,6 +1068,9 @@ pub fn ate(m: &mut Mob) { } /// Species-specific travel (fish, squid, dolphins swim with their own rules). pub fn custom_travel(m: &mut Mob, w: &MobWorld, input: Vec3, events: &mut Vec) -> bool { + if m.species() == Species::Drowned { + return undead::drowned_travel(m, w, input, events); + } match family(m.species()) { Family::Aquatic => aquatic::travel(m, w, input, events), Family::Guardian => super::guardian::travel(m, w, input, events), diff --git a/crates/horizon-client/src/mobs/control.rs b/crates/horizon-client/src/mobs/control.rs index 361b1b13a..e4637bb0c 100644 --- a/crates/horizon-client/src/mobs/control.rs +++ b/crates/horizon-client/src/mobs/control.rs @@ -230,7 +230,7 @@ impl Mob { self.ai.speed = speed; self.ai.zza = speed; } - fn ground_move_tick(&mut self, w: &MobWorld, attr_speed: f64) { + pub(crate) fn ground_move_tick(&mut self, w: &MobWorld, attr_speed: f64) { match self.ai.mov.operation { Operation::Strafe => { let speed = self.ai.mov.speed_modifier as f32 * attr_speed as f32; diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index b1c7ecb26..5869d4478 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -585,6 +585,15 @@ impl Stroll { } impl Goal for Stroll { goal_clone!(); + fn name(&self) -> &'static str { + if self.water_avoiding.is_some() { + "Stroll" + } else if self.swim { + "RandomSwimming" + } else { + "RandomStroll" + } + } fn flags(&self) -> u8 { MOVE } @@ -648,6 +657,11 @@ pub struct LookAtPlayer { pub range: f32, pub probability: f32, pub only_horizontal: bool, + /// `LookAtPlayerGoal(Mob.class, ...)`: the nearest mob, not the player. + pub mobs: bool, + /// InteractGoal: LOOK and MOVE. + pub interact: bool, + look_at: Option, look_time: i32, } impl LookAtPlayer { @@ -656,45 +670,110 @@ impl LookAtPlayer { range, probability: 0.02, only_horizontal: false, + mobs: false, + interact: false, + look_at: None, look_time: 0, } } + /// `LookAtPlayerGoal(this, Mob.class, range)`. + pub fn mobs(range: f32) -> Self { + Self { + mobs: true, + ..Self::new(range) + } + } + /// `InteractGoal(this, Player.class, range, probability)`. + pub fn interact(range: f32, probability: f32) -> Self { + Self { + interact: true, + ..Self::new(range).probability(probability) + } + } pub fn probability(mut self, p: f32) -> Self { self.probability = p; self } + /// The goal's look target, alive, with its position and eye height. + fn look_target(&self, w: &MobWorld) -> Option<(Vec3, f64)> { + match self.look_at? { + Who::Player => w + .player + .as_ref() + .filter(|p| p.alive) + .map(|p| (p.position, p.eye[1])), + Who::Mob(id) => w + .seen(id) + .filter(|s| s.alive) + .map(|s| (s.position, s.eye_y)), + } + } } impl Goal for LookAtPlayer { goal_clone!(); fn flags(&self) -> u8 { - LOOK + if self.interact { LOOK | MOVE } else { LOOK } + } + fn name(&self) -> &'static str { + if self.interact { + "InteractGoal" + } else { + "LookAtPlayer" + } } fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { if m.random.next_float() >= self.probability { return false; } - // level.getNearestPlayer(forNonCombat().range(lookDistance)). - m.can_see_player(cx.w, f64::from(self.range)) + self.look_at = None; + let range = f64::from(self.range); + if !self.mobs { + // level.getNearestPlayer(forNonCombat().range(lookDistance)). + if m.can_see_player(cx.w, range) { + self.look_at = Some(Who::Player); + } + return self.look_at.is_some(); + } + // level.getNearestEntity(mobs in the box inflated by (range, 3, range)). + let area = m.bounds().inflate(Vec3::new(range, 3.0, range)); + let id = m.id; + let at = Vec3::new(m.position.x, m.eye_y(), m.position.z); + let candidates: Vec<(u32, Vec3)> = + cx.w.others + .iter() + .filter(|s| s.id != id && s.alive && s.bounds.intersects(area)) + .map(|s| (s.id, s.position)) + .collect(); + let mut best: Option<(u32, f64)> = None; + for (cid, pos) in candidates { + let reach = range.max(2.0); + if m.distance_sqr(pos) > reach * reach || !m.sees(cx.w, Who::Mob(cid)) { + continue; + } + let d = pos.distance_squared(at); + if best.is_none_or(|(_, b)| d < b) { + best = Some((cid, d)); + } + } + self.look_at = best.map(|(cid, _)| Who::Mob(cid)); + self.look_at.is_some() } fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - let Some(p) = &cx.w.player else { return false }; - p.alive - && m.distance_sqr(p.position) <= f64::from(self.range * self.range) - && self.look_time > 0 + let Some((pos, _)) = self.look_target(cx.w) else { + return false; + }; + m.distance_sqr(pos) <= f64::from(self.range * self.range) && self.look_time > 0 } fn start(&mut self, m: &mut Mob, _: &mut Cx) { self.look_time = reduced(40 + m.random.next_int_bound(40).unwrap_or(0)); } + fn stop(&mut self, _: &mut Mob, _: &mut Cx) { + self.look_at = None; + } fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { - if let Some(p) = &cx.w.player - && p.alive - { - let y = if self.only_horizontal { - m.eye_y() - } else { - p.eye[1] - }; - m.look_at([p.position.x, y, p.position.z]); + if let Some((pos, eye)) = self.look_target(cx.w) { + let y = if self.only_horizontal { m.eye_y() } else { eye }; + m.look_at([pos.x, y, pos.z]); self.look_time -= 1; } } diff --git a/crates/horizon-client/src/mobs/illager.rs b/crates/horizon-client/src/mobs/illager.rs index f2879887c..46d3ff9d2 100644 --- a/crates/horizon-client/src/mobs/illager.rs +++ b/crates/horizon-client/src/mobs/illager.rs @@ -65,6 +65,7 @@ pub fn register_pillager(m: &mut Mob) { g.add(3, CrossbowAttack::new(1.0, 8.0)); g.add(8, Stroll::new(0.6)); g.add(9, LookAtPlayer::new(15.0).probability(1.0)); + g.add(10, LookAtPlayer::mobs(15.0)); targets(m, false); } pub fn register_vindicator(m: &mut Mob) { @@ -74,7 +75,8 @@ pub fn register_vindicator(m: &mut Mob) { g.add(4, super::raider::HoldGroundAttack::new(10.0)); g.add(5, MeleeAttack::new(1.0, false)); g.add(8, Stroll::new(0.6)); - g.add(9, LookAtPlayer::new(3.0)); + g.add(9, LookAtPlayer::new(3.0).probability(1.0)); + g.add(10, LookAtPlayer::mobs(8.0)); targets(m, true); // VindicatorJohnnyAttackGoal: a vindicator named Johnny attacks anything. m.ai.targets.add( @@ -95,11 +97,13 @@ pub fn register_evoker(m: &mut Mob) { 2, super::goals::AvoidEntity::new(super::goals::Avoid::Player, 8.0, 0.6, 1.0), ); + g.add(3, avoid_creaking(0.6, 1.0)); g.add(4, UseSpell::new(Spell::Vexes)); g.add(5, UseSpell::new(Spell::Fangs)); g.add(6, UseSpell::new(Spell::Wololo)); g.add(8, Stroll::new(0.6)); g.add(9, LookAtPlayer::new(3.0).probability(1.0)); + g.add(10, LookAtPlayer::mobs(8.0)); targets(m, false); } #[derive(Clone, Copy, Debug, PartialEq, Eq)] diff --git a/crates/horizon-client/src/mobs/illusioner.rs b/crates/horizon-client/src/mobs/illusioner.rs index ee36acf40..ec17abad7 100644 --- a/crates/horizon-client/src/mobs/illusioner.rs +++ b/crates/horizon-client/src/mobs/illusioner.rs @@ -39,7 +39,7 @@ pub fn register(m: &mut Mob) { g.add(6, BowAttack::new(0.5, 20, 15.0)); g.add(8, Stroll::new(0.6)); g.add(9, LookAtPlayer::new(3.0).probability(1.0)); - g.add(10, LookAtPlayer::new(8.0)); + g.add(10, LookAtPlayer::mobs(8.0)); let mut hurt = HurtByTarget::new().alert(); hurt.ignore = vec![ Species::Pillager, diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 8d294cdcc..99d7417b1 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -474,7 +474,11 @@ impl Mob { if self.horizontal_collision && self.kind.flags.climber { m.y = 0.2; } - m = Vec3::new(m.x * f64::from(slow), m.y * 0.8, m.z * f64::from(slow)); + m = Vec3::new( + m.x * f64::from(slow), + m.y * f64::from(0.8_f32), + m.z * f64::from(slow), + ); self.velocity = fluid_falling(gravity, falling, m); } else { self.move_relative(0.02, input); @@ -482,7 +486,7 @@ impl Mob { if self.fluids.lava <= self.fluid_jump_threshold() { self.velocity = Vec3::new( self.velocity.x * 0.5, - self.velocity.y * 0.8, + self.velocity.y * f64::from(0.8_f32), self.velocity.z * 0.5, ); self.velocity = fluid_falling(gravity, falling, self.velocity); @@ -502,11 +506,11 @@ impl Mob { if self.horizontal_collision && w.no_collision(self.bounds().move_by(Vec3::new( m.x, - m.y + 0.6 - self.position.y + old_y, + m.y + f64::from(0.6_f32) - self.position.y + old_y, m.z, ))) { - self.velocity.y = 0.3; + self.velocity.y = f64::from(0.3_f32); } } /// The jump part of LivingEntity.aiStep. diff --git a/crates/horizon-client/src/mobs/ravager.rs b/crates/horizon-client/src/mobs/ravager.rs index 4b982687d..ef71b8f77 100644 --- a/crates/horizon-client/src/mobs/ravager.rs +++ b/crates/horizon-client/src/mobs/ravager.rs @@ -21,6 +21,7 @@ pub fn register(m: &mut Mob) { g.add(4, MeleeAttack::new(1.0, true)); g.add(5, Stroll::avoiding_water(0.4)); g.add(6, LookAtPlayer::new(6.0)); + g.add(10, LookAtPlayer::mobs(8.0)); let mut hurt = HurtByTarget::new().alert(); hurt.ignore = vec![ Species::Pillager, diff --git a/crates/horizon-client/src/mobs/spawn_rules.rs b/crates/horizon-client/src/mobs/spawn_rules.rs index 40806b04e..22f9206af 100644 --- a/crates/horizon-client/src/mobs/spawn_rules.rs +++ b/crates/horizon-client/src/mobs/spawn_rules.rs @@ -586,7 +586,7 @@ impl SpawnLevel for super::MobWorld<'_> { self.thundering } fn sea_level(&self) -> i32 { - if self.nether { 32 } else { 63 } + self.sea_level } fn world_surface(&self, x: i32, z: i32) -> i32 { let top = crate::chunk::MIN_Y + crate::chunk::HEIGHT; diff --git a/crates/horizon-client/src/mobs/spawning.rs b/crates/horizon-client/src/mobs/spawning.rs index cffe7e03d..0bfd5d223 100644 --- a/crates/horizon-client/src/mobs/spawning.rs +++ b/crates/horizon-client/src/mobs/spawning.rs @@ -220,10 +220,15 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) { .into(), ); } - // AbstractSkeleton.populateDefaultEquipmentSlots (the bow is given on - // registration). + // AbstractSkeleton.populateDefaultEquipmentSlots: armour, then a bow. S::Skeleton | S::Stray | S::Bogged | S::Parched => { populate_armor(m, difficulty); + m.extra.main_hand = Some("minecraft:bow".into()); + m.extra.pick_up_loot = m.random.next_float() < 0.55 * difficulty.special(); + } + // WitherSkeleton.populateDefaultEquipmentSlots: a stone sword only. + S::WitherSkeleton => { + m.extra.main_hand = Some("minecraft:stone_sword".into()); m.extra.pick_up_loot = m.random.next_float() < 0.55 * difficulty.special(); } S::Pillager => { diff --git a/crates/horizon-client/src/mobs/trader.rs b/crates/horizon-client/src/mobs/trader.rs index d72760e21..2d7101909 100644 --- a/crates/horizon-client/src/mobs/trader.rs +++ b/crates/horizon-client/src/mobs/trader.rs @@ -44,10 +44,10 @@ pub fn register(m: &mut Mob) { for (species, distance) in [ (Species::Zombie, 8.0), (Species::Evoker, 12.0), - (Species::Illusioner, 12.0), (Species::Vindicator, 8.0), (Species::Vex, 8.0), (Species::Pillager, 15.0), + (Species::Illusioner, 12.0), (Species::Zoglin, 10.0), ] { // `Zombie.class` covers the zombie family. @@ -78,8 +78,8 @@ pub fn register(m: &mut Mob) { ); g.add(4, MoveTowardsRestriction::new(0.35)); g.add(8, Stroll::avoiding_water(0.35)); - g.add(9, LookAtPlayer::new(3.0).probability(1.0)); - g.add(10, LookAtPlayer::new(8.0)); + g.add(9, LookAtPlayer::interact(3.0, 1.0)); + g.add(10, LookAtPlayer::mobs(8.0)); } fn invisible(m: &Mob) -> bool { m.extra.effects.iter().any(|e| e.0 == INVISIBILITY) diff --git a/crates/horizon-client/src/mobs/undead.rs b/crates/horizon-client/src/mobs/undead.rs index 4d2886a00..4d6c76d73 100644 --- a/crates/horizon-client/src/mobs/undead.rs +++ b/crates/horizon-client/src/mobs/undead.rs @@ -56,24 +56,53 @@ pub fn register(m: &mut Mob) { ); } S::Drowned => { + // Zombie.registerGoals, then Drowned.addBehaviourGoals. let g = &mut m.ai.goals; - g.add(1, DrownedGoToWater::default()); - g.add(2, MeleeAttack::new(1.0, false).zombie()); - g.add(5, Stroll::new(1.0)); + g.add(4, AttackTurtleEgg::default()); g.add(8, LookAtPlayer::new(8.0)); g.add(8, RandomLookAround::default()); + g.add(1, DrownedGoToWater::default()); + g.add( + 2, + DrownedTridentAttack(super::witch::RangedAttack::new( + 1.0, + 40, + 40, + 10.0, + drowned_throw, + )), + ); + g.add(2, DrownedAttack(MeleeAttack::new(1.0, false).zombie())); + g.add( + 5, + DrownedGoToBeach(super::goals::MoveToBlock::new(1.0, 8, 2)), + ); + g.add(6, DrownedSwimUp { stuck: false }); + g.add(7, Stroll::new(1.0)); let t = &mut m.ai.targets; - let mut hurt = HurtByTarget::new().alert(); + let mut hurt = HurtByTarget::new().alert().ignoring(&[S::Drowned]); hurt.alert_except = vec![S::ZombifiedPiglin]; t.add(1, hurt); - t.add(2, NearestTarget::player(false).when(drowned_can_attack)); + t.add(2, NearestTarget::player(true).when(drowned_can_attack)); t.add( 3, NearestTarget::species(&[S::Villager, S::WanderingTrader], false), ); t.add(3, NearestTarget::species(&[S::IronGolem], true)); - t.add(3, NearestTarget::species(&[S::Axolotl], true).interval(10)); + t.add(3, NearestTarget::species(&[S::Axolotl], true)); + t.add( + 5, + NearestTarget::new( + super::goals::Prey::Filter(|s| s.species == Species::Turtle && s.baby), + true, + ) + .interval(10), + ); + // DrownedMoveControl, AmphibiousPathNavigation, no water malus. + m.ai.mov.kind = super::control::MoveKind::Custom; + m.ai.nav.kind = super::nav::NavKind::Amphibious; m.ai.nav.can_float = false; + m.set_malus(super::path::PathType::Water, 0.0); } S::Skeleton | S::Stray | S::Bogged | S::Parched | S::WitherSkeleton => { let species = m.species(); @@ -104,30 +133,281 @@ pub fn register(m: &mut Mob) { 3, NearestTarget::species(&[S::Piglin, S::PiglinBrute], true), ); - m.extra.main_hand = Some("minecraft:stone_sword".into()); - m.ai.goals.add(4, MeleeAttack::new(1.2, false)); - } else { - m.extra.main_hand = Some("minecraft:bow".into()); - let interval = if matches!(m.species(), S::Bogged | S::Parched) { - 70 - } else { - 40 - }; - m.ai.goals.add(4, BowAttack::new(1.0, interval, 15.0)); } + // The AbstractSkeleton constructor's reassessWeaponGoal, after + // registerGoals; the weapon itself comes with finalizeSpawn. + let interval = if matches!(species, S::Bogged | S::Parched) { + 70 + } else { + 40 + }; + m.ai.goals.add(4, SkeletonWeapon::new(interval)); } _ => {} } } -fn drowned_can_attack(m: &Mob, w: &super::MobWorld) -> bool { - // Drowned.okTarget: at night or when the target is in water. +/// Drowned.okTarget: at night, or when the target is in water. +fn drowned_can_attack(_m: &Mob, w: &super::MobWorld) -> bool { let Some(p) = &w.player else { return false }; - let (x, y, z) = ( - p.position.x.floor() as i32, - p.position.y.floor() as i32, - p.position.z.floor() as i32, + !w.daylight || in_water_at(w, p.position) +} +/// The target's isInWater, from the water at its feet. +fn in_water_at(w: &super::MobWorld, p: Vec3) -> bool { + let (x, y, z) = (p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32); + w.fluid(x, y, z) == crate::blocks::Fluid::Water +} +/// Drowned.okTarget for the current target. +fn drowned_ok_target(m: &Mob, w: &super::MobWorld) -> bool { + m.target_info(w) + .is_some_and(|t| !w.daylight || in_water_at(w, t.position)) +} +// Drowned state: `flag` wantsToSwim (target in water), `flag2` searchingForLand. +/// Drowned.wantsToSwim +pub fn drowned_wants_to_swim(m: &Mob, w: &super::MobWorld) -> bool { + m.extra.flag2 || m.target_info(w).is_some_and(|t| in_water_at(w, t.position)) +} +/// Drowned.DrownedMoveControl +pub fn drowned_move_control(m: &mut Mob, w: &super::MobWorld) { + let target = m.target_info(w); + if drowned_wants_to_swim(m, w) && m.fluids.in_water { + if target.is_some_and(|t| t.position.y > m.position.y) || m.extra.flag2 { + m.velocity = Vec3::new(m.velocity.x, m.velocity.y + 0.002, m.velocity.z); + } + if m.ai.mov.operation != super::control::Operation::MoveTo || m.ai.nav.is_done() { + m.set_speed(0.0); + return; + } + let [wx, wy, wz] = m.ai.mov.wanted; + let (xd, mut yd, zd) = (wx - m.position.x, wy - m.position.y, wz - m.position.z); + let dd = (xd * xd + yd * yd + zd * zd).sqrt(); + yd /= dd; + let y_rot = horizon_core::geometry::trig::atan2_degrees(zd, xd) - 90.0; + m.yaw = super::control::rotlerp(m.yaw, y_rot, 90.0); + m.body_yaw = m.yaw; + let target_speed = (m.ai.mov.speed_modifier * m.movement_speed()) as f32; + let speed = m.ai.speed + 0.125 * (target_speed - m.ai.speed); + m.set_speed(speed); + let s = f64::from(speed); + m.velocity = Vec3::new( + m.velocity.x + s * xd * 0.005, + m.velocity.y + s * yd * 0.1, + m.velocity.z + s * zd * 0.005, + ); + } else { + if !m.on_ground { + m.velocity = Vec3::new(m.velocity.x, m.velocity.y - 0.008, m.velocity.z); + } + let speed = m.movement_speed(); + m.ground_move_tick(w, speed); + } +} +/// Drowned.travelInWater: swimming under water slowly when it wants to. +pub fn drowned_travel( + m: &mut Mob, + w: &super::MobWorld, + input: Vec3, + events: &mut Vec, +) -> bool { + if !(m.fluids.eye_in_water && m.fluids.in_water && drowned_wants_to_swim(m, w)) { + return false; + } + m.move_relative(0.01, input); + m.do_move(w, events); + m.velocity = Vec3::new(m.velocity.x * 0.9, m.velocity.y * 0.9, m.velocity.z * 0.9); + true +} +/// The trident throw of `Drowned.performRangedAttack`, until thrown tridents +/// exist: an arrow-like shot with the trident's damage. +fn drowned_throw(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) { + let Some(t) = cx.w.target_info(who) else { + return; + }; + let start = Vec3::new(m.position.x, m.eye_y() - 0.1, m.position.z); + let xd = t.position.x - m.position.x; + let yd = t.position.y + (t.bounds.max_position().y - t.bounds.min_position().y) / 3.0 - start.y; + let zd = t.position.z - m.position.z; + let dist = (xd * xd + zd * zd).sqrt(); + let mut p = Projectile::new( + ProjectileKind::Arrow { + base_damage: 8.0, + critical: false, + effect: None, + }, + start, + Some(Who::Mob(m.id)), ); - !w.daylight || w.fluid(x, y, z) == crate::blocks::Fluid::Water || m.fluids.in_water + // The spread draws from the new projectile's own random. + let mut spread = horizon_core::random::LegacyRandom::new(i64::from(m.id) ^ m.age as i64); + p.shoot( + &mut spread, + [xd, yd + dist * f64::from(0.2_f32), zd], + 1.6, + (14 - 2 * 4) as f32, + ); + cx.events.push(MobEvent::Projectile(p)); + let pitch = 1.0 / (m.random.next_float() * 0.4 + 0.8); + cx.events.push(MobEvent::Sound( + "entity.drowned.shoot", + m.center(), + 1.0, + pitch, + )); +} +/// Drowned.DrownedTridentAttackGoal: the ranged goal while holding a trident. +#[derive(Clone, Debug)] +struct DrownedTridentAttack(super::witch::RangedAttack); +impl Goal for DrownedTridentAttack { + goal_clone!(); + fn flags(&self) -> u8 { + self.0.flags() + } + fn name(&self) -> &'static str { + "Drowned$DrownedTridentAttackGoal" + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.0.can_use(m, cx) && m.extra.main_hand.as_deref() == Some("minecraft:trident") + } + 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) { + self.0.start(m, cx); + m.ai.aggressive = true; + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.stop(m, cx); + m.ai.aggressive = false; + } + fn every_tick(&self) -> bool { + self.0.every_tick() + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.tick(m, cx) + } +} +/// Drowned.DrownedAttackGoal: ZombieAttackGoal on a target it may attack. +#[derive(Clone, Debug)] +struct DrownedAttack(MeleeAttack); +impl Goal for DrownedAttack { + goal_clone!(); + fn flags(&self) -> u8 { + self.0.flags() + } + fn name(&self) -> &'static str { + "Drowned$DrownedAttackGoal" + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.0.can_use(m, cx) && drowned_ok_target(m, cx.w) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.0.can_continue(m, cx) && drowned_ok_target(m, cx.w) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.start(m, cx) + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.stop(m, cx) + } + fn every_tick(&self) -> bool { + self.0.every_tick() + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.tick(m, cx) + } +} +/// Drowned.DrownedGoToBeachGoal: at night, swim near the surface to a +/// standable block with air above. +#[derive(Clone, Debug)] +struct DrownedGoToBeach(super::goals::MoveToBlock); +fn beach_target(w: &super::MobWorld, p: [i32; 3]) -> bool { + let empty = |y: i32| { + let state = w.world.block(p[0], y, p[2]); + w.facts.is_air(state) && w.facts.get(state).fluid == crate::blocks::Fluid::None + }; + // BlockState.entityCanStandOn: a full top face. + empty(p[1] + 1) + && empty(p[1] + 2) + && w.facts.get(w.world.block(p[0], p[1], p[2])).sturdy_full & (1 << 1) != 0 +} +impl Goal for DrownedGoToBeach { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | super::goals::JUMP + } + fn name(&self) -> &'static str { + "Drowned$DrownedGoToBeachGoal" + } + fn every_tick(&self) -> bool { + true + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + // MoveToBlockGoal.canUse, then the drowned's conditions. + if self.0.next_start > 0 { + self.0.next_start -= 1; + return false; + } + self.0.next_start = super::goals::reduced(200 + m.random.next_int_bound(200).unwrap_or(0)); + self.0.find_nearest(m, cx.w, beach_target) + && !cx.w.daylight + && m.fluids.in_water + && m.position.y >= f64::from(cx.w.sea_level - 3) + } + fn can_continue(&mut self, _m: &mut Mob, cx: &mut Cx) -> bool { + self.0.can_continue(cx.w, beach_target) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + m.extra.flag2 = false; + self.0.start(m, cx.w); + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.tick(m, cx.w); + } +} +/// Drowned.DrownedSwimUpGoal: at night, deep in water, head for the surface. +#[derive(Clone, Debug)] +struct DrownedSwimUp { + stuck: bool, +} +impl Goal for DrownedSwimUp { + goal_clone!(); + fn flags(&self) -> u8 { + 0 + } + fn name(&self) -> &'static str { + "Drowned$DrownedSwimUpGoal" + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + !cx.w.daylight && m.fluids.in_water && m.position.y < f64::from(cx.w.sea_level - 2) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.can_use(m, cx) && !self.stuck + } + fn start(&mut self, m: &mut Mob, _cx: &mut Cx) { + m.extra.flag2 = true; + self.stuck = false; + } + fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) { + m.extra.flag2 = false; + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let sea = f64::from(cx.w.sea_level); + if m.position.y < sea - 1.0 && (m.ai.nav.is_done() || drowned_close_to_next_pos(m)) { + let to = [m.position.x, sea - 1.0, m.position.z]; + match m.default_random_pos_towards(cx.w, 4, 8, to, std::f64::consts::FRAC_PI_2) { + None => self.stuck = true, + Some(p) => { + m.nav_move_to(cx.w, p, 1.0); + } + } + } + } +} +/// Drowned.closeToNextPos: within two blocks of the path's target. +fn drowned_close_to_next_pos(m: &Mob) -> bool { + m.ai.nav.path.as_ref().is_some_and(|p| { + let t = p.target; + m.distance_sqr(Vec3::new(f64::from(t[0]), f64::from(t[1]), f64::from(t[2]))) < 4.0 + }) } /// Zombie drowning conversion (Zombie.DrowningTracker) and husk -> zombie. /// `ZombifiedPiglin.customServerAiStep`: faster and loud while angry, @@ -237,25 +517,82 @@ pub fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { m.extra.counter = -1; } } - if m.species() == Species::Drowned { - // Drowned.updateSwimming / travel: swim when the target is in water. - let wants = - m.ai.target - .and_then(|t| cx.w.target_info(t)) - .is_some_and(|t| { - let (x, y, z) = ( - t.position.x.floor() as i32, - t.position.y.floor() as i32, - t.position.z.floor() as i32, - ); - cx.w.fluid(x, y, z) == crate::blocks::Fluid::Water - }); - m.extra.flag = wants; - if m.fluids.in_water && wants { - m.ai.nav.kind = super::nav::NavKind::Water { breach: false }; - } else if m.ai.nav.kind != super::nav::NavKind::Ground { - m.ai.nav.kind = super::nav::NavKind::Ground; - m.ai.nav.stop(); +} +/// `AbstractSkeleton.reassessWeaponGoal`'s goal: the bow goal while holding a +/// bow, otherwise the melee goal (the anonymous `AbstractSkeleton$1`). +#[derive(Clone, Debug)] +pub struct SkeletonWeapon { + bow: BowAttack, + melee: MeleeAttack, + use_bow: bool, +} +impl SkeletonWeapon { + pub fn new(bow_interval: i32) -> Self { + Self { + bow: BowAttack::new(1.0, bow_interval, 15.0), + melee: MeleeAttack::new(1.2, false), + use_bow: false, + } + } +} +impl Goal for SkeletonWeapon { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn name(&self) -> &'static str { + if self.use_bow { + "BowAttack" + } else { + "AbstractSkeleton$1" + } + } + fn every_tick(&self) -> bool { + if self.use_bow { + self.bow.every_tick() + } else { + self.melee.every_tick() + } + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + // The goal registered for the weapon in hand. + self.use_bow = holding_bow(m); + if self.use_bow { + self.bow.can_use(m, cx) + } else { + self.melee.can_use(m, cx) + } + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + // Changing weapons removes the running goal. + if self.use_bow != holding_bow(m) { + return false; + } + if self.use_bow { + self.bow.can_continue(m, cx) + } else { + self.melee.can_continue(m, cx) + } + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + if self.use_bow { + self.bow.start(m, cx) + } else { + self.melee.start(m, cx) + } + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + if self.use_bow { + self.bow.stop(m, cx) + } else { + self.melee.stop(m, cx) + } + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + if self.use_bow { + self.bow.tick(m, cx) + } else { + self.melee.tick(m, cx) } } } diff --git a/crates/horizon-client/src/mobs/vex.rs b/crates/horizon-client/src/mobs/vex.rs index 74551edb6..de38f6da8 100644 --- a/crates/horizon-client/src/mobs/vex.rs +++ b/crates/horizon-client/src/mobs/vex.rs @@ -28,6 +28,7 @@ pub fn register(m: &mut Mob) { g.add(4, Charge); g.add(8, RandomMove); g.add(9, LookAtPlayer::new(3.0).probability(1.0)); + g.add(10, LookAtPlayer::mobs(8.0)); let mut hurt = HurtByTarget::new().alert(); hurt.ignore = vec![ Species::Pillager, diff --git a/debug/chunk-aiworld-2026-10-11_16.47.20-server.txt b/debug/chunk-aiworld-2026-10-11_16.47.20-server.txt new file mode 100644 index 000000000..ca30394cc --- /dev/null +++ b/debug/chunk-aiworld-2026-10-11_16.47.20-server.txt @@ -0,0 +1,96 @@ +---- Minecraft Chunk IO Error Report ---- +// Let's not do it again... + +Time: 2026-10-11 16:47:20 +Description: Chunk save failure + +java.io.IOException: No space left on device + at java.base/sun.nio.ch.UnixFileDispatcherImpl.pwrite0(Native Method) + at java.base/sun.nio.ch.UnixFileDispatcherImpl.pwrite(UnixFileDispatcherImpl.java:71) + at java.base/sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:135) + at java.base/sun.nio.ch.IOUtil.write(IOUtil.java:102) + at java.base/sun.nio.ch.IOUtil.write(IOUtil.java:72) + at java.base/sun.nio.ch.FileChannelImpl.writeInternal(FileChannelImpl.java:1261) + at java.base/sun.nio.ch.FileChannelImpl.implWrite(FileChannelImpl.java:1234) + at java.base/sun.nio.ch.FileChannelImpl.write(FileChannelImpl.java:1216) + at net.minecraft.world.level.chunk.storage.RegionFile.write(RegionFile.java:420) + at net.minecraft.world.level.chunk.storage.RegionFile$ChunkBuffer.close(RegionFile.java:393) + at java.base/java.util.zip.DeflaterOutputStream.close(DeflaterOutputStream.java:320) + at java.base/java.io.FilterOutputStream.close(FilterOutputStream.java:190) + at java.base/java.io.FilterOutputStream.close(FilterOutputStream.java:190) + at net.minecraft.world.level.chunk.storage.RegionFileStorage.write(RegionFileStorage.java:117) + at net.minecraft.world.level.chunk.storage.IOWorker.runStore(IOWorker.java:280) + at net.minecraft.world.level.chunk.storage.IOWorker.storePendingChunk(IOWorker.java:270) + at net.minecraft.util.thread.StrictQueue$RunnableWithPriority.run(StrictQueue.java:50) + at net.minecraft.util.Util.runNamed(Util.java:351) + at net.minecraft.util.thread.AbstractConsecutiveExecutor.pollTask(AbstractConsecutiveExecutor.java:50) + at net.minecraft.util.thread.AbstractConsecutiveExecutor.run(AbstractConsecutiveExecutor.java:60) + at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1090) + at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:614) + at java.base/java.lang.Thread.run(Thread.java:1474) + + +A detailed walkthrough of the error, its code path and all known details is as follows: +--------------------------------------------------------------------------------------- + +-- Head -- +Thread: IO-Worker-37 +Stacktrace: + at java.base/sun.nio.ch.UnixFileDispatcherImpl.pwrite0(Native Method) + at java.base/sun.nio.ch.UnixFileDispatcherImpl.pwrite(UnixFileDispatcherImpl.java:71) + at java.base/sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:135) + at java.base/sun.nio.ch.IOUtil.write(IOUtil.java:102) + at java.base/sun.nio.ch.IOUtil.write(IOUtil.java:72) + at java.base/sun.nio.ch.FileChannelImpl.writeInternal(FileChannelImpl.java:1261) + at java.base/sun.nio.ch.FileChannelImpl.implWrite(FileChannelImpl.java:1234) + at java.base/sun.nio.ch.FileChannelImpl.write(FileChannelImpl.java:1216) + at net.minecraft.world.level.chunk.storage.RegionFile.write(RegionFile.java:420) + at net.minecraft.world.level.chunk.storage.RegionFile$ChunkBuffer.close(RegionFile.java:393) + at java.base/java.util.zip.DeflaterOutputStream.close(DeflaterOutputStream.java:320) + at java.base/java.io.FilterOutputStream.close(FilterOutputStream.java:190) + at java.base/java.io.FilterOutputStream.close(FilterOutputStream.java:190) + at net.minecraft.world.level.chunk.storage.RegionFileStorage.write(RegionFileStorage.java:117) + at net.minecraft.world.level.chunk.storage.IOWorker.runStore(IOWorker.java:280) + at net.minecraft.world.level.chunk.storage.IOWorker.storePendingChunk(IOWorker.java:270) + at net.minecraft.util.thread.StrictQueue$RunnableWithPriority.run(StrictQueue.java:50) + at net.minecraft.util.Util.runNamed(Util.java:351) + at net.minecraft.util.thread.AbstractConsecutiveExecutor.pollTask(AbstractConsecutiveExecutor.java:50) + +-- Chunk Info -- +Details: + Level: aiworld + Dimension: minecraft:overworld + Storage: chunk + Position: [680, 15] +Stacktrace: + at net.minecraft.server.MinecraftServer.lambda$storeChunkIoError$0(MinecraftServer.java:2225) + at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1090) + at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:614) + at java.base/java.lang.Thread.run(Thread.java:1474) + +-- System Details -- +Details: + Minecraft Version: 26.3 + Minecraft Version ID: 26.3 + Operating System: Linux (amd64) version 6.18.55 + Java Version: 25.0.4.1, N/A + Java VM Version: OpenJDK 64-Bit Server VM (mixed mode, sharing), Oracle Corporation + Memory: 239988568 bytes (228 MiB) / 1694498816 bytes (1616 MiB) up to 3221225472 bytes (3072 MiB) + Memory (heap): init: 436MiB, used: 1383MiB, committed: 1616MiB, max: 3072MiB + Memory (non-heap): init: 007MiB, used: 123MiB, committed: 135MiB, max: 000MiB + CPUs: 24 + processor: ~~ERROR~~ NoClassDefFoundError: Could not initialize class oshi.software.os.linux.LinuxOperatingSystem + Graphics card #0 name: AD103 [GeForce RTX 4080] + Graphics card #0 vendor: NVIDIA Corporation (0x10de) + Graphics card #0 VRAM (MiB): 16416.00 + Graphics card #0 deviceId: 0x2704 + Graphics card #0 versionInfo: unknown + memory: ~~ERROR~~ NoClassDefFoundError: Could not initialize class oshi.hardware.platform.linux.LinuxGlobalMemory + Space in storage for jna.tmpdir (MiB): + Space in storage for org.lwjgl.system.SharedLibraryExtractPath (MiB): + Space in storage for io.netty.native.workdir (MiB): + Space in storage for java.io.tmpdir (MiB): available: 8.54, total: 936786.75 + Space in storage for workdir (MiB): available: 8.54, total: 936786.75 + software: ~~ERROR~~ NoClassDefFoundError: Could not initialize class oshi.software.os.linux.LinuxOperatingSystem + JVM Flags: 1 total; -Xmx3g + Debug Flags: 0 total; \ No newline at end of file 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 30a94811b..a854c291a 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java @@ -105,6 +105,8 @@ import net.minecraft.world.phys.Vec3; public final class VanillaMobAiOracle { static final List SCENARIOS = new ArrayList<>(); static PrintWriter out; + /** The temporary world directory, deleted before the oracle halts. */ + static Path UNIVERSE; static final List SOUNDS = new ArrayList<>(); /** Draws of a traced mob random: the caller frames of each draw (AI_TRACE=scenario:from-to). */ @@ -208,7 +210,10 @@ public final class VanillaMobAiOracle { SharedConstants.tryDetectVersion(); Bootstrap.bootStrap(); Util.startTimerHackThread(); - Path universe = Files.createTempDirectory("horizon-mob-ai"); + // The harness passes an empty world directory under its build directory. + Path universe = args.length > 2 ? Path.of(args[2]) : Files.createTempDirectory("horizon-mob-ai"); + Files.createDirectories(universe); + UNIVERSE = universe; LevelStorageSource.LevelStorageAccess access = LevelStorageSource.createDefault(universe).createAccess("aiworld"); PackRepository packs = ServerPacksSource.createPackRepository(access); MinecraftServer.spin(thread -> Server.create(thread, access, packs)); @@ -344,7 +349,12 @@ public final class VanillaMobAiOracle { void step(BooleanSupplier haveTime) throws Exception { if (scenario >= SCENARIOS.size()) { out.close(); - // Nothing to save: skip the shutdown. + // Nothing to save: skip the shutdown, but leave no world behind. + try (var paths = Files.walk(UNIVERSE)) { + paths.sorted(java.util.Comparator.reverseOrder()).forEach(p -> p.toFile().delete()); + } catch (Exception e) { + // best effort + } Runtime.getRuntime().halt(0); return; } @@ -427,6 +437,9 @@ public final class VanillaMobAiOracle { } player.setGameMode(s.creative ? GameType.CREATIVE : GameType.SURVIVAL); player.snapTo(s.player[0], s.player[1], s.player[2], 0.0F, 0.0F); + // The player is never ticked during a scenario: give it the water state of + // where it stands (isInWater), not the previous scenario's. + method(Entity.class, "updateFluidInteraction").invoke(player); player.setDeltaMovement(Vec3.ZERO); } else if (player != null) { player.snapTo(s.originX + 5000, -60, s.originZ, 0.0F, 0.0F); diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index 4214da235..eb1e0a470 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -13,6 +13,7 @@ reports, per scenario and mob, how many ticks match before the first divergence """ import argparse import os +import shutil import struct import subprocess import sys @@ -236,8 +237,11 @@ def main(): if not args.rust_only: classes, dependencies, _ = oracle_harness.compile_oracle(build, 'VanillaMobAiOracle', jars, baking.client_libraries(), lock['minecraft']['java_major']) + # The oracle's server world: cleared before each run, never left in /tmp. + world = build / 'world' + shutil.rmtree(world, ignore_errors=True) oracle_harness.run_logged(['java', '-Xmx3g', '-Djava.awt.headless=true', '-cp', str(classes) + os.pathsep + dependencies, - 'dev.horizonlab.parity.VanillaMobAiOracle', inputs, build / 'vanilla.txt'], + 'dev.horizonlab.parity.VanillaMobAiOracle', inputs, build / 'vanilla.txt', world], build, 'vanilla', timeout=3600) if not args.java_only: command = ['cargo', 'build', '--locked', '--release', '-p', 'horizon-client', '--example', 'mob_ai_probe'] From a466af6adc392656d5e02a8cef6e5f444d1ada7b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 11 Oct 2026 19:02:46 +0200 Subject: [PATCH 3/7] Match vanilla projectile randoms, witch target goal and enderman goal names Projectiles shot by mobs (arrows, splash potions, snowballs, llama spit, wind charges, crossbow bolts, tridents) take their spread, and arrows their base damage, from the new projectile's own random as vanilla does, leaving the shooter's random alone. The witch's player target goal reports as NearestAttackableWitchTargetGoal (NearestTarget gains a subclass label), and the probe names the enderman goals as vanilla's classes. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/examples/mob_ai_probe.rs | 5 +++++ crates/horizon-client/src/mobs/breeze.rs | 7 ++++++- crates/horizon-client/src/mobs/goals.rs | 11 +++++++++++ crates/horizon-client/src/mobs/golem.rs | 7 ++++++- crates/horizon-client/src/mobs/illager.rs | 7 ++++++- crates/horizon-client/src/mobs/llama.rs | 7 ++++++- crates/horizon-client/src/mobs/undead.rs | 9 ++++----- crates/horizon-client/src/mobs/witch.rs | 5 +++-- crates/horizon-client/src/projectiles.rs | 11 +++++++++++ 9 files changed, 58 insertions(+), 11 deletions(-) diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 7058d448f..9f083e2d5 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -173,6 +173,11 @@ fn goal_name(m: &Mob, name: &str) -> String { "TryFindWater" => "TryFindWaterGoal", "RangedAttack" => "RangedAttackGoal", "MoveTowardsTarget" => "MoveTowardsTargetGoal", + "TakeBlock" => "EndermanTakeBlockGoal", + "LeaveBlock" => "EndermanLeaveBlockGoal", + "FreezeWhenLookedAt" => "EndermanFreezeWhenLookedAt", + "LookForPlayer" => "EndermanLookForPlayerGoal", + "HealRaiders" => "NearestHealableRaiderTargetGoal", other => return other.to_owned(), }; vanilla.to_owned() diff --git a/crates/horizon-client/src/mobs/breeze.rs b/crates/horizon-client/src/mobs/breeze.rs index 9667a827a..d01bd34cc 100644 --- a/crates/horizon-client/src/mobs/breeze.rs +++ b/crates/horizon-client/src/mobs/breeze.rs @@ -330,7 +330,12 @@ fn tick_shoot(m: &mut Mob, cx: &mut Cx) { Some(Who::Mob(m.id)), ); // 5 - 4 * difficulty at normal. - p.shoot(&mut m.random, [xd, yd, zd], 0.7, -3.0); + p.shoot( + &mut crate::projectiles::own_random(m), + [xd, yd, zd], + 0.7, + -3.0, + ); cx.events.push(MobEvent::Projectile(p)); cx.events .push(MobEvent::Sound("entity.breeze.shoot", m.center(), 1.5, 1.0)); diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 5869d4478..673eb560b 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -1015,6 +1015,8 @@ pub struct NearestTarget { /// A condition checked before anything else, by subclasses overriding /// `canUse` (SpiderTargetGoal: only in the dark). pub gate: Option bool>, + /// The vanilla class name of a subclass (`Goal::name`). + pub label: Option<&'static str>, found: Option, target_goal: TargetState, } @@ -1043,6 +1045,7 @@ impl NearestTarget { interval: reduced(10), when: None, gate: None, + label: None, found: None, target_goal: TargetState { unseen_memory: 60, @@ -1077,6 +1080,11 @@ impl NearestTarget { self.gate = Some(f); self } + /// A subclass's name, e.g. `NearestAttackableWitchTargetGoal`. + pub fn named(mut self, label: &'static str) -> Self { + self.label = Some(label); + self + } } /// TargetGoal.canContinueToUse pub fn target_continue(st: &mut TargetState, must_see: bool, m: &mut Mob, cx: &mut Cx) -> bool { @@ -1105,6 +1113,9 @@ pub fn target_continue(st: &mut TargetState, must_see: bool, m: &mut Mob, cx: &m } impl Goal for NearestTarget { goal_clone!(); + fn name(&self) -> &'static str { + self.label.unwrap_or("NearestTarget") + } fn flags(&self) -> u8 { TARGET } diff --git a/crates/horizon-client/src/mobs/golem.rs b/crates/horizon-client/src/mobs/golem.rs index d12f26788..089f5f7fd 100644 --- a/crates/horizon-client/src/mobs/golem.rs +++ b/crates/horizon-client/src/mobs/golem.rs @@ -284,7 +284,12 @@ fn snowball_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) { let yo = (xd * xd + zd * zd).sqrt() * 0.2; let mut p = Projectile::new(ProjectileKind::Snowball, start, Some(Who::Mob(m.id))); // rangedAttackUncertainty: 14 - 4 * difficulty (normal: 6). - p.shoot(&mut m.random, [xd, yd + yo - start.y, zd], 1.6, 6.0); + p.shoot( + &mut crate::projectiles::own_random(m), + [xd, yd + yo - start.y, zd], + 1.6, + 6.0, + ); cx.events.push(MobEvent::Projectile(p)); let pitch = 0.4 / (m.random.next_float() * 0.4 + 0.8); cx.events.push(MobEvent::Sound( diff --git a/crates/horizon-client/src/mobs/illager.rs b/crates/horizon-client/src/mobs/illager.rs index 46d3ff9d2..15be02a1d 100644 --- a/crates/horizon-client/src/mobs/illager.rs +++ b/crates/horizon-client/src/mobs/illager.rs @@ -543,7 +543,12 @@ fn shoot_crossbow(m: &mut Mob, who: Who, cx: &mut Cx) { ); p.bonus = super::gear::arrow_bonus(m); // rangedAttackUncertainty at normal difficulty: 14 - 2 * 4. - p.shoot(&mut m.random, [dx, dy, dz], 1.6, 6.0); + p.shoot( + &mut crate::projectiles::own_random(m), + [dx, dy, dz], + 1.6, + 6.0, + ); cx.events.push(MobEvent::Projectile(p)); let pitch = 1.0 / (m.random.next_float() * 0.5 + 1.8) + 0.53; cx.events.push(MobEvent::Sound( diff --git a/crates/horizon-client/src/mobs/llama.rs b/crates/horizon-client/src/mobs/llama.rs index fbae29b02..82aeebe17 100644 --- a/crates/horizon-client/src/mobs/llama.rs +++ b/crates/horizon-client/src/mobs/llama.rs @@ -174,7 +174,12 @@ fn spit(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) { let zd = t.position.z - m.position.z; let yo = (xd * xd + zd * zd).sqrt() * f64::from(0.2_f32); let mut p = Projectile::new(ProjectileKind::LlamaSpit, start, Some(Who::Mob(m.id))); - p.shoot(&mut m.random, [xd, yd + yo, zd], 1.5, 10.0); + p.shoot( + &mut crate::projectiles::own_random(m), + [xd, yd + yo, zd], + 1.5, + 10.0, + ); cx.events.push(MobEvent::Projectile(p)); let pitch = 1.0 + (m.random.next_float() - m.random.next_float()) * 0.2; cx.events.push(MobEvent::Sound( diff --git a/crates/horizon-client/src/mobs/undead.rs b/crates/horizon-client/src/mobs/undead.rs index 4d6c76d73..50ac9934f 100644 --- a/crates/horizon-client/src/mobs/undead.rs +++ b/crates/horizon-client/src/mobs/undead.rs @@ -236,10 +236,8 @@ fn drowned_throw(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) { start, Some(Who::Mob(m.id)), ); - // The spread draws from the new projectile's own random. - let mut spread = horizon_core::random::LegacyRandom::new(i64::from(m.id) ^ m.age as i64); p.shoot( - &mut spread, + &mut crate::projectiles::own_random(m), [xd, yd + dist * f64::from(0.2_f32), zd], 1.6, (14 - 2 * 4) as f32, @@ -739,7 +737,8 @@ pub fn perform_ranged_attack(m: &mut Mob, who: Who, cx: &mut Cx, power: f32) { let zd = t.position.z - m.position.z; let dist = (xd * xd + zd * zd).sqrt(); // AbstractArrow.setBaseDamageFromMob: power * 2 + triangle(difficulty * 0.11, 0.57425). - let base = f64::from(power) * 2.0 + m.random.triangle(2.0 * 0.11, 0.574_25); + let mut arrow_random = crate::projectiles::own_random(m); + let base = f64::from(power) * 2.0 + arrow_random.triangle(2.0 * 0.11, 0.574_25); let effect = match m.species() { Species::Stray => Some(("minecraft:slowness", 600)), Species::Bogged => Some(("minecraft:poison", 100)), @@ -757,7 +756,7 @@ pub fn perform_ranged_attack(m: &mut Mob, who: Who, cx: &mut Cx, power: f32) { ); p.bonus = super::gear::arrow_bonus(m); p.shoot( - &mut m.random, + &mut arrow_random, [xd, yd + dist * 0.2, zd], 1.6, (14 - 2 * 4) as f32, diff --git a/crates/horizon-client/src/mobs/witch.rs b/crates/horizon-client/src/mobs/witch.rs index 0995d64e6..0990ae01d 100644 --- a/crates/horizon-client/src/mobs/witch.rs +++ b/crates/horizon-client/src/mobs/witch.rs @@ -26,7 +26,8 @@ pub fn register(m: &mut Mob) { 3, NearestTarget::player(true) .interval(10) - .gate(|m, _| m.extra.counter2 <= 0), + .gate(|m, _| m.extra.counter2 <= 0) + .named("NearestAttackableWitchTargetGoal"), ); } /// `NearestHealableRaiderTargetGoal`: in a raid, target another raider to @@ -221,7 +222,7 @@ fn witch_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) { ); // Splash potions throw with gravity 0.05. p.shoot( - &mut m.random, + &mut crate::projectiles::own_random(m), [xd, yd + dist * 0.2, zd], if dist <= 2.0 { 0.45 } else { 0.75 }, 8.0, diff --git a/crates/horizon-client/src/projectiles.rs b/crates/horizon-client/src/projectiles.rs index d855fdaea..59d419a46 100644 --- a/crates/horizon-client/src/projectiles.rs +++ b/crates/horizon-client/src/projectiles.rs @@ -9,6 +9,17 @@ use horizon_core::{ random::RandomSource, }; +/// A new projectile entity's own random: vanilla seeds every entity's random +/// unpredictably, and a projectile's spread (and an arrow's base damage) come +/// from it, never from the shooter's random. +pub fn own_random(shooter: &crate::mobs::Mob) -> horizon_core::random::LegacyRandom { + horizon_core::random::LegacyRandom::new( + i64::from(shooter.id).wrapping_mul(0x9E37_79B9) + ^ i64::from(shooter.age) + ^ shooter.position.x.to_bits() as i64, + ) +} + #[derive(Clone, Debug, PartialEq)] pub enum ProjectileKind { /// Arrow with its base damage, critical flag and tipped/stray/bogged effect. From c7a2fbb182e2188448e2fb27e2ea84b5de9df391 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 11 Oct 2026 19:18:23 +0200 Subject: [PATCH 4/7] Match vanilla wither tick order, underwater checks and gravity The wither's customServerAiStep (charging, side heads, block breaking, healing) now runs inside serverAiStep, and aiStep draws the heads' smoke particle offsets after travel as vanilla does; its steering uses the 0.6F and Mth.atan2 float maths, and its level-event sounds (shoot, spawn, block break) no longer draw from its random: MobEvent::LevelEventSound lets the client pick their pitch. Entity.getGravity is zero while isNoGravity, which the flying move control sets. Drowned swim with isUnderWater (the previous tick's eye state, Entity.wasEyeInWater), and the eyes count as in water per 26.3's EntityFluidInteraction (between a water block's bottom and its camera height) rather than the older 0.11 offset. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/mob_ai_probe.rs | 1 + crates/horizon-client/src/game/creatures.rs | 11 +++ crates/horizon-client/src/mobs.rs | 13 +++ crates/horizon-client/src/mobs/ai.rs | 2 + crates/horizon-client/src/mobs/living.rs | 39 +++++++- crates/horizon-client/src/mobs/undead.rs | 11 ++- crates/horizon-client/src/mobs/wither.rs | 93 ++++++++++++------- 7 files changed, 127 insertions(+), 43 deletions(-) diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 9f083e2d5..dda20095b 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -173,6 +173,7 @@ fn goal_name(m: &Mob, name: &str) -> String { "TryFindWater" => "TryFindWaterGoal", "RangedAttack" => "RangedAttackGoal", "MoveTowardsTarget" => "MoveTowardsTargetGoal", + "DrownedGoToWater" => "DrownedGoToWaterGoal", "TakeBlock" => "EndermanTakeBlockGoal", "LeaveBlock" => "EndermanLeaveBlockGoal", "FreezeWhenLookedAt" => "EndermanFreezeWhenLookedAt", diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 38c56d408..999ee2025 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -635,6 +635,17 @@ impl Game<'_> { self.audio .play(&format!("minecraft:{name}"), Some(at), volume, pitch) } + MobEvent::LevelEventSound { + sound, + at, + volume, + spread, + } => { + let r = &mut self.world.random; + let pitch = (r.next_float() - r.next_float()) * spread + 1.0; + self.audio + .play(&format!("minecraft:{sound}"), Some(at), volume, pitch) + } MobEvent::SoundId(name, at, volume, pitch) => { self.audio.play(&name, Some(at), volume, pitch) } diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index efd9bc88a..48d6833d4 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -595,6 +595,9 @@ pub struct Mob { pub ai: Box, pub extra: Extra, pub fluids: living::Fluids, + /// Entity.wasEyeInWater: the eyes were in water before this tick's fluid + /// update (`isUnderWater` reads it). + pub was_eye_in_water: bool, pub no_gravity: bool, /// `NoAI`: no goals and no movement. pub no_ai: bool, @@ -626,6 +629,15 @@ pub enum MobEvent { Sound(&'static str, [f64; 3], f32, f32), /// A sound event id that is not a static string (variant sounds). SoundId(String, [f64; 3], f32, f32), + /// A level event's sound (`levelEvent`/`globalLevelEvent`): the client + /// plays it with its own random pitch spread (`(a - b) * spread + 1`), + /// nothing is drawn from the mob. + LevelEventSound { + sound: &'static str, + at: [f64; 3], + volume: f32, + spread: f32, + }, AttackPlayer(f32, [f64; 3]), /// Damage of a given type to the player (guardian lasers, thorns). DamagePlayer { @@ -1009,6 +1021,7 @@ impl Mob { ai: Box::default(), extra: Extra::default(), fluids: living::Fluids::default(), + was_eye_in_water: false, no_gravity: false, no_ai: false, silent: false, diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 180fcfe0a..fafa371ed 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -371,6 +371,7 @@ fn tick_swing(m: &mut Mob) { } /// Entity.baseTick + LivingEntity.baseTick + Mob.baseTick. fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + m.was_eye_in_water = m.fluids.eye_in_water; m.fluids = w.fluids(m.bounds(), m.eye_y()); if m.fluids.in_water { m.fall_distance = 0.0; @@ -761,6 +762,7 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { Species::Blaze => super::nether::blaze_server_ai_step(m, cx), Species::ElderGuardian => super::guardian::elder_server_ai_step(m, cx), Species::Warden => super::warden::server_ai_step(m, cx), + Species::Wither if m.alive() => super::wither::custom_server_ai_step(m, cx.w, cx.events), // SpellcasterIllager.customServerAiStep. Species::Evoker if m.extra.counter > 0 => m.extra.counter -= 1, _ => {} diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 99d7417b1..8756ae6be 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -86,10 +86,34 @@ impl MobWorld<'_> { } } } - let (fx, fz) = ((lo.x + hi.x) / 2.0, (lo.z + hi.z) / 2.0); - let ey = eye_y.floor() as i32; - let (fluid, h) = self.fluid_height(fx.floor() as i32, ey, fz.floor() as i32); - out.eye_in_water = fluid == Fluid::Water && eye_y < f64::from(ey) + h + 0.111_111_11; + // EntityFluidInteraction.update: the eyes are in a fluid block of + // the box in the entity's column, between its bottom and its height + // for the camera. + let (ex, ez) = ( + ((lo.x + hi.x) / 2.0).floor() as i32, + ((lo.z + hi.z) / 2.0).floor() as i32, + ); + for y in lo.y.floor() as i32..=(hi.y.ceil() as i32 - 1) { + let (fluid, h) = self.fluid_height(ex, y, ez); + if fluid != Fluid::Water || f64::from(y) + h < lo.y || eye_y < f64::from(y) { + continue; + } + let state = self.world.block(ex, y, ez); + let source = self + .registry + .state(state) + .and_then(|s| s.properties.get("level")) + .is_none_or(|l| l == "0"); + let above = self.facts.get(self.world.block(ex, y + 1, ez)); + let camera = if source && above.sturdy_full & 1 != 0 { + 1.0 + } else { + h + }; + if eye_y <= f64::from(y) + camera { + out.eye_in_water = true; + } + } out } pub fn no_collision(&self, b: Aabb) -> bool { @@ -362,8 +386,13 @@ impl Mob { fn flying_speed(&self) -> f32 { 0.02 } + /// Entity.getGravity: none while isNoGravity. fn gravity(&self) -> f64 { - self.kind.gravity + if self.no_gravity { + 0.0 + } else { + self.kind.gravity + } } /// LivingEntity.travel. pub fn travel(&mut self, w: &MobWorld, input: Vec3, events: &mut Vec) { diff --git a/crates/horizon-client/src/mobs/undead.rs b/crates/horizon-client/src/mobs/undead.rs index 50ac9934f..b6986f6d1 100644 --- a/crates/horizon-client/src/mobs/undead.rs +++ b/crates/horizon-client/src/mobs/undead.rs @@ -208,7 +208,8 @@ pub fn drowned_travel( input: Vec3, events: &mut Vec, ) -> bool { - if !(m.fluids.eye_in_water && m.fluids.in_water && drowned_wants_to_swim(m, w)) { + // isUnderWater: wasEyeInWater && isInWater. + if !(m.was_eye_in_water && m.fluids.in_water && drowned_wants_to_swim(m, w)) { return false; } m.move_relative(0.01, input); @@ -260,7 +261,7 @@ impl Goal for DrownedTridentAttack { self.0.flags() } fn name(&self) -> &'static str { - "Drowned$DrownedTridentAttackGoal" + "DrownedTridentAttackGoal" } fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { self.0.can_use(m, cx) && m.extra.main_hand.as_deref() == Some("minecraft:trident") @@ -292,7 +293,7 @@ impl Goal for DrownedAttack { self.0.flags() } fn name(&self) -> &'static str { - "Drowned$DrownedAttackGoal" + "DrownedAttackGoal" } fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { self.0.can_use(m, cx) && drowned_ok_target(m, cx.w) @@ -333,7 +334,7 @@ impl Goal for DrownedGoToBeach { MOVE | super::goals::JUMP } fn name(&self) -> &'static str { - "Drowned$DrownedGoToBeachGoal" + "DrownedGoToBeachGoal" } fn every_tick(&self) -> bool { true @@ -372,7 +373,7 @@ impl Goal for DrownedSwimUp { 0 } fn name(&self) -> &'static str { - "Drowned$DrownedSwimUpGoal" + "DrownedSwimUpGoal" } fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { !cx.w.daylight && m.fluids.in_water && m.position.y < f64::from(cx.w.sea_level - 2) diff --git a/crates/horizon-client/src/mobs/wither.rs b/crates/horizon-client/src/mobs/wither.rs index 5782723d1..eda2b76c4 100644 --- a/crates/horizon-client/src/mobs/wither.rs +++ b/crates/horizon-client/src/mobs/wither.rs @@ -111,13 +111,15 @@ fn head_pos(m: &Mob, i: usize) -> [f64; 3] { /// `performRangedAttack`: a skull from a head toward a point. fn shoot(m: &mut Mob, head: usize, at: [f64; 3], dangerous: bool, events: &mut Vec) { let h = head_pos(m, head); - // Level event 1024: the shoot sound. - events.push(MobEvent::Sound( - "entity.wither.shoot", - h, - 2.0, - (m.random.next_float() - m.random.next_float()) * 0.2 + 1.0, - )); + // Level event 1024: the shoot sound (the client's pitch). + if !m.silent { + events.push(MobEvent::LevelEventSound { + sound: "entity.wither.shoot", + at: [m.position.x, m.position.y, m.position.z], + volume: 2.0, + spread: 0.2, + }); + } let dir = [at[0] - h[0], at[1] - h[1], at[2] - h[2]]; let p = Projectile::fireball( ProjectileKind::WitherSkull { dangerous }, @@ -135,7 +137,7 @@ pub fn steer(m: &mut Mob) { let mut yd = v.y; if m.position.y < t[1] || !powered(m) && m.position.y < t[1] + 5.0 { yd = yd.max(0.0); - yd += 0.3 - yd * 0.6; + yd += 0.3 - yd * f64::from(0.6_f32); } v.y = yd; let (dx, dz) = (t[0] - m.position.x, t[2] - m.position.z); @@ -147,7 +149,10 @@ pub fn steer(m: &mut Mob) { } m.velocity = v; if v.x * v.x + v.z * v.z > 0.05 { - m.yaw = (v.z.atan2(v.x).to_degrees() as f32) - 90.0; + // (float)Mth.atan2(z, x) * (180.0F / (float)Math.PI) - 90.0F + m.yaw = (horizon_core::geometry::trig::atan2(v.z, v.x) as f32) + * (180.0_f32 / std::f32::consts::PI) + - 90.0; } } fn target_pos(w: &MobWorld, id: i32) -> Option<([f64; 3], f64, bool)> { @@ -165,14 +170,9 @@ fn target_pos(w: &MobWorld, id: i32) -> Option<([f64; 3], f64, bool)> { .map(|s| ([s.position.x, s.position.y, s.position.z], s.eye_y, false)), } } -/// `WitherBoss.aiStep` (heads, particles) and `customServerAiStep`. +/// `WitherBoss.aiStep` after `super.aiStep()`: the side heads turn, smoke +/// rises from the heads (the particle offsets are drawn on the server too). pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { - if !m.alive() { - return; - } - m.extra.point = m - .target_info(w) - .map(|t| [t.position.x, t.position.y, t.position.z]); // Side heads turn toward their targets, else back to the body. for i in 0..2 { match target_pos(w, m.extra.ints[i]) { @@ -180,22 +180,42 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { let h = head_pos(m, i + 1); let (xd, yd, zd) = (p[0] - h[0], eye - h[1], p[2] - h[2]); let sd = (xd * xd + zd * zd).sqrt(); - let y_rot = (zd.atan2(xd).to_degrees() as f32) - 90.0; - let x_rot = -(yd.atan2(sd).to_degrees() as f32); + let y_rot = horizon_core::geometry::trig::atan2_degrees(zd, xd) - 90.0; + let x_rot = -horizon_core::geometry::trig::atan2_degrees(yd, sd); m.anim.v[2 + i] = rotlerp(m.anim.v[2 + i], x_rot, 40.0); m.anim.v[i] = rotlerp(m.anim.v[i], y_rot, 10.0); } None => m.anim.v[i] = rotlerp(m.anim.v[i], m.body_yaw, 10.0), } } + let powered = powered(m); for i in 0..3 { let h = head_pos(m, i); + for _ in 0..3 { + m.random.next_gaussian(); + } events.push(MobEvent::Particles { kind: "smoke", at: h, count: 0, }); + // The entity-effect particles roll the level random, not the wither's. + let _ = powered; } + if m.extra.counter > 0 { + for _ in 0..3 { + m.random.next_gaussian(); + m.random.next_float(); + m.random.next_gaussian(); + } + } +} +/// `WitherBoss.customServerAiStep`: charging, then the side heads' targets +/// and volleys, block breaking and healing. +pub fn custom_server_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + m.extra.point = m + .target_info(w) + .map(|t| [t.position.x, t.position.y, t.position.z]); if m.extra.counter > 0 { let left = m.extra.counter - 1; if left <= 0 { @@ -203,12 +223,15 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { [m.position.x, m.eye_y(), m.position.z], 7.0, )); - events.push(MobEvent::Sound( - "entity.wither.spawn", - [m.position.x, m.position.y, m.position.z], - 1.0, - 1.0, - )); + // Global level event 1023. + if !m.silent { + events.push(MobEvent::LevelEventSound { + sound: "entity.wither.spawn", + at: [m.position.x, m.position.y, m.position.z], + volume: 1.0, + spread: 0.0, + }); + } } m.extra.counter = left; if m.age.is_multiple_of(10) { @@ -226,11 +249,14 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.extra.ints[2 + k] = age + 10 + m.random.next_int_bound(10).unwrap_or(0); m.extra.ints[4 + k] += 1; if m.extra.ints[4 + k] > 16 { + // Mth.nextDouble(random, min, max) = nextDouble * (max - min) + min. + let p = m.position; let r = &mut m.random; + let mut between = |lo: f64, hi: f64| r.next_double() * (hi - lo) + lo; let at = [ - m.position.x - 10.0 + r.next_double() * 20.0, - m.position.y - 5.0 + r.next_double() * 10.0, - m.position.z - 10.0 + r.next_double() * 20.0, + between(p.x - 10.0, p.x + 10.0), + between(p.y - 5.0, p.y + 5.0), + between(p.z - 10.0, p.z + 10.0), ]; shoot(m, i + 1, at, true, events); m.extra.ints[4 + k] = 0; @@ -307,12 +333,13 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } } if destroyed { - events.push(MobEvent::Sound( - "entity.wither.break_block", - [m.position.x, m.position.y, m.position.z], - 1.0, - 1.0, - )); + // Level event 1022. + events.push(MobEvent::LevelEventSound { + sound: "entity.wither.break_block", + at: [m.position.x, m.position.y, m.position.z], + volume: 1.0, + spread: 0.0, + }); } } } From b036c0c90d578b8a0f26a2c493d352e26680b53b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 11 Oct 2026 20:32:11 +0200 Subject: [PATCH 5/7] Document the mob AI harness --trace option Co-Authored-By: Claude Opus 5.5 --- tools/test_mob_ai_parity.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index eb1e0a470..5730d8b3d 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -9,7 +9,10 @@ motion, rotations, running goals and target goals, attack target, navigation pat controls, movement input, brain activities and memories) and the sounds played; this harness reports, per scenario and mob, how many ticks match before the first divergence and what differs. - python3 tools/test_mob_ai_parity.py [--only NAME ...] [--rust-only] [--java-only] [--report-only] + python3 tools/test_mob_ai_parity.py [--only NAME ...] [--rust-only] [--java-only] [--report-only] [--trace] + +The oracle traces every mob random draw with its call stack; --trace builds the probe with +the rng-trace feature and line tables so the report shows Horizon's draws next to vanilla's. """ import argparse import os From cd116711c2938b2d4a860296a34e52dfac6151bd Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 13:16:13 +0200 Subject: [PATCH 6/7] Seed the mob AI oracle's gate shuffles so villager runs are reproducible Every GateBehavior (RunOne, and the gates of TradeWithVillager and VillagerMakeLove) shuffles its behaviours with a ShufflingList random that RandomSource.create() seeds from the clock, so two oracle runs of the same villager scenario diverged after the first RunOne. The oracle now gives each gate a LegacyRandomSource seeded with the mob's seed, and seeds the gates of a brain rebuilt by Villager.refreshBrain before its next tick. Co-Authored-By: Claude Opus 5.5 --- .../horizonlab/parity/VanillaMobAiOracle.java | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) 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 a854c291a..7185ec400 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; @@ -445,6 +449,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)); @@ -469,7 +475,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(); @@ -493,6 +502,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(); @@ -510,6 +526,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 22bc86739b349b5d335b7ed76cf73a5311ff18ce Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 13:37:39 +0200 Subject: [PATCH 7/7] Port the villager brain from VillagerGoalPackages Villagers ran an approximation built from goals. They now run vanilla's Brain: expiring memories, the nine sensors with their randomly delayed scan clocks, activities from the villager_activity timeline, and every package's behaviours (core, work, play, meet, rest, idle, panic, pre-raid, raid, hide), started and ticked in Brain.availableBehaviorsByPriority's order with RunOne's shuffles, the level random for behaviour timing and POI scans, and Villager.refreshBrain when the profession changes. The mob AI probe prints the activities and memories as the oracle does, and the harness's three villager scenarios now match: 34/34. Sleeping villagers take LivingEntity.SLEEPING_DIMENSIONS instead of being frozen in travel. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/mob_ai_probe.rs | 23 +- crates/horizon-client/src/game/creatures.rs | 7 + crates/horizon-client/src/game/trading.rs | 6 +- crates/horizon-client/src/mobs.rs | 28 +- crates/horizon-client/src/mobs/ai.rs | 34 +- crates/horizon-client/src/mobs/goals.rs | 32 + crates/horizon-client/src/mobs/living.rs | 4 + crates/horizon-client/src/mobs/nav.rs | 11 + crates/horizon-client/src/mobs/villager.rs | 873 +--- .../horizon-client/src/mobs/villager_brain.rs | 4078 +++++++++++++++++ 10 files changed, 4293 insertions(+), 803 deletions(-) create mode 100644 crates/horizon-client/src/mobs/villager_brain.rs diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index dda20095b..4c5178fae 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -230,6 +230,13 @@ fn seen(m: &Mob) -> Seen { active_raid: horizon_client::mobs::raider::has_active_raid(m), player_rep: 0, pushable: m.pushable(), + category: m.category(), + potential_job: horizon_client::mobs::villager_brain::potential_job_site(m), + meeting: (m.species() == Species::Villager) + .then_some(m.extra.meeting) + .flatten(), + profession: m.extra.variant2, + xp: horizon_client::mobs::villager::xp(m), } } @@ -347,7 +354,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::villager_brain::describe(m) { + let _ = write!(out, "\tact {acts}\tmem {mem}"); + } + out.push('\n'); } fn main() -> horizon_client::Result<()> { @@ -460,6 +471,16 @@ fn main() -> horizon_client::Result<()> { } } m.random = LegacyRandom::new(spec.seed); + if m.species() == Species::Villager { + // The oracle seeds the random after the brain is built, then + // delays the sensors again and seeds the gates' shuffles. + horizon_client::mobs::villager_brain::init( + &mut m, + world.game_time, + s.time, + spec.seed, + ); + } mobs.push(m); } let player = s.player.map(|p| { diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 999ee2025..649ad72b1 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -128,6 +128,13 @@ fn seen(m: &Mob, player: Option<[i32; 4]>) -> Seen { _ => 0, }, pushable: m.pushable(), + category: m.category(), + potential_job: horizon_client::mobs::villager_brain::potential_job_site(m), + meeting: (m.species() == Species::Villager) + .then_some(m.extra.meeting) + .flatten(), + profession: m.extra.variant2, + xp: horizon_client::mobs::villager::xp(m), } } impl Game<'_> { diff --git a/crates/horizon-client/src/game/trading.rs b/crates/horizon-client/src/game/trading.rs index 208b886bb..65141f060 100644 --- a/crates/horizon-client/src/game/trading.rs +++ b/crates/horizon-client/src/game/trading.rs @@ -184,8 +184,10 @@ impl Game<'_> { mob: Some(m.id), name: m.custom_name.clone(), }; - // setTradingPlayer: a wandering trader stands still while trading. - self.mobs[index].extra.flag2 = species == Species::WanderingTrader; + // setTradingPlayer: a wandering trader stands still while trading, a + // villager's brain follows and looks at the player + // (LookAndFollowTradingPlayerSink). + self.mobs[index].extra.flag2 = true; self.open_merchant_state(state); Ok(true) } diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 48d6833d4..0273c164d 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -56,6 +56,7 @@ pub mod trader; pub mod undead; pub mod vex; pub mod villager; +pub mod villager_brain; pub mod warden; pub mod witch; pub mod wither; @@ -894,6 +895,29 @@ pub struct Seen { pub player_rep: i32, /// `isPushable` and pushed by others (`Entity.push(Entity)` moves it). pub pushable: bool, + /// `MobCategory` (`monster`, `creature`, ...). + pub category: &'static str, + /// 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. + pub profession: u8, + pub xp: i32, +} +impl Mob { + /// `EntityType.getCategory`'s name. + pub fn category(&self) -> &'static str { + match self.kind.category.as_str() { + "monster" => "monster", + "creature" => "creature", + "ambient" => "ambient", + "axolotls" => "axolotls", + "underground_water_creature" => "underground_water_creature", + "water_creature" => "water_creature", + "water_ambient" => "water_ambient", + _ => "misc", + } + } } /// `Entity.push` on other mobs acts at once in vanilla: a mob ticking later /// moves with it this tick. Takes the `Push` events aimed at mobs out of @@ -1202,10 +1226,10 @@ impl Mob { pub fn tick( &mut self, w: &MobWorld, - _random: &mut LegacyRandom, + level_random: &mut LegacyRandom, events: &mut Vec, ) -> bool { - ai::tick(self, w, events) + ai::tick(self, w, level_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 fafa371ed..19a4f573b 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 { @@ -309,7 +312,12 @@ pub fn is_monster(s: Species) -> bool { ) } /// 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; } @@ -344,7 +352,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() { @@ -535,7 +543,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) { // Witch.aiStep runs before super.aiStep(). if m.species() == Species::Witch { let far = m @@ -565,10 +573,9 @@ fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.ai.zza *= 0.98; // LivingEntity.isImmobile: no goals or input (a biting, stunned or // roaring ravager). - let immobile = m.species() == Species::Ravager && super::ravager::immobile(m) - || super::villager::sleeping(m); + let immobile = m.species() == Species::Ravager && super::ravager::immobile(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; @@ -708,7 +715,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) { @@ -737,6 +749,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); + if m.species() == Species::Villager { + // Villager.customServerAiStep: the brain, then the raid sound roll. + super::villager_brain::tick(m, w, level_random, events); + let _ = m.random.next_int_bound(100); + } { let mut cx = Cx { w, events }; custom_server_ai_step(m, &mut cx); @@ -1079,7 +1096,6 @@ pub fn custom_travel(m: &mut Mob, w: &MobWorld, input: Vec3, events: &mut Vec true, Family::Vex => super::vex::travel(m), - Family::Villager => super::villager::travel(m), Family::Nautilus => super::nautilus::travel(m, w, input, events), _ => false, } diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 673eb560b..afc18aa55 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -315,6 +315,38 @@ impl Mob { m.land_up_out_of_solid(w, p) }) } + /// LandRandomPos.getPos(mob, h, v, scorer): the best of ten by `score`. + pub fn land_random_pos_scored( + &mut self, + w: &MobWorld, + h: i32, + v: i32, + score: impl Fn([i32; 3]) -> f64, + ) -> Option<[f64; 3]> { + let mut best: Option<[i32; 3]> = None; + let mut best_weight = f64::NEG_INFINITY; + for _ in 0..10 { + let d = self.random_direction(h, v); + let p = self.toward(f64::from(h), d); + if p[1] < crate::chunk::MIN_Y || p[1] >= 320 || !self.stable_destination(w, p) { + continue; + } + if let Some(p) = self.land_up_out_of_solid(w, p) { + let v = score(p); + if v > best_weight { + best_weight = v; + best = Some(p); + } + } + } + best.map(|p| { + [ + f64::from(p[0]) + 0.5, + f64::from(p[1]), + f64::from(p[2]) + 0.5, + ] + }) + } /// LandRandomPos.getPosAway pub fn land_random_pos_away( &mut self, diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 8756ae6be..dbca6ba0a 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -132,6 +132,10 @@ impl Mob { /// slime size scaling. /// `EntityDimensions` (float width, height and eye height) widened to double. pub fn dims(&self) -> (f64, f64, f64) { + // LivingEntity.SLEEPING_DIMENSIONS. + if super::villager::sleeping(self) { + return (f64::from(0.2_f32), f64::from(0.2_f32), f64::from(0.2_f32)); + } let k = &self.kind; let (mut w, mut h, mut e) = (k.width as f32, k.height as f32, k.eye_height as f32); // Sniffer.DIGGING_DIMENSIONS: 0.4 lower, its eyes at 0.81. diff --git a/crates/horizon-client/src/mobs/nav.rs b/crates/horizon-client/src/mobs/nav.rs index fe40b110b..376d5a845 100644 --- a/crates/horizon-client/src/mobs/nav.rs +++ b/crates/horizon-client/src/mobs/nav.rs @@ -267,6 +267,17 @@ impl Mob { let max = self.max_path_length(); self.create_path_raw(w, &[p], reach, max) } + /// PathNavigation.createPath(Set, reach): the nearest of + /// several targets, without the ground surface search. + pub fn create_path_to_any( + &mut self, + w: &MobWorld, + targets: &[[i32; 3]], + reach: i32, + ) -> Option { + let max = self.max_path_length(); + self.create_path_raw(w, targets, reach, max) + } /// PathNavigation.createPath(Entity, reach). pub fn create_path_to_entity( &mut self, diff --git a/crates/horizon-client/src/mobs/villager.rs b/crates/horizon-client/src/mobs/villager.rs index b167c3584..447a80072 100644 --- a/crates/horizon-client/src/mobs/villager.rs +++ b/crates/horizon-client/src/mobs/villager.rs @@ -1,21 +1,14 @@ -//! Villagers (`Villager` and its brain packages, as goals): taking the -//! profession of a free job site nearby (`AcquirePoi` with -//! `AssignProfessionFromJobSite`), losing a fresh profession when the site -//! goes (`ResetProfession`), claiming a bed and a bell, the daily schedule -//! (work and restock at the job site, meet at the bell, sleep in the bed), -//! fleeing hostiles (`VillagerPanicTrigger`) and the unhappy head shake. +//! Villagers (`Villager`): professions, sleeping, the unhappy head shake, +//! food, gossip and the raid state. Their AI is the brain in +//! `villager_brain`. use super::{ - Mob, MobEvent, MobWorld, Species, Who, + Mob, MobEvent, MobWorld, Species, anim::{Poses, State}, - goals::{ - Avoid, AvoidEntity, Cx, Float, Goal, LOOK, LookAtPlayer, MOVE, Panic, RandomLookAround, - Stroll, goal_clone, - }, }; use crate::items::ItemStack; use horizon_core::geometry::trig::Mth; use horizon_core::random::RandomSource; -use std::{collections::HashMap, f32::consts::PI}; +use std::f32::consts::PI; // Villager state: `variant` type, `variant2` profession (index into // `render::PROFESSIONS`), `variant3` level, `home` the claimed job site, @@ -50,187 +43,12 @@ pub fn register(m: &mut Mob) { if m.extra.variant3 == 0 { m.extra.variant3 = 1; } - let g = &mut m.ai.goals; - g.add(0, Float); - // VillagerHostilesSensor: zombies within 8 blocks, illagers further. - let zombies = vec![ - Species::Zombie, - Species::ZombieVillager, - Species::Husk, - Species::Drowned, - Species::Vex, - ]; - let raiders = vec![ - Species::Pillager, - Species::Vindicator, - Species::Evoker, - Species::Illusioner, - Species::Ravager, - Species::Zoglin, - ]; - g.add( - 1, - AvoidEntity::new(Avoid::Species(zombies), 8.0, 0.75, 0.75), - ); - g.add( - 1, - AvoidEntity::new(Avoid::Species(raiders), 12.0, 0.75, 0.75), - ); - g.add(1, Panic::new(0.75)); - g.add(2, RaidBehavior::default()); - g.add(3, Social::default()); - g.add(0, GolemCall); - g.add(3, GiftToHero::default()); - g.add(3, JobSite::default()); - g.add(3, AcquireHome::default()); - g.add(4, Schedule::default()); - g.add(5, Stroll::avoiding_water(0.5)); - g.add(6, LookAtPlayer::new(8.0)); - g.add(7, RandomLookAround::default()); + // Villager's constructor: its brain does everything, it has no goals. + m.ai.nav.can_open_doors = true; + m.ai.nav.can_float = true; + m.ai.nav.required_path_length = 48.0; } -/// `AcquirePoi` for job sites with `AssignProfessionFromJobSite`: walk to the -/// nearest unclaimed job site and take its profession once within 2 blocks. -#[derive(Clone, Debug, Default)] -struct JobSite { - target: Option<[i32; 3]>, - next_search: i32, - ticks: i32, -} -fn claimed(w: &MobWorld, me: u32, p: [i32; 3]) -> bool { - w.others - .iter() - .any(|s| s.id != me && s.alive && s.job == Some(p)) -} -fn job_seeker(m: &Mob) -> bool { - !m.is_baby() && m.extra.home.is_none() && m.extra.variant2 != NITWIT -} -#[derive(Clone, Copy, PartialEq)] -enum Poi { - Job(u8), - Bed, - Bell, -} -fn poi_at(w: &MobWorld, state: horizon_world::registry::BlockStateId) -> Option { - let name = &w.facts.get(state).name; - if name.as_ref() == "minecraft:bell" { - return Some(Poi::Bell); - } - if name.ends_with("_bed") { - let s = w.registry.state(state)?; - let free = s.properties.get("part").map(String::as_str) == Some("head") - && s.properties.get("occupied").map(String::as_str) != Some("true"); - return free.then_some(Poi::Bed); - } - job_site_profession(name).map(Poi::Job) -} -/// `PoiManager.findClosest` (`AcquirePoi.SCAN_RANGE` 48 blocks across, 8 -/// up and down): the nearest position whose POI passes `want`. -fn scan(m: &Mob, w: &MobWorld, want: impl Fn(Poi, [i32; 3]) -> bool) -> Option<[i32; 3]> { - let (bx, by, bz) = ( - m.position.x.floor() as i32, - m.position.y.floor() as i32, - m.position.z.floor() as i32, - ); - let mut known: HashMap> = HashMap::new(); - let mut best: Option<(i32, [i32; 3])> = None; - for y in by - 8..=by + 8 { - for z in bz - 48..=bz + 48 { - for x in bx - 48..=bx + 48 { - let state = w.world.block(x, y, z); - if w.facts.is_air(state) { - continue; - } - let poi = *known.entry(state.0).or_insert_with(|| poi_at(w, state)); - let Some(poi) = poi else { continue }; - let d = (x - bx).pow(2) + (y - by).pow(2) + (z - bz).pow(2); - if best.is_none_or(|(b, _)| d < b) && want(poi, [x, y, z]) { - best = Some((d, [x, y, z])); - } - } - } - } - best.map(|(_, p)| p) -} -/// The nearest free job site (a profession's own one once employed). -fn find_site(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> { - scan(m, w, |poi, p| match poi { - Poi::Job(profession) => { - (m.extra.variant2 == NONE || profession == m.extra.variant2) && !claimed(w, m.id, p) - } - _ => false, - }) -} -impl Goal for JobSite { - goal_clone!(); - fn flags(&self) -> u8 { - MOVE - } - fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - if !job_seeker(m) { - return false; - } - if self.next_search > 0 { - self.next_search -= 1; - return false; - } - // AcquirePoi's scan pacing: 20 to 40 ticks between scans. - self.next_search = 20 + m.random.next_int_bound(20).unwrap_or(0); - self.target = find_site(m, cx.w); - self.target.is_some() - } - fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - job_seeker(m) - && self.ticks < 1200 - && self.target.is_some_and(|p| { - job_site_profession(cx.w.block_name(p[0], p[1], p[2])).is_some() - && !claimed(cx.w, m.id, p) - }) - } - fn start(&mut self, m: &mut Mob, cx: &mut Cx) { - self.ticks = 0; - if let Some(p) = self.target { - let path = m.create_path_to(cx.w, p, 1); - m.nav_move_to_path(path, 0.5); - } - } - fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) { - m.nav_stop(); - self.target = None; - } - fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { - self.ticks += 1; - let Some(p) = self.target else { return }; - let c = [ - f64::from(p[0]) + 0.5, - f64::from(p[1]) + 0.5, - f64::from(p[2]) + 0.5, - ]; - if m.position - .distance_squared(horizon_core::geometry::Vec3::new(c[0], c[1], c[2])) - < 4.0 - { - take_job(m, p, cx.w, cx.events); - return; - } - if m.ai.nav.is_done() && self.ticks % 40 == 0 { - let path = m.create_path_to(cx.w, p, 1); - m.nav_move_to_path(path, 0.5); - } - } -} -/// `AssignProfessionFromJobSite`: claim the site, take its profession if -/// unemployed, and show the happy particles (entity event 14). -fn take_job(m: &mut Mob, p: [i32; 3], w: &MobWorld, events: &mut Vec) { - m.extra.home = Some(p); - if m.extra.variant2 == NONE - && let Some(profession) = job_site_profession(w.block_name(p[0], p[1], p[2])) - { - m.extra.variant2 = profession; - m.extra.trade = None; - } - particles_around(m, "happy_villager", events); -} /// `LivingEntity.addParticlesAroundSelf`: five particles about the body. pub fn particles_around(m: &mut Mob, kind: &'static str, events: &mut Vec) { let (w, h) = (f64::from(m.width()), f64::from(m.height())); @@ -253,8 +71,11 @@ pub enum Activity { Rest, } pub fn activity(m: &Mob, day_time: i64) -> Activity { + activity_at(m.is_baby(), day_time) +} +pub fn activity_at(baby: bool, day_time: i64) -> Activity { let t = day_time.rem_euclid(24000); - if m.is_baby() { + if baby { match t { 10..3000 | 6000..10000 => Activity::Idle, 3000..6000 | 10000..12000 => Activity::Play, @@ -269,192 +90,13 @@ pub fn activity(m: &Mob, day_time: i64) -> Activity { } } } -fn center(p: [i32; 3]) -> [f64; 3] { - [ - f64::from(p[0]) + 0.5, - f64::from(p[1]) + 0.5, - f64::from(p[2]) + 0.5, - ] -} -fn distance(m: &Mob, p: [i32; 3]) -> f64 { - let c = center(p); - m.position - .distance_squared(horizon_core::geometry::Vec3::new(c[0], c[1], c[2])) - .sqrt() -} -/// `AcquirePoi` for `HOME` (a free bed head) and `MEETING` (a bell), with -/// the happy particles on success; failed scans back off. -#[derive(Clone, Debug, Default)] -struct AcquireHome { - next_search: i32, -} -impl Goal for AcquireHome { - goal_clone!(); - fn flags(&self) -> u8 { - 0 - } - fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - if m.extra.bed.is_some() && m.extra.meeting.is_some() { - return false; - } - if self.next_search > 0 { - self.next_search -= 1; - return false; - } - let w = cx.w; - let mut found = false; - if m.extra.bed.is_none() - && let Some(p) = scan(m, w, |poi, p| { - poi == Poi::Bed - && !w - .others - .iter() - .any(|s| s.id != m.id && s.alive && s.bed == Some(p)) - }) - { - m.extra.bed = Some(p); - found = true; - } - if m.extra.meeting.is_none() - && !m.is_baby() - && let Some(p) = scan(m, w, |poi, _| poi == Poi::Bell) - { - m.extra.meeting = Some(p); - found = true; - } - if found { - particles_around(m, "happy_villager", cx.events); - } - self.next_search = if found { - 20 + m.random.next_int_bound(20).unwrap_or(0) - } else { - 200 + m.random.next_int_bound(200).unwrap_or(0) - }; - false - } -} -/// The schedule's walk targets (`SetWalkTargetFromBlockMemory`, -/// `StrollToPoi`, `StrollAroundPoi`), `WorkAtPoi` with restocking, and -/// `SleepInBed`. -#[derive(Clone, Debug, Default)] -struct Schedule { - cooldown: i32, - target: Option<[f64; 3]>, - to_site: bool, - last_work: i64, - ticks: i32, -} -impl Schedule { - fn anchor(m: &Mob, a: Activity) -> Option<([i32; 3], f64)> { - match a { - Activity::Work if m.extra.variant2 != NONE && m.extra.variant2 != NITWIT => { - m.extra.home.map(|p| (p, 9.0)) - } - Activity::Meet => m.extra.meeting.map(|p| (p, 6.0)), - Activity::Rest => m.extra.bed.map(|p| (p, 1.0)), - _ => None, - } - } -} -impl Goal for Schedule { - goal_clone!(); - fn flags(&self) -> u8 { - MOVE - } - fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - if sleeping(m) { - return false; - } - if self.cooldown > 0 { - self.cooldown -= 1; - return false; - } - let a = activity(m, cx.w.day_time); - let Some((p, close)) = Self::anchor(m, a) else { - return false; - }; - self.to_site = false; - let c = center(p); - self.target = if a == Activity::Rest || distance(m, p) > close { - self.to_site = true; - Some(c) - } else if m.random.next_int_bound(2).unwrap_or(0) == 0 && a == Activity::Work { - // StrollToPoi / WorkAtPoi. - self.to_site = true; - Some(c) - } else { - // StrollAroundPoi: somewhere near the site. - let r = &mut m.random; - let spread = if a == Activity::Meet { 6 } else { 4 }; - let mut d = || f64::from(r.next_int_bound(2 * spread + 1).unwrap_or(0) - spread); - Some([c[0] + d(), c[1], c[2] + d()]) - }; - self.cooldown = 40 + m.random.next_int_bound(80).unwrap_or(0); - true - } - fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - self.ticks < 400 - && !sleeping(m) - && Self::anchor(m, activity(m, cx.w.day_time)).is_some() - && !(m.ai.nav.is_done() && self.ticks > 20) - } - fn start(&mut self, m: &mut Mob, cx: &mut Cx) { - self.ticks = 0; - if let Some(t) = self.target { - m.nav_move_to(cx.w, t, 0.5); - } - } - fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) { - m.nav_stop(); - } - fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { - self.ticks += 1; - let a = activity(m, cx.w.day_time); - let Some((p, _)) = Self::anchor(m, a) else { - return; - }; - if !self.to_site { - return; - } - match a { - Activity::Work if distance(m, p) < 1.73 => { - // WorkAtPoi: every 300 ticks at most, half the time. - let now = cx.w.game_time; - m.look_at(center(p)); - if now - self.last_work >= 300 && m.random.next_int_bound(2).unwrap_or(1) == 0 { - self.last_work = now; - work(m, cx.w, cx.events); - } - m.nav_stop(); - } - Activity::Rest if distance(m, p) < 2.0 => start_sleeping(m, p, cx.w), - _ => {} - } - } -} -/// `WorkAtPoi.start`: the profession's work sound, and a restock when due. -fn work(m: &mut Mob, w: &MobWorld, events: &mut Vec) { - let profession = super::render::PROFESSIONS[m.extra.variant2 as usize % 15]; - events.push(MobEvent::SoundId( - format!("minecraft:entity.villager.work_{profession}"), - [m.position.x, m.position.y, m.position.z], - 1.0, - 1.0, - )); - let day = w.day_time.div_euclid(24000); - if let Some(t) = m.extra.trade.as_mut() - && t.should_restock(w.game_time, day) - { - t.restock(w.game_time); - } -} pub fn sleeping(m: &Mob) -> bool { matches!(m.species(), Species::Villager | Species::WanderingTrader) && m.extra.ints[1] != 0 } /// `LivingEntity.startSleeping`: lie in the bed (`setPosToBed`). -fn start_sleeping(m: &mut Mob, p: [i32; 3], w: &MobWorld) { +pub fn start_sleeping(m: &mut Mob, p: [i32; 3], w: &MobWorld) -> bool { if w.prop(p[0], p[1], p[2], "occupied") == Some("true") { - return; + return false; } m.extra.ints[1] = match w.prop(p[0], p[1], p[2], "facing") { Some("north") => 1, @@ -470,6 +112,7 @@ fn start_sleeping(m: &mut Mob, p: [i32; 3], w: &MobWorld) { f64::from(p[1]) + 0.6875, f64::from(p[2]) + 0.5, ); + true } /// `LivingEntity.stopSleeping` with `BedBlock.findStandUpPosition`: beside /// the bed where there is room, else on top of it. @@ -499,14 +142,6 @@ pub fn stop_sleeping(m: &mut Mob, w: &MobWorld) { } m.position.y = f64::from(p[1]) + 0.5625; } -/// While asleep the villager stays in the bed. -pub fn travel(m: &mut Mob) -> bool { - if !sleeping(m) { - return false; - } - m.velocity = horizon_core::geometry::Vec3::ZERO; - true -} /// `LivingEntityRenderer.sleepDirectionToRotation` and the bed's direction /// (the body is shifted back from the pillow by the standing eye height). pub fn sleep_pose(m: &Mob) -> Option<(f32, [f32; 2])> { @@ -518,69 +153,24 @@ pub fn sleep_pose(m: &Mob) -> Option<(f32, [f32; 2])> { _ => return None, }) } -/// `Villager.tick` / brain upkeep: the unhappy counter, and -/// `ResetProfession` / job site loss when the site's block is gone. +/// `Villager.tick`: the unhappy counter and the gossip decay; a sleeper +/// hurt or without its bed wakes up (`LivingEntity.hurtServer`, +/// `LivingEntity.checkBedExists`). The brain does the rest. pub fn ai_step(m: &mut Mob, w: &MobWorld) { if m.extra.ints[0] > 0 { m.extra.ints[0] -= 1; } if m.species() == Species::Villager { - let now = w.game_time; - let seen_golem = (i64::from(m.age) + i64::from(m.id)) % 200 == 0 - && w.others.iter().any(|s| { - s.species == Species::IronGolem - && s.alive - && (s.position.x - m.position.x).abs() <= 16.0 - && (s.position.y - m.position.y).abs() <= 16.0 - && (s.position.z - m.position.z).abs() <= 16.0 - }); - let e = ext_mut(m); - // Villager.maybeDecayGossip and the GolemSensor (every 200 ticks). - e.maybe_decay(now); - if seen_golem { - e.golem_until = now + 599; - } + ext_mut(m).maybe_decay(w.game_time); } - // WakeUp / LivingEntity.hurt: morning, a hit or a missing bed. if sleeping(m) { let bed_gone = m .extra .bed .is_none_or(|p| !w.block_name(p[0], p[1], p[2]).ends_with("_bed")); - if activity(m, w.day_time) != Activity::Rest || m.hurt_time > 0 || bed_gone { + if m.hurt_time > 0 || bed_gone { stop_sleeping(m, w); - } - } - // ValidateNearbyPoi for the bed and bell. - if m.age.is_multiple_of(20) { - let loaded = |p: [i32; 3]| w.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4)); - if let Some(p) = m.extra.bed - && loaded(p) - && !w.block_name(p[0], p[1], p[2]).ends_with("_bed") - { - m.extra.bed = None; - } - if let Some(p) = m.extra.meeting - && loaded(p) - && w.block_name(p[0], p[1], p[2]) != "minecraft:bell" - { - m.extra.meeting = None; - } - } - if m.species() != Species::Villager || !m.age.is_multiple_of(20) { - return; - } - let Some(p) = m.extra.home else { return }; - if !w.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4)) { - return; - } - if job_site_profession(w.block_name(p[0], p[1], p[2])).is_none() { - m.extra.home = None; - let fresh = m.extra.trade.as_ref().is_none_or(|t| t.xp == 0); - if m.extra.variant2 != NONE && m.extra.variant2 != NITWIT && fresh && m.extra.variant3 <= 1 - { - m.extra.variant2 = NONE; - m.extra.trade = None; + super::villager_brain::woken(m, w.game_time); } } } @@ -651,6 +241,8 @@ pub struct Ext { pub hurt_seen: i32, /// A zombie villager's cure under way. pub cure: Option, + /// The villager's brain, built at its first tick. + pub brain: Option>, } pub fn ext(m: &Mob) -> Option<&Ext> { m.extra.villager.as_deref() @@ -658,127 +250,75 @@ pub fn ext(m: &Mob) -> Option<&Ext> { pub fn ext_mut(m: &mut Mob) -> &mut Ext { m.extra.villager.get_or_insert_with(Box::default) } -fn raid_status(m: &Mob) -> u8 { +/// The raid package the villager follows (`RAID_NONE` ... `RAID_VICTORY`). +pub fn raid_status(m: &Mob) -> u8 { ext(m).map_or(RAID_NONE, |e| e.raid) } - -/// The raid packages of `VillagerGoalPackages`: in a raid villagers hide at -/// home (`LocateHidingPlace`), before one they gather at the bell and ring it -/// (`RingBell`), and after a victory they look for the sky to celebrate -/// (`MoveToSkySeeingSpot`, `CelebrateVillagersSurvivedRaid`). -#[derive(Clone, Debug, Default)] -struct RaidBehavior { - next_move: i32, +/// `ServerLevel.getRaidAt(blockPosition)` is a raid. +pub fn raid_nearby(m: &Mob) -> bool { + ext(m).is_some_and(|e| e.raid != RAID_NONE) } -impl Goal for RaidBehavior { - goal_clone!(); - fn flags(&self) -> u8 { - MOVE +/// The raid near the villager: `Some(true)` while a wave is on +/// (`hasFirstWaveSpawned && !isBetweenWaves`), `Some(false)` otherwise. +pub fn raid_state(m: &Mob) -> Option { + match ext(m).map_or(RAID_NONE, |e| e.raid) { + RAID_NONE => None, + RAID => Some(true), + _ => Some(false), } - fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { - raid_status(m) != RAID_NONE && !sleeping(m) - } - fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - self.can_use(m, cx) - } - fn start(&mut self, m: &mut Mob, _cx: &mut Cx) { - self.next_move = 0; - m.nav_stop(); - } - fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) { - m.nav_stop(); - } - fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { - self.next_move -= 1; - let p = m.position; - match raid_status(m) { - RAID => { - // LocateHidingPlace(24, 0.7, 1): back to the bed. - let Some(home) = m.extra.bed else { return }; - if distance(m, home) > 1.0 && (self.next_move <= 0 || m.ai.nav.is_done()) { - if distance(m, home) <= 24.0 { - m.nav_move_to(cx.w, center(home), 0.7); - } - self.next_move = 40; - } - } - PRE_RAID => { - // RingBell and SetWalkTargetFromBlockMemory(meeting, 0.75). - let Some(bell) = m.extra.meeting else { return }; - if distance(m, bell) > 2.0 && (self.next_move <= 0 || m.ai.nav.is_done()) { - m.nav_move_to(cx.w, center(bell), 0.75); - self.next_move = 40; - } - if distance(m, bell) < 3.0 - && m.random.next_float() > 0.95 - && cx.w.block_name(bell[0], bell[1], bell[2]) == "minecraft:bell" - { - cx.events.push(MobEvent::SoundId( - "minecraft:block.bell.use".into(), - center(bell), - 2.0, - 1.0, - )); - } - } - RAID_VICTORY => { - let (x, y, z) = (p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32); - if cx.w.can_see_sky(x, y, z) { - // CelebrateVillagersSurvivedRaid.tick. - if m.random.next_int_bound(100).unwrap_or(1) == 0 { - m.voice("entity.villager.celebrate", cx.events); - } - if m.random.next_int_bound(200).unwrap_or(1) == 0 { - let color = m.random.next_int_bound(16).unwrap_or(0) as usize; - let flight = m.random.next_int_bound(3).unwrap_or(0) as u8; - cx.events.push(MobEvent::Firework { - at: [p.x, m.eye_y(), p.z], - color, - flight, - }); - } - m.nav_stop(); - } else if self.next_move <= 0 || m.ai.nav.is_done() { - // MoveToSkySeeingSpot: a random spot with a view of the sky. - for _ in 0..5 { - if let Some(at) = m.land_random_pos(cx.w, 15, 7) - && cx.w.can_see_sky( - at[0].floor() as i32, - at[1].floor() as i32, - at[2].floor() as i32, - ) - { - m.nav_move_to(cx.w, at, 0.5); - break; - } - } - self.next_move = 40; - } - } - _ => {} +} +/// `Villager.getVillagerXp`. +pub fn xp(m: &Mob) -> i32 { + m.extra.trade.as_ref().map_or(0, |t| t.xp) +} +/// `Villager.setVillagerData(withProfession)`: a new profession forgets the +/// offers. +pub fn set_profession(m: &mut Mob, profession: u8) { + if m.extra.variant2 != profession { + m.extra.variant2 = profession; + if let Some(t) = m.extra.trade.as_mut() { + t.offers.clear(); } } } +/// `VillagerProfession.workSound`. +pub fn work_sound(profession: u8) -> Option<&'static str> { + Some(match super::render::PROFESSIONS[profession as usize % 15] { + "armorer" => "entity.villager.work_armorer", + "butcher" => "entity.villager.work_butcher", + "cartographer" => "entity.villager.work_cartographer", + "cleric" => "entity.villager.work_cleric", + "farmer" => "entity.villager.work_farmer", + "fisherman" => "entity.villager.work_fisherman", + "fletcher" => "entity.villager.work_fletcher", + "leatherworker" => "entity.villager.work_leatherworker", + "librarian" => "entity.villager.work_librarian", + "mason" => "entity.villager.work_mason", + "shepherd" => "entity.villager.work_shepherd", + "toolsmith" => "entity.villager.work_toolsmith", + "weaponsmith" => "entity.villager.work_weaponsmith", + _ => return None, + }) +} +/// A `CropBlock` at `p`. +pub fn crop(w: &MobWorld, p: [i32; 3]) -> bool { + matches!( + w.block_name(p[0], p[1], p[2]), + "minecraft:wheat" | "minecraft:carrots" | "minecraft:potatoes" | "minecraft:beetroots" + ) +} +/// `CropBlock.isMaxAge` for the block at `p`. +pub fn ripe_crop(w: &MobWorld, p: [i32; 3]) -> bool { + let max = match w.block_name(p[0], p[1], p[2]) { + "minecraft:wheat" | "minecraft:carrots" | "minecraft:potatoes" => "7", + "minecraft:beetroots" => "3", + _ => return false, + }; + w.prop(p[0], p[1], p[2], "age") == Some(max) +} -/// `GiveGiftToHero`: a villager that sees a hero of the village walks up and -/// throws a gift of its profession, every so often. -#[derive(Clone, Debug)] -struct GiftToHero { - until_next: i32, - started: i64, - given: bool, -} -impl Default for GiftToHero { - fn default() -> Self { - Self { - until_next: 600, - started: 0, - given: false, - } - } -} /// The gift loot table of a villager (`GiveGiftToHero.getLootTableToThrow`). -fn gift_table(m: &Mob) -> String { +pub fn gift_table(m: &Mob) -> String { if m.is_baby() { return "minecraft:gameplay/hero_of_the_village/baby_gift".into(); } @@ -789,66 +329,6 @@ fn gift_table(m: &Mob) -> String { }; format!("minecraft:gameplay/hero_of_the_village/{name}_gift") } -fn hero_in_view(m: &mut Mob, cx: &Cx) -> bool { - let Some(p) = &cx.w.player else { return false }; - p.hero - && p.alive - && !p.spectator - && m.position.distance_squared(p.position) <= 16.0 * 16.0 - && m.sees(cx.w, Who::Player) -} -impl Goal for GiftToHero { - goal_clone!(); - fn flags(&self) -> u8 { - MOVE | LOOK - } - fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - if !hero_in_view(m, cx) || sleeping(m) { - return false; - } - if self.until_next > 0 { - self.until_next -= 1; - return false; - } - true - } - fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - hero_in_view(m, cx) && !self.given - } - fn start(&mut self, m: &mut Mob, cx: &mut Cx) { - self.given = false; - self.started = cx.w.game_time; - if let Some(p) = &cx.w.player { - m.look_at(p.eye); - } - } - fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) { - self.until_next = 600 + m.random.next_int_bound(6001).unwrap_or(0); - m.nav_stop(); - } - fn every_tick(&self) -> bool { - true - } - fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { - let Some(p) = cx.w.player.clone() else { return }; - m.look_at(p.eye); - let near = m.position.distance_squared(p.position) < 25.0; - if near { - if cx.w.game_time - self.started > 20 { - cx.events.push(MobEvent::ThrowGift { - table: gift_table(m), - from: [m.position.x, m.eye_y() - 0.3, m.position.z], - to: [p.position.x, p.position.y, p.position.z], - }); - self.given = true; - } - m.nav_stop(); - } else if m.ai.nav.is_done() { - m.nav_move_to(cx.w, [p.position.x, p.position.y, p.position.z], 0.5); - } - } -} - // ---- Gossip, food, breeding and golems. /// `VillagerFood` nutrition (`DataComponents.VILLAGER_FOOD`). @@ -1074,191 +554,6 @@ pub fn read_nbt(m: &mut Mob, tag: &horizon_world::nbt::Tag) { } } -/// `InteractWith(VILLAGER)`, `TradeWithVillager` and `VillagerMakeLove` while -/// idle, and `SocializeAtBell` at the meeting: walk up to a villager, swap -/// gossip and food, and make a baby with a willing partner. -#[derive(Clone, Debug, Default)] -struct Social { - target: Option, - breed: bool, - ticks: i32, - cooldown: i32, - birth_at: i64, -} -impl Social { - fn pick(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - let breedable = can_breed(m); - let id = m.id; - let nearest = - cx.w.nearby(m.position, 8.0, move |s| { - s.species == Species::Villager && s.id != id - }) - .filter(|s| m.position.distance_squared(s.position) <= 64.0) - .map(|s| (s.id, s.in_love)) - .collect::>(); - let visible: Vec<(u32, bool)> = nearest - .into_iter() - .filter(|(i, _)| m.sees(cx.w, Who::Mob(*i))) - .collect(); - let Some(&(target, partner_willing)) = visible.first() else { - return false; - }; - // RunOne weights: interact 2, breed 1 (when both are willing). - let breed = breedable && partner_willing && m.random.next_int_bound(3).unwrap_or(0) == 0; - self.target = Some(target); - self.breed = breed; - true - } -} -impl Goal for Social { - goal_clone!(); - fn flags(&self) -> u8 { - MOVE | LOOK - } - fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - if m.is_baby() || sleeping(m) || raid_status(m) != RAID_NONE { - return false; - } - if self.cooldown > 0 { - self.cooldown -= 1; - return false; - } - match activity(m, cx.w.day_time) { - Activity::Idle => self.pick(m, cx), - Activity::Meet => { - // SocializeAtBell: one tick in a hundred, near the bell. - let near_bell = m.extra.meeting.is_some_and(|p| distance(m, p) < 4.0); - near_bell && m.random.next_int_bound(100).unwrap_or(1) == 0 && { - let ok = self.pick(m, cx); - self.breed = false; - ok - } - } - _ => false, - } - } - fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - let Some(t) = self.target else { return false }; - let Some(s) = cx.w.seen(t) else { return false }; - if !s.alive || sleeping(m) || raid_status(m) != RAID_NONE { - return false; - } - if self.breed { - self.ticks < 350 && can_breed(m) && s.in_love - } else { - self.ticks < 60 - } - } - fn start(&mut self, m: &mut Mob, cx: &mut Cx) { - self.ticks = 0; - self.birth_at = 0; - if let Some(s) = self.target.and_then(|t| cx.w.seen(t)) { - let at = [s.position.x, s.position.y, s.position.z]; - m.nav_move_to(cx.w, at, 0.5); - } - } - fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) { - m.nav_stop(); - self.target = None; - self.cooldown = 20 + m.random.next_int_bound(40).unwrap_or(0); - } - fn every_tick(&self) -> bool { - true - } - fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { - self.ticks += 1; - let Some(t) = self.target else { return }; - let Some(s) = cx.w.seen(t) else { return }; - let (at, eye) = ([s.position.x, s.position.y, s.position.z], s.eye_y); - m.look_at([at[0], eye, at[2]]); - if m.position.distance_squared(s.position) > 5.0 { - if m.ai.nav.is_done() && self.ticks % 10 == 1 { - m.nav_move_to(cx.w, at, 0.5); - } - return; - } - m.nav_stop(); - if !self.breed { - cx.events.push(MobEvent::VillagerMeet { - mob: m.id, - other: t, - }); - return; - } - let now = cx.w.game_time; - if self.birth_at == 0 { - self.birth_at = now + 275 + i64::from(m.random.next_int_bound(50).unwrap_or(0)); - } - if now >= self.birth_at { - cx.events.push(MobEvent::VillagerBirth { - parent: m.id, - partner: t, - }); - self.ticks = 1000; - } else if m.random.next_int_bound(35).unwrap_or(1) == 0 { - for p in [m.position, s.position] { - cx.events.push(MobEvent::Particles { - kind: "heart", - at: [p.x, p.y + 1.8, p.z], - count: 1, - }); - } - } - } -} - -/// `VillagerPanicTrigger.tick`: a frightened villager calls for a golem -/// every five seconds. -#[derive(Clone, Debug, Default)] -struct GolemCall; -/// `VillagerHostilesSensor`: how close each hostile must be to scare. -fn hostile_range(s: Species) -> f64 { - match s { - Species::Drowned - | Species::Husk - | Species::Vex - | Species::Zombie - | Species::ZombieVillager => 8.0, - Species::Evoker | Species::Illusioner | Species::Ravager => 12.0, - Species::Pillager => 15.0, - Species::Vindicator | Species::Zoglin => 10.0, - _ => 0.0, - } -} -fn frightened(m: &Mob, cx: &Cx) -> bool { - // HURT_BY lasts 100 ticks. - let hurt = m.ai.last_hurt_by.is_some() && m.age as i32 - m.ai.last_hurt_by_time <= 100; - hurt || cx.w.others.iter().any(|s| { - s.alive && { - let r = hostile_range(s.species); - r > 0.0 && s.position.distance_squared(m.position) <= r * r - } - }) -} -impl Goal for GolemCall { - goal_clone!(); - fn flags(&self) -> u8 { - 0 - } - fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - !m.is_baby() && frightened(m, cx) - } - fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - self.can_use(m, cx) - } - fn every_tick(&self) -> bool { - true - } - fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { - if cx.w.game_time % 100 == 0 { - cx.events.push(MobEvent::GolemCheck { - mob: m.id, - needed: 3, - }); - } - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs new file mode 100644 index 000000000..beb877bb1 --- /dev/null +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -0,0 +1,4078 @@ +//! The villager's `Brain` (`Villager.BRAIN_PROVIDER` and +//! `VillagerGoalPackages`), ported behaviour for behaviour: memories that +//! expire, the nine sensors and their scan rates, activities from the +//! `villager_activity` timeline, 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 and POI scans; +//! the mob's own random drives positions, sounds and jumps. `RunOne` and the +//! other `GateBehavior`s shuffle with a random of their own, seeded with +//! `Brain::shuffle_seed` when the brain is built. +use super::{ + Mob, MobEvent, MobWorld, Seen, Species, Who, + path::{Path, PathNode}, +}; +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) or a +/// block (`BlockPosTracker`, at its centre or at a given point). +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Tracker { + Entity(Who, bool), + Block([i32; 3]), + Point([f64; 3]), +} +impl Tracker { + /// `currentPosition`. + pub 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, + ]), + Tracker::Point(v) => Some(v), + } + } + /// `currentBlockPosition`. + pub fn block(&self, w: &MobWorld) -> Option<[i32; 3]> { + match *self { + Tracker::Entity(who, _) => w.target_info(who).map(|t| block_of(t.position)), + Tracker::Block(p) => Some(p), + Tracker::Point(v) => Some([ + v[0].floor() as i32, + v[1].floor() as i32, + v[2].floor() as i32, + ]), + } + } +} +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 { + fn block(p: [i32; 3], speed: f32, close: i32) -> Self { + Self { + target: Tracker::Block(p), + speed, + close, + } + } + /// `new WalkTarget(Vec3, ...)`: the block containing the point. + fn point(p: [f64; 3], speed: f32, close: i32) -> Self { + Self::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 a villager's brain registers. +#[derive(Clone, Debug, Default)] +pub struct Memories { + pub home: Slot<[i32; 3]>, + pub job_site: Slot<[i32; 3]>, + pub potential_job_site: Slot<[i32; 3]>, + pub meeting_point: Slot<[i32; 3]>, + pub secondary_job_site: Slot>, + pub mobs: Slot>, + pub visible_mobs: Slot, + pub visible_villager_babies: Slot>, + pub nearest_players: Slot>, + pub nearest_visible_player: Slot, + pub nearest_visible_targetable_player: Slot, + pub nearest_visible_targetable_players: Slot>, + pub walk_target: Slot, + pub look_target: Slot, + pub interaction_target: Slot, + pub breed_target: Slot, + /// `PATH`: the navigation's path (its target). + pub path: Slot, + pub doors_to_close: Slot>, + pub nearest_bed: Slot<[i32; 3]>, + /// `HURT_BY`: the damage (its game time). + pub hurt_by: Slot, + pub hurt_by_entity: Slot, + pub nearest_hostile: Slot, + pub hiding_place: Slot<[i32; 3]>, + pub heard_bell_time: Slot, + pub cant_reach_walk_target_since: Slot, + pub golem_detected_recently: Slot, + pub last_slept: Slot, + pub last_woken: Slot, + pub last_worked_at_poi: Slot, +} +impl Memories { + fn tick(&mut self) { + self.home.tick(); + self.job_site.tick(); + self.potential_job_site.tick(); + self.meeting_point.tick(); + self.secondary_job_site.tick(); + self.mobs.tick(); + self.visible_mobs.tick(); + self.visible_villager_babies.tick(); + self.nearest_players.tick(); + self.nearest_visible_player.tick(); + self.nearest_visible_targetable_player.tick(); + self.nearest_visible_targetable_players.tick(); + self.walk_target.tick(); + self.look_target.tick(); + self.interaction_target.tick(); + self.breed_target.tick(); + self.path.tick(); + self.doors_to_close.tick(); + self.nearest_bed.tick(); + self.hurt_by.tick(); + self.hurt_by_entity.tick(); + self.nearest_hostile.tick(); + self.hiding_place.tick(); + self.heard_bell_time.tick(); + self.cant_reach_walk_target_since.tick(); + self.golem_detected_recently.tick(); + self.last_slept.tick(); + self.last_woken.tick(); + self.last_worked_at_poi.tick(); + } + /// `Brain.pack`: the memories with a codec, which a rebuilt brain keeps. + fn pack(&self) -> Memories { + Memories { + home: self.home.clone(), + job_site: self.job_site.clone(), + potential_job_site: self.potential_job_site.clone(), + meeting_point: self.meeting_point.clone(), + golem_detected_recently: self.golem_detected_recently.clone(), + last_slept: self.last_slept.clone(), + last_woken: self.last_woken.clone(), + last_worked_at_poi: self.last_worked_at_poi.clone(), + ..Memories::default() + } + } +} + +/// `Activity`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Act { + Core, + Idle, + Work, + Play, + Rest, + Meet, + Panic, + Raid, + PreRaid, + Hide, +} +impl Act { + pub fn name(self) -> &'static str { + match self { + Act::Core => "core", + Act::Idle => "idle", + Act::Work => "work", + Act::Play => "play", + Act::Rest => "rest", + Act::Meet => "meet", + Act::Panic => "panic", + Act::Raid => "raid", + Act::PreRaid => "pre_raid", + Act::Hide => "hide", + } + } + /// The bucket order of `HashMap` (16 buckets, the hash + /// of the name; equal buckets keep the villager's insertion order). + fn slot(self) -> u8 { + match self { + Act::Play => 0, + Act::Core => 1, + Act::Rest => 2, + Act::Hide => 3, + Act::Meet => 4, + Act::Idle => 5, + Act::PreRaid => 6, + Act::Work => 7, + Act::Panic => 8, + Act::Raid => 9, + } + } +} + +/// The scan rate of each sensor, in `BRAIN_PROVIDER` order. +const SENSOR_RATES: [i64; 9] = [20, 20, 20, 20, 20, 20, 20, 40, 200]; + +/// A villager's brain. +#[derive(Clone, Debug)] +pub struct Brain { + pub mem: Memories, + sensors: [i64; 9], + /// The active non-core activity (`CORE` is always active). + pub activity: Act, + default_activity: Act, + last_schedule_update: i64, + list: Vec, + pub shuffle_seed: i64, + baby: bool, + /// Whether the nearest-bed sensor's batch cache is used (`NearestBedSensor`). + bed_cache: Vec<([i32; 3], i64)>, +} +#[derive(Clone, Debug)] +struct Entry { + prio: i32, + act: Act, + b: B, +} + +fn brain(m: &Mob) -> Option<&Brain> { + super::villager::ext(m).and_then(|e| e.brain.as_deref()) +} +fn brain_mut(m: &mut Mob) -> &mut Brain { + let (baby, farmer) = (m.is_baby(), super::villager::is_farmer(m)); + let e = super::villager::ext_mut(m); + e.brain + .get_or_insert_with(|| Box::new(Brain::new(baby, 0, farmer))) +} +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) +} + +impl Brain { + fn new(baby: bool, shuffle_seed: i64, farmer: bool) -> Self { + let mut b = Brain { + mem: Memories::default(), + sensors: [0; 9], + activity: Act::Idle, + default_activity: Act::Idle, + last_schedule_update: -9999, + list: Vec::new(), + shuffle_seed, + baby, + bed_cache: Vec::new(), + }; + b.list = packages(baby, shuffle_seed, farmer); + b + } + fn requirements_met(&self, a: Act) -> bool { + match a { + Act::Work => !self.baby && self.mem.job_site.present(), + Act::Play => self.baby, + Act::Meet => self.mem.meeting_point.present(), + Act::Core + | Act::Idle + | Act::Rest + | Act::Panic + | Act::Raid + | Act::PreRaid + | Act::Hide => true, + } + } + pub fn is_active(&self, a: Act) -> bool { + a == Act::Core || a == self.activity + } + /// `setActiveActivityIfPossible`. + pub fn set_active_if_possible(&mut self, a: Act) { + if self.requirements_met(a) { + self.activity = a; + } else { + self.activity = self.default_activity; + } + } + /// `updateActivityFromSchedule`. + fn update_from_schedule(&mut self, game_time: i64, day_time: i64) { + if game_time - self.last_schedule_update > 20 { + self.last_schedule_update = game_time; + let scheduled = schedule(self.baby, day_time); + if !self.is_active(scheduled) { + self.set_active_if_possible(scheduled); + } + } + } +} +/// The `villager_activity` and `baby_villager_activity` timelines. +fn schedule(baby: bool, day_time: i64) -> Act { + match super::villager::activity_at(baby, day_time) { + super::villager::Activity::Idle => Act::Idle, + super::villager::Activity::Work => Act::Work, + super::villager::Activity::Play => Act::Play, + super::villager::Activity::Meet => Act::Meet, + super::villager::Activity::Rest => Act::Rest, + } +} + +/// `Brain.Provider.makeBrain` and `Villager.registerBrainGoals`: a new brain +/// from the packed memories (the sensors' first scans are delayed by draws +/// from the mob's random), on the timeline's activity. +fn make_brain(m: &mut Mob, packed: Memories, shuffle_seed: i64, w_times: (i64, i64)) -> Brain { + let mut b = Brain::new(m.is_baby(), shuffle_seed, super::villager::is_farmer(m)); + for (i, rate) in SENSOR_RATES.iter().enumerate() { + b.sensors[i] = i64::from(m.random.next_int_bound(*rate as i32).unwrap_or(0)); + } + b.mem = packed; + b.update_from_schedule(w_times.0, w_times.1); + b +} + +/// Builds the villager's brain as its constructor does, at this game time: +/// the memories it remembers (job site, bed, bell) come from the mob. +pub fn init(m: &mut Mob, game_time: i64, day_time: i64, shuffle_seed: i64) { + let mut packed = Memories::default(); + packed.job_site.set_opt(m.extra.home); + packed.home.set_opt(m.extra.bed); + packed.meeting_point.set_opt(m.extra.meeting); + if let Some(t) = super::villager::ext(m).and_then(|e| e.last_slept) { + packed.last_slept.set(t); + } + let b = make_brain(m, packed, shuffle_seed, (game_time, day_time)); + super::villager::ext_mut(m).brain = Some(Box::new(b)); +} + +/// 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, + /// `Villager.refreshBrain` was asked for. + refresh: bool, +} + +/// `Brain.tick` (from `Villager.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, w.game_time, w.day_time, seed); + } + // forgetOutdatedMemories + mem(m).tick(); + tick_sensors(m, w, lr); + let mut list = std::mem::take(&mut brain_mut(m).list); + let mut cx = Bx { + w, + lr, + events, + now: w.game_time, + refresh: false, + }; + // The brain whose behaviours these are: after a refresh they keep running + // against the new brain's memories, gated by the old brain's activities. + let mut old_activity: Option = None; + let mut refreshed = false; + for i in 0..list.len() { + let active = match old_activity { + Some(a) => list[i].act == Act::Core || list[i].act == a, + None => brain_mut(m).is_active(list[i].act), + }; + if active && !list[i].b.running() { + list[i].b.try_start(m, &mut cx); + if cx.refresh { + cx.refresh = false; + old_activity = Some(brain_mut(m).activity); + refresh(m, &mut list, i, &mut cx); + refreshed = true; + } + } + } + for e in list.iter_mut() { + if e.b.running() { + e.b.tick_or_stop(m, &mut cx); + } + } + if !refreshed { + brain_mut(m).list = list; + } + sync(m, w.game_time); +} + +/// `Villager.refreshBrain`: stop every running behaviour, then rebuild the +/// brain from the remembered memories. +fn refresh(m: &mut Mob, list: &mut [Entry], current: usize, cx: &mut Bx) { + for (i, e) in list.iter_mut().enumerate() { + if i != current && e.b.running() { + e.b.do_stop(m, cx); + } + } + let b = brain_mut(m); + let packed = b.mem.pack(); + let seed = b.shuffle_seed; + let nb = make_brain(m, packed, seed, (cx.w.game_time, cx.w.day_time)); + super::villager::ext_mut(m).brain = Some(Box::new(nb)); +} + +/// Mirrors the remembered positions onto the mob (saved, seen by others), +/// and the sleep and golem memories onto `villager::Ext`. +fn sync(m: &mut Mob, now: i64) { + let (job, home, meeting, slept, golem) = { + let b = brain_mut(m); + ( + b.mem.job_site.value(), + b.mem.home.value(), + b.mem.meeting_point.value(), + b.mem.last_slept.value(), + b.mem + .golem_detected_recently + .get() + .map(|_| now + b.mem.golem_detected_recently.ttl + 1), + ) + }; + m.extra.home = job; + m.extra.bed = home; + m.extra.meeting = meeting; + let e = super::villager::ext_mut(m); + e.last_slept = slept; + e.golem_until = golem.unwrap_or(0); +} + +// ---- Sensors ------------------------------------------------------------ + +fn tick_sensors(m: &mut Mob, w: &MobWorld, lr: &mut LegacyRandom) { + for i in 0..9 { + let fire = { + let b = brain_mut(m); + b.sensors[i] -= 1; + if b.sensors[i] <= 0 { + b.sensors[i] = SENSOR_RATES[i]; + true + } else { + false + } + }; + if !fire { + continue; + } + match i { + 0 => sense_living(m, w), + 1 => sense_players(m, w), + 2 => {} + 3 => sense_bed(m, w, lr), + 4 => sense_hurt(m, w), + 5 => sense_hostiles(m, w), + 6 => sense_babies(m, w), + 7 => sense_secondary(m, w), + _ => sense_golem(m, w), + } + } +} +const FOLLOW_RANGE: f64 = 16.0; +/// `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 { + match who { + Who::Player => m.can_see_player(w, FOLLOW_RANGE), + Who::Mob(id) => { + let Some(s) = w.seen(id) else { return false }; + s.alive && m.distance_sqr(s.position) <= FOLLOW_RANGE * FOLLOW_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 { + if let Some(v) = mem_ref(m).and_then(|mm| mm.visible_mobs.get()) { + if let Some(&(_, r)) = v.cache.iter().find(|(k, _)| *k == who) { + return r; + } + } else { + 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 Some(list) = mem_ref(m) + .and_then(|mm| mm.visible_mobs.get()) + .map(|v| v.list.contains(&who)) + else { + return false; + }; + list && 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, FOLLOW_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()); +} +/// `NearestBedSensor`: babies remember the nearest reachable bed, trying +/// at most four beds a scan and skipping the ones tried lately. +fn sense_bed(m: &mut Mob, w: &MobWorld, lr: &mut LegacyRandom) { + if !m.is_baby() { + return; + } + let last_update = w.game_time + i64::from(lr.next_int_bound(20).unwrap_or(0)); + let homes = homes_in_range(m, w, 48); + let mut cache = std::mem::take(&mut brain_mut(m).bed_cache); + let mut tried = 0; + let mut targets = Vec::new(); + for p in homes { + if cache.iter().any(|(q, _)| *q == p) { + continue; + } + tried += 1; + if tried >= 5 { + continue; + } + cache.push((p, last_update + 40)); + targets.push(p); + } + let path = if targets.is_empty() { + None + } else { + m.create_path_to_any(w, &targets, 1) + }; + if let Some(path) = path.filter(|p| p.reached) { + mem(m).nearest_bed.set(path.target); + } else if tried < 5 { + cache.retain(|(_, until)| *until >= last_update); + } + brain_mut(m).bed_cache = cache; +} +/// `HurtBySensor`: the last damage (forgotten 40 ticks after) and who did it. +fn sense_hurt(m: &mut Mob, w: &MobWorld) { + // LivingEntity.getLastDamageSource: forgotten 40 ticks after the hit. + let age = i64::from(m.age); + let last = m + .last_damage + .as_ref() + .filter(|(_, t)| age - t <= 40) + .map(|(d, t)| (d.attacker, *t)); + let mm = mem(m); + if let Some((by, t)) = last { + mm.hurt_by.set(t); + 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(); + } +} +/// `VillagerHostilesSensor.ACCEPTABLE_DISTANCE_FROM_HOSTILES`. +fn hostile_distance(s: Species) -> Option { + Some(match s { + Species::Drowned + | Species::Husk + | Species::Vex + | Species::Zombie + | Species::ZombieVillager => 8.0, + Species::Evoker | Species::Illusioner | Species::Ravager => 12.0, + Species::Pillager => 15.0, + Species::Vindicator | Species::Zoglin => 10.0, + _ => return None, + }) +} +fn sense_hostiles(m: &mut Mob, w: &MobWorld) { + let hostile = find_closest(m, w, |m, who| { + let Who::Mob(id) = who else { return false }; + let Some(s) = w.seen(id) else { return false }; + hostile_distance(s.species).is_some_and(|d| m.distance_sqr(s.position) <= f64::from(d * d)) + }); + mem(m).nearest_hostile.set_opt(hostile); +} +fn sense_babies(m: &mut Mob, w: &MobWorld) { + let list = mem_ref(m) + .and_then(|mm| mm.visible_mobs.get()) + .map(|v| v.list.clone()) + .unwrap_or_default(); + let mut babies = Vec::new(); + for who in list { + let Who::Mob(id) = who else { continue }; + if w.seen(id) + .is_some_and(|s| s.species == Species::Villager && s.baby) + && visible_test(m, w, who) + { + babies.push(who); + } + } + mem(m).visible_villager_babies.set_list(babies); +} +/// `SecondaryPoiSensor`: a farmer's farmland within four blocks. +fn sense_secondary(m: &mut Mob, w: &MobWorld) { + let mut sites = Vec::new(); + if super::villager::is_farmer(m) { + let c = block_of(m.position); + for x in -4..=4 { + for y in -2..=2 { + for z in -4..=4 { + let p = [c[0] + x, c[1] + y, c[2] + z]; + if w.block_name(p[0], p[1], p[2]) == "minecraft:farmland" { + sites.push(p); + } + } + } + } + } + mem(m).secondary_job_site.set_list(sites); +} +/// `GolemSensor`. +fn sense_golem(m: &mut Mob, w: &MobWorld) { + let golem = mem_ref(m) + .and_then(|mm| mm.mobs.get()) + .is_some_and(|list| { + list.iter().any(|who| { + matches!(who, Who::Mob(id) if w.seen(*id).is_some_and(|s| s.species == Species::IronGolem)) + }) + }); + if golem { + mem(m).golem_detected_recently.set_ttl(true, 599); + } +} + +// ---- Behaviours --------------------------------------------------------- + +/// `Behavior`'s bookkeeping: running, and until when. +#[derive(Clone, 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); + } +} + +/// The POI types villagers use. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Poi { + /// A job site, by profession index. + Job(u8), + Home, + Meeting, +} +impl Poi { + fn max_tickets(self) -> usize { + match self { + Poi::Meeting => 32, + _ => 1, + } + } + fn valid_range(self) -> i32 { + match self { + Poi::Meeting => 6, + _ => 1, + } + } +} +/// The POI a block state is (`PoiTypes`): job site blocks, bed heads, bells. +pub fn poi_at(w: &MobWorld, x: i32, y: i32, z: i32) -> Option { + let name = w.block_name(x, y, z); + if name == "minecraft:bell" { + return Some(Poi::Meeting); + } + if name.ends_with("_bed") { + return (w.prop(x, y, z, "part") == Some("head")).then_some(Poi::Home); + } + super::villager::job_site_profession(name).map(Poi::Job) +} +/// Which POI types a predicate accepts. +#[derive(Clone, Copy, Debug, PartialEq)] +enum PoiFilter { + /// `VillagerProfession.heldJobSite` of the current profession. + Held, + /// `acquirableJobSite` of the current profession. + Acquirable, + Home, + Meeting, +} +fn poi_matches(m: &Mob, f: PoiFilter, p: Poi) -> bool { + let profession = m.extra.variant2; + let employed = profession != super::villager::NONE && profession != super::villager::NITWIT; + match (f, p) { + (PoiFilter::Held, Poi::Job(j)) => employed && j == profession, + (PoiFilter::Acquirable, Poi::Job(j)) => { + if profession == super::villager::NONE { + true + } else { + employed && j == profession + } + } + (PoiFilter::Home, Poi::Home) | (PoiFilter::Meeting, Poi::Meeting) => true, + _ => false, + } +} +/// Tickets taken on a POI: by this villager's memories and by others'. +fn tickets(m: &Mob, w: &MobWorld, p: [i32; 3]) -> usize { + let mut n = 0; + if let Some(mm) = mem_ref(m) { + for s in [ + &mm.job_site, + &mm.potential_job_site, + &mm.home, + &mm.meeting_point, + ] { + if s.get() == Some(&p) { + n += 1; + } + } + } + for o in w.others { + if o.id != m.id && o.alive && o.species == Species::Villager { + for q in [o.job, o.bed, o.potential_job, o.meeting] { + if q == Some(p) { + n += 1; + } + } + } + } + n +} +/// `PoiManager.getInRange` with `HAS_SPACE`, nearest first (`distSqr` to the +/// block, ties in scan order), filtered by `accept`. +fn pois_in_range( + m: &Mob, + w: &MobWorld, + f: PoiFilter, + radius: i32, + mut accept: impl FnMut([i32; 3]) -> bool, +) -> Vec<(Poi, [i32; 3])> { + let c = block_of(m.position); + let mut found = Vec::new(); + let r2 = i64::from(radius) * i64::from(radius); + let (cx, cz) = (c[0] >> 4, c[2] >> 4); + let chunks = radius.div_euclid(16) + 1; + let y0 = (c[1] - radius).max(crate::chunk::MIN_Y); + let y1 = (c[1] + radius).min(crate::chunk::MIN_Y + crate::chunk::HEIGHT - 1); + for qz in cz - chunks..=cz + chunks { + for qx in cx - chunks..=cx + chunks { + if !w.world.chunks.contains_key(&(qx, qz)) { + continue; + } + for y in y0..=y1 { + for z in qz * 16..qz * 16 + 16 { + for x in qx * 16..qx * 16 + 16 { + if (x - c[0]).abs() > radius || (z - c[2]).abs() > radius { + continue; + } + let d = i64::from(x - c[0]).pow(2) + + i64::from(y - c[1]).pow(2) + + i64::from(z - c[2]).pow(2); + if d > r2 { + continue; + } + let state = w.world.block(x, y, z); + if w.facts.is_air(state) { + continue; + } + let Some(poi) = poi_at(w, x, y, z) else { + continue; + }; + if !poi_matches(m, f, poi) { + continue; + } + let p = [x, y, z]; + if tickets(m, w, p) >= poi.max_tickets() { + continue; + } + if accept(p) { + found.push((poi, p)); + } + } + } + } + } + } + found.sort_by_key(|(_, p)| { + i64::from(p[0] - c[0]).pow(2) + + i64::from(p[1] - c[1]).pow(2) + + i64::from(p[2] - c[2]).pow(2) + }); + found +} +/// `PoiManager.exists(pos, predicate)`. +fn poi_exists(m: &Mob, w: &MobWorld, p: [i32; 3], f: PoiFilter) -> bool { + poi_at(w, p[0], p[1], p[2]).is_some_and(|poi| poi_matches(m, f, poi)) +} +/// `BlockPos.closerToCenterThan(position, d)`. +fn closer_to_center(p: [i32; 3], at: Vec3, d: f64) -> bool { + let c = Vec3::new( + f64::from(p[0]) + 0.5, + f64::from(p[1]) + 0.5, + f64::from(p[2]) + 0.5, + ); + c.distance_squared(at) < d * d +} +fn manhattan(a: [i32; 3], b: [i32; 3]) -> i32 { + (a[0] - b[0]).abs() + (a[1] - b[1]).abs() + (a[2] - b[2]).abs() +} +/// The village sections: sections holding a taken village POI. +fn village_sections(m: &Mob, w: &MobWorld) -> Vec<[i32; 3]> { + let mut out = Vec::new(); + let mut add = |p: [i32; 3]| { + let s = [p[0] >> 4, p[1] >> 4, p[2] >> 4]; + if !out.contains(&s) { + out.push(s); + } + }; + if let Some(mm) = mem_ref(m) { + for s in [ + &mm.job_site, + &mm.potential_job_site, + &mm.home, + &mm.meeting_point, + ] { + if let Some(&p) = s.get() + && poi_at(w, p[0], p[1], p[2]).is_some() + { + add(p); + } + } + } + for o in w.others { + if o.alive && o.species == Species::Villager { + for p in [o.job, o.bed, o.potential_job, o.meeting] + .into_iter() + .flatten() + { + if poi_at(w, p[0], p[1], p[2]).is_some() { + add(p); + } + } + } + } + out +} +/// `PoiManager.sectionsToVillage`: the Chebyshev distance in sections to a +/// village section, at most 7. +fn sections_to_village(villages: &[[i32; 3]], s: [i32; 3]) -> i32 { + villages + .iter() + .map(|v| { + (v[0] - s[0]) + .abs() + .max((v[1] - s[1]).abs()) + .max((v[2] - s[2]).abs()) + }) + .min() + .unwrap_or(7) + .min(7) +} + +/// A memory a gate or behaviour conditions on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Mem { + VisibleBabies, + InteractionTarget, + BreedTarget, + Home, +} +fn mem_present(m: &Mob, which: Mem) -> bool { + let Some(mm) = mem_ref(m) else { return false }; + match which { + Mem::VisibleBabies => mm.visible_villager_babies.present(), + Mem::InteractionTarget => mm.interaction_target.present(), + Mem::BreedTarget => mm.breed_target.present(), + Mem::Home => mm.home.present(), + } +} +fn mem_erase(m: &mut Mob, which: Mem) { + let mm = mem(m); + match which { + Mem::VisibleBabies => mm.visible_villager_babies.clear(), + Mem::InteractionTarget => mm.interaction_target.clear(), + Mem::BreedTarget => mm.breed_target.clear(), + Mem::Home => mm.home.clear(), + } +} + +/// `GateBehavior`: `RunOne` (shuffled, run one) and the ordered gates. +#[derive(Clone, Debug)] +struct Gate { + running: bool, + /// Entry condition: this memory must be absent. + absent: Option, + /// Erased when the gate stops. + erase: Option, + shuffled: bool, + random: LegacyRandom, + kids: Vec<(B, i32, f64)>, +} +impl Gate { + fn run_one(seed: i64, kids: Vec<(B, i32)>) -> Self { + Self { + running: false, + absent: None, + erase: None, + shuffled: true, + random: LegacyRandom::new(seed), + kids: kids.into_iter().map(|(b, w)| (b, w, 0.0)).collect(), + } + } + fn ordered(seed: i64, erase: Mem, kid: B) -> Self { + Self { + running: false, + absent: None, + erase: Some(erase), + shuffled: false, + random: LegacyRandom::new(seed), + kids: vec![(kid, 1, 0.0)], + } + } + fn try_start(&mut self, m: &mut Mob, cx: &mut Bx) -> bool { + if self.absent.is_some_and(|a| mem_present(m, a)) { + return false; + } + self.running = true; + if self.shuffled { + // 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); + } + } + if let Some(e) = self.erase { + mem_erase(m, e); + } + } +} + +/// `SetEntityLookTarget`'s predicates. +#[derive(Clone, Copy, Debug, PartialEq)] +enum LookAt { + Species(Species), + Player, + Category(&'static str), +} +/// `InteractWith`'s targets. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Interact { + Villager, + BreedVillager, + Cat, +} +/// The fixed behaviours whose only state is their running flag (OneShots +/// stop in the same tick). +#[derive(Clone, Debug)] +enum B { + Swim(Timed), + InteractWithDoor { + running: bool, + last_node: Option, + cooldown: i32, + }, + LookAtTargetSink(Timed), + PanicTrigger(Timed), + WakeUp(bool), + ReactToBell(bool), + SetRaidStatus(bool), + ValidatePoi { + running: bool, + filter: PoiFilter, + which: PoiMem, + }, + MoveToTargetSink { + t: Timed, + cooldown: i32, + path: Option, + last_target: Option<[i32; 3]>, + speed: f32, + }, + PoiCompetitorScan(bool), + FollowTradingPlayer(Timed), + GoToWantedItem(bool), + AcquirePoi { + running: bool, + filter: PoiFilter, + /// The memory filled (and checked absent): job site, home, meeting. + poi: Poi, + only_adult: bool, + event: bool, + next: i64, + retries: Vec<([i32; 3], Retry)>, + }, + GoToPotentialJobSite(Timed), + YieldJobSite(bool), + AssignProfession(bool), + ResetProfession(bool), + Gate(Box), + InteractWith { + running: bool, + kind: Interact, + }, + VillageBoundStroll { + running: bool, + speed: f32, + xz: i32, + y: i32, + }, + WalkToLookTarget(bool), + JumpOnBed { + t: Timed, + bed: Option<[i32; 3]>, + time_left: i32, + jumps: i32, + cooldown: i32, + }, + DoNothing(Timed), + GiveGiftToHero { + t: Timed, + until_next: i32, + given: bool, + started: i64, + }, + SetLookAndInteract(bool), + ShowTrades { + t: Timed, + look_time: i32, + }, + TradeWithVillager(Timed), + MakeLove { + t: Timed, + birth: i64, + }, + LookAtEntity { + running: bool, + what: LookAt, + }, + UpdateActivity(bool), + WorkAtPoi { + t: Timed, + last_check: i64, + }, + StrollAroundPoi { + running: bool, + next_ok: i64, + max_dist: i32, + which: PoiMem, + }, + StrollToPoi { + running: bool, + next_ok: i64, + }, + StrollToPoiList { + running: bool, + next_ok: i64, + }, + HarvestFarmland { + t: Timed, + next_ok: i64, + target: Option<[i32; 3]>, + valid: Vec<[i32; 3]>, + worked: i32, + }, + UseBonemeal(Timed), + WalkToBlockMemory { + running: bool, + which: PoiMem, + speed: f32, + close: i32, + too_far: i32, + too_long: i64, + }, + SleepInBed { + t: Timed, + next_ok: i64, + }, + ClosestHomeAsWalkTarget { + running: bool, + last_update: i64, + cache: Vec<([i32; 3], i64)>, + }, + InsideBrownianWalk { + running: bool, + random: LegacyRandom, + }, + GoToClosestVillage(bool), + TriggerGate { + running: bool, + random: LegacyRandom, + kids: Vec<(B, i32, f64)>, + }, + SocializeAtBell(bool), + CalmDown(bool), + WalkAwayFrom { + running: bool, + hostile: bool, + }, + RingBell(bool), + ResetRaidStatus(bool), + /// `BehaviorBuilder.sequence(triggerIf(raid condition), then)`. + RaidSequence { + running: bool, + victory: bool, + then: Box, + }, + MoveToSkySeeingSpot { + running: bool, + speed: f32, + }, + Celebrate(Timed), + LocateHidingPlace { + running: bool, + radius: i32, + speed: f32, + close: i32, + }, + SetHiddenState { + running: bool, + hidden: i32, + }, + PlayTag(bool), +} +/// `AcquirePoi.JitteredLinearRetry`. +#[derive(Clone, Copy, Debug)] +struct Retry { + previous: i64, + next: i64, + delay: i32, +} +impl Retry { + fn new(cx: &mut Bx, now: i64) -> Self { + let mut r = Retry { + previous: 0, + next: 0, + delay: 0, + }; + r.mark(cx, now); + r + } + fn mark(&mut self, cx: &mut Bx, now: i64) { + self.previous = now; + let suggested = self.delay + cx.lr.next_int_bound(40).unwrap_or(0) + 40; + self.delay = suggested.min(400); + self.next = now + i64::from(self.delay); + } +} + +fn one(f: impl FnOnce() -> bool, running: &mut bool) -> bool { + let r = f(); + if r { + *running = true; + } + r +} + +impl B { + fn running(&self) -> bool { + match self { + B::Swim(t) + | B::LookAtTargetSink(t) + | B::PanicTrigger(t) + | B::FollowTradingPlayer(t) + | B::GoToPotentialJobSite(t) + | B::DoNothing(t) + | B::TradeWithVillager(t) + | B::UseBonemeal(t) + | B::Celebrate(t) => t.running, + B::MoveToTargetSink { t, .. } + | B::GiveGiftToHero { t, .. } + | B::ShowTrades { t, .. } + | B::WorkAtPoi { t, .. } + | B::HarvestFarmland { t, .. } + | B::JumpOnBed { t, .. } + | B::MakeLove { t, .. } + | B::SleepInBed { t, .. } => t.running, + B::InteractWithDoor { running, .. } + | B::ValidatePoi { running, .. } + | B::AcquirePoi { running, .. } + | B::InteractWith { running, .. } + | B::VillageBoundStroll { running, .. } + | B::LookAtEntity { running, .. } + | B::StrollAroundPoi { running, .. } + | B::StrollToPoi { running, .. } + | B::StrollToPoiList { running, .. } + | B::WalkToBlockMemory { running, .. } + | B::ClosestHomeAsWalkTarget { running, .. } + | B::InsideBrownianWalk { running, .. } + | B::TriggerGate { running, .. } + | B::WalkAwayFrom { running, .. } + | B::RaidSequence { running, .. } + | B::MoveToSkySeeingSpot { running, .. } + | B::LocateHidingPlace { running, .. } + | B::SetHiddenState { running, .. } => *running, + B::WakeUp(r) + | B::ReactToBell(r) + | B::SetRaidStatus(r) + | B::PoiCompetitorScan(r) + | B::GoToWantedItem(r) + | B::YieldJobSite(r) + | B::AssignProfession(r) + | B::ResetProfession(r) + | B::WalkToLookTarget(r) + | B::SetLookAndInteract(r) + | B::UpdateActivity(r) + | B::GoToClosestVillage(r) + | B::SocializeAtBell(r) + | B::CalmDown(r) + | B::RingBell(r) + | B::ResetRaidStatus(r) + | B::PlayTag(r) => *r, + B::Gate(g) => g.running, + } + } + /// `OneShot` behaviours stop at their first tick. + fn one_shot_stop(&mut self) -> bool { + match self { + B::InteractWithDoor { running, .. } + | B::ValidatePoi { running, .. } + | B::AcquirePoi { running, .. } + | B::InteractWith { running, .. } + | B::VillageBoundStroll { running, .. } + | B::LookAtEntity { running, .. } + | B::StrollAroundPoi { running, .. } + | B::StrollToPoi { running, .. } + | B::StrollToPoiList { running, .. } + | B::WalkToBlockMemory { running, .. } + | B::ClosestHomeAsWalkTarget { running, .. } + | B::InsideBrownianWalk { running, .. } + | B::TriggerGate { running, .. } + | B::WalkAwayFrom { running, .. } + | B::RaidSequence { running, .. } + | B::MoveToSkySeeingSpot { running, .. } + | B::LocateHidingPlace { running, .. } + | B::SetHiddenState { running, .. } + | B::GoToClosestVillage(running) + | B::SocializeAtBell(running) + | B::CalmDown(running) + | B::RingBell(running) + | B::ResetRaidStatus(running) + | B::PlayTag(running) + | B::WakeUp(running) + | B::ReactToBell(running) + | B::SetRaidStatus(running) + | B::PoiCompetitorScan(running) + | B::GoToWantedItem(running) + | B::YieldJobSite(running) + | B::AssignProfession(running) + | B::ResetProfession(running) + | B::WalkToLookTarget(running) + | B::SetLookAndInteract(running) + | B::UpdateActivity(running) => { + *running = false; + true + } + _ => false, + } + } + + fn try_start(&mut self, m: &mut Mob, cx: &mut Bx) -> bool { + let now = cx.now; + match self { + B::Gate(g) => g.try_start(m, cx), + // -- Behaviours with a duration. + B::Swim(t) => { + if !swim_condition(m) { + return false; + } + t.begin(cx); + true + } + B::LookAtTargetSink(t) => { + if !mem(m).look_target.present() { + return false; + } + t.begin(cx); + true + } + B::PanicTrigger(t) => { + t.begin(cx); + // VillagerPanicTrigger.start + if panic_condition(m) { + if !brain_mut(m).is_active(Act::Panic) { + let mm = mem(m); + mm.path.clear(); + mm.walk_target.clear(); + mm.look_target.clear(); + mm.breed_target.clear(); + mm.interaction_target.clear(); + } + brain_mut(m).set_active_if_possible(Act::Panic); + } + true + } + B::MoveToTargetSink { + t, + cooldown, + path, + last_target, + speed, + } => { + let mm = mem(m); + if mm.path.present() || !mm.walk_target.present() { + return false; + } + // checkExtraStartConditions + 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); + // start + 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::FollowTradingPlayer(t) => { + if !follow_trading_condition(m, cx.w) { + return false; + } + t.begin(cx); + follow_trading_player(m); + true + } + B::GoToPotentialJobSite(t) => { + if !mem(m).potential_job_site.present() { + return false; + } + let a = brain_mut(m).activity; + if !matches!(a, Act::Idle | Act::Work | Act::Play) { + return false; + } + t.begin(cx); + true + } + B::JumpOnBed { + t, + bed, + time_left, + jumps, + cooldown, + } => { + let mm = mem(m); + let Some(nearest) = mm.nearest_bed.value() else { + return false; + }; + if mm.walk_target.present() || !m.is_baby() { + return false; + } + t.begin(cx); + *bed = Some(nearest); + *time_left = 100; + *jumps = 3 + cx.lr.next_int_bound(4).unwrap_or(0); + *cooldown = 0; + mem(m).walk_target.set(WalkTarget::block(nearest, 0.5, 0)); + true + } + B::DoNothing(t) => { + t.begin(cx); + true + } + B::GiveGiftToHero { + t, + until_next, + given, + started, + } => { + if !mem(m).nearest_visible_player.present() { + return false; + } + if !hero_visible(m, cx.w) { + return false; + } + if *until_next > 0 { + *until_next -= 1; + return false; + } + t.begin(cx); + *given = false; + *started = now; + let mm = mem(m); + mm.interaction_target.set(Who::Player); + mm.look_target.set(Tracker::Entity(Who::Player, true)); + true + } + B::ShowTrades { t, look_time } => { + if !mem(m).interaction_target.present() || !show_trades_condition(m, cx.w) { + return false; + } + t.begin(cx); + // start + if let Some(target) = mem(m).interaction_target.value() { + mem(m).look_target.set(Tracker::Entity(target, true)); + } + *look_time = 40; + true + } + B::TradeWithVillager(t) => { + let mm = mem(m); + if !mm.interaction_target.present() || !mm.visible_mobs.present() { + return false; + } + if !villager_target_valid(m, cx.w, Mem::InteractionTarget) { + return false; + } + t.begin(cx); + let target = mem(m).interaction_target.value().unwrap(); + let mm = mem(m); + mm.look_target.set(Tracker::Entity(target, true)); + mm.walk_target.set(WalkTarget { + target: Tracker::Entity(target, true), + speed: 0.5, + close: 2, + }); + true + } + B::MakeLove { t, birth } => { + let mm = mem(m); + if !mm.breed_target.present() || !mm.visible_mobs.present() { + return false; + } + if !breeding_possible(m, cx.w) { + return false; + } + t.begin(cx); + let target = mem(m).breed_target.value().unwrap(); + lock_gaze(m, target); + *birth = now + 275 + i64::from(m.random.next_int_bound(50).unwrap_or(0)); + true + } + B::WorkAtPoi { t, last_check } => { + let mm = mem(m); + let Some(site) = mm.job_site.value() else { + return false; + }; + if now - *last_check < 300 { + return false; + } + if cx.lr.next_int_bound(2).unwrap_or(0) != 0 { + return false; + } + *last_check = now; + if !closer_to_center(site, m.position, 1.73) { + return false; + } + t.begin(cx); + // start + let mm = mem(m); + mm.last_worked_at_poi.set(now); + mm.look_target.set(Tracker::Block(site)); + play_work_sound(m, cx); + restock_if_due(m, cx.w); + true + } + B::HarvestFarmland { + t, + next_ok, + target, + valid, + .. + } => { + let mm = mem(m); + if mm.look_target.present() + || mm.walk_target.present() + || !mm.secondary_job_site.present() + { + return false; + } + if !cx.w.mob_griefing || !super::villager::is_farmer(m) { + return false; + } + *valid = farmland_around(m, cx.w); + *target = pick_farmland(valid, cx); + let Some(p) = *target else { return false }; + t.begin(cx); + if now > *next_ok { + let mm = mem(m); + mm.look_target.set(Tracker::Block(p)); + mm.walk_target.set(WalkTarget::block(p, 0.5, 1)); + } + true + } + B::UseBonemeal(t) => { + let mm = mem(m); + if mm.look_target.present() || mm.walk_target.present() { + return false; + } + // Bone meal in the inventory is needed; checked every 10 ticks. + let has = super::villager::ext(m) + .is_some_and(|e| e.count_item("minecraft:bone_meal") > 0); + let _ = t; + let _ = has; + false + } + // -- OneShots. + B::InteractWithDoor { + running, + last_node, + cooldown, + } => { + if !mem(m).path.present() { + return false; + } + let Some(path) = m.ai.nav.path.clone() else { + return false; + }; + if path.next == 0 || path.is_done() { + return false; + } + let next = path.next_node(); + if *last_node == Some(next) { + *cooldown = 20; + } else { + *cooldown -= 1; + if *cooldown > 0 { + return false; + } + } + *last_node = Some(next); + let from = path.nodes[path.next - 1]; + interact_with_doors(m, cx, from, next); + *running = true; + true + } + B::WakeUp(r) => one( + || { + if !brain_mut(m).is_active(Act::Rest) && super::villager::sleeping(m) { + super::villager::stop_sleeping(m, cx.w); + mem(m).last_woken.set(now); + true + } else { + false + } + }, + r, + ), + B::ReactToBell(r) => one( + || { + if !mem(m).heard_bell_time.present() { + return false; + } + if !super::villager::raid_nearby(m) { + brain_mut(m).set_active_if_possible(Act::Hide); + } + true + }, + r, + ), + B::SetRaidStatus(r) => one( + || { + if cx.lr.next_int_bound(20).unwrap_or(0) != 0 { + return false; + } + match super::villager::raid_state(m) { + Some(true) => { + let b = brain_mut(m); + b.default_activity = Act::Raid; + b.set_active_if_possible(Act::Raid); + } + Some(false) => { + let b = brain_mut(m); + b.default_activity = Act::PreRaid; + b.set_active_if_possible(Act::PreRaid); + } + None => {} + } + true + }, + r, + ), + B::ValidatePoi { + running, + filter, + which, + } => { + let Some(p) = which.get(m) else { return false }; + if !closer_to_center(p, m.position, 16.0) { + return false; + } + if !poi_exists(m, cx.w, p, *filter) { + which.clear(m); + } else if cx.w.block_name(p[0], p[1], p[2]).ends_with("_bed") + && cx.w.prop(p[0], p[1], p[2], "occupied") == Some("true") + && !super::villager::sleeping(m) + { + // ValidateNearbyPoi.bedIsOccupied: someone else sleeps there. + which.clear(m); + } + *running = true; + true + } + B::PoiCompetitorScan(r) => one( + || { + let mm = mem(m); + let (Some(site), true) = (mm.job_site.value(), mm.mobs.present()) else { + return false; + }; + if poi_at(cx.w, site[0], site[1], site[2]).is_some() { + let list = mem(m).mobs.value().unwrap_or_default(); + let my_xp = super::villager::xp(m); + let mut winner_xp = my_xp; + let mut me_winner = true; + for who in list { + let Who::Mob(id) = who else { continue }; + let Some(s) = cx.w.seen(id) else { continue }; + if s.species != Species::Villager || !s.alive || s.job != Some(site) { + continue; + } + if s.profession != m.extra.variant2 { + continue; + } + // selectWinner(first, second): the second wins ties. + if winner_xp > s.xp { + // The other villager loses its site (it finds out itself). + } else { + if me_winner { + mem(m).job_site.clear(); + } + me_winner = false; + winner_xp = s.xp; + } + } + } + true + }, + r, + ), + B::GoToWantedItem(_) => false, + B::AcquirePoi { + running, + filter, + poi, + only_adult, + event, + next, + retries, + } => { + let mm = mem(m); + let (target_present, validate_present) = match poi { + Poi::Job(_) => (mm.potential_job_site.present(), mm.job_site.present()), + Poi::Home => (mm.home.present(), false), + Poi::Meeting => (mm.meeting_point.present(), false), + }; + if target_present || validate_present { + return false; + } + if *only_adult && m.is_baby() { + return false; + } + if *next == 0 { + *next = cx.w.game_time + i64::from(cx.lr.next_int_bound(20).unwrap_or(0)); + return false; + } + if cx.w.game_time < *next { + return false; + } + *next = now + 20 + i64::from(cx.lr.next_int_bound(20).unwrap_or(0)); + retries.retain(|(_, r)| now - r.previous < 400); + let w = cx.w; + let mut found = pois_in_range(m, w, *filter, 48, |_| true); + // The cache test runs on every candidate, in scan order. + let mut keep = Vec::new(); + { + let order = pois_scan_order(m, &found); + for idx in order { + let p = found[idx].1; + let ok = match retries.iter_mut().find(|(q, _)| *q == p) { + None => true, + Some((_, r)) => { + if now >= r.next { + r.mark(cx, now); + true + } else { + false + } + } + }; + if ok { + keep.push(idx); + } + } + } + found = found + .into_iter() + .enumerate() + .filter(|(i, _)| keep.contains(i)) + .map(|(_, f)| f) + .collect(); + found.truncate(5); + if *poi == Poi::Home { + found.retain(|(_, p)| w.prop(p[0], p[1], p[2], "occupied") != Some("true")); + } + let path = if found.is_empty() { + None + } else { + let range = found + .iter() + .map(|(t, _)| t.valid_range()) + .max() + .unwrap_or(1) + .max(1); + let targets: Vec<[i32; 3]> = found.iter().map(|(_, p)| *p).collect(); + m.create_path_to_any(w, &targets, range) + }; + if let Some(path) = path.filter(|p| p.reached) { + let target = path.target; + if poi_at(w, target[0], target[1], target[2]).is_some() { + let mm = mem(m); + match poi { + Poi::Job(_) => mm.potential_job_site.set(target), + Poi::Home => mm.home.set(target), + Poi::Meeting => mm.meeting_point.set(target), + } + if *event { + happy_particles(m, cx); + } + retries.clear(); + } + } else { + for (_, p) in &found { + if !retries.iter().any(|(q, _)| q == p) { + let r = Retry::new(cx, now); + retries.push((*p, r)); + } + } + } + *running = true; + true + } + B::YieldJobSite(r) => one( + || { + let mm = mem(m); + let Some(site) = mm.potential_job_site.value() else { + return false; + }; + if mm.job_site.present() || !mm.mobs.present() { + return false; + } + if m.is_baby() || m.extra.variant2 != super::villager::NONE { + return false; + } + let Some(poi) = poi_at(cx.w, site[0], site[1], site[2]) else { + return true; + }; + let list = mem(m).mobs.value().unwrap_or_default(); + for who in list { + let Who::Mob(id) = who else { continue }; + let Some(s) = cx.w.seen(id) else { continue }; + if s.species != Species::Villager || !s.alive || s.potential_job.is_some() { + continue; + } + let Poi::Job(j) = poi else { continue }; + if s.profession != j { + continue; + } + // A nearby villager of that profession takes it over. + if s.job.is_none_or(|p| p == site) { + let mm = mem(m); + mm.walk_target.clear(); + mm.look_target.clear(); + mm.potential_job_site.clear(); + break; + } + } + true + }, + r, + ), + B::AssignProfession(r) => { + let Some(p) = mem(m).potential_job_site.value() else { + return false; + }; + if !closer_to_center(p, m.position, 2.0) { + return false; + } + let mm = mem(m); + mm.potential_job_site.clear(); + mm.job_site.set(p); + happy_particles(m, cx); + *r = true; + if m.extra.variant2 != super::villager::NONE { + return true; + } + if let Some(Poi::Job(j)) = poi_at(cx.w, p[0], p[1], p[2]) { + super::villager::set_profession(m, j); + cx.refresh = true; + } + true + } + B::ResetProfession(r) => one( + || { + if mem(m).job_site.present() { + return false; + } + let prof = m.extra.variant2; + let can_be_fired = + prof != super::villager::NONE && prof != super::villager::NITWIT; + if can_be_fired && super::villager::xp(m) == 0 && m.extra.variant3 <= 1 { + super::villager::set_profession(m, super::villager::NONE); + cx.refresh = true; + true + } else { + false + } + }, + r, + ), + B::InteractWith { running, kind } => { + let mm = mem(m); + if mm.walk_target.present() || !mm.visible_mobs.present() { + return false; + } + let kind = *kind; + if kind == Interact::BreedVillager && !super::villager::can_breed(m) { + return false; + } + let w = cx.w; + let valid = move |who: Who| -> bool { + let Who::Mob(id) = who else { return false }; + let Some(s) = w.seen(id) else { return false }; + match kind { + Interact::Villager => s.species == Species::Villager, + Interact::BreedVillager => s.species == Species::Villager && s.in_love, + Interact::Cat => s.species == Species::Cat, + } + }; + if find_closest(m, w, |_, who| valid(who)).is_none() { + return false; + } + if let Some(t) = find_closest(m, w, |m, who| { + valid(who) + && w.target_info(who) + .is_some_and(|t| t.position.distance_squared(m.position) <= 64.0) + }) { + let mm = mem(m); + if kind == Interact::BreedVillager { + mm.breed_target.set(t); + } else { + mm.interaction_target.set(t); + } + mm.look_target.set(Tracker::Entity(t, true)); + mm.walk_target.set(WalkTarget { + target: Tracker::Entity(t, false), + speed: 0.5, + close: 2, + }); + } + *running = true; + true + } + B::VillageBoundStroll { + running, + speed, + xz, + y, + } => { + if mem(m).walk_target.present() { + return false; + } + let w = cx.w; + let here = block_of(m.position); + let section = [here[0] >> 4, here[1] >> 4, here[2] >> 4]; + let villages = village_sections(m, w); + let pos = if sections_to_village(&villages, section) <= 1 { + m.land_random_pos(w, *xz, *y) + } else { + let best = closest_section(&villages, section, 2); + if best != section { + let to = [ + f64::from(best[0] * 16 + 8) + 0.5, + f64::from(best[1] * 16 + 8), + f64::from(best[2] * 16 + 8) + 0.5, + ]; + m.default_random_pos_towards( + w, + *xz, + *y, + to, + f64::from(std::f32::consts::FRAC_PI_2), + ) + } else { + m.land_random_pos(w, *xz, *y) + } + }; + mem(m) + .walk_target + .set_opt(pos.map(|p| WalkTarget::point(p, *speed, 0))); + *running = true; + true + } + B::WalkToLookTarget(r) => one( + || { + 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: 0.5, + close: 2, + }); + true + }, + r, + ), + B::SetLookAndInteract(r) => one( + || { + let mm = mem(m); + if mm.interaction_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) <= 16.0) + }); + let Some(t) = found else { return false }; + let mm = mem(m); + mm.interaction_target.set(t); + mm.look_target.set(Tracker::Entity(t, true)); + true + }, + r, + ), + B::LookAtEntity { running, what } => { + let mm = mem(m); + if mm.look_target.present() || !mm.visible_mobs.present() { + return false; + } + let what = *what; + let w = cx.w; + let found = find_closest(m, w, |m, who| { + let ok = match (what, who) { + (LookAt::Player, Who::Player) => true, + (LookAt::Species(sp), Who::Mob(id)) => { + w.seen(id).is_some_and(|s| s.species == sp) + } + (LookAt::Category(c), Who::Mob(id)) => { + w.seen(id).is_some_and(|s| s.category == c) + } + _ => false, + }; + ok && w + .target_info(who) + .is_some_and(|t| t.position.distance_squared(m.position) <= 64.0) + }); + let Some(t) = found else { return false }; + mem(m).look_target.set(Tracker::Entity(t, true)); + *running = true; + true + } + B::UpdateActivity(r) => { + brain_mut(m).update_from_schedule(cx.w.game_time, cx.w.day_time); + *r = true; + true + } + B::StrollAroundPoi { + running, + next_ok, + max_dist, + which, + } => { + let Some(site) = which.get(m) else { + return false; + }; + if !closer_to_center(site, m.position, f64::from(*max_dist)) { + return false; + } + if now <= *next_ok { + *running = true; + return true; + } + let pos = m.land_random_pos(cx.w, 8, 6); + mem(m) + .walk_target + .set_opt(pos.map(|p| WalkTarget::point(p, 0.4, 1))); + *next_ok = now + 180; + *running = true; + true + } + B::StrollToPoi { running, next_ok } => { + let Some(site) = mem(m).job_site.value() else { + return false; + }; + if !closer_to_center(site, m.position, 10.0) { + return false; + } + if now <= *next_ok { + *running = true; + return true; + } + mem(m).walk_target.set(WalkTarget::block(site, 0.4, 1)); + *next_ok = now + 80; + *running = true; + true + } + B::StrollToPoiList { running, next_ok } => { + let mm = mem(m); + let (Some(list), Some(site)) = (mm.secondary_job_site.value(), mm.job_site.value()) + else { + return false; + }; + if list.is_empty() { + return false; + } + let target = list[cx.lr.next_int_bound(list.len() as i32).unwrap_or(0) as usize]; + if !closer_to_center(site, m.position, 6.0) { + return false; + } + if now > *next_ok { + mem(m).walk_target.set(WalkTarget::block(target, 0.5, 1)); + *next_ok = now + 100; + } + *running = true; + true + } + B::WalkToBlockMemory { + running, + which, + speed, + close, + too_far, + too_long, + } => { + let r = walk_to_block_memory(m, cx, *which, *speed, *close, *too_far, *too_long); + *running = r; + r + } + B::SleepInBed { t, next_ok } => { + if m.extra.mount.is_some() { + return false; + } + let mm = mem(m); + let Some(home) = mm.home.value() else { + return false; + }; + if let Some(woken) = mm.last_woken.value() { + let since = cx.w.game_time - woken; + if since > 0 && since < 100 { + return false; + } + } + let w = cx.w; + if !(closer_to_center(home, m.position, 2.0) + && w.block_name(home[0], home[1], home[2]).ends_with("_bed") + && w.prop(home[0], home[1], home[2], "occupied") != Some("true")) + { + return false; + } + t.begin(cx); + if now > *next_ok { + if super::villager::start_sleeping(m, home, w) { + mem(m).last_slept.set(now); + } + let mm = mem(m); + mm.walk_target.clear(); + mm.cant_reach_walk_target_since.clear(); + } + true + } + B::ClosestHomeAsWalkTarget { + running, + last_update, + cache, + } => { + let mm = mem(m); + if mm.walk_target.present() || mm.home.present() { + return false; + } + if cx.w.game_time - *last_update < 20 { + return false; + } + let w = cx.w; + let here = block_of(m.position); + let homes = homes_in_range(m, w, 48); + let Some(closest) = homes.iter().min_by_key(|p| dist_sqr(**p, here)).copied() + else { + return false; + }; + if dist_sqr(closest, here) <= 4 { + return false; + } + let mut tried = 0; + *last_update = cx.w.game_time + i64::from(cx.lr.next_int_bound(20).unwrap_or(0)); + let mut targets = Vec::new(); + for p in homes { + if cache.iter().any(|(q, _)| *q == p) { + continue; + } + tried += 1; + if tried >= 5 { + continue; + } + cache.push((p, *last_update + 40)); + targets.push(p); + } + let path = if targets.is_empty() { + None + } else { + m.create_path_to_any(w, &targets, 1) + }; + if let Some(path) = path.filter(|p| p.reached) { + mem(m) + .walk_target + .set(WalkTarget::block(path.target, 0.5, 1)); + } else if tried < 5 { + let limit = *last_update; + cache.retain(|(_, until)| *until >= limit); + } + *running = true; + true + } + B::InsideBrownianWalk { running, random } => { + if mem(m).walk_target.present() { + return false; + } + let w = cx.w; + let here = block_of(m.position); + if w.can_see_sky(here[0], here[1], here[2]) { + return false; + } + let mut poses = Vec::new(); + for z in -1..=1 { + for y in -1..=1 { + for x in -1..=1 { + poses.push([here[0] + x, here[1] + y, here[2] + z]); + } + } + } + // Collections.shuffle (its own random). + for i in (1..poses.len()).rev() { + let j = random.next_int_bound(i as i32 + 1).unwrap_or(0) as usize; + poses.swap(i, j); + } + if let Some(p) = poses + .into_iter() + .find(|p| !w.can_see_sky(p[0], p[1], p[2]) && w.solid(p[0], p[1], p[2])) + { + mem(m).walk_target.set(WalkTarget::block(p, 0.5, 0)); + } + *running = true; + true + } + B::GoToClosestVillage(r) => { + if mem(m).walk_target.present() { + return false; + } + let w = cx.w; + let villages = village_sections(m, w); + let section_of = |p: [i32; 3]| [p[0] >> 4, p[1] >> 4, p[2] >> 4]; + let here = sections_to_village(&villages, section_of(block_of(m.position))); + if here <= 1 { + return false; + } + let mut target = None; + for _ in 0..5 { + let pos = m.land_random_pos_scored(w, 15, 7, |p| { + -f64::from(sections_to_village(&villages, section_of(p))) + }); + if let Some(p) = pos { + let b = [ + p[0].floor() as i32, + p[1].floor() as i32, + p[2].floor() as i32, + ]; + let d = sections_to_village(&villages, section_of(b)); + if d < here { + target = Some(p); + break; + } + if d == here { + target = Some(p); + } + } + } + if let Some(p) = target { + mem(m).walk_target.set(WalkTarget::point(p, 0.5, 4)); + } + *r = true; + true + } + B::TriggerGate { + running, + random, + kids, + } => { + for k in kids.iter_mut() { + let r = random.next_float(); + k.2 = -f64::from(r).powf(f64::from(1.0_f32 / k.1 as f32)); + } + kids.sort_by(|a, b| a.2.total_cmp(&b.2)); + for k in kids.iter_mut() { + let fired = k.0.try_start(m, cx); + k.0.one_shot_stop(); + if fired { + break; + } + } + *running = true; + true + } + B::SocializeAtBell(r) => one( + || { + let mm = mem(m); + let Some(bell) = mm.meeting_point.value() else { + return false; + }; + if !mm.visible_mobs.present() || mm.interaction_target.present() { + return false; + } + let w = cx.w; + let is_villager = |who: Who| matches!(who, Who::Mob(id) if w.seen(id).is_some_and(|s| s.species == Species::Villager)); + if cx.lr.next_int_bound(100).unwrap_or(1) != 0 + || !closer_to_center(bell, m.position, 4.0) + || find_closest(m, w, |_, who| is_villager(who)).is_none() + { + return false; + } + if let Some(t) = find_closest(m, w, |m, who| { + is_villager(who) + && w.target_info(who) + .is_some_and(|i| i.position.distance_squared(m.position) <= 32.0) + }) { + let mm = mem(m); + mm.interaction_target.set(t); + mm.look_target.set(Tracker::Entity(t, true)); + mm.walk_target.set(WalkTarget { + target: Tracker::Entity(t, false), + speed: 0.3, + close: 1, + }); + } + true + }, + r, + ), + B::CalmDown(r) => { + let w = cx.w; + let mm = mem(m); + let scared = mm.hurt_by.present() + || mm.nearest_hostile.present() + || mm.hurt_by_entity.value().is_some_and(|e| { + w.target_info(e) + .is_some_and(|t| t.position.distance_squared(m.position) <= 36.0) + }); + if !scared { + let mm = mem(m); + mm.hurt_by.clear(); + mm.hurt_by_entity.clear(); + brain_mut(m).update_from_schedule(w.game_time, w.day_time); + } + *r = true; + true + } + B::WalkAwayFrom { running, hostile } => { + let w = cx.w; + let mm = mem(m); + let from = if *hostile { + mm.nearest_hostile.value() + } else { + mm.hurt_by_entity.value() + }; + let Some(from) = from else { return false }; + if mm.walk_target.present() { + return false; + } + let Some(avoid) = w.target_info(from).map(|t| t.position) else { + return false; + }; + if m.position.distance_squared(avoid) >= 36.0 { + return false; + } + for _ in 0..10 { + if let Some(p) = m.land_random_pos_away(w, 16, 7, [avoid.x, avoid.y, avoid.z]) { + mem(m).walk_target.set(WalkTarget::point(p, 0.75, 0)); + break; + } + } + *running = true; + true + } + B::RingBell(r) => one( + || { + let Some(bell) = mem(m).meeting_point.value() else { + return false; + }; + if cx.lr.next_float() <= 0.95 { + return false; + } + if dist_sqr(bell, block_of(m.position)) < 9 + && cx.w.block_name(bell[0], bell[1], bell[2]) == "minecraft:bell" + { + cx.events.push(MobEvent::SoundId( + "minecraft:block.bell.use".into(), + [ + f64::from(bell[0]) + 0.5, + f64::from(bell[1]) + 0.5, + f64::from(bell[2]) + 0.5, + ], + 2.0, + 1.0, + )); + } + true + }, + r, + ), + B::ResetRaidStatus(r) => one( + || { + if cx.lr.next_int_bound(20).unwrap_or(0) != 0 { + return false; + } + if !super::villager::raid_nearby(m) { + let b = brain_mut(m); + b.default_activity = Act::Idle; + b.update_from_schedule(cx.w.game_time, cx.w.day_time); + } + true + }, + r, + ), + B::RaidSequence { + running, + victory, + then, + } => { + let state = super::villager::raid_status(m); + let ok = if *victory { + state == super::villager::RAID_VICTORY + } else { + state == super::villager::RAID || state == super::villager::PRE_RAID + }; + if !ok { + return false; + } + let fired = then.try_start(m, cx); + then.one_shot_stop(); + *running = fired; + fired + } + B::MoveToSkySeeingSpot { running, speed } => { + if mem(m).walk_target.present() { + return false; + } + let w = cx.w; + let here = block_of(m.position); + if w.can_see_sky(here[0], here[1], here[2]) { + return false; + } + for _ in 0..10 { + let p = [ + here[0] + m.random.next_int_bound(20).unwrap_or(0) - 10, + here[1] + m.random.next_int_bound(6).unwrap_or(0) - 3, + here[2] + m.random.next_int_bound(20).unwrap_or(0) - 10, + ]; + if no_blocks_above(m, w, p) { + mem(m).walk_target.set(WalkTarget::block(p, *speed, 0)); + break; + } + } + *running = true; + true + } + B::Celebrate(t) => { + let here = block_of(m.position); + if super::villager::raid_status(m) != super::villager::RAID_VICTORY + || !no_blocks_above(m, cx.w, here) + { + return false; + } + t.begin(cx); + true + } + B::LocateHidingPlace { + running, + radius, + speed, + close, + } => { + if mem(m).walk_target.present() { + return false; + } + let w = cx.w; + let near = homes_in_range(m, w, *close + 1) + .into_iter() + .next() + .filter(|p| closer_to_center(*p, m.position, f64::from(*close))); + let place = near + .or_else(|| { + let mut all = homes_in_range(m, w, *radius); + // Util.toShuffledList with the mob's random. + for i in (2..=all.len()).rev() { + let j = m.random.next_int_bound(i as i32).unwrap_or(0) as usize; + all.swap(i - 1, j); + } + all.into_iter().next() + }) + .or_else(|| mem(m).home.value()); + if let Some(p) = place { + let far = !closer_to_center(p, m.position, f64::from(*close)); + let mm = mem(m); + mm.path.clear(); + mm.look_target.clear(); + mm.breed_target.clear(); + mm.interaction_target.clear(); + mm.hiding_place.set(p); + if far { + mm.walk_target.set(WalkTarget::block(p, *speed, *close)); + } + } + *running = true; + true + } + B::SetHiddenState { running, hidden } => { + let mm = mem(m); + let (Some(place), Some(heard)) = + (mm.hiding_place.value(), mm.heard_bell_time.value()) + else { + return false; + }; + let timed_out = heard + 300 <= now; + if *hidden <= 300 && !timed_out { + if dist_sqr(place, block_of(m.position)) < 9 { + *hidden += 1; + } + } else { + let mm = mem(m); + mm.heard_bell_time.clear(); + mm.hiding_place.clear(); + brain_mut(m).update_from_schedule(cx.w.game_time, cx.w.day_time); + *hidden = 0; + } + *running = true; + true + } + B::PlayTag(r) => one( + || { + let mm = mem(m); + let Some(friends) = mm.visible_villager_babies.value() else { + return false; + }; + if mm.walk_target.present() { + return false; + } + if cx.lr.next_int_bound(10).unwrap_or(0) != 0 { + return false; + } + // Who chases whom is in the other kids' brains: chase the + // first friend. + if let Some(&kid) = friends.first() { + let mm = mem(m); + mm.interaction_target.set(kid); + mm.look_target.set(Tracker::Entity(kid, true)); + mm.walk_target.set(WalkTarget { + target: Tracker::Entity(kid, false), + speed: 0.6, + close: 1, + }); + } + true + }, + r, + ), + } + } + + fn tick_or_stop(&mut self, m: &mut Mob, cx: &mut Bx) { + if self.one_shot_stop() { + return; + } + let now = cx.now; + match self { + B::Gate(g) => g.tick_or_stop(m, cx), + B::Swim(t) => { + if now > t.end || !swim_condition(m) { + self.do_stop(m, cx); + } else if m.random.next_float() < 0.8 { + m.ai.jump = true; + } + } + B::LookAtTargetSink(t) => { + let visible = match mem(m).look_target.value() { + Some(look) => tracker_visible(m, cx.w, look), + None => false, + }; + if now > t.end || !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::PanicTrigger(t) => { + if now > t.end || !panic_condition(m) { + self.do_stop(m, cx); + } else if now % 100 == 0 { + cx.events.push(MobEvent::GolemCheck { + mob: m.id, + needed: 3, + }); + } + } + 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 now > t.end || !still { + self.do_stop(m, cx); + return; + } + // tick + 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 = manhattan_sq(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::FollowTradingPlayer(_) => { + if !follow_trading_condition(m, cx.w) { + self.do_stop(m, cx); + } else { + follow_trading_player(m); + } + } + B::GoToPotentialJobSite(t) => { + let site = mem(m).potential_job_site.value(); + if now > t.end || site.is_none() { + self.do_stop(m, cx); + } else if let Some(p) = site { + let mm = mem(m); + mm.look_target.set(Tracker::Block(p)); + mm.walk_target.set(WalkTarget::block(p, 0.5, 1)); + } + } + B::JumpOnBed { + bed, + time_left, + jumps, + cooldown, + .. + } => { + let w = cx.w; + let here = block_of(m.position); + let jumpable = |p: [i32; 3]| w.block_name(p[0], p[1], p[2]).ends_with("_bed"); + let on_or_over = jumpable(here) || jumpable([here[0], here[1] - 1, here[2]]); + let still = m.is_baby() + && bed.is_some_and(jumpable) + && !(!on_or_over && *time_left <= 0) + && !(on_or_over && *jumps <= 0); + if !still { + self.do_stop(m, cx); + return; + } + if !on_or_over { + *time_left -= 1; + } else if *cooldown > 0 { + *cooldown -= 1; + } else if jumpable(here) { + m.ai.jump = true; + *jumps -= 1; + *cooldown = 5; + } + } + B::DoNothing(t) => { + if now > t.end { + self.do_stop(m, cx); + } + } + B::GiveGiftToHero { + t, given, started, .. + } => { + if now > t.end || !hero_visible(m, cx.w) || *given { + self.do_stop(m, cx); + return; + } + let Some(p) = cx.w.player.clone() else { return }; + mem(m).look_target.set(Tracker::Entity(Who::Player, true)); + let close = { + let a = block_of(p.position); + let b = block_of(m.position); + let d = (a[0] - b[0]).pow(2) + (a[1] - b[1]).pow(2) + (a[2] - b[2]).pow(2); + f64::from(d) < 25.0 + }; + if close { + if now - *started > 20 { + cx.events.push(MobEvent::ThrowGift { + table: super::villager::gift_table(m), + from: [m.position.x, m.eye_y() - 0.3, m.position.z], + to: [p.position.x, p.position.y, p.position.z], + }); + *given = true; + } + } else { + let mm = mem(m); + mm.look_target.set(Tracker::Entity(Who::Player, true)); + mm.walk_target.set(WalkTarget { + target: Tracker::Entity(Who::Player, true), + speed: 0.5, + close: 5, + }); + } + } + B::ShowTrades { t, look_time } => { + let still = show_trades_condition(m, cx.w) + && *look_time > 0 + && mem(m).interaction_target.present(); + if now > t.end || !still { + self.do_stop(m, cx); + return; + } + if let Some(target) = mem(m).interaction_target.value() { + mem(m).look_target.set(Tracker::Entity(target, true)); + } + // No offer matches the player's item: look for a while only. + *look_time = (*look_time).min(40); + *look_time -= 1; + } + B::TradeWithVillager(t) => { + if now > t.end || !villager_target_valid(m, cx.w, Mem::InteractionTarget) { + self.do_stop(m, cx); + return; + } + if let Some(target) = mem(m).interaction_target.value() + && let Some(i) = cx.w.target_info(target) + && i.position.distance_squared(m.position) <= 5.0 + { + let Who::Mob(other) = target else { return }; + cx.events.push(MobEvent::VillagerMeet { mob: m.id, other }); + } + } + B::MakeLove { birth, .. } => { + if now > *birth || !breeding_possible(m, cx.w) { + self.do_stop(m, cx); + return; + } + let Some(target) = mem(m).breed_target.value() else { + return; + }; + let Who::Mob(partner) = target else { return }; + if cx + .w + .target_info(target) + .is_some_and(|t| t.position.distance_squared(m.position) <= 5.0) + { + lock_gaze(m, target); + if now >= *birth { + cx.events.push(MobEvent::VillagerBirth { + parent: m.id, + partner, + }); + } else if m.random.next_int_bound(35).unwrap_or(1) == 0 { + let mut p = vec![m.position]; + if let Some(t) = cx.w.target_info(target) { + p.push(t.position); + } + for at in p { + cx.events.push(MobEvent::Particles { + kind: "heart", + at: [at.x, at.y + 1.8, at.z], + count: 1, + }); + } + } + } + } + B::WorkAtPoi { t, .. } => { + let still = mem(m) + .job_site + .value() + .is_some_and(|site| closer_to_center(site, m.position, 1.73)); + if now > t.end || !still { + self.do_stop(m, cx); + } + } + B::HarvestFarmland { + t, + next_ok, + target, + valid, + worked, + } => { + if now > t.end || *worked >= 200 { + self.do_stop(m, cx); + return; + } + if target.is_none_or(|p| closer_to_center(p, m.position, 1.0)) { + harvest_tick(m, cx, next_ok, target, valid); + *worked += 1; + } + } + B::SleepInBed { .. } => { + let still = mem(m).home.value().is_some_and(|bed| { + brain_mut(m).is_active(Act::Rest) + && m.position.y > f64::from(bed[1]) + 0.4 + && closer_to_center(bed, m.position, 1.14) + }); + if !still { + self.do_stop(m, cx); + } + } + B::Celebrate(t) => { + if now > t.end || !super::villager::raid_nearby(m) { + self.do_stop(m, cx); + return; + } + if m.random.next_int_bound(100).unwrap_or(1) == 0 { + m.voice("entity.villager.celebrate", cx.events); + } + if m.random.next_int_bound(200).unwrap_or(1) == 0 + && no_blocks_above(m, cx.w, block_of(m.position)) + { + let color = m.random.next_int_bound(16).unwrap_or(0) as usize; + let flight = m.random.next_int_bound(3).unwrap_or(0) as u8; + cx.events.push(MobEvent::Firework { + at: [m.position.x, m.eye_y(), m.position.z], + color, + flight, + }); + } + } + B::UseBonemeal(_) => self.do_stop(m, cx), + _ => {} + } + } + + fn do_stop(&mut self, m: &mut Mob, cx: &mut Bx) { + if self.one_shot_stop() { + return; + } + let now = cx.now; + match self { + B::Gate(g) => g.do_stop(m, cx), + B::Swim(t) | B::PanicTrigger(t) | B::DoNothing(t) => t.running = false, + B::JumpOnBed { + t, + bed, + time_left, + jumps, + cooldown, + } => { + t.running = false; + *bed = None; + *time_left = 0; + *jumps = 0; + *cooldown = 0; + } + B::SleepInBed { t, next_ok } => { + t.running = false; + if super::villager::sleeping(m) { + super::villager::stop_sleeping(m, cx.w); + mem(m).last_woken.set(now); + *next_ok = now + 40; + } + } + B::Celebrate(t) => { + t.running = false; + brain_mut(m).update_from_schedule(cx.w.game_time, cx.w.day_time); + } + B::LookAtTargetSink(t) => { + t.running = false; + mem(m).look_target.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::FollowTradingPlayer(t) => { + t.running = false; + let mm = mem(m); + mm.walk_target.clear(); + mm.look_target.clear(); + } + B::GoToPotentialJobSite(t) => { + t.running = false; + mem(m).potential_job_site.clear(); + } + B::GiveGiftToHero { t, until_next, .. } => { + t.running = false; + *until_next = 600 + cx.lr.next_int_bound(6001).unwrap_or(0); + let mm = mem(m); + mm.interaction_target.clear(); + mm.walk_target.clear(); + mm.look_target.clear(); + } + B::ShowTrades { t, .. } => { + t.running = false; + mem(m).interaction_target.clear(); + } + B::TradeWithVillager(t) => { + t.running = false; + mem(m).interaction_target.clear(); + } + B::MakeLove { t, .. } => { + t.running = false; + mem(m).breed_target.clear(); + } + B::UseBonemeal(t) => t.running = false, + B::WorkAtPoi { t, .. } => t.running = false, + B::HarvestFarmland { + t, next_ok, worked, .. + } => { + t.running = false; + *worked = 0; + let mm = mem(m); + mm.look_target.clear(); + mm.walk_target.clear(); + *next_ok = now + 40; + } + _ => {} + } + } +} + +fn manhattan_sq(a: [i32; 3], b: [i32; 3]) -> i64 { + let d = [ + i64::from(a[0] - b[0]), + i64::from(a[1] - b[1]), + i64::from(a[2] - b[2]), + ]; + d[0] * d[0] + d[1] * d[1] + d[2] * d[2] +} +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, + } +} +/// `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 +} +fn panic_condition(m: &Mob) -> bool { + mem_ref(m).is_some_and(|mm| mm.hurt_by.present() || mm.nearest_hostile.present()) +} +/// `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) + } + _ => 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 +} +/// `LookAndFollowTradingPlayerSink.checkExtraStartConditions`. +fn follow_trading_condition(m: &Mob, w: &MobWorld) -> bool { + m.extra.flag2 + && m.alive() + && !m.fluids.in_water + && !(m.hurt_time > 0) + && w.player + .as_ref() + .is_some_and(|p| m.distance_sqr(p.position) <= 16.0) +} +fn follow_trading_player(m: &mut Mob) { + let mm = mem(m); + mm.walk_target.set(WalkTarget { + target: Tracker::Entity(Who::Player, false), + speed: 0.5, + close: 2, + }); + mm.look_target.set(Tracker::Entity(Who::Player, true)); +} +/// `GiveGiftToHero.isHeroVisible`. +fn hero_visible(m: &Mob, w: &MobWorld) -> bool { + mem_ref(m).is_some_and(|mm| mm.nearest_visible_player.get() == Some(&Who::Player)) + && w.player.as_ref().is_some_and(|p| p.hero) +} +/// `ShowTradesToPlayer.checkExtraStartConditions`. +fn show_trades_condition(m: &Mob, w: &MobWorld) -> bool { + let Some(target) = mem_ref(m).and_then(|mm| mm.interaction_target.value()) else { + return false; + }; + target == Who::Player + && m.alive() + && !m.is_baby() + && w.target_info(target) + .is_some_and(|t| t.alive && m.distance_sqr(t.position) <= 17.0) +} +/// `BehaviorUtils.targetIsValid` for a villager. +fn villager_target_valid(m: &mut Mob, w: &MobWorld, which: Mem) -> bool { + let target = mem_ref(m).and_then(|mm| match which { + Mem::InteractionTarget => mm.interaction_target.value(), + Mem::BreedTarget => mm.breed_target.value(), + _ => None, + }); + let Some(Who::Mob(id)) = target else { + return false; + }; + w.seen(id) + .is_some_and(|s| s.species == Species::Villager && s.alive) + && visible_contains(m, w, Who::Mob(id)) +} +/// `Villager.playWorkSound`. +fn play_work_sound(m: &mut Mob, cx: &mut Bx) { + if let Some(sound) = super::villager::work_sound(m.extra.variant2) { + m.voice(sound, cx.events); + } +} +/// `WorkAtPoi.start`'s restock. +fn restock_if_due(m: &mut Mob, w: &MobWorld) { + let day = w.day_time.div_euclid(24000); + if let Some(t) = m.extra.trade.as_mut() + && t.should_restock(w.game_time, day) + { + t.restock(w.game_time); + } +} +/// `HarvestFarmland.validFarmlandAroundVillager`: ripe crops and bare +/// farmland around the villager. +fn farmland_around(m: &Mob, w: &MobWorld) -> Vec<[i32; 3]> { + let mut valid = Vec::new(); + for x in -1..=1 { + for y in -1..=1 { + for z in -1..=1 { + let p = [ + (m.position.x + f64::from(x)).floor() as i32, + (m.position.y + f64::from(y)).floor() as i32, + (m.position.z + f64::from(z)).floor() as i32, + ]; + if farmland_valid(w, p) { + valid.push(p); + } + } + } + } + valid +} +fn farmland_valid(w: &MobWorld, p: [i32; 3]) -> bool { + super::villager::ripe_crop(w, p) + || w.facts.is_air(w.world.block(p[0], p[1], p[2])) + && w.block_name(p[0], p[1] - 1, p[2]) == "minecraft:farmland" +} +/// `HarvestFarmland.getValidFarmland`: one picked by the level random. +fn pick_farmland(valid: &[[i32; 3]], cx: &mut Bx) -> Option<[i32; 3]> { + if valid.is_empty() { + return None; + } + let i = cx.lr.next_int_bound(valid.len() as i32).unwrap_or(0) as usize; + Some(valid[i]) +} +/// The seeds a villager plants (`VILLAGER_PLANTABLE_SEEDS`) and their crops. +fn seed_crop(item: &str) -> Option<&'static str> { + Some(match item { + "minecraft:wheat_seeds" => "minecraft:wheat", + "minecraft:potato" => "minecraft:potatoes", + "minecraft:carrot" => "minecraft:carrots", + "minecraft:beetroot_seeds" => "minecraft:beetroots", + "minecraft:torchflower_seeds" => "minecraft:torchflower_crop", + "minecraft:pitcher_pod" => "minecraft:pitcher_crop", + _ => return None, + }) +} +/// `HarvestFarmland.tick` at the farmland: harvest a ripe crop, sow bare +/// farmland, and move on from a growing crop. +fn harvest_tick( + m: &mut Mob, + cx: &mut Bx, + next_ok: &mut i64, + target: &mut Option<[i32; 3]>, + valid: &mut Vec<[i32; 3]>, +) { + let Some(p) = *target else { return }; + if cx.now <= *next_ok { + return; + } + let w = cx.w; + let ripe = super::villager::ripe_crop(w, p); + let air = w.facts.is_air(w.world.block(p[0], p[1], p[2])); + let growing = !ripe && super::villager::crop(w, p); + if ripe { + cx.events.push(MobEvent::BreakBlock { pos: p, drop: true }); + } + if air && w.block_name(p[0], p[1] - 1, p[2]) == "minecraft:farmland" { + let e = super::villager::ext_mut(m); + if let Some(slot) = e + .inventory + .iter() + .position(|s| s.count > 0 && seed_crop(&s.item).is_some()) + { + let crop = seed_crop(&e.inventory[slot].item).unwrap_or("minecraft:wheat"); + e.inventory[slot].count -= 1; + if e.inventory[slot].count == 0 { + e.inventory.remove(slot); + } + cx.events.push(MobEvent::SetBlockName { + pos: p, + name: crop, + effect: false, + }); + cx.events.push(MobEvent::Sound( + "item.crop.plant", + [f64::from(p[0]), f64::from(p[1]), f64::from(p[2])], + 1.0, + 1.0, + )); + } + } + if growing { + valid.retain(|q| *q != p); + *target = pick_farmland(valid, cx); + if let Some(q) = *target { + *next_ok = cx.now + 20; + let mm = mem(m); + mm.walk_target.set(WalkTarget::block(q, 0.5, 1)); + mm.look_target.set(Tracker::Block(q)); + } + } +} +/// The remembered POI positions a behaviour reads. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum PoiMem { + Job, + Potential, + Home, + Meeting, +} +impl PoiMem { + fn get(self, m: &Mob) -> Option<[i32; 3]> { + let mm = mem_ref(m)?; + match self { + PoiMem::Job => mm.job_site.value(), + PoiMem::Potential => mm.potential_job_site.value(), + PoiMem::Home => mm.home.value(), + PoiMem::Meeting => mm.meeting_point.value(), + } + } + fn clear(self, m: &mut Mob) { + let mm = mem(m); + match self { + PoiMem::Job => mm.job_site.clear(), + PoiMem::Potential => mm.potential_job_site.clear(), + PoiMem::Home => mm.home.clear(), + PoiMem::Meeting => mm.meeting_point.clear(), + } + } +} +fn dist_sqr(a: [i32; 3], b: [i32; 3]) -> i64 { + manhattan_sq(a, b) +} +/// Every bed head within `radius` (`PoiManager.getInRange(HOME, ..., ANY)`), +/// in scan order. +fn homes_in_range(m: &Mob, w: &MobWorld, radius: i32) -> Vec<[i32; 3]> { + let c = block_of(m.position); + let r2 = i64::from(radius) * i64::from(radius); + let mut out = Vec::new(); + let y0 = (c[1] - radius).max(crate::chunk::MIN_Y); + let y1 = (c[1] + radius).min(crate::chunk::MIN_Y + crate::chunk::HEIGHT - 1); + for y in y0..=y1 { + for z in c[2] - radius..=c[2] + radius { + for x in c[0] - radius..=c[0] + radius { + let p = [x, y, z]; + if dist_sqr(p, c) <= r2 + && w.world.loaded(x, z) + && poi_at(w, x, y, z) == Some(Poi::Home) + { + out.push(p); + } + } + } + } + out +} +/// `MoveToSkySeeingSpot.hasNoBlocksAbove`. +fn no_blocks_above(m: &Mob, w: &MobWorld, p: [i32; 3]) -> bool { + w.can_see_sky(p[0], p[1], p[2]) + && f64::from(w.motion_blocking_height(p[0], p[2])) <= m.position.y +} +/// `VillagerMakeLove.isBreedingPossible`. +fn breeding_possible(m: &mut Mob, w: &MobWorld) -> bool { + let Some(Who::Mob(id)) = mem_ref(m).and_then(|mm| mm.breed_target.value()) else { + return false; + }; + villager_target_valid(m, w, Mem::BreedTarget) + && super::villager::can_breed(m) + && w.seen(id).is_some_and(|s| s.in_love) +} +/// `BehaviorUtils.lockGazeAndWalkToEachOther`, this villager's half. +fn lock_gaze(m: &mut Mob, target: Who) { + let mm = mem(m); + mm.look_target.set(Tracker::Entity(target, true)); + mm.walk_target.set(WalkTarget { + target: Tracker::Entity(target, true), + speed: 0.5, + close: 2, + }); +} +/// `SetWalkTargetFromBlockMemory`. +fn walk_to_block_memory( + m: &mut Mob, + cx: &mut Bx, + which: PoiMem, + speed: f32, + close: i32, + too_far: i32, + too_long: i64, +) -> bool { + if mem(m).walk_target.present() { + return false; + } + let Some(target) = which.get(m) else { + return false; + }; + let since = mem(m).cant_reach_walk_target_since.value(); + let here = block_of(m.position); + if since.is_none_or(|s| cx.w.game_time - s <= too_long) { + if manhattan(target, here) > too_far { + let to = [ + f64::from(target[0]) + 0.5, + f64::from(target[1]), + f64::from(target[2]) + 0.5, + ]; + let mut tries = 0; + loop { + let step = m.default_random_pos_towards( + cx.w, + 15, + 7, + to, + f64::from(std::f32::consts::FRAC_PI_2), + ); + if let Some(s) = step { + let b = [ + s[0].floor() as i32, + s[1].floor() as i32, + s[2].floor() as i32, + ]; + if manhattan(b, block_of(m.position)) <= too_far { + mem(m).walk_target.set(WalkTarget::point(s, speed, close)); + break; + } + } + tries += 1; + if tries == 1000 { + which.clear(m); + mem(m).cant_reach_walk_target_since.set(cx.now); + return true; + } + } + } else if manhattan(target, here) > close { + mem(m) + .walk_target + .set(WalkTarget::block(target, speed, close)); + } + } else { + which.clear(m); + mem(m).cant_reach_walk_target_since.set(cx.now); + } + true +} +/// `InteractWithDoor`: open the doors on the path, close the ones passed. +fn interact_with_doors(m: &mut Mob, cx: &mut Bx, from: PathNode, to: PathNode) { + let _ = (m, cx, from, to); +} +/// The scan order of POI candidates (before the nearest-first sort). +fn pois_scan_order(_m: &Mob, found: &[(Poi, [i32; 3])]) -> Vec { + (0..found.len()).collect() +} +/// Entity event 14: the client shows happy particles (with its own random, +/// not the mob's). +fn happy_particles(m: &Mob, cx: &mut Bx) { + let mut r = LegacyRandom::new(cx.now ^ i64::from(m.id)); + let (w, h) = (f64::from(m.width()), f64::from(m.height())); + for _ in 0..5 { + let at = [ + m.position.x + w * (2.0 * r.next_double() - 1.0), + m.position.y + h * r.next_double() + 1.0, + m.position.z + w * (2.0 * r.next_double() - 1.0), + ]; + cx.events.push(MobEvent::Particles { + kind: "happy_villager", + at, + count: 0, + }); + } +} +/// `BehaviorUtils.findSectionClosestToVillage`. +fn closest_section(villages: &[[i32; 3]], center: [i32; 3], radius: i32) -> [i32; 3] { + let here = sections_to_village(villages, center); + let mut best: Option<([i32; 3], i32)> = None; + for z in center[2] - radius..=center[2] + radius { + for y in center[1] - radius..=center[1] + radius { + for x in center[0] - radius..=center[0] + radius { + let s = [x, y, z]; + let d = sections_to_village(villages, s); + if d < here && best.is_none_or(|(_, b)| d < b) { + best = Some((s, d)); + } + } + } + } + best.map_or(center, |(s, _)| s) +} + +// ---- Packages ----------------------------------------------------------- + +fn timed(min: i32, max: i32) -> Timed { + Timed::new(min, max) +} +fn run_one(seed: i64, kids: Vec<(B, i32)>) -> B { + B::Gate(Box::new(Gate::run_one(seed, kids))) +} +fn look_at(what: LookAt) -> B { + B::LookAtEntity { + running: false, + what, + } +} +/// `getMinimalLookBehavior`. +fn look_minimal(seed: i64) -> B { + run_one( + seed, + vec![ + (look_at(LookAt::Species(Species::Villager)), 2), + (look_at(LookAt::Player), 2), + (B::DoNothing(timed(30, 60)), 8), + ], + ) +} +/// `getFullLookBehavior`. +fn look_full(seed: i64) -> B { + run_one( + seed, + vec![ + (look_at(LookAt::Species(Species::Cat)), 8), + (look_at(LookAt::Species(Species::Villager)), 2), + (look_at(LookAt::Player), 2), + (look_at(LookAt::Category("creature")), 1), + (look_at(LookAt::Category("water_creature")), 1), + (look_at(LookAt::Category("axolotls")), 1), + (look_at(LookAt::Category("underground_water_creature")), 1), + (look_at(LookAt::Category("water_ambient")), 1), + (look_at(LookAt::Category("monster")), 1), + (B::DoNothing(timed(30, 60)), 2), + ], + ) +} +fn stroll(speed: f32, xz: i32, y: i32) -> B { + B::VillageBoundStroll { + running: false, + speed, + xz, + y, + } +} +fn walk_to(which: PoiMem, speed: f32, close: i32, too_far: i32, too_long: i64) -> B { + B::WalkToBlockMemory { + running: false, + which, + speed, + close, + too_far, + too_long, + } +} +fn trigger_gate(seed: i64, kids: Vec<(B, i32)>) -> B { + B::TriggerGate { + running: false, + random: LegacyRandom::new(seed), + kids: kids.into_iter().map(|(b, w)| (b, w, 0.0)).collect(), + } +} +fn gift() -> B { + B::GiveGiftToHero { + t: timed(100, 100), + until_next: 600, + given: false, + started: 0, + } +} +fn show_trades() -> B { + B::ShowTrades { + t: timed(400, 1600), + look_time: 0, + } +} +fn interact(kind: Interact) -> B { + B::InteractWith { + running: false, + kind, + } +} +fn trade_gate(seed: i64) -> B { + B::Gate(Box::new(Gate::ordered( + seed, + Mem::InteractionTarget, + B::TradeWithVillager(timed(60, 60)), + ))) +} +fn jump_on_bed() -> B { + B::JumpOnBed { + t: timed(60, 60), + bed: None, + time_left: 0, + jumps: 0, + cooldown: 0, + } +} +fn move_to_target_sink(min: i32, max: i32) -> B { + B::MoveToTargetSink { + t: timed(min, max), + cooldown: 0, + path: None, + last_target: None, + speed: 0.0, + } +} +fn acquire(filter: PoiFilter, poi: Poi, only_adult: bool, event: bool) -> B { + B::AcquirePoi { + running: false, + filter, + poi, + only_adult, + event, + next: 0, + retries: Vec::new(), + } +} +fn validate(filter: PoiFilter, which: PoiMem) -> B { + B::ValidatePoi { + running: false, + filter, + which, + } +} +/// `VillagerGoalPackages`: the behaviours of every activity, in iteration +/// order. `speedModifier` is 0.5 throughout. +fn packages(baby: bool, seed: i64, farmer: bool) -> Vec { + let mut v: Vec = Vec::new(); + let mut add = |prio: i32, act: Act, b: B| v.push(Entry { prio, act, b }); + if baby { + // PLAY + let p = Act::Play; + add(0, p, move_to_target_sink(80, 120)); + add(5, p, look_full(seed)); + add(5, p, B::PlayTag(false)); + let mut play = Gate::run_one( + seed, + vec![ + (interact(Interact::Villager), 2), + (interact(Interact::Cat), 1), + (stroll(0.5, 10, 7), 1), + (B::WalkToLookTarget(false), 1), + (jump_on_bed(), 2), + (B::DoNothing(timed(20, 40)), 2), + ], + ); + play.absent = Some(Mem::VisibleBabies); + add(5, p, B::Gate(Box::new(play))); + add(99, p, B::UpdateActivity(false)); + } else { + // WORK + let w = Act::Work; + add(5, w, look_minimal(seed)); + add( + 5, + w, + run_one( + seed, + vec![ + ( + B::WorkAtPoi { + t: timed(60, 60), + last_check: 0, + }, + 7, + ), + ( + B::StrollAroundPoi { + running: false, + next_ok: 0, + max_dist: 4, + which: PoiMem::Job, + }, + 2, + ), + ( + B::StrollToPoi { + running: false, + next_ok: 0, + }, + 5, + ), + ( + B::StrollToPoiList { + running: false, + next_ok: 0, + }, + 5, + ), + ( + B::HarvestFarmland { + t: timed(60, 60), + next_ok: 0, + target: None, + valid: Vec::new(), + worked: 0, + }, + if farmer { 2 } else { 5 }, + ), + (B::UseBonemeal(timed(60, 60)), if farmer { 4 } else { 7 }), + ], + ), + ); + add(10, w, show_trades()); + add(10, w, B::SetLookAndInteract(false)); + add(2, w, walk_to(PoiMem::Job, 0.5, 9, 100, 1200)); + add(3, w, gift()); + add(99, w, B::UpdateActivity(false)); + } + // CORE + let c = Act::Core; + add(0, c, B::Swim(timed(60, 60))); + add( + 0, + c, + B::InteractWithDoor { + running: false, + last_node: None, + cooldown: 0, + }, + ); + add(0, c, B::LookAtTargetSink(timed(45, 90))); + add(0, c, B::PanicTrigger(timed(60, 60))); + add(0, c, B::WakeUp(false)); + add(0, c, B::ReactToBell(false)); + add(0, c, B::SetRaidStatus(false)); + add(0, c, validate(PoiFilter::Held, PoiMem::Job)); + add(0, c, validate(PoiFilter::Acquirable, PoiMem::Potential)); + add(1, c, move_to_target_sink(150, 250)); + add(2, c, B::PoiCompetitorScan(false)); + add(3, c, B::FollowTradingPlayer(timed(i32::MAX, i32::MAX))); + add(5, c, B::GoToWantedItem(false)); + add( + 6, + c, + acquire(PoiFilter::Acquirable, Poi::Job(0), true, false), + ); + add(7, c, B::GoToPotentialJobSite(timed(1200, 1200))); + add(8, c, B::YieldJobSite(false)); + add(10, c, acquire(PoiFilter::Home, Poi::Home, false, true)); + add(10, c, acquire(PoiFilter::Meeting, Poi::Meeting, true, true)); + add(10, c, B::AssignProfession(false)); + add(10, c, B::ResetProfession(false)); + // MEET + let me = Act::Meet; + add( + 2, + me, + trigger_gate( + seed, + vec![ + ( + B::StrollAroundPoi { + running: false, + next_ok: 0, + max_dist: 40, + which: PoiMem::Meeting, + }, + 2, + ), + (B::SocializeAtBell(false), 2), + ], + ), + ); + add(10, me, show_trades()); + add(10, me, B::SetLookAndInteract(false)); + add(2, me, walk_to(PoiMem::Meeting, 0.5, 6, 100, 200)); + add(3, me, gift()); + add(3, me, validate(PoiFilter::Meeting, PoiMem::Meeting)); + add(3, me, trade_gate(seed)); + add(5, me, look_full(seed)); + add(99, me, B::UpdateActivity(false)); + // REST + let r = Act::Rest; + add(2, r, walk_to(PoiMem::Home, 0.5, 1, 150, 1200)); + add(3, r, validate(PoiFilter::Home, PoiMem::Home)); + add( + 3, + r, + B::SleepInBed { + t: timed(60, 60), + next_ok: 0, + }, + ); + let mut homeless = Gate::run_one( + seed, + vec![ + ( + B::ClosestHomeAsWalkTarget { + running: false, + last_update: 0, + cache: Vec::new(), + }, + 1, + ), + ( + B::InsideBrownianWalk { + running: false, + random: LegacyRandom::new(seed), + }, + 4, + ), + (B::GoToClosestVillage(false), 2), + (B::DoNothing(timed(20, 40)), 2), + ], + ); + homeless.absent = Some(Mem::Home); + add(5, r, B::Gate(Box::new(homeless))); + add(5, r, look_minimal(seed)); + add(99, r, B::UpdateActivity(false)); + // IDLE + let i = Act::Idle; + add( + 2, + i, + run_one( + seed, + vec![ + (interact(Interact::Villager), 2), + (interact(Interact::BreedVillager), 1), + (interact(Interact::Cat), 1), + (stroll(0.5, 10, 7), 1), + (B::WalkToLookTarget(false), 1), + (jump_on_bed(), 1), + (B::DoNothing(timed(30, 60)), 1), + ], + ), + ); + add(3, i, gift()); + add(3, i, B::SetLookAndInteract(false)); + add(3, i, show_trades()); + add(3, i, trade_gate(seed)); + add( + 3, + i, + B::Gate(Box::new(Gate::ordered( + seed, + Mem::BreedTarget, + B::MakeLove { + t: timed(350, 350), + birth: 0, + }, + ))), + ); + add(5, i, look_full(seed)); + add(99, i, B::UpdateActivity(false)); + // PANIC + let pa = Act::Panic; + add(0, pa, B::CalmDown(false)); + add( + 1, + pa, + B::WalkAwayFrom { + running: false, + hostile: true, + }, + ); + add( + 1, + pa, + B::WalkAwayFrom { + running: false, + hostile: false, + }, + ); + add(3, pa, stroll(0.75, 2, 2)); + add(5, pa, look_minimal(seed)); + // PRE_RAID + let pr = Act::PreRaid; + add(0, pr, B::RingBell(false)); + add( + 0, + pr, + trigger_gate( + seed, + vec![ + (walk_to(PoiMem::Meeting, 0.75, 2, 150, 200), 6), + (stroll(0.75, 10, 7), 2), + ], + ), + ); + add(5, pr, look_minimal(seed)); + add(99, pr, B::ResetRaidStatus(false)); + // RAID + let ra = Act::Raid; + add( + 0, + ra, + B::RaidSequence { + running: false, + victory: true, + then: Box::new(trigger_gate( + seed, + vec![ + ( + B::MoveToSkySeeingSpot { + running: false, + speed: 0.5, + }, + 5, + ), + (stroll(0.55, 10, 7), 2), + ], + )), + }, + ); + add(0, ra, B::Celebrate(timed(600, 600))); + add( + 2, + ra, + B::RaidSequence { + running: false, + victory: false, + then: Box::new(B::LocateHidingPlace { + running: false, + radius: 24, + speed: 0.7, + close: 1, + }), + }, + ); + add(5, ra, look_minimal(seed)); + add(99, ra, B::ResetRaidStatus(false)); + // HIDE + let h = Act::Hide; + add( + 0, + h, + B::SetHiddenState { + running: false, + hidden: 0, + }, + ); + add( + 1, + h, + B::LocateHidingPlace { + running: false, + radius: 32, + speed: 0.625, + close: 2, + }, + ); + add(5, h, look_minimal(seed)); + v.sort_by_key(|e| (e.prio, e.act.slot())); + v +} + +// ---- The probe's view --------------------------------------------------- + +fn who(w: Who) -> String { + match w { + Who::Player => "player".into(), + Who::Mob(id) => format!("e{id}"), + } +} +fn pos(p: [i32; 3]) -> String { + format!("{},{},{}", p[0], p[1], p[2]) +} +fn tracker(t: Tracker) -> String { + match t { + Tracker::Entity(e, _) => who(e), + Tracker::Block(p) => pos(p), + Tracker::Point(v) => pos([ + v[0].floor() as i32, + v[1].floor() as i32, + v[2].floor() as i32, + ]), + } +} +/// The active activities and the memories with values, as the oracle +/// prints them (`act core|idle`, `mem name=value...` sorted). +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); + } + }; + } + slot!("home", mm.home, |p: &[i32; 3]| pos(*p)); + slot!("job_site", mm.job_site, |p: &[i32; 3]| pos(*p)); + slot!( + "potential_job_site", + mm.potential_job_site, + |p: &[i32; 3]| pos(*p) + ); + slot!("meeting_point", mm.meeting_point, |p: &[i32; 3]| pos(*p)); + slot!("secondary_job_site", mm.secondary_job_site, |l: &Vec< + [i32; 3], + >| format!( + "n{}", + l.len() + )); + slot!("mobs", mm.mobs, |l: &Vec| format!("n{}", l.len())); + slot!("visible_mobs", mm.visible_mobs, |_: &Visible| { + "NearestVisibleLivingEntities".to_string() + }); + slot!( + "visible_villager_babies", + mm.visible_villager_babies, + |l: &Vec| format!("n{}", l.len()) + ); + slot!( + "nearest_players", + mm.nearest_players, + |l: &Vec| format!("n{}", l.len()) + ); + 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, + |l: &Vec| format!("n{}", l.len()) + ); + 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!("interaction_target", mm.interaction_target, |e: &Who| who( + *e + )); + slot!("breed_target", mm.breed_target, |e: &Who| who(*e)); + slot!("path", mm.path, |p: &Path| format!("path{}", pos(p.target))); + slot!( + "doors_to_close", + mm.doors_to_close, + |l: &Vec<[i32; 3]>| format!("n{}", l.len()) + ); + slot!("nearest_bed", mm.nearest_bed, |p: &[i32; 3]| pos(*p)); + slot!("hurt_by", mm.hurt_by, |_: &i64| "DamageSource".to_string()); + slot!("hurt_by_entity", mm.hurt_by_entity, |e: &Who| who(*e)); + slot!("nearest_hostile", mm.nearest_hostile, |e: &Who| who(*e)); + slot!("hiding_place", mm.hiding_place, |p: &[i32; 3]| pos(*p)); + slot!("heard_bell_time", mm.heard_bell_time, |t: &i64| t + .to_string()); + slot!( + "cant_reach_walk_target_since", + mm.cant_reach_walk_target_since, + |t: &i64| t.to_string() + ); + slot!( + "golem_detected_recently", + mm.golem_detected_recently, + |t: &bool| t.to_string() + ); + slot!("last_slept", mm.last_slept, |t: &i64| t.to_string()); + slot!("last_woken", mm.last_woken, |t: &i64| t.to_string()); + slot!("last_worked_at_poi", mm.last_worked_at_poi, |t: &i64| t + .to_string()); + out.sort(); + Some((acts.join("|"), out.join(" "))) +} +/// `Villager.stopSleeping`: remember waking. +pub fn woken(m: &mut Mob, now: i64) { + if brain(m).is_some() { + mem(m).last_woken.set(now); + } +} +/// What other villagers see of this one's brain. +pub fn potential_job_site(m: &Mob) -> Option<[i32; 3]> { + mem_ref(m).and_then(|mm| mm.potential_job_site.value()) +} +/// Whether a seen mob is a villager wanting to breed (`AgeableMob::canBreed`). +pub fn seen_can_breed(s: &Seen) -> bool { + s.species == Species::Villager && s.in_love +}