From 5600d6c561b137385fca38ce9c629fa9c81634e5 Mon Sep 17 00:00:00 2001 From: Bill Thiede Date: Wed, 21 Jul 2021 13:17:25 -0700 Subject: [PATCH] shapes: name space helper implementations in a sub module. --- rtchallenge/src/shapes.rs | 61 +++++++++++++++++++++++++-------------- 1 file changed, 39 insertions(+), 22 deletions(-) diff --git a/rtchallenge/src/shapes.rs b/rtchallenge/src/shapes.rs index bf31b20..56d42db 100644 --- a/rtchallenge/src/shapes.rs +++ b/rtchallenge/src/shapes.rs @@ -266,32 +266,49 @@ impl Shape { /// ``` pub fn intersect<'s>(shape: &'s Shape, ray: &Ray) -> Intersections<'s> { match shape.geometry { - Geometry::Sphere => intersect_sphere(shape, ray), - Geometry::Plane => intersect_plane(shape, ray), + Geometry::Sphere => sphere::intersect(shape, ray), + Geometry::Plane => plane::intersect(shape, ray), } } -fn intersect_sphere<'s>(shape: &'s Shape, ray: &Ray) -> Intersections<'s> { - let ray = ray.transform(shape.inverse_transform); - let sphere_to_ray = ray.origin - Tuple::point(0., 0., 0.); - let a = dot(ray.direction, ray.direction); - let b = 2. * dot(ray.direction, sphere_to_ray); - let c = dot(sphere_to_ray, sphere_to_ray) - 1.; - let discriminant = b * b - 4. * a * c; - if discriminant < 0. { - return Intersections::default(); +mod sphere { + use crate::{ + intersections::{Intersection, Intersections}, + rays::Ray, + shapes::Shape, + tuples::{dot, Tuple}, + }; + pub fn intersect<'s>(shape: &'s Shape, ray: &Ray) -> Intersections<'s> { + let ray = ray.transform(shape.inverse_transform); + let sphere_to_ray = ray.origin - Tuple::point(0., 0., 0.); + let a = dot(ray.direction, ray.direction); + let b = 2. * dot(ray.direction, sphere_to_ray); + let c = dot(sphere_to_ray, sphere_to_ray) - 1.; + let discriminant = b * b - 4. * a * c; + if discriminant < 0. { + return Intersections::default(); + } + Intersections::new(vec![ + Intersection::new((-b - discriminant.sqrt()) / (2. * a), &shape), + Intersection::new((-b + discriminant.sqrt()) / (2. * a), &shape), + ]) } - Intersections::new(vec![ - Intersection::new((-b - discriminant.sqrt()) / (2. * a), &shape), - Intersection::new((-b + discriminant.sqrt()) / (2. * a), &shape), - ]) } -fn intersect_plane<'s>(shape: &'s Shape, ray: &Ray) -> Intersections<'s> { - if (ray.direction.y).abs() < EPSILON { - return Intersections::default(); + +mod plane { + use crate::{ + intersections::{Intersection, Intersections}, + rays::Ray, + shapes::Shape, + EPSILON, + }; + pub fn intersect<'s>(shape: &'s Shape, ray: &Ray) -> Intersections<'s> { + if (ray.direction.y).abs() < EPSILON { + return Intersections::default(); + } + Intersections::new(vec![Intersection::new( + -ray.origin.y / ray.direction.y, + &shape, + )]) } - Intersections::new(vec![Intersection::new( - -ray.origin.y / ray.direction.y, - &shape, - )]) }