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
39/// The least sum of squares that [`Vector::length`] takes as it comes,
40/// 2^-1000: each larger square is normal, and the root keeps its digits.
41const SQUARES_LOW: f64 = f64::from_bits(23 << 52);
42
43/// 2^600: a vector whose squares underflow is scaled up by it, which
44/// changes no digit.
45const SCALE_UP: f64 = f64::from_bits(1623 << 52);
46
47/// 2^-600: a vector whose squares overflow is scaled down by it, which
48/// changes no digit of a component large enough to count in its length.
49const SCALE_DOWN: f64 = f64::from_bits(423 << 52);
50
51/// A power of two by which a vector whose largest component is `size` comes
52/// near one in size.
53///
54/// The scaled size is from 2^-74 to 2^24, so that a product of two of its
55/// components neither overflows nor underflows. The scale is exact. It is
56/// one for a size that is zero or not finite.
57#[must_use]
58pub fn unit_scale(size: f64) -> f64 {
59    if !(size.is_finite() && size > 0.0) {
60        return 1.0;
61    }
62    #[allow(clippy::cast_possible_truncation)]
63    let exponent = size.log2().floor().clamp(-1000.0, 1000.0) as i32;
64    2.0_f64.powi(-exponent)
65}
66
67impl<const N: usize> Vector<N> {
68    /// Squared Euclidean length (avoids a sqrt).
69    #[must_use]
70    pub fn length_squared(self) -> f64 {
71        let mut sum = 0.0;
72        let mut i = 0;
73        while i < N {
74            sum = self.0[i].madd(self.0[i], sum);
75            i += 1;
76        }
77        sum
78    }
79
80    /// Euclidean length, at every finite size: a vector whose squares
81    /// overflow or underflow is measured at a power of two of its size. It
82    /// is infinite only for a length past the largest float.
83    #[must_use]
84    pub fn length(self) -> f64 {
85        let sum = self.length_squared();
86        if sum.is_finite() && sum >= SQUARES_LOW {
87            return sum.sqrt();
88        }
89        self.rescaled()
90            .map_or_else(|| sum.sqrt(), |(v, back)| v.length_squared().sqrt() * back)
91    }
92
93    /// The vector times a power of two that brings its largest component
94    /// near one, and the power of two that undoes it; `None` for a zero
95    /// vector or a component that is not finite.
96    fn rescaled(self) -> Option<(Self, f64)> {
97        if !self.0.iter().all(|c| c.is_finite()) {
98            return None;
99        }
100        let most = self.0.iter().fold(0.0_f64, |m, c| m.max(c.abs()));
101        if most <= 0.0 {
102            return None;
103        }
104        let (by, back) = if most > 1.0 {
105            (SCALE_DOWN, SCALE_UP)
106        } else {
107            (SCALE_UP, SCALE_DOWN)
108        };
109        Some((Self(std::array::from_fn(|i| self.0[i] * by)), back))
110    }
111
112    /// The largest of the absolute values of the components; not a number
113    /// if a component is not.
114    #[must_use]
115    pub fn largest_component(self) -> f64 {
116        self.0.iter().fold(0.0_f64, |m, c| {
117            if m.is_nan() || c.is_nan() {
118                f64::NAN
119            } else {
120                m.max(c.abs())
121            }
122        })
123    }
124
125    /// The vector scaled by [`unit_scale`] of its largest component: the
126    /// same direction, with no product of two components out of range.
127    /// Two vectors so scaled give the sign of their dot or cross product,
128    /// and the angle between them, as they are.
129    #[must_use]
130    pub fn at_unit_size(self) -> Self {
131        let by = unit_scale(self.largest_component());
132        Self(std::array::from_fn(|i| self.0[i] * by))
133    }
134
135    /// Return a unit-length vector in the same direction. A vector of any
136    /// finite, non-zero size has one: one whose squares overflow or
137    /// underflow is scaled by a power of two first.
138    ///
139    /// # Errors
140    ///
141    /// Returns [`MathError::ZeroVector`] if the vector is zero or a
142    /// component is not finite.
143    pub fn normalize(self) -> Result<Self, MathError> {
144        let sum = self.length_squared();
145        let v = if sum.is_finite() && sum >= SQUARES_LOW {
146            self
147        } else {
148            self.rescaled().ok_or(MathError::ZeroVector)?.0
149        };
150        let len = v.length_squared().sqrt();
151        if !len.is_finite() || len < f64::MIN_POSITIVE {
152            return Err(MathError::ZeroVector);
153        }
154        let inv = 1.0 / len;
155        Ok(Self(std::array::from_fn(|i| v.0[i] * inv)))
156    }
157}
158
159// ---------------------------------------------------------------------------
160// 2D-specific methods
161// ---------------------------------------------------------------------------
162
163impl Vector<2> {
164    /// Create a new 2D vector.
165    #[must_use]
166    pub const fn new(x: f64, y: f64) -> Self {
167        Self([x, y])
168    }
169
170    /// X component.
171    #[must_use]
172    pub const fn x(self) -> f64 {
173        self.0[0]
174    }
175
176    /// Y component.
177    #[must_use]
178    pub const fn y(self) -> f64 {
179        self.0[1]
180    }
181
182    /// Dot product of two 2D vectors.
183    #[must_use]
184    pub fn dot(self, rhs: Self) -> f64 {
185        self.0[0].madd(rhs.0[0], self.0[1] * rhs.0[1])
186    }
187}
188
189// ---------------------------------------------------------------------------
190// 3D-specific methods
191// ---------------------------------------------------------------------------
192
193impl Vector<3> {
194    /// Create a new 3D vector.
195    #[must_use]
196    pub const fn new(x: f64, y: f64, z: f64) -> Self {
197        Self([x, y, z])
198    }
199
200    /// X component.
201    #[must_use]
202    pub const fn x(self) -> f64 {
203        self.0[0]
204    }
205
206    /// Y component.
207    #[must_use]
208    pub const fn y(self) -> f64 {
209        self.0[1]
210    }
211
212    /// Z component.
213    #[must_use]
214    pub const fn z(self) -> f64 {
215        self.0[2]
216    }
217
218    /// Dot product of two 3D vectors.
219    #[must_use]
220    pub fn dot(self, rhs: Self) -> f64 {
221        self.0[0].madd(rhs.0[0], self.0[1].madd(rhs.0[1], self.0[2] * rhs.0[2]))
222    }
223
224    /// Cross product of two 3D vectors.
225    #[must_use]
226    pub fn cross(self, rhs: Self) -> Self {
227        Self([
228            self.0[1].madd(rhs.0[2], -(self.0[2] * rhs.0[1])),
229            self.0[2].madd(rhs.0[0], -(self.0[0] * rhs.0[2])),
230            self.0[0].madd(rhs.0[1], -(self.0[1] * rhs.0[0])),
231        ])
232    }
233
234    /// The direction of the part of the vector square to the unit vector
235    /// `axis`.
236    ///
237    /// The vector is taken at a unit size first, so that neither the
238    /// projection nor the tests below overflow or lose digits at either end
239    /// of the range. A part of half the vector or more is taken as it is.
240    /// A shorter part is projected again, and is taken only where it is
241    /// longer than the most that rounding alone could leave square to the
242    /// axis; its direction is projected once more, so that it is square to
243    /// the axis to a few units of rounding.
244    ///
245    /// # Errors
246    ///
247    /// Returns [`MathError::ZeroVector`] if the vector is zero or not
248    /// finite, or its part square to `axis` could be rounding alone, as for
249    /// a vector along `axis`.
250    pub fn square_part(self, axis: Self) -> Result<Self, MathError> {
251        let v = self.at_unit_size();
252        let along = axis * v.dot(axis);
253        let part = v - along;
254        if part.length() >= 0.5 * v.length() {
255            return part.normalize();
256        }
257        let tilt = part.dot(axis);
258        let again = part - axis * tilt;
259        // With u the unit rounding, each component of `along` and `part`
260        // is within u of its size, and each of `again` within u of its
261        // size and of `axis * tilt`. The rounding of a dot product lies
262        // along the axis, which the second projection takes out. Error `e_i`
263        // in component i moves the part square to the axis by at most
264        // `e_i * sqrt(1 - axis_i^2)`. The bound is twice their sum.
265        let bound = (0..3)
266            .map(|i| {
267                let off_axis = (1.0 - axis.0[i] * axis.0[i]).max(0.0).sqrt();
268                let sizes = along.0[i].abs()
269                    + part.0[i].abs()
270                    + again.0[i].abs()
271                    + (axis.0[i] * tilt).abs();
272                sizes * off_axis
273            })
274            .sum::<f64>()
275            * f64::EPSILON;
276        let length = again.length();
277        let taken = length > bound && length.is_finite();
278        if !taken {
279            return Err(MathError::ZeroVector);
280        }
281        let unit = again.normalize()?;
282        (unit - axis * unit.dot(axis)).normalize()
283    }
284}
285
286// ---------------------------------------------------------------------------
287// Vector operators (all dimensions)
288// ---------------------------------------------------------------------------
289
290impl<const N: usize> Add for Vector<N> {
291    type Output = Self;
292
293    fn add(self, rhs: Self) -> Self {
294        Self(std::array::from_fn(|i| self.0[i] + rhs.0[i]))
295    }
296}
297
298impl<const N: usize> AddAssign for Vector<N> {
299    fn add_assign(&mut self, rhs: Self) {
300        for i in 0..N {
301            self.0[i] += rhs.0[i];
302        }
303    }
304}
305
306impl<const N: usize> Sub for Vector<N> {
307    type Output = Self;
308
309    fn sub(self, rhs: Self) -> Self {
310        Self(std::array::from_fn(|i| self.0[i] - rhs.0[i]))
311    }
312}
313
314impl<const N: usize> SubAssign for Vector<N> {
315    fn sub_assign(&mut self, rhs: Self) {
316        for i in 0..N {
317            self.0[i] -= rhs.0[i];
318        }
319    }
320}
321
322/// `vector * scalar`
323impl<const N: usize> Mul<f64> for Vector<N> {
324    type Output = Self;
325
326    fn mul(self, s: f64) -> Self {
327        Self(std::array::from_fn(|i| self.0[i] * s))
328    }
329}
330
331/// `scalar * vector`
332impl<const N: usize> Mul<Vector<N>> for f64 {
333    type Output = Vector<N>;
334
335    fn mul(self, rhs: Vector<N>) -> Vector<N> {
336        Vector(std::array::from_fn(|i| self * rhs.0[i]))
337    }
338}
339
340impl<const N: usize> Neg for Vector<N> {
341    type Output = Self;
342
343    fn neg(self) -> Self {
344        Self(std::array::from_fn(|i| -self.0[i]))
345    }
346}
347
348// ===========================================================================
349// Position<N>
350// ===========================================================================
351
352/// An N-dimensional point representing a position.
353#[derive(Debug, Clone, Copy, PartialEq)]
354pub struct Position<const N: usize>(pub [f64; N]);
355
356/// A 2D point.
357pub type Point2 = Position<2>;
358
359/// A 3D point.
360pub type Point3 = Position<3>;
361
362// ---------------------------------------------------------------------------
363// 2D-specific methods
364// ---------------------------------------------------------------------------
365
366impl Position<2> {
367    /// Create a new 2D point.
368    #[must_use]
369    pub const fn new(x: f64, y: f64) -> Self {
370        Self([x, y])
371    }
372
373    /// X coordinate.
374    #[must_use]
375    pub const fn x(self) -> f64 {
376        self.0[0]
377    }
378
379    /// Y coordinate.
380    #[must_use]
381    pub const fn y(self) -> f64 {
382        self.0[1]
383    }
384}
385
386// ---------------------------------------------------------------------------
387// 3D-specific methods
388// ---------------------------------------------------------------------------
389
390impl Position<3> {
391    /// Create a new 3D point.
392    #[must_use]
393    pub const fn new(x: f64, y: f64, z: f64) -> Self {
394        Self([x, y, z])
395    }
396
397    /// X coordinate.
398    #[must_use]
399    pub const fn x(self) -> f64 {
400        self.0[0]
401    }
402
403    /// Y coordinate.
404    #[must_use]
405    pub const fn y(self) -> f64 {
406        self.0[1]
407    }
408
409    /// Z coordinate.
410    #[must_use]
411    pub const fn z(self) -> f64 {
412        self.0[2]
413    }
414}
415
416// ---------------------------------------------------------------------------
417// Position operators (all dimensions)
418// ---------------------------------------------------------------------------
419
420/// Translate a point by a vector: `point + vector → point`.
421impl<const N: usize> Add<Vector<N>> for Position<N> {
422    type Output = Self;
423
424    fn add(self, rhs: Vector<N>) -> Self {
425        Self(std::array::from_fn(|i| self.0[i] + rhs.0[i]))
426    }
427}
428
429/// Translate a point by a negative vector: `point - vector → point`.
430impl<const N: usize> Sub<Vector<N>> for Position<N> {
431    type Output = Self;
432
433    fn sub(self, rhs: Vector<N>) -> Self {
434        Self(std::array::from_fn(|i| self.0[i] - rhs.0[i]))
435    }
436}
437
438/// Displacement from one point to another: `point - point → vector`.
439impl<const N: usize> Sub for Position<N> {
440    type Output = Vector<N>;
441
442    fn sub(self, rhs: Self) -> Vector<N> {
443        Vector(std::array::from_fn(|i| self.0[i] - rhs.0[i]))
444    }
445}
446
447// ===========================================================================
448// Serde support
449// ===========================================================================
450
451/// Implements `Serialize` and `Deserialize` for a const-generic newtype
452/// wrapping `[f64; N]`. Serde's derive macro cannot handle `[T; N]` for
453/// arbitrary `N`, so we provide manual impls that serialize as a tuple.
454macro_rules! impl_serde_for_array_newtype {
455    ($ty:ident, $name:expr) => {
456        #[cfg(feature = "serde")]
457        impl<const N: usize> serde::Serialize for $ty<N> {
458            fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
459                use serde::ser::SerializeTuple;
460                let mut tup = ser.serialize_tuple(N)?;
461                for &val in &self.0 {
462                    tup.serialize_element(&val)?;
463                }
464                tup.end()
465            }
466        }
467
468        #[cfg(feature = "serde")]
469        impl<'de, const N: usize> serde::Deserialize<'de> for $ty<N> {
470            fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
471                struct ArrayVisitor<const M: usize>;
472
473                impl<'de, const M: usize> serde::de::Visitor<'de> for ArrayVisitor<M> {
474                    type Value = [f64; M];
475
476                    fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
477                        write!(f, "an array of {} floats", M)
478                    }
479
480                    fn visit_seq<A: serde::de::SeqAccess<'de>>(
481                        self,
482                        mut seq: A,
483                    ) -> Result<Self::Value, A::Error> {
484                        let mut arr = [0.0; M];
485                        for (i, slot) in arr.iter_mut().enumerate() {
486                            *slot = seq
487                                .next_element()?
488                                .ok_or_else(|| serde::de::Error::invalid_length(i, &self))?;
489                        }
490                        Ok(arr)
491                    }
492                }
493
494                de.deserialize_tuple(N, ArrayVisitor::<N>).map($ty)
495            }
496        }
497    };
498}
499
500impl_serde_for_array_newtype!(Vector, "Vector");
501impl_serde_for_array_newtype!(Position, "Position");
502
503// ===========================================================================
504// Tests
505// ===========================================================================
506
507#[cfg(test)]
508#[allow(clippy::unwrap_used, clippy::expect_used)]
509mod tests {
510    use super::*;
511
512    /// The square part of a vector near the axis, at 1e-15 to 0.3 off it,
513    /// at sizes 1e-200, 1 and 1e200, against z and against (1, 1, 1). A
514    /// part that rounding alone cannot leave is taken: a unit direction
515    /// square to the axis to 8 units of rounding, near the true one. A
516    /// vector along the axis in exact arithmetic leaves only rounding, and
517    /// is refused.
518    #[test]
519    fn a_square_part_near_the_axis_is_square_to_it_or_refused() {
520        let ulps = 8.0 * f64::EPSILON;
521        let z = Vec3::new(0.0, 0.0, 1.0);
522        let x = Vec3::new(1.0, 0.0, 0.0);
523        let diagonal = Vec3::new(1.0, 1.0, 1.0).normalize().unwrap();
524        let across = Vec3::new(1.0, -1.0, 0.0).normalize().unwrap();
525        for s in [1e-200, 1.0, 1e200] {
526            for off in [1e-15, 1e-12, 1e-9] {
527                let part = Vec3::new(off * s, 0.0, s).square_part(z).unwrap();
528                assert!(
529                    (part - x).length() <= ulps,
530                    "size {s}, {off} off z: {part:?}"
531                );
532            }
533            for off in [1e-14, 1e-12, 1e-10, 1e-9, 1e-7, 1e-4, 0.3] {
534                let v = (diagonal + across * off) * s;
535                let part = v.square_part(diagonal).unwrap();
536                assert!(
537                    part.dot(diagonal).abs() <= ulps,
538                    "size {s}, {off} off: {part:?}"
539                );
540                assert!(
541                    (part.length() - 1.0).abs() <= ulps,
542                    "size {s}, {off} off: {part:?}"
543                );
544                assert!(
545                    (part - across).length() <= 64.0 * f64::EPSILON / off,
546                    "size {s}, {off} off: {part:?}"
547                );
548            }
549            assert!(Vec3::new(0.0, 0.0, s).square_part(z).is_err(), "size {s}");
550            assert!(
551                Vec3::new(s, s, s).square_part(diagonal).is_err(),
552                "size {s}"
553            );
554            let tilted = Vec3::new(s, s, s * (1.0 + 1e-10)).square_part(diagonal);
555            if let Ok(part) = tilted {
556                assert!(part.dot(diagonal).abs() <= ulps, "size {s}: {part:?}");
557                assert!((part.length() - 1.0).abs() <= ulps, "size {s}: {part:?}");
558            }
559        }
560    }
561
562    /// The square part of a vector at either end of the float range: a
563    /// reference of 1.7e308 square to z, and one of the least subnormal
564    /// against (1, 1, 1). Each gives a unit direction square to the axis to
565    /// a few units of rounding. A vector along the axis is refused at any
566    /// size, and so is one that is not finite.
567    #[test]
568    fn a_square_part_holds_at_the_ends_of_the_float_range() {
569        let ulps = 8.0 * f64::EPSILON;
570        let z = Vec3::new(0.0, 0.0, 1.0);
571        let diagonal = Vec3::new(1.0, 1.0, 1.0).normalize().unwrap();
572        let least = f64::from_bits(1);
573        for (v, axis, want) in [
574            (
575                Vec3::new(1.7e308, 1.7e308, 0.0),
576                z,
577                Vec3::new(1.0, 1.0, 0.0).normalize().unwrap(),
578            ),
579            (
580                Vec3::new(least, 0.0, 0.0),
581                diagonal,
582                Vec3::new(2.0, -1.0, -1.0).normalize().unwrap(),
583            ),
584            (
585                Vec3::new(f64::MAX, -f64::MAX, f64::MAX),
586                diagonal,
587                Vec3::new(1.0, -2.0, 1.0).normalize().unwrap(),
588            ),
589        ] {
590            let part = v.square_part(axis).unwrap();
591            assert!(part.dot(axis).abs() <= ulps, "{v:?}: {part:?}");
592            assert!((part.length() - 1.0).abs() <= ulps, "{v:?}: {part:?}");
593            assert!((part - want).length() <= ulps, "{v:?}: {part:?}");
594        }
595        for s in [1.0, 1e-300, 1e300, least, f64::MAX] {
596            assert!(
597                Vec3::new(s, s, s).square_part(diagonal).is_err(),
598                "size {s}"
599            );
600        }
601        for bad in [
602            Vec3::new(f64::NAN, 1.0, 0.0),
603            Vec3::new(f64::INFINITY, 1.0, 0.0),
604            Vec3::new(0.0, 0.0, 0.0),
605        ] {
606            assert!(bad.square_part(z).is_err(), "{bad:?}");
607        }
608    }
609
610    /// A vector at a unit size at the ends of the float range: components
611    /// of `f64::MAX`, of the least subnormal, the two in one vector, and
612    /// zero. Each scaled vector is finite, its largest component is from
613    /// 2^-74 to 2^24, and each component keeps its sign. A vector with a
614    /// component that is not a number has no largest component.
615    #[test]
616    fn the_unit_size_holds_at_the_ends_of_the_float_range() {
617        let least = f64::from_bits(1);
618        for v in [
619            Vec3::new(f64::MAX, f64::MAX, -f64::MAX),
620            Vec3::new(least, 0.0, -least),
621            Vec3::new(f64::MAX, least, 0.0),
622            Vec3::new(-least, f64::MAX, 1.0),
623        ] {
624            let u = v.at_unit_size();
625            let most = u.largest_component();
626            assert!(u.0.iter().all(|c| c.is_finite()), "{v:?}: {u:?}");
627            assert!(
628                (2.0_f64.powi(-74)..=2.0_f64.powi(24)).contains(&most),
629                "{v:?}: {u:?}"
630            );
631            for (a, b) in v.0.iter().zip(u.0) {
632                assert!(
633                    b.to_bits() == 0 || a.signum().to_bits() == b.signum().to_bits(),
634                    "{v:?}: {u:?}"
635                );
636            }
637        }
638        let zero = Vec3::new(0.0, 0.0, 0.0);
639        assert_eq!(zero.at_unit_size(), zero);
640        for size in [0.0, f64::NAN, f64::INFINITY, -1.0] {
641            assert_eq!(unit_scale(size).to_bits(), 1.0_f64.to_bits(), "{size}");
642        }
643        assert_eq!(unit_scale(least).to_bits(), 2.0_f64.powi(1000).to_bits());
644        assert_eq!(
645            unit_scale(f64::MAX).to_bits(),
646            2.0_f64.powi(-1000).to_bits()
647        );
648        assert!(Vec3::new(f64::NAN, 1.0, 0.0).largest_component().is_nan());
649        assert!(Vec3::new(1.0, f64::NAN, 0.0).at_unit_size().y().is_nan());
650    }
651
652    /// A vector's length and direction hold at every finite size: squared,
653    /// a component of 1e200 overflows and one of 1e-200 underflows.
654    #[test]
655    fn a_vector_of_any_finite_size_has_a_length_and_a_direction() {
656        let sizes = [
657            1e200,
658            1e-200,
659            1e-310,
660            f64::MIN_POSITIVE,
661            1.7e308,
662            1e155,
663            1e-160,
664        ];
665        for s in sizes {
666            for (v, length) in [
667                (Vec3::new(s, 0.0, 0.0), s),
668                (Vec3::new(0.0, -s, 0.0), s),
669                (Vec3::new(0.0, 0.0, s), s),
670            ] {
671                assert_eq!(v.length().to_bits(), length.to_bits(), "{v:?}");
672                let unit = v.normalize().unwrap();
673                assert!((unit.length() - 1.0).abs() < 1e-15, "{v:?} gives {unit:?}");
674                assert!(
675                    (unit.dot(v) - v.length()).abs() <= 1e-15 * v.length(),
676                    "{v:?}"
677                );
678            }
679            let tilt = Vec3::new(3.0 * s / 4.0, 0.0, s);
680            if (3.0 * s / 4.0).is_normal() {
681                let unit = tilt.normalize().unwrap();
682                assert!(
683                    (unit.x() - 0.6).abs() < 1e-15 && (unit.z() - 0.8).abs() < 1e-15,
684                    "{s}: {unit:?}"
685                );
686                assert!(
687                    (tilt.length() / (1.25 * s) - 1.0).abs() < 1e-15,
688                    "{s}: {}",
689                    tilt.length()
690                );
691            }
692            let flat = Vec2::new(0.0, s);
693            assert_eq!(flat.length().to_bits(), s.to_bits());
694            assert!((flat.normalize().unwrap().y() - 1.0).abs() < 1e-15);
695        }
696        let past = Vec3::new(1.7e308, 1.7e308, 0.0);
697        assert!(past.length().is_infinite());
698        let unit = past.normalize().unwrap();
699        assert!(
700            (unit.x() - std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-15,
701            "{unit:?}"
702        );
703        for bad in [
704            Vec3::new(0.0, 0.0, 0.0),
705            Vec3::new(f64::NAN, 1.0, 0.0),
706            Vec3::new(f64::INFINITY, 1.0, 0.0),
707        ] {
708            assert!(bad.normalize().is_err(), "{bad:?}");
709        }
710    }
711
712    #[test]
713    fn vec3_dot() {
714        let a = Vec3::new(1.0, 2.0, 3.0);
715        let b = Vec3::new(4.0, 5.0, 6.0);
716        assert!((a.dot(b) - 32.0).abs() < 1e-14);
717    }
718
719    #[test]
720    fn vec3_cross() {
721        let x = Vec3::new(1.0, 0.0, 0.0);
722        let y = Vec3::new(0.0, 1.0, 0.0);
723        let z = x.cross(y);
724        assert!((z.x()).abs() < 1e-14);
725        assert!((z.y()).abs() < 1e-14);
726        assert!((z.z() - 1.0).abs() < 1e-14);
727    }
728
729    #[test]
730    fn vec3_normalize() {
731        let v = Vec3::new(3.0, 4.0, 0.0);
732        let n = v.normalize().expect("non-zero");
733        assert!((n.length() - 1.0).abs() < 1e-14);
734    }
735
736    #[test]
737    fn vec3_zero_normalize_fails() {
738        let v = Vec3::new(0.0, 0.0, 0.0);
739        assert!(v.normalize().is_err());
740    }
741
742    /// A vector with a subnormal length still has a direction, and no
743    /// component of it is infinite.
744    #[test]
745    fn vec3_denormal_normalize_gives_a_unit_vector() {
746        let v = Vec3::new(1e-320, 0.0, 0.0);
747        let unit = v.normalize().unwrap();
748        assert!(
749            (unit.x() - 1.0).abs() < 1e-15 && unit.y().abs() < 1e-15,
750            "{unit:?}"
751        );
752    }
753
754    #[test]
755    fn vec2_dot() {
756        let a = Vec2::new(3.0, 4.0);
757        let b = Vec2::new(1.0, 2.0);
758        assert!((a.dot(b) - 11.0).abs() < 1e-14);
759    }
760
761    #[test]
762    fn point3_sub_gives_vec3() {
763        let a = Point3::new(3.0, 4.0, 5.0);
764        let b = Point3::new(1.0, 1.0, 1.0);
765        let v = a - b;
766        assert!((v.x() - 2.0).abs() < 1e-14);
767        assert!((v.y() - 3.0).abs() < 1e-14);
768        assert!((v.z() - 4.0).abs() < 1e-14);
769    }
770
771    #[test]
772    fn point3_add_vec3() {
773        let p = Point3::new(1.0, 2.0, 3.0);
774        let v = Vec3::new(1.0, 1.0, 1.0);
775        let q = p + v;
776        assert!((q.x() - 2.0).abs() < 1e-14);
777    }
778
779    #[test]
780    fn point3_sub_vec3() {
781        let p = Point3::new(3.0, 4.0, 5.0);
782        let v = Vec3::new(1.0, 1.0, 1.0);
783        let q = p - v;
784        assert!((q.x() - 2.0).abs() < 1e-14);
785        assert!((q.y() - 3.0).abs() < 1e-14);
786        assert!((q.z() - 4.0).abs() < 1e-14);
787    }
788
789    #[test]
790    fn scalar_times_vec3() {
791        let v = Vec3::new(1.0, 2.0, 3.0);
792        let scaled = 2.0 * v;
793        assert!((scaled.x() - 2.0).abs() < 1e-14);
794        assert!((scaled.y() - 4.0).abs() < 1e-14);
795        assert!((scaled.z() - 6.0).abs() < 1e-14);
796    }
797
798    #[test]
799    fn vec3_add_assign() {
800        let mut a = Vec3::new(1.0, 2.0, 3.0);
801        a += Vec3::new(4.0, 5.0, 6.0);
802        assert!((a.x() - 5.0).abs() < 1e-14);
803        assert!((a.y() - 7.0).abs() < 1e-14);
804        assert!((a.z() - 9.0).abs() < 1e-14);
805    }
806
807    #[test]
808    fn vec3_sub_assign() {
809        let mut a = Vec3::new(5.0, 7.0, 9.0);
810        a -= Vec3::new(1.0, 2.0, 3.0);
811        assert!((a.x() - 4.0).abs() < 1e-14);
812        assert!((a.y() - 5.0).abs() < 1e-14);
813        assert!((a.z() - 6.0).abs() < 1e-14);
814    }
815
816    use proptest::prelude::*;
817
818    proptest! {
819        #[test]
820        fn prop_normalize_unit_length(x in -10.0f64..10.0, y in -10.0f64..10.0, z in -10.0f64..10.0) {
821            let v = Vec3::new(x, y, z);
822            if let Ok(n) = v.normalize() {
823                prop_assert!((n.length() - 1.0).abs() < 1e-12, "length = {}", n.length());
824            }
825        }
826
827        #[test]
828        fn prop_cross_anticommutative(
829            ax in -10.0f64..10.0, ay in -10.0f64..10.0, az in -10.0f64..10.0,
830            bx in -10.0f64..10.0, by in -10.0f64..10.0, bz in -10.0f64..10.0,
831        ) {
832            let a = Vec3::new(ax, ay, az);
833            let b = Vec3::new(bx, by, bz);
834            let ab = a.cross(b);
835            let ba = b.cross(a);
836            // a×b = -(b×a)
837            prop_assert!((ab.x() + ba.x()).abs() < 1e-10);
838            prop_assert!((ab.y() + ba.y()).abs() < 1e-10);
839            prop_assert!((ab.z() + ba.z()).abs() < 1e-10);
840        }
841
842        #[test]
843        fn prop_point_sub_vec_inverse_of_add(
844            px in -100.0f64..100.0, py in -100.0f64..100.0, pz in -100.0f64..100.0,
845            vx in -100.0f64..100.0, vy in -100.0f64..100.0, vz in -100.0f64..100.0,
846        ) {
847            let p = Point3::new(px, py, pz);
848            let v = Vec3::new(vx, vy, vz);
849            // (p + v) - v == p
850            let roundtrip = (p + v) - v;
851            prop_assert!((roundtrip.x() - p.x()).abs() < 1e-10);
852            prop_assert!((roundtrip.y() - p.y()).abs() < 1e-10);
853            prop_assert!((roundtrip.z() - p.z()).abs() < 1e-10);
854        }
855    }
856}