diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 8428a9410..0efd328f4 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -309,6 +309,9 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { } map.insert("equipment".into(), Tag::Compound(equipment)); } + "minecraft:bat" => { + map.insert("BatFlags".into(), Tag::Byte(i8::from(m.extra.flag))); + } "minecraft:creaking" => { // home_pos: the heart it is bound to. if let Some(home) = m.extra.home { @@ -612,6 +615,10 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.ticks_frozen = number(tag.get("TicksFrozen")).unwrap_or(0) as i32; m.silent = flag(tag, "Silent"); m.invulnerable_flag = flag(tag, "Invulnerable"); + if m.species() == crate::mobs::Species::Bat { + // Bat.readAdditionalSaveData: BatFlags bit 0, resting. + m.extra.flag = number(tag.get("BatFlags")).unwrap_or(0) & 1 != 0; + } if m.species() == crate::mobs::Species::Creeper { m.extra.charged = flag(tag, "powered"); // Creeper.readAdditionalSaveData: `ignited` lights the fuse. diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 12bd29877..5f5ad325b 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -11,6 +11,7 @@ pub mod anim; pub mod animal_brain; pub mod aquatic; pub mod axolotl; +pub mod bat; pub mod body_anim; pub mod brain; pub mod breeze; @@ -294,7 +295,7 @@ pub struct Flags { pub climber: bool, /// Striders stand on lava. pub lava_walker: bool, - /// LivingEntity.omnidirectionalAirMover (bees, parrots, bats, allays). + /// LivingEntity.omnidirectionalAirMover (bees and parrots). pub omnidirectional: bool, pub fire_immune: bool, /// EntityTypeTags.BURN_IN_DAYLIGHT @@ -1752,8 +1753,14 @@ impl Mob { } /// LivingEntity.getVoicePitch. pub fn voice_pitch(&mut self) -> f32 { - (self.random.next_float() - self.random.next_float()) * 0.2 - + if self.is_baby() { 1.5 } else { 1.0 } + let pitch = (self.random.next_float() - self.random.next_float()) * 0.2 + + if self.is_baby() { 1.5 } else { 1.0 }; + // Bat.getVoicePitch: a little lower. + if self.species() == Species::Bat { + pitch * 0.95 + } else { + pitch + } } /// Mob.playSound with LivingEntity.getVoicePitch. pub fn voice(&mut self, event: &'static str, events: &mut Vec) { diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 1f33bcf41..e3aad61df 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -104,6 +104,7 @@ pub enum Family { /// Nautili and zombie nautili. Nautilus, Strider, + Bat, } pub fn family(s: Species) -> Family { use Species as S; @@ -163,6 +164,7 @@ pub fn family(s: Species) -> Family { S::Warden => Family::Warden, S::Shulker => Family::Shulker, S::Strider => Family::Strider, + S::Bat => Family::Bat, _ => Family::Generic, } } @@ -218,6 +220,7 @@ pub fn register(m: &mut Mob) { Family::Creaking => super::creaking::register(m), Family::Nautilus => super::nautilus::register(m), Family::Strider => super::strider::register(m), + Family::Bat => super::bat::register(m), } } /// Mob.tick additions that run before the entity tick (creeper fuse, puffing). @@ -398,6 +401,9 @@ pub fn tick( if m.species() == Species::Strider { super::strider::float(m, w); } + if m.species() == Species::Bat { + super::bat::tick(m); + } true } /// LivingEntity.updateSwingTime (6-tick swing duration). @@ -912,6 +918,7 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut 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, + Species::Bat => super::bat::server_ai_step(m, cx.w, cx.events), _ => {} } } @@ -1209,6 +1216,11 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage, _amount: f32) -> bool { Species::Warden => super::warden::accepts_damage(m, source), Species::Shulker => super::shulker::accepts(m, source), Species::SulfurCube => super::sulfur_cube::accepts_damage(m, source, _amount), + // Bat.hurtServer: a hit wakes it. + Species::Bat => { + super::bat::hurt(m); + true + } Species::Enderman => super::enderman::on_damage(m, source), Species::WitherSkeleton | Species::Blaze | Species::MagmaCube | Species::Strider if source.is_fire() => @@ -1414,6 +1426,7 @@ pub fn step_sound( match m.species() { // Silent footsteps, or only movement events. S::Allay + | S::Bat | S::Bee | S::Cod | S::Salmon diff --git a/crates/horizon-client/src/mobs/bat.rs b/crates/horizon-client/src/mobs/bat.rs new file mode 100644 index 000000000..9f38e9e60 --- /dev/null +++ b/crates/horizon-client/src/mobs/bat.rs @@ -0,0 +1,143 @@ +//! Bats (`Bat`): hanging upside down under a solid block until a player comes +//! near, then fluttering about towards random nearby air (`customServerAiStep`), +//! and `BatModel`'s flying and resting keyframe animations. `extra.flag` is +//! `isResting`, `extra.positions[0]` the `targetPosition`; animation states: +//! flying, resting. +use super::{Mob, MobEvent, MobWorld, data::REDSTONE_CONDUCTOR, living::wrap}; +use horizon_core::{ + geometry::{Vec3, trig}, + random::RandomSource, +}; + +/// `Bat(EntityType, Level)`: a new bat hangs. +pub fn register(m: &mut Mob) { + m.extra.flag = true; +} +pub fn resting(m: &Mob) -> bool { + m.extra.flag +} +/// `Bat.setResting`. +pub fn set_resting(m: &mut Mob, value: bool) { + m.extra.flag = value; +} +/// `Bat.hurtServer`: a hit wakes it. +pub fn hurt(m: &mut Mob) { + set_resting(m, false); +} +/// `levelEvent(1025)`: the take-off flutter, unless silent. +fn take_off(m: &Mob, p: [i32; 3], events: &mut Vec) { + if !m.silent { + events.push(MobEvent::LevelEventSound { + sound: "entity.bat.takeoff", + at: [ + f64::from(p[0]) + 0.5, + f64::from(p[1]) + 0.5, + f64::from(p[2]) + 0.5, + ], + volume: 0.05, + spread: 0.2, + }); + } +} +/// `Bat.customServerAiStep`. +pub fn server_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + let pos = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + let above = [pos[0], pos[1] + 1, pos[2]]; + let conductor = + |p: [i32; 3]| w.data.state(w.world.block(p[0], p[1], p[2])).flags & REDSTONE_CONDUCTOR != 0; + if resting(m) { + if conductor(above) { + if m.random.next_int_bound(200).unwrap_or(1) == 0 { + m.head_yaw = m.random.next_int_bound(360).unwrap_or(0) as f32; + } + // getNearestPlayer(forNonCombat().range(4.0)). + if m.can_see_player(w, 4.0) { + set_resting(m, false); + take_off(m, pos, events); + } + } else { + set_resting(m, false); + take_off(m, pos, events); + } + return; + } + if let Some(&t) = m.extra.positions.first() + && (!w.facts.is_air(w.world.block(t[0], t[1], t[2])) || t[1] <= crate::chunk::MIN_Y) + { + m.extra.positions.clear(); + } + let near = |t: [i32; 3]| { + let d = |a: i32, b: f64| f64::from(a) + 0.5 - b; + let (dx, dy, dz) = ( + d(t[0], m.position.x), + d(t[1], m.position.y), + d(t[2], m.position.z), + ); + dx * dx + dy * dy + dz * dz < 4.0 + }; + let current = m.extra.positions.first().copied(); + if current.is_none() + || m.random.next_int_bound(30).unwrap_or(1) == 0 + || current.is_some_and(near) + { + let r = &mut m.random; + let mut offset = |bound: i32| r.next_int_bound(bound).unwrap_or(0); + let x = m.position.x + f64::from(offset(7)) - f64::from(offset(7)); + let y = m.position.y + f64::from(offset(6)) - 2.0; + let z = m.position.z + f64::from(offset(7)) - f64::from(offset(7)); + m.extra.positions.clear(); + m.extra + .positions + .push([x.floor() as i32, y.floor() as i32, z.floor() as i32]); + } + let t = m.extra.positions[0]; + let dx = f64::from(t[0]) + 0.5 - m.position.x; + let dy = f64::from(t[1]) + 0.1 - m.position.y; + let dz = f64::from(t[2]) + 0.5 - m.position.z; + let v = m.velocity; + let tenth = f64::from(0.1_f32); + let v = Vec3::new( + v.x + (signum(dx) * 0.5 - v.x) * tenth, + v.y + (signum(dy) * f64::from(0.7_f32) - v.y) * tenth, + v.z + (signum(dz) * 0.5 - v.z) * tenth, + ); + m.velocity = v; + let y_rot = trig::atan2_degrees(v.z, v.x) - 90.0; + let diff = wrap(y_rot - m.yaw); + m.ai.zza = 0.5; + m.yaw += diff; + if m.random.next_int_bound(100).unwrap_or(1) == 0 && conductor(above) { + set_resting(m, true); + } +} +/// `Math.signum`: zero stays zero (Rust's `signum` gives 1). +fn signum(v: f64) -> f64 { + if v == 0.0 || v.is_nan() { + v + } else { + v.signum() + } +} +/// `Bat.tick` after `super.tick()`: a hanging bat stays put, hooked to the +/// block above; a flying one loses 40% of its vertical speed. Then +/// `setupAnimationStates`. +pub fn tick(m: &mut Mob) { + if resting(m) { + m.velocity = Vec3::ZERO; + m.position.y = m.position.y.floor() + 1.0 - f64::from(m.height()); + } else { + m.velocity.y *= 0.6; + } + let age = m.age as f32; + if resting(m) { + m.anim.states[0].stop(); + m.anim.states[1].start_if_stopped(age); + } else { + m.anim.states[1].stop(); + m.anim.states[0].start_if_stopped(age); + } +} diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 50250351f..9927ea69c 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -346,10 +346,10 @@ impl Mob { self.vertical_collision_below = vertical && wanted.y < 0.0; self.on_ground = self.vertical_collision_below; // Strider.checkFallDamage: lava breaks any fall, and the fluid state - // waits for the next baseTick. + // waits for the next baseTick; Bat.checkFallDamage does nothing. if self.kind.flags.lava_walker && self.fluids.in_lava { self.fall_distance = 0.0; - } else { + } else if self.kind.species != super::Species::Bat { self.check_fall_damage(w, moved, events); } // restituteMovementAfterCollisions with no bounciness: the colliding diff --git a/crates/horizon-client/src/mobs/species.rs b/crates/horizon-client/src/mobs/species.rs index 1dc832f63..fcfd61992 100644 --- a/crates/horizon-client/src/mobs/species.rs +++ b/crates/horizon-client/src/mobs/species.rs @@ -1444,7 +1444,7 @@ impl Def { flying: matches!(s, S::Ghast | S::Phantom | S::HappyGhast), climber: matches!(s, S::Spider | S::CaveSpider), lava_walker: s == S::Strider, - omnidirectional: matches!(s, S::Bat | S::Bee | S::Parrot), + omnidirectional: matches!(s, S::Bee | S::Parrot), fire_immune: fire_immune || matches!( s, diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index d386063d0..6cbdc4562 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -228,6 +228,15 @@ def scenarios(): add('strider_cold', 200, ['mob minecraft:strider 0.5 -60 0.5 0 134 persistent']) add('strider_tempted', 200, [LAVA, 'player 9.5 -60 0.5 hand=minecraft:warped_fungus', 'mob minecraft:strider 0.5 -61 0.5 0 135 persistent']) + # Bats: hanging under a stone ceiling alone, woken by a player passing beneath, flying off with + # nothing above, and fluttering about a closed cave where they may hang up again. + CEILING = 'fill -6 -57 -6 6 -57 6 minecraft:stone' + add('bat_hanging', 200, [CEILING, 'mob minecraft:bat 0.5 -57.9 0.5 0 141 persistent']) + add('bat_woken', 200, [CEILING, 'player 1.5 -60 0.5', 'mob minecraft:bat 0.5 -57.9 0.5 0 142 persistent']) + add('bat_flying', 300, ['mob minecraft:bat 0.5 -57 0.5 0 143 persistent']) + CAVE = ['fill -5 -60 -5 5 -54 5 minecraft:stone', 'fill -4 -60 -4 4 -55 4 minecraft:air'] + for i, seed in enumerate([144, 145, 146]): + add(f'bat_cave_{i}', 400, CAVE + [f'mob minecraft:bat 0.5 -58 0.5 {90 * i} {seed} persistent']) return s