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