diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 9c6552686..0a7f6e9bb 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -45,6 +45,7 @@ mod shield; mod sign_edit; mod station_control; mod stations; +mod stats; mod storage; mod titles; mod tnt; @@ -612,6 +613,7 @@ struct Game<'a> { ui: chat::UiState, combat: combat::CombatTracker, mount: mounts::MountState, + stats: stats::Stats, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Dim { @@ -1496,6 +1498,8 @@ impl Game<'_> { self.anger_piglins(false); } if !self.creative { + // Block.playerDestroy: the mined statistic and the exhaustion. + self.stats.add("mined", &facts.name, 1); if let Some(p) = self.player.as_mut() { p.health.food.exhaustion = (p.health.food.exhaustion + 0.005).min(40.0); } @@ -2329,6 +2333,10 @@ impl Game<'_> { player.position.z, ]; self.death_message(); + // ServerPlayer.die: deaths, and the time-since counters restart. + self.stats.custom("deaths", 1); + self.stats.reset("custom", "minecraft:time_since_death"); + self.stats.reset("custom", "minecraft:time_since_rest"); if !self.creative && !self.ui.rules.bool("keep_inventory") { // Inventory.dropAll: slots 0..36, armor feet to head (36..39), off hand (40). let mut stacks: Vec = @@ -4238,6 +4246,8 @@ impl Game<'_> { fn tick_mobs(&mut self) -> Result<()> { self.tick_creatures()?; self.position_rider(); + self.tick_stats(); + self.spawn_phantoms(); Ok(()) } /// SkyRenderer.renderSunMoonAndStars: bodies on a frame rotated Y -90 then X by angle. @@ -6082,6 +6092,8 @@ impl Game<'_> { } self.message = Some(("Respawn point set".into(), Instant::now())); self.sleeping = Some((head, 0)); + self.stats.custom("sleep_in_bed", 1); + self.stats.reset("custom", "minecraft:time_since_rest"); } fn tick_sleep(&mut self) { let Some((head, ticks)) = self.sleeping else { @@ -6358,6 +6370,7 @@ impl Game<'_> { self.save_entities()?; self.save_maps(); self.save_fight(); + self.save_stats(); self.level.selected_slot = self.selected as i32; let mode = self.mode_id(); let level = &mut self.level; @@ -7496,6 +7509,7 @@ pub fn run() -> Result<()> { ui: Default::default(), combat: Default::default(), mount: Default::default(), + stats: Default::default(), }; game.ui.vanilla_root = vanilla_root; game.res.atlas.font.uniform = game.settings.force_unicode; diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index f4830ae44..12232bc1c 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -564,6 +564,10 @@ impl Game<'_> { /// LivingEntity.die / dropAllDeathLoot. fn mob_died(&mut self, m: &Mob) { let by_player = self.last_hurt_by_player.remove(&m.id) || m.ai.last_hurt_by_player > 0; + if by_player { + self.stats.add("killed", &m.kind.id, 1); + self.stats.custom("mob_kills", 1); + } let held = self.held().cloned(); let pos = [m.position.x, m.position.y + 0.5, m.position.z]; if !m.is_baby() { @@ -706,6 +710,13 @@ impl Game<'_> { } } MobEvent::FinishAdmiring { mob } => self.finish_admiring(mob), + MobEvent::Hiss { mob } => { + if let Some(m) = self.mobs.iter().find(|m| m.id == mob) { + let at = m.center(); + self.audio + .play("minecraft:entity.cat.hiss", Some(at), 1.0, 1.0); + } + } MobEvent::Tamed { .. } | MobEvent::Buck { .. } => self.mount_event(&e), MobEvent::Launch { target, up } => match target { Who::Player => { diff --git a/crates/horizon-client/src/game/stats.rs b/crates/horizon-client/src/game/stats.rs new file mode 100644 index 000000000..4cc5346de --- /dev/null +++ b/crates/horizon-client/src/game/stats.rs @@ -0,0 +1,282 @@ +//! Player statistics (`ServerStatsCounter`): the custom counters, blocks +//! mined, items used/crafted/broken/picked up/dropped and mobs killed or +//! killed by, saved to `players/stats/.json`, plus the phantom +//! spawner that reads the time since rest (`PhantomSpawner`). +use super::{Dim, Game}; +use horizon_core::random::RandomSource; +use std::collections::BTreeMap; + +/// `stats[type][key]`, with `type` and `key` namespaced ids. +#[derive(Default)] +pub(super) struct Stats { + pub(super) values: BTreeMap>, + loaded: bool, + /// Ticks until the phantom spawner runs again. + phantom_tick: i32, +} +impl Stats { + pub(super) fn add(&mut self, ty: &str, key: &str, n: i32) { + let v = self + .values + .entry(format!("minecraft:{ty}")) + .or_default() + .entry(key.to_owned()) + .or_insert(0); + *v = v.saturating_add(n); + } + pub(super) fn get(&self, ty: &str, key: &str) -> i32 { + self.values + .get(&format!("minecraft:{ty}")) + .and_then(|m| m.get(key)) + .copied() + .unwrap_or(0) + } + pub(super) fn reset(&mut self, ty: &str, key: &str) { + if let Some(m) = self.values.get_mut(&format!("minecraft:{ty}")) { + m.insert(key.to_owned(), 0); + } + } + pub(super) fn custom(&mut self, key: &str, n: i32) { + self.add("custom", &format!("minecraft:{key}"), n); + } +} +impl Game<'_> { + fn stats_path(&self) -> Option { + let uuid = self.level.player_uuid?; + let hex: String = uuid.iter().map(|v| format!("{:08x}", *v as u32)).collect(); + let text = format!( + "{}-{}-{}-{}-{}", + &hex[0..8], + &hex[8..12], + &hex[12..16], + &hex[16..20], + &hex[20..32] + ); + Some( + self.world_root + .join("players/stats") + .join(format!("{text}.json")), + ) + } + /// `ServerStatsCounter.parseLocal`. + pub(super) fn load_stats(&mut self) { + if self.stats.loaded || self.remote.is_some() { + return; + } + self.stats.loaded = true; + let Some(path) = self.stats_path() else { + return; + }; + let Ok(text) = std::fs::read_to_string(path) else { + return; + }; + let Ok(json) = serde_json::from_str::(&text) else { + return; + }; + if let Some(stats) = json.get("stats").and_then(|s| s.as_object()) { + for (ty, entries) in stats { + let Some(entries) = entries.as_object() else { + continue; + }; + let map = self.stats.values.entry(ty.clone()).or_default(); + for (key, v) in entries { + if let Some(n) = v.as_i64() { + map.insert(key.clone(), n as i32); + } + } + } + } + } + /// `ServerStatsCounter.save`. + pub(super) fn save_stats(&self) { + if !self.stats.loaded || self.remote.is_some() { + return; + } + let Some(path) = self.stats_path() else { + return; + }; + let stats: serde_json::Map = self + .stats + .values + .iter() + .filter(|(_, m)| !m.is_empty()) + .map(|(ty, m)| { + let entries: serde_json::Map = + m.iter().map(|(k, v)| (k.clone(), (*v).into())).collect(); + (ty.clone(), serde_json::Value::Object(entries)) + }) + .collect(); + let json = serde_json::json!({ + "stats": stats, + "DataVersion": horizon_world::DATA_VERSION, + }); + if let Some(dir) = path.parent() { + let _ = std::fs::create_dir_all(dir); + } + if let Ok(text) = serde_json::to_string_pretty(&json) { + let _ = std::fs::write(path, text); + } + } + /// The per-tick counters (`Player.tick`/`ServerPlayer.tick` awardStat). + pub(super) fn tick_stats(&mut self) { + self.load_stats(); + let Some(p) = self.player.as_ref() else { + return; + }; + let alive = !p.health.dead_or_dying(); + let crouching = p.pose == horizon_client::pose::Pose::Crouching; + let s = &mut self.stats; + s.custom("play_time", 1); + s.custom("total_world_time", 1); + if alive { + s.custom("time_since_death", 1); + if self.sleeping.is_none() { + s.custom("time_since_rest", 1); + } + } + if crouching { + s.custom("sneak_time", 1); + } + self.tick_movement_stats(); + } + /// `Player.checkMovementStatistics` / `checkRidingStatistics`. + fn tick_movement_stats(&mut self) { + let Some(p) = self.player.as_ref() else { + return; + }; + let d = p.position.subtract(self.previous_position); + let horizontal = ((d.x * d.x + d.z * d.z).sqrt() * 100.0).round() as i32; + let total = ((d.x * d.x + d.y * d.y + d.z * d.z).sqrt() * 100.0).round() as i32; + if total <= 0 { + return; + } + let crouching = p.pose == horizon_client::pose::Pose::Crouching; + let feet = [ + p.position.x.floor() as i32, + p.position.y.floor() as i32, + p.position.z.floor() as i32, + ]; + let eye_in_water = self.res.facts.get(self.world.block( + feet[0], + (p.position.y + f64::from(p.dimensions.eye_height)).floor() as i32, + feet[2], + )); + let in_water = self + .res + .facts + .get(self.world.block(feet[0], feet[1], feet[2])) + .fluid + == horizon_client::blocks::Fluid::Water; + let on_ground = p.ground.on_ground; + let (sprinting, flying, gliding, swimming) = ( + p.sprinting, + p.flying, + p.fall_flying, + p.pose == horizon_client::pose::Pose::Swimming, + ); + let climbing = p.last_climbable.is_some() && d.y > 0.0; + let riding = self.riding.map(|id| { + self.mobs + .iter() + .find(|m| m.id == id) + .map(|m| m.species()) + .ok_or(()) + }); + let s = &mut self.stats; + match riding { + Some(Ok(horizon_client::mobs::Species::Pig)) => s.custom("pig_one_cm", total), + Some(Ok(horizon_client::mobs::Species::Strider)) => s.custom("strider_one_cm", total), + Some(Ok(sp)) if horizon_client::mobs::equine::is_equine(sp) => { + s.custom("horse_one_cm", horizontal) + } + Some(_) => { + if self.boats.iter().any(|b| Some(b.id) == self.riding) { + s.custom("boat_one_cm", total) + } else { + s.custom("minecart_one_cm", total) + } + } + None if swimming => s.custom("swim_one_cm", total), + None if eye_in_water.fluid == horizon_client::blocks::Fluid::Water => { + s.custom("walk_under_water_one_cm", total) + } + None if in_water => s.custom("walk_on_water_one_cm", horizontal), + None if climbing => s.custom("climb_one_cm", (d.y * 100.0).round() as i32), + None if on_ground => { + if sprinting { + s.custom("sprint_one_cm", horizontal) + } else if crouching { + s.custom("crouch_one_cm", horizontal) + } else { + s.custom("walk_one_cm", horizontal) + } + } + None if gliding => s.custom("aviate_one_cm", total), + None if flying => s.custom("fly_one_cm", horizontal), + None if d.y < 0.0 => s.custom("fall_one_cm", (-d.y * 100.0).round() as i32), + None => {} + } + } + /// `PhantomSpawner.tick`: tired players under an open night sky draw + /// phantoms. + pub(super) fn spawn_phantoms(&mut self) { + if !self.ui.rules.bool("spawn_phantoms") || self.dim != Dim::Overworld { + return; + } + self.stats.phantom_tick -= 1; + if self.stats.phantom_tick > 0 { + return; + } + let r = &mut self.world.random; + self.stats.phantom_tick += (60 + r.next_int_bound(60).unwrap_or(0)) * 20; + if self.sky_darken() < 5 || self.spectator() { + return; + } + let Some(p) = self.player.as_ref() else { + return; + }; + let pos = [ + p.position.x.floor() as i32, + p.position.y.floor() as i32, + p.position.z.floor() as i32, + ]; + if pos[1] < 63 || !self.can_see_sky(pos) { + return; + } + // DifficultyInstance.isHarderThan(random * 3) at normal difficulty. + let r = &mut self.world.random; + if r.next_float() * 3.0 >= 2.0 { + return; + } + let rest = self.stats.get("custom", "minecraft:time_since_rest").max(1); + if r.next_int_bound(rest).unwrap_or(0) < 72000 { + return; + } + let at = [ + pos[0] - 10 + r.next_int_bound(21).unwrap_or(10), + pos[1] + 20 + r.next_int_bound(15).unwrap_or(0), + pos[2] - 10 + r.next_int_bound(21).unwrap_or(10), + ]; + if !self.res.facts.is_air(self.world.block(at[0], at[1], at[2])) { + return; + } + let group = 1 + self.world.random.next_int_bound(3).unwrap_or(0); + for _ in 0..group { + let _ = self.spawn_mob( + "minecraft:phantom", + [ + f64::from(at[0]) + 0.5, + f64::from(at[1]), + f64::from(at[2]) + 0.5, + ], + false, + ); + } + } + fn can_see_sky(&self, pos: [i32; 3]) -> bool { + (pos[1] + 1..pos[1] + 256).all(|y| { + let f = self.res.facts.get(self.world.block(pos[0], y, pos[2])); + !f.full_collision && f.fluid == horizon_client::blocks::Fluid::None + }) + } +} diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index ef4b8294e..a75f4cd6f 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -23,6 +23,7 @@ pub mod living; pub mod nav; pub mod nether; pub mod path; +pub mod phantom; pub mod piglin; pub mod render; pub mod spawning; @@ -572,6 +573,10 @@ pub enum MobEvent { name: &'static str, effect: bool, }, + /// A cat hisses (phantoms flee). + Hiss { + mob: u32, + }, /// A horse's rider tamed it. Tamed { mob: u32, diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 67d0e6c9f..4f2aadd28 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -77,6 +77,7 @@ pub enum Family { /// Piglins, brutes, hoglins and zoglins. Piglin, Equine, + Phantom, /// Slimes and magma cubes. Cube, } @@ -110,6 +111,7 @@ pub fn family(s: Species) -> Family { S::Pillager | S::Vindicator => Family::Illager, S::Piglin | S::PiglinBrute | S::Hoglin | S::Zoglin => Family::Piglin, S::Horse | S::Donkey | S::Mule | S::SkeletonHorse | S::ZombieHorse => Family::Equine, + S::Phantom => Family::Phantom, S::Enderman => Family::Enderman, S::Slime | S::MagmaCube => Family::Cube, _ => Family::Generic, @@ -133,6 +135,7 @@ pub fn register(m: &mut Mob) { Family::Illager if m.species() == Species::Pillager => super::illager::register_pillager(m), Family::Illager => super::illager::register_vindicator(m), Family::Equine => super::equine::register(m), + Family::Phantom => super::phantom::register(m), Family::Piglin => match m.species() { Species::Piglin => super::piglin::register_piglin(m), Species::PiglinBrute => super::piglin::register_brute(m), @@ -160,6 +163,9 @@ pub fn custom_move_control(m: &mut Mob, w: &MobWorld, events: &mut Vec if m.species() == Species::Ghast { return super::nether::ghast_move_control(m, w); } + if m.species() == Species::Phantom { + return super::phantom::move_control(m); + } match family(m.species()) { Family::Aquatic => aquatic::fish_move_control(m), Family::Cube => super::cube::move_control(m, events), @@ -505,6 +511,7 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } Species::Zoglin if m.extra.anim_ticks > 0 => m.extra.anim_ticks -= 1, s if super::equine::is_equine(s) => super::equine::ai_step(m, w), + Species::Phantom => super::phantom::flap_sound(m, events), Species::SnowGolem => super::golem::snow_ai_step(m, w, events), Species::Slime | Species::MagmaCube => super::cube::ai_step(m, w, events), Species::Chicken => farm::chicken_ai_step(m, w, events), diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index 35f1e1c32..fbc655441 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -431,6 +431,7 @@ pub fn setup( Anim::IronGolem => super::golem::iron_anim(m, s, p), Anim::Illager => super::illager::anim(m, s, p), Anim::Piglin => super::piglin::piglin_anim(m, s, p), + Anim::Phantom => super::phantom::anim(m, s, p), Anim::Horse => { super::equine::anim(m, s, p); // DonkeyModel: the chests show once fitted. diff --git a/crates/horizon-client/src/mobs/phantom.rs b/crates/horizon-client/src/mobs/phantom.rs new file mode 100644 index 000000000..33ce2c59d --- /dev/null +++ b/crates/horizon-client/src/mobs/phantom.rs @@ -0,0 +1,361 @@ +//! Phantoms: circling an anchor high above, swooping at the player every +//! eight to twelve seconds, scared off by cats (`Phantom`). +use super::{ + Mob, MobEvent, MobWorld, Species, Who, + control::MoveKind, + goals::{Cx, Goal, MOVE, TARGET, goal_clone, reduced}, +}; +use horizon_core::{geometry::Vec3, random::RandomSource}; + +/// Phantom state in `Extra`: `flag` swooping, `home` the anchor, +/// `vector` the move target, `attrs.speed` the move control's speed. +pub fn register(m: &mut Mob) { + m.ai.mov.kind = MoveKind::Custom; + m.attrs.speed = 0.1; + m.extra.home = Some([ + m.position.x.floor() as i32, + m.position.y.floor() as i32 + 5, + m.position.z.floor() as i32, + ]); + m.ai.goals.add(1, AttackStrategy { next_sweep: 0 }); + m.ai.goals.add( + 2, + SweepAttack { + scared: false, + cat_search: 0, + }, + ); + m.ai.goals.add(3, CircleAroundAnchor::default()); + m.ai.targets.add( + 1, + AttackPlayerTarget { + next_scan: reduced(20), + }, + ); +} +fn can_attack(w: &MobWorld) -> bool { + w.player + .as_ref() + .is_some_and(|p| p.alive && !p.creative && !p.spectator) +} +fn sea_level() -> i32 { + 63 +} +/// `PhantomAttackPlayerTargetGoal`: every three seconds, the player +/// within 16 blocks across and 64 up or down. +#[derive(Clone, Debug)] +struct AttackPlayerTarget { + next_scan: i32, +} +impl Goal for AttackPlayerTarget { + goal_clone!(); + fn flags(&self) -> u8 { + TARGET + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if self.next_scan > 0 { + self.next_scan -= 1; + return false; + } + self.next_scan = reduced(60); + let Some(p) = &cx.w.player else { + return false; + }; + let d = p.position; + let near = (d.x - m.position.x).abs() <= 16.0 + f64::from(m.width()) + && (d.y - m.position.y).abs() <= 64.0 + && (d.z - m.position.z).abs() <= 16.0 + f64::from(m.width()); + if near && can_attack(cx.w) { + m.ai.target = Some(Who::Player); + return true; + } + false + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + m.ai.target.is_some() && can_attack(cx.w) + } +} +/// `PhantomAttackStrategyGoal`: circle, then swoop. +#[derive(Clone, Debug)] +struct AttackStrategy { + next_sweep: i32, +} +impl AttackStrategy { + fn anchor_above_target(m: &mut Mob, cx: &Cx) { + let Some(t) = m.ai.target.and_then(|t| cx.w.target_info(t)) else { + return; + }; + let y = (t.position.y.floor() as i32 + 20 + m.random.next_int_bound(20).unwrap_or(0)) + .max(sea_level() + 1); + m.extra.home = Some([t.position.x.floor() as i32, y, t.position.z.floor() as i32]); + } +} +impl Goal for AttackStrategy { + goal_clone!(); + fn flags(&self) -> u8 { + 0 + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + m.ai.target.is_some() && can_attack(cx.w) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.next_sweep = reduced(10); + m.extra.flag = false; + Self::anchor_above_target(m, cx); + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + if let Some(a) = m.extra.home { + let top = cx.w.motion_blocking_height(a[0], a[2]); + m.extra.home = Some([ + a[0], + top + 10 + m.random.next_int_bound(20).unwrap_or(0), + a[2], + ]); + } + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + if !m.extra.flag { + self.next_sweep -= 1; + if self.next_sweep <= 0 { + m.extra.flag = true; + Self::anchor_above_target(m, cx); + self.next_sweep = reduced((8 + m.random.next_int_bound(4).unwrap_or(0)) * 20); + let pitch = 0.95 + m.random.next_float() * 0.1; + cx.events.push(MobEvent::Sound( + "entity.phantom.swoop", + m.center(), + 10.0, + pitch, + )); + } + } + } +} +/// `PhantomCircleAroundAnchorGoal`. +#[derive(Clone, Debug, Default)] +struct CircleAroundAnchor { + angle: f32, + distance: f32, + height: f32, + clockwise: f32, +} +impl CircleAroundAnchor { + fn select_next(&mut self, m: &mut Mob) { + let a = *m.extra.home.get_or_insert([ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]); + self.angle += self.clockwise * 15.0f32.to_radians(); + m.extra.vector = [ + f64::from(a[0]) + f64::from(self.distance * self.angle.cos()), + f64::from(a[1]) + f64::from(-4.0 + self.height), + f64::from(a[2]) + f64::from(self.distance * self.angle.sin()), + ]; + } +} +fn empty(w: &MobWorld, x: i32, y: i32, z: i32) -> bool { + w.facts.get(w.world.block(x, y, z)).name.as_ref() == "minecraft:air" +} +impl Goal for CircleAroundAnchor { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + m.ai.target.is_none() || !m.extra.flag + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + self.distance = 5.0 + m.random.next_float() * 10.0; + self.height = -4.0 + m.random.next_float() * 9.0; + self.clockwise = if m.random.next_int_bound(2).unwrap_or(0) == 0 { + 1.0 + } else { + -1.0 + }; + self.select_next(m); + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + if m.random.next_int_bound(reduced(350)).unwrap_or(1) == 0 { + self.height = -4.0 + m.random.next_float() * 9.0; + } + if m.random.next_int_bound(reduced(250)).unwrap_or(1) == 0 { + self.distance += 1.0; + if self.distance > 15.0 { + self.distance = 5.0; + self.clockwise = -self.clockwise; + } + } + if m.random.next_int_bound(reduced(450)).unwrap_or(1) == 0 { + self.angle = m.random.next_float() * 2.0 * std::f32::consts::PI; + self.select_next(m); + } + let t = m.extra.vector; + let d2 = (t[0] - m.position.x).powi(2) + + (t[1] - m.position.y).powi(2) + + (t[2] - m.position.z).powi(2); + if d2 < 4.0 { + self.select_next(m); + } + let (x, y, z) = ( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ); + if m.extra.vector[1] < m.position.y && !empty(cx.w, x, y - 1, z) { + self.height = self.height.max(1.0); + self.select_next(m); + } + if m.extra.vector[1] > m.position.y && !empty(cx.w, x, y + 1, z) { + self.height = self.height.min(-1.0); + self.select_next(m); + } + } +} +/// `PhantomSweepAttackGoal`: dive at the target, bite on contact. +#[derive(Clone, Debug)] +struct SweepAttack { + scared: bool, + cat_search: u32, +} +impl Goal for SweepAttack { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + m.ai.target.is_some() && m.extra.flag + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if !can_attack(cx.w) || m.ai.target.is_none() || !m.extra.flag { + return false; + } + if m.age > self.cat_search { + self.cat_search = m.age + 20; + let cats: Vec = + cx.w.nearby(m.position, 16.0, |s| s.species == Species::Cat && s.alive) + .map(|s| s.id) + .collect(); + for cat in &cats { + cx.events.push(MobEvent::Hiss { mob: *cat }); + } + self.scared = !cats.is_empty(); + } + !self.scared + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + m.ai.target = None; + m.extra.flag = false; + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(who) = m.ai.target else { + return; + }; + let Some(t) = cx.w.target_info(who) else { + return; + }; + let mid = (t.bounds.min_position().y + t.bounds.max_position().y) * 0.5; + m.extra.vector = [t.position.x, mid, t.position.z]; + let reach = m.bounds().inflate(Vec3::new(0.2, 0.2, 0.2)); + if reach.intersects(t.bounds) { + super::ai::do_hurt_target(m, who, cx); + m.extra.flag = false; + // LevelEvent 1039: the bite. + cx.events + .push(MobEvent::Sound("entity.phantom.bite", m.center(), 1.0, 1.0)); + } else if m.horizontal_collision || m.hurt_time > 0 { + m.extra.flag = false; + } + } +} +fn approach(from: f32, to: f32, step: f32) -> f32 { + if from < to { + (from + step).min(to) + } else { + (from - step).max(to) + } +} +fn wrap(d: f32) -> f32 { + let r = d.rem_euclid(360.0); + if r >= 180.0 { r - 360.0 } else { r } +} +/// `PhantomMoveControl`: bank toward the move target, faster on a straight +/// line. +pub fn move_control(m: &mut Mob) { + let mut speed = m.attrs.speed as f32; + if m.horizontal_collision { + m.yaw += 180.0; + speed = 0.1; + } + let t = m.extra.vector; + let (mut dx, dy, mut dz) = ( + t[0] - m.position.x, + t[1] - m.position.y, + t[2] - m.position.z, + ); + let mut sd = (dx * dx + dz * dz).sqrt(); + if sd.abs() > 1.0e-5 { + let scale = 1.0 - (dy * 0.7).abs() / sd; + dx *= scale; + dz *= scale; + sd = (dx * dx + dz * dz).sqrt(); + let sd2 = (dx * dx + dz * dz + dy * dy).sqrt(); + let prev = m.yaw; + let angle = dz.atan2(dx) as f32; + let a = wrap(m.yaw + 90.0); + let b = wrap(angle.to_degrees()); + // Mth.approachDegrees + let diff = wrap(b - a); + m.yaw = a + diff.clamp(-4.0, 4.0) - 90.0; + m.body_yaw = m.yaw; + if wrap(prev - m.yaw).abs() < 3.0 { + speed = approach(speed, 1.8, 0.005 * (1.8 / speed)); + } else { + speed = approach(speed, 0.2, 0.025); + } + let x_rot = -((-dy).atan2(sd) as f32).to_degrees(); + m.head_pitch = x_rot; + let move_angle = (m.yaw + 90.0).to_radians(); + let tx = f64::from(speed * move_angle.cos()) * (dx / sd2).abs(); + let tz = f64::from(speed * move_angle.sin()) * (dz / sd2).abs(); + let ty = f64::from(speed * x_rot.to_radians().sin()) * (dy / sd2).abs(); + let v = m.velocity; + m.velocity = Vec3::new( + v.x + (tx - v.x) * 0.2, + v.y + (ty - v.y) * 0.2, + v.z + (tz - v.z) * 0.2, + ); + } + m.attrs.speed = f64::from(speed); + // PhantomBodyRotationControl: the head follows the body. + m.head_yaw = m.body_yaw; +} +/// `PhantomModel.setupAnim` (flap time offset by the id). +pub fn anim(m: &Mob, s: &super::anim::State, p: &mut super::anim::Poses) { + let flap = (m.id as f32 * 3.0 + s.age) * 7.448_451_f32.to_radians(); + let wing = flap.cos() * 16.0f32.to_radians(); + p.zrot("left_wing_base", wing); + p.zrot("left_wing_tip", wing); + p.zrot("right_wing_base", -wing); + p.zrot("right_wing_tip", -wing); + let tail = -(5.0 + (flap * 2.0).cos() * 5.0f32).to_radians(); + p.xrot("tail_base", tail); + p.xrot("tail_tip", tail); +} +/// The flap sound when a wingbeat begins (`Phantom.isFlapping`). +pub fn flap_sound(m: &Mob, events: &mut Vec) { + let t = m.id as f32 * 3.0 + m.age as f32; + let a = (t * 7.448_451_f32.to_radians() + std::f32::consts::PI).cos(); + let b = ((t + 1.0) * 7.448_451_f32.to_radians() + std::f32::consts::PI).cos(); + if a > 0.0 && b <= 0.0 { + events.push(MobEvent::Sound( + "entity.phantom.flap", + m.center(), + 0.95 + 0.05, + 0.95, + )); + } +}