Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / games / voxels / src / main / rust / src / raycast.rs
raycast.rs322 lines · 11.5 KiBRaw
| 1 | use crate::world::{ |
| 2 | block::{Block, Shape}, |
| 3 | ChunkMap, |
| 4 | }; |
| 5 | use glam::Vec3; |
| 6 | |
| 7 | #[derive(Debug, Clone, Copy)] |
| 8 | pub struct HitResult { |
| 9 | pub pos: (i32, i32, i32), |
| 10 | pub prev: (i32, i32, i32), |
| 11 | pub normal: (i32, i32, i32), |
| 12 | pub dist: f32, |
| 13 | } |
| 14 | |
| 15 | /// Slab in `t` for a ray against one box, in world space. Returns the entry distance and the axis |
| 16 | /// that was crossed on entry, or None if the ray misses. |
| 17 | fn ray_box(origin: Vec3, dir: Vec3, min: [f32; 3], max: [f32; 3]) -> Option<(f32, usize, bool)> { |
| 18 | let o = [origin.x, origin.y, origin.z]; |
| 19 | let d = [dir.x, dir.y, dir.z]; |
| 20 | let (mut t_near, mut t_far) = (f32::NEG_INFINITY, f32::INFINITY); |
| 21 | let (mut axis, mut positive) = (0usize, false); |
| 22 | for i in 0..3 { |
| 23 | if d[i].abs() < 1e-8 { |
| 24 | // Parallel to this slab: a miss unless the origin already lies inside it. |
| 25 | if o[i] < min[i] || o[i] > max[i] { |
| 26 | return None; |
| 27 | } |
| 28 | continue; |
| 29 | } |
| 30 | let inv = 1.0 / d[i]; |
| 31 | let mut t0 = (min[i] - o[i]) * inv; |
| 32 | let mut t1 = (max[i] - o[i]) * inv; |
| 33 | let mut enter_positive = false; // the ray enters through this axis' max face |
| 34 | if t0 > t1 { |
| 35 | std::mem::swap(&mut t0, &mut t1); |
| 36 | enter_positive = true; |
| 37 | } |
| 38 | if t0 > t_near { |
| 39 | t_near = t0; |
| 40 | axis = i; |
| 41 | positive = enter_positive; |
| 42 | } |
| 43 | if t1 < t_far { |
| 44 | t_far = t1; |
| 45 | } |
| 46 | if t_near > t_far { |
| 47 | return None; |
| 48 | } |
| 49 | } |
| 50 | if t_far < 0.0 { |
| 51 | return None; |
| 52 | } |
| 53 | Some((t_near.max(0.0), axis, positive)) |
| 54 | } |
| 55 | |
| 56 | /// Can a pick ray stop on this block? Collision solidity (`is_solid`) is the wrong predicate |
| 57 | /// here: crops and glass have no collision box (you walk through a crop field, and glass is |
| 58 | /// excluded from `is_solid` for light/face rules) but both fill their cell for interaction — |
| 59 | /// a crop that no ray can hit can never be harvested, and glass could never be broken or |
| 60 | /// built against. Fluids and portals stay untargetable so casts and travel pass through them. |
| 61 | fn targetable(block: Block) -> bool { |
| 62 | block.is_solid() || block.is_crop() || block == Block::Glass |
| 63 | } |
| 64 | |
| 65 | /// The nearest surface of a block within its cell, and the outward normal of the face hit. Cubes |
| 66 | /// short-circuit; slabs and stairs are tested box by box so you can look through their empty half. |
| 67 | fn hit_in_cell( |
| 68 | chunks: &ChunkMap, |
| 69 | cell: (i32, i32, i32), |
| 70 | origin: Vec3, |
| 71 | dir: Vec3, |
| 72 | ) -> Option<(f32, (i32, i32, i32))> { |
| 73 | let (x, y, z) = cell; |
| 74 | let id = chunks.get_block_world(x, y, z); |
| 75 | if id == 0 { |
| 76 | return None; |
| 77 | } |
| 78 | let block = Block::from_id(id); |
| 79 | if !targetable(block) { |
| 80 | return None; |
| 81 | } |
| 82 | let meta = chunks.get_meta_world(x, y, z); |
| 83 | let base = [x as f32, y as f32, z as f32]; |
| 84 | // Crops and glass have no collision boxes, but for picking they occupy the whole cell. |
| 85 | let owned = block.collision_boxes(meta); |
| 86 | let cube = [crate::world::block::FULL_CUBE]; |
| 87 | let boxes: &[crate::world::block::Aabb] = |
| 88 | if block.is_crop() || block == Block::Glass { &cube } else { owned.as_slice() }; |
| 89 | let mut best: Option<(f32, (i32, i32, i32))> = None; |
| 90 | for b in boxes { |
| 91 | let min = [base[0] + b.min[0], base[1] + b.min[1], base[2] + b.min[2]]; |
| 92 | let max = [base[0] + b.max[0], base[1] + b.max[1], base[2] + b.max[2]]; |
| 93 | let Some((t, axis, positive)) = ray_box(origin, dir, min, max) else { |
| 94 | continue; |
| 95 | }; |
| 96 | if best.is_some_and(|(bt, _)| bt <= t) { |
| 97 | continue; |
| 98 | } |
| 99 | let mut n = [0i32; 3]; |
| 100 | n[axis] = if positive { 1 } else { -1 }; |
| 101 | best = Some((t, (n[0], n[1], n[2]))); |
| 102 | } |
| 103 | best |
| 104 | } |
| 105 | |
| 106 | /// The cell a face normal points into — where a block placed against this hit would go. |
| 107 | fn step_out(cell: (i32, i32, i32), normal: (i32, i32, i32)) -> (i32, i32, i32) { |
| 108 | (cell.0 + normal.0, cell.1 + normal.1, cell.2 + normal.2) |
| 109 | } |
| 110 | |
| 111 | pub fn raycast(chunks: &ChunkMap, origin: Vec3, dir: Vec3, max_dist: f32) -> Option<HitResult> { |
| 112 | let dir = dir.normalize_or_zero(); |
| 113 | if dir.length_squared() < 1e-6 { |
| 114 | return None; |
| 115 | } |
| 116 | let mut x = origin.x.floor() as i32; |
| 117 | let mut y = origin.y.floor() as i32; |
| 118 | let mut z = origin.z.floor() as i32; |
| 119 | let step_x = if dir.x > 0.0 { |
| 120 | 1 |
| 121 | } else if dir.x < 0.0 { |
| 122 | -1 |
| 123 | } else { |
| 124 | 0 |
| 125 | }; |
| 126 | let step_y = if dir.y > 0.0 { |
| 127 | 1 |
| 128 | } else if dir.y < 0.0 { |
| 129 | -1 |
| 130 | } else { |
| 131 | 0 |
| 132 | }; |
| 133 | let step_z = if dir.z > 0.0 { |
| 134 | 1 |
| 135 | } else if dir.z < 0.0 { |
| 136 | -1 |
| 137 | } else { |
| 138 | 0 |
| 139 | }; |
| 140 | let t_delta_x = if dir.x != 0.0 { 1.0 / dir.x.abs() } else { f32::INFINITY }; |
| 141 | let t_delta_y = if dir.y != 0.0 { 1.0 / dir.y.abs() } else { f32::INFINITY }; |
| 142 | let t_delta_z = if dir.z != 0.0 { 1.0 / dir.z.abs() } else { f32::INFINITY }; |
| 143 | let mut t_max_x = if step_x != 0 { |
| 144 | let border = if step_x > 0 { x as f32 + 1.0 } else { x as f32 }; |
| 145 | (border - origin.x) / dir.x |
| 146 | } else { |
| 147 | f32::INFINITY |
| 148 | }; |
| 149 | let mut t_max_y = if step_y != 0 { |
| 150 | let border = if step_y > 0 { y as f32 + 1.0 } else { y as f32 }; |
| 151 | (border - origin.y) / dir.y |
| 152 | } else { |
| 153 | f32::INFINITY |
| 154 | }; |
| 155 | let mut t_max_z = if step_z != 0 { |
| 156 | let border = if step_z > 0 { z as f32 + 1.0 } else { z as f32 }; |
| 157 | (border - origin.z) / dir.z |
| 158 | } else { |
| 159 | f32::INFINITY |
| 160 | }; |
| 161 | let mut prev; |
| 162 | let mut dist = 0.0; |
| 163 | // Which axis the DDA last crossed, so a cube hit reports the face it entered through without |
| 164 | // relying on float equality between accumulated t values. |
| 165 | let mut step_axis; |
| 166 | // Starting inside a block still counts, but only if the ray actually meets its geometry — the |
| 167 | // eye can sit in the empty half of a slab's cell. |
| 168 | if let Some((t, normal)) = hit_in_cell(chunks, (x, y, z), origin, dir) { |
| 169 | return Some(HitResult { |
| 170 | pos: (x, y, z), |
| 171 | prev: step_out((x, y, z), normal), |
| 172 | normal, |
| 173 | dist: t, |
| 174 | }); |
| 175 | } |
| 176 | loop { |
| 177 | if dist > max_dist { |
| 178 | return None; |
| 179 | } |
| 180 | if t_max_x < t_max_y && t_max_x < t_max_z { |
| 181 | prev = (x, y, z); |
| 182 | x += step_x; |
| 183 | dist = t_max_x; |
| 184 | t_max_x += t_delta_x; |
| 185 | step_axis = 0; |
| 186 | } else if t_max_y < t_max_z { |
| 187 | prev = (x, y, z); |
| 188 | y += step_y; |
| 189 | dist = t_max_y; |
| 190 | t_max_y += t_delta_y; |
| 191 | step_axis = 1; |
| 192 | } else { |
| 193 | prev = (x, y, z); |
| 194 | z += step_z; |
| 195 | dist = t_max_z; |
| 196 | t_max_z += t_delta_z; |
| 197 | step_axis = 2; |
| 198 | } |
| 199 | if dist > max_dist { |
| 200 | return None; |
| 201 | } |
| 202 | let id = chunks.get_block_world(x, y, z); |
| 203 | if id != 0 && targetable(Block::from_id(id)) { |
| 204 | if Block::from_id(id).shape() == Shape::Cube { |
| 205 | // A full cube is entered exactly at the DDA boundary we just crossed. |
| 206 | let normal = match step_axis { |
| 207 | 0 => (-step_x, 0, 0), |
| 208 | 1 => (0, -step_y, 0), |
| 209 | _ => (0, 0, -step_z), |
| 210 | }; |
| 211 | return Some(HitResult { pos: (x, y, z), prev, normal, dist }); |
| 212 | } |
| 213 | // Partial block: keep going unless the ray really meets one of its boxes. |
| 214 | if let Some((t, normal)) = hit_in_cell(chunks, (x, y, z), origin, dir) { |
| 215 | if t <= max_dist { |
| 216 | return Some(HitResult { |
| 217 | pos: (x, y, z), |
| 218 | prev: step_out((x, y, z), normal), |
| 219 | normal, |
| 220 | dist: t, |
| 221 | }); |
| 222 | } |
| 223 | return None; |
| 224 | } |
| 225 | } |
| 226 | if x.abs() > 10000 || y.abs() > 10000 || z.abs() > 10000 { |
| 227 | return None; |
| 228 | } |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | #[cfg(test)] |
| 233 | mod tests { |
| 234 | use super::*; |
| 235 | use crate::world::block::Id; |
| 236 | use crate::world::block::{Block, FACE_NORTH, META_TOP}; |
| 237 | use glam::vec3; |
| 238 | |
| 239 | // Terrain never reaches this high, so the test cells around it are guaranteed empty air. |
| 240 | const SKY: i32 = 200; |
| 241 | |
| 242 | fn world() -> ChunkMap { |
| 243 | let dir = std::env::temp_dir().join("voxels_raycast_test").to_string_lossy().into_owned(); |
| 244 | ChunkMap::new(1, dir) |
| 245 | } |
| 246 | |
| 247 | // A bottom slab leaves the top half of its cell empty; a ray through that half must pass by. |
| 248 | #[test] |
| 249 | fn a_ray_passes_through_a_slabs_empty_half() { |
| 250 | let mut w = world(); |
| 251 | w.set_block_meta_world(4, SKY, 0, Block::StoneSlab as Id, 0); |
| 252 | |
| 253 | // Aim along +X at 0.75 up the cell, above the slab's solid half. |
| 254 | let high = raycast(&w, vec3(0.0, SKY as f32 + 0.75, 0.5), vec3(1.0, 0.0, 0.0), 20.0); |
| 255 | assert!(high.is_none(), "the upper half of a bottom slab's cell is empty"); |
| 256 | |
| 257 | // The same ray at 0.25 up must strike it. |
| 258 | let low = raycast(&w, vec3(0.0, SKY as f32 + 0.25, 0.5), vec3(1.0, 0.0, 0.0), 20.0) |
| 259 | .expect("must hit the slab"); |
| 260 | assert_eq!(low.pos, (4, SKY, 0)); |
| 261 | assert_eq!(low.normal, (-1, 0, 0), "entered through the slab's west face"); |
| 262 | assert_eq!(low.prev, (3, SKY, 0), "a block placed here goes in front of the slab"); |
| 263 | } |
| 264 | |
| 265 | // Looking straight down onto a bottom slab must report the top surface, not the cell's ceiling. |
| 266 | #[test] |
| 267 | fn looking_down_hits_the_slabs_top_surface() { |
| 268 | let mut w = world(); |
| 269 | w.set_block_meta_world(0, SKY, 0, Block::StoneSlab as Id, 0); |
| 270 | let hit = raycast(&w, vec3(0.5, SKY as f32 + 5.0, 0.5), vec3(0.0, -1.0, 0.0), 20.0) |
| 271 | .expect("must hit"); |
| 272 | assert_eq!(hit.pos, (0, SKY, 0)); |
| 273 | assert_eq!(hit.normal, (0, 1, 0)); |
| 274 | assert!( |
| 275 | (hit.dist - 4.5).abs() < 1e-3, |
| 276 | "the surface is half a block up, got dist {}", |
| 277 | hit.dist |
| 278 | ); |
| 279 | assert_eq!(hit.prev, (0, SKY + 1, 0), "placing against the top goes in the cell above"); |
| 280 | } |
| 281 | |
| 282 | #[test] |
| 283 | fn a_top_slab_is_hit_from_above_at_the_cell_ceiling() { |
| 284 | let mut w = world(); |
| 285 | w.set_block_meta_world(0, SKY, 0, Block::StoneSlab as Id, META_TOP); |
| 286 | let hit = raycast(&w, vec3(0.5, SKY as f32 + 5.0, 0.5), vec3(0.0, -1.0, 0.0), 20.0) |
| 287 | .expect("must hit"); |
| 288 | assert!((hit.dist - 4.0).abs() < 1e-3, "a top slab's surface is the cell ceiling"); |
| 289 | } |
| 290 | |
| 291 | // Cubes must behave exactly as before the sub-voxel test was added. |
| 292 | #[test] |
| 293 | fn cubes_still_hit_at_the_cell_boundary() { |
| 294 | let mut w = world(); |
| 295 | w.set_block_world(4, SKY, 0, Block::Stone as Id); |
| 296 | let hit = raycast(&w, vec3(0.0, SKY as f32 + 0.5, 0.5), vec3(1.0, 0.0, 0.0), 20.0) |
| 297 | .expect("must hit"); |
| 298 | assert_eq!(hit.pos, (4, SKY, 0)); |
| 299 | assert_eq!(hit.normal, (-1, 0, 0)); |
| 300 | assert_eq!(hit.prev, (3, SKY, 0)); |
| 301 | assert!((hit.dist - 4.0).abs() < 1e-3); |
| 302 | } |
| 303 | |
| 304 | // Stairs facing north keep their tall half on the +Z side; a ray into the low half at head |
| 305 | // height should sail over the tread. |
| 306 | #[test] |
| 307 | fn stairs_are_open_above_their_low_half() { |
| 308 | let mut w = world(); |
| 309 | w.set_block_meta_world(4, SKY, 0, Block::StoneStairs as Id, FACE_NORTH); |
| 310 | // z = 0.25 is the low (north) half, 0.75 up the cell is above the tread. |
| 311 | assert!( |
| 312 | raycast(&w, vec3(0.0, SKY as f32 + 0.75, 0.25), vec3(1.0, 0.0, 0.0), 20.0).is_none() |
| 313 | ); |
| 314 | // z = 0.75 is under the tall step, so the same height is solid. |
| 315 | let hit = raycast(&w, vec3(0.0, SKY as f32 + 0.75, 0.75), vec3(1.0, 0.0, 0.0), 20.0); |
| 316 | assert!(hit.is_some(), "the stair's tall half must block the ray"); |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | #[cfg(test)] |
| 321 | #[path = "raycast_coverage_tests.rs"] |
| 322 | mod raycast_coverage_tests; |