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 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
//! This module defines [`Bvh`] and [`BvhNode`] and functions for building and traversing it.
//!
//! [`Bvh`]: struct.Bvh.html
//! [`BvhNode`]: struct.BvhNode.html
//!
use crate::aabb::{Aabb, Bounded};
use crate::bounding_hierarchy::{BHShape, BHValue, BoundingHierarchy};
use crate::bvh::iter::BvhTraverseIterator;
use crate::ray::Ray;
use crate::utils::joint_aabb_of_shapes;
use std::mem::MaybeUninit;
use super::{BvhNode, BvhNodeBuildArgs, ShapeIndex, Shapes};
/// The [`Bvh`] data structure. Contains the list of [`BvhNode`]s.
///
/// [`Bvh`]: struct.Bvh.html
///
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Bvh<T: BHValue, const D: usize> {
/// The list of nodes of the [`Bvh`].
///
/// [`Bvh`]: struct.Bvh.html
///
pub nodes: Vec<BvhNode<T, D>>,
}
impl<T: BHValue, const D: usize> Bvh<T, D> {
/// Creates a new [`Bvh`] from the `shapes` slice.
///
/// [`Bvh`]: struct.Bvh.html
///
pub fn build<Shape: BHShape<T, D>>(shapes: &mut [Shape]) -> Bvh<T, D> {
Self::build_with_executor(shapes, |left, right| {
left.build();
right.build();
})
}
/// Creates a new [`Bvh`] from the `shapes` slice.
/// The executor parameter allows you to parallelize the build of the [`Bvh`]. Using something like rayon::join.
/// You must call either build or build_with_executor on both arguments in order to succesfully complete the build.
///
/// [`Bvh`]: struct.Bvh.html
///
pub fn build_with_executor<Shape: BHShape<T, D>>(
shapes: &mut [Shape],
executor: impl FnMut(BvhNodeBuildArgs<Shape, T, D>, BvhNodeBuildArgs<Shape, T, D>),
) -> Bvh<T, D> {
if shapes.is_empty() {
return Bvh { nodes: Vec::new() };
}
let mut indices = (0..shapes.len())
.map(ShapeIndex)
.collect::<Vec<ShapeIndex>>();
let expected_node_count = shapes.len() * 2 - 1;
let mut nodes = Vec::with_capacity(expected_node_count);
let uninit_slice = unsafe {
std::slice::from_raw_parts_mut(
nodes.as_mut_ptr() as *mut MaybeUninit<BvhNode<T, D>>,
expected_node_count,
)
};
let shapes = Shapes::from_slice(shapes);
let (aabb, centroid) = joint_aabb_of_shapes(&indices, &shapes);
BvhNode::build_with_executor(
BvhNodeBuildArgs {
shapes: &shapes,
indices: &mut indices,
nodes: uninit_slice,
parent_index: 0,
depth: 0,
node_index: 0,
aabb_bounds: aabb,
centroid_bounds: centroid,
},
executor,
);
// SAFETY
// The vec is allocated with this capacity above and is only mutated through slice methods so
// it is guaranteed that the allocated size has not changed.
unsafe {
nodes.set_len(expected_node_count);
}
Bvh { nodes }
}
/// Traverses the [`Bvh`].
/// Returns a subset of `shapes`, in which the [`Aabb`]s of the elements were hit by `ray`.
///
/// [`Bvh`]: struct.Bvh.html
/// [`Aabb`]: ../aabb/struct.Aabb.html
///
pub fn traverse<'a, Shape: Bounded<T, D>>(
&'a self,
ray: &Ray<T, D>,
shapes: &'a [Shape],
) -> Vec<&Shape> {
let mut indices = Vec::new();
BvhNode::traverse_recursive(&self.nodes, 0, ray, &mut indices);
indices
.iter()
.map(|index| &shapes[*index])
.collect::<Vec<_>>()
}
/// Creates a [`BvhTraverseIterator`] to traverse the [`Bvh`].
/// Returns a subset of `shapes`, in which the [`Aabb`]s of the elements were hit by `ray`.
///
/// [`Bvh`]: struct.Bvh.html
/// [`Aabb`]: ../aabb/struct.Aabb.html
///
pub fn traverse_iterator<'bvh, 'shape, Shape: Bounded<T, D>>(
&'bvh self,
ray: &'bvh Ray<T, D>,
shapes: &'shape [Shape],
) -> BvhTraverseIterator<'bvh, 'shape, T, D, Shape> {
BvhTraverseIterator::new(self, ray, shapes)
}
/// Prints the [`Bvh`] in a tree-like visualization.
///
/// [`Bvh`]: struct.Bvh.html
///
pub fn pretty_print(&self) {
let nodes = &self.nodes;
fn print_node<T: BHValue, const D: usize>(
nodes: &[BvhNode<T, D>],
node_index: usize,
depth: usize,
) {
match nodes[node_index] {
BvhNode::Node {
child_l_index,
child_r_index,
child_l_aabb,
child_r_aabb,
..
} => {
let padding: String = " ".repeat(depth);
println!("{}child_l {}", padding, child_l_aabb);
print_node(nodes, child_l_index, depth + 1);
println!("{}child_r {}", padding, child_r_aabb);
print_node(nodes, child_r_index, depth + 1);
}
BvhNode::Leaf { shape_index, .. } => {
let padding: String = " ".repeat(depth);
println!("{}shape\t{:?}", padding, shape_index);
}
}
}
print_node(nodes, 0, 0);
}
/// Verifies that the node at index `node_index` lies inside `expected_outer_aabb`,
/// its parent index is equal to `expected_parent_index`, its depth is equal to
/// `expected_depth`. Increases `node_count` by the number of visited nodes.
fn is_consistent_subtree<Shape: BHShape<T, D>>(
&self,
node_index: usize,
expected_parent_index: usize,
expected_outer_aabb: &Aabb<T, D>,
node_count: &mut usize,
shapes: &[Shape],
) -> bool {
*node_count += 1;
match self.nodes[node_index] {
BvhNode::Node {
parent_index,
child_l_index,
child_l_aabb,
child_r_index,
child_r_aabb,
} => {
let correct_parent_index = expected_parent_index == parent_index;
let left_aabb_in_parent =
expected_outer_aabb.approx_contains_aabb_eps(&child_l_aabb, T::epsilon());
let right_aabb_in_parent =
expected_outer_aabb.approx_contains_aabb_eps(&child_r_aabb, T::epsilon());
let left_subtree_consistent = self.is_consistent_subtree(
child_l_index,
node_index,
&child_l_aabb,
node_count,
shapes,
);
let right_subtree_consistent = self.is_consistent_subtree(
child_r_index,
node_index,
&child_r_aabb,
node_count,
shapes,
);
correct_parent_index
&& left_aabb_in_parent
&& right_aabb_in_parent
&& left_subtree_consistent
&& right_subtree_consistent
}
BvhNode::Leaf {
parent_index,
shape_index,
} => {
let correct_parent_index = expected_parent_index == parent_index;
let shape_aabb = shapes[shape_index].aabb();
let shape_aabb_in_parent =
expected_outer_aabb.approx_contains_aabb_eps(&shape_aabb, T::epsilon());
correct_parent_index && shape_aabb_in_parent
}
}
}
/// Checks if all children of a node have the correct parent index, and that there is no
/// detached subtree. Also checks if the `Aabb` hierarchy is consistent.
pub fn is_consistent<Shape: BHShape<T, D>>(&self, shapes: &[Shape]) -> bool {
// The root node of the bvh is not bounded by anything.
let space = Aabb::infinite();
// The counter for all nodes.
let mut node_count = 0;
let subtree_consistent = self.is_consistent_subtree(0, 0, &space, &mut node_count, shapes);
// Check if all nodes have been counted from the root node.
// If this is false, it means we have a detached subtree.
let is_connected = node_count == self.nodes.len();
subtree_consistent && is_connected
}
/// Assert version of `is_consistent_subtree`.
fn assert_consistent_subtree<Shape: BHShape<T, D>>(
&self,
node_index: usize,
expected_parent_index: usize,
expected_outer_aabb: &Aabb<T, D>,
node_count: &mut usize,
shapes: &[Shape],
) where
T: std::fmt::Display,
{
*node_count += 1;
let node = &self.nodes[node_index];
let parent = node.parent();
assert_eq!(
expected_parent_index, parent,
"Wrong parent index. Expected: {}; Actual: {}",
expected_parent_index, parent
);
match *node {
BvhNode::Node {
child_l_index,
child_l_aabb,
child_r_index,
child_r_aabb,
..
} => {
assert!(
expected_outer_aabb.approx_contains_aabb_eps(&child_l_aabb, T::epsilon()),
"Left child lies outside the expected bounds.
\tBounds: {}
\tLeft child: {}",
expected_outer_aabb,
child_l_aabb
);
assert!(
expected_outer_aabb.approx_contains_aabb_eps(&child_r_aabb, T::epsilon()),
"Right child lies outside the expected bounds.
\tBounds: {}
\tRight child: {}",
expected_outer_aabb,
child_r_aabb
);
self.assert_consistent_subtree(
child_l_index,
node_index,
&child_l_aabb,
node_count,
shapes,
);
self.assert_consistent_subtree(
child_r_index,
node_index,
&child_r_aabb,
node_count,
shapes,
);
}
BvhNode::Leaf { shape_index, .. } => {
let shape_aabb = shapes[shape_index].aabb();
assert!(
expected_outer_aabb.approx_contains_aabb_eps(&shape_aabb, T::epsilon()),
"Shape's Aabb lies outside the expected bounds.\n\tBounds: {}\n\tShape: {}",
expected_outer_aabb,
shape_aabb
);
}
}
}
/// Assert version of `is_consistent`.
pub fn assert_consistent<Shape: BHShape<T, D>>(&self, shapes: &[Shape])
where
T: std::fmt::Display,
{
// The root node of the bvh is not bounded by anything.
let space = Aabb::infinite();
// The counter for all nodes.
let mut node_count = 0;
self.assert_consistent_subtree(0, 0, &space, &mut node_count, shapes);
// Check if all nodes have been counted from the root node.
// If this is false, it means we have a detached subtree.
assert_eq!(node_count, self.nodes.len(), "Detached subtree");
}
/// Check that the `Aabb`s in the `Bvh` are tight, which means, that parent `Aabb`s are not
/// larger than they should be. This function checks, whether the children of node `node_index`
/// lie inside `outer_aabb`.
pub fn assert_tight_subtree(&self, node_index: usize, outer_aabb: &Aabb<T, D>) {
if let BvhNode::Node {
child_l_index,
child_l_aabb,
child_r_index,
child_r_aabb,
..
} = self.nodes[node_index]
{
let joint_aabb = child_l_aabb.join(&child_r_aabb);
assert!(joint_aabb.relative_eq(outer_aabb, T::epsilon()));
self.assert_tight_subtree(child_l_index, &child_l_aabb);
self.assert_tight_subtree(child_r_index, &child_r_aabb);
}
}
/// Check that the `Aabb`s in the `Bvh` are tight, which means, that parent `Aabb`s are not
/// larger than they should be.
pub fn assert_tight(&self) {
// When starting to check whether the `Bvh` is tight, we cannot provide a minimum
// outer `Aabb`, therefore we compute the correct one in this instance.
if let BvhNode::Node {
child_l_aabb,
child_r_aabb,
..
} = self.nodes[0]
{
let joint_aabb = child_l_aabb.join(&child_r_aabb);
self.assert_tight_subtree(0, &joint_aabb);
}
}
}
impl<T: BHValue + std::fmt::Display, const D: usize> BoundingHierarchy<T, D> for Bvh<T, D> {
fn build<Shape: BHShape<T, D>>(shapes: &mut [Shape]) -> Bvh<T, D> {
Bvh::build(shapes)
}
fn traverse<'a, Shape: Bounded<T, D>>(
&'a self,
ray: &Ray<T, D>,
shapes: &'a [Shape],
) -> Vec<&Shape> {
self.traverse(ray, shapes)
}
fn pretty_print(&self) {
self.pretty_print();
}
fn build_with_executor<
Shape: BHShape<T, D>,
Executor: FnMut(BvhNodeBuildArgs<'_, Shape, T, D>, BvhNodeBuildArgs<'_, Shape, T, D>),
>(
shapes: &mut [Shape],
executor: Executor,
) -> Self {
Bvh::build_with_executor(shapes, executor)
}
}
/// Rayon based executor
#[cfg(feature = "rayon")]
pub fn rayon_executor<S, T: Send + BHValue, const D: usize>(
left: BvhNodeBuildArgs<S, T, D>,
right: BvhNodeBuildArgs<S, T, D>,
) where
S: BHShape<T, D> + Send,
{
// 64 was found experimentally. Calling join() has overhead that makes the build slower without this.
if left.node_count() + right.node_count() < 64 {
left.build();
right.build();
} else {
rayon::join(
|| left.build_with_executor(rayon_executor),
|| right.build_with_executor(rayon_executor),
);
}
}
#[cfg(test)]
mod tests {
use crate::testbase::{build_some_bh, traverse_some_bh, TBvh3, TBvhNode3};
#[test]
/// Tests whether the building procedure succeeds in not failing.
fn test_build_bvh() {
build_some_bh::<TBvh3>();
}
#[test]
/// Runs some primitive tests for intersections of a ray with a fixed scene given as a [`Bvh`].
fn test_traverse_bvh() {
traverse_some_bh::<TBvh3>();
}
#[test]
/// Verify contents of the bounding hierarchy for a fixed scene structure
fn test_bvh_shape_indices() {
use std::collections::HashSet;
let (all_shapes, bh) = build_some_bh::<TBvh3>();
// It should find all shape indices.
let expected_shapes: HashSet<_> = (0..all_shapes.len()).collect();
let mut found_shapes = HashSet::new();
for node in bh.nodes.iter() {
match *node {
TBvhNode3::Node { .. } => {
assert_eq!(node.shape_index(), None);
}
TBvhNode3::Leaf { .. } => {
found_shapes.insert(
node.shape_index()
.expect("getting a shape index from a leaf node"),
);
}
}
}
assert_eq!(expected_shapes, found_shapes);
}
#[test]
#[cfg(feature = "rayon")]
/// Tests whether the building procedure succeeds in not failing.
fn test_build_bvh_rayon() {
use crate::testbase::build_some_bh_rayon;
build_some_bh_rayon::<TBvh3>();
}
#[test]
#[cfg(feature = "rayon")]
/// Runs some primitive tests for intersections of a ray with a fixed scene given as a [`Bvh`].
fn test_traverse_bvh_rayon() {
use crate::testbase::traverse_some_bh_rayon;
traverse_some_bh_rayon::<TBvh3>();
}
#[test]
#[cfg(feature = "rayon")]
/// Verify contents of the bounding hierarchy for a fixed scene structure
fn test_bvh_shape_indices_rayon() {
use std::collections::HashSet;
use crate::testbase::build_some_bh_rayon;
let (all_shapes, bh) = build_some_bh_rayon::<TBvh3>();
// It should find all shape indices.
let expected_shapes: HashSet<_> = (0..all_shapes.len()).collect();
let mut found_shapes = HashSet::new();
for node in bh.nodes.iter() {
match *node {
TBvhNode3::Node { .. } => {
assert_eq!(node.shape_index(), None);
}
TBvhNode3::Leaf { .. } => {
found_shapes.insert(
node.shape_index()
.expect("getting a shape index from a leaf node"),
);
}
}
}
assert_eq!(expected_shapes, found_shapes);
}
}
#[cfg(all(feature = "bench", test))]
mod bench {
#[cfg(feature = "rayon")]
use crate::bounding_hierarchy::BoundingHierarchy;
use crate::testbase::{
build_1200_triangles_bh, build_120k_triangles_bh, build_12k_triangles_bh,
intersect_1200_triangles_bh, intersect_120k_triangles_bh, intersect_12k_triangles_bh,
intersect_bh, load_sponza_scene, TBvh3,
};
#[cfg(feature = "rayon")]
use crate::testbase::{
build_1200_triangles_bh_rayon, build_120k_triangles_bh_rayon, build_12k_triangles_bh_rayon,
};
#[bench]
/// Benchmark the construction of a [`Bvh`] with 1,200 triangles.
fn bench_build_1200_triangles_bvh(b: &mut ::test::Bencher) {
build_1200_triangles_bh::<TBvh3>(b);
}
#[bench]
/// Benchmark the construction of a [`Bvh`] with 12,000 triangles.
fn bench_build_12k_triangles_bvh(b: &mut ::test::Bencher) {
build_12k_triangles_bh::<TBvh3>(b);
}
#[bench]
/// Benchmark the construction of a [`Bvh`] with 120,000 triangles.
fn bench_build_120k_triangles_bvh(b: &mut ::test::Bencher) {
build_120k_triangles_bh::<TBvh3>(b);
}
#[bench]
/// Benchmark the construction of a [`Bvh`] for the Sponza scene.
fn bench_build_sponza_bvh(b: &mut ::test::Bencher) {
let (mut triangles, _) = load_sponza_scene();
b.iter(|| {
TBvh3::build(&mut triangles);
});
}
#[cfg(feature = "rayon")]
#[bench]
/// Benchmark the construction of a `BVH` with 1,200 triangles.
fn bench_build_1200_triangles_bvh_rayon(b: &mut ::test::Bencher) {
build_1200_triangles_bh_rayon::<TBvh3>(b);
}
#[bench]
#[cfg(feature = "rayon")]
/// Benchmark the construction of a `BVH` with 12,000 triangles.
fn bench_build_12k_triangles_bvh_rayon(b: &mut ::test::Bencher) {
build_12k_triangles_bh_rayon::<TBvh3>(b);
}
#[bench]
#[cfg(feature = "rayon")]
/// Benchmark the construction of a `BVH` with 120,000 triangles.
fn bench_build_120k_triangles_bvh_rayon(b: &mut ::test::Bencher) {
build_120k_triangles_bh_rayon::<TBvh3>(b);
}
#[bench]
#[cfg(feature = "rayon")]
/// Benchmark the construction of a `BVH` for the Sponza scene.
fn bench_build_sponza_bvh_rayon(b: &mut ::test::Bencher) {
let (mut triangles, _) = load_sponza_scene();
b.iter(|| {
TBvh3::build_par(&mut triangles);
});
}
#[bench]
/// Benchmark intersecting 1,200 triangles using the recursive [`Bvh`].
fn bench_intersect_1200_triangles_bvh(b: &mut ::test::Bencher) {
intersect_1200_triangles_bh::<TBvh3>(b);
}
#[bench]
/// Benchmark intersecting 12,000 triangles using the recursive [`Bvh`].
fn bench_intersect_12k_triangles_bvh(b: &mut ::test::Bencher) {
intersect_12k_triangles_bh::<TBvh3>(b);
}
#[bench]
/// Benchmark intersecting 120,000 triangles using the recursive [`Bvh`].
fn bench_intersect_120k_triangles_bvh(b: &mut ::test::Bencher) {
intersect_120k_triangles_bh::<TBvh3>(b);
}
#[bench]
/// Benchmark the traversal of a [`Bvh`] with the Sponza scene.
fn bench_intersect_sponza_bvh(b: &mut ::test::Bencher) {
let (mut triangles, bounds) = load_sponza_scene();
let bvh = TBvh3::build(&mut triangles);
intersect_bh(&bvh, &triangles, &bounds, b)
}
}