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
use std::borrow::Borrow;
use crate::{
bvh2::Bvh2,
fast_stack,
faststack::FastStack,
ploc::{PlocBuilder, PlocSearchDistance, SortPrecision},
};
/// Provide a set of leaves that need to be rebuilt. After calling, flags will be true for any node index up the tree
/// that needs to be included in the partial rebuild.
pub fn compute_rebuild_path_flags<I, L>(bvh: &Bvh2, leaves: I, flags: &mut Vec<bool>)
where
I: IntoIterator<Item = L>,
L: Borrow<u32>,
{
if bvh.nodes.len() < 2 {
return;
}
if bvh.parents.is_empty() {
panic!(
"Parents must be init before running compute_rebuild_path_flags. Call `bvh.init_parents_if_uninit()` first."
)
}
flags.clear();
flags.resize(bvh.nodes.len(), false);
// Bottom up traverse flagging nodes as being parents of leaves that need to be rebuilt.
for leaf_id in leaves {
let mut index = *leaf_id.borrow() as usize;
debug_assert!(bvh.nodes[index].is_leaf());
flags[index] = true;
while index > 0 {
index = bvh.parents[index] as usize;
if flags[index] {
// If already flagged don't need to continue up further, above this has already been traversed.
break;
}
flags[index] = true;
}
}
}
impl PlocBuilder {
/// Fully rebuild the bvh from its current leaves.
///
/// # Arguments
/// * `bvh` - An existing bvh with valid leaves. Inner nodes are ignored.
/// * `search_distance` - Which search distance should be used when building the ploc.
/// * `sort_precision` - Bits used for ploc radix sort. More bits results in a more accurate but slower sort.
/// * `search_depth_threshold` - Below this depth a search distance of 1 will be used. Set to 0 to bypass and
/// just use search_distance.
pub fn full_rebuild(
&mut self,
bvh: &mut Bvh2,
search_distance: PlocSearchDistance,
sort_precision: SortPrecision,
search_depth_threshold: usize,
) {
if bvh.nodes.len() < 2 {
return;
}
self.current_nodes.clear();
// Collect all leaves
for node in &bvh.nodes {
if node.is_leaf() {
self.current_nodes.push(*node);
}
}
self.rebuild_from_leaves::<false>(
bvh,
search_distance,
sort_precision,
search_depth_threshold,
);
}
/// Partially rebuild the bvh. The given set of leaves and the subtrees that do not include any of the given leaves
/// will be built into a new bvh. If the set of leaves is a small enough proportion of the total this can be faster
/// since there may be large portions of the BVH that don't need to be updated. If the proportion is very high it
/// can be faster to build from scratch instead, avoiding the overhead of doing a partial rebuild. If only a few
/// nodes need to be updated it might be faster and produce a better BVH to selectively reinsert them.
///
/// # Arguments
/// * `bvh` - An existing bvh with valid layout (AABBs in the tree above nodes that are to be rebuilt does not need
/// to be correct)
/// * `should_remove()` - should return true for any node that should be include in the rebuild. This includes the
/// entire chain up from any leaves that need to be updated. Use PlocBuilder::compute_rebuild_path_flags() or
/// similar to compute. The leaves should have their new AABB before calling partial_rebuild() but the BVH does
/// not need to be refit to accommodate them.
/// * `search_distance` - Which search distance should be used when building the ploc.
/// * `sort_precision` - Bits used for ploc radix sort. More bits results in a more accurate but slower sort.
/// * `search_depth_threshold` - Below this depth a search distance of 1 will be used. Set to 0 to bypass and
/// just use search_distance.
pub fn partial_rebuild(
&mut self,
bvh: &mut Bvh2,
should_remove: impl Fn(usize) -> bool,
search_distance: PlocSearchDistance,
sort_precision: SortPrecision,
search_depth_threshold: usize,
) {
if bvh.nodes.len() < 2 {
return;
}
self.current_nodes.clear();
// Top down traverse to collect leaves and unflagged subtrees
fast_stack!(u32, (96, 192), bvh.max_depth, stack, {
stack.push(bvh.nodes[0].first_index);
while let Some(left_node_index) = stack.pop() {
for node_index in [left_node_index as usize, left_node_index as usize + 1] {
let node = &mut bvh.nodes[node_index];
if !should_remove(node_index) || node.is_leaf() {
self.current_nodes.push(*node);
} else {
stack.push(node.first_index);
}
node.set_invalid();
}
}
});
self.rebuild_from_leaves::<true>(
bvh,
search_distance,
sort_precision,
search_depth_threshold,
);
}
fn rebuild_from_leaves<const PARTIAL: bool>(
&mut self,
bvh: &mut Bvh2,
search_distance: PlocSearchDistance,
sort_precision: SortPrecision,
search_depth_threshold: usize,
) {
if bvh.nodes.len() < 2 {
return;
}
let had_parents = !bvh.parents.is_empty();
let had_primitives_to_nodes = !bvh.primitives_to_nodes.is_empty();
self.next_nodes.clear();
self.mortons.clear();
// Rebuild BVH from leaves
let total_aabb = *bvh.nodes[0].aabb();
let sdt = search_depth_threshold;
match search_distance {
PlocSearchDistance::Minimum => {
self.build_ploc_from_leaves::<1, PARTIAL>(bvh, total_aabb, sort_precision, sdt)
}
PlocSearchDistance::VeryLow => {
self.build_ploc_from_leaves::<2, PARTIAL>(bvh, total_aabb, sort_precision, sdt)
}
PlocSearchDistance::Low => {
self.build_ploc_from_leaves::<6, PARTIAL>(bvh, total_aabb, sort_precision, sdt)
}
PlocSearchDistance::Medium => {
self.build_ploc_from_leaves::<14, PARTIAL>(bvh, total_aabb, sort_precision, sdt)
}
PlocSearchDistance::High => {
self.build_ploc_from_leaves::<24, PARTIAL>(bvh, total_aabb, sort_precision, sdt)
}
PlocSearchDistance::VeryHigh => {
self.build_ploc_from_leaves::<32, PARTIAL>(bvh, total_aabb, sort_precision, sdt)
}
}
if had_parents {
bvh.update_parents();
}
if had_primitives_to_nodes {
bvh.update_primitives_to_nodes();
}
}
}
#[cfg(test)]
mod tests {
use glam::UVec2;
use super::*;
use crate::{
INVALID,
test_util::{geometry::demoscene, sampling::hash_noise},
};
#[test]
fn test_full_rebuild() {
let sm = demoscene(5, 0);
for tris in [&demoscene(31, 0), &sm, &sm[..1], &sm[..2], &sm[..3], &[]] {
let mut builder = PlocBuilder::with_capacity(tris.len());
let mut bvh = builder.build(
PlocSearchDistance::Minimum,
tris,
(0..tris.len() as u32).collect::<Vec<_>>(),
SortPrecision::U64,
1,
);
bvh.validate(tris, false, true);
builder.full_rebuild(&mut bvh, PlocSearchDistance::Minimum, SortPrecision::U64, 1);
bvh.validate(tris, false, true);
}
}
#[test]
fn test_full_rebuild_with_free_indices() {
let tris = demoscene(32, 0);
let mut builder = PlocBuilder::with_capacity(tris.len());
let mut bvh = builder.build(
PlocSearchDistance::Minimum,
&tris,
(0..tris.len() as u32).collect::<Vec<_>>(),
SortPrecision::U64,
1,
);
bvh.validate(&tris, false, true);
// Remove some primitives to create free indices
bvh.remove_primitive(6);
bvh.remove_primitive(9);
bvh.remove_primitive(10);
assert_eq!(bvh.primitive_indices_freelist.len(), 3);
assert!(bvh.primitive_indices.contains(&INVALID));
// Now do a full rebuild
builder.full_rebuild(&mut bvh, PlocSearchDistance::Minimum, SortPrecision::U64, 1);
bvh.validate(&tris, false, true);
}
#[test]
fn test_partial_rebuild_with_all_leaves() {
let sm = demoscene(5, 0);
for tris in [&demoscene(31, 0), &sm, &sm[..1], &sm[..2], &sm[..3], &[]] {
let mut builder = PlocBuilder::with_capacity(tris.len());
let mut bvh = builder.build(
PlocSearchDistance::Minimum,
tris,
(0..tris.len() as u32).collect::<Vec<_>>(),
SortPrecision::U64,
1,
);
bvh.validate(tris, false, true);
bvh.init_parents_if_uninit();
let mut flags = Vec::new();
compute_rebuild_path_flags(
&bvh,
bvh.nodes
.iter()
.enumerate()
.filter(|(_i, n)| n.is_leaf())
.map(|(i, _n)| i as u32),
&mut flags,
);
builder.partial_rebuild(
&mut bvh,
|node_id| flags[node_id],
PlocSearchDistance::Minimum,
SortPrecision::U64,
1,
);
bvh.validate(tris, false, true);
}
}
#[test]
fn test_partial_rebuild_with_one_leaf() {
let tris = demoscene(8, 0);
let mut builder = PlocBuilder::with_capacity(tris.len());
let mut bvh = builder.build(
PlocSearchDistance::Minimum,
&tris,
(0..tris.len() as u32).collect::<Vec<_>>(),
SortPrecision::U64,
0,
);
bvh.validate(&tris, false, true);
bvh.init_parents_if_uninit();
let mut flags = Vec::new();
compute_rebuild_path_flags(
&bvh,
bvh.nodes
.iter()
.enumerate()
.filter(|(_i, n)| n.is_leaf())
.map(|(i, _n)| i as u32)
.take(1),
&mut flags,
);
builder.partial_rebuild(
&mut bvh,
|node_id| flags[node_id],
PlocSearchDistance::Minimum,
SortPrecision::U64,
0,
);
bvh.validate(&tris, false, true);
}
#[test]
fn test_partial_rebuild_with_random_leaves() {
let sm = demoscene(5, 0);
for tris in [&demoscene(31, 0), &sm, &sm[..1], &sm[..2], &sm[..3], &[]] {
let mut builder = PlocBuilder::with_capacity(tris.len());
let mut bvh = builder.build(
PlocSearchDistance::Minimum,
tris,
(0..tris.len() as u32).collect::<Vec<_>>(),
SortPrecision::U64,
1,
);
bvh.validate(tris, false, true);
bvh.init_parents_if_uninit();
let mut flags = Vec::new();
compute_rebuild_path_flags(
&bvh,
bvh.nodes
.iter()
.enumerate()
.filter(|(i, n)| n.is_leaf() && hash_noise(UVec2::ZERO, *i as u32) > 0.5)
.map(|(i, _n)| i as u32)
.take(1),
&mut flags,
);
builder.partial_rebuild(
&mut bvh,
|node_id| flags[node_id],
PlocSearchDistance::Minimum,
SortPrecision::U64,
0,
);
bvh.validate(tris, false, true);
}
}
}