revier_glam/f32/sse2/
mat2.rs

1// Generated from mat.rs.tera template. Edit the template, not the generated file.
2
3use crate::{f32::math, swizzles::*, DMat2, Mat3, Mat3A, Vec2};
4#[cfg(not(target_arch = "spirv"))]
5use core::fmt;
6use core::iter::{Product, Sum};
7use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
8
9#[cfg(target_arch = "x86")]
10use core::arch::x86::*;
11#[cfg(target_arch = "x86_64")]
12use core::arch::x86_64::*;
13
14#[repr(C)]
15union UnionCast {
16    a: [f32; 4],
17    v: Mat2,
18}
19
20/// Creates a 2x2 matrix from two column vectors.
21#[inline(always)]
22pub const fn mat2(x_axis: Vec2, y_axis: Vec2) -> Mat2 {
23    Mat2::from_cols(x_axis, y_axis)
24}
25
26/// A 2x2 column major matrix.
27///
28/// SIMD vector types are used for storage on supported platforms.
29///
30/// This type is 16 byte aligned.
31#[derive(Clone, Copy)]
32#[repr(transparent)]
33pub struct Mat2(pub(crate) __m128);
34
35impl Mat2 {
36    /// A 2x2 matrix with all elements set to `0.0`.
37    pub const ZERO: Self = Self::from_cols(Vec2::ZERO, Vec2::ZERO);
38
39    /// A 2x2 identity matrix, where all diagonal elements are `1`, and all off-diagonal elements are `0`.
40    pub const IDENTITY: Self = Self::from_cols(Vec2::X, Vec2::Y);
41
42    /// All NAN:s.
43    pub const NAN: Self = Self::from_cols(Vec2::NAN, Vec2::NAN);
44
45    #[allow(clippy::too_many_arguments)]
46    #[inline(always)]
47    const fn new(m00: f32, m01: f32, m10: f32, m11: f32) -> Self {
48        unsafe {
49            UnionCast {
50                a: [m00, m01, m10, m11],
51            }
52            .v
53        }
54    }
55
56    /// Creates a 2x2 matrix from two column vectors.
57    #[inline(always)]
58    pub const fn from_cols(x_axis: Vec2, y_axis: Vec2) -> Self {
59        unsafe {
60            UnionCast {
61                a: [x_axis.x, x_axis.y, y_axis.x, y_axis.y],
62            }
63            .v
64        }
65    }
66
67    /// Creates a 2x2 matrix from a `[f32; 4]` array stored in column major order.
68    /// If your data is stored in row major you will need to `transpose` the returned
69    /// matrix.
70    #[inline]
71    pub const fn from_cols_array(m: &[f32; 4]) -> Self {
72        Self::new(m[0], m[1], m[2], m[3])
73    }
74
75    /// Creates a `[f32; 4]` array storing data in column major order.
76    /// If you require data in row major order `transpose` the matrix first.
77    #[inline]
78    pub const fn to_cols_array(&self) -> [f32; 4] {
79        unsafe { *(self as *const Self as *const [f32; 4]) }
80    }
81
82    /// Creates a 2x2 matrix from a `[[f32; 2]; 2]` 2D array stored in column major order.
83    /// If your data is in row major order you will need to `transpose` the returned
84    /// matrix.
85    #[inline]
86    pub const fn from_cols_array_2d(m: &[[f32; 2]; 2]) -> Self {
87        Self::from_cols(Vec2::from_array(m[0]), Vec2::from_array(m[1]))
88    }
89
90    /// Creates a `[[f32; 2]; 2]` 2D array storing data in column major order.
91    /// If you require data in row major order `transpose` the matrix first.
92    #[inline]
93    pub const fn to_cols_array_2d(&self) -> [[f32; 2]; 2] {
94        unsafe { *(self as *const Self as *const [[f32; 2]; 2]) }
95    }
96
97    /// Creates a 2x2 matrix with its diagonal set to `diagonal` and all other entries set to 0.
98    #[doc(alias = "scale")]
99    #[inline]
100    pub const fn from_diagonal(diagonal: Vec2) -> Self {
101        Self::new(diagonal.x, 0.0, 0.0, diagonal.y)
102    }
103
104    /// Creates a 2x2 matrix containing the combining non-uniform `scale` and rotation of
105    /// `angle` (in radians).
106    #[inline]
107    pub fn from_scale_angle(scale: Vec2, angle: f32) -> Self {
108        let (sin, cos) = math::sin_cos(angle);
109        Self::new(cos * scale.x, sin * scale.x, -sin * scale.y, cos * scale.y)
110    }
111
112    /// Creates a 2x2 matrix containing a rotation of `angle` (in radians).
113    #[inline]
114    pub fn from_angle(angle: f32) -> Self {
115        let (sin, cos) = math::sin_cos(angle);
116        Self::new(cos, sin, -sin, cos)
117    }
118
119    /// Creates a 2x2 matrix from a 3x3 matrix, discarding the 2nd row and column.
120    #[inline]
121    pub fn from_mat3(m: Mat3) -> Self {
122        Self::from_cols(m.x_axis.xy(), m.y_axis.xy())
123    }
124
125    /// Creates a 2x2 matrix from a 3x3 matrix, discarding the 2nd row and column.
126    #[inline]
127    pub fn from_mat3a(m: Mat3A) -> Self {
128        Self::from_cols(m.x_axis.xy(), m.y_axis.xy())
129    }
130
131    /// Creates a 2x2 matrix from the first 4 values in `slice`.
132    ///
133    /// # Panics
134    ///
135    /// Panics if `slice` is less than 4 elements long.
136    #[inline]
137    pub const fn from_cols_slice(slice: &[f32]) -> Self {
138        Self::new(slice[0], slice[1], slice[2], slice[3])
139    }
140
141    /// Writes the columns of `self` to the first 4 elements in `slice`.
142    ///
143    /// # Panics
144    ///
145    /// Panics if `slice` is less than 4 elements long.
146    #[inline]
147    pub fn write_cols_to_slice(self, slice: &mut [f32]) {
148        slice[0] = self.x_axis.x;
149        slice[1] = self.x_axis.y;
150        slice[2] = self.y_axis.x;
151        slice[3] = self.y_axis.y;
152    }
153
154    /// Returns the matrix column for the given `index`.
155    ///
156    /// # Panics
157    ///
158    /// Panics if `index` is greater than 1.
159    #[inline]
160    pub fn col(&self, index: usize) -> Vec2 {
161        match index {
162            0 => self.x_axis,
163            1 => self.y_axis,
164            _ => panic!("index out of bounds"),
165        }
166    }
167
168    /// Returns a mutable reference to the matrix column for the given `index`.
169    ///
170    /// # Panics
171    ///
172    /// Panics if `index` is greater than 1.
173    #[inline]
174    pub fn col_mut(&mut self, index: usize) -> &mut Vec2 {
175        match index {
176            0 => &mut self.x_axis,
177            1 => &mut self.y_axis,
178            _ => panic!("index out of bounds"),
179        }
180    }
181
182    /// Returns the matrix row for the given `index`.
183    ///
184    /// # Panics
185    ///
186    /// Panics if `index` is greater than 1.
187    #[inline]
188    pub fn row(&self, index: usize) -> Vec2 {
189        match index {
190            0 => Vec2::new(self.x_axis.x, self.y_axis.x),
191            1 => Vec2::new(self.x_axis.y, self.y_axis.y),
192            _ => panic!("index out of bounds"),
193        }
194    }
195
196    /// Returns `true` if, and only if, all elements are finite.
197    /// If any element is either `NaN`, positive or negative infinity, this will return `false`.
198    #[inline]
199    pub fn is_finite(&self) -> bool {
200        self.x_axis.is_finite() && self.y_axis.is_finite()
201    }
202
203    /// Returns `true` if any elements are `NaN`.
204    #[inline]
205    pub fn is_nan(&self) -> bool {
206        self.x_axis.is_nan() || self.y_axis.is_nan()
207    }
208
209    /// Returns the transpose of `self`.
210    #[must_use]
211    #[inline]
212    pub fn transpose(&self) -> Self {
213        Self(unsafe { _mm_shuffle_ps(self.0, self.0, 0b11_01_10_00) })
214    }
215
216    /// Returns the determinant of `self`.
217    #[inline]
218    pub fn determinant(&self) -> f32 {
219        unsafe {
220            let abcd = self.0;
221            let dcba = _mm_shuffle_ps(abcd, abcd, 0b00_01_10_11);
222            let prod = _mm_mul_ps(abcd, dcba);
223            let det = _mm_sub_ps(prod, _mm_shuffle_ps(prod, prod, 0b01_01_01_01));
224            _mm_cvtss_f32(det)
225        }
226    }
227
228    /// Returns the inverse of `self`.
229    ///
230    /// If the matrix is not invertible the returned matrix will be invalid.
231    ///
232    /// # Panics
233    ///
234    /// Will panic if the determinant of `self` is zero when `glam_assert` is enabled.
235    #[must_use]
236    #[inline]
237    pub fn inverse(&self) -> Self {
238        unsafe {
239            const SIGN: __m128 = crate::sse2::m128_from_f32x4([1.0, -1.0, -1.0, 1.0]);
240            let abcd = self.0;
241            let dcba = _mm_shuffle_ps(abcd, abcd, 0b00_01_10_11);
242            let prod = _mm_mul_ps(abcd, dcba);
243            let sub = _mm_sub_ps(prod, _mm_shuffle_ps(prod, prod, 0b01_01_01_01));
244            let det = _mm_shuffle_ps(sub, sub, 0b00_00_00_00);
245            let tmp = _mm_div_ps(SIGN, det);
246            glam_assert!(Mat2(tmp).is_finite());
247            let dbca = _mm_shuffle_ps(abcd, abcd, 0b00_10_01_11);
248            Self(_mm_mul_ps(dbca, tmp))
249        }
250    }
251
252    /// Transforms a 2D vector.
253    #[inline]
254    pub fn mul_vec2(&self, rhs: Vec2) -> Vec2 {
255        unsafe {
256            use crate::Align16;
257            use core::mem::MaybeUninit;
258            let abcd = self.0;
259            let xxyy = _mm_set_ps(rhs.y, rhs.y, rhs.x, rhs.x);
260            let axbxcydy = _mm_mul_ps(abcd, xxyy);
261            let cydyaxbx = _mm_shuffle_ps(axbxcydy, axbxcydy, 0b01_00_11_10);
262            let result = _mm_add_ps(axbxcydy, cydyaxbx);
263            let mut out: MaybeUninit<Align16<Vec2>> = MaybeUninit::uninit();
264            _mm_store_ps(out.as_mut_ptr().cast(), result);
265            out.assume_init().0
266        }
267    }
268
269    /// Multiplies two 2x2 matrices.
270    #[inline]
271    pub fn mul_mat2(&self, rhs: &Self) -> Self {
272        unsafe {
273            let abcd = self.0;
274            let rhs = rhs.0;
275            let xxyy0 = _mm_shuffle_ps(rhs, rhs, 0b01_01_00_00);
276            let xxyy1 = _mm_shuffle_ps(rhs, rhs, 0b11_11_10_10);
277            let axbxcydy0 = _mm_mul_ps(abcd, xxyy0);
278            let axbxcydy1 = _mm_mul_ps(abcd, xxyy1);
279            let cydyaxbx0 = _mm_shuffle_ps(axbxcydy0, axbxcydy0, 0b01_00_11_10);
280            let cydyaxbx1 = _mm_shuffle_ps(axbxcydy1, axbxcydy1, 0b01_00_11_10);
281            let result0 = _mm_add_ps(axbxcydy0, cydyaxbx0);
282            let result1 = _mm_add_ps(axbxcydy1, cydyaxbx1);
283            Self(_mm_shuffle_ps(result0, result1, 0b01_00_01_00))
284        }
285    }
286
287    /// Adds two 2x2 matrices.
288    #[inline]
289    pub fn add_mat2(&self, rhs: &Self) -> Self {
290        Self(unsafe { _mm_add_ps(self.0, rhs.0) })
291    }
292
293    /// Subtracts two 2x2 matrices.
294    #[inline]
295    pub fn sub_mat2(&self, rhs: &Self) -> Self {
296        Self(unsafe { _mm_sub_ps(self.0, rhs.0) })
297    }
298
299    /// Multiplies a 2x2 matrix by a scalar.
300    #[inline]
301    pub fn mul_scalar(&self, rhs: f32) -> Self {
302        Self(unsafe { _mm_mul_ps(self.0, _mm_set_ps1(rhs)) })
303    }
304
305    /// Returns true if the absolute difference of all elements between `self` and `rhs`
306    /// is less than or equal to `max_abs_diff`.
307    ///
308    /// This can be used to compare if two matrices contain similar elements. It works best
309    /// when comparing with a known value. The `max_abs_diff` that should be used used
310    /// depends on the values being compared against.
311    ///
312    /// For more see
313    /// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
314    #[inline]
315    pub fn abs_diff_eq(&self, rhs: Self, max_abs_diff: f32) -> bool {
316        self.x_axis.abs_diff_eq(rhs.x_axis, max_abs_diff)
317            && self.y_axis.abs_diff_eq(rhs.y_axis, max_abs_diff)
318    }
319
320    #[inline]
321    pub fn as_dmat2(&self) -> DMat2 {
322        DMat2::from_cols(self.x_axis.as_dvec2(), self.y_axis.as_dvec2())
323    }
324}
325
326impl Default for Mat2 {
327    #[inline]
328    fn default() -> Self {
329        Self::IDENTITY
330    }
331}
332
333impl Add<Mat2> for Mat2 {
334    type Output = Self;
335    #[inline]
336    fn add(self, rhs: Self) -> Self::Output {
337        self.add_mat2(&rhs)
338    }
339}
340
341impl AddAssign<Mat2> for Mat2 {
342    #[inline]
343    fn add_assign(&mut self, rhs: Self) {
344        *self = self.add_mat2(&rhs);
345    }
346}
347
348impl Sub<Mat2> for Mat2 {
349    type Output = Self;
350    #[inline]
351    fn sub(self, rhs: Self) -> Self::Output {
352        self.sub_mat2(&rhs)
353    }
354}
355
356impl SubAssign<Mat2> for Mat2 {
357    #[inline]
358    fn sub_assign(&mut self, rhs: Self) {
359        *self = self.sub_mat2(&rhs);
360    }
361}
362
363impl Neg for Mat2 {
364    type Output = Self;
365    #[inline]
366    fn neg(self) -> Self::Output {
367        Self(unsafe { _mm_xor_ps(self.0, _mm_set1_ps(-0.0)) })
368    }
369}
370
371impl Mul<Mat2> for Mat2 {
372    type Output = Self;
373    #[inline]
374    fn mul(self, rhs: Self) -> Self::Output {
375        self.mul_mat2(&rhs)
376    }
377}
378
379impl MulAssign<Mat2> for Mat2 {
380    #[inline]
381    fn mul_assign(&mut self, rhs: Self) {
382        *self = self.mul_mat2(&rhs);
383    }
384}
385
386impl Mul<Vec2> for Mat2 {
387    type Output = Vec2;
388    #[inline]
389    fn mul(self, rhs: Vec2) -> Self::Output {
390        self.mul_vec2(rhs)
391    }
392}
393
394impl Mul<Mat2> for f32 {
395    type Output = Mat2;
396    #[inline]
397    fn mul(self, rhs: Mat2) -> Self::Output {
398        rhs.mul_scalar(self)
399    }
400}
401
402impl Mul<f32> for Mat2 {
403    type Output = Self;
404    #[inline]
405    fn mul(self, rhs: f32) -> Self::Output {
406        self.mul_scalar(rhs)
407    }
408}
409
410impl MulAssign<f32> for Mat2 {
411    #[inline]
412    fn mul_assign(&mut self, rhs: f32) {
413        *self = self.mul_scalar(rhs);
414    }
415}
416
417impl Sum<Self> for Mat2 {
418    fn sum<I>(iter: I) -> Self
419    where
420        I: Iterator<Item = Self>,
421    {
422        iter.fold(Self::ZERO, Self::add)
423    }
424}
425
426impl<'a> Sum<&'a Self> for Mat2 {
427    fn sum<I>(iter: I) -> Self
428    where
429        I: Iterator<Item = &'a Self>,
430    {
431        iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
432    }
433}
434
435impl Product for Mat2 {
436    fn product<I>(iter: I) -> Self
437    where
438        I: Iterator<Item = Self>,
439    {
440        iter.fold(Self::IDENTITY, Self::mul)
441    }
442}
443
444impl<'a> Product<&'a Self> for Mat2 {
445    fn product<I>(iter: I) -> Self
446    where
447        I: Iterator<Item = &'a Self>,
448    {
449        iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
450    }
451}
452
453impl PartialEq for Mat2 {
454    #[inline]
455    fn eq(&self, rhs: &Self) -> bool {
456        self.x_axis.eq(&rhs.x_axis) && self.y_axis.eq(&rhs.y_axis)
457    }
458}
459
460#[cfg(not(target_arch = "spirv"))]
461impl AsRef<[f32; 4]> for Mat2 {
462    #[inline]
463    fn as_ref(&self) -> &[f32; 4] {
464        unsafe { &*(self as *const Self as *const [f32; 4]) }
465    }
466}
467
468#[cfg(not(target_arch = "spirv"))]
469impl AsMut<[f32; 4]> for Mat2 {
470    #[inline]
471    fn as_mut(&mut self) -> &mut [f32; 4] {
472        unsafe { &mut *(self as *mut Self as *mut [f32; 4]) }
473    }
474}
475
476impl core::ops::Deref for Mat2 {
477    type Target = crate::deref::Cols2<Vec2>;
478    #[inline]
479    fn deref(&self) -> &Self::Target {
480        unsafe { &*(self as *const Self as *const Self::Target) }
481    }
482}
483
484impl core::ops::DerefMut for Mat2 {
485    #[inline]
486    fn deref_mut(&mut self) -> &mut Self::Target {
487        unsafe { &mut *(self as *mut Self as *mut Self::Target) }
488    }
489}
490
491#[cfg(not(target_arch = "spirv"))]
492impl fmt::Debug for Mat2 {
493    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
494        fmt.debug_struct(stringify!(Mat2))
495            .field("x_axis", &self.x_axis)
496            .field("y_axis", &self.y_axis)
497            .finish()
498    }
499}
500
501#[cfg(not(target_arch = "spirv"))]
502impl fmt::Display for Mat2 {
503    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
504        write!(f, "[{}, {}]", self.x_axis, self.y_axis)
505    }
506}