add transform class, some code tweaks

This commit is contained in:
2025-12-29 23:11:14 +08:00
parent ce41e348f8
commit 960eeaf94b
32 changed files with 368 additions and 314 deletions

View File

@ -218,7 +218,7 @@ namespace Prism
auto viewProj = m_EditorCamera.GetViewProjection(); auto viewProj = m_EditorCamera.GetViewProjection();
Renderer2D::BeginScene(viewProj, false); Renderer2D::BeginScene(viewProj, false);
glm::vec4 color = (m_SelectionMode == SelectionMode::Entity) ? glm::vec4{ 1.0f, 1.0f, 1.0f, 1.0f } : glm::vec4{ 0.2f, 0.9f, 0.2f, 1.0f }; glm::vec4 color = (m_SelectionMode == SelectionMode::Entity) ? glm::vec4{ 1.0f, 1.0f, 1.0f, 1.0f } : glm::vec4{ 0.2f, 0.9f, 0.2f, 1.0f };
Renderer::DrawAABB(selection.Mesh->BoundingBox, selection.Entity.GetComponent<TransformComponent>().Transform * selection.Mesh->Transform, color); Renderer::DrawAABB(selection.Mesh->BoundingBox, selection.Entity.GetComponent<TransformComponent>().Transformation.GetMatrix() * selection.Mesh->Transform, color);
Renderer2D::EndScene(); Renderer2D::EndScene();
Renderer::EndRenderPass(); Renderer::EndRenderPass();
} }
@ -231,7 +231,7 @@ namespace Prism
if (selection.Entity.HasComponent<BoxCollider2DComponent>()) if (selection.Entity.HasComponent<BoxCollider2DComponent>())
{ {
const auto& size = selection.Entity.GetComponent<BoxCollider2DComponent>().Size; const auto& size = selection.Entity.GetComponent<BoxCollider2DComponent>().Size;
auto [translation, rotationQuat, scale] = GetTransformDecomposition(selection.Entity.GetComponent<TransformComponent>().Transform); auto [translation, rotationQuat, scale] = GetTransformDecomposition(selection.Entity.GetComponent<TransformComponent>().Transformation.GetMatrix());
const glm::vec3 rotation = glm::eulerAngles(rotationQuat); const glm::vec3 rotation = glm::eulerAngles(rotationQuat);
Renderer::BeginRenderPass(SceneRenderer::GetFinalRenderPass(), false); Renderer::BeginRenderPass(SceneRenderer::GetFinalRenderPass(), false);
@ -786,21 +786,27 @@ namespace Prism
bool snap = Input::IsKeyPressed(Key::LEFT_CONTROL); bool snap = Input::IsKeyPressed(Key::LEFT_CONTROL);
auto& entityTransform = selection.Entity.Transform(); Transform& entityTransform = selection.Entity.Transformation();
float snapValue = GetSnapValue(); float snapValue = GetSnapValue();
float snapValues[3] = { snapValue, snapValue, snapValue }; float snapValues[3] = { snapValue, snapValue, snapValue };
if (m_SelectionMode == SelectionMode::Entity) if (m_SelectionMode == SelectionMode::Entity)
{ {
glm::mat4 transform = entityTransform.GetMatrix();
ImGuizmo::Manipulate(glm::value_ptr(m_EditorCamera.GetViewMatrix()), ImGuizmo::Manipulate(glm::value_ptr(m_EditorCamera.GetViewMatrix()),
glm::value_ptr(m_EditorCamera.GetProjectionMatrix()), glm::value_ptr(m_EditorCamera.GetProjectionMatrix()),
(ImGuizmo::OPERATION)m_GizmoType, (ImGuizmo::OPERATION)m_GizmoType,
ImGuizmo::LOCAL, ImGuizmo::LOCAL,
glm::value_ptr(entityTransform), glm::value_ptr(transform),
nullptr, nullptr,
snap ? snapValues : nullptr); snap ? snapValues : nullptr);
auto [translation, rotation, scale] = GetTransformDecomposition(transform);
entityTransform.SetTranslation(translation);
entityTransform.SetRotation(rotation);
entityTransform.SetScale(scale);
}else }else
{ {
glm::mat4 transformBase = entityTransform * selection.Mesh->Transform; glm::mat4 transformBase = entityTransform.GetMatrix() * selection.Mesh->Transform;
ImGuizmo::Manipulate(glm::value_ptr(m_EditorCamera.GetViewMatrix()), ImGuizmo::Manipulate(glm::value_ptr(m_EditorCamera.GetViewMatrix()),
glm::value_ptr(m_EditorCamera.GetProjectionMatrix()), glm::value_ptr(m_EditorCamera.GetProjectionMatrix()),
(ImGuizmo::OPERATION)m_GizmoType, (ImGuizmo::OPERATION)m_GizmoType,
@ -809,7 +815,7 @@ namespace Prism
nullptr, nullptr,
snap ? snapValues : nullptr); snap ? snapValues : nullptr);
selection.Mesh->Transform = glm::inverse(entityTransform) * transformBase; selection.Mesh->Transform = glm::inverse(entityTransform.GetMatrix()) * transformBase;
} }
} }
@ -946,8 +952,8 @@ namespace Prism
{ {
auto& submesh = submeshes[i]; auto& submesh = submeshes[i];
Ray ray = { Ray ray = {
glm::inverse(entity.Transform() * submesh.Transform) * glm::vec4(origin, 1.0f), glm::inverse(entity.Transformation().GetMatrix() * submesh.Transform) * glm::vec4(origin, 1.0f),
glm::inverse(glm::mat3(entity.Transform()) * glm::mat3(submesh.Transform)) * direction glm::inverse(glm::mat3(entity.Transformation().GetMatrix()) * glm::mat3(submesh.Transform)) * direction
}; };
float t = 0; float t = 0;

View File

@ -11,7 +11,7 @@ Entities:
Tag: Box Tag: Box
TransformComponent: TransformComponent:
Position: [0, 0, 0] Position: [0, 0, 0]
Rotation: [1, 0, 0, 0] Rotation: [0, 0, 0]
Scale: [50, 1, 50] Scale: [50, 1, 50]
MeshComponent: MeshComponent:
AssetPath: assets/meshes/Cube1m.fbx AssetPath: assets/meshes/Cube1m.fbx
@ -40,7 +40,7 @@ Entities:
Tag: Camera Tag: Camera
TransformComponent: TransformComponent:
Position: [2.808, 2.25, 0] Position: [2.808, 2.25, 0]
Rotation: [1, 0, 0, 0] Rotation: [0, 0, 0]
Scale: [1, 1, 1] Scale: [1, 1, 1]
CameraComponent: CameraComponent:
Camera: some camera data... Camera: some camera data...
@ -50,7 +50,7 @@ Entities:
Tag: Sphere Tag: Sphere
TransformComponent: TransformComponent:
Position: [-3.9876995, 1, -1.9669533e-06] Position: [-3.9876995, 1, -1.9669533e-06]
Rotation: [1, 0, 0, 0] Rotation: [0, 0, 0]
Scale: [1, 1, 1] Scale: [1, 1, 1]
MeshComponent: MeshComponent:
AssetPath: assets/meshes/Sphere1m.fbx AssetPath: assets/meshes/Sphere1m.fbx
@ -78,7 +78,7 @@ Entities:
Tag: Box Tag: Box
TransformComponent: TransformComponent:
Position: [0, 1.5, 0] Position: [0, 1.5, 0]
Rotation: [1, 0, 0, 0] Rotation: [0, 0, 0]
Scale: [2, 2, 2] Scale: [2, 2, 2]
MeshComponent: MeshComponent:
AssetPath: assets/meshes/Cube1m.fbx AssetPath: assets/meshes/Cube1m.fbx
@ -107,7 +107,7 @@ Entities:
Tag: Mesh Collider Tag: Mesh Collider
TransformComponent: TransformComponent:
Position: [-2.6045518, 1, -0.0017139912] Position: [-2.6045518, 1, -0.0017139912]
Rotation: [1, 0, 0, 0] Rotation: [0, 0, 0]
Scale: [1, 1, 1] Scale: [1, 1, 1]
MeshComponent: MeshComponent:
AssetPath: assets/meshes/Sphere1m.fbx AssetPath: assets/meshes/Sphere1m.fbx
@ -135,7 +135,7 @@ Entities:
Tag: Player Tag: Player
TransformComponent: TransformComponent:
Position: [2.8080375, 1.5, 0] Position: [2.8080375, 1.5, 0]
Rotation: [1, 0, 0, 0] Rotation: [0, 0, 0]
Scale: [2, 2, 2] Scale: [2, 2, 2]
ScriptComponent: ScriptComponent:
ModuleName: FPSExample.FPSPlayer ModuleName: FPSExample.FPSPlayer

View File

@ -16,6 +16,7 @@ namespace Example
public void OnUpdate(float ts) public void OnUpdate(float ts)
{ {
/*
Mat4 transform = GetTransform(); Mat4 transform = GetTransform();
Vec3 playerTranstation = m_PlayerEntity.GetTransform().Translation; Vec3 playerTranstation = m_PlayerEntity.GetTransform().Translation;
@ -25,6 +26,7 @@ namespace Example
translation.Y = Math.Max(translation.Y, 4.5f); translation.Y = Math.Max(translation.Y, 4.5f);
transform.Translation = translation; transform.Translation = translation;
SetTransform(transform); SetTransform(transform);
*/
} }

View File

@ -20,8 +20,6 @@ namespace FPSExample
private Entity m_CameraEntity; private Entity m_CameraEntity;
private Vec2 m_LastMousePosition; private Vec2 m_LastMousePosition;
private float m_CameraRotationX = 0.0f;
private float m_RotationY = 0.0f;
void OnCreate() void OnCreate()
{ {
@ -51,6 +49,7 @@ namespace FPSExample
m_CurrentSpeed = Input.IsKeyPressed(KeyCode.LeftControl) ? RunSpeed : WalkingSpeed; m_CurrentSpeed = Input.IsKeyPressed(KeyCode.LeftControl) ? RunSpeed : WalkingSpeed;
UpdateRotation(ts); UpdateRotation(ts);
UpdateMovement(); UpdateMovement();
UpdateCameraTransform(); UpdateCameraTransform();
@ -60,18 +59,17 @@ namespace FPSExample
{ {
Vec2 currentMousePosition = Input.GetMousePosition(); Vec2 currentMousePosition = Input.GetMousePosition();
Vec2 delta = m_LastMousePosition - currentMousePosition; Vec2 delta = m_LastMousePosition - currentMousePosition;
if (delta.X != 0)
float yRotation = delta.X * MouseSensitivity * ts;
float xRotation = delta.Y * MouseSensitivity * ts;
m_RigidBody.Rotate(new Vec3(0.0f, yRotation, 0.0f));
if (delta.X != 0 || delta.Y != 0)
{ {
m_RotationY += delta.X * MouseSensitivity * ts; m_CameraTransform.Rotation += new Vec3(xRotation, yRotation, 0.0f);
} }
m_RigidBody.Rotate(new Vec3(0.0F, delta.X * MouseSensitivity, 0.0f) * ts); m_CameraTransform.Rotation = new Vec3(Mathf.Clamp(m_CameraTransform.Rotation.X, -89.0f, 89.0f), m_CameraTransform.Rotation.YZ);
if (delta.Y != 0.0F)
{
m_CameraRotationX += delta.Y * MouseSensitivity * ts;
m_CameraRotationX = Mathf.Clamp(m_CameraRotationX, -80.0f, 80.0f);
}
m_LastMousePosition = currentMousePosition; m_LastMousePosition = currentMousePosition;
} }
@ -82,8 +80,8 @@ namespace FPSExample
{ {
RaycastHit hitInfo; RaycastHit hitInfo;
if (Input.IsKeyPressed(KeyCode.H) && if (Input.IsKeyPressed(KeyCode.H) &&
Physics.Raycast(m_CameraTransform.Transform.Translation + (m_CameraTransform.Forward * 5.0f), Physics.Raycast(m_CameraTransform.Position + (m_CameraTransform.Transform.Forward * 5.0f),
m_CameraTransform.Forward, 20.0f, out hitInfo)) m_CameraTransform.Transform.Forward, 20.0f, out hitInfo))
{ {
FindEntityByID(hitInfo.EntityID).GetComponent<MeshComponent>().Mesh.GetMaterial(0).Set("u_AlbedoColor", new Vec3(1.0f ,0.0f, 0.0f)); FindEntityByID(hitInfo.EntityID).GetComponent<MeshComponent>().Mesh.GetMaterial(0).Set("u_AlbedoColor", new Vec3(1.0f ,0.0f, 0.0f));
} }
@ -93,7 +91,7 @@ namespace FPSExample
// NOTE: The NonAlloc version of Overlap functions should be used when possible since it doesn't allocate a new array // NOTE: The NonAlloc version of Overlap functions should be used when possible since it doesn't allocate a new array
// whenever you call it. The normal versions allocates a brand new array every time. // whenever you call it. The normal versions allocates a brand new array every time.
int numColliders = Physics.OverlapBoxNonAlloc(m_Transform.Transform.Translation, new Vec3(1.0F), colliders); int numColliders = Physics.OverlapBoxNonAlloc(m_Transform.Position, new Vec3(1.0F), colliders);
Console.WriteLine("Colliders: {0}", numColliders); Console.WriteLine("Colliders: {0}", numColliders);
// When using NonAlloc it's not safe to use a foreach loop since some of the colliders may not exist // When using NonAlloc it's not safe to use a foreach loop since some of the colliders may not exist
@ -104,14 +102,14 @@ namespace FPSExample
} }
if (Input.IsKeyPressed(KeyCode.W)) if (Input.IsKeyPressed(KeyCode.W))
m_RigidBody.AddForce(m_Transform.Forward * m_CurrentSpeed); m_RigidBody.AddForce(m_Transform.Transform.Forward * m_CurrentSpeed);
else if (Input.IsKeyPressed(KeyCode.S)) else if (Input.IsKeyPressed(KeyCode.S))
m_RigidBody.AddForce(m_Transform.Forward * -m_CurrentSpeed); m_RigidBody.AddForce(m_Transform.Transform.Forward * -m_CurrentSpeed);
if (Input.IsKeyPressed(KeyCode.A)) if (Input.IsKeyPressed(KeyCode.A))
m_RigidBody.AddForce(m_Transform.Right * -m_CurrentSpeed); m_RigidBody.AddForce(m_Transform.Transform.Right * -m_CurrentSpeed);
else if (Input.IsKeyPressed(KeyCode.D)) else if (Input.IsKeyPressed(KeyCode.D))
m_RigidBody.AddForce(m_Transform.Right * m_CurrentSpeed); m_RigidBody.AddForce(m_Transform.Transform.Right * m_CurrentSpeed);
if (Input.IsKeyPressed(KeyCode.Space) && m_Colliding) if (Input.IsKeyPressed(KeyCode.Space) && m_Colliding)
m_RigidBody.AddForce(Vec3.Up * JumpForce); m_RigidBody.AddForce(Vec3.Up * JumpForce);
@ -119,19 +117,9 @@ namespace FPSExample
} }
private void UpdateCameraTransform(){ private void UpdateCameraTransform(){
Vec3 position = m_Transform.Position;
// TODO: This workflow needs to be improved. (Will be fixed by object parenting) position.Y += 1.5f;
m_CameraTransform.Position = position;
Mat4 cameraTransform = m_CameraTransform.Transform;
Vec3 cameraTranslation = cameraTransform.Translation;
Vec3 translation = m_Transform.Transform.Translation;
cameraTranslation.XZ = translation.XZ;
cameraTranslation.Y = translation.Y + 1.5F;
cameraTransform.Translation = cameraTranslation + m_CameraTransform.Forward * -Mathf.Clamp(Distance, 0, 10);
m_CameraTransform.Transform = cameraTransform;
m_CameraTransform.Rotation = new Vec3(m_CameraRotationX, m_RotationY, 0.0f);
} }
} }
} }

