Skip to main content

brepkit_math/
frame.rs

1//! Orthonormal reference frame in 3D space.
2//!
3//! [`Frame3`] bundles an origin with three mutually perpendicular unit axes.
4//! It replaces the 14+ hand-rolled "pick a candidate, cross twice" patterns
5//! scattered across surfaces, curves, and intersection code.
6
7use crate::MathError;
8use crate::vec::{Point3, Vec3};
9
10/// An orthonormal reference frame: origin + three mutually perpendicular unit
11/// axes (`x`, `y`, `z`).
12///
13/// The `z` axis is the *primary* direction (surface normal, curve axis, etc.).
14/// `x` and `y` span the plane perpendicular to `z`.
15#[derive(Debug, Clone, Copy, PartialEq)]
16pub struct Frame3 {
17    /// Frame origin.
18    pub origin: Point3,
19    /// First axis in the perpendicular plane.
20    pub x: Vec3,
21    /// Second axis in the perpendicular plane.
22    pub y: Vec3,
23    /// Primary axis / normal.
24    pub z: Vec3,
25}
26
27impl Frame3 {
28    /// Build an orthonormal frame from an origin and a primary axis (normal).
29    ///
30    /// `x` and `y` are chosen arbitrarily in the plane perpendicular to `z`.
31    /// The input `normal` is normalized internally.
32    ///
33    /// # Errors
34    ///
35    /// Returns [`MathError::ZeroVector`] if `normal` is zero-length.
36    pub fn from_normal(origin: Point3, normal: Vec3) -> Result<Self, MathError> {
37        let z = normal.normalize()?;
38        let (x, y) = perpendicular_pair(z)?;
39        Ok(Self { origin, x, y, z })
40    }
41
42    /// Build an orthonormal frame from an origin, a primary axis, and a
43    /// preferred reference direction for `x`.
44    ///
45    /// `ref_dir` is projected onto the plane perpendicular to `z` to produce
46    /// `x`. If `ref_dir` is (nearly) parallel to `z`, the frame falls back to
47    /// an arbitrary perpendicular choice.
48    ///
49    /// # Errors
50    ///
51    /// Returns [`MathError::ZeroVector`] if `normal` is zero-length.
52    pub fn from_normal_and_ref(
53        origin: Point3,
54        normal: Vec3,
55        ref_dir: Vec3,
56    ) -> Result<Self, MathError> {
57        let z = normal.normalize()?;
58        let x = if let Ok(v) = ref_dir.square_part(z) {
59            v
60        } else {
61            // ref_dir is parallel to z — fall back to arbitrary choice.
62            let (arb_x, _) = perpendicular_pair(z)?;
63            arb_x
64        };
65        let y = z.cross(x);
66        Ok(Self { origin, x, y, z })
67    }
68}
69
70/// Given a unit vector `z`, return two unit vectors `(x, y)` forming an
71/// orthonormal basis where `x = z × candidate` and `y = z × x`.
72fn perpendicular_pair(z: Vec3) -> Result<(Vec3, Vec3), MathError> {
73    let candidate = if z.x().abs() < 0.9 {
74        Vec3::new(1.0, 0.0, 0.0)
75    } else {
76        Vec3::new(0.0, 1.0, 0.0)
77    };
78    let x = z.cross(candidate).normalize()?;
79    let y = z.cross(x);
80    Ok((x, y))
81}
82
83#[cfg(test)]
84#[allow(clippy::unwrap_used, clippy::expect_used)]
85mod tests {
86    use super::*;
87    use proptest::prelude::*;
88
89    #[test]
90    fn frame_from_z_axis() {
91        let f = Frame3::from_normal(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 5.0))
92            .expect("non-zero");
93        assert!((f.z.z() - 1.0).abs() < 1e-14);
94        assert!(f.x.dot(f.y).abs() < 1e-14);
95        assert!(f.x.dot(f.z).abs() < 1e-14);
96        assert!(f.y.dot(f.z).abs() < 1e-14);
97    }
98
99    /// A reference along the normal, at any size, has no part square to it
100    /// but rounding: the frame takes its fallback axes, square to each other
101    /// and to the normal, as it does for a reference of size 1.
102    #[test]
103    fn a_reference_along_the_normal_at_any_size_takes_the_fallback_axes() {
104        let normal = Vec3::new(1.0, 1.0, 1.0);
105        for s in [1.0, 1e-200, 1e200, 3.0] {
106            let f =
107                Frame3::from_normal_and_ref(Point3::new(0.0, 0.0, 0.0), normal, Vec3::new(s, s, s))
108                    .unwrap();
109            for (a, b) in [(f.x, f.y), (f.x, f.z), (f.y, f.z)] {
110                assert!(a.dot(b).abs() < 1e-12, "size {s}: {f:?}");
111            }
112            for axis in [f.x, f.y, f.z] {
113                assert!((axis.length() - 1.0).abs() < 1e-12, "size {s}: {f:?}");
114            }
115        }
116    }
117
118    /// A reference 1e-10 off the normal, at size 1e-200, gives a frame
119    /// whose axes are square to each other to 8 units of rounding.
120    #[test]
121    fn a_reference_just_off_the_normal_gives_square_axes() {
122        let f = Frame3::from_normal_and_ref(
123            Point3::new(0.0, 0.0, 0.0),
124            Vec3::new(1.0, 1.0, 1.0),
125            Vec3::new(1e-200, 1e-200, 1e-200 * (1.0 + 1e-10)),
126        )
127        .unwrap();
128        for (a, b) in [(f.x, f.y), (f.x, f.z), (f.y, f.z)] {
129            assert!(a.dot(b).abs() <= 8.0 * f64::EPSILON, "{f:?}");
130        }
131    }
132
133    #[test]
134    fn frame_from_x_axis() {
135        // Tests the branch where x_component > 0.9
136        let f = Frame3::from_normal(Point3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0))
137            .expect("non-zero");
138        assert!((f.z.x() - 1.0).abs() < 1e-14);
139        assert!(f.x.dot(f.z).abs() < 1e-14);
140    }
141
142    #[test]
143    fn frame_with_ref_dir() {
144        let f = Frame3::from_normal_and_ref(
145            Point3::new(0.0, 0.0, 0.0),
146            Vec3::new(0.0, 0.0, 1.0),
147            Vec3::new(1.0, 0.0, 0.0),
148        )
149        .expect("non-zero");
150        // x should align with the reference direction
151        assert!((f.x.x() - 1.0).abs() < 1e-14);
152        assert!(f.x.y().abs() < 1e-14);
153    }
154
155    #[test]
156    fn frame_with_parallel_ref_falls_back() {
157        // ref_dir parallel to normal — should still produce valid frame
158        let f = Frame3::from_normal_and_ref(
159            Point3::new(0.0, 0.0, 0.0),
160            Vec3::new(0.0, 0.0, 1.0),
161            Vec3::new(0.0, 0.0, 1.0),
162        )
163        .expect("non-zero");
164        assert!(f.x.dot(f.z).abs() < 1e-14);
165        assert!((f.x.length() - 1.0).abs() < 1e-14);
166    }
167
168    #[test]
169    fn zero_normal_errors() {
170        let r = Frame3::from_normal(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 0.0));
171        assert!(r.is_err());
172    }
173
174    proptest! {
175        #[test]
176        fn prop_frame_orthonormal(
177            nx in -10.0f64..10.0, ny in -10.0f64..10.0, nz in -10.0f64..10.0,
178        ) {
179            let n = Vec3::new(nx, ny, nz);
180            if let Ok(f) = Frame3::from_normal(Point3::new(0.0, 0.0, 0.0), n) {
181                // All axes are unit length
182                prop_assert!((f.x.length() - 1.0).abs() < 1e-12);
183                prop_assert!((f.y.length() - 1.0).abs() < 1e-12);
184                prop_assert!((f.z.length() - 1.0).abs() < 1e-12);
185                // Mutually perpendicular
186                prop_assert!(f.x.dot(f.y).abs() < 1e-12);
187                prop_assert!(f.x.dot(f.z).abs() < 1e-12);
188                prop_assert!(f.y.dot(f.z).abs() < 1e-12);
189                // Right-handed: x × y ≈ z
190                let cross = f.x.cross(f.y);
191                prop_assert!((cross.x() - f.z.x()).abs() < 1e-12);
192                prop_assert!((cross.y() - f.z.y()).abs() < 1e-12);
193                prop_assert!((cross.z() - f.z.z()).abs() < 1e-12);
194            }
195        }
196    }
197}