rs_math3d/
vector.rs

1// Copyright 2020-Present (c) Raja Lehtihet & Wael El Oraiby
2//
3// Redistribution and use in source and binary forms, with or without
4// modification, are permitted provided that the following conditions are met:
5//
6// 1. Redistributions of source code must retain the above copyright notice,
7// this list of conditions and the following disclaimer.
8//
9// 2. Redistributions in binary form must reproduce the above copyright notice,
10// this list of conditions and the following disclaimer in the documentation
11// and/or other materials provided with the distribution.
12//
13// 3. Neither the name of the copyright holder nor the names of its contributors
14// may be used to endorse or promote products derived from this software without
15// specific prior written permission.
16//
17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
21// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27// POSSIBILITY OF SUCH DAMAGE.
28//! Vector mathematics module providing 2D, 3D, and 4D vector operations.
29//!
30//! This module provides generic vector types and operations for computer graphics
31//! and linear algebra applications. All vectors support standard arithmetic operations,
32//! dot products, and component-wise operations.
33//!
34//! # Examples
35//!
36//! ```
37//! use rs_math3d::vector::{FloatVector, Vector, Vector3};
38//! 
39//! let v1 = Vector3::new(1.0, 2.0, 3.0);
40//! let v2 = Vector3::new(4.0, 5.0, 6.0);
41//! 
42//! // Vector addition
43//! let sum = v1 + v2;
44//! 
45//! // Dot product
46//! let dot = Vector3::dot(&v1, &v2);
47//! 
48//! // Normalization
49//! let normalized = v1.normalize();
50//! ```
51
52use crate::scalar::*;
53use num_traits::{Zero, One};
54use core::ops::{Add, Div, Mul, Neg, Rem, Sub};
55
56/// Generic vector trait defining common vector operations.
57///
58/// This trait provides the foundation for all vector types, defining
59/// operations like addition, subtraction, dot product, and component-wise operations.
60///
61/// # Mathematical Operations
62///
63/// For vectors **v** and **w**, and scalar `s`:
64/// - Addition: **v** + **w** = (v₁ + w₁, v₂ + w₂, ...)
65/// - Subtraction: **v** - **w** = (v₁ - w₁, v₂ - w₂, ...)
66/// - Scalar multiplication: s**v** = (sv₁, sv₂, ...)
67/// - Dot product: **v** · **w** = v₁w₁ + v₂w₂ + ...
68pub trait Vector<T: Scalar, Rhs = Self, Output = Self>:
69    Add<Rhs, Output = Output>
70    + Sub<Rhs, Output = Output>
71    + Mul<Rhs, Output = Output>
72    + Mul<T, Output = Output>
73    + Div<Rhs, Output = Output>
74    + Div<T, Output = Output>
75    + Neg<Output = Output>
76    + Clone
77    + Copy
78{
79    /// Returns the zero vector (all components are zero).
80    fn zero() -> Self;
81
82    /// Adds two vectors component-wise.
83    fn add_vv(l: &Self, r: &Self) -> Self;
84    
85    /// Subtracts two vectors component-wise.
86    fn sub_vv(l: &Self, r: &Self) -> Self;
87    
88    /// Multiplies two vectors component-wise (Hadamard product).
89    fn mul_vv(l: &Self, r: &Self) -> Self;
90    
91    /// Divides two vectors component-wise.
92    fn div_vv(l: &Self, r: &Self) -> Self;
93    
94    /// Multiplies a vector by a scalar.
95    fn mul_vs(l: &Self, r: T) -> Self;
96    
97    /// Divides a vector by a scalar.
98    fn div_vs(l: &Self, r: T) -> Self;
99    
100    /// Computes the remainder of component-wise division.
101    fn rem_vv(l: &Self, r: &Self) -> Self;
102
103    /// Computes the dot product of two vectors.
104    ///
105    /// For vectors **v** and **w**:
106    /// ```text
107    /// v · w = Σᵢ vᵢwᵢ
108    /// ```
109    fn dot(l: &Self, r: &Self) -> T;
110
111    /// Returns a vector with the minimum components from both vectors.
112    fn min(l: &Self, r: &Self) -> Self;
113    
114    /// Returns a vector with the maximum components from both vectors.
115    fn max(l: &Self, r: &Self) -> Self;
116}
117
118/// Trait for vectors with floating-point components.
119///
120/// Extends the base `Vector` trait with operations that require
121/// floating-point arithmetic, such as length calculation and normalization.
122pub trait FloatVector<T: FloatScalar>: Vector<T> {
123    /// Computes the Euclidean length (magnitude) of the vector.
124    ///
125    /// For vector **v**:
126    /// ```text
127    /// ||v|| = √(v₁² + v₂² + ... + vₙ²)
128    /// ```
129    fn length(&self) -> T;
130    
131    /// Returns a unit vector in the same direction.
132    ///
133    /// For vector **v**:
134    /// ```text
135    /// v̂ = v / ||v||
136    /// ```
137    ///
138    /// # Note
139    /// Returns NaN or Inf components if the vector has zero length.
140    fn normalize(&self) -> Self;
141    
142    /// Computes the Euclidean distance between two vectors.
143    ///
144    /// For vectors **v** and **w**:
145    /// ```text
146    /// d(v, w) = ||v - w||
147    /// ```
148    fn distance(l: &Self, r: &Self) -> T;
149
150    /// Computes the squared length (avoids a square root).
151    ///
152    /// ```text
153    /// ||v||² = v · v
154    /// ```
155    fn length_squared(&self) -> T {
156        Self::dot(self, self)
157    }
158
159    /// Returns a normalized vector or `None` when the length is too small.
160    fn try_normalize(&self, epsilon: T) -> Option<Self> {
161        let len_sq = self.length_squared();
162        if len_sq <= epsilon * epsilon {
163            None
164        } else {
165            Some(*self / len_sq.tsqrt())
166        }
167    }
168
169    /// Returns a normalized vector or the zero vector when too small.
170    fn normalize_or_zero(&self, epsilon: T) -> Self {
171        self.try_normalize(epsilon).unwrap_or_else(Self::zero)
172    }
173
174    /// Normalizes using a precomputed inverse length (e.g., from rsqrt).
175    fn normalize_with_inv_len(&self, inv_len: T) -> Self {
176        *self * inv_len
177    }
178
179    /// Normalizes with precomputed length squared and inverse length.
180    fn try_normalize_with_inv_len(&self, len_sq: T, inv_len: T, epsilon: T) -> Option<Self> {
181        if len_sq <= epsilon * epsilon {
182            None
183        } else {
184            Some(*self * inv_len)
185        }
186    }
187}
188
189macro_rules! implVecScalar {
190    ($vecName:ident, $scalar:ident) => {
191        impl Mul<$vecName<$scalar>> for $scalar {
192            type Output = $vecName<$scalar>;
193
194            fn mul(self, rhs: $vecName<$scalar>) -> Self::Output {
195                $vecName::mul_vs(&rhs, self)
196            }
197        }
198    };
199}
200
201macro_rules! vector_field_doc {
202    (x) => { "X component." };
203    (y) => { "Y component." };
204    (z) => { "Z component." };
205    (w) => { "W component." };
206}
207
208macro_rules! implVector {
209    ($(#[$meta:meta])* $vecName:ident, $($field:ident)*) => {
210        $(#[$meta])*
211        #[repr(C)]
212        #[derive(Copy, Clone, Debug, Default)]
213        pub struct $vecName<T> { $(#[doc = vector_field_doc!($field)] pub $field: T),* }
214
215        impl<T: Scalar> $vecName<T> {
216            /// Creates a vector from components.
217            pub fn new($($field:T),*) -> Self { Self { $($field: $field),* } }
218        }
219
220        impl<T: Scalar> Vector<T> for $vecName<T> {
221            fn zero() -> Self { Self { $($field: <T as Zero>::zero()),* } }
222            fn dot  (l: &Self, r: &Self) -> T { $(l.$field * r.$field +)* <T as Zero>::zero() }
223            fn add_vv(l: &Self, r: &Self) -> Self { Self::new($(l.$field + r.$field),*) }
224            fn sub_vv(l: &Self, r: &Self) -> Self { Self::new($(l.$field - r.$field),*) }
225            fn mul_vv(l: &Self, r: &Self) -> Self { Self::new($(l.$field * r.$field),*) }
226            fn div_vv(l: &Self, r: &Self) -> Self { Self::new($(l.$field / r.$field),*) }
227            fn mul_vs(l: &Self, r: T) -> Self { Self::new($(l.$field * r),*) }
228            fn div_vs(l: &Self, r: T) -> Self { Self::new($(l.$field / r),*) }
229            fn rem_vv(l: &Self, r: &Self) -> Self { Self::new($(l.$field % r.$field),*) }
230            fn min(l: &Self, r: &Self) -> Self { Self::new($(T::min(l.$field, r.$field)),*) }
231            fn max(l: &Self, r: &Self) -> Self { Self::new($(T::max(l.$field, r.$field)),*) }
232        }
233
234        impl<T> Add for $vecName<T> where T: Scalar {
235            type Output = $vecName<T>;
236
237            fn add(self, rhs: Self) -> Self::Output {
238                Self { $($field: self.$field + rhs.$field),* }
239            }
240        }
241
242        impl<T> Sub for $vecName<T> where T: Scalar {
243            type Output = $vecName<T>;
244
245            fn sub(self, rhs: Self) -> Self::Output {
246                Self { $($field: self.$field - rhs.$field),* }
247            }
248        }
249
250        impl<T> Mul for $vecName<T> where T: Scalar {
251            type Output = $vecName<T>;
252
253            fn mul(self, rhs: Self) -> Self::Output {
254                Self { $($field: self.$field * rhs.$field),* }
255            }
256        }
257
258        impl<T> Mul<T> for $vecName<T> where T:Scalar {
259            type Output = $vecName<T>;
260
261            fn mul(self, rhs: T) -> Self::Output {
262                Self { $($field: self.$field * rhs),* }
263            }
264        }
265
266        implVecScalar!($vecName, f32);
267        implVecScalar!($vecName, f64);
268        implVecScalar!($vecName, i32);
269        implVecScalar!($vecName, i64);
270
271        impl<T> Div for $vecName<T> where T:Scalar {
272            type Output = $vecName<T>;
273
274            fn div(self, rhs: Self) -> Self::Output {
275                Self { $($field: self.$field / rhs.$field),* }
276            }
277        }
278
279        impl<T> Div<T> for $vecName<T> where T:Scalar {
280            type Output = $vecName<T>;
281
282            fn div(self, rhs: T) -> Self::Output {
283                Self { $($field: self.$field / rhs),* }
284            }
285        }
286
287        impl<T> Rem for $vecName<T> where T: Scalar {
288            type Output = $vecName<T>;
289
290            fn rem(self, rhs: $vecName<T>) -> Self::Output {
291                Self { $($field: self.$field % rhs.$field),* }
292            }
293        }
294
295        impl<T> Rem<T> for $vecName<T> where T:Scalar {
296            type Output = $vecName<T>;
297
298            fn rem(self, rhs: T) -> Self::Output {
299                Self { $($field: self.$field % rhs),* }
300            }
301        }
302
303        impl<T: Scalar> Neg for $vecName<T> {
304            type Output = $vecName<T>;
305            fn neg(self) -> Self::Output {
306                Self { $($field: -self.$field),* }
307            }
308        }
309    };
310}
311
312macro_rules! implFloatVector {
313    ($vecName:ident) => {
314        impl<T: FloatScalar> FloatVector<T> for $vecName<T> {
315            fn length(&self) -> T {
316                Self::dot(self, self).tsqrt()
317            }
318            fn normalize(&self) -> Self {
319                let len = Self::length(self);
320                *self / len
321            }
322            fn distance(l: &Self, r: &Self) -> T {
323                Self::length(&(*r - *l))
324            }
325        }
326    };
327}
328
329/// Trait for computing the cross product of 3D vectors.
330///
331/// The cross product is only defined for 3D vectors and produces
332/// a vector perpendicular to both input vectors.
333pub trait CrossProduct {
334    /// Computes the cross product of two vectors.
335    ///
336    /// For 3D vectors **v** and **w**:
337    /// ```text
338    /// v × w = (v₂w₃ - v₃w₂, v₃w₁ - v₁w₃, v₁w₂ - v₂w₁)
339    /// ```
340    ///
341    /// The resulting vector is perpendicular to both input vectors,
342    /// with magnitude ||v|| ||w|| sin(θ), where θ is the angle between them.
343    fn cross(l: &Self, r: &Self) -> Self;
344}
345
346implVector!(
347    /// A 2D vector with x and y components.
348    ///
349    /// # Examples
350    /// ```
351    /// use rs_math3d::vector::Vector2;
352    /// 
353    /// let v = Vector2::new(3.0, 4.0);
354    /// assert_eq!(v.x, 3.0);
355    /// assert_eq!(v.y, 4.0);
356    /// ```
357    Vector2,
358    x y
359);
360
361implVector!(
362    /// A 3D vector with x, y, and z components.
363    ///
364    /// # Examples
365    /// ```
366    /// use rs_math3d::vector::{Vector3, CrossProduct};
367    /// 
368    /// let v1 = Vector3::new(1.0, 0.0, 0.0);
369    /// let v2 = Vector3::new(0.0, 1.0, 0.0);
370    /// let cross = Vector3::cross(&v1, &v2);
371    /// // Result is (0, 0, 1) - the z-axis
372    /// ```
373    Vector3,
374    x y z
375);
376
377implVector!(
378    /// A 4D vector with x, y, z, and w components.
379    ///
380    /// Often used for homogeneous coordinates in 3D graphics.
381    ///
382    /// # Examples
383    /// ```
384    /// use rs_math3d::vector::Vector4;
385    /// 
386    /// let v = Vector4::new(1.0, 2.0, 3.0, 1.0);
387    /// // w=1 for positions, w=0 for directions
388    /// ```
389    Vector4,
390    x y z w
391);
392
393implFloatVector!(Vector2);
394implFloatVector!(Vector3);
395implFloatVector!(Vector4);
396
397impl<T> CrossProduct for Vector3<T>
398where
399    T: Scalar,
400{
401    /// Computes the cross product of two 3D vectors.
402    ///
403    /// The cross product **v** × **w** produces a vector perpendicular
404    /// to both **v** and **w**, following the right-hand rule.
405    ///
406    /// # Properties
407    /// - Anti-commutative: **v** × **w** = -(**w** × **v**)
408    /// - Distributive: **v** × (**w** + **u**) = **v** × **w** + **v** × **u**
409    /// - **v** × **v** = **0**
410    fn cross(l: &Vector3<T>, r: &Vector3<T>) -> Vector3<T> {
411        Vector3::new(
412            l.y * r.z - l.z * r.y,
413            l.z * r.x - l.x * r.z,
414            l.x * r.y - l.y * r.x,
415        )
416    }
417}
418
419/// Trait for 2D swizzle operations on vectors.
420///
421/// Provides methods to rearrange and duplicate vector components
422/// into 2D vectors using familiar shader-style syntax.
423pub trait Swizzle2<T: Scalar> {
424    /// Returns a vector with components (x, x).
425    fn xx(&self) -> Vector2<T>;
426    /// Returns a vector with components (x, y).
427    fn xy(&self) -> Vector2<T>;
428    /// Returns a vector with components (x, z).
429    fn xz(&self) -> Vector2<T>;
430    /// Returns a vector with components (y, x).
431    fn yx(&self) -> Vector2<T>;
432    /// Returns a vector with components (y, y).
433    fn yy(&self) -> Vector2<T>;
434    /// Returns a vector with components (y, z).
435    fn yz(&self) -> Vector2<T>;
436    /// Returns a vector with components (z, x).
437    fn zx(&self) -> Vector2<T>;
438    /// Returns a vector with components (z, y).
439    fn zy(&self) -> Vector2<T>;
440    /// Returns a vector with components (z, z).
441    fn zz(&self) -> Vector2<T>;
442}
443
444macro_rules! swizzle_field {
445    ($s:ident, x) => {
446        $s.x
447    };
448    ($s:ident, y) => {
449        $s.y
450    };
451    ($s:ident, z) => {
452        $s.z
453    };
454    ($s:ident, zero) => {
455        <T as Zero>::zero()
456    };
457}
458
459macro_rules! impl_swizzle2 {
460    ($vec:ident, $x:tt, $y:tt, $z:tt) => {
461        impl<T: Scalar> Swizzle2<T> for $vec<T> {
462            fn xx(&self) -> Vector2<T> {
463                Vector2::new(swizzle_field!(self, $x), swizzle_field!(self, $x))
464            }
465            fn xy(&self) -> Vector2<T> {
466                Vector2::new(swizzle_field!(self, $x), swizzle_field!(self, $y))
467            }
468            fn xz(&self) -> Vector2<T> {
469                Vector2::new(swizzle_field!(self, $x), swizzle_field!(self, $z))
470            }
471            fn yx(&self) -> Vector2<T> {
472                Vector2::new(swizzle_field!(self, $y), swizzle_field!(self, $x))
473            }
474            fn yy(&self) -> Vector2<T> {
475                Vector2::new(swizzle_field!(self, $y), swizzle_field!(self, $y))
476            }
477            fn yz(&self) -> Vector2<T> {
478                Vector2::new(swizzle_field!(self, $y), swizzle_field!(self, $z))
479            }
480            fn zx(&self) -> Vector2<T> {
481                Vector2::new(swizzle_field!(self, $z), swizzle_field!(self, $x))
482            }
483            fn zy(&self) -> Vector2<T> {
484                Vector2::new(swizzle_field!(self, $z), swizzle_field!(self, $y))
485            }
486            fn zz(&self) -> Vector2<T> {
487                Vector2::new(swizzle_field!(self, $z), swizzle_field!(self, $z))
488            }
489        }
490    };
491}
492
493impl_swizzle2!(Vector2, x, y, zero);
494impl_swizzle2!(Vector3, x, y, z);
495impl_swizzle2!(Vector4, x, y, z);
496
497/// Trait for 3D swizzle operations on vectors.
498///
499/// Provides methods to rearrange and duplicate vector components
500/// into 3D vectors using familiar shader-style syntax.
501pub trait Swizzle3<T: Scalar> {
502    /// Returns a vector with components (x, x, x).
503    fn xxx(&self) -> Vector3<T>;
504    /// Returns a vector with components (x, x, y).
505    fn xxy(&self) -> Vector3<T>;
506    /// Returns a vector with components (x, x, z).
507    fn xxz(&self) -> Vector3<T>;
508    /// Returns a vector with components (x, y, x).
509    fn xyx(&self) -> Vector3<T>;
510    /// Returns a vector with components (x, y, y).
511    fn xyy(&self) -> Vector3<T>;
512    /// Returns a vector with components (x, y, z).
513    fn xyz(&self) -> Vector3<T>;
514    /// Returns a vector with components (x, z, x).
515    fn xzx(&self) -> Vector3<T>;
516    /// Returns a vector with components (x, z, y).
517    fn xzy(&self) -> Vector3<T>;
518    /// Returns a vector with components (x, z, z).
519    fn xzz(&self) -> Vector3<T>;
520
521    /// Returns a vector with components (y, x, x).
522    fn yxx(&self) -> Vector3<T>;
523    /// Returns a vector with components (y, x, y).
524    fn yxy(&self) -> Vector3<T>;
525    /// Returns a vector with components (y, x, z).
526    fn yxz(&self) -> Vector3<T>;
527    /// Returns a vector with components (y, y, x).
528    fn yyx(&self) -> Vector3<T>;
529    /// Returns a vector with components (y, y, y).
530    fn yyy(&self) -> Vector3<T>;
531    /// Returns a vector with components (y, y, z).
532    fn yyz(&self) -> Vector3<T>;
533    /// Returns a vector with components (y, z, x).
534    fn yzx(&self) -> Vector3<T>;
535    /// Returns a vector with components (y, z, y).
536    fn yzy(&self) -> Vector3<T>;
537    /// Returns a vector with components (y, z, z).
538    fn yzz(&self) -> Vector3<T>;
539
540    /// Returns a vector with components (z, x, x).
541    fn zxx(&self) -> Vector3<T>;
542    /// Returns a vector with components (z, x, y).
543    fn zxy(&self) -> Vector3<T>;
544    /// Returns a vector with components (z, x, z).
545    fn zxz(&self) -> Vector3<T>;
546    /// Returns a vector with components (z, y, x).
547    fn zyx(&self) -> Vector3<T>;
548    /// Returns a vector with components (z, y, y).
549    fn zyy(&self) -> Vector3<T>;
550    /// Returns a vector with components (z, y, z).
551    fn zyz(&self) -> Vector3<T>;
552    /// Returns a vector with components (z, z, x).
553    fn zzx(&self) -> Vector3<T>;
554    /// Returns a vector with components (z, z, y).
555    fn zzy(&self) -> Vector3<T>;
556    /// Returns a vector with components (z, z, z).
557    fn zzz(&self) -> Vector3<T>;
558}
559
560macro_rules! impl_swizzle3 {
561    ($vec:ident, $x:tt, $y:tt, $z:tt) => {
562        impl<T: Scalar> Swizzle3<T> for $vec<T> {
563            fn xxx(&self) -> Vector3<T> {
564                Vector3::new(swizzle_field!(self, $x), swizzle_field!(self, $x), swizzle_field!(self, $x))
565            }
566            fn xxy(&self) -> Vector3<T> {
567                Vector3::new(swizzle_field!(self, $x), swizzle_field!(self, $x), swizzle_field!(self, $y))
568            }
569            fn xxz(&self) -> Vector3<T> {
570                Vector3::new(swizzle_field!(self, $x), swizzle_field!(self, $x), swizzle_field!(self, $z))
571            }
572            fn xyx(&self) -> Vector3<T> {
573                Vector3::new(swizzle_field!(self, $x), swizzle_field!(self, $y), swizzle_field!(self, $x))
574            }
575            fn xyy(&self) -> Vector3<T> {
576                Vector3::new(swizzle_field!(self, $x), swizzle_field!(self, $y), swizzle_field!(self, $y))
577            }
578            fn xyz(&self) -> Vector3<T> {
579                Vector3::new(swizzle_field!(self, $x), swizzle_field!(self, $y), swizzle_field!(self, $z))
580            }
581            fn xzx(&self) -> Vector3<T> {
582                Vector3::new(swizzle_field!(self, $x), swizzle_field!(self, $z), swizzle_field!(self, $x))
583            }
584            fn xzy(&self) -> Vector3<T> {
585                Vector3::new(swizzle_field!(self, $x), swizzle_field!(self, $z), swizzle_field!(self, $y))
586            }
587            fn xzz(&self) -> Vector3<T> {
588                Vector3::new(swizzle_field!(self, $x), swizzle_field!(self, $z), swizzle_field!(self, $z))
589            }
590
591            fn yxx(&self) -> Vector3<T> {
592                Vector3::new(swizzle_field!(self, $y), swizzle_field!(self, $x), swizzle_field!(self, $x))
593            }
594            fn yxy(&self) -> Vector3<T> {
595                Vector3::new(swizzle_field!(self, $y), swizzle_field!(self, $x), swizzle_field!(self, $y))
596            }
597            fn yxz(&self) -> Vector3<T> {
598                Vector3::new(swizzle_field!(self, $y), swizzle_field!(self, $x), swizzle_field!(self, $z))
599            }
600            fn yyx(&self) -> Vector3<T> {
601                Vector3::new(swizzle_field!(self, $y), swizzle_field!(self, $y), swizzle_field!(self, $x))
602            }
603            fn yyy(&self) -> Vector3<T> {
604                Vector3::new(swizzle_field!(self, $y), swizzle_field!(self, $y), swizzle_field!(self, $y))
605            }
606            fn yyz(&self) -> Vector3<T> {
607                Vector3::new(swizzle_field!(self, $y), swizzle_field!(self, $y), swizzle_field!(self, $z))
608            }
609            fn yzx(&self) -> Vector3<T> {
610                Vector3::new(swizzle_field!(self, $y), swizzle_field!(self, $z), swizzle_field!(self, $x))
611            }
612            fn yzy(&self) -> Vector3<T> {
613                Vector3::new(swizzle_field!(self, $y), swizzle_field!(self, $z), swizzle_field!(self, $y))
614            }
615            fn yzz(&self) -> Vector3<T> {
616                Vector3::new(swizzle_field!(self, $y), swizzle_field!(self, $z), swizzle_field!(self, $z))
617            }
618
619            fn zxx(&self) -> Vector3<T> {
620                Vector3::new(swizzle_field!(self, $z), swizzle_field!(self, $x), swizzle_field!(self, $x))
621            }
622            fn zxy(&self) -> Vector3<T> {
623                Vector3::new(swizzle_field!(self, $z), swizzle_field!(self, $x), swizzle_field!(self, $y))
624            }
625            fn zxz(&self) -> Vector3<T> {
626                Vector3::new(swizzle_field!(self, $z), swizzle_field!(self, $x), swizzle_field!(self, $z))
627            }
628            fn zyx(&self) -> Vector3<T> {
629                Vector3::new(swizzle_field!(self, $z), swizzle_field!(self, $y), swizzle_field!(self, $x))
630            }
631            fn zyy(&self) -> Vector3<T> {
632                Vector3::new(swizzle_field!(self, $z), swizzle_field!(self, $y), swizzle_field!(self, $y))
633            }
634            fn zyz(&self) -> Vector3<T> {
635                Vector3::new(swizzle_field!(self, $z), swizzle_field!(self, $y), swizzle_field!(self, $z))
636            }
637            fn zzx(&self) -> Vector3<T> {
638                Vector3::new(swizzle_field!(self, $z), swizzle_field!(self, $z), swizzle_field!(self, $x))
639            }
640            fn zzy(&self) -> Vector3<T> {
641                Vector3::new(swizzle_field!(self, $z), swizzle_field!(self, $z), swizzle_field!(self, $y))
642            }
643            fn zzz(&self) -> Vector3<T> {
644                Vector3::new(swizzle_field!(self, $z), swizzle_field!(self, $z), swizzle_field!(self, $z))
645            }
646        }
647    };
648}
649
650impl_swizzle3!(Vector3, x, y, z);
651impl_swizzle3!(Vector4, x, y, z);
652
653#[cfg(test)]
654mod tests {
655    use super::*;
656    use crate::scalar::{FloatScalar, EPS_F32};
657    
658    #[test]
659    pub fn test() {
660        let f1 = Vector2 { x: 1.0, y: 2.0 };
661        let f2 = Vector2 { x: 3.0, y: 4.0 };
662        let out = f1 + f2;
663        assert_eq!(out.x, 4.0);
664        assert_eq!(out.y, 6.0);
665
666        let f22: Vector2<f32> = 2.0 * f2;
667        let f23: Vector2<f32> = f2 * 2.0;
668
669        assert_eq!(f22.x, 6.0);
670        assert_eq!(f22.y, 8.0);
671        assert_eq!(f23.x, f22.x);
672        assert_eq!(f23.y, f22.y);
673    }
674
675    #[test]
676    fn test_vector_normalization() {
677        // Test normal case
678        let v = Vector3::<f32>::new(3.0, 4.0, 0.0);
679        let nv = v.normalize();
680        let len = nv.length();
681        assert!((len - 1.0).abs() < f32::epsilon());
682        
683        // Test zero vector normalization (should handle gracefully)
684        let v_zero = Vector3::<f32>::new(0.0, 0.0, 0.0);
685        let nv_zero = v_zero.normalize();
686        // When normalizing zero vector, we get NaN or Inf components
687        // The current implementation divides by zero, resulting in inf/nan
688        assert!(nv_zero.x.is_infinite() || nv_zero.x.is_nan());
689        
690        // Test already normalized vector
691        let v_unit = Vector3::<f32>::new(1.0, 0.0, 0.0);
692        let nv_unit = v_unit.normalize();
693        assert!((nv_unit.x - 1.0).abs() < f32::epsilon());
694        assert!((nv_unit.y).abs() < f32::epsilon());
695        assert!((nv_unit.z).abs() < f32::epsilon());
696    }
697
698    #[test]
699    fn test_vector_try_normalize() {
700        let v = Vector3::<f32>::new(3.0, 4.0, 0.0);
701        let nv = v.try_normalize(EPS_F32).expect("should normalize");
702        assert!((nv.length() - 1.0).abs() < 0.001);
703
704        let zero = Vector3::<f32>::zero();
705        assert!(zero.try_normalize(EPS_F32).is_none());
706        let zero_norm = zero.normalize_or_zero(EPS_F32);
707        assert_eq!(zero_norm.x, 0.0);
708        assert_eq!(zero_norm.y, 0.0);
709        assert_eq!(zero_norm.z, 0.0);
710
711        let len_sq = v.length_squared();
712        let inv_len = 1.0f32 / len_sq.tsqrt();
713        let nv_fast = v.normalize_with_inv_len(inv_len);
714        assert!((nv_fast.length() - 1.0).abs() < 0.001);
715
716        let nv_fast_try = v
717            .try_normalize_with_inv_len(len_sq, inv_len, EPS_F32)
718            .expect("should normalize");
719        assert!((nv_fast_try.length() - 1.0).abs() < 0.001);
720        assert!(zero
721            .try_normalize_with_inv_len(0.0, 0.0, EPS_F32)
722            .is_none());
723    }
724
725    #[test]
726    fn test_vector_length() {
727        let v2 = Vector2::<f32>::new(3.0, 4.0);
728        assert!((v2.length() - 5.0).abs() < f32::epsilon());
729        
730        let v3 = Vector3::<f32>::new(2.0, 3.0, 6.0);
731        assert!((v3.length() - 7.0).abs() < f32::epsilon());
732        
733        let v4 = Vector4::<f32>::new(1.0, 2.0, 2.0, 0.0);
734        assert!((v4.length() - 3.0).abs() < f32::epsilon());
735        
736        // Test zero vector
737        let v_zero = Vector3::<f32>::zero();
738        assert_eq!(v_zero.length(), 0.0);
739    }
740
741    #[test]
742    fn test_vector_dot_product() {
743        let v1 = Vector3::<f32>::new(1.0, 2.0, 3.0);
744        let v2 = Vector3::<f32>::new(4.0, 5.0, 6.0);
745        let dot = Vector3::dot(&v1, &v2);
746        assert_eq!(dot, 32.0); // 1*4 + 2*5 + 3*6 = 32
747        
748        // Test orthogonal vectors
749        let v_ortho1 = Vector3::<f32>::new(1.0, 0.0, 0.0);
750        let v_ortho2 = Vector3::<f32>::new(0.0, 1.0, 0.0);
751        assert_eq!(Vector3::dot(&v_ortho1, &v_ortho2), 0.0);
752        
753        // Test dot product with itself equals length squared
754        let self_dot = Vector3::dot(&v1, &v1);
755        let len_squared = v1.length() * v1.length();
756        assert!((self_dot - len_squared).abs() < 0.0001);
757    }
758
759    #[test]
760    fn test_vector_cross_product() {
761        // Test standard basis vectors
762        let x = Vector3::<f32>::new(1.0, 0.0, 0.0);
763        let y = Vector3::<f32>::new(0.0, 1.0, 0.0);
764        let z = Vector3::<f32>::new(0.0, 0.0, 1.0);
765        
766        let x_cross_y = Vector3::cross(&x, &y);
767        assert!((x_cross_y.x - z.x).abs() < f32::epsilon());
768        assert!((x_cross_y.y - z.y).abs() < f32::epsilon());
769        assert!((x_cross_y.z - z.z).abs() < f32::epsilon());
770        
771        let y_cross_z = Vector3::cross(&y, &z);
772        assert!((y_cross_z.x - x.x).abs() < f32::epsilon());
773        assert!((y_cross_z.y - x.y).abs() < f32::epsilon());
774        assert!((y_cross_z.z - x.z).abs() < f32::epsilon());
775        
776        let z_cross_x = Vector3::cross(&z, &x);
777        assert!((z_cross_x.x - y.x).abs() < f32::epsilon());
778        assert!((z_cross_x.y - y.y).abs() < f32::epsilon());
779        assert!((z_cross_x.z - y.z).abs() < f32::epsilon());
780        
781        // Test anti-commutativity: a × b = -(b × a)
782        let a = Vector3::<f32>::new(1.0, 2.0, 3.0);
783        let b = Vector3::<f32>::new(4.0, 5.0, 6.0);
784        let a_cross_b = Vector3::cross(&a, &b);
785        let b_cross_a = Vector3::cross(&b, &a);
786        assert!((a_cross_b.x + b_cross_a.x).abs() < f32::epsilon());
787        assert!((a_cross_b.y + b_cross_a.y).abs() < f32::epsilon());
788        assert!((a_cross_b.z + b_cross_a.z).abs() < f32::epsilon());
789        
790        // Test cross product with itself is zero
791        let self_cross = Vector3::cross(&a, &a);
792        assert!(self_cross.x.abs() < f32::epsilon());
793        assert!(self_cross.y.abs() < f32::epsilon());
794        assert!(self_cross.z.abs() < f32::epsilon());
795    }
796
797    #[test]
798    fn test_vector_distance() {
799        let v1 = Vector3::<f32>::new(1.0, 2.0, 3.0);
800        let v2 = Vector3::<f32>::new(4.0, 6.0, 3.0);
801        let dist = Vector3::distance(&v1, &v2);
802        assert!((dist - 5.0).abs() < f32::epsilon()); // sqrt(9 + 16 + 0) = 5
803        
804        // Distance to itself should be zero
805        let self_dist = Vector3::distance(&v1, &v1);
806        assert!(self_dist.abs() < f32::epsilon());
807    }
808
809    #[test]
810    fn test_vector_min_max() {
811        let v1 = Vector3::<f32>::new(1.0, 5.0, 3.0);
812        let v2 = Vector3::<f32>::new(4.0, 2.0, 6.0);
813        
814        let v_min = Vector3::min(&v1, &v2);
815        assert_eq!(v_min.x, 1.0);
816        assert_eq!(v_min.y, 2.0);
817        assert_eq!(v_min.z, 3.0);
818        
819        let v_max = Vector3::max(&v1, &v2);
820        assert_eq!(v_max.x, 4.0);
821        assert_eq!(v_max.y, 5.0);
822        assert_eq!(v_max.z, 6.0);
823    }
824
825    #[test]
826    fn test_vector_arithmetic() {
827        let v1 = Vector3::<f32>::new(1.0, 2.0, 3.0);
828        let v2 = Vector3::<f32>::new(4.0, 5.0, 6.0);
829        
830        // Addition
831        let sum = v1 + v2;
832        assert_eq!(sum.x, 5.0);
833        assert_eq!(sum.y, 7.0);
834        assert_eq!(sum.z, 9.0);
835        
836        // Subtraction
837        let diff = v2 - v1;
838        assert_eq!(diff.x, 3.0);
839        assert_eq!(diff.y, 3.0);
840        assert_eq!(diff.z, 3.0);
841        
842        // Component-wise multiplication
843        let prod = v1 * v2;
844        assert_eq!(prod.x, 4.0);
845        assert_eq!(prod.y, 10.0);
846        assert_eq!(prod.z, 18.0);
847        
848        // Component-wise division
849        let div = v2 / v1;
850        assert_eq!(div.x, 4.0);
851        assert_eq!(div.y, 2.5);
852        assert_eq!(div.z, 2.0);
853        
854        // Scalar multiplication
855        let scaled = v1 * 2.0;
856        assert_eq!(scaled.x, 2.0);
857        assert_eq!(scaled.y, 4.0);
858        assert_eq!(scaled.z, 6.0);
859        
860        // Scalar division
861        let divided = v2 / 2.0;
862        assert_eq!(divided.x, 2.0);
863        assert_eq!(divided.y, 2.5);
864        assert_eq!(divided.z, 3.0);
865        
866        // Negation
867        let neg = -v1;
868        assert_eq!(neg.x, -1.0);
869        assert_eq!(neg.y, -2.0);
870        assert_eq!(neg.z, -3.0);
871    }
872
873    #[test]
874    fn test_swizzle_operations() {
875        let v2 = Vector2::<f32>::new(1.0, 2.0);
876        
877        assert_eq!(v2.xx().x, 1.0);
878        assert_eq!(v2.xx().y, 1.0);
879        
880        assert_eq!(v2.xy().x, 1.0);
881        assert_eq!(v2.xy().y, 2.0);
882        
883        assert_eq!(v2.yx().x, 2.0);
884        assert_eq!(v2.yx().y, 1.0);
885        
886        assert_eq!(v2.yy().x, 2.0);
887        assert_eq!(v2.yy().y, 2.0);
888
889        let v2_xz = v2.xz();
890        assert_eq!(v2_xz.x, 1.0);
891        assert_eq!(v2_xz.y, 0.0);
892        
893        let v3 = Vector3::<f32>::new(1.0, 2.0, 3.0);
894        
895        assert_eq!(v3.xz().x, 1.0);
896        assert_eq!(v3.xz().y, 3.0);
897        
898        assert_eq!(v3.zy().x, 3.0);
899        assert_eq!(v3.zy().y, 2.0);
900        
901        let v3_swizzle = v3.zyx();
902        assert_eq!(v3_swizzle.x, 3.0);
903        assert_eq!(v3_swizzle.y, 2.0);
904        assert_eq!(v3_swizzle.z, 1.0);
905
906        let v4 = Vector4::<f32>::new(1.0, 2.0, 3.0, 4.0);
907        let v4_xz = v4.xz();
908        assert_eq!(v4_xz.x, 1.0);
909        assert_eq!(v4_xz.y, 3.0);
910        let v4_swizzle = v4.zyx();
911        assert_eq!(v4_swizzle.x, 3.0);
912        assert_eq!(v4_swizzle.y, 2.0);
913        assert_eq!(v4_swizzle.z, 1.0);
914    }
915
916    #[test]
917    fn test_vector_rem_operation() {
918        let v1 = Vector3::<i32>::new(10, 15, 20);
919        let v2 = Vector3::<i32>::new(3, 4, 6);
920        
921        let rem = v1 % v2;
922        assert_eq!(rem.x, 1); // 10 % 3 = 1
923        assert_eq!(rem.y, 3); // 15 % 4 = 3
924        assert_eq!(rem.z, 2); // 20 % 6 = 2
925        
926        let v3 = Vector3::<i32>::new(10, 15, 20);
927        let rem_scalar = v3 % 7;
928        assert_eq!(rem_scalar.x, 3); // 10 % 7 = 3
929        assert_eq!(rem_scalar.y, 1); // 15 % 7 = 1
930        assert_eq!(rem_scalar.z, 6); // 20 % 7 = 6
931    }
932}