Added physics system (untested)

This commit is contained in:
Diren D Bharwani 2022-10-01 15:26:08 +08:00
parent e956797441
commit 4f56a32a9b
17 changed files with 1193 additions and 640 deletions

View File

@ -90,7 +90,7 @@ namespace Sandbox
SHADE::SHSystemManager::RegisterRoutine<SHADE::SHGraphicsSystem, SHADE::SHGraphicsSystem::RenderRoutine>(); SHADE::SHSystemManager::RegisterRoutine<SHADE::SHGraphicsSystem, SHADE::SHGraphicsSystem::RenderRoutine>();
SHADE::SHSystemManager::RegisterRoutine<SHADE::SHGraphicsSystem, SHADE::SHGraphicsSystem::EndRoutine>(); SHADE::SHSystemManager::RegisterRoutine<SHADE::SHGraphicsSystem, SHADE::SHGraphicsSystem::EndRoutine>();
//SHADE::SHComponentManager::CreateComponentSparseSet<SHADE::SHRigidBodyComponent>(); SHADE::SHComponentManager::CreateComponentSparseSet<SHADE::SHRigidBodyComponent>();
SHADE::SHComponentManager::CreateComponentSparseSet<SHADE::SHTransformComponent>(); SHADE::SHComponentManager::CreateComponentSparseSet<SHADE::SHTransformComponent>();
SHADE::SHComponentManager::CreateComponentSparseSet<SHADE::SHRenderable>(); SHADE::SHComponentManager::CreateComponentSparseSet<SHADE::SHRenderable>();

View File

