diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 729ac88f1..528f7e540 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -10,7 +10,7 @@ use horizon_client::{ chunk::{Chunk, HEIGHT, MIN_Y}, collisions, containers::{BlockEntity, CreakingHeart}, - items::Items, + items::{ItemStack, Items}, light::{LightTables, light_chunk}, mobs::{ Damage, MobType, creaking, @@ -87,7 +87,9 @@ fn parse(text: &str) -> Vec { } } "origin" => s.origin = [f[1].parse().unwrap(), f[2].parse().unwrap()], - "fill" | "block" => s.blocks.push(f.iter().map(|x| (*x).to_owned()).collect()), + "fill" | "block" | "chest" => { + 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" => { @@ -559,6 +561,14 @@ fn print(out: &mut String, t: i32, i: usize, m: &Mob) { if m.species() == Species::Villager { let _ = write!(out, "\tvx {}", villager(m)); } + if m.species() == Species::CopperGolem { + let held = horizon_client::mobs::transport_items::held(m).map_or("-".into(), stack); + let opened = m + .extra + .opened_chest + .map_or("-".into(), |p| format!("{},{},{}", p[0], p[1], p[2])); + let _ = write!(out, "\tcg {} {held} {opened}", m.extra.variant3); + } out.push('\n'); } @@ -696,8 +706,23 @@ fn main() -> horizon_client::Result<()> { } for b in &s.blocks { let n = |i: usize| b[i].parse::().unwrap(); - if b[0] == "block" { + if b[0] == "block" || b[0] == "chest" { world.set(n(1), n(2), n(3), state(registry, &b[4]))?; + if b[0] == "chest" { + // chest X Y Z STATE SLOTS: item*count or - per slot. + let mut slots = vec![None; 27]; + for (k, item) in b.get(5).map_or("", String::as_str).split(',').enumerate() { + if let Some((id, count)) = item.split_once('*') { + slots[k] = Some(ItemStack::new( + &format!("minecraft:{id}"), + count.parse().unwrap(), + )); + } + } + world + .block_entities + .insert((n(1), n(2), n(3)), BlockEntity::Chest(slots)); + } } else { let st = state(registry, &b[7]); for x in n(1).min(n(4))..=n(1).max(n(4)) { @@ -766,6 +791,14 @@ fn main() -> horizon_client::Result<()> { "tame" => m.extra.tame = true, x if x.starts_with("age=") => m.extra.age = x[4..].parse().unwrap(), x if x.starts_with("strength=") => m.extra.variant2 = x[9..].parse().unwrap(), + x if x.starts_with("hand=") => { + let (id, count) = x[5..].split_once('*').unwrap(); + let stack = + ItemStack::new(&format!("minecraft:{id}"), count.parse().unwrap()); + horizon_client::mobs::transport_items::set_held(&mut m, Some(stack)); + } + // Set once the brain exists (below). + x if x.starts_with("cooldown=") => {} "leashed" => m.extra.leash = Some(horizon_client::mobs::leash::Holder::Player), x if x.starts_with("leashto=") => { let n: u32 = x[8..].parse().unwrap(); @@ -794,6 +827,12 @@ fn main() -> horizon_client::Result<()> { if horizon_client::mobs::animal_brain::kind_of(&m).is_some() { horizon_client::mobs::animal_brain::init(&mut m, spec.seed); } + if let Some(c) = spec.flags.iter().find_map(|f| f.strip_prefix("cooldown=")) { + horizon_client::mobs::animal_brain::set_transport_cooldown( + &mut m, + c.parse().unwrap(), + ); + } mobs.push(m); } let mut player = s.player.map(|p| { @@ -854,6 +893,7 @@ fn main() -> horizon_client::Result<()> { world_seed: 0, // FlatLevelSource.getSeaLevel. sea_level: -63, + items: Some(&items), } }; } @@ -964,6 +1004,36 @@ fn main() -> horizon_client::Result<()> { &mut born, s.time, ); + // What a copper golem did to chests, before the next mob ticks. + for e in &events[from.min(events.len())..] { + match e { + MobEvent::ChestOpen { chest, open } => { + let o = world + .chest_openers + .entry((chest[0], chest[1], chest[2])) + .or_insert((0, 0.0)); + if *open { + o.0 += 1; + o.1 = o.1.max(3.0); + } else { + o.0 -= 1; + if o.0 == 0 { + o.1 = 0.0; + } + } + } + MobEvent::ChestSlot { chest, slot, stack } => { + if let Some(e) = world + .block_entities + .get_mut(&(chest[0], chest[1], chest[2])) + && let Some(sl) = e.slots_mut().get_mut(*slot) + { + *sl = stack.clone(); + } + } + _ => {} + } + } // ServerLevel ticks entities one after another: the ones // after this mob see it as it is now. if let Some(e) = snapshot.iter_mut().find(|e| e.id == mobs[i].id) { @@ -1033,6 +1103,34 @@ fn main() -> horizon_client::Result<()> { for (at, h) in &hearts { print_heart(&mut out, t, registry, &world, *at, h, &scratch); } + for b in s.blocks.iter().filter(|b| b[0] == "chest") { + let n = |i: usize| b[i].parse::().unwrap(); + let key = (n(1), n(2), n(3)); + let Some(e) = world.block_entities.get(&key) else { + continue; + }; + let mut slots: Vec = e + .slots() + .iter() + .map(|s| s.as_ref().map_or("-".into(), stack)) + .collect(); + while slots.last().is_some_and(|s| s == "-") { + slots.pop(); + } + let count = world.chest_openers.get(&key).map_or(0, |o| o.0); + let _ = writeln!( + out, + "{t} chest {},{},{} {} {count}", + key.0 - s.origin[0], + key.1, + key.2 - s.origin[1], + if slots.is_empty() { + "-".into() + } else { + slots.join(",") + } + ); + } for line in traces { let _ = writeln!(out, "{line}"); } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2b4521e34..ed93ebf36 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -755,8 +755,6 @@ struct Game<'a> { ender_open: Option<(i32, i32, i32)>, /// Block entity data of broken blocks waiting for their dropped item. pending: spill::Pending, - /// The chest each copper golem has open (`CopperGolem.openedChestPos`). - golem_openers: HashMap, /// Item entities spawned and block entities removed while the block /// behaviour ran (spilled contents, popped resources). spill: spill::Spill, @@ -2816,7 +2814,7 @@ impl Game<'_> { self.spawn_loaded_entities(); if running { self.tick_mobs()?; - self.tick_copper_golems(); + self.recheck_golem_openers(); self.tick_experience(); } self.tick_lan(); @@ -8390,7 +8388,6 @@ pub fn run() -> Result<()> { ender_items: vec![None; 27], ender_open: None, pending: Default::default(), - golem_openers: HashMap::new(), spill: Default::default(), recipe_ui: Default::default(), mount_menu: Default::default(), diff --git a/crates/horizon-client/src/game/copper_golems.rs b/crates/horizon-client/src/game/copper_golems.rs index 209b2078d..59cc3c8b7 100644 --- a/crates/horizon-client/src/game/copper_golems.rs +++ b/crates/horizon-client/src/game/copper_golems.rs @@ -1,177 +1,151 @@ -//! Copper golems on the game side: `TransportItemsBetweenContainers` (carry -//! items from copper chests to ordinary chests), weathering and turning into -//! statues, and the hand-over, waxing, scraping and shearing interactions. +//! Copper golems on the game side: what their brain (`mobs::transport_items`) +//! does to chests (opener counts, the lid block events, slots), the openers +//! recheck, turning into statues, and the hand-over, waxing, scraping and +//! shearing interactions. use super::Game; use horizon_client::{ - containers::BlockEntity, items::ItemStack, - mobs::{Mob, Species, copper_golem as cg, goals::should_panic}, + mobs::{ + Mob, Species, + transport_items::{held, set_held}, + }, }; use horizon_core::random::RandomSource; use horizon_world::chunk::BlockState; -type Key = (i32, i32, i32); -/// `TransportItemState`. -const TRAVELLING: i32 = 0; -const QUEUING: i32 = 1; -const INTERACTING: i32 = 2; -/// `ContainerInteractionState` (0 = none). -const PICKUP_ITEM: i32 = 1; -const PICKUP_NO_ITEM: i32 = 2; -const PLACE_ITEM: i32 = 3; -const PLACE_NO_ITEM: i32 = 4; -/// Positions that were unreachable are kept in `positions` with this offset. -const UNREACHABLE: i32 = 1 << 20; -/// `TransportItemsBetweenContainers.VISITED_POSITIONS_MEMORY_TIME`. -const MEMORY_TICKS: i32 = 6000; - -/// Whether a block is a copper chest (the pick-up sources). -pub(super) fn is_copper_chest(name: &str) -> bool { - name.ends_with("copper_chest") -} -/// The held stack (`getMainHandItem`). -pub(super) fn held(m: &Mob) -> Option<&ItemStack> { - m.extra.items.first().and_then(Option::as_ref) -} -/// `setItemInHand(MAIN_HAND, ..)`, keeping the rendered copy in step. -pub(super) fn set_held(m: &mut Mob, stack: Option) { - let stack = stack.filter(|s| s.count > 0); - m.extra.main_hand = stack.as_ref().map(|s| s.item.clone()); - m.extra.ints[1] = stack.as_ref().map_or(0, |s| s.count as i32); - if m.extra.items.is_empty() { - m.extra.items.push(None); - } - m.extra.items[0] = stack; -} -fn visited(m: &Mob) -> Vec<[i32; 3]> { - m.extra - .positions - .iter() - .filter(|p| p[1] < UNREACHABLE) - .copied() - .collect() -} -fn blocked_list(m: &Mob) -> impl Iterator + '_ { - m.extra.positions.iter().map(|p| { - if p[1] >= UNREACHABLE { - [p[0], p[1] - UNREACHABLE, p[2]] - } else { - *p - } - }) -} -fn chest_center(h: [i32; 3]) -> [f64; 3] { - [ - f64::from(h[0]) + 0.5, - f64::from(h[1]) + 0.5, - f64::from(h[2]) + 0.5, - ] -} -/// The copper golem state the model, sounds and animations follow. -fn set_state(m: &mut Mob, state: u8) { - m.extra.variant3 = state; -} +/// `ContainerOpenersCounter.CHECK_TICK_DELAY`. +const RECHECK_TICKS: i64 = 5; impl Game<'_> { - pub(super) fn tick_copper_golems(&mut self) { - let ids: Vec = self - .mobs - .iter() - .filter(|m| m.species() == Species::CopperGolem && m.alive() && !m.removed) - .map(|m| m.id) - .collect(); - for id in ids { - let Some(i) = self.mobs.iter().position(|m| m.id == id) else { + /// A copper golem opened or closed a chest half: the counter changes and + /// the clients see the block event (`openerCountChanged`). + pub(super) fn golem_chest_open(&mut self, chest: [i32; 3], open: bool) { + let key = (chest[0], chest[1], chest[2]); + let entry = self.world.chest_openers.entry(key).or_insert((0, 0.0)); + if open { + entry.0 += 1; + entry.1 = entry.1.max(3.0); + } else { + entry.0 -= 1; + if entry.0 == 0 { + entry.1 = 0.0; + } + } + let count = entry.0; + if count <= 0 { + self.world.chest_openers.remove(&key); + } + self.block_entity_event(chest, 1, count.max(0)); + } + /// A copper golem took from or filled a chest slot. + pub(super) fn golem_chest_slot( + &mut self, + chest: [i32; 3], + slot: usize, + stack: Option, + ) { + if let Some(e) = self + .world + .block_entities + .get_mut(&(chest[0], chest[1], chest[2])) + && let Some(s) = e.slots_mut().get_mut(slot) + { + *s = stack; + } + } + /// `ContainerOpenersCounter.recheckOpeners` every five ticks: the golems + /// whose opened chest is this one, within its range plus 4; when none + /// is left the chest closes (a double chest the golem left open). + pub(super) fn recheck_golem_openers(&mut self) { + if self.world.game_time % RECHECK_TICKS != 0 { + return; + } + let open: Vec<(i32, i32, i32)> = self.world.chest_openers.keys().copied().collect(); + for key in open { + let p = [key.0, key.1, key.2]; + let other = self.chest_other_half(key).map(|o| [o.0, o.1, o.2]); + let range = self.world.chest_openers.get(&key).map_or(0.0, |o| o.1) + 4.0; + let area = horizon_core::geometry::Aabb::new( + horizon_core::geometry::Vec3::new( + f64::from(p[0]) - range, + f64::from(p[1]) - range, + f64::from(p[2]) - range, + ), + horizon_core::geometry::Vec3::new( + f64::from(p[0]) + 1.0 + range, + f64::from(p[1]) + 1.0 + range, + f64::from(p[2]) + 1.0 + range, + ), + ); + let count = self + .mobs + .iter() + .filter(|m| { + m.species() == Species::CopperGolem + && !m.removed + && m.extra + .opened_chest + .is_some_and(|o| o == p || Some(o) == other) + && m.bounds().intersects(area) + }) + .count() as i32; + let before = self.world.chest_openers.get(&key).map_or(0, |o| o.0); + if count == before { continue; - }; - let mut m = self.mobs[i].clone(); - self.copper_golem_step(&mut m); - if let Some(i) = self.mobs.iter().position(|x| x.id == id) { - self.mobs[i] = m; } - } - let alive: std::collections::HashSet = self.mobs.iter().map(|m| m.id).collect(); - self.golem_openers.retain(|id, _| alive.contains(id)); - } - fn copper_golem_step(&mut self, m: &mut Mob) { - if self.golem_weathering(m) { - return; - } - // CountDownCooldownTicks(TRANSPORT_ITEMS_COOLDOWN_TICKS). - if m.extra.scratch[3] > 0 { - m.extra.scratch[3] -= 1; - } - // The visited positions fade after 6000 ticks. - if m.extra.ints[2] > 0 && m.age as i32 >= m.extra.ints[2] { - m.extra.positions.clear(); - m.extra.ints[2] = 0; - } - let running = m.extra.scratch[3] <= 0 && !should_panic(m) && m.extra.leash.is_none(); - if !running { - if m.extra.home.is_some() || m.extra.scratch[0] != TRAVELLING { - self.golem_on_start_travelling(m); - m.extra.point = None; - m.ai.nav.stop(); + if count == 0 { + self.world.chest_openers.remove(&key); + self.golem_chest_sound(p, false); + } else if let Some(o) = self.world.chest_openers.get_mut(&key) { + o.0 = count; } - return; - } - let invalid = self.golem_update_invalid_target(m); - if m.extra.home.is_none() { - self.golem_on_start_travelling(m); - return; - } - if invalid { - return; - } - if m.extra.scratch[0] == QUEUING { - self.golem_on_queuing(m); - } - if m.extra.scratch[0] == TRAVELLING { - self.golem_on_travel(m); - } - if m.extra.scratch[0] == INTERACTING { - self.golem_on_reached(m); + self.block_entity_event(p, 1, count); } } - // ---- weathering ------------------------------------------------------- - /// `CopperGolem.updateWeathering`; true when it turned into a statue. - fn golem_weathering(&mut self, m: &mut Mob) -> bool { - let now = self.world.game_time; - let next = m.extra.vector[0] as i64; - if next == -2 { - return false; - } - // updateWeathering draws from the level random. - let r = &mut self.world.random; - let mut interval = || 504_000 + i64::from(r.next_int_bound(48_001).unwrap_or(0)); - if next == -1 { - m.extra.vector[0] = (now + interval()) as f64; - return false; - } - let fully = m.extra.variant >= 3; - if now >= next && !fully { - let new = cg::weather_next(m.extra.variant); - m.extra.variant = new; - m.extra.vector[0] = if new >= 3 { - 0.0 - } else { - (next + interval()) as f64 - }; - } - if fully && self.golem_can_turn_to_statue(m) { - self.golem_turn_to_statue(m); - return true; - } - false - } - fn golem_can_turn_to_statue(&mut self, m: &mut Mob) -> bool { - let p = [ - m.position.x.floor() as i32, - m.position.y.floor() as i32, - m.position.z.floor() as i32, + /// `ChestBlockEntity.playSound` for a chest the recheck closed. + fn golem_chest_sound(&mut self, p: [i32; 3], open: bool) { + let name = self + .res + .facts + .get(self.world.block(p[0], p[1], p[2])) + .name + .clone(); + let base = name + .trim_start_matches("minecraft:") + .trim_start_matches("waxed_"); + let kind = if !base.ends_with("copper_chest") { + "chest" + } else if base.starts_with("weathered") { + "copper_chest_weathered" + } else if base.starts_with("oxidized") { + "copper_chest_oxidized" + } else { + "copper_chest" + }; + let side = if open { "open" } else { "close" }; + let at = [ + f64::from(p[0]) + 0.5, + f64::from(p[1]) + 0.5, + f64::from(p[2]) + 0.5, ]; - let at = self.world.block(p[0], p[1], p[2]); - self.res.facts.is_air(at) && self.world.random.next_float() <= 0.0058 + let pitch = self.world.random.next_float() * 0.1 + 0.9; + self.audio.play( + &format!("minecraft:block.{kind}.{side}"), + Some(at), + 0.5, + pitch, + ); + } + /// `CopperGolem.turnToStatue`, which its weathering asked for. + pub(super) fn golem_become_statue(&mut self, id: u32) { + let Some(i) = self.mobs.iter().position(|m| m.id == id) else { + return; + }; + let mut m = self.mobs[i].clone(); + self.golem_turn_to_statue(&mut m); + if let Some(i) = self.mobs.iter().position(|x| x.id == id) { + self.mobs[i] = m; + } } fn golem_turn_to_statue(&mut self, m: &mut Mob) { let pos = [ @@ -202,7 +176,7 @@ impl Game<'_> { return; } self.golem_drop_equipment(m); - self.golem_release(m); + m.extra.opened_chest = None; if m.extra.leash.is_some() { self.break_leash(m.id, true, false); m.extra.leash = None; @@ -229,450 +203,6 @@ impl Game<'_> { self.spawn_at_location(at, 0.0, antenna); } } - // ---- containers ------------------------------------------------------- - /// The block entities of the container at a chest, in slot order. - fn golem_container(&self, key: Key) -> Vec { - let Some(other) = self.chest_other_half(key) else { - return vec![key]; - }; - let right = self - .res - .assets - .registry - .state(self.world.block(key.0, key.1, key.2)) - .and_then(|s| s.properties.get("type")) - .is_some_and(|t| t == "right"); - if right { - vec![key, other] - } else { - vec![other, key] - } - } - fn golem_block_name(&self, key: Key) -> std::sync::Arc { - self.res - .facts - .get(self.world.block(key.0, key.1, key.2)) - .name - .clone() - } - fn golem_chest_blocked(&self, keys: &[Key]) -> bool { - keys.iter().any(|k| { - let above = self.world.block(k.0, k.1 + 1, k.2); - self.res.behaviours.facts(above).flags - & horizon_world::level::data::state_flags::CONDUCTOR - != 0 - }) - } - fn golem_slots(&self, keys: &[Key]) -> Vec> { - keys.iter() - .filter_map(|k| self.world.block_entities.get(k)) - .flat_map(|e| e.slots().to_vec()) - .collect() - } - fn golem_slot_mut(&mut self, keys: &[Key], mut n: usize) -> Option<&mut Option> { - for k in keys { - let len = self.world.block_entities.get(k)?.slots().len(); - if n < len { - return self.world.block_entities.get_mut(k)?.slots_mut().get_mut(n); - } - n -= len; - } - None - } - fn golem_max_stack(&self, stack: &ItemStack) -> u32 { - self.res - .items - .get(&stack.item) - .map_or(64, |i| i.max_stack) - .max(1) - } - /// `pickupItemFromContainer`: up to 16 of the first non-empty slot. - fn golem_pick_up(&mut self, keys: &[Key]) -> Option { - let slots = self.golem_slots(keys); - let (n, stack) = slots - .iter() - .enumerate() - .find_map(|(n, s)| s.as_ref().map(|s| (n, s.clone())))?; - let take = stack.count.min(16); - let slot = self.golem_slot_mut(keys, n)?; - let mut out = stack; - out.count = take; - match slot { - Some(s) if s.count > take => s.count -= take, - _ => *slot = None, - } - Some(out) - } - /// `addItemsToContainer`: the part that did not fit. - fn golem_put_down(&mut self, keys: &[Key], mut stack: ItemStack) -> Option { - let max = self.golem_max_stack(&stack); - let slots = self.golem_slots(keys); - for (n, existing) in slots.iter().enumerate() { - match existing { - None => { - if let Some(slot) = self.golem_slot_mut(keys, n) { - *slot = Some(stack); - } - return None; - } - Some(e) - if e.item == stack.item - && e.damage == stack.damage - && e.extra == stack.extra - && e.count < max => - { - let room = max - e.count; - let add = room.min(stack.count); - if let Some(Some(s)) = self.golem_slot_mut(keys, n) { - s.count += add; - } - // Vanilla subtracts the whole room, which empties the stack - // when it fitted. - stack.count = stack.count.saturating_sub(room); - if stack.count == 0 { - return None; - } - } - _ => {} - } - } - Some(stack) - } - /// Whether any other golem or a player has the chest open. - fn golem_chest_busy(&self, m: &Mob, keys: &[Key]) -> bool { - self.golem_openers - .iter() - .any(|(id, k)| *id != m.id && keys.contains(k)) - || self.container.is_some_and(|c| keys.contains(&c)) - } - // ---- the behaviour ---------------------------------------------------- - fn golem_wanted_block(&self, m: &Mob, key: Key) -> bool { - let name = self.golem_block_name(key); - if held(m).is_none() { - is_copper_chest(&name) - } else { - matches!(&*name, "minecraft:chest" | "minecraft:trapped_chest") - } - } - fn golem_update_invalid_target(&mut self, m: &mut Mob) -> bool { - if self.golem_has_valid_target(m) { - return false; - } - self.golem_stop_targeting(m); - match self.golem_find_target(m) { - Some(t) => { - m.extra.home = Some([t.0, t.1, t.2]); - self.golem_on_start_travelling(m); - self.golem_set_visited(m, [t.0, t.1, t.2]); - } - None => self.golem_enter_cooldown(m), - } - true - } - fn golem_has_valid_target(&mut self, m: &mut Mob) -> bool { - let Some(h) = m.extra.home else { return false }; - let key = (h[0], h[1], h[2]); - let valid = self.golem_wanted_block(m, key) - && matches!( - self.world.block_entities.get(&key), - Some(BlockEntity::Chest(_)) - ) - && !self.golem_chest_blocked(&self.golem_container(key)); - if !valid { - return false; - } - if m.extra.scratch[0] != TRAVELLING { - return true; - } - if self.golem_valid_travelling_path(m, h) { - return true; - } - self.golem_mark_unreachable(m, h); - false - } - /// `hasValidTravellingPath`, without the line-of-sight clip. - fn golem_valid_travelling_path(&mut self, m: &mut Mob, h: [i32; 3]) -> bool { - let w = self.mob_world_base(&[]); - let path = match &m.ai.nav.path { - Some(p) => Some(p.clone()), - None => m.create_path_to(&w, h, 0), - }; - let from = match path.as_ref().and_then(|p| p.end()) { - Some(n) => [ - f64::from(n.x) + 0.5, - f64::from(n.y) + m.kind.height / 2.0, - f64::from(n.z) + 0.5, - ], - None => [ - m.position.x, - m.position.y + m.kind.height / 2.0, - m.position.z, - ], - }; - let reach = golem_within(m, self.golem_range(m), from, h); - (path.is_none() && !reach) || reach - } - fn golem_range(&self, m: &Mob) -> f64 { - if m.ai.nav.path.as_ref().is_some_and(|p| p.is_done()) { - 1.0 - } else { - 0.5 - } - } - fn golem_find_target(&self, m: &Mob) -> Option { - let bx = m.position.x.floor() as i32; - let by = m.position.y.floor() as i32; - let bz = m.position.z.floor() as i32; - let skip: Vec<[i32; 3]> = blocked_list(m).collect(); - let mut best: Option<(f64, Key)> = None; - for (key, entity) in &self.world.block_entities { - if !matches!(entity, BlockEntity::Chest(_)) { - continue; - } - if (key.0 - bx).abs() > 32 || (key.1 - by).abs() > 8 || (key.2 - bz).abs() > 32 { - continue; - } - let center = chest_center([key.0, key.1, key.2]); - let d = (center[0] - m.position.x).powi(2) - + (center[1] - m.position.y).powi(2) - + (center[2] - m.position.z).powi(2); - if best.is_some_and(|(b, _)| d >= b) { - continue; - } - if !self.golem_wanted_block(m, *key) { - continue; - } - let keys = self.golem_container(*key); - if keys.iter().any(|k| skip.contains(&[k.0, k.1, k.2])) { - continue; - } - if self.golem_chest_blocked(&keys) { - continue; - } - best = Some((d, *key)); - } - best.map(|b| b.1) - } - fn golem_set_visited(&mut self, m: &mut Mob, h: [i32; 3]) { - let mut list = visited(m); - if !list.contains(&h) { - list.push(h); - } - if list.len() > 10 { - self.golem_enter_cooldown(m); - return; - } - m.extra.positions.retain(|p| p[1] >= UNREACHABLE); - m.extra.positions.extend(list); - m.extra.ints[2] = m.age as i32 + MEMORY_TICKS; - } - fn golem_mark_unreachable(&mut self, m: &mut Mob, h: [i32; 3]) { - m.extra.positions.retain(|p| *p != h); - let marked = [h[0], h[1] + UNREACHABLE, h[2]]; - if !m.extra.positions.contains(&marked) { - m.extra.positions.push(marked); - } - let count = m - .extra - .positions - .iter() - .filter(|p| p[1] >= UNREACHABLE) - .count(); - if count > 50 { - self.golem_enter_cooldown(m); - } else { - m.extra.ints[2] = m.age as i32 + MEMORY_TICKS; - } - } - fn golem_stop_targeting(&mut self, m: &mut Mob) { - m.extra.scratch[1] = 0; - m.extra.home = None; - m.extra.point = None; - m.ai.nav.stop(); - } - fn golem_clear_memories(&mut self, m: &mut Mob) { - self.golem_stop_targeting(m); - m.extra.positions.clear(); - } - fn golem_enter_cooldown(&mut self, m: &mut Mob) { - self.golem_stop_targeting(m); - m.extra.scratch[3] = 140; - m.extra.positions.clear(); - } - /// `onStartTravelling` and the golem's own consumer. - fn golem_on_start_travelling(&mut self, m: &mut Mob) { - self.golem_release(m); - set_state(m, cg::IDLE); - m.extra.scratch[0] = TRAVELLING; - m.extra.scratch[2] = 0; - m.extra.scratch[1] = 0; - } - /// `clearOpenedChestPos` (and so `stopOpen` at the next recheck). - fn golem_release(&mut self, m: &Mob) { - if let Some(key) = self.golem_openers.remove(&m.id) { - let keys = self.golem_container(key); - if !self.golem_chest_busy(m, &keys) { - self.golem_chest_sound(key, false); - } - } - } - fn golem_chest_sound(&mut self, key: Key, open: bool) { - let name = self.golem_block_name(key); - let base = name - .trim_start_matches("minecraft:") - .trim_start_matches("waxed_"); - let kind = if base.starts_with("weathered") { - "copper_chest_weathered" - } else if base.starts_with("oxidized") { - "copper_chest_oxidized" - } else if base.ends_with("copper_chest") { - "copper_chest" - } else { - "chest" - }; - let side = if open { "open" } else { "close" }; - let at = chest_center([key.0, key.1, key.2]); - let pitch = self.world.random.next_float() * 0.1 + 0.9; - self.audio.play( - &format!("minecraft:block.{kind}.{side}"), - Some(at), - 0.5, - pitch, - ); - } - fn golem_on_queuing(&mut self, m: &mut Mob) { - let Some(h) = m.extra.home else { return }; - let keys = self.golem_container((h[0], h[1], h[2])); - if !self.golem_chest_busy(m, &keys) { - m.extra.scratch[0] = TRAVELLING; - m.extra.point = Some(chest_center(h)); - } - } - fn golem_on_travel(&mut self, m: &mut Mob) { - let Some(h) = m.extra.home else { return }; - let key = (h[0], h[1], h[2]); - let keys = self.golem_container(key); - let center = [ - m.position.x, - m.position.y + m.kind.height / 2.0, - m.position.z, - ]; - if golem_within(m, 3.0, center, h) && self.golem_chest_busy(m, &keys) { - // startQueuing. - m.extra.point = None; - m.ai.nav.stop(); - m.extra.scratch[0] = QUEUING; - } else if golem_within(m, self.golem_range(m), center, h) { - // startOnReachedTargetInteraction. - let slots = self.golem_slots(&keys); - let state = if held(m).is_none() { - if slots.iter().any(Option::is_some) { - PICKUP_ITEM - } else { - PICKUP_NO_ITEM - } - } else if slots.iter().all(Option::is_none) - || slots - .iter() - .flatten() - .any(|s| held(m).is_some_and(|h| h.item == s.item)) - { - PLACE_ITEM - } else { - PLACE_NO_ITEM - }; - m.extra.scratch[2] = state; - m.extra.scratch[0] = INTERACTING; - } else { - m.extra.point = Some(chest_center(h)); - } - } - fn golem_on_reached(&mut self, m: &mut Mob) { - let Some(h) = m.extra.home else { return }; - let key = (h[0], h[1], h[2]); - let center = [ - m.position.x, - m.position.y + m.kind.height / 2.0, - m.position.z, - ]; - if !golem_within(m, 2.0, center, h) { - self.golem_on_start_travelling(m); - return; - } - m.extra.scratch[1] += 1; - let ticks = m.extra.scratch[1]; - // onTargetInteraction: stand still, and the reached interaction. - m.extra.point = None; - m.ai.nav.stop(); - let (state, sound) = match m.extra.scratch[2] { - PICKUP_ITEM => (cg::GETTING_ITEM, Some("entity.copper_golem.no_item_get")), - PICKUP_NO_ITEM => ( - cg::GETTING_NO_ITEM, - Some("entity.copper_golem.no_item_no_get"), - ), - PLACE_ITEM => (cg::DROPPING_ITEM, Some("entity.copper_golem.item_drop")), - PLACE_NO_ITEM => ( - cg::DROPPING_NO_ITEM, - Some("entity.copper_golem.item_no_drop"), - ), - _ => (cg::IDLE, None), - }; - if m.extra.scratch[2] != 0 { - if ticks == 1 { - let keys = self.golem_container(key); - if !self.golem_chest_busy(m, &keys) { - self.golem_chest_sound(key, true); - } - self.golem_openers.insert(m.id, key); - set_state(m, state); - } - if ticks == 9 - && let Some(sound) = sound - { - let at = [m.position.x, m.position.y, m.position.z]; - self.audio - .play(&format!("minecraft:{sound}"), Some(at), 1.0, 1.0); - } - if ticks == 60 { - self.golem_release(m); - } - } - if ticks >= 60 { - let keys = self.golem_container(key); - if held(m).is_none() { - if self.golem_slots(&keys).iter().any(Option::is_some) { - // pickUpItems. - let stack = self.golem_pick_up(&keys); - set_held(m, stack); - self.golem_clear_memories(m); - } else { - self.golem_stop_targeting(m); - } - } else if self.golem_slots(&keys).iter().all(Option::is_none) - || self - .golem_slots(&keys) - .iter() - .flatten() - .any(|s| held(m).is_some_and(|h| h.item == s.item)) - { - // putDownItem. - let stack = held(m) - .cloned() - .unwrap_or_else(|| ItemStack::new("minecraft:air", 0)); - let left = self.golem_put_down(&keys, stack); - let emptied = left.is_none(); - set_held(m, left); - if emptied { - self.golem_clear_memories(m); - } else { - self.golem_stop_targeting(m); - } - } else { - self.golem_stop_targeting(m); - } - self.golem_on_start_travelling(m); - } - } // ---- interactions ----------------------------------------------------- /// `CopperGolem.mobInteract`; true when handled. pub(super) fn interact_copper_golem(&mut self, index: usize, item: &str) -> bool { @@ -743,7 +273,7 @@ impl Game<'_> { if is_axe && self.mobs[index].extra.variant > 0 { let m = &mut self.mobs[index]; m.extra.vector[0] = -1.0; - m.extra.variant = cg::weather_previous(m.extra.variant); + m.extra.variant = horizon_client::mobs::copper_golem::weather_previous(m.extra.variant); self.audio .play("minecraft:item.axe.scrape", Some(at), 1.0, 1.0); self.damage_held_tool(); @@ -762,25 +292,3 @@ impl Game<'_> { }) } } -/// `isWithinTargetDistance`: the golem's box centred on `from` against the -/// chest's collision box inflated by `distance` (and half a block vertically). -fn golem_within(m: &Mob, distance: f64, from: [f64; 3], h: [i32; 3]) -> bool { - let hw = m.kind.width / 2.0; - let hh = m.kind.height / 2.0; - let lo = [ - f64::from(h[0]) + 0.0625 - distance, - f64::from(h[1]) - 0.5, - f64::from(h[2]) + 0.0625 - distance, - ]; - let hi = [ - f64::from(h[0]) + 0.9375 + distance, - f64::from(h[1]) + 0.875 + 0.5, - f64::from(h[2]) + 0.9375 + distance, - ]; - from[0] + hw > lo[0] - && from[0] - hw < hi[0] - && from[1] + hh > lo[1] - && from[1] - hh < hi[1] - && from[2] + hw > lo[2] - && from[2] - hw < hi[2] -} diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index bd958893f..a7946e1ed 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -328,6 +328,7 @@ impl Game<'_> { world_seed: self.level.seed, sea_level: if self.dim == Dim::Nether { 32 } else { 63 }, teams: self.mob_teams(), + items: Some(&self.res.items), difficulty: self.local_difficulty( self.player .as_ref() @@ -755,6 +756,11 @@ impl Game<'_> { } } }, + MobEvent::ChestOpen { chest, open } => self.golem_chest_open(chest, open), + MobEvent::ChestSlot { chest, slot, stack } => { + self.golem_chest_slot(chest, slot, stack) + } + MobEvent::BecomeStatue { mob } => self.golem_become_statue(mob), MobEvent::Gift { target, item } => { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == target) && m.saddle_item().is_none() diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 9e0f55097..5bf61ace9 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -57,6 +57,7 @@ pub mod species; pub mod sulfur_cube; pub mod tame; pub mod trader; +pub mod transport_items; pub mod undead; pub mod vex; pub mod villager; @@ -520,6 +521,8 @@ pub struct Extra { pub counter: i32, pub counter2: i32, pub home: Option<[i32; 3]>, + /// A copper golem's `openedChestPos`. + pub opened_chest: Option<[i32; 3]>, pub point: Option<[f64; 3]>, pub vector: [f64; 3], /// Active status effects: (effect id, ticks left, amplifier). @@ -636,6 +639,22 @@ pub struct Mob { #[derive(Clone, Debug)] pub enum MobEvent { Sound(&'static str, [f64; 3], f32, f32), + /// `ChestBlockEntity.startOpen` / `stopOpen` by a copper golem: the + /// chest's opener count goes up or down (interaction range 3). + ChestOpen { + chest: [i32; 3], + open: bool, + }, + /// `CopperGolem.turnToStatue`. + BecomeStatue { + mob: u32, + }, + /// A copper golem took from or filled a chest slot. + ChestSlot { + chest: [i32; 3], + slot: usize, + stack: Option, + }, /// `OfferFlowerGoal.stop`: the item goes to the target's antenna (saddle) /// slot if it is empty, as a guaranteed drop. Gift { @@ -927,6 +946,8 @@ pub struct Seen { pub hurt_by: Option<(Who, i32)>, /// A raider in an active raid. pub active_raid: bool, + /// A copper golem's `openedChestPos` (`ContainerUser.hasContainerOpen`). + pub opened_chest: Option<[i32; 3]>, /// A villager's reputation of the player (`getPlayerReputation`). pub player_rep: i32, /// `isPushable` and pushed by others (`Entity.push(Entity)` moves it). @@ -981,6 +1002,7 @@ impl Mob { delay: m.extra.ints[5], hurt_by: m.ai.last_hurt_by.map(|w| (w, m.ai.last_hurt_by_time)), active_raid: raider::has_active_raid(m), + opened_chest: m.extra.opened_chest, player_rep: match (villager, player) { (true, Some(uuid)) => villager::ext(m).map_or(0, |e| e.gossips.reputation(uuid)), _ => 0, @@ -1137,6 +1159,8 @@ pub struct MobWorld<'a> { pub sea_level: i32, /// The scoreboard teams of the player and the mobs (collision rules). pub teams: Teams, + /// Item data (max stack sizes), when the host has it. + pub items: Option<&'a crate::items::Items>, } /// `Entity.getTeam` of the player and of the mobs on a team. #[derive(Clone, Debug, Default)] diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 9c825d61b..903e0f437 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -370,6 +370,10 @@ pub fn tick( m.update_walk_animation(); m.anim.end_tick(m.ai.swinging); tick_swing(m); + if m.species() == Species::CopperGolem { + // CopperGolem.tick: updateWeathering after the living tick. + super::copper_golem::update_weathering(m, w, level_random, events); + } true } /// LivingEntity.updateSwingTime (6-tick swing duration). @@ -797,7 +801,10 @@ fn server_ai_step( } // Sniffer and HappyGhast.customServerAiStep: the brain (a happy ghast's // only while it is a ghastling), then updateActivity. - if m.species() == Species::Sniffer || m.species() == Species::HappyGhast && m.is_baby() { + if m.species() == Species::Sniffer + || m.species() == Species::HappyGhast && m.is_baby() + || m.species() == Species::CopperGolem + { super::animal_brain::tick(m, w, level_random, events); } { @@ -1276,6 +1283,8 @@ pub fn step_sound( S::CamelHusk => Some(("entity.camel_husk.step", 0.4, 1.0)), S::Camel => Some(("entity.camel.step", 1.0, 1.0)), S::IronGolem => Some(("entity.iron_golem.step", 1.0, 1.0)), + // CopperGolem.playStepSound: its oxidation level's step. + S::CopperGolem => Some((super::copper_golem::sound(m, "step"), 1.0, 1.0)), S::Strider if m.fluids.in_lava => Some(("entity.strider.step_lava", 1.0, 1.0)), S::Strider => Some(("entity.strider.step", 1.0, 1.0)), S::Warden => Some(("entity.warden.step", 10.0, 1.0)), diff --git a/crates/horizon-client/src/mobs/animal_brain.rs b/crates/horizon-client/src/mobs/animal_brain.rs index 9edf2accf..c3bafd68f 100644 --- a/crates/horizon-client/src/mobs/animal_brain.rs +++ b/crates/horizon-client/src/mobs/animal_brain.rs @@ -192,6 +192,10 @@ pub struct Memories { pub sniffer_sniffing_target: Slot<[i32; 3]>, pub sniffer_happy: Slot, pub sniff_cooldown: Slot<()>, + pub gaze_cooldown_ticks: Slot, + pub transport_items_cooldown_ticks: Slot, + pub visited_block_positions: Slot>, + pub unreachable_transport_block_positions: Slot>, } impl Memories { fn tick(&mut self) { @@ -216,6 +220,10 @@ impl Memories { self.sniffer_sniffing_target.tick(); self.sniffer_happy.tick(); self.sniff_cooldown.tick(); + self.gaze_cooldown_ticks.tick(); + self.transport_items_cooldown_ticks.tick(); + self.visited_block_positions.tick(); + self.unreachable_transport_block_positions.tick(); } } @@ -246,6 +254,8 @@ pub enum Kind { Sniffer, /// A happy ghast (the brain ticks while it is a ghastling). Ghastling, + /// `CopperGolemAi`. + CopperGolem, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -273,6 +283,7 @@ impl Kind { Sensor::AdultAnyType, Sensor::Players, ], + Kind::CopperGolem => &[Sensor::Living, Sensor::HurtBy], } } } @@ -302,10 +313,10 @@ fn brain_mut(m: &mut Mob) -> &mut Brain { .as_deref_mut() .expect("the animal brain is built before it is used") } -fn mem(m: &mut Mob) -> &mut Memories { +pub(super) fn mem(m: &mut Mob) -> &mut Memories { &mut brain_mut(m).mem } -fn mem_ref(m: &Mob) -> Option<&Memories> { +pub(super) fn mem_ref(m: &Mob) -> Option<&Memories> { brain(m).map(|b| &b.mem) } @@ -315,6 +326,7 @@ pub fn kind_of(m: &Mob) -> Option { Species::Sniffer => Some(Kind::Sniffer), // Every happy ghast has the brain; only the ghastling's ticks. Species::HappyGhast => Some(Kind::Ghastling), + Species::CopperGolem => Some(Kind::CopperGolem), _ => None, } } @@ -324,6 +336,10 @@ pub fn kind_of(m: &Mob) -> Option { /// The gates shuffle with a random seeded with `shuffle_seed`. pub fn init(m: &mut Mob, shuffle_seed: i64) { let Some(kind) = kind_of(m) else { return }; + // The copper golem's constructor: TRANSPORT_ITEMS_COOLDOWN_TICKS of + // nextInt(60, 100). + let cooldown = + (kind == Kind::CopperGolem).then(|| 60 + m.random.next_int_bound(40).unwrap_or(0)); let sensors = kind .sensors() .iter() @@ -339,10 +355,27 @@ pub fn init(m: &mut Mob, shuffle_seed: i64) { b.list = match kind { Kind::Sniffer => sniffer_package(shuffle_seed), Kind::Ghastling => ghastling_package(shuffle_seed), + Kind::CopperGolem => copper_golem_package(shuffle_seed), }; + if let Some(c) = cooldown { + b.mem.transport_items_cooldown_ticks.set(c); + } m.extra.animal_brain = Some(Box::new(b)); } +/// A copper golem's `TRANSPORT_ITEMS_COOLDOWN_TICKS`, or none for 0. +pub fn set_transport_cooldown(m: &mut Mob, ticks: i32) { + if m.extra.animal_brain.is_none() { + return; + } + let slot = &mut mem(m).transport_items_cooldown_ticks; + if ticks > 0 { + slot.set(ticks); + } else { + slot.clear(); + } +} + /// The happy ghast grew up (`adultGhastSetup`): every running behaviour /// stops (`Brain.stopAll`) and the memories are cleared; the brain no /// longer ticks. @@ -434,6 +467,7 @@ fn update_activity(m: &mut Mob) { let order: &[Act] = match b.kind { Kind::Sniffer => &[Act::Dig, Act::Sniff, Act::Idle], Kind::Ghastling => &[Act::Panic, Act::Idle], + Kind::CopperGolem => &[Act::Idle], }; for &a in order { let ok = match a { @@ -727,6 +761,8 @@ struct Gate { running: bool, random: LegacyRandom, kids: Vec<(B, i32, f64)>, + /// The gate's memory requirements. + when: Option bool>, } impl Gate { fn run_one(seed: i64, kids: Vec<(B, i32)>) -> Self { @@ -734,9 +770,19 @@ impl Gate { running: false, random: LegacyRandom::new(seed), kids: kids.into_iter().map(|(b, w)| (b, w, 0.0)).collect(), + when: None, } } + fn when(mut self, f: fn(&Memories) -> bool) -> Self { + self.when = Some(f); + self + } fn try_start(&mut self, m: &mut Mob, cx: &mut Bx) -> bool { + if let Some(f) = self.when + && !f(mem(m)) + { + return false; + } self.running = true; // ShufflingList.shuffle: a fresh weight for each entry in the // current order, then a stable sort. @@ -780,6 +826,7 @@ enum B { AnimalPanic { t: Timed, fly: bool, + speed: f32, }, MoveToTargetSink { t: Timed, @@ -819,6 +866,8 @@ enum B { running: bool, fly: bool, speed: f32, + /// Horizontal and vertical range (land strolls). + range: (i32, i32), }, /// `BabyFollowAdult.create(3..16, 1.1, memory, true)`: the nearest /// visible player or adult. @@ -827,6 +876,15 @@ enum B { player: bool, }, Gate(Box), + /// `CountDownCooldownTicks(GAZE_COOLDOWN_TICKS)` and + /// `(TRANSPORT_ITEMS_COOLDOWN_TICKS)`. + CountDownGaze(Timed), + CountDownTransport(Timed), + /// `SetEntityLookTargetSometimes.create(PLAYER, 6, 40..80)`: running, + /// and the ticker's ticks until the next start. + LookAtPlayerSometimes(bool, i32), + /// `TransportItemsBetweenContainers`. + Transport(Box), } impl B { @@ -845,7 +903,11 @@ impl B { | B::Searching(t) | B::Scenting(t) | B::Sniffing(t) - | B::DoNothing(t) => t.running, + | B::DoNothing(t) + | B::CountDownGaze(t) + | B::CountDownTransport(t) => t.running, + B::Transport(x) => x.running, + B::LookAtPlayerSometimes(running, _) => *running, B::WalkToLookTarget { running, .. } | B::LookAtPlayer(running) | B::Stroll { running, .. } @@ -869,7 +931,10 @@ impl B { | B::Searching(t) | B::Scenting(t) | B::Sniffing(t) - | B::DoNothing(t) => t.running = false, + | B::DoNothing(t) + | B::CountDownGaze(t) + | B::CountDownTransport(t) => t.running = false, + B::Transport(x) => x.running = false, B::MoveToTargetSink { t, path, .. } => { t.running = false; *path = None; @@ -889,6 +954,7 @@ impl B { self, B::WalkToLookTarget { .. } | B::LookAtPlayer(_) + | B::LookAtPlayerSometimes(..) | B::Stroll { .. } | B::FollowAdult { .. } ) @@ -897,6 +963,7 @@ impl B { match self { B::WalkToLookTarget { running, .. } | B::LookAtPlayer(running) + | B::LookAtPlayerSometimes(running, _) | B::Stroll { running, .. } | B::FollowAdult { running, .. } => *running = on, _ => {} @@ -975,6 +1042,21 @@ impl B { t.begin(cx); true } + B::CountDownGaze(t) => { + if !mem(m).gaze_cooldown_ticks.present() { + return false; + } + t.begin(cx); + true + } + B::CountDownTransport(t) => { + if !mem(m).transport_items_cooldown_ticks.present() { + return false; + } + t.begin(cx); + true + } + B::Transport(x) => x.try_start(m, cx), B::MakeLove { t, spawn_at } => { let mm = mem(m); if !mm.visible_mobs.present() @@ -1116,6 +1198,7 @@ impl B { } B::WalkToLookTarget { .. } | B::LookAtPlayer(_) + | B::LookAtPlayerSometimes(..) | B::Stroll { .. } | B::FollowAdult { .. } => unreachable!("one-shots trigger"), } @@ -1155,7 +1238,33 @@ impl B { mem(m).look_target.set(Tracker::entity(t, true)); true } - B::Stroll { fly, speed, .. } => { + B::LookAtPlayerSometimes(_, ref mut ticks) => { + 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| { + who == Who::Player + && w.target_info(who) + .is_some_and(|t| t.position.distance_squared(m.position) <= 36.0) + }); + let Some(t) = found else { return false }; + // Ticker.tickDownAndCheck (UniformInt 40..80 on the level random). + if *ticks == 0 { + *ticks = 40 + cx.lr.next_int_bound(41).unwrap_or(0) - 1; + return false; + } + *ticks -= 1; + if *ticks != 0 { + return false; + } + mem(m).look_target.set(Tracker::entity(t, true)); + true + } + B::Stroll { + fly, speed, range, .. + } => { if mem(m).walk_target.present() { return false; } @@ -1163,7 +1272,7 @@ impl B { let view = m.view_vector(); m.air_and_water_random_pos(cx.w, 10, 7, -2, view[0], view[2]) } else { - m.land_random_pos(cx.w, 10, 7) + m.land_random_pos(cx.w, range.0, range.1) }; mem(m) .walk_target @@ -1226,7 +1335,7 @@ impl B { m.ai.jump = true; } } - B::AnimalPanic { t, fly } => { + B::AnimalPanic { t, fly, speed } => { if t.timed_out(now) { self.do_stop(m, cx); return; @@ -1234,7 +1343,7 @@ impl B { if m.ai.nav.is_done() { let pos = panic_pos(m, cx.w, *fly); if let Some(p) = pos { - mem(m).walk_target.set(WalkTarget::point(p, 2.0, 0)); + mem(m).walk_target.set(WalkTarget::point(p, *speed, 0)); } } } @@ -1280,6 +1389,21 @@ impl B { _ => self.do_stop(m, cx), } } + B::CountDownGaze(_) => { + let v = mem(m).gaze_cooldown_ticks.value(); + match v { + Some(v) if v > 0 => mem(m).gaze_cooldown_ticks.set(v - 1), + _ => self.do_stop(m, cx), + } + } + B::CountDownTransport(_) => { + let v = mem(m).transport_items_cooldown_ticks.value(); + match v { + Some(v) if v > 0 => mem(m).transport_items_cooldown_ticks.set(v - 1), + _ => self.do_stop(m, cx), + } + } + B::Transport(x) => x.tick_or_stop(m, cx), B::MakeLove { spawn_at, .. } => { let Some(partner) = mem(m).breed_target.value() else { self.do_stop(m, cx); @@ -1422,6 +1546,7 @@ impl B { } B::WalkToLookTarget { .. } | B::LookAtPlayer(_) + | B::LookAtPlayerSometimes(..) | B::Stroll { .. } | B::FollowAdult { .. } => {} } @@ -1461,6 +1586,15 @@ impl B { t.running = false; mem(m).temptation_cooldown_ticks.clear(); } + B::CountDownGaze(t) => { + t.running = false; + mem(m).gaze_cooldown_ticks.clear(); + } + B::CountDownTransport(t) => { + t.running = false; + mem(m).transport_items_cooldown_ticks.clear(); + } + B::Transport(x) => x.do_stop(m, cx), B::MakeLove { t, spawn_at } => { t.running = false; let mm = mem(m); @@ -1536,6 +1670,7 @@ impl B { } B::WalkToLookTarget { .. } | B::LookAtPlayer(_) + | B::LookAtPlayerSometimes(..) | B::Stroll { .. } | B::FollowAdult { .. } => {} } @@ -1653,7 +1788,7 @@ fn follow_temptation_close(m: &mut Mob) -> f64 { 3.5 } } - Kind::Ghastling => 3.0, + Kind::Ghastling | Kind::CopperGolem => 3.0, } } fn can_mate_with(m: &Mob, w: &MobWorld, partner: Who) -> bool { @@ -1777,6 +1912,7 @@ fn sniffer_package(seed: i64) -> Vec { B::AnimalPanic { t: Timed::new(100, 120), fly: false, + speed: 2.0, }, ), e( @@ -1815,6 +1951,7 @@ fn sniffer_package(seed: i64) -> Vec { running: false, fly: false, speed: 1.0, + range: (10, 7), }, 1, ), @@ -1825,6 +1962,59 @@ fn sniffer_package(seed: i64) -> Vec { l } /// `HappyGhastAi.getActivities`, in `availableBehaviorsByPriority` order. +/// `CopperGolemAi.getActivities`, in tick order: the core behaviours take +/// priorities 0 to 5 in turn (`ActivityData.create(CORE, 0, ..)`), the idle +/// ones 0, 1 and 2. +fn copper_golem_package(seed: i64) -> Vec { + let e = |act: Act, b: B| Entry { act, b }; + vec![ + // Priority 0. + e( + Act::Core, + B::AnimalPanic { + t: Timed::new(100, 120), + fly: false, + speed: 1.5, + }, + ), + e(Act::Idle, B::Transport(Box::default())), + // Priority 1. + e(Act::Core, B::LookAtTargetSink(Timed::new(45, 90))), + e(Act::Idle, B::LookAtPlayerSometimes(false, 0)), + // Priority 2: RunOne(stroll or do nothing) while there is no walk + // target and the transport cools down. + e(Act::Core, move_to_target_sink(150, 250)), + e( + Act::Idle, + B::Gate(Box::new( + Gate::run_one( + seed, + vec![ + ( + B::Stroll { + running: false, + fly: false, + speed: 1.0, + range: (2, 2), + }, + 1, + ), + (B::DoNothing(Timed::new(30, 60)), 1), + ], + ) + .when(|mm| { + !mm.walk_target.present() && mm.transport_items_cooldown_ticks.present() + }), + )), + ), + // Priority 3 is InteractWithDoor, which only acts on doors along the + // path; these golems pass none. + // Priorities 4 and 5. + e(Act::Core, B::CountDownGaze(Timed::new(60, 60))), + e(Act::Core, B::CountDownTransport(Timed::new(60, 60))), + ] +} + fn ghastling_package(seed: i64) -> Vec { let e = |act: Act, b: B| Entry { act, b }; vec![ @@ -1836,6 +2026,7 @@ fn ghastling_package(seed: i64) -> Vec { B::AnimalPanic { t: Timed::new(100, 120), fly: true, + speed: 2.0, }, ), e( @@ -1875,6 +2066,7 @@ fn ghastling_package(seed: i64) -> Vec { running: false, fly: true, speed: 1.0, + range: (10, 7), }, 1, ), @@ -2000,6 +2192,23 @@ pub fn describe(m: &Mob) -> Option<(String, String)> { slot!("sniffer_happy", mm.sniffer_happy, |b: &bool| b.to_string()); slot!("sniff_cooldown", mm.sniff_cooldown, |_: &()| "u" .to_string()); + slot!("gaze_cooldown_ticks", mm.gaze_cooldown_ticks, |t: &i32| t + .to_string()); + slot!( + "transport_items_cooldown_ticks", + mm.transport_items_cooldown_ticks, + |t: &i32| t.to_string() + ); + slot!( + "visited_block_positions", + mm.visited_block_positions, + |l: &Vec<[i32; 3]>| format!("n{}", l.len()) + ); + slot!( + "unreachable_transport_block_positions", + mm.unreachable_transport_block_positions, + |l: &Vec<[i32; 3]>| format!("n{}", l.len()) + ); if b.kind == Kind::Sniffer && !m.extra.positions.is_empty() { put( "sniffer_explored_positions", diff --git a/crates/horizon-client/src/mobs/copper_golem.rs b/crates/horizon-client/src/mobs/copper_golem.rs index de037016c..398022485 100644 --- a/crates/horizon-client/src/mobs/copper_golem.rs +++ b/crates/horizon-client/src/mobs/copper_golem.rs @@ -1,12 +1,10 @@ -//! Copper golems (`CopperGolem`, `CopperGolemAi`): they carry items from -//! copper chests to chests (see `game::copper_golems` for the container side -//! of `TransportItemsBetweenContainers`), play the chest interaction -//! animations, spin their heads when idle, oxidise over time and finally turn -//! into statues. +//! Copper golems (`CopperGolem`): their brain (`CopperGolemAi`, in +//! `animal_brain`) carries items from copper chests to chests +//! (`transport_items`); here the chest interaction animations, the idle head +//! spin, and weathering until they turn into statues. use super::{ Mob, MobEvent, MobWorld, anim::{Poses, State}, - goals::{Cx, Goal, JUMP, LOOK, MOVE, Panic, goal_clone}, keyframes::Animation, }; use horizon_core::random::RandomSource; @@ -15,11 +13,10 @@ use std::collections::HashMap; // Copper golem state: `variant` the weathering (0 unaffected .. 3 oxidized), // `variant3` the `CopperGolemState`, `main_hand` with `ints[1]` the carried // stack, the saddle slot the antenna (`EQUIPMENT_SLOT_ANTENNA`), `vector[0]` -// the next weathering tick (-1 unset, -2 waxed), `ints[0]` the idle animation start tick, `home` the chest -// being served with `positions` the visited chests, `point` where it walks, -// `scratch` = [transport phase, ticks since reaching the target, interaction -// state, transport cooldown ticks]. AnimationState slots: idle (0), getting an -// item (1), getting nothing (2), dropping an item (3), dropping nothing (4). +// the next weathering tick (-1 unset, -2 waxed), `ints[0]` the idle animation +// start tick, `opened_chest` the `openedChestPos`. AnimationState slots: idle +// (0), getting an item (1), getting nothing (2), dropping an item (3), +// dropping nothing (4). pub const IDLE: u8 = 0; pub const GETTING_ITEM: u8 = 1; pub const GETTING_NO_ITEM: u8 = 2; @@ -34,12 +31,6 @@ pub fn register(m: &mut Mob) { m.persistent = true; // nextWeatheringTick starts unset (-1); waxed is -2. m.extra.vector[0] = -1.0; - m.extra.scratch[3] = 60 + m.random.next_int_bound(40).unwrap_or(0); - let g = &mut m.ai.goals; - g.add(0, Panic::new(1.5)); - g.add(1, Serve); - g.add(2, super::goals::LookAtPlayer::new(6.0).probability(0.02)); - g.add(3, Idle::default()); } /// `CopperGolemOxidationLevels`: the body and eye textures. pub fn texture(m: &Mob) -> String { @@ -77,101 +68,6 @@ pub fn sound(m: &Mob, what: &str) -> &'static str { _ => "entity.copper_golem.step", } } -/// `CopperGolemAi`'s transport behaviour is running a target. -fn serving(m: &Mob) -> bool { - m.extra.home.is_some() -} -/// `TransportItemsBetweenContainers` walking and looking at its chest, and -/// standing still while interacting with it. -#[derive(Clone, Debug)] -struct Serve; -impl Goal for Serve { - goal_clone!(); - fn flags(&self) -> u8 { - MOVE | LOOK - } - fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool { - serving(m) && !m.ai.panicking - } - fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - self.can_use(m, cx) - } - fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { - let Some(h) = m.extra.home else { return }; - m.look_at([ - f64::from(h[0]) + 0.5, - f64::from(h[1]) + 0.5, - f64::from(h[2]) + 0.5, - ]); - match m.extra.point { - Some(p) => { - if m.ai.nav.is_done() || m.age.is_multiple_of(10) { - let block = [ - p[0].floor() as i32, - p[1].floor() as i32, - p[2].floor() as i32, - ]; - let path = m.create_path_to(cx.w, block, 0); - m.nav_move_to_path(path, 1.0); - } - } - None => { - // stopInPlace. - m.ai.nav.stop(); - m.velocity.x = 0.0; - m.velocity.z = 0.0; - } - } - } - fn stop(&mut self, m: &mut Mob, _: &mut Cx) { - m.ai.nav.stop(); - } -} -/// The idle `RunOne`: `RandomStroll.stroll(1.0, 2, 2)` or `DoNothing(30, 60)`, -/// only while the transport cooldown runs. -#[derive(Clone, Debug, Default)] -struct Idle { - wait: i32, - stroll: bool, -} -impl Goal for Idle { - goal_clone!(); - fn flags(&self) -> u8 { - MOVE | JUMP - } - fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - if serving(m) || m.extra.scratch[3] <= 0 || !m.ai.nav.is_done() { - return false; - } - if m.random.next_int_bound(2).unwrap_or(0) == 0 { - let Some(p) = m.land_random_pos(cx.w, 2, 2) else { - return false; - }; - self.stroll = true; - m.nav_move_to(cx.w, p, 1.0); - } else { - self.stroll = false; - self.wait = 30 + m.random.next_int_bound(30).unwrap_or(0); - } - true - } - fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { - if serving(m) { - return false; - } - if self.stroll { - !m.ai.nav.is_done() - } else { - self.wait > 0 - } - } - fn tick(&mut self, _: &mut Mob, _: &mut Cx) { - self.wait -= 1; - } - fn stop(&mut self, m: &mut Mob, _: &mut Cx) { - m.ai.nav.stop(); - } -} /// `CopperGolem.setupAnimationStates` (client) and the sound of the head spin. pub fn ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec) { let age = m.age as f32; @@ -191,11 +87,14 @@ pub fn ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec) { if m.extra.ints[0] == tick { st[0].start(age); } else if m.extra.ints[0] == 0 { - m.extra.ints[0] = tick + 200 + m.random.next_int_bound(40).unwrap_or(0); + // The client entity's own random, not the server's. + let mut r = + horizon_core::random::LegacyRandom::new(i64::from(m.id) ^ i64::from(tick)); + m.extra.ints[0] = tick + 200 + r.next_int_bound(40).unwrap_or(0); } if tick == m.extra.ints[0] + 10 { let at = [m.position.x, m.position.y, m.position.z]; - events.push(MobEvent::Sound(sound(m, "spin"), at, 1.0, 1.0)); + events.push(MobEvent::LocalSound(sound(m, "spin"), at, 1.0, 1.0)); m.extra.ints[0] = 0; } } @@ -208,6 +107,51 @@ pub fn ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec) { _ => {} } } +/// `CopperGolem.updateWeathering` on the level random: the first tick sets +/// the next weathering tick, which advances the weather state; once +/// oxidized, a golem on an air block may turn into a statue +/// (`MobEvent::BecomeStatue`, done by the host). +pub fn update_weathering( + m: &mut Mob, + w: &MobWorld, + lr: &mut impl RandomSource, + events: &mut Vec, +) { + if !m.alive() || m.removed { + return; + } + let now = w.game_time; + let next = m.extra.vector[0] as i64; + if next == -2 { + return; + } + let interval = |r: &mut dyn FnMut() -> i32| 504_000 + i64::from(r()); + let mut draw = || lr.next_int_bound(48_001).unwrap_or(0); + if next == -1 { + m.extra.vector[0] = (now + interval(&mut draw)) as f64; + return; + } + let fully = m.extra.variant >= 3; + if now >= next && !fully { + let new = weather_next(m.extra.variant); + m.extra.variant = new; + m.extra.vector[0] = if new >= 3 { + 0.0 + } else { + (next + interval(&mut draw)) as f64 + }; + } + if fully { + let p = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + if w.facts.is_air(w.world.block(p[0], p[1], p[2])) && lr.next_float() <= 0.0058 { + events.push(MobEvent::BecomeStatue { mob: m.id }); + } + } +} /// `CopperGolemModel.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/transport_items.rs b/crates/horizon-client/src/mobs/transport_items.rs new file mode 100644 index 000000000..934e59695 --- /dev/null +++ b/crates/horizon-client/src/mobs/transport_items.rs @@ -0,0 +1,827 @@ +//! `TransportItemsBetweenContainers` as the copper golem's brain runs it +//! (`CopperGolemAi`): find the nearest wanted chest (a copper chest with +//! nothing in hand, a chest or trapped chest holding something), walk to it, +//! queue while another golem has it open, open it for 60 ticks and take up +//! to 16 items or put the carried stack down, remembering visited and +//! unreachable chests. +//! +//! The chests are read from the world; what changes them comes out as +//! [`MobEvent::ChestOpen`] and [`MobEvent::ChestSlot`] for the host to apply +//! before the next mob ticks. +use super::{ + Mob, MobEvent, MobWorld, + animal_brain::{Bx, Tracker, WalkTarget, mem, mem_ref}, + copper_golem as cg, +}; +use crate::{containers::BlockEntity, items::ItemStack}; +use horizon_core::{ + geometry::{Aabb, Vec3}, + random::RandomSource, +}; +use horizon_world::java_hash_map::{JavaHashMap, JavaKey}; + +/// `TransportItemState`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum State { + Travelling, + Queuing, + Interacting, +} +/// `ContainerInteractionState`. +#[allow(clippy::enum_variant_names)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Interaction { + PickupItem, + PickupNoItem, + PlaceItem, + PlaceNoItem, +} + +/// `TransportItemTarget`: the chest and its block state when it was chosen. +#[derive(Clone, Debug)] +struct Target { + pos: [i32; 3], + name: String, + /// The halves of the container in slot order (the right half first). + halves: Vec<[i32; 3]>, +} + +#[derive(Clone, Debug)] +pub(super) struct Transport { + pub(super) running: bool, + end: i64, + target: Option, + state: State, + interaction: Option, + ticks: i32, +} +impl Default for Transport { + fn default() -> Self { + Self { + running: false, + end: 0, + target: None, + state: State::Travelling, + interaction: None, + ticks: 0, + } + } +} + +/// The golem's held stack (`getMainHandItem`). +pub fn held(m: &Mob) -> Option<&ItemStack> { + m.extra.items.first().and_then(Option::as_ref) +} +/// `setItemSlot(MAINHAND, ..)`, keeping the rendered copy in step. +pub fn set_held(m: &mut Mob, stack: Option) { + let stack = stack.filter(|s| s.count > 0); + m.extra.main_hand = stack.as_ref().map(|s| s.item.clone()); + m.extra.ints[1] = stack.as_ref().map_or(0, |s| s.count as i32); + if m.extra.items.is_empty() { + m.extra.items.push(None); + } + m.extra.items[0] = stack; +} + +fn name_at(w: &MobWorld, p: [i32; 3]) -> String { + w.facts + .get(w.world.block(p[0], p[1], p[2])) + .name + .to_string() +} +fn is_chest_block(name: &str) -> bool { + matches!(name, "minecraft:chest" | "minecraft:trapped_chest") || name.ends_with("copper_chest") +} +/// `CopperGolemAi.TRANSPORT_ITEM_SOURCE_BLOCK` / `_DESTINATION_BLOCK`. +fn wanted(w: &MobWorld, m: &Mob, name: &str) -> bool { + if held(m).is_none() { + w.has_tag("minecraft:copper_chests", name) || w.has_tag("copper_chests", name) + } else { + matches!(name, "minecraft:chest" | "minecraft:trapped_chest") + } +} +/// `ChestBlock.getConnectedBlockPos`: the other half of a double chest. +fn connected(w: &MobWorld, p: [i32; 3]) -> Option<[i32; 3]> { + let kind = w.prop(p[0], p[1], p[2], "type")?; + if kind == "single" { + return None; + } + let facing = w.prop(p[0], p[1], p[2], "facing")?; + // LEFT: facing.getClockWise(), else getCounterClockWise(). + let order = ["north", "east", "south", "west"]; + let i = order.iter().position(|f| *f == facing)?; + let dir = order[if kind == "left" { + (i + 1) % 4 + } else { + (i + 3) % 4 + }]; + let (dx, dz) = match dir { + "north" => (0, -1), + "south" => (0, 1), + "east" => (1, 0), + _ => (-1, 0), + }; + Some([p[0] + dx, p[1], p[2] + dz]) +} +/// `ChestBlock.isChestBlockedAt` (a cat sitting on it aside): a redstone +/// conductor above. +fn blocked(w: &MobWorld, p: [i32; 3]) -> bool { + let above = w.world.block(p[0], p[1] + 1, p[2]); + w.data.state(above).flags & super::data::REDSTONE_CONDUCTOR != 0 +} +/// `ChestBlock.getContainer(.., false)`: the chest's halves in slot order, +/// none when either half is blocked. +fn container(w: &MobWorld, p: [i32; 3]) -> Option> { + if blocked(w, p) { + return None; + } + let mut halves = vec![p]; + if let Some(other) = connected(w, p) { + let same = w.world.block(other[0], other[1], other[2]) == w.world.block(p[0], p[1], p[2]) + || name_at(w, other) == name_at(w, p) + && w.prop(other[0], other[1], other[2], "facing") + == w.prop(p[0], p[1], p[2], "facing") + && w.prop(other[0], other[1], other[2], "type") + .is_some_and(|t| t != "single") + && w.prop(other[0], other[1], other[2], "type") != w.prop(p[0], p[1], p[2], "type"); + if same + && matches!( + w.world.block_entities.get(&(other[0], other[1], other[2])), + Some(BlockEntity::Chest(_)) + ) + { + if blocked(w, other) { + return None; + } + if w.prop(p[0], p[1], p[2], "type") == Some("right") { + halves.push(other); + } else { + halves.insert(0, other); + } + } + } + Some(halves) +} +fn slots(w: &MobWorld, halves: &[[i32; 3]]) -> Vec> { + halves + .iter() + .filter_map(|h| w.world.block_entities.get(&(h[0], h[1], h[2]))) + .flat_map(|e| e.slots().to_vec()) + .collect() +} +/// Where slot `n` of the container is: the half and its own slot. +fn slot_at(w: &MobWorld, halves: &[[i32; 3]], mut n: usize) -> Option<([i32; 3], usize)> { + for h in halves { + let len = w + .world + .block_entities + .get(&(h[0], h[1], h[2]))? + .slots() + .len(); + if n < len { + return Some((*h, n)); + } + n -= len; + } + None +} +fn max_stack(w: &MobWorld, s: &ItemStack) -> u32 { + w.items + .and_then(|i| i.get(&s.item)) + .map_or(64, |i| i.max_stack) + .max(1) +} + +/// `BlockPos` keys in a chunk's block entity map. +#[derive(PartialEq, Eq)] +struct PosKey([i32; 3]); +impl JavaKey for PosKey { + fn java_hash(&self) -> i32 { + // Vec3i.hashCode. + (self.0[1].wrapping_add(self.0[2].wrapping_mul(31))) + .wrapping_mul(31) + .wrapping_add(self.0[0]) + } + fn tie_break(&self, _: &Self) -> std::cmp::Ordering { + std::cmp::Ordering::Less + } +} + +/// `AABB.ofSize(center, ..)` of the mob's box, and whether the chest's +/// collision box grown by `distance` (and 0.5 up and down) reaches it. +fn within(w: &MobWorld, m: &Mob, distance: f64, t: &Target, from: [f64; 3]) -> bool { + let size = m.bounds().size(); + let moved = Aabb::new( + Vec3::new( + from[0] - size.x / 2.0, + from[1] - size.y / 2.0, + from[2] - size.z / 2.0, + ), + Vec3::new( + from[0] + size.x / 2.0, + from[1] + size.y / 2.0, + from[2] + size.z / 2.0, + ), + ); + // getCollisionShape of the state the target was chosen with: the block + // there now (the target is dropped once it changes). + let Some(shape) = w.collision_bounds(t.pos) else { + return false; + }; + let p = Vec3::new( + f64::from(t.pos[0]), + f64::from(t.pos[1]), + f64::from(t.pos[2]), + ); + shape + .inflate(Vec3::new(distance, 0.5, distance)) + .move_by(p) + .intersects(moved) +} +fn center(m: &Mob) -> [f64; 3] { + [ + m.position.x, + m.position.y + m.bounds().size().y / 2.0, + m.position.z, + ] +} +fn finished_path(m: &Mob) -> bool { + m.ai.nav.path.as_ref().is_some_and(|p| p.is_done()) +} +/// `getInteractionRange`. +fn range(m: &Mob) -> f64 { + if finished_path(m) { 1.0 } else { 0.5 } +} +/// `stopInPlace`. +fn stop_in_place(m: &mut Mob) { + m.nav_stop(); + m.ai.xxa = 0.0; + m.ai.yya = 0.0; + m.ai.speed = 0.0; + m.velocity.x = 0.0; + m.velocity.z = 0.0; +} +/// `ContainerOpenersCounter.getEntitiesWithContainerOpen`: the golems with +/// either half of the chest open, within the counter's interaction range +/// plus 4. +fn openers(w: &MobWorld, m: &Mob, p: [i32; 3]) -> usize { + let area = opener_area(w, p); + let me = usize::from(has_open(w, m, p)); + me + w + .others + .iter() + .filter(|s| { + s.id != m.id && s.alive && holds(w, s.opened_chest, p) && s.bounds.intersects(area) + }) + .count() +} +/// `CopperGolem.hasContainerOpen`: its opened chest is `p` or `p`'s other half. +fn holds(w: &MobWorld, opened: Option<[i32; 3]>, p: [i32; 3]) -> bool { + opened.is_some_and(|o| o == p || connected(w, o) == Some(p)) +} +/// Whether the counter at `p` lists this golem. +fn has_open(w: &MobWorld, m: &Mob, p: [i32; 3]) -> bool { + holds(w, m.extra.opened_chest, p) && m.bounds().intersects(opener_area(w, p)) +} +fn opener_area(w: &MobWorld, p: [i32; 3]) -> Aabb { + let range = w + .world + .chest_openers + .get(&(p[0], p[1], p[2])) + .map_or(0.0, |o| o.1) + + 4.0; + Aabb::new( + Vec3::new( + f64::from(p[0]) - range, + f64::from(p[1]) - range, + f64::from(p[2]) - range, + ), + Vec3::new( + f64::from(p[0]) + 1.0 + range, + f64::from(p[1]) + 1.0 + range, + f64::from(p[2]) + 1.0 + range, + ), + ) +} +/// `ChestBlockEntity.startOpen` / `stopOpen` by a golem (interaction range +/// 3): the opener count changes and the first opener or the last closer +/// plays the chest's sound (`ChestBlockEntity.playSound`, at the middle of +/// a double chest from its right half, none from its left). +fn open_or_close(cx: &mut Bx, p: [i32; 3], open: bool) { + let w = cx.w; + let count = w + .world + .chest_openers + .get(&(p[0], p[1], p[2])) + .map_or(0, |o| o.0); + let sounds = if open { count == 0 } else { count == 1 }; + if sounds + && let Some(kind) = w.prop(p[0], p[1], p[2], "type") + && kind != "left" + { + let mut at = [ + f64::from(p[0]) + 0.5, + f64::from(p[1]) + 0.5, + f64::from(p[2]) + 0.5, + ]; + if kind == "right" + && let Some(o) = connected(w, p) + { + at[0] += f64::from(o[0] - p[0]) * 0.5; + at[2] += f64::from(o[2] - p[2]) * 0.5; + } + let name = name_at(w, p); + let base = name + .trim_start_matches("minecraft:") + .trim_start_matches("waxed_"); + let sound = match (base.ends_with("copper_chest"), base.split('_').next(), open) { + (false, _, true) => "block.chest.open", + (false, _, false) => "block.chest.close", + (true, Some("weathered"), true) => "block.copper_chest_weathered.open", + (true, Some("weathered"), false) => "block.copper_chest_weathered.close", + (true, Some("oxidized"), true) => "block.copper_chest_oxidized.open", + (true, Some("oxidized"), false) => "block.copper_chest_oxidized.close", + (true, _, true) => "block.copper_chest.open", + (true, _, false) => "block.copper_chest.close", + }; + let pitch = cx.lr.next_float() * 0.1 + 0.9; + cx.events.push(MobEvent::Sound(sound, at, 0.5, pitch)); + } + cx.events.push(MobEvent::ChestOpen { chest: p, open }); +} + +impl Transport { + /// `Behavior.tryStart`: no transport cooldown, not panicking, not + /// leashed; the duration draw, then `start`. + pub(super) fn try_start(&mut self, m: &mut Mob, cx: &mut Bx) -> bool { + let mm = mem(m); + if mm.transport_items_cooldown_ticks.present() || mm.is_panicking.present() { + return false; + } + if m.extra.leash.is_some() { + return false; + } + self.running = true; + self.end = cx.now + i64::from(cx.lr.next_int_bound(1).unwrap_or(0)) + 60; + m.ai.nav.below_surface = true; + true + } + pub(super) fn tick_or_stop(&mut self, m: &mut Mob, cx: &mut Bx) { + let mm = mem(m); + let can_still = !mm.transport_items_cooldown_ticks.present() + && !mm.is_panicking.present() + && m.extra.leash.is_none(); + if !can_still { + self.do_stop(m, cx); + return; + } + self.tick(m, cx); + } + pub(super) fn do_stop(&mut self, m: &mut Mob, cx: &mut Bx) { + self.running = false; + self.on_start_travelling(m, cx); + m.ai.nav.below_surface = false; + } + fn tick(&mut self, m: &mut Mob, cx: &mut Bx) { + let updated = self.update_invalid_target(m, cx); + let Some(target) = self.target.clone() else { + // `this.stop(..)`: the stop effects, the behaviour still running. + self.on_start_travelling(m, cx); + m.ai.nav.below_surface = false; + return; + }; + if updated { + return; + } + if self.state == State::Queuing && !self.another_interacting(m, cx.w, &target) { + self.state = State::Travelling; + self.walk_towards(m); + } + if self.state == State::Travelling { + let c = center(m); + if within(cx.w, m, 3.0, &target, c) && self.another_interacting(m, cx.w, &target) { + stop_in_place(m); + self.state = State::Queuing; + } else if within(cx.w, m, range(m), &target, c) { + self.interaction = Some(reached_interaction(m, cx.w, &target.halves)); + self.state = State::Interacting; + } else { + self.walk_towards(m); + } + } + if self.state == State::Interacting { + self.on_reached(m, cx, &target); + } + } + fn update_invalid_target(&mut self, m: &mut Mob, cx: &mut Bx) -> bool { + if self.has_valid_target(m, cx) { + return false; + } + self.stop_targeting(m); + match self.find_target(m, cx.w) { + Some(t) => { + let pos = t.pos; + self.target = Some(t); + self.on_start_travelling(m, cx); + self.set_visited(m, pos); + } + None => self.enter_cooldown(m), + } + true + } + fn has_valid_target(&mut self, m: &mut Mob, cx: &mut Bx) -> bool { + let Some(t) = self.target.clone() else { + return false; + }; + let w = cx.w; + let unchanged = matches!( + w.world.block_entities.get(&(t.pos[0], t.pos[1], t.pos[2])), + Some(BlockEntity::Chest(_)) + ) && is_chest_block(&name_at(w, t.pos)); + if !(wanted(w, m, &t.name) && unchanged) || blocked(w, t.pos) { + return false; + } + if self.state != State::Travelling { + return true; + } + if self.valid_travelling_path(m, w, &t) { + return true; + } + self.mark_unreachable(m, t.pos); + false + } + fn valid_travelling_path(&mut self, m: &mut Mob, w: &MobWorld, t: &Target) -> bool { + let path = match &m.ai.nav.path { + Some(p) => Some(p.clone()), + None => m.create_path_to(w, t.pos, 0), + }; + let from = match path.as_ref().and_then(|p| p.end()) { + Some(n) => [f64::from(n.x) + 0.5, f64::from(n.y), f64::from(n.z) + 0.5], + None => [m.position.x, m.position.y, m.position.z], + }; + let from = [from[0], from[1] + m.bounds().size().y / 2.0, from[2]]; + let reach = within(w, m, range(m), t, from); + (path.is_none() && !reach) || reach && sees_a_side(w, t.pos, from) + } + fn find_target(&self, m: &Mob, w: &MobWorld) -> Option { + let bx = m.position.x.floor() as i32; + let by = m.position.y.floor() as i32; + let bz = m.position.z.floor() as i32; + let (h, v): (i32, i32) = if m.extra.mount.is_some() { + (1, 1) + } else { + (32, 8) + }; + let visited = mem_list(m, false); + let unreachable = mem_list(m, true); + let (cx, cz) = (bx >> 4, bz >> 4); + let r = h.div_euclid(16) + 1; + // Each chunk's block entities in their HashMap's order. + let mut by_chunk: std::collections::HashMap<(i32, i32), Vec<[i32; 3]>> = Default::default(); + for (k, e) in &w.world.block_entities { + if matches!(e, BlockEntity::Chest(_)) { + by_chunk + .entry((k.0 >> 4, k.2 >> 4)) + .or_default() + .push([k.0, k.1, k.2]); + } + } + let mut best: Option<(f64, Target)> = None; + for z in cz - r..=cz + r { + for x in cx - r..=cx + r { + let Some(list) = by_chunk.get_mut(&(x, z)) else { + continue; + }; + list.sort(); + let mut map: JavaHashMap = JavaHashMap::default(); + for p in list.iter() { + map.put(PosKey(*p), ()); + } + for (key, _) in map.entries() { + let p = key.0; + let d = (f64::from(p[0]) + 0.5 - m.position.x).powi(2) + + (f64::from(p[1]) + 0.5 - m.position.y).powi(2) + + (f64::from(p[2]) + 0.5 - m.position.z).powi(2); + if best.as_ref().map_or(f64::from(f32::MAX), |b| b.0) <= d { + continue; + } + // The search box: the mob's block grown by h, v, h. + let inside = (bx - h..bx + 1 + h).contains(&p[0]) + && (by - v..by + 1 + v).contains(&p[1]) + && (bz - h..bz + 1 + h).contains(&p[2]); + if !inside { + continue; + } + let Some(halves) = container(w, p) else { + continue; + }; + let name = name_at(w, p); + let seen = + std::iter::once(p) + .chain(connected(w, p).filter(|o| { + w.world.block_entities.contains_key(&(o[0], o[1], o[2])) + })) + .any(|q| visited.contains(&q) || unreachable.contains(&q)); + if wanted(w, m, &name) && !seen { + best = Some(( + d, + Target { + pos: p, + name, + halves, + }, + )); + } + } + } + } + best.map(|b| b.1) + } + /// `isAnotherMobInteractingWithTarget`: either half has an opener. + fn another_interacting(&self, m: &Mob, w: &MobWorld, t: &Target) -> bool { + let mut chests = vec![t.pos]; + if let Some(o) = connected(w, t.pos) + && w.world.block_entities.contains_key(&(o[0], o[1], o[2])) + { + chests.push(o); + } + chests.iter().any(|p| openers(w, m, *p) > 0) + } + fn walk_towards(&self, m: &mut Mob) { + if let Some(t) = &self.target { + // BehaviorUtils.setWalkAndLookTargetMemories(body, pos, 1, 0). + let mm = mem(m); + mm.look_target.set(Tracker::Block(t.pos)); + mm.walk_target.set(WalkTarget { + target: Tracker::Block(t.pos), + speed: 1.0, + close: 0, + }); + } + } + fn on_reached(&mut self, m: &mut Mob, cx: &mut Bx, t: &Target) { + if !within(cx.w, m, 2.0, t, center(m)) { + self.on_start_travelling(m, cx); + return; + } + self.ticks += 1; + // onTargetInteraction. + mem(m).look_target.set(Tracker::Block(t.pos)); + stop_in_place(m); + if let Some(i) = self.interaction { + let (state, sound) = match i { + Interaction::PickupItem => (cg::GETTING_ITEM, "entity.copper_golem.no_item_get"), + Interaction::PickupNoItem => { + (cg::GETTING_NO_ITEM, "entity.copper_golem.no_item_no_get") + } + Interaction::PlaceItem => (cg::DROPPING_ITEM, "entity.copper_golem.item_drop"), + Interaction::PlaceNoItem => { + (cg::DROPPING_NO_ITEM, "entity.copper_golem.item_no_drop") + } + }; + if self.ticks == 1 { + // container.startOpen, before setOpenedChestPos. + for h in &t.halves { + open_or_close(cx, *h, true); + } + m.extra.opened_chest = Some(t.pos); + m.extra.variant3 = state; + } + if self.ticks == 9 && !m.silent { + let at = [m.position.x, m.position.y, m.position.z]; + cx.events.push(MobEvent::Sound(sound, at, 1.0, 1.0)); + } + if self.ticks == 60 { + // container.getEntitiesWithContainerOpen().contains(body): + // only a single chest lists its openers (CompoundContainer + // keeps Container's empty list, so a double chest is left + // to the openers recheck). + if t.halves.len() == 1 && has_open(cx.w, m, t.pos) { + open_or_close(cx, t.pos, false); + } + m.extra.opened_chest = None; + } + } + if self.ticks >= 60 { + let items = slots(cx.w, &t.halves); + if held(m).is_none() { + if items.iter().any(Option::is_some) { + self.pick_up(m, cx, &t.halves, &items); + } else { + self.stop_targeting(m); + } + } else if leaving_ok(m, &items) { + self.put_down(m, cx, &t.halves, items); + } else { + self.stop_targeting(m); + } + self.on_start_travelling(m, cx); + } + } + /// `pickUpItems`: up to 16 of the first non-empty slot. + fn pick_up( + &mut self, + m: &mut Mob, + cx: &mut Bx, + halves: &[[i32; 3]], + items: &[Option], + ) { + if let Some((n, s)) = items + .iter() + .enumerate() + .find_map(|(n, s)| s.as_ref().map(|s| (n, s.clone()))) + { + let take = s.count.min(16); + let mut left = s.clone(); + left.count -= take; + let mut got = s; + got.count = take; + if let Some((h, slot)) = slot_at(cx.w, halves, n) { + cx.events.push(MobEvent::ChestSlot { + chest: h, + slot, + stack: (left.count > 0).then_some(left), + }); + } + set_held(m, Some(got)); + } + self.clear_memories(m); + } + /// `putDownItem` (`addItemsToContainer`, which takes from the carried + /// stack all the room a slot had, not what it put there). + fn put_down( + &mut self, + m: &mut Mob, + cx: &mut Bx, + halves: &[[i32; 3]], + items: Vec>, + ) { + let mut carried = held(m).cloned(); + for (n, slot) in items.into_iter().enumerate() { + let Some(stack) = carried.clone() else { break }; + match slot { + None => { + if let Some((h, s)) = slot_at(cx.w, halves, n) { + cx.events.push(MobEvent::ChestSlot { + chest: h, + slot: s, + stack: Some(stack), + }); + } + carried = None; + break; + } + Some(mut there) => { + let max = max_stack(cx.w, &there); + if there.item == stack.item + && there.extra == stack.extra + && there.damage == stack.damage + && there.count < max + { + let room = max - there.count; + let add = room.min(stack.count); + there.count += add; + if let Some((h, s)) = slot_at(cx.w, halves, n) { + cx.events.push(MobEvent::ChestSlot { + chest: h, + slot: s, + stack: Some(there), + }); + } + let left = i64::from(stack.count) - i64::from(room); + if left <= 0 { + carried = None; + break; + } + let mut rest = stack; + rest.count = left as u32; + carried = Some(rest); + } + } + } + } + let emptied = carried.is_none(); + set_held(m, carried); + if emptied { + self.clear_memories(m); + } else { + self.stop_targeting(m); + } + } + fn on_start_travelling(&mut self, m: &mut Mob, _: &mut Bx) { + // CopperGolemAi.onTravelling: clearOpenedChestPos, IDLE. + m.extra.opened_chest = None; + m.extra.variant3 = cg::IDLE; + self.state = State::Travelling; + self.interaction = None; + self.ticks = 0; + } + fn stop_targeting(&mut self, m: &mut Mob) { + self.ticks = 0; + self.target = None; + m.nav_stop(); + mem(m).walk_target.clear(); + } + fn clear_memories(&mut self, m: &mut Mob) { + self.stop_targeting(m); + let mm = mem(m); + mm.visited_block_positions.clear(); + mm.unreachable_transport_block_positions.clear(); + } + fn enter_cooldown(&mut self, m: &mut Mob) { + self.stop_targeting(m); + let mm = mem(m); + mm.transport_items_cooldown_ticks.set(140); + mm.visited_block_positions.clear(); + mm.unreachable_transport_block_positions.clear(); + } + fn set_visited(&mut self, m: &mut Mob, p: [i32; 3]) { + let mut list = mem_list(m, false); + if !list.contains(&p) { + list.push(p); + } + if list.len() > 10 { + self.enter_cooldown(m); + } else { + mem(m).visited_block_positions.set_ttl(list, 6000); + } + } + fn mark_unreachable(&mut self, m: &mut Mob, p: [i32; 3]) { + let mut visited = mem_list(m, false); + visited.retain(|q| *q != p); + let mut unreachable = mem_list(m, true); + if !unreachable.contains(&p) { + unreachable.push(p); + } + if unreachable.len() > 50 { + self.enter_cooldown(m); + } else { + let mm = mem(m); + mm.visited_block_positions.set_ttl(visited, 6000); + mm.unreachable_transport_block_positions + .set_ttl(unreachable, 6000); + } + } +} +fn mem_list(m: &Mob, unreachable: bool) -> Vec<[i32; 3]> { + let Some(mm) = mem_ref(m) else { + return Vec::new(); + }; + let slot = if unreachable { + &mm.unreachable_transport_block_positions + } else { + &mm.visited_block_positions + }; + slot.get().cloned().unwrap_or_default() +} +/// `matchesLeavingItemsRequirement`: an empty container, or one holding the +/// carried item. +fn leaving_ok(m: &Mob, items: &[Option]) -> bool { + let carried = held(m); + items.iter().all(Option::is_none) + || items + .iter() + .flatten() + .any(|s| carried.is_some_and(|c| c.item == s.item)) +} +fn reached_interaction(m: &Mob, w: &MobWorld, halves: &[[i32; 3]]) -> Interaction { + let items = slots(w, halves); + if held(m).is_none() { + if items.iter().any(Option::is_some) { + Interaction::PickupItem + } else { + Interaction::PickupNoItem + } + } else if leaving_ok(m, &items) { + Interaction::PlaceItem + } else { + Interaction::PlaceNoItem + } +} +/// `canSeeAnyTargetSide`: a clip from `eye` to the middle of any face of the +/// chest's block hits that block. +fn sees_a_side(w: &MobWorld, p: [i32; 3], eye: [f64; 3]) -> bool { + let c = Vec3::new( + f64::from(p[0]) + 0.5, + f64::from(p[1]) + 0.5, + f64::from(p[2]) + 0.5, + ); + // Direction order: down, up, north, south, west, east. + let steps = [ + [0, -1, 0], + [0, 1, 0], + [0, 0, -1], + [0, 0, 1], + [-1, 0, 0], + [1, 0, 0], + ]; + let from = Vec3::new(eye[0], eye[1], eye[2]); + steps.iter().any(|s| { + let to = Vec3::new( + c.x + 0.5 * f64::from(s[0]), + c.y + 0.5 * f64::from(s[1]), + c.z + 0.5 * f64::from(s[2]), + ); + w.clip_block_at(from, to) == Some(p) + }) +} diff --git a/crates/horizon-client/src/mobs/world.rs b/crates/horizon-client/src/mobs/world.rs index 55a507fa7..40931fcff 100644 --- a/crates/horizon-client/src/mobs/world.rs +++ b/crates/horizon-client/src/mobs/world.rs @@ -131,6 +131,38 @@ impl MobWorld<'_> { }); result.ok().flatten() } + /// Level.clip with COLLIDER shapes and no fluids: the block the segment + /// first hits, if it does. + pub fn clip_block_at(&self, from: Vec3, to: Vec3) -> Option<[i32; 3]> { + 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(|_| [p.x, p.y, p.z]) + }); + result.ok().flatten() + } + /// The bounds of the block's collision shape, relative to the block. + pub fn collision_bounds(&self, p: [i32; 3]) -> Option { + let mut scene = SceneCollisions { + world: self.world, + binding: self.collision, + }; + let state = self.world.block(p[0], p[1], p[2]); + self.collision + .collision_shape(&mut scene, state, p) + .ok()? + .bounds() + } /// 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-client/src/world.rs b/crates/horizon-client/src/world.rs index f27b27108..15a413491 100644 --- a/crates/horizon-client/src/world.rs +++ b/crates/horizon-client/src/world.rs @@ -26,6 +26,9 @@ pub struct World { /// Chunks changed since the last save. pub modified: HashSet<(i32, i32)>, pub block_entities: HashMap<(i32, i32, i32), crate::containers::BlockEntity>, + /// Each chest's `ContainerOpenersCounter`: opener count and largest + /// interaction range. + pub chest_openers: HashMap<(i32, i32, i32), (i32, f64)>, /// `BaseContainerBlockEntity.name`: custom names of container block entities. pub block_names: HashMap<(i32, i32, i32), String>, /// States (by id) whose writes are recorded in `watched_writes` (sculk @@ -116,6 +119,7 @@ impl World { loaded_entities: Vec::new(), modified: HashSet::new(), block_entities: HashMap::new(), + chest_openers: HashMap::new(), block_names: HashMap::new(), watched: Vec::new(), watched_writes: Vec::new(), 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 6185d65f0..4a575f30d 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java @@ -211,7 +211,7 @@ public final class VanillaMobAiOracle { } } case "origin" -> { s.originX = Integer.parseInt(f[1]); s.originZ = Integer.parseInt(f[2]); } - case "fill", "block" -> s.blocks.add(f); + case "fill", "block", "chest" -> s.blocks.add(f); case "at" -> s.timed.add(new Object[] {Integer.parseInt(f[1]), java.util.Arrays.copyOfRange(f, 2, f.length)}); case "watch" -> { int[] box = new int[6]; @@ -450,9 +450,21 @@ public final class VanillaMobAiOracle { static void place(String[] b, ServerLevel level) throws Exception { var blocks = level.holderLookup(Registries.BLOCK); { - if (b[0].equals("block")) { + if (b[0].equals("block") || b[0].equals("chest")) { BlockState state = BlockStateParser.parseForBlock(blocks, b[4], false).blockState(); - level.setBlock(new BlockPos(Integer.parseInt(b[1]), Integer.parseInt(b[2]), Integer.parseInt(b[3])), state, 2 | 16); + BlockPos at = new BlockPos(Integer.parseInt(b[1]), Integer.parseInt(b[2]), Integer.parseInt(b[3])); + level.setBlock(at, state, 2 | 16); + // chest X Y Z STATE SLOTS: the slots' contents (item*count, - for empty). + if (b[0].equals("chest") && b.length > 5) { + var chest = (net.minecraft.world.level.block.entity.ChestBlockEntity) level.getBlockEntity(at); + String[] slots = b[5].split(","); + for (int k = 0; k < slots.length; k++) { + if (slots[k].equals("-")) continue; + String[] ic = slots[k].split("\\*"); + chest.setItem(k, new net.minecraft.world.item.ItemStack( + BuiltInRegistries.ITEM.getValue(net.minecraft.resources.Identifier.parse(ic[0])), Integer.parseInt(ic[1]))); + } + } } else { BlockState state = BlockStateParser.parseForBlock(blocks, b[7], false).blockState(); int x0 = Integer.parseInt(b[1]), y0 = Integer.parseInt(b[2]), z0 = Integer.parseInt(b[3]); @@ -565,6 +577,14 @@ public final class VanillaMobAiOracle { case "leashed", "leashto" -> { // Leashed once every mob exists (below). } + case "hand" -> { + String[] ic = v.split("\\*"); + mob.setItemSlot(net.minecraft.world.entity.EquipmentSlot.MAINHAND, new net.minecraft.world.item.ItemStack( + BuiltInRegistries.ITEM.getValue(net.minecraft.resources.Identifier.parse(ic[0])), Integer.parseInt(ic[1]))); + } + case "cooldown" -> { + // Set after the seeded constructor draw (below). + } default -> throw new IllegalArgumentException(flag); } } @@ -572,6 +592,15 @@ public final class VanillaMobAiOracle { for (Runnable r : afterAdd) r.run(); mob.getRandom().setSeed(spec.seed); Brain brain = mob.getBrain(); + if (mob instanceof net.minecraft.world.entity.animal.golem.CopperGolem) { + // The constructor's TRANSPORT_ITEMS_COOLDOWN_TICKS draw, made with the seeded + // random; "cooldown=N" then sets it (0: none, transporting at once). + int cooldown = mob.getRandom().nextInt(60, 100); + for (String flag : spec.flags) + if (flag.startsWith("cooldown=")) cooldown = Integer.parseInt(flag.substring(9)); + if (cooldown > 0) brain.setMemory(MemoryModuleType.TRANSPORT_ITEMS_COOLDOWN_TICKS, cooldown); + else brain.eraseMemory(MemoryModuleType.TRANSPORT_ITEMS_COOLDOWN_TICKS); + } @SuppressWarnings("unchecked") Map> sensors = (Map>) get(brain, "sensors"); for (Sensor sensor : sensors.values()) sensor.randomlyDelayStart(mob.getRandom()); @@ -722,6 +751,7 @@ public final class VanillaMobAiOracle { } for (int i = 0; i < ENTS.size(); i++) print(t, i, ENTS.get(i)); for (BlockPos h : heartPositions) printHeart(t, level, h); + for (String[] b : s.blocks) if (b[0].equals("chest")) printChest(t, s, level, b); for (String sound : SOUNDS) out.println(t + " sound " + sound); for (var w : watched.entrySet()) { BlockState now = level.getBlockState(w.getKey()); @@ -755,6 +785,19 @@ public final class VanillaMobAiOracle { return sb.toString(); } + /** A chest's slots (trailing empties dropped) and opener count. */ + static void printChest(int t, Scenario s, ServerLevel level, String[] b) throws Exception { + BlockPos at = new BlockPos(Integer.parseInt(b[1]), Integer.parseInt(b[2]), Integer.parseInt(b[3])); + if (!(level.getBlockEntity(at) instanceof net.minecraft.world.level.block.entity.ChestBlockEntity chest)) return; + List slots = new ArrayList<>(); + for (int k = 0; k < chest.getContainerSize(); k++) slots.add(stack(chest.getItem(k))); + while (!slots.isEmpty() && slots.getLast().equals("-")) slots.removeLast(); + Object counter = get(chest, "openersCounter"); + out.println(t + " chest " + (at.getX() - s.originX) + "," + at.getY() + "," + (at.getZ() - s.originZ) + " " + + (slots.isEmpty() ? "-" : String.join(",", slots)) + " " + + ((net.minecraft.world.level.block.entity.ContainerOpenersCounter) counter).getOpenerCount()); + } + /** 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(); @@ -913,6 +956,11 @@ public final class VanillaMobAiOracle { sb.append("\tmem ").append(String.join(" ", mem)); } if (m instanceof Villager villager) sb.append("\tvx ").append(villager(villager)); + if (m instanceof net.minecraft.world.entity.animal.golem.CopperGolem golem) { + Object opened = get(golem, "openedChestPos"); + sb.append("\tcg ").append(golem.getState().ordinal()).append(' ').append(stack(golem.getMainHandItem())).append(' ') + .append(opened == null ? "-" : pos((BlockPos) opened)); + } out.println(sb); } diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index 9abc3f960..9dd7535d4 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -174,6 +174,28 @@ def scenarios(): 'mob minecraft:wandering_trader 0.5 -60 0.5 0 104 persistent', 'mob minecraft:trader_llama 3.5 -60 1.5 0 105 persistent leashto=0 strength=2', 'mob minecraft:trader_llama 3.5 -60 -1.5 0 106 persistent leashto=0 strength=4']) + # Copper golems sorting chests (TransportItemsBetweenContainers): from a copper chest to a chest, + # skipping a chest without the carried item, queueing at a chest another golem has open, a double + # chest, a blocked copper chest, a part-full chest, and idling with nothing to carry. + def chest(x, z, slots='-', kind='chest', facing='north', half='single', y=-60): + return f'chest {x} {y} {z} minecraft:{kind}[facing={facing},type={half},waterlogged=false] {slots}' + golem = 'mob minecraft:copper_golem {} -60 {} {} {} persistent cooldown=0' + add('golem_copper_to_chest', 600, [chest(4, 0, 'cobblestone*20,-,iron_ingot*5', 'copper_chest'), + chest(-4, 3), golem.format(0.5, 0.5, 0, 111)]) + add('golem_skips_other_items', 700, [chest(4, 0, 'cobblestone*40', 'copper_chest'), + chest(-3, 0, 'dirt*3'), chest(-6, 5, 'cobblestone*10'), + golem.format(0.5, 0.5, 90, 112)]) + add('golem_queue', 600, [chest(3, 0, 'oak_log*48,stick*7', 'copper_chest'), chest(-4, 0), + golem.format(0.5, 0.5, 0, 113), golem.format(0.5, 3.5, 180, 114)]) + add('golem_double_chest', 600, [chest(4, 0, 'apple*30', 'exposed_copper_chest'), + chest(-4, 2, '-', 'chest', 'north', 'left'), chest(-5, 2, 'apple*2', 'chest', 'north', 'right'), + golem.format(0.5, 0.5, 0, 115)]) + add('golem_blocked_chest', 400, [chest(3, 0, 'sand*5', 'copper_chest'), 'block 3 -59 0 minecraft:stone', + chest(-5, -2, 'gravel*9', 'oxidized_copper_chest'), chest(0, 6), + golem.format(0.5, 0.5, 0, 116)]) + add('golem_part_full', 500, [chest(-3, 1, 'cobblestone*60,cobblestone*64,-,cobblestone*63'), + 'mob minecraft:copper_golem 0.5 -60 0.5 0 117 persistent cooldown=0 hand=cobblestone*16']) + add('golem_idle', 400, ['player 4.5 -60 2.5', 'mob minecraft:copper_golem 0.5 -60 0.5 0 118 persistent']) return s @@ -193,7 +215,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] in ('block', 'heart'): + elif f[0] in ('block', 'heart', 'chest'): f[1] = str(int(f[1]) + ox) f[3] = str(int(f[3]) + oz) elif f[0] == 'fill': @@ -228,6 +250,9 @@ def parse(path): if parts[1] == 'heart': cur.setdefault('hearts', {}).setdefault(t, []).append(line.split(' ', 2)[2]) continue + if parts[1] == 'chest': + cur.setdefault('chests', {}).setdefault(t, []).append(parts[2]) + continue mob = int(parts[1]) row = {} if len(parts) > 2: @@ -321,8 +346,8 @@ def compare(vanilla, rust, fields=None): report.append(f'{name}: hearts differ at tick {t}: vanilla {v.get("hearts", {}).get(t)} | horizon {r.get("hearts", {}).get(t)}') clean = False break - # Sounds and watched block changes: first differing tick. - for kind in ('sounds', 'blocks'): + # Sounds, watched block changes and chest contents: first differing tick. + for kind in ('sounds', 'blocks', 'chests'): va, ra = v.get(kind, {}), r.get(kind, {}) for t in sorted(set(va) | set(ra)): if va.get(t, []) != ra.get(t, []):