From c4369f86c920888bfaa00e46d74e3f5a1872a9ab Mon Sep 17 00:00:00 2001 From: Julian T Date: Sun, 31 Jan 2021 17:21:11 +0100 Subject: Add Scene type and Sphere intersect --- src/scene/mod.rs | 5 +++-- src/scene/scene.rs | 38 ++++++++++++++++++++++++++++++++++++++ src/scene/shapes/mod.rs | 6 ++---- src/scene/shapes/sphere.rs | 37 +++++++++++++++++++++++++++++++++++++ 4 files changed, 80 insertions(+), 6 deletions(-) create mode 100644 src/scene/scene.rs (limited to 'src/scene') diff --git a/src/scene/mod.rs b/src/scene/mod.rs index 3482bb6..13c5e23 100644 --- a/src/scene/mod.rs +++ b/src/scene/mod.rs @@ -1,3 +1,4 @@ -mod shapes; - +pub mod shapes; +mod scene; +pub use scene::*; diff --git a/src/scene/scene.rs b/src/scene/scene.rs new file mode 100644 index 0000000..a2f5b88 --- /dev/null +++ b/src/scene/scene.rs @@ -0,0 +1,38 @@ +use super::shapes::Shape; +use crate::Float; +use crate::core::Ray; + +pub struct Scene { + shps: Vec>, +} + +pub struct Intersection<'a> { + pub shp: &'a dyn Shape, + pub t: Float, +} + +impl Scene { + pub fn new() -> Self { + Self { + shps: Vec::new(), + } + } + + pub fn add_shape(&mut self, shp: Box) { + self.shps.push(shp); + } + + pub fn intersect(&self, ray: Ray) -> Option { + for shp in self.shps.iter() { + if let Some(t) = shp.intersect(&ray) { + return Some(Intersection { + shp: shp.as_ref(), + t, + }) + } + } + + None + } +} + diff --git a/src/scene/shapes/mod.rs b/src/scene/shapes/mod.rs index 76fb6f2..7fbb8db 100644 --- a/src/scene/shapes/mod.rs +++ b/src/scene/shapes/mod.rs @@ -5,8 +5,6 @@ pub use sphere::Sphere; use crate::core::Ray; use crate::Float; -trait Shape { - // - fn intersect(ray: Ray) -> Float; - fn intersect_ +pub trait Shape { + fn intersect(&self, ray: &Ray) -> Option; } diff --git a/src/scene/shapes/sphere.rs b/src/scene/shapes/sphere.rs index 9598422..f8ae11e 100644 --- a/src/scene/shapes/sphere.rs +++ b/src/scene/shapes/sphere.rs @@ -1,5 +1,6 @@ use crate::Float; use crate::core::{Ray, Vector3f}; +use super::Shape; pub struct Sphere { radius: Float, @@ -14,3 +15,39 @@ impl Sphere { } } } + +impl Shape for Sphere { + // Implementation from ray tracing in a weekend + fn intersect(&self, ray: &Ray) -> Option { + let oc = ray.origin - self.center; + let a = ray.direction.len_squared(); + let half_b = oc.dot(&ray.direction); + let c = oc.len_squared() - self.radius * self.radius; + let disc = half_b*half_b - a*c; + + if disc < 0.0 { + None + } else { + Some( (-half_b - disc.sqrt()) / a) + } + + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sphere_intersect() { + let sph = Sphere::new(2.0, Vector3f::new_xyz(2.0, 3.0, 4.0)); + + let ray = Ray { + origin: Vector3f::new_xyz(1.0, 0.0, 0.0), + direction: Vector3f::new_xyz(0.0, 1.0, 1.5).norm(), + }; + + let dist = sph.intersect(&ray); + assert!((dist.unwrap() - 3.28).abs() < 0.01); + } +} -- cgit v1.2.3