@ -18,9 +18,9 @@ using namespace SHADE;
namespace Sandbox namespace Sandbox
{ {
void SBTestScene::WindowFocusFunc([[maybe_unused]]void* window, int focused) void SBTestScene::WindowFocusFunc([[maybe_unused]] void* window, int focused)
{ {
if(focused) if (focused)
{ {
} }
else else
@ -79,7 +79,7 @@ namespace Sandbox
constexpr int NUM_ROWS = 100; constexpr int NUM_ROWS = 100;
constexpr int NUM_COLS = 100; constexpr int NUM_COLS = 100;
static const SHVec3 TEST_OBJ_SPACING = { 0.05f, 0.05f, 0.05f }; static const SHVec3 TEST_OBJ_SPACING = { 0.05f, 0.05f, 0.05f };
static const SHVec3 TEST_OBJ_START_POS = { - (NUM_COLS / 2 * TEST_OBJ_SPACING.x ) + 1.0f, -2.0f, -1.0f }; static const SHVec3 TEST_OBJ_START_POS = { -(NUM_COLS / 2 * TEST_OBJ_SPACING.x) + 1.0f, -2.0f, -1.0f };
for (int y = 0; y < NUM_ROWS; ++y) for (int y = 0; y < NUM_ROWS; ++y)
for (int x = 0; x < NUM_COLS; ++x) for (int x = 0; x < NUM_COLS; ++x)
@ -117,8 +117,8 @@ namespace Sandbox
renderable.GetModifiableMaterial()->SetProperty("data.alpha", 1.0f); renderable.GetModifiableMaterial()->SetProperty("data.alpha", 1.0f);
renderable.GetModifiableMaterial()->SetProperty("data.textureIndex", 1); renderable.GetModifiableMaterial()->SetProperty("data.textureIndex", 1);
transform.SetWorldPosition ({-3.0f, -1.0f, -1.0f}); transform.SetWorldPosition({ -3.0f, -1.0f, -1.0f });
transform.SetLocalScale({5.0f, 5.0f, 5.0f}); transform.SetLocalScale({ 5.0f, 5.0f, 5.0f });
//auto entity = SHEntityManager::CreateEntity<SHRenderable, SHTransformComponent>(); //auto entity = SHEntityManager::CreateEntity<SHRenderable, SHTransformComponent>();
//auto& renderable = *SHComponentManager::GetComponent_s<SHRenderable>(entity); //auto& renderable = *SHComponentManager::GetComponent_s<SHRenderable>(entity);
@ -186,8 +186,4 @@ namespace Sandbox
{ {
//SHSerialization::SerializeScene("resources/scenes/Scene01.SHADE"); //SHSerialization::SerializeScene("resources/scenes/Scene01.SHADE");
} }
} }

View File

@ -21,7 +21,7 @@ namespace SHADE
/* Constructors & Destructor Definitions */ /* Constructors & Destructor Definitions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
SHBoundingBox::SHBoundingBox(const SHVec3& c, SHVec3& hE) noexcept SHBoundingBox::SHBoundingBox(const SHVec3& c, const SHVec3& hE) noexcept
: SHShape {} : SHShape {}
, center { c } , center { c }
, halfExtents { hE } , halfExtents { hE }

View File

@ -27,7 +27,7 @@ namespace SHADE
/* Constructors & Destructor */ /* Constructors & Destructor */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
SHBoundingBox (const SHVec3& center, SHVec3& halfExtents) noexcept; SHBoundingBox (const SHVec3& center, const SHVec3& halfExtents) noexcept;
SHBoundingBox (const SHVec3* vertices, size_t numVertices) noexcept; SHBoundingBox (const SHVec3* vertices, size_t numVertices) noexcept;
SHBoundingBox (const SHBoundingBox* boxes, size_t numBoxes) noexcept; SHBoundingBox (const SHBoundingBox* boxes, size_t numBoxes) noexcept;

View File

@ -30,7 +30,9 @@ namespace SHADE
enum class Type enum class Type
{ {
BOUNDING_BOX BOUNDING_BOX
, RAY , SPHERE
, CAPSULE
, CONVEX_HULL
, TRIANGLE , TRIANGLE
, COUNT , COUNT

View File

@ -152,7 +152,7 @@ RTTR_REGISTRATION
using namespace rttr; using namespace rttr;
registration::class_<SHTransformComponent>("Transform Component") registration::class_<SHTransformComponent>("Transform Component")
.property("Translate", &SHTransformComponent::GetLocalPosition, &SHTransformComponent::SetLocalPosition) .property("Translate" , &SHTransformComponent::GetLocalPosition , &SHTransformComponent::SetLocalPosition )
.property("Rotate", &SHTransformComponent::GetLocalRotation, select_overload<void(SHVec3 const&)>(&SHTransformComponent::SetLocalRotation)) .property("Rotate" , &SHTransformComponent::GetLocalRotation , select_overload<void(SHVec3 const&)>(&SHTransformComponent::SetLocalRotation) )
.property("Scale", &SHTransformComponent::GetLocalScale, &SHTransformComponent::SetLocalScale); .property("Scale" , &SHTransformComponent::GetLocalScale , &SHTransformComponent::SetLocalScale );
} }

View File

@ -13,6 +13,7 @@
#include <queue> #include <queue>
#include <rttr/registration> #include <rttr/registration>
// Project Headers // Project Headers
#include "SH_API.h" #include "SH_API.h"
#include "ECS_Base/Components/SHComponent.h" #include "ECS_Base/Components/SHComponent.h"

View File

@ -0,0 +1,98 @@
/****************************************************************************************
* \file SHColliderComponent.cpp
* \author Diren D Bharwani, diren.dbharwani, 390002520
* \brief Implementation for a Collider Component.
*
* \copyright Copyright (C) 2022 DigiPen Institute of Technology. Reproduction or
* disclosure of this file or its contents without the prior written consent
* of DigiPen Institute of Technology is prohibited.
****************************************************************************************/
#include <SHpch.h>
// Primary Header
#include "SHColliderComponent.h"
namespace SHADE
{
/*-----------------------------------------------------------------------------------*/
/* Getter Function Definitions */
/*-----------------------------------------------------------------------------------*/
bool SHColliderComponent::HasChanged() const noexcept
{
return dirty;
}
const SHVec3& SHColliderComponent::GetPosition() const noexcept
{
return position;
}
const SHQuaternion& SHColliderComponent::GetOrientation() const noexcept
{
return orientation;
}
SHVec3 SHColliderComponent::GetRotation() const noexcept
{
return orientation.ToEuler();
}
const SHColliderComponent::Colliders& SHColliderComponent::GetColliders() const noexcept
{
return colliders;
}
SHCollider& SHColliderComponent::GetCollider(int index) noexcept
{
if (index < 0 || static_cast<size_t>(index) >= colliders.size())
throw std::invalid_argument("Out-of-range access!");
return colliders[index].first;
}
/*-----------------------------------------------------------------------------------*/
/* Public Function Member Definitions */
/*-----------------------------------------------------------------------------------*/
void SHColliderComponent::OnCreate()
{
}
void SHColliderComponent::OnDestroy()
{
}
void SHColliderComponent::AddBoundingBox() noexcept
{
const auto BOX_PAIR = std::make_pair(SHCollider{SHCollider::Type::BOX}, true);
colliders.emplace_back(BOX_PAIR);
}
void SHColliderComponent::AddSphere() noexcept
{
}
void SHColliderComponent::RemoveCollider(int index) noexcept
{
if (index < 0 || static_cast<size_t>(index) >= colliders.size())
throw std::invalid_argument("Out-of-range access!");
int idx = 0;
auto it = colliders.begin();
for (; it != colliders.end(); ++it)
{
if (idx == index)
break;
++idx;
}
it = colliders.erase(it);
}
} // namespace SHADE

View File

@ -0,0 +1,94 @@
/****************************************************************************************
* \file SHColliderComponent.h
* \author Diren D Bharwani, diren.dbharwani, 390002520
* \brief Interface for a Collider Component.
*
* \copyright Copyright (C) 2022 DigiPen Institute of Technology. Reproduction or
* disclosure of this file or its contents without the prior written consent
* of DigiPen Institute of Technology is prohibited.
****************************************************************************************/
#pragma once
// Project Headers
#include "ECS_Base/Components/SHComponent.h"
#include "Physics/SHCollider.h"
namespace SHADE
{
/*-----------------------------------------------------------------------------------*/
/* Type Definitions */
/*-----------------------------------------------------------------------------------*/
class SH_API SHColliderComponent : public SHComponent
{
private:
/*---------------------------------------------------------------------------------*/
/* Friends */
/*---------------------------------------------------------------------------------*/
friend class SHPhysicsSystem;
/*---------------------------------------------------------------------------------*/
/* Type Definitions */
/*---------------------------------------------------------------------------------*/
using ColliderDirtyPair = std::pair<SHCollider, bool>;
using Colliders = std::vector<ColliderDirtyPair>;
public:
/*---------------------------------------------------------------------------------*/
/* Constructors & Destructor */
/*---------------------------------------------------------------------------------*/
SHColliderComponent () noexcept = default;
SHColliderComponent (const SHColliderComponent& rhs) noexcept = default;
SHColliderComponent (SHColliderComponent&& rhs) noexcept = default;
~SHColliderComponent () override = default;
/*---------------------------------------------------------------------------------*/
/* Operator Overloads */
/*---------------------------------------------------------------------------------*/
SHColliderComponent& operator=(const SHColliderComponent& rhs) noexcept = default;
SHColliderComponent& operator=(SHColliderComponent&& rhs) noexcept = default;
/*---------------------------------------------------------------------------------*/
/* Getter Functions */
/*---------------------------------------------------------------------------------*/
[[nodiscard]] bool HasChanged () const noexcept;
[[nodiscard]] const SHVec3& GetPosition () const noexcept;
[[nodiscard]] const SHQuaternion& GetOrientation () const noexcept;
[[nodiscard]] SHVec3 GetRotation () const noexcept;
[[nodiscard]] const Colliders& GetColliders () const noexcept;
[[nodiscard]] SHCollider& GetCollider (int index) noexcept;
/*---------------------------------------------------------------------------------*/
/* Function Members */
/*---------------------------------------------------------------------------------*/
void OnCreate () override;
void OnDestroy () override;
void AddBoundingBox () noexcept;
void AddSphere () noexcept;
void RemoveCollider (int index) noexcept;
private:
/*---------------------------------------------------------------------------------*/
/* Data Members */
/*---------------------------------------------------------------------------------*/
bool dirty;
SHVec3 position;
SHQuaternion orientation;
Colliders colliders;
};
} // namespace SHADE

View File

@ -14,9 +14,8 @@
#include "SHRigidBodyComponent.h" #include "SHRigidBodyComponent.h"
// Project Headers // Project Headers
#include "Tools/SHUtilities.h" #include "ECS_Base/Managers/SHSystemManager.h"
#include "Math/SHMathHelpers.h" #include "Physics/SHPhysicsSystem.h"
#include "Math/SHQuaternion.h"
namespace SHADE namespace SHADE
{ {
@ -26,46 +25,32 @@ namespace SHADE
SHRigidBodyComponent::SHRigidBodyComponent() noexcept SHRigidBodyComponent::SHRigidBodyComponent() noexcept
: type { Type::DYNAMIC } : type { Type::DYNAMIC }
, flags { 0 }
, dirtyFlags { 0 }
, interpolate { true }
, system { nullptr }
, mass { 1.0f } , mass { 1.0f }
, drag { 0.01f } , drag { 0.01f }
, angularDrag { 0.01f } , angularDrag { 0.01f }
, flags { 0 }
{ {
// Set default flags: Gravity & Sleeping enabled // Set default flags: Gravity & Sleeping enabled
flags |= 1U << 0; flags |= 1U << 0;
flags |= 1U << 1; flags |= 1U << 1;
} }
SHRigidBodyComponent::~SHRigidBodyComponent()
{
}
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
/* Getter Function Definitions */ /* Getter Function Definitions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
bool SHRigidBodyComponent::IsGravityEnabled() const noexcept bool SHRigidBodyComponent::IsGravityEnabled() const noexcept
{ {
const bool GRAVITY = flags & (1U << 0); return flags & (1U << 0);
if (rp3dBody)
{
SHASSERT(reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->isGravityEnabled() == GRAVITY, "ReactPhysics and SHADE body enable gravity do not match!")
} }
return GRAVITY; bool SHRigidBodyComponent::IsAllowedToSleep() const noexcept
}
bool SHRigidBodyComponent::IsSleepingEnabled() const noexcept
{ {
const bool SLEEP = flags & (1U << 1); return flags & (1U << 1);
if (rp3dBody)
{
SHASSERT(reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->isAllowedToSleep() == SLEEP, "ReactPhysics and SHADE body enable sleep do not match!")
}
return SLEEP;
} }
bool SHRigidBodyComponent::IsInterpolating() const noexcept bool SHRigidBodyComponent::IsInterpolating() const noexcept
@ -75,178 +60,87 @@ namespace SHADE
SHRigidBodyComponent::Type SHRigidBodyComponent::GetType() const noexcept SHRigidBodyComponent::Type SHRigidBodyComponent::GetType() const noexcept
{ {
if (rp3dBody)
{
SHASSERT
(
SHUtilities::ConvertEnum(reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->getType()) == SHUtilities::ConvertEnum(type),
"ReactPhysics and SHADE body types do not match!"
)
}
return type; return type;
} }
float SHRigidBodyComponent::GetMass() const noexcept float SHRigidBodyComponent::GetMass() const noexcept
{ {
if (rp3dBody)
{
SHASSERT(reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->getMass() == mass, "ReactPhysics and SHADE body masses do not match!")
}
return mass; return mass;
} }
float SHRigidBodyComponent::GetDrag() const noexcept float SHRigidBodyComponent::GetDrag() const noexcept
{ {
if (rp3dBody)
{
SHASSERT
(
SHMath::CompareFloat(reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->getLinearDamping(), drag),
"ReactPhysics and SADE body drag coefficients do not match!"
)
}
return drag; return drag;
} }
float SHRigidBodyComponent::GetAngularDrag() const noexcept float SHRigidBodyComponent::GetAngularDrag() const noexcept
{ {
if (rp3dBody)
{
SHASSERT
(
SHMath::CompareFloat(reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->getAngularDamping(), angularDrag),
"ReactPhysics and SADE body drag coefficients do not match!"
)
}
return angularDrag; return angularDrag;
} }
bool SHRigidBodyComponent::GetFreezePositionX() const noexcept bool SHRigidBodyComponent::GetFreezePositionX() const noexcept
{ {
const bool FREEZE_X_POS = flags & (1U << 2); return flags & (1U << 2);
if (rp3dBody)
{
const bool RP3D_FREEZE_X_POS = fabs(reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->getLinearLockAxisFactor().x) > 0.0f;
SHASSERT(RP3D_FREEZE_X_POS == FREEZE_X_POS, "ReactPhysics and SHADE body x-axis position lock do not match!")
}
return FREEZE_X_POS;
} }
bool SHRigidBodyComponent::GetFreezePositionY() const noexcept bool SHRigidBodyComponent::GetFreezePositionY() const noexcept
{ {
const bool FREEZE_Y_POS = flags & (1U << 3); return flags & (1U << 3);
if (rp3dBody)
{
const bool RP3D_FREEZE_Y_POS = fabs(reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->getLinearLockAxisFactor().y) > 0.0f;
SHASSERT(RP3D_FREEZE_Y_POS == FREEZE_Y_POS, "ReactPhysics and SHADE body y-axis position lock do not match!")
}
return FREEZE_Y_POS;
} }
bool SHRigidBodyComponent::GetFreezePositionZ() const noexcept bool SHRigidBodyComponent::GetFreezePositionZ() const noexcept
{ {
const bool FREEZE_Z_POS = flags & (1U << 4); return flags & (1U << 4);
if (rp3dBody)
{
const bool RP3D_FREEZE_Z_POS = fabs(reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->getLinearLockAxisFactor().z) > 0.0f;
SHASSERT(RP3D_FREEZE_Z_POS == FREEZE_Z_POS, "ReactPhysics and SHADE body z-axis position lock do not match!")
}
return FREEZE_Z_POS;
} }
bool SHRigidBodyComponent::GetFreezeRotationX() const noexcept bool SHRigidBodyComponent::GetFreezeRotationX() const noexcept
{ {
const bool FREEZE_X_ROT = flags & (1U << 5); return flags & (1U << 5);
if (rp3dBody)
{
const bool RP3D_FREEZE_Y_ROT = fabs(reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->getAngularLockAxisFactor().x) > 0.0f;
SHASSERT(RP3D_FREEZE_Y_ROT == FREEZE_X_ROT, "ReactPhysics and SHADE body x-axis rotation lock do not match!")
}
return FREEZE_X_ROT;
} }
bool SHRigidBodyComponent::GetFreezeRotationY() const noexcept bool SHRigidBodyComponent::GetFreezeRotationY() const noexcept
{ {
const bool FREEZE_Y_ROT = flags & (1U << 6); return flags & (1U << 6);
if (rp3dBody)
{
const bool RP3D_FREEZE_Y_ROT = fabs(reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->getAngularLockAxisFactor().y) > 0.0f;
SHASSERT(RP3D_FREEZE_Y_ROT == FREEZE_Y_ROT, "ReactPhysics and SHADE body y-axis rotation lock do not match!")
}
return FREEZE_Y_ROT;
} }
bool SHRigidBodyComponent::GetFreezeRotationZ() const noexcept bool SHRigidBodyComponent::GetFreezeRotationZ() const noexcept
{ {
const bool FREEZE_Z_ROT = flags & (1U << 7); return flags & (1U << 7);
if (rp3dBody)
{
const bool RP3D_FREEZE_Z_ROT = fabs(reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->getAngularLockAxisFactor().z) > 0.0f;
SHASSERT(RP3D_FREEZE_Z_ROT == FREEZE_Z_ROT, "ReactPhysics and SHADE body z-axis rotation lock do not match!")
} }
return FREEZE_Z_ROT; const SHVec3& SHRigidBodyComponent::GetForce() const noexcept
{
return force;
} }
SHVec3 SHRigidBodyComponent::GetForce() const noexcept const SHVec3& SHRigidBodyComponent::GetTorque() const noexcept
{ {
SHVec3 result; return torque;
if (rp3dBody)
{
const auto& RP3D_RESULT = reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->getForce();
result = SHVec3{ RP3D_RESULT.x, RP3D_RESULT.y, RP3D_RESULT.z };
} }
return result; const SHVec3& SHRigidBodyComponent::GetLinearVelocity() const noexcept
{
return linearVelocity;
} }
SHVec3 SHRigidBodyComponent::GetTorque() const noexcept const SHVec3& SHRigidBodyComponent::GetAngularVelocity() const noexcept
{ {
SHVec3 result; return angularVelocity;
if (rp3dBody)
{
const auto& RP3D_RESULT = reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->getTorque();
result = SHVec3{ RP3D_RESULT.x, RP3D_RESULT.y, RP3D_RESULT.z };
} }
return result; const SHVec3& SHRigidBodyComponent::GetPosition() const noexcept
{
return position;
} }
SHVec3 SHRigidBodyComponent::GetLinearVelocity() const noexcept const SHQuaternion& SHRigidBodyComponent::GetOrientation() const noexcept
{ {
SHVec3 result; return orientation;
if (rp3dBody)
{
const auto& RP3D_RESULT = reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->getLinearVelocity();
result = SHVec3{ RP3D_RESULT.x, RP3D_RESULT.y, RP3D_RESULT.z };
} }
return result; SHVec3 SHRigidBodyComponent::GetRotation() const noexcept
}
SHVec3 SHRigidBodyComponent::GetAngularVelocity() const noexcept
{ {
SHVec3 result; return orientation.ToEuler();
if (rp3dBody)
{
const auto& RP3D_RESULT = reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->getAngularVelocity();
result = SHVec3{ RP3D_RESULT.x, RP3D_RESULT.y, RP3D_RESULT.z };
}
return result;
} }
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
@ -258,80 +152,72 @@ namespace SHADE
if (type == newType) if (type == newType)
return; return;
dirtyFlags |= 1U << 4;
type = newType; type = newType;
if (rp3dBody)
reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->setType(static_cast<rp3d::BodyType>(newType));
}
void SHRigidBodyComponent::SetMass(float newMass) noexcept
{
mass = newMass;
if (rp3dBody)
reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->setMass(newMass);
}
void SHRigidBodyComponent::SetDrag(float newDrag) noexcept
{
drag = newDrag;
if (rp3dBody)
reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->setLinearDamping(newDrag);
}
void SHRigidBodyComponent::SetAngularDrag(float newAngularDrag) noexcept
{
angularDrag = newAngularDrag;
if (rp3dBody)
reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->setAngularDamping(newAngularDrag);
} }
void SHRigidBodyComponent::SetGravityEnabled(bool enableGravity) noexcept void SHRigidBodyComponent::SetGravityEnabled(bool enableGravity) noexcept
{ {
SetFlag(enableGravity, 0); constexpr int FLAG_POS = 0;
if (rp3dBody)
reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->enableGravity(enableGravity); dirtyFlags |= 1U << FLAG_POS;
enableGravity ? flags |= (1U << FLAG_POS) : flags &= ~(1U << FLAG_POS);
} }
void SHRigidBodyComponent::SetSleepingEnabled(bool enableSleeping) noexcept void SHRigidBodyComponent::SetIsAllowedToSleep(bool isAllowedToSleep) noexcept
{ {
SetFlag(enableSleeping, 1); constexpr int FLAG_POS = 1;
if (rp3dBody)
reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->setIsAllowedToSleep(enableSleeping); dirtyFlags |= 1U << 1;
isAllowedToSleep ? flags |= (1U << FLAG_POS) : flags &= ~(1U << FLAG_POS);
} }
void SHRigidBodyComponent::SetFreezePositionX(bool freezePositionX) noexcept void SHRigidBodyComponent::SetFreezePositionX(bool freezePositionX) noexcept
{ {
SetFlag(freezePositionX, 2); constexpr int FLAG_POS = 2;
SetRP3DLinearConstraints();
dirtyFlags |= 1U << 2;
freezePositionX ? flags |= (1U << FLAG_POS) : flags &= ~(1U << FLAG_POS);
} }
void SHRigidBodyComponent::SetFreezePositionY(bool freezePositionY) noexcept void SHRigidBodyComponent::SetFreezePositionY(bool freezePositionY) noexcept
{ {
SetFlag(freezePositionY, 3); constexpr int FLAG_POS = 3;
SetRP3DLinearConstraints();
dirtyFlags |= 1U << 2;
freezePositionY ? flags |= (1U << FLAG_POS) : flags &= ~(1U << FLAG_POS);
} }
void SHRigidBodyComponent::SetFreezePositionZ(bool freezePositionZ) noexcept void SHRigidBodyComponent::SetFreezePositionZ(bool freezePositionZ) noexcept
{ {
SetFlag(freezePositionZ, 4); constexpr int FLAG_POS = 4;
SetRP3DLinearConstraints();
dirtyFlags |= 1U << 2;
freezePositionZ ? flags |= (1U << FLAG_POS) : flags &= ~(1U << FLAG_POS);
} }
void SHRigidBodyComponent::SetFreezeRotationX(bool freezeRotationX) noexcept void SHRigidBodyComponent::SetFreezeRotationX(bool freezeRotationX) noexcept
{ {
SetFlag(freezeRotationX, 5); constexpr int FLAG_POS = 5;
SetRP3DAngularConstraints();
dirtyFlags |= 1U << 3;
freezeRotationX ? flags |= (1U << FLAG_POS) : flags &= ~(1U << FLAG_POS);
} }
void SHRigidBodyComponent::SetFreezeRotationY(bool freezeRotationY) noexcept void SHRigidBodyComponent::SetFreezeRotationY(bool freezeRotationY) noexcept
{ {
SetFlag(freezeRotationY, 6); constexpr int FLAG_POS = 6;
SetRP3DAngularConstraints();
dirtyFlags |= 1U << 3;
freezeRotationY ? flags |= (1U << FLAG_POS) : flags &= ~(1U << FLAG_POS);
} }
void SHRigidBodyComponent::SetFreezeRotationZ(bool freezeRotationZ) noexcept void SHRigidBodyComponent::SetFreezeRotationZ(bool freezeRotationZ) noexcept
{ {
SetFlag(freezeRotationZ, 7); constexpr int FLAG_POS = 7;
SetRP3DAngularConstraints();
dirtyFlags |= 1U << 3;
freezeRotationZ ? flags |= (1U << FLAG_POS) : flags &= ~(1U << FLAG_POS);
} }
void SHRigidBodyComponent::SetInterpolate(bool allowInterpolation) noexcept void SHRigidBodyComponent::SetInterpolate(bool allowInterpolation) noexcept
@ -339,22 +225,34 @@ namespace SHADE
interpolate = allowInterpolation; interpolate = allowInterpolation;
} }
void SHRigidBodyComponent::SetLinearVelocity(const SHVec3& newLinearVelocity) const noexcept void SHRigidBodyComponent::SetMass(float newMass) noexcept
{ {
if (rp3dBody) dirtyFlags |= 1U << 5;
{ mass = newMass;
const rp3d::Vector3 NEW_V { newLinearVelocity.x, newLinearVelocity.y, newLinearVelocity.z };
reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->setLinearVelocity(NEW_V);
}
} }
void SHRigidBodyComponent::SetAngularVelocity(const SHVec3& newAngularVelocity) const noexcept void SHRigidBodyComponent::SetDrag(float newDrag) noexcept
{ {
if (rp3dBody) dirtyFlags |= 1U << 6;
{ drag = newDrag;
const rp3d::Vector3 NEW_V { newAngularVelocity.x, newAngularVelocity.y, newAngularVelocity.z };
reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->setAngularVelocity(NEW_V);
} }
void SHRigidBodyComponent::SetAngularDrag(float newAngularDrag) noexcept
{
dirtyFlags |= 1U << 7;
angularDrag = newAngularDrag;
}
void SHRigidBodyComponent::SetLinearVelocity(const SHVec3& newLinearVelocity) noexcept
{
dirtyFlags |= 1U << 8;
linearVelocity = newLinearVelocity;
}
void SHRigidBodyComponent::SetAngularVelocity(const SHVec3& newAngularVelocity) noexcept
{
dirtyFlags |= 1U << 9;
angularVelocity = newAngularVelocity;
} }
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
@ -363,148 +261,143 @@ namespace SHADE
void SHRigidBodyComponent::OnCreate() void SHRigidBodyComponent::OnCreate()
{ {
componentFlags |= 1U << 0; // dirty system = SHSystemManager::GetSystem<SHPhysicsSystem>();
componentFlags |= 1U << 1; // rb dirty if (!system)
componentFlags |= 1U << 2; // has rb {
SHLOG_ERROR("Physics system does not exist, Rigid Body Component not added!")
return;
}
Synchronise(); // Notify Physics System
system->AddRigidBody(GetEID());
} }
void SHRigidBodyComponent::OnDestroy() void SHRigidBodyComponent::OnDestroy()
{ {
componentFlags |= 1U << 0; // dirty // Notify Physics System
componentFlags |= 1U << 1; // rb dirty if (!system)
componentFlags &= ~(1U << 2); // no rb {
SHLOG_ERROR("Physics system does not exist, unable to remove Rigid Body Component!")
return;
}
Synchronise(); system->RemoveRigidBody(GetEID());
} }
void SHRigidBodyComponent::AddForce(const SHVec3& force) const noexcept void SHRigidBodyComponent::AddForce(const SHVec3& force) const noexcept
{ {
if (rp3dBody) if (!system)
{ {
const rp3d::Vector3 F { force.x, force.y, force.z }; SHLOG_ERROR("Physics system does not exist, unable to Add Force to a body!")
reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->applyWorldForceAtCenterOfMass(F); return;
} }
// Notify Physics Systems
system->AddForce(GetEID(), force);
} }
void SHRigidBodyComponent::AddForceAtLocalPos(const SHVec3& force, const SHVec3& localPos) const noexcept void SHRigidBodyComponent::AddForceAtLocalPos(const SHVec3& force, const SHVec3& localPos) const noexcept
{ {
if (rp3dBody) if (!system)
{ {
const rp3d::Vector3 F{ force.x, force.y, force.z }; SHLOG_ERROR("Physics system does not exist, unable to Add Force to a body!")
const rp3d::Vector3 P{ localPos.x, localPos.y, localPos.z }; return;
reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->applyWorldForceAtLocalPosition(F, P);
} }
// Notify Physics Systems
system->AddForceAtLocalPos(GetEID(), force, localPos);
} }
void SHRigidBodyComponent::AddForceAtWorldPos(const SHVec3& force, const SHVec3& worldPos) const noexcept void SHRigidBodyComponent::AddForceAtWorldPos(const SHVec3& force, const SHVec3& worldPos) const noexcept
{ {
if (rp3dBody) if (!system)
{ {
const rp3d::Vector3 F{ force.x, force.y, force.z }; SHLOG_ERROR("Physics system does not exist, unable to Add Force to a body!")
const rp3d::Vector3 P{ worldPos.x, worldPos.y, worldPos.z }; return;
reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->applyWorldForceAtWorldPosition(F, P);
} }
// Notify Physics Systems
system->AddForceAtWorldPos(GetEID(), force, worldPos);
} }
void SHRigidBodyComponent::AddRelativeForce(const SHVec3& relativeForce) const noexcept void SHRigidBodyComponent::AddRelativeForce(const SHVec3& relativeForce) const noexcept
{ {
if (rp3dBody) if (!system)
{ {
const rp3d::Vector3 F{ relativeForce.x, relativeForce.y, relativeForce.z }; SHLOG_ERROR("Physics system does not exist, unable to Add Force to a body!")
reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->applyLocalForceAtCenterOfMass(F); return;
} }
// Notify Physics Systems
system->AddRelativeForce(GetEID(), force);
} }
void SHRigidBodyComponent::AddRelativeForceAtLocalPos(const SHVec3& relativeForce, const SHVec3& localPos) const noexcept void SHRigidBodyComponent::AddRelativeForceAtLocalPos(const SHVec3& relativeForce, const SHVec3& localPos) const noexcept
{ {
if (rp3dBody) if (!system)
{ {
const rp3d::Vector3 F{ relativeForce.x, relativeForce.y, relativeForce.z }; SHLOG_ERROR("Physics system does not exist, unable to Add Force to a body!")
const rp3d::Vector3 P{ localPos.x, localPos.y, localPos.z }; return;
reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->applyLocalForceAtLocalPosition(F, P);
} }
// Notify Physics Systems
system->AddRelativeForceAtLocalPos(GetEID(), force, localPos);
} }
void SHRigidBodyComponent::AddRelativeForceAtWorldPos(const SHVec3& relativeForce, const SHVec3& worldPos) const noexcept void SHRigidBodyComponent::AddRelativeForceAtWorldPos(const SHVec3& relativeForce, const SHVec3& worldPos) const noexcept
{ {
if (rp3dBody) if (!system)
{ {
const rp3d::Vector3 F{ relativeForce.x, relativeForce.y, relativeForce.z }; SHLOG_ERROR("Physics system does not exist, unable to Add Force to a body!")
const rp3d::Vector3 P{ worldPos.x, worldPos.y, worldPos.z }; return;
reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->applyLocalForceAtWorldPosition(F, P);
} }
// Notify Physics Systems
system->AddRelativeForceAtWorldPos(GetEID(), force, worldPos);
} }
void SHRigidBodyComponent::AddTorque(const SHVec3& torque) const noexcept void SHRigidBodyComponent::AddTorque(const SHVec3& torque) const noexcept
{ {
if (rp3dBody) if (!system)
{ {
const rp3d::Vector3 T{ torque.x, torque.y, torque.z }; SHLOG_ERROR("Physics system does not exist, unable to Add Force to a body!")
reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->applyWorldTorque(T); return;
} }
// Notify Physics Systems
system->AddTorque(GetEID(), torque);
} }
void SHRigidBodyComponent::AddRelativeTorque(const SHVec3& relativeTorque) const noexcept void SHRigidBodyComponent::AddRelativeTorque(const SHVec3& relativeTorque) const noexcept
{ {
if (rp3dBody) if (!system)
{ {
const rp3d::Vector3 T{ relativeTorque.x, relativeTorque.y, relativeTorque.z }; SHLOG_ERROR("Physics system does not exist, unable to Add Force to a body!")
reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->applyLocalTorque(T); return;
}
} }
/*-----------------------------------------------------------------------------------*/ // Notify Physics Systems
/* Private Function Member Definitions */ system->AddRelativeTorque(GetEID(), relativeTorque);
/*-----------------------------------------------------------------------------------*/
void SHRigidBodyComponent::SyncRP3DAndSHADE()
{
auto* rigidBody = reinterpret_cast<rp3d::RigidBody*>(rp3dBody);
rigidBody->setType(static_cast<rp3d::BodyType>(type));
rigidBody->setMass(mass);
rigidBody->setLinearDamping(drag);
rigidBody->setAngularDamping(angularDrag);
rigidBody->enableGravity(flags & (1U << 0));
rigidBody->setIsAllowedToSleep(flags & (1U << 1));
SetRP3DLinearConstraints();
SetRP3DAngularConstraints();
}
void SHRigidBodyComponent::SetFlag(bool flagState, int flagPos)
{
flagState ? flags |= (1U << flagPos) : flags &= ~(1U << flagPos);
}
void SHRigidBodyComponent::SetRP3DLinearConstraints() const
{
const rp3d::Vector3 CONSTRAINTS
{
flags & 1U << 2 ? 1.0f : 0.0f,
flags & 1U << 3 ? 1.0f : 0.0f,
flags & 1U << 4 ? 1.0f : 0.0f
};
if (rp3dBody)
reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->setLinearLockAxisFactor(CONSTRAINTS);
}
void SHRigidBodyComponent::SetRP3DAngularConstraints() const
{
const rp3d::Vector3 CONSTRAINTS
{
flags & 1U << 5 ? 1.0f : 0.0f,
flags & 1U << 6 ? 1.0f : 0.0f,
flags & 1U << 7 ? 1.0f : 0.0f
};
if (rp3dBody)
reinterpret_cast<rp3d::RigidBody*>(rp3dBody)->setAngularLockAxisFactor(CONSTRAINTS);
} }
} // namespace SHADE } // namespace SHADE
RTTR_REGISTRATION
{
using namespace SHADE;
using namespace rttr;
registration::class_<SHRigidBodyComponent>("RigidBody Component")
.property("Type" , &SHRigidBodyComponent::GetType , &SHRigidBodyComponent::SetType )
.property("Mass" , &SHRigidBodyComponent::GetMass , &SHRigidBodyComponent::SetMass )
.property("Drag" , &SHRigidBodyComponent::GetDrag , &SHRigidBodyComponent::SetDrag )
.property("Angular Drag" , &SHRigidBodyComponent::GetAngularDrag , &SHRigidBodyComponent::SetAngularDrag )
.property("Use Gravity" , &SHRigidBodyComponent::IsGravityEnabled , &SHRigidBodyComponent::SetGravityEnabled )
.property("Interpolate" , &SHRigidBodyComponent::IsInterpolating , &SHRigidBodyComponent::SetInterpolate )
.property("Freeze Position X" , &SHRigidBodyComponent::GetFreezePositionX , &SHRigidBodyComponent::SetFreezePositionX )
.property("Freeze Position Y" , &SHRigidBodyComponent::GetFreezePositionY , &SHRigidBodyComponent::SetFreezePositionY )
.property("Freeze Position Z" , &SHRigidBodyComponent::GetFreezePositionZ , &SHRigidBodyComponent::SetFreezePositionZ )
.property("Freeze Rotation X" , &SHRigidBodyComponent::GetFreezeRotationX , &SHRigidBodyComponent::SetFreezeRotationX )
.property("Freeze Rotation Y" , &SHRigidBodyComponent::GetFreezeRotationY , &SHRigidBodyComponent::SetFreezeRotationY )
.property("Freeze Rotation Z" , &SHRigidBodyComponent::GetFreezeRotationZ , &SHRigidBodyComponent::SetFreezeRotationZ );
}

View File

@ -10,6 +10,8 @@
#pragma once #pragma once
#include <rttr/registration>
// Project Headers // Project Headers
#include "ECS_Base/Components/SHComponent.h" #include "ECS_Base/Components/SHComponent.h"
#include "Physics/SHPhysicsObject.h" #include "Physics/SHPhysicsObject.h"
@ -20,7 +22,7 @@ namespace SHADE
/* Type Definitions */ /* Type Definitions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
class SH_API SHRigidBodyComponent : public SHComponent, public SHPhysicsObject class SH_API SHRigidBodyComponent : public SHComponent
{ {
private: private:
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
@ -43,8 +45,6 @@ namespace SHADE
, COUNT , COUNT
}; };
// TODO(Diren): Collision Types
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Constructors & Destructor */ /* Constructors & Destructor */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
@ -52,7 +52,7 @@ namespace SHADE
SHRigidBodyComponent () noexcept; SHRigidBodyComponent () noexcept;
SHRigidBodyComponent (const SHRigidBodyComponent& rhs) noexcept = default; SHRigidBodyComponent (const SHRigidBodyComponent& rhs) noexcept = default;
SHRigidBodyComponent (SHRigidBodyComponent&& rhs) noexcept = default; SHRigidBodyComponent (SHRigidBodyComponent&& rhs) noexcept = default;
~SHRigidBodyComponent () override; ~SHRigidBodyComponent () override = default;
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Operator Overloads */ /* Operator Overloads */
@ -66,7 +66,7 @@ namespace SHADE
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
[[nodiscard]] bool IsGravityEnabled () const noexcept; [[nodiscard]] bool IsGravityEnabled () const noexcept;
[[nodiscard]] bool IsSleepingEnabled () const noexcept; [[nodiscard]] bool IsAllowedToSleep () const noexcept;
[[nodiscard]] bool IsInterpolating () const noexcept; [[nodiscard]] bool IsInterpolating () const noexcept;
[[nodiscard]] Type GetType () const noexcept; [[nodiscard]] Type GetType () const noexcept;
@ -82,22 +82,23 @@ namespace SHADE
[[nodiscard]] bool GetFreezeRotationY () const noexcept; [[nodiscard]] bool GetFreezeRotationY () const noexcept;
[[nodiscard]] bool GetFreezeRotationZ () const noexcept; [[nodiscard]] bool GetFreezeRotationZ () const noexcept;
[[nodiscard]] SHVec3 GetForce () const noexcept; [[nodiscard]] const SHVec3& GetForce () const noexcept;
[[nodiscard]] SHVec3 GetTorque () const noexcept; [[nodiscard]] const SHVec3& GetTorque () const noexcept;
[[nodiscard]] SHVec3 GetLinearVelocity () const noexcept; [[nodiscard]] const SHVec3& GetLinearVelocity () const noexcept;
[[nodiscard]] SHVec3 GetAngularVelocity () const noexcept; [[nodiscard]] const SHVec3& GetAngularVelocity () const noexcept;
[[nodiscard]] const SHVec3& GetPosition () const noexcept;
[[nodiscard]] const SHQuaternion& GetOrientation () const noexcept;
[[nodiscard]] SHVec3 GetRotation () const noexcept;
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Setter Functions */ /* Setter Functions */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
void SetType (Type newType) noexcept; void SetType (Type newType) noexcept;
void SetMass (float newMass) noexcept;
void SetDrag (float newDrag) noexcept;
void SetAngularDrag (float newAngularDrag) noexcept;
void SetGravityEnabled (bool enableGravity) noexcept; void SetGravityEnabled (bool enableGravity) noexcept;
void SetSleepingEnabled (bool enableSleeping) noexcept; void SetIsAllowedToSleep(bool isAllowedToSleep) noexcept;
void SetFreezePositionX (bool freezePositionX) noexcept; void SetFreezePositionX (bool freezePositionX) noexcept;
void SetFreezePositionY (bool freezePositionY) noexcept; void SetFreezePositionY (bool freezePositionY) noexcept;
void SetFreezePositionZ (bool freezePositionZ) noexcept; void SetFreezePositionZ (bool freezePositionZ) noexcept;
@ -106,8 +107,12 @@ namespace SHADE
void SetFreezeRotationZ (bool freezeRotationZ) noexcept; void SetFreezeRotationZ (bool freezeRotationZ) noexcept;
void SetInterpolate (bool allowInterpolation) noexcept; void SetInterpolate (bool allowInterpolation) noexcept;
void SetLinearVelocity (const SHVec3& newLinearVelocity) const noexcept; void SetMass (float newMass) noexcept;
void SetAngularVelocity (const SHVec3& newAngularVelocity) const noexcept; void SetDrag (float newDrag) noexcept;
void SetAngularDrag (float newAngularDrag) noexcept;
void SetLinearVelocity (const SHVec3& newLinearVelocity) noexcept;
void SetAngularVelocity (const SHVec3& newAngularVelocity) noexcept;
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Function Members */ /* Function Members */
@ -134,23 +139,33 @@ namespace SHADE
Type type; Type type;
// rX rY rZ pX pY pZ slp g
uint8_t flags;
// 0 0 0 0 0 0 aV lV aD d m t ag lc slp g
uint16_t dirtyFlags;
bool interpolate;
SHPhysicsSystem* system;
float mass; float mass;
float drag; float drag;
float angularDrag; float angularDrag;
// rX rY rZ pX pY pZ slp g SHVec3 force;
uint8_t flags; SHVec3 linearVelocity;
bool interpolate;
SHVec3 torque;
SHVec3 angularVelocity;
// TODO(Diren): Once quaternions have replaced euler angles in transforms, store it for the rigidbody.
SHVec3 position;
SHQuaternion orientation;
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Function Members */ /* Function Members */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
void SyncRP3DAndSHADE (); RTTR_ENABLE()
void SetFlag (bool flagState, int flagPos);
void SetRP3DLinearConstraints () const ;
void SetRP3DAngularConstraints () const ;
}; };
} // namespace SHADE } // namespace SHADE

