khora_data/ecs/components/global_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::{affine_transform::AffineTransform, Mat4};
16use khora_macros::Component;
17
18/// A component that stores the final, calculated, world-space transformation of an entity.
19///
20/// This component's value is the result of combining the entity's local `Transform`
21/// with the `GlobalTransform` of its `Parent`, recursively up to the root of the scene.
22///
23/// It is intended to be **read-only** for most systems (like rendering and physics).
24/// It should only be written to by the dedicated transform propagation system.
25/// This acts as a cache to avoid re-calculating the full transform hierarchy every time
26/// it's needed.
27#[derive(Debug, Clone, Copy, PartialEq, Component)]
28#[component(domain = Spatial, provenance = Derived)]
29pub struct GlobalTransform(pub AffineTransform);
30
31impl GlobalTransform {
32 /// Creates a new `GlobalTransform` from a `Mat4`.
33 pub fn new(matrix: Mat4) -> Self {
34 Self(AffineTransform(matrix))
35 }
36
37 /// Creates a new identity `GlobalTransform`.
38 pub fn identity() -> Self {
39 Self(AffineTransform::IDENTITY)
40 }
41
42 /// Returns the inner `Mat4` representation.
43 pub fn to_matrix(&self) -> Mat4 {
44 self.0.into()
45 }
46
47 /// Creates a `GlobalTransform` representing a translation.
48 pub fn at_position(position: khora_core::math::Vec3) -> Self {
49 Self::new(Mat4::from_translation(position))
50 }
51}
52
53impl Default for GlobalTransform {
54 /// Returns the identity `GlobalTransform`.
55 fn default() -> Self {
56 Self::identity()
57 }
58}