vkmEngine 1.0.0
A C++ game engine · vkmengine.com
Loading...
Searching...
No Matches
transform.h
1#pragma once
2
3#include <glm/glm.hpp>
4#include <glm/gtc/quaternion.hpp>
5#include <glm/gtc/matrix_transform.hpp>
6
7#include "core/math/rotation.h"
8#include "core/reflect.h"
9
10namespace Vkm::Engine {
11
17struct Transform {
18 glm::vec3 position = {0.0f, 0.0f, 0.0f};
19 glm::quat rotation = {1.0f, 0.0f, 0.0f, 0.0f};
20 glm::vec3 scale = {1.0f, 1.0f, 1.0f};
21
28 static glm::mat4 computeModelMatrix(const Transform& transform) {
29 const glm::mat4 rot = glm::mat4_cast(transform.rotation);
30
31 glm::mat4 model;
32 model[0] = rot[0] * transform.scale.x;
33 model[1] = rot[1] * transform.scale.y;
34 model[2] = rot[2] * transform.scale.z;
35 model[3] = glm::vec4(transform.position, 1.0f);
36
37 return model;
38 }
39
50 static Transform fromModelMatrix(const glm::mat4& model) {
51 const glm::mat3 basis(model);
52
53 Transform out;
54 out.position = glm::vec3(model[3]);
55 out.scale = {glm::length(basis[0]), glm::length(basis[1]), glm::length(basis[2])};
56
57 // No rotation reproduces a mirror, so the flip goes on the scale axis
58 // Math::worldRotationOf takes it off.
59 if (glm::determinant(basis) < 0.0f) out.scale.x = -out.scale.x;
60
61 out.rotation = Math::worldRotationOf(model);
62
63 return out;
64 }
65
72 static glm::mat4 computeView(const Transform& transform) {
73 return glm::lookAt(
74 transform.position,
75 transform.position + Math::computeForward(transform.rotation),
76 Math::computeUp(transform.rotation)
77 );
78 }
79};
80
81} // namespace Vkm::Engine
82
83VKM_REFLECT_BEGIN(::Vkm::Engine::Transform)
84 VKM_F(position)
85 VKM_F(rotation)
86 VKM_F(scale)
87VKM_REFLECT_END()
Local position, rotation and scale of an entity.
Definition transform.h:17
static glm::mat4 computeModelMatrix(const Transform &transform)
Compute the model matrix from transform data.
Definition transform.h:28
glm::vec3 scale
Local scale.
Definition transform.h:20
static glm::mat4 computeView(const Transform &transform)
Compute the view matrix from a transform.
Definition transform.h:72
static Transform fromModelMatrix(const glm::mat4 &model)
Recover the TRS that computeModelMatrix() would have built model from.
Definition transform.h:50
glm::quat rotation
Local rotation.
Definition transform.h:19
glm::vec3 position
Local position.
Definition transform.h:18