glam/f64/
daffine2.rs

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