Skip to main content

vrm_runtime/
transform.rs

1use glam::{Mat4, Quat, Vec3};
2
3/// A node transform stored as a 4x4 matrix (column-major order).
4///
5/// Wraps a `glam::Mat4` in a plain `[[f32; 4]; 4]` so it can cross FFI
6/// boundaries; every operation goes through `glam` under the hood.
7#[derive(Debug, Clone, Copy, PartialEq)]
8pub struct Transform {
9    matrix: [[f32; 4]; 4],
10}
11
12impl Transform {
13    /// Identity transform with no translation, rotation, or scale.
14    pub const IDENTITY: Self = Self {
15        matrix: [
16            [1.0, 0.0, 0.0, 0.0],
17            [0.0, 1.0, 0.0, 0.0],
18            [0.0, 0.0, 1.0, 0.0],
19            [0.0, 0.0, 0.0, 1.0],
20        ],
21    };
22
23    /// Creates a transform from a column-major matrix array.
24    pub fn from_matrix(matrix: [[f32; 4]; 4]) -> Self {
25        Self { matrix }
26    }
27
28    /// Creates a transform from a `glam` matrix.
29    pub fn from_mat4(mat: Mat4) -> Self {
30        Self {
31            matrix: mat.to_cols_array_2d(),
32        }
33    }
34
35    /// Creates a transform containing only a translation.
36    pub fn from_translation(translation: Vec3) -> Self {
37        Self::from_mat4(Mat4::from_translation(translation))
38    }
39
40    /// Creates a transform from scale, rotation, and translation components.
41    pub fn from_scale_rotation_translation(scale: Vec3, rotation: Quat, translation: Vec3) -> Self {
42        Self::from_mat4(Mat4::from_scale_rotation_translation(
43            scale,
44            rotation,
45            translation,
46        ))
47    }
48
49    /// Returns the underlying column-major matrix array.
50    pub fn matrix(&self) -> &[[f32; 4]; 4] {
51        &self.matrix
52    }
53
54    /// Converts this value into a `glam` matrix.
55    pub fn to_mat4(&self) -> Mat4 {
56        Mat4::from_cols_array_2d(&self.matrix)
57    }
58
59    /// Extracts the translation component.
60    pub fn translation(&self) -> Vec3 {
61        let (_scale, _rotation, translation) = self.to_scale_rotation_translation();
62        translation
63    }
64
65    /// Decomposes this transform into scale, rotation, and translation.
66    pub fn to_scale_rotation_translation(&self) -> (Vec3, Quat, Vec3) {
67        self.to_mat4().to_scale_rotation_translation()
68    }
69
70    /// Composes this transform with `rhs` using matrix multiplication.
71    pub fn multiply(self, rhs: Self) -> Self {
72        Self::from_mat4(self.to_mat4() * rhs.to_mat4())
73    }
74}
75
76impl From<Mat4> for Transform {
77    fn from(mat: Mat4) -> Self {
78        Self::from_mat4(mat)
79    }
80}
81
82impl From<Transform> for Mat4 {
83    fn from(t: Transform) -> Self {
84        t.to_mat4()
85    }
86}