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
5#[cfg(not(target_arch = "spirv"))]
6use core::fmt;
7use core::iter::{Product, Sum};
8use core::{f32, ops::*};
9
10/// Creates a 2-dimensional vector.
11#[inline(always)]
12#[must_use]
13pub const fn vec2(x: f32, y: f32) -> Vec2 {
14    Vec2::new(x, y)
15}
16
17/// A 2-dimensional vector.
18#[derive(Clone, Copy, PartialEq)]
19#[cfg_attr(feature = "cuda", repr(align(8)))]
20#[cfg_attr(not(target_arch = "spirv"), repr(C))]
21#[cfg_attr(target_arch = "spirv", repr(simd))]
22pub struct Vec2 {
23    pub x: f32,
24    pub y: f32,
25}
26
27impl Vec2 {
28    /// All zeroes.
29    pub const ZERO: Self = Self::splat(0.0);
30
31    /// All ones.
32    pub const ONE: Self = Self::splat(1.0);
33
34    /// All negative ones.
35    pub const NEG_ONE: Self = Self::splat(-1.0);
36
37    /// All `f32::MIN`.
38    pub const MIN: Self = Self::splat(f32::MIN);
39
40    /// All `f32::MAX`.
41    pub const MAX: Self = Self::splat(f32::MAX);
42
43    /// All `f32::NAN`.
44    pub const NAN: Self = Self::splat(f32::NAN);
45
46    /// All `f32::INFINITY`.
47    pub const INFINITY: Self = Self::splat(f32::INFINITY);
48
49    /// All `f32::NEG_INFINITY`.
50    pub const NEG_INFINITY: Self = Self::splat(f32::NEG_INFINITY);
51
52    /// A unit vector pointing along the positive X axis.
53    pub const X: Self = Self::new(1.0, 0.0);
54
55    /// A unit vector pointing along the positive Y axis.
56    pub const Y: Self = Self::new(0.0, 1.0);
57
58    /// A unit vector pointing along the negative X axis.
59    pub const NEG_X: Self = Self::new(-1.0, 0.0);
60
61    /// A unit vector pointing along the negative Y axis.
62    pub const NEG_Y: Self = Self::new(0.0, -1.0);
63
64    /// The unit axes.
65    pub const AXES: [Self; 2] = [Self::X, Self::Y];
66
67    /// Creates a new vector.
68    #[inline(always)]
69    #[must_use]
70    pub const fn new(x: f32, y: f32) -> Self {
71        Self { x, y }
72    }
73
74    /// Creates a vector with all elements set to `v`.
75    #[inline]
76    #[must_use]
77    pub const fn splat(v: f32) -> Self {
78        Self { x: v, y: v }
79    }
80
81    /// Creates a vector from the elements in `if_true` and `if_false`, selecting which to use
82    /// for each element of `self`.
83    ///
84    /// A true element in the mask uses the corresponding element from `if_true`, and false
85    /// uses the element from `if_false`.
86    #[inline]
87    #[must_use]
88    pub fn select(mask: BVec2, if_true: Self, if_false: Self) -> Self {
89        Self {
90            x: if mask.test(0) { if_true.x } else { if_false.x },
91            y: if mask.test(1) { if_true.y } else { if_false.y },
92        }
93    }
94
95    /// Creates a new vector from an array.
96    #[inline]
97    #[must_use]
98    pub const fn from_array(a: [f32; 2]) -> Self {
99        Self::new(a[0], a[1])
100    }
101
102    /// `[x, y]`
103    #[inline]
104    #[must_use]
105    pub const fn to_array(&self) -> [f32; 2] {
106        [self.x, self.y]
107    }
108
109    /// Creates a vector from the first 2 values in `slice`.
110    ///
111    /// # Panics
112    ///
113    /// Panics if `slice` is less than 2 elements long.
114    #[inline]
115    #[must_use]
116    pub const fn from_slice(slice: &[f32]) -> Self {
117        Self::new(slice[0], slice[1])
118    }
119
120    /// Writes the elements of `self` to the first 2 elements in `slice`.
121    ///
122    /// # Panics
123    ///
124    /// Panics if `slice` is less than 2 elements long.
125    #[inline]
126    pub fn write_to_slice(self, slice: &mut [f32]) {
127        slice[0] = self.x;
128        slice[1] = self.y;
129    }
130
131    /// Creates a 3D vector from `self` and the given `z` value.
132    #[inline]
133    #[must_use]
134    pub const fn extend(self, z: f32) -> Vec3 {
135        Vec3::new(self.x, self.y, z)
136    }
137
138    /// Creates a 2D vector from `self` with the given value of `x`.
139    #[inline]
140    #[must_use]
141    pub fn with_x(mut self, x: f32) -> Self {
142        self.x = x;
143        self
144    }
145
146    /// Creates a 2D vector from `self` with the given value of `y`.
147    #[inline]
148    #[must_use]
149    pub fn with_y(mut self, y: f32) -> Self {
150        self.y = y;
151        self
152    }
153
154    /// Computes the dot product of `self` and `rhs`.
155    #[inline]
156    #[must_use]
157    pub fn dot(self, rhs: Self) -> f32 {
158        (self.x * rhs.x) + (self.y * rhs.y)
159    }
160
161    /// Returns a vector where every component is the dot product of `self` and `rhs`.
162    #[inline]
163    #[must_use]
164    pub fn dot_into_vec(self, rhs: Self) -> Self {
165        Self::splat(self.dot(rhs))
166    }
167
168    /// Returns a vector containing the minimum values for each element of `self` and `rhs`.
169    ///
170    /// In other words this computes `[self.x.min(rhs.x), self.y.min(rhs.y), ..]`.
171    #[inline]
172    #[must_use]
173    pub fn min(self, rhs: Self) -> Self {
174        Self {
175            x: self.x.min(rhs.x),
176            y: self.y.min(rhs.y),
177        }
178    }
179
180    /// Returns a vector containing the maximum values for each element of `self` and `rhs`.
181    ///
182    /// In other words this computes `[self.x.max(rhs.x), self.y.max(rhs.y), ..]`.
183    #[inline]
184    #[must_use]
185    pub fn max(self, rhs: Self) -> Self {
186        Self {
187            x: self.x.max(rhs.x),
188            y: self.y.max(rhs.y),
189        }
190    }
191
192    /// Component-wise clamping of values, similar to [`f32::clamp`].
193    ///
194    /// Each element in `min` must be less-or-equal to the corresponding element in `max`.
195    ///
196    /// # Panics
197    ///
198    /// Will panic if `min` is greater than `max` when `glam_assert` is enabled.
199    #[inline]
200    #[must_use]
201    pub fn clamp(self, min: Self, max: Self) -> Self {
202        glam_assert!(min.cmple(max).all(), "clamp: expected min <= max");
203        self.max(min).min(max)
204    }
205
206    /// Returns the horizontal minimum of `self`.
207    ///
208    /// In other words this computes `min(x, y, ..)`.
209    #[inline]
210    #[must_use]
211    pub fn min_element(self) -> f32 {
212        self.x.min(self.y)
213    }
214
215    /// Returns the horizontal maximum of `self`.
216    ///
217    /// In other words this computes `max(x, y, ..)`.
218    #[inline]
219    #[must_use]
220    pub fn max_element(self) -> f32 {
221        self.x.max(self.y)
222    }
223
224    /// Returns the sum of all elements of `self`.
225    ///
226    /// In other words, this computes `self.x + self.y + ..`.
227    #[inline]
228    #[must_use]
229    pub fn element_sum(self) -> f32 {
230        self.x + self.y
231    }
232
233    /// Returns the product of all elements of `self`.
234    ///
235    /// In other words, this computes `self.x * self.y * ..`.
236    #[inline]
237    #[must_use]
238    pub fn element_product(self) -> f32 {
239        self.x * self.y
240    }
241
242    /// Returns a vector mask containing the result of a `==` comparison for each element of
243    /// `self` and `rhs`.
244    ///
245    /// In other words, this computes `[self.x == rhs.x, self.y == rhs.y, ..]` for all
246    /// elements.
247    #[inline]
248    #[must_use]
249    pub fn cmpeq(self, rhs: Self) -> BVec2 {
250        BVec2::new(self.x.eq(&rhs.x), self.y.eq(&rhs.y))
251    }
252
253    /// Returns a vector mask containing the result of a `!=` comparison for each element of
254    /// `self` and `rhs`.
255    ///
256    /// In other words this computes `[self.x != rhs.x, self.y != rhs.y, ..]` for all
257    /// elements.
258    #[inline]
259    #[must_use]
260    pub fn cmpne(self, rhs: Self) -> BVec2 {
261        BVec2::new(self.x.ne(&rhs.x), self.y.ne(&rhs.y))
262    }
263
264    /// Returns a vector mask containing the result of a `>=` comparison for each element of
265    /// `self` and `rhs`.
266    ///
267    /// In other words this computes `[self.x >= rhs.x, self.y >= rhs.y, ..]` for all
268    /// elements.
269    #[inline]
270    #[must_use]
271    pub fn cmpge(self, rhs: Self) -> BVec2 {
272        BVec2::new(self.x.ge(&rhs.x), self.y.ge(&rhs.y))
273    }
274
275    /// Returns a vector mask containing the result of a `>` comparison for each element of
276    /// `self` and `rhs`.
277    ///
278    /// In other words this computes `[self.x > rhs.x, self.y > rhs.y, ..]` for all
279    /// elements.
280    #[inline]
281    #[must_use]
282    pub fn cmpgt(self, rhs: Self) -> BVec2 {
283        BVec2::new(self.x.gt(&rhs.x), self.y.gt(&rhs.y))
284    }
285
286    /// Returns a vector mask containing the result of a `<=` comparison for each element of
287    /// `self` and `rhs`.
288    ///
289    /// In other words this computes `[self.x <= rhs.x, self.y <= rhs.y, ..]` for all
290    /// elements.
291    #[inline]
292    #[must_use]
293    pub fn cmple(self, rhs: Self) -> BVec2 {
294        BVec2::new(self.x.le(&rhs.x), self.y.le(&rhs.y))
295    }
296
297    /// Returns a vector mask containing the result of a `<` comparison for each element of
298    /// `self` and `rhs`.
299    ///
300    /// In other words this computes `[self.x < rhs.x, self.y < rhs.y, ..]` for all
301    /// elements.
302    #[inline]
303    #[must_use]
304    pub fn cmplt(self, rhs: Self) -> BVec2 {
305        BVec2::new(self.x.lt(&rhs.x), self.y.lt(&rhs.y))
306    }
307
308    /// Returns a vector containing the absolute value of each element of `self`.
309    #[inline]
310    #[must_use]
311    pub fn abs(self) -> Self {
312        Self {
313            x: math::abs(self.x),
314            y: math::abs(self.y),
315        }
316    }
317
318    /// Returns a vector with elements representing the sign of `self`.
319    ///
320    /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
321    /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
322    /// - `NAN` if the number is `NAN`
323    #[inline]
324    #[must_use]
325    pub fn signum(self) -> Self {
326        Self {
327            x: math::signum(self.x),
328            y: math::signum(self.y),
329        }
330    }
331
332    /// Returns a vector with signs of `rhs` and the magnitudes of `self`.
333    #[inline]
334    #[must_use]
335    pub fn copysign(self, rhs: Self) -> Self {
336        Self {
337            x: math::copysign(self.x, rhs.x),
338            y: math::copysign(self.y, rhs.y),
339        }
340    }
341
342    /// Returns a bitmask with the lowest 2 bits set to the sign bits from the elements of `self`.
343    ///
344    /// A negative element results in a `1` bit and a positive element in a `0` bit.  Element `x` goes
345    /// into the first lowest bit, element `y` into the second, etc.
346    #[inline]
347    #[must_use]
348    pub fn is_negative_bitmask(self) -> u32 {
349        (self.x.is_sign_negative() as u32) | (self.y.is_sign_negative() as u32) << 1
350    }
351
352    /// Returns `true` if, and only if, all elements are finite.  If any element is either
353    /// `NaN`, positive or negative infinity, this will return `false`.
354    #[inline]
355    #[must_use]
356    pub fn is_finite(self) -> bool {
357        self.x.is_finite() && self.y.is_finite()
358    }
359
360    /// Returns `true` if any elements are `NaN`.
361    #[inline]
362    #[must_use]
363    pub fn is_nan(self) -> bool {
364        self.x.is_nan() || self.y.is_nan()
365    }
366
367    /// Performs `is_nan` on each element of self, returning a vector mask of the results.
368    ///
369    /// In other words, this computes `[x.is_nan(), y.is_nan(), z.is_nan(), w.is_nan()]`.
370    #[inline]
371    #[must_use]
372    pub fn is_nan_mask(self) -> BVec2 {
373        BVec2::new(self.x.is_nan(), self.y.is_nan())
374    }
375
376    /// Computes the length of `self`.
377    #[doc(alias = "magnitude")]
378    #[inline]
379    #[must_use]
380    pub fn length(self) -> f32 {
381        math::sqrt(self.dot(self))
382    }
383
384    /// Computes the squared length of `self`.
385    ///
386    /// This is faster than `length()` as it avoids a square root operation.
387    #[doc(alias = "magnitude2")]
388    #[inline]
389    #[must_use]
390    pub fn length_squared(self) -> f32 {
391        self.dot(self)
392    }
393
394    /// Computes `1.0 / length()`.
395    ///
396    /// For valid results, `self` must _not_ be of length zero.
397    #[inline]
398    #[must_use]
399    pub fn length_recip(self) -> f32 {
400        self.length().recip()
401    }
402
403    /// Computes the Euclidean distance between two points in space.
404    #[inline]
405    #[must_use]
406    pub fn distance(self, rhs: Self) -> f32 {
407        (self - rhs).length()
408    }
409
410    /// Compute the squared euclidean distance between two points in space.
411    #[inline]
412    #[must_use]
413    pub fn distance_squared(self, rhs: Self) -> f32 {
414        (self - rhs).length_squared()
415    }
416
417    /// Returns the element-wise quotient of [Euclidean division] of `self` by `rhs`.
418    #[inline]
419    #[must_use]
420    pub fn div_euclid(self, rhs: Self) -> Self {
421        Self::new(
422            math::div_euclid(self.x, rhs.x),
423            math::div_euclid(self.y, rhs.y),
424        )
425    }
426
427    /// Returns the element-wise remainder of [Euclidean division] of `self` by `rhs`.
428    ///
429    /// [Euclidean division]: f32::rem_euclid
430    #[inline]
431    #[must_use]
432    pub fn rem_euclid(self, rhs: Self) -> Self {
433        Self::new(
434            math::rem_euclid(self.x, rhs.x),
435            math::rem_euclid(self.y, rhs.y),
436        )
437    }
438
439    /// Returns `self` normalized to length 1.0.
440    ///
441    /// For valid results, `self` must _not_ be of length zero, nor very close to zero.
442    ///
443    /// See also [`Self::try_normalize()`] and [`Self::normalize_or_zero()`].
444    ///
445    /// Panics
446    ///
447    /// Will panic if `self` is zero length when `glam_assert` is enabled.
448    #[inline]
449    #[must_use]
450    pub fn normalize(self) -> Self {
451        #[allow(clippy::let_and_return)]
452        let normalized = self.mul(self.length_recip());
453        glam_assert!(normalized.is_finite());
454        normalized
455    }
456
457    /// Returns `self` normalized to length 1.0 if possible, else returns `None`.
458    ///
459    /// In particular, if the input is zero (or very close to zero), or non-finite,
460    /// the result of this operation will be `None`.
461    ///
462    /// See also [`Self::normalize_or_zero()`].
463    #[inline]
464    #[must_use]
465    pub fn try_normalize(self) -> Option<Self> {
466        let rcp = self.length_recip();
467        if rcp.is_finite() && rcp > 0.0 {
468            Some(self * rcp)
469        } else {
470            None
471        }
472    }
473
474    /// Returns `self` normalized to length 1.0 if possible, else returns a
475    /// fallback value.
476    ///
477    /// In particular, if the input is zero (or very close to zero), or non-finite,
478    /// the result of this operation will be the fallback value.
479    ///
480    /// See also [`Self::try_normalize()`].
481    #[inline]
482    #[must_use]
483    pub fn normalize_or(self, fallback: Self) -> Self {
484        let rcp = self.length_recip();
485        if rcp.is_finite() && rcp > 0.0 {
486            self * rcp
487        } else {
488            fallback
489        }
490    }
491
492    /// Returns `self` normalized to length 1.0 if possible, else returns zero.
493    ///
494    /// In particular, if the input is zero (or very close to zero), or non-finite,
495    /// the result of this operation will be zero.
496    ///
497    /// See also [`Self::try_normalize()`].
498    #[inline]
499    #[must_use]
500    pub fn normalize_or_zero(self) -> Self {
501        self.normalize_or(Self::ZERO)
502    }
503
504    /// Returns whether `self` is length `1.0` or not.
505    ///
506    /// Uses a precision threshold of approximately `1e-4`.
507    #[inline]
508    #[must_use]
509    pub fn is_normalized(self) -> bool {
510        math::abs(self.length_squared() - 1.0) <= 2e-4
511    }
512
513    /// Returns the vector projection of `self` onto `rhs`.
514    ///
515    /// `rhs` must be of non-zero length.
516    ///
517    /// # Panics
518    ///
519    /// Will panic if `rhs` is zero length when `glam_assert` is enabled.
520    #[inline]
521    #[must_use]
522    pub fn project_onto(self, rhs: Self) -> Self {
523        let other_len_sq_rcp = rhs.dot(rhs).recip();
524        glam_assert!(other_len_sq_rcp.is_finite());
525        rhs * self.dot(rhs) * other_len_sq_rcp
526    }
527
528    /// Returns the vector rejection of `self` from `rhs`.
529    ///
530    /// The vector rejection is the vector perpendicular to the projection of `self` onto
531    /// `rhs`, in rhs words the result of `self - self.project_onto(rhs)`.
532    ///
533    /// `rhs` must be of non-zero length.
534    ///
535    /// # Panics
536    ///
537    /// Will panic if `rhs` has a length of zero when `glam_assert` is enabled.
538    #[inline]
539    #[must_use]
540    pub fn reject_from(self, rhs: Self) -> Self {
541        self - self.project_onto(rhs)
542    }
543
544    /// Returns the vector projection of `self` onto `rhs`.
545    ///
546    /// `rhs` must be normalized.
547    ///
548    /// # Panics
549    ///
550    /// Will panic if `rhs` is not normalized when `glam_assert` is enabled.
551    #[inline]
552    #[must_use]
553    pub fn project_onto_normalized(self, rhs: Self) -> Self {
554        glam_assert!(rhs.is_normalized());
555        rhs * self.dot(rhs)
556    }
557
558    /// Returns the vector rejection of `self` from `rhs`.
559    ///
560    /// The vector rejection is the vector perpendicular to the projection of `self` onto
561    /// `rhs`, in rhs words the result of `self - self.project_onto(rhs)`.
562    ///
563    /// `rhs` must be normalized.
564    ///
565    /// # Panics
566    ///
567    /// Will panic if `rhs` is not normalized when `glam_assert` is enabled.
568    #[inline]
569    #[must_use]
570    pub fn reject_from_normalized(self, rhs: Self) -> Self {
571        self - self.project_onto_normalized(rhs)
572    }
573
574    /// Returns a vector containing the nearest integer to a number for each element of `self`.
575    /// Round half-way cases away from 0.0.
576    #[inline]
577    #[must_use]
578    pub fn round(self) -> Self {
579        Self {
580            x: math::round(self.x),
581            y: math::round(self.y),
582        }
583    }
584
585    /// Returns a vector containing the largest integer less than or equal to a number for each
586    /// element of `self`.
587    #[inline]
588    #[must_use]
589    pub fn floor(self) -> Self {
590        Self {
591            x: math::floor(self.x),
592            y: math::floor(self.y),
593        }
594    }
595
596    /// Returns a vector containing the smallest integer greater than or equal to a number for
597    /// each element of `self`.
598    #[inline]
599    #[must_use]
600    pub fn ceil(self) -> Self {
601        Self {
602            x: math::ceil(self.x),
603            y: math::ceil(self.y),
604        }
605    }
606
607    /// Returns a vector containing the integer part each element of `self`. This means numbers are
608    /// always truncated towards zero.
609    #[inline]
610    #[must_use]
611    pub fn trunc(self) -> Self {
612        Self {
613            x: math::trunc(self.x),
614            y: math::trunc(self.y),
615        }
616    }
617
618    /// Returns a vector containing the fractional part of the vector as `self - self.trunc()`.
619    ///
620    /// Note that this differs from the GLSL implementation of `fract` which returns
621    /// `self - self.floor()`.
622    ///
623    /// Note that this is fast but not precise for large numbers.
624    #[inline]
625    #[must_use]
626    pub fn fract(self) -> Self {
627        self - self.trunc()
628    }
629
630    /// Returns a vector containing the fractional part of the vector as `self - self.floor()`.
631    ///
632    /// Note that this differs from the Rust implementation of `fract` which returns
633    /// `self - self.trunc()`.
634    ///
635    /// Note that this is fast but not precise for large numbers.
636    #[inline]
637    #[must_use]
638    pub fn fract_gl(self) -> Self {
639        self - self.floor()
640    }
641
642    /// Returns a vector containing `e^self` (the exponential function) for each element of
643    /// `self`.
644    #[inline]
645    #[must_use]
646    pub fn exp(self) -> Self {
647        Self::new(math::exp(self.x), math::exp(self.y))
648    }
649
650    /// Returns a vector containing each element of `self` raised to the power of `n`.
651    #[inline]
652    #[must_use]
653    pub fn powf(self, n: f32) -> Self {
654        Self::new(math::powf(self.x, n), math::powf(self.y, n))
655    }
656
657    /// Returns a vector containing the reciprocal `1.0/n` of each element of `self`.
658    #[inline]
659    #[must_use]
660    pub fn recip(self) -> Self {
661        Self {
662            x: 1.0 / self.x,
663            y: 1.0 / self.y,
664        }
665    }
666
667    /// Performs a linear interpolation between `self` and `rhs` based on the value `s`.
668    ///
669    /// When `s` is `0.0`, the result will be equal to `self`.  When `s` is `1.0`, the result
670    /// will be equal to `rhs`. When `s` is outside of range `[0, 1]`, the result is linearly
671    /// extrapolated.
672    #[doc(alias = "mix")]
673    #[inline]
674    #[must_use]
675    pub fn lerp(self, rhs: Self, s: f32) -> Self {
676        self + ((rhs - self) * s)
677    }
678
679    /// Moves towards `rhs` based on the value `d`.
680    ///
681    /// When `d` is `0.0`, the result will be equal to `self`. When `d` is equal to
682    /// `self.distance(rhs)`, the result will be equal to `rhs`. Will not go past `rhs`.
683    #[inline]
684    #[must_use]
685    pub fn move_towards(&self, rhs: Self, d: f32) -> Self {
686        let a = rhs - *self;
687        let len = a.length();
688        if len <= d || len <= 1e-4 {
689            return rhs;
690        }
691        *self + a / len * d
692    }
693
694    /// Calculates the midpoint between `self` and `rhs`.
695    ///
696    /// The midpoint is the average of, or halfway point between, two vectors.
697    /// `a.midpoint(b)` should yield the same result as `a.lerp(b, 0.5)`
698    /// while being slightly cheaper to compute.
699    #[inline]
700    pub fn midpoint(self, rhs: Self) -> Self {
701        (self + rhs) * 0.5
702    }
703
704    /// Returns true if the absolute difference of all elements between `self` and `rhs` is
705    /// less than or equal to `max_abs_diff`.
706    ///
707    /// This can be used to compare if two vectors contain similar elements. It works best when
708    /// comparing with a known value. The `max_abs_diff` that should be used used depends on
709    /// the values being compared against.
710    ///
711    /// For more see
712    /// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
713    #[inline]
714    #[must_use]
715    pub fn abs_diff_eq(self, rhs: Self, max_abs_diff: f32) -> bool {
716        self.sub(rhs).abs().cmple(Self::splat(max_abs_diff)).all()
717    }
718
719    /// Returns a vector with a length no less than `min` and no more than `max`
720    ///
721    /// # Panics
722    ///
723    /// Will panic if `min` is greater than `max` when `glam_assert` is enabled.
724    #[inline]
725    #[must_use]
726    pub fn clamp_length(self, min: f32, max: f32) -> Self {
727        glam_assert!(min <= max);
728        let length_sq = self.length_squared();
729        if length_sq < min * min {
730            min * (self / math::sqrt(length_sq))
731        } else if length_sq > max * max {
732            max * (self / math::sqrt(length_sq))
733        } else {
734            self
735        }
736    }
737
738    /// Returns a vector with a length no more than `max`
739    #[inline]
740    #[must_use]
741    pub fn clamp_length_max(self, max: f32) -> Self {
742        let length_sq = self.length_squared();
743        if length_sq > max * max {
744            max * (self / math::sqrt(length_sq))
745        } else {
746            self
747        }
748    }
749
750    /// Returns a vector with a length no less than `min`
751    #[inline]
752    #[must_use]
753    pub fn clamp_length_min(self, min: f32) -> Self {
754        let length_sq = self.length_squared();
755        if length_sq < min * min {
756            min * (self / math::sqrt(length_sq))
757        } else {
758            self
759        }
760    }
761
762    /// Fused multiply-add. Computes `(self * a) + b` element-wise with only one rounding
763    /// error, yielding a more accurate result than an unfused multiply-add.
764    ///
765    /// Using `mul_add` *may* be more performant than an unfused multiply-add if the target
766    /// architecture has a dedicated fma CPU instruction. However, this is not always true,
767    /// and will be heavily dependant on designing algorithms with specific target hardware in
768    /// mind.
769    #[inline]
770    #[must_use]
771    pub fn mul_add(self, a: Self, b: Self) -> Self {
772        Self::new(
773            math::mul_add(self.x, a.x, b.x),
774            math::mul_add(self.y, a.y, b.y),
775        )
776    }
777
778    /// Creates a 2D vector containing `[angle.cos(), angle.sin()]`. This can be used in
779    /// conjunction with the [`rotate()`][Self::rotate()] method, e.g.
780    /// `Vec2::from_angle(PI).rotate(Vec2::Y)` will create the vector `[-1, 0]`
781    /// and rotate [`Vec2::Y`] around it returning `-Vec2::Y`.
782    #[inline]
783    #[must_use]
784    pub fn from_angle(angle: f32) -> Self {
785        let (sin, cos) = math::sin_cos(angle);
786        Self { x: cos, y: sin }
787    }
788
789    /// Returns the angle (in radians) of this vector in the range `[-π, +π]`.
790    ///
791    /// The input does not need to be a unit vector however it must be non-zero.
792    #[inline]
793    #[must_use]
794    pub fn to_angle(self) -> f32 {
795        math::atan2(self.y, self.x)
796    }
797
798    /// Returns the angle (in radians) between `self` and `rhs` in the range `[-π, +π]`.
799    ///
800    /// The inputs do not need to be unit vectors however they must be non-zero.
801    #[inline]
802    #[must_use]
803    pub fn angle_between(self, rhs: Self) -> f32 {
804        let angle = math::acos_approx(
805            self.dot(rhs) / math::sqrt(self.length_squared() * rhs.length_squared()),
806        );
807
808        angle * math::signum(self.perp_dot(rhs))
809    }
810
811    /// Returns a vector that is equal to `self` rotated by 90 degrees.
812    #[inline]
813    #[must_use]
814    pub fn perp(self) -> Self {
815        Self {
816            x: -self.y,
817            y: self.x,
818        }
819    }
820
821    /// The perpendicular dot product of `self` and `rhs`.
822    /// Also known as the wedge product, 2D cross product, and determinant.
823    #[doc(alias = "wedge")]
824    #[doc(alias = "cross")]
825    #[doc(alias = "determinant")]
826    #[inline]
827    #[must_use]
828    pub fn perp_dot(self, rhs: Self) -> f32 {
829        (self.x * rhs.y) - (self.y * rhs.x)
830    }
831
832    /// Returns `rhs` rotated by the angle of `self`. If `self` is normalized,
833    /// then this just rotation. This is what you usually want. Otherwise,
834    /// it will be like a rotation with a multiplication by `self`'s length.
835    #[inline]
836    #[must_use]
837    pub fn rotate(self, rhs: Self) -> Self {
838        Self {
839            x: self.x * rhs.x - self.y * rhs.y,
840            y: self.y * rhs.x + self.x * rhs.y,
841        }
842    }
843
844    /// Casts all elements of `self` to `f64`.
845    #[inline]
846    #[must_use]
847    pub fn as_dvec2(&self) -> crate::DVec2 {
848        crate::DVec2::new(self.x as f64, self.y as f64)
849    }
850
851    /// Casts all elements of `self` to `i16`.
852    #[inline]
853    #[must_use]
854    pub fn as_i16vec2(&self) -> crate::I16Vec2 {
855        crate::I16Vec2::new(self.x as i16, self.y as i16)
856    }
857
858    /// Casts all elements of `self` to `u16`.
859    #[inline]
860    #[must_use]
861    pub fn as_u16vec2(&self) -> crate::U16Vec2 {
862        crate::U16Vec2::new(self.x as u16, self.y as u16)
863    }
864
865    /// Casts all elements of `self` to `i32`.
866    #[inline]
867    #[must_use]
868    pub fn as_ivec2(&self) -> crate::IVec2 {
869        crate::IVec2::new(self.x as i32, self.y as i32)
870    }
871
872    /// Casts all elements of `self` to `u32`.
873    #[inline]
874    #[must_use]
875    pub fn as_uvec2(&self) -> crate::UVec2 {
876        crate::UVec2::new(self.x as u32, self.y as u32)
877    }
878
879    /// Casts all elements of `self` to `i64`.
880    #[inline]
881    #[must_use]
882    pub fn as_i64vec2(&self) -> crate::I64Vec2 {
883        crate::I64Vec2::new(self.x as i64, self.y as i64)
884    }
885
886    /// Casts all elements of `self` to `u64`.
887    #[inline]
888    #[must_use]
889    pub fn as_u64vec2(&self) -> crate::U64Vec2 {
890        crate::U64Vec2::new(self.x as u64, self.y as u64)
891    }
892}
893
894impl Default for Vec2 {
895    #[inline(always)]
896    fn default() -> Self {
897        Self::ZERO
898    }
899}
900
901impl Div<Vec2> for Vec2 {
902    type Output = Self;
903    #[inline]
904    fn div(self, rhs: Self) -> Self {
905        Self {
906            x: self.x.div(rhs.x),
907            y: self.y.div(rhs.y),
908        }
909    }
910}
911
912impl DivAssign<Vec2> for Vec2 {
913    #[inline]
914    fn div_assign(&mut self, rhs: Self) {
915        self.x.div_assign(rhs.x);
916        self.y.div_assign(rhs.y);
917    }
918}
919
920impl Div<f32> for Vec2 {
921    type Output = Self;
922    #[inline]
923    fn div(self, rhs: f32) -> Self {
924        Self {
925            x: self.x.div(rhs),
926            y: self.y.div(rhs),
927        }
928    }
929}
930
931impl DivAssign<f32> for Vec2 {
932    #[inline]
933    fn div_assign(&mut self, rhs: f32) {
934        self.x.div_assign(rhs);
935        self.y.div_assign(rhs);
936    }
937}
938
939impl Div<Vec2> for f32 {
940    type Output = Vec2;
941    #[inline]
942    fn div(self, rhs: Vec2) -> Vec2 {
943        Vec2 {
944            x: self.div(rhs.x),
945            y: self.div(rhs.y),
946        }
947    }
948}
949
950impl Mul<Vec2> for Vec2 {
951    type Output = Self;
952    #[inline]
953    fn mul(self, rhs: Self) -> Self {
954        Self {
955            x: self.x.mul(rhs.x),
956            y: self.y.mul(rhs.y),
957        }
958    }
959}
960
961impl MulAssign<Vec2> for Vec2 {
962    #[inline]
963    fn mul_assign(&mut self, rhs: Self) {
964        self.x.mul_assign(rhs.x);
965        self.y.mul_assign(rhs.y);
966    }
967}
968
969impl Mul<f32> for Vec2 {
970    type Output = Self;
971    #[inline]
972    fn mul(self, rhs: f32) -> Self {
973        Self {
974            x: self.x.mul(rhs),
975            y: self.y.mul(rhs),
976        }
977    }
978}
979
980impl MulAssign<f32> for Vec2 {
981    #[inline]
982    fn mul_assign(&mut self, rhs: f32) {
983        self.x.mul_assign(rhs);
984        self.y.mul_assign(rhs);
985    }
986}
987
988impl Mul<Vec2> for f32 {
989    type Output = Vec2;
990    #[inline]
991    fn mul(self, rhs: Vec2) -> Vec2 {
992        Vec2 {
993            x: self.mul(rhs.x),
994            y: self.mul(rhs.y),
995        }
996    }
997}
998
999impl Add<Vec2> for Vec2 {
1000    type Output = Self;
1001    #[inline]
1002    fn add(self, rhs: Self) -> Self {
1003        Self {
1004            x: self.x.add(rhs.x),
1005            y: self.y.add(rhs.y),
1006        }
1007    }
1008}
1009
1010impl AddAssign<Vec2> for Vec2 {
1011    #[inline]
1012    fn add_assign(&mut self, rhs: Self) {
1013        self.x.add_assign(rhs.x);
1014        self.y.add_assign(rhs.y);
1015    }
1016}
1017
1018impl Add<f32> for Vec2 {
1019    type Output = Self;
1020    #[inline]
1021    fn add(self, rhs: f32) -> Self {
1022        Self {
1023            x: self.x.add(rhs),
1024            y: self.y.add(rhs),
1025        }
1026    }
1027}
1028
1029impl AddAssign<f32> for Vec2 {
1030    #[inline]
1031    fn add_assign(&mut self, rhs: f32) {
1032        self.x.add_assign(rhs);
1033        self.y.add_assign(rhs);
1034    }
1035}
1036
1037impl Add<Vec2> for f32 {
1038    type Output = Vec2;
1039    #[inline]
1040    fn add(self, rhs: Vec2) -> Vec2 {
1041        Vec2 {
1042            x: self.add(rhs.x),
1043            y: self.add(rhs.y),
1044        }
1045    }
1046}
1047
1048impl Sub<Vec2> for Vec2 {
1049    type Output = Self;
1050    #[inline]
1051    fn sub(self, rhs: Self) -> Self {
1052        Self {
1053            x: self.x.sub(rhs.x),
1054            y: self.y.sub(rhs.y),
1055        }
1056    }
1057}
1058
1059impl SubAssign<Vec2> for Vec2 {
1060    #[inline]
1061    fn sub_assign(&mut self, rhs: Vec2) {
1062        self.x.sub_assign(rhs.x);
1063        self.y.sub_assign(rhs.y);
1064    }
1065}
1066
1067impl Sub<f32> for Vec2 {
1068    type Output = Self;
1069    #[inline]
1070    fn sub(self, rhs: f32) -> Self {
1071        Self {
1072            x: self.x.sub(rhs),
1073            y: self.y.sub(rhs),
1074        }
1075    }
1076}
1077
1078impl SubAssign<f32> for Vec2 {
1079    #[inline]
1080    fn sub_assign(&mut self, rhs: f32) {
1081        self.x.sub_assign(rhs);
1082        self.y.sub_assign(rhs);
1083    }
1084}
1085
1086impl Sub<Vec2> for f32 {
1087    type Output = Vec2;
1088    #[inline]
1089    fn sub(self, rhs: Vec2) -> Vec2 {
1090        Vec2 {
1091            x: self.sub(rhs.x),
1092            y: self.sub(rhs.y),
1093        }
1094    }
1095}
1096
1097impl Rem<Vec2> for Vec2 {
1098    type Output = Self;
1099    #[inline]
1100    fn rem(self, rhs: Self) -> Self {
1101        Self {
1102            x: self.x.rem(rhs.x),
1103            y: self.y.rem(rhs.y),
1104        }
1105    }
1106}
1107
1108impl RemAssign<Vec2> for Vec2 {
1109    #[inline]
1110    fn rem_assign(&mut self, rhs: Self) {
1111        self.x.rem_assign(rhs.x);
1112        self.y.rem_assign(rhs.y);
1113    }
1114}
1115
1116impl Rem<f32> for Vec2 {
1117    type Output = Self;
1118    #[inline]
1119    fn rem(self, rhs: f32) -> Self {
1120        Self {
1121            x: self.x.rem(rhs),
1122            y: self.y.rem(rhs),
1123        }
1124    }
1125}
1126
1127impl RemAssign<f32> for Vec2 {
1128    #[inline]
1129    fn rem_assign(&mut self, rhs: f32) {
1130        self.x.rem_assign(rhs);
1131        self.y.rem_assign(rhs);
1132    }
1133}
1134
1135impl Rem<Vec2> for f32 {
1136    type Output = Vec2;
1137    #[inline]
1138    fn rem(self, rhs: Vec2) -> Vec2 {
1139        Vec2 {
1140            x: self.rem(rhs.x),
1141            y: self.rem(rhs.y),
1142        }
1143    }
1144}
1145
1146#[cfg(not(target_arch = "spirv"))]
1147impl AsRef<[f32; 2]> for Vec2 {
1148    #[inline]
1149    fn as_ref(&self) -> &[f32; 2] {
1150        unsafe { &*(self as *const Vec2 as *const [f32; 2]) }
1151    }
1152}
1153
1154#[cfg(not(target_arch = "spirv"))]
1155impl AsMut<[f32; 2]> for Vec2 {
1156    #[inline]
1157    fn as_mut(&mut self) -> &mut [f32; 2] {
1158        unsafe { &mut *(self as *mut Vec2 as *mut [f32; 2]) }
1159    }
1160}
1161
1162impl Sum for Vec2 {
1163    #[inline]
1164    fn sum<I>(iter: I) -> Self
1165    where
1166        I: Iterator<Item = Self>,
1167    {
1168        iter.fold(Self::ZERO, Self::add)
1169    }
1170}
1171
1172impl<'a> Sum<&'a Self> for Vec2 {
1173    #[inline]
1174    fn sum<I>(iter: I) -> Self
1175    where
1176        I: Iterator<Item = &'a Self>,
1177    {
1178        iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
1179    }
1180}
1181
1182impl Product for Vec2 {
1183    #[inline]
1184    fn product<I>(iter: I) -> Self
1185    where
1186        I: Iterator<Item = Self>,
1187    {
1188        iter.fold(Self::ONE, Self::mul)
1189    }
1190}
1191
1192impl<'a> Product<&'a Self> for Vec2 {
1193    #[inline]
1194    fn product<I>(iter: I) -> Self
1195    where
1196        I: Iterator<Item = &'a Self>,
1197    {
1198        iter.fold(Self::ONE, |a, &b| Self::mul(a, b))
1199    }
1200}
1201
1202impl Neg for Vec2 {
1203    type Output = Self;
1204    #[inline]
1205    fn neg(self) -> Self {
1206        Self {
1207            x: self.x.neg(),
1208            y: self.y.neg(),
1209        }
1210    }
1211}
1212
1213impl Index<usize> for Vec2 {
1214    type Output = f32;
1215    #[inline]
1216    fn index(&self, index: usize) -> &Self::Output {
1217        match index {
1218            0 => &self.x,
1219            1 => &self.y,
1220            _ => panic!("index out of bounds"),
1221        }
1222    }
1223}
1224
1225impl IndexMut<usize> for Vec2 {
1226    #[inline]
1227    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
1228        match index {
1229            0 => &mut self.x,
1230            1 => &mut self.y,
1231            _ => panic!("index out of bounds"),
1232        }
1233    }
1234}
1235
1236#[cfg(not(target_arch = "spirv"))]
1237impl fmt::Display for Vec2 {
1238    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1239        if let Some(p) = f.precision() {
1240            write!(f, "[{:.*}, {:.*}]", p, self.x, p, self.y)
1241        } else {
1242            write!(f, "[{}, {}]", self.x, self.y)
1243        }
1244    }
1245}
1246
1247#[cfg(not(target_arch = "spirv"))]
1248impl fmt::Debug for Vec2 {
1249    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1250        fmt.debug_tuple(stringify!(Vec2))
1251            .field(&self.x)
1252            .field(&self.y)
1253            .finish()
1254    }
1255}
1256
1257impl From<[f32; 2]> for Vec2 {
1258    #[inline]
1259    fn from(a: [f32; 2]) -> Self {
1260        Self::new(a[0], a[1])
1261    }
1262}
1263
1264impl From<Vec2> for [f32; 2] {
1265    #[inline]
1266    fn from(v: Vec2) -> Self {
1267        [v.x, v.y]
1268    }
1269}
1270
1271impl From<(f32, f32)> for Vec2 {
1272    #[inline]
1273    fn from(t: (f32, f32)) -> Self {
1274        Self::new(t.0, t.1)
1275    }
1276}
1277
1278impl From<Vec2> for (f32, f32) {
1279    #[inline]
1280    fn from(v: Vec2) -> Self {
1281        (v.x, v.y)
1282    }
1283}
1284
1285impl From<BVec2> for Vec2 {
1286    #[inline]
1287    fn from(v: BVec2) -> Self {
1288        Self::new(f32::from(v.x), f32::from(v.y))
1289    }
1290}