diff --git a/csg/src/aabb.rs b/csg/src/aabb.rs new file mode 100644 index 0000000..ff4eca0 --- /dev/null +++ b/csg/src/aabb.rs @@ -0,0 +1,44 @@ +use glam::Vec3; + +#[derive(Default, Debug)] +pub struct Aabb { + pub min: Vec3, + pub max: Vec3, +} + +impl Aabb { + pub fn new() -> Self { + Self { + min: Vec3::ZERO, + max: Vec3::ZERO, + } + } + + pub fn from_min_max(min: Vec3, max: Vec3) -> Self { + Self { min, max } + } + + pub fn from_positions(positions: &[Vec3]) -> Self { + let mut min = positions[0]; + let mut max = min; + + for pos in positions { + min = min.min(*pos); + max = max.max(*pos); + } + + Self { min, max } + } + + pub fn intersects(&self, other: &Aabb) -> bool { + (self.min.x <= other.max.x && self.max.x >= other.min.x) + && (self.min.y <= other.max.y && self.max.y >= other.min.y) + && (self.min.z <= other.max.z && self.max.z >= other.min.z) + } + + pub fn contains(&self, other: &Aabb) -> bool { + (self.min.x <= other.min.x && self.max.x >= other.max.x) + && (self.min.y <= other.min.y && self.max.y >= other.max.y) + && (self.min.z <= other.min.z && self.max.z >= other.max.z) + } +} diff --git a/csg/src/brush.rs b/csg/src/brush.rs index e68e0f2..cc34a9f 100644 --- a/csg/src/brush.rs +++ b/csg/src/brush.rs @@ -1,6 +1,7 @@ use glam::Vec3; use crate::{ + aabb::Aabb, math, plane::{Plane, PlaneIntersection}, }; @@ -40,6 +41,7 @@ pub struct Brush { pub planes: Vec, raw_vertices: Vec, vertices: Vec, + aabb: Aabb, } impl Brush { @@ -48,6 +50,7 @@ impl Brush { planes: planes.to_vec(), raw_vertices: vec![], vertices: vec![], + aabb: Aabb::new(), } } @@ -58,6 +61,7 @@ impl Brush { self.calculate_raw_vertices(); self.merge_vertices(); + self.aabb = Aabb::from_positions(&self.vertices); } pub fn get_vertices(&self) -> Vec { @@ -68,6 +72,10 @@ impl Brush { self.raw_vertices.clone() } + pub fn get_aabb(&self) -> &Aabb { + &self.aabb + } + fn calculate_raw_vertices(&mut self) { // Test all permutations of brush planes for intersections let mut intersections = vec![]; diff --git a/csg/src/lib.rs b/csg/src/lib.rs index b34e55c..3425e0d 100644 --- a/csg/src/lib.rs +++ b/csg/src/lib.rs @@ -1,3 +1,4 @@ +mod aabb; pub mod brush; pub mod math; pub mod plane;