View File

@ -78,6 +78,7 @@ namespace Example
void OnUpdate(float ts) void OnUpdate(float ts)
{ {
/*
Mat4 transform = GetTransform(); Mat4 transform = GetTransform();
Vec3 translation = transform.Translation; Vec3 translation = transform.Translation;
translation.Y += ts * speed; translation.Y += ts * speed;
@ -91,6 +92,7 @@ namespace Example
transform.Translation = translation; transform.Translation = translation;
SetTransform(transform); SetTransform(transform);
*/
} }

View File

@ -72,9 +72,11 @@ namespace Example
if (Input.IsKeyPressed(KeyCode.R)) if (Input.IsKeyPressed(KeyCode.R))
{ {
/*
Mat4 transform = GetTransform(); Mat4 transform = GetTransform();
transform.Translation = new Vec3(0.0f); transform.Translation = new Vec3(0.0f);
SetTransform(transform); SetTransform(transform);
*/
} }
} }

View File

@ -68,17 +68,17 @@ namespace Example
} }
if (Input.IsKeyPressed(KeyCode.W)) if (Input.IsKeyPressed(KeyCode.W))
m_PhysicsBody.AddForce(m_Transform.Forward * movementForce); m_PhysicsBody.AddForce(m_Transform.Transform.Forward * movementForce);
else if (Input.IsKeyPressed(KeyCode.S)) else if (Input.IsKeyPressed(KeyCode.S))
m_PhysicsBody.AddForce(m_Transform.Forward * -movementForce); m_PhysicsBody.AddForce(m_Transform.Transform.Forward * -movementForce);
if (Input.IsKeyPressed(KeyCode.D)) if (Input.IsKeyPressed(KeyCode.D))
m_PhysicsBody.AddForce(m_Transform.Right * movementForce); m_PhysicsBody.AddForce(m_Transform.Transform.Right * movementForce);
else if (Input.IsKeyPressed(KeyCode.A)) else if (Input.IsKeyPressed(KeyCode.A))
m_PhysicsBody.AddForce(m_Transform.Right * -movementForce); m_PhysicsBody.AddForce(m_Transform.Transform.Right * -movementForce);
if (Colliding && Input.IsKeyPressed(KeyCode.Space)) if (Colliding && Input.IsKeyPressed(KeyCode.Space))
m_PhysicsBody.AddForce(m_Transform.Up * JumpForce); m_PhysicsBody.AddForce(m_Transform.Transform.Up * JumpForce);
if (Colliding) if (Colliding)
m_MeshMaterial.Set("u_AlbedoColor", new Vec3(1.0f, 0.0f, 0.0f)); m_MeshMaterial.Set("u_AlbedoColor", new Vec3(1.0f, 0.0f, 0.0f));
@ -91,9 +91,11 @@ namespace Example
if (Input.IsKeyPressed(KeyCode.R)) if (Input.IsKeyPressed(KeyCode.R))
{ {
/*
Mat4 transform = GetTransform(); Mat4 transform = GetTransform();
transform.Translation = new Vec3(0.0f); transform.Translation = new Vec3(0.0f);
SetTransform(transform); SetTransform(transform);
*/
} }
} }