View File

@ -0,0 +1,215 @@
/****************************************************************************************
* \file SHCollider.cpp
* \author Diren D Bharwani, diren.dbharwani, 390002520
* \brief Implementation for a Collider.
*
* \copyright Copyright (C) 2022 DigiPen Institute of Technology. Reproduction or
* disclosure of this file or its contents without the prior written consent
* of DigiPen Institute of Technology is prohibited.
****************************************************************************************/
#include <SHpch.h>
// Primary Header
#include "SHCollider.h"
namespace SHADE
{
/*-----------------------------------------------------------------------------------*/
/* Constructors & Destructor Definitions */
/*-----------------------------------------------------------------------------------*/
SHCollider::SHCollider(Type colliderType)
: type { colliderType }
, isTrigger { false }
, dirty { true }
, shape { nullptr }
{
CreateShape();
}
SHCollider::SHCollider(const SHCollider& rhs) noexcept
: type { rhs.type}
, isTrigger { rhs.isTrigger }
, dirty { true }
, shape { nullptr }
{
CreateShape();
// TODO(Diren): Copy transform data over
}
SHCollider::SHCollider(SHCollider&& rhs) noexcept
: type { rhs.type}
, isTrigger { rhs.isTrigger }
, dirty { true }
, shape { nullptr }
{
CreateShape();
// TODO(Diren): Copy transform data over
}
SHCollider::~SHCollider() noexcept
{
delete shape;
}
/*-----------------------------------------------------------------------------------*/
/* Operator Overload Definitions */
/*-----------------------------------------------------------------------------------*/
SHCollider& SHCollider::operator=(const SHCollider& rhs) noexcept
{
type = rhs.type;
isTrigger = rhs.isTrigger;
dirty = true;
CreateShape();
// TODO(Diren): Copy transform data over
return *this;
}
SHCollider& SHCollider::operator=(SHCollider&& rhs) noexcept
{
type = rhs.type;
isTrigger = rhs.isTrigger;
dirty = true;
CreateShape();
// TODO(Diren): Copy transform data over
return *this;
}
/*-----------------------------------------------------------------------------------*/
/* Getter Function Definitions */
/*-----------------------------------------------------------------------------------*/
bool SHCollider::HasChanged() const noexcept
{
return dirty;
}
bool SHCollider::IsTrigger() const noexcept
{
return isTrigger;
}
SHCollider::Type SHCollider::GetType() const noexcept
{
return type;
}
SHShape* SHCollider::GetShape() const noexcept
{
return shape;
}
float SHCollider::GetFriction() const noexcept
{
// TODO(Diren): Fix after implementing materials
return 0.0f;
}
float SHCollider::GetBounciness() const noexcept
{
// TODO(Diren): Fix after implementing materials
return 0.0f;
}
float SHCollider::GetDensity() const noexcept
{
// TODO(Diren): Fix after implementing materials
return 0.0f;
}
SHVec3 SHCollider::GetPosition() const noexcept
{
// TODO(Diren): Fix after linking transform data
return SHVec3::Zero;
}
const SHVec3& SHCollider::GetPositionOffset() const noexcept
{
return positionOffset;
}
SHQuaternion SHCollider::GetOrientation() const noexcept
{
// TODO(Diren): Fix after linking transform data
return SHQuaternion::Identity;
}
/*-----------------------------------------------------------------------------------*/
/* Setter Function Definitions */
/*-----------------------------------------------------------------------------------*/
void SHCollider::SetType(Type newType) noexcept
{
if (type == newType)
return;
dirty = true;
type = newType;
CreateShape();
}
void SHCollider::SetIsTrigger(bool trigger) noexcept
{
dirty = true;
isTrigger = trigger;
}
void SHCollider::SetFriction(float friction) noexcept
{
dirty = true;
}
void SHCollider::SetBounciness(float bounciness) noexcept
{
dirty = true;
}
void SHCollider::SetDensity(float density) noexcept
{
dirty = true;
}
void SHCollider::SetPositionOffset(const SHVec3& posOffset) noexcept
{
dirty = true;
positionOffset = posOffset;
}
/*-----------------------------------------------------------------------------------*/
/* Private Member Function Definitions */
/*-----------------------------------------------------------------------------------*/
void SHCollider::CreateShape()
{
// Remove current shape
delete shape;
switch (type)
{
case Type::BOX: CreateBoundingBox(); break;
case Type::SPHERE: CreateSphere(); break;
default: break;
}
}
void SHCollider::CreateBoundingBox()
{
shape = new SHBoundingBox{ SHVec3::Zero, SHVec3::One };
}
void SHCollider::CreateSphere()
{
}
} // namespace SHADE

