From 371ffc52dabe294600505026694d8d15cf21911d Mon Sep 17 00:00:00 2001 From: Diren D Bharwani Date: Thu, 27 Oct 2022 03:14:46 +0800 Subject: [PATCH 01/12] Colliders now use relative sizes --- SHADE_Application/src/Scenes/SBTestScene.cpp | 6 +- .../Inspector/SHEditorComponentView.hpp | 35 ++++-- SHADE_Engine/src/Math/Geometry/SHShape.cpp | 3 +- SHADE_Engine/src/Math/Geometry/SHShape.h | 4 +- .../Components/SHColliderComponent.cpp | 21 ++-- .../Physics/Components/SHColliderComponent.h | 3 +- SHADE_Engine/src/Physics/SHCollider.cpp | 85 ++++++++++--- SHADE_Engine/src/Physics/SHCollider.h | 55 +++++---- .../src/Physics/SHPhysicsMaterial.cpp | 104 ++++++++++++++++ SHADE_Engine/src/Physics/SHPhysicsMaterial.h | 113 ++++++++++++++++++ SHADE_Engine/src/Physics/SHPhysicsObject.cpp | 6 +- SHADE_Engine/src/Physics/SHPhysicsSystem.cpp | 6 +- SHADE_Engine/src/Scene/SHSceneGraph.cpp | 10 +- SHADE_Engine/src/Scene/SHSceneGraph.h | 2 +- 14 files changed, 369 insertions(+), 84 deletions(-) create mode 100644 SHADE_Engine/src/Physics/SHPhysicsMaterial.cpp create mode 100644 SHADE_Engine/src/Physics/SHPhysicsMaterial.h diff --git a/SHADE_Application/src/Scenes/SBTestScene.cpp b/SHADE_Application/src/Scenes/SBTestScene.cpp index a06e68c2..d0d64c73 100644 --- a/SHADE_Application/src/Scenes/SBTestScene.cpp +++ b/SHADE_Application/src/Scenes/SBTestScene.cpp @@ -95,11 +95,7 @@ namespace Sandbox transform.SetWorldRotation(SHMath::GenerateRandomNumber(0.0f, 360.0f), SHMath::GenerateRandomNumber(0.0f, 360.0f), SHMath::GenerateRandomNumber(0.0f, 360.0f)); transform.SetWorldScale(TEST_OBJ_SCALE); - //if (const bool IS_EVEN = (y * NUM_ROWS + x) % 2; IS_EVEN) - collider.AddBoundingBox(SHVec3::One * 0.5f, SHVec3::Zero); - //else - // collider.AddBoundingSphere(0.5f, SHVec3::Zero); - + collider.AddBoundingBox(SHVec3::One, SHVec3::Zero); stressTestObjects.emplace_back(entity); } diff --git a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp index 7fa39d74..4645bf52 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp +++ b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp @@ -207,6 +207,10 @@ namespace SHADE { if (!component) return; + + // Get transform component for extrapolating relative sizes + auto* transformComponent = SHComponentManager::GetComponent(component->GetEID()); + const auto componentType = rttr::type::get(*component); SHEditorWidgets::CheckBox("##IsActive", [component]() {return component->isActive; }, [component](bool const& active) {component->isActive = active; }); ImGui::SameLine(); @@ -221,28 +225,41 @@ namespace SHADE for (int i{}; i < size; ++i) { ImGui::PushID(i); - SHCollider& collider = component->GetCollider(i); + SHCollider* collider = &component->GetCollider(i); auto cursorPos = ImGui::GetCursorPos(); - if (collider.GetType() == SHCollider::Type::BOX) + if (collider->GetType() == SHCollider::Type::BOX) { SHEditorWidgets::BeginPanel( std::format("{} Box Collider #{}", ICON_FA_CUBE, i).data(), { ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y }); - auto box = reinterpret_cast(collider.GetShape()); - SHEditorWidgets::DragVec3("Half Extents", { "X", "Y", "Z" }, [box] {return box->GetHalfExtents(); }, [box](SHVec3 const& vec) {box->SetHalfExtents(vec);}); + auto box = reinterpret_cast(collider->GetShape()); + SHEditorWidgets::DragVec3 + ( + "Half Extents", { "X", "Y", "Z" }, + [box, transformComponent] { return (transformComponent->GetWorldScale() * 2.0f) * box->GetHalfExtents(); }, + [collider](SHVec3 const& vec) { collider->SetBoundingBox(vec); }); } - else if (collider.GetType() == SHCollider::Type::SPHERE) + else if (collider->GetType() == SHCollider::Type::SPHERE) { SHEditorWidgets::BeginPanel(std::format("{} Sphere Collider #{}", ICON_MD_CIRCLE, i).data(), { ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y }); - auto sphere = reinterpret_cast(collider.GetShape()); - SHEditorWidgets::DragFloat("Radius", [sphere] {return sphere->GetRadius(); }, [sphere](float const& value) {sphere->SetRadius(value);}); + auto sphere = reinterpret_cast(collider->GetShape()); + SHEditorWidgets::DragFloat + ( + "Radius", + [sphere, transformComponent] + { + const SHVec3& TF_WORLD_SCALE = transformComponent->GetWorldScale(); + const float MAX_SCALE = SHMath::Max({ TF_WORLD_SCALE.x, TF_WORLD_SCALE.y, TF_WORLD_SCALE.z }); + return sphere->GetRadius() / MAX_SCALE; + }, + [collider](float const& value) { collider->SetBoundingSphere(value);}); } - else if (collider.GetType() == SHCollider::Type::CAPSULE) + else if (collider->GetType() == SHCollider::Type::CAPSULE) { } { SHEditorWidgets::BeginPanel("Offset", { ImGui::GetContentRegionAvail().x, 30.0f }); - SHEditorWidgets::DragVec3("Position", { "X", "Y", "Z" }, [&collider] {return collider.GetPositionOffset(); }, [&collider](SHVec3 const& vec) {collider.SetPositionOffset(vec); }); + SHEditorWidgets::DragVec3("Position", { "X", "Y", "Z" }, [&collider] {return collider->GetPositionOffset(); }, [&collider](SHVec3 const& vec) {collider->SetPositionOffset(vec); }); SHEditorWidgets::EndPanel(); } if(ImGui::Button(std::format("{} Remove Collider #{}", ICON_MD_REMOVE, i).data())) diff --git a/SHADE_Engine/src/Math/Geometry/SHShape.cpp b/SHADE_Engine/src/Math/Geometry/SHShape.cpp index 3fc5775d..2f869029 100644 --- a/SHADE_Engine/src/Math/Geometry/SHShape.cpp +++ b/SHADE_Engine/src/Math/Geometry/SHShape.cpp @@ -27,10 +27,9 @@ namespace SHADE /* Getter Function Definitions */ /*-----------------------------------------------------------------------------------*/ - SHShape::Type SHShape::GetType() const + SHShape::Type SHShape::GetType() const noexcept { return type; } - } // namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/Math/Geometry/SHShape.h b/SHADE_Engine/src/Math/Geometry/SHShape.h index 18f54fe6..62198897 100644 --- a/SHADE_Engine/src/Math/Geometry/SHShape.h +++ b/SHADE_Engine/src/Math/Geometry/SHShape.h @@ -63,7 +63,7 @@ namespace SHADE /* Getter Functions */ /*---------------------------------------------------------------------------------*/ - [[nodiscard]] Type GetType() const; + [[nodiscard]] Type GetType () const noexcept; /*---------------------------------------------------------------------------------*/ /* Function Members */ @@ -77,6 +77,6 @@ namespace SHADE /* Data Members */ /*---------------------------------------------------------------------------------*/ - Type type; + Type type; }; } // namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/Components/SHColliderComponent.cpp b/SHADE_Engine/src/Physics/Components/SHColliderComponent.cpp index 75a00491..fb999847 100644 --- a/SHADE_Engine/src/Physics/Components/SHColliderComponent.cpp +++ b/SHADE_Engine/src/Physics/Components/SHColliderComponent.cpp @@ -58,7 +58,7 @@ namespace SHADE if (index < 0 || static_cast(index) >= colliders.size()) throw std::invalid_argument("Out-of-range access!"); - return colliders[index].first; + return colliders[index]; } /*-----------------------------------------------------------------------------------*/ @@ -85,13 +85,11 @@ namespace SHADE static constexpr auto TYPE = SHCollider::Type::BOX; - auto boxPair = std::make_pair(SHCollider{ TYPE }, true); - auto& collider = colliders.emplace_back(boxPair).first; - - const auto* tf = SHComponentManager::GetComponent(GetEID()); + auto& collider = colliders.emplace_back(SHCollider{ GetEID(), TYPE }); + collider.entityID = GetEID(); collider.SetPositionOffset(posOffset); - collider.SetAsBoundingBox(tf->GetWorldScale() * halfExtents); + collider.SetBoundingBox(halfExtents); // Notify Physics System system->AddCollisionShape(GetEID(), &collider); @@ -109,16 +107,11 @@ namespace SHADE static constexpr auto TYPE = SHCollider::Type::SPHERE; - auto spherePair = std::make_pair(SHCollider{ TYPE }, true); - auto& collider = colliders.emplace_back(spherePair).first; - - const auto* tf = SHComponentManager::GetComponent(GetEID()); + auto& collider = colliders.emplace_back(SHCollider{ GetEID(), TYPE }); + collider.entityID = GetEID(); collider.SetPositionOffset(posOffset); - - const SHVec3 TF_WORLD_SCALE = tf->GetWorldScale(); - const float MAX_SCALE = SHMath::Max({ TF_WORLD_SCALE.x, TF_WORLD_SCALE.y, TF_WORLD_SCALE.z }); - collider.SetAsBoundingSphere(MAX_SCALE * 0.5f * radius); + collider.SetBoundingSphere(radius); // Notify Physics System system->AddCollisionShape(GetEID(), &collider); diff --git a/SHADE_Engine/src/Physics/Components/SHColliderComponent.h b/SHADE_Engine/src/Physics/Components/SHColliderComponent.h index 4ecd0e93..af726b51 100644 --- a/SHADE_Engine/src/Physics/Components/SHColliderComponent.h +++ b/SHADE_Engine/src/Physics/Components/SHColliderComponent.h @@ -43,8 +43,7 @@ namespace SHADE /* Type Definitions */ /*---------------------------------------------------------------------------------*/ - using ColliderDirtyPair = std::pair; - using Colliders = std::vector; + using Colliders = std::vector; public: diff --git a/SHADE_Engine/src/Physics/SHCollider.cpp b/SHADE_Engine/src/Physics/SHCollider.cpp index f5899cfc..6e929a17 100644 --- a/SHADE_Engine/src/Physics/SHCollider.cpp +++ b/SHADE_Engine/src/Physics/SHCollider.cpp @@ -15,6 +15,8 @@ // Project Headers #include "Math/Geometry/SHBoundingBox.h" #include "Math/Geometry/SHBoundingSphere.h" +#include "Math/Transform/SHTransformComponent.h" +#include "Math/SHMathHelpers.h" namespace SHADE { @@ -22,22 +24,24 @@ namespace SHADE /* Constructors & Destructor Definitions */ /*-----------------------------------------------------------------------------------*/ - SHCollider::SHCollider(Type colliderType) + SHCollider::SHCollider(EntityID eid, Type colliderType, const SHPhysicsMaterial& physicsMaterial) : type { colliderType } + , entityID { eid } , isTrigger { false } , dirty { true } , shape { nullptr } + , material { physicsMaterial } { switch (type) { case Type::BOX: { - SetAsBoundingBox(SHVec3::One); + shape = new SHBoundingBox{ SHVec3::Zero, SHVec3::One }; break; } case Type::SPHERE: { - SetAsBoundingSphere(1.0f); + shape = new SHBoundingSphere{ SHVec3::Zero, 0.5f }; break; } default: break; @@ -46,17 +50,21 @@ namespace SHADE SHCollider::SHCollider(const SHCollider& rhs) noexcept : type { rhs.type} + , entityID { rhs.entityID } , isTrigger { rhs.isTrigger } , dirty { true } , shape { rhs.shape } + , material { rhs.material } , positionOffset { rhs.positionOffset } {} SHCollider::SHCollider(SHCollider&& rhs) noexcept : type { rhs.type} + , entityID { rhs.entityID } , isTrigger { rhs.isTrigger } , dirty { true } , shape { rhs.shape } + , material { rhs.material } , positionOffset { rhs.positionOffset } {} @@ -75,9 +83,11 @@ namespace SHADE return *this; type = rhs.type; + entityID = rhs.entityID; isTrigger = rhs.isTrigger; dirty = true; shape = rhs.shape; + material = rhs.material; positionOffset = rhs.positionOffset; return *this; @@ -86,9 +96,11 @@ namespace SHADE SHCollider& SHCollider::operator=(SHCollider&& rhs) noexcept { type = rhs.type; + entityID = rhs.entityID; isTrigger = rhs.isTrigger; dirty = true; shape = rhs.shape; + material = rhs.material; positionOffset = rhs.positionOffset; return *this; @@ -115,19 +127,16 @@ namespace SHADE float SHCollider::GetFriction() const noexcept { - // TODO(Diren): Fix after implementing materials - return 0.0f; + return material.GetFriction(); } float SHCollider::GetBounciness() const noexcept { - // TODO(Diren): Fix after implementing materials - return 0.0f; + return material.GetBounciness(); } float SHCollider::GetDensity() const noexcept { - // TODO(Diren): Fix after implementing materials - return 0.0f; + return material.GetDensity(); } const SHVec3& SHCollider::GetPositionOffset() const noexcept @@ -145,22 +154,60 @@ namespace SHADE /* Setter Function Definitions */ /*-----------------------------------------------------------------------------------*/ - void SHCollider::SetAsBoundingBox(const SHVec3& halfExtents) + void SHCollider::SetBoundingBox(const SHVec3& halfExtents) { dirty = true; - type = Type::BOX; - delete shape; - shape = new SHBoundingBox{ positionOffset, halfExtents }; + // Set the half extents relative to transform + SHVec3 worldHalfExtents = halfExtents; + + const auto* transformComponent = SHComponentManager::GetComponent_s(entityID); + if (transformComponent != nullptr) + worldHalfExtents *= (transformComponent->GetWorldScale() * 0.5f); + + if (type == Type::BOX) + { + auto* box = reinterpret_cast(shape); + box->SetHalfExtents(worldHalfExtents); + } + else + { + type = Type::BOX; + + delete shape; + shape = new SHBoundingBox{ positionOffset, worldHalfExtents }; + } } - void SHCollider::SetAsBoundingSphere(float radius) + void SHCollider::SetBoundingSphere(float radius) { dirty = true; - type = Type::SPHERE; - delete shape; - shape = new SHBoundingSphere{ positionOffset, radius }; + // Set the radius relative to transform + float worldRadius = radius; + + const auto* transformComponent = SHComponentManager::GetComponent_s(entityID); + if (transformComponent != nullptr) + { + const SHVec3 TF_WORLD_SCALE = transformComponent->GetWorldScale(); + const float MAX_SCALE = SHMath::Max({ TF_WORLD_SCALE.x, TF_WORLD_SCALE.y, TF_WORLD_SCALE.z }); + + worldRadius *= MAX_SCALE; + } + + if (type == Type::SPHERE) + { + auto* sphere = reinterpret_cast(shape); + sphere->SetRadius(worldRadius); + } + else + { + type = Type::SPHERE; + + delete shape; + shape = new SHBoundingSphere{ positionOffset, worldRadius }; + } + } void SHCollider::SetIsTrigger(bool trigger) noexcept @@ -172,16 +219,19 @@ namespace SHADE void SHCollider::SetFriction(float friction) noexcept { dirty = true; + material.SetFriction(friction); } void SHCollider::SetBounciness(float bounciness) noexcept { dirty = true; + material.SetBounciness(bounciness); } void SHCollider::SetDensity(float density) noexcept { dirty = true; + material.SetDensity(density); } void SHCollider::SetPositionOffset(const SHVec3& posOffset) noexcept @@ -205,5 +255,4 @@ RTTR_REGISTRATION registration::class_("Collider") .property("Position Offset", &SHCollider::GetPositionOffset, &SHCollider::SetPositionOffset); - // TODO(Diren): Add Physics Materials } \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/SHCollider.h b/SHADE_Engine/src/Physics/SHCollider.h index 0e024f09..4fa483c9 100644 --- a/SHADE_Engine/src/Physics/SHCollider.h +++ b/SHADE_Engine/src/Physics/SHCollider.h @@ -13,8 +13,10 @@ #include // Project Headers +#include "ECS_Base/Entity/SHEntity.h" #include "Math/Geometry/SHShape.h" #include "Math/SHQuaternion.h" +#include "SHPhysicsMaterial.h" namespace SHADE { @@ -24,6 +26,15 @@ namespace SHADE class SH_API SHCollider { + private: + + /*---------------------------------------------------------------------------------*/ + /* Friends */ + /*---------------------------------------------------------------------------------*/ + + friend class SHColliderComponent; + friend class SHPhysicsObject; + public: /*---------------------------------------------------------------------------------*/ /* Type Definitions */ @@ -40,7 +51,7 @@ namespace SHADE /* Constructors & Destructor */ /*---------------------------------------------------------------------------------*/ - SHCollider (Type colliderType = Type::BOX); + SHCollider (EntityID eid, Type colliderType = Type::BOX, const SHPhysicsMaterial& physicsMaterial = SHPhysicsMaterial::DEFAULT); SHCollider (const SHCollider& rhs) noexcept; SHCollider (SHCollider&& rhs) noexcept; @@ -57,31 +68,33 @@ namespace SHADE /* Getter Functions */ /*---------------------------------------------------------------------------------*/ - [[nodiscard]] bool HasChanged () const noexcept; + [[nodiscard]] bool HasChanged () const noexcept; - [[nodiscard]] bool IsTrigger () const noexcept; + [[nodiscard]] bool IsTrigger () const noexcept; - [[nodiscard]] Type GetType () const noexcept; + [[nodiscard]] Type GetType () const noexcept; - [[nodiscard]] float GetFriction () const noexcept; - [[nodiscard]] float GetBounciness () const noexcept; - [[nodiscard]] float GetDensity () const noexcept; + [[nodiscard]] float GetFriction () const noexcept; + [[nodiscard]] float GetBounciness () const noexcept; + [[nodiscard]] float GetDensity () const noexcept; + [[nodiscard]] const SHPhysicsMaterial& GetMaterial () const noexcept; - [[nodiscard]] const SHVec3& GetPositionOffset () const noexcept; + [[nodiscard]] const SHVec3& GetPositionOffset () const noexcept; - [[nodiscard]] SHShape* GetShape () noexcept; + [[nodiscard]] SHShape* GetShape () noexcept; /*---------------------------------------------------------------------------------*/ /* Setter Functions */ /*---------------------------------------------------------------------------------*/ - void SetAsBoundingBox (const SHVec3& halfExtents); - void SetAsBoundingSphere (float radius); + void SetBoundingBox (const SHVec3& halfExtents); + void SetBoundingSphere (float radius); - void SetIsTrigger (bool isTrigger) noexcept; - void SetFriction (float friction) noexcept; - void SetBounciness (float bounciness) noexcept; - void SetDensity (float density) noexcept; + void SetIsTrigger (bool isTrigger) noexcept; + void SetFriction (float friction) noexcept; + void SetBounciness (float bounciness) noexcept; + void SetDensity (float density) noexcept; + void SetMaterial (const SHPhysicsMaterial& newMaterial) noexcept; void SetPositionOffset (const SHVec3& positionOffset) noexcept; @@ -90,11 +103,13 @@ namespace SHADE /* Data Members */ /*---------------------------------------------------------------------------------*/ - Type type; - bool isTrigger; - bool dirty; - SHShape* shape; - SHVec3 positionOffset; + Type type; + EntityID entityID; // The entity this collider belongs to + bool isTrigger; + bool dirty; + SHShape* shape; + SHPhysicsMaterial material; + SHVec3 positionOffset; RTTR_ENABLE() }; diff --git a/SHADE_Engine/src/Physics/SHPhysicsMaterial.cpp b/SHADE_Engine/src/Physics/SHPhysicsMaterial.cpp new file mode 100644 index 00000000..677e448f --- /dev/null +++ b/SHADE_Engine/src/Physics/SHPhysicsMaterial.cpp @@ -0,0 +1,104 @@ +/**************************************************************************************** + * \file SHPhysicsMaterial.cpp + * \author Diren D Bharwani, diren.dbharwani, 390002520 + * \brief Implementation for a Physics Material. + * + * \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 + +// Primary Header +#include "SHPhysicsMaterial.h" +// Project Headers +#include "Math/SHMathHelpers.h" + +namespace SHADE +{ + /*-----------------------------------------------------------------------------------*/ + /* Static Data Member Definitions */ + /*-----------------------------------------------------------------------------------*/ + + const SHPhysicsMaterial SHPhysicsMaterial::DEFAULT { 0.4f, 0.0f, 1.0f }; + + /*-----------------------------------------------------------------------------------*/ + /* Constructors & Destructor Definitions */ + /*-----------------------------------------------------------------------------------*/ + + SHPhysicsMaterial::SHPhysicsMaterial(float _friction, float _bounciness, float _density) noexcept + : friction { std::clamp(_friction, 0.0f, 1.0f) } + , bounciness{ std::clamp(_bounciness, 0.0f, 1.0f) } + , density { std::fabs(_density) } + {} + + /*-----------------------------------------------------------------------------------*/ + /* Operator Overload Definitions */ + /*-----------------------------------------------------------------------------------*/ + + bool SHPhysicsMaterial::operator==(const SHPhysicsMaterial& rhs) const noexcept + { + return SHMath::CompareFloat(friction, rhs.friction) + && SHMath::CompareFloat(bounciness, rhs.bounciness) + && SHMath::CompareFloat(density, rhs.density); + } + + bool SHPhysicsMaterial::operator!=(const SHPhysicsMaterial& rhs) const noexcept + { + return !SHMath::CompareFloat(friction, rhs.friction) + || !SHMath::CompareFloat(bounciness, rhs.bounciness) + || !SHMath::CompareFloat(density, rhs.density); + } + + /*-----------------------------------------------------------------------------------*/ + /* Getter Function Definitions */ + /*-----------------------------------------------------------------------------------*/ + + float SHPhysicsMaterial::GetFriction() const noexcept + { + return friction; + } + + float SHPhysicsMaterial::GetBounciness() const noexcept + { + return bounciness; + } + + float SHPhysicsMaterial::GetDensity() const noexcept + { + return density; + } + + /*-----------------------------------------------------------------------------------*/ + /* Setter Function Definitions */ + /*-----------------------------------------------------------------------------------*/ + + void SHPhysicsMaterial::SetFriction(float newFriction) noexcept + { + if (newFriction < 0.0f || newFriction > 1.0f) + { + SHLOG_WARNING("Clamping friction of Physics Material between [0,1].") + } + friction = std::clamp(newFriction, 0.0f, 1.0f); + } + + void SHPhysicsMaterial::SetBounciness(float newBounciness) noexcept + { + if (newBounciness < 0.0f || newBounciness > 1.0f) + { + SHLOG_WARNING("Clamping bounciness of Physics Material between [0,1].") + } + bounciness = std::clamp(newBounciness, 0.0f, 1.0f); + } + + void SHPhysicsMaterial::SetDensity(float newDensity) noexcept + { + if (newDensity < 0.0f) + { + SHLOG_WARNING("Setting negative density of Physics Material to positive.") + } + density = std::fabs(newDensity); + } + +} // namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/SHPhysicsMaterial.h b/SHADE_Engine/src/Physics/SHPhysicsMaterial.h new file mode 100644 index 00000000..b3db1655 --- /dev/null +++ b/SHADE_Engine/src/Physics/SHPhysicsMaterial.h @@ -0,0 +1,113 @@ +/**************************************************************************************** + * \file SHPhysicsMaterial.h + * \author Diren D Bharwani, diren.dbharwani, 390002520 + * \brief Interface for a Physics Material. + * + * \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 "SH_API.h" + +namespace SHADE +{ + /*-----------------------------------------------------------------------------------*/ + /* Type Definitions */ + /*-----------------------------------------------------------------------------------*/ + + class SH_API SHPhysicsMaterial + { + public: + /*---------------------------------------------------------------------------------*/ + /* Static Data Members */ + /*---------------------------------------------------------------------------------*/ + + static const SHPhysicsMaterial DEFAULT; + + /*---------------------------------------------------------------------------------*/ + /* Constructors & Destructor */ + /*---------------------------------------------------------------------------------*/ + + SHPhysicsMaterial (const SHPhysicsMaterial&) noexcept = default; + SHPhysicsMaterial (SHPhysicsMaterial&&) noexcept = default; + ~SHPhysicsMaterial() = default; + + /** + * @brief Default constructor for a physics material. + * @param friction The friction of the material. Clamped between [0,1]. Defaults to 0.4. + * @param bounciness The bounciness of the material. Clamped between [0,1]. + * @param density The mass density of the material. Always made positive. + */ + SHPhysicsMaterial (float friction = 0.4f, float bounciness = 0.0f, float density = 1.0f) noexcept; + + /*---------------------------------------------------------------------------------*/ + /* Operator Overloads */ + /*---------------------------------------------------------------------------------*/ + + SHPhysicsMaterial& operator= (const SHPhysicsMaterial&) noexcept = default; + SHPhysicsMaterial& operator= (SHPhysicsMaterial&&) noexcept = default; + + bool operator==(const SHPhysicsMaterial& rhs) const noexcept; + bool operator!=(const SHPhysicsMaterial& rhs) const noexcept; + + /*---------------------------------------------------------------------------------*/ + /* Getter Functions */ + /*---------------------------------------------------------------------------------*/ + + [[nodiscard]] float GetFriction () const noexcept; + [[nodiscard]] float GetBounciness () const noexcept; + [[nodiscard]] float GetDensity () const noexcept; + + /*---------------------------------------------------------------------------------*/ + /* Setter Functions */ + /*---------------------------------------------------------------------------------*/ + + /** + * @brief Sets the friction coefficient of the physics material. + * @param newFriction The friction value to set. Clamped between [0,1]. + */ + void SetFriction (float newFriction) noexcept; + + /** + * @brief Sets the bounciness factor of the physics material. + * @param newBounciness The bounciness value to set. Clamped between [0,1]. + */ + void SetBounciness (float newBounciness) noexcept; + + /** + * @brief Sets the mass density of the physics material. + * @param newDensity The density value to set. Always made positive. + */ + void SetDensity (float newDensity) noexcept; + + private: + + /*---------------------------------------------------------------------------------*/ + /* Data Members */ + /*---------------------------------------------------------------------------------*/ + + /** + * @brief The friction coefficient of the physics object., clamped between [0,1].
+ * 0 means the object will never experience friction. + * 1 means the friction force against the object is equal to the applied force. + */ + float friction; + + /** + * @brief The bounciness factor of the physics object., clamped between [0,1].
+ * 0 means the object will never bounce. + * 1 means the object never loses energy on a bounce. + */ + float bounciness; + + /** + * @brief The density of the collider that determines the mass of the collision shape + * if it is automatically computed. Must be a positive number. + */ + float density; + }; +} \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/SHPhysicsObject.cpp b/SHADE_Engine/src/Physics/SHPhysicsObject.cpp index 986ce503..4d4d8cd7 100644 --- a/SHADE_Engine/src/Physics/SHPhysicsObject.cpp +++ b/SHADE_Engine/src/Physics/SHPhysicsObject.cpp @@ -261,9 +261,9 @@ namespace SHADE void SHPhysicsObject::SyncColliders(SHColliderComponent* c) const noexcept { int index = 0; - for (auto& [collider, dirty] : c->colliders) + for (auto& collider : c->colliders) { - if (!dirty) + if (!collider.dirty) continue; // Update offsets @@ -293,7 +293,7 @@ namespace SHADE default: break; } - dirty = false; + collider.dirty = false; ++index; } } diff --git a/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp b/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp index 1c6e79d7..c3cd5ebc 100644 --- a/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp +++ b/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp @@ -517,7 +517,7 @@ namespace SHADE // Add collision shapes back into the body if (colliderComponent != nullptr) { - for (auto& collider : colliderComponent->colliders | std::views::keys) + for (auto& collider : colliderComponent->colliders) physicsObject->AddCollider(&collider); } } @@ -538,7 +538,7 @@ namespace SHADE } // Add Collision Shapes - for (auto& collider : colliderComponent->colliders | std::views::keys) + for (auto& collider : colliderComponent->colliders) physicsObject->AddCollider(&collider); } } @@ -576,7 +576,7 @@ namespace SHADE rp3d::Transform{ colliderComponent->position, colliderComponent->orientation } ); - for (auto& collider : colliderComponent->colliders | std::views::keys) + for (auto& collider : colliderComponent->colliders) physicsObject->AddCollider(&collider); } diff --git a/SHADE_Engine/src/Scene/SHSceneGraph.cpp b/SHADE_Engine/src/Scene/SHSceneGraph.cpp index 950fd6a0..df46b3fb 100644 --- a/SHADE_Engine/src/Scene/SHSceneGraph.cpp +++ b/SHADE_Engine/src/Scene/SHSceneGraph.cpp @@ -582,9 +582,9 @@ namespace SHADE ReleaseNode(node); } - void SHSceneGraph::Traverse (const UnaryFunction& predicate) const + void SHSceneGraph::Traverse (const UnaryFunction& function) const { - TraverseAndInvokePredicate(root, predicate); + TraverseAndInvokeFunction(root, function); } /*-----------------------------------------------------------------------------------*/ @@ -621,12 +621,12 @@ namespace SHADE delete node; } - void SHSceneGraph::TraverseAndInvokePredicate(const SHSceneNode* node, const UnaryFunction& predicate) + void SHSceneGraph::TraverseAndInvokeFunction(const SHSceneNode* node, const UnaryFunction& function) { for (auto* child : node->children) { - predicate(child); - TraverseAndInvokePredicate(child, predicate); + function(child); + TraverseAndInvokeFunction(child, function); } } diff --git a/SHADE_Engine/src/Scene/SHSceneGraph.h b/SHADE_Engine/src/Scene/SHSceneGraph.h index b52fd1ff..45ab48e5 100644 --- a/SHADE_Engine/src/Scene/SHSceneGraph.h +++ b/SHADE_Engine/src/Scene/SHSceneGraph.h @@ -142,7 +142,7 @@ namespace SHADE bool RemoveNode (SHSceneNode* nodeToRemove) noexcept; void Reset () noexcept; - void Traverse (const UnaryFunction& predicate) const; + void Traverse (const UnaryFunction& function) const; private: /*---------------------------------------------------------------------------------*/ From 75fd02c08a35e0d4f3145d671a9c7c00634ca86b Mon Sep 17 00:00:00 2001 From: Diren D Bharwani Date: Thu, 27 Oct 2022 03:35:32 +0800 Subject: [PATCH 02/12] small change to where forces are cleared (1 less comparison) --- SHADE_Engine/src/Physics/SHPhysicsSystem.cpp | 26 +++++++++----------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp b/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp index c3cd5ebc..44142aaf 100644 --- a/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp +++ b/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp @@ -246,21 +246,6 @@ namespace SHADE if (physicsObject.rp3dBody == nullptr) continue; - auto* rigidBodyComponent = SHComponentManager::GetComponent_s(entityID); - - // Clear all forces and velocities if editor is not in play - if (SHSystemManager::GetSystem()->editorState == SHEditor::State::STOP) - { - if (rigidBodyComponent) - { - auto* rp3dRigidBody = reinterpret_cast(physicsObject.rp3dBody); - rp3dRigidBody->resetForce(); - rp3dRigidBody->resetTorque(); - rp3dRigidBody->setLinearVelocity(SHVec3::Zero); - rp3dRigidBody->setAngularVelocity(SHVec3::Zero); - } - } - const auto* transformComponent = SHComponentManager::GetComponent_s(entityID); if (transformComponent && transformComponent->HasChanged()) { @@ -270,10 +255,21 @@ namespace SHADE physicsObject.SetPosition(WORLD_POS); physicsObject.SetOrientation(WORLD_ROT); + auto* rigidBodyComponent = SHComponentManager::GetComponent_s(entityID); if (rigidBodyComponent) { rigidBodyComponent->position = WORLD_POS; rigidBodyComponent->orientation = WORLD_ROT; + + // Clear all forces and velocities if editor is stopped + if (SHSystemManager::GetSystem()->editorState == SHEditor::State::STOP) + { + auto* rp3dRigidBody = reinterpret_cast(physicsObject.rp3dBody); + rp3dRigidBody->resetForce(); + rp3dRigidBody->resetTorque(); + rp3dRigidBody->setLinearVelocity(SHVec3::Zero); + rp3dRigidBody->setAngularVelocity(SHVec3::Zero); + } } auto* colliderComponent = SHComponentManager::GetComponent_s(entityID); From 621dae4c4047113e52ac46d81dab0c466bc828bb Mon Sep 17 00:00:00 2001 From: Kah Wei Date: Fri, 28 Oct 2022 13:32:13 +0800 Subject: [PATCH 03/12] All Vec3 and Vec4s in materials are now automatically set to full 1.0 vectors --- SHADE_Application/src/Scenes/SBTestScene.cpp | 3 +-- .../MiddleEnd/Interface/SHGraphicsSystem.cpp | 1 - .../MiddleEnd/Interface/SHGraphicsSystem.h | 1 + .../MiddleEnd/Interface/SHMaterial.cpp | 18 ++++++++++++++++++ .../Graphics/MiddleEnd/Interface/SHMaterial.h | 6 ++++++ .../MiddleEnd/Interface/SHMaterial.hpp | 10 ++++++++-- 6 files changed, 34 insertions(+), 5 deletions(-) diff --git a/SHADE_Application/src/Scenes/SBTestScene.cpp b/SHADE_Application/src/Scenes/SBTestScene.cpp index f80ec19e..8cbeb43a 100644 --- a/SHADE_Application/src/Scenes/SBTestScene.cpp +++ b/SHADE_Application/src/Scenes/SBTestScene.cpp @@ -124,8 +124,7 @@ namespace Sandbox auto& floorCollider = *SHComponentManager::GetComponent_s(floor); floorRenderable.SetMesh(CUBE_MESH); - floorRenderable.SetMaterial(customMat); - floorRenderable.GetModifiableMaterial()->SetProperty("data.color", SHVec4(1.0f, 1.0f, 1.0f, 1.0f)); + floorRenderable.SetMaterial(graphicsSystem->GetDefaultMaterialInstance()); floorTransform.SetWorldScale({ 7.5f, 0.5f, 7.5 }); floorTransform.SetWorldPosition({ 0.0f, -3.0f, -5.0f }); diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp index 2b8e97bc..3330a189 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp @@ -200,7 +200,6 @@ namespace SHADE auto cubeFS = shaderModuleLibrary.GetBuiltInShaderModule("TestCube_FS"); defaultMaterial = AddMaterial(cubeVS, cubeFS, gBufferSubpass); - } void SHGraphicsSystem::InitMiddleEnd(void) noexcept diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h index 4e91ca8d..f657965c 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h @@ -144,6 +144,7 @@ namespace SHADE Handle AddMaterialInstanceCopy(Handle materialInst); void RemoveMaterialInstance(Handle materialInstance); Handle GetDefaultMaterial() { return defaultMaterial; } + Handle GetDefaultMaterialInstance() { return AddOrGetBaseMaterialInstance(defaultMaterial); } /*-----------------------------------------------------------------------------*/ /* Mesh Registration Functions */ diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHMaterial.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHMaterial.cpp index b6e1974f..b27f48b9 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHMaterial.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHMaterial.cpp @@ -4,6 +4,8 @@ #include "Graphics/Pipeline/SHVkPipeline.h" #include "SHGraphicsConstants.h" #include "Graphics/Shaders/BlockInterface/SHShaderBlockInterface.h" +#include "Math/Vector/SHVec3.h" +#include "Math/Vector/SHVec4.h" namespace SHADE { @@ -49,6 +51,22 @@ namespace SHADE // Reset all the properties to default values if (propMemory) memset(propMemory.get(), 0, propMemorySize); + + // Initialize Vectors to all 1.0 by default + const Handle SHADER_INFO = GetShaderBlockInterface(); + for (int i = 0; i < SHADER_INFO->GetVariableCount(); ++i) + { + const auto& VAR = SHADER_INFO->GetVariable(i); + switch (VAR->type) + { + case SHShaderBlockInterface::Variable::Type::VECTOR3: + setPropertyUnsafe(VAR->offset, SHVec3::One); + break; + case SHShaderBlockInterface::Variable::Type::VECTOR4: + setPropertyUnsafe(VAR->offset, SHVec4::One); + break; + } + } } void SHMaterial::ExportProperties(void* dest) const noexcept diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHMaterial.h b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHMaterial.h index ad7da4a6..964f9e34 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHMaterial.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHMaterial.h @@ -75,6 +75,12 @@ namespace SHADE Handle pipeline; std::unique_ptr propMemory; Byte propMemorySize = 0; + + /*-----------------------------------------------------------------------------*/ + /* Helper Functions */ + /*-----------------------------------------------------------------------------*/ + template + inline void setPropertyUnsafe(uint32_t memOffset, const T& value); // SetProperty() but without checks }; } diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHMaterial.hpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHMaterial.hpp index 3e56bfd5..8c205570 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHMaterial.hpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHMaterial.hpp @@ -33,7 +33,7 @@ namespace SHADE } // Get offset and modify the memory directly - T* dataPtr = propMemory.get() + PROP_INFO->offset; + T* dataPtr = reinterpret_cast(propMemory.get() + PROP_INFO->offset); *dataPtr = value; } @@ -44,7 +44,7 @@ namespace SHADE if (memOffset + sizeof(T) > propMemorySize) throw std::invalid_argument("Attempted to set an invalid property!"); // Set - (*reinterpret_cast(propMemory.get() + memOffset)) = value; + setPropertyUnsafe(memOffset, value); } template @@ -81,4 +81,10 @@ namespace SHADE { return const_cast(const_cast(this)->GetProperty(memOffset)); } + + template + void SHMaterial::setPropertyUnsafe(uint32_t memOffset, const T& value) + { + (*reinterpret_cast(propMemory.get() + memOffset)) = value; + } } From 7d6af884a46beded910ca49aa8d01fe25376e489 Mon Sep 17 00:00:00 2001 From: Kah Wei Date: Fri, 28 Oct 2022 13:53:05 +0800 Subject: [PATCH 04/12] Added Color struct --- SHADE_Managed/src/Graphics/Color.cxx | 154 ++++++++++++++ SHADE_Managed/src/Graphics/Color.hxx | 287 +++++++++++++++++++++++++++ SHADE_Managed/src/Math/Math.cxx | 11 + SHADE_Managed/src/Math/Math.hxx | 20 +- 4 files changed, 471 insertions(+), 1 deletion(-) create mode 100644 SHADE_Managed/src/Graphics/Color.cxx create mode 100644 SHADE_Managed/src/Graphics/Color.hxx diff --git a/SHADE_Managed/src/Graphics/Color.cxx b/SHADE_Managed/src/Graphics/Color.cxx new file mode 100644 index 00000000..cf1fff47 --- /dev/null +++ b/SHADE_Managed/src/Graphics/Color.cxx @@ -0,0 +1,154 @@ +/************************************************************************************//*! +\file Color.cxx +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Nov 3, 2021 +\brief Contains the definition of the functions of the managed Color struct. + + Note: This file is written in C++17/CLI. + +Copyright (C) 2021 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. +*//*************************************************************************************/ +// Precompiled Headers +#include "SHpch.h" +// Primary Header +#include "Graphics/Color.hxx" +// Standard Libraries +#include +// Project Includes +#include "Math/Math.hxx" + +namespace SHADE +{ + /*---------------------------------------------------------------------------------*/ + /* Constructors */ + /*---------------------------------------------------------------------------------*/ + Color::Color(float _red) + : Color { _red, 0.0f, 0.0f, 1.0f } + {} + Color::Color(float _red, float _green) + : Color { _red, _green, 0.0f, 1.0f } + {} + Color::Color(float _red, float _green, float _blue) + : Color { _red, _green, _blue, 1.0f } + {} + Color::Color(float _red, float _green, float _blue, float _alpha) + : r { _red } + , g { _green } + , b { _blue } + , a { _alpha } + {} + + /*---------------------------------------------------------------------------------*/ + /* IEquatable */ + /*---------------------------------------------------------------------------------*/ + bool Color::Equals(Object^ o) + { + try + { + Color col = safe_cast(o); + return Equals(col); + } + catch (System::InvalidCastException^) + { + return false; + } + } + + /*---------------------------------------------------------------------------------*/ + /* Object Overrides */ + /*---------------------------------------------------------------------------------*/ + bool Color::Equals(Color other) + { + return Math::CompareFloat(this->r, other.r) + && + Math::CompareFloat(this->g, other.g) + && + Math::CompareFloat(this->b, other.b) + && + Math::CompareFloat(this->a, other.a); + } + int Color::GetHashCode() + { + const int HASH = 19; + const int HASH2 = 23; + const int HASH3 = 29; + return r.GetHashCode() * HASH + + g.GetHashCode() * HASH2 + + b.GetHashCode() * HASH3 + + a.GetHashCode(); + } + + /*---------------------------------------------------------------------------------*/ + /* Static Functions */ + /*---------------------------------------------------------------------------------*/ + Color Color::Lerp(Color colA, Color colB, float t) + { + return LerpUnclamped(colA, colB, std::clamp(t, 0.0f, 1.0f)); + } + + Color Color::LerpUnclamped(Color colA, Color colB, float t) + { + return colA + ((colB - colA) * t); + } + Color Color::operator+(Color lhs, Color rhs) + { + return Color + ( + lhs.r + rhs.r, + lhs.g + rhs.g, + lhs.b + rhs.b, + lhs.a + rhs.a + ); + } + Color Color::operator-(Color lhs, Color rhs) + { + return Color + ( + lhs.r - rhs.r, + lhs.g - rhs.g, + lhs.b - rhs.b, + lhs.a - rhs.a + ); + } + Color Color::operator*(Color lhs, Color rhs) + { + return Color + ( + lhs.r * rhs.r, + lhs.g * rhs.g, + lhs.b * rhs.b, + lhs.a * rhs.a + ); + } + Color Color::operator*(Color lhs, float rhs) + { + return Color + ( + lhs.r * rhs, + lhs.g * rhs, + lhs.b * rhs, + lhs.a * rhs + ); + } + Color Color::operator/(Color lhs, float rhs) + { + return Color + ( + lhs.r / rhs, + lhs.g / rhs, + lhs.b / rhs, + lhs.a / rhs + ); + } + bool Color::operator==(Color lhs, Color rhs) + { + return lhs.Equals(rhs); + } + bool Color::operator!=(Color lhs, Color rhs) + { + return !(lhs == rhs); + } +} diff --git a/SHADE_Managed/src/Graphics/Color.hxx b/SHADE_Managed/src/Graphics/Color.hxx new file mode 100644 index 00000000..d6a46216 --- /dev/null +++ b/SHADE_Managed/src/Graphics/Color.hxx @@ -0,0 +1,287 @@ +/************************************************************************************//*! +\file Color.hxx +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Oct 28, 2022 +\brief Contains the definition of the managed Color struct with the + declaration of functions for working with it. + + Note: This file is written in C++17/CLI. + +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 + +namespace SHADE +{ + /// + /// CLR version of the the SHADE Engine's Color struct which describes a Color + /// encoded using floating point numbers that range from 0.0f to 1.0f. + /// + [System::Runtime::InteropServices::StructLayout(System::Runtime::InteropServices::LayoutKind::Sequential)] + public value struct Color : public System::IEquatable + { + public: + /*-----------------------------------------------------------------------------*/ + /* Type Definitions */ + /*-----------------------------------------------------------------------------*/ + /// + /// A static class that contains a set of default Colors. + /// + ref class Defaults abstract sealed + { + public: + /*-------------------------------------------------------------------------*/ + /* Properties */ + /*-------------------------------------------------------------------------*/ + /// + /// Pure black. + /// + static property Color Black + { + Color get() { return Color(0.0f, 0.0f, 0.0f); } + } + /// + /// Light Gray, lighter than gray. + /// + static property Color LightGray + { + Color get() { return Color(0.827451f, 0.827451f, 0.827451f); } + } + /// + /// Gray, halfway between black and white. + /// + static property Color Gray + { + Color get() { return Color(0.5f, 0.5f, 0.5f); } + } + /// + /// Dark Gray, darker than gray. + /// + static property Color DarkGray + { + Color get() { return Color(0.622f, 0.622f, 0.622f); } + } + /// + /// Pure white. + /// + static property Color White + { + Color get() { return Color(1.0f, 1.0f, 1.0f); } + } + /// + /// Pure red. + /// + static property Color Red + { + Color get() { return Color(1.0f, 0.0f, 0.0f); } + } + /// + /// Pure green. + /// + static property Color Green + { + Color get() { return Color(0.0f, 1.0f, 0.0f); } + } + /// + /// Pure blue. + /// + static property Color Blue + { + Color get() { return Color(0.0f, 0.0f, 1.0f); } + } + /// + /// Pure cyan, mix of pure green and blue. + /// + static property Color Cyan + { + Color get() { return Color(0.0f, 1.0f, 1.0f); } + } + /// + /// Pure magenta, mix of pure red and blue. + /// + static property Color Magenta + { + Color get() { return Color(1.0f, 0.0f, 1.0f); } + } + /// + /// Pure yellow, mix of pure red and green. + /// + static property Color Yellow + { + Color get() { return Color(1.0f, 1.0f, 0.0f); } + } + }; + + /*-----------------------------------------------------------------------------*/ + /* Constructors */ + /*-----------------------------------------------------------------------------*/ + /// + /// Constructor to construct a Color with the specified components with the + /// green, blue and alpha component set to 1.0f. + /// + /// Red component to set. + Color(float _red); + /// + /// Constructor to construct a Color with the specified components with the + /// blue and alpha component set to 1.0f. + /// + /// Red component to set. + /// Green component to set. + Color(float _red, float _green); + /// + /// Constructor to construct a Color with the specified components with the + /// alpha component set to 1.0f. + /// + /// Red component to set. + /// Green component to set. + /// Blue component to set. + Color(float _red, float _green, float _blue); + /// + /// Constructor to construct a Color with the specified components. + /// + /// Red component to set. + /// Green component to set. + /// Blue component to set. + /// Alpha component to set. + Color(float _red, float _green, float _blue, float _alpha); + + /*-----------------------------------------------------------------------------*/ + /* Public Members */ + /*-----------------------------------------------------------------------------*/ + /// + /// Red component of the colour. Ranges from 0.0f to 1.0f. + /// + float r; + /// + /// Green component of the colour. Ranges from 0.0f to 1.0f. + /// + float g; + /// + /// Blue component of the colour. Ranges from 0.0f to 1.0f. + /// + float b; + /// + /// Alpha component of the colour. Ranges from 0.0f to 1.0f. + /// + float a; + + /*-----------------------------------------------------------------------------*/ + /* IEquatable */ + /*-----------------------------------------------------------------------------*/ + /// + /// Compares equality with an object of the same type. + /// + /// The object to compare with. + /// True if both objects are the same. + virtual bool Equals(Color other); + + /*-----------------------------------------------------------------------------*/ + /* Object */ + /*-----------------------------------------------------------------------------*/ + /// + /// Compares equality with another unboxed object. + /// + /// The unboxed object to compare with. + /// True if both objects are the same. + bool Equals(Object^ o) override; + /// + /// Gets a unique hash for this object. + /// + /// Unique hash for this object. + int GetHashCode() override; + + + /*-----------------------------------------------------------------------------*/ + /* Static Functions */ + /*-----------------------------------------------------------------------------*/ + /// + /// Linearly interpolates between two specified points. + /// This is most commonly used to find a point some fraction of the way along a + /// line between two endpoints. + /// + /// The start Color, returned when t = 0.0. + /// The end Color, returned when t = 1.0. + /// + /// Value used to interpolate between a and b which is clamped to + /// the range[0, 1]. + /// + /// The interpolated Vector3. + static Color Lerp(Color colA, Color colB, float t); + /// + /// Linearly interpolates between two specified points. + /// This is most commonly used to find a point some fraction of the way along a + /// line between two endpoints. + /// Unlike Lerp(), t is not clamped to a range at all. + /// + /// The start Color, returned when t = 0.0. + /// The end Color, returned when t = 1.0. + /// Value used to interpolate between a and b. + /// The interpolated Color. + static Color LerpUnclamped(Color colA, Color colB, float t); + + /*-----------------------------------------------------------------------------*/ + /* Overloaded Operators */ + /*-----------------------------------------------------------------------------*/ + /// + /// Adds two Colors together and returns the result. + /// + /// Color to add. + /// Another Color to add. + /// The result of lhs added to rhs + static Color operator+(Color lhs, Color rhs); + /// + /// Subtracts a Color from another Color and returns the result. + /// + /// Color to subtract from. + /// Another Color to subtract. + /// The result of rhs subtracted from lhs. + static Color operator-(Color lhs, Color rhs); + /// + /// Calculates the component-wise multiplication of two Colors and returns the + /// result. + /// + /// Color to multiply with. + /// Another Color to multiply with. + /// The result of rhs subtracted from lhs. + static Color operator*(Color lhs, Color rhs); + /// + /// Calculates the multiplication of a Color with a scalar value and returns + /// the result. + /// + /// Color to multiply with. + /// Scalar to multiply with. + /// The result of the scalar multiplication. + static Color operator*(Color lhs, float rhs); + /// + /// Calculates the division of a Color with a scalar value and returns + /// the result. + /// + /// Scalar to divide with. + /// Color to divide with. + /// The result of the scalar division. + static Color operator/(Color lhs, float rhs); + /// + /// Checks if two Colors are approximately equal. + /// + /// Color to compare. + /// Another Color to compare. + /// + /// True if all components are approximately equal within the default + /// tolerance value. + /// + static bool operator==(Color lhs, Color rhs); + /// + /// Checks if two Colors are not approximately equal. + /// + /// Color to compare. + /// Another Color to compare. + /// + /// True if all components are not approximately equal within the default + /// tolerance value. + /// + static bool operator!=(Color lhs, Color rhs); + }; +} diff --git a/SHADE_Managed/src/Math/Math.cxx b/SHADE_Managed/src/Math/Math.cxx index fa72e2b6..bc625f5b 100644 --- a/SHADE_Managed/src/Math/Math.cxx +++ b/SHADE_Managed/src/Math/Math.cxx @@ -54,4 +54,15 @@ namespace SHADE { return (value - a) / (b - a); } + + bool Math::CompareFloat(float a, float b) + { + return CompareFloat(a, b, Epsilon); + } + + bool Math::CompareFloat(float a, float b, float tolerance) + { + return System::MathF::Abs(a - b) < tolerance; + } + } diff --git a/SHADE_Managed/src/Math/Math.hxx b/SHADE_Managed/src/Math/Math.hxx index 1578d97c..c6b8394e 100644 --- a/SHADE_Managed/src/Math/Math.hxx +++ b/SHADE_Managed/src/Math/Math.hxx @@ -81,12 +81,30 @@ namespace SHADE /// The interpolated float result between the two float values. static float LerpUnclamped(float a, float b, float t); /// - /// Calculates the linear parameter t that produces the interpolant value within the range [a, b]. + /// Calculates the linear parameter t that produces the interpolant value within + /// the range [a, b]. /// /// Start value. /// End value. /// Value between start and end. /// Percentage of value between start and end. static float InverseLerp(float a, float b, float value); + /// + /// Compares if two float values are close enough to be the same with a tolerance + /// of Epsilon. + /// + /// One of the values to compare. + /// The other value to compare. + /// True if a and b are practically the same. + static bool CompareFloat(float a, float b); + /// + /// Compares if two float values are close enough to be the same with the + /// specified tolerance value. + /// + /// One of the values to compare. + /// The other value to compare. + /// Tolerance for floating point comparison. + /// True if a and b are practically the same. + static bool CompareFloat(float a, float b, float tolerance); }; } From 4fc87866eec93168d9b1980d1935f3a55f660a2b Mon Sep 17 00:00:00 2001 From: Diren D Bharwani Date: Fri, 28 Oct 2022 14:23:11 +0800 Subject: [PATCH 05/12] Fixed compilation error --- SHADE_Managed/src/Components/Collider.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SHADE_Managed/src/Components/Collider.cxx b/SHADE_Managed/src/Components/Collider.cxx index 6d2c2f01..6768ad1c 100644 --- a/SHADE_Managed/src/Components/Collider.cxx +++ b/SHADE_Managed/src/Components/Collider.cxx @@ -233,7 +233,7 @@ namespace SHADE for (const auto& collider : GetNativeComponent()->GetColliders()) { ColliderBound^ bound = nullptr; - switch (collider.first.GetType()) + switch (collider.GetType()) { case SHCollider::Type::BOX: bound = gcnew BoxColliderBound(i, Owner.GetEntity()); From 1a4b15feb274307bf4a48b96b0eeda78ef96c5e8 Mon Sep 17 00:00:00 2001 From: Diren D Bharwani Date: Fri, 28 Oct 2022 14:29:05 +0800 Subject: [PATCH 06/12] Changed ColliderBound to CollisionShape because ColliderBound sounds weird --- SHADE_Engine/src/Scripting/SHScriptEngine.cpp | 4 +- SHADE_Managed/src/Components/Collider.cxx | 66 +++++++++---------- SHADE_Managed/src/Components/Collider.h++ | 6 +- SHADE_Managed/src/Components/Collider.hxx | 42 ++++++------ 4 files changed, 59 insertions(+), 59 deletions(-) diff --git a/SHADE_Engine/src/Scripting/SHScriptEngine.cpp b/SHADE_Engine/src/Scripting/SHScriptEngine.cpp index f0f8912b..21ce7b82 100644 --- a/SHADE_Engine/src/Scripting/SHScriptEngine.cpp +++ b/SHADE_Engine/src/Scripting/SHScriptEngine.cpp @@ -417,13 +417,13 @@ namespace SHADE ( DEFAULT_CSHARP_LIB_NAME, DEFAULT_CSHARP_NAMESPACE + ".Collider", - "OnColliderBoundChanged" + "OnCollisionShapeChanged" ); csColliderOnRemoved = dotNet.GetFunctionPtr ( DEFAULT_CSHARP_LIB_NAME, DEFAULT_CSHARP_NAMESPACE + ".Collider", - "OnColliderRemoved" + "OnCollisionShapeRemoved" ); csEditorRenderScripts = dotNet.GetFunctionPtr ( diff --git a/SHADE_Managed/src/Components/Collider.cxx b/SHADE_Managed/src/Components/Collider.cxx index 6768ad1c..f2119b43 100644 --- a/SHADE_Managed/src/Components/Collider.cxx +++ b/SHADE_Managed/src/Components/Collider.cxx @@ -22,7 +22,7 @@ namespace SHADE /*---------------------------------------------------------------------------------*/ /* ColliderBound - Constructors */ /*---------------------------------------------------------------------------------*/ - ColliderBound::ColliderBound(int arrayIdx, Entity attachedEntity) + CollisionShape::CollisionShape(int arrayIdx, Entity attachedEntity) : arrayIndex { arrayIdx } , entity { attachedEntity } {} @@ -30,7 +30,7 @@ namespace SHADE /*---------------------------------------------------------------------------------*/ /* ColliderBound - Setter Functions */ /*---------------------------------------------------------------------------------*/ - void ColliderBound::updateArrayIndex(int index) + void CollisionShape::updateArrayIndex(int index) { arrayIndex = index; } @@ -38,42 +38,42 @@ namespace SHADE /*---------------------------------------------------------------------------------*/ /* BoxColliderBound - Constructors */ /*---------------------------------------------------------------------------------*/ - BoxColliderBound::BoxColliderBound(int arrayIdx, Entity attachedEntity) - : ColliderBound { arrayIndex, attachedEntity } + BoxCollider::BoxCollider(int arrayIdx, Entity attachedEntity) + : CollisionShape { arrayIndex, attachedEntity } {} /*---------------------------------------------------------------------------------*/ /* BoxColliderBound - Properties */ /*---------------------------------------------------------------------------------*/ - Vector3 BoxColliderBound::Center::get() + Vector3 BoxCollider::Center::get() { return Convert::ToCLI(getNativeBoundObject().GetCenter()); } - void BoxColliderBound::Center::set(Vector3 value) + void BoxCollider::Center::set(Vector3 value) { getNativeBoundObject().SetCenter(Convert::ToNative(value)); } - Vector3 BoxColliderBound::HalfExtents::get() + Vector3 BoxCollider::HalfExtents::get() { return Convert::ToCLI(getNativeBoundObject().GetHalfExtents()); } - void BoxColliderBound::HalfExtents::set(Vector3 value) + void BoxCollider::HalfExtents::set(Vector3 value) { getNativeBoundObject().SetHalfExtents(Convert::ToNative(value)); } - Vector3 BoxColliderBound::Min::get() + Vector3 BoxCollider::Min::get() { return Convert::ToCLI(getNativeBoundObject().GetMin()); } - void BoxColliderBound::Min::set(Vector3 value) + void BoxCollider::Min::set(Vector3 value) { getNativeBoundObject().SetMin(Convert::ToNative(value)); } - Vector3 BoxColliderBound::Max::get() + Vector3 BoxCollider::Max::get() { return Convert::ToCLI(getNativeBoundObject().GetMax()); } - void BoxColliderBound::Max::set(Vector3 value) + void BoxCollider::Max::set(Vector3 value) { getNativeBoundObject().SetMax(Convert::ToNative(value)); } @@ -81,11 +81,11 @@ namespace SHADE /*---------------------------------------------------------------------------------*/ /* BoxColliderBound - Usage Functions */ /*---------------------------------------------------------------------------------*/ - bool BoxColliderBound::TestPoint(Vector3 point) + bool BoxCollider::TestPoint(Vector3 point) { return getNativeBoundObject().TestPoint(Convert::ToNative(point)); } - bool BoxColliderBound::Raycast(Ray ray, float maxDistance) + bool BoxCollider::Raycast(Ray ray, float maxDistance) { return getNativeBoundObject().Raycast(Convert::ToNative(ray), maxDistance); } @@ -93,19 +93,19 @@ namespace SHADE /*---------------------------------------------------------------------------------*/ /* BoxColliderBound - Properties */ /*---------------------------------------------------------------------------------*/ - Vector3 SphereColliderBound::Center::get() + Vector3 SphereCollider::Center::get() { return Convert::ToCLI(getNativeBoundObject().GetCenter()); } - void SphereColliderBound::Center::set(Vector3 value) + void SphereCollider::Center::set(Vector3 value) { getNativeBoundObject().SetCenter(Convert::ToNative(value)); } - float SphereColliderBound::Radius::get() + float SphereCollider::Radius::get() { return getNativeBoundObject().GetRadius(); } - void SphereColliderBound::Radius::set(float value) + void SphereCollider::Radius::set(float value) { getNativeBoundObject().SetRadius(value); } @@ -113,11 +113,11 @@ namespace SHADE /*---------------------------------------------------------------------------------*/ /* SphereColliderBound - Usage Functions */ /*---------------------------------------------------------------------------------*/ - bool SphereColliderBound::TestPoint(Vector3 point) + bool SphereCollider::TestPoint(Vector3 point) { return getNativeBoundObject().TestPoint(Convert::ToNative(point)); } - bool SphereColliderBound::Raycast(Ray ray, float maxDistance) + bool SphereCollider::Raycast(Ray ray, float maxDistance) { return getNativeBoundObject().Raycast(Convert::ToNative(ray), maxDistance); } @@ -125,8 +125,8 @@ namespace SHADE /*---------------------------------------------------------------------------------*/ /* SphereColliderBound - Constructors */ /*---------------------------------------------------------------------------------*/ - SphereColliderBound::SphereColliderBound(int arrayIndex, Entity attachedEntity) - : ColliderBound{ arrayIndex, attachedEntity } + SphereCollider::SphereCollider(int arrayIndex, Entity attachedEntity) + : CollisionShape{ arrayIndex, attachedEntity } {} /*---------------------------------------------------------------------------------*/ @@ -137,7 +137,7 @@ namespace SHADE { // Create lists if they don't exist if (colliders == nullptr) - colliders = gcnew CollidersMap; + colliders = gcnew ColliderMap; if (!colliders->ContainsKey(entity)) colliders->Add(entity, gcnew WeakReferenceList()); @@ -148,7 +148,7 @@ namespace SHADE /*---------------------------------------------------------------------------------*/ /* Collider - Properties */ /*---------------------------------------------------------------------------------*/ - int Collider::ColliderBoundsCount::get() + int Collider::CollisionShapeCount::get() { return static_cast(GetNativeComponent()->GetColliders().size()); } @@ -156,7 +156,7 @@ namespace SHADE /*---------------------------------------------------------------------------------*/ /* Collider - ColliderBound Functions */ /*---------------------------------------------------------------------------------*/ - ColliderBound^ Collider::GetColliderBound(int index) + CollisionShape^ Collider::GetCollisionShape(int index) { // Populate the list if it hasn't been if (subColliderList == nullptr) @@ -172,15 +172,15 @@ namespace SHADE return subColliderList[index]; } generic - T Collider::GetColliderBound(int index) + T Collider::GetCollisionShape(int index) { - return safe_cast(GetColliderBound(index)); + return safe_cast(GetCollisionShape(index)); } /*---------------------------------------------------------------------------------*/ /* Event Handling Functions */ /*---------------------------------------------------------------------------------*/ - void Collider::OnColliderRemoved(EntityID entity) + void Collider::OnCollisionShapeRemoved(EntityID entity) { SAFE_NATIVE_CALL_BEGIN // Check if there are any colliders to update @@ -192,7 +192,7 @@ namespace SHADE SAFE_NATIVE_CALL_END("Collider.OnColliderRemoved") } - void Collider::OnColliderBoundChanged(EntityID entity) + void Collider::OnCollisionShapeChanged(EntityID entity) { SAFE_NATIVE_CALL_BEGIN // Check if there are any colliders to update @@ -226,20 +226,20 @@ namespace SHADE if (subColliderList) subColliderList->Clear(); else - subColliderList = gcnew System::Collections::Generic::List(); + subColliderList = gcnew System::Collections::Generic::List(); // Populate the list int i = 0; for (const auto& collider : GetNativeComponent()->GetColliders()) { - ColliderBound^ bound = nullptr; + CollisionShape^ bound = nullptr; switch (collider.GetType()) { case SHCollider::Type::BOX: - bound = gcnew BoxColliderBound(i, Owner.GetEntity()); + bound = gcnew BoxCollider(i, Owner.GetEntity()); break; case SHCollider::Type::SPHERE: - bound = gcnew SphereColliderBound(i, Owner.GetEntity()); + bound = gcnew SphereCollider(i, Owner.GetEntity()); break; case SHCollider::Type::CAPSULE: // TODO diff --git a/SHADE_Managed/src/Components/Collider.h++ b/SHADE_Managed/src/Components/Collider.h++ index 66f77e18..1f8b43eb 100644 --- a/SHADE_Managed/src/Components/Collider.h++ +++ b/SHADE_Managed/src/Components/Collider.h++ @@ -18,8 +18,8 @@ of DigiPen Institute of Technology is prohibited. #include "Component.hxx" namespace SHADE { - template - ColliderBoundType& SHADE::ColliderBound::getNativeBoundObject() + template + CollisionShapeType& SHADE::CollisionShape::getNativeBoundObject() { SHColliderComponent* collider = SHComponentManager::GetComponent_s(entity); if (!collider) @@ -31,7 +31,7 @@ namespace SHADE if (bounds.GetType() != SHCollider::Type::BOX) throw gcnew System::InvalidOperationException("Attempted to retrieve invalid ColliderBound."); - return reinterpret_cast(bounds); + return reinterpret_cast(bounds); } catch (std::invalid_argument&) { diff --git a/SHADE_Managed/src/Components/Collider.hxx b/SHADE_Managed/src/Components/Collider.hxx index f827ab71..9555976f 100644 --- a/SHADE_Managed/src/Components/Collider.hxx +++ b/SHADE_Managed/src/Components/Collider.hxx @@ -27,7 +27,7 @@ namespace SHADE /// /// Base interface for all Collider Shapes. /// - public ref class ColliderBound + public ref class CollisionShape { public: /*-----------------------------------------------------------------------------*/ @@ -51,7 +51,7 @@ namespace SHADE /*-----------------------------------------------------------------------------*/ /* Constructors */ /*-----------------------------------------------------------------------------*/ - ColliderBound(int arrayIdx, Entity attachedEntity); + CollisionShape(int arrayIdx, Entity attachedEntity); /*-----------------------------------------------------------------------------*/ /* Data Members */ @@ -62,8 +62,8 @@ namespace SHADE /*-----------------------------------------------------------------------------*/ /* Helper Functions */ /*-----------------------------------------------------------------------------*/ - template - ColliderBoundType& getNativeBoundObject(); + template + CollisionShapeType& getNativeBoundObject(); internal: /*-----------------------------------------------------------------------------*/ @@ -75,7 +75,7 @@ namespace SHADE /// /// Box-shaped Collider Bound. /// - public ref class BoxColliderBound : public ColliderBound + public ref class BoxCollider : public CollisionShape { public: /*-----------------------------------------------------------------------------*/ @@ -128,13 +128,13 @@ namespace SHADE /*-----------------------------------------------------------------------------*/ /* Constructors */ /*-----------------------------------------------------------------------------*/ - BoxColliderBound(int arrayIndex, Entity attachedEntity); + BoxCollider(int arrayIndex, Entity attachedEntity); }; /// /// Sphere-shaped Collider Bound. /// - public ref class SphereColliderBound : public ColliderBound + public ref class SphereCollider : public CollisionShape { public: /*-----------------------------------------------------------------------------*/ @@ -169,7 +169,7 @@ namespace SHADE /*-----------------------------------------------------------------------------*/ /* Constructors */ /*-----------------------------------------------------------------------------*/ - SphereColliderBound(int arrayIndex, Entity attachedEntity); + SphereCollider(int arrayIndex, Entity attachedEntity); }; /// @@ -196,7 +196,7 @@ namespace SHADE /// /// Total number of ColliderBounds in the Collider component. /// - property int ColliderBoundsCount + property int CollisionShapeCount { int get(); } @@ -209,7 +209,7 @@ namespace SHADE /// /// Index to retrieve a ColliderBound from. /// ColliderBound for the specified index. - ColliderBound^ GetColliderBound(int index); + CollisionShape^ GetCollisionShape(int index); /// /// Retrieves a ColliderBound at the specified index in the ColliderBound list /// and casts it to the appropriate type. @@ -217,42 +217,42 @@ namespace SHADE /// Type of the ColliderBound to cast to. /// Index to retrieve a ColliderBound from. /// ColliderBound for the specified index. - generic where T:ColliderBound - T GetColliderBound(int index); + generic where T:CollisionShape + T GetCollisionShape(int index); internal: /*-----------------------------------------------------------------------------*/ /* Event Handling Functions */ /*-----------------------------------------------------------------------------*/ /// - /// To be called from native code when a collider has been removed. + /// To be called from native code when a collision shape has been removed. /// - /// The entity which has it's collider removed. - static void OnColliderRemoved(EntityID entity); + /// The entity which has it's collision shape removed. + static void OnCollisionShapeRemoved(EntityID entity); /// - /// To be called from native code when a Collider bound has been removed. + /// To be called from native code when a Collision Shape has been changed. /// /// - /// The entity which has it's collider bounds changed. + /// The entity which has it's collision shape changed. /// - static void OnColliderBoundChanged(EntityID entity); + static void OnCollisionShapeChanged(EntityID entity); private: /*-----------------------------------------------------------------------------*/ /* Type Definitions */ /*-----------------------------------------------------------------------------*/ using WeakReferenceList = System::Collections::Generic::List; - using CollidersMap = System::Collections::Generic::Dictionary; + using ColliderMap = System::Collections::Generic::Dictionary; /*-----------------------------------------------------------------------------*/ /* Static Data Members */ /*-----------------------------------------------------------------------------*/ - static CollidersMap^ colliders; + static ColliderMap^ colliders; /*-----------------------------------------------------------------------------*/ /* Data Members */ /*-----------------------------------------------------------------------------*/ - System::Collections::Generic::List^ subColliderList; + System::Collections::Generic::List^ subColliderList; /*-----------------------------------------------------------------------------*/ /* Helper Functions */ From b0175dba31ab24fac5358956d1761e3bf7e65e2b Mon Sep 17 00:00:00 2001 From: Diren D Bharwani Date: Fri, 28 Oct 2022 15:29:28 +0800 Subject: [PATCH 07/12] Ensured a deep copy (recreation) of collision shapes --- SHADE_Engine/src/Physics/SHCollider.cpp | 74 +++++++++++++++++++++++-- SHADE_Engine/src/Physics/SHCollider.h | 6 ++ 2 files changed, 74 insertions(+), 6 deletions(-) diff --git a/SHADE_Engine/src/Physics/SHCollider.cpp b/SHADE_Engine/src/Physics/SHCollider.cpp index 6e929a17..9488042d 100644 --- a/SHADE_Engine/src/Physics/SHCollider.cpp +++ b/SHADE_Engine/src/Physics/SHCollider.cpp @@ -53,20 +53,24 @@ namespace SHADE , entityID { rhs.entityID } , isTrigger { rhs.isTrigger } , dirty { true } - , shape { rhs.shape } + , shape { nullptr } , material { rhs.material } , positionOffset { rhs.positionOffset } - {} + { + CopyShape(rhs.shape); + } SHCollider::SHCollider(SHCollider&& rhs) noexcept : type { rhs.type} , entityID { rhs.entityID } , isTrigger { rhs.isTrigger } , dirty { true } - , shape { rhs.shape } + , shape { nullptr } , material { rhs.material } , positionOffset { rhs.positionOffset } - {} + { + CopyShape(rhs.shape); + } SHCollider::~SHCollider() noexcept { @@ -86,10 +90,12 @@ namespace SHADE entityID = rhs.entityID; isTrigger = rhs.isTrigger; dirty = true; - shape = rhs.shape; material = rhs.material; positionOffset = rhs.positionOffset; + delete shape; + CopyShape(rhs.shape); + return *this; } @@ -99,10 +105,12 @@ namespace SHADE entityID = rhs.entityID; isTrigger = rhs.isTrigger; dirty = true; - shape = rhs.shape; material = rhs.material; positionOffset = rhs.positionOffset; + delete shape; + CopyShape(rhs.shape); + return *this; } @@ -134,11 +142,17 @@ namespace SHADE { return material.GetBounciness(); } + float SHCollider::GetDensity() const noexcept { return material.GetDensity(); } + const SHPhysicsMaterial& SHCollider::GetMaterial() const noexcept + { + return material; + } + const SHVec3& SHCollider::GetPositionOffset() const noexcept { return positionOffset; @@ -234,11 +248,59 @@ namespace SHADE material.SetDensity(density); } + void SHCollider::SetMaterial(const SHPhysicsMaterial& newMaterial) noexcept + { + dirty = true; + material = newMaterial; + } + void SHCollider::SetPositionOffset(const SHVec3& posOffset) noexcept { dirty = true; positionOffset = posOffset; + + switch (type) + { + case Type::BOX: + { + reinterpret_cast(shape)->SetCenter(positionOffset); + break; + } + case Type::SPHERE: + { + reinterpret_cast(shape)->SetCenter(positionOffset); + break; + } + default: break; + } } + + /*-----------------------------------------------------------------------------------*/ + /* Private Function Member Definitions */ + /*-----------------------------------------------------------------------------------*/ + + void SHCollider::CopyShape(const SHShape* rhs) + { + switch (type) + { + case Type::BOX: + { + const auto* RHS_BOX = reinterpret_cast(rhs); + + shape = new SHBoundingBox{ positionOffset, RHS_BOX->GetHalfExtents() }; + break; + } + case Type::SPHERE: + { + const auto* RHS_SPHERE = reinterpret_cast(rhs); + + shape = new SHBoundingSphere{ positionOffset, RHS_SPHERE->GetRadius() }; + break; + } + default: break; + } + } + } // namespace SHADE RTTR_REGISTRATION diff --git a/SHADE_Engine/src/Physics/SHCollider.h b/SHADE_Engine/src/Physics/SHCollider.h index 4fa483c9..f760ffd0 100644 --- a/SHADE_Engine/src/Physics/SHCollider.h +++ b/SHADE_Engine/src/Physics/SHCollider.h @@ -111,6 +111,12 @@ namespace SHADE SHPhysicsMaterial material; SHVec3 positionOffset; + /*---------------------------------------------------------------------------------*/ + /* Function Members */ + /*---------------------------------------------------------------------------------*/ + + void CopyShape(const SHShape* rhs); + RTTR_ENABLE() }; From 199897adb4cd084551ae1f2d554955e096867eb7 Mon Sep 17 00:00:00 2001 From: Kah Wei Date: Fri, 28 Oct 2022 19:00:17 +0800 Subject: [PATCH 08/12] Added GenericHandles to SHADE_Managed --- SHADE_Engine/src/Resource/SHHandle.h | 6 ++ SHADE_Engine/src/Resource/SHHandle.hpp | 5 ++ SHADE_Engine/src/Resource/SparseSet.hpp | 8 +-- SHADE_Managed/src/Engine/GenericHandle.cxx | 47 +++++++++++++++ SHADE_Managed/src/Engine/GenericHandle.hxx | 68 ++++++++++++++++++++++ SHADE_Managed/src/Utility/Convert.cxx | 16 +++++ SHADE_Managed/src/Utility/Convert.hxx | 19 ++++++ 7 files changed, 165 insertions(+), 4 deletions(-) create mode 100644 SHADE_Managed/src/Engine/GenericHandle.cxx create mode 100644 SHADE_Managed/src/Engine/GenericHandle.hxx diff --git a/SHADE_Engine/src/Resource/SHHandle.h b/SHADE_Engine/src/Resource/SHHandle.h index 6acc85ed..49dd56b9 100644 --- a/SHADE_Engine/src/Resource/SHHandle.h +++ b/SHADE_Engine/src/Resource/SHHandle.h @@ -195,6 +195,11 @@ namespace SHADE template inline bool operator==(const Handle& rhs) const noexcept; + /*-----------------------------------------------------------------------------*/ + /* Query Functions */ + /*-----------------------------------------------------------------------------*/ + inline SHResourceLibraryBase* GetLibrary() const; + protected: /*-----------------------------------------------------------------------------*/ /* Data Members */ @@ -206,6 +211,7 @@ namespace SHADE /*-----------------------------------------------------------------------------*/ template friend class Handle; + friend class Convert; }; /// diff --git a/SHADE_Engine/src/Resource/SHHandle.hpp b/SHADE_Engine/src/Resource/SHHandle.hpp index 53061ac7..91eed058 100644 --- a/SHADE_Engine/src/Resource/SHHandle.hpp +++ b/SHADE_Engine/src/Resource/SHHandle.hpp @@ -96,6 +96,11 @@ namespace SHADE return id.Raw == rhs.id.Raw && library == static_cast(rhs.library); } + SHResourceLibraryBase* SHADE::Handle::GetLibrary() const + { + return library; + } + /*---------------------------------------------------------------------------------*/ /* ISelfHandle - Constructors */ /*---------------------------------------------------------------------------------*/ diff --git a/SHADE_Engine/src/Resource/SparseSet.hpp b/SHADE_Engine/src/Resource/SparseSet.hpp index 5afcdee7..816ca432 100644 --- a/SHADE_Engine/src/Resource/SparseSet.hpp +++ b/SHADE_Engine/src/Resource/SparseSet.hpp @@ -70,13 +70,13 @@ namespace SHADE } template - SparseSet::reference SparseSet::at(index_type idx) + typename SparseSet::reference SparseSet::at(index_type idx) { return const_cast(static_cast&>(*this).at(idx)); } template - SparseSet::const_reference SparseSet::at(index_type idx) const + typename SparseSet::const_reference SparseSet::at(index_type idx) const { // Range Check if (idx >= sparseArray.size() || !contains(idx)) @@ -84,7 +84,7 @@ namespace SHADE return denseArray[sparseArray[idx]]; } template - SparseSet::size_type SparseSet::size() const + typename SparseSet::size_type SparseSet::size() const { return denseArray.size(); } @@ -105,7 +105,7 @@ namespace SHADE } template template - SparseSet::reference SparseSet::insert(index_type idx, Args && ...args) + typename SparseSet::reference SparseSet::insert(index_type idx, Args && ...args) { // We need to resize the array if (idx >= sparseArray.size()) diff --git a/SHADE_Managed/src/Engine/GenericHandle.cxx b/SHADE_Managed/src/Engine/GenericHandle.cxx new file mode 100644 index 00000000..41a69c18 --- /dev/null +++ b/SHADE_Managed/src/Engine/GenericHandle.cxx @@ -0,0 +1,47 @@ +/************************************************************************************//*! +\file Renderable.cxx +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Oct 28, 2022 +\brief Contains the definition of the functions of the managed Renderable class. + + Note: This file is written in C++17/CLI. + +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" +#include "GenericHandle.hxx" + +namespace SHADE +{ + /*---------------------------------------------------------------------------------*/ + /* Constructors */ + /*---------------------------------------------------------------------------------*/ + GenericHandle::GenericHandle(Handle handle) + : id { handle.GetId().Raw } + , library { reinterpret_cast(handle.GetLibrary()) } + {} + + /*---------------------------------------------------------------------------------*/ + /* Properties */ + /*---------------------------------------------------------------------------------*/ + System::UInt64 GenericHandle::Id::get() + { + return id; + } + System::IntPtr GenericHandle::Library::get() + { + return library; + } + + /*---------------------------------------------------------------------------------*/ + /* Overloaded Operators */ + /*---------------------------------------------------------------------------------*/ + GenericHandle::operator bool() + { + return library.ToPointer() != nullptr && id != System::UInt64::MaxValue; + } + +} diff --git a/SHADE_Managed/src/Engine/GenericHandle.hxx b/SHADE_Managed/src/Engine/GenericHandle.hxx new file mode 100644 index 00000000..3f8e395f --- /dev/null +++ b/SHADE_Managed/src/Engine/GenericHandle.hxx @@ -0,0 +1,68 @@ +/************************************************************************************//*! +\file Handle.hxx +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Oct 28, 2022 +\brief Contains the definition of the managed GenericHandle struct. + + Note: This file is written in C++17/CLI. + +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 + +// External Dependencies +#include "Resource/SHHandle.h" + +namespace SHADE +{ + /// + /// Managed version of the generic Handle. + /// + public value struct GenericHandle + { + public: + /*-----------------------------------------------------------------------------*/ + /* Constructors */ + /*-----------------------------------------------------------------------------*/ + /// + /// Constructs a GenericHandle for a native generic Handle. + /// + /// Handle to create a GenericHandle from. + explicit GenericHandle(Handle handle); + + /*-----------------------------------------------------------------------------*/ + /* Properties */ + /*-----------------------------------------------------------------------------*/ + /// + /// The internal ID of the handle. + /// + property System::UInt64 Id + { + System::UInt64 get(); + } + /// + /// The library that the handle was issued by. + /// + property System::IntPtr Library + { + System::IntPtr get(); + } + + /*-----------------------------------------------------------------------------*/ + /* Overloaded Operators */ + /*-----------------------------------------------------------------------------*/ + /// + /// Converts to true if this is a valid Handle. + /// + inline operator bool(); + + /*-----------------------------------------------------------------------------*/ + /* Data Members */ + /*-----------------------------------------------------------------------------*/ + System::UInt64 id; + System::IntPtr library; + }; +} \ No newline at end of file diff --git a/SHADE_Managed/src/Utility/Convert.cxx b/SHADE_Managed/src/Utility/Convert.cxx index cb4815aa..1d89569f 100644 --- a/SHADE_Managed/src/Utility/Convert.cxx +++ b/SHADE_Managed/src/Utility/Convert.cxx @@ -84,4 +84,20 @@ namespace SHADE { return msclr::interop::marshal_as(str); } + + /*---------------------------------------------------------------------------------*/ + /* Handle Conversions */ + /*---------------------------------------------------------------------------------*/ + Handle Convert::ToNative(GenericHandle handle) + { + Handle nativeHandle; + nativeHandle.id.Raw = handle.Id; + nativeHandle.library = reinterpret_cast(handle.Library.ToPointer()); + return nativeHandle; + } + + GenericHandle Convert::ToCLI(Handle handle) + { + return GenericHandle(handle); + } } diff --git a/SHADE_Managed/src/Utility/Convert.hxx b/SHADE_Managed/src/Utility/Convert.hxx index 19faffde..d3dca740 100644 --- a/SHADE_Managed/src/Utility/Convert.hxx +++ b/SHADE_Managed/src/Utility/Convert.hxx @@ -20,6 +20,7 @@ of DigiPen Institute of Technology is prohibited. #include "Math/Vector/SHVec3.h" #include "Math/SHQuaternion.h" #include "Math/SHRay.h" +#include "Resource/SHHandle.h" // Project Includes #include "Engine/Entity.hxx" @@ -27,6 +28,7 @@ of DigiPen Institute of Technology is prohibited. #include "Math/Vector3.hxx" #include "Math/Quaternion.hxx" #include "Math/Ray.hxx" +#include "Engine/GenericHandle.hxx" namespace SHADE { @@ -118,6 +120,23 @@ namespace SHADE /// The native std::string to convert from. /// Managed copy of a native std::string. static System::String^ ToCLI(const std::string& str); + + /*-----------------------------------------------------------------------------*/ + /* Handle Conversions */ + /*-----------------------------------------------------------------------------*/ + /// + /// Converts from a managed GenericHandle to a Handle. + /// + /// GenericHandle to convert from. + /// Native generic Handle. + static Handle ToNative(GenericHandle handle); + /// + /// Converts from a native generic Handle to a managed GenericHandle. + /// + /// The native handle to convert. + /// Managed copy of the native Handle. + static GenericHandle ToCLI(Handle handle); + }; /// From 541f44c039c4b5234d94ffd3f7d2e213c6566bb2 Mon Sep 17 00:00:00 2001 From: Kah Wei Date: Fri, 28 Oct 2022 19:02:54 +0800 Subject: [PATCH 09/12] Fixed bugs in SHMaterial, SHMeshLibrary and removed unused functions in SHTextureLibrary --- .../MiddleEnd/Interface/SHMaterial.hpp | 4 +- .../Interface/SHMaterialInstance.hpp | 10 +-- .../MiddleEnd/Interface/SHMeshLibrary.h | 3 +- .../MiddleEnd/Textures/SHTextureLibrary.cpp | 62 ------------------- .../MiddleEnd/Textures/SHTextureLibrary.h | 3 - 5 files changed, 9 insertions(+), 73 deletions(-) diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHMaterial.hpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHMaterial.hpp index 49587921..dceee512 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHMaterial.hpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHMaterial.hpp @@ -33,7 +33,7 @@ namespace SHADE } // Get offset and modify the memory directly - T* dataPtr = propMemory.get() + PROP_INFO->offset; + T* dataPtr = reinterpret_cast(propMemory.get() + PROP_INFO->offset); *dataPtr = value; } template @@ -47,7 +47,7 @@ namespace SHADE } // Get offset and return the memory directly - T* dataPtr = propMemory.get() + PROP_INFO->offset; + T* dataPtr = reinterpret_cast(propMemory.get() + PROP_INFO->offset); return *dataPtr; } template diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHMaterialInstance.hpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHMaterialInstance.hpp index 4621c273..e70631ea 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHMaterialInstance.hpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHMaterialInstance.hpp @@ -69,15 +69,15 @@ namespace SHADE // Search Override Data for the property uint32_t PROP_IDX = SHADER_INFO->GetVariableIndex(key); - auto prop = std::find(overrideData.begin(), overrideData.end(), [&](const OverrideData& data) - { - return PROP_IDX == data.Index; - }); + auto prop = std::find_if(overrideData.begin(), overrideData.end(), [&](const OverrideData& data) + { + return PROP_IDX == data.Index; + }); if (prop == overrideData.end()) throw std::invalid_argument("Attempted to get an property that was not set previously!"); // Get offset and return the memory directly - T* dataPtr = dataStore.get() + prop->StoredDataOffset; + T* dataPtr = reinterpret_cast(dataStore.get() + prop->StoredDataOffset); return *dataPtr; } template diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHMeshLibrary.h b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHMeshLibrary.h index 72ac1878..b0cbdce1 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHMeshLibrary.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHMeshLibrary.h @@ -17,7 +17,8 @@ of DigiPen Institute of Technology is prohibited. // Project Includes #include "Resource/SHHandle.h" #include "Resource/SHResourceLibrary.h" -#include "Math/SHMath.h" +#include "Math/Vector/SHVec2.h" +#include "Math/Vector/SHVec3.h" namespace SHADE { diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Textures/SHTextureLibrary.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Textures/SHTextureLibrary.cpp index 5c315ff6..8719458b 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Textures/SHTextureLibrary.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Textures/SHTextureLibrary.cpp @@ -214,66 +214,4 @@ namespace SHADE SHLOG_ERROR("Image layouts are invalid. "); } } - - vk::Format SHTextureLibrary::ddsLoaderToVkFormat(tinyddsloader::DDSFile::DXGIFormat format, bool isLinear) - { - switch (format) - { - case tinyddsloader::DDSFile::DXGIFormat::BC1_UNorm: - return vk::Format::eBc1RgbaUnormBlock; - case tinyddsloader::DDSFile::DXGIFormat::BC1_UNorm_SRGB: - return vk::Format::eBc1RgbaSrgbBlock; - case tinyddsloader::DDSFile::DXGIFormat::BC2_UNorm: - case tinyddsloader::DDSFile::DXGIFormat::BC2_UNorm_SRGB: - return isLinear ? vk::Format::eBc2UnormBlock : vk::Format::eBc2SrgbBlock; - case tinyddsloader::DDSFile::DXGIFormat::BC3_UNorm: - case tinyddsloader::DDSFile::DXGIFormat::BC3_UNorm_SRGB: - return isLinear ? vk::Format::eBc3UnormBlock : vk::Format::eBc3SrgbBlock; - case tinyddsloader::DDSFile::DXGIFormat::BC5_UNorm: - case tinyddsloader::DDSFile::DXGIFormat::BC5_SNorm: - return isLinear ? vk::Format::eBc5UnormBlock : vk::Format::eBc5SnormBlock; - case tinyddsloader::DDSFile::DXGIFormat::R8G8B8A8_UNorm: - case tinyddsloader::DDSFile::DXGIFormat::R8G8B8A8_UNorm_SRGB: - return isLinear ? vk::Format::eR8G8B8A8Unorm : vk::Format::eR8G8B8A8Srgb; - case tinyddsloader::DDSFile::DXGIFormat::R8G8B8A8_SNorm: - return vk::Format::eR8G8B8A8Snorm; - case tinyddsloader::DDSFile::DXGIFormat::B8G8R8A8_UNorm: - case tinyddsloader::DDSFile::DXGIFormat::B8G8R8A8_UNorm_SRGB: - return isLinear ? vk::Format::eB8G8R8A8Unorm : vk::Format::eB8G8R8A8Srgb; - case tinyddsloader::DDSFile::DXGIFormat::B8G8R8X8_UNorm: - case tinyddsloader::DDSFile::DXGIFormat::B8G8R8X8_UNorm_SRGB: - return isLinear ? vk::Format::eB8G8R8A8Unorm : vk::Format::eB8G8R8Srgb; - default: - throw std::runtime_error("Unsupported DDS format."); - } - - //switch (format) - //{ - //case tinyddsloader::DDSFile::DXGIFormat::R8G8B8A8_UNorm: - //case tinyddsloader::DDSFile::DXGIFormat::R8G8B8A8_UNorm_SRGB: - // return (isLinear) ? vk::Format::eR8G8B8A8Unorm : vk::Format::eR8G8B8A8Srgb; - // - - //case tinyddsloader::DDSFile::DXGIFormat::B8G8R8A8_UNorm: - //case tinyddsloader::DDSFile::DXGIFormat::B8G8R8A8_UNorm_SRGB: - // return (isLinear) ? vk::Format::eB8G8R8A8Unorm : vk::Format::eB8G8R8A8Srgb; - // - - //case tinyddsloader::DDSFile::DXGIFormat::BC1_UNorm: - //case tinyddsloader::DDSFile::DXGIFormat::BC1_UNorm_SRGB: - // return (isLinear) ? vk::Format::eBc1RgbaUnormBlock : vk::Format::eBc1RgbaSrgbBlock; - - //case tinyddsloader::DDSFile::DXGIFormat::BC2_UNorm: - //case tinyddsloader::DDSFile::DXGIFormat::BC2_UNorm_SRGB: - // return (isLinear) ? vk::Format::eBc2UnormBlock : vk::Format::eBc2SrgbBlock; - - //case tinyddsloader::DDSFile::DXGIFormat::BC3_UNorm: - //case tinyddsloader::DDSFile::DXGIFormat::BC3_UNorm_SRGB: - // return (isLinear) ? vk::Format::eBc3UnormBlock : vk::Format::eBc3SrgbBlock; - - //case tinyddsloader::DDSFile::DXGIFormat::BC5_UNorm: - // return (isLinear) ? vk::Format::eBc5UnormBlock : vk::Format::eBc5SnormBlock; - // - //} - } } diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Textures/SHTextureLibrary.h b/SHADE_Engine/src/Graphics/MiddleEnd/Textures/SHTextureLibrary.h index 935a7a4d..9357b0e0 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Textures/SHTextureLibrary.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Textures/SHTextureLibrary.h @@ -14,8 +14,6 @@ of DigiPen Institute of Technology is prohibited. // STL Includes #include -// External Dependencies -#include "tinyddsloader.h" // Project Includes #include "Resource/SHHandle.h" #include "Resource/SHResourceLibrary.h" @@ -169,6 +167,5 @@ namespace SHADE /* Helper Functions */ /*-----------------------------------------------------------------------------*/ void preparePipelineBarriers(vk::ImageLayout oldLayout, vk::ImageLayout newLayout, vk::PipelineStageFlagBits& srcStage, vk::PipelineStageFlagBits& dstStage, std::vector& barriers); - vk::Format ddsLoaderToVkFormat(tinyddsloader::DDSFile::DXGIFormat format, bool isLinear); }; } From 7e5c8198133ad264304fb3caddbf97d1f8f30a29 Mon Sep 17 00:00:00 2001 From: Kah Wei Date: Fri, 28 Oct 2022 19:03:07 +0800 Subject: [PATCH 10/12] Fixed warning with Collider not being made abstract --- SHADE_Managed/src/Components/Collider.hxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SHADE_Managed/src/Components/Collider.hxx b/SHADE_Managed/src/Components/Collider.hxx index f827ab71..9f88b983 100644 --- a/SHADE_Managed/src/Components/Collider.hxx +++ b/SHADE_Managed/src/Components/Collider.hxx @@ -27,7 +27,7 @@ namespace SHADE /// /// Base interface for all Collider Shapes. /// - public ref class ColliderBound + public ref class ColliderBound abstract { public: /*-----------------------------------------------------------------------------*/ From 9617ed3838d210585413ec5a076343bc231eaaa1 Mon Sep 17 00:00:00 2001 From: Kah Wei Date: Fri, 28 Oct 2022 19:23:40 +0800 Subject: [PATCH 11/12] Added NativeAsset, Material and Mesh representations along with a stub for Renderable --- SHADE_Managed/src/Assets/Material.cxx | 119 ++++++++++++++++++++ SHADE_Managed/src/Assets/Material.hxx | 81 +++++++++++++ SHADE_Managed/src/Assets/Mesh.cxx | 34 ++++++ SHADE_Managed/src/Assets/Mesh.hxx | 41 +++++++ SHADE_Managed/src/Assets/NativeAsset.cxx | 26 +++++ SHADE_Managed/src/Assets/NativeAsset.h++ | 49 ++++++++ SHADE_Managed/src/Assets/NativeAsset.hxx | 66 +++++++++++ SHADE_Managed/src/Components/Renderable.cxx | 37 ++++++ SHADE_Managed/src/Components/Renderable.hxx | 53 +++++++++ 9 files changed, 506 insertions(+) create mode 100644 SHADE_Managed/src/Assets/Material.cxx create mode 100644 SHADE_Managed/src/Assets/Material.hxx create mode 100644 SHADE_Managed/src/Assets/Mesh.cxx create mode 100644 SHADE_Managed/src/Assets/Mesh.hxx create mode 100644 SHADE_Managed/src/Assets/NativeAsset.cxx create mode 100644 SHADE_Managed/src/Assets/NativeAsset.h++ create mode 100644 SHADE_Managed/src/Assets/NativeAsset.hxx create mode 100644 SHADE_Managed/src/Components/Renderable.cxx create mode 100644 SHADE_Managed/src/Components/Renderable.hxx diff --git a/SHADE_Managed/src/Assets/Material.cxx b/SHADE_Managed/src/Assets/Material.cxx new file mode 100644 index 00000000..f4262c2a --- /dev/null +++ b/SHADE_Managed/src/Assets/Material.cxx @@ -0,0 +1,119 @@ +/************************************************************************************//*! +\file Material.cxx +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Oct 28, 2022 +\brief Contains the implementation of the functions of the managed Material + class. + + Note: This file is written in C++17/CLI. + +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. +*//*************************************************************************************/ +// Precompiled Headers +#include "SHpch.h" +// Primary Header +#include "Material.hxx" +// Standard Library +#include +// Project Includes +#include "Utility/Convert.hxx" + +namespace SHADE +{ + /*---------------------------------------------------------------------------------*/ + /* Macro Definitions */ + /*---------------------------------------------------------------------------------*/ + #define SET_PROP(NATIVE_TYPE, MANAGED_TYPE) \ + (T::typeid == MANAGED_TYPE::typeid) \ + { \ + const NATIVE_TYPE VAL = safe_cast(System::Convert::ChangeType(value, MANAGED_TYPE::typeid)); \ + NativeObject->SetProperty(PROP_NAME, VAL); \ + } \ + + #define SET_PROP_CONVERT(NATIVE_TYPE, MANAGED_TYPE) \ + (T::typeid == MANAGED_TYPE::typeid) \ + { \ + const NATIVE_TYPE VAL = Convert::ToNative(safe_cast(System::Convert::ChangeType(value, MANAGED_TYPE::typeid))); \ + NativeObject->SetProperty(PROP_NAME, VAL); \ + } \ + + #define GET_PROP(NATIVE_TYPE, MANAGED_TYPE) \ + (T::typeid == MANAGED_TYPE::typeid) \ + { \ + return safe_cast(NativeObject->GetProperty(PROP_NAME)); \ + } \ + + #define GET_PROP_CONVERT(NATIVE_TYPE, MANAGED_TYPE) \ + (T::typeid == MANAGED_TYPE::typeid) \ + { \ + return safe_cast(Convert::ToCLI(NativeObject->GetProperty(PROP_NAME))); \ + } + + /*---------------------------------------------------------------------------------*/ + /* Explicit Template Instantiation */ + /*---------------------------------------------------------------------------------*/ + template ref class NativeAsset; + + /*---------------------------------------------------------------------------------*/ + /* Constructors/Destructor */ + /*---------------------------------------------------------------------------------*/ + Material::Material(Handle material) + : NativeAsset{ material } + {} + + /*---------------------------------------------------------------------------------*/ + /* Material Properties Functions */ + /*---------------------------------------------------------------------------------*/ + generic + void Material::SetProperty(System::String^ name, T value) + { + if (!NativeObject) + throw gcnew System::InvalidOperationException("Attempted to set property on an invalid material!"); + + // Call the correct one based on type + const std::string PROP_NAME = Convert::ToNative(name); + try + { + if SET_PROP (int, System::Int32) + else if SET_PROP (int, System::Int64) + else if SET_PROP (float, float) + else if SET_PROP (double, double) + else if SET_PROP_CONVERT(SHVec2, Vector2) + else if SET_PROP_CONVERT(SHVec3, Vector3) + // TODO: Vector4 + } + catch (const std::invalid_argument&) + { + throw gcnew System::ArgumentException("Attempted to modify an invalid property on a material."); + } + } + + generic + T Material::GetProperty(System::String^ name) + { + if (!NativeObject) + throw gcnew System::InvalidOperationException("[Material] Attempted to get property of an invalid material!"); + + // Call the correct one based on type + const std::string PROP_NAME = Convert::ToNative(name); + try + { + if GET_PROP (int, System::Int32) + else if GET_PROP (int, System::Int64) + else if GET_PROP (float, float) + else if GET_PROP (double, double) + else if GET_PROP_CONVERT(SHVec2, Vector2) + else if GET_PROP_CONVERT(SHVec3, Vector3) + // TODO: Vector4 + } + catch (const std::invalid_argument&) + { + throw gcnew System::ArgumentException("Attempted to retrieve a property on a material with an invalid type."); + } + + throw gcnew System::ArgumentException("Attempted to retrieve an invalid property on a material."); + } +} diff --git a/SHADE_Managed/src/Assets/Material.hxx b/SHADE_Managed/src/Assets/Material.hxx new file mode 100644 index 00000000..25cc96a6 --- /dev/null +++ b/SHADE_Managed/src/Assets/Material.hxx @@ -0,0 +1,81 @@ +/************************************************************************************//*! +\file Material.hxx +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Oct 28, 2022 +\brief Contains the definition of the managed Mesh class. + + Note: This file is written in C++17/CLI. + +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 + +// External Dependencies +#include "Resource/SHHandle.h" +#include "Graphics/MiddleEnd/Interface/SHMaterialInstance.h" +// Project Includes +#include "NativeAsset.hxx" +#include "Engine/GenericHandle.hxx" + +namespace SHADE +{ + /// + /// Managed counterpart of the native MaterialInstance object containing material + /// data that can be fed to Renderables for rendering. + /// + public ref class Material : public NativeAsset + { + internal: + /*-----------------------------------------------------------------------------*/ + /* Constructors/Destructor */ + /*-----------------------------------------------------------------------------*/ + /// + /// Constructor for the Material + /// + /// Handle to the native material object. + Material(Handle material); + + public: + /*-----------------------------------------------------------------------------*/ + /* Properties */ + /*-----------------------------------------------------------------------------*/ + // TODO: Change Shader + + /*-----------------------------------------------------------------------------*/ + /* Material Properties Functions */ + /*-----------------------------------------------------------------------------*/ + /// + /// Set the value of a specific property. + /// + /// Type of property to set. + /// Name of the property to set. + /// Value to set te property to. + /// + /// If this Material object is invalid. + /// + /// + /// If the name or type was specified that does not match the material's shader's + /// defined properties. + /// + generic + void SetProperty(System::String^ name, T value); + /// + /// Retrieves the value of a specified property on the material. + /// + /// Type of property to get. + /// Name of the property to get. + /// Value of that property on the material. + /// + /// If this Material object is invalid. + /// + /// + /// If the name or type was specified that does not match the material's shader's + /// defined properties. + /// + generic + T GetProperty(System::String^ name); + }; +} diff --git a/SHADE_Managed/src/Assets/Mesh.cxx b/SHADE_Managed/src/Assets/Mesh.cxx new file mode 100644 index 00000000..95a61ff6 --- /dev/null +++ b/SHADE_Managed/src/Assets/Mesh.cxx @@ -0,0 +1,34 @@ +/************************************************************************************//*! +\file Mesh.cxx +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Oct 28, 2022 +\brief Contains the implementation of the functions of the managed Mesh class. + + Note: This file is written in C++17/CLI. + +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. +*//*************************************************************************************/ +// Precompiled Headers +#include "SHpch.h" +// Primary Header +#include "Mesh.hxx" +// Project Headers +#include "Utility/Convert.hxx" + +namespace SHADE +{ + /*---------------------------------------------------------------------------------*/ + /* Explicit Template Instantiation */ + /*---------------------------------------------------------------------------------*/ + template ref class NativeAsset; + + /*---------------------------------------------------------------------------------*/ + /* Constructors/Destructor */ + /*---------------------------------------------------------------------------------*/ + Mesh::Mesh(Handle mesh) + : NativeAsset { mesh } + {} +} diff --git a/SHADE_Managed/src/Assets/Mesh.hxx b/SHADE_Managed/src/Assets/Mesh.hxx new file mode 100644 index 00000000..8cd356ba --- /dev/null +++ b/SHADE_Managed/src/Assets/Mesh.hxx @@ -0,0 +1,41 @@ +/************************************************************************************//*! +\file Mesh.hxx +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Oct 28, 2022 +\brief Contains the definition of the managed Mesh class. + + Note: This file is written in C++17/CLI. + +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 + +// External Dependencies +#include "Resource/SHHandle.h" +#include "Graphics/MiddleEnd/Interface/SHMeshLibrary.h" +// Project Includes +#include "NativeAsset.hxx" +#include "Engine/GenericHandle.hxx" + +namespace SHADE +{ + /// + /// Managed counterpart of the native Mesh object containing vertex data that can + /// be fed to Renderables for rendering. + /// + public ref class Mesh : public NativeAsset + { + internal: + /*-----------------------------------------------------------------------------*/ + /* Constructors/Destructor */ + /*-----------------------------------------------------------------------------*/ + /// + /// Constructor for the Mesh + /// + /// Handle to the mesh object. + Mesh(Handle mesh); + }; +} diff --git a/SHADE_Managed/src/Assets/NativeAsset.cxx b/SHADE_Managed/src/Assets/NativeAsset.cxx new file mode 100644 index 00000000..674207a1 --- /dev/null +++ b/SHADE_Managed/src/Assets/NativeAsset.cxx @@ -0,0 +1,26 @@ +/************************************************************************************//*! +\file NativeAsset.cxx +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Oct 28, 2022 +\brief Contains the explicit template instantiation for some types of the + templated managed NativeAsset class. + + Note: This file is written in C++17/CLI. + +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 Include +#include "NativeAsset.hxx" +// Project Includes +#include "Engine/GenericHandle.hxx" + +namespace SHADE +{ + /*---------------------------------------------------------------------------------*/ + /* Explicit Tempalte Instantiations */ + /*---------------------------------------------------------------------------------*/ +} \ No newline at end of file diff --git a/SHADE_Managed/src/Assets/NativeAsset.h++ b/SHADE_Managed/src/Assets/NativeAsset.h++ new file mode 100644 index 00000000..a4cd94b4 --- /dev/null +++ b/SHADE_Managed/src/Assets/NativeAsset.h++ @@ -0,0 +1,49 @@ +/************************************************************************************//*! +\file NativeAsset.h++ +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Oct 28, 2022 +\brief Contains the definition of templated functions for the managed + NativeAsset classes. + + Note: This file is written in C++17/CLI. + +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 + +// Primary Include +#include "NativeAsset.hxx" + +namespace SHADE +{ + /*---------------------------------------------------------------------------------*/ + /* Properties */ + /*---------------------------------------------------------------------------------*/ + template + GenericHandle NativeAsset::NativeObjectHandle::get() + { + return nativeObjHandle; + } + template + Handle NativeAsset::NativeObject::get() + try + { + return Handle(Convert::ToNative(nativeObjHandle)); + } + catch (const BadHandleCastException&) + { + return Handle(); // Null handle + } + + /*---------------------------------------------------------------------------------*/ + /* Constructors */ + /*---------------------------------------------------------------------------------*/ + template + NativeAsset::NativeAsset(Handle nativeObj) + : nativeObjHandle{ Convert::ToCLI(Handle(nativeObj)) } + {} + +} diff --git a/SHADE_Managed/src/Assets/NativeAsset.hxx b/SHADE_Managed/src/Assets/NativeAsset.hxx new file mode 100644 index 00000000..68addb75 --- /dev/null +++ b/SHADE_Managed/src/Assets/NativeAsset.hxx @@ -0,0 +1,66 @@ +/************************************************************************************//*! +\file NativeAsset.hxx +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Oct 28, 2022 +\brief Contains the template definition of the managed class that represents + native assets with a pointer to the corresponding native object. + + Note: This file is written in C++17/CLI. + +Copyright (C) 2021 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 + +#include "Engine/GenericHandle.hxx" + +namespace SHADE +{ + /// + /// Generalised template class for a managed representation of a native asset + /// + /// + /// The type of the asset's native representation. + /// + template + public ref class NativeAsset + { + internal: + /*-----------------------------------------------------------------------------*/ + /* Properties */ + /*-----------------------------------------------------------------------------*/ + /// + /// Generic handle for the native object + /// + property GenericHandle NativeObjectHandle + { + GenericHandle get(); + } + /// + /// Copy of the Handle to the native object. + /// + property Handle NativeObject + { + Handle get(); + } + + /*-----------------------------------------------------------------------------*/ + /* Constructors/Destructor */ + /*-----------------------------------------------------------------------------*/ + /// + /// Constructor for the native asset + /// + /// Native asset object. + NativeAsset(Handle ptr); + + protected: + /*-----------------------------------------------------------------------------*/ + /* Data Members */ + /*-----------------------------------------------------------------------------*/ + GenericHandle nativeObjHandle; + }; +} + +#include "NativeAsset.h++" diff --git a/SHADE_Managed/src/Components/Renderable.cxx b/SHADE_Managed/src/Components/Renderable.cxx new file mode 100644 index 00000000..08a43506 --- /dev/null +++ b/SHADE_Managed/src/Components/Renderable.cxx @@ -0,0 +1,37 @@ +/************************************************************************************//*! +\file Renderable.cxx +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Oct 28, 2022 +\brief Contains the definition of the functions of the managed Renderable class. + + Note: This file is written in C++17/CLI. + +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. +*//*************************************************************************************/ +// Precompiled Headers +#include "SHpch.h" +// Primary Header +#include "Renderable.hxx" +#include "Assets/NativeAsset.hxx" + +namespace SHADE +{ + /*---------------------------------------------------------------------------------*/ + /* Properties */ + /*---------------------------------------------------------------------------------*/ + + /*---------------------------------------------------------------------------------*/ + /* Constructors */ + /*---------------------------------------------------------------------------------*/ + Renderable::Renderable(Entity entity) + : Component(entity) + {} + + /*---------------------------------------------------------------------------------*/ + /* Usage Functions */ + /*---------------------------------------------------------------------------------*/ + +} diff --git a/SHADE_Managed/src/Components/Renderable.hxx b/SHADE_Managed/src/Components/Renderable.hxx new file mode 100644 index 00000000..c21ebdd6 --- /dev/null +++ b/SHADE_Managed/src/Components/Renderable.hxx @@ -0,0 +1,53 @@ +/************************************************************************************//*! +\file Renderable.hxx +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Oct 28, 2022 +\brief Contains the definition of the managed Renderable class with the + declaration of functions for working with it. + + Note: This file is written in C++17/CLI. + +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 Includes +#include "Components/Component.hxx" +#include "Math/Vector3.hxx" +#include "Math/Quaternion.hxx" +// External Dependencies +#include "Graphics/MiddleEnd/Interface/SHRenderable.h" + +namespace SHADE +{ + /// + /// CLR version of the SHADE Engine's SHRenderableComponent. + /// + public ref class Renderable : public Component + { + internal: + /*-----------------------------------------------------------------------------*/ + /* Constructors */ + /*-----------------------------------------------------------------------------*/ + /// + /// Constructs a Renderable Component that represents a native Renderable + /// component tied to the specified Entity. + /// + /// Entity that this Component will be tied to. + Renderable(Entity entity); + + public: + /*-----------------------------------------------------------------------------*/ + /* Properties */ + /*-----------------------------------------------------------------------------*/ + + /*-----------------------------------------------------------------------------*/ + /* Usage Functions */ + /*-----------------------------------------------------------------------------*/ + + }; +} + From 19dc999e4f2b233945f4c61e0fcbd87b68e4d71f Mon Sep 17 00:00:00 2001 From: Kah Wei Date: Sat, 29 Oct 2022 02:19:36 +0800 Subject: [PATCH 12/12] Added full implementation of Renderable script interface --- SHADE_Managed/src/Components/Renderable.cxx | 42 ++++++++++++++++++--- SHADE_Managed/src/Components/Renderable.hxx | 30 ++++++++++++--- 2 files changed, 61 insertions(+), 11 deletions(-) diff --git a/SHADE_Managed/src/Components/Renderable.cxx b/SHADE_Managed/src/Components/Renderable.cxx index 08a43506..d1bbb4c8 100644 --- a/SHADE_Managed/src/Components/Renderable.cxx +++ b/SHADE_Managed/src/Components/Renderable.cxx @@ -16,13 +16,10 @@ of DigiPen Institute of Technology is prohibited. // Primary Header #include "Renderable.hxx" #include "Assets/NativeAsset.hxx" +#include "Utility/Convert.hxx" namespace SHADE { - /*---------------------------------------------------------------------------------*/ - /* Properties */ - /*---------------------------------------------------------------------------------*/ - /*---------------------------------------------------------------------------------*/ /* Constructors */ /*---------------------------------------------------------------------------------*/ @@ -31,7 +28,40 @@ namespace SHADE {} /*---------------------------------------------------------------------------------*/ - /* Usage Functions */ + /* Properties */ /*---------------------------------------------------------------------------------*/ - + SHADE::Mesh^ Renderable::Mesh::get() + { + return gcnew SHADE::Mesh(GetNativeComponent()->Mesh); + } + void Renderable::Mesh::set(SHADE::Mesh^ value) + { + if (value == nullptr) + { + GetNativeComponent()->Mesh = Handle(); + } + else + { + GetNativeComponent()->Mesh = Handle(Convert::ToNative(value->NativeObjectHandle)); + } + } + SHADE::Material^ Renderable::Material::get() + { + return gcnew SHADE::Material(GetNativeComponent()->GetMaterial()); + } + void Renderable::Material::set(SHADE::Material^ value) + { + if (value == nullptr) + { + GetNativeComponent()->SetMaterial(Handle()); + } + else + { + GetNativeComponent()->SetMaterial(Handle(Convert::ToNative(value->NativeObjectHandle))); + } + } + System::Byte Renderable::LightLayer::get() + { + return GetNativeComponent()->GetLightLayer(); + } } diff --git a/SHADE_Managed/src/Components/Renderable.hxx b/SHADE_Managed/src/Components/Renderable.hxx index c21ebdd6..e8f11ef6 100644 --- a/SHADE_Managed/src/Components/Renderable.hxx +++ b/SHADE_Managed/src/Components/Renderable.hxx @@ -20,6 +20,8 @@ of DigiPen Institute of Technology is prohibited. #include "Math/Quaternion.hxx" // External Dependencies #include "Graphics/MiddleEnd/Interface/SHRenderable.h" +#include "Assets/Mesh.hxx" +#include "Assets/Material.hxx" namespace SHADE { @@ -43,11 +45,29 @@ namespace SHADE /*-----------------------------------------------------------------------------*/ /* Properties */ /*-----------------------------------------------------------------------------*/ - - /*-----------------------------------------------------------------------------*/ - /* Usage Functions */ - /*-----------------------------------------------------------------------------*/ - + /// + /// Mesh used to render this Renderable. + /// + property SHADE::Mesh^ Mesh + { + SHADE::Mesh^ get(); + void set(SHADE::Mesh^ value); + } + /// + /// Material used to render this Renderable. + /// + property SHADE::Material^ Material + { + SHADE::Material^ get(); + void set(SHADE::Material^ value); + } + /// + /// Material used to render this Renderable. + /// + property System::Byte LightLayer + { + System::Byte get(); + } }; }