View File

@ -21,6 +21,7 @@ namespace Example
public void OnUpdate(float ts) public void OnUpdate(float ts)
{ {
/*
Rotation += ts; Rotation += ts;
@ -34,19 +35,10 @@ namespace Example
translation.Z += Velocity.Z * ts; translation.Z += Velocity.Z * ts;
translation.Y -= SinkRate * ts; translation.Y -= SinkRate * ts;
/*
if (Input.IsKeyPressed(KeyCode.Up))
translation.Y += speed;
else if (Input.IsKeyPressed(KeyCode.Down))
translation.Y -= speed;
if (Input.IsKeyPressed(KeyCode.Right))
translation.X += speed;
else if (Input.IsKeyPressed(KeyCode.Left))
translation.X -= speed;
*/
transform.Translation = translation; transform.Translation = translation;
SetTransform(transform); SetTransform(transform);
*/
} }
} }

View File

@ -14,6 +14,7 @@ namespace Example
void OnUpdate(float ts) void OnUpdate(float ts)
{ {
/*
Mat4 transform = GetTransform(); Mat4 transform = GetTransform();
Vec3 translation = transform.Translation; Vec3 translation = transform.Translation;
@ -21,6 +22,7 @@ namespace Example
transform.Translation = translation; transform.Translation = translation;
SetTransform(transform); SetTransform(transform);
*/
} }
} }

View File

@ -61,18 +61,6 @@ namespace Prism
return new Entity(entityID); return new Entity(entityID);
} }
public Mat4 GetTransform()
{
Mat4 mat4Instance;
GetTransform_Native(ID, out mat4Instance);
return mat4Instance;
}
public void SetTransform(Mat4 transform)
{
SetTransform_Native(ID, ref transform);
}
public void AddCollision2DBeginCallback(Action<float> callback) public void AddCollision2DBeginCallback(Action<float> callback)
{ {
m_Collision2DBeginCallbacks += callback; m_Collision2DBeginCallbacks += callback;
@ -142,12 +130,10 @@ namespace Prism
[MethodImpl(MethodImplOptions.InternalCall)] [MethodImpl(MethodImplOptions.InternalCall)]
private static extern void CreateComponent_Native(ulong entityID, Type type); private static extern void CreateComponent_Native(ulong entityID, Type type);
[MethodImpl(MethodImplOptions.InternalCall)] [MethodImpl(MethodImplOptions.InternalCall)]
private static extern bool HasComponent_Native(ulong entityID, Type type); private static extern bool HasComponent_Native(ulong entityID, Type type);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void GetTransform_Native(ulong entityID, out Mat4 matrix);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void SetTransform_Native(ulong entityID, ref Mat4 matrix);
[MethodImpl(MethodImplOptions.InternalCall)] [MethodImpl(MethodImplOptions.InternalCall)]
private static extern ulong FindEntityByTag_Native(string tag); private static extern ulong FindEntityByTag_Native(string tag);
} }

View File

