diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index a655c2dcd..a9c3052b7 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -194,7 +194,9 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { | "minecraft:donkey" | "minecraft:mule" | "minecraft:skeleton_horse" - | "minecraft:zombie_horse" => { + | "minecraft:zombie_horse" + | "minecraft:llama" + | "minecraft:trader_llama" => { map.insert("Tame".into(), Tag::Byte(i8::from(m.extra.tame))); map.insert("Temper".into(), Tag::Int(i32::from(m.extra.variant3))); if let Some(owner) = m.extra.owner { @@ -204,6 +206,9 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { let v = i32::from(m.extra.variant) | i32::from(m.extra.variant2) << 8; map.insert("Variant".into(), Tag::Int(v)); } + if crate::mobs::llama::is_llama(m.species()) { + crate::mobs::llama::to_nbt(m, map); + } map.insert("ChestedHorse".into(), Tag::Byte(i8::from(m.extra.chested))); let mut equipment = Vec::new(); if m.extra.saddled { @@ -478,6 +483,9 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - let v = number(tag.get("Variant")).unwrap_or(0) as i32; m.extra.variant = (v & 0xFF).clamp(0, 6) as u8; m.extra.variant2 = ((v >> 8) & 0xFF).clamp(0, 4) as u8; + if crate::mobs::llama::is_llama(m.species()) { + crate::mobs::llama::from_nbt(&mut m, tag); + } m.extra.chested = flag(tag, "ChestedHorse"); let eq = tag.get("equipment"); m.extra.saddled = eq.and_then(|e| e.get("saddle")).is_some(); @@ -565,6 +573,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - if m.species() == crate::mobs::Species::Wither { m.extra.counter = number(tag.get("Invul")).unwrap_or(0) as i32; } + m.extra.leash_pending = crate::mobs::leash::pending_from_nbt(tag.get("leash")); if m.species() == crate::mobs::Species::Ravager { m.extra.counter = number(tag.get("AttackTick")).unwrap_or(0) as i32; m.extra.counter2 = number(tag.get("StunTick")).unwrap_or(0) as i32; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 66925932c..065433937 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -27,7 +27,9 @@ mod frames; mod game_mode; mod growth; mod jukebox; +mod leads; mod lightning; +mod llamas; mod machines; mod maps; mod minecarts; @@ -59,6 +61,7 @@ mod tnt; mod totem; mod trading; mod trident; +mod wandering_trader; mod wither; use horizon_client::{ Result, @@ -1648,6 +1651,7 @@ impl Game<'_> { || self.interact_boat() || self.interact_cart() || self.interact_mob()? + || self.interact_knot() { return Ok(()); } @@ -3999,6 +4003,7 @@ impl Game<'_> { self.cart_geometry(camera, alpha, &mut out); self.beacon_geometry(camera, alpha, &mut out); self.fishing_geometry(camera, alpha, &mut out); + self.leash_geometry(camera, alpha, &mut out); self.trident_geometry(camera, alpha, &mut out); self.rocket_geometry(camera, alpha, &mut out); // Particles (ParticleEngine.extract): camera-facing quads. @@ -4674,6 +4679,7 @@ impl Game<'_> { self.spawn = None; self.spawn_search = 0; self.mobs.clear(); + self.creatures.reset_trader(); self.arrows.clear(); self.dropped.clear(); self.particles.clear(); @@ -6498,6 +6504,7 @@ impl Game<'_> { self.save_entities()?; self.save_maps(); self.save_fight(); + self.save_wandering_trader(); self.save_stats(); self.save_advancements(); self.level.selected_slot = self.selected as i32; diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index f2cbf245e..9bf3b9c99 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -32,6 +32,8 @@ pub(super) struct Creatures { pub pearl_cooldown: u32, /// Ticks left of the elder guardian's apparition (MobAppearanceParticle). pub elder_apparition: i32, + /// The wandering trader spawner's clock. + pub trader: super::wandering_trader::Spawner, } /// MobCategory caps (maxInstancesPerChunk with the 17x17 spawnable chunk area). const CATEGORIES: [(&str, usize); 7] = [ @@ -115,6 +117,12 @@ fn seen(m: &Mob) -> Seen { bed: (m.species() == Species::Villager) .then_some(m.extra.bed) .flatten(), + yaw: m.yaw, + velocity: m.velocity, + leash: m.extra.leash, + caravan: horizon_client::mobs::caravan::head_of(m), + delay: m.extra.ints[5], + hurt_by: m.ai.last_hurt_by.map(|w| (w, m.ai.last_hurt_by_time)), } } impl Game<'_> { @@ -150,6 +158,8 @@ impl Game<'_> { gold_armor: self.wearing_gold(), hurt_by: self.player_hurt_by(), last_hurt: self.combat.last_hurt_mob.map(|(id, at)| (Who::Mob(id), at)), + velocity: p.velocity, + yaw: self.yaw, }) } /// Biome facts at a position for finalizeSpawn and variant rules. @@ -259,13 +269,18 @@ impl Game<'_> { "on_ground": m.on_ground, "variant": m.extra.variant, "color": m.extra.color, + "leash": m.extra.leash.map(|h| format!("{h:?}")), + "tame": m.extra.tame, + "temper": m.extra.variant3, + "chested": m.extra.chested, + "head": m.extra.head.as_deref(), }) }) .collect(); serde_json::json!({ "count": self.mobs.len(), "near": list, "projectiles": self.creatures.projectiles.len() }) } /// Highest motion-blocking (no leaves) block + 1 (Heightmap MOTION_BLOCKING_NO_LEAVES). - fn motion_top(&self, x: i32, z: i32) -> i32 { + pub(super) fn motion_top(&self, x: i32, z: i32) -> i32 { let top = if self.dim == Dim::Nether { 127 } else { 319 }; for y in (horizon_client::chunk::MIN_Y..=top).rev() { let f = self.res.facts.get(self.world.block(x, y, z)); @@ -601,6 +616,8 @@ impl Game<'_> { self.spawn_generation_creatures(key.0, key.1); } self.tick_inhabited(); + self.tick_leads(); + self.tick_wandering_trader(); self.spawn_natural(); let snapshot: Vec = self.mobs.iter().map(seen).collect(); let mut events = Vec::new(); @@ -970,6 +987,7 @@ impl Game<'_> { } }, MobEvent::Breed { parent, partner } => self.breed(parent, partner), + MobEvent::LeashBreak { mob, drop, sound } => self.break_leash(mob, drop, sound), MobEvent::GiftLoot { table, at } => { let drops = self.res @@ -1069,6 +1087,9 @@ impl Game<'_> { let other = q.clone().unwrap_or_else(|| p.clone()); let mut r = self.world.random.clone(); horizon_client::mobs::equine::inherit(child, &p, &other, &mut r); + if horizon_client::mobs::llama::is_llama(p.species()) { + horizon_client::mobs::llama::offspring(child, &p, &other, &mut r); + } // Horse.getBreedOffspring: coat from either parent or new. if p.species() == Species::Horse && other.species() == Species::Horse { let c = r.next_int_bound(9).unwrap_or(0); @@ -1651,6 +1672,13 @@ impl Game<'_> { if self.name_mob(index) { return Ok(true); } + { + let item = self.held().map(|h| h.item.to_string()).unwrap_or_default(); + if self.interact_leash(index, &item) { + self.swing_arm(); + return Ok(true); + } + } let held = self.held().cloned(); let item = held .as_ref() @@ -1997,7 +2025,7 @@ impl Game<'_> { } Ok(true) } - fn damage_held_tool(&mut self) { + pub(super) fn damage_held_tool(&mut self) { if self.creative { return; } @@ -2300,6 +2328,7 @@ fn eat_sound(s: Species) -> &'static str { match s { Species::Pig => "entity.pig.eat", Species::Horse | Species::Donkey | Species::Mule => "entity.horse.eat", + Species::Llama | Species::TraderLlama => "entity.llama.eat", Species::Goat => "entity.goat.eat", Species::Fox => "entity.fox.eat", Species::Cat => "entity.cat.eat", diff --git a/crates/horizon-client/src/game/leads.rs b/crates/horizon-client/src/game/leads.rs new file mode 100644 index 000000000..dfcb34746 --- /dev/null +++ b/crates/horizon-client/src/game/leads.rs @@ -0,0 +1,450 @@ +//! Leads on the game side: putting them on and taking them off mobs +//! (`Entity.interact`'s leash part), fence knots (`LeadItem.useOn` and +//! `LeashFenceKnotEntity.interact`), loading and saving who holds what, +//! breaking, and drawing the rope (`LeashFeatureRenderer`) and the knot. +use super::Game; +use horizon_client::{ + items::ItemStack, + mesher::Vertex, + mobs::leash::{self, Holder, Pending}, +}; +use horizon_core::random::RandomSource; +use horizon_world::nbt::Tag; + +/// `Vec3.yRot(angle)`. +fn rot_y(v: glam::DVec3, angle: f64) -> glam::DVec3 { + let (s, c) = (angle.sin(), angle.cos()); + glam::DVec3::new(v.x * c + v.z * s, v.y, v.z * c - v.x * s) +} +fn pack_light(light: u8) -> u32 { + (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8) +} +fn abgr(r: f32, g: f32, b: f32) -> u32 { + let c = |v: f32| (v * 255.0) as u32 & 255; + 0xFF00_0000 | c(b) << 16 | c(g) << 8 | c(r) +} +impl Game<'_> { + fn lead_sound(&mut self, sound: &str, at: [f64; 3]) { + self.audio + .play(&format!("minecraft:item.lead.{sound}"), Some(at), 1.0, 1.0); + } + /// `Leashable.canHaveALeashAttachedTo` for the mob at `index` and a + /// holder whose box centre is `center`: within snapping range and + /// leashable. + fn can_attach_lead(&self, index: usize, center: glam::DVec3) -> bool { + let m = &self.mobs[index]; + if !leash::can_be_leashed(m) || !m.alive() { + return false; + } + let b = m.bounds(); + let (lo, hi) = (b.min_position(), b.max_position()); + let mine = glam::DVec3::new( + (lo.x + hi.x) / 2.0, + (lo.y + hi.y) / 2.0, + (lo.z + hi.z) / 2.0, + ); + mine.distance(center) <= leash::SNAP + } + fn player_center(&self) -> glam::DVec3 { + self.player.as_ref().map_or(glam::DVec3::ZERO, |p| { + glam::DVec3::new( + p.position.x, + p.position.y + f64::from(p.dimensions.height) / 2.0, + p.position.z, + ) + }) + } + /// The mobs on the player's lead within 32 blocks of a point. + fn player_leashed(&self, around: glam::DVec3) -> Vec { + (0..self.mobs.len()) + .filter(|&i| { + let m = &self.mobs[i]; + m.extra.leash == Some(Holder::Player) + && (m.position.x - around.x).abs() <= 16.0 + && (m.position.y - around.y).abs() <= 16.0 + && (m.position.z - around.z).abs() <= 16.0 + }) + .collect() + } + fn drop_lead_item(&mut self, at: [f64; 3]) { + let r = &mut self.world.random; + let v = [ + f64::from(r.next_float()) * 0.2 - 0.1, + 0.2, + f64::from(r.next_float()) * 0.2 - 0.1, + ]; + self.spawn_item(ItemStack::new("minecraft:lead", 1), at, v, 10); + } + /// `Leashable.dropLeash` / `removeLeash`: the lead falls as an item. + pub(super) fn break_leash(&mut self, id: u32, drop: bool, sound: bool) { + let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) else { + return; + }; + if m.extra.leash.take().is_none() { + return; + } + let at = [m.position.x, m.position.y, m.position.z]; + if sound { + self.lead_sound("break", at); + } + if drop { + self.drop_lead_item(at); + } + } + /// Holders read from a save become real once the entity is found; a + /// holder that never shows up drops the lead after 100 ticks. + pub(super) fn tick_leads(&mut self) { + let player_uuid = self.level.player_uuid.unwrap_or([0, 0, 0, 1]); + for i in 0..self.mobs.len() { + let Some(pending) = self.mobs[i].extra.leash_pending else { + continue; + }; + let holder = match pending { + Pending::Knot(p) => Some(Holder::Knot(p)), + Pending::Uuid(u) if u == player_uuid => Some(Holder::Player), + Pending::Uuid(u) => self.mob_by_uuid(u).map(Holder::Mob), + }; + let m = &mut self.mobs[i]; + if let Some(h) = holder { + m.extra.leash = Some(h); + m.extra.leash_pending = None; + } else if m.age > 100 { + m.extra.leash_pending = None; + let at = [m.position.x, m.position.y, m.position.z]; + self.drop_lead_item(at); + } + } + } + /// The `leash` tag of a mob about to be saved. + pub(super) fn write_leash(&mut self, tag: &mut Tag, index: usize) { + let Tag::Compound(map) = tag else { return }; + map.remove(&"leash".into()); + let m = &self.mobs[index]; + let holder = m.extra.leash; + let pending = m.extra.leash_pending; + let uuid = match (holder, pending) { + (Some(Holder::Player), _) => Some(self.level.player_uuid.unwrap_or([0, 0, 0, 1])), + (Some(Holder::Mob(id)), _) => Some(self.mob_uuid(id)), + (_, Some(Pending::Uuid(u))) => Some(u), + _ => None, + }; + let value = match (holder, pending) { + (Some(h), _) => leash::to_nbt(h, uuid), + (None, Some(Pending::Knot(p))) => leash::to_nbt(Holder::Knot(p), None), + (None, Some(Pending::Uuid(u))) => leash::to_nbt(Holder::Player, Some(u)), + _ => None, + }; + if let Some(v) = value { + map.insert("leash".into(), v); + } + } + /// `Entity.interact`'s leash part for a mob. Returns whether it was used. + pub(super) fn interact_leash(&mut self, index: usize, item: &str) -> bool { + let sneaking = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft); + let id = self.mobs[index].id; + let at = self.mobs[index].center(); + if !self.mobs[index].alive() { + return false; + } + // Sneaking with mobs in hand: tie them to this one. + if sneaking && leash::can_be_leashed(&self.mobs[index]) && !self.mobs[index].is_baby() { + let b = self.mobs[index].bounds(); + let (lo, hi) = (b.min_position(), b.max_position()); + let center = glam::DVec3::new( + (lo.x + hi.x) / 2.0, + (lo.y + hi.y) / 2.0, + (lo.z + hi.z) / 2.0, + ); + let held = self.player_leashed(center); + let mut any = false; + for j in held { + if j != index && self.can_attach_lead(j, center) { + self.mobs[j].extra.leash = Some(Holder::Mob(id)); + any = true; + } + } + if any { + self.lead_sound("tied", at); + return true; + } + } + if item == "minecraft:shears" { + let mut dropped = false; + if self.mobs[index].extra.leash.is_some() { + self.break_leash(id, true, false); + dropped = true; + } + let others: Vec = self + .mobs + .iter() + .filter(|m| m.extra.leash == Some(Holder::Mob(id))) + .map(|m| m.id) + .collect(); + for o in others { + self.break_leash(o, true, false); + dropped = true; + } + if dropped { + self.audio + .play("minecraft:item.shears.snip", Some(at), 1.0, 1.0); + self.damage_held_tool(); + return true; + } + } + if self.mobs[index].extra.leash == Some(Holder::Player) { + let creative = self.creative; + self.break_leash(id, !creative, false); + self.lead_sound("untied", at); + return true; + } + if item == "minecraft:lead" { + let center = self.player_center(); + if self.can_attach_lead(index, center) { + if self.mobs[index].extra.leash.is_some() { + self.break_leash(id, true, false); + } + self.mobs[index].extra.leash = Some(Holder::Player); + self.lead_sound("tied", at); + // The lead is always used up. + if let Some(stack) = self.inventory[self.selected].as_mut() { + stack.count -= 1; + if stack.count == 0 { + self.inventory[self.selected] = None; + } + } + return true; + } + } + false + } + /// `LeadItem.useOn` and `LeashFenceKnotEntity.interact` on a fence. + pub(super) fn interact_knot(&mut self) -> bool { + let Some(hit) = self.pick() else { + return false; + }; + let name = self + .res + .facts + .get(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2])); + if !self + .res + .items + .block_tags + .get("minecraft:fences") + .is_some_and(|s| s.contains(&*name.name)) + { + return false; + } + let knot_pos = hit.pos; + let knot = leash::knot_state(knot_pos).center; + let center = glam::DVec3::new(knot.x, knot.y, knot.z); + let at = [center.x, center.y, center.z]; + let existing: Vec = (0..self.mobs.len()) + .filter(|&i| self.mobs[i].extra.leash == Some(Holder::Knot(knot_pos))) + .collect(); + let held_item = self.held().map(|s| s.item.to_string()); + let sneaking = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft); + // Shears snip every lead on the knot. + if held_item.as_deref() == Some("minecraft:shears") && !existing.is_empty() { + for i in existing { + let id = self.mobs[i].id; + self.break_leash(id, true, false); + } + self.audio + .play("minecraft:item.shears.snip", Some(at), 1.0, 1.0); + self.damage_held_tool(); + return true; + } + let in_hand = self.player_leashed(center); + // The knot is only made for the lead item, or when mobs already hang on it. + if held_item.as_deref() != Some("minecraft:lead") + && existing.is_empty() + && in_hand.is_empty() + { + return false; + } + let mut attached = false; + for j in in_hand { + if self.can_attach_lead(j, center) { + self.mobs[j].extra.leash = Some(Holder::Knot(knot_pos)); + attached = true; + } + } + if !attached && !sneaking { + let player = self.player_center(); + for i in existing { + if self.can_attach_lead(i, player) { + self.mobs[i].extra.leash = Some(Holder::Player); + attached = true; + } + } + } + if attached { + self.lead_sound("tied", at); + self.swing_arm(); + } + attached + } + /// `LeashFeatureRenderer` for every lead and `LeashKnotRenderer` for the knots. + pub(super) fn leash_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { + let atlas = &self.res.atlas; + let white = atlas.font.white(); + let uv = [ + [white.u0, white.v1], + [white.u1, white.v1], + [white.u1, white.v0], + [white.u0, white.v0], + ]; + let lerp3 = |a: horizon_core::geometry::Vec3, b: horizon_core::geometry::Vec3| { + glam::DVec3::new( + a.x + (b.x - a.x) * alpha, + a.y + (b.y - a.y) * alpha, + a.z + (b.z - a.z) * alpha, + ) + }; + let mut knots: Vec<[i32; 3]> = Vec::new(); + for m in &self.mobs { + let Some(holder) = m.extra.leash else { + continue; + }; + let body = f64::from( + m.previous_body_yaw + + horizon_client::mobs::living::wrap(m.body_yaw - m.previous_body_yaw) + * alpha as f32, + ) + .to_radians(); + let offset = leash::leash_offset(m); + let offset = rot_y(glam::DVec3::from_array(offset), -body); + let start = lerp3(m.previous, m.position) + offset; + let end = match holder { + Holder::Knot(p) => { + if !knots.contains(&p) { + knots.push(p); + } + glam::DVec3::new( + f64::from(p[0]) + 0.5, + f64::from(p[1]) + 0.375 + 0.2, + f64::from(p[2]) + 0.5, + ) + } + Holder::Mob(id) => { + let Some(o) = self.mobs.iter().find(|o| o.id == id) else { + continue; + }; + lerp3(o.previous, o.position) + glam::DVec3::new(0.0, o.eye_height() * 0.7, 0.0) + } + Holder::Player => { + let Some(p) = self.player.as_ref() else { + continue; + }; + self.player_rope_hold(p, alpha) + } + }; + let light = |p: glam::DVec3| { + self.world + .light(p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32) + }; + // Block and sky light averaged between the two ends. + let (a, b) = (light(start), light(end)); + let packed = pack_light((((a >> 4) + (b >> 4)) / 2) << 4 | (((a & 15) + (b & 15)) / 2)); + let d = end - start; + let k = 1.0 / (d.x * d.x + d.z * d.z).sqrt().max(1e-6) * 0.05 / 2.0; + let (dx_off, dz_off) = (d.z * k, d.x * k); + let point = |step: i32, fudge: f64| { + let progress = f64::from(step) / 24.0; + let y = if d.y > 0.0 { + d.y * progress * progress + } else { + d.y - d.y * (1.0 - progress) * (1.0 - progress) + }; + let base = start + glam::DVec3::new(d.x * progress, y, d.z * progress); + ( + base + glam::DVec3::new(-dx_off, fudge, dz_off), + base + glam::DVec3::new(dx_off, 0.05 - fudge, -dz_off), + ) + }; + for (fudge, backwards) in [(0.05, false), (0.0, true)] { + for step in 0..24 { + let shade = |s: i32| { + let dark = s % 2 == i32::from(backwards); + let f = if dark { 0.7 } else { 1.0 }; + abgr(0.5 * f, 0.4 * f, 0.3 * f) + }; + let (a0, b0) = point(step, fudge); + let (a1, b1) = point(step + 1, fudge); + let color = shade(step); + // Both faces: the leash is not culled. + for quad in [[a0, b0, b1, a1], [a1, b1, b0, a0]] { + for (v, uv) in quad.iter().zip(uv) { + out.push(Vertex { + pos: (*v - camera).as_vec3().to_array(), + uv, + layer: 0, + color, + light: packed, + }); + } + } + } + } + } + // The knots: a 6 by 8 by 6 pixel block on the fence post. + static KNOT: std::sync::OnceLock> = + std::sync::OnceLock::new(); + let model = KNOT.get_or_init(|| { + horizon_client::mobs::load_model(&self.options.resources, "minecraft:leash_knot#main") + }); + let Some(model) = model else { return }; + let Some(r) = atlas.sprites.get("entity/lead_knot/lead_knot").copied() else { + return; + }; + for p in knots { + let state = leash::knot_state(p); + let at = + glam::DVec3::new(state.position.x, state.position.y, state.position.z) - camera; + let base = glam::Mat4::from_translation(at.as_vec3()) + * glam::Mat4::from_scale(glam::Vec3::new(-1.0, -1.0, 1.0)); + let poses = horizon_client::mobs::anim::Poses::new(model); + let light = pack_light(self.world.light(p[0], p[1], p[2])); + horizon_client::mobs::render::draw( + model, + base, + &poses, + [r.u0, r.v0, r.u1, r.v1], + 0xFFFF_FFFF, + light, + 0, + out, + ); + } + } + /// `Player.getRopeHoldPosition` (and `LocalPlayer`'s in first person). + fn player_rope_hold( + &self, + p: &horizon_client::motion::PlayerMotion, + alpha: f64, + ) -> glam::DVec3 { + let pos = glam::DVec3::new(p.position.x, p.position.y, p.position.z); + let _ = alpha; + if self.camera_type.first_person() { + let (yaw, pitch) = ( + f64::from(self.yaw.to_radians()), + f64::from(self.pitch.to_radians()), + ); + let v = glam::DVec3::new(-0.39, -0.6, 0.3); + // Vec3.xRot(-pitch) then yRot(-yaw). + let (s, c) = ((-pitch).sin(), (-pitch).cos()); + let v = glam::DVec3::new(v.x, v.y * c + v.z * s, v.z * c - v.y * s); + let eye = pos + glam::DVec3::new(0.0, f64::from(p.dimensions.eye_height), 0.0); + return rot_y(v, -yaw) + eye; + } + let yaw = f64::from(self.yaw.to_radians()); + let crouching = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft); + let v = glam::DVec3::new( + -0.22, + f64::from(p.dimensions.height) - 1.0, + if crouching { -0.2 } else { 0.07 }, + ); + pos + rot_y(v, -yaw) + } +} diff --git a/crates/horizon-client/src/game/llamas.rs b/crates/horizon-client/src/game/llamas.rs new file mode 100644 index 000000000..5b54f6719 --- /dev/null +++ b/crates/horizon-client/src/game/llamas.rs @@ -0,0 +1,144 @@ +//! Llamas on the game side: `AbstractChestedHorse.mobInteract` and +//! `Llama.handleEating` (wheat and hay), chests, carpets, shearing a carpet +//! off and riding. +use super::Game; +use horizon_client::{ + items::ItemStack, + mobs::{MobEvent, equine, llama}, +}; +use horizon_core::random::RandomSource; + +impl Game<'_> { + fn llama_sound(&mut self, index: usize, sound: &str, volume: f32) { + let at = self.mobs[index].center(); + let pitch = (self.world.random.next_float() - self.world.random.next_float()) * 0.2 + 1.0; + self.audio + .play(&format!("minecraft:{sound}"), Some(at), volume, pitch); + } + /// `Llama.handleEating`: wheat and hay bales heal, age up a baby, raise + /// the temper and, from a hay bale, put a tame adult in love. + fn feed_llama(&mut self, index: usize, item: &str) -> bool { + let (age_up, temper, heal) = match item { + "minecraft:wheat" => (10, 3, 2.0), + "minecraft:hay_block" => (90, 6, 10.0), + _ => return false, + }; + let m = &mut self.mobs[index]; + let mut used = false; + if item == "minecraft:hay_block" && m.extra.tame && m.extra.age == 0 && m.extra.in_love <= 0 + { + m.extra.in_love = 600; + m.extra.love_player = true; + used = true; + } + if m.health < m.attrs.max_health { + m.health = (m.health + heal).min(m.attrs.max_health); + used = true; + } + let mut happy = false; + if m.is_baby() && !m.extra.age_locked { + m.extra.age = (m.extra.age + age_up * 20).min(0); + used = true; + happy = true; + } + if (used || !m.extra.tame) && i32::from(m.extra.variant3) < llama::MAX_TEMPER { + m.extra.variant3 = (i32::from(m.extra.variant3) + temper).min(llama::MAX_TEMPER) as u8; + used = true; + } + let at = m.center(); + if happy { + let _ = self.handle_mob_events(vec![MobEvent::Particles { + kind: "happy_villager", + at, + count: 1, + }]); + } + if !used { + return false; + } + self.llama_sound(index, "entity.llama.eat", 1.0); + self.consume_held(); + true + } + /// `AbstractChestedHorse.mobInteract` and `AbstractHorse.mobInteract` for + /// llamas and trader llamas. Returns whether the click was used. + pub(super) fn interact_llama(&mut self, index: usize, item: &str) -> bool { + let m = &self.mobs[index]; + if !m.alive() || Some(m.id) == self.riding { + return false; + } + let sneaking = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft); + let (baby, tamed, vehicle) = (m.is_baby(), m.extra.tame, m.rider.is_some()); + let open_inventory = !baby && tamed && sneaking; + if !vehicle && !open_inventory && !item.is_empty() { + if self.mobs[index].kind.food.iter().any(|f| f == item) { + return self.feed_llama(index, item); + } + if !tamed { + let mut events = Vec::new(); + equine::make_mad(&mut self.mobs[index], &mut events); + let _ = self.handle_mob_events(events); + return true; + } + if !self.mobs[index].extra.chested && item == "minecraft:chest" { + self.mobs[index].extra.chested = true; + self.llama_sound(index, "entity.llama.chest", 1.0); + self.consume_held(); + return true; + } + } + // AbstractHorse.mobInteract. + if vehicle || baby { + return false; + } + if tamed && sneaking { + // The horse inventory screen is not available yet. + return true; + } + let m = &self.mobs[index]; + let carpet = |i: &str| i.ends_with("_carpet") && i.starts_with("minecraft:"); + if !item.is_empty() { + if item == "minecraft:shears" && m.extra.head.as_deref().is_some_and(carpet) { + // Equippable.canBeSheared: the carpet comes off. + let at = m.center(); + let carpet = self.mobs[index].extra.head.take().unwrap_or_default(); + self.audio + .play("minecraft:item.llama_carpet.unequip", Some(at), 1.0, 1.0); + self.spawn_item(ItemStack::new(&carpet, 1), at, [0.0, 0.2, 0.0], 10); + self.damage_held_tool(); + return true; + } + if carpet(item) && m.extra.head.is_none() { + self.mobs[index].extra.head = Some(item.into()); + self.llama_sound(index, "entity.llama.swag", 1.0); + self.consume_held(); + return true; + } + } + // TraderLlama.doPlayerRide: not while a wandering trader leads it. + if self.is_led_by_trader(index) { + return true; + } + // doPlayerRide; mounting drops a lead. + let id = self.mobs[index].id; + self.break_leash(id, true, false); + let m = &mut self.mobs[index]; + m.extra.flag = false; + m.extra.counter = 0; + self.yaw = m.yaw; + self.riding = Some(m.id); + self.mount.reset_jump(); + self.trigger_player("minecraft:started_riding"); + true + } + fn is_led_by_trader(&self, index: usize) -> bool { + let m = &self.mobs[index]; + m.species() == horizon_client::mobs::Species::TraderLlama + && matches!( + m.extra.leash, + Some(horizon_client::mobs::leash::Holder::Mob(id)) + if self.mobs.iter().any(|o| o.id == id + && o.species() == horizon_client::mobs::Species::WanderingTrader) + ) + } +} diff --git a/crates/horizon-client/src/game/mounts.rs b/crates/horizon-client/src/game/mounts.rs index 3865dfc82..f46e81b0c 100644 --- a/crates/horizon-client/src/game/mounts.rs +++ b/crates/horizon-client/src/game/mounts.rs @@ -17,6 +17,7 @@ fn seat(s: Species) -> f64 { Species::Pig => 0.86875, Species::Strider => 1.7, Species::Horse => 1.44375, + Species::Llama | Species::TraderLlama => 1.37, Species::Donkey => 1.1125, Species::Mule => 1.2125, _ => 1.31875, @@ -31,6 +32,12 @@ pub(super) struct MountState { pub(super) jump_scale: f32, was_jumping: bool, } +impl MountState { + pub(super) fn reset_jump(&mut self) { + self.jump_ticks = 0; + self.jump_scale = 0.0; + } +} impl Game<'_> { fn mount_index(&self) -> Option { let id = self.riding?; @@ -96,6 +103,9 @@ impl Game<'_> { if matches!(species, Species::Pig | Species::Strider) { return self.interact_steerable(index, item); } + if horizon_client::mobs::llama::is_llama(species) { + return self.interact_llama(index, item); + } if !equine::is_equine(species) || !m.alive() || Some(m.id) == self.riding { return false; } @@ -306,6 +316,20 @@ impl Game<'_> { m.position.z + f64::from(0.5 * scale * yaw.cos()), ); } + if horizon_client::mobs::llama::is_llama(m.species()) { + // The passenger attachment (0, 1.37, -0.3), half of it for a baby. + let (y, z) = if m.is_baby() { + (0.81, -0.15) + } else { + (1.37, -0.3) + }; + let yaw = f64::from(m.yaw.to_radians()); + at = Vec3::new( + m.position.x - z * yaw.sin(), + m.position.y + y - 0.6, + m.position.z + z * yaw.cos(), + ); + } if let Some(p) = self.player.as_mut() { self.previous_position = p.position; p.position = at; diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 548ae34ee..ad3d26356 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -269,6 +269,18 @@ impl Game<'_> { } self.persist.raw.insert(id, tag); } + /// The mob that was loaded or saved with a UUID. + pub(super) fn mob_by_uuid(&self, uuid: [i32; 4]) -> Option { + self.persist + .uuids + .iter() + .find(|(id, u)| **u == uuid && self.mobs.iter().any(|m| m.id == **id)) + .map(|(id, _)| *id) + } + /// A mob's UUID, made up for new ones. + pub(super) fn mob_uuid(&mut self, id: u32) -> [i32; 4] { + self.uuid_for(id) + } fn uuid_for(&mut self, id: u32) -> [i32; 4] { *self.persist.uuids.entry(id).or_insert_with(random_uuid) } @@ -322,7 +334,8 @@ impl Game<'_> { for i in mobs { let id = self.mobs[i].id; let uuid = self.uuid_for(id); - let tag = entity_nbt::mob_to_nbt(&self.mobs[i], uuid, self.persist.raw.get(&id)); + let mut tag = entity_nbt::mob_to_nbt(&self.mobs[i], uuid, self.persist.raw.get(&id)); + self.write_leash(&mut tag, i); out.entry(chunk_of(self.mobs[i].position)) .or_default() .push(tag); diff --git a/crates/horizon-client/src/game/trading.rs b/crates/horizon-client/src/game/trading.rs index d7070b3c8..622244645 100644 --- a/crates/horizon-client/src/game/trading.rs +++ b/crates/horizon-client/src/game/trading.rs @@ -174,6 +174,8 @@ impl Game<'_> { mob: Some(m.id), name: m.custom_name.clone(), }; + // setTradingPlayer: a wandering trader stands still while trading. + self.mobs[index].extra.flag2 = species == Species::WanderingTrader; self.open_merchant_state(state); Ok(true) } @@ -187,6 +189,7 @@ impl Game<'_> { if state.progress() { m.extra.variant3 = state.level.clamp(1, 5) as u8; } + m.extra.flag2 = false; let trade = m.extra.trade.get_or_insert_default(); trade.xp = state.xp; trade.offers = state.offers.clone(); diff --git a/crates/horizon-client/src/game/wandering_trader.rs b/crates/horizon-client/src/game/wandering_trader.rs new file mode 100644 index 000000000..b336cdf0b --- /dev/null +++ b/crates/horizon-client/src/game/wandering_trader.rs @@ -0,0 +1,245 @@ +//! `WanderingTraderSpawner`: every 1200 ticks the spawn delay counts down; +//! when it runs out a trader may appear near the player (or the nearest +//! bell), bringing two llamas on leads, and wanders off after two days. +use super::{Dim, Game, creatures::Creatures}; +use horizon_client::{ + mobs::{Species, leash::Holder, spawning, trader}, + save::{read_dat, write_dat}, +}; +use horizon_core::random::RandomSource; +use horizon_world::nbt::Tag; + +const TICK_DELAY: i32 = 1200; +const SPAWN_DELAY: i32 = 24000; +const MIN_CHANCE: i32 = 25; +const MAX_CHANCE: i32 = 75; +const ATTEMPTS: i32 = 10; + +/// The spawner's clock and the `WanderingTraderData` saved with the world. +pub(super) struct Spawner { + tick_delay: i32, + spawn_delay: i32, + chance: i32, + loaded: bool, + dirty: bool, +} +impl Default for Spawner { + fn default() -> Self { + Self { + tick_delay: TICK_DELAY, + spawn_delay: SPAWN_DELAY, + chance: MIN_CHANCE, + loaded: false, + dirty: false, + } + } +} +impl Creatures { + /// A fresh spawner for a newly opened world. + pub(super) fn reset_trader(&mut self) { + self.trader = Spawner::default(); + } +} +impl Game<'_> { + fn trader_path(&self) -> std::path::PathBuf { + self.world_root + .join("data") + .join("minecraft") + .join("wandering_trader.dat") + } + fn load_trader_data(&mut self) { + if self.creatures.trader.loaded { + return; + } + let tag = read_dat(&self.trader_path()); + let data = tag.as_ref().and_then(|t| t.get("data")); + let get = |k: &str, d: i32| match data.and_then(|d| d.get(k)) { + Some(Tag::Int(v)) => *v, + _ => d, + }; + let t = &mut self.creatures.trader; + t.spawn_delay = get("spawn_delay", SPAWN_DELAY); + t.chance = get("spawn_chance", MIN_CHANCE); + t.loaded = true; + } + pub(super) fn save_wandering_trader(&mut self) { + if !self.creatures.trader.loaded || !self.creatures.trader.dirty { + return; + } + let t = &self.creatures.trader; + let tag = Tag::compound([ + ( + "data", + Tag::compound([ + ("spawn_delay", Tag::Int(t.spawn_delay)), + ("spawn_chance", Tag::Int(t.chance)), + ]), + ), + ("DataVersion", Tag::Int(horizon_world::DATA_VERSION)), + ]); + if write_dat(&self.trader_path(), tag).is_ok() { + self.creatures.trader.dirty = false; + } + } + /// `WanderingTraderSpawner.tick`. + pub(super) fn tick_wandering_trader(&mut self) { + if self.dim != Dim::Overworld + || self.player.is_none() + || !self.ui.rules.bool("spawn_wandering_traders") + { + return; + } + self.load_trader_data(); + self.creatures.trader.tick_delay -= 1; + if self.creatures.trader.tick_delay > 0 { + return; + } + self.creatures.trader.tick_delay = TICK_DELAY; + let t = &mut self.creatures.trader; + t.spawn_delay -= TICK_DELAY; + t.dirty = true; + if t.spawn_delay > 0 { + return; + } + t.spawn_delay = SPAWN_DELAY; + let chance = t.chance; + t.chance = (chance + 25).clamp(MIN_CHANCE, MAX_CHANCE); + if self.world.random.next_int_bound(100).unwrap_or(100) <= chance && self.spawn_trader() { + self.creatures.trader.chance = MIN_CHANCE; + } + } + /// `WanderingTraderSpawner.spawn`. + fn spawn_trader(&mut self) -> bool { + let Some(p) = self.player.as_ref().map(|p| p.position) else { + return true; + }; + if self.world.random.next_int_bound(10).unwrap_or(1) != 0 { + return false; + } + let player_pos = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]; + let reference = self.nearest_bell(player_pos, 48).unwrap_or(player_pos); + let Some(pos) = self.find_trader_spawn_near(reference, 48) else { + return false; + }; + if !self.trader_has_space(pos) { + return false; + } + let biome = self.world.chunks.get(&(pos[0] >> 4, pos[2] >> 4)).map(|c| { + self.res + .biomes + .get(c.biome(pos[0], pos[1], pos[2])) + .name + .clone() + }); + if biome.is_some_and(|b| { + self.res + .mob_data + .biome_has("minecraft:without_wandering_trader_spawns", &b) + }) { + return false; + } + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]), + f64::from(pos[2]) + 0.5, + ]; + let Some(id) = self.spawn_mob("minecraft:wandering_trader", at, true) else { + return false; + }; + for _ in 0..2 { + self.spawn_trader_llama(id, 4); + } + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + m.extra.ints[5] = trader::DESPAWN_DELAY; + m.extra.point = Some([ + f64::from(reference[0]), + f64::from(reference[1]), + f64::from(reference[2]), + ]); + m.extra.home = Some(reference); + m.extra.ints[4] = 16; + } + true + } + /// `tryToSpawnLlamaFor`: a trader llama near the trader, on its lead. + fn spawn_trader_llama(&mut self, trader: u32, radius: i32) { + let Some(at) = self.mobs.iter().find(|m| m.id == trader).map(|m| { + [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ] + }) else { + return; + }; + let Some(pos) = self.find_trader_spawn_near(at, radius) else { + return; + }; + let spot = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]), + f64::from(pos[2]) + 0.5, + ]; + if let Some(id) = self.spawn_mob("minecraft:trader_llama", spot, false) + && let Some(l) = self.mobs.iter_mut().find(|m| m.id == id) + { + // EntitySpawnReason.EVENT: grown up. + l.extra.age = 0; + l.extra.leash = Some(Holder::Mob(trader)); + } + } + /// `findSpawnPositionNear`: ten tries at a column near the reference + /// where the trader could stand. + fn find_trader_spawn_near(&mut self, reference: [i32; 3], radius: i32) -> Option<[i32; 3]> { + for _ in 0..ATTEMPTS { + let x = + reference[0] + self.world.random.next_int_bound(radius * 2).unwrap_or(0) - radius; + let z = + reference[2] + self.world.random.next_int_bound(radius * 2).unwrap_or(0) - radius; + if !self.world.loaded(x, z) { + continue; + } + let y = self.motion_top(x, z); + let w = self.mob_world_base(&[]); + if spawning::placement_ok(Species::WanderingTrader, &w, x, y, z) { + return Some([x, y, z]); + } + } + None + } + /// `hasEnoughSpace`: no collision in the 2 by 3 by 2 box. + fn trader_has_space(&self, pos: [i32; 3]) -> bool { + (0..=1).all(|dx| { + (0..=2).all(|dy| { + (0..=1).all(|dz| { + !self + .res + .facts + .get(self.world.block(pos[0] + dx, pos[1] + dy, pos[2] + dz)) + .full_collision + }) + }) + }) + } + /// The closest bell (`PoiTypes.MEETING`) within `range` blocks. + fn nearest_bell(&self, from: [i32; 3], range: i32) -> Option<[i32; 3]> { + let mut best: Option<([i32; 3], i32)> = None; + for x in from[0] - range..=from[0] + range { + for z in from[2] - range..=from[2] + range { + if !self.world.loaded(x, z) { + continue; + } + for y in (from[1] - range).max(horizon_client::chunk::MIN_Y)..=from[1] + range { + if &*self.res.facts.get(self.world.block(x, y, z)).name != "minecraft:bell" { + continue; + } + let d = (x - from[0]).pow(2) + (y - from[1]).pow(2) + (z - from[2]).pow(2); + if best.is_none_or(|b| d < b.1) { + best = Some(([x, y, z], d)); + } + } + } + } + best.map(|b| b.0) + } +} diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index a15b1e1c6..3e0d9a01a 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -10,6 +10,7 @@ pub mod allay; pub mod anim; pub mod aquatic; pub mod camel; +pub mod caravan; pub mod control; pub mod cube; pub mod data; @@ -22,7 +23,9 @@ pub mod guardian; pub mod hostile; pub mod illager; pub mod keyframes; +pub mod leash; pub mod living; +pub mod llama; pub mod nav; pub mod nether; pub mod path; @@ -34,6 +37,7 @@ pub mod shulker; pub mod spawning; pub mod species; pub mod tame; +pub mod trader; pub mod undead; pub mod vex; pub mod villager; @@ -473,6 +477,11 @@ pub struct Extra { pub meeting: Option<[i32; 3]>, /// Villager and wandering trader offers and experience. pub trade: Option>, + /// Who holds this mob's lead, a holder not yet found after loading, and + /// the spin the rope's torque gives it. + pub leash: Option, + pub leash_pending: Option, + pub leash_spin: f64, } #[derive(Clone, Debug)] pub struct Mob { @@ -662,6 +671,12 @@ pub enum MobEvent { table: &'static str, at: [f64; 3], }, + /// A lead snaps or loses its holder: the lead item drops when asked. + LeashBreak { + mob: u32, + drop: bool, + sound: bool, + }, } /// How a spawned-by-kind mob should be set up. #[derive(Clone, Debug, Default)] @@ -701,6 +716,16 @@ pub struct Seen { /// A villager's claimed job site and bed. pub job: Option<[i32; 3]>, pub bed: Option<[i32; 3]>, + pub yaw: f32, + pub velocity: Vec3, + /// Who holds this mob's lead. + pub leash: Option, + /// A llama's caravan head (its id plus one, 0 when not in a caravan). + pub caravan: u32, + /// A wandering trader's despawn delay. + pub delay: i32, + /// `getLastHurtByMob` and its timestamp. + pub hurt_by: Option<(Who, i32)>, } /// The player as mobs see it. #[derive(Clone, Debug)] @@ -723,6 +748,8 @@ pub struct PlayerView { pub hurt_by: Option<(Who, i64)>, /// `getLastHurtMob` and when. pub last_hurt: Option<(Who, i64)>, + pub velocity: Vec3, + pub yaw: f32, } pub struct MobWorld<'a> { pub world: &'a World, diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index d7a9e0084..1f07db6c1 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -87,6 +87,7 @@ pub enum Family { Wither, Allay, Villager, + Trader, } pub fn family(s: Species) -> Family { use Species as S; @@ -122,10 +123,16 @@ pub fn family(s: Species) -> Family { S::Wither => Family::Wither, S::Allay => Family::Allay, S::Villager => Family::Villager, + S::WanderingTrader => Family::Trader, S::Piglin | S::PiglinBrute | S::Hoglin | S::Zoglin => Family::Piglin, - S::Horse | S::Donkey | S::Mule | S::SkeletonHorse | S::ZombieHorse | S::Camel => { - Family::Equine - } + S::Horse + | S::Donkey + | S::Mule + | S::SkeletonHorse + | S::ZombieHorse + | S::Camel + | S::Llama + | S::TraderLlama => Family::Equine, S::Phantom => Family::Phantom, S::Enderman => Family::Enderman, S::Slime | S::MagmaCube => Family::Cube, @@ -169,6 +176,7 @@ pub fn register(m: &mut Mob) { Family::Wither => super::wither::register(m), Family::Allay => super::allay::register(m), Family::Villager => super::villager::register(m), + Family::Trader => super::trader::register(m), } } /// Mob.tick additions that run before the entity tick (creeper fuse, puffing). @@ -342,6 +350,7 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } else if m.air < 300 { m.air = (m.air + 4).min(300); } + if m.kind.flags.water_sensitive && (m.fluids.in_water || w.raining && w.can_see_sky(ex, ey, ez)) { @@ -368,6 +377,8 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { play_ambient(m, w, events); } } + // Entity.baseTick ends with Leashable.tickLeash. + super::leash::tick(m, w, events); } fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec) { let sound = match m.species() { @@ -564,7 +575,11 @@ 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::Villager | Species::WanderingTrader => super::villager::ai_step(m, w), + Species::Villager => super::villager::ai_step(m, w), + Species::WanderingTrader => { + super::villager::ai_step(m, w); + super::trader::ai_step(m, w); + } Species::Shulker => { super::shulker::tick(m, w, events); super::shulker::ai_step(m, w, events); @@ -632,7 +647,11 @@ pub fn sound_volume(m: &Mob) -> f32 { | Species::Pufferfish | Species::Bat => 0.1, Species::Squid | Species::GlowSquid => 0.4, - Species::Horse | Species::Donkey | Species::Mule => 0.8, + Species::Horse + | Species::Donkey + | Species::Mule + | Species::Llama + | Species::TraderLlama => 0.8, _ => 1.0, } } diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index f56e504a4..cbfe2da3a 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -190,7 +190,7 @@ fn head(p: &mut Poses, s: &State) { p.yrot("head", s.y_rot.to_radians()); } /// QuadrupedModel.setupAnim -fn quadruped(p: &mut Poses, s: &State) { +pub(super) fn quadruped(p: &mut Poses, s: &State) { head(p, s); let (pos, sp) = (s.pos, s.speed); p.xrot("right_hind_leg", (pos * 0.6662).cos() * 1.4 * sp); @@ -345,6 +345,7 @@ pub fn setup( ) { match m.kind.anim { Anim::Camel => super::camel::anim(m, s, p, w_anims), + Anim::Llama => super::llama::anim(m, s, p), Anim::Allay => super::allay::anim(m, s, p), Anim::Squid | Anim::Fish | Anim::Pufferfish | Anim::Dolphin => { super::aquatic::anim(m, s, p) diff --git a/crates/horizon-client/src/mobs/caravan.rs b/crates/horizon-client/src/mobs/caravan.rs new file mode 100644 index 000000000..3ba4055a5 --- /dev/null +++ b/crates/horizon-client/src/mobs/caravan.rs @@ -0,0 +1,271 @@ +//! Llama caravans and the trader's llamas: `LlamaFollowCaravanGoal` (a +//! llama joins the nearest line of llamas that starts at a leashed one and +//! follows the llama ahead), `TraderLlamaDefendWanderingTraderGoal` and the +//! trader llama's despawn. +use super::{ + Mob, MobWorld, Seen, Species, Who, + goals::{Cx, Goal, TARGET, TargetState, goal_clone, reduced, target_continue}, + llama::is_llama, +}; +use horizon_core::geometry::Vec3; + +const CARAVAN_LIMIT: i32 = 8; + +/// The id plus one of the llama this one follows, 0 when not in a caravan +/// (`Llama.caravanHead`, kept in `ints[1]`). +pub fn head_of(m: &Mob) -> u32 { + if is_llama(m.species()) { + m.extra.ints[1].max(0) as u32 + } else { + 0 + } +} +fn in_caravan(m: &Mob) -> bool { + head_of(m) != 0 +} +fn is_leashed_seen(s: &Seen) -> bool { + s.leash.is_some() +} +/// Whether another llama follows `s` (`hasCaravanTail`). +fn has_tail(cx: &Cx, s: &Seen) -> bool { + cx.w.others + .iter() + .any(|o| is_llama(o.species) && o.alive && o.caravan == s.id + 1) +} +/// `firstIsLeashed`: the line leads back to a leashed llama in at most +/// eight links. +fn first_is_leashed(cx: &Cx, caravan: u32, leashed: bool, counter: i32) -> bool { + if counter > CARAVAN_LIMIT { + return false; + } + let _ = leashed; + if caravan == 0 { + return false; + } + let Some(head) = cx.w.seen(caravan - 1) else { + return false; + }; + if is_leashed_seen(head) { + true + } else { + first_is_leashed(cx, head.caravan, false, counter + 1) + } +} +/// `LlamaFollowCaravanGoal`. +#[derive(Clone, Debug)] +pub struct FollowCaravan { + speed: f64, + base_speed: f64, + dist_check: i32, +} +impl FollowCaravan { + pub fn new(speed: f64) -> Self { + Self { + speed, + base_speed: speed, + dist_check: 0, + } + } +} +impl Goal for FollowCaravan { + goal_clone!(); + fn flags(&self) -> u8 { + super::goals::MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if m.extra.leash.is_some() || in_caravan(m) { + return false; + } + let area = m.bounds().inflate(Vec3::new(9.0, 4.0, 9.0)); + let mine = m.position; + let id = m.id; + let candidates: Vec<&Seen> = cx + .w + .others + .iter() + .filter(|s| s.id != id && is_llama(s.species) && s.alive && s.bounds.intersects(area)) + .collect(); + let mut closest: Option<&Seen> = None; + let mut best = f64::MAX; + for c in &candidates { + if c.caravan != 0 && !has_tail(cx, c) { + let d = mine.distance_squared(c.position); + if d <= best { + best = d; + closest = Some(c); + } + } + } + if closest.is_none() { + for c in &candidates { + if is_leashed_seen(c) && !has_tail(cx, c) { + let d = mine.distance_squared(c.position); + if d <= best { + best = d; + closest = Some(c); + } + } + } + } + let Some(head) = closest else { + return false; + }; + if best < 4.0 { + return false; + } + if !is_leashed_seen(head) && !first_is_leashed(cx, head.caravan, false, 1) { + return false; + } + m.extra.ints[1] = head.id as i32 + 1; + true + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let caravan = head_of(m); + if caravan == 0 { + return false; + } + let Some(head) = cx.w.seen(caravan - 1).filter(|h| h.alive) else { + return false; + }; + if !first_is_leashed(cx, caravan, false, 0) { + return false; + } + // Two llamas that joined the same one in the same tick: the one with + // the higher id leaves and looks for another place. + if cx + .w + .others + .iter() + .any(|o| o.id < m.id && is_llama(o.species) && o.alive && o.caravan == caravan) + { + return false; + } + let dist_sqr = m.position.distance_squared(head.position); + if dist_sqr > 676.0 { + if self.speed <= 3.0 { + self.speed *= 1.2; + self.dist_check = reduced(40); + return true; + } + if self.dist_check == 0 { + return false; + } + } + if self.dist_check > 0 { + self.dist_check -= 1; + } + true + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + m.extra.ints[1] = 0; + self.speed = self.base_speed; + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let caravan = head_of(m); + if caravan == 0 { + return; + } + // A llama leashed to a fence knot does not walk to the one ahead. + if matches!(m.extra.leash, Some(super::leash::Holder::Knot(_))) { + return; + } + let Some(head) = cx.w.seen(caravan - 1) else { + return; + }; + let to = Vec3::new( + head.position.x - m.position.x, + head.position.y - m.position.y, + head.position.z - m.position.z, + ); + let distance = to.length(); + let delta = to.normalize().scale((distance - 2.0).max(0.0)); + m.nav_move_to( + cx.w, + [ + m.position.x + delta.x, + m.position.y + delta.y, + m.position.z + delta.z, + ], + self.speed, + ); + } +} +/// `TraderLlamaDefendWanderingTraderGoal`: attack whoever last hurt the +/// wandering trader holding this llama's lead. +#[derive(Clone, Debug, Default)] +pub struct DefendTrader { + attacker: Option, + timestamp: i32, + st: TargetState, +} +impl Goal for DefendTrader { + goal_clone!(); + fn flags(&self) -> u8 { + TARGET + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let Some(super::leash::Holder::Mob(id)) = m.extra.leash else { + return false; + }; + let Some(owner) = + cx.w.seen(id) + .filter(|s| s.species == Species::WanderingTrader) + else { + return false; + }; + let Some((by, stamp)) = owner.hurt_by else { + return false; + }; + if stamp == self.timestamp { + return false; + } + let Some(t) = cx.w.target_info(by) else { + return false; + }; + if !t.alive || t.is_player && t.creative { + return false; + } + let follow = m.attrs.follow_range; + if m.distance_sqr(t.position) > follow * follow || !m.sees(cx.w, by) { + return false; + } + self.attacker = Some(by); + true + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + target_continue(&mut self.st, false, m, cx) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + m.ai.target = self.attacker; + if let Some(super::leash::Holder::Mob(id)) = m.extra.leash + && let Some(owner) = cx.w.seen(id) + && let Some((_, stamp)) = owner.hurt_by + { + self.timestamp = stamp; + } + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + m.ai.target = None; + } +} +/// `TraderLlama.maybeDespawn`: counts down its own delay, or follows the +/// trader's when led by one, unless tamed, led by something else, ridden, +/// age-locked or kept. +pub fn trader_llama_tick(m: &mut Mob, w: &MobWorld) { + let trader = match m.extra.leash { + Some(super::leash::Holder::Mob(id)) => w + .seen(id) + .filter(|s| s.species == Species::WanderingTrader) + .map(|s| s.delay), + _ => None, + }; + let leashed_other = m.extra.leash.is_some() && trader.is_none(); + if m.extra.tame || leashed_other || m.rider.is_some() || m.extra.age_locked || m.persistent { + return; + } + m.extra.ints[0] = trader.unwrap_or(m.extra.ints[0]) - 1; + if m.extra.ints[0] <= 0 { + m.extra.leash = None; + m.removed = true; + } +} diff --git a/crates/horizon-client/src/mobs/equine.rs b/crates/horizon-client/src/mobs/equine.rs index 33be2a248..e87b1c0c0 100644 --- a/crates/horizon-client/src/mobs/equine.rs +++ b/crates/horizon-client/src/mobs/equine.rs @@ -52,8 +52,18 @@ pub fn is_equine(s: Species) -> bool { | Species::SkeletonHorse | Species::ZombieHorse | Species::Camel + | Species::Llama + | Species::TraderLlama ) } +/// `AbstractHorse.getMaxTemper`: 100, 30 for llamas. +pub fn max_temper(s: Species) -> i32 { + if super::llama::is_llama(s) { + super::llama::MAX_TEMPER + } else { + 100 + } +} /// `canPerformRearing`: not donkeys or mules. fn can_rear(s: Species) -> bool { matches!( @@ -65,6 +75,9 @@ pub fn register(m: &mut Mob) { if m.species() == Species::Camel { return super::camel::register(m); } + if super::llama::is_llama(m.species()) { + return super::llama::register(m); + } let tempt = m.kind.tempt.clone(); let rears = can_rear(m.species()); let g = &mut m.ai.goals; @@ -190,7 +203,7 @@ impl Goal for MountPanic { /// `RunAroundLikeCrazyGoal`: an untamed horse with a rider bolts about until /// it is tamed (temper) or throws the rider off. #[derive(Clone, Debug)] -struct RunAroundLikeCrazy; +pub(super) struct RunAroundLikeCrazy; impl Goal for RunAroundLikeCrazy { goal_clone!(); fn flags(&self) -> u8 { @@ -224,13 +237,14 @@ impl Goal for RunAroundLikeCrazy { return; } let temper = i32::from(m.extra.variant3); - if m.random.next_int_bound(100).unwrap_or(0) < temper { + let max = max_temper(m.species()); + if m.random.next_int_bound(max).unwrap_or(0) < temper { // tameWithName m.extra.tame = true; cx.events.push(MobEvent::Tamed { mob: m.id }); return; } - m.extra.variant3 = (temper + 5).min(100) as u8; + m.extra.variant3 = (temper + 5).min(max) as u8; cx.events.push(MobEvent::Buck { mob: m.id }); make_mad(m, cx.events); } @@ -247,6 +261,7 @@ pub fn make_mad(m: &mut Mob, events: &mut Vec) { let sound = match m.species() { Species::Donkey => "entity.donkey.angry", Species::Mule => "entity.mule.angry", + Species::Llama | Species::TraderLlama => "entity.llama.angry", _ => "entity.horse.angry", }; events.push(MobEvent::Sound(sound, m.center(), 1.0, 1.0)); @@ -375,6 +390,9 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { if m.species() == Species::Camel { return super::camel::ai_step(m, events); } + if super::llama::is_llama(m.species()) { + return super::llama::ai_step(m, w); + } if m.alive() && m.random.next_int_bound(900).unwrap_or(1) == 0 && m.death_time == 0 { m.health = (m.health + 1.0).min(m.attrs.max_health); } diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 814d6a3f1..60c73e804 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -915,12 +915,25 @@ pub struct NearestTarget { found: Option, target_goal: TargetState, } -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug)] pub struct TargetState { unseen: i32, pub unseen_memory: i32, reach_cache: i32, reach_time: i32, + /// `TargetGoal.getFollowDistance` as a fraction of the follow range. + pub follow_scale: f64, +} +impl Default for TargetState { + fn default() -> Self { + Self { + unseen: 0, + unseen_memory: 0, + reach_cache: 0, + reach_time: 0, + follow_scale: 1.0, + } + } } impl NearestTarget { pub fn new(prey: Prey, must_see: bool) -> Self { @@ -947,6 +960,11 @@ impl NearestTarget { self.interval = reduced(i); self } + /// Scale the follow distance (llamas hunt wolves within a quarter of it). + pub fn follow_scale(mut self, scale: f64) -> Self { + self.target_goal.follow_scale = scale; + self + } pub fn reach(mut self) -> Self { self.must_reach = true; self @@ -965,7 +983,8 @@ pub fn target_continue(st: &mut TargetState, must_see: bool, m: &mut Mob, cx: &m if !t.alive || t.is_player && t.creative { return false; } - if m.distance_sqr(t.position) > m.attrs.follow_range * m.attrs.follow_range { + let follow = m.attrs.follow_range * st.follow_scale; + if m.distance_sqr(t.position) > follow * follow { return false; } if must_see { @@ -1011,7 +1030,7 @@ impl Goal for NearestTarget { { return false; } - let range = m.attrs.follow_range; + let range = m.attrs.follow_range * self.target_goal.follow_scale; self.found = None; match &self.prey { Prey::Player => { @@ -1422,14 +1441,20 @@ impl Goal for Breed { } let id = m.id; // Horses and donkeys breed together (AbstractHorse.canParent: tame). - let equine = matches!(species, Species::Horse | Species::Donkey); + let llama = super::llama::is_llama(species); + let equine = matches!(species, Species::Horse | Species::Donkey) || llama; if equine && !m.extra.tame { return false; } + // Llama.canParent: not ridden, and at full health. + if llama && (m.rider.is_some() || m.health < m.attrs.max_health) { + return false; + } self.partner = cx.w.nearby(m.position, 8.0, move |s| { let same = s.species == species - || equine && matches!(s.species, Species::Horse | Species::Donkey); + || llama && super::llama::is_llama(s.species) + || !llama && equine && matches!(s.species, Species::Horse | Species::Donkey); s.id != id && same && s.in_love diff --git a/crates/horizon-client/src/mobs/leash.rs b/crates/horizon-client/src/mobs/leash.rs new file mode 100644 index 000000000..cc48bc4d8 --- /dev/null +++ b/crates/horizon-client/src/mobs/leash.rs @@ -0,0 +1,400 @@ +//! Leads (`Leashable`): who holds a mob's lead and the elastic physics of +//! `Leashable.tickLeash` (a pull once the rope stretches past six blocks, +//! the lead snapping past twelve, `PathfinderMob`'s walk toward the holder +//! while the rope is slack). +use super::{Mob, MobEvent, MobWorld, Species, Who}; +use horizon_core::geometry::Vec3; +use horizon_world::nbt::Tag; + +/// `Leashable.LEASH_ELASTIC_DIST`. +pub const ELASTIC: f64 = 6.0; +/// `Leashable.LEASH_TOO_FAR_DIST`. +pub const SNAP: f64 = 12.0; + +/// What holds the other end of a lead. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Holder { + Player, + Mob(u32), + /// A `LeashFenceKnotEntity` on the fence at this block. + Knot([i32; 3]), +} +impl Holder { + pub fn who(self) -> Option { + match self { + Holder::Player => Some(Who::Player), + Holder::Mob(id) => Some(Who::Mob(id)), + Holder::Knot(_) => None, + } + } +} +/// A holder read from a save that is not in the world yet (the entity may +/// load later): the holder's UUID, or the fence knot's block. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Pending { + Uuid([i32; 4]), + Knot([i32; 3]), +} +/// `Leashable.LeashData.CODEC`: `{UUID: [I;..]}` for an entity holder or the +/// fence's block position as an int array. +pub fn pending_from_nbt(tag: Option<&Tag>) -> Option { + match tag? { + Tag::IntArray(p) if p.len() == 3 => Some(Pending::Knot([p[0], p[1], p[2]])), + t @ Tag::Compound(_) => crate::save::uuid_from_tag(t.get("UUID")).map(Pending::Uuid), + _ => None, + } +} +/// The `leash` tag for a holder: the holder entity's UUID, or the knot's block. +pub fn to_nbt(holder: Holder, uuid: Option<[i32; 4]>) -> Option { + match holder { + Holder::Knot(p) => Some(Tag::IntArray(p.to_vec())), + _ => uuid.map(|u| Tag::compound([("UUID", Tag::IntArray(u.to_vec()))])), + } +} +/// Where the other end of the lead is this tick. +#[derive(Clone, Copy, Debug)] +pub struct HolderState { + pub position: Vec3, + pub center: Vec3, + pub width: f64, + pub height: f64, + pub yaw: f32, + pub velocity: Vec3, +} +/// `LeashFenceKnotEntity`: 0.375 wide, 0.5 tall, centred a block's 0.375 up. +pub fn knot_state(pos: [i32; 3]) -> HolderState { + let position = Vec3::new( + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.375, + f64::from(pos[2]) + 0.5, + ); + HolderState { + position, + center: Vec3::new(position.x, position.y + 0.25, position.z), + width: 0.375, + height: 0.5, + yaw: 0.0, + velocity: Vec3::ZERO, + } +} +/// The holder's state, or `None` when it is gone. +pub fn holder_state(w: &MobWorld, holder: Holder) -> Option { + match holder { + Holder::Player => { + let p = w.player.as_ref()?; + let size = p.bounds.max_position().subtract(p.bounds.min_position()); + Some(HolderState { + position: p.position, + center: Vec3::new(p.position.x, p.position.y + size.y / 2.0, p.position.z), + width: size.x, + height: size.y, + yaw: p.yaw, + velocity: p.velocity, + }) + } + Holder::Mob(id) => { + let s = w.seen(id).filter(|s| s.alive)?; + let lo = s.bounds.min_position(); + let hi = s.bounds.max_position(); + Some(HolderState { + position: s.position, + center: Vec3::new( + (lo.x + hi.x) / 2.0, + (lo.y + hi.y) / 2.0, + (lo.z + hi.z) / 2.0, + ), + width: hi.x - lo.x, + height: hi.y - lo.y, + yaw: s.yaw, + velocity: s.velocity, + }) + } + Holder::Knot(pos) => { + let fence = w.has_tag("minecraft:fences", w.block_name(pos[0], pos[1], pos[2])); + fence.then(|| knot_state(pos)) + } + } +} +/// `Entity.yRot(angle)` on a vector (rotation about the Y axis). +fn rot_y(v: [f64; 3], angle: f64) -> [f64; 3] { + let (s, c) = (angle.sin(), angle.cos()); + [v[0] * c + v[2] * s, v[1], v[2] * c - v[0] * s] +} +/// `Leashable.computeDampenedSpringInteraction` for the single attachment +/// of a mob (0, 0.5, 0.5 of its box) and its holder (0, 0.5, 0): the force +/// toward the holder and the torque on the mob, or `None` while slack. +pub fn spring( + position: Vec3, + yaw: f32, + size: (f64, f64), + holder: &HolderState, + own_motion: Vec3, +) -> Option<([f64; 3], f64)> { + let (w, h) = size; + let lever = rot_y([0.0, 0.5 * h, 0.5 * w], -f64::from(yaw.to_radians())); + let object = [ + position.x + lever[0], + position.y + lever[1], + position.z + lever[2], + ]; + let arm = rot_y( + [0.0, 0.5 * holder.height, 0.0], + -f64::from(holder.yaw.to_radians()), + ); + let pivot = [ + holder.position.x + arm[0], + holder.position.y + arm[1], + holder.position.z + arm[2], + ]; + let d = [ + pivot[0] - object[0], + pivot[1] - object[1], + pivot[2] - object[2], + ]; + let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); + if distance < ELASTIC { + return None; + } + let scale = (distance - ELASTIC) / distance; + let mut force = [d[0] * scale, d[1] * scale, d[2] * scale]; + let torque = lever[2] * force[0] - lever[0] * force[2]; + let same_direction = + own_motion.x * force[0] + own_motion.y * force[1] + own_motion.z * force[2] >= 0.0; + if same_direction { + for f in &mut force { + *f *= f64::from(0.3_f32); + } + } + Some((force, torque)) +} +/// `Entity.checkFallDistanceAccumulation`. +fn check_fall_distance(m: &mut Mob) { + if m.velocity.y > -0.5 && m.fall_distance > 1.0 { + m.fall_distance = 1.0; + } +} +/// Whether a mob can be put on a lead (`Mob.canBeLeashed` and overrides). +pub fn can_be_leashed(m: &Mob) -> bool { + use Species as S; + match m.species() { + S::Hoglin | S::Zoglin => true, + S::Villager + | S::WanderingTrader + | S::Turtle + | S::Panda + | S::Bat + | S::Cod + | S::Salmon + | S::TropicalFish + | S::Pufferfish + | S::Tadpole => false, + S::Wolf => !super::tame::angry(m), + _ => !m.hostile() && !m.removed, + } +} +/// `Leashable.tickLeash` at the end of `Entity.baseTick`. +pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + let Some(holder) = m.extra.leash else { + m.extra.leash_spin = 0.0; + return; + }; + let Some(state) = holder_state(w, holder) else { + // The holder is gone: the lead drops. + if !matches!(holder, Holder::Player) { + events.push(MobEvent::LeashBreak { + mob: m.id, + drop: true, + sound: false, + }); + } + return; + }; + let b = m.bounds(); + let (lo, hi) = (b.min_position(), b.max_position()); + let center = Vec3::new( + (lo.x + hi.x) / 2.0, + (lo.y + hi.y) / 2.0, + (lo.z + hi.z) / 2.0, + ); + let distance = ((state.center.x - center.x).powi(2) + + (state.center.y - center.y).powi(2) + + (state.center.z - center.z).powi(2)) + .sqrt(); + if distance > SNAP { + events.push(MobEvent::LeashBreak { + mob: m.id, + drop: true, + sound: true, + }); + return; + } + let stretched = distance > ELASTIC - state.width - f64::from(m.width()); + let pulled = stretched + && spring( + m.position, + m.yaw, + (f64::from(m.width()), f64::from(m.height())), + &state, + m.velocity, + ) + .is_some_and(|(force, torque)| { + m.extra.leash_spin += 10.0 * torque; + let rel = Vec3::new( + state.velocity.x - m.velocity.x, + state.velocity.y - m.velocity.y, + state.velocity.z - m.velocity.z, + ); + m.velocity = Vec3::new( + m.velocity.x + force[0] * 0.8 + rel.x * 0.11, + m.velocity.y + force[1] * 0.2 + rel.y * 0.11, + m.velocity.z + force[2] * 0.8 + rel.z * 0.11, + ); + check_fall_distance(m); + true + }); + if !pulled { + close_range(m, w, &state); + } + m.yaw -= m.extra.leash_spin as f32; + let friction = if m.on_ground { + 0.6 * 0.91 + } else if m.is_in_liquid() { + 0.8 + } else { + 0.91 + }; + m.extra.leash_spin *= friction; +} +/// `PathfinderMob.closeRangeLeashBehaviour`: walk to within two blocks of +/// the holder unless panicking. +fn close_range(m: &mut Mob, w: &MobWorld, holder: &HolderState) { + if m.ai.panicking { + return; + } + let d = Vec3::new( + holder.position.x - m.position.x, + holder.position.y - m.position.y, + holder.position.z - m.position.z, + ); + let dist = d.length(); + let len = d.length(); + let scale = if len > 0.0 { + (dist - 2.0).max(0.0) / len + } else { + 0.0 + }; + let target = [ + m.position.x + d.x * scale, + m.position.y + d.y * scale, + m.position.z + d.z * scale, + ]; + let speed = follow_speed(m); + m.nav_move_to(w, target, speed); +} +/// `followLeashSpeed`: 1.0, 2.0 for llamas. +pub fn follow_speed(m: &Mob) -> f64 { + if super::llama::is_llama(m.species()) { + 2.0 + } else { + 1.0 + } +} +/// `Mob.leashable` position of the rope on a mob (`getLeashOffset`). +pub fn leash_offset(m: &Mob) -> [f64; 3] { + if super::llama::is_llama(m.species()) { + // Llama.getLeashOffset. + [0.0, 0.75 * m.eye_height(), f64::from(m.width()) * 0.5] + } else { + [0.0, m.eye_height(), f64::from(m.width() * 0.4)] + } +} +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rotating_about_y_matches_vanilla() { + let v = rot_y([0.0, 1.0, 1.0], std::f64::consts::FRAC_PI_2); + assert!((v[0] - 1.0).abs() < 1e-9 && v[2].abs() < 1e-9); + } + fn holder(x: f64) -> HolderState { + let position = Vec3::new(x, 64.0, 0.0); + HolderState { + position, + center: Vec3::new(x, 64.9, 0.0), + width: 0.6, + height: 1.8, + yaw: 0.0, + velocity: Vec3::ZERO, + } + } + #[test] + fn a_slack_rope_does_not_pull() { + let pulled = spring( + Vec3::new(0.0, 64.0, 0.0), + 0.0, + (0.9, 1.87), + &holder(3.0), + Vec3::ZERO, + ); + assert!(pulled.is_none()); + } + #[test] + fn a_stretched_rope_pulls_toward_the_holder() { + let (force, _) = spring( + Vec3::new(0.0, 64.0, 0.0), + 0.0, + (0.9, 1.87), + &holder(10.0), + Vec3::ZERO, + ) + .expect("past the slack"); + // Moving away from nothing: the same-direction damping applies. + assert!(force[0] > 0.0); + assert!(force[0] < 10.0 - ELASTIC); + } + #[test] + fn moving_with_the_pull_damps_it() { + let at = Vec3::new(0.0, 64.0, 0.0); + let still = spring( + at, + 0.0, + (0.9, 1.87), + &holder(10.0), + Vec3::new(-0.1, 0.0, 0.0), + ) + .expect("pull") + .0; + let following = spring( + at, + 0.0, + (0.9, 1.87), + &holder(10.0), + Vec3::new(0.1, 0.0, 0.0), + ) + .expect("pull") + .0; + assert!((following[0] - still[0] * 0.3_f32 as f64).abs() < 1e-9); + } + #[test] + fn leash_tags_round_trip() { + let knot = to_nbt(Holder::Knot([1, 2, 3]), None).expect("knot tag"); + assert_eq!( + pending_from_nbt(Some(&knot)), + Some(Pending::Knot([1, 2, 3])) + ); + let held = to_nbt(Holder::Player, Some([4, 5, 6, 7])).expect("uuid tag"); + assert_eq!( + pending_from_nbt(Some(&held)), + Some(Pending::Uuid([4, 5, 6, 7])) + ); + assert_eq!(to_nbt(Holder::Mob(1), None), None); + } + #[test] + fn a_knot_sits_on_the_fence_post() { + let k = knot_state([10, 64, -3]); + assert_eq!(k.position.x, 10.5); + assert_eq!(k.position.y, 64.375); + assert_eq!(k.center.y, 64.625); + } +} diff --git a/crates/horizon-client/src/mobs/llama.rs b/crates/horizon-client/src/mobs/llama.rs new file mode 100644 index 000000000..4dd746407 --- /dev/null +++ b/crates/horizon-client/src/mobs/llama.rs @@ -0,0 +1,286 @@ +//! Llamas and trader llamas (`Llama`, `TraderLlama`): coat variants and +//! strength, chests and carpets, taming by riding (maximum temper 30), the +//! spit ranged attack, hunting wolves (and, for traders, zombies and +//! illagers) and `LlamaModel`. +use super::{ + Mob, MobEvent, MobWorld, Seen, Species, Who, + anim::{Poses, State}, + equine, + goals::{ + Breed, Cx, Float, FollowParent, Goal, HurtByTarget, LookAtPlayer, NearestTarget, Panic, + Prey, RandomLookAround, Stroll, Tempt, goal_clone, + }, + witch::RangedAttack, +}; +use crate::projectiles::{Projectile, ProjectileKind}; +use horizon_core::{geometry::Vec3, random::RandomSource}; +use std::f32::consts::PI; + +pub const VARIANTS: [&str; 4] = ["creamy", "white", "brown", "gray"]; +/// `Llama.getMaxTemper`. +pub const MAX_TEMPER: i32 = 30; + +// Llama state: `variant` the coat, `variant2` the strength (1 to 5), +// `variant3` the temper, `chested` the chest, `head` the carpet, `flag2` +// `didSpit`, `ints[0]` a trader llama's despawn delay. +pub fn is_llama(s: Species) -> bool { + matches!(s, Species::Llama | Species::TraderLlama) +} +pub fn is_trader(m: &Mob) -> bool { + m.species() == Species::TraderLlama +} +/// `Llama.getStrength`. +pub fn strength(m: &Mob) -> i32 { + i32::from(m.extra.variant2).clamp(1, 5) +} +/// `getInventoryColumns`: a chest holds three rows of `strength` columns. +pub fn inventory_columns(m: &Mob) -> i32 { + if m.extra.chested { strength(m) } else { 0 } +} +/// The mob is a zombie of any kind (`Zombie.class`). +fn is_zombie(s: &Seen) -> bool { + matches!( + s.species, + Species::Zombie | Species::Husk | Species::Drowned | Species::ZombieVillager + ) +} +/// The mob is an illager (`AbstractIllager.class`). +pub fn is_illager(s: &Seen) -> bool { + matches!( + s.species, + Species::Pillager | Species::Vindicator | Species::Evoker + ) +} +pub fn register(m: &mut Mob) { + m.ai.nav.required_path_length = 40.0; + let tempt = m.kind.tempt.clone(); + let trader = is_trader(m); + if trader { + m.extra.ints[0] = DEFAULT_DESPAWN_DELAY; + } + let g = &mut m.ai.goals; + g.add(0, Float); + if trader { + g.add(1, Panic::new(2.0)); + } + g.add(1, equine::RunAroundLikeCrazy); + g.add(2, super::caravan::FollowCaravan::new(2.1)); + g.add(3, RangedAttack::new(1.25, 40, 40, 20.0, spit)); + g.add(3, Panic::new(1.2)); + g.add(4, Breed::new(1.0)); + g.add(5, Tempt::new(1.25, tempt, false)); + g.add(6, FollowParent::new(1.0)); + g.add(7, Stroll::avoiding_water(0.7)); + g.add(8, LookAtPlayer::new(6.0)); + g.add(9, RandomLookAround::default()); + m.ai.targets.add(1, LlamaHurtBy(HurtByTarget::new())); + if trader { + m.ai.targets.add(1, super::caravan::DefendTrader::default()); + } + m.ai.targets.add( + 2, + NearestTarget::new( + Prey::Filter(|s| s.species == Species::Wolf && !s.tame), + false, + ) + .interval(16) + .reach() + .follow_scale(0.25), + ); + if trader { + m.ai.targets + .add(2, NearestTarget::new(Prey::Filter(is_zombie), true)); + m.ai.targets + .add(2, NearestTarget::new(Prey::Filter(is_illager), true)); + } +} +/// `TraderLlama.DEFAULT_DESPAWN_DELAY`. +pub const DEFAULT_DESPAWN_DELAY: i32 = 47999; +/// `Llama.finalizeSpawn` and `AbstractChestedHorse.randomizeAttributes`: +/// health 15 to 30, a coat and the strength. +pub fn finalize(m: &mut Mob) { + let r = &mut m.random; + let health = + 15.0 + r.next_int_bound(8).unwrap_or(0) as f32 + r.next_int_bound(9).unwrap_or(0) as f32; + let max = if r.next_float() < 0.04 { 5 } else { 3 }; + let strength = 1 + r.next_int_bound(max).unwrap_or(0); + let variant = r.next_int_bound(4).unwrap_or(0); + m.attrs.max_health = health; + m.health = health; + m.extra.variant2 = strength as u8; + m.extra.variant = variant as u8; + m.extra.vector[0] = m.kind.jump_strength; +} +/// `Llama.getBreedOffspring` after `setOffspringAttributes`: the strength +/// (rarely one more) and either parent's coat. +pub fn offspring(child: &mut Mob, a: &Mob, b: &Mob, r: &mut impl RandomSource) { + let top = strength(a).max(strength(b)); + let mut s = r.next_int_bound(top).unwrap_or(0) + 1; + if r.next_float() < 0.03 { + s += 1; + } + child.extra.variant2 = s.clamp(1, 5) as u8; + child.extra.variant = if r.next_boolean() { + a.extra.variant + } else { + b.extra.variant + }; + if is_trader(child) { + child.persistent = true; + } +} +/// `LlamaHurtByTargetGoal`: stops hunting right after a spit. +#[derive(Clone, Debug)] +struct LlamaHurtBy(HurtByTarget); +impl Goal for LlamaHurtBy { + goal_clone!(); + fn flags(&self) -> u8 { + self.0.flags() + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.0.can_use(m, cx) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if m.extra.flag2 { + m.extra.flag2 = false; + return false; + } + self.0.can_continue(m, cx) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.start(m, cx) + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.stop(m, cx) + } +} +/// `Llama.performRangedAttack` / `spit`: a llama spit toward the target's +/// lower third, 1.5 fast, with 10 degrees of spread. +fn spit(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) { + let Some(t) = cx.w.target_info(who) else { + return; + }; + let body = m.body_yaw.to_radians(); + let reach = (f64::from(m.width()) + 1.0) * 0.5; + let start = Vec3::new( + m.position.x - reach * f64::from(body.sin()), + m.eye_y() - f64::from(0.1_f32), + m.position.z + reach * f64::from(body.cos()), + ); + let top = t.bounds.max_position(); + let low = t.bounds.min_position(); + let xd = t.position.x - m.position.x; + let yd = low.y + (top.y - low.y) * 0.333_333_333_333_333_3 - start.y; + let zd = t.position.z - m.position.z; + let yo = (xd * xd + zd * zd).sqrt() * f64::from(0.2_f32); + let mut p = Projectile::new(ProjectileKind::LlamaSpit, start, Some(Who::Mob(m.id))); + p.shoot(&mut m.random, [xd, yd + yo, zd], 1.5, 10.0); + cx.events.push(MobEvent::Projectile(p)); + let pitch = 1.0 + (m.random.next_float() - m.random.next_float()) * 0.2; + cx.events.push(MobEvent::Sound( + "entity.llama.spit", + [m.position.x, m.position.y, m.position.z], + 1.0, + pitch, + )); + m.extra.flag2 = true; +} +/// `AbstractHorse.aiStep` for llamas, which never graze: the slow healing. +pub fn ai_step(m: &mut Mob, w: &MobWorld) { + if m.alive() && m.random.next_int_bound(900).unwrap_or(1) == 0 && m.death_time == 0 { + m.health = (m.health + 1.0).min(m.attrs.max_health); + } + if is_trader(m) { + super::caravan::trader_llama_tick(m, w); + } +} +/// The llama's own save fields, over the horse ones: `Variant` (the coat id), +/// `Strength` and a trader llama's `DespawnDelay`. +pub fn to_nbt(m: &Mob, map: &mut horizon_world::nbt::Compound) { + use horizon_world::nbt::Tag; + map.insert("Variant".into(), Tag::Int(i32::from(m.extra.variant))); + map.insert("Strength".into(), Tag::Int(strength(m))); + if is_trader(m) { + map.insert("DespawnDelay".into(), Tag::Int(m.extra.ints[0])); + } +} +pub fn from_nbt(m: &mut Mob, tag: &horizon_world::nbt::Tag) { + use crate::save::number; + m.extra.variant = number(tag.get("Variant")).unwrap_or(0).clamp(0, 3) as u8; + m.extra.variant2 = number(tag.get("Strength")).unwrap_or(1).clamp(1, 5) as u8; + m.extra.variant3 = i32::from(m.extra.variant3).min(MAX_TEMPER) as u8; + if is_trader(m) { + m.extra.ints[0] = + number(tag.get("DespawnDelay")).map_or(DEFAULT_DESPAWN_DELAY, |v| v as i32); + } +} +/// The coat texture (`LlamaRenderer`). +pub fn texture(m: &Mob) -> String { + let baby = if m.is_baby() { "_baby" } else { "" }; + let coat = VARIANTS[(m.extra.variant as usize).min(3)]; + format!("entity/llama/llama_{coat}{baby}") +} +/// The carpet colour on the llama, if it wears one. +fn carpet(m: &Mob) -> Option<&str> { + m.extra + .head + .as_deref() + .and_then(|i| i.strip_prefix("minecraft:")) + .and_then(|i| i.strip_suffix("_carpet")) +} +/// `LlamaDecorLayer`: the carpet of an adult, else the trader's blanket. +pub fn decor(m: &Mob) -> Option<(String, String)> { + let baby = m.is_baby(); + let model = if baby { + "llama_baby#decor" + } else { + "llama#decor" + }; + if let Some(color) = carpet(m) + && !baby + { + return Some((model.into(), format!("entity/equipment/llama_body/{color}"))); + } + is_trader(m).then(|| { + let name = if baby { + "trader_llama_baby" + } else { + "trader_llama" + }; + (model.into(), format!("entity/equipment/llama_body/{name}")) + }) +} +/// `LlamaModel.setupAnim`. +pub fn anim(m: &Mob, s: &State, p: &mut Poses) { + super::anim::quadruped(p, s); + let chest = m.extra.chested && !s.baby; + for part in ["right_chest", "left_chest"] { + if !chest { + p.visible(part, false); + } + } + let _ = PI; +} +#[cfg(test)] +mod tests { + use super::*; + use horizon_core::random::LegacyRandom; + + #[test] + fn strength_stays_in_range_and_rarely_reaches_five() { + let mut r = LegacyRandom::new(7); + let mut fives = 0; + for _ in 0..4000 { + let max = if r.next_float() < 0.04 { 5 } else { 3 }; + let s = 1 + r.next_int_bound(max).unwrap(); + assert!((1..=5).contains(&s)); + fives += i32::from(s > 3); + } + assert!(fives > 0 && fives < 200); + } + #[test] + fn a_chest_holds_strength_columns() { + assert_eq!(DEFAULT_DESPAWN_DELAY, 47999); + assert_eq!(MAX_TEMPER, 30); + } +} diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index 13a24e1a9..2eeaea675 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -106,6 +106,17 @@ pub fn body(m: &Mob) -> (String, String) { return ("main".into(), m.kind.texture.to_string()); } match m.species() { + S::Llama | S::TraderLlama => { + let name = if m.species() == S::Llama { + "llama" + } else { + "trader_llama" + }; + ( + baby_or(m, &format!("{name}#main"), &format!("{name}_baby#main")), + super::llama::texture(m), + ) + } s if super::equine::is_equine(s) => { let name = super::equine::model_name(s); ( @@ -302,6 +313,12 @@ pub fn layers(m: &Mob) -> Vec { false, ); } + // LlamaDecorLayer: the carpet, or the trader's blanket. + S::Llama | S::TraderLlama => { + if let Some((model, texture)) = super::llama::decor(m) { + push(&mut v, &model, &texture, white, false); + } + } // HorseMarkingLayer, the saddle and the horse armour. s if super::equine::is_equine(s) => { let name = super::equine::model_name(s); @@ -739,6 +756,10 @@ pub fn render_with( extra: &[(&Part, [f32; 4], u32)], out: &mut Vec, ) { + // The invisibility effect hides the model (a drinking wandering trader). + if super::trader::is_invisible(m) { + return; + } let base = base_transform(m, alpha, camera); let overlay = u32::from(m.hurt_time > 0 || m.death_time > 0); let s = anim::state(m, alpha); diff --git a/crates/horizon-client/src/mobs/spawning.rs b/crates/horizon-client/src/mobs/spawning.rs index 1138649b2..a590c9aaa 100644 --- a/crates/horizon-client/src/mobs/spawning.rs +++ b/crates/horizon-client/src/mobs/spawning.rs @@ -103,6 +103,7 @@ pub fn spawn_rules_ok( | S::Horse | S::Donkey | S::Llama + | S::Camel | S::Wolf | S::Cat | S::Fox @@ -116,6 +117,7 @@ pub fn spawn_rules_ok( | S::Bee => { let tag = match species { S::Mooshroom => "minecraft:mooshrooms_spawnable_on", + S::Camel => "minecraft:camels_spawnable_on", S::Wolf => "minecraft:wolves_spawnable_on", S::Fox => "minecraft:foxes_spawnable_on", S::Rabbit => "minecraft:rabbits_spawnable_on", @@ -353,6 +355,7 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) { S::Horse | S::Donkey | S::Mule | S::SkeletonHorse | S::ZombieHorse => { super::equine::finalize(m) } + S::Llama | S::TraderLlama => super::llama::finalize(m), // Camel.finalizeSpawn: standing, with fixed attributes. S::Camel => super::camel::stand_up_instantly(m), // Piglin.createSpawnWeapon: half crossbows, half golden swords, and diff --git a/crates/horizon-client/src/mobs/species.rs b/crates/horizon-client/src/mobs/species.rs index 820006f32..a0bf56dd2 100644 --- a/crates/horizon-client/src/mobs/species.rs +++ b/crates/horizon-client/src/mobs/species.rs @@ -1174,7 +1174,7 @@ impl Def { Species::Donkey => &["donkey_baby"], Species::Mule => &["mule_baby"], Species::Llama => &["llama_baby"], - Species::TraderLlama => &["trader_llama_baby", "llama"], + Species::TraderLlama => &["trader_llama_baby", "llama", "llama_baby"], Species::Goat => &["goat_baby"], Species::Panda => &["panda_baby"], Species::PolarBear => &["polar_bear_baby"], diff --git a/crates/horizon-client/src/mobs/trader.rs b/crates/horizon-client/src/mobs/trader.rs new file mode 100644 index 000000000..6df29b246 --- /dev/null +++ b/crates/horizon-client/src/mobs/trader.rs @@ -0,0 +1,314 @@ +//! The wandering trader (`WanderingTrader`): drinking invisibility at night +//! and milk by day, fleeing monsters, walking to the place it came to +//! visit, staying within its home, trading and leaving after its despawn +//! delay. +use super::{ + Mob, MobEvent, MobWorld, Species, + goals::{ + Avoid, AvoidEntity, Cx, Float, Goal, JUMP, LOOK, LookAtPlayer, MOVE, Panic, Stroll, + goal_clone, + }, +}; +use horizon_core::random::RandomSource; + +// Trader state: `point` the wander target, `home` the place it is tied to +// with `ints[4]` the radius, `ints[5]` the despawn delay, `flag2` whether +// a player is trading with it and `using_item` how long it has been +// drinking. + +/// `WanderingTraderSpawner`: how long a spawned trader stays. +pub const DESPAWN_DELAY: i32 = 48000; +const DRINK_TICKS: i32 = 32; +const INVISIBILITY: &str = "minecraft:invisibility"; + +pub fn register(m: &mut Mob) { + let g = &mut m.ai.goals; + g.add(0, Float); + g.add( + 0, + DrinkItem { + item: "minecraft:potion", + finish_sound: "entity.wandering_trader.disappeared", + dark: true, + }, + ); + g.add( + 0, + DrinkItem { + item: "minecraft:milk_bucket", + finish_sound: "entity.wandering_trader.reappeared", + dark: false, + }, + ); + g.add(1, TradeWithPlayer); + for (species, distance) in [ + (Species::Zombie, 8.0), + (Species::Evoker, 12.0), + (Species::Vindicator, 8.0), + (Species::Vex, 8.0), + (Species::Pillager, 15.0), + (Species::Zoglin, 10.0), + ] { + // `Zombie.class` covers the zombie family. + let list = if species == Species::Zombie { + vec![ + Species::Zombie, + Species::Husk, + Species::Drowned, + Species::ZombieVillager, + Species::ZombifiedPiglin, + ] + } else { + vec![species] + }; + g.add( + 1, + AvoidEntity::new(Avoid::Species(list), distance, 0.5, 0.5), + ); + } + g.add(1, Panic::new(0.5)); + g.add(1, LookAtTradingPlayer); + g.add( + 2, + WanderToPosition { + stop: 2.0, + speed: 0.35, + }, + ); + g.add(4, MoveTowardsRestriction::new(0.35)); + g.add(8, Stroll::avoiding_water(0.35)); + g.add(9, LookAtPlayer::new(3.0).probability(1.0)); + g.add(10, LookAtPlayer::new(8.0)); +} +fn invisible(m: &Mob) -> bool { + m.extra.effects.iter().any(|e| e.0 == INVISIBILITY) +} +pub fn is_invisible(m: &Mob) -> bool { + invisible(m) +} +/// `UseItemGoal`: drink a potion of invisibility once it is dark outside, +/// or milk to clear it by day. +#[derive(Clone, Debug)] +struct DrinkItem { + item: &'static str, + finish_sound: &'static str, + dark: bool, +} +impl Goal for DrinkItem { + goal_clone!(); + fn flags(&self) -> u8 { + 0 + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if cx.w.nether { + return false; + } + if self.dark { + !cx.w.daylight && !invisible(m) + } else { + cx.w.daylight && invisible(m) + } + } + fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + m.extra.using_item > 0 + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + m.extra.main_hand = Some(self.item.into()); + m.extra.using_item = 1; + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + m.extra.main_hand = None; + m.extra.using_item = 0; + let pitch = m.random.next_float() * 0.2 + 0.9; + cx.events + .push(MobEvent::Sound(self.finish_sound, m.center(), 1.0, pitch)); + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + if m.extra.using_item == 0 { + return; + } + m.extra.using_item += 1; + if m.extra.using_item > DRINK_TICKS { + // LivingEntity.completeUsingItem: the potion or the milk takes effect. + if self.dark { + m.extra.effects.retain(|e| e.0 != INVISIBILITY); + m.extra.effects.push((INVISIBILITY, 3600, 0)); + cx.events.push(MobEvent::Sound( + "entity.wandering_trader.drink_potion", + m.center(), + 1.0, + 1.0, + )); + } else { + m.extra.effects.clear(); + cx.events.push(MobEvent::Sound( + "entity.wandering_trader.drink_milk", + m.center(), + 1.0, + 1.0, + )); + } + m.extra.using_item = 0; + } + } +} +/// `TradeWithPlayerGoal`: stand still while trading. +#[derive(Clone, Debug)] +struct TradeWithPlayer; +impl Goal for TradeWithPlayer { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | JUMP + } + fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + m.extra.flag2 && m.alive() && !m.fluids.in_water && m.on_ground + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + m.nav_stop(); + } +} +/// `LookAtTradingPlayerGoal`. +#[derive(Clone, Debug)] +struct LookAtTradingPlayer; +impl Goal for LookAtTradingPlayer { + goal_clone!(); + fn flags(&self) -> u8 { + LOOK + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + m.extra.flag2 && cx.w.player.is_some() + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + if let Some(p) = &cx.w.player { + m.look_at([p.position.x, p.eye[1], p.position.z]); + } + } +} +/// `WanderingTrader.WanderToPositionGoal`: head for the wander target, in +/// hops of ten blocks while it is far. +#[derive(Clone, Debug)] +struct WanderToPosition { + stop: f64, + speed: f64, +} +fn too_far(m: &Mob, p: [f64; 3], distance: f64) -> bool { + // BlockPos.closerToCenterThan. + let (x, y, z) = (p[0].floor() + 0.5, p[1].floor() + 0.5, p[2].floor() + 0.5); + let d = (x - m.position.x).powi(2) + (y - m.position.y).powi(2) + (z - m.position.z).powi(2); + d >= distance * distance +} +impl Goal for WanderToPosition { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + m.extra.point.is_some_and(|p| too_far(m, p, self.stop)) + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + m.extra.point = None; + m.nav_stop(); + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(p) = m.extra.point else { return }; + if !m.ai.nav.is_done() { + return; + } + if too_far(m, p, 10.0) { + let d = [ + p[0].floor() - m.position.x, + p[1].floor() - m.position.y, + p[2].floor() - m.position.z, + ]; + let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt().max(1e-9); + let at = [ + d[0] / len * 10.0 + m.position.x, + d[1] / len * 10.0 + m.position.y, + d[2] / len * 10.0 + m.position.z, + ]; + m.nav_move_to(cx.w, at, self.speed); + } else { + m.nav_move_to(cx.w, [p[0].floor(), p[1].floor(), p[2].floor()], self.speed); + } + } +} +/// `Mob.isWithinHome`. +pub fn within_home(m: &Mob) -> bool { + let Some(h) = m.extra.home else { return true }; + let r = m.extra.ints[4]; + if r <= 0 { + return true; + } + let d = (h[0] - m.position.x.floor() as i32).pow(2) + + (h[1] - m.position.y.floor() as i32).pow(2) + + (h[2] - m.position.z.floor() as i32).pow(2); + d < r * r +} +/// `MoveTowardsRestrictionGoal`. +#[derive(Clone, Debug)] +struct MoveTowardsRestriction { + speed: f64, + wanted: [f64; 3], +} +impl MoveTowardsRestriction { + fn new(speed: f64) -> Self { + Self { + speed, + wanted: [0.0; 3], + } + } +} +impl Goal for MoveTowardsRestriction { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if within_home(m) { + return false; + } + let Some(h) = m.extra.home else { return false }; + let to = [ + f64::from(h[0]) + 0.5, + f64::from(h[1]), + f64::from(h[2]) + 0.5, + ]; + match m.default_random_pos_towards(cx.w, 16, 7, to, std::f64::consts::FRAC_PI_2) { + Some(p) => { + self.wanted = p; + true + } + None => false, + } + } + fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + !m.ai.nav.is_done() + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + m.nav_move_to(cx.w, self.wanted, self.speed); + } +} +/// `WanderingTrader.maybeDespawn` in `aiStep`. +pub fn ai_step(m: &mut Mob, _w: &MobWorld) { + if m.extra.ints[5] > 0 && !m.extra.flag2 { + m.extra.ints[5] -= 1; + if m.extra.ints[5] == 0 { + m.removed = true; + } + } +} +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn despawn_delay_is_two_days() { + assert_eq!(DESPAWN_DELAY, 2 * 24000); + } +} diff --git a/crates/horizon-client/src/mobs/villager.rs b/crates/horizon-client/src/mobs/villager.rs index 105db50f2..a458a054e 100644 --- a/crates/horizon-client/src/mobs/villager.rs +++ b/crates/horizon-client/src/mobs/villager.rs @@ -442,7 +442,7 @@ fn work(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } } pub fn sleeping(m: &Mob) -> bool { - m.extra.ints[1] != 0 + matches!(m.species(), Species::Villager | Species::WanderingTrader) && m.extra.ints[1] != 0 } /// `LivingEntity.startSleeping`: lie in the bed (`setPosToBed`). fn start_sleeping(m: &mut Mob, p: [i32; 3], w: &MobWorld) { diff --git a/crates/horizon-client/src/projectiles.rs b/crates/horizon-client/src/projectiles.rs index 84e4a7a69..596dc8e18 100644 --- a/crates/horizon-client/src/projectiles.rs +++ b/crates/horizon-client/src/projectiles.rs @@ -484,6 +484,12 @@ impl Projectile { ); } ProjectileKind::Arrow { .. } => {} + // LlamaSpit.tick: gone in water; drag and gravity follow the move. + ProjectileKind::LlamaSpit => { + if water { + return (false, Hit::None); + } + } _ => { // ThrowableProjectile: gravity, then inertia. self.velocity.y -= self.gravity(); @@ -548,6 +554,32 @@ impl Projectile { } return (false, Hit::Block { pos, at, face }); } + if self.kind == ProjectileKind::LlamaSpit { + // The 0.25 box touching anything but air discards the spit. + let h = 0.125; + let touches = [-h, h].iter().any(|dx| { + [-h, h].iter().any(|dy| { + [-h, h].iter().any(|dz| { + !w.empty([ + (from.x + dx).floor() as i32, + (from.y + dy + h).floor() as i32, + (from.z + dz).floor() as i32, + ]) + }) + }) + }); + if touches { + return (false, Hit::None); + } + self.position = to; + self.velocity = Vec3::new( + self.velocity.x * 0.99, + self.velocity.y * 0.99 - self.gravity(), + self.velocity.z * 0.99, + ); + self.update_rotation(); + return (self.position.y > -128.0 && self.age < 6000, Hit::None); + } self.position = to; if self.is_arrow() { // AbstractArrow.tick: inertia 0.99 (0.6 in water) after moving, then gravity. @@ -638,6 +670,17 @@ mod tests { assert!((p.position.x - 0.99).abs() < 1e-9); } #[test] + fn llama_spit_moves_first_then_drags_and_falls() { + let mut p = Projectile::new(ProjectileKind::LlamaSpit, Vec3::new(0.0, 100.0, 0.0), None); + p.velocity = Vec3::new(1.0, 0.0, 0.0); + let w = Empty(vec![]); + let (keep, _) = p.tick(&w); + assert!(keep); + assert!((p.position.x - 1.0).abs() < 1e-9); + assert!((p.velocity.x - 0.99).abs() < 1e-9); + assert!((p.velocity.y + 0.06).abs() < 1e-9); + } + #[test] fn arrow_applies_drag_then_gravity_after_moving() { let mut p = Projectile::new( ProjectileKind::Arrow {