From 248a634ecb66a984ede5b02ec10ff91d816eebba Mon Sep 17 00:00:00 2001 From: Vijfhoek Date: Sun, 30 May 2021 03:52:16 +0200 Subject: [PATCH] Add (yet) unused AABB implementation --- src/aabb.rs | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/aabb.rs diff --git a/src/aabb.rs b/src/aabb.rs new file mode 100644 index 0000000..c7589db --- /dev/null +++ b/src/aabb.rs @@ -0,0 +1,49 @@ +use cgmath::Vector3; +use std::ops::{Div, Sub}; + +pub struct Aabb { + pub min: Vector3, + pub max: Vector3, +} + +impl + Div> Aabb { + pub fn intersects_ray( + &self, + ray_origin: Vector3, + ray_direction: Vector3, + ) -> Option<(T, T)> { + let mut t_min = (self.min.x - ray_origin.x) / ray_direction.x; + let mut t_max = (self.max.x - ray_origin.x) / ray_direction.x; + if t_min > t_max { + std::mem::swap(&mut t_min, &mut t_max); + } + + let mut ty_min = (self.min.y - ray_origin.y) / ray_direction.y; + let mut ty_max = (self.max.y - ray_origin.y) / ray_direction.y; + if ty_min > ty_max { + std::mem::swap(&mut ty_min, &mut ty_max); + } + + if t_min > ty_max || ty_min > t_max { + return None; + } + + t_min = T::max(t_min, ty_min); + t_max = T::min(t_min, ty_max); + + let mut tz_min = (self.min.z - ray_origin.z) / ray_direction.z; + let mut tz_max = (self.max.z - ray_origin.z) / ray_direction.z; + if tz_min > tz_max { + std::mem::swap(&mut tz_min, &mut tz_max); + } + + if t_min > tz_max || tz_min > t_max { + return None; + } + + t_min = T::max(t_min, tz_min); + t_max = T::max(t_max, tz_max); + + Some((t_min, t_max)) + } +}