1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
use na::{DMatrix, Point3};
use crate::bounding_volume::AABB;
use crate::math::{Real, Vector};
use crate::shape::{FeatureId, Triangle};
bitflags! {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Default)]
pub struct HeightFieldCellStatus: u8 {
const ZIGZAG_SUBDIVISION = 0b00000001;
const LEFT_TRIANGLE_REMOVED = 0b00000010;
const RIGHT_TRIANGLE_REMOVED = 0b00000100;
const CELL_REMOVED = Self::LEFT_TRIANGLE_REMOVED.bits | Self::RIGHT_TRIANGLE_REMOVED.bits;
}
}
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug)]
pub struct HeightField {
heights: DMatrix<Real>,
scale: Vector<Real>,
aabb: AABB,
num_triangles: usize,
status: DMatrix<HeightFieldCellStatus>,
}
impl HeightField {
pub fn new(heights: DMatrix<Real>, scale: Vector<Real>) -> Self {
assert!(
heights.nrows() > 1 && heights.ncols() > 1,
"A heightfield heights must have at least 2 rows and columns."
);
let max = heights.max();
let min = heights.min();
let hscale = scale * na::convert::<_, Real>(0.5);
let aabb = AABB::new(
Point3::new(-hscale.x, min * scale.y, -hscale.z),
Point3::new(hscale.x, max * scale.y, hscale.z),
);
let num_triangles = (heights.nrows() - 1) * (heights.ncols() - 1) * 2;
let status = DMatrix::repeat(
heights.nrows() - 1,
heights.ncols() - 1,
HeightFieldCellStatus::default(),
);
HeightField {
heights,
scale,
aabb,
num_triangles,
status,
}
}
pub fn nrows(&self) -> usize {
self.heights.nrows() - 1
}
pub fn ncols(&self) -> usize {
self.heights.ncols() - 1
}
fn triangle_id(&self, i: usize, j: usize, left: bool) -> u32 {
let tid = j * (self.heights.nrows() - 1) + i;
if left {
tid as u32
} else {
(tid + self.num_triangles / 2) as u32
}
}
fn face_id(&self, i: usize, j: usize, left: bool, front: bool) -> u32 {
let tid = self.triangle_id(i, j, left);
if front {
tid
} else {
tid + self.num_triangles as u32
}
}
fn quantize_floor(&self, val: Real, cell_size: Real, num_cells: usize) -> usize {
let _0_5: Real = na::convert::<f64, Real>(0.5);
let i = na::clamp(
((val + _0_5) / cell_size).floor(),
0.0,
na::convert::<f64, Real>((num_cells - 1) as f64),
);
na::convert_unchecked::<Real, f64>(i) as usize
}
fn quantize_ceil(&self, val: Real, cell_size: Real, num_cells: usize) -> usize {
let _0_5: Real = na::convert::<f64, Real>(0.5);
let i = na::clamp(
((val + _0_5) / cell_size).ceil(),
0.0,
na::convert::<f64, Real>(num_cells as f64),
);
na::convert_unchecked::<Real, f64>(i) as usize
}
pub fn cell_at_point(&self, pt: &Point3<Real>) -> Option<(usize, usize)> {
let _0_5: Real = na::convert::<f64, Real>(0.5);
let scaled_pt = pt.coords.component_div(&self.scale);
let cell_width = self.unit_cell_width();
let cell_height = self.unit_cell_height();
let ncells_x = self.ncols();
let ncells_z = self.nrows();
if scaled_pt.x < -_0_5 || scaled_pt.x > _0_5 || scaled_pt.z < -_0_5 || scaled_pt.z > _0_5 {
None
} else {
let j = self.quantize_floor(scaled_pt.x, cell_width, ncells_x);
let i = self.quantize_floor(scaled_pt.z, cell_height, ncells_z);
Some((i, j))
}
}
pub fn x_at(&self, j: usize) -> Real {
let _0_5: Real = na::convert::<f64, Real>(0.5);
(-_0_5 + self.unit_cell_width() * na::convert::<f64, Real>(j as f64)) * self.scale.x
}
pub fn z_at(&self, i: usize) -> Real {
let _0_5: Real = na::convert::<f64, Real>(0.5);
(-_0_5 + self.unit_cell_height() * na::convert::<f64, Real>(i as f64)) * self.scale.z
}
pub fn triangles<'a>(&'a self) -> impl Iterator<Item = Triangle> + 'a {
HeightfieldTriangles {
heightfield: self,
curr: (0, 0),
tris: self.triangles_at(0, 0),
}
}
pub fn triangles_at(&self, i: usize, j: usize) -> (Option<Triangle>, Option<Triangle>) {
let status = self.status[(i, j)];
if status.contains(
HeightFieldCellStatus::LEFT_TRIANGLE_REMOVED
| HeightFieldCellStatus::RIGHT_TRIANGLE_REMOVED,
) {
return (None, None);
}
let cell_width = self.unit_cell_width();
let cell_height = self.unit_cell_height();
let _0_5: Real = na::convert::<f64, Real>(0.5);
let z0 = -_0_5 + cell_height * na::convert::<f64, Real>(i as f64);
let z1 = z0 + cell_height;
let x0 = -_0_5 + cell_width * na::convert::<f64, Real>(j as f64);
let x1 = x0 + cell_width;
let y00 = self.heights[(i + 0, j + 0)];
let y10 = self.heights[(i + 1, j + 0)];
let y01 = self.heights[(i + 0, j + 1)];
let y11 = self.heights[(i + 1, j + 1)];
let mut p00 = Point3::new(x0, y00, z0);
let mut p10 = Point3::new(x0, y10, z1);
let mut p01 = Point3::new(x1, y01, z0);
let mut p11 = Point3::new(x1, y11, z1);
p00.coords.component_mul_assign(&self.scale);
p10.coords.component_mul_assign(&self.scale);
p01.coords.component_mul_assign(&self.scale);
p11.coords.component_mul_assign(&self.scale);
if status.contains(HeightFieldCellStatus::ZIGZAG_SUBDIVISION) {
let tri1 = if status.contains(HeightFieldCellStatus::LEFT_TRIANGLE_REMOVED) {
None
} else {
Some(Triangle::new(p00, p10, p11))
};
let tri2 = if status.contains(HeightFieldCellStatus::RIGHT_TRIANGLE_REMOVED) {
None
} else {
Some(Triangle::new(p00, p11, p01))
};
(tri1, tri2)
} else {
let tri1 = if status.contains(HeightFieldCellStatus::LEFT_TRIANGLE_REMOVED) {
None
} else {
Some(Triangle::new(p00, p10, p01))
};
let tri2 = if status.contains(HeightFieldCellStatus::RIGHT_TRIANGLE_REMOVED) {
None
} else {
Some(Triangle::new(p10, p11, p01))
};
(tri1, tri2)
}
}
pub fn cell_status(&self, i: usize, j: usize) -> HeightFieldCellStatus {
self.status[(i, j)]
}
pub fn set_cell_status(&mut self, i: usize, j: usize, status: HeightFieldCellStatus) {
self.status[(i, j)] = status
}
pub fn cells_statuses(&self) -> &DMatrix<HeightFieldCellStatus> {
&self.status
}
pub fn cells_statuses_mut(&mut self) -> &mut DMatrix<HeightFieldCellStatus> {
&mut self.status
}
pub fn heights(&self) -> &DMatrix<Real> {
&self.heights
}
pub fn scale(&self) -> &Vector<Real> {
&self.scale
}
pub fn cell_width(&self) -> Real {
self.unit_cell_width() * self.scale.x
}
pub fn cell_height(&self) -> Real {
self.unit_cell_height() * self.scale.z
}
pub fn unit_cell_width(&self) -> Real {
1.0 / na::convert::<f64, Real>(self.heights.ncols() as f64 - 1.0)
}
pub fn unit_cell_height(&self) -> Real {
1.0 / na::convert::<f64, Real>(self.heights.nrows() as f64 - 1.0)
}
pub fn root_aabb(&self) -> &AABB {
&self.aabb
}
pub fn convert_triangle_feature_id(
&self,
i: usize,
j: usize,
left: bool,
fid: FeatureId,
) -> FeatureId {
match fid {
FeatureId::Vertex(ivertex) => {
let nrows = self.heights.nrows();
let ij = i + j * nrows;
if self.status[(i, j)].contains(HeightFieldCellStatus::ZIGZAG_SUBDIVISION) {
if left {
FeatureId::Vertex([ij, ij + 1, ij + 1 + nrows][ivertex as usize] as u32)
} else {
FeatureId::Vertex([ij, ij + 1 + nrows, ij + nrows][ivertex as usize] as u32)
}
} else {
if left {
FeatureId::Vertex([ij, ij + 1, ij + nrows][ivertex as usize] as u32)
} else {
FeatureId::Vertex(
[ij + 1, ij + 1 + nrows, ij + nrows][ivertex as usize] as u32,
)
}
}
}
FeatureId::Edge(iedge) => {
let (nrows, ncols) = self.heights.shape();
let vshift = 0;
let hshift = (nrows - 1) * ncols;
let dshift = hshift + nrows * (ncols - 1);
let idiag = dshift + i + j * (nrows - 1);
let itop = hshift + i + j * nrows;
let ibottom = itop + 1;
let ileft = vshift + i + j * (nrows - 1);
let iright = ileft + nrows - 1;
if self.status[(i, j)].contains(HeightFieldCellStatus::ZIGZAG_SUBDIVISION) {
if left {
FeatureId::Edge([ileft, ibottom, idiag][iedge as usize] as u32)
} else {
FeatureId::Edge([idiag, iright, itop][iedge as usize] as u32)
}
} else {
if left {
FeatureId::Edge([ileft, idiag, itop][iedge as usize] as u32)
} else {
FeatureId::Edge([ibottom, iright, idiag][iedge as usize] as u32)
}
}
}
FeatureId::Face(iface) => {
if iface == 0 {
FeatureId::Face(self.face_id(i, j, left, true))
} else {
FeatureId::Face(self.face_id(i, j, left, false))
}
}
FeatureId::Unknown => FeatureId::Unknown,
}
}
pub fn map_elements_in_local_aabb(&self, aabb: &AABB, f: &mut impl FnMut(u32, &Triangle)) {
let _0_5: Real = na::convert::<f64, Real>(0.5);
let ncells_x = self.ncols();
let ncells_z = self.nrows();
let ref_mins = aabb.mins.coords.component_div(&self.scale);
let ref_maxs = aabb.maxs.coords.component_div(&self.scale);
let cell_width = self.unit_cell_width();
let cell_height = self.unit_cell_height();
if ref_maxs.x <= -_0_5 || ref_maxs.z <= -_0_5 || ref_mins.x >= _0_5 || ref_mins.z >= _0_5 {
return;
}
let min_x = self.quantize_floor(ref_mins.x, cell_width, ncells_x);
let min_z = self.quantize_floor(ref_mins.z, cell_height, ncells_z);
let max_x = self.quantize_ceil(ref_maxs.x, cell_width, ncells_x);
let max_z = self.quantize_ceil(ref_maxs.z, cell_height, ncells_z);
for j in min_x..max_x {
for i in min_z..max_z {
let status = self.status[(i, j)];
if status.contains(HeightFieldCellStatus::CELL_REMOVED) {
continue;
}
let z0 = -_0_5 + cell_height * na::convert::<f64, Real>(i as f64);
let z1 = z0 + cell_height;
let x0 = -_0_5 + cell_width * na::convert::<f64, Real>(j as f64);
let x1 = x0 + cell_width;
let y00 = self.heights[(i + 0, j + 0)];
let y10 = self.heights[(i + 1, j + 0)];
let y01 = self.heights[(i + 0, j + 1)];
let y11 = self.heights[(i + 1, j + 1)];
if (y00 > ref_maxs.y && y10 > ref_maxs.y && y01 > ref_maxs.y && y11 > ref_maxs.y)
|| (y00 < ref_mins.y
&& y10 < ref_mins.y
&& y01 < ref_mins.y
&& y11 < ref_mins.y)
{
continue;
}
let mut p00 = Point3::new(x0, y00, z0);
let mut p10 = Point3::new(x0, y10, z1);
let mut p01 = Point3::new(x1, y01, z0);
let mut p11 = Point3::new(x1, y11, z1);
p00.coords.component_mul_assign(&self.scale);
p10.coords.component_mul_assign(&self.scale);
p01.coords.component_mul_assign(&self.scale);
p11.coords.component_mul_assign(&self.scale);
if !status.contains(HeightFieldCellStatus::LEFT_TRIANGLE_REMOVED) {
let tri1 = if status.contains(HeightFieldCellStatus::ZIGZAG_SUBDIVISION) {
Triangle::new(p00, p10, p11)
} else {
Triangle::new(p00, p10, p01)
};
let tid = self.triangle_id(i, j, true);
f(tid as u32, &tri1);
}
if !status.contains(HeightFieldCellStatus::RIGHT_TRIANGLE_REMOVED) {
let tri2 = if status.contains(HeightFieldCellStatus::ZIGZAG_SUBDIVISION) {
Triangle::new(p00, p11, p01)
} else {
Triangle::new(p10, p11, p01)
};
let tid = self.triangle_id(i, j, false);
f(tid as u32, &tri2);
}
}
}
}
}
struct HeightfieldTriangles<'a> {
heightfield: &'a HeightField,
curr: (usize, usize),
tris: (Option<Triangle>, Option<Triangle>),
}
impl<'a> Iterator for HeightfieldTriangles<'a> {
type Item = Triangle;
fn next(&mut self) -> Option<Triangle> {
loop {
if let Some(tri1) = self.tris.0.take() {
return Some(tri1);
} else if let Some(tri2) = self.tris.1.take() {
return Some(tri2);
} else {
self.curr.0 += 1;
if self.curr.0 >= self.heightfield.nrows() {
if self.curr.1 >= self.heightfield.ncols() - 1 {
return None;
}
self.curr.0 = 0;
self.curr.1 += 1;
}
self.tris = self.heightfield.triangles_at(self.curr.0, self.curr.1);
}
}
}
}