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