Merge origin/parity/entity-ai into parity/rendering-be

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-12 15:39:00 +02:00
34 changed files with 5724 additions and 1011 deletions
+4
View File
@@ -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
+88 -4
View File
@@ -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",
@@ -171,6 +173,12 @@ fn goal_name(m: &Mob, name: &str) -> String {
"TryFindWater" => "TryFindWaterGoal",
"RangedAttack" => "RangedAttackGoal",
"MoveTowardsTarget" => "MoveTowardsTargetGoal",
"DrownedGoToWater" => "DrownedGoToWaterGoal",
"TakeBlock" => "EndermanTakeBlockGoal",
"LeaveBlock" => "EndermanLeaveBlockGoal",
"FreezeWhenLookedAt" => "EndermanFreezeWhenLookedAt",
"LookForPlayer" => "EndermanLookForPlayerGoal",
"HealRaiders" => "NearestHealableRaiderTargetGoal",
other => return other.to_owned(),
};
vanilla.to_owned()
@@ -221,13 +229,43 @@ 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(),
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),
}
}
/// 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,
}
}
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;
@@ -316,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<()> {
@@ -429,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| {
@@ -485,16 +537,38 @@ 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();
for m in &mut mobs {
#[allow(unused_mut)] // filled only with the rng-trace feature
let mut traces: Vec<String> = 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 +582,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)?;
+3 -1
View File
@@ -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",
+28 -37
View File
@@ -127,6 +127,14 @@ 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<'_> {
@@ -365,6 +373,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()
@@ -445,6 +454,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 +462,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();
@@ -627,6 +642,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)
}
@@ -2384,6 +2410,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).
@@ -2421,42 +2448,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
+4 -2
View File
@@ -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)
}
+76 -2
View File
@@ -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;
@@ -359,6 +360,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 +417,7 @@ impl Damage {
| DamageKind::InWall
| DamageKind::Generic
| DamageKind::SonicBoom
| DamageKind::OutOfWorld
)
}
pub fn is_fire(&self) -> bool {
@@ -436,6 +440,7 @@ impl Damage {
| DamageKind::Cactus
| DamageKind::Generic
| DamageKind::InWall
| DamageKind::OutOfWorld
)
}
pub fn is_projectile(&self) -> bool {
@@ -591,6 +596,9 @@ pub struct Mob {
pub ai: Box<ai::Ai>,
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,
@@ -622,6 +630,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 {
@@ -876,6 +893,60 @@ 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,
/// `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
/// `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<MobEvent>, 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)]
@@ -929,6 +1000,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<MobType>, position: Vec3, yaw: f32) -> Self {
@@ -972,6 +1045,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,
@@ -1164,10 +1238,10 @@ impl Mob {
pub fn tick(
&mut self,
w: &MobWorld,
_random: &mut LegacyRandom,
level_random: &mut LegacyRandom,
events: &mut Vec<MobEvent>,
) -> bool {
ai::tick(self, w, events)
ai::tick(self, w, level_random, events)
}
pub fn distance_to(&self, p: [f64; 3]) -> f64 {
let d = [
+171 -17
View File
@@ -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 {
@@ -158,6 +161,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 +206,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<MobEvent>) {
@@ -220,6 +224,9 @@ fn pre_tick(m: &mut Mob, events: &mut Vec<MobEvent>) {
}
/// Move controls implemented by the species (MoveKind::Custom).
pub fn custom_move_control(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
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);
}
@@ -263,8 +270,54 @@ 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<MobEvent>) -> bool {
pub fn tick(
m: &mut Mob,
w: &MobWorld,
level_random: &mut LegacyRandom,
events: &mut Vec<MobEvent>,
) -> bool {
if m.removed {
return false;
}
@@ -299,7 +352,7 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) -> 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() {
@@ -309,7 +362,7 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) -> 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) {
@@ -326,6 +379,7 @@ fn tick_swing(m: &mut Mob) {
}
/// Entity.baseTick + LivingEntity.baseTick + Mob.baseTick.
fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
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;
@@ -354,6 +408,10 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
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) = (
@@ -489,7 +547,20 @@ fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
}
}
/// LivingEntity.aiStep (and Mob/AgeableMob/Animal additions).
fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: &mut Vec<MobEvent>) {
// 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);
}
// 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);
}
@@ -506,10 +577,9 @@ fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
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;
@@ -522,6 +592,7 @@ fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
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;
@@ -558,6 +629,82 @@ fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
}
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<MobEvent>) {
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;
@@ -572,7 +719,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<MobEvent>) {
fn server_ai_step(
m: &mut Mob,
w: &MobWorld,
level_random: &mut LegacyRandom,
events: &mut Vec<MobEvent>,
) {
m.ai.no_action_time += 1;
// A creaking looked at stands still.
if super::creaking::is_creaking(m) && !super::creaking::can_move(m) {
@@ -601,6 +753,11 @@ fn server_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
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);
@@ -626,6 +783,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,
_ => {}
@@ -636,12 +794,6 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
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),
@@ -939,13 +1091,15 @@ 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<MobEvent>) -> 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),
// Shulkers never move on their own.
Family::Shulker => true,
Family::Vex => super::vex::travel(m),
Family::Villager => super::villager::travel(m),
Family::Nautilus => super::nautilus::travel(m, w, input, events),
_ => false,
}
+6 -1
View File
@@ -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));
+1 -1
View File
@@ -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;
+172 -20
View File
@@ -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,
@@ -397,9 +429,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;
@@ -572,6 +617,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
}
@@ -635,6 +689,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<Who>,
look_time: i32,
}
impl LookAtPlayer {
@@ -643,45 +702,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;
}
let Some(p) = &cx.w.player else { return false };
p.alive && m.distance_sqr(p.position) <= f64::from(self.range * 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;
}
}
@@ -918,8 +1042,13 @@ 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<fn(&Mob, &MobWorld) -> bool>,
/// A condition checked before anything else, by subclasses overriding
/// `canUse` (SpiderTargetGoal: only in the dark).
pub gate: Option<fn(&Mob, &MobWorld) -> bool>,
/// The vanilla class name of a subclass (`Goal::name`).
pub label: Option<&'static str>,
found: Option<Who>,
target_goal: TargetState,
}
@@ -947,6 +1076,8 @@ impl NearestTarget {
must_reach: false,
interval: reduced(10),
when: None,
gate: None,
label: None,
found: None,
target_goal: TargetState {
unseen_memory: 60,
@@ -977,6 +1108,15 @@ impl NearestTarget {
self.when = Some(f);
self
}
pub fn gate(mut self, f: fn(&Mob, &MobWorld) -> bool) -> Self {
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 {
@@ -1005,10 +1145,18 @@ 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
}
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 +1976,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 +2029,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 +2041,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 {
+6 -1
View File
@@ -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(
+2 -2
View File
@@ -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;
}
+25 -3
View File
@@ -48,20 +48,35 @@ 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));
g.add(10, LookAtPlayer::mobs(15.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));
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(
@@ -82,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)]
@@ -526,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(
+1 -1
View File
@@ -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,
+46 -9
View File
@@ -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 {
@@ -108,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.
@@ -362,8 +390,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<MobEvent>) {
@@ -474,7 +507,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 +519,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 +539,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.
+6 -1
View File
@@ -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(
+11
View File
@@ -267,6 +267,17 @@ impl Mob {
let max = self.max_path_length();
self.create_path_raw(w, &[p], reach, max)
}
/// PathNavigation.createPath(Set<BlockPos>, 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<Path> {
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,
+3 -9
View File
@@ -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`.
@@ -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,
@@ -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;
+7 -2
View File
@@ -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 => {
+3 -3
View File
@@ -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)
+527 -44
View File
@@ -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());
@@ -55,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();
@@ -103,30 +133,280 @@ 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<MobEvent>,
) -> bool {
// 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);
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
p.shoot(
&mut crate::projectiles::own_random(m),
[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 {
"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 {
"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 {
"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 {
"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,
@@ -236,25 +516,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)
}
}
}
@@ -401,7 +738,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)),
@@ -419,7 +757,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,
@@ -476,3 +814,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;
}
}
+1
View File
@@ -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,
+84 -789
View File
@@ -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<Poi> {
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<u32, Option<Poi>> = 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<MobEvent>) {
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<MobEvent>) {
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<MobEvent>) {
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<super::zombie_villager::Cure>,
/// The villager's brain, built at its first tick.
pub brain: Option<Box<super::villager_brain::Brain>>,
}
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<bool> {
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<u32>,
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::<Vec<_>>();
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::*;
File diff suppressed because it is too large Load Diff
+71 -20
View File
@@ -20,20 +20,57 @@ 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)
.named("NearestAttackableWitchTargetGoal"),
);
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 +160,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
@@ -180,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,
@@ -194,14 +236,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<MobEvent>, 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<MobEvent>, 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() {
+60 -33
View File
@@ -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<MobEvent>) {
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<MobEvent>) {
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<MobEvent>) {
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<MobEvent>) {
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<MobEvent>) {
[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<MobEvent>) {
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<MobEvent>) {
}
}
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,
});
}
}
}
+11
View File
@@ -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.
+4
View File
@@ -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"
+47 -1
View File
@@ -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<bool> = const { Cell::new(false) };
static LOG: RefCell<Vec<String>> = 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<String> {
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
}
}
@@ -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): <path not set>
Space in storage for org.lwjgl.system.SharedLibraryExtractPath (MiB): <path not set>
Space in storage for io.netty.native.workdir (MiB): <path not set>
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;
@@ -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;
@@ -105,6 +109,8 @@ import net.minecraft.world.phys.Vec3;
public final class VanillaMobAiOracle {
static final List<Scenario> SCENARIOS = new ArrayList<>();
static PrintWriter out;
/** The temporary world directory, deleted before the oracle halts. */
static Path UNIVERSE;
static final List<String> SOUNDS = new ArrayList<>();
/** Draws of a traced mob random: the caller frames of each draw (AI_TRACE=scenario:from-to). */
@@ -208,7 +214,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 +353,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;
}
@@ -420,14 +434,23 @@ 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);
// 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);
}
List<Mob> mobs = new ArrayList<>();
List<Brain<?>> brains = new ArrayList<>();
List<Long> seeds = new ArrayList<>();
int id = 100000;
for (MobSpec spec : s.mobs) {
EntityType<?> type = BuiltInRegistries.ENTITY_TYPE.getValue(net.minecraft.resources.Identifier.parse(spec.type));
@@ -452,7 +475,10 @@ public final class VanillaMobAiOracle {
@SuppressWarnings("unchecked")
Map<Object, Sensor<?>> sensors = (Map<Object, Sensor<?>>) 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();
@@ -467,6 +493,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);
@@ -474,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();
@@ -491,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<Integer, Map<?, Set<BehaviorControl<?>>>> byPriority = (Map<Integer, Map<?, Set<BehaviorControl<?>>>>) get(brain, "availableBehaviorsByPriority");
for (Map<?, Set<BehaviorControl<?>>> byActivity : byPriority.values())
for (Set<BehaviorControl<?>> 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";
+23 -5
View File
@@ -9,10 +9,14 @@ 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
import shutil
import struct
import subprocess
import sys
@@ -200,6 +204,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 +228,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)
@@ -231,13 +240,22 @@ 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:
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