diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index acb2203a4..ed8fe4dec 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -24,6 +24,9 @@ pub struct ItemEntity { pub age: u32, pub pickup_delay: u32, pub bob_offset: f32, + /// `Entity.tickCount`: ticks since the item entered the level, which + /// paces `ItemEntity.mergeWithNeighbours`. + pub ticks: u32, } /// Environment results needed by the entity owner, including lethal lava damage. #[derive(Debug)] @@ -102,6 +105,7 @@ impl ItemEntity { facts: &BlockFacts, collision: &BlockCollisionRegistry<'_>, ) -> bool { + self.ticks += 1; self.previous = self.position; if self.pickup_delay > 0 && self.pickup_delay != u32::MAX { self.pickup_delay -= 1; @@ -175,6 +179,130 @@ impl ItemEntity { self.age += 1; self.age < 6000 && self.position.y > -128.0 } + /// `ItemEntity.isMergable` at `age`: a stack below its size whose pickup + /// delay isn't infinite, before its lifetime ends. + fn mergeable(&self, age: u32, max_stack: u32) -> bool { + self.pickup_delay != u32::MAX && age < 6000 && self.stack.count < max_stack + } +} +/// Dropped items by block cell, for `ItemEntity.mergeWithNeighbours`'s +/// search around an item. Holds indexes into the tick's item list. +#[derive(Default)] +pub struct ItemCells { + cells: crate::fast_hash::FxHashMap<(i32, i32, i32), Vec>, +} +impl ItemCells { + pub fn new(items: &[ItemEntity]) -> Self { + let mut cells = Self::default(); + for (i, item) in items.iter().enumerate() { + cells.add(i, item.position); + } + cells + } + fn cell(p: Vec3) -> (i32, i32, i32) { + (p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32) + } + fn add(&mut self, i: usize, at: Vec3) { + self.cells.entry(Self::cell(at)).or_default().push(i as u32); + } + pub fn remove(&mut self, i: usize, at: Vec3) { + if let Some(list) = self.cells.get_mut(&Self::cell(at)) { + list.retain(|&j| j as usize != i); + } + } + pub fn moved(&mut self, i: usize, from: Vec3, to: Vec3) { + if Self::cell(from) != Self::cell(to) { + self.remove(i, from); + self.add(i, to); + } + } + /// The items whose cells could hold a box meeting `area`, in the order + /// they were added (vanilla lists a section's entities in the order they + /// entered it). + fn near(&self, area: Aabb, out: &mut Vec) { + out.clear(); + // An item's box reaches 0.125 sideways and 0.25 up from its position. + let (min, max) = (area.min_position(), area.max_position()); + let (lo, hi) = ( + Self::cell(Vec3::new(min.x - 0.125, min.y - 0.25, min.z - 0.125)), + Self::cell(Vec3::new(max.x + 0.125, max.y, max.z + 0.125)), + ); + for x in lo.0..=hi.0 { + for y in lo.1..=hi.1 { + for z in lo.2..=hi.2 { + if let Some(list) = self.cells.get(&(x, y, z)) { + out.extend_from_slice(list); + } + } + } + } + out.sort_unstable(); + } +} +/// `ItemEntity.mergeWithNeighbours` for `items[i]`, which has just moved in +/// its tick (its `age` already counts this tick; vanilla's doesn't yet): each +/// mergeable item whose box meets this one's grown by 0.5 sideways takes this +/// stack or gives it its own, the smaller into the larger +/// (`ItemEntity.tryToMerge`), until this item is used up. An emptied item is +/// marked in `removed`. +pub fn merge_with_neighbours( + items: &mut [ItemEntity], + removed: &mut [bool], + cells: &mut ItemCells, + i: usize, + max_stack: &dyn Fn(&ItemStack) -> u32, +) { + let age = |items: &[ItemEntity], j: usize| { + if j == i { + items[j].age - 1 + } else { + items[j].age + } + }; + if removed[i] || !items[i].mergeable(age(items, i), max_stack(&items[i].stack)) { + return; + } + let area = items[i].bounds().inflate(Vec3::new(0.5, 0.0, 0.5)); + let mut near = Vec::new(); + cells.near(area, &mut near); + for j in near { + let j = j as usize; + if j == i + || removed[j] + || !items[j].bounds().intersects(area) + || !items[j].mergeable(age(items, j), max_stack(&items[j].stack)) + { + continue; + } + // ItemEntity.areMergable: both fit one stack of the same item and components. + let (this, other) = (&items[i].stack, &items[j].stack); + if this.count + other.count > max_stack(other) || !this.same_item_same_components(other) { + continue; + } + let (to, from) = if other.count < this.count { + (i, j) + } else { + (j, i) + }; + // ItemEntity.merge(toStack, fromStack, 64). + let room = max_stack(&items[to].stack).min(64) - items[to].stack.count; + let moved = room.min(items[from].stack.count); + items[to].stack.count += moved; + items[from].stack.count -= moved; + let (delay, from_age, to_age) = + (items[from].pickup_delay, age(items, from), age(items, to)); + let to_item = &mut items[to]; + to_item.pickup_delay = to_item.pickup_delay.max(delay); + // This item's age goes up once its tick ends. + to_item.age = to_age.min(from_age) + u32::from(to == i); + if items[from].stack.count == 0 { + removed[from] = true; + cells.remove(from, items[from].position); + } + if removed[i] { + return; + } + } } /// ExperienceOrb: gravity 0.03, homing towards the player within 8 blocks. #[derive(Clone, Debug)] @@ -634,6 +762,7 @@ mod fire_environment_tests { age: 0, pickup_delay: 0, bob_offset: 0.0, + ticks: 0, }; let mut wood = make("minecraft:oak_planks"); let mut metal = make("minecraft:netherite_ingot"); @@ -705,3 +834,179 @@ mod fire_environment_tests { assert_eq!(stand.health, 20.0, "lava does not hurt armor stands"); } } +#[cfg(test)] +mod merge_tests { + use super::*; + + fn item(id: &str, count: u32, x: f64, age: u32) -> ItemEntity { + let at = Vec3::new(x, 64.0, 0.5); + ItemEntity { + id: 0, + thrower: None, + stack: ItemStack { + item: std::sync::Arc::from(id), + count, + damage: 0, + extra: None, + }, + health: 5, + fire_ticks: 0, + position: at, + previous: at, + velocity: Vec3::ZERO, + on_ground: true, + age, + pickup_delay: 0, + bob_offset: 0.0, + ticks: age, + } + } + fn max_stack(stack: &ItemStack) -> u32 { + if &*stack.item == "minecraft:ender_pearl" { + 16 + } else { + 64 + } + } + /// Merges around `items[i]` as its tick would; returns the counts left. + fn merge(items: &mut [ItemEntity], i: usize) -> Vec> { + let mut removed = vec![false; items.len()]; + let mut cells = ItemCells::new(items); + merge_with_neighbours(items, &mut removed, &mut cells, i, &max_stack); + items + .iter() + .zip(removed) + .map(|(item, gone)| (!gone).then_some(item.stack.count)) + .collect() + } + + #[test] + fn the_smaller_stack_goes_into_the_larger() { + let mut items = [ + item("minecraft:sand", 3, 0.5, 41), + item("minecraft:sand", 5, 1.2, 7), + ]; + assert_eq!(merge(&mut items, 0), [None, Some(8)]); + // ItemEntity.merge keeps the younger age; the ticking item's is + // still the one before its tick. + assert_eq!(items[1].age, 7); + let mut items = [ + item("minecraft:sand", 5, 0.5, 41), + item("minecraft:sand", 3, 1.2, 7), + ]; + assert_eq!(merge(&mut items, 0), [Some(8), None]); + assert_eq!(items[0].age, 8, "age 7, plus the rest of this tick"); + } + + #[test] + fn items_merge_only_within_half_a_block_sideways() { + // Boxes 0.25 wide grown by 0.5: centres closer than 0.75 meet. + let mut items = [ + item("minecraft:sand", 1, 0.5, 1), + item("minecraft:sand", 1, 1.24, 1), + ]; + assert_eq!(merge(&mut items, 0), [None, Some(2)]); + let mut items = [ + item("minecraft:sand", 1, 0.5, 1), + item("minecraft:sand", 1, 1.26, 1), + ]; + assert_eq!(merge(&mut items, 0), [Some(1), Some(1)]); + let mut items = [ + item("minecraft:sand", 1, 0.5, 1), + item("minecraft:sand", 1, 0.5, 1), + ]; + items[1].position.y += 0.3; + assert_eq!( + merge(&mut items, 0), + [Some(1), Some(1)], + "no vertical growth" + ); + } + + #[test] + fn different_or_full_stacks_stay_apart() { + let mut items = [ + item("minecraft:sand", 1, 0.5, 1), + item("minecraft:gravel", 1, 0.5, 1), + ]; + assert_eq!(merge(&mut items, 0), [Some(1), Some(1)]); + let mut items = [ + item("minecraft:sand", 60, 0.5, 1), + item("minecraft:sand", 10, 0.5, 1), + ]; + assert_eq!( + merge(&mut items, 0), + [Some(60), Some(10)], + "70 is over a stack" + ); + let mut items = [ + item("minecraft:ender_pearl", 10, 0.5, 1), + item("minecraft:ender_pearl", 6, 0.5, 1), + ]; + assert_eq!(merge(&mut items, 0), [Some(16), None]); + let mut items = [ + item("minecraft:ender_pearl", 16, 0.5, 1), + item("minecraft:ender_pearl", 1, 0.5, 1), + ]; + assert_eq!( + merge(&mut items, 0), + [Some(16), Some(1)], + "a full stack doesn't merge" + ); + } + + #[test] + fn unmergeable_items_are_skipped() { + let mut items = [ + item("minecraft:sand", 1, 0.5, 1), + item("minecraft:sand", 1, 0.5, 1), + ]; + items[1].pickup_delay = u32::MAX; + assert_eq!(merge(&mut items, 0), [Some(1), Some(1)]); + // At age 6000 the other item's lifetime is over; this one's tick + // started at 5999, so it may still merge into a live item. + let mut items = [ + item("minecraft:sand", 1, 0.5, 6000), + item("minecraft:sand", 1, 0.5, 6000), + ]; + assert_eq!(merge(&mut items, 0), [Some(1), Some(1)]); + items[1].age = 10; + assert_eq!(merge(&mut items, 0), [None, Some(2)]); + assert_eq!(items[1].age, 10); + } + + #[test] + fn a_stack_takes_its_neighbours_in_spawn_order_until_full() { + let mut items = [ + item("minecraft:sand", 40, 0.5, 1), + item("minecraft:sand", 20, 0.7, 1), + item("minecraft:sand", 10, 0.3, 1), + item("minecraft:sand", 3, 0.4, 1), + ]; + // 40 + 20 = 60; 60 + 10 is over 64; then 3 more. + assert_eq!(merge(&mut items, 0), [Some(63), None, Some(10), None]); + let mut items = [ + item("minecraft:sand", 1, 0.5, 1), + item("minecraft:sand", 1, 0.5, 1), + ]; + items[1].pickup_delay = 30; + assert_eq!(merge(&mut items, 0), [None, Some(2)]); + assert_eq!(items[1].pickup_delay, 30, "the longer pickup delay stays"); + } + + #[test] + fn the_cells_follow_moves() { + let mut items = [ + item("minecraft:sand", 1, 0.5, 1), + item("minecraft:sand", 1, 5.5, 1), + ]; + let mut removed = [false; 2]; + let mut cells = ItemCells::new(&items); + let from = items[1].position; + items[1].position.x = 0.9; + cells.moved(1, from, items[1].position); + merge_with_neighbours(&mut items, &mut removed, &mut cells, 0, &max_stack); + assert_eq!(removed, [true, false]); + assert_eq!(items[1].stack.count, 2); + } +} diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index d1c3665ed..a42bc8ba6 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -914,6 +914,7 @@ pub fn item_entity_from_nbt(tag: &Tag, id: u32, bob_offset: f32) -> Option { age: 0, pickup_delay, bob_offset: bob, + ticks: 0, }); } /// `Block.getDrops`: the block's loot table, drawing from its server random @@ -1972,15 +1982,51 @@ impl Game<'_> { let mut items = std::mem::take(&mut self.dropped); // ServerLevel.tick: only entities in entity-ticking chunks tick. let ticking = self.entity_ticking_area(); - items.retain_mut(|item| { + let mut removed = vec![false; items.len()]; + let mut cells = horizon_client::entities::ItemCells::new(&items); + let catalog = self.res.items(); + let max_stack = + |stack: &ItemStack| catalog.get(&stack.item).map_or(64, |i| i.max_stack).max(1); + // A LAN or server guest only shows the host's items. + let merging = self.remote.is_none(); + for i in 0..items.len() { + if removed[i] { + continue; + } + let item = &mut items[i]; if !ticking( item.position.x.floor() as i32, item.position.z.floor() as i32, ) { - return true; + continue; } - if !item.tick(&self.world, self.res.facts(), self.collision) { - return false; + let alive = item.tick(&self.world, self.res.facts(), self.collision); + cells.moved(i, item.previous, item.position); + // ItemEntity.tick: merge every 2 ticks while moving between + // blocks, every 40 otherwise, before the lifetime check. + let block = |v: Vec3| (v.x.floor(), v.y.floor(), v.z.floor()); + let rate = if block(item.previous) == block(item.position) { + 40 + } else { + 2 + }; + if merging + && (alive || item.age == 6000 && item.position.y > -128.0) + && item.ticks.is_multiple_of(rate) + { + horizon_client::entities::merge_with_neighbours( + &mut items, + &mut removed, + &mut cells, + i, + &max_stack, + ); + } + let item = &mut items[i]; + if !alive || removed[i] { + removed[i] = true; + cells.remove(i, item.position); + continue; } let environment = item.environment_tick( &self.world, @@ -1998,8 +2044,13 @@ impl Game<'_> { pitch, ); } - environment.alive - }); + if !environment.alive { + removed[i] = true; + cells.remove(i, item.position); + } + } + let mut removed = removed.into_iter(); + items.retain(|_| !removed.next().unwrap_or(false)); let Some(p) = self.player.as_ref() else { self.dropped = items; return; @@ -2693,155 +2744,163 @@ impl Game<'_> { } /// FallingBlockEntity.tick: fall with 0.04 gravity and 0.98 drag, then land. fn tick_falling(&mut self) -> Result<()> { - let mut falling = std::mem::take(&mut self.falling); - let mut landed = Vec::new(); - let mut dropped = Vec::new(); + let falling = std::mem::take(&mut self.falling); + let mut kept = Vec::with_capacity(falling.len()); let mut collision_error = None; let entity_drops = self.ui.rules.bool("entity_drops"); // ServerLevel.tick: only entities in entity-ticking chunks tick. let ticking = self.entity_ticking_area(); - falling.retain_mut(|f| { + // FallingBlockEntity.tick places or drops each block in its own tick, + // so a block falling onto one that just landed lands on top of it. + for mut f in falling { if !ticking(f.position.x.floor() as i32, f.position.z.floor() as i32) { - return true; + kept.push(f); + continue; } let original = f.clone(); - f.previous = f.position; - f.age = f.age.wrapping_add(1); - if !f.no_gravity { - f.velocity.y -= 0.04; - } - let mut wanted = f.velocity; - // Entity.move: a cobweb it was in scales this move, which then - // starts from rest. - if f.stuck.length_squared() > 1.0e-7 { - wanted = wanted.multiply(f.stuck); - f.stuck = Vec3::ZERO; - f.velocity = Vec3::ZERO; - } - let mut scene = collisions::SceneCollisions { - world: &self.world, - binding: self.collision, - subject: Some(collisions::PowderSnowSubject { - fall_distance: f.fall_distance, - falling_block: true, - ..Default::default() - }), - }; - let context = CollisionContext::for_entity( - CollisionEntity { - identity: EntityIdentity(0), - y: f.position.y, - descending: wanted.y < 0.0, - main_hand: None, - }, - false, - ); - let movement = match scene.resolve_with_context( - horizon_client::falling_block::bounds(f.position), - wanted, - 0.0, - false, - context, - ) { - Ok(movement) => movement, + match self.fall_step(&mut f, entity_drops) { + Ok(FallStep::Falling) => kept.push(f), + Ok(FallStep::Gone) => {} + Ok(FallStep::Dropped(at)) => self.drop_falling_block(f.state, at), + Ok(FallStep::Landed(pos)) => self.finish_falling_block(f, pos), Err(error) => { - *f = original; + kept.push(original); collision_error.get_or_insert(error); - return true; } - }; - let next = Vec3::new( - f.position.x + movement.x, - f.position.y + movement.y, - f.position.z + movement.z, - ); - let on_ground = wanted.y < 0.0 && movement.y != wanted.y; - // FallingBlockEntity.tick: off the ground, it gives up after 600 - // ticks (100 outside the world) and drops itself as an item. - let y = next.y.floor() as i32; - let outside = - y <= horizon_client::chunk::MIN_Y || y >= horizon_client::chunk::MIN_Y + 384; - if !on_ground && (f.age > 100 && outside || f.age > 600) { - if f.drop_item && entity_drops { - dropped.push((f.state, next)); - } - return false; - } - if next.y < f.position.y { - f.fall_distance += f.position.y - next.y; - } - let from = f.position; - f.position = next; - if on_ground { - let pos = [ - f.position.x.floor() as i32, - f.position.y.floor() as i32, - f.position.z.floor() as i32, - ]; - landed.push((f.clone(), pos)); - return false; - } - // applyEffectsFromBlocks: WebBlock.entityInside makes it stuck - // (Entity.makeStuckInBlock, which forgets the fall). Entity.move - // records the move unless it was blocked short of a tiny one. - let moved = movement.length_squared(); - let recorded = moved > 1.0e-7 || wanted.length_squared() - moved < 1.0e-7; - let world = &self.world; - let facts = self.res.facts(); - if horizon_client::falling_block::passes_cobweb( - from, - f.position, - recorded.then_some(wanted), - |p| &*facts.get(world.block(p.x, p.y, p.z)).name == "minecraft:cobweb", - ) { - f.fall_distance = 0.0; - f.stuck = horizon_client::falling_block::web_multiplier(); - } - if movement.x != wanted.x { - f.velocity.x = 0.0; - } - if movement.y != wanted.y { - f.velocity.y = 0.0; - } - if movement.z != wanted.z { - f.velocity.z = 0.0; - } - f.velocity = Vec3::new( - f.velocity.x * 0.98, - f.velocity.y * 0.98, - f.velocity.z * 0.98, - ); - true - }); - self.falling = falling; - for (state, at) in dropped { - // Entity.spawnAtLocation: an item entity where the block was. - let item = self.res.facts().get(state).item.clone(); - if &*item != "minecraft:air" { - let r = &mut self.world.random; - let v = [ - r.next_double() * 0.2 - 0.1, - 0.2, - r.next_double() * 0.2 - 0.1, - ]; - let stack = ItemStack { - item, - count: 1, - damage: 0, - extra: None, - }; - self.spawn_item(stack, [at.x, at.y, at.z], v, 10); } } - for (block, pos) in landed { - self.finish_falling_block(block, pos); - } + // Blocks that started falling meanwhile tick from the next tick on. + let started = std::mem::replace(&mut self.falling, kept); + self.falling.extend(started); self.process_level_events()?; if let Some(error) = collision_error { return Err(error); } Ok(()) } + /// One `FallingBlockEntity.tick` move of `f`. + fn fall_step(&self, f: &mut FallingBlock, entity_drops: bool) -> Result { + f.previous = f.position; + f.age = f.age.wrapping_add(1); + if !f.no_gravity { + f.velocity.y -= 0.04; + } + let mut wanted = f.velocity; + // Entity.move: a cobweb it was in scales this move, which then + // starts from rest. + if f.stuck.length_squared() > 1.0e-7 { + wanted = wanted.multiply(f.stuck); + f.stuck = Vec3::ZERO; + f.velocity = Vec3::ZERO; + } + let mut scene = collisions::SceneCollisions { + world: &self.world, + binding: self.collision, + subject: Some(collisions::PowderSnowSubject { + fall_distance: f.fall_distance, + falling_block: true, + ..Default::default() + }), + }; + let context = CollisionContext::for_entity( + CollisionEntity { + identity: EntityIdentity(0), + y: f.position.y, + descending: wanted.y < 0.0, + main_hand: None, + }, + false, + ); + // On an error the caller keeps the block as it was before this tick. + let movement = scene.resolve_with_context( + horizon_client::falling_block::bounds(f.position), + wanted, + 0.0, + false, + context, + )?; + let next = Vec3::new( + f.position.x + movement.x, + f.position.y + movement.y, + f.position.z + movement.z, + ); + let on_ground = wanted.y < 0.0 && movement.y != wanted.y; + // FallingBlockEntity.tick: off the ground, it gives up after 600 + // ticks (100 outside the world) and drops itself as an item. + let y = next.y.floor() as i32; + let outside = y <= horizon_client::chunk::MIN_Y || y >= horizon_client::chunk::MIN_Y + 384; + if !on_ground && (f.age > 100 && outside || f.age > 600) { + return Ok(if f.drop_item && entity_drops { + FallStep::Dropped(next) + } else { + FallStep::Gone + }); + } + if next.y < f.position.y { + f.fall_distance += f.position.y - next.y; + } + let from = f.position; + f.position = next; + if on_ground { + let pos = [ + f.position.x.floor() as i32, + f.position.y.floor() as i32, + f.position.z.floor() as i32, + ]; + return Ok(FallStep::Landed(pos)); + } + // applyEffectsFromBlocks: WebBlock.entityInside makes it stuck + // (Entity.makeStuckInBlock, which forgets the fall). Entity.move + // records the move unless it was blocked short of a tiny one. + let moved = movement.length_squared(); + let recorded = moved > 1.0e-7 || wanted.length_squared() - moved < 1.0e-7; + let world = &self.world; + let facts = self.res.facts(); + if horizon_client::falling_block::passes_cobweb( + from, + f.position, + recorded.then_some(wanted), + |p| &*facts.get(world.block(p.x, p.y, p.z)).name == "minecraft:cobweb", + ) { + f.fall_distance = 0.0; + f.stuck = horizon_client::falling_block::web_multiplier(); + } + if movement.x != wanted.x { + f.velocity.x = 0.0; + } + if movement.y != wanted.y { + f.velocity.y = 0.0; + } + if movement.z != wanted.z { + f.velocity.z = 0.0; + } + f.velocity = Vec3::new( + f.velocity.x * 0.98, + f.velocity.y * 0.98, + f.velocity.z * 0.98, + ); + Ok(FallStep::Falling) + } + /// `Entity.spawnAtLocation`: an item entity where the block was. + fn drop_falling_block(&mut self, state: BlockStateId, at: Vec3) { + // Entity.spawnAtLocation: an item entity where the block was. + let item = self.res.facts().get(state).item.clone(); + if &*item != "minecraft:air" { + let r = &mut self.world.random; + let v = [ + r.next_double() * 0.2 - 0.1, + 0.2, + r.next_double() * 0.2 - 0.1, + ]; + let stack = ItemStack { + item, + count: 1, + damage: 0, + extra: None, + }; + self.spawn_item(stack, [at.x, at.y, at.z], v, 10); + } + } /// `DecoratedPotBlock.playerWillDestroy`: a pot mined with an item in /// `breaks_decorated_pots`, unless an enchantment prevents shattering, is /// cracked first (flags 260), so it shatters into its sherds. diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 604964367..5bb3e172c 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2403,6 +2403,7 @@ impl Game<'_> { age: 0, pickup_delay: 0, bob_offset, + ticks: 0, }); } fn apply_remote_health(&mut self) {