voxels: make slabs cast shadow and have players and mobs stand on their real surface
- Commit
d8358cc8a418611bf37c6591c279311393d56608- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-05 16:16 UTC (4 months ago)
- Parents
34416fb
Diff
games/voxels/src/main/rust/src/engine.rs
diff --git a/games/voxels/src/main/rust/src/engine.rs b/games/voxels/src/main/rust/src/engine.rsindex 002a5faa43..f47da1c612 100644--- a/games/voxels/src/main/rust/src/engine.rs+++ b/games/voxels/src/main/rust/src/engine.rs@@ -457,8 +457,11 @@ pub fn tick_and_render() { let player_pos = state.player.pos; { let chunks = &state.chunks;- let solid = |x: i32, y: i32, z: i32| { let id = chunks.get_block_world(x, y, z); id != 0 && Block::from_id(id).is_solid() };- for m in state.mobs.iter_mut() { m.tick(dt, player_pos, &solid); }+ let terrain = crate::entity::Terrain {+ solid: &|x, y, z| chunks.solid_at(x, y, z),+ surface: &|x, z, ceiling| chunks.surface_below(x, z, ceiling, 2),+ };+ for m in state.mobs.iter_mut() { m.tick(dt, player_pos, &terrain); } } // Mob melee contact damage + creeper fuse + ranged fire. let mut incoming = 0.0f32;
games/voxels/src/main/rust/src/entity.rs
diff --git a/games/voxels/src/main/rust/src/entity.rs b/games/voxels/src/main/rust/src/entity.rsindex d28cb2cddb..3f29eaffdf 100644--- a/games/voxels/src/main/rust/src/entity.rs+++ b/games/voxels/src/main/rust/src/entity.rs@@ -172,16 +172,24 @@ fn xorshift(s: &mut u32) -> f32 { (x >> 8) as f32 / 16_777_216.0 // [0,1) } +/// The world queries a mob's physics needs, both understanding slab and stair geometry:+/// whether a point is inside solid material, and how high the surface under a column is.+pub struct Terrain<'a> {+ pub solid: &'a dyn Fn(f32, f32, f32) -> bool,+ /// (x, z, ceiling) -> the highest surface at or below `ceiling` in that column.+ pub surface: &'a dyn Fn(f32, f32, f32) -> Option<f32>,+}+ impl Mob { pub fn new(kind: MobKind, pos: Vec3, seed: u32) -> Self { Mob { kind, pos, vel: Vec3::ZERO, yaw: 0.0, health: kind.max_health(), attack_cd: 0.0, fuse: 0.0, target_yaw: 0.0, wander: 0.0, anim: 0.0, on_ground: false, rng: seed | 1 } } - pub fn tick(&mut self, dt: f32, player: Vec3, solid: &dyn Fn(i32, i32, i32) -> bool) {+ pub fn tick(&mut self, dt: f32, player: Vec3, terrain: &Terrain) { // Flying bosses (Dragon/Wither): no gravity/collision; orbit + periodic swoop at the player. if self.kind.flies() {- let _ = solid;+ let _ = terrain; self.attack_cd = (self.attack_cd - dt).max(0.0); self.wander -= dt; if self.wander <= 0.0 { self.wander = 9.0; }@@ -232,16 +240,16 @@ impl Mob { self.vel.y -= 24.0 * dt; self.vel.y = self.vel.y.max(-40.0); - let at = |x: f32, y: f32, z: f32| solid(x.floor() as i32, y.floor() as i32, z.floor() as i32);+ let at = |x: f32, y: f32, z: f32| (terrain.solid)(x, y, z); let r = 0.3;- // Horizontal move per axis, blocked by walls, with a 1-block auto step-up on the ground.+ // Horizontal move per axis, blocked by walls, stepping up onto whatever is actually there. let dx = fwd.x * speed * dt; if dx != 0.0 { let nx = self.pos.x + dx + r * dx.signum(); if !at(nx, self.pos.y + 0.2, self.pos.z) && !at(nx, self.pos.y + 1.0, self.pos.z) { self.pos.x += dx;- } else if self.on_ground && !at(nx, self.pos.y + 1.2, self.pos.z) && !at(nx, self.pos.y + 2.0, self.pos.z) {- self.pos.x += dx; self.pos.y += 1.0;+ } else if let Some(top) = self.step_target(terrain, nx, self.pos.z) {+ self.pos.x += dx; self.pos.y = top; } } let dz = fwd.z * speed * dt;@@ -249,17 +257,22 @@ impl Mob { let nz = self.pos.z + dz + r * dz.signum(); if !at(self.pos.x, self.pos.y + 0.2, nz) && !at(self.pos.x, self.pos.y + 1.0, nz) { self.pos.z += dz;- } else if self.on_ground && !at(self.pos.x, self.pos.y + 1.2, nz) && !at(self.pos.x, self.pos.y + 2.0, nz) {- self.pos.z += dz; self.pos.y += 1.0;+ } else if let Some(top) = self.step_target(terrain, self.pos.x, nz) {+ self.pos.z += dz; self.pos.y = top; } }- // Vertical: fall until a block is underfoot.+ // Vertical: fall until something is underfoot, then rest on its actual surface.+ let prev_y = self.pos.y; self.pos.y += self.vel.y * dt; self.on_ground = false;- if self.vel.y <= 0.0 && at(self.pos.x, self.pos.y - 0.05, self.pos.z) {- self.pos.y = self.pos.y.floor() + 1.0;- self.vel.y = 0.0;- self.on_ground = true;+ if self.vel.y <= 0.0 {+ if let Some(top) = (terrain.surface)(self.pos.x, self.pos.z, prev_y) {+ if self.pos.y <= top {+ self.pos.y = top;+ self.vel.y = 0.0;+ self.on_ground = true;+ }+ } } // Hostiles hop toward the player over small ledges. if chasing && self.on_ground && speed > 0.0 && at(self.pos.x + fwd.x * 0.4, self.pos.y + 0.1, self.pos.z + fwd.z * 0.4) {@@ -268,6 +281,19 @@ impl Mob { self.anim += speed * dt * 5.5; } + /// The height to climb to when a mob walks into something at (x, z): the surface just above its+ /// feet, if the rise is at most a block and the mob's body fits standing there. Following the+ /// real surface means a slab lifts a mob half a block, not a whole one.+ fn step_target(&self, terrain: &Terrain, x: f32, z: f32) -> Option<f32> {+ if !self.on_ground { return None; }+ let top = (terrain.surface)(x, z, self.pos.y + 1.0)?;+ let rise = top - self.pos.y;+ if rise <= 1e-4 || rise > 1.0 { return None; }+ let head = self.kind.height().max(1.0);+ if (terrain.solid)(x, top + 0.2, z) || (terrain.solid)(x, top + head, z) { return None; }+ Some(top)+ }+ fn append_mesh(&self, verts: &mut Vec<Vertex>, indices: &mut Vec<u32>) { let col = (self.kind.cell() % 4) as f32 * CELL; let row = (self.kind.cell() / 4) as f32 * CELL;@@ -411,3 +437,86 @@ pub fn append_particles(verts: &mut Vec<Vertex>, indices: &mut Vec<u32>, ps: &[P indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]); } }++#[cfg(test)]+mod tests {+ use super::*;+ use crate::world::block::Block;+ use crate::world::ChunkMap;++ // Terrain never reaches this high, so the test platform sits in clear air.+ const SKY: i32 = 200;++ fn world() -> ChunkMap {+ let dir = std::env::temp_dir().join("voxels_mob_test").to_string_lossy().into_owned();+ ChunkMap::new(3, dir)+ }++ /// A wide platform so a wandering mob can't stroll off it during the test.+ fn platform(w: &mut ChunkMap, id: u8, meta: u8) {+ for x in -6..=6 { for z in -6..=6 { w.set_block_meta_world(x, SKY, z, id, meta); } }+ }++ fn settle(w: &ChunkMap, kind: MobKind, from_y: f32) -> Mob {+ let terrain = Terrain {+ solid: &|x, y, z| w.solid_at(x, y, z),+ surface: &|x, z, ceiling| w.surface_below(x, z, ceiling, 2),+ };+ let mut m = Mob::new(kind, Vec3::new(0.5, from_y, 0.5), 7);+ // A player far away, so passive mobs just wander and hostiles don't charge off the platform.+ let player = Vec3::new(0.5, from_y, 400.0);+ for _ in 0..180 { m.tick(1.0 / 60.0, player, &terrain); }+ m+ }++ // A mob standing on a slab must rest on its surface, not float at the cell boundary.+ #[test]+ fn a_mob_rests_on_a_slabs_surface() {+ let mut w = world();+ platform(&mut w, Block::StoneSlab as u8, 0);+ let m = settle(&w, MobKind::Pig, SKY as f32 + 3.0);+ assert!(m.on_ground, "the pig should have landed");+ assert!((m.pos.y - (SKY as f32 + 0.5)).abs() < 1e-3,+ "expected to stand on the slab top at {}, got {}", SKY as f32 + 0.5, m.pos.y);+ }++ // The same fall onto full blocks rests a whole block up, so the slab case really follows shape.+ #[test]+ fn a_mob_rests_a_whole_block_up_on_cubes() {+ let mut w = world();+ platform(&mut w, Block::Stone as u8, 0);+ let m = settle(&w, MobKind::Pig, SKY as f32 + 3.0);+ assert!((m.pos.y - (SKY as f32 + 1.0)).abs() < 1e-3, "got {}", m.pos.y);+ }++ // A top slab's solid half is its upper half, so a mob stands at the cell ceiling.+ #[test]+ fn a_mob_stands_on_top_of_a_top_slab() {+ let mut w = world();+ platform(&mut w, Block::StoneSlab as u8, crate::world::block::META_TOP);+ let m = settle(&w, MobKind::Pig, SKY as f32 + 3.0);+ assert!((m.pos.y - (SKY as f32 + 1.0)).abs() < 1e-3, "got {}", m.pos.y);+ }++ // Mobs step up half a block onto a slab rather than the full block they used to.+ #[test]+ fn a_mob_steps_up_onto_a_slab() {+ let mut w = world();+ // A long floor so the chase never runs off the end, with a slab ledge across the path.+ for x in -3..=3 { for z in -20..=3 { w.set_block_world(x, SKY, z, Block::Stone as u8); } }+ for x in -3..=3 { w.set_block_meta_world(x, SKY + 1, -3, Block::StoneSlab as u8, 0); }++ let terrain = Terrain {+ solid: &|x, y, z| w.solid_at(x, y, z),+ surface: &|x, z, ceiling| w.surface_below(x, z, ceiling, 2),+ };+ let mut m = Mob::new(MobKind::Zombie, Vec3::new(0.5, SKY as f32 + 1.0, 0.5), 11);+ // A hostile chases the player, who stands beyond the ledge.+ let player = Vec3::new(0.5, SKY as f32 + 1.5, -8.0);+ for _ in 0..240 { m.tick(1.0 / 60.0, player, &terrain); }++ assert!(m.pos.z < -2.0, "the zombie should have reached the ledge, z = {}", m.pos.z);+ assert!(m.pos.y >= SKY as f32 + 1.0, "and never sunk below the floor, y = {}", m.pos.y);+ assert!(m.pos.y <= SKY as f32 + 2.0, "nor been launched onto a phantom full block, y = {}", m.pos.y);+ }+}
games/voxels/src/main/rust/src/player.rs
diff --git a/games/voxels/src/main/rust/src/player.rs b/games/voxels/src/main/rust/src/player.rsindex a37786ce27..a0e3ac9b08 100644--- a/games/voxels/src/main/rust/src/player.rs+++ b/games/voxels/src/main/rust/src/player.rs@@ -180,16 +180,19 @@ impl Player { if !self.collides_at(try_x, chunks) { if !(sneaking && self.on_ground) || self.supported_at(try_x, chunks) { new_pos.x = try_x.x; } } else if self.on_ground && !sneaking {- let step = vec3(try_x.x, new_pos.y + step_h, new_pos.z);- if !self.collides_at(step, chunks) { new_pos.x = step.x; new_pos.y = step.y; }+ // Climb to the surface that blocked us, not by a fixed amount.+ if let Some(top) = self.step_up_to(try_x, chunks, new_pos.y, step_h) {+ new_pos.x = try_x.x; new_pos.y = top;+ } } // Z axis, same rules. let try_z = vec3(new_pos.x, new_pos.y, new_pos.z + horiz_vel.z * dt); if !self.collides_at(try_z, chunks) { if !(sneaking && self.on_ground) || self.supported_at(try_z, chunks) { new_pos.z = try_z.z; } } else if self.on_ground && !sneaking {- let step = vec3(new_pos.x, new_pos.y + step_h, try_z.z);- if !self.collides_at(step, chunks) { new_pos.z = step.z; new_pos.y = step.y; }+ if let Some(top) = self.step_up_to(try_z, chunks, new_pos.y, step_h) {+ new_pos.z = try_z.z; new_pos.y = top;+ } } self.walk_dist += (vec3(new_pos.x, 0.0, new_pos.z) - vec3(self.pos.x, 0.0, self.pos.z)).length(); // Vertical: gravity + collision, resting at whatever height horizontal step-up left us at.@@ -204,8 +207,15 @@ impl Player { if self.gliding { self.vel.y = self.vel.y.max(-3.5); } // slow, gliding descent new_pos.y = base_y + self.vel.y * dt; if self.collides_at(new_pos, chunks) {- new_pos.y = base_y;- if self.vel.y <= 0.0 { self.on_ground = true; }+ if self.vel.y <= 0.0 {+ // Landing: come to rest exactly on the surface, so a slab holds you half a+ // block up instead of at the cell boundary.+ let depth = ((base_y - new_pos.y).ceil() as i32 + 2).max(2);+ new_pos.y = self.surface_under(new_pos, chunks, base_y, depth).unwrap_or(base_y);+ self.on_ground = true;+ } else {+ new_pos.y = base_y; // knocked our head on something above+ } self.vel.y = 0.0; } else { let mut probe = new_pos; probe.y -= 0.05;@@ -252,30 +262,36 @@ impl Player { feet == 12 || chest == 12 } - // True if there is something solid to stand on just under the player's footprint at `pos` (used- // so a sneaking player won't walk off ledges). A slab counts only where its solid half reaches.- fn supported_at(&self, pos: Vec3, chunks: &ChunkMap) -> bool {+ /// The highest surface under the player's footprint at or below `ceiling` — the height they+ /// should come to rest at. Probing all four corners means the tallest thing under any part of+ /// the body wins, so you stand on a stair's step rather than sinking into it.+ fn surface_under(&self, pos: Vec3, chunks: &ChunkMap, ceiling: f32, depth: i32) -> Option<f32> { let hw = 0.3;- let foot = pos.y - 0.05;- let y = foot.floor() as i32;+ let mut best: Option<f32> = None; for &dx in &[-hw, hw] { for &dz in &[-hw, hw] {- let x = (pos.x + dx).floor() as i32;- let z = (pos.z + dz).floor() as i32;- let id = chunks.get_block_world(x, y, z);- if id == 0 { continue; }- let meta = chunks.get_meta_world(x, y, z);- // The probe point sits `foot` above the cell floor; something must fill it.- let local = foot - y as f32;- let (lx, lz) = (pos.x + dx - x as f32, pos.z + dz - z as f32);- for b in Block::from_id(id).collision_boxes(meta).as_slice() {- if local >= b.min[1] && local <= b.max[1]- && lx >= b.min[0] && lx <= b.max[0]- && lz >= b.min[2] && lz <= b.max[2] { return true; }+ if let Some(t) = chunks.surface_below(pos.x + dx, pos.z + dz, ceiling, depth) {+ if best.is_none_or(|b| t > b) { best = Some(t); } } } }- false+ best+ }++ /// The height to climb to when walking into something: the surface just above the feet, if it+ /// is within `max_step` and the player actually fits standing on it. Returns the real surface+ /// height, so a slab lifts you half a block rather than the full step allowance.+ fn step_up_to(&self, pos: Vec3, chunks: &ChunkMap, from_y: f32, max_step: f32) -> Option<f32> {+ let target = self.surface_under(pos, chunks, from_y + max_step, 2)?;+ if target <= from_y + 1e-4 { return None; }+ if self.collides_at(vec3(pos.x, target, pos.z), chunks) { return None; }+ Some(target)+ }++ // True if there is something solid to stand on just under the player's footprint at `pos` (used+ // so a sneaking player won't walk off ledges). A slab counts only where its solid half reaches.+ fn supported_at(&self, pos: Vec3, chunks: &ChunkMap) -> bool {+ self.surface_under(pos, chunks, pos.y + 1e-3, 1).is_some_and(|t| pos.y - t < 0.1) } fn collides_at(&self, pos: Vec3, chunks: &ChunkMap) -> bool {@@ -408,6 +424,115 @@ mod tests { assert!(p.collides_at(vec3(0.5, SKY as f32 + 0.5, 0.75), &w), "the step fills the far half"); } + fn walk(p: &mut Player, w: &ChunkMap, forward: f32, ticks: usize) {+ let input = crate::input::InputState { move_forward: forward, ..Default::default() };+ for _ in 0..ticks { p.tick(1.0 / 60.0, &input, w); }+ }++ // Falling onto a slab must leave you standing on its surface, not hovering at the cell+ // boundary and not sunk into it.+ #[test]+ fn you_come_to_rest_on_a_slabs_surface() {+ let mut w = world();+ w.set_block_meta_world(0, SKY, 0, Block::StoneSlab as u8, 0);+ let mut p = Player::new(0.5, SKY as f32 + 3.0, 0.5);+ let input = crate::input::InputState::default();+ for _ in 0..120 { p.tick(1.0 / 60.0, &input, &w); }++ assert!(p.on_ground, "the player should have landed");+ assert!((p.pos.y - (SKY as f32 + 0.5)).abs() < 1e-3,+ "expected to rest on the slab top at {}, got {}", SKY as f32 + 0.5, p.pos.y);+ }++ // The same drop onto a full block rests a whole block up, so the slab case is really following+ // the shape rather than getting lucky.+ #[test]+ fn a_full_block_still_holds_you_a_whole_block_up() {+ let mut w = world();+ w.set_block_world(0, SKY, 0, Block::Stone as u8);+ let mut p = Player::new(0.5, SKY as f32 + 3.0, 0.5);+ let input = crate::input::InputState::default();+ for _ in 0..120 { p.tick(1.0 / 60.0, &input, &w); }+ assert!((p.pos.y - (SKY as f32 + 1.0)).abs() < 1e-3, "got {}", p.pos.y);+ }++ /// A long floor to walk along, so a test never runs off the end of the world.+ fn floor(w: &mut ChunkMap, from_z: i32, to_z: i32, cell_y: i32) {+ for z in from_z..=to_z { w.set_block_world(0, cell_y, z, Block::Stone as u8); }+ }++ // Walking into a slab should climb it, and land on its surface rather than the step allowance.+ #[test]+ fn you_walk_up_onto_a_slab() {+ let mut w = world();+ floor(&mut w, -20, 1, SKY);+ for z in -20..=-2 { w.set_block_meta_world(0, SKY + 1, z, Block::StoneSlab as u8, 0); }++ let mut p = Player::new(0.5, SKY as f32 + 1.0, 0.5);+ p.yaw = 0.0; // facing -Z+ walk(&mut p, &w, 1.0, 90);++ assert!(p.pos.z < -2.5, "the player should have walked onto the slab, z = {}", p.pos.z);+ assert!((p.pos.y - (SKY as f32 + 1.5)).abs() < 1e-3,+ "expected to stand on the slab surface at {}, got {}", SKY as f32 + 1.5, p.pos.y);+ }++ // A staircase is a pair of half-steps per block, so it must be climbable without jumping.+ #[test]+ fn you_walk_up_a_staircase() {+ use crate::world::block::FACE_SOUTH;+ let mut w = world();+ floor(&mut w, -20, 1, SKY);+ // Six steps rising away from the player: column -(2+i) is filled to the previous step's+ // height and capped with a stair whose low side faces the approach (+Z).+ const STEPS: i32 = 6;+ for i in 0..STEPS {+ let z = -2 - i;+ for c in 1..=i { w.set_block_world(0, SKY + c, z, Block::Stone as u8); }+ w.set_block_meta_world(0, SKY + 1 + i, z, Block::StoneStairs as u8, FACE_SOUTH);+ }+ // A landing at the top so the climb has somewhere to finish.+ for z in -20..=-(2 + STEPS) {+ for c in 1..=STEPS { w.set_block_world(0, SKY + c, z, Block::Stone as u8); }+ }++ let mut p = Player::new(0.5, SKY as f32 + 1.0, 0.5);+ p.yaw = 0.0;+ walk(&mut p, &w, 1.0, 240);++ assert!(p.pos.y > SKY as f32 + 5.0, "the player should have climbed the stairs, y = {}", p.pos.y);+ assert!(p.pos.z < -6.0, "and travelled along them, z = {}", p.pos.z);+ }++ // A full block is too tall to walk up — only jumping clears it.+ #[test]+ fn a_full_block_still_blocks_you() {+ let mut w = world();+ floor(&mut w, -20, 1, SKY);+ w.set_block_world(0, SKY + 1, -2, Block::Stone as u8);++ let mut p = Player::new(0.5, SKY as f32 + 1.0, 0.5);+ p.yaw = 0.0;+ walk(&mut p, &w, 1.0, 90);+ assert!(p.pos.z > -1.8, "a full block should stop you, z = {}", p.pos.z);+ assert!((p.pos.y - (SKY as f32 + 1.0)).abs() < 1e-3, "and you stay on the floor, y = {}", p.pos.y);+ }++ // Sneaking must still refuse to step off a ledge, including off the edge of a slab.+ #[test]+ fn sneaking_wont_walk_off_a_slab_ledge() {+ let mut w = world();+ for z in -20..=1 { w.set_block_meta_world(0, SKY, z, Block::StoneSlab as u8, 0); }+ let p = Player::new(0.5, SKY as f32 + 0.5, 0.5);++ // Over the slab: supported.+ assert!(p.supported_at(vec3(0.5, SKY as f32 + 0.5, 0.5), &w));+ // Out past the end of the run: nothing underfoot.+ assert!(!p.supported_at(vec3(0.5, SKY as f32 + 0.5, 3.5), &w));+ // Standing a whole block above the slab is not "supported" either.+ assert!(!p.supported_at(vec3(0.5, SKY as f32 + 1.5, 0.5), &w));+ }+ #[test] fn attunements_are_independent() { let p = blessed_player(&[205, 211]);
games/voxels/src/main/rust/src/world/block.rs
diff --git a/games/voxels/src/main/rust/src/world/block.rs b/games/voxels/src/main/rust/src/world/block.rsindex 0349edf3a4..1ecff01db9 100644--- a/games/voxels/src/main/rust/src/world/block.rs+++ b/games/voxels/src/main/rust/src/world/block.rs@@ -185,6 +185,17 @@ impl Block { } pub fn is_opaque(self) -> bool { !self.is_transparent() } + /// Does this block stop light? Distinct from `is_opaque`, which asks whether a neighbour's face+ /// can be culled. A slab fills only half its cell so it can never hide a face, but it is still+ /// cut from solid stone and must cast shadow — the opposite of glass, which fills the whole cell+ /// and lets light straight through.+ pub fn blocks_light(self) -> bool {+ match self.shape() {+ Shape::Cube => self.is_opaque(),+ _ => self.parent().is_opaque(),+ }+ }+ pub fn shape(self) -> Shape { match self { Self::StoneSlab | Self::CobbleSlab | Self::PlankSlab | Self::BrickSlab@@ -601,6 +612,24 @@ mod tests { assert_eq!(step(FACE_WEST).min[0], 0.5, "west-facing steps sit on +X"); } + // Occluding a face and blocking light are different questions, and slabs and glass sit on+ // opposite sides of both.+ #[test]+ fn slabs_cast_shadow_even_though_they_cannot_cull_faces() {+ // A slab fills half its cell, so it can never hide a neighbour's face...+ assert!(!Block::StoneSlab.is_opaque());+ assert!(!Block::StoneStairs.is_opaque());+ // ...but it is cut from solid stone, so light must not pass through it.+ assert!(Block::StoneSlab.blocks_light());+ assert!(Block::StoneStairs.blocks_light());+ assert!(Block::PlankSlab.blocks_light());++ // Glass is the mirror image: it fills the cell but lets light straight through.+ assert!(!Block::Glass.blocks_light());+ assert!(!Block::Air.blocks_light());+ assert!(Block::Stone.blocks_light());+ }+ #[test] fn cubes_are_unchanged() { assert_eq!(Block::Stone.collision_boxes(0).as_slice(), &[FULL_CUBE]);
games/voxels/src/main/rust/src/world/chunk_map.rs
diff --git a/games/voxels/src/main/rust/src/world/chunk_map.rs b/games/voxels/src/main/rust/src/world/chunk_map.rsindex 4e3d02b866..ea063a4b95 100644--- a/games/voxels/src/main/rust/src/world/chunk_map.rs+++ b/games/voxels/src/main/rust/src/world/chunk_map.rs@@ -1,3 +1,4 @@+use super::block::Block; use super::chunk::{Chunk, ChunkPos, CHUNK_SIZE, CHUNK_HEIGHT}; use super::generator::TerrainGen; use super::save;@@ -77,6 +78,44 @@ impl ChunkMap { } } pub fn chunks_iter(&self) -> impl Iterator<Item=(&ChunkPos, &Chunk)> { self.chunks.iter() }++ /// Is this world point inside solid block geometry? Slabs and stairs fill only part of their+ /// cell, so this tests their actual boxes instead of treating the whole cell as solid.+ pub fn solid_at(&self, x: f32, y: f32, z: f32) -> bool {+ let (cx, cy, cz) = (x.floor() as i32, y.floor() as i32, z.floor() as i32);+ let id = self.get_block_world(cx, cy, cz);+ if id == 0 { return false; }+ let block = Block::from_id(id);+ if !block.is_solid() { return false; }+ let (lx, ly, lz) = (x - cx as f32, y - cy as f32, z - cz as f32);+ block.collision_boxes(self.get_meta_world(cx, cy, cz)).as_slice().iter().any(|b| {+ lx >= b.min[0] && lx <= b.max[0] && ly >= b.min[1] && ly <= b.max[1] && lz >= b.min[2] && lz <= b.max[2]+ })+ }++ /// The height of the highest solid surface in the column at (x, z) that sits at or below+ /// `ceiling`, searching `depth` cells down. This is the height an entity should rest at, so a+ /// slab holds you half a block up rather than a whole one.+ pub fn surface_below(&self, x: f32, z: f32, ceiling: f32, depth: i32) -> Option<f32> {+ let (cx, cz) = (x.floor() as i32, z.floor() as i32);+ let (lx, lz) = (x - cx as f32, z - cz as f32);+ let top_cell = ceiling.floor() as i32;+ for cy in (0.max(top_cell - depth)..=top_cell).rev() {+ let id = self.get_block_world(cx, cy, cz);+ if id == 0 { continue; }+ let block = Block::from_id(id);+ if !block.is_solid() { continue; }+ let mut best: Option<f32> = None;+ for b in block.collision_boxes(self.get_meta_world(cx, cy, cz)).as_slice() {+ // Only boxes actually underfoot in this column can hold anything up.+ if lx < b.min[0] || lx > b.max[0] || lz < b.min[2] || lz > b.max[2] { continue; }+ let top = cy as f32 + b.max[1];+ if top <= ceiling + 1e-4 && best.is_none_or(|v| top > v) { best = Some(top); }+ }+ if best.is_some() { return best; }+ }+ None+ } pub fn get(&self, pos: ChunkPos) -> Option<&Chunk> { self.chunks.get(&pos) } pub fn get_mut(&mut self, pos: ChunkPos) -> Option<&mut Chunk> { self.chunks.get_mut(&pos) } pub fn save_all(&self) {
games/voxels/src/main/rust/src/world/mesher.rs
diff --git a/games/voxels/src/main/rust/src/world/mesher.rs b/games/voxels/src/main/rust/src/world/mesher.rsindex 4c9f0d18bd..8251793e1a 100644--- a/games/voxels/src/main/rust/src/world/mesher.rs+++ b/games/voxels/src/main/rust/src/world/mesher.rs@@ -12,7 +12,7 @@ fn compute_light(chunk: &Chunk) -> ([[i32; 16]; 16], Vec<u8>) { for x in 0..16 { for z in 0..16 { for y in (0..CHUNK_HEIGHT).rev() { let id = chunk.get_block(x, y, z);- if id != 0 && Block::from_id(id).is_opaque() { col_top[x][z] = y as i32; break; }+ if id != 0 && Block::from_id(id).blocks_light() { col_top[x][z] = y as i32; break; } } }} let mut blk = vec![0u8; 16 * CHUNK_HEIGHT * 16];@@ -32,7 +32,7 @@ fn compute_light(chunk: &Chunk) -> ([[i32; 16]; 16], Vec<u8>) { if nx < 0 || nx >= 16 || nz < 0 || nz >= 16 || ny < 0 || ny >= CHUNK_HEIGHT as i32 { continue; } let (nx, ny, nz) = (nx as usize, ny as usize, nz as usize); let bid = chunk.get_block(nx, ny, nz);- if bid != 0 && Block::from_id(bid).is_opaque() { continue; }+ if bid != 0 && Block::from_id(bid).blocks_light() { continue; } let i = idx(nx, ny, nz); if blk[i] < nl { blk[i] = nl; q.push_back((nx, ny, nz, nl)); } }@@ -458,6 +458,31 @@ mod tests { .count() } + // A slab roof has to darken what is under it, or interiors built from slabs stay daylit.+ #[test]+ fn a_slab_roof_casts_shadow() {+ // The light packed into the floor block's up-facing quad, under an optional roof.+ let floor_light = |roof: Option<u8>| -> f32 {+ let mut c = Chunk::new(ChunkPos(0, 0));+ c.set_block(8, 10, 8, Block::Stone as u8);+ if let Some(r) = roof { c.set_block_meta(8, 14, 8, r, 0); }+ let m = mesh_alone(&c);+ m.iter().flatten()+ .flat_map(|md| md.indices.chunks(6).map(move |ci| md.vertices[ci[0] as usize]))+ .find(|v| v.normal == [0.0, 1.0, 0.0] && (v.pos[1] - 11.0).abs() < 1e-5)+ .expect("the floor block must have a top face")+ .light+ };+ let open_sky = floor_light(None);+ let under_slab = floor_light(Some(Block::StoneSlab as u8));+ let under_stairs = floor_light(Some(Block::StoneStairs as u8));+ let under_glass = floor_light(Some(Block::Glass as u8));++ assert!(under_slab < open_sky, "a slab roof must dim the floor ({under_slab} vs {open_sky})");+ assert!(under_stairs < open_sky, "so must a stair roof ({under_stairs} vs {open_sky})");+ assert_eq!(under_glass, open_sky, "glass has always let daylight through");+ }+ // Two boxes of one stair share a plane. Emitting both sides would z-fight, so the sealed one is // dropped — but the visible tread must survive. #[test]