Skip to main content

glam/f32/sse2/
vec4.rs

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