Skip to main content

glam/f32/
vec2.rs

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