Skip to main content

glam/f32/neon/
vec4.rs

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