@ -3,12 +3,13 @@ namespace Prism
{ {
public static class Mathf public static class Mathf
{ {
public const float DegreeToRadians = (float)Math.PI * 2.0f / 360.0f;
public const float RadiansToDegrees = 360.0f / ((float)Math.PI * 2.0f);
public static float Clamp(float value, float min, float max) public static float Clamp(float value, float min, float max)
{ {
if (value < min) if (value < min) return min;
return min; if (value > max) return max;
if (value > max)
return max;
return value; return value;
} }
} }

View File

@ -1,56 +0,0 @@
using System;
using System.Runtime.InteropServices;
namespace Prism
{
[StructLayout(LayoutKind.Sequential)]
public struct Quaternion
{
public float X;
public float Y;
public float Z;
public float W;
public Quaternion(float x, float y, float z, float w)
{
X = x;
Y = y;
Z = z;
W = w;
}
public Quaternion(float w, Vec3 xyz)
{
X = xyz.X;
Y = xyz.Y;
Z = xyz.Z;
W = w;
}
public Quaternion(Vec3 eulerAngles)
{
Vec3 c = Vec3.Cos(eulerAngles * 0.5F);
Vec3 s = Vec3.Sin(eulerAngles * 0.5F);
W = c.X * c.Y * c.Z + s.X * s.Y * s.Z;
X = s.X * c.Y * c.Z - c.X * s.Y * s.Z;
Y = c.X * s.Y * c.Z + s.X * c.Y * s.Z;
Z = c.X * c.Y * s.Z - s.X * s.Y * c.Z;
}
public static Quaternion AngleAxis(float angle, Vec3 axis)
{
float s = (float)Math.Sin(angle * 0.5F);
return new Quaternion(s, axis * s);
}
public static Quaternion operator*(Quaternion a, Quaternion b)
{
float w = a.W * b.W - a.X * b.X - a.Y * b.Y - a.Z * b.Z;
float x = a.W * b.X + a.X * b.W + a.Y * b.Z - a.Z * b.Y;
float y = a.W * b.Y + a.Y * b.W + a.Z * b.X - a.X * b.Z;
float z = a.W * b.Z + a.Z * b.W + a.X * b.Y - a.Y * b.X;
return new Quaternion(x, y, z, w);
}
}
}

View File

@ -0,0 +1,16 @@
using System.Runtime.InteropServices;
namespace Prism
{
[StructLayout(LayoutKind.Sequential)]
public struct Transform
{
public Vec3 Position;
public Vec3 Rotation;
public Vec3 Scale;
public Vec3 Up;
public Vec3 Right;
public Vec3 Forward;
}
}

View File

@ -20,12 +20,25 @@ namespace Prism
X = Y = Z = scalar; X = Y = Z = scalar;
} }
public Vec3(Vec2 vec) { public Vec3(Vec2 vec2) {
X = vec.X; X = vec2.X;
Y = vec.Y; Y = vec2.Y;
Z = 0.0f; Z = 0.0f;
} }
public Vec3(Vec2 vec2, float z) {
X = vec2.X;
Y = vec2.Y;
Z = z;
}
public Vec3(float x, Vec2 vec2)
{
X = x;
Y = vec2.X;
Z = vec2.Y;
}
public Vec3(float x, float y, float z) public Vec3(float x, float y, float z)
{ {
X = x; X = x;
@ -33,6 +46,7 @@ namespace Prism
Z = z; Z = z;
} }
public Vec3(Vec4 vec) { public Vec3(Vec4 vec) {
X = vec.X; X = vec.X;
Y = vec.Y; Y = vec.Y;

View File

@ -1,4 +1,5 @@
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Prism namespace Prism
{ {
@ -32,17 +33,21 @@ namespace Prism
public class TransformComponent : Component public class TransformComponent : Component
{ {
public Mat4 Transform private Transform m_Transform;
public Transform Transform { get { return m_Transform; } }
public Vec3 Position
{ {
get get
{ {
Mat4 result; GetTransform_Native(Entity.ID, out m_Transform);
GetTransform_Native(Entity.ID, out result); return m_Transform.Position;
return result;
} }
set set
{ {
SetTransform_Native(Entity.ID, ref value); m_Transform.Position = value;
SetTransform_Native(Entity.ID, ref m_Transform);
} }
} }
@ -50,58 +55,35 @@ namespace Prism
{ {
get get
{ {
GetRotation_Native(Entity.ID, out Vec3 rotation); GetTransform_Native(Entity.ID, out m_Transform);
return rotation; return m_Transform.Rotation;
} }
set set
{ {
SetRotation_Native(Entity.ID, ref value); m_Transform.Rotation = value;
SetTransform_Native(Entity.ID, ref m_Transform);
} }
} }
public Vec3 Forward public Vec3 Scale
{ {
get get
{ {
GetRelativeDirection_Native(Entity.ID, out Vec3 result, ref Vec3.Forward); GetTransform_Native(Entity.ID, out m_Transform);
return result; return m_Transform.Scale;
} }
} set
public Vec3 Right
{ {
get m_Transform.Scale = value;
{ SetTransform_Native(Entity.ID, ref m_Transform);
GetRelativeDirection_Native(Entity.ID, out Vec3 result, ref Vec3.Right);
return result;
}
}
public Vec3 Up
{
get
{
GetRelativeDirection_Native(Entity.ID, out Vec3 result, ref Vec3.Up);
return result;
} }
} }
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void GetTransform_Native(ulong entityID, out Transform result);
[MethodImpl(MethodImplOptions.InternalCall)] [MethodImpl(MethodImplOptions.InternalCall)]
public static extern void GetTransform_Native(ulong entityID, out Mat4 result); internal static extern void SetTransform_Native(ulong entityID, ref Transform result);
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void SetTransform_Native(ulong entityID, ref Mat4 result);
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void GetRelativeDirection_Native(ulong entityID, out Vec3 result, ref Vec3 direction);
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void GetRotation_Native(ulong entityID, out Vec3 rotation);
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void SetRotation_Native(ulong entityID, ref Vec3 rotation);
} }

View File

@ -0,0 +1,39 @@
//
// Created by sfd on 25-12-29.
//
#include "Transform.h"
namespace Prism
{
Transform::Transform()
: m_Translation(glm::vec3(0.0f)), m_Rotation(glm::vec3(0.0f)), m_Scale(glm::vec3(1.0f))
{
RecalculateMatrix();
}
Transform::Transform(const glm::vec3& translation, const glm::vec3& rotation, const glm::vec3& scale)
: m_Translation(translation), m_Rotation(rotation), m_Scale(scale)
{
RecalculateMatrix();
}
const glm::mat4& Transform::GetMatrix()
{
if (m_HasChanged) RecalculateMatrix();
return m_Matrix;
}
void Transform::RecalculateMatrix()
{
const auto rotation = glm::quat(glm::radians(m_Rotation));
m_Up = glm::normalize(glm::rotate(rotation, glm::vec3(0.0f, 1.0f, 0.0f)));
m_Right = glm::normalize(glm::rotate(rotation, glm::vec3(1.0f, 0.0f, 0.0f)));
m_Forward = glm::normalize(glm::rotate(rotation, glm::vec3(0.0f, 0.0f, -1.0f)));
m_Matrix = glm::translate(glm::mat4(1.0f), m_Translation)
* glm::toMat4(rotation)
* glm::scale(glm::mat4(1.0f), m_Scale);
}
}

View File

@ -0,0 +1,60 @@
//
// Created by sfd on 25-12-29.
//
#ifndef TRANSFORM_H
#define TRANSFORM_H
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/gtx/common.hpp>
#include "glm/gtc/type_ptr.hpp"
namespace Prism
{
class PRISM_API Transform
{
public:
Transform();
Transform(const glm::vec3& translation, const glm::vec3& rotation = glm::vec3(0.0f), const glm::vec3& scale = glm::vec3(1.0f));
void Translate(const glm::vec3& translation) { m_Translation += translation; m_HasChanged = true;}
void Rotate(const glm::vec3& rotation) { m_Rotation += rotation; m_HasChanged = true;}
void SetTranslation(const glm::vec3& position) { m_Translation = position; m_HasChanged = true;}
void SetRotation(const glm::vec3& rotation) { m_Rotation = rotation; m_HasChanged = true;}
void SetRotation(const glm::quat& rotation) { m_Rotation = glm::degrees(glm::eulerAngles(rotation)); m_HasChanged = true;}
void SetScale(const glm::vec3& scale) { m_Scale = scale; m_HasChanged = true;}
const glm::vec3& GetTranslation() const { return m_Translation; }
const glm::vec3& GetRotation() const { return m_Rotation; }
const glm::vec3& GetScale() const { return m_Scale; }
const glm::vec3& GetUpDirection() const { return m_Up; }
const glm::vec3& GetRightDirection() const { return m_Right; }
const glm::vec3& GetForwardDirection() const { return m_Forward; }
const glm::mat4& GetMatrix();
float* Data() { return glm::value_ptr(m_Matrix); }
private:
void RecalculateMatrix();
private:
glm::vec3 m_Translation;
glm::vec3 m_Rotation;
glm::vec3 m_Scale;
glm::vec3 m_Forward, m_Right, m_Up;
glm::mat4 m_Matrix = glm::mat4(1.0f);
bool m_HasChanged = false;
};
}
#endif //TRANSFORM_H

View File

@ -644,23 +644,21 @@ namespace Prism
if (entity.HasComponent<TransformComponent>()) if (entity.HasComponent<TransformComponent>())
{ {
auto& tc = entity.GetComponent<TransformComponent>(); Transform& transform = entity.GetComponent<TransformComponent>();
if (ImGui::TreeNodeEx((void*)((uint32_t)entity | typeid(TransformComponent).hash_code()), ImGuiTreeNodeFlags_DefaultOpen, "Transform")) if (ImGui::TreeNodeEx((void*)((uint32_t)entity | typeid(TransformComponent).hash_code()), ImGuiTreeNodeFlags_DefaultOpen, "Transform"))
{ {
auto [translation, rotationQuat, scale] = GetTransformDecomposition(tc); glm::vec3 translation = transform.GetTranslation();
glm::vec3 rotation = glm::degrees(glm::eulerAngles(rotationQuat)); glm::vec3 rotation = transform.GetRotation();
glm::vec3 scale = transform.GetScale();
ImGui::Columns(2); ImGui::Columns(2);
ImGui::Text("Translation"); ImGui::Text("Translation");
ImGui::NextColumn(); ImGui::NextColumn();
ImGui::PushItemWidth(-1); ImGui::PushItemWidth(-1);
bool updateTransform = false;
if (ImGui::DragFloat3("##translation", glm::value_ptr(translation), 0.25f)) if (ImGui::DragFloat3("##translation", glm::value_ptr(translation), 0.25f))
{ {
// tc.Transform[3] = glm::vec4(translation, 1.0f); transform.SetTranslation(translation);
updateTransform = true;
} }
ImGui::PopItemWidth(); ImGui::PopItemWidth();
@ -672,8 +670,7 @@ namespace Prism
if (ImGui::DragFloat3("##rotation", glm::value_ptr(rotation), 0.25f)) if (ImGui::DragFloat3("##rotation", glm::value_ptr(rotation), 0.25f))
{ {
updateTransform = true; transform.SetRotation(rotation);
// tc.Transform[3] = glm::vec4(translation, 1.0f);
} }
ImGui::PopItemWidth(); ImGui::PopItemWidth();
@ -689,21 +686,13 @@ namespace Prism
if (scale.y == 0) scale.y = 0.01f; if (scale.y == 0) scale.y = 0.01f;
if (scale.z == 0) scale.z = 0.01f; if (scale.z == 0) scale.z = 0.01f;
updateTransform = true; transform.SetScale(scale);
} }
ImGui::PopItemWidth(); ImGui::PopItemWidth();
ImGui::NextColumn(); ImGui::NextColumn();
ImGui::Columns(1); ImGui::Columns(1);
if (updateTransform)
{
tc.Transform = glm::translate(glm::mat4(1.0f), translation) *
glm::toMat4(glm::quat(glm::radians(rotation))) *
glm::scale(glm::mat4(1.0f), scale);
}
ImGui::TreePop(); ImGui::TreePop();
} }
ImGui::Separator(); ImGui::Separator();

View File

@ -29,15 +29,6 @@ namespace Prism
static std::tuple<glm::vec3, glm::quat, glm::vec3> GetTransformDecomposition(const glm::mat4& transform)
{
glm::vec3 scale, translation, skew;
glm::vec4 perspective;
glm::quat orientation;
glm::decompose(transform, scale, orientation, translation, skew, perspective);
return { translation, orientation, scale };
}
void Physics3D::Init() void Physics3D::Init()
{ {
@ -96,7 +87,7 @@ namespace Prism
RigidBodyComponent& rigidbody = e.GetComponent<RigidBodyComponent>(); RigidBodyComponent& rigidbody = e.GetComponent<RigidBodyComponent>();
physx::PxRigidActor* actor = PhysicsWrappers::CreateActor(rigidbody, e.Transform()); physx::PxRigidActor* actor = PhysicsWrappers::CreateActor(rigidbody, e.Transformation());
if (rigidbody.BodyType == RigidBodyComponent::Type::Dynamic) if (rigidbody.BodyType == RigidBodyComponent::Type::Dynamic)
s_SimulatedEntities.push_back(e); s_SimulatedEntities.push_back(e);
@ -109,8 +100,8 @@ namespace Prism
const physx::PxMaterial* material = PhysicsWrappers::CreateMaterial(e.GetComponent<PhysicsMaterialComponent>()); const physx::PxMaterial* material = PhysicsWrappers::CreateMaterial(e.GetComponent<PhysicsMaterialComponent>());
const auto& transform = e.Transform(); const auto& transform = e.Transformation();
auto [translation, rotation, scale] = GetTransformDecomposition(transform); const auto& scale = transform.GetScale();
// Add all colliders // Add all colliders
@ -163,13 +154,13 @@ namespace Prism
for (Entity& e : s_SimulatedEntities) for (Entity& e : s_SimulatedEntities)
{ {
auto& transform = e.Transform(); auto& transform = e.Transformation();
// TODO: Come up with a better solution for scale
auto [position, rotation, scale] = GetTransformDecomposition(transform);
const auto& rb = e.GetComponent<RigidBodyComponent>(); const auto& rb = e.GetComponent<RigidBodyComponent>();
const auto actor = static_cast<physx::PxRigidActor*>(rb.RuntimeActor); const auto actor = static_cast<physx::PxRigidActor*>(rb.RuntimeActor);
transform = FromPhysXTransform(actor->getGlobalPose()) * glm::scale(glm::mat4(1.0F), scale); physx::PxTransform actorPose = actor->getGlobalPose();
transform.SetTranslation(FromPhysXVector(actorPose.p));
transform.SetRotation(FromPhysXQuat(actorPose.q));
} }
} }

View File

@ -24,7 +24,7 @@ namespace Prism
uint32_t PhysicsLayerManager::AddLayer(const std::string& name, bool setCollisions) uint32_t PhysicsLayerManager::AddLayer(const std::string& name, bool setCollisions)
{ {
const uint32_t layerId = GetNextLayerID(); const uint32_t layerId = GetNextLayerID();
const PhysicsLayer layer = { layerId, name, static_cast<uint32_t>(BIT(layerId)) }; const PhysicsLayer layer = { layerId, name, static_cast<uint32_t>(BIT(layerId)), BIT(layerId)};
s_Layers.push_back(layer); s_Layers.push_back(layer);
if (setCollisions) if (setCollisions)

View File

@ -5,12 +5,21 @@
#include "PhysicsUtils.h" #include "PhysicsUtils.h"
#define GLM_ENABLE_EXPERIMENTAL #define GLM_ENABLE_EXPERIMENTAL
#include <filesystem>
#include "glm/gtx/quaternion.hpp" #include "glm/gtx/quaternion.hpp"
#include "Prism/Script/ScriptEngine.h" #include "Prism/Script/ScriptEngine.h"
namespace Prism namespace Prism
{ {
physx::PxTransform ToPhysXTransform(const Transform& transform)
{
const physx::PxQuat r = ToPhysXQuat(glm::normalize(glm::quat(glm::radians(transform.GetRotation()))));
const physx::PxVec3 p = ToPhysXVector(transform.GetTranslation());
return physx::PxTransform{p, r};
}
physx::PxTransform ToPhysXTransform(const glm::mat4& matrix) physx::PxTransform ToPhysXTransform(const glm::mat4& matrix)
{ {
const physx::PxQuat r = ToPhysXQuat(glm::normalize(glm::toQuat(matrix))); const physx::PxQuat r = ToPhysXQuat(glm::normalize(glm::toQuat(matrix)));

View File

@ -9,10 +9,12 @@
#include <PxPhysicsAPI.h> #include <PxPhysicsAPI.h>
#include "glm/glm.hpp" #include "glm/glm.hpp"
#include "Prism/Core/Math/Transform.h"
namespace Prism namespace Prism
{ {
physx::PxTransform ToPhysXTransform(const Transform& matrix);
physx::PxTransform ToPhysXTransform(const glm::mat4& matrix); physx::PxTransform ToPhysXTransform(const glm::mat4& matrix);
physx::PxMat44 ToPhysXMatrix(const glm::mat4& matrix); physx::PxMat44 ToPhysXMatrix(const glm::mat4& matrix);
physx::PxVec3 ToPhysXVector(const glm::vec3& vector); physx::PxVec3 ToPhysXVector(const glm::vec3& vector);
@ -28,8 +30,6 @@ namespace Prism
physx::PxFilterFlags PrismFilterShader(physx::PxFilterObjectAttributes attributes0, physx::PxFilterData filterData0, physx::PxFilterObjectAttributes attributes1, physx::PxFilterFlags PrismFilterShader(physx::PxFilterObjectAttributes attributes0, physx::PxFilterData filterData0, physx::PxFilterObjectAttributes attributes1,
physx::PxFilterData filterData1, physx::PxPairFlags& pairFlags, const void* constantBlock, physx::PxU32 constantBlockSize); physx::PxFilterData filterData1, physx::PxPairFlags& pairFlags, const void* constantBlock, physx::PxU32 constantBlockSize);
} }

View File

@ -177,7 +177,7 @@ namespace Prism
return s_Physics->createScene(sceneDesc); return s_Physics->createScene(sceneDesc);
} }
physx::PxRigidActor* PhysicsWrappers::CreateActor(const RigidBodyComponent& rigidbody, const glm::mat4& transform) physx::PxRigidActor* PhysicsWrappers::CreateActor(const RigidBodyComponent& rigidbody, const Transform& transform)
{ {
physx::PxRigidActor* actor = nullptr; physx::PxRigidActor* actor = nullptr;

View File

@ -37,7 +37,7 @@ namespace Prism
{ {
public: public:
static physx::PxScene* CreateScene(); static physx::PxScene* CreateScene();
static physx::PxRigidActor* CreateActor(const RigidBodyComponent& rigidbody, const glm::mat4& transform); static physx::PxRigidActor* CreateActor(const RigidBodyComponent& rigidbody, const Transform& transform);
static void SetCollisionFilters(const physx::PxRigidActor& actor, uint32_t physicsLayer); static void SetCollisionFilters(const physx::PxRigidActor& actor, uint32_t physicsLayer);
static void AddBoxCollider(physx::PxRigidActor& actor, const physx::PxMaterial& material, const BoxColliderComponent& collider, const glm::vec3& scale = glm::vec3(0.0f)); static void AddBoxCollider(physx::PxRigidActor& actor, const physx::PxMaterial& material, const BoxColliderComponent& collider, const glm::vec3& scale = glm::vec3(0.0f));

View File

@ -12,6 +12,7 @@
#include "glm/glm.hpp" #include "glm/glm.hpp"
#include "Prism/Core/Ref.h" #include "Prism/Core/Ref.h"
#include "Prism/Core/UUID.h" #include "Prism/Core/UUID.h"
#include "Prism/Core/Math/Transform.h"
#include "Prism/Renderer/Mesh.h" #include "Prism/Renderer/Mesh.h"
namespace Prism namespace Prism
@ -37,15 +38,15 @@ namespace Prism
struct TransformComponent struct TransformComponent
{ {
glm::mat4 Transform; Transform Transformation;
TransformComponent() = default; TransformComponent() = default;
TransformComponent(const TransformComponent& other) = default; TransformComponent(const TransformComponent& other) = default;
TransformComponent(const glm::mat4& transform) TransformComponent(const Transform& transform)
: Transform(transform) {} : Transformation(transform) {}
operator glm::mat4& () { return Transform; } operator Transform& () { return Transformation; }
operator const glm::mat4& () const { return Transform; } operator const Transform& () const { return Transformation; }
}; };

View File

@ -50,8 +50,8 @@ namespace Prism
} }
const std::string& Tag() const { return m_Scene->m_Registry.get<TagComponent>(m_EntityHandle).Tag; } const std::string& Tag() const { return m_Scene->m_Registry.get<TagComponent>(m_EntityHandle).Tag; }
glm::mat4& Transform() { return m_Scene->m_Registry.get<TransformComponent>(m_EntityHandle); } Transform& Transformation() { return m_Scene->m_Registry.get<TransformComponent>(m_EntityHandle); }
const glm::mat4& Transform() const { return m_Scene->m_Registry.get<TransformComponent>(m_EntityHandle); } const Transform& Transformation() const { return m_Scene->m_Registry.get<TransformComponent>(m_EntityHandle); }
operator uint32_t () const { return (uint32_t)m_EntityHandle; } operator uint32_t () const { return (uint32_t)m_EntityHandle; }
operator entt::entity() const{ return m_EntityHandle; } operator entt::entity() const{ return m_EntityHandle; }

View File

@ -106,16 +106,6 @@ namespace Prism
ScriptEngine::OnScriptComponentDestroyed(sceneID, entityID); ScriptEngine::OnScriptComponentDestroyed(sceneID, entityID);
} }
static std::tuple<glm::vec3, glm::quat, glm::vec3> GetTransformDecomposition(const glm::mat4& transform)
{
glm::vec3 scale, translation, skew;
glm::vec4 perspective;
glm::quat orientation;
glm::decompose(transform, scale, orientation, translation, skew, perspective);
return { translation, orientation, scale };
}
Environment Environment::Load(const std::string& filepath) Environment Environment::Load(const std::string& filepath)
{ {
auto [radiance, irradiance] = SceneRenderer::CreateEnvironmentMap(filepath); auto [radiance, irradiance] = SceneRenderer::CreateEnvironmentMap(filepath);
@ -198,18 +188,17 @@ namespace Prism
for (const auto entity : view) for (const auto entity : view)
{ {
Entity e = { entity, this }; Entity e = { entity, this };
auto& transform = e.Transform(); auto& transform = e.Transformation();
const auto& rb2d = e.GetComponent<RigidBody2DComponent>(); const auto& rb2d = e.GetComponent<RigidBody2DComponent>();
const auto& position = b2Body_GetPosition(rb2d.RuntimeBodyID); const auto& position = b2Body_GetPosition(rb2d.RuntimeBodyID);
auto [translation, rotationQuat, scale] = GetTransformDecomposition(transform); const auto& rotation = transform.GetRotation();
glm::vec3 rotation = glm::eulerAngles(rotationQuat);
float angle = b2Rot_GetAngle(b2Body_GetRotation(rb2d.RuntimeBodyID)); float angle = b2Rot_GetAngle(b2Body_GetRotation(rb2d.RuntimeBodyID));
transform = glm::translate(glm::mat4(1.0f), { position.x, position.y, transform[3].z }) * transform.SetRotation({rotation.x, rotation.y, angle});
glm::toMat4(glm::quat({ rotation.x, rotation.y, angle })) * transform.SetScale(transform.GetScale());
glm::scale(glm::mat4(1.0f), scale); transform.SetTranslation({position.x, position.y, transform.GetTranslation().z});
} }
} }
@ -225,7 +214,7 @@ namespace Prism
if (!cameraEntity) if (!cameraEntity)
return; return;
glm::mat4 cameraViewMatrix = glm::inverse(cameraEntity.GetComponent<TransformComponent>().Transform); const glm::mat4 cameraViewMatrix = glm::inverse(cameraEntity.Transformation().GetMatrix());
PM_CORE_ASSERT(cameraEntity, "Scene does not contain any cameras!"); PM_CORE_ASSERT(cameraEntity, "Scene does not contain any cameras!");
SceneCamera& camera = cameraEntity.GetComponent<CameraComponent>(); SceneCamera& camera = cameraEntity.GetComponent<CameraComponent>();
camera.SetViewportSize(m_ViewportWidth, m_ViewportHeight); camera.SetViewportSize(m_ViewportWidth, m_ViewportHeight);
@ -242,7 +231,7 @@ namespace Prism
meshComponent.Mesh->OnUpdate(ts); meshComponent.Mesh->OnUpdate(ts);
// TODO: Should we render (logically) // TODO: Should we render (logically)
SceneRenderer::SubmitMesh(meshComponent, transformComponent, nullptr); SceneRenderer::SubmitMesh(meshComponent, transformComponent.Transformation.GetMatrix(), nullptr);
} }
} }
SceneRenderer::EndScene(); SceneRenderer::EndScene();
@ -284,7 +273,7 @@ namespace Prism
meshComponent.Mesh->OnUpdate(ts); meshComponent.Mesh->OnUpdate(ts);
// TODO: Should we render (logically) // TODO: Should we render (logically)
SceneRenderer::SubmitMesh(meshComponent, transformComponent); SceneRenderer::SubmitMesh(meshComponent, transformComponent.Transformation.GetMatrix());
} }
} }
@ -296,7 +285,7 @@ namespace Prism
auto& collider = e.GetComponent<BoxColliderComponent>(); auto& collider = e.GetComponent<BoxColliderComponent>();
if (m_SelectedEntity == entity) if (m_SelectedEntity == entity)
SceneRenderer::SubmitColliderMesh(collider, e.GetComponent<TransformComponent>()); SceneRenderer::SubmitColliderMesh(collider, e.GetComponent<TransformComponent>().Transformation.GetMatrix());
} }
} }
@ -308,7 +297,7 @@ namespace Prism
auto& collider = e.GetComponent<SphereColliderComponent>(); auto& collider = e.GetComponent<SphereColliderComponent>();
if (m_SelectedEntity == entity) if (m_SelectedEntity == entity)
SceneRenderer::SubmitColliderMesh(collider, e.GetComponent<TransformComponent>()); SceneRenderer::SubmitColliderMesh(collider, e.GetComponent<TransformComponent>().Transformation.GetMatrix());
} }
} }
@ -320,7 +309,7 @@ namespace Prism
auto& collider = e.GetComponent<CapsuleColliderComponent>(); auto& collider = e.GetComponent<CapsuleColliderComponent>();
if (m_SelectedEntity == entity) if (m_SelectedEntity == entity)
SceneRenderer::SubmitColliderMesh(collider, e.GetComponent<TransformComponent>()); SceneRenderer::SubmitColliderMesh(collider, e.GetComponent<TransformComponent>().Transformation.GetMatrix());
} }
} }
@ -333,7 +322,7 @@ namespace Prism
if (m_SelectedEntity == entity) if (m_SelectedEntity == entity)
{ {
SceneRenderer::SubmitColliderMesh(collider, e.GetComponent<TransformComponent>()); SceneRenderer::SubmitColliderMesh(collider, e.GetComponent<TransformComponent>().Transformation.GetMatrix());
} }
} }
} }
@ -388,8 +377,9 @@ namespace Prism
for (auto entity : view) for (auto entity : view)
{ {
Entity e = { entity, this }; Entity e = { entity, this };
UUID entityID = e.GetComponent<IDComponent>().ID; auto& transform = e.Transformation();
auto& transform = e.Transform(); const auto& position = transform.GetTranslation();
const auto& rotation = transform.GetRotation();
auto& rigidBody2D = m_Registry.get<RigidBody2DComponent>(entity); auto& rigidBody2D = m_Registry.get<RigidBody2DComponent>(entity);
b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyDef bodyDef = b2DefaultBodyDef();
@ -399,10 +389,9 @@ namespace Prism
bodyDef.type = b2_dynamicBody; bodyDef.type = b2_dynamicBody;
else if (rigidBody2D.BodyType == RigidBody2DComponent::Type::Kinematic) else if (rigidBody2D.BodyType == RigidBody2DComponent::Type::Kinematic)
bodyDef.type = b2_kinematicBody; bodyDef.type = b2_kinematicBody;
bodyDef.position = {transform[3].x, transform[3].y}; bodyDef.position = {position.x, position.y};
auto [translation, rotationQuat, scale] = GetTransformDecomposition(transform); float rotationZ = rotation.z;
float rotationZ = glm::eulerAngles(rotationQuat).z;
bodyDef.rotation = b2Rot{cos(rotationZ), sin(rotationZ)}; bodyDef.rotation = b2Rot{cos(rotationZ), sin(rotationZ)};
// box2D fixRotation renamed to motionlocks // box2D fixRotation renamed to motionlocks
@ -422,7 +411,6 @@ namespace Prism
for (auto entity : view) for (auto entity : view)
{ {
Entity e = { entity, this }; Entity e = { entity, this };
auto& transform = e.Transform();
auto& boxCollider2D = m_Registry.get<BoxCollider2DComponent>(entity); auto& boxCollider2D = m_Registry.get<BoxCollider2DComponent>(entity);
if (e.HasComponent<RigidBody2DComponent>()) if (e.HasComponent<RigidBody2DComponent>())
@ -537,7 +525,7 @@ namespace Prism
auto& idComponent = entity.AddComponent<IDComponent>(); auto& idComponent = entity.AddComponent<IDComponent>();
idComponent.ID = {}; idComponent.ID = {};
entity.AddComponent<TransformComponent>(glm::mat4(1.0f)); entity.AddComponent<TransformComponent>(Transform());
if (!name.empty()) if (!name.empty())
entity.AddComponent<TagComponent>(name); entity.AddComponent<TagComponent>(name);
@ -551,7 +539,7 @@ namespace Prism
auto& idComponent = entity.AddComponent<IDComponent>(); auto& idComponent = entity.AddComponent<IDComponent>();
idComponent.ID = uuid; idComponent.ID = uuid;
entity.AddComponent<TransformComponent>(glm::mat4(1.0f)); entity.AddComponent<TransformComponent>(Transform());
if (!name.empty()) if (!name.empty())
entity.AddComponent<TagComponent>(name); entity.AddComponent<TagComponent>(name);

View File

@ -162,16 +162,6 @@ namespace Prism
{ {
} }
static std::tuple<glm::vec3, glm::quat, glm::vec3> GetTransformDecomposition(const glm::mat4& transform)
{
glm::vec3 scale, translation, skew;
glm::vec4 perspective;
glm::quat orientation;
glm::decompose(transform, scale, orientation, translation, skew, perspective);
return { translation, orientation, scale };
}
static void SerializeEntity(YAML::Emitter& out, Entity entity) static void SerializeEntity(YAML::Emitter& out, Entity entity)
{ {
UUID uuid = entity.GetComponent<IDComponent>().ID; UUID uuid = entity.GetComponent<IDComponent>().ID;
@ -195,11 +185,10 @@ namespace Prism
out << YAML::Key << "TransformComponent"; out << YAML::Key << "TransformComponent";
out << YAML::BeginMap; // TransformComponent out << YAML::BeginMap; // TransformComponent
auto& transform = entity.GetComponent<TransformComponent>().Transform; auto& transform = entity.GetComponent<TransformComponent>().Transformation;
auto[pos, rot, scale] = GetTransformDecomposition(transform); out << YAML::Key << "Position" << YAML::Value << transform.GetTranslation();
out << YAML::Key << "Position" << YAML::Value << pos; out << YAML::Key << "Rotation" << YAML::Value << transform.GetRotation();
out << YAML::Key << "Rotation" << YAML::Value << rot; // Quat rotation out << YAML::Key << "Scale" << YAML::Value << transform.GetScale();
out << YAML::Key << "Scale" << YAML::Value << scale;
out << YAML::EndMap; // TransformComponent out << YAML::EndMap; // TransformComponent
} }
@ -542,17 +531,19 @@ namespace Prism
if (transformComponent) if (transformComponent)
{ {
// Entities always have transforms // Entities always have transforms
auto& transform = deserializedEntity.GetComponent<TransformComponent>().Transform; auto& transform = deserializedEntity.GetComponent<TransformComponent>().Transformation;
glm::vec3 translation = transformComponent["Position"].as<glm::vec3>();
glm::quat rotation = transformComponent["Rotation"].as<glm::quat>();
glm::vec3 scale = transformComponent["Scale"].as<glm::vec3>();
transform = glm::translate(glm::mat4(1.0f), translation) * auto translation = transformComponent["Position"].as<glm::vec3>();
glm::toMat4(rotation) * glm::scale(glm::mat4(1.0f), scale); auto rotation = transformComponent["Rotation"].as<glm::vec3>();
auto scale = transformComponent["Scale"].as<glm::vec3>();
transform.SetTranslation(translation);
transform.SetRotation(rotation);
transform.SetScale(scale);
PM_CORE_INFO("Entity Transform:"); PM_CORE_INFO("Entity Transform:");
PM_CORE_INFO(" Translation: {0}, {1}, {2}", translation.x, translation.y, translation.z); PM_CORE_INFO(" Translation: {0}, {1}, {2}", translation.x, translation.y, translation.z);
PM_CORE_INFO(" Rotation: {0}, {1}, {2}, {3}", rotation.w, rotation.x, rotation.y, rotation.z); PM_CORE_INFO(" Rotation: {0}, {1}, {2}", rotation.x, rotation.y, rotation.z);
PM_CORE_INFO(" Scale: {0}, {1}, {2}", scale.x, scale.y, scale.z); PM_CORE_INFO(" Scale: {0}, {1}, {2}", scale.x, scale.y, scale.z);
} }

View File

@ -162,10 +162,10 @@ namespace Prism
if (s_EnableMonoPDBDebug) if (s_EnableMonoPDBDebug)
{ {
const char* argv[2] const char* argv[]
{ {
"--debugger-agent=transport=dt_socket,address=127.0.0.1:2550,server=y,suspend=n,loglevel=3,logfile=MonoDebugger.log", "--debugger-agent=transport=dt_socket,address=127.0.0.1:2550,server=y,suspend=n",
"--soft-breakpoints" "--soft-breakpoints",
}; };
mono_jit_parse_options(2, (char**)argv); mono_jit_parse_options(2, (char**)argv);

View File

@ -60,15 +60,23 @@ namespace Prism
mono_add_internal_call("Prism.Physics::OverlapSphereNonAlloc_Native", (const void*)Prism::Script::Prism_Physics_OverlapSphereNonAlloc); mono_add_internal_call("Prism.Physics::OverlapSphereNonAlloc_Native", (const void*)Prism::Script::Prism_Physics_OverlapSphereNonAlloc);
/*
mono_add_internal_call("Prism.Entity::GetTransform_Native",(const void*)Prism::Script::Prism_Entity_GetTransform); mono_add_internal_call("Prism.Entity::GetTransform_Native",(const void*)Prism::Script::Prism_Entity_GetTransform);
mono_add_internal_call("Prism.Entity::SetTransform_Native",(const void*)Prism::Script::Prism_Entity_SetTransform); mono_add_internal_call("Prism.Entity::SetTransform_Native",(const void*)Prism::Script::Prism_Entity_SetTransform);
mono_add_internal_call("Prism.TransformComponent::GetRelativeDirection_Native", (const void*)Prism::Script::Prism_TransformComponent_GetRelativeDirection); mono_add_internal_call("Prism.TransformComponent::GetRelativeDirection_Native", (const void*)Prism::Script::Prism_TransformComponent_GetRelativeDirection);
*/
mono_add_internal_call("Prism.TransformComponent::GetTransform_Native", (const void*)Prism::Script::Prism_TransformComponent_GetTransform);
mono_add_internal_call("Prism.TransformComponent::SetTransform_Native", (const void*)Prism::Script::Prism_TransformComponent_SetTransform);
/*
mono_add_internal_call("Prism.TransformComponent::GetTransform_Native", (const void*)Prism::Script::Prism_Entity_GetTransform); mono_add_internal_call("Prism.TransformComponent::GetTransform_Native", (const void*)Prism::Script::Prism_Entity_GetTransform);
mono_add_internal_call("Prism.TransformComponent::SetTransform_Native", (const void*)Prism::Script::Prism_Entity_SetTransform); mono_add_internal_call("Prism.TransformComponent::SetTransform_Native", (const void*)Prism::Script::Prism_Entity_SetTransform);
mono_add_internal_call("Prism.TransformComponent::GetRotation_Native", (const void*)Prism::Script::Prism_TransformComponent_GetRotation); mono_add_internal_call("Prism.TransformComponent::GetRotation_Native", (const void*)Prism::Script::Prism_TransformComponent_GetRotation);
mono_add_internal_call("Prism.TransformComponent::SetRotation_Native", (const void*)Prism::Script::Prism_TransformComponent_SetRotation); mono_add_internal_call("Prism.TransformComponent::SetRotation_Native", (const void*)Prism::Script::Prism_TransformComponent_SetRotation);
*/
/* /*
mono_add_internal_call("Prism.Entity::GetForwardDirection_Native", Prism::Script::Prism_Entity_GetForwardDirection); mono_add_internal_call("Prism.Entity::GetForwardDirection_Native", Prism::Script::Prism_Entity_GetForwardDirection);

View File

@ -41,18 +41,6 @@ namespace Prism { namespace Script {
SpriteRenderer = 4 SpriteRenderer = 4
}; };
static std::tuple<glm::vec3, glm::quat, glm::vec3> GetTransformDecomposition(const glm::mat4& transform)
{
glm::vec3 scale, translation, skew;
glm::vec4 perspective;
glm::quat orientation;
glm::decompose(transform, scale, orientation, translation, skew, perspective);
return { translation, orientation, scale };
}
//////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////
// Math //////////////////////////////////////////////////////// // Math ////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////
@ -279,6 +267,7 @@ namespace Prism { namespace Script {
// Entity // // Entity //
//////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////
/*
void Prism_Entity_GetTransform(const uint64_t entityID, glm::mat4* outTransform) void Prism_Entity_GetTransform(const uint64_t entityID, glm::mat4* outTransform)
{ {
Ref<Scene> scene = ScriptEngine::GetCurrentSceneContext(); Ref<Scene> scene = ScriptEngine::GetCurrentSceneContext();
@ -288,7 +277,7 @@ namespace Prism { namespace Script {
Entity entity = entityMap.at(entityID); Entity entity = entityMap.at(entityID);
auto& transformComponent = entity.GetComponent<TransformComponent>(); auto& transformComponent = entity.GetComponent<TransformComponent>();
memcpy(outTransform, glm::value_ptr(transformComponent.Transform), sizeof(glm::mat4)); memcpy(outTransform, glm::value_ptr(transformComponent.Transformation), sizeof(glm::mat4));
} }
void Prism_Entity_SetTransform(const uint64_t entityID, const glm::mat4* inTransform) void Prism_Entity_SetTransform(const uint64_t entityID, const glm::mat4* inTransform)
@ -300,8 +289,9 @@ namespace Prism { namespace Script {
Entity entity = entityMap.at(entityID); Entity entity = entityMap.at(entityID);
auto& transformComponent = entity.GetComponent<TransformComponent>(); auto& transformComponent = entity.GetComponent<TransformComponent>();
memcpy(glm::value_ptr(transformComponent.Transform), inTransform, sizeof(glm::mat4)); memcpy(glm::value_ptr(transformComponent.Transformation), inTransform, sizeof(glm::mat4));
} }
*/
void Prism_Entity_CreateComponent(const uint64_t entityID, void* type) void Prism_Entity_CreateComponent(const uint64_t entityID, void* type)
{ {
@ -330,6 +320,7 @@ namespace Prism { namespace Script {
uint64_t Prism_Entity_FindEntityByTag(MonoString* tag) uint64_t Prism_Entity_FindEntityByTag(MonoString* tag)
{ {
size_t a = sizeof(ScriptTransform);
Ref<Scene> scene = ScriptEngine::GetCurrentSceneContext(); Ref<Scene> scene = ScriptEngine::GetCurrentSceneContext();
PM_CORE_ASSERT(scene, "No active scene!"); PM_CORE_ASSERT(scene, "No active scene!");
@ -340,6 +331,7 @@ namespace Prism { namespace Script {
return 0; return 0;
} }
/*
void Prism_TransformComponent_GetRelativeDirection(const uint64_t entityID, glm::vec3* outDirection, const glm::vec3* inAbsoluteDirection) void Prism_TransformComponent_GetRelativeDirection(const uint64_t entityID, glm::vec3* outDirection, const glm::vec3* inAbsoluteDirection)
{ {
Ref<Scene> scene = ScriptEngine::GetCurrentSceneContext(); Ref<Scene> scene = ScriptEngine::GetCurrentSceneContext();
@ -350,7 +342,7 @@ namespace Prism { namespace Script {
Entity entity = entityMap.at(entityID); Entity entity = entityMap.at(entityID);
const auto& transformComponent = entity.GetComponent<TransformComponent>(); const auto& transformComponent = entity.GetComponent<TransformComponent>();
auto [position, rotation, scale] = GetTransformDecomposition(transformComponent.Transform); auto [position, rotation, scale] = GetTransformDecomposition(transformComponent.Transformation);
*outDirection = glm::rotate(rotation, *inAbsoluteDirection); *outDirection = glm::rotate(rotation, *inAbsoluteDirection);
} }
@ -364,7 +356,7 @@ namespace Prism { namespace Script {
Entity entity = entityMap.at(entityID); Entity entity = entityMap.at(entityID);
const auto& transformComponent = entity.GetComponent<TransformComponent>(); const auto& transformComponent = entity.GetComponent<TransformComponent>();
auto [position, rotation, scale] = GetTransformDecomposition(transformComponent.Transform); auto [position, rotation, scale] = GetTransformDecomposition(transformComponent.Transformation);
*outRotation = glm::degrees(glm::eulerAngles(rotation)); *outRotation = glm::degrees(glm::eulerAngles(rotation));
} }
@ -376,13 +368,46 @@ namespace Prism { namespace Script {
PM_CORE_ASSERT(entityMap.find(entityID) != entityMap.end(), "Invalid entity ID or entity doesn't exist in scene!"); PM_CORE_ASSERT(entityMap.find(entityID) != entityMap.end(), "Invalid entity ID or entity doesn't exist in scene!");
Entity entity = entityMap.at(entityID); Entity entity = entityMap.at(entityID);
auto& transform = entity.Transform(); auto& transform = entity.Transformation();
auto [position, rotation, scale] = GetTransformDecomposition(transform); auto [position, rotation, scale] = GetTransformDecomposition(transform);
transform = glm::translate(glm::mat4(1.0f), position) * transform = glm::translate(glm::mat4(1.0f), position) *
glm::toMat4(glm::quat(glm::radians(*inRotation))) * glm::toMat4(glm::quat(glm::radians(*inRotation))) *
glm::scale(glm::mat4(1.0f), scale); glm::scale(glm::mat4(1.0f), scale);
} }
*/
void Prism_TransformComponent_GetTransform(const uint64_t entityID, ScriptTransform* outTransform)
{
Ref<Scene> scene = ScriptEngine::GetCurrentSceneContext();
PM_CORE_ASSERT(scene, "No active scene!");
const auto& entityMap = scene->GetEntityMap();
PM_CORE_ASSERT(entityMap.find(entityID) != entityMap.end(), "Invalid entity ID or entity doesn't exist in scene!");
Entity entity = entityMap.at(entityID);
const Transform& transform = entity.GetComponent<TransformComponent>();
*outTransform = {
transform.GetTranslation(), transform.GetRotation(), transform.GetScale(),
transform.GetUpDirection(), transform.GetRightDirection(), transform.GetForwardDirection()
};
}
void Prism_TransformComponent_SetTransform(const uint64_t entityID, const ScriptTransform* inTransform)
{
Ref<Scene> scene = ScriptEngine::GetCurrentSceneContext();
PM_CORE_ASSERT(scene, "No active scene!");
const auto& entityMap = scene->GetEntityMap();
PM_CORE_ASSERT(entityMap.find(entityID) != entityMap.end(), "Invalid entity ID or entity doesn't exist in scene!");
Entity entity = entityMap.at(entityID);
Transform& transform = entity.GetComponent<TransformComponent>();
transform.SetTranslation(inTransform->Translation);
transform.SetRotation(inTransform->Rotation);
transform.SetScale(inTransform->Scale);
}
void* Prism_MeshComponent_GetMesh(const uint64_t entityID) void* Prism_MeshComponent_GetMesh(const uint64_t entityID)
{ {

View File

@ -19,6 +19,14 @@ extern "C" {
namespace Prism { namespace Script { namespace Prism { namespace Script {
struct ScriptTransform
{
glm::vec3 Translation;
glm::vec3 Rotation;
glm::vec3 Scale;
glm::vec3 Up, Right, Forward;
};
// Math // Math
float Prism_Noise_PerlinNoise(float x, float y); float Prism_Noise_PerlinNoise(float x, float y);
@ -42,12 +50,18 @@ namespace Prism { namespace Script {
void Prism_Entity_CreateComponent(uint64_t entityID, void* type); void Prism_Entity_CreateComponent(uint64_t entityID, void* type);
bool Prism_Entity_HasComponent(uint64_t entityID, void* type); bool Prism_Entity_HasComponent(uint64_t entityID, void* type);
uint64_t Prism_Entity_FindEntityByTag(MonoString* tag); uint64_t Prism_Entity_FindEntityByTag(MonoString* tag);
/*
void Prism_Entity_GetTransform(uint64_t entityID, glm::mat4* outTransform); void Prism_Entity_GetTransform(uint64_t entityID, glm::mat4* outTransform);
void Prism_Entity_SetTransform(uint64_t entityID, const glm::mat4* inTransform); void Prism_Entity_SetTransform(uint64_t entityID, const glm::mat4* inTransform);
*/
/*
void Prism_TransformComponent_GetRelativeDirection(uint64_t entityID, glm::vec3* outDirection, const glm::vec3* inAbsoluteDirection); void Prism_TransformComponent_GetRelativeDirection(uint64_t entityID, glm::vec3* outDirection, const glm::vec3* inAbsoluteDirection);
void Prism_TransformComponent_GetRotation(uint64_t entityID,glm::vec3* outRotation); void Prism_TransformComponent_GetRotation(uint64_t entityID,glm::vec3* outRotation);
void Prism_TransformComponent_SetRotation(uint64_t entityID,const glm::vec3* inRotation); void Prism_TransformComponent_SetRotation(uint64_t entityID,const glm::vec3* inRotation);
*/
void Prism_TransformComponent_GetTransform(uint64_t entityID, ScriptTransform* outTransform);
void Prism_TransformComponent_SetTransform(uint64_t entityID, const ScriptTransform* inTransform);
// 2D Physic // 2D Physic
void Prism_RigidBody2DComponent_ApplyLinearImpulse(uint64_t entityID, const glm::vec2* impulse, const glm::vec2* offset, bool wake); void Prism_RigidBody2DComponent_ApplyLinearImpulse(uint64_t entityID, const glm::vec2* impulse, const glm::vec2* offset, bool wake);