diff --git a/crates/horizon-core/src/geometry/mod.rs b/crates/horizon-core/src/geometry/mod.rs index f8ad81331..950403ee8 100644 --- a/crates/horizon-core/src/geometry/mod.rs +++ b/crates/horizon-core/src/geometry/mod.rs @@ -425,6 +425,16 @@ impl Aabb { ), ) } + /// `AABB.intersects(minX, minY, minZ, maxX, maxY, maxZ)`: `intersects` + /// with a box given by its corners, `min` below `max` on every axis. + pub fn intersects_corners(self, min: Vec3, max: Vec3) -> bool { + self.min.x < max.x + && self.max.x > min.x + && self.min.y < max.y + && self.max.y > min.y + && self.min.z < max.z + && self.max.z > min.z + } pub fn intersects(self, other: Self) -> bool { self.min.x < other.max.x && self.max.x > other.min.x diff --git a/crates/horizon-core/src/geometry/shape.rs b/crates/horizon-core/src/geometry/shape.rs index 62593ebc6..e416f24d9 100644 --- a/crates/horizon-core/src/geometry/shape.rs +++ b/crates/horizon-core/src/geometry/shape.rs @@ -125,10 +125,16 @@ impl VoxelShape { .clone() } pub fn block() -> Self { + Self::block_ref().clone() + } + fn block_ref() -> &'static Self { static BLOCK: OnceLock = OnceLock::new(); - BLOCK - .get_or_init(|| Self::from_cube([1, 1, 1], &[true]).expect("valid unit cube")) - .clone() + BLOCK.get_or_init(|| Self::from_cube([1, 1, 1], &[true]).expect("valid unit cube")) + } + /// `shape == Shapes.block()`: the same as `same_identity(&block())` + /// without cloning the shared unit cube. + pub fn is_block(&self) -> bool { + self.same_identity(Self::block_ref()) } pub fn is_empty(&self) -> bool { self.bounds.is_none() @@ -283,7 +289,9 @@ impl VoxelShape { } } result.coords = Arc::new(coords); - result.boxes = Arc::new(result.decompose()); + // The same occupancy decomposes into the same boxes, over coordinates + // moved by the same additions. + result.boxes = Arc::new(self.boxes.iter().map(|b| b.move_by(offset)).collect()); result.bounds = self.bounds.map(|bounds| bounds.move_by(offset)); result } @@ -548,4 +556,45 @@ mod tests { ); assert!(VoxelShape::from_grid(std::array::from_fn(|_| vec![0.0, 1.0]), &[]).is_err()); } + #[test] + fn moved_boxes_are_the_moved_shapes_decomposition() { + let stair = VoxelShape::from_cube( + [2, 2, 2], + &[true, true, false, false, true, true, true, true], + ) + .unwrap(); + let slab = VoxelShape::from_grid([vec![0.0, 1.0], vec![0.0, 0.5], vec![0.0, 1.0]], &[true]) + .unwrap(); + let offsets = [ + Vec3::new(3.0, -64.0, -7.0), + Vec3::new(-0.0, 0.0, -0.0), + Vec3::new(1.0e-9, 319.999, -30_000_000.0), + Vec3::new(f64::from(i32::MAX), f64::from(i32::MIN), 0.1), + ]; + for shape in [VoxelShape::block(), stair, slab] { + for offset in offsets { + let moved = shape.moved(offset); + let [nx, ny, nz] = shape.sizes(); + let occupied: Vec = (0..nx * ny * nz) + .map(|i| { + shape.is_full( + (i / (ny * nz)) as i32, + (i / nz % ny) as i32, + (i % nz) as i32, + ) + }) + .collect(); + let rebuilt = VoxelShape::from_grid( + Axis::ALL.map(|axis| moved.coordinates(axis).to_vec()), + &occupied, + ) + .unwrap(); + assert_eq!(moved.boxes(), rebuilt.boxes()); + assert_eq!(moved.bounds(), rebuilt.bounds()); + } + } + assert!(VoxelShape::block().is_block()); + assert!(!VoxelShape::block().moved(Vec3::ZERO).is_block()); + assert!(!VoxelShape::block().fresh_identity().is_block()); + } } diff --git a/crates/horizon-world/src/block_collision.rs b/crates/horizon-world/src/block_collision.rs index 71c324cdf..b84db5def 100644 --- a/crates/horizon-world/src/block_collision.rs +++ b/crates/horizon-world/src/block_collision.rs @@ -111,7 +111,8 @@ impl<'r> BlockCollisionRegistry<'r> { scan_flags.push( u8::from(large) | (u8::from(state.name == "minecraft:moving_piston") << 1) - | (u8::from(empty) << 2), + | (u8::from(empty) << 2) + | (u8::from(contextual.contains_key(&id)) << 3), ); if cached.cached_shape(id)?.is_none() { if let Some(rule) = @@ -183,7 +184,12 @@ impl<'r> BlockCollisionRegistry<'r> { + LiquidCollisionWorld + PowderSnowWorld, { - match self.contextual.get(&state) { + // Most states have no contextual rule: their flag spares the lookup. + let contextual = self + .scan_flags + .get(state.0 as usize) + .is_none_or(|flags| flags & 8 != 0); + match contextual.then(|| self.contextual.get(&state)).flatten() { Some(ContextualRule::Scaffolding(rule)) => Ok(rule.shape(context, position)), Some(ContextualRule::Liquid(rule)) => rule .shape(world, position, context) diff --git a/crates/horizon-world/src/block_collision_scan.rs b/crates/horizon-world/src/block_collision_scan.rs index 1d8f75227..6c26c6631 100644 --- a/crates/horizon-world/src/block_collision_scan.rs +++ b/crates/horizon-world/src/block_collision_scan.rs @@ -83,6 +83,8 @@ pub struct BlockCollisionScan<'w, 'c, W: BlockCollisionWorld> { start: BlockPos, sizes: [usize; 3], index: usize, + /// The cell at `index`, relative to `start` (x fastest, then y, then z). + cursor: [usize; 3], count: usize, budget: usize, chunk: Option<(ChunkPos, W::Chunk)>, @@ -131,6 +133,7 @@ impl<'w, 'c, W: BlockCollisionWorld> BlockCollisionScan<'w, 'c, W> { start, sizes: sizes.map(|s| s as usize), index: 0, + cursor: [0; 3], count, budget: candidate_budget, chunk: None, @@ -144,12 +147,17 @@ impl<'w, 'c, W: BlockCollisionWorld> BlockCollisionScan<'w, 'c, W> { return Err(CollisionScanError::VisitBudget); } let [width, height, _] = self.sizes; - let relative = [ - self.index % width, - self.index / width % height, - self.index / width / height, - ]; + let relative = self.cursor; self.index += 1; + self.cursor[0] += 1; + if self.cursor[0] == width { + self.cursor[0] = 0; + self.cursor[1] += 1; + if self.cursor[1] == height { + self.cursor[1] = 0; + self.cursor[2] += 1; + } + } let kind = relative .into_iter() .zip(self.sizes) @@ -199,13 +207,10 @@ impl<'w, 'c, W: BlockCollisionWorld> BlockCollisionScan<'w, 'c, W> { .context_shape(block, p, &self.context) .map_err(CollisionScanError::World)?; let offset = Vec3::new(f64::from(p.x), f64::from(p.y), f64::from(p.z)); - let moved = if shape.same_identity(&VoxelShape::block()) { + let moved = if shape.is_block() { // Native adds one in floating point, including at i32::MAX. - let unit = Aabb::new( - offset, - Vec3::new(offset.x + 1.0, offset.y + 1.0, offset.z + 1.0), - ); - if !self.bounds.intersects(unit) { + let top = Vec3::new(offset.x + 1.0, offset.y + 1.0, offset.z + 1.0); + if !self.bounds.intersects_corners(offset, top) { continue; } shape.moved(offset) diff --git a/crates/horizon-world/tests/block_collision_scan.rs b/crates/horizon-world/tests/block_collision_scan.rs index d9f4a9fd5..32735f826 100644 --- a/crates/horizon-world/tests/block_collision_scan.rs +++ b/crates/horizon-world/tests/block_collision_scan.rs @@ -7,6 +7,7 @@ use horizon_world::{ BlockCollisionScan, BlockCollisionWorld, CollisionBlock, CollisionScanError, }, collision_context::CollisionContext, + registry::BlockStateId, }; use std::io; @@ -106,3 +107,85 @@ fn invalid_or_excessive_domains_fail_before_world_queries() { )); assert_eq!(world.calls, 0); } + +/// Records every cell the scan reads; every block passes the edge filters +/// and has an empty shape. +struct Recording { + cells: Vec, +} +impl BlockCollisionWorld for Recording { + type Error = io::Error; + type Chunk = (); + fn collision_chunk(&mut self, _: ChunkPos) -> io::Result> { + Ok(Some(())) + } + fn collision_block(&mut self, _: (), p: BlockPos) -> io::Result { + self.cells.push(p); + Ok(CollisionBlock { + state: BlockStateId(0), + large_collision_shape: true, + moving_piston: true, + empty_shape: true, + }) + } + fn is_suffocating(&mut self, _: (), _: CollisionBlock, _: BlockPos) -> io::Result { + unreachable!() + } + fn context_shape( + &mut self, + _: CollisionBlock, + _: BlockPos, + _: &CollisionContext<'_>, + ) -> io::Result { + unreachable!() + } +} + +#[test] +fn cells_follow_the_cursor_order_without_corners() { + let boxes = [ + Aabb::new(Vec3::new(0.2, 64.0, 0.3), Vec3::new(0.8, 65.95, 0.9)), + Aabb::new(Vec3::new(-17.5, -3.25, 31.0), Vec3::new(-15.0, -3.25, 33.5)), + Aabb::new(Vec3::new(5.0, 5.0, 5.0), Vec3::new(5.0, 5.0, 5.0)), + Aabb::new(Vec3::new(-0.3, 0.0, -0.3), Vec3::new(0.3, 0.9, 0.3)), + ]; + for bounds in boxes { + let mut world = Recording { cells: Vec::new() }; + let hits = BlockCollisionScan::new( + &mut world, + CollisionContext::empty(false), + bounds, + false, + 1_000_000, + ) + .unwrap() + .count(); + assert_eq!(hits, 0); + // Cursor3D: x fastest, then y, then z, skipping the 8 corners. + let (min, max) = (bounds.min_position(), bounds.max_position()); + let start = BlockPos::containing(Vec3::new(min.x - 1.0e-7, min.y - 1.0e-7, min.z - 1.0e-7)) + .offset(-1, -1, -1); + let end = BlockPos::containing(Vec3::new(max.x + 1.0e-7, max.y + 1.0e-7, max.z + 1.0e-7)) + .offset(1, 1, 1); + let sizes = [ + end.x - start.x + 1, + end.y - start.y + 1, + end.z - start.z + 1, + ]; + let mut expected = Vec::new(); + for i in 0..sizes[0] * sizes[1] * sizes[2] { + let r = [ + i % sizes[0], + i / sizes[0] % sizes[1], + i / sizes[0] / sizes[1], + ]; + let edges = (0..3) + .filter(|&a| r[a] == 0 || r[a] == sizes[a] - 1) + .count(); + if edges < 3 { + expected.push(start.offset(r[0], r[1], r[2])); + } + } + assert_eq!(world.cells, expected); + } +}