View File

@ -0,0 +1,108 @@
/****************************************************************************************
* \file SHCollider.h
* \author Diren D Bharwani, diren.dbharwani, 390002520
* \brief Interface for a Collider.
*
* \copyright Copyright (C) 2022 DigiPen Institute of Technology. Reproduction or
* disclosure of this file or its contents without the prior written consent
* of DigiPen Institute of Technology is prohibited.
****************************************************************************************/
#pragma once
// Project Headers
#include "Math/Geometry/SHBoundingBox.h"
#include "Math/SHQuaternion.h"
namespace SHADE
{
/*-----------------------------------------------------------------------------------*/
/* Type Definitions */
/*-----------------------------------------------------------------------------------*/
class SH_API SHCollider
{
public:
/*---------------------------------------------------------------------------------*/
/* Type Definitions */
/*---------------------------------------------------------------------------------*/
enum class Type
{
BOX
, SPHERE
, CAPSULE
, CONVEX_HULL
, CONVEX_MESH
};
/*---------------------------------------------------------------------------------*/
/* Constructors & Destructor */
/*---------------------------------------------------------------------------------*/
SHCollider (Type colliderType);
SHCollider (const SHCollider& rhs) noexcept;
SHCollider (SHCollider&& rhs) noexcept;
~SHCollider () noexcept;
/*---------------------------------------------------------------------------------*/
/* Operator Overloads */
/*---------------------------------------------------------------------------------*/
SHCollider& operator=(const SHCollider& rhs) noexcept;
SHCollider& operator=(SHCollider&& rhs) noexcept;
/*---------------------------------------------------------------------------------*/
/* Getter Functions */
/*---------------------------------------------------------------------------------*/
[[nodiscard]] bool HasChanged () const noexcept;
[[nodiscard]] bool IsTrigger () const noexcept;
[[nodiscard]] Type GetType () const noexcept;
[[nodiscard]] SHShape* GetShape () const noexcept;
[[nodiscard]] float GetFriction () const noexcept;
[[nodiscard]] float GetBounciness () const noexcept;
[[nodiscard]] float GetDensity () const noexcept;
[[nodiscard]] SHVec3 GetPosition () const noexcept;
[[nodiscard]] const SHVec3& GetPositionOffset () const noexcept;
[[nodiscard]] SHQuaternion GetOrientation () const noexcept;
/*---------------------------------------------------------------------------------*/
/* Setter Functions */
/*---------------------------------------------------------------------------------*/
void SetType (Type newType) noexcept;
void SetIsTrigger (bool isTrigger) noexcept;
void SetFriction (float friction) noexcept;
void SetBounciness (float bounciness) noexcept;
void SetDensity (float density) noexcept;
void SetPositionOffset (const SHVec3& positionOffset) noexcept;
private:
/*---------------------------------------------------------------------------------*/
/* Data Members */
/*---------------------------------------------------------------------------------*/
Type type;
bool isTrigger;
bool dirty;
SHShape* shape;
SHVec3 positionOffset;
/*---------------------------------------------------------------------------------*/
/* Function Members */
/*---------------------------------------------------------------------------------*/
void CreateShape ();
void CreateBoundingBox ();
void CreateSphere ();
};
} // namespace SHADE

