Skip to main content

glam/f32/
vec3.rs

1// Generated from vec.rs.tera template. Edit the template, not the generated file.
2
3use crate::{f32::math, BVec3, BVec3A, Quat, Vec2, Vec3A, Vec4};
4
5use core::fmt;
6use core::iter::{Product, Sum};
7use core::ops::*;
8
9#[cfg(feature = "zerocopy-08")]
10use zerocopy_derive_08::*;
11
12/// Creates a 3-dimensional vector.
13#[inline(always)]
14#[must_use]
15pub const fn vec3(x: f32, y: f32, z: f32) -> Vec3 {
16    Vec3::new(x, y, z)
17}
18
19/// A 3-dimensional vector.
20#[derive(Clone, Copy, PartialEq)]
21#[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))]
22#[cfg_attr(
23    feature = "zerocopy-08",
24    derive(FromBytes, Immutable, IntoBytes, KnownLayout)
25)]
26#[repr(C)]
27#[cfg_attr(target_arch = "spirv", rust_gpu::vector::v1)]
28pub struct Vec3 {
29    pub x: f32,
30    pub y: f32,
31    pub z: f32,
32}
33
34impl Vec3 {
35    /// All zeroes.
36    pub const ZERO: Self = Self::splat(0.0);
37
38    /// All ones.
39    pub const ONE: Self = Self::splat(1.0);
40
41    /// All negative ones.
42    pub const NEG_ONE: Self = Self::splat(-1.0);
43
44    /// All `f32::MIN`.
45    pub const MIN: Self = Self::splat(f32::MIN);
46
47    /// All `f32::MAX`.
48    pub const MAX: Self = Self::splat(f32::MAX);
49
50    /// All `f32::NAN`.
51    pub const NAN: Self = Self::splat(f32::NAN);
52
53    /// All `f32::INFINITY`.
54    pub const INFINITY: Self = Self::splat(f32::INFINITY);
55
56    /// All `f32::NEG_INFINITY`.
57    pub const NEG_INFINITY: Self = Self::splat(f32::NEG_INFINITY);
58
59    /// A unit vector pointing along the positive X axis.
60    pub const X: Self = Self::new(1.0, 0.0, 0.0);
61
62    /// A unit vector pointing along the positive Y axis.
63    pub const Y: Self = Self::new(0.0, 1.0, 0.0);
64
65    /// A unit vector pointing along the positive Z axis.
66    pub const Z: Self = Self::new(0.0, 0.0, 1.0);
67
68    /// A unit vector pointing along the negative X axis.
69    pub const NEG_X: Self = Self::new(-1.0, 0.0, 0.0);
70
71    /// A unit vector pointing along the negative Y axis.
72    pub const NEG_Y: Self = Self::new(0.0, -1.0, 0.0);
73
74    /// A unit vector pointing along the negative Z axis.
75    pub const NEG_Z: Self = Self::new(0.0, 0.0, -1.0);
76
77    /// The unit axes.
78    pub const AXES: [Self; 3] = [Self::X, Self::Y, Self::Z];
79
80    /// Vec3 uses Rust Portable SIMD
81    pub const USES_CORE_SIMD: bool = false;
82    /// Vec3 uses Arm NEON
83    pub const USES_NEON: bool = false;
84    /// Vec3 uses scalar math
85    pub const USES_SCALAR_MATH: bool = true;
86    /// Vec3 uses Intel SSE2
87    pub const USES_SSE2: bool = false;
88    /// Vec3 uses WebAssembly 128-bit SIMD
89    pub const USES_WASM_SIMD: bool = false;
90    #[deprecated(since = "0.31.0", note = "Renamed to USES_WASM_SIMD")]
91    pub const USES_WASM32_SIMD: bool = false;
92
93    /// Creates a new vector.
94    #[inline(always)]
95    #[must_use]
96    pub const fn new(x: f32, y: f32, z: f32) -> Self {
97        Self { x, y, z }
98    }
99
100    /// Creates a vector with all elements set to `v`.
101    #[inline]
102    #[must_use]
103    pub const fn splat(v: f32) -> Self {
104        Self::new(v, v, v)
105    }
106
107    /// Returns a vector containing each element of `self` modified by a mapping function `f`.
108    #[inline]
109    #[must_use]
110    pub fn map<F>(self, mut f: F) -> Self
111    where
112        F: FnMut(f32) -> f32,
113    {
114        Self::new(f(self.x), f(self.y), f(self.z))
115    }
116
117    /// Creates a vector from the elements in `if_true` and `if_false`, selecting which to use
118    /// for each element of `self`.
119    ///
120    /// A true element in the mask uses the corresponding element from `if_true`, and false
121    /// uses the element from `if_false`.
122    #[inline]
123    #[must_use]
124    pub fn select(mask: BVec3, if_true: Self, if_false: Self) -> Self {
125        Self::new(
126            if mask.test(0) { if_true.x } else { if_false.x },
127            if mask.test(1) { if_true.y } else { if_false.y },
128            if mask.test(2) { if_true.z } else { if_false.z },
129        )
130    }
131
132    /// Creates a new vector from an array.
133    #[inline]
134    #[must_use]
135    pub const fn from_array(a: [f32; 3]) -> Self {
136        Self::new(a[0], a[1], a[2])
137    }
138
139    /// Converts `self` to `[x, y, z]`
140    #[inline]
141    #[must_use]
142    pub const fn to_array(&self) -> [f32; 3] {
143        [self.x, self.y, self.z]
144    }
145
146    /// Creates a vector from the first 3 values in `slice`.
147    ///
148    /// # Panics
149    ///
150    /// Panics if `slice` is less than 3 elements long.
151    #[inline]
152    #[must_use]
153    pub const fn from_slice(slice: &[f32]) -> Self {
154        assert!(slice.len() >= 3);
155        Self::new(slice[0], slice[1], slice[2])
156    }
157
158    /// Writes the elements of `self` to the first 3 elements in `slice`.
159    ///
160    /// # Panics
161    ///
162    /// Panics if `slice` is less than 3 elements long.
163    #[inline]
164    pub fn write_to_slice(self, slice: &mut [f32]) {
165        slice[..3].copy_from_slice(&self.to_array());
166    }
167
168    /// Internal method for creating a 3D vector from a 4D vector, discarding `w`.
169    #[allow(dead_code)]
170    #[inline]
171    #[must_use]
172    pub(crate) fn from_vec4(v: Vec4) -> Self {
173        Self::new(v.x, v.y, v.z)
174    }
175
176    /// Creates a 4D vector from `self` and the given `w` value.
177    #[inline]
178    #[must_use]
179    pub fn extend(self, w: f32) -> Vec4 {
180        Vec4::new(self.x, self.y, self.z, w)
181    }
182
183    /// Creates a 2D vector from the `x` and `y` elements of `self`, discarding `z`.
184    ///
185    /// Truncation may also be performed by using [`self.xy()`][crate::swizzles::Vec3Swizzles::xy()].
186    #[inline]
187    #[must_use]
188    pub fn truncate(self) -> Vec2 {
189        use crate::swizzles::Vec3Swizzles;
190        self.xy()
191    }
192
193    /// Projects a homogeneous coordinate to 3D space by performing perspective divide.
194    ///
195    /// # Panics
196    ///
197    /// Will panic if `v.w` is `0` when `glam_assert` is enabled.
198    #[inline]
199    #[must_use]
200    pub fn from_homogeneous(v: Vec4) -> Self {
201        glam_assert!(v.w != 0.0);
202        Self::from_vec4(v) / v.w
203    }
204
205    /// Creates a homogeneous coordinate from `self`, equivalent to `self.extend(1.0)`.
206    #[inline]
207    #[must_use]
208    pub fn to_homogeneous(self) -> Vec4 {
209        self.extend(1.0)
210    }
211
212    // Converts `self` to a `Vec3A`.
213    #[inline]
214    #[must_use]
215    pub fn to_vec3a(self) -> Vec3A {
216        Vec3A::from(self)
217    }
218
219    /// Creates a 3D vector from `self` with the given value of `x`.
220    #[inline]
221    #[must_use]
222    pub fn with_x(mut self, x: f32) -> Self {
223        self.x = x;
224        self
225    }
226
227    /// Creates a 3D vector from `self` with the given value of `y`.
228    #[inline]
229    #[must_use]
230    pub fn with_y(mut self, y: f32) -> Self {
231        self.y = y;
232        self
233    }
234
235    /// Creates a 3D vector from `self` with the given value of `z`.
236    #[inline]
237    #[must_use]
238    pub fn with_z(mut self, z: f32) -> Self {
239        self.z = z;
240        self
241    }
242
243    /// Computes the dot product of `self` and `rhs`.
244    #[inline]
245    #[must_use]
246    pub fn dot(self, rhs: Self) -> f32 {
247        (self.x * rhs.x) + (self.y * rhs.y) + (self.z * rhs.z)
248    }
249
250    /// Returns a vector where every component is the dot product of `self` and `rhs`.
251    #[inline]
252    #[must_use]
253    pub fn dot_into_vec(self, rhs: Self) -> Self {
254        Self::splat(self.dot(rhs))
255    }
256
257    /// Computes the cross product of `self` and `rhs`.
258    #[inline]
259    #[must_use]
260    pub fn cross(self, rhs: Self) -> Self {
261        Self::new(
262            self.y * rhs.z - rhs.y * self.z,
263            self.z * rhs.x - rhs.z * self.x,
264            self.x * rhs.y - rhs.x * self.y,
265        )
266    }
267
268    /// Returns a vector containing the minimum values for each element of `self` and `rhs`.
269    ///
270    /// In other words this computes `[min(x, rhs.x), min(self.y, rhs.y), ..]`.
271    ///
272    /// NaN propogation does not follow IEEE 754-2008 semantics for minNum and may differ on
273    /// different SIMD architectures.
274    #[inline]
275    #[must_use]
276    pub fn min(self, rhs: Self) -> Self {
277        Self::new(
278            if self.x < rhs.x { self.x } else { rhs.x },
279            if self.y < rhs.y { self.y } else { rhs.y },
280            if self.z < rhs.z { self.z } else { rhs.z },
281        )
282    }
283
284    /// Returns a vector containing the maximum values for each element of `self` and `rhs`.
285    ///
286    /// In other words this computes `[max(self.x, rhs.x), max(self.y, rhs.y), ..]`.
287    ///
288    /// NaN propogation does not follow IEEE 754-2008 semantics for maxNum and may differ on
289    /// different SIMD architectures.
290    #[inline]
291    #[must_use]
292    pub fn max(self, rhs: Self) -> Self {
293        Self::new(
294            if self.x > rhs.x { self.x } else { rhs.x },
295            if self.y > rhs.y { self.y } else { rhs.y },
296            if self.z > rhs.z { self.z } else { rhs.z },
297        )
298    }
299
300    /// Component-wise clamping of values, similar to [`f32::clamp`].
301    ///
302    /// Each element in `min` must be less-or-equal to the corresponding element in `max`.
303    ///
304    /// NaN propogation does not follow IEEE 754-2008 semantics and may differ on
305    /// different SIMD architectures.
306    ///
307    /// # Panics
308    ///
309    /// Will panic if `min` is greater than `max` when `glam_assert` is enabled.
310    #[inline]
311    #[must_use]
312    pub fn clamp(self, min: Self, max: Self) -> Self {
313        glam_assert!(min.cmple(max).all(), "clamp: expected min <= max");
314        self.max(min).min(max)
315    }
316
317    /// Returns the horizontal minimum of `self`.
318    ///
319    /// In other words this computes `min(x, y, ..)`.
320    ///
321    /// NaN propogation does not follow IEEE 754-2008 semantics and may differ on
322    /// different SIMD architectures.
323    #[inline]
324    #[must_use]
325    pub fn min_element(self) -> f32 {
326        let min = |a, b| if a < b { a } else { b };
327        min(self.x, min(self.y, self.z))
328    }
329
330    /// Returns the horizontal maximum of `self`.
331    ///
332    /// In other words this computes `max(x, y, ..)`.
333    ///
334    /// NaN propogation does not follow IEEE 754-2008 semantics and may differ on
335    /// different SIMD architectures.
336    #[inline]
337    #[must_use]
338    pub fn max_element(self) -> f32 {
339        let max = |a, b| if a > b { a } else { b };
340        max(self.x, max(self.y, self.z))
341    }
342
343    /// Returns the index of the first minimum element of `self`.
344    #[doc(alias = "argmin")]
345    #[inline]
346    #[must_use]
347    pub fn min_position(self) -> usize {
348        let mut min = self.x;
349        let mut index = 0;
350        if self.y < min {
351            min = self.y;
352            index = 1;
353        }
354        if self.z < min {
355            index = 2;
356        }
357        index
358    }
359
360    /// Returns the index of the first maximum element of `self`.
361    #[doc(alias = "argmax")]
362    #[inline]
363    #[must_use]
364    pub fn max_position(self) -> usize {
365        let mut max = self.x;
366        let mut index = 0;
367        if self.y > max {
368            max = self.y;
369            index = 1;
370        }
371        if self.z > max {
372            index = 2;
373        }
374        index
375    }
376
377    /// Returns the sum of all elements of `self`.
378    ///
379    /// In other words, this computes `self.x + self.y + ..`.
380    #[inline]
381    #[must_use]
382    pub fn element_sum(self) -> f32 {
383        self.x + self.y + self.z
384    }
385
386    /// Returns the product of all elements of `self`.
387    ///
388    /// In other words, this computes `self.x * self.y * ..`.
389    #[inline]
390    #[must_use]
391    pub fn element_product(self) -> f32 {
392        self.x * self.y * self.z
393    }
394
395    /// Returns a vector mask containing the result of a `==` comparison for each element of
396    /// `self` and `rhs`.
397    ///
398    /// In other words, this computes `[self.x == rhs.x, self.y == rhs.y, ..]` for all
399    /// elements.
400    #[inline]
401    #[must_use]
402    pub fn cmpeq(self, rhs: Self) -> BVec3 {
403        BVec3::new(self.x.eq(&rhs.x), self.y.eq(&rhs.y), self.z.eq(&rhs.z))
404    }
405
406    /// Returns a vector mask containing the result of a `!=` comparison for each element of
407    /// `self` and `rhs`.
408    ///
409    /// In other words this computes `[self.x != rhs.x, self.y != rhs.y, ..]` for all
410    /// elements.
411    #[inline]
412    #[must_use]
413    pub fn cmpne(self, rhs: Self) -> BVec3 {
414        BVec3::new(self.x.ne(&rhs.x), self.y.ne(&rhs.y), self.z.ne(&rhs.z))
415    }
416
417    /// Returns a vector mask containing the result of a `>=` comparison for each element of
418    /// `self` and `rhs`.
419    ///
420    /// In other words this computes `[self.x >= rhs.x, self.y >= rhs.y, ..]` for all
421    /// elements.
422    #[inline]
423    #[must_use]
424    pub fn cmpge(self, rhs: Self) -> BVec3 {
425        BVec3::new(self.x.ge(&rhs.x), self.y.ge(&rhs.y), self.z.ge(&rhs.z))
426    }
427
428    /// Returns a vector mask containing the result of a `>` comparison for each element of
429    /// `self` and `rhs`.
430    ///
431    /// In other words this computes `[self.x > rhs.x, self.y > rhs.y, ..]` for all
432    /// elements.
433    #[inline]
434    #[must_use]
435    pub fn cmpgt(self, rhs: Self) -> BVec3 {
436        BVec3::new(self.x.gt(&rhs.x), self.y.gt(&rhs.y), self.z.gt(&rhs.z))
437    }
438
439    /// Returns a vector mask containing the result of a `<=` comparison for each element of
440    /// `self` and `rhs`.
441    ///
442    /// In other words this computes `[self.x <= rhs.x, self.y <= rhs.y, ..]` for all
443    /// elements.
444    #[inline]
445    #[must_use]
446    pub fn cmple(self, rhs: Self) -> BVec3 {
447        BVec3::new(self.x.le(&rhs.x), self.y.le(&rhs.y), self.z.le(&rhs.z))
448    }
449
450    /// Returns a vector mask containing the result of a `<` comparison for each element of
451    /// `self` and `rhs`.
452    ///
453    /// In other words this computes `[self.x < rhs.x, self.y < rhs.y, ..]` for all
454    /// elements.
455    #[inline]
456    #[must_use]
457    pub fn cmplt(self, rhs: Self) -> BVec3 {
458        BVec3::new(self.x.lt(&rhs.x), self.y.lt(&rhs.y), self.z.lt(&rhs.z))
459    }
460
461    /// Returns a vector containing the absolute value of each element of `self`.
462    #[inline]
463    #[must_use]
464    pub fn abs(self) -> Self {
465        Self::new(math::abs(self.x), math::abs(self.y), math::abs(self.z))
466    }
467
468    /// Returns a vector with elements representing the sign of `self`.
469    ///
470    /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
471    /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
472    /// - `NAN` if the number is `NAN`
473    #[inline]
474    #[must_use]
475    pub fn signum(self) -> Self {
476        Self::new(
477            math::signum(self.x),
478            math::signum(self.y),
479            math::signum(self.z),
480        )
481    }
482
483    /// Returns a vector with signs of `rhs` and the magnitudes of `self`.
484    #[inline]
485    #[must_use]
486    pub fn copysign(self, rhs: Self) -> Self {
487        Self::new(
488            math::copysign(self.x, rhs.x),
489            math::copysign(self.y, rhs.y),
490            math::copysign(self.z, rhs.z),
491        )
492    }
493
494    /// Returns a bitmask with the lowest 3 bits set to the sign bits from the elements of `self`.
495    ///
496    /// A negative element results in a `1` bit and a positive element in a `0` bit.  Element `x` goes
497    /// into the first lowest bit, element `y` into the second, etc.
498    ///
499    /// An element is negative if it has a negative sign, including -0.0, NaNs with negative sign
500    /// bit and negative infinity.
501    #[inline]
502    #[must_use]
503    pub fn is_negative_bitmask(self) -> u32 {
504        (self.x.is_sign_negative() as u32)
505            | ((self.y.is_sign_negative() as u32) << 1)
506            | ((self.z.is_sign_negative() as u32) << 2)
507    }
508
509    /// Returns a mask indicating which components are negative.
510    ///
511    /// An element is negative if it has a negative sign, including -0.0, NaNs with negative sign
512    /// bit and negative infinity.
513    #[inline]
514    #[must_use]
515    pub fn is_negative_mask(self) -> BVec3 {
516        BVec3::new(
517            self.x.is_sign_negative(),
518            self.y.is_sign_negative(),
519            self.z.is_sign_negative(),
520        )
521    }
522
523    /// Returns `true` if, and only if, all elements are finite.  If any element is either
524    /// `NaN`, positive or negative infinity, this will return `false`.
525    #[inline]
526    #[must_use]
527    pub fn is_finite(self) -> bool {
528        self.x.is_finite() && self.y.is_finite() && self.z.is_finite()
529    }
530
531    /// Performs `is_finite` on each element of self, returning a vector mask of the results.
532    ///
533    /// In other words, this computes `[x.is_finite(), y.is_finite(), ...]`.
534    #[inline]
535    #[must_use]
536    pub fn is_finite_mask(self) -> BVec3 {
537        BVec3::new(self.x.is_finite(), self.y.is_finite(), self.z.is_finite())
538    }
539
540    /// Returns `true` if any elements are `NaN`.
541    #[inline]
542    #[must_use]
543    pub fn is_nan(self) -> bool {
544        self.x.is_nan() || self.y.is_nan() || self.z.is_nan()
545    }
546
547    /// Performs `is_nan` on each element of self, returning a vector mask of the results.
548    ///
549    /// In other words, this computes `[x.is_nan(), y.is_nan(), ...]`.
550    #[inline]
551    #[must_use]
552    pub fn is_nan_mask(self) -> BVec3 {
553        BVec3::new(self.x.is_nan(), self.y.is_nan(), self.z.is_nan())
554    }
555
556    /// Computes the length of `self`.
557    #[doc(alias = "magnitude")]
558    #[inline]
559    #[must_use]
560    pub fn length(self) -> f32 {
561        math::sqrt(self.dot(self))
562    }
563
564    /// Returns `true` if the vector is not the zero vector (also rejects NaN).
565    #[allow(dead_code)]
566    fn is_non_zero(self) -> bool {
567        self.length_squared() > 0.0
568    }
569
570    /// Computes the squared length of `self`.
571    ///
572    /// This is faster than `length()` as it avoids a square root operation.
573    #[doc(alias = "magnitude2")]
574    #[inline]
575    #[must_use]
576    pub fn length_squared(self) -> f32 {
577        self.dot(self)
578    }
579
580    /// Computes `1.0 / length()`.
581    ///
582    /// For valid results, `self` must _not_ be of length zero.
583    #[inline]
584    #[must_use]
585    pub fn length_recip(self) -> f32 {
586        1.0 / self.length()
587    }
588
589    /// Computes the Euclidean distance between two points in space.
590    #[inline]
591    #[must_use]
592    pub fn distance(self, rhs: Self) -> f32 {
593        (self - rhs).length()
594    }
595
596    /// Compute the squared euclidean distance between two points in space.
597    #[inline]
598    #[must_use]
599    pub fn distance_squared(self, rhs: Self) -> f32 {
600        (self - rhs).length_squared()
601    }
602
603    /// Returns the element-wise quotient of [Euclidean division] of `self` by `rhs`.
604    #[inline]
605    #[must_use]
606    pub fn div_euclid(self, rhs: Self) -> Self {
607        Self::new(
608            math::div_euclid(self.x, rhs.x),
609            math::div_euclid(self.y, rhs.y),
610            math::div_euclid(self.z, rhs.z),
611        )
612    }
613
614    /// Returns the element-wise remainder of [Euclidean division] of `self` by `rhs`.
615    ///
616    /// [Euclidean division]: f32::rem_euclid
617    #[inline]
618    #[must_use]
619    pub fn rem_euclid(self, rhs: Self) -> Self {
620        Self::new(
621            math::rem_euclid(self.x, rhs.x),
622            math::rem_euclid(self.y, rhs.y),
623            math::rem_euclid(self.z, rhs.z),
624        )
625    }
626
627    /// Returns `self` normalized to length 1.0.
628    ///
629    /// For valid results, `self` must be finite and _not_ of length zero, nor very close to zero.
630    ///
631    /// See also [`Self::try_normalize()`] and [`Self::normalize_or_zero()`].
632    ///
633    /// # Panics
634    ///
635    /// Will panic if the resulting normalized vector is not finite when `glam_assert` is enabled.
636    #[inline]
637    #[must_use]
638    pub fn normalize(self) -> Self {
639        #[allow(clippy::let_and_return)]
640        let normalized = self.mul(self.length_recip());
641        glam_assert!(normalized.is_finite());
642        normalized
643    }
644
645    /// Returns `self` normalized to length 1.0 if possible, else returns `None`.
646    ///
647    /// In particular, if the input is zero (or very close to zero), or non-finite,
648    /// the result of this operation will be `None`.
649    ///
650    /// See also [`Self::normalize_or_zero()`].
651    #[inline]
652    #[must_use]
653    pub fn try_normalize(self) -> Option<Self> {
654        let rcp = self.length_recip();
655        if rcp.is_finite() && rcp > 0.0 {
656            Some(self * rcp)
657        } else {
658            None
659        }
660    }
661
662    /// Returns `self` normalized to length 1.0 if possible, else returns a
663    /// fallback value.
664    ///
665    /// In particular, if the input is zero (or very close to zero), or non-finite,
666    /// the result of this operation will be the fallback value.
667    ///
668    /// See also [`Self::try_normalize()`].
669    #[inline]
670    #[must_use]
671    pub fn normalize_or(self, fallback: Self) -> Self {
672        let rcp = self.length_recip();
673        if rcp.is_finite() && rcp > 0.0 {
674            self * rcp
675        } else {
676            fallback
677        }
678    }
679
680    /// Returns `self` normalized to length 1.0 if possible, else returns zero.
681    ///
682    /// In particular, if the input is zero (or very close to zero), or non-finite,
683    /// the result of this operation will be zero.
684    ///
685    /// See also [`Self::try_normalize()`].
686    #[inline]
687    #[must_use]
688    pub fn normalize_or_zero(self) -> Self {
689        self.normalize_or(Self::ZERO)
690    }
691
692    /// Returns `self` normalized to length 1.0 and the length of `self`.
693    ///
694    /// If `self` is zero length then `(Self::X, 0.0)` is returned.
695    #[inline]
696    #[must_use]
697    pub fn normalize_and_length(self) -> (Self, f32) {
698        let length = self.length();
699        let rcp = 1.0 / length;
700        if rcp.is_finite() && rcp > 0.0 {
701            (self * rcp, length)
702        } else {
703            (Self::X, 0.0)
704        }
705    }
706
707    /// Returns whether `self` is length `1.0` or not.
708    ///
709    /// Uses a precision threshold of approximately `1e-4`.
710    #[inline]
711    #[must_use]
712    pub fn is_normalized(self) -> bool {
713        math::abs(self.length_squared() - 1.0) <= 2e-4
714    }
715
716    /// Returns the vector projection of `self` onto `rhs`.
717    ///
718    /// `rhs` must be of non-zero length.
719    ///
720    /// # Panics
721    ///
722    /// Will panic if `rhs` is zero length when `glam_assert` is enabled.
723    #[inline]
724    #[must_use]
725    pub fn project_onto(self, rhs: Self) -> Self {
726        let other_len_sq_rcp = 1.0 / rhs.dot(rhs);
727        glam_assert!(other_len_sq_rcp.is_finite());
728        rhs * self.dot(rhs) * other_len_sq_rcp
729    }
730
731    /// Returns the vector rejection of `self` from `rhs`.
732    ///
733    /// The vector rejection is the vector perpendicular to the projection of `self` onto
734    /// `rhs`, in rhs words the result of `self - self.project_onto(rhs)`.
735    ///
736    /// `rhs` must be of non-zero length.
737    ///
738    /// # Panics
739    ///
740    /// Will panic if `rhs` has a length of zero when `glam_assert` is enabled.
741    #[doc(alias("plane"))]
742    #[inline]
743    #[must_use]
744    pub fn reject_from(self, rhs: Self) -> Self {
745        self - self.project_onto(rhs)
746    }
747
748    /// Returns the vector projection of `self` onto `rhs`.
749    ///
750    /// `rhs` must be normalized.
751    ///
752    /// # Panics
753    ///
754    /// Will panic if `rhs` is not normalized when `glam_assert` is enabled.
755    #[inline]
756    #[must_use]
757    pub fn project_onto_normalized(self, rhs: Self) -> Self {
758        glam_assert!(rhs.is_normalized());
759        rhs * self.dot(rhs)
760    }
761
762    /// Returns the vector rejection of `self` from `rhs`.
763    ///
764    /// The vector rejection is the vector perpendicular to the projection of `self` onto
765    /// `rhs`, in rhs words the result of `self - self.project_onto(rhs)`.
766    ///
767    /// `rhs` must be normalized.
768    ///
769    /// # Panics
770    ///
771    /// Will panic if `rhs` is not normalized when `glam_assert` is enabled.
772    #[doc(alias("plane"))]
773    #[inline]
774    #[must_use]
775    pub fn reject_from_normalized(self, rhs: Self) -> Self {
776        self - self.project_onto_normalized(rhs)
777    }
778
779    /// Returns a vector containing the nearest integer to a number for each element of `self`.
780    /// Round half-way cases away from 0.0.
781    #[inline]
782    #[must_use]
783    pub fn round(self) -> Self {
784        Self::new(
785            math::round(self.x),
786            math::round(self.y),
787            math::round(self.z),
788        )
789    }
790
791    /// Returns a vector containing the largest integer less than or equal to a number for each
792    /// element of `self`.
793    #[inline]
794    #[must_use]
795    pub fn floor(self) -> Self {
796        Self::new(
797            math::floor(self.x),
798            math::floor(self.y),
799            math::floor(self.z),
800        )
801    }
802
803    /// Returns a vector containing the smallest integer greater than or equal to a number for
804    /// each element of `self`.
805    #[inline]
806    #[must_use]
807    pub fn ceil(self) -> Self {
808        Self::new(math::ceil(self.x), math::ceil(self.y), math::ceil(self.z))
809    }
810
811    /// Returns a vector containing the integer part each element of `self`. This means numbers are
812    /// always truncated towards zero.
813    #[inline]
814    #[must_use]
815    pub fn trunc(self) -> Self {
816        Self::new(
817            math::trunc(self.x),
818            math::trunc(self.y),
819            math::trunc(self.z),
820        )
821    }
822
823    /// Returns a vector containing `0.0` if `rhs < self` and 1.0 otherwise.
824    ///
825    /// Similar to glsl's step(edge, x), which translates into edge.step(x)
826    #[inline]
827    #[must_use]
828    pub fn step(self, rhs: Self) -> Self {
829        Self::select(rhs.cmplt(self), Self::ZERO, Self::ONE)
830    }
831
832    /// Performs Hermite interpolation between `0.0` and `1.0` using `x` normalized to `[edge0, edge1]`.
833    ///
834    /// This is equivalent to `t * t * (3.0 - 2.0 * t)`, where `t` is clamped to `[0.0, 1.0]`.
835    /// Results are undefined if any element of `edge0` is greater than or equal to the corresponding
836    /// element of `edge1`.
837    ///
838    /// # Panics
839    ///
840    /// Will panic if any element of `edge0` is greater than or equal to the corresponding element
841    /// of `edge1`, when `glam_assert` is enabled.
842    #[inline]
843    #[must_use]
844    pub fn smoothstep(self, edge0: Self, edge1: Self) -> Self {
845        glam_assert!(edge0.cmplt(edge1).all());
846        let t = ((self - edge0) / (edge1 - edge0)).saturate();
847        t * t * (Self::splat(3.0) - Self::splat(2.0) * t)
848    }
849
850    /// Returns a vector containing all elements of `self` clamped to the range of `[0, 1]`.
851    #[inline]
852    #[must_use]
853    pub fn saturate(self) -> Self {
854        self.clamp(Self::ZERO, Self::ONE)
855    }
856
857    /// Returns a vector containing the fractional part of the vector as `self - self.trunc()`.
858    ///
859    /// Note that this differs from the GLSL implementation of `fract` which returns
860    /// `self - self.floor()`.
861    ///
862    /// Note that this is fast but not precise for large numbers.
863    #[inline]
864    #[must_use]
865    pub fn fract(self) -> Self {
866        self - self.trunc()
867    }
868
869    /// Returns a vector containing the fractional part of the vector as `self - self.floor()`.
870    ///
871    /// Note that this differs from the Rust implementation of `fract` which returns
872    /// `self - self.trunc()`.
873    ///
874    /// Note that this is fast but not precise for large numbers.
875    #[inline]
876    #[must_use]
877    pub fn fract_gl(self) -> Self {
878        self - self.floor()
879    }
880
881    /// Returns a vector containing `e^self` (the exponential function) for each element of
882    /// `self`.
883    #[inline]
884    #[must_use]
885    pub fn exp(self) -> Self {
886        Self::new(math::exp(self.x), math::exp(self.y), math::exp(self.z))
887    }
888
889    /// Returns a vector containing `2^self` for each element of `self`.
890    #[inline]
891    #[must_use]
892    pub fn exp2(self) -> Self {
893        Self::new(math::exp2(self.x), math::exp2(self.y), math::exp2(self.z))
894    }
895
896    /// Returns a vector containing the natural logarithm for each element of `self`.
897    /// This returns NaN when the element is negative and negative infinity when the element is zero.
898    #[inline]
899    #[must_use]
900    pub fn ln(self) -> Self {
901        Self::new(math::ln(self.x), math::ln(self.y), math::ln(self.z))
902    }
903
904    /// Returns a vector containing the base 2 logarithm for each element of `self`.
905    /// This returns NaN when the element is negative and negative infinity when the element is zero.
906    #[inline]
907    #[must_use]
908    pub fn log2(self) -> Self {
909        Self::new(math::log2(self.x), math::log2(self.y), math::log2(self.z))
910    }
911
912    /// Returns a vector containing each element of `self` raised to the power of `n`.
913    #[inline]
914    #[must_use]
915    pub fn powf(self, n: f32) -> Self {
916        Self::new(
917            math::powf(self.x, n),
918            math::powf(self.y, n),
919            math::powf(self.z, n),
920        )
921    }
922
923    /// Returns a vector containing the square root for each element of `self`.
924    /// This returns NaN when the element is negative.
925    #[inline]
926    #[must_use]
927    pub fn sqrt(self) -> Self {
928        Self::new(math::sqrt(self.x), math::sqrt(self.y), math::sqrt(self.z))
929    }
930
931    /// Returns a vector containing the cosine for each element of `self`.
932    #[inline]
933    #[must_use]
934    pub fn cos(self) -> Self {
935        Self::new(math::cos(self.x), math::cos(self.y), math::cos(self.z))
936    }
937
938    /// Returns a vector containing the sine for each element of `self`.
939    #[inline]
940    #[must_use]
941    pub fn sin(self) -> Self {
942        Self::new(math::sin(self.x), math::sin(self.y), math::sin(self.z))
943    }
944
945    /// Returns a tuple of two vectors containing the sine and cosine for each element of `self`.
946    #[inline]
947    #[must_use]
948    pub fn sin_cos(self) -> (Self, Self) {
949        let (sin_x, cos_x) = math::sin_cos(self.x);
950        let (sin_y, cos_y) = math::sin_cos(self.y);
951        let (sin_z, cos_z) = math::sin_cos(self.z);
952
953        (
954            Self::new(sin_x, sin_y, sin_z),
955            Self::new(cos_x, cos_y, cos_z),
956        )
957    }
958
959    /// Returns a vector containing the reciprocal `1.0/n` of each element of `self`.
960    #[inline]
961    #[must_use]
962    pub fn recip(self) -> Self {
963        Self::new(1.0 / self.x, 1.0 / self.y, 1.0 / self.z)
964    }
965
966    /// Performs a linear interpolation between `self` and `rhs` based on the value `s`, using the
967    /// form `self * (1.0 - s) + rhs * s`.
968    ///
969    /// When `s` is `0.0`, the result will be equal to `self`. When `s` is `1.0`, the result will
970    /// be equal to `rhs`. When `s` is outside of the range `[0, 1]`, the result is linearly
971    /// extrapolated.
972    ///
973    /// The result is guaranteed to be `self` at `s == 0.0` and `rhs` at `s == 1.0`, even when the
974    /// values differ greatly in magnitude, but it is not monotonic in `s` for nearly equal inputs
975    /// and may not preserve equal inputs exactly. Consider [`lerp_monotonic`](Self::lerp_monotonic)
976    /// instead when interpolating between values that may be equal or nearly equal.
977    #[doc(alias = "mix")]
978    #[inline]
979    #[must_use]
980    pub fn lerp(self, rhs: Self, s: f32) -> Self {
981        self * (1.0 - s) + rhs * s
982    }
983
984    /// Performs a linear interpolation between `self` and `rhs` based on the value `s`, using the
985    /// monotonic form `self + (rhs - self) * s`.
986    ///
987    /// When `s` is `0.0`, the result will be equal to `self`. When `s` is `1.0`, the result will
988    /// be equal to `rhs`. When `s` is outside of the range `[0, 1]`, the result is linearly
989    /// extrapolated.
990    ///
991    /// Prefer this over [`lerp`](Self::lerp) when interpolating between values that may be equal or
992    /// nearly equal: the result is monotonic in `s` and equal inputs are preserved exactly, avoiding
993    /// the rounding jitter that [`lerp`](Self::lerp) can introduce. The tradeoff is that
994    /// `rhs - self` is evaluated first, so this is less accurate than [`lerp`](Self::lerp) when
995    /// `self` and `rhs` differ greatly in magnitude, and overflows to infinity when they have
996    /// opposite signs and large magnitudes.
997    ///
998    /// On SIMD back-ends the multiply and add are fused when the target supports it, which has a
999    /// single rounding step and can be more accurate than a separate multiply and add.
1000    #[doc(alias = "mix")]
1001    #[inline]
1002    #[must_use]
1003    pub fn lerp_monotonic(self, rhs: Self, s: f32) -> Self {
1004        self + (rhs - self) * s
1005    }
1006
1007    /// Moves towards `rhs` based on the value `d`.
1008    ///
1009    /// When `d` is `0.0`, the result will be equal to `self`. When `d` is equal to
1010    /// `self.distance(rhs)`, the result will be equal to `rhs`. Will not go past `rhs`.
1011    #[inline]
1012    #[must_use]
1013    pub fn move_towards(self, rhs: Self, d: f32) -> Self {
1014        let a = rhs - self;
1015        let len = a.length();
1016        if len <= d || len <= 1e-4 {
1017            return rhs;
1018        }
1019        self + a / len * d
1020    }
1021
1022    /// Calculates the midpoint between `self` and `rhs`.
1023    ///
1024    /// The midpoint is the average of, or halfway point between, two vectors.
1025    /// `a.midpoint(b)` should yield the same result as `a.lerp(b, 0.5)`
1026    /// while being slightly cheaper to compute.
1027    #[inline]
1028    pub fn midpoint(self, rhs: Self) -> Self {
1029        (self + rhs) * 0.5
1030    }
1031
1032    /// Returns true if the absolute difference of all elements between `self` and `rhs` is
1033    /// less than or equal to `max_abs_diff`.
1034    ///
1035    /// This can be used to compare if two vectors contain similar elements. It works best when
1036    /// comparing with a known value. The `max_abs_diff` that should be used used depends on
1037    /// the values being compared against.
1038    ///
1039    /// For more see
1040    /// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
1041    #[inline]
1042    #[must_use]
1043    pub fn abs_diff_eq(self, rhs: Self, max_abs_diff: f32) -> bool {
1044        self.sub(rhs).abs().cmple(Self::splat(max_abs_diff)).all()
1045    }
1046
1047    /// Returns a vector with a length no less than `min` and no more than `max`.
1048    ///
1049    /// # Panics
1050    ///
1051    /// Will panic if `min` is greater than `max`, or if either `min` or `max` is negative, when `glam_assert` is enabled.
1052    #[inline]
1053    #[must_use]
1054    pub fn clamp_length(self, min: f32, max: f32) -> Self {
1055        glam_assert!(0.0 <= min);
1056        glam_assert!(min <= max);
1057        let length_sq = self.length_squared();
1058        if length_sq < min * min {
1059            min * (self / math::sqrt(length_sq))
1060        } else if length_sq > max * max {
1061            max * (self / math::sqrt(length_sq))
1062        } else {
1063            self
1064        }
1065    }
1066
1067    /// Returns a vector with a length no more than `max`.
1068    ///
1069    /// # Panics
1070    ///
1071    /// Will panic if `max` is negative when `glam_assert` is enabled.
1072    #[inline]
1073    #[must_use]
1074    pub fn clamp_length_max(self, max: f32) -> Self {
1075        glam_assert!(0.0 <= max);
1076        let length_sq = self.length_squared();
1077        if length_sq > max * max {
1078            max * (self / math::sqrt(length_sq))
1079        } else {
1080            self
1081        }
1082    }
1083
1084    /// Returns a vector with a length no less than `min`.
1085    ///
1086    /// # Panics
1087    ///
1088    /// Will panic if `min` is negative when `glam_assert` is enabled.
1089    #[inline]
1090    #[must_use]
1091    pub fn clamp_length_min(self, min: f32) -> Self {
1092        glam_assert!(0.0 <= min);
1093        let length_sq = self.length_squared();
1094        if length_sq < min * min {
1095            min * (self / math::sqrt(length_sq))
1096        } else {
1097            self
1098        }
1099    }
1100
1101    /// Fused multiply-add. Computes `(self * a) + b` element-wise with only one rounding
1102    /// error, yielding a more accurate result than an unfused multiply-add.
1103    ///
1104    /// Using `mul_add` *may* be more performant than an unfused multiply-add if the target
1105    /// architecture has a dedicated fma CPU instruction. However, this is not always true,
1106    /// and will be heavily dependant on designing algorithms with specific target hardware in
1107    /// mind.
1108    #[inline]
1109    #[must_use]
1110    pub fn mul_add(self, a: Self, b: Self) -> Self {
1111        Self::new(
1112            math::mul_add(self.x, a.x, b.x),
1113            math::mul_add(self.y, a.y, b.y),
1114            math::mul_add(self.z, a.z, b.z),
1115        )
1116    }
1117
1118    /// Returns the reflection vector for a given incident vector `self` and surface normal
1119    /// `normal`.
1120    ///
1121    /// `normal` must be normalized.
1122    ///
1123    /// # Panics
1124    ///
1125    /// Will panic if `normal` is not normalized when `glam_assert` is enabled.
1126    #[inline]
1127    #[must_use]
1128    pub fn reflect(self, normal: Self) -> Self {
1129        glam_assert!(normal.is_normalized());
1130        self - 2.0 * self.dot(normal) * normal
1131    }
1132
1133    /// Returns the refraction direction for a given incident vector `self`, surface normal
1134    /// `normal` and ratio of indices of refraction, `eta`. When total internal reflection occurs,
1135    /// a zero vector will be returned.
1136    ///
1137    /// `self` and `normal` must be normalized.
1138    ///
1139    /// # Panics
1140    ///
1141    /// Will panic if `self` or `normal` is not normalized when `glam_assert` is enabled.
1142    #[inline]
1143    #[must_use]
1144    pub fn refract(self, normal: Self, eta: f32) -> Self {
1145        glam_assert!(self.is_normalized());
1146        glam_assert!(normal.is_normalized());
1147        let n_dot_i = normal.dot(self);
1148        let k = 1.0 - eta * eta * (1.0 - n_dot_i * n_dot_i);
1149        if k >= 0.0 {
1150            eta * self - (eta * n_dot_i + math::sqrt(k)) * normal
1151        } else {
1152            Self::ZERO
1153        }
1154    }
1155
1156    /// Returns the angle (in radians) between two vectors in the range `[0, +Ï€]`.
1157    ///
1158    /// For the full rotation between two vectors as a quaternion, see
1159    /// [`Quat::from_rotation_arc`].
1160    ///
1161    /// The inputs do not need to be unit vectors however they must be non-zero.
1162    ///
1163    /// # Panics
1164    ///
1165    /// Will panic if `self` or `rhs` has zero length when `glam_assert` is enabled.
1166    #[inline]
1167    #[must_use]
1168    pub fn angle_between(self, rhs: Self) -> f32 {
1169        glam_assert!(self.is_non_zero());
1170        glam_assert!(rhs.is_non_zero());
1171        math::acos_approx(
1172            self.dot(rhs)
1173                .div(math::sqrt(self.length_squared().mul(rhs.length_squared()))),
1174        )
1175    }
1176
1177    /// Returns the signed angle (in radians) from `self` to `rhs` around `axis`
1178    /// in the range `[-Ï€, +Ï€]`.
1179    ///
1180    /// The `axis` must be a unit vector. The angle follows the right-hand rule
1181    /// around `axis` and can be used with [`Self::rotate_axis`], e.g.
1182    /// `self.rotate_axis(axis, self.angle_to(rhs, axis))` will be equal to `rhs`.
1183    ///
1184    /// For the unsigned angle without a reference axis, see [`Self::angle_between`].
1185    ///
1186    /// The inputs do not need to be unit vectors however they must be non-zero.
1187    ///
1188    /// # Panics
1189    ///
1190    /// Will panic if `axis` is not normalized when `glam_assert` is enabled.
1191    /// Will panic if `self` or `rhs` has zero length when `glam_assert` is enabled.
1192    #[doc(alias = "signed_angle")]
1193    #[inline]
1194    #[must_use]
1195    pub fn angle_to(self, rhs: Self, axis: Self) -> f32 {
1196        glam_assert!(axis.is_normalized());
1197        glam_assert!(self.is_non_zero());
1198        glam_assert!(rhs.is_non_zero());
1199        math::atan2(self.cross(rhs).dot(axis), self.dot(rhs))
1200    }
1201
1202    /// Rotates around the x axis by `angle` (in radians).
1203    #[inline]
1204    #[must_use]
1205    pub fn rotate_x(self, angle: f32) -> Self {
1206        let (sina, cosa) = math::sin_cos(angle);
1207        Self::new(
1208            self.x,
1209            self.y * cosa - self.z * sina,
1210            self.y * sina + self.z * cosa,
1211        )
1212    }
1213
1214    /// Rotates around the y axis by `angle` (in radians).
1215    #[inline]
1216    #[must_use]
1217    pub fn rotate_y(self, angle: f32) -> Self {
1218        let (sina, cosa) = math::sin_cos(angle);
1219        Self::new(
1220            self.x * cosa + self.z * sina,
1221            self.y,
1222            self.x * -sina + self.z * cosa,
1223        )
1224    }
1225
1226    /// Rotates around the z axis by `angle` (in radians).
1227    #[inline]
1228    #[must_use]
1229    pub fn rotate_z(self, angle: f32) -> Self {
1230        let (sina, cosa) = math::sin_cos(angle);
1231        Self::new(
1232            self.x * cosa - self.y * sina,
1233            self.x * sina + self.y * cosa,
1234            self.z,
1235        )
1236    }
1237
1238    /// Rotates around `axis` by `angle` (in radians).
1239    ///
1240    /// The axis must be a unit vector.
1241    ///
1242    /// # Panics
1243    ///
1244    /// Will panic if `axis` is not normalized when `glam_assert` is enabled.
1245    #[inline]
1246    #[must_use]
1247    pub fn rotate_axis(self, axis: Self, angle: f32) -> Self {
1248        Quat::from_axis_angle(axis, angle) * self
1249    }
1250
1251    /// Rotates towards `rhs` up to `max_angle` (in radians).
1252    ///
1253    /// When `max_angle` is `0.0`, the result will be equal to `self`. When `max_angle` is equal to
1254    /// `self.angle_between(rhs)`, the result will be parallel to `rhs`. If `max_angle` is negative,
1255    /// rotates towards the exact opposite of `rhs`. Will not go past the target.
1256    #[inline]
1257    #[must_use]
1258    pub fn rotate_towards(self, rhs: Self, max_angle: f32) -> Self {
1259        let angle_between = self.angle_between(rhs);
1260        // When `max_angle < 0`, rotate no further than `PI` radians away
1261        let angle = max_angle.clamp(angle_between - core::f32::consts::PI, angle_between);
1262        let axis = self
1263            .cross(rhs)
1264            .try_normalize()
1265            .unwrap_or_else(|| self.any_orthogonal_vector().normalize());
1266        Quat::from_axis_angle(axis, angle) * self
1267    }
1268
1269    /// Returns some vector that is orthogonal to the given one.
1270    ///
1271    /// The input vector must be finite and non-zero.
1272    ///
1273    /// The output vector is not necessarily unit length. For that use
1274    /// [`Self::any_orthonormal_vector()`] instead.
1275    #[inline]
1276    #[must_use]
1277    pub fn any_orthogonal_vector(self) -> Self {
1278        // This can probably be optimized
1279        if math::abs(self.x) > math::abs(self.y) {
1280            Self::new(-self.z, 0.0, self.x) // self.cross(Self::Y)
1281        } else {
1282            Self::new(0.0, self.z, -self.y) // self.cross(Self::X)
1283        }
1284    }
1285
1286    /// Returns any unit vector that is orthogonal to the given one.
1287    ///
1288    /// The input vector must be unit length.
1289    ///
1290    /// # Panics
1291    ///
1292    /// Will panic if `self` is not normalized when `glam_assert` is enabled.
1293    #[inline]
1294    #[must_use]
1295    pub fn any_orthonormal_vector(self) -> Self {
1296        glam_assert!(self.is_normalized());
1297        // From https://graphics.pixar.com/library/OrthonormalB/paper.pdf
1298        let sign = math::signum(self.z);
1299        let a = -1.0 / (sign + self.z);
1300        let b = self.x * self.y * a;
1301        Self::new(b, sign + self.y * self.y * a, -self.y)
1302    }
1303
1304    /// Given a unit vector return two other vectors that together form a right-handed orthonormal
1305    /// basis. That is, all three vectors are orthogonal to each other and are normalized.
1306    ///
1307    /// # Panics
1308    ///
1309    /// Will panic if `self` is not normalized when `glam_assert` is enabled.
1310    #[inline]
1311    #[must_use]
1312    pub fn any_orthonormal_pair(self) -> (Self, Self) {
1313        glam_assert!(self.is_normalized());
1314        // From https://graphics.pixar.com/library/OrthonormalB/paper.pdf
1315        let sign = math::signum(self.z);
1316        let a = -1.0 / (sign + self.z);
1317        let b = self.x * self.y * a;
1318        (
1319            Self::new(1.0 + sign * self.x * self.x * a, sign * b, -sign * self.x),
1320            Self::new(b, sign + self.y * self.y * a, -self.y),
1321        )
1322    }
1323
1324    /// Performs a spherical linear interpolation between `self` and `rhs` based on the value `s`.
1325    ///
1326    /// When `s` is `0.0`, the result will be equal to `self`.  When `s` is `1.0`, the result
1327    /// will be equal to `rhs`. When `s` is outside of range `[0, 1]`, the result is linearly
1328    /// extrapolated.
1329    #[inline]
1330    #[must_use]
1331    pub fn slerp(self, rhs: Self, s: f32) -> Self {
1332        let self_length = self.length();
1333        let rhs_length = rhs.length();
1334        // Cosine of the angle between the vectors [-1, 1], or NaN if either vector has a zero length
1335        let dot = self.dot(rhs) / (self_length * rhs_length);
1336        // If dot is close to 1 or -1, or is NaN the calculations for t1 and t2 break down
1337        if math::abs(dot) < 1.0 - 3e-7 {
1338            // Angle between the vectors [0, +Ï€]
1339            let theta = math::acos_approx(dot);
1340            // Sine of the angle between vectors [0, 1]
1341            let sin_theta = math::sin(theta);
1342            let t1 = math::sin(theta * (1.0 - s));
1343            let t2 = math::sin(theta * s);
1344
1345            // Interpolate vector lengths using the monotone form to keep equal lengths exact.
1346            let result_length = self_length + (rhs_length - self_length) * s;
1347            // Scale the vectors to the target length and interpolate them
1348            return (self * (result_length / self_length) * t1
1349                + rhs * (result_length / rhs_length) * t2)
1350                * (1.0 / sin_theta);
1351        }
1352        if dot < 0.0 {
1353            // Vectors are almost parallel in opposing directions
1354
1355            // Create a rotation from self to rhs along some axis
1356            let axis = self.any_orthogonal_vector().normalize();
1357            let rotation = Quat::from_axis_angle(axis, core::f32::consts::PI * s);
1358            // Interpolate vector lengths using the monotone form to keep equal lengths exact.
1359            let result_length = self_length + (rhs_length - self_length) * s;
1360            rotation * self * (result_length / self_length)
1361        } else {
1362            // Vectors are almost parallel in the same direction, or dot was NaN
1363            self.lerp(rhs, s)
1364        }
1365    }
1366
1367    /// Casts all elements of `self` to `f64`.
1368    #[cfg(feature = "f64")]
1369    #[inline]
1370    #[must_use]
1371    pub fn as_dvec3(self) -> crate::DVec3 {
1372        crate::DVec3::new(self.x as f64, self.y as f64, self.z as f64)
1373    }
1374
1375    /// Casts all elements of `self` to `i8`.
1376    #[cfg(feature = "i8")]
1377    #[inline]
1378    #[must_use]
1379    pub fn as_i8vec3(self) -> crate::I8Vec3 {
1380        crate::I8Vec3::new(self.x as i8, self.y as i8, self.z as i8)
1381    }
1382
1383    /// Casts all elements of `self` to `u8`.
1384    #[cfg(feature = "u8")]
1385    #[inline]
1386    #[must_use]
1387    pub fn as_u8vec3(self) -> crate::U8Vec3 {
1388        crate::U8Vec3::new(self.x as u8, self.y as u8, self.z as u8)
1389    }
1390
1391    /// Casts all elements of `self` to `i16`.
1392    #[cfg(feature = "i16")]
1393    #[inline]
1394    #[must_use]
1395    pub fn as_i16vec3(self) -> crate::I16Vec3 {
1396        crate::I16Vec3::new(self.x as i16, self.y as i16, self.z as i16)
1397    }
1398
1399    /// Casts all elements of `self` to `u16`.
1400    #[cfg(feature = "u16")]
1401    #[inline]
1402    #[must_use]
1403    pub fn as_u16vec3(self) -> crate::U16Vec3 {
1404        crate::U16Vec3::new(self.x as u16, self.y as u16, self.z as u16)
1405    }
1406
1407    /// Casts all elements of `self` to `i32`.
1408    #[cfg(feature = "i32")]
1409    #[inline]
1410    #[must_use]
1411    pub fn as_ivec3(self) -> crate::IVec3 {
1412        crate::IVec3::new(self.x as i32, self.y as i32, self.z as i32)
1413    }
1414
1415    /// Casts all elements of `self` to `u32`.
1416    #[cfg(feature = "u32")]
1417    #[inline]
1418    #[must_use]
1419    pub fn as_uvec3(self) -> crate::UVec3 {
1420        crate::UVec3::new(self.x as u32, self.y as u32, self.z as u32)
1421    }
1422
1423    /// Casts all elements of `self` to `i64`.
1424    #[cfg(feature = "i64")]
1425    #[inline]
1426    #[must_use]
1427    pub fn as_i64vec3(self) -> crate::I64Vec3 {
1428        crate::I64Vec3::new(self.x as i64, self.y as i64, self.z as i64)
1429    }
1430
1431    /// Casts all elements of `self` to `u64`.
1432    #[cfg(feature = "u64")]
1433    #[inline]
1434    #[must_use]
1435    pub fn as_u64vec3(self) -> crate::U64Vec3 {
1436        crate::U64Vec3::new(self.x as u64, self.y as u64, self.z as u64)
1437    }
1438
1439    /// Casts all elements of `self` to `isize`.
1440    #[cfg(feature = "isize")]
1441    #[inline]
1442    #[must_use]
1443    pub fn as_isizevec3(self) -> crate::ISizeVec3 {
1444        crate::ISizeVec3::new(self.x as isize, self.y as isize, self.z as isize)
1445    }
1446
1447    /// Casts all elements of `self` to `usize`.
1448    #[cfg(feature = "usize")]
1449    #[inline]
1450    #[must_use]
1451    pub fn as_usizevec3(self) -> crate::USizeVec3 {
1452        crate::USizeVec3::new(self.x as usize, self.y as usize, self.z as usize)
1453    }
1454}
1455
1456impl Default for Vec3 {
1457    #[inline(always)]
1458    fn default() -> Self {
1459        Self::ZERO
1460    }
1461}
1462
1463impl Div for Vec3 {
1464    type Output = Self;
1465    #[inline]
1466    fn div(self, rhs: Self) -> Self {
1467        Self::new(self.x.div(rhs.x), self.y.div(rhs.y), self.z.div(rhs.z))
1468    }
1469}
1470
1471impl Div<&Self> for Vec3 {
1472    type Output = Self;
1473    #[inline]
1474    fn div(self, rhs: &Self) -> Self {
1475        self.div(*rhs)
1476    }
1477}
1478
1479impl Div<&Vec3> for &Vec3 {
1480    type Output = Vec3;
1481    #[inline]
1482    fn div(self, rhs: &Vec3) -> Vec3 {
1483        (*self).div(*rhs)
1484    }
1485}
1486
1487impl Div<Vec3> for &Vec3 {
1488    type Output = Vec3;
1489    #[inline]
1490    fn div(self, rhs: Vec3) -> Vec3 {
1491        (*self).div(rhs)
1492    }
1493}
1494
1495impl DivAssign for Vec3 {
1496    #[inline]
1497    fn div_assign(&mut self, rhs: Self) {
1498        self.x.div_assign(rhs.x);
1499        self.y.div_assign(rhs.y);
1500        self.z.div_assign(rhs.z);
1501    }
1502}
1503
1504impl DivAssign<&Self> for Vec3 {
1505    #[inline]
1506    fn div_assign(&mut self, rhs: &Self) {
1507        self.div_assign(*rhs);
1508    }
1509}
1510
1511impl Div<f32> for Vec3 {
1512    type Output = Self;
1513    #[inline]
1514    fn div(self, rhs: f32) -> Self {
1515        Self::new(self.x.div(rhs), self.y.div(rhs), self.z.div(rhs))
1516    }
1517}
1518
1519impl Div<&f32> for Vec3 {
1520    type Output = Self;
1521    #[inline]
1522    fn div(self, rhs: &f32) -> Self {
1523        self.div(*rhs)
1524    }
1525}
1526
1527impl Div<&f32> for &Vec3 {
1528    type Output = Vec3;
1529    #[inline]
1530    fn div(self, rhs: &f32) -> Vec3 {
1531        (*self).div(*rhs)
1532    }
1533}
1534
1535impl Div<f32> for &Vec3 {
1536    type Output = Vec3;
1537    #[inline]
1538    fn div(self, rhs: f32) -> Vec3 {
1539        (*self).div(rhs)
1540    }
1541}
1542
1543impl DivAssign<f32> for Vec3 {
1544    #[inline]
1545    fn div_assign(&mut self, rhs: f32) {
1546        self.x.div_assign(rhs);
1547        self.y.div_assign(rhs);
1548        self.z.div_assign(rhs);
1549    }
1550}
1551
1552impl DivAssign<&f32> for Vec3 {
1553    #[inline]
1554    fn div_assign(&mut self, rhs: &f32) {
1555        self.div_assign(*rhs);
1556    }
1557}
1558
1559impl Div<Vec3> for f32 {
1560    type Output = Vec3;
1561    #[inline]
1562    fn div(self, rhs: Vec3) -> Vec3 {
1563        Vec3::new(self.div(rhs.x), self.div(rhs.y), self.div(rhs.z))
1564    }
1565}
1566
1567impl Div<&Vec3> for f32 {
1568    type Output = Vec3;
1569    #[inline]
1570    fn div(self, rhs: &Vec3) -> Vec3 {
1571        self.div(*rhs)
1572    }
1573}
1574
1575impl Div<&Vec3> for &f32 {
1576    type Output = Vec3;
1577    #[inline]
1578    fn div(self, rhs: &Vec3) -> Vec3 {
1579        (*self).div(*rhs)
1580    }
1581}
1582
1583impl Div<Vec3> for &f32 {
1584    type Output = Vec3;
1585    #[inline]
1586    fn div(self, rhs: Vec3) -> Vec3 {
1587        (*self).div(rhs)
1588    }
1589}
1590
1591impl Mul for Vec3 {
1592    type Output = Self;
1593    #[inline]
1594    fn mul(self, rhs: Self) -> Self {
1595        Self::new(self.x.mul(rhs.x), self.y.mul(rhs.y), self.z.mul(rhs.z))
1596    }
1597}
1598
1599impl Mul<&Self> for Vec3 {
1600    type Output = Self;
1601    #[inline]
1602    fn mul(self, rhs: &Self) -> Self {
1603        self.mul(*rhs)
1604    }
1605}
1606
1607impl Mul<&Vec3> for &Vec3 {
1608    type Output = Vec3;
1609    #[inline]
1610    fn mul(self, rhs: &Vec3) -> Vec3 {
1611        (*self).mul(*rhs)
1612    }
1613}
1614
1615impl Mul<Vec3> for &Vec3 {
1616    type Output = Vec3;
1617    #[inline]
1618    fn mul(self, rhs: Vec3) -> Vec3 {
1619        (*self).mul(rhs)
1620    }
1621}
1622
1623impl MulAssign for Vec3 {
1624    #[inline]
1625    fn mul_assign(&mut self, rhs: Self) {
1626        self.x.mul_assign(rhs.x);
1627        self.y.mul_assign(rhs.y);
1628        self.z.mul_assign(rhs.z);
1629    }
1630}
1631
1632impl MulAssign<&Self> for Vec3 {
1633    #[inline]
1634    fn mul_assign(&mut self, rhs: &Self) {
1635        self.mul_assign(*rhs);
1636    }
1637}
1638
1639impl Mul<f32> for Vec3 {
1640    type Output = Self;
1641    #[inline]
1642    fn mul(self, rhs: f32) -> Self {
1643        Self::new(self.x.mul(rhs), self.y.mul(rhs), self.z.mul(rhs))
1644    }
1645}
1646
1647impl Mul<&f32> for Vec3 {
1648    type Output = Self;
1649    #[inline]
1650    fn mul(self, rhs: &f32) -> Self {
1651        self.mul(*rhs)
1652    }
1653}
1654
1655impl Mul<&f32> for &Vec3 {
1656    type Output = Vec3;
1657    #[inline]
1658    fn mul(self, rhs: &f32) -> Vec3 {
1659        (*self).mul(*rhs)
1660    }
1661}
1662
1663impl Mul<f32> for &Vec3 {
1664    type Output = Vec3;
1665    #[inline]
1666    fn mul(self, rhs: f32) -> Vec3 {
1667        (*self).mul(rhs)
1668    }
1669}
1670
1671impl MulAssign<f32> for Vec3 {
1672    #[inline]
1673    fn mul_assign(&mut self, rhs: f32) {
1674        self.x.mul_assign(rhs);
1675        self.y.mul_assign(rhs);
1676        self.z.mul_assign(rhs);
1677    }
1678}
1679
1680impl MulAssign<&f32> for Vec3 {
1681    #[inline]
1682    fn mul_assign(&mut self, rhs: &f32) {
1683        self.mul_assign(*rhs);
1684    }
1685}
1686
1687impl Mul<Vec3> for f32 {
1688    type Output = Vec3;
1689    #[inline]
1690    fn mul(self, rhs: Vec3) -> Vec3 {
1691        Vec3::new(self.mul(rhs.x), self.mul(rhs.y), self.mul(rhs.z))
1692    }
1693}
1694
1695impl Mul<&Vec3> for f32 {
1696    type Output = Vec3;
1697    #[inline]
1698    fn mul(self, rhs: &Vec3) -> Vec3 {
1699        self.mul(*rhs)
1700    }
1701}
1702
1703impl Mul<&Vec3> for &f32 {
1704    type Output = Vec3;
1705    #[inline]
1706    fn mul(self, rhs: &Vec3) -> Vec3 {
1707        (*self).mul(*rhs)
1708    }
1709}
1710
1711impl Mul<Vec3> for &f32 {
1712    type Output = Vec3;
1713    #[inline]
1714    fn mul(self, rhs: Vec3) -> Vec3 {
1715        (*self).mul(rhs)
1716    }
1717}
1718
1719impl Add for Vec3 {
1720    type Output = Self;
1721    #[inline]
1722    fn add(self, rhs: Self) -> Self {
1723        Self::new(self.x.add(rhs.x), self.y.add(rhs.y), self.z.add(rhs.z))
1724    }
1725}
1726
1727impl Add<&Self> for Vec3 {
1728    type Output = Self;
1729    #[inline]
1730    fn add(self, rhs: &Self) -> Self {
1731        self.add(*rhs)
1732    }
1733}
1734
1735impl Add<&Vec3> for &Vec3 {
1736    type Output = Vec3;
1737    #[inline]
1738    fn add(self, rhs: &Vec3) -> Vec3 {
1739        (*self).add(*rhs)
1740    }
1741}
1742
1743impl Add<Vec3> for &Vec3 {
1744    type Output = Vec3;
1745    #[inline]
1746    fn add(self, rhs: Vec3) -> Vec3 {
1747        (*self).add(rhs)
1748    }
1749}
1750
1751impl AddAssign for Vec3 {
1752    #[inline]
1753    fn add_assign(&mut self, rhs: Self) {
1754        self.x.add_assign(rhs.x);
1755        self.y.add_assign(rhs.y);
1756        self.z.add_assign(rhs.z);
1757    }
1758}
1759
1760impl AddAssign<&Self> for Vec3 {
1761    #[inline]
1762    fn add_assign(&mut self, rhs: &Self) {
1763        self.add_assign(*rhs);
1764    }
1765}
1766
1767impl Add<f32> for Vec3 {
1768    type Output = Self;
1769    #[inline]
1770    fn add(self, rhs: f32) -> Self {
1771        Self::new(self.x.add(rhs), self.y.add(rhs), self.z.add(rhs))
1772    }
1773}
1774
1775impl Add<&f32> for Vec3 {
1776    type Output = Self;
1777    #[inline]
1778    fn add(self, rhs: &f32) -> Self {
1779        self.add(*rhs)
1780    }
1781}
1782
1783impl Add<&f32> for &Vec3 {
1784    type Output = Vec3;
1785    #[inline]
1786    fn add(self, rhs: &f32) -> Vec3 {
1787        (*self).add(*rhs)
1788    }
1789}
1790
1791impl Add<f32> for &Vec3 {
1792    type Output = Vec3;
1793    #[inline]
1794    fn add(self, rhs: f32) -> Vec3 {
1795        (*self).add(rhs)
1796    }
1797}
1798
1799impl AddAssign<f32> for Vec3 {
1800    #[inline]
1801    fn add_assign(&mut self, rhs: f32) {
1802        self.x.add_assign(rhs);
1803        self.y.add_assign(rhs);
1804        self.z.add_assign(rhs);
1805    }
1806}
1807
1808impl AddAssign<&f32> for Vec3 {
1809    #[inline]
1810    fn add_assign(&mut self, rhs: &f32) {
1811        self.add_assign(*rhs);
1812    }
1813}
1814
1815impl Add<Vec3> for f32 {
1816    type Output = Vec3;
1817    #[inline]
1818    fn add(self, rhs: Vec3) -> Vec3 {
1819        Vec3::new(self.add(rhs.x), self.add(rhs.y), self.add(rhs.z))
1820    }
1821}
1822
1823impl Add<&Vec3> for f32 {
1824    type Output = Vec3;
1825    #[inline]
1826    fn add(self, rhs: &Vec3) -> Vec3 {
1827        self.add(*rhs)
1828    }
1829}
1830
1831impl Add<&Vec3> for &f32 {
1832    type Output = Vec3;
1833    #[inline]
1834    fn add(self, rhs: &Vec3) -> Vec3 {
1835        (*self).add(*rhs)
1836    }
1837}
1838
1839impl Add<Vec3> for &f32 {
1840    type Output = Vec3;
1841    #[inline]
1842    fn add(self, rhs: Vec3) -> Vec3 {
1843        (*self).add(rhs)
1844    }
1845}
1846
1847impl Sub for Vec3 {
1848    type Output = Self;
1849    #[inline]
1850    fn sub(self, rhs: Self) -> Self {
1851        Self::new(self.x.sub(rhs.x), self.y.sub(rhs.y), self.z.sub(rhs.z))
1852    }
1853}
1854
1855impl Sub<&Self> for Vec3 {
1856    type Output = Self;
1857    #[inline]
1858    fn sub(self, rhs: &Self) -> Self {
1859        self.sub(*rhs)
1860    }
1861}
1862
1863impl Sub<&Vec3> for &Vec3 {
1864    type Output = Vec3;
1865    #[inline]
1866    fn sub(self, rhs: &Vec3) -> Vec3 {
1867        (*self).sub(*rhs)
1868    }
1869}
1870
1871impl Sub<Vec3> for &Vec3 {
1872    type Output = Vec3;
1873    #[inline]
1874    fn sub(self, rhs: Vec3) -> Vec3 {
1875        (*self).sub(rhs)
1876    }
1877}
1878
1879impl SubAssign for Vec3 {
1880    #[inline]
1881    fn sub_assign(&mut self, rhs: Self) {
1882        self.x.sub_assign(rhs.x);
1883        self.y.sub_assign(rhs.y);
1884        self.z.sub_assign(rhs.z);
1885    }
1886}
1887
1888impl SubAssign<&Self> for Vec3 {
1889    #[inline]
1890    fn sub_assign(&mut self, rhs: &Self) {
1891        self.sub_assign(*rhs);
1892    }
1893}
1894
1895impl Sub<f32> for Vec3 {
1896    type Output = Self;
1897    #[inline]
1898    fn sub(self, rhs: f32) -> Self {
1899        Self::new(self.x.sub(rhs), self.y.sub(rhs), self.z.sub(rhs))
1900    }
1901}
1902
1903impl Sub<&f32> for Vec3 {
1904    type Output = Self;
1905    #[inline]
1906    fn sub(self, rhs: &f32) -> Self {
1907        self.sub(*rhs)
1908    }
1909}
1910
1911impl Sub<&f32> for &Vec3 {
1912    type Output = Vec3;
1913    #[inline]
1914    fn sub(self, rhs: &f32) -> Vec3 {
1915        (*self).sub(*rhs)
1916    }
1917}
1918
1919impl Sub<f32> for &Vec3 {
1920    type Output = Vec3;
1921    #[inline]
1922    fn sub(self, rhs: f32) -> Vec3 {
1923        (*self).sub(rhs)
1924    }
1925}
1926
1927impl SubAssign<f32> for Vec3 {
1928    #[inline]
1929    fn sub_assign(&mut self, rhs: f32) {
1930        self.x.sub_assign(rhs);
1931        self.y.sub_assign(rhs);
1932        self.z.sub_assign(rhs);
1933    }
1934}
1935
1936impl SubAssign<&f32> for Vec3 {
1937    #[inline]
1938    fn sub_assign(&mut self, rhs: &f32) {
1939        self.sub_assign(*rhs);
1940    }
1941}
1942
1943impl Sub<Vec3> for f32 {
1944    type Output = Vec3;
1945    #[inline]
1946    fn sub(self, rhs: Vec3) -> Vec3 {
1947        Vec3::new(self.sub(rhs.x), self.sub(rhs.y), self.sub(rhs.z))
1948    }
1949}
1950
1951impl Sub<&Vec3> for f32 {
1952    type Output = Vec3;
1953    #[inline]
1954    fn sub(self, rhs: &Vec3) -> Vec3 {
1955        self.sub(*rhs)
1956    }
1957}
1958
1959impl Sub<&Vec3> for &f32 {
1960    type Output = Vec3;
1961    #[inline]
1962    fn sub(self, rhs: &Vec3) -> Vec3 {
1963        (*self).sub(*rhs)
1964    }
1965}
1966
1967impl Sub<Vec3> for &f32 {
1968    type Output = Vec3;
1969    #[inline]
1970    fn sub(self, rhs: Vec3) -> Vec3 {
1971        (*self).sub(rhs)
1972    }
1973}
1974
1975impl Rem for Vec3 {
1976    type Output = Self;
1977    #[inline]
1978    fn rem(self, rhs: Self) -> Self {
1979        Self::new(self.x.rem(rhs.x), self.y.rem(rhs.y), self.z.rem(rhs.z))
1980    }
1981}
1982
1983impl Rem<&Self> for Vec3 {
1984    type Output = Self;
1985    #[inline]
1986    fn rem(self, rhs: &Self) -> Self {
1987        self.rem(*rhs)
1988    }
1989}
1990
1991impl Rem<&Vec3> for &Vec3 {
1992    type Output = Vec3;
1993    #[inline]
1994    fn rem(self, rhs: &Vec3) -> Vec3 {
1995        (*self).rem(*rhs)
1996    }
1997}
1998
1999impl Rem<Vec3> for &Vec3 {
2000    type Output = Vec3;
2001    #[inline]
2002    fn rem(self, rhs: Vec3) -> Vec3 {
2003        (*self).rem(rhs)
2004    }
2005}
2006
2007impl RemAssign for Vec3 {
2008    #[inline]
2009    fn rem_assign(&mut self, rhs: Self) {
2010        self.x.rem_assign(rhs.x);
2011        self.y.rem_assign(rhs.y);
2012        self.z.rem_assign(rhs.z);
2013    }
2014}
2015
2016impl RemAssign<&Self> for Vec3 {
2017    #[inline]
2018    fn rem_assign(&mut self, rhs: &Self) {
2019        self.rem_assign(*rhs);
2020    }
2021}
2022
2023impl Rem<f32> for Vec3 {
2024    type Output = Self;
2025    #[inline]
2026    fn rem(self, rhs: f32) -> Self {
2027        Self::new(self.x.rem(rhs), self.y.rem(rhs), self.z.rem(rhs))
2028    }
2029}
2030
2031impl Rem<&f32> for Vec3 {
2032    type Output = Self;
2033    #[inline]
2034    fn rem(self, rhs: &f32) -> Self {
2035        self.rem(*rhs)
2036    }
2037}
2038
2039impl Rem<&f32> for &Vec3 {
2040    type Output = Vec3;
2041    #[inline]
2042    fn rem(self, rhs: &f32) -> Vec3 {
2043        (*self).rem(*rhs)
2044    }
2045}
2046
2047impl Rem<f32> for &Vec3 {
2048    type Output = Vec3;
2049    #[inline]
2050    fn rem(self, rhs: f32) -> Vec3 {
2051        (*self).rem(rhs)
2052    }
2053}
2054
2055impl RemAssign<f32> for Vec3 {
2056    #[inline]
2057    fn rem_assign(&mut self, rhs: f32) {
2058        self.x.rem_assign(rhs);
2059        self.y.rem_assign(rhs);
2060        self.z.rem_assign(rhs);
2061    }
2062}
2063
2064impl RemAssign<&f32> for Vec3 {
2065    #[inline]
2066    fn rem_assign(&mut self, rhs: &f32) {
2067        self.rem_assign(*rhs);
2068    }
2069}
2070
2071impl Rem<Vec3> for f32 {
2072    type Output = Vec3;
2073    #[inline]
2074    fn rem(self, rhs: Vec3) -> Vec3 {
2075        Vec3::new(self.rem(rhs.x), self.rem(rhs.y), self.rem(rhs.z))
2076    }
2077}
2078
2079impl Rem<&Vec3> for f32 {
2080    type Output = Vec3;
2081    #[inline]
2082    fn rem(self, rhs: &Vec3) -> Vec3 {
2083        self.rem(*rhs)
2084    }
2085}
2086
2087impl Rem<&Vec3> for &f32 {
2088    type Output = Vec3;
2089    #[inline]
2090    fn rem(self, rhs: &Vec3) -> Vec3 {
2091        (*self).rem(*rhs)
2092    }
2093}
2094
2095impl Rem<Vec3> for &f32 {
2096    type Output = Vec3;
2097    #[inline]
2098    fn rem(self, rhs: Vec3) -> Vec3 {
2099        (*self).rem(rhs)
2100    }
2101}
2102
2103impl AsRef<[f32; 3]> for Vec3 {
2104    #[inline]
2105    fn as_ref(&self) -> &[f32; 3] {
2106        unsafe { &*(self as *const Self as *const [f32; 3]) }
2107    }
2108}
2109
2110impl AsMut<[f32; 3]> for Vec3 {
2111    #[inline]
2112    fn as_mut(&mut self) -> &mut [f32; 3] {
2113        unsafe { &mut *(self as *mut Self as *mut [f32; 3]) }
2114    }
2115}
2116
2117impl Sum for Vec3 {
2118    #[inline]
2119    fn sum<I>(iter: I) -> Self
2120    where
2121        I: Iterator<Item = Self>,
2122    {
2123        iter.fold(Self::ZERO, Self::add)
2124    }
2125}
2126
2127impl<'a> Sum<&'a Self> for Vec3 {
2128    #[inline]
2129    fn sum<I>(iter: I) -> Self
2130    where
2131        I: Iterator<Item = &'a Self>,
2132    {
2133        iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
2134    }
2135}
2136
2137impl Product for Vec3 {
2138    #[inline]
2139    fn product<I>(iter: I) -> Self
2140    where
2141        I: Iterator<Item = Self>,
2142    {
2143        iter.fold(Self::ONE, Self::mul)
2144    }
2145}
2146
2147impl<'a> Product<&'a Self> for Vec3 {
2148    #[inline]
2149    fn product<I>(iter: I) -> Self
2150    where
2151        I: Iterator<Item = &'a Self>,
2152    {
2153        iter.fold(Self::ONE, |a, &b| Self::mul(a, b))
2154    }
2155}
2156
2157impl Neg for Vec3 {
2158    type Output = Self;
2159    #[inline]
2160    fn neg(self) -> Self {
2161        Self::new(self.x.neg(), self.y.neg(), self.z.neg())
2162    }
2163}
2164
2165impl Neg for &Vec3 {
2166    type Output = Vec3;
2167    #[inline]
2168    fn neg(self) -> Vec3 {
2169        (*self).neg()
2170    }
2171}
2172
2173impl Index<usize> for Vec3 {
2174    type Output = f32;
2175    #[inline]
2176    fn index(&self, index: usize) -> &Self::Output {
2177        match index {
2178            0 => &self.x,
2179            1 => &self.y,
2180            2 => &self.z,
2181            _ => panic!("index out of bounds"),
2182        }
2183    }
2184}
2185
2186impl IndexMut<usize> for Vec3 {
2187    #[inline]
2188    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
2189        match index {
2190            0 => &mut self.x,
2191            1 => &mut self.y,
2192            2 => &mut self.z,
2193            _ => panic!("index out of bounds"),
2194        }
2195    }
2196}
2197
2198impl fmt::Display for Vec3 {
2199    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2200        if let Some(p) = f.precision() {
2201            write!(f, "[{:.*}, {:.*}, {:.*}]", p, self.x, p, self.y, p, self.z)
2202        } else {
2203            write!(f, "[{}, {}, {}]", self.x, self.y, self.z)
2204        }
2205    }
2206}
2207
2208impl fmt::Debug for Vec3 {
2209    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2210        fmt.debug_tuple(stringify!(Vec3))
2211            .field(&self.x)
2212            .field(&self.y)
2213            .field(&self.z)
2214            .finish()
2215    }
2216}
2217
2218impl From<[f32; 3]> for Vec3 {
2219    #[inline]
2220    fn from(a: [f32; 3]) -> Self {
2221        Self::new(a[0], a[1], a[2])
2222    }
2223}
2224
2225impl From<Vec3> for [f32; 3] {
2226    #[inline]
2227    fn from(v: Vec3) -> Self {
2228        [v.x, v.y, v.z]
2229    }
2230}
2231
2232impl From<(f32, f32, f32)> for Vec3 {
2233    #[inline]
2234    fn from(t: (f32, f32, f32)) -> Self {
2235        Self::new(t.0, t.1, t.2)
2236    }
2237}
2238
2239impl From<Vec3> for (f32, f32, f32) {
2240    #[inline]
2241    fn from(v: Vec3) -> Self {
2242        (v.x, v.y, v.z)
2243    }
2244}
2245
2246impl From<(Vec2, f32)> for Vec3 {
2247    #[inline]
2248    fn from((v, z): (Vec2, f32)) -> Self {
2249        Self::new(v.x, v.y, z)
2250    }
2251}
2252
2253impl From<BVec3> for Vec3 {
2254    #[inline]
2255    fn from(v: BVec3) -> Self {
2256        Self::new(f32::from(v.x), f32::from(v.y), f32::from(v.z))
2257    }
2258}
2259
2260impl From<BVec3A> for Vec3 {
2261    #[inline]
2262    fn from(v: BVec3A) -> Self {
2263        let bool_array: [bool; 3] = v.into();
2264        Self::new(
2265            f32::from(bool_array[0]),
2266            f32::from(bool_array[1]),
2267            f32::from(bool_array[2]),
2268        )
2269    }
2270}