Skip to main content

glam/f32/
affine3a.rs

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