View File

@ -25,7 +25,8 @@ namespace SHADE
SHPhysicsObject::SHPhysicsObject() noexcept SHPhysicsObject::SHPhysicsObject() noexcept
: entityID { MAX_EID } : entityID { MAX_EID }
, componentFlags { 0 } , isRigidBody { false }
, hasColliders{ false }
, rp3dBody { nullptr } , rp3dBody { nullptr }
{} {}
@ -81,32 +82,11 @@ namespace SHADE
/* Public Function Member Definitions */ /* Public Function Member Definitions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
void SHPhysicsObject::Synchronise() const
{
if (const bool IS_DIRTY = componentFlags & 1U << 0; IS_DIRTY)
{
auto* physicsSystem = SHSystemManager::GetSystem<SHPhysicsSystem>();
const bool IS_RIGIDBODY_DIRTY = componentFlags & 1U << 1; /*-----------------------------------------------------------------------------------*/
const bool IS_COLLIDER_DIRTY = componentFlags & 1U << 3; /* Private Function Member Definitions */
/*-----------------------------------------------------------------------------------*/
if (IS_RIGIDBODY_DIRTY)
{
static constexpr auto COMP_ENUM = SHPhysicsSystem::UpdateComponent::RIGID_BODY;
const bool HAS_RIGIDBODY = componentFlags & 1U << 2;
HAS_RIGIDBODY ? physicsSystem->AddComponent(COMP_ENUM, entityID) : physicsSystem->RemoveComponent(COMP_ENUM, entityID);
}
if (IS_COLLIDER_DIRTY)
{
static constexpr auto COMP_ENUM = SHPhysicsSystem::UpdateComponent::COLLIDER;
const bool HAS_COLLIDER = componentFlags & 1U << 2;
HAS_COLLIDER ? physicsSystem->AddComponent(COMP_ENUM, entityID) : physicsSystem->RemoveComponent(COMP_ENUM, entityID);
}
}
}
} // namespace SHADE } // namespace SHADE

