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
use crate::{
    primitives::{Direction2d, Direction3d, Plane2d, Plane3d},
    Vec2, Vec3,
};

/// An infinite half-line starting at `origin` and going in `direction` in 2D space.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
pub struct Ray2d {
    /// The origin of the ray.
    pub origin: Vec2,
    /// The direction of the ray.
    pub direction: Direction2d,
}

impl Ray2d {
    /// Create a new `Ray2d` from a given origin and direction
    ///
    /// # Panics
    ///
    /// Panics if the given `direction` is zero (or very close to zero), or non-finite.
    #[inline]
    pub fn new(origin: Vec2, direction: Vec2) -> Self {
        Self {
            origin,
            direction: Direction2d::new(direction)
                .expect("ray direction must be nonzero and finite"),
        }
    }

    /// Get a point at a given distance along the ray
    #[inline]
    pub fn get_point(&self, distance: f32) -> Vec2 {
        self.origin + *self.direction * distance
    }

    /// Get the distance to a plane if the ray intersects it
    #[inline]
    pub fn intersect_plane(&self, plane_origin: Vec2, plane: Plane2d) -> Option<f32> {
        let denominator = plane.normal.dot(*self.direction);
        if denominator.abs() > f32::EPSILON {
            let distance = (plane_origin - self.origin).dot(*plane.normal) / denominator;
            if distance > f32::EPSILON {
                return Some(distance);
            }
        }
        None
    }
}

/// An infinite half-line starting at `origin` and going in `direction` in 3D space.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
pub struct Ray3d {
    /// The origin of the ray.
    pub origin: Vec3,
    /// The direction of the ray.
    pub direction: Direction3d,
}

impl Ray3d {
    /// Create a new `Ray3d` from a given origin and direction
    ///
    /// # Panics
    ///
    /// Panics if the given `direction` is zero (or very close to zero), or non-finite.
    #[inline]
    pub fn new(origin: Vec3, direction: Vec3) -> Self {
        Self {
            origin,
            direction: Direction3d::new(direction)
                .expect("ray direction must be nonzero and finite"),
        }
    }

    /// Get a point at a given distance along the ray
    #[inline]
    pub fn get_point(&self, distance: f32) -> Vec3 {
        self.origin + *self.direction * distance
    }

    /// Get the distance to a plane if the ray intersects it
    #[inline]
    pub fn intersect_plane(&self, plane_origin: Vec3, plane: Plane3d) -> Option<f32> {
        let denominator = plane.normal.dot(*self.direction);
        if denominator.abs() > f32::EPSILON {
            let distance = (plane_origin - self.origin).dot(*plane.normal) / denominator;
            if distance > f32::EPSILON {
                return Some(distance);
            }
        }
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn intersect_plane_2d() {
        let ray = Ray2d::new(Vec2::ZERO, Vec2::Y);

        // Orthogonal, and test that an inverse plane_normal has the same result
        assert_eq!(
            ray.intersect_plane(Vec2::Y, Plane2d::new(Vec2::Y)),
            Some(1.0)
        );
        assert_eq!(
            ray.intersect_plane(Vec2::Y, Plane2d::new(Vec2::NEG_Y)),
            Some(1.0)
        );
        assert!(ray
            .intersect_plane(Vec2::NEG_Y, Plane2d::new(Vec2::Y))
            .is_none());
        assert!(ray
            .intersect_plane(Vec2::NEG_Y, Plane2d::new(Vec2::NEG_Y))
            .is_none());

        // Diagonal
        assert_eq!(
            ray.intersect_plane(Vec2::Y, Plane2d::new(Vec2::ONE)),
            Some(1.0)
        );
        assert!(ray
            .intersect_plane(Vec2::NEG_Y, Plane2d::new(Vec2::ONE))
            .is_none());

        // Parallel
        assert!(ray
            .intersect_plane(Vec2::X, Plane2d::new(Vec2::X))
            .is_none());

        // Parallel with simulated rounding error
        assert!(ray
            .intersect_plane(Vec2::X, Plane2d::new(Vec2::X + Vec2::Y * f32::EPSILON))
            .is_none());
    }

    #[test]
    fn intersect_plane_3d() {
        let ray = Ray3d::new(Vec3::ZERO, Vec3::Z);

        // Orthogonal, and test that an inverse plane_normal has the same result
        assert_eq!(
            ray.intersect_plane(Vec3::Z, Plane3d::new(Vec3::Z)),
            Some(1.0)
        );
        assert_eq!(
            ray.intersect_plane(Vec3::Z, Plane3d::new(Vec3::NEG_Z)),
            Some(1.0)
        );
        assert!(ray
            .intersect_plane(Vec3::NEG_Z, Plane3d::new(Vec3::Z))
            .is_none());
        assert!(ray
            .intersect_plane(Vec3::NEG_Z, Plane3d::new(Vec3::NEG_Z))
            .is_none());

        // Diagonal
        assert_eq!(
            ray.intersect_plane(Vec3::Z, Plane3d::new(Vec3::ONE)),
            Some(1.0)
        );
        assert!(ray
            .intersect_plane(Vec3::NEG_Z, Plane3d::new(Vec3::ONE))
            .is_none());

        // Parallel
        assert!(ray
            .intersect_plane(Vec3::X, Plane3d::new(Vec3::X))
            .is_none());

        // Parallel with simulated rounding error
        assert!(ray
            .intersect_plane(Vec3::X, Plane3d::new(Vec3::X + Vec3::Z * f32::EPSILON))
            .is_none());
    }
}