Skip to main content

rayengine_core/spatial/
ray.rs

1//! Normalized rays and exact slab contacts with inclusive boundaries.
2
3use super::{SpatialError, valid_distance};
4use crate::collision::{Aabb2, Aabb3};
5use glam::{Vec2, Vec3};
6
7/// A 2D ray with a unit-length direction; distances are world units.
8#[derive(Clone, Copy, Debug, PartialEq)]
9pub struct Ray2 {
10    /// Ray origin in world coordinates.
11    pub(crate) origin: Vec2,
12    /// Unit-length direction.
13    pub(crate) direction: Vec2,
14}
15
16/// A 3D ray with a unit-length direction; distances are world units.
17#[derive(Clone, Copy, Debug, PartialEq)]
18pub struct Ray3 {
19    /// Ray origin in world coordinates.
20    pub(crate) origin: Vec3,
21    /// Unit-length direction.
22    pub(crate) direction: Vec3,
23}
24
25/// Contact on a 2D box. The normal points outward; strict inside starts have zero normal.
26#[derive(Clone, Copy, Debug, PartialEq)]
27pub struct RayHit2 {
28    /// World-unit distance along the normalized ray.
29    pub distance: f32,
30    /// World-space contact point.
31    pub point: Vec2,
32    /// Outward box-face normal, or zero for a strict inside start.
33    pub normal: Vec2,
34}
35
36/// Contact on a 3D box. The normal points outward; strict inside starts have zero normal.
37#[derive(Clone, Copy, Debug, PartialEq)]
38pub struct RayHit3 {
39    /// World-unit distance along the normalized ray.
40    pub distance: f32,
41    /// World-space contact point.
42    pub point: Vec3,
43    /// Outward box-face normal, or zero for a strict inside start.
44    pub normal: Vec3,
45}
46
47fn unit<const N: usize>(origin: [f32; N], direction: [f32; N]) -> Result<[f32; N], SpatialError> {
48    if !origin.iter().chain(direction.iter()).all(|v| v.is_finite()) {
49        return Err(SpatialError::InvalidRay);
50    }
51    let scale = direction
52        .iter()
53        .fold(0.0_f32, |largest, v| largest.max(v.abs()));
54    if scale == 0.0 {
55        return Err(SpatialError::InvalidRay);
56    }
57    // Scaling avoids overflow for large finite vectors and underflow for tiny
58    // nonzero vectors before normalization.
59    let scaled = direction.map(|v| v / scale);
60    let squared: f32 = scaled.iter().map(|v| v * v).sum();
61    let length = squared.sqrt();
62    Ok(scaled.map(|v| v / length))
63}
64
65/// Slab intersection. Axis order breaks exact corner ties deterministically.
66pub(crate) fn slab<const N: usize>(
67    origin: [f32; N],
68    direction: [f32; N],
69    min: [f32; N],
70    max: [f32; N],
71    limit: f32,
72) -> Option<(f32, [f32; N])> {
73    let mut enter = 0.0_f32;
74    let mut exit = limit;
75    let mut normal = [0.0; N];
76    for axis in 0..N {
77        let d = direction[axis];
78        if d == 0.0 {
79            if origin[axis] < min[axis] || origin[axis] > max[axis] {
80                return None;
81            }
82            continue;
83        }
84        let (near, far, side) = if d > 0.0 {
85            (
86                (min[axis] - origin[axis]) / d,
87                (max[axis] - origin[axis]) / d,
88                -1.0,
89            )
90        } else {
91            (
92                (max[axis] - origin[axis]) / d,
93                (min[axis] - origin[axis]) / d,
94                1.0,
95            )
96        };
97        if near >= 0.0 && near >= enter {
98            enter = near;
99            normal = [0.0; N];
100            normal[axis] = side;
101        }
102        exit = exit.min(far);
103        if enter > exit {
104            return None;
105        }
106    }
107    if enter.is_finite() && exit >= 0.0 {
108        Some((enter, normal))
109    } else {
110        None
111    }
112}
113
114macro_rules! ray_impl {
115    ($ray:ident, $hit:ident, $vec:ident, $box:ident, $n:expr) => {
116        impl $ray {
117            /// Ray origin in world coordinates.
118            pub fn origin(self) -> $vec {
119                self.origin
120            }
121
122            /// Unit-length ray direction.
123            pub fn direction(self) -> $vec {
124                self.direction
125            }
126
127            /// Constructs a ray, normalizing its finite, nonzero direction.
128            pub fn new(origin: $vec, direction: $vec) -> Result<Self, SpatialError> {
129                let direction =
130                    <$vec>::from_array(unit::<$n>(origin.to_array(), direction.to_array())?);
131                Ok(Self { origin, direction })
132            }
133
134            /// World-space position at a distance along the ray.
135            pub fn at(self, distance: f32) -> $vec {
136                self.origin + self.direction * distance
137            }
138
139            /// First box contact, inclusive of faces and `max_distance`.
140            ///
141            /// Strict inside starts return distance zero and a zero normal.
142            /// A boundary start reports zero distance; an outward start uses
143            /// zero normal, while an inward start reports that face's normal.
144            /// `f32::INFINITY` is accepted for an unbounded search.
145            pub fn cast(
146                self,
147                bounds: $box,
148                max_distance: f32,
149            ) -> Result<Option<$hit>, SpatialError> {
150                valid_distance(max_distance)?;
151                if !bounds.min.is_finite()
152                    || !bounds.max.is_finite()
153                    || !bounds.min.cmple(bounds.max).all()
154                {
155                    return Err(SpatialError::InvalidBounds(0));
156                }
157                Ok(slab::<$n>(
158                    self.origin.to_array(),
159                    self.direction.to_array(),
160                    bounds.min.to_array(),
161                    bounds.max.to_array(),
162                    max_distance,
163                )
164                .map(|(distance, normal)| $hit {
165                    distance,
166                    point: self.at(distance),
167                    normal: <$vec>::from_array(normal),
168                }))
169            }
170        }
171    };
172}
173
174ray_impl!(Ray2, RayHit2, Vec2, Aabb2, 2);
175ray_impl!(Ray3, RayHit3, Vec3, Aabb3, 3);