Files
vxls/src/bvh/aabb.rs
T
2026-11-12 15:51:33 +01:00

469 lines
12 KiB
Rust

//! Axis aligned bounding box used by the BVH build.
use glam::Mat4;
use glam::Vec3;
/// An axis aligned bounding box.
///
/// A box is empty when `min` is greater than `max` on any axis. [`Aabb::EMPTY`]
/// uses inverted infinities, which makes it the identity element for
/// [`Aabb::union`] and [`Aabb::union_point`].
#[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
#[repr(C)]
pub struct Aabb
{
min: Vec3,
max: Vec3,
}
impl Aabb
{
/// The empty box: it contains no point and is the identity element for
/// union operations.
pub const EMPTY: Self = Self {
min: Vec3::INFINITY,
max: Vec3::NEG_INFINITY,
};
/// The local voxel chunk space is [0,1]^3.
/// This is the box that encompasses that block.
pub const CHUNK: Self = Self {
min: Vec3::ZERO,
max: Vec3::ONE,
};
/// Builds a box from its corners.
///
/// No validation is performed so that [`Aabb::EMPTY`] can be built; use
/// [`Aabb::is_empty`] to check the result.
pub const fn new(min: Vec3, max: Vec3) -> Self
{
Self { min, max }
}
/// Builds a box from a center and the half extents along each axis.
pub fn from_center_half_extents(center: Vec3, half_extents: Vec3) -> Self
{
Self {
min: center - half_extents,
max: center + half_extents,
}
}
/// Builds the tightest box containing every point.
///
/// An empty iterator produces [`Aabb::EMPTY`].
pub fn from_points(points: impl IntoIterator<Item = Vec3>) -> Self
{
let mut aabb = Self::EMPTY;
for point in points
{
aabb.union_point(point);
}
aabb
}
pub const fn min(&self) -> Vec3
{
self.min
}
pub const fn max(&self) -> Vec3
{
self.max
}
/// Center of the box. Not meaningful for an empty box.
pub fn center(&self) -> Vec3
{
(self.min + self.max) * 0.5
}
/// Full extent of the box along each axis (`max - min`).
pub fn size(&self) -> Vec3
{
self.max - self.min
}
/// Half extent of the box along each axis.
pub fn half_size(&self) -> Vec3
{
self.size() * 0.5
}
/// Surface area of the box, used by SAH heuristics.
pub fn surface_area(&self) -> f32
{
let size = self.size();
2.0 * (size.x * size.y + size.y * size.z + size.z * size.x)
}
pub fn volume(&self) -> f32
{
self.size().element_product()
}
/// Index of the axis with the largest extent (0 = x, 1 = y, 2 = z).
///
/// Ties are broken in favor of the lower axis.
pub fn longest_axis(&self) -> usize
{
let size = self.size();
if size.x >= size.y && size.x >= size.z
{
0
}
else if size.y >= size.z
{
1
}
else
{
2
}
}
/// Returns `true` when the box contains no point.
pub fn is_empty(&self) -> bool
{
self.min.x > self.max.x || self.min.y > self.max.y || self.min.z > self.max.z
}
/// Returns `true` when both corners are finite.
pub fn is_finite(&self) -> bool
{
self.min.is_finite() && self.max.is_finite()
}
pub fn contains_point(&self, point: Vec3) -> bool
{
point.cmpge(self.min).all() && point.cmple(self.max).all()
}
/// Returns `true` when `other` is fully inside `self`.
///
/// An empty `other` is contained in every box.
pub fn contains(&self, other: &Self) -> bool
{
other.is_empty() || (self.min.cmple(other.min).all() && self.max.cmpge(other.max).all())
}
/// Returns `true` when both boxes share at least one point.
///
/// Boxes touching exactly on a face, edge or corner do intersect.
pub fn intersects(&self, other: &Self) -> bool
{
!self.is_empty()
&& !other.is_empty()
&& self.min.cmple(other.max).all()
&& other.min.cmple(self.max).all()
}
/// Overlap of both boxes.
///
/// The result is empty when the boxes do not intersect.
pub fn intersection(&self, other: &Self) -> Self
{
Self {
min: self.min.max(other.min),
max: self.max.min(other.max),
}
}
/// Grows the box to contain `point`.
pub fn union_point(&mut self, point: Vec3)
{
self.min = self.min.min(point);
self.max = self.max.max(point);
}
/// Grows the box to contain `other`.
pub fn union(&mut self, other: &Self)
{
self.min = self.min.min(other.min);
self.max = self.max.max(other.max);
}
/// Returns a copy of the box grown by `margin` on every side.
pub fn expanded(&self, margin: f32) -> Self
{
let margin = Vec3::splat(margin);
Self {
min: self.min - margin,
max: self.max + margin,
}
}
/// Returns a copy of the box with every axis at least `min_size` long,
/// keeping the center unchanged.
///
/// This avoids degenerate (flat) boxes, which are problematic for SAH
/// splitting. An empty box is returned unchanged.
pub fn padded_to_min_size(&self, min_size: f32) -> Self
{
if self.is_empty()
{
return Self::EMPTY;
}
let half_extents = self.half_size().max(Vec3::splat(min_size * 0.5));
Self::from_center_half_extents(self.center(), half_extents)
}
/// Returns an iterator over all of the corner points of the box
pub fn corner_points(&self) -> impl Iterator<Item = Vec3>
{
(0..=7).map(|i| {
let a = &self.min;
let b = &self.max;
Vec3::new(
if i & 1 == 0 { a.x } else { b.x },
if i & 2 == 0 { a.y } else { b.y },
if i & 4 == 0 { a.z } else { b.z },
)
})
}
/// Returns the Aabb bounding box of the box transformed by `transformed`
pub fn as_transformed_by(&self, transform: &Mat4) -> Self
{
Self::from_points(
self.corner_points()
.map(|point| transform.transform_point3(point)),
)
}
}
impl Default for Aabb
{
fn default() -> Self
{
Self::EMPTY
}
}
#[cfg(test)]
mod tests
{
use super::*;
const EPSILON: f32 = 1e-6;
fn assert_vec3_eq(a: Vec3, b: Vec3)
{
assert!(
(a - b).abs().max_element() <= EPSILON,
"expected {b:?}, got {a:?}"
);
}
#[test]
fn empty_box_contains_nothing()
{
let aabb = Aabb::EMPTY;
assert!(aabb.is_empty());
assert!(!aabb.contains_point(Vec3::ZERO));
assert!(!aabb.intersects(&Aabb::new(Vec3::ZERO, Vec3::ONE)));
}
#[test]
fn empty_is_identity_for_union()
{
let aabb = Aabb::new(Vec3::ZERO, Vec3::ONE);
let mut grown = Aabb::EMPTY;
grown.union(&aabb);
assert_eq!(grown, aabb);
let mut grown = aabb;
grown.union(&Aabb::EMPTY);
assert_eq!(grown, aabb);
}
#[test]
fn from_points_of_empty_iterator_is_empty()
{
assert!(Aabb::from_points(std::iter::empty()).is_empty());
}
#[test]
fn from_points_bounds_all_points()
{
let points = [
Vec3::new(1.0, -2.0, 3.0),
Vec3::new(-4.0, 5.0, -6.0),
Vec3::new(0.0, 0.0, 0.0),
];
let aabb = Aabb::from_points(points);
assert_eq!(aabb.min(), Vec3::new(-4.0, -2.0, -6.0));
assert_eq!(aabb.max(), Vec3::new(1.0, 5.0, 3.0));
for point in points
{
assert!(aabb.contains_point(point));
}
}
#[test]
fn center_and_size()
{
let aabb = Aabb::new(Vec3::new(-1.0, 0.0, 2.0), Vec3::new(3.0, 4.0, 6.0));
assert_vec3_eq(aabb.center(), Vec3::new(1.0, 2.0, 4.0));
assert_vec3_eq(aabb.size(), Vec3::new(4.0, 4.0, 4.0));
assert_vec3_eq(aabb.half_size(), Vec3::new(2.0, 2.0, 2.0));
}
#[test]
fn from_center_half_extents_round_trips()
{
let aabb = Aabb::from_center_half_extents(Vec3::new(1.0, 2.0, 3.0), Vec3::splat(2.0));
assert_eq!(aabb.min(), Vec3::new(-1.0, 0.0, 1.0));
assert_eq!(aabb.max(), Vec3::new(3.0, 4.0, 5.0));
}
#[test]
fn union_grows_to_contain_both_boxes()
{
let a = Aabb::new(Vec3::ZERO, Vec3::ONE);
let b = Aabb::new(Vec3::splat(2.0), Vec3::splat(4.0));
let mut union = a;
union.union(&b);
assert_eq!(union.min(), Vec3::ZERO);
assert_eq!(union.max(), Vec3::splat(4.0));
assert!(union.contains(&a));
assert!(union.contains(&b));
}
#[test]
fn contains_point_respects_faces()
{
let aabb = Aabb::new(Vec3::ZERO, Vec3::ONE);
assert!(aabb.contains_point(Vec3::ZERO));
assert!(aabb.contains_point(Vec3::ONE));
assert!(aabb.contains_point(Vec3::splat(0.5)));
assert!(!aabb.contains_point(Vec3::splat(-EPSILON)));
assert!(!aabb.contains_point(Vec3::splat(1.0 + EPSILON)));
}
#[test]
fn contains_box()
{
let outer = Aabb::new(Vec3::ZERO, Vec3::splat(4.0));
let inner = Aabb::new(Vec3::ONE, Vec3::splat(3.0));
assert!(outer.contains(&inner));
assert!(!inner.contains(&outer));
assert!(outer.contains(&Aabb::EMPTY));
}
#[test]
fn separated_boxes_do_not_intersect()
{
let a = Aabb::new(Vec3::ZERO, Vec3::ONE);
let b = Aabb::new(Vec3::new(2.0, 0.0, 0.0), Vec3::new(3.0, 1.0, 1.0));
assert!(!a.intersects(&b));
assert!(!b.intersects(&a));
assert!(a.intersection(&b).is_empty());
}
#[test]
fn touching_boxes_intersect()
{
let a = Aabb::new(Vec3::ZERO, Vec3::ONE);
let b = Aabb::new(Vec3::new(1.0, 0.0, 0.0), Vec3::new(2.0, 1.0, 1.0));
assert!(a.intersects(&b));
assert_eq!(a.intersection(&b).size(), Vec3::new(0.0, 1.0, 1.0));
}
#[test]
fn overlapping_boxes_intersect()
{
let a = Aabb::new(Vec3::ZERO, Vec3::splat(2.0));
let b = Aabb::new(Vec3::ONE, Vec3::splat(3.0));
assert!(a.intersects(&b));
let intersection = a.intersection(&b);
assert_eq!(intersection.min(), Vec3::ONE);
assert_eq!(intersection.max(), Vec3::splat(2.0));
}
#[test]
fn surface_area_and_volume()
{
let aabb = Aabb::new(Vec3::ZERO, Vec3::new(2.0, 3.0, 4.0));
assert!((aabb.volume() - 24.0).abs() <= EPSILON);
assert!((aabb.surface_area() - 52.0).abs() <= EPSILON);
}
#[test]
fn longest_axis_picks_largest_extent()
{
assert_eq!(
Aabb::new(Vec3::ZERO, Vec3::new(3.0, 1.0, 2.0)).longest_axis(),
0
);
assert_eq!(
Aabb::new(Vec3::ZERO, Vec3::new(1.0, 3.0, 2.0)).longest_axis(),
1
);
assert_eq!(
Aabb::new(Vec3::ZERO, Vec3::new(1.0, 2.0, 3.0)).longest_axis(),
2
);
}
#[test]
fn expanded_adds_margin_on_every_side()
{
let aabb = Aabb::new(Vec3::ZERO, Vec3::ONE).expanded(0.5);
assert_eq!(aabb.min(), Vec3::splat(-0.5));
assert_eq!(aabb.max(), Vec3::splat(1.5));
assert!(aabb.contains(&Aabb::new(Vec3::ZERO, Vec3::ONE)));
}
#[test]
fn padded_to_min_size_keeps_flat_box_usable()
{
let flat = Aabb::new(Vec3::new(0.0, 0.0, 5.0), Vec3::new(2.0, 2.0, 5.0));
let padded = flat.padded_to_min_size(1.0);
assert!(!padded.is_empty());
assert!((padded.size().z - 1.0).abs() <= EPSILON);
assert_eq!(padded.size().x, 2.0);
assert_eq!(padded.size().y, 2.0);
assert_vec3_eq(padded.center(), flat.center());
assert!(padded.contains(&flat));
}
#[test]
fn padded_empty_box_stays_empty()
{
assert!(Aabb::EMPTY.padded_to_min_size(1.0).is_empty());
}
#[test]
fn default_is_empty()
{
assert_eq!(Aabb::default(), Aabb::EMPTY);
assert!(Aabb::default().is_empty());
}
#[test]
fn layout_is_two_vec3s()
{
assert_eq!(std::mem::size_of::<Aabb>(), 24);
assert_eq!(bytemuck::bytes_of(&Aabb::EMPTY).len(), 24);
}
}