diff --git a/crates/horizon-client/examples/entity_anim_fixture.rs b/crates/horizon-client/examples/entity_anim_fixture.rs index f03d91a21..3e7176520 100644 --- a/crates/horizon-client/examples/entity_anim_fixture.rs +++ b/crates/horizon-client/examples/entity_anim_fixture.rs @@ -173,6 +173,15 @@ fn entity_state(mob: &mut Mob, species: Species, case: &Value) { mob.anim.states[i].started = case[k].as_f64().map(|v| v as f32); } } + Species::Breeze => { + // breeze::anim's state slots. + for (i, k) in ["idle", "shoot", "slide", "slideBack", "inhale", "longJump"] + .into_iter() + .enumerate() + { + mob.anim.states[i].started = case[k].as_f64().map(|v| v as f32); + } + } Species::Witch if flag("isHoldingItem") => { mob.extra.main_hand = Some("minecraft:potion".into()); } @@ -215,6 +224,9 @@ fn main() -> horizon_client::Result<()> { base = base.replace(cut, ""); } let base = base.replace("undead_horse#", "zombie_horse#"); + // The breeze's wind and eyes and the creaking's eyes are layers of + // the species' own model class. + let base = base.replace("#wind", "#main").replace("#eyes", "#main"); let base = base.trim_start_matches("cold_").trim_start_matches("warm_"); let Some(def) = species::ALL.iter().find(|d| { d.model == layer diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 554f2cb4f..e4ab1d317 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -9,8 +9,13 @@ use horizon_client::{ blocks::BlockFacts, chunk::{Chunk, HEIGHT, MIN_Y}, collisions, + containers::{BlockEntity, CreakingHeart}, items::Items, light::{LightTables, light_chunk}, + mobs::{ + Damage, MobType, creaking, + creaking_heart::{self, HeartEvent, HeartHost}, + }, mobs::{ Mob, MobData, MobEvent, MobTypes, MobWorld, PlayerView, Seen, Species, Who, control::Operation, spawning::LocalDifficulty, @@ -43,6 +48,14 @@ struct Scenario { blocks: Vec>, player: Option<[f64; 3]>, creative: bool, + /// The tick from which the player faces another yaw. + turn: Option<(i32, f32)>, + /// Creaking hearts placed when the scenario starts. + hearts: Vec>, + /// `ServerLevel.isSpawningMonsters`. + spawning: bool, + /// The player hits a mob for 1 at the start of a tick: (tick, mob index). + hurts: Vec<(i32, usize)>, mobs: Vec, } @@ -67,19 +80,31 @@ fn parse(text: &str) -> Vec { "rain" => s.rain = true, "thunder" => s.thunder = true, "levelseed" => {} + "spawning" => s.spawning = true, _ => panic!("unknown scenario option {kv}"), } } } "origin" => s.origin = [f[1].parse().unwrap(), f[2].parse().unwrap()], "fill" | "block" => s.blocks.push(f.iter().map(|x| (*x).to_owned()).collect()), + "heart" => s.hearts.push(f.iter().map(|x| (*x).to_owned()).collect()), + "hurt" => s.hurts.push((f[1].parse().unwrap(), f[2].parse().unwrap())), "player" => { s.player = Some([ f[1].parse().unwrap(), f[2].parse().unwrap(), f[3].parse().unwrap(), ]); - s.creative = f.get(4) == Some(&"creative"); + for opt in &f[4..] { + if *opt == "creative" { + s.creative = true; + } else if let Some(t) = opt.strip_prefix("turn=") { + let (tick, yaw) = t.split_once(',').unwrap(); + s.turn = Some((tick.parse().unwrap(), yaw.parse().unwrap())); + } else { + panic!("unknown player option {opt}"); + } + } } "mob" => s.mobs.push(MobSpec { kind: f[1].to_owned(), @@ -240,6 +265,91 @@ fn seen(m: &Mob) -> Seen { } } +/// The probe's mobs as a creaking heart sees them: creakings it creates take +/// the n-th seed from 1000, as the oracle's do. +struct Host<'a> { + mobs: &'a mut Vec, + added: Vec, + types: &'a MobTypes, + created: &'a mut i64, + spawning: bool, +} +impl HeartHost for Host<'_> { + fn mob(&self, id: u32) -> Option<&Mob> { + self.mobs + .iter() + .chain(self.added.iter()) + .find(|m| m.id == id) + } + fn mob_mut(&mut self, id: u32) -> Option<&mut Mob> { + self.mobs + .iter_mut() + .chain(self.added.iter_mut()) + .find(|m| m.id == id) + } + fn mob_for_uuid(&self, uuid: [i32; 4]) -> Option { + self.mob(uuid[3] as u32) + .filter(|m| !m.removed) + .map(|m| m.id) + } + fn uuid_for(&mut self, id: u32) -> [i32; 4] { + [0, 0, 0, id as i32] + } + fn creaking_type(&self) -> Option> { + self.types + .types + .get("minecraft:creaking") + .map(|t| Arc::new(t.clone())) + } + fn create_mob(&mut self, kind: Arc, at: Vec3) -> Mob { + let seed = 1000 + *self.created; + *self.created += 1; + let mut m = Mob::new(200_000 + seed as u32, kind, at, 0.0); + m.random = LegacyRandom::new(seed); + horizon_client::mobs::monster_brain::init(&mut m, seed); + m + } + fn add_mob(&mut self, m: Mob) { + self.added.push(m); + } + fn spawning_monsters(&self) -> bool { + self.spawning + } +} +/// The heart's state, block entity and the level random, as the oracle +/// prints them. +fn print_heart( + out: &mut String, + t: i32, + registry: &BlockRegistry, + world: &World, + at: [i32; 3], + heart: &CreakingHeart, + lr: &LegacyRandom, +) { + let state = registry + .state(world.block(at[0], at[1], at[2])) + .and_then(|s| s.properties.get("creaking_heart_state").cloned()) + .unwrap_or_default(); + let _ = writeln!( + out, + "{t} heart {},{},{}\t{state}\t{} {} {} {} {}\tlrng {:x}", + at[0], + at[1], + at[2], + heart.ticker, + heart.emitter, + heart.output_signal, + heart.ticks_existed, + if heart.creaking.is_some() { + "linked" + } else { + "none" + }, + lr.state() + ); +} + /// 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 { @@ -355,7 +465,9 @@ fn print(out: &mut String, t: i32, i: usize, m: &Mob) { u8::from(m.ai.jumping) ); let _ = write!(out, "\trng {:x}", m.random.state()); - if let Some((acts, mem)) = horizon_client::mobs::villager_brain::describe(m) { + if let Some((acts, mem)) = horizon_client::mobs::villager_brain::describe(m) + .or_else(|| horizon_client::mobs::monster_brain::describe(m)) + { let _ = write!(out, "\tact {acts}\tmem {mem}"); } out.push('\n'); @@ -425,6 +537,17 @@ fn main() -> horizon_client::Result<()> { } } } + let mut hearts: Vec<([i32; 3], CreakingHeart)> = Vec::new(); + for h in &s.hearts { + let at = [ + h[1].parse::().unwrap(), + h[2].parse::().unwrap(), + h[3].parse::().unwrap(), + ]; + world.set(at[0], at[1], at[2], state(registry, &h[4]))?; + hearts.push((at, CreakingHeart::default())); + } + let mut created = 0_i64; let keys: Vec<(i32, i32)> = world.chunks.keys().copied().collect(); let lit: Vec<((i32, i32), Chunk)> = keys .iter() @@ -471,6 +594,11 @@ fn main() -> horizon_client::Result<()> { } } m.random = LegacyRandom::new(spec.seed); + if horizon_client::mobs::monster_brain::has_brain(m.species()) { + // The oracle delays the sensors again with the seeded random + // and seeds RunOne's shuffles with the mob's seed. + horizon_client::mobs::monster_brain::init(&mut m, 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. @@ -483,7 +611,7 @@ fn main() -> horizon_client::Result<()> { } mobs.push(m); } - let player = s.player.map(|p| { + let mut player = s.player.map(|p| { let position = Vec3::new(p[0], p[1], p[2]); PlayerView { position, @@ -517,6 +645,26 @@ fn main() -> horizon_client::Result<()> { } for t in 1..=s.ticks { world.game_time += 1; + let mut heart_events_later: Vec = Vec::new(); + // Creaking.tick reads the heart's block entity. + for (at, h) in &hearts { + world.block_entities.insert( + (at[0], at[1], at[2]), + BlockEntity::CreakingHeart(Box::new(h.clone())), + ); + } + if let (Some(p), Some((tick, yaw))) = (player.as_mut(), s.turn) + && t >= tick + { + // Entity.calculateViewVector(0, yaw). + let r = -yaw * horizon_core::geometry::trig::DEG_TO_RAD; + let (cos, sin) = ( + horizon_core::geometry::trig::cos(f64::from(r)), + horizon_core::geometry::trig::sin(f64::from(r)), + ); + p.look = [f64::from(sin), -0.0, f64::from(cos)]; + p.yaw = yaw; + } let snapshot: Vec = mobs.iter().filter(|m| !m.removed).map(seen).collect(); let w = MobWorld { teams: Default::default(), @@ -543,6 +691,51 @@ fn main() -> horizon_client::Result<()> { sea_level: -63, }; let mut events = Vec::new(); + let mut heart_events = Vec::new(); + let mut added = Vec::new(); + for &(tick, i) in &s.hurts { + if tick != t || i >= mobs.len() || mobs[i].removed { + continue; + } + let at = player + .as_ref() + .map_or([0.0; 3], |p| [p.position.x, p.position.y, p.position.z]); + mobs[i].damage(1.0, Damage::player(at)); + // Creaking.hurtServer: the heart's reaction, then the sway. + if let Some((home, by_player)) = creaking::take_hurt(&mut mobs[i], &w) { + if by_player && let Some((_, h)) = hearts.iter_mut().find(|(at, _)| *at == home) + { + let mut host = Host { + mobs: &mut mobs, + added: Vec::new(), + types: &types, + created: &mut created, + spawning: s.spawning, + }; + creaking_heart::creaking_hurt( + h, + home, + &w, + &mut scratch, + &mut host, + &mut heart_events, + ); + added.append(&mut host.added); + } + for e in heart_events.drain(..) { + match e { + HeartEvent::Sound(name, _, volume, pitch) => { + events.push(MobEvent::Sound(name, [0.0; 3], volume, pitch)) + } + HeartEvent::SetBlock(..) => heart_events_later.push(e), + HeartEvent::Mob(ev) => events.push(ev), + _ => {} + } + } + creaking::sway(&mut mobs[i], &mut events); + } + events.append(&mut mobs[i].outbox); + } #[allow(unused_mut)] // filled only with the rng-trace feature let mut traces: Vec = Vec::new(); let mut pushes = Vec::new(); @@ -571,6 +764,38 @@ fn main() -> horizon_client::Result<()> { for m in &mut mobs { horizon_client::mobs::apply_mob_pushes(m, &mut pushes); } + // ServerLevel.tickBlockEntities: the hearts (none ticks once uprooted). + heart_events.append(&mut heart_events_later); + for (at, h) in &mut hearts { + let uprooted = registry + .state(w.world.block(at[0], at[1], at[2])) + .and_then(|s| s.properties.get("creaking_heart_state").cloned()) + .is_some_and(|v| v == "uprooted"); + if uprooted { + continue; + } + let mut host = Host { + mobs: &mut mobs, + added: Vec::new(), + types: &types, + created: &mut created, + spawning: s.spawning, + }; + creaking_heart::server_tick(h, *at, &w, &mut scratch, &mut host, &mut heart_events); + added.append(&mut host.added); + } + drop(w); + mobs.append(&mut added); + for e in &heart_events { + match e { + HeartEvent::SetBlock(at, st) => world.set(at[0], at[1], at[2], *st)?, + HeartEvent::Sound(name, _, volume, pitch) => { + events.push(MobEvent::Sound(name, [0.0; 3], *volume, *pitch)) + } + HeartEvent::Mob(ev) => events.push(ev.clone()), + _ => {} + } + } for (i, m) in mobs.iter().enumerate() { print(&mut out, t, i, m); } @@ -593,6 +818,9 @@ fn main() -> horizon_client::Result<()> { ); } } + for (at, h) in &hearts { + print_heart(&mut out, t, registry, &world, *at, h, &scratch); + } for line in traces { let _ = writeln!(out, "{line}"); } diff --git a/crates/horizon-client/src/game/creaking.rs b/crates/horizon-client/src/game/creaking.rs index 98727ba8b..6147b419d 100644 --- a/crates/horizon-client/src/game/creaking.rs +++ b/crates/horizon-client/src/game/creaking.rs @@ -1,37 +1,29 @@ -//! The creaking heart block entity (`CreakingHeartBlockEntity`): at night an -//! awake heart in a pale oak trunk spawns a creaking that protects it, -//! hurting the creaking makes the heart emit trails and spread resin over -//! the logs, and breaking the heart tears the creaking down. -use super::Game; +//! The creaking heart block entity in the game: `mobs::creaking_heart` +//! ticks each heart (spawning, letting go of and bleeding for its creaking) +//! and this applies what it reports to the world, the mobs and the speakers. +use super::{Game, creatures::seen}; use horizon_client::{ Result, containers::{BlockEntity, CreakingHeart}, - mobs::creaking, + mobs::{ + Mob, MobType, + creaking_heart::{self, HeartEvent, HeartHost}, + }, particles::{ParticleOptions, ParticleType}, }; -use horizon_core::{geometry::Aabb, position::BlockPos, random::RandomSource}; +use horizon_core::{ + geometry::Vec3, + position::BlockPos, + random::{LegacyRandom, RandomSource}, +}; use horizon_world::registry::BlockStateId; -use std::collections::{HashSet, VecDeque}; +use std::{ + collections::{HashMap, HashSet}, + sync::Arc, +}; type Pos = (i32, i32, i32); -/// `Creaking.CREAKING_ORANGE` and `CREAKING_GRAY`. -const ORANGE: u32 = 16_545_810; -const GRAY: u32 = 6_250_335; -/// `CreakingHeartBlockEntity.DISTANCE_CREAKING_TOO_FAR`. -const TOO_FAR: f64 = 34.0; - -/// `Direction.values()`: down, up, north, south, west, east. -const DIRECTIONS: [[i32; 3]; 6] = [ - [0, -1, 0], - [0, 1, 0], - [0, 0, -1], - [0, 0, 1], - [-1, 0, 0], - [1, 0, 0], -]; -const FACE_NAMES: [&str; 6] = ["down", "up", "north", "south", "west", "east"]; - /// Comparator input of a heart (`getAnalogOutputSignal`). pub(super) fn heart_signal(world: &horizon_client::world::World, pos: BlockPos) -> Option { match world.block_entities.get(&(pos.x, pos.y, pos.z))? { @@ -40,6 +32,59 @@ pub(super) fn heart_signal(world: &horizon_client::world::World, pos: BlockPos) } } +/// The game's mobs as a heart sees them, taken out of the game for the tick. +struct Host<'a> { + mobs: &'a mut Vec, + added: Vec, + uuids: &'a mut HashMap, + creaking: Option>, + next_entity: &'a mut u32, + spawning: bool, +} +impl HeartHost for Host<'_> { + fn mob(&self, id: u32) -> Option<&Mob> { + self.mobs + .iter() + .chain(self.added.iter()) + .find(|m| m.id == id && !m.removed) + } + fn mob_mut(&mut self, id: u32) -> Option<&mut Mob> { + self.mobs + .iter_mut() + .chain(self.added.iter_mut()) + .find(|m| m.id == id && !m.removed) + } + fn mob_for_uuid(&self, uuid: [i32; 4]) -> Option { + self.uuids + .iter() + .find(|(id, u)| **u == uuid && self.mob(**id).is_some()) + .map(|(id, _)| *id) + } + fn uuid_for(&mut self, id: u32) -> [i32; 4] { + *self + .uuids + .entry(id) + .or_insert_with(horizon_client::save::random_uuid) + } + fn creaking_type(&self) -> Option> { + self.creaking.clone() + } + fn create_mob(&mut self, kind: Arc, at: Vec3) -> Mob { + *self.next_entity += 1; + // A new entity's random is its own (Mob::new seeds it). + let mut m = Mob::new(*self.next_entity, kind, at, 0.0); + let seed = i64::from(m.id); + horizon_client::mobs::monster_brain::init(&mut m, seed); + m + } + fn add_mob(&mut self, m: Mob) { + self.added.push(m); + } + fn spawning_monsters(&self) -> bool { + self.spawning + } +} + impl Game<'_> { fn heart_state_name(&self, state: BlockStateId) -> String { self.res @@ -49,204 +94,75 @@ impl Game<'_> { .and_then(|s| s.properties.get("creaking_heart_state").cloned()) .unwrap_or_default() } - /// `Util.shuffledCopy(Direction.values(), random)`. - fn shuffled_directions(&mut self) -> [usize; 6] { - let mut order = [0, 1, 2, 3, 4, 5]; - for i in (2..=6).rev() { - let j = self.world.random.next_int_bound(i as i32).unwrap_or(0) as usize; - order.swap(i - 1, j); - } - order - } - fn is_pale_oak_log(&self, p: Pos) -> bool { - let name = &self.res.facts.get(self.world.block(p.0, p.1, p.2)).name; - self.res - .items - .block_tags - .get("minecraft:pale_oak_logs") - .is_some_and(|s| s.contains(&**name)) - } - fn mob_center(&self, id: u32) -> Option<([f64; 3], Aabb)> { - let m = self.mobs.iter().find(|m| m.id == id && !m.removed)?; - Some((m.center(), m.bounds())) - } - /// The protector's entity, resolving a UUID read from a save. - fn heart_protector(&mut self, heart: &mut CreakingHeart) -> Option { - let (id, uuid) = heart.creaking?; - if let Some(id) = id { - if self.mobs.iter().any(|m| m.id == id && !m.removed) { - return Some(id); - } - // The entity is gone: remember it by UUID until it reappears. - heart.creaking = Some((None, uuid)); - } - if let Some(id) = self.mob_id_for_uuid(uuid) { - heart.creaking = Some((Some(id), uuid)); - return Some(id); - } - if heart.ticks_existed >= 30 { - heart.creaking = None; - } - None - } - /// `CreakingHeartBlockEntity.removeProtector`: the creaking falls apart. - fn heart_remove_protector(&mut self, heart: &mut CreakingHeart, by_player: bool) { - let Some(id) = self.heart_protector(heart) else { - return; + /// Runs `f` on the heart at `key` with the game's mobs and level random, + /// then applies what the heart reported. + fn with_heart( + &mut self, + key: Pos, + heart: &mut CreakingHeart, + f: impl FnOnce( + &mut CreakingHeart, + &horizon_client::mobs::MobWorld, + &mut LegacyRandom, + &mut Host, + &mut Vec, + ), + ) -> Result<()> { + let mut mobs = std::mem::take(&mut self.mobs); + let mut uuids = std::mem::take(&mut self.persist.uuids); + let mut next_entity = self.next_entity; + let mut random = self.world.random.clone(); + let spawning = self.spawning_monsters(); + let creaking = self.res.mob_types.get("minecraft:creaking").cloned(); + let player_uuid = self.level.player_uuid; + let snapshot: Vec<_> = mobs.iter().map(|m| seen(m, player_uuid)).collect(); + let mut events = Vec::new(); + let added = { + let w = self.mob_world_base(&snapshot); + let mut host = Host { + mobs: &mut mobs, + added: Vec::new(), + uuids: &mut uuids, + creaking, + next_entity: &mut next_entity, + spawning, + }; + f(heart, &w, &mut random, &mut host, &mut events); + host.added }; - if by_player { - // creakingDeathEffects: a twitching death. - if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { - creaking::set_tearing_down(m); - m.health = 0.0; - m.death_time = m.death_time.max(0); - let at = m.center(); - self.audio - .play("minecraft:entity.creaking.twitch", Some(at), 1.0, 1.0); - } - } else if let Some(i) = self.mobs.iter().position(|m| m.id == id) { - let mut events = Vec::new(); - creaking::tear_down(&mut self.mobs[i], &mut events); - let _ = self.handle_mob_events(events); - } - heart.creaking = None; - } - fn heart_distance_to_creaking(&self, id: u32, pos: Pos) -> f64 { - self.mob_center(id).map_or(0.0, |_| { - let m = self.mobs.iter().find(|m| m.id == id).unwrap(); - let at = ( - f64::from(pos.0) + 0.5, - f64::from(pos.1), - f64::from(pos.2) + 0.5, - ); - ((m.position.x - at.0).powi(2) - + (m.position.y - at.1).powi(2) - + (m.position.z - at.2).powi(2)) - .sqrt() - }) - } - /// `emitParticles`: trails between the creaking and the heart. - fn heart_emit(&mut self, heart: &mut CreakingHeart, pos: Pos, count: i32, towards: bool) { - let Some(id) = self.heart_protector(heart) else { - return; - }; - let Some((_, b)) = self.mob_center(id) else { - return; - }; - let (lo, hi) = (b.min_position(), b.max_position()); - for _ in 0..count { - let r = &mut self.world.random; - let mut source = [ - lo.x + r.next_double() * (hi.x - lo.x), - lo.y + r.next_double() * (hi.y - lo.y), - lo.z + r.next_double() * (hi.z - lo.z), - ]; - let mut destination = [ - f64::from(pos.0) + r.next_double(), - f64::from(pos.1) + r.next_double(), - f64::from(pos.2) + r.next_double(), - ]; - if towards { - std::mem::swap(&mut source, &mut destination); - } - let duration = r.next_int_bound(40).unwrap_or(0) + 10; - let color = if towards { ORANGE } else { GRAY }; - self.particles.add( - &ParticleOptions::trail(destination, color, duration), - source, - [0.0; 3], - ); - } - } - /// `CreakingHeartBlockEntity.spreadResin`: a resin clump on the first log - /// face found within two steps of pale oak logs. - fn heart_spread_resin(&mut self, pos: Pos) -> Option { - let mut visited: HashSet = HashSet::new(); - let mut queue: VecDeque<(Pos, i32)> = VecDeque::new(); - queue.push_back((pos, 0)); - let mut count = 0; - while let Some((current, depth)) = queue.pop_front() { - if !visited.insert(current) { - continue; - } - // The node processor. - if self.is_pale_oak_log(current) { - for d in self.shuffled_directions() { - let n = ( - current.0 + DIRECTIONS[d][0], - current.1 + DIRECTIONS[d][1], - current.2 + DIRECTIONS[d][2], - ); - let neighbour = self.world.block(n.0, n.1, n.2); - let opposite = d ^ 1; - let clump = self.resin_clump_for(neighbour); - let Some(clump) = clump else { continue }; - if self.prop_is(clump, FACE_NAMES[opposite]) { - continue; - } - let Some(placed) = self.with_face(clump, FACE_NAMES[opposite]) else { - continue; - }; - let _ = self.level_set([n.0, n.1, n.2], placed); - return Some(n); - } - } - count += 1; - if count >= 64 { - return None; - } - if depth < 2 { - // The neighbour provider: adjacent pale oak logs. - for d in self.shuffled_directions() { - let n = ( - current.0 + DIRECTIONS[d][0], - current.1 + DIRECTIONS[d][1], - current.2 + DIRECTIONS[d][2], - ); - if self.is_pale_oak_log(n) { - queue.push_back((n, depth + 1)); - } + mobs.extend(added); + self.mobs = mobs; + self.persist.uuids = uuids; + self.next_entity = next_entity; + self.world.random = random; + let mut mob_events = Vec::new(); + for e in events { + match e { + HeartEvent::SetBlock(at, state) => self.level_set(at, state)?, + HeartEvent::Sound(name, at, volume, pitch) => { + self.audio + .play(&format!("minecraft:{name}"), Some(at), volume, pitch) } + HeartEvent::Trail { + at, + target, + color, + duration, + } => self.particles.add( + &ParticleOptions::trail(target, color, duration), + at, + [0.0; 3], + ), + HeartEvent::OutputChanged(at) => self.container_changed((at[0], at[1], at[2])), + HeartEvent::Mob(event) => mob_events.push(event), } } - None - } - /// The state a face of resin can be added to: air, a source of water, or - /// a clump already there. - fn resin_clump_for(&self, neighbour: BlockStateId) -> Option { - let registry = self.res.assets.registry; - let clump = registry.default_state("minecraft:resin_clump")?; - let facts = self.res.facts.get(neighbour); - if self.res.facts.is_air(neighbour) { - Some(clump) - } else if &*facts.name == "minecraft:water" - && facts.fluid_level == 8 - && !facts.fluid_falling - { - let mut s = registry.state(clump)?.clone(); - s.properties.insert("waterlogged".into(), "true".into()); - registry.resolve(&s).ok() - } else if &*facts.name == "minecraft:resin_clump" { - Some(neighbour) - } else { - None - } - } - fn prop_is(&self, state: BlockStateId, key: &str) -> bool { - self.res - .assets - .registry - .state(state) - .and_then(|s| s.properties.get(key)) - .is_some_and(|v| v == "true") - } - fn with_face(&self, state: BlockStateId, face: &str) -> Option { - let mut s = self.res.assets.registry.state(state)?.clone(); - s.properties.insert(face.to_owned(), "true".to_owned()); - self.res.assets.registry.resolve(&s).ok() + self.handle_mob_events(mob_events)?; + let _ = key; + Ok(()) } /// A creaking bound to the heart at `home` was hurt (`creakingHurt`). - pub(super) fn creaking_hurt(&mut self, home: [i32; 3], id: u32, by_player: bool) { + pub(super) fn creaking_hurt(&mut self, home: [i32; 3], _id: u32, by_player: bool) { if !by_player { return; } @@ -255,29 +171,9 @@ impl Game<'_> { else { return; }; - if self.heart_protector(&mut heart) == Some(id) && heart.emitter <= 0 { - self.heart_emit(&mut heart, key, 20, false); - let state = self.world.block(key.0, key.1, key.2); - if self.heart_state_name(state) == "awake" { - let clumps = 2 + self.world.random.next_int_bound(2).unwrap_or(0); - for _ in 0..clumps { - if let Some(at) = self.heart_spread_resin(key) { - self.audio.play( - "minecraft:block.resin.place", - Some([ - f64::from(at.0) + 0.5, - f64::from(at.1) + 0.5, - f64::from(at.2) + 0.5, - ]), - 1.0, - 1.0, - ); - } - } - } - heart.emitter = 100; - heart.emitter_target = self.mob_center(id).map(|(c, _)| c); - } + let _ = self.with_heart(key, &mut heart, |h, w, lr, host, out| { + creaking_heart::creaking_hurt(h, home, w, lr, host, out); + }); self.world .block_entities .insert(key, BlockEntity::CreakingHeart(heart)); @@ -331,9 +227,18 @@ impl Game<'_> { else { return; }; - self.heart_remove_protector(&mut heart, true); + let _ = self.with_heart(key, &mut heart, |h, _, _, host, out| { + creaking_heart::remove_protector(h, host, true, out); + }); let state = self.world.block(key.0, key.1, key.2); - if self.prop_is(state, "natural") && !self.creative && !self.spectator() { + let natural = self + .res + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("natural").cloned()) + .is_some_and(|v| v == "true"); + if natural && !self.creative && !self.spectator() { let xp = 20 + self.world.random.next_int_bound(5).unwrap_or(0) as u32; self.spawn_orbs( [ @@ -348,96 +253,6 @@ impl Game<'_> { .block_entities .insert(key, BlockEntity::CreakingHeart(heart)); } - /// `SpawnUtil.trySpawnMob(CREAKING, .., 5, 16, 8, ON_TOP_OF_COLLIDER_NO_LEAVES, true)`. - fn spawn_protector(&mut self, pos: Pos) -> Option { - let t = self.res.mob_types.get("minecraft:creaking").cloned()?; - for _ in 0..5 { - let r = &mut self.world.random; - let dx = r.next_int_bound(33).unwrap_or(16) - 16; - let dz = r.next_int_bound(33).unwrap_or(16) - 16; - let mut at = (pos.0 + dx, pos.1 + 8, pos.2 + dz); - if !self.world.loaded(at.0, at.2) { - continue; - } - // moveToPossibleSpawnPosition: scan down for a collider with room above. - let mut above = self.world.block(at.0, at.1, at.2); - let mut found = false; - for _ in 0..=16 { - at.1 -= 1; - let current = self.world.block(at.0, at.1, at.2); - let facts = self.res.facts.get(current); - let leaves = self - .res - .items - .block_tags - .get("minecraft:leaves") - .is_some_and(|s| s.contains(&*facts.name)); - let clear_above = self - .res - .behaviours - .collision_shape(above) - .map_or(!self.res.facts.get(above).full_collision, |s| s.is_empty()); - if clear_above && !leaves && facts.sturdy_full & (1 << 1) != 0 { - at.1 += 1; - found = true; - break; - } - above = current; - } - if !found { - continue; - } - // noCollision(spawn box) and no liquid. - let w = t.width / 2.0; - let bounds = Aabb::new( - horizon_core::geometry::Vec3::new( - f64::from(at.0) + 0.5 - w, - f64::from(at.1), - f64::from(at.2) + 0.5 - w, - ), - horizon_core::geometry::Vec3::new( - f64::from(at.0) + 0.5 + w, - f64::from(at.1) + t.height, - f64::from(at.2) + 0.5 + w, - ), - ); - let mut scene = horizon_client::collisions::SceneCollisions { - world: &self.world, - binding: self.collision, - }; - let free = scene.unobstructed(bounds).unwrap_or(false); - let wet = self.res.facts.get(self.world.block(at.0, at.1, at.2)).fluid - != horizon_client::blocks::Fluid::None; - if !free || wet { - continue; - } - let id = self.spawn_mob( - "minecraft:creaking", - [ - f64::from(at.0) + 0.5, - f64::from(at.1), - f64::from(at.2) + 0.5, - ], - false, - )?; - if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { - creaking::set_transient(m, [pos.0, pos.1, pos.2]); - } - return Some(id); - } - None - } - /// `CreakingHeartBlockEntity.computeAnalogOutputSignal`. - fn heart_output(&mut self, heart: &mut CreakingHeart, pos: Pos) -> i32 { - if heart.creaking.is_none() { - return 0; - } - let Some(id) = self.heart_protector(heart) else { - return 0; - }; - let distance = self.heart_distance_to_creaking(id, pos).clamp(0.0, 32.0) / 32.0; - 15 - (distance * 15.0).floor() as i32 - } /// `CreakingHeartBlockEntity.serverTick` for every heart. pub(super) fn tick_creaking_hearts(&mut self) -> Result<()> { let keys: Vec = self @@ -456,11 +271,17 @@ impl Game<'_> { let state = self.world.block(key.0, key.1, key.2); if &*self.res.facts.get(state).name != "minecraft:creaking_heart" { // The block is gone: preRemoveSideEffects. - self.heart_remove_protector(&mut heart, false); + self.with_heart(key, &mut heart, |h, _, _, host, out| { + creaking_heart::remove_protector(h, host, false, out); + })?; continue; } + // getTicker: none once uprooted. if self.heart_state_name(state) != "uprooted" { - self.heart_tick(&mut heart, key, state)?; + let pos = [key.0, key.1, key.2]; + self.with_heart(key, &mut heart, |h, w, lr, host, out| { + creaking_heart::server_tick(h, pos, w, lr, host, out); + })?; } self.world .block_entities @@ -469,139 +290,11 @@ impl Game<'_> { self.scan_for_hearts(); Ok(()) } - fn heart_tick( - &mut self, - heart: &mut CreakingHeart, - key: Pos, - state: BlockStateId, - ) -> Result<()> { - heart.ticks_existed += 1; - let output = self.heart_output(heart, key); - if output != heart.output_signal { - heart.output_signal = output; - self.container_changed(key); - } - if heart.emitter > 0 { - if heart.emitter > 50 { - self.heart_emit(heart, key, 1, true); - self.heart_emit(heart, key, 1, false); - } - if heart.emitter % 10 == 0 && heart.emitter_target.is_some() { - if let Some(id) = self.heart_protector(heart) - && let Some((c, _)) = self.mob_center(id) - { - heart.emitter_target = Some(c); - } - if let Some(target) = heart.emitter_target { - let center = [ - f64::from(key.0) + 0.5, - f64::from(key.1) + 0.5, - f64::from(key.2) + 0.5, - ]; - let progress = 0.2 + 0.8 * f64::from(100 - heart.emitter) / 100.0; - let at = [ - (center[0] - target[0]) * progress + target[0], - (center[1] - target[1]) * progress + target[1], - (center[2] - target[2]) * progress + target[2], - ]; - let volume = heart.emitter as f32 / 2.0 / 100.0 + 0.5; - self.audio - .play("minecraft:block.creaking_heart.hurt", Some(at), volume, 1.0); - } - } - heart.emitter -= 1; - } - let ticker = heart.ticker; - heart.ticker -= 1; - if ticker >= 0 { - return Ok(()); - } - heart.ticker = self.world.random.next_int_bound(5).unwrap_or(0) + 20; - // updateCreakingState: logs gone and no creaking means uprooted. - let active = self.creaking_active(); - let has_logs = self.with_level(|b, level, ticks| { - b.creaking_heart_has_logs(level, ticks, BlockPos::new(key.0, key.1, key.2), state) - }); - let wanted = if !has_logs && heart.creaking.is_none() { - "uprooted" - } else if active { - "awake" - } else { - "dormant" - }; - let mut current = self.heart_state_name(state); - if wanted != current - && let Some(next) = self.heart_with_state(state, wanted) - { - self.level_set([key.0, key.1, key.2], next)?; - current = wanted.to_owned(); - if wanted == "uprooted" { - return Ok(()); - } - } - if heart.creaking.is_none() { - if current == "awake" && self.spawning_monsters() { - let near = self.player.as_ref().is_some_and(|p| { - let (dx, dy, dz) = ( - p.position.x - (f64::from(key.0) + 0.5), - p.position.y - (f64::from(key.1) + 0.5), - p.position.z - (f64::from(key.2) + 0.5), - ); - dx * dx + dy * dy + dz * dz < 32.0 * 32.0 - }) && !self.spectator(); - if near && let Some(id) = self.spawn_protector(key) { - let uuid = self.uuid_for(id); - heart.creaking = Some((Some(id), uuid)); - heart.ticks_existed = 0; - let at = self.mob_center(id).map(|(c, _)| c); - self.audio - .play("minecraft:entity.creaking.spawn", at, 1.0, 1.0); - self.audio.play( - "minecraft:block.creaking_heart.spawn", - Some([ - f64::from(key.0) + 0.5, - f64::from(key.1) + 0.5, - f64::from(key.2) + 0.5, - ]), - 1.0, - 1.0, - ); - } - } - } else if let Some(id) = self.heart_protector(heart) { - let persistent = self - .mobs - .iter() - .find(|m| m.id == id) - .is_some_and(|m| m.persistent); - let eye = self.player_view().map(|v| v.eye); - let stuck = self - .mobs - .iter_mut() - .find(|m| m.id == id) - .is_some_and(|m| creaking::player_is_stuck(m, eye)); - if (!active && !persistent) - || self.heart_distance_to_creaking(id, key) > TOO_FAR - || stuck - { - self.heart_remove_protector(heart, false); - } - } - Ok(()) - } - fn heart_with_state(&self, state: BlockStateId, wanted: &str) -> Option { - let mut s = self.res.assets.registry.state(state)?.clone(); - s.properties - .insert("creaking_heart_state".to_owned(), wanted.to_owned()); - self.res.assets.registry.resolve(&s).ok() - } /// `ServerLevel.isSpawningMonsters`. fn spawning_monsters(&self) -> bool { - self.ui.difficulty != 0 && self.ui.rules.bool("spawn_monsters") - } - /// `EnvironmentAttributes.CREAKING_ACTIVE`. - pub(super) fn creaking_active(&mut self) -> bool { - self.with_level(|b, level, ticks| b.creaking_active(level, ticks)) + self.ui.difficulty != 0 + && self.ui.rules.bool("spawn_mobs") + && self.ui.rules.bool("spawn_monsters") } /// Hearts that came with generated or loaded chunks get their block /// entity (`newBlockEntity`) the first time their chunk is seen. diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index beec2036e..c5cf7ec02 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -86,7 +86,7 @@ impl ProjectileWorld for ProjWorld<'_, '_> { .full_collision } } -fn seen(m: &Mob, player: Option<[i32; 4]>) -> Seen { +pub(super) fn seen(m: &Mob, player: Option<[i32; 4]>) -> Seen { let villager = m.species() == Species::Villager; Seen { id: m.id, @@ -453,9 +453,11 @@ impl Game<'_> { let mut events = Vec::new(); let mut mobs = std::mem::take(&mut self.mobs); let mut dead = Vec::new(); + // The level random (`ServerLevel.getRandom`): behaviours' durations and + // the like draw from it, and it goes on from where they left it. + let mut scratch = self.world.random.clone(); { 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 @@ -477,6 +479,7 @@ impl Game<'_> { horizon_client::mobs::apply_mob_pushes(m, &mut pushes); } } + self.world.random = scratch; self.mobs.append(&mut mobs); self.sync_riders(); self.tick_skeleton_traps(); @@ -644,7 +647,8 @@ impl Game<'_> { pub(super) fn handle_mob_events(&mut self, events: Vec) -> Result<()> { for e in events { match e { - MobEvent::Sound(name, at, volume, pitch) => { + MobEvent::Sound(name, at, volume, pitch) + | MobEvent::LocalSound(name, at, volume, pitch) => { self.audio .play(&format!("minecraft:{name}"), Some(at), volume, pitch) } diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 948039fcc..a72530e6a 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -477,14 +477,6 @@ impl Game<'_> { pub(super) fn uuid_for(&mut self, id: u32) -> [i32; 4] { *self.persist.uuids.entry(id).or_insert_with(random_uuid) } - /// The loaded mob with a saved UUID. - pub(super) fn mob_id_for_uuid(&self, uuid: [i32; 4]) -> Option { - self.persist - .uuids - .iter() - .find(|(id, u)| **u == uuid && self.mobs.iter().any(|m| m.id == **id && !m.removed)) - .map(|(id, _)| *id) - } /// `BlockState.CODEC`: a block name or `{id, properties}` (or legacy `{Name, Properties}`). fn state_from_nbt(&self, tag: &Tag) -> Option { let registry = self.res.assets.registry; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index cd22c40e8..804f3aad6 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -17,6 +17,7 @@ pub mod caravan; pub mod control; pub mod copper_golem; pub mod creaking; +pub mod creaking_heart; pub mod cube; pub mod data; pub mod drops; @@ -35,6 +36,7 @@ pub mod keyframes; pub mod leash; pub mod living; pub mod llama; +pub mod monster_brain; pub mod nautilus; pub mod nav; pub mod nether; @@ -556,6 +558,8 @@ pub struct Extra { /// `Mob.dropChances` by `EquipmentSlot` (`drops::SLOTS` order) when set /// explicitly; None uses the defaults of `drops::drop_chance`. pub drop_chances: Option>, + /// A breeze's or creaking's brain (`monster_brain`). + pub brain: Option>, } #[derive(Clone, Debug)] pub struct Mob { @@ -637,6 +641,9 @@ pub enum MobEvent { }, /// A sound event id that is not a static string (variant sounds). SoundId(String, [f64; 3], f32, f32), + /// `Level.playLocalSound`: a sound the client plays for itself, never + /// sent by a server (a breeze's whirl and idle sounds). + LocalSound(&'static str, [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. diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index fc9bd0398..7b276542c 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -213,6 +213,9 @@ fn pre_tick(m: &mut Mob, events: &mut Vec) { if m.species() == Species::Wither && m.alive() { super::wither::steer(m); } + if m.species() == Species::Breeze { + super::breeze::tick(m, events); + } match family(m.species()) { Family::Hostile => { if m.species() == Species::Creeper { @@ -355,8 +358,9 @@ pub fn tick( if !m.no_ai { ai_step(m, w, level_random, events); } - // Mob.tickHeadTurn -> BodyRotationControl.clientTick - if m.alive() { + // Mob.tickHeadTurn -> BodyRotationControl.clientTick (a frozen + // creaking's waits). + if m.alive() && !(super::creaking::is_creaking(m) && !super::creaking::can_move(m)) { m.body_rotation_tick(); } events.append(&mut m.outbox); @@ -528,11 +532,14 @@ fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec) { Some(s) => s, None => return, }, - // Breeze.playAmbientSound. - Species::Breeze => match super::breeze::ambient(m) { - Some(s) => s, - None => return, - }, + // Breeze.playAmbientSound: a local sound, nothing drawn. + Species::Breeze => { + if let Some(s) = super::breeze::ambient(m) { + let at = [m.position.x, m.position.y, m.position.z]; + events.push(MobEvent::LocalSound(s, at, 1.0, 1.0)); + } + return; + } // Creaking.getAmbientSound: silent while awake. Species::Creaking if m.extra.flag => return, // Shulker.playAmbientSound: silent while closed. @@ -730,10 +737,6 @@ fn server_ai_step( events: &mut Vec, ) { m.ai.no_action_time += 1; - // A creaking looked at stands still. - if super::creaking::is_creaking(m) && !super::creaking::can_move(m) { - return; - } // A saddled mount follows its rider instead of its goals. if super::equine::controlled(m) { super::equine::ridden_step(m); @@ -756,7 +759,16 @@ fn server_ai_step( } m.ai.targets = targets; m.ai.goals = goals; - m.nav_tick(w); + // A creaking looked at stands still: its navigation, move, look and jump + // controls wait (CreakingPathNavigation and the Creaking*Control). + let frozen = super::creaking::is_creaking(m) && !super::creaking::can_move(m); + if !frozen { + m.nav_tick(w); + } + if super::monster_brain::has_brain(m.species()) { + // Breeze/Creaking.customServerAiStep: the brain, then updateActivity. + super::monster_brain::tick(m, w, level_random, events); + } if m.species() == Species::Villager { // Villager.customServerAiStep: the brain, then the raid sound roll. super::villager_brain::tick(m, w, level_random, events); @@ -766,6 +778,10 @@ fn server_ai_step( let mut cx = Cx { w, events }; custom_server_ai_step(m, &mut cx); } + if frozen { + m.ai.jumping = false; + return; + } m.move_control_tick(w, events); m.look_control_tick(); m.jump_control_tick(); @@ -815,7 +831,7 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { Species::Ravager => super::ravager::ai_step(m, w, events), Species::Wither => super::wither::ai_step(m, w, events), Species::Allay => super::allay::ai_step(m), - Species::Breeze => super::breeze::ai_step(m, events), + Species::Breeze => super::breeze::ai_step(m), Species::Sniffer => super::sniffer::ai_step(m, events), Species::HappyGhast => super::happy_ghast::ai_step(m, w), Species::Villager => super::villager::ai_step(m, w), @@ -935,8 +951,11 @@ pub fn walk_target_value(m: &Mob, w: &MobWorld, p: [i32; 3]) -> f32 { if family(m.species()) == Family::Guardian && w.fluid(p[0], p[1], p[2]) == Fluid::Water { return 10.0 + light(); } - // AbstractNautilus.getWalkTargetValue: everywhere alike. - if matches!(m.species(), Species::Nautilus | Species::ZombieNautilus) { + // AbstractNautilus and Creaking.getWalkTargetValue: everywhere alike. + if matches!( + m.species(), + Species::Nautilus | Species::ZombieNautilus | Species::Creaking + ) { return 0.0; } if m.hostile() @@ -1082,6 +1101,10 @@ pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { source, }), } + // Mob.doHurtTarget ends with playAttackSound once the hit landed. + if super::creaking::is_creaking(m) { + m.voice("entity.creaking.attack", cx.events); + } let _ = Fluid::None; } /// Mob.ate (sheep regrow wool, babies grow). diff --git a/crates/horizon-client/src/mobs/breeze.rs b/crates/horizon-client/src/mobs/breeze.rs index d01bd34cc..4a8484835 100644 --- a/crates/horizon-client/src/mobs/breeze.rs +++ b/crates/horizon-client/src/mobs/breeze.rs @@ -1,474 +1,43 @@ -//! Breezes (`Breeze`, `BreezeAi`): the brain's idle and fight activities as -//! one simulation (start attacking the nearest player or iron golem or whoever -//! hurt it, slide to a walk target, then shoot, long jump, shoot when stuck or -//! slide), memories with vanilla's expiry, the poses and their animations, -//! `BreezeModel`'s layers and the wind charges it shoots. +//! Breezes (`Breeze`): the poses and their animations, the long jump's +//! arithmetic, the sounds of `Breeze.tick` and `BreezeModel`'s layers. The +//! brain (`BreezeAi` and its behaviours) is in `monster_brain`. use super::{ - Mob, MobEvent, MobWorld, Species, Who, + Mob, MobEvent, MobWorld, Species, anim::{Poses, State}, - goals::{Cx, Float, Goal, goal_clone}, keyframes::Animation, }; -use crate::projectiles::{Projectile, ProjectileKind}; use horizon_core::{geometry::Vec3, random::RandomSource}; use std::collections::HashMap; -// Breeze state (see `brain`): `variant3` the pose, `variant` the pose the -// animations last saw, `ints[0..6]` the memories (shoot, shoot cooldown, -// shoot charging, shoot recovering, jump cooldown, jump inhaling) as the -// remaining ticks plus one, `point` the walk target with `vector[0]` its -// speed and `vector[1]` how close is close enough, `home` the jump target, -// `vector[2]` the whirl sound clock, `flag` the long jump behaviour with its -// end tick in `anim_ticks`, `flag2` the shoot behaviour with its end tick in -// `egg_time`, `counter` the end tick of the slide to the walk target (0 when -// not sliding), `counter2` the end tick of doing nothing, `anger` the -// cooldown before the next try to walk, `scratch[0]` the ticks it may still -// be unable to attack its target. AnimState states: -// idle, shoot, slide, slide back, inhale, long jump. +// `variant3` is the pose, `variant` the pose the animations last saw, +// `vector[2]` `soundTick`. AnimState states: idle, shoot, slide, slide back, +// inhale, long jump. pub const STANDING: u8 = 0; pub const SHOOTING: u8 = 1; pub const INHALING: u8 = 2; pub const LONG_JUMPING: u8 = 3; pub const SLIDING: u8 = 4; -const SHOOT: usize = 0; -const SHOOT_COOLDOWN: usize = 1; -const SHOOT_CHARGING: usize = 2; -const SHOOT_RECOVERING: usize = 3; -const JUMP_COOLDOWN: usize = 4; -const JUMP_INHALING: usize = 5; - -const SHOOT_INITIAL_DELAY: i32 = 15; -const SHOOT_RECOVER_DELAY: i32 = 4; -const SHOOT_COOLDOWN_TICKS: i32 = 10; -const INHALING_TICKS: i32 = 10; const ALLOWED_ANGLES: [i32; 5] = [40, 55, 60, 75, 80]; +/// `Breeze`'s constructor: no goals, the brain thinks (`monster_brain`). pub fn register(m: &mut Mob) { m.set_malus(super::path::PathType::OnTopOfTrapdoor, -1.0); m.set_malus(super::path::PathType::Fire, -1.0); - // Swim(0.8) and the brain. - m.ai.goals.add(0, Float); - m.ai.goals.add(0, Brain); } pub fn pose(m: &Mob) -> u8 { m.extra.variant3 } -fn set_pose(m: &mut Mob, pose: u8) { +pub(super) fn set_pose(m: &mut Mob, pose: u8) { m.extra.variant3 = pose; } -fn has(m: &Mob, memory: usize) -> bool { - m.extra.ints[memory] > 0 -} -/// `Brain.setMemoryWithExpiry`: present now and for `ttl` more ticks. -fn remember(m: &mut Mob, memory: usize, ttl: i32) { - m.extra.ints[memory] = ttl + 1; -} -fn forget(m: &mut Mob, memory: usize) { - m.extra.ints[memory] = 0; -} -fn walk_target(m: &Mob) -> bool { - m.extra.point.is_some() -} -fn now(m: &Mob) -> i32 { - m.age as i32 -} /// `Breeze.getFiringYPosition`. pub fn firing_y(m: &Mob) -> f64 { m.position.y + f64::from(m.height()) / 2.0 + f64::from(0.3_f32) } -/// `Breeze.withinInnerCircleRange`. -fn within_inner_circle(m: &Mob, target: Vec3) -> bool { - let me = Vec3::new( - m.position.x.floor() + 0.5, - m.position.y.floor() + 0.5, - m.position.z.floor() + 0.5, - ); - (target.x - me.x).powi(2) + (target.z - me.z).powi(2) < 16.0 && (target.y - me.y).abs() < 10.0 -} -/// `Entity.lookAt` with the eyes anchor: snap body and head to face a point. -fn snap_look(m: &mut Mob, at: [f64; 3]) { - let (dx, dy, dz) = ( - at[0] - m.position.x, - at[1] - m.eye_y(), - at[2] - m.position.z, - ); - let flat = (dx * dx + dz * dz).sqrt(); - m.head_pitch = (-dy.atan2(flat).to_degrees()) as f32; - m.yaw = (dz.atan2(dx).to_degrees() - 90.0) as f32; - m.head_yaw = m.yaw; - m.previous_head_pitch = m.head_pitch; - m.previous_yaw = m.yaw; - m.previous_head_yaw = m.yaw; -} -/// `BreezeUtil.hasLineOfSight`. -fn line_of_sight(m: &Mob, w: &MobWorld, target: Vec3) -> bool { - let from = m.position; - let range = 50.0_f64.max(m.attrs.follow_range); - from.distance(target) <= range && w.clear_between(from, target, false) -} -/// `BreezeUtil.randomPointBehindTarget`: four to eight blocks behind the -/// target's facing, with a spread of 45 degrees. -fn point_behind(m: &mut Mob, target: Vec3, head_yaw: f32) -> Vec3 { - let view = head_yaw + 180.0 + m.random.next_gaussian() as f32 * 90.0 / 2.0; - let r = 4.0 + m.random.next_float() * 4.0; - let d = Vec3::direction_from_rotation(0.0, view).scale(f64::from(r)); - target.add_vector(d) -} -/// The attack target's position, eye height, facing and whether it is a -/// player. -struct Quarry { - position: Vec3, - eye: f64, - yaw: f32, - height: f64, -} -fn quarry(m: &Mob, cx: &Cx, who: Who) -> Option { - let t = cx.w.target_info(who)?; - let yaw = match who { - Who::Player => { - cx.w.player - .as_ref() - .map_or(0.0, |p| (-p.look[0]).atan2(p.look[2]).to_degrees() as f32) - } - Who::Mob(id) => cx.w.seen(id).map_or(m.yaw, |s| s.yaw), - }; - Some(Quarry { - position: t.position, - eye: t.eye_y, - yaw, - height: t.bounds.max_position().y - t.bounds.min_position().y, - }) -} -/// `TargetingConditions.forCombat().range(follow)` plus `canAttack`: a -/// player (not in creative or spectator) or an iron golem it can see. -fn attackable(m: &mut Mob, cx: &Cx, who: Who) -> bool { - let follow = m.attrs.follow_range; - match who { - Who::Player => m.can_target_player(cx.w, follow, true), - Who::Mob(id) => { - let Some(s) = cx.w.seen(id) else { - return false; - }; - s.alive - && s.species == Species::IronGolem - && m.distance_sqr(s.position) <= follow * follow - && m.sees(cx.w, who) - } - } -} -/// `BreezeAttackEntitySensor` and `HurtBySensor`: candidates for -/// `StartAttacking`. -fn nearest_attackable(m: &mut Mob, cx: &Cx) -> Option { - let follow = m.attrs.follow_range; - let mut candidates: Vec<(f64, Who)> = Vec::new(); - if let Some(p) = &cx.w.player - && p.alive - && !p.creative - && !p.spectator - { - candidates.push((m.distance_sqr(p.position), Who::Player)); - } - for s in - cx.w.nearby(m.position, follow, |s| s.species == Species::IronGolem) - { - candidates.push((m.distance_sqr(s.position), Who::Mob(s.id))); - } - candidates.sort_by(|a, b| a.0.total_cmp(&b.0)); - candidates - .into_iter() - .map(|c| c.1) - .find(|w| attackable(m, cx, *w)) -} -fn hurt_by(m: &Mob, cx: &Cx) -> Option { - let (d, at) = m.last_damage?; - if i64::from(m.age) - at > 40 { - return None; - } - match d.attacker? { - Who::Player => Some(Who::Player), - Who::Mob(id) => { - cx.w.seen(id) - .filter(|s| s.alive && s.species == Species::IronGolem) - .map(|_| Who::Mob(id)) - } - } -} -/// The goal that runs the brain every tick. -#[derive(Clone, Debug)] -struct Brain; -impl Goal for Brain { - goal_clone!(); - fn flags(&self) -> u8 { - 0 - } - fn can_use(&mut self, _: &mut Mob, _: &mut Cx) -> bool { - true - } - fn every_tick(&self) -> bool { - true - } - fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { - brain(m, cx); - } -} -/// `Brain.tick`: memories expire, sensors scan, behaviours start in -/// priority order for the active activity, then the running ones tick. -fn brain(m: &mut Mob, cx: &mut Cx) { - for i in 0..6 { - if m.extra.ints[i] > 0 { - m.extra.ints[i] -= 1; - } - } - if m.extra.anger > 0 { - m.extra.anger -= 1; - } - let fight = m.ai.target.is_some() && !walk_target(m); - if fight { - stop_if_target_invalid(m, cx); - start_shoot(m, cx); - start_long_jump(m, cx); - start_shoot_when_stuck(m); - start_slide(m, cx); - } else { - // StartAttacking on the nearest attackable, then on whoever hurt it. - if m.ai.target.is_none() { - let scan = (m.age + m.id).is_multiple_of(20); - let found = if scan { - nearest_attackable(m, cx) - } else { - None - }; - let found = found.or_else(|| hurt_by(m, cx)); - if let Some(who) = found { - m.ai.target = Some(who); - m.extra.anger = 0; - m.extra.counter2 = 0; - } - } - start_walking(m, cx); - idle_stroll(m, cx); - } - tick_shoot(m, cx); - tick_long_jump(m, cx); - tick_walking(m, cx); -} -/// `StopAttackingIfTargetInvalid` with `wasEntityAttackableLastNTicks(100)`: -/// the target is dropped once it has not been attackable for 100 ticks. -fn stop_if_target_invalid(m: &mut Mob, cx: &mut Cx) { - let Some(who) = m.ai.target else { return }; - let alive = cx.w.target_info(who).is_some_and(|t| t.alive); - if alive && attackable(m, cx, who) { - m.extra.scratch[0] = 100; - return; - } - m.extra.scratch[0] -= 1; - if !alive || m.extra.scratch[0] < 0 { - m.ai.target = None; - m.extra.scratch[0] = 0; - } -} -/// `Shoot.checkExtraStartConditions` and `start`. -fn start_shoot(m: &mut Mob, cx: &mut Cx) { - if m.extra.flag2 - || !has(m, SHOOT) - || has(m, SHOOT_COOLDOWN) - || has(m, SHOOT_CHARGING) - || has(m, SHOOT_RECOVERING) - || walk_target(m) - || m.extra.home.is_some() - || pose(m) != STANDING - { - return; - } - let Some(q) = m.ai.target.and_then(|w| quarry(m, cx, w)) else { - return; - }; - if m.position.distance_squared(q.position) >= 256.0 { - forget(m, SHOOT); - return; - } - m.extra.flag2 = true; - m.extra.egg_time = now(m) + SHOOT_INITIAL_DELAY + 1 + SHOOT_RECOVER_DELAY; - set_pose(m, SHOOTING); - remember(m, SHOOT_CHARGING, SHOOT_INITIAL_DELAY); - let at = m.center(); - cx.events - .push(MobEvent::Sound("entity.breeze.inhale", at, 1.0, 1.0)); -} -fn tick_shoot(m: &mut Mob, cx: &mut Cx) { - if !m.extra.flag2 { - return; - } - let target = m.ai.target; - if now(m) > m.extra.egg_time || target.is_none() || !has(m, SHOOT) { - // Shoot.stop. - m.extra.flag2 = false; - if pose(m) == SHOOTING { - set_pose(m, STANDING); - } - remember(m, SHOOT_COOLDOWN, SHOOT_COOLDOWN_TICKS); - forget(m, SHOOT); - return; - } - let Some(q) = target.and_then(|w| quarry(m, cx, w)) else { - return; - }; - snap_look(m, [q.position.x, q.eye, q.position.z]); - if !has(m, SHOOT_CHARGING) && !has(m, SHOOT_RECOVERING) { - remember(m, SHOOT_RECOVERING, SHOOT_RECOVER_DELAY); - let start = Vec3::new(m.position.x, firing_y(m), m.position.z); - let passenger_offset = 0.3; - let (xd, yd, zd) = ( - q.position.x - m.position.x, - q.position.y + q.height * passenger_offset - start.y, - q.position.z - m.position.z, - ); - let mut p = Projectile::new( - ProjectileKind::BreezeWindCharge, - start, - Some(Who::Mob(m.id)), - ); - // 5 - 4 * difficulty at normal. - 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)); - } -} -/// `ShootWhenStuck`. -fn start_shoot_when_stuck(m: &mut Mob) { - if has(m, SHOOT) || has(m, JUMP_INHALING) || m.extra.home.is_some() || walk_target(m) { - return; - } - if m.rider.is_some() || m.fluids.in_water || m.extra.levitation_effect() { - remember(m, SHOOT, 60); - } -} -impl super::Extra { - fn levitation_effect(&self) -> bool { - self.effects.iter().any(|e| e.0 == "minecraft:levitation") - } -} -/// `Slide.start`: pick a point to slide to. -fn start_slide(m: &mut Mob, cx: &mut Cx) { - if has(m, SHOOT) - || has(m, JUMP_COOLDOWN) - || walk_target(m) - || !m.on_ground - || m.fluids.in_water - || pose(m) != STANDING - { - return; - } - let Some(q) = m.ai.target.and_then(|w| quarry(m, cx, w)) else { - return; - }; - let mut position: Option = None; - if within_inner_circle(m, q.position) - && let Some(away) = - m.default_random_pos_away(cx.w, 5, 5, [q.position.x, q.position.y, q.position.z]) - { - let away = Vec3::new(away[0], away[1], away[2]); - if line_of_sight(m, cx.w, away) - && q.position.distance_squared(away) > q.position.distance_squared(m.position) - { - position = Some(away); - } - } - let position = position.unwrap_or_else(|| { - if m.random.next_boolean() { - point_behind(m, q.position, q.yaw) - } else { - // randomPointInMiddleCircle: stop four to eight blocks short. - let d = q.position.subtract(m.position); - let distance = d.length() - (8.0 + (4.0 - 8.0) * m.random.next_double()); - m.position.add_vector(d.normalize().scale(distance)) - } - }); - m.extra.point = Some([position.x.floor(), position.y.floor(), position.z.floor()]); - m.extra.vector[0] = 0.6; - m.extra.vector[1] = 1.0; -} -/// `SlideToTargetSink` (`MoveToTargetSink`): walk to the walk target. -fn start_walking(m: &mut Mob, cx: &mut Cx) { - if m.extra.counter != 0 { - return; - } - let Some(target) = m.extra.point else { - return; - }; - if m.extra.anger > 0 { - return; - } - let close = m.extra.vector[1] as i32; - let here = [ - m.position.x.floor() as i32, - m.position.y.floor() as i32, - m.position.z.floor() as i32, - ]; - let reached = (target[0] as i32 - here[0]).abs() - + (target[1] as i32 - here[1]).abs() - + (target[2] as i32 - here[2]).abs() - <= close; - let speed = m.extra.vector[0]; - if !reached && m.nav_move_to(cx.w, [target[0] + 0.5, target[1], target[2] + 0.5], speed) { - m.extra.counter = now(m) + 20 + m.random.next_int_bound(21).unwrap_or(0); - cx.events - .push(MobEvent::Sound("entity.breeze.slide", m.center(), 1.0, 1.0)); - set_pose(m, SLIDING); - } else { - m.extra.point = None; - } -} -fn tick_walking(m: &mut Mob, _cx: &mut Cx) { - if m.extra.counter == 0 { - return; - } - let reached = m.extra.point.is_none_or(|target| { - let here = [ - m.position.x.floor() as i32, - m.position.y.floor() as i32, - m.position.z.floor() as i32, - ]; - (target[0] as i32 - here[0]).abs() - + (target[1] as i32 - here[1]).abs() - + (target[2] as i32 - here[2]).abs() - <= m.extra.vector[1] as i32 - }); - if now(m) > m.extra.counter || m.ai.nav.is_done() || reached { - // SlideToTargetSink.stop. - m.extra.counter = 0; - m.extra.point = None; - m.nav_stop(); - set_pose(m, STANDING); - if m.ai.target.is_some() { - remember(m, SHOOT, 60); - } - } -} -/// `RunOne` of `DoNothing(20, 100)` and `RandomStroll.stroll(0.6)`. -fn idle_stroll(m: &mut Mob, cx: &mut Cx) { - if m.extra.counter != 0 || walk_target(m) || m.ai.target.is_some() { - return; - } - if now(m) < m.extra.counter2 { - return; - } - if m.random.next_int_bound(3).unwrap_or(0) == 0 { - m.extra.counter2 = now(m) + 20 + m.random.next_int_bound(81).unwrap_or(0); - } else if let Some(p) = m.land_random_pos(cx.w, 10, 7) { - m.extra.point = Some([p[0].floor(), p[1].floor(), p[2].floor()]); - m.extra.vector[0] = 0.6; - m.extra.vector[1] = 0.0; - } -} -fn can_jump_from_here(m: &Mob, w: &MobWorld) -> bool { +/// `LongJump.canJumpFromCurrentPosition`: not on honey, and four blocks of +/// air or water above. +pub(super) fn can_jump_from_here(m: &Mob, w: &MobWorld) -> bool { let (x, y, z) = ( m.position.x.floor() as i32, m.position.y.floor() as i32, @@ -482,115 +51,36 @@ fn can_jump_from_here(m: &Mob, w: &MobWorld) -> bool { || w.fluid(x, y + i, z) == crate::blocks::Fluid::Water }) } -/// `LongJump.snapToSurface`: the block above the surface below the point, -/// else above the ceiling over it. -fn snap_to_surface(w: &MobWorld, p: Vec3) -> Option<[i32; 3]> { - let (x, z) = (p.x.floor() as i32, p.z.floor() as i32); - let y0 = p.y.floor() as i32; - for y in (y0 - 10..=y0).rev() { - let top = f64::from(w.data.state(w.world.block(x, y, z)).top); - if top > 0.0 { - let hit = (f64::from(y) + top).min(p.y); - return Some([x, hit.floor() as i32 + 1, z]); - } +/// `LongJump.snapToSurface`: the block above where a clip ten blocks down +/// hits, else ten blocks up. +pub(super) fn snap_to_surface(w: &MobWorld, p: Vec3) -> Option<[i32; 3]> { + let above = |hit: Vec3| { + [ + hit.x.floor() as i32, + hit.y.floor() as i32 + 1, + hit.z.floor() as i32, + ] + }; + if let Some(hit) = w.clip_block(p, Vec3::new(p.x, p.y - 10.0, p.z)) { + return Some(above(hit)); } - for y in y0..=y0 + 10 { - if w.data.state(w.world.block(x, y, z)).top > 0.0 { - return Some([x, y + 1, z]); - } - } - None + w.clip_block(p, Vec3::new(p.x, p.y + 10.0, p.z)).map(above) } -fn dangerous_block(name: &str) -> bool { +/// `EntityType.isBlockDangerous` for the breeze (not fire immune). +pub(super) fn dangerous_block(name: &str) -> bool { matches!( name, "minecraft:fire" | "minecraft:soul_fire" | "minecraft:lava" | "minecraft:magma_block" - | "minecraft:campfire" - | "minecraft:soul_campfire" + | "minecraft:lava_cauldron" | "minecraft:wither_rose" | "minecraft:sweet_berry_bush" | "minecraft:cactus" | "minecraft:powder_snow" ) } -/// `LongJump.canRun` and `start`. -fn start_long_jump(m: &mut Mob, cx: &mut Cx) { - if m.extra.flag - || has(m, SHOOT) - || has(m, JUMP_COOLDOWN) - || walk_target(m) - || !can_run_long_jump(m, cx) - { - return; - } - m.extra.flag = true; - m.extra.anim_ticks = now(m) + 200; - if !has(m, JUMP_INHALING) { - remember(m, JUMP_INHALING, INHALING_TICKS); - } - set_pose(m, INHALING); - let at = m.center(); - cx.events - .push(MobEvent::Sound("entity.breeze.charge", at, 1.0, 1.0)); - if let Some(t) = m.extra.home { - snap_look( - m, - [ - f64::from(t[0]) + 0.5, - f64::from(t[1]) + 0.5, - f64::from(t[2]) + 0.5, - ], - ); - } -} -fn can_run_long_jump(m: &mut Mob, cx: &mut Cx) -> bool { - if !m.on_ground && !m.fluids.in_water { - return false; - } - if m.fluids.water > m.eye_height() || m.fluids.in_lava { - return false; - } - if m.extra.home.is_some() { - return true; - } - let Some(who) = m.ai.target else { - return false; - }; - let Some(q) = quarry(m, cx, who) else { - return false; - }; - let follow = m.attrs.follow_range; - let distance = m.position.distance(q.position); - if distance >= follow { - m.ai.target = None; - return false; - } - if distance - 4.0 <= 0.0 || !can_jump_from_here(m, cx.w) { - return false; - } - let behind = point_behind(m, q.position, q.yaw); - let Some(target) = snap_to_surface(cx.w, behind) else { - return false; - }; - if dangerous_block(cx.w.block_name(target[0], target[1] - 1, target[2])) { - return false; - } - let centre = Vec3::new( - f64::from(target[0]) + 0.5, - f64::from(target[1]) + 0.5, - f64::from(target[2]) + 0.5, - ); - if !line_of_sight(m, cx.w, centre) - && !line_of_sight(m, cx.w, centre.add_vector(Vec3::new(0.0, 4.0, 0.0))) - { - return false; - } - m.extra.home = Some(target); - true -} /// `LongJumpUtil.calculateJumpVectorForAngle` without the collision check. fn jump_vector(m: &Mob, target: Vec3, max_velocity: f32, angle: i32) -> Option { let pos = m.position; @@ -599,14 +89,17 @@ fn jump_vector(m: &Mob, target: Vec3, max_velocity: f32, angle: i32) -> Option Option f64::from(max_velocity) { return None; } - let v0r = v0 * angrad.cos(); - let v0y = v0 * angrad.sin(); + let (v0r, v0y) = (v0 * cos, v0 * sin); Some(Vec3::new(v0r * xz.cos(), v0y, v0r * xz.sin()).scale(f64::from(0.95_f32))) } -fn tick_long_jump(m: &mut Mob, cx: &mut Cx) { - if !m.extra.flag { - return; +/// `LongJump.calculateOptimalJumpVector`: the allowed angles shuffled, the +/// first that reaches the target. +pub(super) fn optimal_jump_vector(m: &mut Mob, target: Vec3) -> Option { + let mut angles = ALLOWED_ANGLES; + for i in (2..=angles.len()).rev() { + let j = m.random.next_int_bound(i as i32).unwrap_or(0) as usize; + angles.swap(i - 1, j); } - let ongoing = pose(m) != STANDING && !has(m, JUMP_COOLDOWN); - if now(m) > m.extra.anim_ticks || !ongoing { - // LongJump.stop. - m.extra.flag = false; - if matches!(pose(m), LONG_JUMPING | INHALING) { - set_pose(m, STANDING); - } - m.extra.home = None; - forget(m, JUMP_INHALING); - m.extra.variant2 = 0; - return; - } - let in_water = m.fluids.in_water; - if !in_water && m.extra.variant2 != 0 { - m.extra.variant2 = 0; - } - let finished_inhaling = !has(m, JUMP_INHALING) && pose(m) == INHALING; - if finished_inhaling { - let target = m.extra.home.map(|t| { - Vec3::new( - f64::from(t[0]) + 0.5, - f64::from(t[1]), - f64::from(t[2]) + 0.5, - ) - }); - let mut angles = ALLOWED_ANGLES; - for i in (1..angles.len()).rev() { - let j = m.random.next_int_bound(i as i32 + 1).unwrap_or(0) as usize; - angles.swap(i, j); - } - let max = 0.058_333_334_f32 * m.attrs.follow_range as f32; - let v = target.and_then(|t| angles.iter().find_map(|&a| jump_vector(m, t, max, a))); - let Some(v) = v else { - set_pose(m, STANDING); - return; - }; - if in_water { - m.extra.variant2 = 1; - } - let at = m.center(); - cx.events - .push(MobEvent::Sound("entity.breeze.jump", at, 1.0, 1.0)); - set_pose(m, LONG_JUMPING); - m.yaw = m.body_yaw; - m.velocity = v; - m.on_ground = false; - return; - } - let landed_in_water = in_water && m.extra.variant2 == 0; - if pose(m) == LONG_JUMPING && (m.on_ground || landed_in_water) { - let at = m.center(); - cx.events - .push(MobEvent::Sound("entity.breeze.land", at, 1.0, 1.0)); - set_pose(m, STANDING); - let hurt = m - .last_damage - .is_some_and(|(_, t)| i64::from(m.age) - t <= 40); - remember(m, JUMP_COOLDOWN, if hurt { 2 } else { 10 }); - remember(m, SHOOT, 100); + let max = 0.058_333_334_f32 * m.attrs.follow_range as f32; + let v = angles + .iter() + .find_map(|&a| jump_vector(m, target, max, a))?; + if m.has_effect("minecraft:jump_boost") { + let amp = m + .extra + .effects + .iter() + .find(|e| e.0 == "minecraft:jump_boost") + .map_or(0, |e| e.2); + // LivingEntity.getJumpBoostPower + let boost = f64::from(0.1_f32 * (amp + 1) as f32); + return Some(v.add_vector(Vec3::new(0.0, v.normalize().y * boost, 0.0))); } + Some(v) } /// Whether `Breeze.shouldDiscardFriction` applies (a long jump in the air). pub fn discards_friction(m: &Mob) -> bool { m.species() == Species::Breeze && pose(m) == LONG_JUMPING } -/// `Breeze.tick` and the client's pose-driven animation states. -pub fn ai_step(m: &mut Mob, events: &mut Vec) { +/// The random draws of `Breeze.tick` before `super.tick()`: the ground +/// particle count (standing, shooting or inhaling) and the whirl sound clock +/// (`playWhirlSound` is a local sound, heard on the client only). +pub fn tick(m: &mut Mob, events: &mut Vec) { + if matches!(pose(m), SHOOTING | INHALING | STANDING) { + // emitGroundParticles(1 + random.nextInt(1)) + let _ = m.random.next_int_bound(1); + } + if m.extra.vector[2] == 0.0 { + m.extra.vector[2] = f64::from(m.random.next_int_between_inclusive(1, 80).unwrap_or(1)); + } else { + m.extra.vector[2] -= 1.0; + } + if m.extra.vector[2] == 0.0 { + let pitch = 0.7 + 0.4 * m.random.next_float(); + let volume = 0.8 + 0.2 * m.random.next_float(); + events.push(MobEvent::LocalSound( + "entity.breeze.whirl", + [m.position.x, m.position.y, m.position.z], + volume, + pitch, + )); + } +} +/// The client's pose-driven animation states (`onSyncedDataUpdated` and +/// `Breeze.tick`). +pub fn ai_step(m: &mut Mob) { let age = m.age as f32; let current = pose(m); if current != m.extra.variant { @@ -714,24 +191,9 @@ pub fn ai_step(m: &mut Mob, events: &mut Vec) { m.anim.states[3].start(age); m.anim.states[2].stop(); } - // The whirl sound. - if m.extra.vector[2] <= 0.0 { - m.extra.vector[2] = f64::from(1 + m.random.next_int_bound(80).unwrap_or(0)); - } else { - m.extra.vector[2] -= 1.0; - if m.extra.vector[2] <= 0.0 { - let pitch = 0.7 + 0.4 * m.random.next_float(); - let volume = 0.8 + 0.2 * m.random.next_float(); - events.push(MobEvent::Sound( - "entity.breeze.whirl", - [m.position.x, m.position.y, m.position.z], - volume, - pitch, - )); - } - } } -/// `Breeze.playAmbientSound` and its sound selection. +/// `Breeze.playAmbientSound` (a local sound at volume and pitch 1) and its +/// sound selection. pub fn ambient(m: &Mob) -> Option<&'static str> { if m.ai.target.is_some() && m.on_ground { return None; @@ -763,21 +225,6 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, animations: &HashMap 0 { - v -= 1; - } - if v > 0 { - present += 1; - } - } - assert_eq!(present, 16); - } #[test] fn the_highest_arc_reaches_a_target_within_range() { // Angle 80 degrees: v0^2 = r^2 g / (r sin 2a - 2 y cos^2 a). diff --git a/crates/horizon-client/src/mobs/creaking.rs b/crates/horizon-client/src/mobs/creaking.rs index 0a2e8603a..1d8da0ae8 100644 --- a/crates/horizon-client/src/mobs/creaking.rs +++ b/crates/horizon-client/src/mobs/creaking.rs @@ -1,13 +1,14 @@ -//! Creakings (`Creaking`, `CreakingAi`): they freeze while any player looks at -//! them, wake up when one looks from within 12 blocks, then hunt the nearest -//! visible player and hit every 40 ticks. One bound to a creaking heart takes -//! no damage (it only sways and hurts the heart's resin spreader), dies when -//! the heart no longer protects it and falls apart with the heart. +//! Creakings (`Creaking`): they freeze while any player looks at them, wake +//! up when one looks from within 12 blocks, then hunt the nearest visible +//! player and hit every 40 ticks (the brain, `CreakingAi`, is in +//! `monster_brain`). One bound to a creaking heart takes no damage (it only +//! sways and hurts the heart's resin spreader), dies when the heart no +//! longer protects it and falls apart with the heart. use super::{ Damage, DamageKind, Mob, MobEvent, MobWorld, Species, Who, anim::{Poses, State}, - goals::{Cx, Float, Goal, LookAtPlayer, MeleeAttack, Stroll, TARGET, goal_clone}, keyframes::Animation, + monster_brain, path::PathType, }; use crate::containers::BlockEntity; @@ -33,13 +34,10 @@ const ATTACK_TICKS: i32 = 15; /// `Creaking.TWITCH_DEATH_DURATION`. const TWITCH_TICKS: i32 = 45; +/// `Creaking`'s constructor: no goals (the brain thinks), a navigation that +/// floats. pub fn register(m: &mut Mob) { - let g = &mut m.ai.goals; - g.add(0, Float); - g.add(2, MeleeAttack::new(1.0, false).interval(40)); - g.add(5, Stroll::avoiding_water(0.3)); - g.add(6, LookAtPlayer::new(8.0)); - m.ai.targets.add(1, HuntPlayer); + m.ai.nav.can_float = true; } /// Bound to a heart (`getHomePos() != null`). pub fn heart_bound(m: &Mob) -> bool { @@ -132,10 +130,29 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage) -> bool { m.extra.counter |= HURT | if by_player { HURT_BY_PLAYER } else { 0 }; false } -/// `Creaking.doHurtTarget` extras: the attack animation and sound. -pub fn on_attack(m: &mut Mob, events: &mut Vec) { +/// The rest of `Creaking.hurtServer` for a heart-bound creaking, run by the +/// host right after the damage: whether its heart still protects it, and +/// whether a player is to blame (the heart then calls `creakingHurt`). The +/// caller plays [`sway`] after the heart's reaction. +pub fn take_hurt(m: &mut Mob, w: &MobWorld) -> Option<([i32; 3], bool)> { + if m.extra.counter & HURT == 0 { + return None; + } + let by_player = m.extra.counter & HURT_BY_PLAYER != 0; + m.extra.counter &= !(HURT | HURT_BY_PLAYER); + let home = m.extra.home?; + protected(m, w).then_some((home, by_player)) +} +/// `Mob.playHurtSound` of a heart-bound creaking: the ambient sound clock +/// restarts and it sways. +pub fn sway(m: &mut Mob, events: &mut Vec) { + m.ambient_timer = -m.kind.ambient_interval; + m.voice("entity.creaking.sway", events); +} +/// `Creaking.doHurtTarget`: the attack animation (the sound is the +/// `playAttackSound` that ends `Mob.doHurtTarget`). +pub fn on_attack(m: &mut Mob, _events: &mut Vec) { m.extra.ints[ATTACKING] = ATTACK_TICKS; - m.voice("entity.creaking.attack", events); } /// The heart this creaking is bound to protects it (`isProtector`); a link /// read from a save is trusted until the heart resolves it. @@ -178,7 +195,7 @@ pub fn update(m: &mut Mob, w: &MobWorld, events: &mut Vec) { id: m.id, }); } - m.voice("entity.creaking.sway", events); + sway(m, events); } m.extra.counter &= !(HURT | HURT_BY_PLAYER); } @@ -215,71 +232,84 @@ pub fn stop_in_place(m: &mut Mob) { m.ai.yya = 0.0; m.ai.zza = 0.0; m.ai.speed = 0.0; + m.velocity = horizon_core::geometry::Vec3::ZERO; + m.extra.leash_spin = 0.0; } +/// `Creaking.activate`. fn activate(m: &mut Mob, events: &mut Vec) { - m.ai.target = Some(Who::Player); + monster_brain::set_attack_target(m, Some(Who::Player)); m.voice("entity.creaking.activate", events); m.extra.flag = true; } +/// `Creaking.deactivate`. fn deactivate(m: &mut Mob, events: &mut Vec) { - m.ai.target = None; + monster_brain::set_attack_target(m, None); m.voice("entity.creaking.deactivate", events); m.extra.flag = false; } -/// `LivingEntity.isLookingAtMe(player, 0.5, false, true, eyeY, y + 0.5, mid)`. +/// `LivingEntity.isLookingAtMe(player, 0.5, false, true, eyeY, y + 0.5, +/// (eyeY + y) / 2)`: within the player's view cone and seen through +/// transparent blocks. fn looked_at_by(m: &Mob, w: &MobWorld) -> bool { let Some(p) = &w.player else { return false }; - let look = p.look; + let look = normalize(p.look); let eye = m.eye_y(); [eye, m.position.y + 0.5, (eye + m.position.y) / 2.0] .into_iter() .any(|y| { - let d = [ + let d = normalize([ m.position.x - p.position.x, y - p.eye[1], m.position.z - p.position.z, - ]; - let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); - if len < 1.0e-6 { - return true; + ]); + let dot = look[0] * d[0] + look[1] * d[1] + look[2] * d[2]; + if dot <= 0.5 { + return false; } - let dot = (look[0] * d[0] + look[1] * d[1] + look[2] * d[2]) / len; - dot > 0.5 - && w.line_of_sight( - Vec3::new(p.eye[0], p.eye[1], p.eye[2]), - Vec3::new(m.position.x, y, m.position.z), - ) + // Player.hasLineOfSight(this, VISUAL, NONE, y). + let from = Vec3::new(p.position.x, p.eye[1], p.position.z); + let to = Vec3::new(m.position.x, y, m.position.z); + to.distance(from) <= 128.0 && w.visual_clear_between(from, to) }) } +/// `Vec3.normalize`. +fn normalize(v: [f64; 3]) -> [f64; 3] { + let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt(); + if len < f64::from(1.0e-5_f32) { + [0.0; 3] + } else { + [v[0] / len, v[1] / len, v[2] / len] + } +} /// `Creaking.checkCanMove`: false while looked at; also wakes and calms it. fn check_can_move(m: &mut Mob, w: &MobWorld, events: &mut Vec) -> bool { + let players = monster_brain::nearest_players(m); let active = is_active(m); - // NEAREST_PLAYERS: players within the follow range. - let near = w.player.as_ref().filter(|p| { - let d = Vec3::new(p.position.x, p.position.y, p.position.z); - m.distance_sqr(d) < 32.0 * 32.0 - }); - let Some(p) = near else { + if players.is_empty() { if active { deactivate(m, events); } return true; - }; - // canAttack: alive and not creative or spectator. - let attackable = p.alive && !p.creative; - if attackable { - // GAZE_DISGUISE_EQUIPMENT hides the player once the creaking is awake. - let disguised = p.head.as_deref() == Some("minecraft:carved_pumpkin"); - if (!active || !disguised) && looked_at_by(m, w) { - if active { - return false; - } - if m.distance_sqr(p.position) < ACTIVATION_RANGE_SQ { - activate(m, events); - return false; + } + let mut potential = false; + if let Some(p) = w.player.as_ref().filter(|_| players.contains(&Who::Player)) { + // canAttack (not creative, spectator or dead) and not allied. + if p.alive && !p.creative && !p.spectator { + potential = true; + // GAZE_DISGUISE_EQUIPMENT hides the player once the creaking is awake. + let disguised = p.head.as_deref() == Some("minecraft:carved_pumpkin"); + if (!active || !disguised) && looked_at_by(m, w) { + if active { + return false; + } + if m.distance_sqr(p.position) < ACTIVATION_RANGE_SQ { + activate(m, events); + return false; + } } } - } else if active { + } + if !potential && active { deactivate(m, events); } true @@ -292,12 +322,13 @@ pub fn player_is_stuck(m: &mut Mob, eye: Option<[f64; 3]>) -> bool { }; let b = m.bounds(); let (lo, hi) = (b.min_position(), b.max_position()); + // AABB.contains: the far faces are outside. let inside = eye[0] >= lo.x - && eye[0] <= hi.x + && eye[0] < hi.x && eye[1] >= lo.y - && eye[1] <= hi.y + && eye[1] < hi.y && eye[2] >= lo.z - && eye[2] <= hi.z; + && eye[2] < hi.z; if inside { m.extra.ints[STUCK] += 1; m.extra.ints[STUCK] > 4 @@ -306,39 +337,6 @@ pub fn player_is_stuck(m: &mut Mob, eye: Option<[f64; 3]>) -> bool { false } } -/// The nearest attackable player the creaking can see. -fn sees_attackable_player(m: &mut Mob, cx: &mut Cx) -> bool { - let Some(p) = &cx.w.player else { - return false; - }; - let near = m.distance_sqr(p.position) < m.attrs.follow_range.powi(2); - p.alive && !p.creative && near && m.sees(cx.w, Who::Player) -} -/// `StartAttacking` / `StopAttackingIfTargetInvalid`: while awake, hunt the -/// nearest visible player. -#[derive(Clone, Debug)] -struct HuntPlayer; -impl Goal for HuntPlayer { - goal_clone!(); - fn flags(&self) -> u8 { - TARGET - } - fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - if !is_active(m) || !sees_attackable_player(m, cx) { - return false; - } - m.ai.target = Some(Who::Player); - true - } - fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - is_active(m) && m.ai.target == Some(Who::Player) && sees_attackable_player(m, cx) - } - fn stop(&mut self, m: &mut Mob, _: &mut Cx) { - if m.ai.target == Some(Who::Player) { - m.ai.target = None; - } - } -} /// `CreakingModel.setupAnim`. pub fn anim(m: &Mob, s: &State, p: &mut Poses, animations: &HashMap) { p.xrot("head", s.x_rot.to_radians()); diff --git a/crates/horizon-client/src/mobs/creaking_heart.rs b/crates/horizon-client/src/mobs/creaking_heart.rs new file mode 100644 index 000000000..038e24515 --- /dev/null +++ b/crates/horizon-client/src/mobs/creaking_heart.rs @@ -0,0 +1,603 @@ +//! The creaking heart's block entity (`CreakingHeartBlockEntity`): at night +//! an awake heart in a pale oak trunk spawns a creaking that protects it +//! (`SpawnUtil.trySpawnMob`), lets it go by day, when it strays or when a +//! player is stuck in it, and when that creaking is hurt by a player emits +//! trails and spreads resin over the logs. The game and the mob AI probe +//! both tick hearts through this module; the host applies the block changes +//! and plays what it reports. +use super::{Mob, MobEvent, MobType, MobWorld, creaking}; +use crate::{collisions::SceneCollisions, containers::CreakingHeart}; +use horizon_core::{ + geometry::{Aabb, Vec3}, + random::{LegacyRandom, RandomSource}, +}; +use horizon_world::registry::BlockStateId; +use std::sync::Arc; + +/// `Creaking.CREAKING_ORANGE` and `CREAKING_GRAY`. +pub const ORANGE: u32 = 16_545_810; +pub const GRAY: u32 = 6_250_335; +/// `CreakingHeartBlockEntity.DISTANCE_CREAKING_TOO_FAR`. +const TOO_FAR: f64 = 34.0; +/// `Direction.values()`: down, up, north, south, west, east. +const DIRECTIONS: [[i32; 3]; 6] = [ + [0, -1, 0], + [0, 1, 0], + [0, 0, -1], + [0, 0, 1], + [-1, 0, 0], + [1, 0, 0], +]; +const FACE_NAMES: [&str; 6] = ["down", "up", "north", "south", "west", "east"]; + +/// What a heart's tick did, for its host to apply. +#[derive(Clone, Debug)] +pub enum HeartEvent { + /// `Level.setBlockAndUpdate`. + SetBlock([i32; 3], BlockStateId), + /// `Level.playSound(null, ...)`: heard by everyone. + Sound(&'static str, [f64; 3], f32, f32), + /// A `TrailParticleOption` sent from `at` towards `target`. + Trail { + at: [f64; 3], + target: [f64; 3], + color: u32, + duration: i32, + }, + /// `updateNeighbourForOutputSignal`: comparators read the new signal. + OutputChanged([i32; 3]), + /// A mob's own sounds and effects (the spawned creaking's voice, a + /// creaking falling apart). + Mob(MobEvent), +} + +/// The mobs a heart sees and the creakings it spawns. +pub trait HeartHost { + fn mob(&self, id: u32) -> Option<&Mob>; + fn mob_mut(&mut self, id: u32) -> Option<&mut Mob>; + /// The loaded mob with this UUID. + fn mob_for_uuid(&self, uuid: [i32; 4]) -> Option; + fn uuid_for(&mut self, id: u32) -> [i32; 4]; + /// The creaking's entity type. + fn creaking_type(&self) -> Option>; + /// A new mob of the type (the next entity id, its random seeded). + fn create_mob(&mut self, kind: Arc, at: Vec3) -> Mob; + /// `Level.addFreshEntity`. + fn add_mob(&mut self, m: Mob); + /// `ServerLevel.isSpawningMonsters` (rules and difficulty). + fn spawning_monsters(&self) -> bool; +} + +/// Block reads during a tick see the tick's own changes. +struct Blocks<'a, 'w> { + w: &'a MobWorld<'w>, + changed: Vec<([i32; 3], BlockStateId)>, +} +impl Blocks<'_, '_> { + fn get(&self, p: [i32; 3]) -> BlockStateId { + self.changed + .iter() + .rev() + .find(|(q, _)| *q == p) + .map_or_else(|| self.w.world.block(p[0], p[1], p[2]), |(_, s)| *s) + } + fn set(&mut self, p: [i32; 3], s: BlockStateId, out: &mut Vec) { + self.changed.push((p, s)); + out.push(HeartEvent::SetBlock(p, s)); + } + fn name(&self, s: BlockStateId) -> &str { + &self.w.facts.get(s).name + } + fn prop(&self, s: BlockStateId, key: &str) -> Option { + self.w + .registry + .state(s) + .and_then(|st| st.properties.get(key).cloned()) + } + fn with_prop(&self, s: BlockStateId, key: &str, value: &str) -> Option { + let mut st = self.w.registry.state(s)?.clone(); + st.properties.insert(key.to_owned(), value.to_owned()); + self.w.registry.resolve(&st).ok() + } + fn is_pale_oak_log(&self, p: [i32; 3]) -> bool { + let s = self.get(p); + self.w.has_tag("minecraft:pale_oak_logs", self.name(s)) + } +} + +/// `EnvironmentAttributes.CREAKING_ACTIVE`: the overworld's night, from +/// 12600 to 23400. +pub fn creaking_active(w: &MobWorld) -> bool { + !w.nether && !w.end && (12600..23401).contains(&w.day_time.rem_euclid(24000)) +} +/// `CreakingHeartBlock.hasRequiredLogs`: pale oak logs on both ends of the +/// heart's axis, along the same axis. +fn has_required_logs(b: &Blocks, state: BlockStateId, pos: [i32; 3]) -> bool { + let axis = b.prop(state, "axis").unwrap_or_else(|| "y".into()); + let dirs: [usize; 2] = match axis.as_str() { + "x" => [4, 5], + "z" => [2, 3], + _ => [0, 1], + }; + dirs.iter().all(|&d| { + let n = [ + pos[0] + DIRECTIONS[d][0], + pos[1] + DIRECTIONS[d][1], + pos[2] + DIRECTIONS[d][2], + ]; + let s = b.get(n); + b.w.has_tag("minecraft:pale_oak_logs", b.name(s)) + && b.prop(s, "axis").as_deref() == Some(axis.as_str()) + }) +} + +/// `getCreakingProtector`: the protector's entity, resolving a UUID read +/// from a save (forgotten 30 ticks after the heart came back unresolved). +pub fn protector(heart: &mut CreakingHeart, host: &impl HeartHost) -> Option { + let (id, uuid) = heart.creaking?; + if let Some(id) = id { + if host.mob(id).is_some_and(|m| !m.removed) { + return Some(id); + } + // setCreakingInfo(uuid) + heart.creaking = Some((None, uuid)); + heart.ticks_existed = 0; + } + if let Some(id) = host.mob_for_uuid(uuid) { + heart.creaking = Some((Some(id), uuid)); + return Some(id); + } + if heart.ticks_existed >= 30 { + heart.creaking = None; + } + None +} +/// `isProtector`. +pub fn is_protector(heart: &mut CreakingHeart, host: &impl HeartHost, id: u32) -> bool { + protector(heart, host) == Some(id) +} +fn distance_to_creaking(heart: &mut CreakingHeart, pos: [i32; 3], host: &impl HeartHost) -> f64 { + protector(heart, host) + .and_then(|id| host.mob(id)) + .map_or(0.0, |m| { + let at = Vec3::new( + f64::from(pos[0]) + 0.5, + f64::from(pos[1]), + f64::from(pos[2]) + 0.5, + ); + m.distance_sqr(at).sqrt() + }) +} +/// `computeAnalogOutputSignal`. +fn output_signal(heart: &mut CreakingHeart, pos: [i32; 3], host: &impl HeartHost) -> i32 { + if heart.creaking.is_none() || protector(heart, host).is_none() { + return 0; + } + let scaled = distance_to_creaking(heart, pos, host).clamp(0.0, 32.0) / 32.0; + 15 - (scaled * 15.0).floor() as i32 +} +/// `removeProtector`: the creaking falls apart (`tearDown`), or with a +/// damage source (`by_player`) twitches to death. +pub fn remove_protector( + heart: &mut CreakingHeart, + host: &mut impl HeartHost, + by_player: bool, + out: &mut Vec, +) { + let Some(id) = protector(heart, host) else { + return; + }; + if let Some(m) = host.mob_mut(id) { + let mut events = Vec::new(); + if by_player { + // creakingDeathEffects, setTearingDown, setHealth(0). + creaking::set_tearing_down(m); + m.health = 0.0; + m.voice("entity.creaking.twitch", &mut events); + } else { + creaking::tear_down(m, &mut events); + } + out.extend(events.into_iter().map(HeartEvent::Mob)); + } + heart.creaking = None; +} +/// `emitParticles`: trails between the protector and the heart. +fn emit_particles( + heart: &mut CreakingHeart, + pos: [i32; 3], + count: i32, + towards: bool, + lr: &mut LegacyRandom, + host: &impl HeartHost, + out: &mut Vec, +) { + let Some(b) = protector(heart, host) + .and_then(|id| host.mob(id)) + .map(Mob::bounds) + else { + return; + }; + let (lo, hi) = (b.min_position(), b.max_position()); + for _ in 0..count { + let mut source = [ + lo.x + lr.next_double() * (hi.x - lo.x), + lo.y + lr.next_double() * (hi.y - lo.y), + lo.z + lr.next_double() * (hi.z - lo.z), + ]; + let mut destination = [ + f64::from(pos[0]) + lr.next_double(), + f64::from(pos[1]) + lr.next_double(), + f64::from(pos[2]) + lr.next_double(), + ]; + if towards { + std::mem::swap(&mut source, &mut destination); + } + let duration = lr.next_int_bound(40).unwrap_or(0) + 10; + out.push(HeartEvent::Trail { + at: source, + target: destination, + color: if towards { ORANGE } else { GRAY }, + duration, + }); + } +} +/// `Util.shuffledCopy(Direction.values(), random)`. +fn shuffled_directions(lr: &mut LegacyRandom) -> [usize; 6] { + let mut order = [0, 1, 2, 3, 4, 5]; + for i in (2..=6).rev() { + let j = lr.next_int_bound(i as i32).unwrap_or(0) as usize; + order.swap(i - 1, j); + } + order +} +fn offset(p: [i32; 3], d: usize) -> [i32; 3] { + [ + p[0] + DIRECTIONS[d][0], + p[1] + DIRECTIONS[d][1], + p[2] + DIRECTIONS[d][2], + ] +} +/// `spreadResin`: a resin clump on the first log face found within two steps +/// of pale oak logs (`BlockPos.breadthFirstTraversal(pos, 2, 64, ...)`). +fn spread_resin( + b: &mut Blocks, + pos: [i32; 3], + lr: &mut LegacyRandom, + out: &mut Vec, +) -> Option<[i32; 3]> { + let mut visited: Vec<[i32; 3]> = Vec::new(); + let mut queue: std::collections::VecDeque<([i32; 3], i32)> = Default::default(); + queue.push_back((pos, 0)); + let mut count = 0; + while let Some((current, depth)) = queue.pop_front() { + if visited.contains(¤t) { + continue; + } + visited.push(current); + // The node visitor. + if b.is_pale_oak_log(current) { + for d in shuffled_directions(lr) { + let n = offset(current, d); + let mut neighbour = b.get(n); + let opposite = d ^ 1; + let facts = b.w.facts.get(neighbour); + if b.w.facts.is_air(neighbour) { + neighbour = b.w.registry.default_state("minecraft:resin_clump")?; + } else if &*facts.name == "minecraft:water" + && facts.fluid_level == 8 + && !facts.fluid_falling + { + let clump = b.w.registry.default_state("minecraft:resin_clump")?; + neighbour = b.with_prop(clump, "waterlogged", "true")?; + } + if b.name(neighbour) == "minecraft:resin_clump" + && b.prop(neighbour, FACE_NAMES[opposite]).as_deref() != Some("true") + { + let placed = b.with_prop(neighbour, FACE_NAMES[opposite], "true")?; + b.set(n, placed, out); + return Some(n); + } + } + } + count += 1; + if count >= 64 { + return None; + } + if depth < 2 { + // The neighbour provider: adjacent pale oak logs. + for d in shuffled_directions(lr) { + let n = offset(current, d); + if b.is_pale_oak_log(n) { + queue.push_back((n, depth + 1)); + } + } + } + } + None +} +/// `creakingHurt`: a player hurt the protector. +pub fn creaking_hurt( + heart: &mut CreakingHeart, + pos: [i32; 3], + w: &MobWorld, + lr: &mut LegacyRandom, + host: &mut impl HeartHost, + out: &mut Vec, +) { + let Some(id) = protector(heart, host) else { + return; + }; + if heart.emitter > 0 { + return; + } + emit_particles(heart, pos, 20, false, lr, host, out); + let mut b = Blocks { + w, + changed: Vec::new(), + }; + let state = b.get(pos); + if b.prop(state, "creaking_heart_state").as_deref() == Some("awake") { + let clumps = lr.next_int_between_inclusive(2, 3).unwrap_or(2); + for _ in 0..clumps { + if let Some(at) = spread_resin(&mut b, pos, lr, out) { + out.push(HeartEvent::Sound("block.resin.place", centre(at), 1.0, 1.0)); + } + } + } + heart.emitter = 100; + heart.emitter_target = host.mob(id).map(Mob::center); +} +fn centre(p: [i32; 3]) -> [f64; 3] { + [ + f64::from(p[0]) + 0.5, + f64::from(p[1]) + 0.5, + f64::from(p[2]) + 0.5, + ] +} + +/// `SpawnUtil.Strategy.ON_TOP_OF_COLLIDER_NO_LEAVES`. +fn can_spawn_on(b: &Blocks, pos: [i32; 3], state: BlockStateId, above: BlockStateId) -> bool { + let mut scene = SceneCollisions { + world: b.w.world, + binding: b.w.collision, + }; + let above_pos = [pos[0], pos[1] + 1, pos[2]]; + let above_empty = + b.w.collision + .collision_shape(&mut scene, above, above_pos) + .is_ok_and(|s| s.is_empty()); + above_empty + && !b.w.has_tag("minecraft:leaves", b.name(state)) + && b.w.facts.get(state).sturdy_full & (1 << 1) != 0 +} +/// `SpawnUtil.trySpawnMob(CREAKING, SPAWNER, level, pos, 5, 16, 8, +/// ON_TOP_OF_COLLIDER_NO_LEAVES, true)` and `spawnProtector`. +fn spawn_protector( + pos: [i32; 3], + w: &MobWorld, + lr: &mut LegacyRandom, + host: &mut impl HeartHost, + out: &mut Vec, +) -> Option { + let kind = host.creaking_type()?; + let b = Blocks { + w, + changed: Vec::new(), + }; + for _ in 0..5 { + let dx = lr.next_int_between_inclusive(-16, 16).unwrap_or(0); + let dz = lr.next_int_between_inclusive(-16, 16).unwrap_or(0); + let mut at = [pos[0] + dx, pos[1] + 8, pos[2] + dz]; + if !w.world.loaded(at[0], at[2]) { + continue; + } + // moveToPossibleSpawnPosition + let mut above = b.get(at); + let mut found = false; + for _ in (-8..=8).rev() { + at[1] -= 1; + let current = b.get(at); + if can_spawn_on(&b, at, current, above) { + at[1] += 1; + found = true; + break; + } + above = current; + } + if !found { + continue; + } + // noCollision(getSpawnAABB) + let half = f64::from(kind.width as f32 / 2.0); + let height = f64::from(kind.height as f32); + let (x, y, z) = ( + f64::from(at[0]) + 0.5, + f64::from(at[1]), + f64::from(at[2]) + 0.5, + ); + let bounds = Aabb::new( + Vec3::new(x - half, y, z - half), + Vec3::new(x + half, y + height, z + half), + ); + let mut scene = SceneCollisions { + world: w.world, + binding: w.collision, + }; + if !scene.unobstructed(bounds).unwrap_or(false) { + continue; + } + // EntityType.create: a random yaw, then Mob.finalizeSpawn. + let mut m = host.create_mob(kind.clone(), Vec3::new(x, y, z)); + let yaw = wrap_degrees(lr.next_float() * 360.0); + m.yaw = yaw; + m.previous_yaw = yaw; + m.head_yaw = yaw; + m.body_yaw = yaw; + finalize_spawn(&mut m, lr); + // Mob.checkSpawnRules (always true for a creaking) and + // checkSpawnObstruction (no liquid in the box). + if liquid_in(w, m.bounds()) { + continue; + } + let id = m.id; + // SpawnUtil: addFreshEntityWithPassengers, then playAmbientSound. + let mut events = Vec::new(); + if !creaking::is_active(&m) { + m.voice("entity.creaking.ambient", &mut events); + } + creaking::set_transient(&mut m, pos); + // spawnProtector's caller: the creaking's spawn sound. + m.voice("entity.creaking.spawn", &mut events); + host.add_mob(m); + out.extend(events.into_iter().map(HeartEvent::Mob)); + out.push(HeartEvent::Sound( + "block.creaking_heart.spawn", + centre(pos), + 1.0, + 1.0, + )); + return Some(id); + } + None +} +/// `Mob.finalizeSpawn`: the follow range's random spawn bonus and the +/// handedness, from the level random. +pub fn finalize_spawn(m: &mut Mob, lr: &mut LegacyRandom) { + let bonus = lr.triangle(0.0, 0.114_850_000_000_000_01); + // ADD_MULTIPLIED_BASE on the base value. + m.attrs.follow_range += m.kind.follow_range * bonus; + let _left_handed = lr.next_float() < 0.05; +} +fn wrap_degrees(angle: f32) -> f32 { + let mut w = angle % 360.0; + if w >= 180.0 { + w -= 360.0; + } + if w < -180.0 { + w += 360.0; + } + w +} +fn liquid_in(w: &MobWorld, b: Aabb) -> bool { + let (lo, hi) = (b.min_position(), b.max_position()); + for x in lo.x.floor() as i32..=(hi.x.ceil() as i32 - 1) { + for y in lo.y.floor() as i32..=(hi.y.ceil() as i32 - 1) { + for z in lo.z.floor() as i32..=(hi.z.ceil() as i32 - 1) { + if w.fluid(x, y, z) != crate::blocks::Fluid::None { + return true; + } + } + } + } + false +} + +/// `CreakingHeartBlockEntity.serverTick` (hearts that are not uprooted). +pub fn server_tick( + heart: &mut CreakingHeart, + pos: [i32; 3], + w: &MobWorld, + lr: &mut LegacyRandom, + host: &mut impl HeartHost, + out: &mut Vec, +) { + heart.ticks_existed += 1; + let signal = output_signal(heart, pos, host); + if heart.output_signal != signal { + heart.output_signal = signal; + out.push(HeartEvent::OutputChanged(pos)); + } + if heart.emitter > 0 { + if heart.emitter > 50 { + emit_particles(heart, pos, 1, true, lr, host, out); + emit_particles(heart, pos, 1, false, lr, host, out); + } + if heart.emitter % 10 == 0 && heart.emitter_target.is_some() { + if let Some(m) = protector(heart, host).and_then(|id| host.mob(id)) { + heart.emitter_target = Some(m.center()); + } + if let Some(target) = heart.emitter_target { + let c = centre(pos); + let progress = 0.2 + 0.8 * f64::from(100 - heart.emitter) / 100.0; + let sound = [ + (c[0] - target[0]) * progress + target[0], + (c[1] - target[1]) * progress + target[1], + (c[2] - target[2]) * progress + target[2], + ]; + // playSound(null, BlockPos.containing(soundLocation), ...) + let at = centre([ + sound[0].floor() as i32, + sound[1].floor() as i32, + sound[2].floor() as i32, + ]); + let volume = heart.emitter as f32 / 2.0 / 100.0 + 0.5; + out.push(HeartEvent::Sound( + "block.creaking_heart.hurt", + at, + volume, + 1.0, + )); + } + } + heart.emitter -= 1; + } + let ticker = heart.ticker; + heart.ticker -= 1; + if ticker >= 0 { + return; + } + heart.ticker = lr.next_int_bound(5).unwrap_or(0) + 20; + let mut b = Blocks { + w, + changed: Vec::new(), + }; + let state = b.get(pos); + // updateCreakingState + let active = creaking_active(w); + let wanted = if !has_required_logs(&b, state, pos) && heart.creaking.is_none() { + "uprooted" + } else if active { + "awake" + } else { + "dormant" + }; + let mut updated = state; + if b.prop(state, "creaking_heart_state").as_deref() != Some(wanted) + && let Some(next) = b.with_prop(state, "creaking_heart_state", wanted) + { + updated = next; + b.set(pos, next, out); + if wanted == "uprooted" { + return; + } + } + if heart.creaking.is_none() { + let awake = b.prop(updated, "creaking_heart_state").as_deref() == Some("awake"); + if awake && host.spawning_monsters() { + // getNearestPlayer(pos, 32, false): no spectators. + let (x, y, z) = (f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])); + let near = w.player.as_ref().is_some_and(|p| { + !p.spectator + && (p.position.x - x).powi(2) + + (p.position.y - y).powi(2) + + (p.position.z - z).powi(2) + < 32.0 * 32.0 + }); + if near && let Some(id) = spawn_protector(pos, w, lr, host, out) { + let uuid = host.uuid_for(id); + heart.creaking = Some((Some(id), uuid)); + } + } + } else if let Some(id) = protector(heart, host) { + let persistent = host.mob(id).is_some_and(|m| m.persistent); + // playerIsStuckInYou reads the creaking's NEAREST_PLAYERS. + let stuck = host.mob_mut(id).is_some_and(|m| { + let listed = super::monster_brain::nearest_players(m).contains(&super::Who::Player); + let eye = w.player.as_ref().filter(|_| listed).map(|p| p.eye); + creaking::player_is_stuck(m, eye) + }); + if !active && !persistent || distance_to_creaking(heart, pos, host) > TOO_FAR || stuck { + remove_protector(heart, host, false, out); + } + } +} diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index dbca6ba0a..c770f16df 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -249,13 +249,12 @@ impl Mob { let x_hit = differs(wanted.x, moved.x); let z_hit = differs(wanted.z, moved.z); self.horizontal_collision = x_hit || z_hit; + // A server's mobs are authoritative (`isLocalInstanceAuthoritative`): + // the vertical flags update even without vertical movement. let moved_vertically = wanted.y.abs() > 0.0; - let mut vertical = false; - if moved_vertically { - vertical = wanted.y != moved.y; - self.vertical_collision_below = vertical && wanted.y < 0.0; - self.on_ground = self.vertical_collision_below; - } + let vertical = wanted.y != moved.y; + self.vertical_collision_below = vertical && wanted.y < 0.0; + self.on_ground = self.vertical_collision_below; // LivingEntity.checkFallDamage refreshes the fluid state out of water // (touching water resets the fall). if !self.fluids.in_water { @@ -359,6 +358,11 @@ impl Mob { ] } fn cause_fall_damage(&mut self, events: &mut Vec) { + // Breeze.causeFallDamage: a landing from higher than three blocks. + if self.species() == super::Species::Breeze && self.fall_distance > 3.0 { + let at = [self.position.x, self.position.y, self.position.z]; + events.push(MobEvent::Sound("entity.breeze.land", at, 1.0, 1.0)); + } if self.kind.flags.fall_immune { return; } @@ -391,7 +395,7 @@ impl Mob { 0.02 } /// Entity.getGravity: none while isNoGravity. - fn gravity(&self) -> f64 { + pub fn gravity(&self) -> f64 { if self.no_gravity { 0.0 } else { diff --git a/crates/horizon-client/src/mobs/monster_brain.rs b/crates/horizon-client/src/mobs/monster_brain.rs new file mode 100644 index 000000000..c770858a6 --- /dev/null +++ b/crates/horizon-client/src/mobs/monster_brain.rs @@ -0,0 +1,1663 @@ +//! The brains of the breeze (`Breeze.BRAIN_PROVIDER`, `BreezeAi`) and the +//! creaking (`Creaking.BRAIN_PROVIDER`, `CreakingAi`), ported behaviour for +//! behaviour on the villager brain's memories (`villager_brain::Slot`): +//! sensors with vanilla's scan delays, the core, idle and fight activities, +//! and their behaviours started and ticked in `Brain.tick`'s order +//! (priority, then the activity's slot in its hash map, then insertion). +//! +//! Behaviour durations, `DoNothing` and the creaking's look ticker draw from +//! the level random; positions, sounds and jumps from the mob's own random; +//! `RunOne` shuffles with a random of its own (`ShufflingList.random`), +//! seeded when the brain is built. +use super::{ + Mob, MobEvent, MobWorld, Species, Who, + goals::Cx, + path::Path, + villager_brain::{NEVER, Slot, Tracker, Visible, WalkTarget}, +}; +use crate::projectiles::{Projectile, ProjectileKind}; +use horizon_core::{ + geometry::{Vec3, trig}, + random::{LegacyRandom, RandomSource}, +}; + +/// `Activity` (the ones these brains use). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Act { + Core, + Idle, + Fight, +} +impl Act { + fn name(self) -> &'static str { + match self { + Act::Core => "core", + Act::Idle => "idle", + Act::Fight => "fight", + } + } +} + +/// The memories either brain registers. +#[derive(Clone, Debug, Default)] +pub struct Memories { + pub attack_target: Slot, + pub attack_cooling_down: Slot, + pub cant_reach_walk_target_since: Slot, + /// `HURT_BY`: the damage (its game time). + pub hurt_by: Slot, + pub hurt_by_entity: Slot, + pub look_target: Slot, + pub mobs: Slot>, + pub visible_mobs: Slot, + pub nearest_attackable: Slot, + pub nearest_players: Slot>, + pub nearest_visible_player: Slot, + pub nearest_visible_targetable_player: Slot, + pub nearest_visible_targetable_players: Slot>, + pub path: Slot, + pub walk_target: Slot, + pub breeze_shoot: Slot<()>, + pub breeze_shoot_charging: Slot<()>, + pub breeze_shoot_recovering: Slot<()>, + pub breeze_shoot_cooldown: Slot<()>, + pub breeze_jump_cooldown: Slot<()>, + pub breeze_jump_inhaling: Slot<()>, + pub breeze_jump_target: Slot<[i32; 3]>, + pub breeze_leaving_water: Slot<()>, +} +impl Memories { + /// `Brain.forgetOutdatedMemories`. + fn tick(&mut self) { + self.attack_target.tick(); + self.attack_cooling_down.tick(); + self.cant_reach_walk_target_since.tick(); + self.hurt_by.tick(); + self.hurt_by_entity.tick(); + self.look_target.tick(); + self.mobs.tick(); + self.visible_mobs.tick(); + self.nearest_attackable.tick(); + self.nearest_players.tick(); + self.nearest_visible_player.tick(); + self.nearest_visible_targetable_player.tick(); + self.nearest_visible_targetable_players.tick(); + self.path.tick(); + self.walk_target.tick(); + self.breeze_shoot.tick(); + self.breeze_shoot_charging.tick(); + self.breeze_shoot_recovering.tick(); + self.breeze_shoot_cooldown.tick(); + self.breeze_jump_cooldown.tick(); + self.breeze_jump_inhaling.tick(); + self.breeze_jump_target.tick(); + self.breeze_leaving_water.tick(); + } +} + +/// The sensors, in `BRAIN_PROVIDER` order (all scan every 20 ticks). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Sensor { + NearestLiving, + HurtBy, + NearestPlayers, + BreezeAttack, +} + +/// A breeze's or creaking's brain. +#[derive(Clone, Debug)] +pub struct Brain { + pub mem: Memories, + sensors: Vec<(Sensor, i64)>, + /// The active non-core activity (`CORE` is always active). + pub activity: Act, + default_activity: Act, + list: Vec, +} +#[derive(Clone, Debug)] +struct Entry { + act: Act, + b: B, +} + +fn brain(m: &Mob) -> Option<&Brain> { + m.extra.brain.as_deref() +} +fn brain_mut(m: &mut Mob) -> &mut Brain { + m.extra.brain.as_deref_mut().expect("brain") +} +fn mem(m: &mut Mob) -> &mut Memories { + &mut brain_mut(m).mem +} +fn mem_ref(m: &Mob) -> &Memories { + &brain(m).expect("brain").mem +} +/// Whether the species thinks with this brain. +pub fn has_brain(s: Species) -> bool { + matches!(s, Species::Breeze | Species::Creaking) +} + +/// `Brain.Provider.makeBrain`: the sensors' first scans are delayed by draws +/// from the mob's random; `RunOne` shuffles with `shuffle_seed`. +pub fn init(m: &mut Mob, shuffle_seed: i64) { + let breeze = m.species() == Species::Breeze; + let kinds: &[Sensor] = if breeze { + &[ + Sensor::NearestLiving, + Sensor::HurtBy, + Sensor::NearestPlayers, + Sensor::BreezeAttack, + ] + } else { + &[Sensor::NearestLiving, Sensor::NearestPlayers] + }; + let sensors = kinds + .iter() + .map(|&k| (k, i64::from(m.random.next_int_bound(20).unwrap_or(0)))) + .collect(); + let (list, default_activity) = if breeze { + (breeze_packages(shuffle_seed), Act::Fight) + } else { + (creaking_packages(shuffle_seed), Act::Idle) + }; + m.extra.brain = Some(Box::new(Brain { + mem: Memories::default(), + sensors, + activity: default_activity, + default_activity, + list, + })); +} + +/// What behaviours read and emit during a brain tick. +struct Bx<'a, 'w> { + w: &'a MobWorld<'w>, + lr: &'a mut LegacyRandom, + events: &'a mut Vec, + now: i64, +} + +/// `Brain.tick`, then the species' `updateActivity` +/// (`Breeze.customServerAiStep`, `Creaking.customServerAiStep`). +pub fn tick(m: &mut Mob, w: &MobWorld, lr: &mut LegacyRandom, events: &mut Vec) { + if brain(m).is_none() { + let seed = i64::from(m.id); + init(m, seed); + } + mem(m).tick(); + tick_sensors(m, w); + let mut list = std::mem::take(&mut brain_mut(m).list); + let mut cx = Bx { + w, + lr, + events, + now: w.game_time, + }; + for e in list.iter_mut() { + let active = e.act == Act::Core || e.act == brain_mut(m).activity; + if active && !e.b.running() { + e.b.try_start(m, &mut cx); + } + } + for e in list.iter_mut() { + if e.b.running() { + e.b.tick_or_stop(m, &mut cx); + } + } + brain_mut(m).list = list; + update_activity(m); + sync_target(m); +} +/// `BreezeAi.updateActivity` and `CreakingAi.updateActivity`. +fn update_activity(m: &mut Mob) { + let frozen = m.species() == Species::Creaking && !super::creaking::can_move(m); + let b = brain_mut(m); + if frozen { + // useDefaultActivity + b.activity = b.default_activity; + return; + } + if fight_requirements(b) { + b.activity = Act::Fight; + } else { + b.activity = Act::Idle; + } +} +fn fight_requirements(b: &Brain) -> bool { + b.mem.attack_target.present() + && (b.default_activity != Act::Fight || !b.mem.walk_target.present()) +} +/// `Mob.getTarget` is `getTargetFromBrain` for both species. +fn sync_target(m: &mut Mob) { + m.ai.target = mem_ref(m).attack_target.value(); +} +/// Sets or erases the attack target (and the mob's view of it). +pub fn set_attack_target(m: &mut Mob, who: Option) { + if brain(m).is_none() { + let seed = i64::from(m.id); + init(m, seed); + } + mem(m).attack_target.set_opt(who); + m.ai.target = who; +} +/// The attack target the brain remembers. +pub fn attack_target(m: &Mob) -> Option { + brain(m).and_then(|b| b.mem.attack_target.value()) +} +/// `NEAREST_PLAYERS`. +pub fn nearest_players(m: &Mob) -> Vec { + brain(m) + .and_then(|b| b.mem.nearest_players.value()) + .unwrap_or_default() +} +/// The damage the brain remembers (`HURT_BY`). +pub fn hurt_by_present(m: &Mob) -> bool { + brain(m).is_some_and(|b| b.mem.hurt_by.present()) +} +/// `HURT_BY`'s damage source entity, if a living one. +fn hurt_by_entity(m: &Mob, w: &MobWorld) -> Option { + let t = brain(m)?.mem.hurt_by.value()?; + let (d, at) = m.last_damage?; + if at != t { + return None; + } + let who = d.attacker?; + w.target_info(who).map(|_| who) +} + +// ---- Sensors ------------------------------------------------------------ + +fn tick_sensors(m: &mut Mob, w: &MobWorld) { + for i in 0..brain_mut(m).sensors.len() { + let (kind, fire) = { + let s = &mut brain_mut(m).sensors[i]; + s.1 -= 1; + if s.1 <= 0 { + s.1 = 20; + (s.0, true) + } else { + (s.0, false) + } + }; + if !fire { + continue; + } + match kind { + Sensor::NearestLiving => sense_living(m, w), + Sensor::HurtBy => sense_hurt(m, w), + Sensor::NearestPlayers => sense_players(m, w), + Sensor::BreezeAttack => { + sense_living(m, w); + sense_breeze_attack(m, w); + } + } + } +} +/// `NearestLivingEntitySensor`: everything alive within the follow range, +/// nearest first. +fn sense_living(m: &mut Mob, w: &MobWorld) { + let r = m.attrs.follow_range; + let area = m.bounds().inflate(Vec3::new(r, r, r)); + let mut found: Vec<(Who, f64)> = Vec::new(); + for o in w.others { + if o.id != m.id && o.alive && o.bounds.intersects(area) { + found.push((Who::Mob(o.id), m.distance_sqr(o.position))); + } + } + if let Some(p) = &w.player + && p.alive + && p.bounds.intersects(area) + { + found.push((Who::Player, m.distance_sqr(p.position))); + } + found.sort_by(|a, b| a.1.total_cmp(&b.1)); + let list: Vec = found.into_iter().map(|(w, _)| w).collect(); + let mm = mem(m); + mm.mobs.set_list(list.clone()); + mm.visible_mobs.set(Visible { + list, + cache: Vec::new(), + }); +} +/// `HurtBySensor`: the last damage (forgotten 40 ticks after) and who did it. +fn sense_hurt(m: &mut Mob, w: &MobWorld) { + let age = i64::from(m.age); + let last = m + .last_damage + .as_ref() + .filter(|(_, t)| age - t <= 40) + .map(|(d, t)| (d.attacker, *t)); + let mm = mem(m); + if let Some((by, t)) = last { + mm.hurt_by.set(t); + if let Some(by) = by { + mm.hurt_by_entity.set(by); + } + } else { + mm.hurt_by.clear(); + } + if let Some(who) = mm.hurt_by_entity.value() + && !w.target_info(who).is_some_and(|t| t.alive) + { + mm.hurt_by_entity.clear(); + } +} +/// `Sensor.isEntityTargetable`: `TargetingConditions.forNonCombat()` within +/// the follow range, in sight. +fn targetable(m: &mut Mob, w: &MobWorld, who: Who) -> bool { + let range = m.attrs.follow_range; + match who { + Who::Player => m.can_see_player(w, range), + Who::Mob(id) => { + let Some(s) = w.seen(id) else { return false }; + s.alive && m.distance_sqr(s.position) <= range * range && m.sees(w, who) + } + } +} +/// `LivingEntity.canAttack` with the species' own rule (`Breeze.canAttack`: +/// players and iron golems only). +fn can_attack(m: &Mob, w: &MobWorld, who: Who) -> bool { + match who { + Who::Player => w + .player + .as_ref() + .is_some_and(|p| p.alive && !p.creative && !p.spectator), + Who::Mob(id) => { + let Some(s) = w.seen(id) else { return false }; + s.alive && (m.species() != Species::Breeze || s.species == Species::IronGolem) + } + } +} +/// `Sensor.isEntityAttackable`: `TargetingConditions.forCombat()` within the +/// follow range, in sight. +fn attackable(m: &mut Mob, w: &MobWorld, who: Who) -> bool { + let range = m.attrs.follow_range; + if !can_attack(m, w, who) { + return false; + } + match who { + Who::Player => m.can_target_player(w, range, true), + Who::Mob(id) => { + let Some(s) = w.seen(id) else { return false }; + m.distance_sqr(s.position) <= range * range && m.sees(w, who) + } + } +} +/// The visible-entities memory's line-of-sight test, cached per memory. +fn visible_test(m: &mut Mob, w: &MobWorld, who: Who) -> bool { + match mem_ref(m).visible_mobs.get() { + Some(v) => { + if let Some(&(_, r)) = v.cache.iter().find(|(k, _)| *k == who) { + return r; + } + } + None => return false, + } + let r = targetable(m, w, who); + if let Some(v) = mem(m).visible_mobs.get_mut() { + v.cache.push((who, r)); + } + r +} +/// `NearestVisibleLivingEntities.findClosest`. +fn find_closest(m: &mut Mob, w: &MobWorld, filter: impl Fn(&Mob, Who) -> bool) -> Option { + let list = mem_ref(m).visible_mobs.get()?.list.clone(); + list.into_iter() + .find(|&who| filter(m, who) && visible_test(m, w, who)) +} +/// `NearestVisibleLivingEntities.contains(entity)`. +fn visible_contains(m: &mut Mob, w: &MobWorld, who: Who) -> bool { + let listed = mem_ref(m) + .visible_mobs + .get() + .is_some_and(|v| v.list.contains(&who)); + listed && visible_test(m, w, who) +} +/// `PlayerSensor`. +fn sense_players(m: &mut Mob, w: &MobWorld) { + let range = m.attrs.follow_range; + let near = w + .player + .as_ref() + .is_some_and(|p| !p.spectator && m.distance_sqr(p.position) < range * range); + let players: Vec = if near { vec![Who::Player] } else { vec![] }; + let visible: Vec = players + .iter() + .copied() + .filter(|&p| targetable(m, w, p)) + .collect(); + let attackable: Vec = visible + .iter() + .copied() + .filter(|&p| attackable(m, w, p)) + .collect(); + let mm = mem(m); + mm.nearest_players.set_list(players); + mm.nearest_visible_player.set_opt(visible.first().copied()); + mm.nearest_visible_targetable_players + .set_list(attackable.clone()); + mm.nearest_visible_targetable_player + .set_opt(attackable.first().copied()); +} +/// `BreezeAttackEntitySensor`: the nearest living entity (not a creative or +/// spectator player) it may attack. +fn sense_breeze_attack(m: &mut Mob, w: &MobWorld) { + let list = mem_ref(m).mobs.value().unwrap_or_default(); + let found = list.into_iter().find(|&who| { + let shown = match who { + Who::Player => w + .player + .as_ref() + .is_some_and(|p| !p.creative && !p.spectator), + Who::Mob(_) => true, + }; + shown && attackable(m, w, who) + }); + mem(m).nearest_attackable.set_opt(found); +} + +// ---- Behaviours --------------------------------------------------------- + +/// `Behavior`'s bookkeeping: running, and until when. +#[derive(Clone, Debug)] +struct Timed { + running: bool, + end: i64, + min: i32, + max: i32, +} +impl Timed { + fn new(min: i32, max: i32) -> Self { + Self { + running: false, + end: 0, + min, + max, + } + } + /// `Behavior.tryStart`'s duration draw from the level random. + fn begin(&mut self, cx: &mut Bx) { + self.running = true; + let d = self.min + cx.lr.next_int_bound(self.max + 1 - self.min).unwrap_or(0); + self.end = cx.now + i64::from(d); + } +} + +/// `StartAttacking`'s target finders. +#[derive(Clone, Copy, Debug)] +enum Finder { + /// The breeze's `NEAREST_ATTACKABLE`. + NearestAttackable, + /// The breeze's `HURT_BY` source, if living. + HurtBy, + /// The creaking's `NEAREST_VISIBLE_ATTACKABLE_PLAYER`, while active. + ActiveCreaking, +} + +/// The behaviours of both brains. +#[derive(Clone, Debug)] +enum B { + Swim { + t: Timed, + creaking: bool, + }, + LookAtTargetSink(Timed), + /// `MoveToTargetSink`, and the breeze's `SlideToTargetSink`. + MoveToTargetSink { + t: Timed, + cooldown: i32, + path: Option, + last_target: Option<[i32; 3]>, + speed: f32, + slide: bool, + }, + StartAttacking(bool, Finder), + /// `StopAttackingIfTargetInvalid`: the breeze's while the target was + /// attackable within the last 100 ticks (`positives_left`), the + /// creaking's while a visible attackable player. + StopAttacking { + running: bool, + breeze: bool, + positives_left: i32, + }, + RunOne(Box), + DoNothing(Timed), + RandomStroll(bool, f32), + SetEntityLookTargetSometimes { + running: bool, + until_next: i32, + }, + SetWalkTargetFromLookTarget(bool), + SetWalkTargetFromAttackTarget(bool), + MeleeAttack(bool), + Shoot(Timed), + LongJump(Timed), + ShootWhenStuck(Timed), + Slide(Timed), +} + +/// `RunOne`: shuffled by weight, the first that starts runs. +#[derive(Clone, Debug)] +struct RunOne { + running: bool, + random: LegacyRandom, + kids: Vec<(B, i32, f64)>, +} +impl RunOne { + fn try_start(&mut self, m: &mut Mob, cx: &mut Bx) -> bool { + self.running = true; + // ShufflingList.shuffle: a fresh weight for each entry in the current + // order, then a stable sort. + for k in &mut self.kids { + let r = self.random.next_float(); + k.2 = -f64::from(r).powf(f64::from(1.0_f32 / k.1 as f32)); + } + self.kids.sort_by(|a, b| a.2.total_cmp(&b.2)); + for k in &mut self.kids { + if !k.0.running() && k.0.try_start(m, cx) { + break; + } + } + true + } + fn tick_or_stop(&mut self, m: &mut Mob, cx: &mut Bx) { + for k in &mut self.kids { + if k.0.running() { + k.0.tick_or_stop(m, cx); + } + } + if !self.kids.iter().any(|k| k.0.running()) { + self.do_stop(m, cx); + } + } + fn do_stop(&mut self, m: &mut Mob, cx: &mut Bx) { + self.running = false; + for k in &mut self.kids { + if k.0.running() { + k.0.do_stop(m, cx); + } + } + } +} + +impl B { + fn running(&self) -> bool { + match self { + B::Swim { t, .. } + | B::LookAtTargetSink(t) + | B::MoveToTargetSink { t, .. } + | B::DoNothing(t) + | B::Shoot(t) + | B::LongJump(t) + | B::ShootWhenStuck(t) + | B::Slide(t) => t.running, + B::StartAttacking(r, _) + | B::StopAttacking { running: r, .. } + | B::RandomStroll(r, _) + | B::SetEntityLookTargetSometimes { running: r, .. } + | B::SetWalkTargetFromLookTarget(r) + | B::SetWalkTargetFromAttackTarget(r) + | B::MeleeAttack(r) => *r, + B::RunOne(g) => g.running, + } + } + + fn try_start(&mut self, m: &mut Mob, cx: &mut Bx) -> bool { + match self { + B::RunOne(g) => g.try_start(m, cx), + B::Swim { t, creaking } => { + if *creaking && !super::creaking::can_move(m) || !swim_condition(m) { + return false; + } + t.begin(cx); + true + } + B::LookAtTargetSink(t) => { + if !mem(m).look_target.present() { + return false; + } + t.begin(cx); + true + } + B::MoveToTargetSink { + t, + cooldown, + path, + last_target, + speed, + slide, + } => { + let mm = mem(m); + if mm.path.present() || !mm.walk_target.present() { + return false; + } + // checkExtraStartConditions + if *cooldown > 0 { + *cooldown -= 1; + return false; + } + let walk = mm.walk_target.value().unwrap(); + let reached = reached(m, cx.w, &walk); + if !reached && compute_path(m, cx, &walk, path, speed) { + *last_target = walk.target.block(cx.w); + t.begin(cx); + // start + mem(m).path.set_opt(path.clone()); + m.nav_move_to_path(path.clone(), f64::from(*speed)); + if *slide { + // SlideToTargetSink.start + let at = m.center(); + cx.events + .push(MobEvent::Sound("entity.breeze.slide", at, 1.0, 1.0)); + super::breeze::set_pose(m, super::breeze::SLIDING); + } + return true; + } + let mm = mem(m); + mm.walk_target.clear(); + if reached { + mm.cant_reach_walk_target_since.clear(); + } + false + } + B::StartAttacking(running, finder) => { + if mem(m).attack_target.present() { + return false; + } + let target = match finder { + Finder::NearestAttackable => mem(m).nearest_attackable.value(), + Finder::HurtBy => hurt_by_entity(m, cx.w), + Finder::ActiveCreaking => { + if !super::creaking::is_active(m) { + return false; + } + mem(m).nearest_visible_targetable_player.value() + } + }; + let Some(target) = target else { return false }; + if !can_attack(m, cx.w, target) { + return false; + } + set_attack_target(m, Some(target)); + mem(m).cant_reach_walk_target_since.clear(); + *running = true; + true + } + B::StopAttacking { + running, + breeze, + positives_left, + } => { + let Some(target) = mem(m).attack_target.value() else { + return false; + }; + let alive = cx.w.target_info(target).is_some_and(|t| t.alive); + let tired = mem(m) + .cant_reach_walk_target_since + .value() + .is_some_and(|since| cx.now - since > 200); + let stop_when = if *breeze { + // Sensor.wasEntityAttackableLastNTicks(100).negate() + if attackable(m, cx.w, target) { + *positives_left = 100; + false + } else { + *positives_left -= 1; + *positives_left < 0 + } + } else { + // CreakingAi.isAttackTargetStillReachable + let reachable = target == Who::Player + && mem(m) + .nearest_visible_targetable_players + .get() + .is_some_and(|l| l.contains(&Who::Player)); + !reachable + }; + if !(can_attack(m, cx.w, target) && !tired && alive && !stop_when) { + set_attack_target(m, None); + } + *running = true; + true + } + B::DoNothing(t) => { + t.begin(cx); + true + } + B::RandomStroll(running, speed) => { + if mem(m).walk_target.present() { + return false; + } + let pos = m.land_random_pos(cx.w, 10, 7); + mem(m) + .walk_target + .set_opt(pos.map(|p| WalkTarget::point(p, *speed, 0))); + *running = true; + true + } + B::SetEntityLookTargetSometimes { + running, + until_next, + } => { + let mm = mem(m); + if mm.look_target.present() || !mm.visible_mobs.present() { + return false; + } + let w = cx.w; + let found = find_closest(m, w, |m, who| { + w.target_info(who) + .is_some_and(|t| t.position.distance_squared(m.position) <= 64.0) + }); + let Some(t) = found else { return false }; + // Ticker.tickDownAndCheck with UniformInt.of(30, 60). + if *until_next == 0 { + *until_next = 30 + cx.lr.next_int_bound(31).unwrap_or(0) - 1; + return false; + } + *until_next -= 1; + if *until_next != 0 { + return false; + } + mem(m).look_target.set(Tracker::Entity(t, true)); + *running = true; + true + } + B::SetWalkTargetFromLookTarget(running) => { + let mm = mem(m); + if mm.walk_target.present() { + return false; + } + let Some(look) = mm.look_target.value() else { + return false; + }; + mm.walk_target.set(WalkTarget { + target: look, + speed: 0.3, + close: 3, + }); + *running = true; + true + } + B::SetWalkTargetFromAttackTarget(running) => { + let Some(target) = mem(m).attack_target.value() else { + return false; + }; + let w = cx.w; + let seen = mem_ref(m).visible_mobs.present() && visible_contains(m, w, target); + if seen && within_attack_range(m, w, target) { + mem(m).walk_target.clear(); + } else { + let mm = mem(m); + mm.look_target.set(Tracker::Entity(target, true)); + mm.walk_target.set(WalkTarget { + target: Tracker::Entity(target, false), + speed: 1.0, + close: 0, + }); + } + *running = true; + true + } + B::MeleeAttack(running) => { + let mm = mem(m); + let Some(target) = mm.attack_target.value() else { + return false; + }; + if mm.attack_cooling_down.present() || !mm.visible_mobs.present() { + return false; + } + let w = cx.w; + let in_reach = w + .target_info(target) + .is_some_and(|t| m.within_melee_range(&t)); + if !super::creaking::can_move(m) || !in_reach || !visible_contains(m, w, target) { + return false; + } + mem(m).look_target.set(Tracker::Entity(target, true)); + m.swing(); + let mut gcx = Cx { + w, + events: cx.events, + }; + super::ai::do_hurt_target(m, target, &mut gcx); + mem(m).attack_cooling_down.set_ttl(true, 40); + *running = true; + true + } + B::Shoot(t) => { + let mm = mem(m); + if !mm.attack_target.present() + || mm.breeze_shoot_cooldown.present() + || mm.breeze_shoot_charging.present() + || mm.breeze_shoot_recovering.present() + || !mm.breeze_shoot.present() + || mm.walk_target.present() + || mm.breeze_jump_target.present() + { + return false; + } + // checkExtraStartConditions + if super::breeze::pose(m) != super::breeze::STANDING { + return false; + } + let Some(target) = mem(m).attack_target.value() else { + return false; + }; + let within = + cx.w.target_info(target) + .is_some_and(|t| m.position.distance_squared(t.position) < 256.0); + if !within { + mem(m).breeze_shoot.clear(); + return false; + } + t.begin(cx); + // start + super::breeze::set_pose(m, super::breeze::SHOOTING); + mem(m).breeze_shoot_charging.set_ttl((), 15); + breeze_sound(m, cx, "entity.breeze.inhale", 1.0); + true + } + B::LongJump(t) => { + let mm = mem(m); + if !mm.attack_target.present() + || mm.breeze_jump_cooldown.present() + || mm.breeze_shoot.present() + || mm.walk_target.present() + { + return false; + } + if !long_jump_can_run(m, cx) { + return false; + } + t.begin(cx); + // start + if !mem(m).breeze_jump_inhaling.present() { + mem(m).breeze_jump_inhaling.set_ttl((), 10); + } + super::breeze::set_pose(m, super::breeze::INHALING); + // level.playSound(null, breeze, BREEZE_CHARGE, HOSTILE, 1, 1) + let at = [m.position.x, m.position.y, m.position.z]; + cx.events + .push(MobEvent::Sound("entity.breeze.charge", at, 1.0, 1.0)); + if let Some(p) = mem(m).breeze_jump_target.value() { + look_at_eyes( + m, + [ + f64::from(p[0]) + 0.5, + f64::from(p[1]) + 0.5, + f64::from(p[2]) + 0.5, + ], + ); + } + true + } + B::ShootWhenStuck(t) => { + let mm = mem(m); + if !mm.attack_target.present() + || mm.breeze_jump_inhaling.present() + || mm.breeze_jump_target.present() + || mm.walk_target.present() + || mm.breeze_shoot.present() + { + return false; + } + let stuck = m.extra.mount.is_some() + || m.fluids.in_water + || m.has_effect("minecraft:levitation"); + if !stuck { + return false; + } + t.begin(cx); + mem(m).breeze_shoot.set_ttl((), 60); + true + } + B::Slide(t) => { + let mm = mem(m); + if !mm.attack_target.present() + || mm.walk_target.present() + || mm.breeze_jump_cooldown.present() + || mm.breeze_shoot.present() + { + return false; + } + if !m.on_ground + || m.fluids.in_water + || super::breeze::pose(m) != super::breeze::STANDING + { + return false; + } + t.begin(cx); + slide_start(m, cx); + true + } + } + } + + fn tick_or_stop(&mut self, m: &mut Mob, cx: &mut Bx) { + let now = cx.now; + match self { + B::RunOne(g) => g.tick_or_stop(m, cx), + // OneShots stop in the tick they started. + B::StartAttacking(r, _) + | B::StopAttacking { running: r, .. } + | B::RandomStroll(r, _) + | B::SetEntityLookTargetSometimes { running: r, .. } + | B::SetWalkTargetFromLookTarget(r) + | B::SetWalkTargetFromAttackTarget(r) + | B::MeleeAttack(r) => *r = false, + B::Swim { t, .. } => { + if now > t.end || !swim_condition(m) { + self.do_stop(m, cx); + } else if m.random.next_float() < 0.8 { + m.ai.jump = true; + } + } + B::LookAtTargetSink(t) => { + let visible = match mem(m).look_target.value() { + Some(look) => tracker_visible(m, cx.w, look), + None => false, + }; + if now > t.end || !visible { + self.do_stop(m, cx); + } else if let Some(at) = mem(m).look_target.value().and_then(|l| l.position(cx.w)) { + m.look_at(at); + } + } + B::MoveToTargetSink { + t, + path, + last_target, + speed, + .. + } => { + let still = path.is_some() + && last_target.is_some() + && mem(m) + .walk_target + .value() + .is_some_and(|walk| !m.ai.nav.is_done() && !reached(m, cx.w, &walk)); + if now > t.end || !still { + self.do_stop(m, cx); + return; + } + let new_path = m.ai.nav.path.clone(); + if !same_path(path.as_ref(), new_path.as_ref()) { + *path = new_path.clone(); + mem(m).path.set_opt(new_path.clone()); + } + if new_path.is_some() + && let Some(last) = *last_target + && let Some(walk) = mem(m).walk_target.value() + && let Some(now_target) = walk.target.block(cx.w) + { + let d = manhattan_sq(now_target, last); + if d > 4 && compute_path(m, cx, &walk, path, speed) { + *last_target = Some(now_target); + mem(m).path.set_opt(path.clone()); + m.nav_move_to_path(path.clone(), f64::from(*speed)); + } + } + } + B::DoNothing(t) => { + if now > t.end { + self.do_stop(m, cx); + } + } + B::Shoot(t) => { + let mm = mem(m); + if now > t.end || !mm.attack_target.present() || !mm.breeze_shoot.present() { + self.do_stop(m, cx); + return; + } + shoot_tick(m, cx); + } + B::LongJump(t) => { + let still = super::breeze::pose(m) != super::breeze::STANDING + && !mem(m).breeze_jump_cooldown.present(); + if now > t.end || !still { + self.do_stop(m, cx); + return; + } + long_jump_tick(m, cx); + } + // canStillUse is false: stops at once. + B::ShootWhenStuck(_) | B::Slide(_) => self.do_stop(m, cx), + } + } + + fn do_stop(&mut self, m: &mut Mob, cx: &mut Bx) { + match self { + B::RunOne(g) => g.do_stop(m, cx), + B::StartAttacking(r, _) + | B::StopAttacking { running: r, .. } + | B::RandomStroll(r, _) + | B::SetEntityLookTargetSometimes { running: r, .. } + | B::SetWalkTargetFromLookTarget(r) + | B::SetWalkTargetFromAttackTarget(r) + | B::MeleeAttack(r) => *r = false, + B::Swim { t, .. } | B::DoNothing(t) | B::ShootWhenStuck(t) | B::Slide(t) => { + t.running = false + } + B::LookAtTargetSink(t) => { + t.running = false; + mem(m).look_target.clear(); + } + B::MoveToTargetSink { + t, + cooldown, + path, + slide, + .. + } => { + t.running = false; + if let Some(walk) = mem(m).walk_target.value() + && !reached(m, cx.w, &walk) + && m.ai.nav.stuck + { + *cooldown = cx.lr.next_int_bound(40).unwrap_or(0); + } + m.nav_stop(); + let mm = mem(m); + mm.walk_target.clear(); + mm.path.clear(); + *path = None; + if *slide { + // SlideToTargetSink.stop + super::breeze::set_pose(m, super::breeze::STANDING); + if mem(m).attack_target.present() { + mem(m).breeze_shoot.set_ttl((), 60); + } + } + } + B::Shoot(t) => { + t.running = false; + if super::breeze::pose(m) == super::breeze::SHOOTING { + super::breeze::set_pose(m, super::breeze::STANDING); + } + let mm = mem(m); + mm.breeze_shoot_cooldown.set_ttl((), 10); + mm.breeze_shoot.clear(); + } + B::LongJump(t) => { + t.running = false; + let pose = super::breeze::pose(m); + if pose == super::breeze::LONG_JUMPING || pose == super::breeze::INHALING { + super::breeze::set_pose(m, super::breeze::STANDING); + } + let mm = mem(m); + mm.breeze_jump_target.clear(); + mm.breeze_jump_inhaling.clear(); + mm.breeze_leaving_water.clear(); + } + } + } +} + +fn manhattan_sq(a: [i32; 3], b: [i32; 3]) -> i64 { + let d = [ + i64::from(a[0] - b[0]), + i64::from(a[1] - b[1]), + i64::from(a[2] - b[2]), + ]; + d[0] * d[0] + d[1] * d[1] + d[2] * d[2] +} +fn same_path(a: Option<&Path>, b: Option<&Path>) -> bool { + match (a, b) { + (None, None) => true, + (Some(a), Some(b)) => a.nodes == b.nodes && a.target == b.target, + _ => false, + } +} +fn block_of(p: Vec3) -> [i32; 3] { + [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32] +} +/// `Swim`: deeper than the jump threshold, or in lava. +fn swim_condition(m: &Mob) -> bool { + m.fluids.water > m.fluid_jump_threshold() || m.fluids.in_lava +} +/// `PositionTracker.isVisibleBy`. +fn tracker_visible(m: &mut Mob, w: &MobWorld, t: Tracker) -> bool { + match t { + Tracker::Entity(who, _) => { + w.target_info(who).is_some_and(|i| i.alive) && visible_contains(m, w, who) + } + _ => true, + } +} +/// `MoveToTargetSink.reachedTarget`. +fn reached(m: &Mob, w: &MobWorld, walk: &WalkTarget) -> bool { + walk.target.block(w).is_some_and(|p| { + let h = block_of(m.position); + (p[0] - h[0]).abs() + (p[1] - h[1]).abs() + (p[2] - h[2]).abs() <= walk.close + }) +} +/// `MoveToTargetSink.tryComputePath`. +fn compute_path( + m: &mut Mob, + cx: &mut Bx, + walk: &WalkTarget, + path: &mut Option, + speed: &mut f32, +) -> bool { + let Some(target) = walk.target.block(cx.w) else { + return false; + }; + *path = m.create_path_to(cx.w, target, 0); + *speed = walk.speed; + if reached(m, cx.w, walk) { + mem(m).cant_reach_walk_target_since.clear(); + } else { + let can_reach = path.as_ref().is_some_and(|p| p.reached); + let mm = mem(m); + if can_reach { + mm.cant_reach_walk_target_since.clear(); + } else if !mm.cant_reach_walk_target_since.present() { + mm.cant_reach_walk_target_since.set(cx.now); + } + if path.is_some() { + return true; + } + let to = [ + f64::from(target[0]) + 0.5, + f64::from(target[1]), + f64::from(target[2]) + 0.5, + ]; + if let Some(step) = + m.default_random_pos_towards(cx.w, 10, 7, to, f64::from(std::f32::consts::FRAC_PI_2)) + { + *path = m.create_path_to(cx.w, block_of(Vec3::new(step[0], step[1], step[2])), 0); + return path.is_some(); + } + } + false +} +/// `BehaviorUtils.isWithinAttackRange(body, target, 1)` for a mob without a +/// ranged weapon: `Mob.isWithinMeleeAttackRange`. +fn within_attack_range(m: &Mob, w: &MobWorld, target: Who) -> bool { + w.target_info(target) + .is_some_and(|t| m.within_melee_range(&t)) +} + +// ---- The breeze's behaviours -------------------------------------------- + +/// `Mob.playSound(sound, volume, 1)`: at the mob, no pitch drawn. +fn breeze_sound(m: &Mob, cx: &mut Bx, sound: &'static str, volume: f32) { + let at = [m.position.x, m.position.y, m.position.z]; + cx.events.push(MobEvent::Sound(sound, at, volume, 1.0)); +} +/// `Entity.lookAt(EntityAnchorArgument.Anchor.EYES, pos)`. +pub fn look_at_eyes(m: &mut Mob, at: [f64; 3]) { + let (xd, yd, zd) = ( + at[0] - m.position.x, + at[1] - m.eye_y(), + at[2] - m.position.z, + ); + let sd = (xd * xd + zd * zd).sqrt(); + // The compiled code multiplies by the folded `Mth.RAD_TO_DEG`. + let deg = f64::from(trig::RAD_TO_DEG); + m.head_pitch = wrap_degrees((-(trig::atan2(yd, sd) * deg)) as f32); + m.yaw = wrap_degrees((trig::atan2(zd, xd) * deg) as f32 - 90.0); + m.head_yaw = m.yaw; + m.previous_head_pitch = m.head_pitch; + m.previous_yaw = m.yaw; + // LivingEntity.lookAt: the body follows the head. + m.previous_head_yaw = m.head_yaw; + m.body_yaw = m.head_yaw; + m.previous_body_yaw = m.body_yaw; +} +/// `Mth.wrapDegrees(float)`. +fn wrap_degrees(angle: f32) -> f32 { + let mut w = angle % 360.0; + if w >= 180.0 { + w -= 360.0; + } + if w < -180.0 { + w += 360.0; + } + w +} +/// The attack target's position, eye height, facing and height. +struct Quarry { + position: Vec3, + head_yaw: f32, + height: f64, +} +fn quarry(w: &MobWorld, who: Who) -> Option { + let t = w.target_info(who)?; + let head_yaw = match who { + Who::Player => w.player.as_ref().map_or(0.0, |p| p.yaw), + Who::Mob(id) => w.seen(id).map_or(0.0, |s| s.yaw), + }; + Some(Quarry { + position: t.position, + head_yaw, + height: t.bounds.max_position().y - t.bounds.min_position().y, + }) +} +/// `BreezeUtil.randomPointBehindTarget`. +fn point_behind(m: &mut Mob, q: &Quarry) -> Vec3 { + let view = q.head_yaw + 180.0 + m.random.next_gaussian() as f32 * 90.0 / 2.0; + let f = m.random.next_float(); + let r = 4.0 + f * (8.0 - 4.0); + let d = Vec3::direction_from_rotation(0.0, view).scale(f64::from(r)); + q.position.add_vector(d) +} +/// `BreezeUtil.hasLineOfSight`. +fn line_of_sight(m: &Mob, w: &MobWorld, target: Vec3) -> bool { + let from = m.position; + let range = 50.0_f64.max(m.attrs.follow_range); + target.distance(from) <= range && w.clear_between(from, target, false) +} +/// `Slide.start`. +fn slide_start(m: &mut Mob, cx: &mut Bx) { + let Some(target) = mem(m).attack_target.value() else { + return; + }; + let Some(q) = quarry(cx.w, target) else { + return; + }; + // Breeze.withinInnerCircleRange + let centre = Vec3::new( + m.position.x.floor() + 0.5, + m.position.y.floor() + 0.5, + m.position.z.floor() + 0.5, + ); + let (dx, dy, dz) = ( + q.position.x - centre.x, + q.position.y - centre.y, + q.position.z - centre.z, + ); + let inner = dx * dx + dz * dz < 16.0 && dy.abs() < 10.0; + let mut position: Option = None; + if inner + && let Some(away) = + m.default_random_pos_away(cx.w, 5, 5, [q.position.x, q.position.y, q.position.z]) + { + let away = Vec3::new(away[0], away[1], away[2]); + if line_of_sight(m, cx.w, away) + && q.position.distance_squared(away) > q.position.distance_squared(m.position) + { + position = Some(away); + } + } + let position = match position { + Some(p) => p, + None => { + if m.random.next_boolean() { + point_behind(m, &q) + } else { + // randomPointInMiddleCircle + let d = q.position.subtract(m.position); + let a = m.random.next_double(); + let distance = d.length() - (8.0 + a * (4.0 - 8.0)); + let n = d.normalize(); + m.position + .add_vector(Vec3::new(n.x * distance, n.y * distance, n.z * distance)) + } + } + }; + mem(m) + .walk_target + .set(WalkTarget::block(block_of(position), 0.6, 1)); +} +/// `Shoot.tick`. +fn shoot_tick(m: &mut Mob, cx: &mut Bx) { + let Some(target) = mem(m).attack_target.value() else { + return; + }; + let Some(q) = quarry(cx.w, target) else { + return; + }; + look_at_eyes(m, [q.position.x, q.position.y, q.position.z]); + let mm = mem(m); + if mm.breeze_shoot_charging.present() || mm.breeze_shoot_recovering.present() { + return; + } + mm.breeze_shoot_recovering.set_ttl((), 4); + let firing = super::breeze::firing_y(m); + let (xd, yd, zd) = ( + q.position.x - m.position.x, + q.position.y + q.height * 0.3 - firing, + q.position.z - m.position.z, + ); + let start = Vec3::new(m.position.x, firing, m.position.z); + let mut p = Projectile::new( + ProjectileKind::BreezeWindCharge, + start, + Some(Who::Mob(m.id)), + ); + // The new entity's own random spreads the shot (5 - difficulty * 4 at + // normal): not the breeze's. + let mut own = LegacyRandom::new( + cx.now + .wrapping_mul(0x5DEE_CE66) + .wrapping_add(i64::from(m.id)), + ); + p.shoot(&mut own, [xd, yd, zd], 0.7, -3.0); + cx.events.push(MobEvent::Projectile(p)); + breeze_sound(m, cx, "entity.breeze.shoot", 1.5); +} +/// `LongJump.canRun`. +fn long_jump_can_run(m: &mut Mob, cx: &mut Bx) -> bool { + if !m.on_ground && !m.fluids.in_water { + return false; + } + if m.fluids.water > m.fluid_jump_threshold() || m.fluids.in_lava { + return false; + } + if mem(m).breeze_jump_target.present() { + return true; + } + let Some(target) = mem(m).attack_target.value() else { + return false; + }; + let Some(q) = quarry(cx.w, target) else { + return false; + }; + // outOfAggroRange: !target.closerThan(breeze, follow range) + let follow = m.attrs.follow_range; + if q.position.distance_squared(m.position) >= follow * follow { + set_attack_target(m, None); + return false; + } + // tooCloseForJump: (float) distance - 4 <= 0 + if q.position.distance(m.position) as f32 - 4.0 <= 0.0 { + return false; + } + if !super::breeze::can_jump_from_here(m, cx.w) { + return false; + } + let behind = point_behind(m, &q); + let Some(target_pos) = super::breeze::snap_to_surface(cx.w, behind) else { + return false; + }; + let below = + cx.w.block_name(target_pos[0], target_pos[1] - 1, target_pos[2]); + if super::breeze::dangerous_block(below) { + return false; + } + let centre = Vec3::new( + f64::from(target_pos[0]) + 0.5, + f64::from(target_pos[1]) + 0.5, + f64::from(target_pos[2]) + 0.5, + ); + if !line_of_sight(m, cx.w, centre) + && !line_of_sight(m, cx.w, centre.add_vector(Vec3::new(0.0, 4.0, 0.0))) + { + return false; + } + mem(m).breeze_jump_target.set(target_pos); + true +} +/// `LongJump.tick`. +fn long_jump_tick(m: &mut Mob, cx: &mut Bx) { + let in_water = m.fluids.in_water; + if !in_water && mem(m).breeze_leaving_water.present() { + mem(m).breeze_leaving_water.clear(); + } + let pose = super::breeze::pose(m); + let finished_inhaling = + !mem(m).breeze_jump_inhaling.present() && pose == super::breeze::INHALING; + if finished_inhaling { + let target = mem(m).breeze_jump_target.value(); + let v = target.and_then(|t| { + super::breeze::optimal_jump_vector( + m, + Vec3::new( + f64::from(t[0]) + 0.5, + f64::from(t[1]), + f64::from(t[2]) + 0.5, + ), + ) + }); + let Some(v) = v else { + super::breeze::set_pose(m, super::breeze::STANDING); + return; + }; + if in_water { + mem(m).breeze_leaving_water.set(()); + } + breeze_sound(m, cx, "entity.breeze.jump", 1.0); + super::breeze::set_pose(m, super::breeze::LONG_JUMPING); + m.yaw = m.body_yaw; + m.velocity = v; + return; + } + let landed_in_water = m.fluids.in_water && !mem(m).breeze_leaving_water.present(); + if pose == super::breeze::LONG_JUMPING && (m.on_ground || landed_in_water) { + breeze_sound(m, cx, "entity.breeze.land", 1.0); + super::breeze::set_pose(m, super::breeze::STANDING); + let hurt = mem(m).hurt_by.present(); + let mm = mem(m); + mm.breeze_jump_cooldown + .set_ttl((), if hurt { 2 } else { 10 }); + mm.breeze_shoot.set_ttl((), 100); + } +} + +// ---- The packages ------------------------------------------------------- + +fn timed(min: i32, max: i32) -> Timed { + Timed::new(min, max) +} +/// `availableBehaviorsByPriority`'s order: priority, then the activity's +/// hash slot (core 1, idle 5, fight 14), then insertion order. +fn sorted(mut v: Vec<(i32, Act, B)>) -> Vec { + let slot = |a: Act| match a { + Act::Core => 1, + Act::Idle => 5, + Act::Fight => 14, + }; + v.sort_by_key(|(p, a, _)| (*p, slot(*a))); + v.into_iter().map(|(_, act, b)| Entry { act, b }).collect() +} +fn run_one(seed: i64, kids: Vec<(B, i32)>) -> B { + B::RunOne(Box::new(RunOne { + running: false, + random: LegacyRandom::new(seed), + kids: kids.into_iter().map(|(b, w)| (b, w, 0.0)).collect(), + })) +} +fn move_sink(min: i32, max: i32, slide: bool) -> B { + B::MoveToTargetSink { + t: timed(min, max), + cooldown: 0, + path: None, + last_target: None, + speed: 0.0, + slide, + } +} +/// `BreezeAi.getActivities`. +fn breeze_packages(seed: i64) -> Vec { + use Act::*; + sorted(vec![ + ( + 0, + Core, + B::Swim { + t: timed(60, 60), + creaking: false, + }, + ), + (1, Core, B::LookAtTargetSink(timed(45, 90))), + (0, Idle, B::StartAttacking(false, Finder::NearestAttackable)), + (1, Idle, B::StartAttacking(false, Finder::HurtBy)), + (2, Idle, move_sink(20, 40, true)), + ( + 3, + Idle, + run_one( + seed, + vec![ + (B::DoNothing(timed(20, 100)), 1), + (B::RandomStroll(false, 0.6), 2), + ], + ), + ), + ( + 0, + Fight, + B::StopAttacking { + running: false, + breeze: true, + positives_left: 0, + }, + ), + (1, Fight, B::Shoot(timed(20, 20))), + (2, Fight, B::LongJump(timed(200, 200))), + (3, Fight, B::ShootWhenStuck(timed(60, 60))), + (4, Fight, B::Slide(timed(60, 60))), + ]) +} +/// `CreakingAi.getActivities`. +fn creaking_packages(seed: i64) -> Vec { + use Act::*; + sorted(vec![ + ( + 0, + Core, + B::Swim { + t: timed(60, 60), + creaking: true, + }, + ), + (1, Core, B::LookAtTargetSink(timed(45, 90))), + (2, Core, move_sink(150, 250, false)), + (10, Idle, B::StartAttacking(false, Finder::ActiveCreaking)), + ( + 11, + Idle, + B::SetEntityLookTargetSometimes { + running: false, + until_next: 0, + }, + ), + ( + 12, + Idle, + run_one( + seed, + vec![ + (B::RandomStroll(false, 0.3), 2), + (B::SetWalkTargetFromLookTarget(false), 2), + (B::DoNothing(timed(30, 60)), 1), + ], + ), + ), + (10, Fight, B::SetWalkTargetFromAttackTarget(false)), + (11, Fight, B::MeleeAttack(false)), + ( + 12, + Fight, + B::StopAttacking { + running: false, + breeze: false, + positives_left: 0, + }, + ), + ]) +} + +// ---- The probe's view --------------------------------------------------- + +fn who(w: Who) -> String { + match w { + Who::Player => "player".into(), + Who::Mob(id) => format!("e{id}"), + } +} +fn pos(p: [i32; 3]) -> String { + format!("{},{},{}", p[0], p[1], p[2]) +} +fn tracker(t: Tracker) -> String { + match t { + Tracker::Entity(e, _) => who(e), + Tracker::Block(p) => pos(p), + Tracker::Point(v) => pos([ + v[0].floor() as i32, + v[1].floor() as i32, + v[2].floor() as i32, + ]), + } +} +/// The active activities and the memories with values, as the mob AI +/// oracle prints them. +pub fn describe(m: &Mob) -> Option<(String, String)> { + let b = brain(m)?; + let mut acts = ["core", b.activity.name()]; + acts.sort_unstable(); + let mm = &b.mem; + let mut out: Vec = Vec::new(); + let mut put = |name: &str, value: String, ttl: i64| { + if ttl == NEVER { + out.push(format!("{name}={value}")); + } else { + out.push(format!("{name}={value}@{ttl}")); + } + }; + macro_rules! slot { + ($name:expr, $s:expr, $f:expr) => { + if let Some(v) = $s.get() { + put($name, $f(v), $s.ttl); + } + }; + } + let unit = |_: &()| "u".to_string(); + let list = |l: &Vec| format!("n{}", l.len()); + slot!("attack_target", mm.attack_target, |e: &Who| who(*e)); + slot!("attack_cooling_down", mm.attack_cooling_down, |b: &bool| b + .to_string()); + slot!( + "cant_reach_walk_target_since", + mm.cant_reach_walk_target_since, + |t: &i64| t.to_string() + ); + slot!("hurt_by", mm.hurt_by, |_: &i64| "DamageSource".to_string()); + slot!("hurt_by_entity", mm.hurt_by_entity, |e: &Who| who(*e)); + slot!("look_target", mm.look_target, |t: &Tracker| tracker(*t)); + slot!("mobs", mm.mobs, list); + slot!("visible_mobs", mm.visible_mobs, |_: &Visible| { + "NearestVisibleLivingEntities".to_string() + }); + slot!("nearest_attackable", mm.nearest_attackable, |e: &Who| who( + *e + )); + slot!("nearest_players", mm.nearest_players, list); + slot!( + "nearest_visible_player", + mm.nearest_visible_player, + |e: &Who| who(*e) + ); + slot!( + "nearest_visible_targetable_player", + mm.nearest_visible_targetable_player, + |e: &Who| who(*e) + ); + slot!( + "nearest_visible_targetable_players", + mm.nearest_visible_targetable_players, + list + ); + slot!("path", mm.path, |p: &Path| format!("path{}", pos(p.target))); + slot!("walk_target", mm.walk_target, |t: &WalkTarget| format!( + "{}/{:x}/{}", + tracker(t.target), + t.speed.to_bits(), + t.close + )); + slot!("breeze_shoot", mm.breeze_shoot, unit); + slot!("breeze_shoot_charging", mm.breeze_shoot_charging, unit); + slot!("breeze_shoot_recover", mm.breeze_shoot_recovering, unit); + slot!("breeze_shoot_cooldown", mm.breeze_shoot_cooldown, unit); + slot!("breeze_jump_cooldown", mm.breeze_jump_cooldown, unit); + slot!("breeze_jump_inhaling", mm.breeze_jump_inhaling, unit); + slot!( + "breeze_jump_target", + mm.breeze_jump_target, + |p: &[i32; 3]| { pos(*p) } + ); + slot!("breeze_leaving_water", mm.breeze_leaving_water, unit); + out.sort(); + Some((acts.join("|"), out.join(" "))) +} diff --git a/crates/horizon-client/src/mobs/species.rs b/crates/horizon-client/src/mobs/species.rs index 1d2ad6180..1dc832f63 100644 --- a/crates/horizon-client/src/mobs/species.rs +++ b/crates/horizon-client/src/mobs/species.rs @@ -1439,6 +1439,7 @@ impl Def { | S::MagmaCube | S::Wither | S::Allay + | S::Breeze ), flying: matches!(s, S::Ghast | S::Phantom | S::HappyGhast), climber: matches!(s, S::Spider | S::CaveSpider), @@ -1537,6 +1538,8 @@ impl Def { | S::Ravager | S::Wither | S::Warden + | S::Breeze + | S::Creaking ) } /// The item tag Animal.isFood tests. diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index 51110f8a9..86dff2251 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -19,13 +19,13 @@ use horizon_core::{ }; /// `MemorySlot.NEVER_EXPIRE`. -const NEVER: i64 = i64::MAX; +pub(super) const NEVER: i64 = i64::MAX; /// `MemorySlot`: a value and its time to live. #[derive(Clone, Debug)] pub struct Slot { v: Option, - ttl: i64, + pub(super) ttl: i64, } impl Default for Slot { fn default() -> Self { @@ -36,7 +36,8 @@ impl Default for Slot { } } impl Slot { - fn tick(&mut self) { + /// `MemorySlot.tick`. + pub(super) fn tick(&mut self) { if self.v.is_some() && self.ttl != NEVER { if self.ttl <= 0 { self.clear(); @@ -66,6 +67,9 @@ impl Slot { pub fn get(&self) -> Option<&T> { self.v.as_ref() } + pub fn get_mut(&mut self) -> Option<&mut T> { + self.v.as_mut() + } pub fn present(&self) -> bool { self.v.is_some() } @@ -77,7 +81,7 @@ impl Slot { } impl Slot> { /// `Brain.setMemory` of a collection: an empty one erases the memory. - fn set_list(&mut self, v: Vec) { + pub(super) fn set_list(&mut self, v: Vec) { if v.is_empty() { self.clear(); } else { @@ -137,7 +141,7 @@ pub struct WalkTarget { pub close: i32, } impl WalkTarget { - fn block(p: [i32; 3], speed: f32, close: i32) -> Self { + pub(super) fn block(p: [i32; 3], speed: f32, close: i32) -> Self { Self { target: Tracker::Block(p), speed, @@ -145,7 +149,7 @@ impl WalkTarget { } } /// `new WalkTarget(Vec3, ...)`: the block containing the point. - fn point(p: [f64; 3], speed: f32, close: i32) -> Self { + pub(super) fn point(p: [f64; 3], speed: f32, close: i32) -> Self { Self::block( [ p[0].floor() as i32, @@ -162,8 +166,8 @@ impl WalkTarget { /// cache of `Sensor.isEntityTargetable`. #[derive(Clone, Debug, Default)] pub struct Visible { - list: Vec, - cache: Vec<(Who, bool)>, + pub(super) list: Vec, + pub(super) cache: Vec<(Who, bool)>, } /// The memories a villager's brain registers. diff --git a/crates/horizon-client/src/mobs/world.rs b/crates/horizon-client/src/mobs/world.rs index 218a48b46..55a507fa7 100644 --- a/crates/horizon-client/src/mobs/world.rs +++ b/crates/horizon-client/src/mobs/world.rs @@ -79,6 +79,58 @@ impl MobWorld<'_> { }); matches!(result, Ok(None)) } + /// Level.clip with VISUAL shapes and no fluids: true on a miss. Glass + /// (`TransparentBlock`) and bars and panes (`IronBarsBlock`) have no + /// visual shape; mud, soul sand and powder snow look like full blocks. + pub fn visual_clear_between(&self, from: Vec3, to: Vec3) -> bool { + let mut scene = SceneCollisions { + world: self.world, + binding: self.collision, + }; + let full = horizon_core::geometry::Aabb::new(Vec3::ZERO, Vec3::new(1.0, 1.0, 1.0)); + let result = traverse_blocks(from, to, 512, |p: BlockPos| { + let state = self.world.block(p.x, p.y, p.z); + if self.facts.is_air(state) { + return None; + } + let name = self.facts.get(state).name.trim_start_matches("minecraft:"); + if name.ends_with("glass") || name.ends_with("glass_pane") || name.ends_with("_bars") { + return None; + } + if matches!(name, "mud" | "soul_sand" | "powder_snow") { + return full + .move_by(Vec3::new(f64::from(p.x), f64::from(p.y), f64::from(p.z))) + .clip(from, to) + .map(|_| ()); + } + let shape = self + .collision + .collision_shape(&mut scene, state, [p.x, p.y, p.z]) + .ok()?; + shape.clip(from, to, p).map(|_| ()) + }); + matches!(result, Ok(None)) + } + /// Level.clip with COLLIDER shapes and no fluids: where the segment + /// first hits a block, if it does. + pub fn clip_block(&self, from: Vec3, to: Vec3) -> Option { + let mut scene = SceneCollisions { + world: self.world, + binding: self.collision, + }; + let result = traverse_blocks(from, to, 512, |p: BlockPos| { + let state = self.world.block(p.x, p.y, p.z); + if self.facts.is_air(state) { + return None; + } + let shape = self + .collision + .collision_shape(&mut scene, state, [p.x, p.y, p.z]) + .ok()?; + shape.clip(from, to, p).map(|hit| hit.location) + }); + result.ok().flatten() + } /// LivingEntity.hasLineOfSight: eye to eye within 128 blocks. pub fn line_of_sight(&self, from_eye: Vec3, to: Vec3) -> bool { let d = diff --git a/crates/horizon-core/src/geometry/trig.rs b/crates/horizon-core/src/geometry/trig.rs index d2c3a0746..f7b2484b5 100644 --- a/crates/horizon-core/src/geometry/trig.rs +++ b/crates/horizon-core/src/geometry/trig.rs @@ -154,6 +154,164 @@ pub fn fdlibm_asin(x: f64) -> f64 { if hx > 0 { t } else { -t } } +/// fdlibm `atan`, as `StrictMath.atan` computes it. +#[allow(clippy::excessive_precision, clippy::approx_constant)] // fdlibm's constants, verbatim. +pub fn fdlibm_atan(x: f64) -> f64 { + const ATANHI: [f64; 4] = [ + 4.636_476_090_008_060_935_15e-01, + 7.853_981_633_974_482_789_99e-01, + 9.827_937_232_473_290_540_77e-01, + 1.570_796_326_794_896_558_00e+00, + ]; + const ATANLO: [f64; 4] = [ + 2.269_877_745_296_168_709_24e-17, + 3.061_616_997_868_383_017_93e-17, + 1.390_331_103_123_099_845_16e-17, + 6.123_233_995_736_766_035_87e-17, + ]; + const AT: [f64; 11] = [ + 3.333_333_333_333_293_180_27e-01, + -1.999_999_999_987_648_324_76e-01, + 1.428_571_427_250_346_637_11e-01, + -1.111_111_040_546_235_578_80e-01, + 9.090_887_133_436_506_561_96e-02, + -7.691_876_205_044_829_994_95e-02, + 6.661_073_137_387_531_206_69e-02, + -5.833_570_133_790_573_486_45e-02, + 4.976_877_994_615_932_360_17e-02, + -3.653_157_274_421_691_552_70e-02, + 1.628_582_011_536_578_236_23e-02, + ]; + let hx = (x.to_bits() >> 32) as i32; + let ix = hx & 0x7fff_ffff; + let mut x = x; + let id: i32; + if ix >= 0x4410_0000 { + // |x| >= 2^66 + if ix > 0x7ff0_0000 || (ix == 0x7ff0_0000 && (x.to_bits() as u32) != 0) { + return x + x; // NaN + } + return if hx > 0 { + ATANHI[3] + ATANLO[3] + } else { + -ATANHI[3] - ATANLO[3] + }; + } + if ix < 0x3fdc_0000 { + // |x| < 0.4375 + if ix < 0x3e20_0000 && 1.0e300 + x > 1.0 { + // |x| < 2^-29: raise inexact + return x; + } + id = -1; + } else { + x = x.abs(); + if ix < 0x3ff3_0000 { + if ix < 0x3fe6_0000 { + id = 0; + x = (2.0 * x - 1.0) / (2.0 + x); + } else { + id = 1; + x = (x - 1.0) / (x + 1.0); + } + } else if ix < 0x4003_8000 { + id = 2; + x = (x - 1.5) / (1.0 + 1.5 * x); + } else { + id = 3; + x = -1.0 / x; + } + } + let z = x * x; + let w = z * z; + let s1 = z * (AT[0] + w * (AT[2] + w * (AT[4] + w * (AT[6] + w * (AT[8] + w * AT[10]))))); + let s2 = w * (AT[1] + w * (AT[3] + w * (AT[5] + w * (AT[7] + w * AT[9])))); + if id < 0 { + return x - x * (s1 + s2); + } + let i = id as usize; + let z = ATANHI[i] - ((x * (s1 + s2) - ATANLO[i]) - x); + if hx < 0 { -z } else { z } +} + +/// fdlibm `__ieee754_atan2`, as `StrictMath.atan2` (and so `Math.atan2`) +/// computes it. +#[allow(clippy::excessive_precision, clippy::approx_constant)] // fdlibm's constants, verbatim. +pub fn fdlibm_atan2(y: f64, x: f64) -> f64 { + const TINY: f64 = 1.0e-300; + const PI_O_4: f64 = 7.853_981_633_974_482_789_99e-01; + const PI_O_2: f64 = 1.570_796_326_794_896_558_00e+00; + const PI: f64 = 3.141_592_653_589_793_115_98e+00; + const PI_LO: f64 = 1.224_646_799_147_353_207_17e-16; + let (xb, yb) = (x.to_bits(), y.to_bits()); + let hx = (xb >> 32) as i32; + let ix = hx & 0x7fff_ffff; + let lx = xb as u32; + let hy = (yb >> 32) as i32; + let iy = hy & 0x7fff_ffff; + let ly = yb as u32; + if (ix as u32 | ((lx | lx.wrapping_neg()) >> 31)) > 0x7ff0_0000 + || (iy as u32 | ((ly | ly.wrapping_neg()) >> 31)) > 0x7ff0_0000 + { + return x + y; // NaN + } + if hx.wrapping_sub(0x3ff0_0000) as u32 | lx == 0 { + return fdlibm_atan(y); // x = 1.0 + } + let m = ((hy >> 31) & 1) | ((hx >> 30) & 2); + if (iy as u32 | ly) == 0 { + return match m { + 0 | 1 => y, + 2 => PI + TINY, + _ => -PI - TINY, + }; + } + if (ix as u32 | lx) == 0 { + return if hy < 0 { + -PI_O_2 - TINY + } else { + PI_O_2 + TINY + }; + } + if ix == 0x7ff0_0000 { + if iy == 0x7ff0_0000 { + return match m { + 0 => PI_O_4 + TINY, + 1 => -PI_O_4 - TINY, + 2 => 3.0 * PI_O_4 + TINY, + _ => -3.0 * PI_O_4 - TINY, + }; + } + return match m { + 0 => 0.0, + 1 => -0.0, + 2 => PI + TINY, + _ => -PI - TINY, + }; + } + if iy == 0x7ff0_0000 { + return if hy < 0 { + -PI_O_2 - TINY + } else { + PI_O_2 + TINY + }; + } + let k = (iy - ix) >> 20; + let z = if k > 60 { + PI_O_2 + 0.5 * PI_LO + } else if hx < 0 && k < -60 { + 0.0 + } else { + fdlibm_atan((y / x).abs()) + }; + match m { + 0 => z, + 1 => -z, + 2 => PI - (z - PI_LO), + _ => (z - PI_LO) - PI, + } +} + #[cfg(test)] mod tests { use super::*; @@ -191,4 +349,36 @@ mod tests { assert_eq!(cos(0.0), 1.0); assert_eq!(sin(std::f64::consts::FRAC_PI_2), 1.0); } + + #[test] + fn fdlibm_atan2_matches_java_math_atan2() { + // (y, x, Math.atan2(y, x)) bits from a HotSpot 25 run. + let cases: [(u64, u64, u64); 21] = [ + (0x4036c1a1555ddb90, 0x40b1a89b60fc338e, 0x3f749e66db543fc4), + (0xbfc9752ac321b894, 0x3f3d80a505d0aa2b, 0xbff918b5f001ade8), + (0x4013fbdac7d52a8f, 0x4043e369b0fa3aad, 0x3fbffc728a3272d5), + (0x3fd89fe141e1eea2, 0x3fcfd23d2fa01b78, 0x3fefe8a13ebea603), + (0xbf815cc85b3c5c7a, 0x40b1ab07dd5012f3, 0xbebf72476f1c300d), + (0xbf6decaf388fcf29, 0x3ffbedddfbfb829e, 0xbf6124a1265c6efd), + (0xbfeb43b46f5bbbfc, 0xc0057a5b64b11a12, 0xc006aca11bc899f9), + (0x3fd0d1695a72bc5c, 0x3fa34c15b3f8f245, 0x3ff6da7c56d44150), + (0xc00e3df263d3716a, 0x4002565c34839cb6, 0xbff069572866761a), + (0xbf22b9569c9c365e, 0xbffb7bf36ef636e8, 0xc00921cfba70e58c), + (0x40001bca146d16b0, 0xc074c72be81b2112, 0x40091593dd9f4b9d), + (0xbf58f46b45074b90, 0x3f752f2393097fe7, 0xbfd25467b1734764), + (0x40aa8c9dfed35afe, 0x401d5279f1fc1595, 0x3ff919256ef21d22), + (0x3f304a34e8c07c8b, 0xbf346080834c6bae, 0x4003bcd457a3e152), + (0x407bc14a1749ce5b, 0x3fa94314f9e58f65, 0x3ff92186d3893ce6), + (0xbf4c9156e5163833, 0xc0b2c3a07f21df29, 0xc00921fb3be82bfe), + (0xc001fda2a9c29687, 0xc07917504bff0cb1, 0xc009168273a10702), + (0xc06911a6f4f07751, 0xbfce4df079fb6418, 0xbff926d12f47ff9f), + (0xc044ef11007719e6, 0xbf9984e712cc5687, 0xbff9246b79ec6a20), + (0xbfecf1294a501faa, 0x409b7de1660f155a, 0xbf40d815260dd369), + (0xc0a7a9f851863c31, 0xc03b3bd7d7a8f4a8, 0xbff946cee06eebe8), + ]; + for (y, x, expected) in cases { + let got = fdlibm_atan2(f64::from_bits(y), f64::from_bits(x)); + assert_eq!(got.to_bits(), expected, "atan2({y:x}, {x:x})"); + } + } } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java index 7185ec400..75fe7d24a 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java @@ -61,6 +61,8 @@ import net.minecraft.world.clock.WorldClocks; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntitySpawnReason; import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.monster.creaking.Creaking; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.Mob; @@ -157,8 +159,17 @@ public final class VanillaMobAiOracle { List blocks = new ArrayList<>(); double[] player; boolean creative; + /** The tick from which the player faces turnYaw (head and body), else 0. */ + int turnTick = Integer.MAX_VALUE; + float turnYaw; List mobs = new ArrayList<>(); long levelSeed = 0; + /** Blocks placed when the scenario starts, so their block entities start afresh and tick. */ + List hearts = new ArrayList<>(); + /** ServerLevel.isSpawningMonsters during the scenario (a heart spawns creakings). */ + boolean spawning; + /** The player hits a mob for 1 at the start of a tick: {tick, mob index}. */ + List hurts = new ArrayList<>(); } static void parse(Path path) throws Exception { @@ -179,15 +190,25 @@ public final class VanillaMobAiOracle { case "rain" -> s.rain = true; case "thunder" -> s.thunder = true; case "levelseed" -> s.levelSeed = Long.parseLong(kv[1]); + case "spawning" -> s.spawning = true; default -> throw new IllegalArgumentException(line); } } } case "origin" -> { s.originX = Integer.parseInt(f[1]); s.originZ = Integer.parseInt(f[2]); } case "fill", "block" -> s.blocks.add(f); + case "heart" -> s.hearts.add(f); + case "hurt" -> s.hurts.add(new int[] {Integer.parseInt(f[1]), Integer.parseInt(f[2])}); case "player" -> { s.player = new double[] {Double.parseDouble(f[1]), Double.parseDouble(f[2]), Double.parseDouble(f[3])}; - s.creative = f.length > 4 && f[4].equals("creative"); + for (int i = 4; i < f.length; i++) { + if (f[i].equals("creative")) s.creative = true; + else if (f[i].startsWith("turn=")) { + String[] tv = f[i].substring(5).split(","); + s.turnTick = Integer.parseInt(tv[0]); + s.turnYaw = Float.parseFloat(tv[1]); + } else throw new IllegalArgumentException(line); + } } case "mob" -> { MobSpec m = new MobSpec(); @@ -441,6 +462,11 @@ public final class VanillaMobAiOracle { } player.setGameMode(s.creative ? GameType.CREATIVE : GameType.SURVIVAL); player.snapTo(s.player[0], s.player[1], s.player[2], 0.0F, 0.0F); + // snapTo leaves the head and body as the player was created + // (a random head yaw): face +z like the probe's player. + player.setYHeadRot(0.0F); + player.yHeadRotO = 0.0F; + player.setYBodyRot(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); @@ -480,6 +506,42 @@ public final class VanillaMobAiOracle { brains.add(brain); seeds.add(spec.seed); } + // Hearts start with the scenario: their tickers have not run during the warm-up. + var blockLookup = level.holderLookup(Registries.BLOCK); + List heartPositions = new ArrayList<>(); + for (String[] h : s.hearts) { + BlockPos at = new BlockPos(Integer.parseInt(h[1]), Integer.parseInt(h[2]), Integer.parseInt(h[3])); + level.setBlock(at, BlockStateParser.parseForBlock(blockLookup, h[4], false).blockState(), 2 | 16); + heartPositions.add(at); + } + // Mobs the level creates during the scenario (a heart's creakings) get a seeded + // random, delayed sensors and seeded gates as the scenario's own mobs do, the + // n-th with seed 1000 + n; they join the list once in the level. + List created = new ArrayList<>(); + Field factoryField = field(EntityType.class, "factory"); + Object creakingFactory = factoryField.get(EntityTypes.CREAKING); + final List mobsView = mobs; + factoryField.set(EntityTypes.CREAKING, (EntityType.EntityFactory) (type, lvl) -> { + Creaking c = new Creaking(type, lvl); + try { + long seed = 1000 + created.size(); + if (tracing(s)) field(Entity.class, "random").set(c, new TracingRandom(0L, TRACE, mobsView.size() + created.size())); + c.getRandom().setSeed(seed); + @SuppressWarnings("unchecked") + Map> cs = (Map>) get(c.getBrain(), "sensors"); + for (Sensor sensor : cs.values()) sensor.randomlyDelayStart(c.getRandom()); + seedGates(c.getBrain(), seed); + } catch (Exception e) { + throw new IllegalStateException(e); + } + created.add(c); + return c; + }); + boolean spawnMobs = this.getGameRules().get(GameRules.SPAWN_MOBS); + boolean spawnMonsters = this.getGameRules().get(GameRules.SPAWN_MONSTERS); + this.getGameRules().set(GameRules.SPAWN_MOBS, s.spawning, this); + this.getGameRules().set(GameRules.SPAWN_MONSTERS, s.spawning, this); + int adopted = 0; level.getRandom().setSeed(s.levelSeed); SOUNDS.clear(); Method tickTime = method(ServerLevel.class, "tickTime"); @@ -498,6 +560,12 @@ public final class VanillaMobAiOracle { player.hurtTime = 0; player.snapTo(s.player[0], s.player[1], s.player[2], 0.0F, 0.0F); player.setDeltaMovement(Vec3.ZERO); + if (t >= s.turnTick) { + // The view vector follows the head (LivingEntity.getViewYRot). + player.setYRot(s.turnYaw); + player.setYHeadRot(s.turnYaw); + player.setYBodyRot(s.turnYaw); + } } TracingRandom.tick = t; TracingRandom.on = tracing(s) && t >= traceFrom() && t <= traceTo(); @@ -509,23 +577,57 @@ public final class VanillaMobAiOracle { seedGates(brains.get(i), seeds.get(i)); } } + for (int[] hurt : s.hurts) { + if (hurt[0] == t && hurt[1] < mobs.size() && !mobs.get(hurt[1]).isRemoved()) + mobs.get(hurt[1]).hurtServer(level, level.damageSources().playerAttack(player), 1.0F); + } for (Mob mob : mobs) { if (mob.isRemoved()) continue; mob.checkDespawn(); if (mob.isRemoved()) continue; level.tickNonPassenger(mob); } + if (!heartPositions.isEmpty()) level.tickBlockEntities(); managerTick.invoke(manager); + // Created mobs that made it into the level, in creation order. + for (; adopted < created.size(); adopted++) { + Mob c = created.get(adopted); + if (!c.isRemoved()) { + mobs.add(c); + brains.add(c.getBrain()); + seeds.add(1000L + adopted); + } + } for (int i = 0; i < mobs.size(); i++) print(t, i, mobs.get(i)); + for (BlockPos h : heartPositions) printHeart(t, level, h); for (String sound : SOUNDS) out.println(t + " sound " + sound); for (String line : TRACE) out.println(line); TRACE.clear(); } for (Mob mob : mobs) mob.discard(); + for (BlockPos h : heartPositions) level.setBlock(h, net.minecraft.world.level.block.Blocks.AIR.defaultBlockState(), 2 | 16); + factoryField.set(EntityTypes.CREAKING, creakingFactory); + this.getGameRules().set(GameRules.SPAWN_MOBS, spawnMobs, this); + this.getGameRules().set(GameRules.SPAWN_MONSTERS, spawnMonsters, this); managerTick.invoke(manager); out.flush(); } + /** A heart's block state and block entity, and the level random. */ + static void printHeart(int t, ServerLevel level, BlockPos at) throws Exception { + StringBuilder sb = new StringBuilder(); + sb.append(t).append(" heart ").append(pos(at)).append('\t') + .append(level.getBlockState(at).getValue(net.minecraft.world.level.block.CreakingHeartBlock.STATE).getSerializedName()); + if (level.getBlockEntity(at) instanceof net.minecraft.world.level.block.entity.CreakingHeartBlockEntity be) { + sb.append('\t').append(get(be, "ticker")).append(' ').append(get(be, "emitter")).append(' ').append(get(be, "outputSignal")) + .append(' ').append(get(be, "ticksExisted")); + Object info = get(be, "creakingInfo"); + sb.append(' ').append(info == null ? "none" : "linked"); + } + sb.append("\tlrng ").append(Long.toHexString(((java.util.concurrent.atomic.AtomicLong) field(net.minecraft.world.level.levelgen.LegacyRandomSource.class, "seed").get(level.getRandom())).get())); + out.println(sb); + } + /** * Every GateBehavior (RunOne and the gates of TradeWithVillager and VillagerMakeLove) shuffles * its behaviours with its own ShufflingList random, which RandomSource.create() seeds from the diff --git a/tools/test_entity_model_parity.py b/tools/test_entity_model_parity.py index 18ed6838f..a8d23bd33 100644 --- a/tools/test_entity_model_parity.py +++ b/tools/test_entity_model_parity.py @@ -54,6 +54,10 @@ EXTRAS = [ ('minecraft:skeleton_horse_baby#main', 'BabyHorseModel'), ('minecraft:zombie_horse_baby#main', 'BabyHorseModel'), ('minecraft:cave_spider#main', 'SpiderModel'), ('minecraft:stray#main', 'SkeletonModel'), + # BreezeWindLayer and BreezeEyesLayer bake their own layers into a BreezeModel; + # the creaking's emissive eyes layer is a CreakingModel. + ('minecraft:breeze#wind', 'BreezeModel'), ('minecraft:breeze#eyes', 'BreezeModel'), + ('minecraft:creaking#eyes', 'CreakingModel'), ] # Layers a renderer reuses for another entity under a different constant. SKIP_LAYERS = re.compile(r'(banner|bell|book|skull|head|chest|shulker_box|boat|cushion|conduit|leash|arrow|trident|' @@ -156,6 +160,8 @@ SPECIES = { 'skeleton': SKELETON, 'stray': SKELETON, 'wither_skeleton': SKELETON, 'bogged': SKELETON, 'piglin': PIGLIN, 'piglin_brute': PIGLIN, 'cat': FELINE, 'ocelot': FELINE, + 'breeze': [{'idle': 3}, {'shoot': 2}, {'slide': 4}, {'slideBack': 1}, {'inhale': 5}, {'longJump': 2}, + {'idle': 1, 'shoot': 6}, {'idle': 9, 'slideBack': 7, 'longJump': 3}, {'idle': 2, 'inhale': 0, 'slide': 8}], 'creaking': [{'canMove': F}, {'attackAnimationState': 2}, {'invulnerabilityAnimationState': 3}, {'deathAnimationState': 1}], 'evoker': ILLAGER, 'pillager': ILLAGER, 'vindicator': ILLAGER, 'illusioner': ILLAGER, 'sheep': [{'eatTick': t} for t in (2, 10, 36, 39)], diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index 5730d8b3d..d3a19f9a3 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -77,6 +77,27 @@ def scenarios(): 'player 12.5 -60 0.5', 'mob minecraft:villager 0.5 -60 0.5 0 51 persistent', ]) + # Breezes: idle, and fighting a player near, in, and beyond the inner jump circle. + add('breeze_alone', 200, ['mob minecraft:breeze 0.5 -60 0.5 90 61 persistent']) + add('breeze_player', 200, ['player 8.5 -60 0.5', 'mob minecraft:breeze 0.5 -60 0.5 0 62 persistent']) + add('breeze_close', 200, ['player 2.5 -60 1.5', 'mob minecraft:breeze 0.5 -60 0.5 0 63 persistent']) + add('breeze_far', 200, ['player 13.5 -60 6.5', 'mob minecraft:breeze 0.5 -60 0.5 0 64 persistent']) + # Creakings: the player faces +z, so it watches one and turns its back on the other. + add('creaking_alone', 200, ['mob minecraft:creaking 0.5 -60 0.5 90 71 persistent']) + add('creaking_watched', 200, ['player 0.5 -60 -7.5', 'mob minecraft:creaking 0.5 -60 0.5 180 72 persistent']) + add('creaking_behind', 200, ['player 0.5 -60 8.5', 'mob minecraft:creaking 0.5 -60 0.5 0 73 persistent']) + # Woken while watched, then free to hunt and hit once the player turns away. + add('creaking_attack', 240, ['player 0.5 -60 -7.5 turn=40,180', 'mob minecraft:creaking 0.5 -60 0.5 180 74 persistent']) + # A creaking heart in a pale oak trunk: by night it spawns its creaking near a player, + # by day it sleeps, without logs it is uprooted, with no player near it waits. + TRUNK = ['block 3 -60 3 minecraft:pale_oak_log[axis=y]', 'block 3 -58 3 minecraft:pale_oak_log[axis=y]'] + add('heart_night', 300, TRUNK + ['heart 3 -59 3 minecraft:creaking_heart[axis=y,creaking_heart_state=awake,natural=true]', 'player 0.5 -60 -6.5'], 'time=18000 spawning') + add('heart_day', 120, TRUNK + ['heart 3 -59 3 minecraft:creaking_heart[axis=y,creaking_heart_state=awake,natural=true]', 'player 0.5 -60 -6.5'], 'spawning') + add('heart_uprooted', 60, ['heart 3 -59 3 minecraft:creaking_heart[axis=y,creaking_heart_state=awake,natural=true]', 'player 0.5 -60 -6.5'], 'time=18000 spawning') + # A player hits the heart's creaking: no damage, but the heart bleeds resin and trails. + add('heart_hurt', 260, TRUNK + ['heart 3 -59 3 minecraft:creaking_heart[axis=y,creaking_heart_state=awake,natural=true]', 'player 0.5 -60 -6.5', + 'hurt 60 0', 'hurt 64 0', 'hurt 200 0'], 'time=18000 spawning') + add('heart_far', 120, TRUNK + ['heart 3 -59 3 minecraft:creaking_heart[axis=y,creaking_heart_state=awake,natural=true]', 'player 40.5 -60 0.5'], 'time=18000 spawning') return s @@ -94,7 +115,7 @@ def write_scenarios(path, chosen): elif f[0] == 'mob': f[2] = repr(float(f[2]) + ox) f[4] = repr(float(f[4]) + oz) - elif f[0] == 'block': + elif f[0] in ('block', 'heart'): f[1] = str(int(f[1]) + ox) f[3] = str(int(f[3]) + oz) elif f[0] == 'fill': @@ -123,6 +144,9 @@ def parse(path): if parts[1] == 'trace': cur.setdefault('trace', {}).setdefault(t, []).append(parts[2]) continue + if parts[1] == 'heart': + cur.setdefault('hearts', {}).setdefault(t, []).append(line.split(' ', 2)[2]) + continue mob = int(parts[1]) row = {} if len(parts) > 2: @@ -210,7 +234,12 @@ def compare(vanilla, rust, fields=None): report.extend(' ' + d for d in diffs[:12]) if first is not None: clean = False - # Sounds: first differing tick. + # Creaking hearts (state, block entity, level random): first differing tick. + for t in sorted(set(v.get('hearts', {})) | set(r.get('hearts', {}))): + if v.get('hearts', {}).get(t) != r.get('hearts', {}).get(t): + report.append(f'{name}: hearts differ at tick {t}: vanilla {v.get("hearts", {}).get(t)} | horizon {r.get("hearts", {}).get(t)}') + clean = False + break for t in sorted(set(v['sounds']) | set(r['sounds'])): if v['sounds'].get(t, []) != r['sounds'].get(t, []): report.append(f'{name}: sounds differ at tick {t}: vanilla {v["sounds"].get(t, [])} | horizon {r["sounds"].get(t, [])}')