[go: up one dir, main page]

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