Skip to main content

re_core/
transform.rs

1use glam::{Affine3A, Mat4, Quat, Vec3};
2use serde::{Deserialize, Serialize};
3
4/// Translation / Rotation / Scale. Rotation is a quaternion stored as `[x, y, z, w]`.
5#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
6pub struct Transform {
7    pub translation: [f32; 3],
8    pub rotation: [f32; 4],
9    pub scale: [f32; 3],
10}
11
12impl Default for Transform {
13    fn default() -> Self {
14        Self {
15            translation: [0.0, 0.0, 0.0],
16            rotation: [0.0, 0.0, 0.0, 1.0],
17            scale: [1.0, 1.0, 1.0],
18        }
19    }
20}
21
22impl Transform {
23    pub const IDENTITY: Transform = Self {
24        translation: [0.0, 0.0, 0.0],
25        rotation: [0.0, 0.0, 0.0, 1.0],
26        scale: [1.0, 1.0, 1.0],
27    };
28
29    pub fn from_parts(translation: Vec3, rotation: Quat, scale: Vec3) -> Self {
30        Self {
31            translation: translation.to_array(),
32            rotation: rotation.to_array(),
33            scale: scale.to_array(),
34        }
35    }
36
37    pub fn translation_vec(&self) -> Vec3 {
38        Vec3::from_array(self.translation)
39    }
40
41    pub fn rotation_quat(&self) -> Quat {
42        Quat::from_array(self.rotation)
43    }
44
45    pub fn scale_vec(&self) -> Vec3 {
46        Vec3::from_array(self.scale)
47    }
48
49    pub fn to_mat4(&self) -> Mat4 {
50        Mat4::from_scale_rotation_translation(
51            self.scale_vec(),
52            self.rotation_quat(),
53            self.translation_vec(),
54        )
55    }
56
57    /// Decompose an arbitrary affine matrix back into TRS.
58    /// Returns `None` for degenerate (non-invertible) matrices.
59    pub fn from_mat4(m: &Mat4) -> Option<Self> {
60        let affine = Affine3A::from_mat4(*m);
61        let (scale, rotation, translation) = affine.to_scale_rotation_translation();
62        if !scale.is_finite() || scale.to_array().iter().any(|s| s.abs() < f32::EPSILON) {
63            return None;
64        }
65        Some(Self::from_parts(translation, rotation, scale))
66    }
67
68    /// Concatenate: apply `self` first, then `other` (i.e. `self * other`).
69    pub fn then(&self, other: &Transform) -> Transform {
70        Transform::from_mat4(&(self.to_mat4() * other.to_mat4())).unwrap_or_default()
71    }
72}