View File

@ -25,12 +25,14 @@ namespace SHADE
class SH_API SHPhysicsObject class SH_API SHPhysicsObject
{ {
protected: private:
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Friends */ /* Friends */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
friend class SHPhysicsSystem; friend class SHPhysicsSystem;
friend class SHRigidBodyComponent;
friend class SHColliderComponent;
public: public:
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
@ -40,7 +42,7 @@ namespace SHADE
SHPhysicsObject () noexcept; SHPhysicsObject () noexcept;
SHPhysicsObject (const SHPhysicsObject& rhs) noexcept = default; SHPhysicsObject (const SHPhysicsObject& rhs) noexcept = default;
SHPhysicsObject (SHPhysicsObject&& rhs) noexcept = default; SHPhysicsObject (SHPhysicsObject&& rhs) noexcept = default;
~SHPhysicsObject () noexcept; virtual ~SHPhysicsObject () noexcept;
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Operator Overloads */ /* Operator Overloads */
@ -53,30 +55,31 @@ namespace SHADE
/* Getter Functions */ /* Getter Functions */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
[[nodiscard]] SHVec3 GetPosition () const noexcept; [[nodiscard]] virtual SHVec3 GetPosition () const noexcept;
[[nodiscard]] SHQuaternion GetOrientation () const noexcept; [[nodiscard]] virtual SHQuaternion GetOrientation () const noexcept;
[[nodiscard]] SHVec3 GetRotation () const noexcept; [[nodiscard]] virtual SHVec3 GetRotation () const noexcept;
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Function Members */ /* Function Members */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/** private:
* @brief Checks for updates in the component states and tells the physics system to
* make any necessary additions / removals to rp3d side to sync with the SHADE
* component.
*/
void Synchronise() const;
protected:
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Data Members */ /* Data Members */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
EntityID entityID; EntityID entityID;
uint8_t componentFlags; // 0 0 0 c cDirty rb rbDirty dirty bool isRigidBody;
bool hasColliders;
rp3d::CollisionBody* rp3dBody; // Can be either a collision body or a rigid body rp3d::CollisionBody* rp3dBody; // Can be either a collision body or a rigid body
rp3d::Transform prevTransform; // Cached transform for interpolation rp3d::Transform prevTransform; // Cached transform for interpolation
/*---------------------------------------------------------------------------------*/
/* Function Members */
/*---------------------------------------------------------------------------------*/
}; };
} // namespace SHADE } // namespace SHADE

View File

