glam/f32/
affine2.rs

1// Generated from affine.rs.tera template. Edit the template, not the generated file.
2
3use crate::{Mat2, Mat3, Mat3A, Vec2, Vec3A};
4use core::ops::{Deref, DerefMut, Mul, MulAssign};
5
6/// A 2D affine transform, which can represent translation, rotation, scaling and shear.
7#[derive(Copy, Clone)]
8#[cfg_attr(
9    all(
10        feature = "bytemuck",
11        not(any(feature = "scalar-math", target_arch = "spirv"))
12    ),
13    derive(bytemuck::AnyBitPattern)
14)]
15#[cfg_attr(
16    all(
17        feature = "bytemuck",
18        feature = "scalar-math",
19        not(target_arch = "spirv")
20    ),
21    derive(bytemuck::Pod, bytemuck::Zeroable)
22)]
23#[repr(C)]
24pub struct Affine2 {
25    pub matrix2: Mat2,
26    pub translation: Vec2,
27}
28
29impl Affine2 {
30    /// The degenerate zero transform.
31    ///
32    /// This transforms any finite vector and point to zero.
33    /// The zero transform is non-invertible.
34    pub const ZERO: Self = Self {
35        matrix2: Mat2::ZERO,
36        translation: Vec2::ZERO,
37    };
38
39    /// The identity transform.
40    ///
41    /// Multiplying a vector with this returns the same vector.
42    pub const IDENTITY: Self = Self {
43        matrix2: Mat2::IDENTITY,
44        translation: Vec2::ZERO,
45    };
46
47    /// All NAN:s.
48    pub const NAN: Self = Self {
49        matrix2: Mat2::NAN,
50        translation: Vec2::NAN,
51    };
52
53    /// Creates an affine transform from three column vectors.
54    #[inline(always)]
55    #[must_use]
56    pub const fn from_cols(x_axis: Vec2, y_axis: Vec2, z_axis: Vec2) -> Self {
57        Self {
58            matrix2: Mat2::from_cols(x_axis, y_axis),
59            translation: z_axis,
60        }
61    }
62
63    /// Creates an affine transform from a `[f32; 6]` array stored in column major order.
64    #[inline]
65    #[must_use]
66    pub fn from_cols_array(m: &[f32; 6]) -> Self {
67        Self {
68            matrix2: Mat2::from_cols_array(&[m[0], m[1], m[2], m[3]]),
69            translation: Vec2::from_array([m[4], m[5]]),
70        }
71    }
72
73    /// Creates a `[f32; 6]` array storing data in column major order.
74    #[inline]
75    #[must_use]
76    pub fn to_cols_array(&self) -> [f32; 6] {
77        let x = &self.matrix2.x_axis;
78        let y = &self.matrix2.y_axis;
79        let z = &self.translation;
80        [x.x, x.y, y.x, y.y, z.x, z.y]
81    }
82
83    /// Creates an affine transform from a `[[f32; 2]; 3]`
84    /// 2D array stored in column major order.
85    /// If your data is in row major order you will need to `transpose` the returned
86    /// matrix.
87    #[inline]
88    #[must_use]
89    pub fn from_cols_array_2d(m: &[[f32; 2]; 3]) -> Self {
90        Self {
91            matrix2: Mat2::from_cols(m[0].into(), m[1].into()),
92            translation: m[2].into(),
93        }
94    }
95
96    /// Creates a `[[f32; 2]; 3]` 2D array storing data in
97    /// column major order.
98    /// If you require data in row major order `transpose` the matrix first.
99    #[inline]
100    #[must_use]
101    pub fn to_cols_array_2d(&self) -> [[f32; 2]; 3] {
102        [
103            self.matrix2.x_axis.into(),
104            self.matrix2.y_axis.into(),
105            self.translation.into(),
106        ]
107    }
108
109    /// Creates an affine transform from the first 6 values in `slice`.
110    ///
111    /// # Panics
112    ///
113    /// Panics if `slice` is less than 6 elements long.
114    #[inline]
115    #[must_use]
116    pub fn from_cols_slice(slice: &[f32]) -> Self {
117        Self {
118            matrix2: Mat2::from_cols_slice(&slice[0..4]),
119            translation: Vec2::from_slice(&slice[4..6]),
120        }
121    }
122
123    /// Writes the columns of `self` to the first 6 elements in `slice`.
124    ///
125    /// # Panics
126    ///
127    /// Panics if `slice` is less than 6 elements long.
128    #[inline]
129    pub fn write_cols_to_slice(self, slice: &mut [f32]) {
130        self.matrix2.write_cols_to_slice(&mut slice[0..4]);
131        self.translation.write_to_slice(&mut slice[4..6]);
132    }
133
134    /// Creates an affine transform that changes scale.
135    /// Note that if any scale is zero the transform will be non-invertible.
136    #[inline]
137    #[must_use]
138    pub fn from_scale(scale: Vec2) -> Self {
139        Self {
140            matrix2: Mat2::from_diagonal(scale),
141            translation: Vec2::ZERO,
142        }
143    }
144
145    /// Creates an affine transform from the given rotation `angle`.
146    #[inline]
147    #[must_use]
148    pub fn from_angle(angle: f32) -> Self {
149        Self {
150            matrix2: Mat2::from_angle(angle),
151            translation: Vec2::ZERO,
152        }
153    }
154
155    /// Creates an affine transformation from the given 2D `translation`.
156    #[inline]
157    #[must_use]
158    pub fn from_translation(translation: Vec2) -> Self {
159        Self {
160            matrix2: Mat2::IDENTITY,
161            translation,
162        }
163    }
164
165    /// Creates an affine transform from a 2x2 matrix (expressing scale, shear and rotation)
166    #[inline]
167    #[must_use]
168    pub fn from_mat2(matrix2: Mat2) -> Self {
169        Self {
170            matrix2,
171            translation: Vec2::ZERO,
172        }
173    }
174
175    /// Creates an affine transform from a 2x2 matrix (expressing scale, shear and rotation) and a
176    /// translation vector.
177    ///
178    /// Equivalent to
179    /// `Affine2::from_translation(translation) * Affine2::from_mat2(mat2)`
180    #[inline]
181    #[must_use]
182    pub fn from_mat2_translation(matrix2: Mat2, translation: Vec2) -> Self {
183        Self {
184            matrix2,
185            translation,
186        }
187    }
188
189    /// Creates an affine transform from the given 2D `scale`, rotation `angle` (in radians) and
190    /// `translation`.
191    ///
192    /// Equivalent to `Affine2::from_translation(translation) *
193    /// Affine2::from_angle(angle) * Affine2::from_scale(scale)`
194    #[inline]
195    #[must_use]
196    pub fn from_scale_angle_translation(scale: Vec2, angle: f32, translation: Vec2) -> Self {
197        let rotation = Mat2::from_angle(angle);
198        Self {
199            matrix2: Mat2::from_cols(rotation.x_axis * scale.x, rotation.y_axis * scale.y),
200            translation,
201        }
202    }
203
204    /// Creates an affine transform from the given 2D rotation `angle` (in radians) and
205    /// `translation`.
206    ///
207    /// Equivalent to `Affine2::from_translation(translation) * Affine2::from_angle(angle)`
208    #[inline]
209    #[must_use]
210    pub fn from_angle_translation(angle: f32, translation: Vec2) -> Self {
211        Self {
212            matrix2: Mat2::from_angle(angle),
213            translation,
214        }
215    }
216
217    /// The given `Mat3` must be an affine transform,
218    #[inline]
219    #[must_use]
220    pub fn from_mat3(m: Mat3) -> Self {
221        use crate::swizzles::Vec3Swizzles;
222        Self {
223            matrix2: Mat2::from_cols(m.x_axis.xy(), m.y_axis.xy()),
224            translation: m.z_axis.xy(),
225        }
226    }
227
228    /// The given [`Mat3A`] must be an affine transform,
229    #[inline]
230    #[must_use]
231    pub fn from_mat3a(m: Mat3A) -> Self {
232        use crate::swizzles::Vec3Swizzles;
233        Self {
234            matrix2: Mat2::from_cols(m.x_axis.xy(), m.y_axis.xy()),
235            translation: m.z_axis.xy(),
236        }
237    }
238
239    /// Extracts `scale`, `angle` and `translation` from `self`.
240    ///
241    /// The transform is expected to be non-degenerate and without shearing, or the output
242    /// will be invalid.
243    ///
244    /// # Panics
245    ///
246    /// Will panic if the determinant `self.matrix2` is zero or if the resulting scale
247    /// vector contains any zero elements when `glam_assert` is enabled.
248    #[inline]
249    #[must_use]
250    pub fn to_scale_angle_translation(self) -> (Vec2, f32, Vec2) {
251        use crate::f32::math;
252        let det = self.matrix2.determinant();
253        glam_assert!(det != 0.0);
254
255        let scale = Vec2::new(
256            self.matrix2.x_axis.length() * math::signum(det),
257            self.matrix2.y_axis.length(),
258        );
259
260        glam_assert!(scale.cmpne(Vec2::ZERO).all());
261
262        let angle = math::atan2(-self.matrix2.y_axis.x, self.matrix2.y_axis.y);
263
264        (scale, angle, self.translation)
265    }
266
267    /// Transforms the given 2D point, applying shear, scale, rotation and translation.
268    #[inline]
269    #[must_use]
270    pub fn transform_point2(&self, rhs: Vec2) -> Vec2 {
271        self.matrix2 * rhs + self.translation
272    }
273
274    /// Transforms the given 2D vector, applying shear, scale and rotation (but NOT
275    /// translation).
276    ///
277    /// To also apply translation, use [`Self::transform_point2()`] instead.
278    #[inline]
279    pub fn transform_vector2(&self, rhs: Vec2) -> Vec2 {
280        self.matrix2 * rhs
281    }
282
283    /// Returns `true` if, and only if, all elements are finite.
284    ///
285    /// If any element is either `NaN`, positive or negative infinity, this will return
286    /// `false`.
287    #[inline]
288    #[must_use]
289    pub fn is_finite(&self) -> bool {
290        self.matrix2.is_finite() && self.translation.is_finite()
291    }
292
293    /// Returns `true` if any elements are `NaN`.
294    #[inline]
295    #[must_use]
296    pub fn is_nan(&self) -> bool {
297        self.matrix2.is_nan() || self.translation.is_nan()
298    }
299
300    /// Returns true if the absolute difference of all elements between `self` and `rhs`
301    /// is less than or equal to `max_abs_diff`.
302    ///
303    /// This can be used to compare if two 3x4 matrices contain similar elements. It works
304    /// best when comparing with a known value. The `max_abs_diff` that should be used used
305    /// depends on the values being compared against.
306    ///
307    /// For more see
308    /// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
309    #[inline]
310    #[must_use]
311    pub fn abs_diff_eq(&self, rhs: Self, max_abs_diff: f32) -> bool {
312        self.matrix2.abs_diff_eq(rhs.matrix2, max_abs_diff)
313            && self.translation.abs_diff_eq(rhs.translation, max_abs_diff)
314    }
315
316    /// Return the inverse of this transform.
317    ///
318    /// Note that if the transform is not invertible the result will be invalid.
319    #[inline]
320    #[must_use]
321    pub fn inverse(&self) -> Self {
322        let matrix2 = self.matrix2.inverse();
323        // transform negative translation by the matrix inverse:
324        let translation = -(matrix2 * self.translation);
325
326        Self {
327            matrix2,
328            translation,
329        }
330    }
331
332    /// Casts all elements of `self` to `f64`.
333    #[inline]
334    #[must_use]
335    pub fn as_daffine2(&self) -> crate::DAffine2 {
336        crate::DAffine2::from_mat2_translation(self.matrix2.as_dmat2(), self.translation.as_dvec2())
337    }
338}
339
340impl Default for Affine2 {
341    #[inline(always)]
342    fn default() -> Self {
343        Self::IDENTITY
344    }
345}
346
347impl Deref for Affine2 {
348    type Target = crate::deref::Cols3<Vec2>;
349    #[inline(always)]
350    fn deref(&self) -> &Self::Target {
351        unsafe { &*(self as *const Self as *const Self::Target) }
352    }
353}
354
355impl DerefMut for Affine2 {
356    #[inline(always)]
357    fn deref_mut(&mut self) -> &mut Self::Target {
358        unsafe { &mut *(self as *mut Self as *mut Self::Target) }
359    }
360}
361
362impl PartialEq for Affine2 {
363    #[inline]
364    fn eq(&self, rhs: &Self) -> bool {
365        self.matrix2.eq(&rhs.matrix2) && self.translation.eq(&rhs.translation)
366    }
367}
368
369impl core::fmt::Debug for Affine2 {
370    fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
371        fmt.debug_struct(stringify!(Affine2))
372            .field("matrix2", &self.matrix2)
373            .field("translation", &self.translation)
374            .finish()
375    }
376}
377
378impl core::fmt::Display for Affine2 {
379    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
380        if let Some(p) = f.precision() {
381            write!(
382                f,
383                "[{:.*}, {:.*}, {:.*}]",
384                p, self.matrix2.x_axis, p, self.matrix2.y_axis, p, self.translation
385            )
386        } else {
387            write!(
388                f,
389                "[{}, {}, {}]",
390                self.matrix2.x_axis, self.matrix2.y_axis, self.translation
391            )
392        }
393    }
394}
395
396impl<'a> core::iter::Product<&'a Self> for Affine2 {
397    fn product<I>(iter: I) -> Self
398    where
399        I: Iterator<Item = &'a Self>,
400    {
401        iter.fold(Self::IDENTITY, |a, &b| a * b)
402    }
403}
404
405impl Mul for Affine2 {
406    type Output = Self;
407
408    #[inline]
409    fn mul(self, rhs: Self) -> Self {
410        Self {
411            matrix2: self.matrix2 * rhs.matrix2,
412            translation: self.matrix2 * rhs.translation + self.translation,
413        }
414    }
415}
416
417impl Mul<&Self> for Affine2 {
418    type Output = Self;
419    #[inline]
420    fn mul(self, rhs: &Self) -> Self {
421        self.mul(*rhs)
422    }
423}
424
425impl Mul<&Affine2> for &Affine2 {
426    type Output = Affine2;
427    #[inline]
428    fn mul(self, rhs: &Affine2) -> Affine2 {
429        (*self).mul(*rhs)
430    }
431}
432
433impl Mul<Affine2> for &Affine2 {
434    type Output = Affine2;
435    #[inline]
436    fn mul(self, rhs: Affine2) -> Affine2 {
437        (*self).mul(rhs)
438    }
439}
440
441impl MulAssign for Affine2 {
442    #[inline]
443    fn mul_assign(&mut self, rhs: Self) {
444        *self = self.mul(rhs);
445    }
446}
447
448impl MulAssign<&Self> for Affine2 {
449    #[inline]
450    fn mul_assign(&mut self, rhs: &Self) {
451        self.mul_assign(*rhs);
452    }
453}
454
455impl From<Affine2> for Mat3 {
456    #[inline]
457    fn from(m: Affine2) -> Self {
458        Self::from_cols(
459            m.matrix2.x_axis.extend(0.0),
460            m.matrix2.y_axis.extend(0.0),
461            m.translation.extend(1.0),
462        )
463    }
464}
465
466impl Mul<Mat3> for Affine2 {
467    type Output = Mat3;
468
469    #[inline]
470    fn mul(self, rhs: Mat3) -> Self::Output {
471        Mat3::from(self) * rhs
472    }
473}
474
475impl Mul<&Mat3> for Affine2 {
476    type Output = Mat3;
477    #[inline]
478    fn mul(self, rhs: &Mat3) -> Mat3 {
479        self.mul(*rhs)
480    }
481}
482
483impl Mul<&Mat3> for &Affine2 {
484    type Output = Mat3;
485    #[inline]
486    fn mul(self, rhs: &Mat3) -> Mat3 {
487        (*self).mul(*rhs)
488    }
489}
490
491impl Mul<Mat3> for &Affine2 {
492    type Output = Mat3;
493    #[inline]
494    fn mul(self, rhs: Mat3) -> Mat3 {
495        (*self).mul(rhs)
496    }
497}
498
499impl Mul<Affine2> for Mat3 {
500    type Output = Self;
501
502    #[inline]
503    fn mul(self, rhs: Affine2) -> Self {
504        self * Self::from(rhs)
505    }
506}
507
508impl Mul<&Affine2> for Mat3 {
509    type Output = Self;
510    #[inline]
511    fn mul(self, rhs: &Affine2) -> Self {
512        self.mul(*rhs)
513    }
514}
515
516impl Mul<&Affine2> for &Mat3 {
517    type Output = Mat3;
518    #[inline]
519    fn mul(self, rhs: &Affine2) -> Mat3 {
520        (*self).mul(*rhs)
521    }
522}
523
524impl Mul<Affine2> for &Mat3 {
525    type Output = Mat3;
526    #[inline]
527    fn mul(self, rhs: Affine2) -> Mat3 {
528        (*self).mul(rhs)
529    }
530}
531
532impl MulAssign<Affine2> for Mat3 {
533    #[inline]
534    fn mul_assign(&mut self, rhs: Affine2) {
535        *self = self.mul(rhs);
536    }
537}
538
539impl MulAssign<&Affine2> for Mat3 {
540    #[inline]
541    fn mul_assign(&mut self, rhs: &Affine2) {
542        self.mul_assign(*rhs);
543    }
544}
545
546impl Mul<Mat3A> for Affine2 {
547    type Output = Mat3A;
548
549    #[inline]
550    fn mul(self, rhs: Mat3A) -> Self::Output {
551        Mat3A::from(self) * rhs
552    }
553}
554
555impl Mul<&Mat3A> for Affine2 {
556    type Output = Mat3A;
557    #[inline]
558    fn mul(self, rhs: &Mat3A) -> Mat3A {
559        self.mul(*rhs)
560    }
561}
562
563impl Mul<&Mat3A> for &Affine2 {
564    type Output = Mat3A;
565    #[inline]
566    fn mul(self, rhs: &Mat3A) -> Mat3A {
567        (*self).mul(*rhs)
568    }
569}
570
571impl Mul<Mat3A> for &Affine2 {
572    type Output = Mat3A;
573    #[inline]
574    fn mul(self, rhs: Mat3A) -> Mat3A {
575        (*self).mul(rhs)
576    }
577}
578
579impl Mul<Affine2> for Mat3A {
580    type Output = Self;
581
582    #[inline]
583    fn mul(self, rhs: Affine2) -> Self {
584        self * Self::from(rhs)
585    }
586}
587
588impl Mul<&Affine2> for Mat3A {
589    type Output = Self;
590    #[inline]
591    fn mul(self, rhs: &Affine2) -> Self {
592        self.mul(*rhs)
593    }
594}
595
596impl Mul<&Affine2> for &Mat3A {
597    type Output = Mat3A;
598    #[inline]
599    fn mul(self, rhs: &Affine2) -> Mat3A {
600        (*self).mul(*rhs)
601    }
602}
603
604impl Mul<Affine2> for &Mat3A {
605    type Output = Mat3A;
606    #[inline]
607    fn mul(self, rhs: Affine2) -> Mat3A {
608        (*self).mul(rhs)
609    }
610}
611
612impl MulAssign<Affine2> for Mat3A {
613    #[inline]
614    fn mul_assign(&mut self, rhs: Affine2) {
615        *self = self.mul(rhs);
616    }
617}
618
619impl MulAssign<&Affine2> for Mat3A {
620    #[inline]
621    fn mul_assign(&mut self, rhs: &Affine2) {
622        self.mul_assign(*rhs);
623    }
624}
625
626impl From<Affine2> for Mat3A {
627    #[inline]
628    fn from(m: Affine2) -> Self {
629        Self::from_cols(
630            Vec3A::from((m.matrix2.x_axis, 0.0)),
631            Vec3A::from((m.matrix2.y_axis, 0.0)),
632            Vec3A::from((m.translation, 1.0)),
633        )
634    }
635}