Skip to main content

brepkit_math/
vec.rs

1//! Vector and point types for geometric computation.
2//!
3//! [`Vector`] represents directions and displacements; [`Position`] represents
4//! positions. Both are newtypes over fixed-size `f64` arrays, parameterized by
5//! dimension via const generics.
6//!
7//! Ergonomic type aliases are provided for common dimensions:
8//!
9//! | Alias    | Underlying type |
10//! |----------|-----------------|
11//! | [`Vec2`] | `Vector<2>` |
12//! | [`Vec3`] | `Vector<3>` |
13//! | [`Point2`] | `Position<2>` |
14//! | [`Point3`] | `Position<3>` |
15
16use crate::madd::Madd;
17use std::ops::{Add, AddAssign, Mul, Neg, Sub, SubAssign};
18
19use crate::MathError;
20
21// ===========================================================================
22// Vector<N>
23// ===========================================================================
24
25/// An N-dimensional vector representing a direction or displacement.
26#[derive(Debug, Clone, Copy, PartialEq)]
27pub struct Vector<const N: usize>(pub [f64; N]);
28
29/// A 2D vector.
30pub type Vec2 = Vector<2>;
31
32/// A 3D vector.
33pub type Vec3 = Vector<3>;
34
35// ---------------------------------------------------------------------------
36// Shared methods (all dimensions)
37// ---------------------------------------------------------------------------
38
39impl<const N: usize> Vector<N> {
40    /// Squared Euclidean length (avoids a sqrt).
41    #[must_use]
42    pub fn length_squared(self) -> f64 {
43        let mut sum = 0.0;
44        let mut i = 0;
45        while i < N {
46            sum = self.0[i].madd(self.0[i], sum);
47            i += 1;
48        }
49        sum
50    }
51
52    /// Euclidean length.
53    #[must_use]
54    pub fn length(self) -> f64 {
55        self.length_squared().sqrt()
56    }
57
58    /// Return a unit-length vector in the same direction.
59    ///
60    /// # Errors
61    ///
62    /// Returns [`MathError::ZeroVector`] if the vector is zero, has
63    /// denormalized length (< [`f64::MIN_POSITIVE`]), or has overflowed
64    /// length (non-finite).
65    pub fn normalize(self) -> Result<Self, MathError> {
66        let len = self.length();
67        if !len.is_finite() || len < f64::MIN_POSITIVE {
68            return Err(MathError::ZeroVector);
69        }
70        let inv = 1.0 / len;
71        Ok(Self(std::array::from_fn(|i| self.0[i] * inv)))
72    }
73}
74
75// ---------------------------------------------------------------------------
76// 2D-specific methods
77// ---------------------------------------------------------------------------
78
79impl Vector<2> {
80    /// Create a new 2D vector.
81    #[must_use]
82    pub const fn new(x: f64, y: f64) -> Self {
83        Self([x, y])
84    }
85
86    /// X component.
87    #[must_use]
88    pub const fn x(self) -> f64 {
89        self.0[0]
90    }
91
92    /// Y component.
93    #[must_use]
94    pub const fn y(self) -> f64 {
95        self.0[1]
96    }
97
98    /// Dot product of two 2D vectors.
99    #[must_use]
100    pub fn dot(self, rhs: Self) -> f64 {
101        self.0[0].madd(rhs.0[0], self.0[1] * rhs.0[1])
102    }
103}
104
105// ---------------------------------------------------------------------------
106// 3D-specific methods
107// ---------------------------------------------------------------------------
108
109impl Vector<3> {
110    /// Create a new 3D vector.
111    #[must_use]
112    pub const fn new(x: f64, y: f64, z: f64) -> Self {
113        Self([x, y, z])
114    }
115
116    /// X component.
117    #[must_use]
118    pub const fn x(self) -> f64 {
119        self.0[0]
120    }
121
122    /// Y component.
123    #[must_use]
124    pub const fn y(self) -> f64 {
125        self.0[1]
126    }
127
128    /// Z component.
129    #[must_use]
130    pub const fn z(self) -> f64 {
131        self.0[2]
132    }
133
134    /// Dot product of two 3D vectors.
135    #[must_use]
136    pub fn dot(self, rhs: Self) -> f64 {
137        self.0[0].madd(rhs.0[0], self.0[1].madd(rhs.0[1], self.0[2] * rhs.0[2]))
138    }
139
140    /// Cross product of two 3D vectors.
141    #[must_use]
142    pub fn cross(self, rhs: Self) -> Self {
143        Self([
144            self.0[1].madd(rhs.0[2], -(self.0[2] * rhs.0[1])),
145            self.0[2].madd(rhs.0[0], -(self.0[0] * rhs.0[2])),
146            self.0[0].madd(rhs.0[1], -(self.0[1] * rhs.0[0])),
147        ])
148    }
149}
150
151// ---------------------------------------------------------------------------
152// Vector operators (all dimensions)
153// ---------------------------------------------------------------------------
154
155impl<const N: usize> Add for Vector<N> {
156    type Output = Self;
157
158    fn add(self, rhs: Self) -> Self {
159        Self(std::array::from_fn(|i| self.0[i] + rhs.0[i]))
160    }
161}
162
163impl<const N: usize> AddAssign for Vector<N> {
164    fn add_assign(&mut self, rhs: Self) {
165        for i in 0..N {
166            self.0[i] += rhs.0[i];
167        }
168    }
169}
170
171impl<const N: usize> Sub for Vector<N> {
172    type Output = Self;
173
174    fn sub(self, rhs: Self) -> Self {
175        Self(std::array::from_fn(|i| self.0[i] - rhs.0[i]))
176    }
177}
178
179impl<const N: usize> SubAssign for Vector<N> {
180    fn sub_assign(&mut self, rhs: Self) {
181        for i in 0..N {
182            self.0[i] -= rhs.0[i];
183        }
184    }
185}
186
187/// `vector * scalar`
188impl<const N: usize> Mul<f64> for Vector<N> {
189    type Output = Self;
190
191    fn mul(self, s: f64) -> Self {
192        Self(std::array::from_fn(|i| self.0[i] * s))
193    }
194}
195
196/// `scalar * vector`
197impl<const N: usize> Mul<Vector<N>> for f64 {
198    type Output = Vector<N>;
199
200    fn mul(self, rhs: Vector<N>) -> Vector<N> {
201        Vector(std::array::from_fn(|i| self * rhs.0[i]))
202    }
203}
204
205impl<const N: usize> Neg for Vector<N> {
206    type Output = Self;
207
208    fn neg(self) -> Self {
209        Self(std::array::from_fn(|i| -self.0[i]))
210    }
211}
212
213// ===========================================================================
214// Position<N>
215// ===========================================================================
216
217/// An N-dimensional point representing a position.
218#[derive(Debug, Clone, Copy, PartialEq)]
219pub struct Position<const N: usize>(pub [f64; N]);
220
221/// A 2D point.
222pub type Point2 = Position<2>;
223
224/// A 3D point.
225pub type Point3 = Position<3>;
226
227// ---------------------------------------------------------------------------
228// 2D-specific methods
229// ---------------------------------------------------------------------------
230
231impl Position<2> {
232    /// Create a new 2D point.
233    #[must_use]
234    pub const fn new(x: f64, y: f64) -> Self {
235        Self([x, y])
236    }
237
238    /// X coordinate.
239    #[must_use]
240    pub const fn x(self) -> f64 {
241        self.0[0]
242    }
243
244    /// Y coordinate.
245    #[must_use]
246    pub const fn y(self) -> f64 {
247        self.0[1]
248    }
249}
250
251// ---------------------------------------------------------------------------
252// 3D-specific methods
253// ---------------------------------------------------------------------------
254
255impl Position<3> {
256    /// Create a new 3D point.
257    #[must_use]
258    pub const fn new(x: f64, y: f64, z: f64) -> Self {
259        Self([x, y, z])
260    }
261
262    /// X coordinate.
263    #[must_use]
264    pub const fn x(self) -> f64 {
265        self.0[0]
266    }
267
268    /// Y coordinate.
269    #[must_use]
270    pub const fn y(self) -> f64 {
271        self.0[1]
272    }
273
274    /// Z coordinate.
275    #[must_use]
276    pub const fn z(self) -> f64 {
277        self.0[2]
278    }
279}
280
281// ---------------------------------------------------------------------------
282// Position operators (all dimensions)
283// ---------------------------------------------------------------------------
284
285/// Translate a point by a vector: `point + vector → point`.
286impl<const N: usize> Add<Vector<N>> for Position<N> {
287    type Output = Self;
288
289    fn add(self, rhs: Vector<N>) -> Self {
290        Self(std::array::from_fn(|i| self.0[i] + rhs.0[i]))
291    }
292}
293
294/// Translate a point by a negative vector: `point - vector → point`.
295impl<const N: usize> Sub<Vector<N>> for Position<N> {
296    type Output = Self;
297
298    fn sub(self, rhs: Vector<N>) -> Self {
299        Self(std::array::from_fn(|i| self.0[i] - rhs.0[i]))
300    }
301}
302
303/// Displacement from one point to another: `point - point → vector`.
304impl<const N: usize> Sub for Position<N> {
305    type Output = Vector<N>;
306
307    fn sub(self, rhs: Self) -> Vector<N> {
308        Vector(std::array::from_fn(|i| self.0[i] - rhs.0[i]))
309    }
310}
311
312// ===========================================================================
313// Serde support
314// ===========================================================================
315
316/// Implements `Serialize` and `Deserialize` for a const-generic newtype
317/// wrapping `[f64; N]`. Serde's derive macro cannot handle `[T; N]` for
318/// arbitrary `N`, so we provide manual impls that serialize as a tuple.
319macro_rules! impl_serde_for_array_newtype {
320    ($ty:ident, $name:expr) => {
321        #[cfg(feature = "serde")]
322        impl<const N: usize> serde::Serialize for $ty<N> {
323            fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
324                use serde::ser::SerializeTuple;
325                let mut tup = ser.serialize_tuple(N)?;
326                for &val in &self.0 {
327                    tup.serialize_element(&val)?;
328                }
329                tup.end()
330            }
331        }
332
333        #[cfg(feature = "serde")]
334        impl<'de, const N: usize> serde::Deserialize<'de> for $ty<N> {
335            fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
336                struct ArrayVisitor<const M: usize>;
337
338                impl<'de, const M: usize> serde::de::Visitor<'de> for ArrayVisitor<M> {
339                    type Value = [f64; M];
340
341                    fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
342                        write!(f, "an array of {} floats", M)
343                    }
344
345                    fn visit_seq<A: serde::de::SeqAccess<'de>>(
346                        self,
347                        mut seq: A,
348                    ) -> Result<Self::Value, A::Error> {
349                        let mut arr = [0.0; M];
350                        for (i, slot) in arr.iter_mut().enumerate() {
351                            *slot = seq
352                                .next_element()?
353                                .ok_or_else(|| serde::de::Error::invalid_length(i, &self))?;
354                        }
355                        Ok(arr)
356                    }
357                }
358
359                de.deserialize_tuple(N, ArrayVisitor::<N>).map($ty)
360            }
361        }
362    };
363}
364
365impl_serde_for_array_newtype!(Vector, "Vector");
366impl_serde_for_array_newtype!(Position, "Position");
367
368// ===========================================================================
369// Tests
370// ===========================================================================
371
372#[cfg(test)]
373#[allow(clippy::unwrap_used, clippy::expect_used)]
374mod tests {
375    use super::*;
376
377    #[test]
378    fn vec3_dot() {
379        let a = Vec3::new(1.0, 2.0, 3.0);
380        let b = Vec3::new(4.0, 5.0, 6.0);
381        assert!((a.dot(b) - 32.0).abs() < 1e-14);
382    }
383
384    #[test]
385    fn vec3_cross() {
386        let x = Vec3::new(1.0, 0.0, 0.0);
387        let y = Vec3::new(0.0, 1.0, 0.0);
388        let z = x.cross(y);
389        assert!((z.x()).abs() < 1e-14);
390        assert!((z.y()).abs() < 1e-14);
391        assert!((z.z() - 1.0).abs() < 1e-14);
392    }
393
394    #[test]
395    fn vec3_normalize() {
396        let v = Vec3::new(3.0, 4.0, 0.0);
397        let n = v.normalize().expect("non-zero");
398        assert!((n.length() - 1.0).abs() < 1e-14);
399    }
400
401    #[test]
402    fn vec3_zero_normalize_fails() {
403        let v = Vec3::new(0.0, 0.0, 0.0);
404        assert!(v.normalize().is_err());
405    }
406
407    #[test]
408    fn vec3_denormal_normalize_fails() {
409        // Denormalized-length vector should be rejected (A1 fix)
410        let v = Vec3::new(1e-320, 0.0, 0.0);
411        assert!(v.normalize().is_err());
412    }
413
414    #[test]
415    fn vec2_dot() {
416        let a = Vec2::new(3.0, 4.0);
417        let b = Vec2::new(1.0, 2.0);
418        assert!((a.dot(b) - 11.0).abs() < 1e-14);
419    }
420
421    #[test]
422    fn point3_sub_gives_vec3() {
423        let a = Point3::new(3.0, 4.0, 5.0);
424        let b = Point3::new(1.0, 1.0, 1.0);
425        let v = a - b;
426        assert!((v.x() - 2.0).abs() < 1e-14);
427        assert!((v.y() - 3.0).abs() < 1e-14);
428        assert!((v.z() - 4.0).abs() < 1e-14);
429    }
430
431    #[test]
432    fn point3_add_vec3() {
433        let p = Point3::new(1.0, 2.0, 3.0);
434        let v = Vec3::new(1.0, 1.0, 1.0);
435        let q = p + v;
436        assert!((q.x() - 2.0).abs() < 1e-14);
437    }
438
439    #[test]
440    fn point3_sub_vec3() {
441        let p = Point3::new(3.0, 4.0, 5.0);
442        let v = Vec3::new(1.0, 1.0, 1.0);
443        let q = p - v;
444        assert!((q.x() - 2.0).abs() < 1e-14);
445        assert!((q.y() - 3.0).abs() < 1e-14);
446        assert!((q.z() - 4.0).abs() < 1e-14);
447    }
448
449    #[test]
450    fn scalar_times_vec3() {
451        let v = Vec3::new(1.0, 2.0, 3.0);
452        let scaled = 2.0 * v;
453        assert!((scaled.x() - 2.0).abs() < 1e-14);
454        assert!((scaled.y() - 4.0).abs() < 1e-14);
455        assert!((scaled.z() - 6.0).abs() < 1e-14);
456    }
457
458    #[test]
459    fn vec3_add_assign() {
460        let mut a = Vec3::new(1.0, 2.0, 3.0);
461        a += Vec3::new(4.0, 5.0, 6.0);
462        assert!((a.x() - 5.0).abs() < 1e-14);
463        assert!((a.y() - 7.0).abs() < 1e-14);
464        assert!((a.z() - 9.0).abs() < 1e-14);
465    }
466
467    #[test]
468    fn vec3_sub_assign() {
469        let mut a = Vec3::new(5.0, 7.0, 9.0);
470        a -= Vec3::new(1.0, 2.0, 3.0);
471        assert!((a.x() - 4.0).abs() < 1e-14);
472        assert!((a.y() - 5.0).abs() < 1e-14);
473        assert!((a.z() - 6.0).abs() < 1e-14);
474    }
475
476    use proptest::prelude::*;
477
478    proptest! {
479        #[test]
480        fn prop_normalize_unit_length(x in -10.0f64..10.0, y in -10.0f64..10.0, z in -10.0f64..10.0) {
481            let v = Vec3::new(x, y, z);
482            if let Ok(n) = v.normalize() {
483                prop_assert!((n.length() - 1.0).abs() < 1e-12, "length = {}", n.length());
484            }
485        }
486
487        #[test]
488        fn prop_cross_anticommutative(
489            ax in -10.0f64..10.0, ay in -10.0f64..10.0, az in -10.0f64..10.0,
490            bx in -10.0f64..10.0, by in -10.0f64..10.0, bz in -10.0f64..10.0,
491        ) {
492            let a = Vec3::new(ax, ay, az);
493            let b = Vec3::new(bx, by, bz);
494            let ab = a.cross(b);
495            let ba = b.cross(a);
496            // a×b = -(b×a)
497            prop_assert!((ab.x() + ba.x()).abs() < 1e-10);
498            prop_assert!((ab.y() + ba.y()).abs() < 1e-10);
499            prop_assert!((ab.z() + ba.z()).abs() < 1e-10);
500        }
501
502        #[test]
503        fn prop_point_sub_vec_inverse_of_add(
504            px in -100.0f64..100.0, py in -100.0f64..100.0, pz in -100.0f64..100.0,
505            vx in -100.0f64..100.0, vy in -100.0f64..100.0, vz in -100.0f64..100.0,
506        ) {
507            let p = Point3::new(px, py, pz);
508            let v = Vec3::new(vx, vy, vz);
509            // (p + v) - v == p
510            let roundtrip = (p + v) - v;
511            prop_assert!((roundtrip.x() - p.x()).abs() < 1e-10);
512            prop_assert!((roundtrip.y() - p.y()).abs() < 1e-10);
513            prop_assert!((roundtrip.z() - p.z()).abs() < 1e-10);
514        }
515    }
516}