@ -26,7 +26,7 @@ namespace SHADE
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
SHPhysicsSystem::SHPhysicsSystem() SHPhysicsSystem::SHPhysicsSystem()
: accumulatedTime { 0.0 } : interpolationFactor { 0.0 }
, fixedDT { 1.0 / 60.0 } , fixedDT { 1.0 / 60.0 }
, world { nullptr } , world { nullptr }
{} {}
@ -36,17 +36,22 @@ namespace SHADE
{} {}
SHPhysicsSystem::PhysicsFixedUpdate::PhysicsFixedUpdate() SHPhysicsSystem::PhysicsFixedUpdate::PhysicsFixedUpdate()
: SHFixedSystemRoutine { DEFAULT_FIXED_STEP, "Physics FixedUpdate", true } : SHFixedSystemRoutine { DEFAULT_FIXED_STEP, "Physics FixedUpdate", false }
{} {}
SHPhysicsSystem::PhysicsPostUpdate::PhysicsPostUpdate() SHPhysicsSystem::PhysicsPostUpdate::PhysicsPostUpdate()
: SHSystemRoutine { "Physics PostUpdate", true } : SHSystemRoutine { "Physics PostUpdate", false }
{} {}
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
/* Getter Function Definitions */ /* Getter Function Definitions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
double SHPhysicsSystem::GetFixedDT() const noexcept
{
return fixedDT;
}
bool SHPhysicsSystem::IsSleepingEnabled() const noexcept bool SHPhysicsSystem::IsSleepingEnabled() const noexcept
{ {
if (world) if (world)
@ -97,6 +102,11 @@ namespace SHADE
/* Setter Function Definitions */ /* Setter Function Definitions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
void SHPhysicsSystem::SetFixedDT(double fixedUpdateRate) noexcept
{
fixedDT = fixedUpdateRate;
}
void SHPhysicsSystem::SetWorldGravity(const SHVec3& gravity) const noexcept void SHPhysicsSystem::SetWorldGravity(const SHVec3& gravity) const noexcept
{ {
if (world) if (world)
@ -185,228 +195,362 @@ namespace SHADE
factory.destroyPhysicsWorld(world); factory.destroyPhysicsWorld(world);
} }
void SHPhysicsSystem::PhysicsPreUpdate::Execute([[maybe_unused]]double dt) noexcept void SHPhysicsSystem::AddRigidBody(EntityID entityID) noexcept
{
#ifdef _DEBUG
SHLOG_INFO("Adding a Rigidbody to the Physics World.")
#endif
// Check if entity is already a physics object
auto* physicsObject = GetPhysicsObject(entityID);
if (!physicsObject)
physicsObject = &(map.emplace(entityID, SHPhysicsObject{}).first->second);
// Get entity transform
auto const* SHADE_TF = SHComponentManager::GetComponent_s<SHTransformComponent>(entityID);
// Possibly redundant
if (!SHADE_TF)
{
SHComponentManager::AddComponent<SHTransformComponent>(entityID);
SHADE_TF = SHComponentManager::GetComponent<SHTransformComponent>(entityID);
}
const SHVec3& SHADE_POS = SHADE_TF->GetWorldPosition();
const SHVec3& SHADE_ROT = SHADE_TF->GetWorldRotation();
const rp3d::Vector3 RP3D_POS { SHADE_POS.x, SHADE_POS.y, SHADE_POS.z };
const rp3d::Quaternion RP3D_ROT = rp3d::Quaternion::fromEulerAngles( SHADE_ROT.x, SHADE_ROT.y, SHADE_ROT.z );
physicsObject->rp3dBody = world->createRigidBody(rp3d::Transform{ RP3D_POS, RP3D_ROT });
physicsObject->isRigidBody = true;
}
void SHPhysicsSystem::AddCollider(EntityID entityID) noexcept
{
#ifdef _DEBUG
SHLOG_INFO("Adding a Collider to the Physics World.")
#endif
}
void SHPhysicsSystem::RemoveRigidBody(EntityID entityID) noexcept
{
#ifdef _DEBUG
SHLOG_INFO("Removing a Rigidbody from the Physics World.")
#endif
}
void SHPhysicsSystem::RemoveCollider(EntityID entityID) noexcept
{
#ifdef _DEBUG
SHLOG_INFO("Removing a Collider from the Physics World.")
#endif
}
void SHPhysicsSystem::AddForce(EntityID entityID, const SHVec3& force) const noexcept
{
}
void SHPhysicsSystem::AddForceAtLocalPos(EntityID entityID, const SHVec3& force, const SHVec3& localPos) const noexcept
{
}
void SHPhysicsSystem::AddForceAtWorldPos(EntityID entityID, const SHVec3& force, const SHVec3& worldPos) const noexcept
{
}
void SHPhysicsSystem::AddRelativeForce(EntityID entityID, const SHVec3& relativeForce) const noexcept
{
}
void SHPhysicsSystem::AddRelativeForceAtLocalPos(EntityID entityID, const SHVec3& relativeForce, const SHVec3& localPos) const noexcept
{
}
void SHPhysicsSystem::AddRelativeForceAtWorldPos(EntityID entityID, const SHVec3& relativeForce, const SHVec3& worldPos) const noexcept
{
}
void SHPhysicsSystem::AddTorque(EntityID entityID, const SHVec3& torque) const noexcept
{
}
void SHPhysicsSystem::AddRelativeTorque(EntityID entityID, const SHVec3& relativeTorque) const noexcept
{
}
void SHPhysicsSystem::PhysicsPreUpdate::Execute(double) noexcept
{ {
auto* system = reinterpret_cast<SHPhysicsSystem*>(GetSystem()); auto* system = reinterpret_cast<SHPhysicsSystem*>(GetSystem());
system->ClearUpdateQueue(); // Update bodies and colliders if component is dirty
//system->SyncActiveStates(SHSceneManager::GetCurrentSceneGraph()); const auto& sceneGraph = SHSceneManager::GetCurrentSceneGraph();
system->SyncComponents(sceneGraph);
} }
void SHPhysicsSystem::PhysicsFixedUpdate::FixedExecute(double dt) noexcept void SHPhysicsSystem::PhysicsFixedUpdate::Execute(double dt) noexcept
{ {
auto* system = reinterpret_cast<SHPhysicsSystem*>(GetSystem()); auto* system = reinterpret_cast<SHPhysicsSystem*>(GetSystem());
system->world->update(static_cast<rp3d::decimal>(dt)); fixedTimeStep = 1.0 / system->fixedDT;
accumulatedTime += dt;
system->fixedDT = fixedTimeStep; int count = 0;
system->accumulatedTime = accumulatedTime; while (accumulatedTime > fixedTimeStep)
{
system->world->update(static_cast<rp3d::decimal>(fixedTimeStep));
accumulatedTime -= fixedTimeStep;
++count;
} }
void SHPhysicsSystem::PhysicsPostUpdate::Execute(double dt) noexcept stats.numSteps = count;
system->interpolationFactor = accumulatedTime / fixedTimeStep;
}
void SHPhysicsSystem::PhysicsPostUpdate::Execute(double) noexcept
{ {
auto* system = reinterpret_cast<SHPhysicsSystem*>(GetSystem()); auto* system = reinterpret_cast<SHPhysicsSystem*>(GetSystem());
// Interpolate transforms for rendering // Interpolate transforms for rendering
const auto& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); const auto& sceneGraph = SHSceneManager::GetCurrentSceneGraph();
//system->SyncTransforms(sceneGraph); system->SyncTransforms(sceneGraph);
// TODO(Diren): Handle trigger messages for scripting // TODO(Diren): Handle trigger messages for scripting
} }
/*-----------------------------------------------------------------------------------*/
/* Protected Function Member Definitions */
/*-----------------------------------------------------------------------------------*/
void SHPhysicsSystem::AddComponent(UpdateComponent comp, EntityID entityID) noexcept
{
updateQueue.push({ comp, UpdateType::ADD, entityID });
}
void SHPhysicsSystem::RemoveComponent(UpdateComponent comp, EntityID entityID) noexcept
{
updateQueue.push({ comp, UpdateType::REMOVE, entityID });
}
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
/* Private Function Member Definitions */ /* Private Function Member Definitions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
void SHPhysicsSystem::ClearUpdateQueue() noexcept SHPhysicsObject* SHPhysicsSystem::GetPhysicsObject(EntityID entityID) noexcept
{ {
while (!updateQueue.empty()) const auto it = map.find(entityID);
if (it == map.end())
{ {
const auto& CMD = updateQueue.front(); SHLOG_ERROR("Entity {} is not in the physics system!", entityID)
switch (CMD.type) return nullptr;
{
case UpdateType::ADD:
{
switch (CMD.component)
{
case UpdateComponent::RIGID_BODY: AddRigidBody(CMD.entityID); break;
//case UpdateComponent::COLLIDER: AddCollider(CMD.entityID); break;
default: break;
}
}
case UpdateType::REMOVE:
{
switch (CMD.component)
{
case UpdateComponent::RIGID_BODY: RemoveRigidBody(CMD.entityID); break;
//case UpdateComponent::COLLIDER: RemoveCollider(CMD.entityID); break;
default: break;
}
}
default: break;
} }
updateQueue.pop(); return &(it->second);
}
} }
void SHPhysicsSystem::SyncActiveStates(const SHSceneGraph& sceneGraph) const noexcept void SHPhysicsSystem::SyncComponents(const SHSceneGraph& sceneGraph) noexcept
{ {
// Sync active states: if node or component is not active, set rp3d to inactive static const auto SYNC_COMPONENTS = [&](SHSceneNode* node)
static constexpr auto SYNC_ACTIVE = [](SHSceneNode* node)
{ {
const EntityID ENTITY_ID = node->GetEntityID(); const EntityID ENTITY_ID = node->GetEntityID();
// Check if has rigid body // Get physics object
auto const* rigidBodyComponent = SHComponentManager::GetComponent_s<SHRigidBodyComponent>(ENTITY_ID); auto const* physicsObject = GetPhysicsObject(ENTITY_ID);
if(rigidBodyComponent) if (!physicsObject)
{ return;
const bool RP3D_ACTIVE = rigidBodyComponent->rp3dBody->isActive();
const bool SHADE_ACTIVE = node->IsActive() && rigidBodyComponent->isActive;
if (RP3D_ACTIVE != SHADE_ACTIVE) const bool RP3D_ACTIVE = physicsObject->rp3dBody->isActive();
rigidBodyComponent->rp3dBody->setIsActive(SHADE_ACTIVE); const bool NODE_ACTIVE = node->IsActive();
// Sync rigid body
if (physicsObject->isRigidBody)
{
auto* rbComponent = SHComponentManager::GetComponent_s<SHRigidBodyComponent>(ENTITY_ID);
if (rbComponent->dirtyFlags > 0)
{
SyncRB(physicsObject, rbComponent);
rbComponent->dirtyFlags = 0;
} }
else // Check for a collider
{
// Sync active states
const bool SHADE_ACTIVE = NODE_ACTIVE && rbComponent->isActive;
if (SHADE_ACTIVE != RP3D_ACTIVE)
physicsObject->rp3dBody->setIsActive(SHADE_ACTIVE);
}
// Sync colliders
if (physicsObject->hasColliders)
{
auto const* colliderComponent = SHComponentManager::GetComponent_s<SHColliderComponent>(ENTITY_ID);
}
// Sync transforms
auto const* tfComponent = SHComponentManager::GetComponent<SHTransformComponent>(ENTITY_ID);
if (tfComponent->HasChanged())
{
const SHVec3& SHADE_POS = tfComponent->GetWorldPosition();
const SHVec3& SHADE_ROT = tfComponent->GetWorldRotation();
const rp3d::Vector3 RP3D_POS { SHADE_POS.x, SHADE_POS.y, SHADE_POS.z };
const rp3d::Quaternion RP3D_ROT = rp3d::Quaternion::fromEulerAngles(SHADE_ROT.x, SHADE_ROT.y, SHADE_ROT.z);
physicsObject->rp3dBody->setTransform(rp3d::Transform{ RP3D_POS, RP3D_ROT });
} }
}; };
sceneGraph.Traverse(SYNC_ACTIVE); sceneGraph.Traverse(SYNC_COMPONENTS);
} }
void SHPhysicsSystem::SyncTransforms(const SHSceneGraph& sceneGraph) const noexcept void SHPhysicsSystem::SyncTransforms(const SHSceneGraph& sceneGraph) noexcept
{ {
const rp3d::decimal INTERPOLATION_FACTOR = static_cast<rp3d::decimal>(accumulatedTime / fixedDT);
static const auto SYNC_TRANSFORMS = [&](SHSceneNode* node) static const auto SYNC_TRANSFORMS = [&](SHSceneNode* node)
{ {
const EntityID ENTITY_ID = node->GetEntityID(); const EntityID ENTITY_ID = node->GetEntityID();
// Check if has rigid body // Get physics object
if (auto* rb = SHComponentManager::GetComponent_s<SHRigidBodyComponent>(ENTITY_ID); rb) auto* physicsObject = GetPhysicsObject(ENTITY_ID);
if (!physicsObject)
return;
auto* tfComponent = SHComponentManager::GetComponent_s<SHTransformComponent>(ENTITY_ID);
rp3d::Vector3 rp3dPos;
rp3d::Quaternion rp3dRot;
const rp3d::Transform CURRENT_TF = physicsObject->rp3dBody->getTransform();
// Check if transform should be interpolated
auto const* rbComponent = SHComponentManager::GetComponent_s<SHRigidBodyComponent>(ENTITY_ID);
if (rbComponent && rbComponent->IsInterpolating())
{ {
if (node->IsActive() && rb->isActive) const rp3d::Transform PREV_TF = physicsObject->prevTransform;
{ const rp3d::Transform INTERPOLATED_TF = rp3d::Transform::interpolateTransforms(PREV_TF, CURRENT_TF, static_cast<rp3d::decimal>(interpolationFactor));
// Get SHADE transform
auto* transformComponent = SHComponentManager::GetComponent_s<SHTransformComponent>(ENTITY_ID);
SHASSERT(transformComponent != nullptr, "Transform Component missing from Entity " + std::to_string(ENTITY_ID))
SHVec3 shadePos, shadeRot;
if (rb->interpolate) rp3dPos = INTERPOLATED_TF.getPosition();
{ rp3dRot = INTERPOLATED_TF.getOrientation();
const rp3d::Transform CURRENT_TRANSFORM = rb->rp3dBody->getTransform();
const rp3d::Transform INTERPOLATED_TRANSFORM = rp3d::Transform::interpolateTransforms(rb->prevTransform, CURRENT_TRANSFORM, INTERPOLATION_FACTOR);
const auto& RP3D_POS = INTERPOLATED_TRANSFORM.getPosition();
shadePos = SHVec3{ RP3D_POS.x, RP3D_POS.y, RP3D_POS.z };
const auto& RP3D_ORT = INTERPOLATED_TRANSFORM.getOrientation();
shadeRot = SHQuaternion{ RP3D_ORT.x, RP3D_ORT.y, RP3D_ORT.z, RP3D_ORT.w }.ToEuler();
rb->prevTransform = CURRENT_TRANSFORM;
} }
else else
{ {
rp3dPos = CURRENT_TF.getPosition();
const auto& RP3D_POS = rb->GetPosition(); rp3dRot = CURRENT_TF.getOrientation();
shadePos = SHVec3{ RP3D_POS.x, RP3D_POS.y, RP3D_POS.z };
shadeRot = rb->GetOrientation().ToEuler();
} }
transformComponent->SetWorldPosition(shadePos); // Convert RP3D Transform to SHADE
transformComponent->SetWorldRotation(shadeRot); const SHVec3 SHADE_POS = SHVec3{ rp3dPos.x, rp3dPos.y, rp3dPos.z };
} const SHVec3 SHADE_ROT = SHQuaternion{ rp3dRot.x, rp3dRot.y, rp3dRot.z, rp3dRot.w }.ToEuler();
else // Check for a collider
{
} tfComponent->SetWorldPosition(SHADE_POS);
} tfComponent->SetWorldRotation(SHADE_ROT);
// Cache transforms
physicsObject->prevTransform = CURRENT_TF;
}; };
sceneGraph.Traverse(SYNC_TRANSFORMS); sceneGraph.Traverse(SYNC_TRANSFORMS);
} }
void SHPhysicsSystem::SyncRB(SHPhysicsObject const* physicsObject, const SHRigidBodyComponent* comp) noexcept
void SHPhysicsSystem::AddRigidBody(EntityID entityID) const noexcept
{ {
#ifdef _DEBUG auto* rigidBody = reinterpret_cast<rp3d::RigidBody*>(physicsObject->rp3dBody);
SHLOG_INFO("Adding a Rigidbody to the Physics World.")
#endif
// Rigid Bodies need a transform. const uint16_t RB_FLAGS = comp->dirtyFlags;
auto const* transformComponent = SHComponentManager::GetComponent_s<SHTransformComponent>(entityID); const size_t NUM_FLAGS = sizeof(RB_FLAGS) * 8U;
if (!transformComponent) for (size_t i = 0; i < NUM_FLAGS; ++i)
{ {
// NOTE: This should already be handled by the editor. // Check if current dirty flag has been set to true
if (RB_FLAGS & 1U << i)
{
switch (i)
{
case 0: // Gravity
{
rigidBody->enableGravity(comp->IsGravityEnabled());
break;
}
case 1: // Sleeping
{
rigidBody->setIsAllowedToSleep(comp->IsAllowedToSleep());
break;
}
case 2: // Linear Constraints
{
SetRP3DLinearConstraints(rigidBody, comp->flags);
break;
}
case 3: // Angular Constraints
{
SetRP3DAngularConstraints(rigidBody, comp->flags);
break;
}
case 4: // Type
{
rigidBody->setType(static_cast<rp3d::BodyType>(comp->GetType()));
break;
}
case 5: // Mass
{
rigidBody->setMass(comp->GetMass());
break;
}
case 6: // Drag
{
rigidBody->setLinearDamping(comp->GetDrag());
break;
}
case 7: // Angular Drag
{
rigidBody->setAngularDamping(comp->GetAngularDrag());
break;
}
case 8: // Linear Velocity
{
const SHVec3& SHADE_VEL = comp->GetLinearVelocity();
rp3d::Vector3 RP3D_VEL { SHADE_VEL.x, SHADE_VEL.y, SHADE_VEL.z };
SHLOG_INFO("Automatically adding a transform to Entity {}", entityID) rigidBody->setLinearVelocity(RP3D_VEL);
SHComponentManager::AddComponent<SHTransformComponent>(entityID); break;
transformComponent = SHComponentManager::GetComponent<SHTransformComponent>(entityID); }
case 9: // Angular Velocity
{
const SHVec3& SHADE_VEL = comp->GetAngularVelocity();
rp3d::Vector3 RP3D_VEL { SHADE_VEL.x, SHADE_VEL.y, SHADE_VEL.z };
rigidBody->setAngularVelocity(RP3D_VEL);
break;
}
default: break;
}
}
}
} }
const SHVec3& SHADE_WORLD_POSITION = transformComponent->GetWorldPosition(); void SHPhysicsSystem::SetRP3DLinearConstraints(rp3d::RigidBody const* rp3dRigidBody, uint8_t rbFlags) noexcept
const rp3d::Vector3 RP3D_POSITION { SHADE_WORLD_POSITION.x, SHADE_WORLD_POSITION.y, SHADE_WORLD_POSITION.z };
const SHVec3& SHADE_WORLD_ROTATION = transformComponent->GetWorldRotation();
const rp3d::Quaternion RP3D_ORIENTATION = rp3d::Quaternion::fromEulerAngles(SHADE_WORLD_ROTATION.x, SHADE_WORLD_ROTATION.y, SHADE_WORLD_ROTATION.z);
const rp3d::Transform RP3D_TF { RP3D_POSITION, RP3D_ORIENTATION };
auto* rigidBodyComponent = SHComponentManager::GetComponent_s<SHRigidBodyComponent>(entityID);
if (!rigidBodyComponent)
{ {
// NOTE: This should already be handled by the editor. const rp3d::Vector3 CONSTRAINTS
{
rbFlags & 1U << 2 ? 1.0f : 0.0f,
rbFlags & 1U << 3 ? 1.0f : 0.0f,
rbFlags & 1U << 4 ? 1.0f : 0.0f
};
SHLOG_INFO("Automatically adding a rigidbody to Entity {}", entityID)
SHComponentManager::AddComponent<SHRigidBodyComponent>(entityID); rp3dRigidBody->setLinearLockAxisFactor(CONSTRAINTS);
rigidBodyComponent = SHComponentManager::GetComponent<SHRigidBodyComponent>(entityID);
} }
rigidBodyComponent->rp3dBody = world->createRigidBody(RP3D_TF); void SHPhysicsSystem::SetRP3DAngularConstraints(rp3d::RigidBody const* rp3dRigidBody, uint8_t rbFlags) noexcept
rigidBodyComponent->prevTransform = RP3D_TF; {
rigidBodyComponent->SyncRP3DAndSHADE(); const rp3d::Vector3 CONSTRAINTS
{
rbFlags & 1U << 5 ? 1.0f : 0.0f,
rbFlags & 1U << 6 ? 1.0f : 0.0f,
rbFlags & 1U << 7 ? 1.0f : 0.0f
};
// Reassign collider rp3dRigidBody->setAngularLockAxisFactor(CONSTRAINTS);
//if (collider)
//{
// collider.
//}
} }
void SHPhysicsSystem::RemoveRigidBody(EntityID entityID) const noexcept void SHPhysicsSystem::SyncColliders(SHPhysicsObject const* physicsObject, const SHColliderComponent* comp) noexcept
{ {
#ifdef _DEBUG
SHLOG_INFO("Removing a Rigidbody from the Physics World.")
#endif
auto* rigidBodyComponent = SHComponentManager::GetComponent_s<SHRigidBodyComponent>(entityID);
if (rigidBodyComponent == nullptr)
{
SHLOG_ERROR("Entity {} does not have a rigidbody component to remove!", entityID)
return;
}
// If a collider exists, remake the colliders with a collision body
world->destroyRigidBody(reinterpret_cast<rp3d::RigidBody*>(rigidBodyComponent->rp3dBody));
rigidBodyComponent->rp3dBody = nullptr; // this should be redundant
} }
} // namespace SHADE } // namespace SHADE

View File

@ -11,16 +11,20 @@
#pragma once #pragma once
#include <queue> #include <queue>
#include <unordered_map>
#include <reactphysics3d/reactphysics3d.h> #include <reactphysics3d/reactphysics3d.h>
// Project Headers // Project Headers
#include "Math/SHQuaternion.h" #include "SHPhysicsObject.h"
#include "Components/SHRigidBodyComponent.h" #include "Components/SHRigidBodyComponent.h"
#include "Components/SHColliderComponent.h"
#include "Scene/SHSceneGraph.h" #include "Scene/SHSceneGraph.h"
#include "ECS_Base/System/SHSystemRoutine.h" #include "ECS_Base/System/SHSystemRoutine.h"
#include "ECS_Base/System/SHFixedSystemRoutine.h" #include "ECS_Base/System/SHFixedSystemRoutine.h"
namespace SHADE namespace SHADE
{ {
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
@ -29,13 +33,6 @@ namespace SHADE
class SH_API SHPhysicsSystem : public SHSystem class SH_API SHPhysicsSystem : public SHSystem
{ {
protected:
/*---------------------------------------------------------------------------------*/
/* Friends */
/*---------------------------------------------------------------------------------*/
friend class SHPhysicsObject;
public: public:
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Type Definitions */ /* Type Definitions */
@ -59,6 +56,8 @@ namespace SHADE
/* Getter Functions */ /* Getter Functions */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
[[nodiscard]] double GetFixedDT () const noexcept;
[[nodiscard]] bool IsSleepingEnabled () const noexcept; [[nodiscard]] bool IsSleepingEnabled () const noexcept;
[[nodiscard]] SHVec3 GetWorldGravity () const noexcept; [[nodiscard]] SHVec3 GetWorldGravity () const noexcept;
@ -70,7 +69,7 @@ namespace SHADE
/* Setter Functions */ /* Setter Functions */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
//void SetFixedUpdate (double fixedUpdateRate) noexcept; void SetFixedDT (double fixedUpdateRate) noexcept;
void SetWorldGravity (const SHVec3& gravity) const noexcept; void SetWorldGravity (const SHVec3& gravity) const noexcept;
void SetNumberVelocityIterations (uint16_t numVelIterations) const noexcept; void SetNumberVelocityIterations (uint16_t numVelIterations) const noexcept;
void SetNumberPositionIterations (uint16_t numPosIterations) const noexcept; void SetNumberPositionIterations (uint16_t numPosIterations) const noexcept;
@ -85,10 +84,29 @@ namespace SHADE
void Init () override; void Init () override;
void Exit () override; void Exit () override;
void AddRigidBody (EntityID entityID) noexcept;
void AddCollider (EntityID entityID) noexcept;
void RemoveRigidBody (EntityID entityID) noexcept;
void RemoveCollider (EntityID entityID) noexcept;
void AddForce (EntityID entityID, const SHVec3& force) const noexcept;
void AddForceAtLocalPos (EntityID entityID, const SHVec3& force, const SHVec3& localPos) const noexcept;
void AddForceAtWorldPos (EntityID entityID, const SHVec3& force, const SHVec3& worldPos) const noexcept;
void AddRelativeForce (EntityID entityID, const SHVec3& relativeForce) const noexcept;
void AddRelativeForceAtLocalPos (EntityID entityID, const SHVec3& relativeForce, const SHVec3& localPos) const noexcept;
void AddRelativeForceAtWorldPos (EntityID entityID, const SHVec3& relativeForce, const SHVec3& worldPos) const noexcept;
void AddTorque (EntityID entityID, const SHVec3& torque) const noexcept;
void AddRelativeTorque (EntityID entityID, const SHVec3& relativeTorque) const noexcept;
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* System Routines */ /* System Routines */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/**
* @brief Synchronises RP3D with SHADE
*/
class SH_API PhysicsPreUpdate : public SHSystemRoutine class SH_API PhysicsPreUpdate : public SHSystemRoutine
{ {
public: public:
@ -118,8 +136,7 @@ namespace SHADE
/* Function Members */ /* Function Members */
/*-------------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------------*/
//void Execute (double dt) noexcept override; void Execute (double dt) noexcept override;
void FixedExecute (double dt) noexcept override;
}; };
class SH_API PhysicsPostUpdate : public SHSystemRoutine class SH_API PhysicsPostUpdate : public SHSystemRoutine
@ -138,56 +155,43 @@ namespace SHADE
void Execute(double dt) noexcept override; void Execute(double dt) noexcept override;
}; };
protected: private:
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Type Definitions */ /* Type Definitions */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
enum class UpdateComponent { RIGID_BODY, COLLIDER }; using EntityObjectMap = std::unordered_map<EntityID, SHPhysicsObject>;
enum class UpdateType { ADD, REMOVE };
struct UpdateCommand
{
UpdateComponent component;
UpdateType type;
EntityID entityID;
};
/*---------------------------------------------------------------------------------*/
/* Function Members */
/*---------------------------------------------------------------------------------*/
void AddComponent (UpdateComponent comp, EntityID entityID) noexcept;
void RemoveComponent (UpdateComponent comp, EntityID entityID) noexcept;
private:
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Data Members */ /* Data Members */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
// TODO(Diren): Store interpFactor & fixedUpdate for modifiable fixedDT // TODO(Diren): Store interpFactor
double accumulatedTime; double interpolationFactor;
double fixedDT; double fixedDT;
rp3d::PhysicsCommon factory; rp3d::PhysicsCommon factory;
rp3d::PhysicsWorld* world; rp3d::PhysicsWorld* world;
std::queue<UpdateCommand> updateQueue; EntityObjectMap map;
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Function Members */ /* Function Members */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
SHPhysicsObject* GetPhysicsObject (EntityID entityID) noexcept;
void ClearUpdateQueue () noexcept; void SyncComponents (const SHSceneGraph& sceneGraph) noexcept;
void SyncActiveStates (const SHSceneGraph& sceneGraph) const noexcept; void SyncTransforms (const SHSceneGraph& sceneGraph) noexcept;
void SyncTransforms (const SHSceneGraph& sceneGraph) const noexcept;
// TODO(Diren): Trigger handling // TODO(Diren): Trigger handling
void AddRigidBody (EntityID entityID) const noexcept; static void SyncRB (SHPhysicsObject const* physicsObject, const SHRigidBodyComponent* comp) noexcept;
void AddCollider (EntityID entityID) const noexcept; static void SetRP3DLinearConstraints (rp3d::RigidBody const* rp3dRigidBody, uint8_t rbFlags) noexcept;
void RemoveRigidBody (EntityID entityID) const noexcept; static void SetRP3DAngularConstraints (rp3d::RigidBody const* rp3dRigidBody, uint8_t rbFlags) noexcept;
void RemoveCollider (EntityID entityID) const noexcept;
static void SyncColliders (SHPhysicsObject const* physicsObject, const SHColliderComponent* comp) noexcept;
}; };