From 75611d47d31a9a17fb5c02809641d7a94345cf75 Mon Sep 17 00:00:00 2001 From: Matthew Gordon Date: Fri, 10 Jan 2020 17:15:35 -0500 Subject: [PATCH] Add HasBoundingBox trait with implementation for Sphere --- src/raycasting/mod.rs | 4 ++++ src/raycasting/sphere.rs | 27 ++++++++++++++++++++++++--- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/src/raycasting/mod.rs b/src/raycasting/mod.rs index 36ecb3a..4dac05d 100644 --- a/src/raycasting/mod.rs +++ b/src/raycasting/mod.rs @@ -60,6 +60,10 @@ pub trait IntersectP: Send + Sync { fn intersect(&self, ray: &Ray) -> bool; } +pub trait HasBoundingBox: Send + Sync { + fn bounding_box(&self) -> BoundingBox; +} + #[cfg(test)] mod tests { use quickcheck_macros::quickcheck; diff --git a/src/raycasting/sphere.rs b/src/raycasting/sphere.rs index 6effcf7..1872923 100644 --- a/src/raycasting/sphere.rs +++ b/src/raycasting/sphere.rs @@ -2,7 +2,7 @@ use nalgebra::{convert, Point3, RealField, Vector3}; use crate::materials::Material; -use super::{Intersect, IntersectionInfo, Ray}; +use super::{BoundingBox, HasBoundingBox, Intersect, IntersectionInfo, Ray}; use std::sync::Arc; @@ -77,11 +77,18 @@ impl Intersect for Sphere { } } +impl HasBoundingBox for Sphere { + fn bounding_box(&self) -> BoundingBox { + let radius_xyz = Vector3::new(self.radius, self.radius, self.radius); + BoundingBox::from_corners(self.centre + radius_xyz, self.centre - radius_xyz) + } +} + #[cfg(test)] mod tests { - use quickcheck_macros::quickcheck; use quickcheck::TestResult; - + use quickcheck_macros::quickcheck; + use super::*; use crate::materials::LambertianMaterial; @@ -158,4 +165,18 @@ mod tests { (distance_to_centre - (info.distance + sphere.radius)).abs() < 0.00001, ) } + + #[quickcheck] + fn all_points_on_sphere_are_in_bounding_box( + sphere_centre: Point3, + radius_vector: Vector3, + ) -> bool { + let target_sphere = Sphere::new( + sphere_centre, + radius_vector.norm(), + Arc::new(LambertianMaterial::new_dummy()), + ); + let bounding_box = target_sphere.bounding_box(); + bounding_box.contains_point(sphere_centre + radius_vector) + } }