1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
//! Axis-aligned cuboid.

use nalgebra::{Point3, Unit, Vector3};
use std::cmp::Ordering;

use crate::rt::{Ray, Side};

/// Cuboid oriented along the Cartesian axes.
#[derive(Clone)]
pub struct Cube {
    /// Minimum bound.
    pub mins: Point3<f64>,
    /// Maximum bound.
    pub maxs: Point3<f64>,
}

impl Cube {
    /// Construct a new instance.
    #[inline]
    #[must_use]
    pub fn new(mins: Point3<f64>, maxs: Point3<f64>) -> Self {
        debug_assert!(mins < maxs);

        Self { mins, maxs }
    }

    /// Calculate the centre position.
    #[inline]
    #[must_use]
    pub fn centre(&self) -> Point3<f64> {
        nalgebra::center(&self.mins, &self.maxs)
    }

    /// Calculate the widths.
    #[inline]
    #[must_use]
    pub fn widths(&self) -> Vector3<f64> {
        self.maxs - self.mins
    }

    /// Calculate the half-widths.
    #[inline]
    #[must_use]
    pub fn half_widths(&self) -> Vector3<f64> {
        (self.maxs - self.mins) * 0.5
    }

    /// Calculate the surface area.
    #[inline]
    #[must_use]
    pub fn area(&self) -> f64 {
        let ws = self.widths();
        2.0 * ws.z.mul_add(ws.x, ws.x.mul_add(ws.y, ws.y * ws.z))
    }

    /// Calculate the volume.
    #[inline]
    #[must_use]
    pub fn vol(&self) -> f64 {
        let ws = self.widths();
        ws.x * ws.y * ws.z
    }

    /// Determine if the given point if contained with the volume.
    /// Points lying on the surface are contained contained.
    #[inline]
    #[must_use]
    pub fn contains(&self, p: &Point3<f64>) -> bool {
        p >= &self.mins && p <= &self.maxs
    }

    /// Shrink by a fraction of the side lengths.
    /// Central position is maintained.
    #[inline]
    pub fn shrink(&mut self, f: f64) {
        debug_assert!(f > 0.0);
        debug_assert!(f < 1.0);

        let delta = self.half_widths() * f;

        self.mins += delta;
        self.maxs -= delta;
    }

    /// Expand by a fraction of the side lengths.
    /// Central position is maintained.
    #[inline]
    pub fn expand(&mut self, f: f64) {
        debug_assert!(f > 0.0);

        let delta = self.half_widths() * f;

        self.mins -= delta;
        self.maxs += delta;
    }

    /// Check for an intersection with another Cube.
    #[inline]
    #[must_use]
    pub fn collides(&self, cube: &Self) -> bool {
        self.mins <= cube.maxs && self.maxs >= cube.mins
    }

    /// Determine the distances from a given Ray to the axial planes of a Cube's minimum and maximal bounds.
    #[inline]
    #[must_use]
    fn intersections(&self, ray: &Ray) -> (f64, f64) {
        let t_0: Vec<_> = self
            .mins
            .iter()
            .zip(ray.pos.iter().zip(ray.dir.iter()))
            .map(|(m, (p, d))| (m - p) / d)
            .collect();

        let t_1: Vec<_> = self
            .maxs
            .iter()
            .zip(ray.pos.iter().zip(ray.dir.iter()))
            .map(|(m, (p, d))| (m - p) / d)
            .collect();

        let t_min = t_0
            .iter()
            .zip(t_1.iter())
            .map(|(a, b)| a.min(*b))
            .max_by(|a, b| {
                if a < b {
                    Ordering::Less
                } else {
                    Ordering::Greater
                }
            })
            .expect("Failed to perform Ray-Cube intersection.");

        let t_max = t_0
            .iter()
            .zip(t_1.iter())
            .map(|(a, b)| a.max(*b))
            .min_by(|a, b| {
                if a < b {
                    Ordering::Less
                } else {
                    Ordering::Greater
                }
            })
            .expect("Failed to perform Ray-Cube intersection.");

        (t_min, t_max)
    }

    /// Determine if a Ray-Cube intersection occurs.
    #[inline]
    #[must_use]
    pub fn hit(&self, ray: &Ray) -> bool {
        let (t_min, t_max) = self.intersections(ray);

        !(t_max <= 0.0 || t_min > t_max)
    }

    /// Determine the distance to a Ray-Cube intersection.
    #[inline]
    #[must_use]
    pub fn dist(&self, ray: &Ray) -> Option<f64> {
        let (t_min, t_max) = self.intersections(ray);

        if t_max <= 0.0 || t_min > t_max {
            return None;
        }

        if t_min > 0.0 {
            return Some(t_min);
        }

        Some(t_max)
    }

    /// Determine the distance and facing side of a Ray-Cube intersection.
    #[inline]
    #[must_use]
    pub fn dist_side(&self, ray: &Ray) -> Option<(f64, Side)> {
        if let Some(dist) = self.dist(ray) {
            let hit = ray.pos + (dist * ray.dir.as_ref());
            let relative = hit - self.centre();

            let xy = relative.y / relative.x;
            let zy = relative.z / relative.y;

            let norm = Unit::new_normalize(if (-1.0..=1.0).contains(&xy) {
                Vector3::new(1.0_f64.copysign(relative.x), 0.0, 0.0)
            } else if (-1.0..=1.0).contains(&zy) {
                Vector3::new(0.0, 1.0_f64.copysign(relative.y), 0.0)
            } else {
                Vector3::new(0.0, 0.0, 1.0_f64.copysign(relative.z))
            });

            return Some((dist, Side::new(&ray.dir, norm)));
        }

        None
    }
}