khora_data/ecs/components/transform.rs
1// Copyright 2025 eraflo
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use khora_core::math::{Mat4, Quaternion, Vec3};
16use khora_macros::Component;
17
18/// A component that describes an entity's position, rotation, and scale
19/// relative to its `Parent`. If the entity has no `Parent`, this is relative
20/// to the world origin.
21///
22/// This is the component that users and other systems should modify. A dedicated
23/// transform propagation system will use this component's value to calculate
24/// the final `GlobalTransform`.
25#[derive(Debug, Clone, Copy, PartialEq, Component)]
26pub struct Transform {
27 /// The translation (position) of the entity.
28 pub translation: Vec3,
29 /// The rotation of the entity, represented as a quaternion.
30 pub rotation: Quaternion,
31 /// The scale of the entity.
32 pub scale: Vec3,
33}
34
35impl Transform {
36 /// Creates a new `Transform` with a given translation, rotation, and scale.
37 pub fn new(translation: Vec3, rotation: Quaternion, scale: Vec3) -> Self {
38 Self {
39 translation,
40 rotation,
41 scale,
42 }
43 }
44
45 /// Creates a new `Transform` with a given translation, and identity rotation/scale.
46 pub fn from_translation(translation: Vec3) -> Self {
47 Self {
48 translation,
49 rotation: Quaternion::IDENTITY,
50 scale: Vec3::ONE,
51 }
52 }
53
54 /// Creates a new identity `Transform`, with no translation, rotation, or scaling.
55 /// This represents the origin.
56 pub fn identity() -> Self {
57 Self {
58 translation: Vec3::ZERO,
59 rotation: Quaternion::IDENTITY,
60 scale: Vec3::ONE,
61 }
62 }
63
64 /// Calculates the `Mat4` transformation matrix from this component's
65 /// translation, rotation, and scale.
66 ///
67 /// The final matrix is calculated in the standard `Scale -> Rotate -> Translate` order.
68 pub fn to_mat4(&self) -> Mat4 {
69 // T * R * S
70 Mat4::from_translation(self.translation)
71 * Mat4::from_quat(self.rotation)
72 * Mat4::from_scale(self.scale)
73 }
74}
75
76impl Default for Transform {
77 /// Returns the identity `Transform`.
78 fn default() -> Self {
79 Self::identity()
80 }
81}