1use super::mesh::HeightGrid;
10
11type Vec3 = [f32; 3];
12
13fn sub(a: Vec3, b: Vec3) -> Vec3 {
14 [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
15}
16
17fn cross(a: Vec3, b: Vec3) -> Vec3 {
19 [
20 a[1] * b[2] - a[2] * b[1],
21 b[0] * a[2] - a[0] * b[2],
22 a[0] * b[1] - b[0] * a[1],
23 ]
24}
25
26fn dot(a: Vec3, b: Vec3) -> f32 {
27 a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
28}
29
30fn normalize(v: Vec3) -> Vec3 {
32 let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
33 if len == 0.0 {
34 return v;
35 }
36 let inv = 1.0 / len;
37 [v[0] * inv, v[1] * inv, v[2] * inv]
38}
39
40const EPSILON: f32 = -1e-4;
41const RAY_TOP: f32 = 100.0;
42const RAY_LENGTH: f32 = 200.0;
43
44#[allow(clippy::too_many_arguments, clippy::neg_cmp_op_on_partial_ord)]
47fn ray_triangle(
48 origin: Vec3,
49 dir: Vec3,
50 tmax: f32,
51 v0: Vec3,
52 v1: Vec3,
53 v2: Vec3,
54 t: &mut f32,
55 normal: &mut Vec3,
56) -> bool {
57 let e1 = sub(v1, v0);
58 let e2 = sub(v2, v0);
59 let p = cross(dir, e2);
60 let det = dot(e1, p);
61 let s = sub(origin, v0);
62 let q = cross(s, e1);
63 let u = dot(s, p);
64 let v = dot(dir, q);
65 if !(det > 0.0) || EPSILON > u || u > det || EPSILON > v || v + u > det {
67 return false;
68 }
69 let hit = 1.0 / det * dot(e2, q);
70 *t = hit;
71 if !(hit >= 0.0) || !(tmax >= hit) {
73 return false;
74 }
75 *normal = normalize(cross(e1, e2));
76 true
77}
78
79impl HeightGrid<'_> {
80 pub fn intersect(&self, origin: Vec3, direction: Vec3, maximum: f32) -> Option<(f32, Vec3)> {
88 let n = self.width as i32 - 1;
89 let half = n >> 1;
90 let end = [
91 origin[0] + direction[0] * maximum,
92 origin[1] + direction[1] * maximum,
93 ];
94 let lo = std::array::from_fn::<_, 2, _>(|k| {
95 ((origin[k].min(end[k]) + half as f32).floor() as i32 - 1).clamp(0, n - 1)
96 });
97 let hi = std::array::from_fn::<_, 2, _>(|k| {
98 ((origin[k].max(end[k]) + half as f32).floor() as i32 + 1).clamp(0, n - 1)
99 });
100 let mut limit = maximum;
101 let mut found = false;
102 let mut normal = [0.; 3];
103 for y in lo[1]..=hi[1] {
104 for x in lo[0]..=hi[0] {
105 let [a, b, c, d] = [
106 self.corner(x, y, half),
107 self.corner(x + 1, y, half),
108 self.corner(x + 1, y + 1, half),
109 self.corner(x, y + 1, half),
110 ];
111 let triangles = if (x + y) & 1 == 0 {
112 [[a, b, d], [b, c, d]]
113 } else {
114 [[a, b, c], [a, c, d]]
115 };
116 for [a, b, c] in triangles {
117 let mut t = limit;
118 if ray_triangle(origin, direction, limit, a, b, c, &mut t, &mut normal) {
119 limit = t;
120 found = true;
121 }
122 }
123 }
124 }
125 found.then(|| {
126 (
127 limit,
128 [
129 origin[0] + direction[0] * limit,
130 origin[1] + direction[1] * limit,
131 origin[2] + direction[2] * limit,
132 ],
133 )
134 })
135 }
136
137 fn corner(&self, x: i32, y: i32, half: i32) -> Vec3 {
138 let hi = self.width as i32 - 1;
139 let h = self.heights[y.clamp(0, hi) as usize * self.width + x.clamp(0, hi) as usize];
140 [
141 (x - half) as f32,
142 (y - half) as f32,
143 h as i32 as f32 * 0.00390625,
144 ]
145 }
146
147 fn raycast_cell(
150 &self,
151 x: i32,
152 y: i32,
153 dir: Vec3,
154 origin: Vec3,
155 tmax: f32,
156 normal: &mut Vec3,
157 ) -> (bool, f32) {
158 let half = (self.width as i32 - 1) >> 1;
159 let a = self.corner(x, y, half);
160 let b = self.corner(x + 1, y, half);
161 let c = self.corner(x + 1, y + 1, half);
162 let d = self.corner(x, y + 1, half);
163 let (first, second) = if (x + y) & 1 == 0 {
164 ([a, b, d], [b, c, d])
165 } else {
166 ([a, b, c], [a, c, d])
167 };
168 let mut limit = tmax;
169 let mut t = 0.0f32;
170 let mut hit = false;
171 if ray_triangle(
172 origin, dir, limit, first[0], first[1], first[2], &mut t, normal,
173 ) {
174 limit = t;
175 hit = true;
176 }
177 if ray_triangle(
178 origin, dir, limit, second[0], second[1], second[2], &mut t, normal,
179 ) {
180 hit = true;
181 }
182 (hit, t)
183 }
184
185 pub fn normal_below(&self, x: f32, y: f32, top: f32, length: f32) -> [f32; 3] {
190 let half = ((self.width as i32 - 1) >> 1) as f32;
191 let mut normal = [0.0; 3];
192 self.raycast_cell(
193 (x + half) as i32,
194 (y + half) as i32,
195 [0.0, 0.0, -1.0],
196 [x, y, top],
197 length,
198 &mut normal,
199 );
200 normal
201 }
202
203 pub fn ground(&self, x: f32, y: f32, normal: &mut [f32; 3]) -> f32 {
208 let half = ((self.width as i32 - 1) >> 1) as f32;
209 let ix = (x + half) as i32;
210 let iy = (y + half) as i32;
211 let dir = [0.0, 0.0, -1.0];
212 let origin = [x, y, RAY_TOP];
213 let (hit, t) = self.raycast_cell(ix, iy, dir, origin, RAY_LENGTH, normal);
214 if hit {
215 t * dir[2] + origin[2]
216 } else {
217 0.0
218 }
219 }
220
221 pub fn natural_cell_type(&self, map_size: usize, index: usize) -> CellType {
226 let size = map_size as i32;
227 let index = index as i32;
228 let offset = (size >> 1) as f32 - 0.5;
229 let x = (index % size) as f32 - offset;
230 let y = (index / size) as f32 - offset;
231 let mut normal = [0.0; 3];
232 let h = self.ground(x, y, &mut normal);
233 CellType::classify(h, normal[2])
234 }
235}
236
237#[derive(Debug, Clone, Copy, PartialEq, Eq)]
241pub struct CellType(pub u8);
242
243impl CellType {
244 pub const GROUND: CellType = CellType(2);
246 pub const HIGH: CellType = CellType(6);
248 pub const SHALLOW_WATER: CellType = CellType(7);
250 pub const DEEP_WATER: CellType = CellType(8);
252 pub const ROUGH: CellType = CellType(10);
254
255 pub fn classify(height: f32, up: f32) -> CellType {
261 if height < -1.4 {
262 return CellType::DEEP_WATER;
263 }
264 if height < -0.25 {
265 return CellType::SHALLOW_WATER;
266 }
267 if (-0.25..=0.75).contains(&height) && 0.9 <= up {
268 return CellType::GROUND;
269 }
270 if height < 2.0 {
271 CellType::ROUGH
272 } else {
273 CellType::HIGH
274 }
275 }
276
277 pub fn blocks_movement(self) -> bool {
279 (1u32 << self.0) & 0x1e0 != 0
280 }
281}
282
283#[cfg(test)]
284mod tests {
285 use super::*;
286
287 #[test]
290 fn a_nan_distance_misses_the_triangle() {
291 let (v0, v1, v2) = ([0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]);
292 let down = [0.0, 0.0, -1.0];
293 let (mut t, mut normal) = (0.0, [0.0; 3]);
294 assert!(ray_triangle(
295 [0.25, 0.25, 1.0],
296 down,
297 10.0,
298 v0,
299 v1,
300 v2,
301 &mut t,
302 &mut normal
303 ));
304 assert_eq!(t, 1.0);
305 let origin = [0.25, 0.25, f32::NAN];
306 assert!(!ray_triangle(
307 origin,
308 down,
309 10.0,
310 v0,
311 v1,
312 v2,
313 &mut t,
314 &mut normal
315 ));
316 assert!(t.is_nan());
317 }
318}