1use std::ops::{Add, Mul};
2
3use crate::{Max, Min, Ray3, Real, Vector3, Zero};
4
5#[derive(Debug, Clone)]
7pub struct AABB3<T> {
8 pub min: Vector3<T>,
9 pub max: Vector3<T>,
10}
11impl<T> AABB3<T> {
12 #[inline(always)]
13 pub fn scale(&self, scale: &Vector3<T>) -> Self
14 where
15 T: Copy + Mul<T, Output = T>,
16 {
17 Self {
18 min: Vector3(
19 self.min.0 * scale.0,
20 self.min.1 * scale.1,
21 self.min.2 * scale.2,
22 ),
23 max: Vector3(
24 self.max.0 * scale.0,
25 self.max.1 * scale.1,
26 self.max.2 * scale.2,
27 ),
28 }
29 }
30
31 #[inline(always)]
32 pub fn translate(&self, offset: &Vector3<T>) -> Self
33 where
34 T: Copy + Add<T, Output = T>,
35 {
36 Self {
37 min: self.min + offset.clone(),
38 max: self.max + offset.clone(),
39 }
40 }
41
42 pub fn intersect(&self, ray: &Ray3<T>) -> Option<core::range::Range<T>>
43 where
44 T: Copy + Real + Min<Output = T> + Max<Output = T>,
45 {
46 let tx0 = (self.min.0 - ray.origin.0) / ray.direction.0;
47 let tx1 = (self.max.0 - ray.origin.0) / ray.direction.0;
48 let ty0 = (self.min.1 - ray.origin.1) / ray.direction.1;
49 let ty1 = (self.max.1 - ray.origin.1) / ray.direction.1;
50 let tz0 = (self.min.2 - ray.origin.2) / ray.direction.2;
51 let tz1 = (self.max.2 - ray.origin.2) / ray.direction.2;
52
53 let (tx0, tx1) = (tx0.min(tx1), tx0.max(tx1));
54 let (ty0, ty1) = (ty0.min(ty1), ty0.max(ty1));
55 let (tz0, tz1) = (tz0.min(tz1), tz0.max(tz1));
56 let t0 = tx0.max(ty0).max(tz0);
57 let t1 = tx1.min(ty1).min(tz1);
58
59 if t0 < t1 {
60 Some((t0..t1).into())
61 } else {
62 None
63 }
64 }
65}
66
67#[derive(Debug, Clone)]
69pub struct Sphere3<T> {
70 pub center: Vector3<T>,
71 pub radius: T,
72}
73impl<T> Sphere3<T> {
74 #[inline(always)]
75 pub fn scale(&self, scale: T) -> Self
76 where
77 T: Copy + Mul<T, Output = T>,
78 {
79 Self {
80 center: self.center.clone(),
81 radius: self.radius * scale,
82 }
83 }
84
85 #[inline(always)]
86 pub fn translate(&self, offset: &Vector3<T>) -> Self
87 where
88 T: Copy + Add<T, Output = T>,
89 {
90 Self {
91 center: self.center + offset.clone(),
92 radius: self.radius,
93 }
94 }
95
96 pub fn intersect(&self, ray: &Ray3<T>) -> Option<core::range::Range<T>>
97 where
98 T: Copy + Real + Zero,
99 {
100 let l = self.center - ray.origin;
101 let t_center = l.dot(ray.direction);
102 let d2 = (self.center - ray.point(t_center)).len2();
103 let t_bounds2 = self.radius * self.radius - d2;
104 if t_bounds2 < T::ZERO {
105 return None;
107 }
108
109 let t_bounds = t_bounds2.sqrt();
110 Some(((t_center - t_bounds)..(t_center + t_bounds)).into())
111 }
112}