From f64f13521b000f2c2dabeae1a2710958f6ea4e5e Mon Sep 17 00:00:00 2001 From: Sri Sham Haran Date: Tue, 25 Oct 2022 08:42:51 +0800 Subject: [PATCH 01/44] SHVec to yaml node convert --- Assets/Editor/Layouts/UserLayout.ini | 54 ------- .../src/Serialization/SHSerialization.cpp | 4 + .../Serialization/SHSerializationHelper.hpp | 132 +++++++++++++++--- 3 files changed, 115 insertions(+), 75 deletions(-) delete mode 100644 Assets/Editor/Layouts/UserLayout.ini diff --git a/Assets/Editor/Layouts/UserLayout.ini b/Assets/Editor/Layouts/UserLayout.ini deleted file mode 100644 index baced6b8..00000000 --- a/Assets/Editor/Layouts/UserLayout.ini +++ /dev/null @@ -1,54 +0,0 @@ -[Window][MainStatusBar] -Pos=0,1060 -Size=1920,20 -Collapsed=0 - -[Window][SHEditorMenuBar] -Pos=0,48 -Size=1920,1012 -Collapsed=0 - -[Window][Hierarchy Panel] -Pos=0,142 -Size=387,918 -Collapsed=0 -DockId=0x00000004,0 - -[Window][Debug##Default] -Pos=60,60 -Size=400,400 -Collapsed=0 - -[Window][Inspector] -Pos=1649,48 -Size=271,1012 -Collapsed=0 -DockId=0x00000006,0 - -[Window][Profiler] -Pos=0,48 -Size=387,92 -Collapsed=0 -DockId=0x00000003,0 - -[Window][Viewport] -Pos=648,48 -Size=2519,1319 -Collapsed=0 -DockId=0x00000002,0 - -[Window][ Viewport] -Pos=389,48 -Size=1258,1012 -Collapsed=0 -DockId=0x00000002,0 - -[Docking][Data] -DockSpace ID=0xC5C9B8AB Window=0xBE4044E9 Pos=8,79 Size=1920,1012 Split=X - DockNode ID=0x00000005 Parent=0xC5C9B8AB SizeRef=1992,1036 Split=X - DockNode ID=0x00000001 Parent=0x00000005 SizeRef=387,1036 Split=Y Selected=0x1E6EB881 - DockNode ID=0x00000003 Parent=0x00000001 SizeRef=225,94 Selected=0x1E6EB881 - DockNode ID=0x00000004 Parent=0x00000001 SizeRef=225,940 Selected=0xE096E5AE - DockNode ID=0x00000002 Parent=0x00000005 SizeRef=1258,1036 CentralNode=1 Selected=0xB41284E7 - DockNode ID=0x00000006 Parent=0xC5C9B8AB SizeRef=271,1036 Selected=0xE7039252 - diff --git a/SHADE_Engine/src/Serialization/SHSerialization.cpp b/SHADE_Engine/src/Serialization/SHSerialization.cpp index 3804db95..3e569690 100644 --- a/SHADE_Engine/src/Serialization/SHSerialization.cpp +++ b/SHADE_Engine/src/Serialization/SHSerialization.cpp @@ -192,6 +192,10 @@ namespace SHADE { components[rttr::type::get().get_name().data()] = SHSerializationHelper::SerializeComponentToNode(rigidbody); } + if (const auto collisionComp = SHComponentManager::GetComponent_s(eid)) + { + components[rttr::type::get().get_name().data()] = SHSerializationHelper::SerializeComponentToNode(collisionComp); + } node[ComponentsNode] = components; YAML::Node scripts; diff --git a/SHADE_Engine/src/Serialization/SHSerializationHelper.hpp b/SHADE_Engine/src/Serialization/SHSerializationHelper.hpp index da98c885..f8b55d7e 100644 --- a/SHADE_Engine/src/Serialization/SHSerializationHelper.hpp +++ b/SHADE_Engine/src/Serialization/SHSerializationHelper.hpp @@ -9,46 +9,125 @@ #include "Math/Vector/SHVec2.h" #include "Math/Vector/SHVec3.h" #include "Math/Vector/SHVec4.h" +#include "Physics/Components/SHColliderComponent.h" + +namespace YAML +{ + using namespace SHADE; + + template<> + struct convert + { + static constexpr const char* x = "x"; + static constexpr const char* y = "y"; + static constexpr const char* z = "z"; + static constexpr const char* w = "w"; + + static Node encode(SHVec4 const& rhs) + { + Node node; + node.SetStyle(EmitterStyle::Flow); + node[x] = rhs.x; + node[y] = rhs.y; + node[z] = rhs.z; + node[w] = rhs.w; + return node; + } + static bool decode(Node const& node, SHVec4& rhs) + { + if(node[x]) + rhs.x = node[x].as(); + if(node[y]) + rhs.y = node[y].as(); + if(node[z]) + rhs.z = node[z].as(); + if(node[w]) + rhs.w = node[w].as(); + return true; + } + }; + + template<> + struct convert + { + static constexpr const char* x = "x"; + static constexpr const char* y = "y"; + static constexpr const char* z = "z"; + + static Node encode(SHVec3 const& rhs) + { + Node node; + node.SetStyle(EmitterStyle::Flow); + node[x] = rhs.x; + node[y] = rhs.y; + node[z] = rhs.z; + return node; + } + static bool decode(Node const& node, SHVec3& rhs) + { + if(node[x]) + rhs.x = node[x].as(); + if(node[y]) + rhs.y = node[y].as(); + if(node[z]) + rhs.z = node[z].as(); + return true; + } + }; + + template<> + struct convert + { + static constexpr const char* x = "x"; + static constexpr const char* y = "y"; + + static Node encode(SHVec2 const& rhs) + { + Node node; + node.SetStyle(EmitterStyle::Flow); + node[x] = rhs.x; + node[y] = rhs.y; + return node; + } + static bool decode(Node const& node, SHVec2& rhs) + { + if(node[x]) + rhs.x = node[x].as(); + if(node[y]) + rhs.y = node[y].as(); + return true; + } + }; +} namespace SHADE { struct SHSerializationHelper { - template , bool> = true> - static std::string SerializeComponentToString(ComponentType* component) - { - return std::string(); - } - template , bool> = true> - static void SerializeComponentToFile(ComponentType* component, std::filesystem::path const& path) - { - } static YAML::Node RTTRToNode(const rttr::variant& var) { YAML::Node node; auto varType = var.get_type(); + if(varType.is_sequential_container()) + { + for(auto const& elem : var.create_sequential_view()) + { + node.push_back(RTTRToNode(elem)); + } + } if (varType == rttr::type::get()) { - node.SetStyle(YAML::EmitterStyle::Flow); - node["X"] = var.convert().x; - node["Y"] = var.convert().y; - node["Z"] = var.convert().z; - node["W"] = var.convert().w; + node = YAML::convert::encode(var.convert()); } else if (varType == rttr::type::get()) { - node.SetStyle(YAML::EmitterStyle::Flow); - node["X"] = var.convert().x; - node["Y"] = var.convert().y; - node["Z"] = var.convert().z; + node = YAML::convert::encode(var.convert()); } else if (varType == rttr::type::get()) { - node.SetStyle(YAML::EmitterStyle::Flow); - node["X"] = var.convert().x; - node["Y"] = var.convert().y; + node = YAML::convert::encode(var.convert()); } else if (varType.is_arithmetic()) { @@ -107,6 +186,17 @@ namespace SHADE return node; } + template , bool> = true> + static std::string SerializeComponentToString(ComponentType* component) + { + return std::string(); + } + + template , bool> = true> + static void SerializeComponentToFile(ComponentType* component, std::filesystem::path const& path) + { + } + template , bool> = true> static YAML::Node SerializeComponentToNode(ComponentType* component) { From 8466309e2fc43119e56708348d2999d346442ba8 Mon Sep 17 00:00:00 2001 From: Sri Sham Haran Date: Tue, 25 Oct 2022 15:09:45 +0800 Subject: [PATCH 02/44] Serialize/Deserialize SHCollider & SHColliderComponent --- .../HierarchyPanel/SHHierarchyPanel.cpp | 29 ++- .../HierarchyPanel/SHHierarchyPanel.h | 4 +- .../src/Serialization/SHSerialization.cpp | 12 +- .../Serialization/SHSerializationHelper.hpp | 203 ++++++++++++++++-- 4 files changed, 221 insertions(+), 27 deletions(-) diff --git a/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp b/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp index 27e46d98..5d7b6a81 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp +++ b/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp @@ -48,15 +48,28 @@ namespace SHADE if (Begin()) { + if(skipFrame) + { + ImGui::End(); + skipFrame = false; + return; + } DrawMenuBar(); auto const& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); - if(const auto root = sceneGraph.GetRoot()) + + if (const auto root = sceneGraph.GetRoot()) { auto const& children = root->GetChildren(); - + for (const auto child : children) { - RecursivelyDrawEntityNode(child); + if(child) + RecursivelyDrawEntityNode(child); + if(skipFrame) + { + ImGui::End(); + return; + } } } else @@ -120,8 +133,10 @@ namespace SHADE } } - ImRect SHHierarchyPanel::RecursivelyDrawEntityNode(SHSceneNode* currentNode) + ImRect SHHierarchyPanel::RecursivelyDrawEntityNode(SHSceneNode* const currentNode) { + if(currentNode == nullptr) + return {}; auto const& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); //Get node data (Children, eid, selected) @@ -193,10 +208,16 @@ namespace SHADE if(ImGui::Selectable("Paste")) { SetScrollTo(SHSerialization::DeserializeEntitiesFromString(SHClipboardUtilities::GetDataFromClipboard())); + skipFrame = true; + ImGui::EndPopup(); + if(isNodeOpen) + ImGui::TreePop(); + return nodeRect; } if(ImGui::Selectable("Paste as Child")) { SetScrollTo(SHSerialization::DeserializeEntitiesFromString(SHClipboardUtilities::GetDataFromClipboard(), eid)); + skipFrame = true; } if(ImGui::Selectable(std::format("{} Delete", ICON_MD_DELETE).data())) { diff --git a/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.h b/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.h index 0cfe6474..8fae5d6d 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.h +++ b/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.h @@ -26,10 +26,12 @@ namespace SHADE void SetScrollTo(EntityID eid); private: void DrawMenuBar() const noexcept; - ImRect RecursivelyDrawEntityNode(SHSceneNode*); + ImRect RecursivelyDrawEntityNode(SHSceneNode* const); void CreateChildEntity(EntityID parentEID) const noexcept; void ParentSelectedEntities(EntityID parentEID) const noexcept; void SelectRangeOfEntities(EntityID beginEID, EntityID EndEID); + + bool skipFrame = false; std::string filter; bool isAnyNodeSelected = false; EntityID scrollTo = MAX_EID; diff --git a/SHADE_Engine/src/Serialization/SHSerialization.cpp b/SHADE_Engine/src/Serialization/SHSerialization.cpp index 3e569690..31b15409 100644 --- a/SHADE_Engine/src/Serialization/SHSerialization.cpp +++ b/SHADE_Engine/src/Serialization/SHSerialization.cpp @@ -85,6 +85,8 @@ namespace SHADE // Deserialise scripts if (node[ScriptsNode]) SHSystemManager::GetSystem()->DeserialiseScripts(eid, node[ScriptsNode]); + + return eid; } void SHSerialization::DeserializeSceneFromFile(std::filesystem::path const& path) @@ -192,9 +194,9 @@ namespace SHADE { components[rttr::type::get().get_name().data()] = SHSerializationHelper::SerializeComponentToNode(rigidbody); } - if (const auto collisionComp = SHComponentManager::GetComponent_s(eid)) + if (auto collisionComp = SHComponentManager::GetComponent_s(eid)) { - components[rttr::type::get().get_name().data()] = SHSerializationHelper::SerializeComponentToNode(collisionComp); + components[rttr::type::get().get_name().data()] = YAML::convert::encode(*collisionComp); } node[ComponentsNode] = components; @@ -254,6 +256,10 @@ namespace SHADE if (id.has_value()) componentIDList.push_back(id.value()); + id = GetComponentID(componentsNode); + if(id.has_value()) + componentIDList.push_back(id.value()); + return componentIDList; } @@ -263,5 +269,7 @@ namespace SHADE if (!componentsNode) return; SHSerializationHelper::InitializeComponentFromNode(componentsNode, eid); + SHSerializationHelper::InitializeComponentFromNode(componentsNode, eid); + SHSerializationHelper::InitializeComponentFromNodeData(componentsNode, eid); } } diff --git a/SHADE_Engine/src/Serialization/SHSerializationHelper.hpp b/SHADE_Engine/src/Serialization/SHSerializationHelper.hpp index f8b55d7e..6d52df7d 100644 --- a/SHADE_Engine/src/Serialization/SHSerializationHelper.hpp +++ b/SHADE_Engine/src/Serialization/SHSerializationHelper.hpp @@ -35,13 +35,13 @@ namespace YAML } static bool decode(Node const& node, SHVec4& rhs) { - if(node[x]) + if (node[x]) rhs.x = node[x].as(); - if(node[y]) + if (node[y]) rhs.y = node[y].as(); - if(node[z]) + if (node[z]) rhs.z = node[z].as(); - if(node[w]) + if (node[w]) rhs.w = node[w].as(); return true; } @@ -65,11 +65,11 @@ namespace YAML } static bool decode(Node const& node, SHVec3& rhs) { - if(node[x]) + if (node[x]) rhs.x = node[x].as(); - if(node[y]) + if (node[y]) rhs.y = node[y].as(); - if(node[z]) + if (node[z]) rhs.z = node[z].as(); return true; } @@ -91,13 +91,162 @@ namespace YAML } static bool decode(Node const& node, SHVec2& rhs) { - if(node[x]) + if (node[x]) rhs.x = node[x].as(); - if(node[y]) + if (node[y]) rhs.y = node[y].as(); return true; } }; + + template<> + struct convert + { + static constexpr const char* IsTrigger = "Is Trigger"; + + static constexpr const char* Type = "Type"; + static constexpr const char* HalfExtents = "Half Extents"; + static constexpr const char* Radius = "Radius"; + + static constexpr const char* Friction = "Friction"; + static constexpr const char* Bounciness = "Bounciness"; + static constexpr const char* Density = "Density"; + static constexpr const char* PositionOffset = "Position Offset"; + + static Node encode(SHCollider& rhs) + { + Node node; + node[IsTrigger] = rhs.IsTrigger(); + + rttr::type const shapeRttrType = rttr::type::get(); + rttr::enumeration const enumAlign = shapeRttrType.get_enumeration(); + SHCollider::Type colliderType = rhs.GetType(); + + node[Type] = enumAlign.value_to_name(colliderType).data(); + + switch (colliderType) + { + case SHCollider::Type::BOX: + { + auto const bb = reinterpret_cast(rhs.GetShape()); + node[HalfExtents] = bb->GetHalfExtents(); + } + break; + case SHCollider::Type::SPHERE: + { + auto const bs = reinterpret_cast(rhs.GetShape()); + node[Radius] = bs->GetRadius(); + } + break; + case SHCollider::Type::CAPSULE: break; + default:; + } + + node[Friction] = rhs.GetFriction(); + node[Bounciness] = rhs.GetBounciness(); + node[Density] = rhs.GetDensity(); + node[PositionOffset] = rhs.GetPositionOffset(); + + return node; + } + static bool decode(Node const& node, SHCollider& rhs) + { + if (node[IsTrigger]) + rhs.SetIsTrigger(node[IsTrigger].as()); + if (!node[Type]) + return false; + rttr::type const shapeRttrType = rttr::type::get(); + rttr::enumeration const enumAlign = shapeRttrType.get_enumeration(); + bool ok; + const SHCollider::Type colliderType = enumAlign.name_to_value(node[Type].as()).convert(&ok); + if (!ok) + return false; + switch (colliderType) + { + case SHCollider::Type::BOX: + { + if(auto const bb = dynamic_cast(rhs.GetShape()); bb) + { + if (node[HalfExtents]) + { + bb->SetHalfExtents(node[HalfExtents].as()); + } + } + } + break; + case SHCollider::Type::SPHERE: + { + if(auto const bs = dynamic_cast(rhs.GetShape()); bs) + { + if (node[Radius]) + { + bs->SetRadius(node[Radius].as()); + } + } + } + break; + case SHCollider::Type::CAPSULE: break; + default:; + } + if (node[Friction]) + rhs.SetFriction(node[Friction].as()); + if (node[Bounciness]) + rhs.SetBounciness(rhs.GetBounciness()); + if (node[Density]) + rhs.SetDensity(node[Density].as()); + if (node[PositionOffset]) + rhs.SetPositionOffset(node[PositionOffset].as()); + + return true; + } + }; + + template<> + struct convert + { + static constexpr const char* Colliders = "Colliders"; + static Node encode(SHColliderComponent& rhs) + { + Node node, collidersNode; + auto const& colliders = rhs.GetColliders(); + int const numColliders = static_cast(colliders.size()); + for (int i = 0; i < numColliders; ++i) + { + auto& collider = rhs.GetCollider(i); + Node colliderNode = convert::encode(collider); + if (colliderNode.IsDefined()) + collidersNode[i] = colliderNode; + } + node[Colliders] = collidersNode; + return node; + } + static bool decode(Node const& node, SHColliderComponent& rhs) + { + if(node.IsNull()) + return false; + if (node[Colliders]) + { + int numColliders{}; + for (auto const& colliderNode : node[Colliders]) + { + rttr::type const shapeRttrType = rttr::type::get(); + rttr::enumeration const enumAlign = shapeRttrType.get_enumeration(); + bool ok; + const SHCollider::Type colliderType = enumAlign.name_to_value(colliderNode[convert::Type].as()).convert(&ok); + if (!ok) + return false; + switch (colliderType) + { + case SHCollider::Type::BOX: rhs.AddBoundingBox(); break; + case SHCollider::Type::SPHERE: rhs.AddBoundingSphere(); break; + case SHCollider::Type::CAPSULE: break; + default:; + } + rhs.GetCollider(numColliders++) = colliderNode.as(); + } + } + } + }; } namespace SHADE @@ -110,11 +259,11 @@ namespace SHADE { YAML::Node node; auto varType = var.get_type(); - if(varType.is_sequential_container()) + if (varType.is_sequential_container()) { - for(auto const& elem : var.create_sequential_view()) + for (auto const& elem : var.create_sequential_view()) { - node.push_back(RTTRToNode(elem)); + node.push_back(RTTRToNode(elem)); } } if (varType == rttr::type::get()) @@ -178,7 +327,7 @@ namespace SHADE else { auto properties = var.get_type().get_properties(); - for (auto property : properties) + for (auto const& property : properties) { node[property.get_name().data()] = RTTRToNode(property.get_value(var)); } @@ -186,7 +335,7 @@ namespace SHADE return node; } - template , bool> = true> + template , bool> = true> static std::string SerializeComponentToString(ComponentType* component) { return std::string(); @@ -216,17 +365,17 @@ namespace SHADE auto propType = prop.get_type(); if (propType == rttr::type::get()) { - SHVec4 vec{ propertyNode["X"].as(), propertyNode["Y"].as(), propertyNode["Z"].as(), propertyNode["W"].as() }; + SHVec4 vec = propertyNode.as(); prop.set_value(component, vec); } else if (propType == rttr::type::get()) { - SHVec3 vec{ propertyNode["X"].as(), propertyNode["Y"].as(), propertyNode["Z"].as() }; + SHVec3 vec = propertyNode.as(); prop.set_value(component, vec); } else if (propType == rttr::type::get()) { - SHVec2 vec{ propertyNode["X"].as(), propertyNode["Y"].as() }; + SHVec2 vec = propertyNode.as(); prop.set_value(component, vec); } else if (propType.is_arithmetic()) @@ -263,7 +412,7 @@ namespace SHADE else { auto properties = propType.get_properties(); - for (auto property : properties) + for (auto const& property : properties) { InitializeProperty(component, property, propertyNode[property.get_name().data()]); } @@ -273,7 +422,7 @@ namespace SHADE template , bool> = true> static void InitializeComponentFromNode(YAML::Node const& componentsNode, EntityID const& eid) { - auto component = SHComponentManager::GetComponent_s(eid); + ComponentType* component = SHComponentManager::GetComponent_s(eid); if (componentsNode.IsNull() && !component) return; auto rttrType = rttr::type::get(); @@ -283,12 +432,26 @@ namespace SHADE auto properties = rttrType.get_properties(); for (auto const& prop : properties) { - if (componentNode[prop.get_name().data()]) + + if (componentNode[prop.get_name().data()].IsDefined()) { InitializeProperty(component, prop, componentNode[prop.get_name().data()]); } } } + template , bool> = true> + static void InitializeComponentFromNodeData(YAML::Node const& componentsNode, EntityID const& eid) + { + ComponentType* component = SHComponentManager::GetComponent_s(eid); + if (componentsNode.IsNull() && !component) + return; + auto rttrType = rttr::type::get(); + auto componentNode = componentsNode[rttrType.get_name().data()]; + if (componentsNode.IsNull()) + return; + YAML::convert::decode(componentNode, *component); + } + }; } From d9584a0e39932b403e6ecde24854016309a2a143 Mon Sep 17 00:00:00 2001 From: Sri Sham Haran Date: Wed, 26 Oct 2022 14:32:00 +0800 Subject: [PATCH 03/44] Changed SHEditor.hpp to .h Handle editor camera update when interacting with viewport window only --- .../src/Application/SBApplication.cpp | 4 +- .../HierarchyPanel/SHHierarchyPanel.cpp | 2 +- .../Inspector/SHEditorInspector.cpp | 12 +++-- .../EditorWindow/MenuBar/SHEditorMenuBar.cpp | 2 +- .../ViewportWindow/SHEditorViewport.cpp | 47 ++++++++++++++++++- .../src/Editor/Gizmos/SHTransformGizmo.cpp | 2 +- SHADE_Engine/src/Editor/SHEditor.cpp | 2 +- .../src/Editor/{SHEditor.hpp => SHEditor.h} | 0 .../MiddleEnd/Interface/SHGraphicsSystem.cpp | 2 +- 9 files changed, 60 insertions(+), 13 deletions(-) rename SHADE_Engine/src/Editor/{SHEditor.hpp => SHEditor.h} (100%) diff --git a/SHADE_Application/src/Application/SBApplication.cpp b/SHADE_Application/src/Application/SBApplication.cpp index 54dc0ccf..c6750707 100644 --- a/SHADE_Application/src/Application/SBApplication.cpp +++ b/SHADE_Application/src/Application/SBApplication.cpp @@ -4,7 +4,7 @@ //#define SHEDITOR #ifdef SHEDITOR -#include "Editor/SHEditor.hpp" +#include "Editor/SHEditor.h" //#include "Scenes/SBEditorScene.h" #endif // SHEDITOR @@ -94,7 +94,7 @@ namespace Sandbox SHSystemManager::RegisterRoutine(); SHSystemManager::RegisterRoutine(); - SHSystemManager::RegisterRoutine(); + //SHSystemManager::RegisterRoutine(); SHSystemManager::RegisterRoutine(); #ifdef SHEDITOR diff --git a/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp b/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp index f2f8d927..fff0a188 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp +++ b/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp @@ -6,7 +6,7 @@ //#==============================================================# //|| SHADE Includes || //#==============================================================# -#include "Editor/SHEditor.hpp" +#include "Editor/SHEditor.h" #include "Editor/SHImGuiHelpers.hpp" #include "Editor/SHEditorWidgets.hpp" #include "SHHierarchyPanel.h" diff --git a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorInspector.cpp b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorInspector.cpp index ada5a35a..511f8642 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorInspector.cpp +++ b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorInspector.cpp @@ -1,6 +1,6 @@ #include "SHpch.h" -#include "Editor/SHEditor.hpp" +#include "Editor/SHEditor.h" #include "SHEditorInspector.h" #include "ECS_Base/SHECSMacros.h" @@ -92,11 +92,15 @@ namespace SHADE DrawAddComponentButton(eid); DrawAddComponentButton(eid); DrawAddComponentButton(eid); - if(DrawAddComponentButton(eid)) + if (!SHComponentManager::HasComponent(eid)) { - if(SHComponentManager::GetComponent_s(eid) == nullptr) + if (ImGui::Selectable(std::format("Add {}", rttr::type::get().get_name().data()).data())) { - SHComponentManager::AddComponent(eid); + if (SHComponentManager::GetComponent_s(eid) == nullptr) + { + SHComponentManager::AddComponent(eid); + } + SHComponentManager::AddComponent(eid); } } ImGui::EndMenu(); diff --git a/SHADE_Engine/src/Editor/EditorWindow/MenuBar/SHEditorMenuBar.cpp b/SHADE_Engine/src/Editor/EditorWindow/MenuBar/SHEditorMenuBar.cpp index c33f4fb6..50b878a8 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/MenuBar/SHEditorMenuBar.cpp +++ b/SHADE_Engine/src/Editor/EditorWindow/MenuBar/SHEditorMenuBar.cpp @@ -3,7 +3,7 @@ //#==============================================================# //|| SHADE Includes || //#==============================================================# -#include "Editor/SHEditor.hpp" +#include "Editor/SHEditor.h" #include "SHEditorMenuBar.h" #include "Editor/IconsMaterialDesign.h" #include "Editor/Command/SHCommandManager.h" diff --git a/SHADE_Engine/src/Editor/EditorWindow/ViewportWindow/SHEditorViewport.cpp b/SHADE_Engine/src/Editor/EditorWindow/ViewportWindow/SHEditorViewport.cpp index f5170999..17bf6fa5 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/ViewportWindow/SHEditorViewport.cpp +++ b/SHADE_Engine/src/Editor/EditorWindow/ViewportWindow/SHEditorViewport.cpp @@ -5,13 +5,15 @@ #include "ImGuizmo.h" #include "ECS_Base/Managers/SHSystemManager.h" #include "Editor/IconsMaterialDesign.h" -#include "Editor/SHEditor.hpp" +#include "Editor/SHEditor.h" #include "Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.h" #include "Graphics/MiddleEnd/Interface/SHGraphicsSystem.h" #include "Graphics/Descriptors/SHVkDescriptorSetGroup.h" #include "Graphics/MiddleEnd/Interface/SHMousePickSystem.h" #include +#include "Camera/SHCameraSystem.h" + constexpr std::string_view windowName = "\xef\x80\x95 Viewport"; namespace SHADE @@ -25,6 +27,8 @@ namespace SHADE { SHEditorWindow::Init(); transformGizmo.Init(); + auto camSystem = SHSystemManager::GetSystem(); + camSystem->UpdateEditorCamera(0.016f); } void SHEditorViewport::Update() @@ -51,6 +55,24 @@ namespace SHADE ImGui::PushStyleColor(ImGuiCol_Text, ImGuiColors::green); ImGui::Text(ICON_FA_EYE); ImGui::PopStyleColor(); + + auto camSystem = SHSystemManager::GetSystem(); + camSystem->UpdateEditorCamera(0.016f); + } + if(ImGui::IsWindowFocused() && !ImGui::IsMouseDown(ImGuiMouseButton_Right)) + { + if(ImGui::IsKeyReleased(ImGuiKey_Q)) + { + transformGizmo.operation = SHTransformGizmo::Operation::TRANSLATE; + } + if(ImGui::IsKeyReleased(ImGuiKey_W)) + { + transformGizmo.operation = SHTransformGizmo::Operation::ROTATE; + } + if(ImGui::IsKeyReleased(ImGuiKey_E)) + { + transformGizmo.operation = SHTransformGizmo::Operation::SCALE; + } } } ImGuizmo::SetRect(beginCursorPos.x , beginCursorPos.y, beginContentRegionAvailable.x, beginContentRegionAvailable.y); @@ -77,6 +99,8 @@ namespace SHADE beginContentRegionAvailable = windowSize; } gfxSystem->PrepareResize(static_cast(beginContentRegionAvailable.x), static_cast(beginContentRegionAvailable.y)); + auto camSystem = SHSystemManager::GetSystem(); + camSystem->UpdateEditorCamera(0.016f); } void SHEditorViewport::OnPosChange() @@ -88,6 +112,7 @@ namespace SHADE { if(ImGui::BeginMenuBar()) { + ImGui::BeginDisabled(ImGui::IsWindowFocused() && ImGui::IsMouseDown(ImGuiMouseButton_Right)); bool const isTranslate = transformGizmo.operation == SHTransformGizmo::Operation::TRANSLATE; ImGui::BeginDisabled(isTranslate); if(isTranslate) @@ -97,6 +122,12 @@ namespace SHADE transformGizmo.operation = SHTransformGizmo::Operation::TRANSLATE; } ImGui::EndDisabled(); + if(ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + { + ImGui::BeginTooltip(); + ImGui::Text("Translate [Q]"); + ImGui::EndTooltip(); + } if(isTranslate) ImGui::PopStyleColor(); @@ -109,6 +140,12 @@ namespace SHADE transformGizmo.operation = SHTransformGizmo::Operation::ROTATE; } ImGui::EndDisabled(); + if(ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + { + ImGui::BeginTooltip(); + ImGui::Text("Rotate [W]"); + ImGui::EndTooltip(); + } if(isRotate) ImGui::PopStyleColor(); @@ -121,9 +158,15 @@ namespace SHADE transformGizmo.operation = SHTransformGizmo::Operation::SCALE; } ImGui::EndDisabled(); + if(ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + { + ImGui::BeginTooltip(); + ImGui::Text("Scale [E]"); + ImGui::EndTooltip(); + } if(isScale) ImGui::PopStyleColor(); - + ImGui::EndDisabled(); ImGui::EndMenuBar(); } } diff --git a/SHADE_Engine/src/Editor/Gizmos/SHTransformGizmo.cpp b/SHADE_Engine/src/Editor/Gizmos/SHTransformGizmo.cpp index 3c984051..55e99ff9 100644 --- a/SHADE_Engine/src/Editor/Gizmos/SHTransformGizmo.cpp +++ b/SHADE_Engine/src/Editor/Gizmos/SHTransformGizmo.cpp @@ -3,7 +3,7 @@ #include "ECS_Base/Managers/SHComponentManager.h" #include "ECS_Base/Managers/SHSystemManager.h" -#include "Editor/SHEditor.hpp" +#include "Editor/SHEditor.h" #include "Editor/SHImGuiHelpers.hpp" #include #include diff --git a/SHADE_Engine/src/Editor/SHEditor.cpp b/SHADE_Engine/src/Editor/SHEditor.cpp index 06fadfee..99125e65 100644 --- a/SHADE_Engine/src/Editor/SHEditor.cpp +++ b/SHADE_Engine/src/Editor/SHEditor.cpp @@ -21,7 +21,7 @@ #include "Graphics/MiddleEnd/Interface/SHViewport.h" #include "Graphics/MiddleEnd/Interface/SHRenderer.h" -#include "SHEditor.hpp" +#include "SHEditor.h" #include "SHEditorWidgets.hpp" #include "Math/Transform/SHTransformSystem.h" diff --git a/SHADE_Engine/src/Editor/SHEditor.hpp b/SHADE_Engine/src/Editor/SHEditor.h similarity index 100% rename from SHADE_Engine/src/Editor/SHEditor.hpp rename to SHADE_Engine/src/Editor/SHEditor.h diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp index 4280cafd..8744b083 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp @@ -17,7 +17,7 @@ of DigiPen Institute of Technology is prohibited. #include "Graphics/Windowing/Surface/SHVkSurface.h" #include "Graphics/Swapchain/SHVkSwapchain.h" #include "Camera/SHCameraSystem.h" -#include "Editor/SHEditor.hpp" +#include "Editor/SHEditor.h" #include "ECS_Base/Managers/SHSystemManager.h" //#include "SHRenderer.h" #include "Graphics/Windowing/SHWindow.h" From b013d09f42273ae984ac0b33e7d3efe44b10feeb Mon Sep 17 00:00:00 2001 From: Sri Sham Haran Date: Wed, 26 Oct 2022 15:31:23 +0800 Subject: [PATCH 04/44] Tooltips. editor tweaks --- .../Inspector/SHEditorComponentView.hpp | 47 ++++++++------- .../src/Editor/Gizmos/SHTransformGizmo.cpp | 3 + SHADE_Engine/src/Editor/SHEditorWidgets.hpp | 58 ++++++++++--------- .../Math/Transform/SHTransformComponent.cpp | 7 ++- 4 files changed, 61 insertions(+), 54 deletions(-) diff --git a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp index 7fa39d74..71a31bb8 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp +++ b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp @@ -51,8 +51,10 @@ namespace SHADE { if (!component) return; - const auto componentType = rttr::type::get(*component); + const auto componentType = rttr::type::get(); + ImGui::PushID(component->GetEID()); SHEditorWidgets::CheckBox("##IsActive", [component]() {return component->isActive; }, [component](bool const& active) {component->isActive = active; }, "Is Component Active"); + ImGui::PopID(); ImGui::SameLine(); if (ImGui::CollapsingHeader(componentType.get_name().data())) { @@ -61,6 +63,7 @@ namespace SHADE for (auto const& property : properties) { auto const& type = property.get_type(); + auto tooltip = property.get_metadata(META::tooltip); if (type.is_enumeration()) { @@ -75,29 +78,25 @@ namespace SHADE auto values = enumAlign.get_values(); auto it = std::next(values.begin(), idx); property.set_value(component, *it); - }); + }, tooltip.is_valid() ? tooltip.template get_value() : std::string()); } else if (type.is_arithmetic()) { if (type == rttr::type::get()) { - SHEditorWidgets::CheckBox(property.get_name().data(), [component, property] {return property.get_value(component).to_bool(); }, [component, property](bool const& result) {property.set_value(component, result); }); + SHEditorWidgets::CheckBox(property.get_name().data(), [component, property] {return property.get_value(component).to_bool(); }, [component, property](bool const& result) {property.set_value(component, result); }, tooltip.is_valid() ? tooltip.template get_value() : std::string()); } - //else if (type == rttr::type::get()) - //{ - // - //} else if (type == rttr::type::get() || type == rttr::type::get() || type == rttr::type::get() || type == rttr::type::get()) { auto metaMin = property.get_metadata(META::min); auto metaMax = property.get_metadata(META::max); if (metaMin && metaMax) { - SHEditorWidgets::SliderInt(property.get_name().data(), metaMin.template get_value(), metaMax.template get_value(), [component, property] {return property.get_value(component).to_int(); }, [component, property](int const& result) {property.set_value(component, result); }); + SHEditorWidgets::SliderInt(property.get_name().data(), metaMin.template get_value(), metaMax.template get_value(), [component, property] {return property.get_value(component).to_int(); }, [component, property](int const& result) {property.set_value(component, result); }, tooltip.is_valid() ? tooltip.template get_value() : std::string()); } else { - SHEditorWidgets::DragInt(property.get_name().data(), [component, property] {return property.get_value(component).to_int(); }, [component, property](int const& result) {property.set_value(component, result); }); + SHEditorWidgets::DragInt(property.get_name().data(), [component, property] {return property.get_value(component).to_int(); }, [component, property](int const& result) {property.set_value(component, result); }, tooltip.is_valid() ? tooltip.template get_value() : std::string()); } } else if (type == rttr::type::get()) @@ -106,11 +105,11 @@ namespace SHADE auto metaMax = property.get_metadata(META::max); if (metaMin.is_valid() && metaMax.is_valid()) { - SHEditorWidgets::SliderScalar(property.get_name().data(), ImGuiDataType_U8, metaMin.template get_value(), metaMax.template get_value(), [component, property] {return property.get_value(component).to_uint8(); }, [component, property](uint8_t const& result) {property.set_value(component, result); }, "%zu"); + SHEditorWidgets::SliderScalar(property.get_name().data(), ImGuiDataType_U8, metaMin.template get_value(), metaMax.template get_value(), [component, property] {return property.get_value(component).to_uint8(); }, [component, property](uint8_t const& result) {property.set_value(component, result); }, tooltip.is_valid() ? tooltip.template get_value() : std::string(), "%zu"); } else { - SHEditorWidgets::DragScalar(property.get_name().data(), ImGuiDataType_U8, [component, property] {return property.get_value(component).to_uint8(); }, [component, property](uint8_t const& result) {property.set_value(component, result); }, 0.1f, 0, 0, "%zu"); + SHEditorWidgets::DragScalar(property.get_name().data(), ImGuiDataType_U8, [component, property] {return property.get_value(component).to_uint8(); }, [component, property](uint8_t const& result) {property.set_value(component, result); }, 0.1f, 0, 0, "%zu", tooltip.is_valid() ? tooltip.template get_value() : std::string()); } } else if (type == rttr::type::get()) @@ -119,11 +118,11 @@ namespace SHADE auto metaMax = property.get_metadata(META::max); if (metaMin.is_valid() && metaMax.is_valid()) { - SHEditorWidgets::SliderScalar(property.get_name().data(), ImGuiDataType_U16, metaMin.template get_value(), metaMax.template get_value(), [component, property] {return property.get_value(component).to_uint16(); }, [component, property](uint16_t const& result) {property.set_value(component, result); }, "%zu"); + SHEditorWidgets::SliderScalar(property.get_name().data(), ImGuiDataType_U16, metaMin.template get_value(), metaMax.template get_value(), [component, property] {return property.get_value(component).to_uint16(); }, [component, property](uint16_t const& result) {property.set_value(component, result); }, tooltip.is_valid() ? tooltip.template get_value() : std::string(), "%zu"); } else { - SHEditorWidgets::DragScalar(property.get_name().data(), ImGuiDataType_U16, [component, property] {return property.get_value(component).to_uint16(); }, [component, property](uint16_t const& result) {property.set_value(component, result); }, 0.1f, 0, 0, "%zu"); + SHEditorWidgets::DragScalar(property.get_name().data(), ImGuiDataType_U16, [component, property] {return property.get_value(component).to_uint16(); }, [component, property](uint16_t const& result) {property.set_value(component, result); }, 0.1f, 0, 0, "%zu", tooltip.is_valid() ? tooltip.template get_value() : std::string()); } } else if (type == rttr::type::get()) @@ -132,11 +131,11 @@ namespace SHADE auto metaMax = property.get_metadata(META::max); if (metaMin.is_valid() && metaMax.is_valid()) { - SHEditorWidgets::SliderScalar(property.get_name().data(), ImGuiDataType_U32, metaMin.template get_value(), metaMax.template get_value(), [component, property] { return property.get_value(component).to_uint32(); }, [component, property](uint32_t const& result) {property.set_value(component, result); }, "%zu"); + SHEditorWidgets::SliderScalar(property.get_name().data(), ImGuiDataType_U32, metaMin.template get_value(), metaMax.template get_value(), [component, property] { return property.get_value(component).to_uint32(); }, [component, property](uint32_t const& result) {property.set_value(component, result); }, tooltip.is_valid() ? tooltip.template get_value() : std::string(), "%zu"); } else { - SHEditorWidgets::DragScalar(property.get_name().data(), ImGuiDataType_U32, [component, property] { return property.get_value(component).to_uint32(); }, [component, property](uint32_t const& result) {property.set_value(component, result); }, 0.1f, 0, 0, "%zu"); + SHEditorWidgets::DragScalar(property.get_name().data(), ImGuiDataType_U32, [component, property] { return property.get_value(component).to_uint32(); }, [component, property](uint32_t const& result) {property.set_value(component, result); }, 0.1f, 0, 0, "%zu", tooltip.is_valid() ? tooltip.template get_value() : std::string()); } } else if (type == rttr::type::get()) @@ -145,11 +144,11 @@ namespace SHADE auto metaMax = property.get_metadata(META::max); if (metaMin.is_valid() && metaMax.is_valid()) { - SHEditorWidgets::SliderScalar(property.get_name().data(), ImGuiDataType_U64, metaMin.template get_value(), metaMax.template get_value(), [component, property] {return property.get_value(component).to_uint64(); }, [component, property](uint64_t const& result) {property.set_value(component, result); }, "%zu"); + SHEditorWidgets::SliderScalar(property.get_name().data(), ImGuiDataType_U64, metaMin.template get_value(), metaMax.template get_value(), [component, property] {return property.get_value(component).to_uint64(); }, [component, property](uint64_t const& result) {property.set_value(component, result); }, tooltip.is_valid() ? tooltip.template get_value() : std::string(), "%zu"); } else { - SHEditorWidgets::DragScalar(property.get_name().data(), ImGuiDataType_U64, [component, property] {return property.get_value(component).to_uint64(); }, [component, property](uint64_t const& result) {property.set_value(component, result); }, 0.1f, 0, 0, "%zu"); + SHEditorWidgets::DragScalar(property.get_name().data(), ImGuiDataType_U64, [component, property] {return property.get_value(component).to_uint64(); }, [component, property](uint64_t const& result) {property.set_value(component, result); }, 0.1f, 0, 0, "%zu", tooltip.is_valid() ? tooltip.template get_value() : std::string()); } } else if (type == rttr::type::get()) @@ -163,11 +162,11 @@ namespace SHADE max = std::min(metaMax.template get_value(), FLT_MAX * 0.5f); if (metaMin.is_valid() && metaMax.is_valid()) { - SHEditorWidgets::SliderFloat(property.get_name().data(), min, max, [component, property] {return property.get_value(component).to_float(); }, [component, property](float const& result) {property.set_value(component, result); }); + SHEditorWidgets::SliderFloat(property.get_name().data(), min, max, [component, property] {return property.get_value(component).to_float(); }, [component, property](float const& result) {property.set_value(component, result); }, tooltip.is_valid() ? tooltip.template get_value() : std::string()); } else { - SHEditorWidgets::DragFloat(property.get_name().data(), [component, property] {return property.get_value(component).to_float(); }, [component, property](float const& result) {property.set_value(component, result); }, "Test"); + SHEditorWidgets::DragFloat(property.get_name().data(), [component, property] {return property.get_value(component).to_float(); }, [component, property](float const& result) {property.set_value(component, result); }, tooltip.is_valid() ? tooltip.template get_value() : std::string()); } } else if (type == rttr::type::get()) @@ -176,25 +175,25 @@ namespace SHADE auto metaMax = property.get_metadata(META::max); if (metaMin.is_valid() && metaMax.is_valid()) { - SHEditorWidgets::SliderScalar(property.get_name().data(), ImGuiDataType_Double, metaMin.template get_value(), metaMax.template get_value(), [component, property] {return property.get_value(component).to_double(); }, [component, property](double const& result) {property.set_value(component, result); }); + SHEditorWidgets::SliderScalar(property.get_name().data(), ImGuiDataType_Double, metaMin.template get_value(), metaMax.template get_value(), [component, property] {return property.get_value(component).to_double(); }, [component, property](double const& result) {property.set_value(component, result); }, tooltip.is_valid() ? tooltip.template get_value() : std::string()); } else { - SHEditorWidgets::DragScalar(property.get_name().data(), ImGuiDataType_Double, [component, property] {return property.get_value(component).to_double(); }, [component, property](double const& result) {property.set_value(component, result); }, 0.1f); + SHEditorWidgets::DragScalar(property.get_name().data(), ImGuiDataType_Double, [component, property] {return property.get_value(component).to_double(); }, [component, property](double const& result) {property.set_value(component, result); }, 0.1f, {}, {}, "%.3f", tooltip.is_valid() ? tooltip.template get_value() : std::string()); } } } else if (type == rttr::type::get()) { - SHEditorWidgets::DragVec4(property.get_name().data(), { "X", "Y", "Z", "W" }, [component, property]() {return property.get_value(component).template convert(); }, [component, property](SHVec4 vec) {return property.set_value(component, vec); }); + SHEditorWidgets::DragVec4(property.get_name().data(), { "X", "Y", "Z", "W" }, [component, property]() {return property.get_value(component).template convert(); }, [component, property](SHVec4 vec) {return property.set_value(component, vec); }, tooltip.is_valid() ? tooltip.template get_value() : std::string()); } else if (type == rttr::type::get()) { - SHEditorWidgets::DragVec3(property.get_name().data(), { "X", "Y", "Z" }, [component, property]() {return property.get_value(component).template convert(); }, [component, property](SHVec3 vec) {return property.set_value(component, vec); }); + SHEditorWidgets::DragVec3(property.get_name().data(), { "X", "Y", "Z" }, [component, property]() {return property.get_value(component).template convert(); }, [component, property](SHVec3 vec) {return property.set_value(component, vec); }, tooltip.is_valid() ? tooltip.template get_value() : std::string()); } else if (type == rttr::type::get()) { - SHEditorWidgets::DragVec2(property.get_name().data(), { "X", "Y" }, [component, property]() {return property.get_value(component).template convert(); }, [component, property](SHVec2 vec) {return property.set_value(component, vec); }); + SHEditorWidgets::DragVec2(property.get_name().data(), { "X", "Y" }, [component, property]() {return property.get_value(component).template convert(); }, [component, property](SHVec2 vec) {return property.set_value(component, vec); }, tooltip.is_valid() ? tooltip.template get_value() : std::string()); } } diff --git a/SHADE_Engine/src/Editor/Gizmos/SHTransformGizmo.cpp b/SHADE_Engine/src/Editor/Gizmos/SHTransformGizmo.cpp index 55e99ff9..e3bbc809 100644 --- a/SHADE_Engine/src/Editor/Gizmos/SHTransformGizmo.cpp +++ b/SHADE_Engine/src/Editor/Gizmos/SHTransformGizmo.cpp @@ -63,6 +63,9 @@ namespace SHADE if (selectedEntityTransformComponent == nullptr) return; + if(!selectedEntityTransformComponent->isActive) + return; + SHMatrix mat = selectedEntityTransformComponent->GetTRS(); useSnap = ImGui::IsKeyDown(ImGuiKey_LeftCtrl); if(useSnap) diff --git a/SHADE_Engine/src/Editor/SHEditorWidgets.hpp b/SHADE_Engine/src/Editor/SHEditorWidgets.hpp index b54a6799..26cac23e 100644 --- a/SHADE_Engine/src/Editor/SHEditorWidgets.hpp +++ b/SHADE_Engine/src/Editor/SHEditorWidgets.hpp @@ -174,15 +174,19 @@ namespace SHADE ImGui::SetColumnWidth(-1, 80.0f); ImGui::Text(label.c_str()); if (isHovered) - *isHovered = ImGui::IsItemHovered(); + *isHovered |= ImGui::IsItemHovered(); ImGui::NextColumn(); for (std::size_t i = 0; i < N; ++i) { ImGui::PushID(static_cast(i)); - ImGui::TextUnformatted(componentLabels[i].c_str(), ImGui::FindRenderedTextEnd(componentLabels[i].c_str())); ImGui::SameLine(); + ImGui::TextUnformatted(componentLabels[i].c_str(), ImGui::FindRenderedTextEnd(componentLabels[i].c_str())); + if (isHovered) + *isHovered |= ImGui::IsItemHovered(); + ImGui::SameLine(); ImGui::SetNextItemWidth(80.0f); valueChanged |= ImGui::DragFloat("##v", values[i], speed, valueMin, valueMax, displayFormat, flags); - + if (isHovered) + *isHovered |= ImGui::IsItemHovered(); const ImVec2 min = ImGui::GetItemRectMin(); const ImVec2 max = ImGui::GetItemRectMax(); const float spacing = g.Style.FrameRounding; @@ -203,7 +207,7 @@ namespace SHADE } static bool DragVec2(const std::string& label, std::vectorconst& componentLabels, std::function get, - std::function set, float speed = 0.1f, const char* displayFormat = "%.3f", std::string_view const& tooltip = {}, float valueMin = 0.0f, float valueMax = 0.0f, + std::function set, std::string_view const& tooltip = {}, float speed = 0.1f, const char* displayFormat = "%.3f", float valueMin = 0.0f, float valueMax = 0.0f, ImGuiSliderFlags flags = 0) { SHVec2 values = get(); @@ -217,9 +221,9 @@ namespace SHADE } if (startRecording && ImGui::IsMouseReleased(ImGuiMouseButton_Left)) startRecording = false; - if(!tooltip.empty()) + if (!tooltip.empty()) { - if(ImGui::IsItemHovered()) + if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); ImGui::Text(tooltip.data()); @@ -230,11 +234,12 @@ namespace SHADE } static bool DragVec3(const std::string& label, std::vectorconst& componentLabels, std::function get, - std::function set, float speed = 0.1f, const char* displayFormat = "%.3f", std::string_view const& tooltip = {}, float valueMin = 0.0f, float valueMax = 0.0f, + std::function set, std::string_view const& tooltip = {}, float speed = 0.1f, const char* displayFormat = "%.3f", float valueMin = 0.0f, float valueMax = 0.0f, ImGuiSliderFlags flags = 0) { SHVec3 values = get(); - bool const changed = DragN(label, componentLabels, { &values.x, &values.y, &values.z }, speed, displayFormat, valueMin, valueMax, flags); + bool isHovered = false; + bool const changed = DragN(label, componentLabels, { &values.x, &values.y, &values.z }, speed, displayFormat, valueMin, valueMax, flags, &isHovered); static bool startRecording = false; @@ -249,9 +254,9 @@ namespace SHADE { startRecording = false; } - if(!tooltip.empty()) + if (!tooltip.empty()) { - if(ImGui::IsItemHovered()) + if (isHovered) { ImGui::BeginTooltip(); ImGui::Text(tooltip.data()); @@ -262,7 +267,7 @@ namespace SHADE } static bool DragVec4(const std::string& label, std::vectorconst& componentLabels, std::function get, - std::function set, float speed = 0.1f, const char* displayFormat = "%.3f", std::string_view const& tooltip = {}, float valueMin = 0.0f, float valueMax = 0.0f, + std::function set, std::string_view const& tooltip = {}, float speed = 0.1f, const char* displayFormat = "%.3f", float valueMin = 0.0f, float valueMax = 0.0f, ImGuiSliderFlags flags = 0) { SHVec4 values = get(); @@ -278,9 +283,9 @@ namespace SHADE { startRecording = false; } - if(!tooltip.empty()) + if (!tooltip.empty()) { - if(ImGui::IsItemHovered()) + if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); ImGui::Text(tooltip.data()); @@ -297,7 +302,7 @@ namespace SHADE static void TextLabel(std::string_view const& text, bool sameLine = true) { const ImVec2 textSize = ImGui::CalcTextSize(text.data(), NULL, true); - if(textSize.x > 0.0f) + if (textSize.x > 0.0f) { ImGui::Text(text.data()); ImGui::SameLine(); @@ -310,32 +315,32 @@ namespace SHADE ImGui::BeginGroup(); ImGui::PushID(label.data()); TextLabel(label); - if (ImGui::Checkbox("##", &value)) + bool const changed = ImGui::Checkbox("##", &value); + if (changed) { SHCommandManager::PerformCommand(std::reinterpret_pointer_cast(std::make_shared>(get(), value, set)), false); - return true; } ImGui::PopID(); ImGui::EndGroup(); - if(!tooltip.empty()) + if (!tooltip.empty()) { - if(ImGui::IsItemHovered()) + if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); ImGui::Text(tooltip.data()); ImGui::EndTooltip(); } } - return false; + return changed; } template - static bool RadioButton(std::vector const& label, std::vector const& listTypes, std::function get, std::function set ,std::string_view const& tooltip = {}) + static bool RadioButton(std::vector const& label, std::vector const& listTypes, std::function get, std::function set, std::string_view const& tooltip = {}) { T type = get(); ImGui::BeginGroup(); ImGui::PushID(label.data()); - TextLabel(label); + //TextLabel(label); for (size_t i = 0; i < listTypes.size(); i++) { if (ImGui::RadioButton(label[i].c_str(), type == listTypes[i])) @@ -366,12 +371,11 @@ namespace SHADE ImGui::BeginGroup(); ImGui::PushID(label.data()); TextLabel(label); - if (ImGui::InputText("##", &text, flag, callback, userData)) + bool const changed = ImGui::InputText("##", &text, flag, callback, userData); + if (changed) { if (ImGui::IsItemDeactivatedAfterEdit()) SHCommandManager::PerformCommand(std::reinterpret_pointer_cast(std::make_shared>(get(), text, set)), false); - - return true; } ImGui::PopID(); ImGui::EndGroup(); @@ -384,7 +388,7 @@ namespace SHADE ImGui::EndTooltip(); } } - return false; + return changed; } template @@ -442,9 +446,9 @@ namespace SHADE } ImGui::PopID(); ImGui::EndGroup(); - if(!tooltip.empty()) + if (!tooltip.empty()) { - if(ImGui::IsItemHovered()) + if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); ImGui::Text(tooltip.data()); diff --git a/SHADE_Engine/src/Math/Transform/SHTransformComponent.cpp b/SHADE_Engine/src/Math/Transform/SHTransformComponent.cpp index e56cbc8d..c6068f1a 100644 --- a/SHADE_Engine/src/Math/Transform/SHTransformComponent.cpp +++ b/SHADE_Engine/src/Math/Transform/SHTransformComponent.cpp @@ -14,6 +14,7 @@ #include "SHTransformComponent.h" // Project Headers #include "Math/SHMathHelpers.h" +#include "Reflection/SHReflectionMetadata.h" namespace SHADE { @@ -184,7 +185,7 @@ RTTR_REGISTRATION using namespace rttr; registration::class_("Transform Component") - .property("Translate" , &SHTransformComponent::GetLocalPosition , &SHTransformComponent::SetLocalPosition ) - .property("Rotate" , &SHTransformComponent::GetLocalRotation , select_overload(&SHTransformComponent::SetLocalRotation) ) - .property("Scale" , &SHTransformComponent::GetLocalScale , &SHTransformComponent::SetLocalScale ); + .property("Translate" , &SHTransformComponent::GetLocalPosition , &SHTransformComponent::SetLocalPosition)(metadata(META::tooltip, "Translate")) + .property("Rotate" , &SHTransformComponent::GetLocalRotation , select_overload(&SHTransformComponent::SetLocalRotation))(metadata(META::tooltip, "Rotate")) + .property("Scale" , &SHTransformComponent::GetLocalScale , &SHTransformComponent::SetLocalScale)(metadata(META::tooltip, "Scale")); } \ No newline at end of file From 1c099acccb403fd3bbfd842b9c7c275802b0784a Mon Sep 17 00:00:00 2001 From: Sri Sham Haran Date: Wed, 26 Oct 2022 16:05:52 +0800 Subject: [PATCH 05/44] handle vec2/3/4 that contain values in radians --- .../Inspector/SHEditorComponentView.hpp | 8 ++--- SHADE_Engine/src/Editor/SHEditorWidgets.hpp | 32 ++++++++++++++++--- .../Math/Transform/SHTransformComponent.cpp | 6 ++-- .../src/Reflection/SHReflectionMetadata.h | 1 + 4 files changed, 35 insertions(+), 12 deletions(-) diff --git a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp index 71a31bb8..046dba2f 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp +++ b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp @@ -64,7 +64,7 @@ namespace SHADE { auto const& type = property.get_type(); auto tooltip = property.get_metadata(META::tooltip); - + bool const& isAngleInRad = property.get_metadata(META::angleInRad).is_valid() ? property.get_metadata(META::angleInRad).template get_value() : false; if (type.is_enumeration()) { auto enumAlign = type.get_enumeration(); @@ -185,15 +185,15 @@ namespace SHADE } else if (type == rttr::type::get()) { - SHEditorWidgets::DragVec4(property.get_name().data(), { "X", "Y", "Z", "W" }, [component, property]() {return property.get_value(component).template convert(); }, [component, property](SHVec4 vec) {return property.set_value(component, vec); }, tooltip.is_valid() ? tooltip.template get_value() : std::string()); + SHEditorWidgets::DragVec4(property.get_name().data(), { "X", "Y", "Z", "W" }, [component, property]() {return property.get_value(component).template convert(); }, [component, property](SHVec4 vec) {return property.set_value(component, vec); }, isAngleInRad, tooltip.is_valid() ? tooltip.template get_value() : std::string()); } else if (type == rttr::type::get()) { - SHEditorWidgets::DragVec3(property.get_name().data(), { "X", "Y", "Z" }, [component, property]() {return property.get_value(component).template convert(); }, [component, property](SHVec3 vec) {return property.set_value(component, vec); }, tooltip.is_valid() ? tooltip.template get_value() : std::string()); + SHEditorWidgets::DragVec3(property.get_name().data(), { "X", "Y", "Z" }, [component, property]() {return property.get_value(component).template convert(); }, [component, property](SHVec3 vec) {return property.set_value(component, vec); }, isAngleInRad, tooltip.is_valid() ? tooltip.template get_value() : std::string()); } else if (type == rttr::type::get()) { - SHEditorWidgets::DragVec2(property.get_name().data(), { "X", "Y" }, [component, property]() {return property.get_value(component).template convert(); }, [component, property](SHVec2 vec) {return property.set_value(component, vec); }, tooltip.is_valid() ? tooltip.template get_value() : std::string()); + SHEditorWidgets::DragVec2(property.get_name().data(), { "X", "Y" }, [component, property]() {return property.get_value(component).template convert(); }, [component, property](SHVec2 vec) {return property.set_value(component, vec); }, isAngleInRad, tooltip.is_valid() ? tooltip.template get_value() : std::string()); } } diff --git a/SHADE_Engine/src/Editor/SHEditorWidgets.hpp b/SHADE_Engine/src/Editor/SHEditorWidgets.hpp index 26cac23e..60cd7a86 100644 --- a/SHADE_Engine/src/Editor/SHEditorWidgets.hpp +++ b/SHADE_Engine/src/Editor/SHEditorWidgets.hpp @@ -207,14 +207,22 @@ namespace SHADE } static bool DragVec2(const std::string& label, std::vectorconst& componentLabels, std::function get, - std::function set, std::string_view const& tooltip = {}, float speed = 0.1f, const char* displayFormat = "%.3f", float valueMin = 0.0f, float valueMax = 0.0f, + std::function set, bool const& isAnAngleInRad = false, std::string_view const& tooltip = {}, float speed = 0.1f, const char* displayFormat = "%.3f", float valueMin = 0.0f, float valueMax = 0.0f, ImGuiSliderFlags flags = 0) { SHVec2 values = get(); + if(isAnAngleInRad) + { + values = {SHMath::RadiansToDegrees(values.x), SHMath::RadiansToDegrees(values.y)}; + } bool const changed = DragN(label, componentLabels, { &values.x, &values.y }, speed, displayFormat, valueMin, valueMax, flags); static bool startRecording = false; if (changed) { + if(isAnAngleInRad) + { + values = {SHMath::DegreesToRadians(values.x), SHMath::DegreesToRadians(values.y)}; + } SHCommandManager::PerformCommand(std::reinterpret_pointer_cast(std::make_shared>(get(), values, set)), startRecording); if (!startRecording) startRecording = true; @@ -234,18 +242,24 @@ namespace SHADE } static bool DragVec3(const std::string& label, std::vectorconst& componentLabels, std::function get, - std::function set, std::string_view const& tooltip = {}, float speed = 0.1f, const char* displayFormat = "%.3f", float valueMin = 0.0f, float valueMax = 0.0f, + std::function set, bool const& isAnAngleInRad = false, std::string_view const& tooltip = {}, float speed = 0.1f, const char* displayFormat = "%.3f", float valueMin = 0.0f, float valueMax = 0.0f, ImGuiSliderFlags flags = 0) { SHVec3 values = get(); + if(isAnAngleInRad) + { + values = {SHMath::RadiansToDegrees(values.x), SHMath::RadiansToDegrees(values.y), SHMath::RadiansToDegrees(values.z)}; + } bool isHovered = false; bool const changed = DragN(label, componentLabels, { &values.x, &values.y, &values.z }, speed, displayFormat, valueMin, valueMax, flags, &isHovered); - - static bool startRecording = false; if (changed) { SHVec3 old = get(); + if(isAnAngleInRad) + { + values = {SHMath::DegreesToRadians(values.x), SHMath::DegreesToRadians(values.y), SHMath::DegreesToRadians(values.z)}; + } SHCommandManager::PerformCommand(std::reinterpret_pointer_cast(std::make_shared>(old, values, set)), startRecording); if (!startRecording) startRecording = true; @@ -267,14 +281,22 @@ namespace SHADE } static bool DragVec4(const std::string& label, std::vectorconst& componentLabels, std::function get, - std::function set, std::string_view const& tooltip = {}, float speed = 0.1f, const char* displayFormat = "%.3f", float valueMin = 0.0f, float valueMax = 0.0f, + std::function set, bool const& isAnAngleInRad = false, std::string_view const& tooltip = {}, float speed = 0.1f, const char* displayFormat = "%.3f", float valueMin = 0.0f, float valueMax = 0.0f, ImGuiSliderFlags flags = 0) { SHVec4 values = get(); + if(isAnAngleInRad) + { + values = {SHMath::RadiansToDegrees(values.x), SHMath::RadiansToDegrees(values.y), SHMath::RadiansToDegrees(values.z), SHMath::RadiansToDegrees(values.w)}; + } bool const changed = DragN(label, componentLabels, { &values.x, &values.y, &values.z, &values.w }, speed, displayFormat, valueMin, valueMax, flags); static bool startRecording = false; if (changed) { + if(isAnAngleInRad) + { + values = {SHMath::DegreesToRadians(values.x), SHMath::DegreesToRadians(values.y), SHMath::DegreesToRadians(values.z), SHMath::DegreesToRadians(values.w)}; + } SHCommandManager::PerformCommand(std::reinterpret_pointer_cast(std::make_shared>(get(), values, set)), startRecording); if (!startRecording) startRecording = true; diff --git a/SHADE_Engine/src/Math/Transform/SHTransformComponent.cpp b/SHADE_Engine/src/Math/Transform/SHTransformComponent.cpp index c6068f1a..43742855 100644 --- a/SHADE_Engine/src/Math/Transform/SHTransformComponent.cpp +++ b/SHADE_Engine/src/Math/Transform/SHTransformComponent.cpp @@ -185,7 +185,7 @@ RTTR_REGISTRATION using namespace rttr; registration::class_("Transform Component") - .property("Translate" , &SHTransformComponent::GetLocalPosition , &SHTransformComponent::SetLocalPosition)(metadata(META::tooltip, "Translate")) - .property("Rotate" , &SHTransformComponent::GetLocalRotation , select_overload(&SHTransformComponent::SetLocalRotation))(metadata(META::tooltip, "Rotate")) - .property("Scale" , &SHTransformComponent::GetLocalScale , &SHTransformComponent::SetLocalScale)(metadata(META::tooltip, "Scale")); + .property("Translate" ,&SHTransformComponent::GetLocalPosition ,&SHTransformComponent::SetLocalPosition ) (metadata(META::tooltip, "Translate")) + .property("Rotate" ,&SHTransformComponent::GetLocalRotation ,select_overload(&SHTransformComponent::SetLocalRotation) ) (metadata(META::tooltip, "Rotate"), metadata(META::angleInRad, true)) + .property("Scale" ,&SHTransformComponent::GetLocalScale ,&SHTransformComponent::SetLocalScale ) (metadata(META::tooltip, "Scale")); } \ No newline at end of file diff --git a/SHADE_Engine/src/Reflection/SHReflectionMetadata.h b/SHADE_Engine/src/Reflection/SHReflectionMetadata.h index 0cc6d8a5..b4dc009c 100644 --- a/SHADE_Engine/src/Reflection/SHReflectionMetadata.h +++ b/SHADE_Engine/src/Reflection/SHReflectionMetadata.h @@ -7,5 +7,6 @@ namespace SHADE constexpr const char* min = "MIN"; constexpr const char* max = "MAX"; constexpr const char* tooltip = "tooltip"; + constexpr const char* angleInRad = "angleInRad"; } } From 1018454f2e9f3dd2c2525fd0b4c51b42cac9ab59 Mon Sep 17 00:00:00 2001 From: Sri Sham Haran Date: Wed, 26 Oct 2022 20:21:47 +0800 Subject: [PATCH 06/44] Add Win32 MessageBox Add Prefab Manager --- Assets/Editor/Layouts/UserLayout.ini | 62 ------------------- .../Serialization/Prefab/SHPrefabManager.cpp | 56 +++++++++++++++++ .../Serialization/Prefab/SHPrefabManager.h | 28 +++++++++ SHADE_Engine/src/Tools/Dialog/SHWinDialog.cpp | 31 ++++++++++ SHADE_Engine/src/Tools/Dialog/SHWinDialog.h | 35 +++++++++++ 5 files changed, 150 insertions(+), 62 deletions(-) delete mode 100644 Assets/Editor/Layouts/UserLayout.ini create mode 100644 SHADE_Engine/src/Serialization/Prefab/SHPrefabManager.cpp create mode 100644 SHADE_Engine/src/Serialization/Prefab/SHPrefabManager.h create mode 100644 SHADE_Engine/src/Tools/Dialog/SHWinDialog.cpp create mode 100644 SHADE_Engine/src/Tools/Dialog/SHWinDialog.h diff --git a/Assets/Editor/Layouts/UserLayout.ini b/Assets/Editor/Layouts/UserLayout.ini deleted file mode 100644 index e27f5cca..00000000 --- a/Assets/Editor/Layouts/UserLayout.ini +++ /dev/null @@ -1,62 +0,0 @@ -[Window][MainStatusBar] -Pos=0,1060 -Size=1920,20 -Collapsed=0 - -[Window][SHEditorMenuBar] -Pos=0,48 -Size=1920,1012 -Collapsed=0 - -[Window][Hierarchy Panel] -Pos=0,142 -Size=494,690 -Collapsed=0 -DockId=0x00000007,0 - -[Window][Debug##Default] -Pos=60,60 -Size=400,400 -Collapsed=0 - -[Window][Inspector] -Pos=1649,48 -Size=271,1012 -Collapsed=0 -DockId=0x00000006,0 - -[Window][Profiler] -Pos=0,48 -Size=494,92 -Collapsed=0 -DockId=0x00000003,0 - -[Window][Viewport] -Pos=648,48 -Size=2519,1319 -Collapsed=0 -DockId=0x00000002,0 - -[Window][ Viewport] -Pos=496,48 -Size=1151,1012 -Collapsed=0 -DockId=0x00000002,0 - -[Window][ Asset Browser] -Pos=0,834 -Size=494,226 -Collapsed=0 -DockId=0x00000008,0 - -[Docking][Data] -DockSpace ID=0xC5C9B8AB Window=0xBE4044E9 Pos=8,79 Size=1920,1012 Split=X - DockNode ID=0x00000005 Parent=0xC5C9B8AB SizeRef=1992,1036 Split=X - DockNode ID=0x00000001 Parent=0x00000005 SizeRef=494,1036 Split=Y Selected=0x1E6EB881 - DockNode ID=0x00000003 Parent=0x00000001 SizeRef=225,94 Selected=0x1E6EB881 - DockNode ID=0x00000004 Parent=0x00000001 SizeRef=225,940 Split=Y Selected=0xE096E5AE - DockNode ID=0x00000007 Parent=0x00000004 SizeRef=494,690 Selected=0xE096E5AE - DockNode ID=0x00000008 Parent=0x00000004 SizeRef=494,226 Selected=0xB128252A - DockNode ID=0x00000002 Parent=0x00000005 SizeRef=1151,1036 CentralNode=1 Selected=0xB41284E7 - DockNode ID=0x00000006 Parent=0xC5C9B8AB SizeRef=271,1036 Selected=0xE7039252 - diff --git a/SHADE_Engine/src/Serialization/Prefab/SHPrefabManager.cpp b/SHADE_Engine/src/Serialization/Prefab/SHPrefabManager.cpp new file mode 100644 index 00000000..8ab098b8 --- /dev/null +++ b/SHADE_Engine/src/Serialization/Prefab/SHPrefabManager.cpp @@ -0,0 +1,56 @@ +#include "SHpch.h" +#include "SHPrefabManager.h" + +namespace SHADE +{ + SHPrefabManager::PrefabMap SHPrefabManager::prefabMap{}; + + void SHPrefabManager::AddPrefab(AssetID const& prefabAssetID) noexcept + { + prefabMap.insert({ prefabAssetID, {} }); + } + + void SHPrefabManager::RemovePrefab(AssetID const& prefabAssetID) noexcept + { + prefabMap.erase(prefabAssetID); + } + + void SHPrefabManager::ClearPrefab(AssetID const& prefabAssetID) noexcept + { + if (prefabMap.contains(prefabAssetID)) + { + prefabMap[prefabAssetID].clear(); + } + } + + void SHPrefabManager::UpdateAllPrefabEntities(AssetID const& prefabAssetID) noexcept + { + //Loop through all entities and deserialize new data + } + + void SHPrefabManager::AddEntity(AssetID const& prefabAssetID, EntityID const& eid) noexcept + { + if (prefabMap.contains(prefabAssetID)) + { + prefabMap[prefabAssetID].insert(eid); + } + } + + void SHPrefabManager::RemoveEntity(AssetID const& prefabAssetID, EntityID const& eid) noexcept + { + if (prefabMap.contains(prefabAssetID)) + { + prefabMap[prefabAssetID].erase(eid); + } + } + + void SHPrefabManager::Clear() noexcept + { + prefabMap.clear(); + } + + bool SHPrefabManager::Empty() noexcept + { + return prefabMap.empty(); + } +} diff --git a/SHADE_Engine/src/Serialization/Prefab/SHPrefabManager.h b/SHADE_Engine/src/Serialization/Prefab/SHPrefabManager.h new file mode 100644 index 00000000..37c317ed --- /dev/null +++ b/SHADE_Engine/src/Serialization/Prefab/SHPrefabManager.h @@ -0,0 +1,28 @@ +#pragma once + +#include "Assets/SHAssetMacros.h" +#include "ECS_Base/SHECSMacros.h" +#include +#include + + +namespace SHADE +{ + class SHPrefabManager + { + public: + using PrefabMap = std::unordered_map>; + + static void AddPrefab(AssetID const& prefabAssetID) noexcept; + static void RemovePrefab(AssetID const& prefabAssetID) noexcept; + static void ClearPrefab(AssetID const& prefabAssetID) noexcept; + static void UpdateAllPrefabEntities(AssetID const& prefabAssetID) noexcept; + static void AddEntity(AssetID const& prefabAssetID, EntityID const& eid) noexcept; + static void RemoveEntity(AssetID const& prefabAssetID, EntityID const& eid) noexcept; + static void Clear() noexcept; + static bool Empty() noexcept; + + private: + static PrefabMap prefabMap; + }; +} diff --git a/SHADE_Engine/src/Tools/Dialog/SHWinDialog.cpp b/SHADE_Engine/src/Tools/Dialog/SHWinDialog.cpp new file mode 100644 index 00000000..a2900401 --- /dev/null +++ b/SHADE_Engine/src/Tools/Dialog/SHWinDialog.cpp @@ -0,0 +1,31 @@ +#include "SHpch.h" +#include "SHWinDialog.h" +#include +#include + +namespace SHADE +{ + void SHWinDialog::DisplayMessageBox(MessageBoxType const& messageBoxType, std::string const& title, std::string const& text) + { + if(messageBoxType == MessageBoxType::MB_MAX) + return; + + UINT flags = MB_APPLMODAL | MB_SETFOREGROUND | MB_OK; + flags |= static_cast(messageBoxType); + + const std::wstring wTitle(title.begin(), title.end()); + const std::wstring wText(text.begin(), text.end()); + + MessageBox(GetDesktopWindow(), wText.data(), wTitle.data(), flags); + } + + std::vector SHWinDialog::DisplayOpenDialog(OpenSaveConfig const& openSaveConfig) + { + return {}; + } + + std::vector SHWinDialog::DisplaySaveAsDialog(OpenSaveConfig const& openSaveConfig) + { + return{}; + } +} diff --git a/SHADE_Engine/src/Tools/Dialog/SHWinDialog.h b/SHADE_Engine/src/Tools/Dialog/SHWinDialog.h new file mode 100644 index 00000000..0c11f768 --- /dev/null +++ b/SHADE_Engine/src/Tools/Dialog/SHWinDialog.h @@ -0,0 +1,35 @@ +#pragma once +#include +#include + +namespace SHADE +{ + //https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-messagebox + enum class MessageBoxType + { + MB_ERROR = 0x00000010L, + MB_QUESTION = 0x00000020L, + MB_WARNING = 0x00000030L, + MB_INFO = 0x00000040L, + MB_MAX = 0 + }; + + struct OpenSaveConfig + { + using Extension = std::string; + using Extensions = std::vector; + using FileTypeDesc = std::pair; + using FilterList = std::vector; + + std::string title = "Open"; + bool openFolders = false; + FilterList filterList{}; + }; + + struct SHWinDialog + { + static void DisplayMessageBox(MessageBoxType const& messageBoxType, std::string const& title, std::string const& text); + static std::vector DisplayOpenDialog(OpenSaveConfig const& openSaveConfig); + static std::vector DisplaySaveAsDialog(OpenSaveConfig const& openSaveConfig); + }; +} From 3518004266bdcce320934c1884a7a006e86bb0cc Mon Sep 17 00:00:00 2001 From: Sri Sham Haran Date: Wed, 26 Oct 2022 21:06:09 +0800 Subject: [PATCH 07/44] Add Open File DIalog (WIP) --- SHADE_Engine/src/Tools/Dialog/SHWinDialog.cpp | 40 +++++++++++++++++++ SHADE_Engine/src/Tools/Dialog/SHWinDialog.h | 1 + 2 files changed, 41 insertions(+) diff --git a/SHADE_Engine/src/Tools/Dialog/SHWinDialog.cpp b/SHADE_Engine/src/Tools/Dialog/SHWinDialog.cpp index a2900401..bd13801a 100644 --- a/SHADE_Engine/src/Tools/Dialog/SHWinDialog.cpp +++ b/SHADE_Engine/src/Tools/Dialog/SHWinDialog.cpp @@ -21,6 +21,46 @@ namespace SHADE std::vector SHWinDialog::DisplayOpenDialog(OpenSaveConfig const& openSaveConfig) { + const HWND hwnd = GetDesktopWindow(); + HRESULT hResult = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); + if(SUCCEEDED(hResult)) + { + IFileOpenDialog* pFileOpen; + + //Create Dialog object + hResult = CoCreateInstance(CLSID_FileOpenDialog, nullptr, CLSCTX_ALL, IID_IFileOpenDialog, reinterpret_cast(pFileOpen)); + + if(SUCCEEDED(hResult)) + { + //Show the open dialog box + hResult = pFileOpen->Show(hwnd); + + //Get file name from the dialoh box + if(SUCCEEDED(hResult)) + { + if(openSaveConfig.openMultiple) + { + IShellItemArray* pItemArray; + hResult = pFileOpen->GetResults(&pItemArray); + if(SUCCEEDED(hResult)) + { + + } + } + else + { + IShellItem* pItem; + hResult = pFileOpen->GetResult(&pItem); + if(SUCCEEDED(hResult)) + { + PWSTR pszFilePath; + hResult = pItem->GetDisplayName(SIGDN_FILESYSPATH, &pszFilePath); + } + } + + } + } + } return {}; } diff --git a/SHADE_Engine/src/Tools/Dialog/SHWinDialog.h b/SHADE_Engine/src/Tools/Dialog/SHWinDialog.h index 0c11f768..02fe07b9 100644 --- a/SHADE_Engine/src/Tools/Dialog/SHWinDialog.h +++ b/SHADE_Engine/src/Tools/Dialog/SHWinDialog.h @@ -23,6 +23,7 @@ namespace SHADE std::string title = "Open"; bool openFolders = false; + bool openMultiple = false; FilterList filterList{}; }; From 6e9f54987f2ec25d0a04a35587447684881a766c Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Wed, 26 Oct 2022 22:40:04 +0800 Subject: [PATCH 08/44] Prepared light global desc set layout data and render graph resources - Fixed material padding - Lighting desc sets now have a buffer at binding 0 to store light counts. - Added position, normals, albedo resources in render graph --- .../Graphics/MiddleEnd/Batching/SHBatch.cpp | 8 +- .../GlobalData/SHGraphicsGlobalData.cpp | 31 ++++---- .../MiddleEnd/Interface/SHGraphicsConstants.h | 32 ++------ .../MiddleEnd/Interface/SHGraphicsSystem.cpp | 40 ++++++++-- .../MiddleEnd/Interface/SHRenderable.cpp | 2 +- .../MiddleEnd/Lights/SHLightingSubSystem.cpp | 71 +++++++++++++----- .../MiddleEnd/Lights/SHLightingSubSystem.h | 19 ++++- TempShaderFolder/DeferredCompositeCs.glsl | 30 ++++++++ TempShaderFolder/DeferredCompositeCs.spv | Bin 0 -> 1716 bytes TempShaderFolder/TestCubeFs.glsl | 17 +++-- TempShaderFolder/TestCubeFs.spv | Bin 2300 -> 2536 bytes TempShaderFolder/TestCubeVs.glsl | 12 ++- TempShaderFolder/TestCubeVs.spv | Bin 2492 -> 2684 bytes 13 files changed, 175 insertions(+), 87 deletions(-) create mode 100644 TempShaderFolder/DeferredCompositeCs.glsl create mode 100644 TempShaderFolder/DeferredCompositeCs.spv diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Batching/SHBatch.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Batching/SHBatch.cpp index 09fde60f..f5c51914 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Batching/SHBatch.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Batching/SHBatch.cpp @@ -180,7 +180,8 @@ namespace SHADE { SHLOG_WARNING("[SHBatch] Entity with a missing SHRenderable found!"); } - propsCurrPtr += singleMatPropAlignedSize; + //propsCurrPtr += singleMatPropAlignedSize; + propsCurrPtr += singleMatPropSize; } // Transfer to GPU @@ -302,7 +303,7 @@ namespace SHADE { singleMatPropSize = SHADER_INFO->GetBytesRequired(); singleMatPropAlignedSize = device->PadSSBOSize(static_cast(singleMatPropSize)); - matPropTotalBytes = numTotalElements * singleMatPropAlignedSize; + matPropTotalBytes = numTotalElements * singleMatPropSize; if (matPropsDataSize < matPropTotalBytes) { matPropsData.reset(new char[matPropTotalBytes]); @@ -361,7 +362,8 @@ namespace SHADE { SHLOG_WARNING("[SHBatch] Entity with a missing SHRenderable found!"); } - propsCurrPtr += singleMatPropAlignedSize; + //propsCurrPtr += singleMatPropAlignedSize; + propsCurrPtr += singleMatPropSize; } } } diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/GlobalData/SHGraphicsGlobalData.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/GlobalData/SHGraphicsGlobalData.cpp index 0f1658f3..d5fb81bd 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/GlobalData/SHGraphicsGlobalData.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/GlobalData/SHGraphicsGlobalData.cpp @@ -47,36 +47,35 @@ namespace SHADE // For global data (generic data and textures) Handle staticGlobalLayout = logicalDevice->CreateDescriptorSetLayout(SHGraphicsConstants::DescriptorSetIndex::STATIC_GLOBALS,{ genericDataBinding, texturesBinding }); + std::vector lightBindings{}; - for (uint32_t i = 0; i < SHUtilities::ToUnderlying(SH_LIGHT_TYPE::NUM_TYPES); ++i) + + // This is the binding we use to count the lights (binding 0) + lightBindings.push_back(SHVkDescriptorSetLayout::Binding + { + .Type = vk::DescriptorType::eUniformBufferDynamic, + .Stage = vk::ShaderStageFlagBits::eCompute, + .BindPoint = 0, + .DescriptorCount = 1, + + }); + + for (uint32_t i = 1; i <= SHUtilities::ToUnderlying(SH_LIGHT_TYPE::NUM_TYPES); ++i) { lightBindings.push_back (SHVkDescriptorSetLayout::Binding { .Type = vk::DescriptorType::eStorageBufferDynamic, - .Stage = vk::ShaderStageFlagBits::eFragment, + .Stage = vk::ShaderStageFlagBits::eCompute, .BindPoint = i, .DescriptorCount = 1, }); } - //SHVkDescriptorSetLayout::Binding pointLightBinding - //{ - // .Type = vk::DescriptorType::eStorageBufferDynamic, - // .Stage = vk::ShaderStageFlagBits::eFragment, - // .BindPoint = SHGraphicsConstants::DescriptorSetBindings::POINT_LIGHT_DATA, - // .DescriptorCount = 1, - //}; - //SHVkDescriptorSetLayout::Binding spotLightBinding - //{ - // .Type = vk::DescriptorType::eStorageBufferDynamic, - // .Stage = vk::ShaderStageFlagBits::eFragment, - // .BindPoint = SHGraphicsConstants::DescriptorSetBindings::SPOT_LIGHT_DATA, - // .DescriptorCount = 1, - //}; // For Dynamic global data (lights) Handle dynamicGlobalLayout = logicalDevice->CreateDescriptorSetLayout(SHGraphicsConstants::DescriptorSetIndex::DYNAMIC_GLOBALS, lightBindings); + SHVkDescriptorSetLayout::Binding cameraDataBinding { .Type = vk::DescriptorType::eUniformBufferDynamic, diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsConstants.h b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsConstants.h index 4c3ba7f9..a39ec10e 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsConstants.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsConstants.h @@ -94,32 +94,14 @@ namespace SHADE /***************************************************************************/ static constexpr uint32_t IMAGE_AND_SAMPLERS_DATA = 1; - ///***************************************************************************/ - ///*! - // \brief - // DescriptorSet binding for directional lights. + /***************************************************************************/ + /*! + \brief + DescriptorSet binding for combined image sampler data. - //*/ - ///***************************************************************************/ - //static constexpr uint32_t DIRECTIONAL_LIGHT_DATA = 0; - - ///***************************************************************************/ - ///*! - // \brief - // DescriptorSet binding for directional lights. - - //*/ - ///***************************************************************************/ - //static constexpr uint32_t POINT_LIGHT_DATA = 1; - - ///***************************************************************************/ - ///*! - // \brief - // DescriptorSet binding for directional lights. - - //*/ - ///***************************************************************************/ - //static constexpr uint32_t SPOT_LIGHT_DATA = 2; + */ + /***************************************************************************/ + static constexpr uint32_t LIGHTING_COUNT = 0; /***************************************************************************/ /*! diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp index 9b984a4b..dfa4e41e 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp @@ -127,15 +127,20 @@ namespace SHADE shaderSourceLibrary.LoadShader(2, "KirschCs.glsl", SH_SHADER_TYPE::COMPUTE, true); shaderSourceLibrary.LoadShader(3, "PureCopyCs.glsl", SH_SHADER_TYPE::COMPUTE, true); + shaderSourceLibrary.LoadShader(4, "DeferredCompositeCs.glsl", SH_SHADER_TYPE::COMPUTE, true); + + shaderModuleLibrary.ImportFromSourceLibrary(device, shaderSourceLibrary); auto cubeVS = shaderModuleLibrary.GetShaderModule("TestCubeVs.glsl"); auto cubeFS = shaderModuleLibrary.GetShaderModule("TestCubeFs.glsl"); auto greyscale = shaderModuleLibrary.GetShaderModule("KirschCs.glsl"); auto pureCopy = shaderModuleLibrary.GetShaderModule("PureCopyCs.glsl"); + auto deferredComposite = shaderModuleLibrary.GetShaderModule("DeferredCompositeCs.glsl"); cubeVS->Reflect(); cubeFS->Reflect(); greyscale->Reflect(); pureCopy->Reflect(); + deferredComposite->Reflect(); } void SHGraphicsSystem::InitSceneRenderGraph(void) noexcept @@ -176,26 +181,45 @@ namespace SHADE // Initialize world render graph worldRenderGraph->Init(device, swapchain); - worldRenderGraph->AddResource("Scene Pre-Process", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second); - worldRenderGraph->AddResource("Scene", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second); + worldRenderGraph->AddResource("Position", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second); + worldRenderGraph->AddResource("Normals", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second); + worldRenderGraph->AddResource("Albedo", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second); worldRenderGraph->AddResource("Depth Buffer", { SH_ATT_DESC_TYPE_FLAGS::DEPTH_STENCIL }, windowDims.first, windowDims.second, vk::Format::eD32SfloatS8Uint); worldRenderGraph->AddResource("Entity ID", { SH_ATT_DESC_TYPE_FLAGS::COLOR }, windowDims.first, windowDims.second, vk::Format::eR32Uint, 1, vk::ImageUsageFlagBits::eTransferSrc); worldRenderGraph->AddResource("Light Layer Indices", { SH_ATT_DESC_TYPE_FLAGS::COLOR }, windowDims.first, windowDims.second, vk::Format::eR32Uint, 1, vk::ImageUsageFlagBits::eTransferSrc); + worldRenderGraph->AddResource("Scene", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second); + + auto gBufferNode = worldRenderGraph->AddNode("G-Buffer", + { + "Position", + "Entity ID", + "Light Layer Indices", + "Normals", + "Albedo", + "Depth Buffer", + "Scene" + }, + {}); // no predecessors - auto gBufferNode = worldRenderGraph->AddNode("G-Buffer", { "Light Layer Indices", "Entity ID", "Depth Buffer", "Scene", "Scene Pre-Process"}, {}); // no predecessors auto gBufferSubpass = gBufferNode->AddSubpass("G-Buffer Write"); - gBufferSubpass->AddColorOutput("Scene Pre-Process"); + gBufferSubpass->AddColorOutput("Position"); gBufferSubpass->AddColorOutput("Entity ID"); gBufferSubpass->AddColorOutput("Light Layer Indices"); + gBufferSubpass->AddColorOutput("Normals"); + gBufferSubpass->AddColorOutput("Albedo"); gBufferSubpass->AddDepthOutput("Depth Buffer", SH_ATT_DESC_TYPE_FLAGS::DEPTH_STENCIL); //// kirsch //auto kirschShader = shaderModuleLibrary.GetShaderModule("KirschCs.glsl"); - //gBufferNode->AddNodeCompute(kirschShader, { "Scene Pre-Process", "Scene" }); + //gBufferNode->AddNodeCompute(kirschShader, { "Position", "Scene" }); - // copy - auto pureCopyShader = shaderModuleLibrary.GetShaderModule("PureCopyCs.glsl"); - gBufferNode->AddNodeCompute(pureCopyShader, { "Scene Pre-Process", "Scene" }); + //// copy + //auto pureCopyShader = shaderModuleLibrary.GetShaderModule("PureCopyCs.glsl"); + //gBufferNode->AddNodeCompute(pureCopyShader, { "Position", "Scene" }); + + // deferred composite + auto deferredCompositeShader = shaderModuleLibrary.GetShaderModule("DeferredCompositeCs.glsl"); + gBufferNode->AddNodeCompute(deferredCompositeShader, { "Albedo", "Scene" }); auto dummyNode = worldRenderGraph->AddNode("Dummy Pass", { "Scene" }, {"G-Buffer"}); // no predecessors diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHRenderable.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHRenderable.cpp index 7c4d0bb9..c935194f 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHRenderable.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHRenderable.cpp @@ -28,7 +28,7 @@ namespace SHADE material = {}; oldMaterial = {}; - lightLayer = 0; + lightLayer = 1; } void SHRenderable::OnDestroy() diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp index 8d9efe54..a22fb662 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp @@ -76,8 +76,8 @@ namespace SHADE // boilerplate intermediateData = nullptr; - // initialize alignment - lightDataAlignmentSize = logicalDevice->PadSSBOSize(GetLightTypeSize(type)); + // Get data required for struct + lightDataSize = GetLightTypeSize(type); // So create some data! Expand(logicalDevice); @@ -94,7 +94,7 @@ namespace SHADE /***************************************************************************/ void SHLightingSubSystem::PerTypeData::Expand(Handle logicalDevice) noexcept { - if (lightDataAlignmentSize == 0) + if (lightDataSize == 0) { SHLOG_ERROR ("One of the types of lights have not been accounted for. Make sure lightDataAlignmentSize is not nullptr."); return; @@ -111,10 +111,12 @@ namespace SHADE numLights = 0; // Initialize the data for lights - intermediateData = std::make_unique(lightDataAlignmentSize * maxLights); + intermediateData = std::make_unique(lightDataSize * maxLights); + + lightDataAlignedSize = logicalDevice->PadSSBOSize(lightDataSize * maxLights); // We want to initialize 3 times the amount of data required. - dataBuffer = logicalDevice->CreateBuffer(maxLights * lightDataAlignmentSize * SHGraphicsConstants::NUM_FRAME_BUFFERS, nullptr, maxLights * lightDataAlignmentSize * SHGraphicsConstants::NUM_FRAME_BUFFERS, vk::BufferUsageFlagBits::eStorageBuffer, VMA_MEMORY_USAGE_AUTO, VMA_ALLOCATION_CREATE_MAPPED_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT); + dataBuffer = logicalDevice->CreateBuffer(lightDataAlignedSize * SHGraphicsConstants::NUM_FRAME_BUFFERS, nullptr, lightDataAlignedSize * SHGraphicsConstants::NUM_FRAME_BUFFERS, vk::BufferUsageFlagBits::eStorageBuffer, VMA_MEMORY_USAGE_AUTO, VMA_ALLOCATION_CREATE_MAPPED_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT); } else { @@ -122,24 +124,27 @@ namespace SHADE uint32_t const OLD_MAX_LIGHTS = maxLights; // before we increase the number of lights, create space to store old data. - std::unique_ptr oldData = std::make_unique(lightDataAlignmentSize * OLD_MAX_LIGHTS); + std::unique_ptr oldData = std::make_unique(lightDataSize * OLD_MAX_LIGHTS); // copy data over. - std::memcpy (oldData.get(), intermediateData.get(), lightDataAlignmentSize * OLD_MAX_LIGHTS); + std::memcpy (oldData.get(), intermediateData.get(), lightDataSize * OLD_MAX_LIGHTS); // now we start to expand.... // double space for lights maxLights *= 2; + // calculate total + padding + lightDataAlignedSize = logicalDevice->PadSSBOSize(lightDataSize * maxLights); + // destroy old data and initialize container for double the amount of data. - intermediateData = std::make_unique(lightDataAlignmentSize * maxLights); + intermediateData = std::make_unique(lightDataSize * maxLights); // copy old data to new container - std::memcpy(intermediateData.get(), oldData.get(), lightDataAlignmentSize * OLD_MAX_LIGHTS); + std::memcpy(intermediateData.get(), oldData.get(), lightDataSize * OLD_MAX_LIGHTS); // Resize the GPU buffer. TODO: Replace with Resize no copy here - dataBuffer->ResizeReplace(maxLights * lightDataAlignmentSize * SHGraphicsConstants::NUM_FRAME_BUFFERS, oldData.get(), lightDataAlignmentSize * OLD_MAX_LIGHTS); + dataBuffer->ResizeReplace(maxLights * lightDataAlignedSize * SHGraphicsConstants::NUM_FRAME_BUFFERS, oldData.get(), lightDataAlignedSize * OLD_MAX_LIGHTS); } @@ -187,7 +192,12 @@ namespace SHADE uint32_t SHLightingSubSystem::PerTypeData::GetAlignmentSize(void) const noexcept { - return lightDataAlignmentSize; + return lightDataAlignedSize; + } + + uint32_t SHLightingSubSystem::PerTypeData::GetDataSize(void) const noexcept + { + return lightDataSize; } uint32_t SHLightingSubSystem::PerTypeData::GetNumLights(void) const noexcept @@ -231,7 +241,7 @@ namespace SHADE // Now that the container is big enough, bind the new light // Get address of write location - void* writeLocation = reinterpret_cast(intermediateData.get()) + (lightDataAlignmentSize * numLights); + void* writeLocation = reinterpret_cast(intermediateData.get()) + (lightDataSize * numLights); // Write the light data to address WriteLightToAddress(writeLocation, unboundLight); @@ -257,7 +267,7 @@ namespace SHADE /***************************************************************************/ void SHLightingSubSystem::PerTypeData::ModifyLight(SHLightComponent* lightComp) noexcept { - void* writeLocation = reinterpret_cast(intermediateData.get()) + (lightDataAlignmentSize * lightComp->GetIndexInBuffer()); + void* writeLocation = reinterpret_cast(intermediateData.get()) + (lightDataSize * lightComp->GetIndexInBuffer()); WriteLightToAddress(writeLocation, lightComp); } @@ -266,7 +276,7 @@ namespace SHADE if (intermediateData) { // we want to write to the offset of the current frame - dataBuffer->WriteToMemory(intermediateData.get(), lightDataAlignmentSize * numLights, 0, lightDataAlignmentSize * maxLights * frameIndex); + dataBuffer->WriteToMemory(intermediateData.get(), lightDataSize * numLights, 0, lightDataSize * maxLights * frameIndex); } } @@ -287,12 +297,12 @@ namespace SHADE // We bind the buffer with the correct desc set binding lightingDataDescSet->ModifyWriteDescBuffer(SHGraphicsConstants::DescriptorSetIndex::DYNAMIC_GLOBALS, - binding, + binding + 1, // we want to +1 here because the first binding is reserved for count { &buffer, 1 }, 0, - perTypeData[binding].GetAlignmentSize() * perTypeData[binding].GetMaxLights()); + perTypeData[binding].GetDataSize() * perTypeData[binding].GetMaxLights()); - lightingDataDescSet->UpdateDescriptorSetBuffer(SHGraphicsConstants::DescriptorSetIndex::DYNAMIC_GLOBALS, binding); + lightingDataDescSet->UpdateDescriptorSetBuffer(SHGraphicsConstants::DescriptorSetIndex::DYNAMIC_GLOBALS, binding + 1); // +1 here, same reason. see above } /***************************************************************************/ @@ -307,11 +317,13 @@ namespace SHADE { for (uint32_t i = 0; i < SHGraphicsConstants::NUM_FRAME_BUFFERS; ++i) { - for (uint32_t j = 0; j < dynamicOffsets.size(); ++j) + dynamicOffsets[i][0] = i * lightCountsAlignedSize; + // Even if the first binding is a count, we want to account for that too + for (uint32_t j = 1; j < static_cast(dynamicOffsets.size()); ++j) { auto const& typeData = perTypeData[j]; { - dynamicOffsets[i][j] = j * typeData.GetAlignmentSize() * typeData.GetMaxLights(); + dynamicOffsets[i][j] = j * typeData.GetAlignmentSize(); } } } @@ -346,11 +358,23 @@ namespace SHADE // initialize all the data first. We add more lights here as we add more types. perTypeData[i].InitializeData(logicalDevice, static_cast(i)); UpdateDescSet(i); + + // no lights at first + lightCountsData[i] = 0; } + + lightCountsAlignedSize = sizeof (uint32_t) * NUM_LIGHT_TYPES; + lightCountsAlignedSize = logicalDevice->PadUBOSize(lightCountsAlignedSize); + + // Create the GPU buffer to hold light count + lightCountsBuffer = logicalDevice->CreateBuffer(lightCountsAlignedSize * SHGraphicsConstants::NUM_FRAME_BUFFERS, nullptr, lightCountsAlignedSize * SHGraphicsConstants::NUM_FRAME_BUFFERS, vk::BufferUsageFlagBits::eUniformBuffer, VMA_MEMORY_USAGE_AUTO, VMA_ALLOCATION_CREATE_MAPPED_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT); + + lightingDataDescSet->ModifyWriteDescBuffer(SHGraphicsConstants::DescriptorSetIndex::DYNAMIC_GLOBALS, SHGraphicsConstants::DescriptorSetBindings::LIGHTING_COUNT, {&lightCountsBuffer, 1}, 0, sizeof (uint32_t) * NUM_LIGHT_TYPES); + lightingDataDescSet->UpdateDescriptorSetBuffer(SHGraphicsConstants::DescriptorSetIndex::DYNAMIC_GLOBALS, SHGraphicsConstants::DescriptorSetBindings::LIGHTING_COUNT); for (uint32_t i = 0; i < SHGraphicsConstants::NUM_FRAME_BUFFERS; ++i) { - dynamicOffsets[i].resize(NUM_LIGHT_TYPES); + dynamicOffsets[i].resize(NUM_LIGHT_TYPES + 1); // +1 for the count } } @@ -366,6 +390,8 @@ namespace SHADE /***************************************************************************/ void SHLightingSubSystem::Run(Handle cmdBuffer, uint32_t frameIndex) noexcept { + static uint32_t constexpr NUM_LIGHT_TYPES = SHUtilities::ToUnderlying(SH_LIGHT_TYPE::NUM_TYPES); + auto& lightComps = SHComponentManager::GetDense(); bool expanded = false; for (auto& light : lightComps) @@ -377,6 +403,9 @@ namespace SHADE if (!light.GetBound()) { perTypeData[enumValue].AddLight(logicalDevice, &light, expanded); + + // add to light count + ++lightCountsData[enumValue]; } // if there was modification to the light data @@ -396,6 +425,8 @@ namespace SHADE data.WriteToGPU(frameIndex); } + lightCountsBuffer->WriteToMemory(lightCountsData.data(), lightCountsData.size() * sizeof (uint32_t), 0, lightCountsAlignedSize * frameIndex); + // If any of the buffers got expanded, the descriptor set is invalid because the expanded buffer // is a new buffer. If some expansion was detected, update descriptor sets. if (expanded) diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.h b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.h index e5336b4e..6c974730 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.h @@ -17,7 +17,7 @@ namespace SHADE class SHVkCommandBuffer; // Represents how the data will be interpreted in GPU. we want to copy to a container of these before passing to GPU. - struct SHDirectionalLightData + struct SHDirectionalLightData { //! Direction of the light SHVec3 direction; @@ -53,8 +53,11 @@ namespace SHADE //! Capacity of the container. uint32_t maxLights; - //! SSBOs need to be aligned. This is to pad lighting structs - uint32_t lightDataAlignmentSize; + //! SSBOs need to be aligned. This is to pad descriptor offset + uint32_t lightDataAlignedSize; + + //! size needed to store 1 struct object + uint32_t lightDataSize; //! type of the light. Will be used later when we want to expand SH_LIGHT_TYPE lightType; @@ -87,6 +90,7 @@ namespace SHADE static uint32_t GetLightTypeSize (SH_LIGHT_TYPE type) noexcept; Handle GetDataBuffer (void) const noexcept; uint32_t GetAlignmentSize (void) const noexcept; + uint32_t GetDataSize (void) const noexcept; uint32_t GetNumLights (void) const noexcept; uint32_t GetMaxLights (void) const noexcept; }; @@ -105,6 +109,15 @@ namespace SHADE //! Container to store dynamic offsets for binding descriptor sets std::array, static_cast(SHGraphicsConstants::NUM_FRAME_BUFFERS)> dynamicOffsets; + //! holds the data that represents how many lights are in the scene + std::array(SH_LIGHT_TYPE::NUM_TYPES)> lightCountsData; + + //! GPU buffer to hold lightCountData + Handle lightCountsBuffer; + + //! For padding in the buffer + uint32_t lightCountsAlignedSize; + /*-----------------------------------------------------------------------*/ /* PRIVATE MEMBER FUNCTIONS */ /*-----------------------------------------------------------------------*/ diff --git a/TempShaderFolder/DeferredCompositeCs.glsl b/TempShaderFolder/DeferredCompositeCs.glsl new file mode 100644 index 00000000..354a8954 --- /dev/null +++ b/TempShaderFolder/DeferredCompositeCs.glsl @@ -0,0 +1,30 @@ +#version 450 + +struct DirectionalLightStruct +{ + vec3 direction; + uint isActive; + uint cullingMask; + vec4 diffuseColor; +}; + +layout(local_size_x = 16, local_size_y = 16) in; +layout(set = 4, binding = 0, rgba8) uniform image2D inputImage; +layout(set = 4, binding = 1, rgba8) uniform image2D targetImage; + +layout(set = 1, binding = 0) buffer DirectionalLightData +{ + DirectionalLightStruct dLightData[]; +} DirLightData; + +void main() +{ + // convenient variables + ivec2 globalThread = ivec2(gl_GlobalInvocationID); + + vec3 color = imageLoad (inputImage, globalThread).rgb; + + // store result into result image + imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(color, 1.0f)); + +} \ No newline at end of file diff --git a/TempShaderFolder/DeferredCompositeCs.spv b/TempShaderFolder/DeferredCompositeCs.spv new file mode 100644 index 0000000000000000000000000000000000000000..679dc135f5f556eb95565c51c1c9f1c2aca8821a GIT binary patch literal 1716 zcmZ9MYflqF6ov=dLID900dL@zs;FSSp)oOPjF`1aO)>brS++~rxa>CVmc+yl{x*M= zUrc!{Tj=H15rizhIa zOvw`AEQ?c-E=$gWIK{Cjxhx!P#qP1mVsx^k=*Ik#QC3#J)$!YHzxA;b_WPY-{ym90 zNt{NVZaj#>JU)-$RVR3H8YZLeB%vb4Wd4eB&nZVQ$&Q2M>**j0x-wN~)z;QaI=*!^ z)AKA0@;FPI2i9LU8`5ExWCLqg%nj){?T_;2SzgF`b9CWt&BkxICF`I?_Ib5aOM<_5{;wxIT(Huf7Zrf`rY{CWHgLE zxKeFzPlf+q!$FV-f^9DRtgfwY>|s{Vh3VV`YK*Uma*qp=TM}$$u`OZNg$?Zcr+g!CvYupy`3dynYMee+w>m#{UJg!)A{B4`9EM zO^r(u?&XJU?u358z91r@GMfsQs1^Vw?i_z**$mnQsmJ$ z{~-0nH~%VMtn&NWn+XeD)z{tM?&<07>AlXe<>SW8n0a%`d}F3`&KwhB4D!#{rt&W@ z|CXFLb7p(%hj{a+@8i@~qtcD*qKsXh+Gj4`H7Cq$bG|>^9F30hT_>}m(_>%a#ctiY1d{$?PRk6}Ks?3;wl&Gsy{b9WR-NU%DctqjRAQVZ`R*jywei~O&2cjNMS14PLrZy)PjdIPDEH%ECrRd> zI$O#=kH7!qNq@K*kH+J;st+?8XD+vK>Pp?@4lH*yd3>D9N7*E82lN!t?zv}rP2c09 zaZZIwS3&ld_} zZun-z)}=?W)R(#4y?U4&+Hx9APWEq*uPT49*~4N|Z|1eD4+k4UjyHSx!Z|l;hS%3U z>~feDHhbN+c@J#nfS>okW;d{T4|;@xy(pd9AL;gxYncF1!0>~eZDI5Wrcd`Mj(fo( zG5Oz;oE7t-k}Hygh=Ka5G?L^T@ze&l?M2xTvCQstqjwwqd9NL_BK!{(Lmc-7{o^CO z+svCYGh*)JKLDFv&g&PssPo*9eo-3rN8(G0=YIm5c}Du3lOz`WuD5w3FyiMWi6_^B z`sbS?792^Alakbfj~v*%E7%3u^c#8mhPThihB(ig5ZkVSJ)njV&l^!gsFA(Ee_0## zx+FD{qfNoSqR7i~5O-Dj8U z_f6lSYd(?=g&C|$CqHjWzB`h{hxfhbZTiLkm1IXuebj@!;W7N1(#hBMv!|T7tscqE z{y|{>3h7C%>z7?PCuV=xk$Z}yj#tIt_jQ8(#18Qnq!Z7Mg!qfn!HH*=u!(0@?~0jU z$j@Bf^Z2@MV_qMKm&C;2W1i$D_CqoLZEvr5jQq@&ZGcOz^R?L`%D~a#~1n}=jYxZ^4*pFa=tHwfs>E7zb_8? z@P#?E4_|u!mSV~Oz+>QnfA{^Y3*-I=;@>>>P&$3$#_+KBF{BO_S zh)zk0kv}xGA_1|_ zDoR}(+K*j|;RDeX(buAfqK@dC?%<;$CDl}sG5;t)UEbYZ)cNUgG`6ESi*p-|_u_%g zqT%zGwx5sR^^r-XMM<3QPU2k~tt>B%;{GeenIaCYq{DQQx);N2KYBfh6ZgW|O!jH) z-Dl6bz0IgU8b#y$D6vuEQX36ircCa@lBUh8JDlWChRHBf zTS6L|kukYF%qN*u2PJl1{ArwTXT#A(oX47OL%S(Y-(PNOLSW3+-``>%cm;oE7bl~= zxPq~f=T<>=8j5j2T)AxK;)H}Y%N>;v0~=>R5jymAQQX%iy=E?B(4n3n@B4V6pr-C& zqgLw%$G+5;xZS8d|4?%~fqsIRJ19|vD%Ne}oU(;IbQ1V~;B4SY+yCN64Tawr< zb>Rn&ogC~4TT3##Kqnu2E$2|?LuWr=H+;TJk~!p`6>p>Hw6tr!5psc-wz_6e)`yKA z(Agt3lXK3?+zUCvez1Qgocv|4_2R8bEoMZ|Ur44md|J}^mgpIr`(KHZ3!MDu{J#$Q zzwvVL=iL&E7@?k3j}dRp%j87=PMmquFY(cNV_?`HiIb~p?|A!~W=1aF5{Eng3TcRU z^vi5M6)`X7{!pIG;i?F{qbiwCTg0C5!N&Z8@4V!;Xvg2ZCK-(Q3*vk?;eP~oczb+5 z;P^0~8zN>F;xen79{*K7%<7hid*Gq=Mal2iep?tgwKMBGqEI`w&?hmMy*Gb7JQ|h`{mZU7!d5$CB|6HRAt71de~l>;LHmt&83QTD-=O diff --git a/TempShaderFolder/TestCubeVs.glsl b/TempShaderFolder/TestCubeVs.glsl index 7b58d1cf..bac9444d 100644 --- a/TempShaderFolder/TestCubeVs.glsl +++ b/TempShaderFolder/TestCubeVs.glsl @@ -14,13 +14,14 @@ layout(location = 8) in uvec2 integerData; layout(location = 0) out struct { - vec4 vertColor; // location 0 + vec4 vertPos; // location 0 vec2 uv; // location = 1 + vec4 normal; // location = 2 } Out; // material stuff -layout(location = 2) out struct +layout(location = 3) out struct { int materialIndex; uint eid; @@ -36,10 +37,13 @@ layout(set = 2, binding = 0) uniform CameraData void main() { - Out.uv = aUV; + Out2.materialIndex = gl_InstanceIndex; Out2.eid = integerData[0]; Out2.lightLayerIndex = integerData[1]; + + Out.vertPos = worldTransform * vec4(aVertexPos, 1.0f); + Out.uv = aUV; + Out.normal = vec4 (aNormal, 1.0f); gl_Position = cameraData.vpMat * worldTransform * vec4 (aVertexPos, 1.0f); - Out.vertColor = vec4 (aVertexPos, 1.0f); } \ No newline at end of file diff --git a/TempShaderFolder/TestCubeVs.spv b/TempShaderFolder/TestCubeVs.spv index 731e31d107fda1e44cdbef3c2445017205b6b841..9cf9d86def3a980db6b334d741cd492d99e8a0bc 100644 GIT binary patch literal 2684 zcmZ9OX>%Jz5QfLr;Uvz9$w3H4vI!U*4CEpZau^@7K|X>Ve^pIMi`lC6O0`;>B%ksZ z;3x5`_(B!$GrR3ZRM)Of zx7XR(>2%k6{n4m5&R-`{FNxErH;A*SpT{Q=yfYPEoc5FBL6y)DqgqQtXPnU)tfref zwU2xrWwB2-(?Rqq#K=r1oQvYYDVO?^`0$Us>t9D%!R8F^xO1G}m2wT`<-UhWZ!;a| zKJ7=ARc{XY_<(YjFW%=%KEUX?dYB@f6$Dx*Vm>v0qGi#x@ zszG)$^!U$VmJIeYpN@YQ3r-{S-5)4%^orDBAMfB_9>}hT_wd_AQu3@QrhDv0S+Pm3 z&;rLMHXO%!JWPd71wM5KT$kL7-{_T!UXzQO6pdkrg7FK7v!r$!N>x((K=m?pOAMF?)XBr-xAr&2`H6oRv*Y_`K(| zWU=&_W#Y^T@!O>@75s(LXZDCQ@9Cc90qE{@=WEln@3~d;Dz^K(Q zY_Q_|TF7U)tzYwsvo^%CUNwUMu6J-QzlZ4uB48bz$UgFN2YNgAp5KxH`5wU*%beE7mi+U=$xj~m z_`EL|ael$rOWgKfkxl%%;vYzJHZ{YaktPOCK78f_jQw!0N?7o(NfWdBKa$OP_;%jM zvdM4zZ^>rQH8ES#2(`3Jn|H>aD}DCTuX$-W;03qtK9kLP#Hbga`31Wn|8r@$Emf$~>hD*)t$LD(i zBmRRle2bHx?}zv;#ebG=1)Clezg6uLBUZ%gZdEpURwSH*&u(WhPArY+4ssO*PNoVoc+d5PVVa5fxj zWsV+5m}To3K0IohlYS&&mf$l-KT6ELY%q!MZ&C6r}h2U5;wmqpLh6Mdw7>E2^?^{&$jI9+w8~( vW7&OnWrJ1k^P5=4rhyKdR literal 2492 zcmZ9MX-^bE5QbY=78Su;@j?)96fab~56}f&MdR^x)7c$yl3{i;JD~W#cgLy1J`o2M4Byo!jAdyHWSn6>Gm6kj1$XR}Xum`Jp-6&pWeox39w( zbAy2hXRm&&nqk-K@$!W=~iU_!5oP&8H|b`< zUJG{av%cXRG2CHgJr6o}@t-~i{g8B4-3>d_*L)sju}_xMPV_zaYQaaoDDG@=xoZ-y ze$AVHGs+4!_3}!voHF&y4(HEAuU{oJSR$kNI;6y7pU^Jq277Jcqzsk%Bp%(bm7VJv)A^xG4E$)PmI^|nP;@)Ch)UXvt=kcv4$(E1z zqQ5L^WJnhLT9o-vVyGnyj_f@vM0&mCQp-l~jnB0c&qK5;@!XNw`PR*n&d1EB{V&~Y zt>7|GzPPsTh^-dp%fA)HCm|oR=0Ey$HA*?cHN>I6696qRJqA+?n4W-n3ovs`%uI=y zY5Y4SOFD&jW5HpWjeOYH%|=dayrtRDu`#<1d8`lk?d_)JV=ak=jhsUP7aTC0ecNpM zz=Msv#MzyA=QG>zlrW1s^XA;KsHqmdT`&uOQ+xG|cxNzoIjB=OXG#c+eneVb`=sQk z;;9QvelTwdhC3n5w+aXQr0{O-mT=rL(AETs!BH2R@kDvKmfECl)_% za!NaA@g~IczHqS<4`vpzabC4%_*13N>OCt=ez4VdUOM?L{(^M!omBjcc6x$sLfRGW z);D|z=UmlJUi{Pr=05@3xbQXY#L;Vd%N&BS6MsWHHDD(m%zWCtZPyPqm@nMG#=D!0Q_lEme;@r`X8m%W+XUIW9;n$0h05Eyrc)f`s$oa0mMSLc;9YTZ7?QZ7-!)YikH&V_6+b(y>)*TP|(Y+Fr> Date: Thu, 27 Oct 2022 02:28:38 +0800 Subject: [PATCH 09/44] Lighting shader kind of done (still has bugs) --- .../MiddleEnd/Interface/SHGraphicsSystem.cpp | 3 +- .../MiddleEnd/Lights/SHLightingSubSystem.cpp | 12 +++-- .../MiddleEnd/Lights/SHLightingSubSystem.h | 2 +- .../RenderGraph/SHRenderGraphNodeCompute.cpp | 1 - TempShaderFolder/DeferredCompositeCs.glsl | 47 +++++++++++++++--- TempShaderFolder/DeferredCompositeCs.spv | Bin 1716 -> 3384 bytes TempShaderFolder/TestCubeFs.glsl | 2 +- TempShaderFolder/TestCubeVs.glsl | 2 +- TempShaderFolder/TestCubeVs.spv | Bin 2684 -> 3036 bytes 9 files changed, 54 insertions(+), 15 deletions(-) diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp index dfa4e41e..58a86bcd 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp @@ -219,7 +219,7 @@ namespace SHADE // deferred composite auto deferredCompositeShader = shaderModuleLibrary.GetShaderModule("DeferredCompositeCs.glsl"); - gBufferNode->AddNodeCompute(deferredCompositeShader, { "Albedo", "Scene" }); + gBufferNode->AddNodeCompute(deferredCompositeShader, { "Position", "Normals", "Albedo", "Scene" }); auto dummyNode = worldRenderGraph->AddNode("Dummy Pass", { "Scene" }, {"G-Buffer"}); // no predecessors @@ -403,6 +403,7 @@ namespace SHADE // Force set the pipeline layout currentCmdBuffer->ForceSetPipelineLayout(SHGraphicsGlobalData::GetDummyPipelineLayout(), SH_PIPELINE_TYPE::GRAPHICS); + currentCmdBuffer->ForceSetPipelineLayout(SHGraphicsGlobalData::GetDummyPipelineLayout(), SH_PIPELINE_TYPE::COMPUTE); // Bind all the buffers required for meshes for (auto& [buffer, bindingPoint] : MESH_DATA) diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp index a22fb662..6e8dd916 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp @@ -319,11 +319,12 @@ namespace SHADE { dynamicOffsets[i][0] = i * lightCountsAlignedSize; // Even if the first binding is a count, we want to account for that too - for (uint32_t j = 1; j < static_cast(dynamicOffsets.size()); ++j) + for (uint32_t j = 0; j < static_cast(SH_LIGHT_TYPE::NUM_TYPES); ++j) { auto const& typeData = perTypeData[j]; { - dynamicOffsets[i][j] = j * typeData.GetAlignmentSize(); + // +1 because 1st reserved for count + dynamicOffsets[i][j + 1] = i * typeData.GetAlignmentSize(); } } } @@ -376,6 +377,7 @@ namespace SHADE { dynamicOffsets[i].resize(NUM_LIGHT_TYPES + 1); // +1 for the count } + } /***************************************************************************/ @@ -425,7 +427,7 @@ namespace SHADE data.WriteToGPU(frameIndex); } - lightCountsBuffer->WriteToMemory(lightCountsData.data(), lightCountsData.size() * sizeof (uint32_t), 0, lightCountsAlignedSize * frameIndex); + lightCountsBuffer->WriteToMemory(lightCountsData.data(), static_cast(lightCountsData.size()) * sizeof (uint32_t), 0, lightCountsAlignedSize * frameIndex); // If any of the buffers got expanded, the descriptor set is invalid because the expanded buffer // is a new buffer. If some expansion was detected, update descriptor sets. @@ -442,8 +444,10 @@ namespace SHADE // so we do it anyway. #NoteToSelf: if at any point it affects performance, do a check before computing. ComputeDynamicOffsets(); + //cmdBuffer->ForceSetPipelineLayout() + // Bind descriptor set (We bind at an offset because the buffer holds NUM_FRAME_BUFFERS sets of data). - cmdBuffer->BindDescriptorSet(lightingDataDescSet, SH_PIPELINE_TYPE::GRAPHICS, SHGraphicsConstants::DescriptorSetIndex::DYNAMIC_GLOBALS, {dynamicOffsets[frameIndex]}); + cmdBuffer->BindDescriptorSet(lightingDataDescSet, SH_PIPELINE_TYPE::COMPUTE, SHGraphicsConstants::DescriptorSetIndex::DYNAMIC_GLOBALS, {dynamicOffsets[frameIndex]}); } diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.h b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.h index 6c974730..efc6ddf6 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.h @@ -31,7 +31,7 @@ namespace SHADE uint32_t cullingMask; //! Diffuse color emitted by the light - SHVec4 diffuseColor; + alignas (16) SHVec4 diffuseColor; }; diff --git a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp index a5208fcf..678fc41b 100644 --- a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp +++ b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp @@ -53,7 +53,6 @@ namespace SHADE descSetGroups[i] = graphStorage->descriptorPool->Allocate(layouts, variableCounts); } - HandleResize(); } diff --git a/TempShaderFolder/DeferredCompositeCs.glsl b/TempShaderFolder/DeferredCompositeCs.glsl index 354a8954..c5e543db 100644 --- a/TempShaderFolder/DeferredCompositeCs.glsl +++ b/TempShaderFolder/DeferredCompositeCs.glsl @@ -9,22 +9,57 @@ struct DirectionalLightStruct }; layout(local_size_x = 16, local_size_y = 16) in; -layout(set = 4, binding = 0, rgba8) uniform image2D inputImage; -layout(set = 4, binding = 1, rgba8) uniform image2D targetImage; +layout(set = 4, binding = 0, rgba8) uniform image2D positions; +layout(set = 4, binding = 1, rgba8) uniform image2D normals; +layout(set = 4, binding = 2, rgba8) uniform image2D albedo; +layout(set = 4, binding = 3, rgba8) uniform image2D targetImage; -layout(set = 1, binding = 0) buffer DirectionalLightData +layout(set = 1, binding = 0) uniform LightCounts +{ + uint directionalLights; + uint pointLights; + uint spotLights; + +} lightCounts; + +layout(std430, set = 1, binding = 1) buffer DirectionalLightData { DirectionalLightStruct dLightData[]; } DirLightData; void main() -{ +{ // convenient variables ivec2 globalThread = ivec2(gl_GlobalInvocationID); - vec3 color = imageLoad (inputImage, globalThread).rgb; + // Get the diffuse color of the pixel + vec3 pixelDiffuse = imageLoad (albedo, globalThread).rgb; + + // Get position of fragment in world space + vec3 positionWorld = imageLoad (positions, globalThread).rgb; + + // normal of fragment + vec3 normalWorld = imageLoad(normals, globalThread).rgb; + normalWorld = normalize (normalWorld); + + vec3 fragColor = vec3 (0.0f); + + for (int i = 0; i < lightCounts.directionalLights; ++i) + { + // get normalized direction of light + vec3 dLightNormalized = vec3 (0.0f, 0.0f, 1.0f); + //vec3 dLightNormalized = normalize (DirLightData.dLightData[i].direction); + + // Get diffuse strength + float diffuseStrength = max (0, dot (dLightNormalized, normalWorld)); + + //fragColor += vec3 (1.0f) * diffuseStrength.rrr * pixelDiffuse; + fragColor += DirLightData.dLightData[i].diffuseColor.rgb * diffuseStrength.rrr * pixelDiffuse; + //fragColor += vec3 (dLightNormalized.rgb); + } // store result into result image - imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(color, 1.0f)); + //imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(fragColor, 1.0f)); + imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(normalWorld, 1.0f)); } \ No newline at end of file diff --git a/TempShaderFolder/DeferredCompositeCs.spv b/TempShaderFolder/DeferredCompositeCs.spv index 679dc135f5f556eb95565c51c1c9f1c2aca8821a..ffd0343f71e1704bba6f534f17d842cba15ac6cf 100644 GIT binary patch literal 3384 zcmZ9O`*Ku85XL8$O#(>>2qAbOZio^UjHuicxx_3k(S-zp;(a;UJ=q*NIcID4gi^~t z@DJa>2k{wvC`zre%I|k}I!@Fk2i{s7>xx;SSZ5l7re8A!~GVk(lO!fupgIHrZ8;^B^!IyP0Dc8(~!bAQShRn>Z< zSzlkTH*Pmu-EOmA{FKJcG|A#-JL$!(B6%7UHxa}oSu5RZhXEBug!L<`eMmJrX}%Su z4|jTT)Rw6}C(7PBX|rCs*0QI0D=LyaTdS4+F*hgKO@55iTC%;p*H?A+jk=d4qjW27 z>ypS{mEFzz37a3~y_5nK{aXn5zUR(LW_fQnN(YhTTiWOP<-TRv+r6l>nx}cM+&ALh zlT1pz;;unzlxM;<#McJn+wVyMd#z&77k<`$ z-_q#|o_>@5il6-dJpH!zQaz2%-KhUW(c@)2FVXj4S6B9MPyE3iYEco1E^Fau4bC?3 zFxL%n+E<>~;+ZQOi>TL$i?!XT6YK1wqgAIzCL?4vF=by)1T`Gj?BHgHoxoYmp; zZF@(g6IT_;e^+u$;LC#;yL-z|e{k$0o*9JwVbh=W8+pIoGd6zPpGjvfFAB$XYI^^$OV7R+k6jN{u$}yC;p`V zo{+2xMUB&v)F9sc3({F;FAYq0 zPEo|Zw&vCt=r~Z;+vPw`@?4cx+J~8(H}N% z5YEo{K)TIq)BDJ4{-*RH!R|Ja&SDlVNqVt-=&5j2U_bV*z<$ojo8nCq1Mpqe-Lju~ zvgqY6G5i)&llRMSAoqaHo8q@Ew5tc~vj^sr%du(uw2j8;Yaeae-KTH*`|Y1xFp;`^y4v9h-Q*kBQmRer7T+ z5Cgxio8c|ID!>C4^|(*+b5Hm!{~75E-X{N|5axePHZky)|8?o`fEDJi%EoW`-;loK zZSubv;igO1F;vwm>|e9ekV_KRh~fzu&N+WqUcMVX6^MbK(#wJSOyF*~Z@yQE zA$MI8pPlQzbk4P+eVdXGg$;po;Cmnt%lrFWz;Cnr!gKH}n;r4=@JOKEhM(7$o`VO! zssCBYuLN@8w=;e%eNM2LZ=@3kZ!zCWXU4z!Jl{!&Bi7~*$4swCa>q#aGt=({&i+jM zu^$U?O@aOR9t+`{VOH!vCAlR;-ky|f3w%$k>n>Z8vFG4f+z;=E&&IZZ-_FvJ&P@4E s;qG<>IF@mVbU5-D_k-t#B{!6rIXw~BPdxsb&{AFcr7r$|mF24NAM&9b*#H0l delta 778 zcmYjP%Sr=55bS*<@wK3+1S6XD{fdbi4}wT8N(?9}=*iQPgmp0{5;r#?{(z_X5>dg6 z|KQbwpCVYbnUzc^db+Bor+Ts`?jP-q}pn<+K37KGKfL* zz7tmNJip%KTyUY+_UoEV$bb~om6@F?K;fzd?Rqr~T21Ve_!ZQ%nT}KwOtsT!1Wo_c zd$@&`g8FGr8{6s|9kzKKt9BCjH{qcddb~3!MKxxPt34~%rCJtST*P_6?#t(}H*}sy z90sOEq~<+-M(X^*D8H4_3CYPXdhW6T6Okm&J-Wo}t$wBE81m znA5Ag{@7Wg>vD^gMk&jN09x2UK7qIbh&+{;Q_BIg7U!GTvvm%pI5J0P4MA-dJjb5| zc%GPvU~z;h$U69Q&Z|C@NgnB(0vKHRsv@*nkJ9^Zly0 Oh=zGF^PpcWd0L&ED1CCW3$Y z74#$dsr<((pWp0uxMEUW-Tm~_Gd(@MSEra>Y93W`#I+%+-T#wYS?V zlYF>xUPP$4U!g*PLtg2+s$0_zv$qC6B$wkQ}$p@0pBpZ^RWGJcVZ&vyrZB$iO ztKDyPI<5BI{$M=rPx5C;)KB6x>JQ^A8szbT3aq*#Q@l7GB>Tf@LQRb6T53Auh|XZu z-Q1zQ=kq9weX^Afqo*Op&UC`LC>|bisV|9lf6LqcS(FuQ&ft!n{rs|&t7%{EyPNd4 z(n;>qL1f!1RttTI(>&UZvUQ((Ar-eoqE=m=*#}XUcSjRp)qqjU{=st&wWOnL&nKK& z3B6Sfvg@J8zmKwH*vou6`Bf}9wa|CJqm84dY#s7=2mfeCb~U_*e^6}7KHn&&dvv3$ zNRlhGz_E#qCUG8*QlWE!Pn`kRCAZ^0!WdbMniX41;_-T1^yV;+DI&I?B!@BX#eA@+ z|B>{X--|LIS{G^oV~wp4+4K>dS`NndeJ)M@x6*^Dd@yFu_k6k=rO;ffe9r~h)P&D_ z9+NDW{uycF%m{Jj8lQ#FjN>zV_{{rsoSx%TA920|eEPGgn&>-=Gg*eg2SXc14j8o> zh7DGnUkUr!-qx=r#aWwTS+8orf8IMdue^Zi2O?lCok$-0atC_5_=4Y*&mvBrxg)im zRu*|pdHC38#i>g-B-{_5v+!99>I?mb175_c?j_mmLF|Td@cACWmdib@j}7_9g|k2V zz{lr(!HDwy0>L>9x>|0XMVxX%YR22E_+h% zyV5ffaQOJlHyCHWFWr!k4}V#j7&v@<<{ymvG^AG~&i#2C{uNo|HYNDiq~TIC`S^S< zV8lO{hEJS&Z%K0&n4PyF+xS~$tRZdvd?1@1T~Pi*=|-^WS@GM}EHPq5yy~`Pa|Yig z=iv8BY(YNX0(ta_I(MWw0~|g+-v}7-$E9t3rB6f2jO3c$4jym7;@p3Q@O|DCT9-a4 zVQyE2GP8WA%ssPyOBwiZh|f!(lQ5UeB6~1z=Oy59n8Vj4?7_UV2Rw6OB2cLKQP{MpXR1FR3k0f9$!}v!7jNTabNr};?u5Qzm zzAPahK5^#kFYQb0Qwe9op;qSZs)X6Mp5eozwngdd5@ruRbN7V=zV!zmj@|8sZ0>ek zFT`EHlu$E!5$lybxG9?$ccHf15-?Urzhv~~jszTGu@85(oK@N6fLqR2vcVA+vFV&O z`Q(6E&bn-Hgk?Eh-GOiGuH=q{z2VxswPbHd=r8qdO5lR8Dwpr>YYF{g7MMF~Z%E&h zz-KWd@W3puE!*;#HOsp%n>=bH4<4B1b!1x}-?-&c>n37>yrNgtsCHs delta 934 zcmZ8fO-lk%6ut8tlZt`FAj%Leis)3rYB^0SD9J(gA06accp`#}x6kq+r(p)>F^? zJdi=(1#LwpVB Date: Thu, 27 Oct 2022 02:46:38 +0800 Subject: [PATCH 10/44] Working abit more now. Error with device extension thingy. --- .../MiddleEnd/Interface/SHGraphicsSystem.cpp | 4 ++-- TempShaderFolder/DeferredCompositeCs.glsl | 6 +++--- TempShaderFolder/DeferredCompositeCs.spv | Bin 3384 -> 3332 bytes TempShaderFolder/TestCubeVs.glsl | 3 ++- TempShaderFolder/TestCubeVs.spv | Bin 3036 -> 3296 bytes 5 files changed, 7 insertions(+), 6 deletions(-) diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp index 58a86bcd..df884f57 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp @@ -181,8 +181,8 @@ namespace SHADE // Initialize world render graph worldRenderGraph->Init(device, swapchain); - worldRenderGraph->AddResource("Position", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second); - worldRenderGraph->AddResource("Normals", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second); + worldRenderGraph->AddResource("Position", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second, vk::Format::eR32G32B32A32Sfloat); + worldRenderGraph->AddResource("Normals", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second, vk::Format::eR32G32B32A32Sfloat); worldRenderGraph->AddResource("Albedo", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second); worldRenderGraph->AddResource("Depth Buffer", { SH_ATT_DESC_TYPE_FLAGS::DEPTH_STENCIL }, windowDims.first, windowDims.second, vk::Format::eD32SfloatS8Uint); worldRenderGraph->AddResource("Entity ID", { SH_ATT_DESC_TYPE_FLAGS::COLOR }, windowDims.first, windowDims.second, vk::Format::eR32Uint, 1, vk::ImageUsageFlagBits::eTransferSrc); diff --git a/TempShaderFolder/DeferredCompositeCs.glsl b/TempShaderFolder/DeferredCompositeCs.glsl index c5e543db..c0e42cea 100644 --- a/TempShaderFolder/DeferredCompositeCs.glsl +++ b/TempShaderFolder/DeferredCompositeCs.glsl @@ -40,7 +40,7 @@ void main() // normal of fragment vec3 normalWorld = imageLoad(normals, globalThread).rgb; - normalWorld = normalize (normalWorld); + //normalWorld = normalize (normalWorld); vec3 fragColor = vec3 (0.0f); @@ -59,7 +59,7 @@ void main() } // store result into result image - //imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(fragColor, 1.0f)); - imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(normalWorld, 1.0f)); + imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(fragColor, 1.0f)); + //imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(normalWorld, 1.0f)); } \ No newline at end of file diff --git a/TempShaderFolder/DeferredCompositeCs.spv b/TempShaderFolder/DeferredCompositeCs.spv index ffd0343f71e1704bba6f534f17d842cba15ac6cf..a87b7548fb45981226d5a85fa1e4c3f4cf88dbd4 100644 GIT binary patch literal 3332 zcmZ9OZF5sq5XVoOCM|`6$fFO`lqyxJ^{GV^0Yi(S7-(uyd=9tCZF=Q4Hi7a* z_znCZeg;33qs}-sy3c-Tm*L-95W|Q%mFXlg^E~X*c8c+~}Ni<3gM}>MEYs z8(WQ~VcuC_TBX&1GKkxG@+8J@s^FLO+Ub6$=unnNF@IUPk0?hs&9ucU#ap%PQ$q#Y5mh9~850#yJ6YhEODBX@b z8G6N4rT4R8!sUnAASFRr|IHQfVZbhl_p-rWl#V=!w{UqV(|A#X+hafhDwv!s^?i{Z>**v}01HCz*x z7IKu`q^k+*_`CQ03zDDW(94RujcwGXt$Yyoy7{i+Ou4(l*GA(zs7Vg{?R-=hcFsZF zlBo-vdXr%-O#XkIdfWS{R-=0_8a|fyr1xhNLk-qCUqeIq;TqPWJQD14VdsqAHnK3+ z`@(e3zu5elYfE?@4Z3l@z87_4SJw>L^P{2{Md<9vMbSh-pOZ}O*pZ8NbclnUohaJT zv5$%Fs0QZAnIEwO3_BQk&5xX5Q=+=QIqq5=%$YpgBQH96INZ1S6!X|@z>XFCEDzte z-7QJRuPP$`C*l=ZkV4}|TCddq$0 z$)T3Ngz&eRoa`@u1L*@gJH_9&qFz0uUpk~O7Ify!_glPQE9mr`zX#Z_D<3r<7tM%% zmd^h3KCn$y$)4E%8%R9Bo|TLrZ*R(vc&9}8V!NT2@-8s)u@V+~QxB3=VOM@tGrb-ogy|ZjqTE-{#+X={w@=3;a*@ZCQLp#KC?= z96Ovknb&(FVldBX@v8x=sn2|~*F}8C>2qAbOZio^UjHuicxx_3k(S-zp;(a;UJ=q*NIcID4gi^~t z@DJa>2k{wvC`zre%I|k}I!@Fk2i{s7>xx;SSZ5l7re8A!~GVk(lO!fupgIHrZ8;^B^!IyP0Dc8(~!bAQShRn>Z< zSzlkTH*Pmu-EOmA{FKJcG|A#-JL$!(B6%7UHxa}oSu5RZhXEBug!L<`eMmJrX}%Su z4|jTT)Rw6}C(7PBX|rCs*0QI0D=LyaTdS4+F*hgKO@55iTC%;p*H?A+jk=d4qjW27 z>ypS{mEFzz37a3~y_5nK{aXn5zUR(LW_fQnN(YhTTiWOP<-TRv+r6l>nx}cM+&ALh zlT1pz;;unzlxM;<#McJn+wVyMd#z&77k<`$ z-_q#|o_>@5il6-dJpH!zQaz2%-KhUW(c@)2FVXj4S6B9MPyE3iYEco1E^Fau4bC?3 zFxL%n+E<>~;+ZQOi>TL$i?!XT6YK1wqgAIzCL?4vF=by)1T`Gj?BHgHoxoYmp; zZF@(g6IT_;e^+u$;LC#;yL-z|e{k$0o*9JwVbh=W8+pIoGd6zPpGjvfFAB$XYI^^$OV7R+k6jN{u$}yC;p`V zo{+2xMUB&v)F9sc3({F;FAYq0 zPEo|Zw&vCt=r~Z;+vPw`@?4cx+J~8(H}N% z5YEo{K)TIq)BDJ4{-*RH!R|Ja&SDlVNqVt-=&5j2U_bV*z<$ojo8nCq1Mpqe-Lju~ zvgqY6G5i)&llRMSAoqaHo8q@Ew5tc~vj^sr%du(uw2j8;Yaeae-KTH*`|Y1xFp;`^y4v9h-Q*kBQmRer7T+ z5Cgxio8c|ID!>C4^|(*+b5Hm!{~75E-X{N|5axePHZky)|8?o`fEDJi%EoW`-;loK zZSubv;igO1F;vwm>|e9ekV_KRh~fzu&N+WqUcMVX6^MbK(#wJSOyF*~Z@yQE zA$MI8pPlQzbk4P+eVdXGg$;po;Cmnt%lrFWz;Cnr!gKH}n;r4=@JOKEhM(7$o`VO! zssCBYuLN@8w=;e%eNM2LZ=@3kZ!zCWXU4z!Jl{!&Bi7~*$4swCa>q#aGt=({&i+jM zu^$U?O@aOR9t+`{VOH!vCAlR;-ky|f3w%$k>n>Z8vFG4f+z;=E&&IZZ-_FvJ&P@4E s;qG<>IF@mVbU5-D_k-t#B{!6rIXw~BPdxsb&{AFcr7r$|mF24NAM&9b*#H0l diff --git a/TempShaderFolder/TestCubeVs.glsl b/TempShaderFolder/TestCubeVs.glsl index dc8f0b98..49f107dd 100644 --- a/TempShaderFolder/TestCubeVs.glsl +++ b/TempShaderFolder/TestCubeVs.glsl @@ -44,6 +44,7 @@ void main() Out.vertPos = worldTransform * vec4(aVertexPos, 1.0f); Out.uv = aUV; - Out.normal.rgb = mat3 (transpose (inverse (worldTransform))) * aNormal.rgb; + Out.normal.rgb = mat3(transpose(inverse(worldTransform))) * aNormal.rgb; + Out.normal.rgb = normalize (Out.normal.rgb); gl_Position = cameraData.vpMat * worldTransform * vec4 (aVertexPos, 1.0f); } \ No newline at end of file diff --git a/TempShaderFolder/TestCubeVs.spv b/TempShaderFolder/TestCubeVs.spv index 0dfd6cf270dcc59b66eab56b32b571b5f96caa4c..d8c3c3d072f76728073803b4f4baa5c981426184 100644 GIT binary patch delta 966 zcmZ9L&rVZO5XR@8{v*X2Nf!;2kSfvm4_7Ws3?y9`a6zOhYPGdq|4^%VO9CNb)$j;- z7OZ&$!V~x&F7zQ>n)v@quQ|a+RT#E zgX1Xb`5D)k?J35F+k=hq?r3i`PONMd>-n~8O4Coj4_vcGC05dB;7?qAX^;`N6ABfV z$;wB<{?2;5Cr?G}f4X{<_+QT72+y2W4qH?W@iwuE_MLHjcs zvX($D%NMP$GkcJ~uX1AU6mB7(nYwF2OYs|dW??4u#IXQJ{%v-?m=++oB_cUHtn3!z zyE=A+t3p#)R+`?A1^7ocWjE!Y93T#Dt zY|6t0)pMQ01l&$XZ>uH$LI|CyLkAb?y8c_WF?pG*m!oLzTAK$%x=r)vqeCTMY>5g^j4ARFMtfsdv&EAhV;U zKUBhS^{3LC;WHPZF^bU1v49gR~de2#NDi*pN@QA1u6S@}a`K{9A?XLW0$MrD)^unJ`G{@jf=2cQ<{mYm|u_n>}= zcGkR8a+&$g>{|yM)aS_Dg*(yDnmduBei59P{017fLAbN$Sl=8`y9DTu14ocK_X;2% z*4H?1057;l>NfyA Date: Thu, 27 Oct 2022 11:31:11 +0800 Subject: [PATCH 11/44] Some lighting fixes --- .../Graphics/Devices/SHVkLogicalDevice.cpp | 5 +++-- TempShaderFolder/DeferredCompositeCs.glsl | 12 ++++-------- TempShaderFolder/DeferredCompositeCs.spv | Bin 3332 -> 3460 bytes TempShaderFolder/TestCubeFs.glsl | 2 -- 4 files changed, 7 insertions(+), 12 deletions(-) diff --git a/SHADE_Engine/src/Graphics/Devices/SHVkLogicalDevice.cpp b/SHADE_Engine/src/Graphics/Devices/SHVkLogicalDevice.cpp index a6b415a9..6bf2e731 100644 --- a/SHADE_Engine/src/Graphics/Devices/SHVkLogicalDevice.cpp +++ b/SHADE_Engine/src/Graphics/Devices/SHVkLogicalDevice.cpp @@ -186,9 +186,10 @@ namespace SHADE vk::PhysicalDeviceFeatures features{}; // ADD MORE FEATURES HERE IF NEEDED // point and lines fill mode - features.fillModeNonSolid = true; + features.fillModeNonSolid = VK_TRUE; features.samplerAnisotropy = VK_TRUE; - features.multiDrawIndirect = true; + features.multiDrawIndirect = VK_TRUE; + features.independentBlend = VK_TRUE; // for wide lines features.wideLines = true; diff --git a/TempShaderFolder/DeferredCompositeCs.glsl b/TempShaderFolder/DeferredCompositeCs.glsl index c0e42cea..c707901f 100644 --- a/TempShaderFolder/DeferredCompositeCs.glsl +++ b/TempShaderFolder/DeferredCompositeCs.glsl @@ -9,8 +9,8 @@ struct DirectionalLightStruct }; layout(local_size_x = 16, local_size_y = 16) in; -layout(set = 4, binding = 0, rgba8) uniform image2D positions; -layout(set = 4, binding = 1, rgba8) uniform image2D normals; +layout(set = 4, binding = 0, rgba32f) uniform image2D positions; +layout(set = 4, binding = 1, rgba32f) uniform image2D normals; layout(set = 4, binding = 2, rgba8) uniform image2D albedo; layout(set = 4, binding = 3, rgba8) uniform image2D targetImage; @@ -40,26 +40,22 @@ void main() // normal of fragment vec3 normalWorld = imageLoad(normals, globalThread).rgb; - //normalWorld = normalize (normalWorld); vec3 fragColor = vec3 (0.0f); for (int i = 0; i < lightCounts.directionalLights; ++i) { // get normalized direction of light - vec3 dLightNormalized = vec3 (0.0f, 0.0f, 1.0f); - //vec3 dLightNormalized = normalize (DirLightData.dLightData[i].direction); + vec3 dLightNormalized = normalize (DirLightData.dLightData[i].direction); // Get diffuse strength float diffuseStrength = max (0, dot (dLightNormalized, normalWorld)); - //fragColor += vec3 (1.0f) * diffuseStrength.rrr * pixelDiffuse; + // Calculate the fragment color fragColor += DirLightData.dLightData[i].diffuseColor.rgb * diffuseStrength.rrr * pixelDiffuse; - //fragColor += vec3 (dLightNormalized.rgb); } // store result into result image imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(fragColor, 1.0f)); - //imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(normalWorld, 1.0f)); } \ No newline at end of file diff --git a/TempShaderFolder/DeferredCompositeCs.spv b/TempShaderFolder/DeferredCompositeCs.spv index a87b7548fb45981226d5a85fa1e4c3f4cf88dbd4..455ab5483f63c9c8c37d786c435e1d7ca6138b50 100644 GIT binary patch literal 3460 zcmZvd>2e!I5XZ-de8hH)$;lBT#~cX>CO{GbA&0Sp;-Ewh&cQ9#(pp};-WAe11r#5` z2i|}O;Td=+3aFxr|8F#Hwp>iA)7}5>>0`QA9vNO7cW%fXax<>)24~I<3vq7Bjd@#?3Uz;$}PP#jPTF65}^f@=LN-y4Nl{ROC_4Us3K!<>;jOW|ThI z?!{4Cs_LBZwRO^F&70P;CwVI>k~~{m_4YA$LcE)NAE&Fy*4AEM*||6Bo)?eO&A6ST zkGZP!Zr)G0{5bEWB&g`$VhQIx!OnJjkveP z6E9cXRq=Y#*)CS{y{zb~f(efacHyb=EK0o#dB^mRJG^-}PqHFd3}*)YZf>xz;hM0t zl%wLt-HNcbzkAPjko*|$za?+BIvCS_?v0|i*D412v2*t8lT3ba>Pq^{VZ#66)YaNc zwE~^HQGZ9?*035Ckzk(-J7>_tz{31)3)4N{nfZe^@Ezn) zD{*~3VB|H7oM028n!Y*iS{=-pJlrEMI(azUXFi;A9x%%@E!q4m58t<8 zBjIjUocOoI$3*;i;A1nf_|yl+J^YzXxjuC2vwGXXPQUo0W4HT!Kg{Jh(Ghh`jSI43 zM?R)I)Ke7^^MrK$2zm^ARXXnm2H}6mSm0NK&VE?@S;^$Y|G54? zDqa;4>zFvY#X2r|ke41N-N|4lR{2mXZ$N%}<={(xboP-$j#J{~z@L~4LI1y)V8lEv z&cTZNWbPalx-34g$gASiVX=6JQ+jE365G6Fb`PC6HF08skq4dqvpjc#OicXm ziPHO?$KG^DvU5*wpkwQb_})zaPBQU$ zbM}w@#|Of8S#L@_X3wFvKZR7psexUe6wwDd`^VqGvR*x)pE;oO_sjg5FMqpCC*Dd) z=gk^HzovZDd|1Ty@{{ygary(huPWJ(xqyl7W6uVR-q+82W^V^NjrtUMNc@aL~4ZRF=en|ulamdGe5}$X%PP_&2mqmOd7XKB=<@m1#A8?ER znq+W@Q;uJij@{zFF8OTGssEg)9RIv@e84UK8hz*G z`vU(%eO?xSSH!`7MI1YvI+@pdB4RL4cJ}>%E$f~6R&R*-e#yZdd~S-sf0NI$_=h6y z-4y*TAM{Hi@{ya~Sn*mw)}6`c6^ ztc$=*zb~1$`&G5_?SCS|2YgyJfNh9~iyyy#_z;`j$7Z!ZkZiR-lKfa?wPSlI!k7L0 zRD|7T`&q!iIW}ATso`@G`PM_PUjz&s`bG8A- zX0Ro`9WZbX@54^=?Ia@X*2}k&>4o1M-Yyk^aSYp)3`QKovVaYXuPZWh%0=AAAN!7| PrM%QjUhMxU$`#SSUL_#7 literal 3332 zcmZ9OZF5sq5XVoOCM|`6$fFO`lqyxJ^{GV^0Yi(S7-(uyd=9tCZF=Q4Hi7a* z_znCZeg;33qs}-sy3c-Tm*L-95W|Q%mFXlg^E~X*c8c+~}Ni<3gM}>MEYs z8(WQ~VcuC_TBX&1GKkxG@+8J@s^FLO+Ub6$=unnNF@IUPk0?hs&9ucU#ap%PQ$q#Y5mh9~850#yJ6YhEODBX@b z8G6N4rT4R8!sUnAASFRr|IHQfVZbhl_p-rWl#V=!w{UqV(|A#X+hafhDwv!s^?i{Z>**v}01HCz*x z7IKu`q^k+*_`CQ03zDDW(94RujcwGXt$Yyoy7{i+Ou4(l*GA(zs7Vg{?R-=hcFsZF zlBo-vdXr%-O#XkIdfWS{R-=0_8a|fyr1xhNLk-qCUqeIq;TqPWJQD14VdsqAHnK3+ z`@(e3zu5elYfE?@4Z3l@z87_4SJw>L^P{2{Md<9vMbSh-pOZ}O*pZ8NbclnUohaJT zv5$%Fs0QZAnIEwO3_BQk&5xX5Q=+=QIqq5=%$YpgBQH96INZ1S6!X|@z>XFCEDzte z-7QJRuPP$`C*l=ZkV4}|TCddq$0 z$)T3Ngz&eRoa`@u1L*@gJH_9&qFz0uUpk~O7Ify!_glPQE9mr`zX#Z_D<3r<7tM%% zmd^h3KCn$y$)4E%8%R9Bo|TLrZ*R(vc&9}8V!NT2@-8s)u@V+~QxB3=VOM@tGrb-ogy|ZjqTE-{#+X={w@=3;a*@ZCQLp#KC?= z96Ovknb&(FVldBX@v8x=sn2|~*F}8C Date: Thu, 27 Oct 2022 18:34:19 +0800 Subject: [PATCH 12/44] Fix editor component view bug where fields from different components that have the same name clash --- .../Inspector/SHEditorComponentView.hpp | 3 +- SHADE_Engine/src/Editor/SHEditor.cpp | 2 + SHADE_Engine/src/Editor/SHEditorWidgets.hpp | 6 +-- .../src/Graphics/Windowing/SHWindow.cpp | 39 +++++++++++++------ .../src/Graphics/Windowing/SHWindow.h | 5 ++- 5 files changed, 38 insertions(+), 17 deletions(-) diff --git a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp index 046dba2f..adabb87a 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp +++ b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp @@ -15,6 +15,7 @@ #include "Editor/SHEditorWidgets.hpp" #include "Physics/Components/SHColliderComponent.h" #include "Reflection/SHReflectionMetadata.h" + namespace SHADE { template::value, bool> = true> @@ -52,7 +53,7 @@ namespace SHADE if (!component) return; const auto componentType = rttr::type::get(); - ImGui::PushID(component->GetEID()); + ImGui::PushID(SHFamilyID::GetID()); SHEditorWidgets::CheckBox("##IsActive", [component]() {return component->isActive; }, [component](bool const& active) {component->isActive = active; }, "Is Component Active"); ImGui::PopID(); ImGui::SameLine(); diff --git a/SHADE_Engine/src/Editor/SHEditor.cpp b/SHADE_Engine/src/Editor/SHEditor.cpp index 99125e65..6ae94cdc 100644 --- a/SHADE_Engine/src/Editor/SHEditor.cpp +++ b/SHADE_Engine/src/Editor/SHEditor.cpp @@ -293,6 +293,7 @@ namespace SHADE //#==============================================================# void SHEditor::InitBackend() { +#ifdef SHEDITOR if(ImGui_ImplSDL2_InitForVulkan(sdlWindow) == false) { SHLOG_CRITICAL("Editor backend initialisation; Failed to perform SDL initialisation for Vulkan") @@ -339,6 +340,7 @@ namespace SHADE renderGraph->GetNode("ImGui Node")->GetSubpass("ImGui Draw")->AddExteriorDrawCalls([](Handle& cmd) { ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), cmd->GetVkCommandBuffer()); }); +#endif } void SHEditor::PollPicking() diff --git a/SHADE_Engine/src/Editor/SHEditorWidgets.hpp b/SHADE_Engine/src/Editor/SHEditorWidgets.hpp index 60cd7a86..d511c106 100644 --- a/SHADE_Engine/src/Editor/SHEditorWidgets.hpp +++ b/SHADE_Engine/src/Editor/SHEditorWidgets.hpp @@ -41,7 +41,7 @@ namespace SHADE ImGui::BeginGroup(); auto itemSpacing = ImGui::GetStyle().ItemSpacing; - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f)); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.2f)); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 0.0f)); auto frameHeight = ImGui::GetFrameHeight(); @@ -86,7 +86,7 @@ namespace SHADE auto itemSpacing = ImGui::GetStyle().ItemSpacing; - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f)); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.2f)); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 0.0f)); auto frameHeight = ImGui::GetFrameHeight(); @@ -127,7 +127,7 @@ namespace SHADE ImGui::GetWindowDrawList()->AddRect( frameRect.Min, frameRect.Max, - ImColor(ImGui::GetStyleColorVec4(ImGuiCol_Button)), + ImColor(ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled)), halfFrame.x); ImGui::PopClipRect(); diff --git a/SHADE_Engine/src/Graphics/Windowing/SHWindow.cpp b/SHADE_Engine/src/Graphics/Windowing/SHWindow.cpp index 44a1cb0e..7995e394 100644 --- a/SHADE_Engine/src/Graphics/Windowing/SHWindow.cpp +++ b/SHADE_Engine/src/Graphics/Windowing/SHWindow.cpp @@ -54,13 +54,14 @@ namespace SHADE if (wndData.isFullscreen) { - dwExStyle = WS_EX_APPWINDOW | WS_EX_ACCEPTFILES; + dwExStyle = WS_EX_APPWINDOW; dwStyle = WS_POPUP | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; + dwExStyle |= WS_EX_ACCEPTFILES; } else { - dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE | WS_EX_ACCEPTFILES; - + dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; + dwExStyle |= WS_EX_ACCEPTFILES; if (wndData.frameEnabled) { dwStyle = WNDSTYLE::SHWS_WINDOWED; @@ -87,7 +88,7 @@ namespace SHADE } } - //DPI_AWARENESS_CONTEXT prevDPIContext = SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); + DPI_AWARENESS_CONTEXT prevDPIContext = SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); RECT windowRect; windowRect.left = wndData.x; //or CW_USEDEFAULT ? @@ -97,13 +98,16 @@ namespace SHADE AdjustWindowRectEx(&windowRect, dwStyle, false, dwExStyle); //Create window - wndHWND = CreateWindowEx(0, (LPWSTR) wndData.name.c_str(), (LPWSTR)wndData.title.c_str(), dwStyle, 0, 0, windowRect.right - windowRect.left, windowRect.bottom - windowRect.top, parent, NULL, hInstance, NULL); - + wndHWND = CreateWindowEx(dwExStyle, (LPWSTR) wndData.name.c_str(), (LPWSTR)wndData.title.c_str(), dwStyle, 0, 0, windowRect.right - windowRect.left, windowRect.bottom - windowRect.top, parent, NULL, hInstance, NULL); + if (!wndHWND) { //DWORD err = GetLastError(); return false; } + BOOL help = ChangeWindowMessageFilter (WM_DROPFILES, MSGFLT_ADD); + help &= ChangeWindowMessageFilter (WM_COPYDATA, MSGFLT_ADD); + help &= ChangeWindowMessageFilter (0x0049, MSGFLT_ADD); if (wndData.isVisible) { @@ -318,13 +322,13 @@ namespace SHADE case WM_CREATE: OnCreate(hwnd, reinterpret_cast(wparam)); break; + case WM_QUIT: case WM_CLOSE: - case WM_DESTROY: OnDestroy(); return 0; case WM_DROPFILES: - //OnFileDrop(reinterpret_cast(wparam)); + OnFileDrop(reinterpret_cast(wparam)); break; case WM_ENTERSIZEMOVE: case WM_EXITSIZEMOVE: @@ -386,12 +390,25 @@ namespace SHADE void SHWindow::OnDestroy() { OnClose(); + DragAcceptFiles(wndHWND, false); this->Destroy(); } - //void SHWindow::OnFileDrop(HDROP drop) - //{ - //} + void SHWindow::OnFileDrop(HDROP drop) + { + + int const numFiles = static_cast(DragQueryFile(drop, 0xFFFFFFFF, nullptr, 0)); + for(int i = 0; i < numFiles; ++i) + { + //char fileNameBuffer[MAX_PATH]; + std::wstring fileNameBuffer; + fileNameBuffer.reserve(MAX_PATH); + DragQueryFile(drop, static_cast(i), fileNameBuffer.data(), MAX_PATH); + std::string name(fileNameBuffer.begin(), fileNameBuffer.end()); + SHLOG_INFO("Dropped: {}", name) + } + DragFinish(drop); + } void SHWindow::OnSize([[maybe_unused]] UINT msg,[[maybe_unused]] UINT type, SIZE size) { diff --git a/SHADE_Engine/src/Graphics/Windowing/SHWindow.h b/SHADE_Engine/src/Graphics/Windowing/SHWindow.h index 0a180285..8068c82e 100644 --- a/SHADE_Engine/src/Graphics/Windowing/SHWindow.h +++ b/SHADE_Engine/src/Graphics/Windowing/SHWindow.h @@ -2,6 +2,7 @@ #define SH_WINDOW_H #include +#include #include #include #include "SHWindowMap.h" @@ -10,7 +11,7 @@ namespace SHADE { constexpr uint16_t MAX_BUFFER = 1024; - + enum WNDSTYLE : DWORD { SHWS_WINDOWED = WS_OVERLAPPEDWINDOW, @@ -168,7 +169,7 @@ namespace SHADE void OnCreate(HWND hwnd, LPCREATESTRUCT create_struct); void OnClose(); void OnDestroy(); - //void OnFileDrop(HDROP drop); + void OnFileDrop(HDROP drop); void OnSize(UINT msg, UINT type, SIZE size); void OnPosChange(LPWINDOWPOS pos); void OnPaint(HDC hdc, LPPAINTSTRUCT paint); From 09c5843cdb2492686e692f5f2237ed73f50c057f Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Thu, 27 Oct 2022 19:02:55 +0800 Subject: [PATCH 13/44] Ambient lighting added --- SHADE_Application/src/Scenes/SBTestScene.cpp | 10 +++++++ .../MiddleEnd/Lights/SHLightComponent.cpp | 15 ++++++++-- .../MiddleEnd/Lights/SHLightComponent.h | 4 ++- .../Graphics/MiddleEnd/Lights/SHLightData.cpp | 2 +- .../Graphics/MiddleEnd/Lights/SHLightData.h | 6 +++- .../MiddleEnd/Lights/SHLightingSubSystem.cpp | 26 ++++++++++++++---- .../MiddleEnd/Lights/SHLightingSubSystem.h | 20 ++++++++++++++ TempShaderFolder/DeferredCompositeCs.glsl | 21 ++++++++++++++ TempShaderFolder/DeferredCompositeCs.spv | Bin 3460 -> 4532 bytes 9 files changed, 94 insertions(+), 10 deletions(-) diff --git a/SHADE_Application/src/Scenes/SBTestScene.cpp b/SHADE_Application/src/Scenes/SBTestScene.cpp index a06e68c2..eb6149ad 100644 --- a/SHADE_Application/src/Scenes/SBTestScene.cpp +++ b/SHADE_Application/src/Scenes/SBTestScene.cpp @@ -162,12 +162,22 @@ namespace Sandbox SHComponentManager::AddComponent(0); SHComponentManager::RemoveComponent (0); SHComponentManager::RemoveComponent (0); + + auto ambientLight = SHEntityManager::CreateEntity(); + SHComponentManager::GetComponent(ambientLight)->SetColor(SHVec4(1.0f, 1.0f, 1.0f, 1.0f)); + SHComponentManager::GetComponent(ambientLight)->SetStrength(0.25f); + SHComponentManager::GetComponent(ambientLight)->SetType(SH_LIGHT_TYPE::AMBIENT); } void SBTestScene::Update(float dt) { static float rotation = 0.0f; + SHVec3 direction{0.0f, 0.0f, 1.0f}; + direction = SHVec3::RotateY(direction, rotation); + auto* lightComp =SHComponentManager::GetComponent(0); + lightComp->SetDirection (direction); + rotation += 0.005f; //auto& transform = *SHADE::SHComponentManager::GetComponent_s(testObj); //transform.SetWorldPosition({1.0f, 1.0f, -1.0f}); diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.cpp index fd122334..6800e955 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.cpp @@ -41,9 +41,9 @@ namespace SHADE } - void SHLightComponent::SetDiffuseColor(SHVec4 diffuseColor) noexcept + void SHLightComponent::SetColor(SHVec4 color) noexcept { - lightData.diffuseColor = diffuseColor; + lightData.color = color; MakeDirty(); } @@ -100,6 +100,12 @@ namespace SHADE } + void SHLightComponent::SetStrength(float value) noexcept + { + lightData.strength = value; + MakeDirty(); + } + SHLightData const& SHLightComponent::GetLightData(void) const noexcept { return lightData; @@ -115,6 +121,11 @@ namespace SHADE return bound; } + bool SHLightComponent::GetActive(void) const noexcept + { + return active; + } + uint32_t SHLightComponent::GetIndexInBuffer(void) const noexcept { return indexInBuffer; diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.h b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.h index 20ae3892..d267d2d4 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.h @@ -40,7 +40,7 @@ namespace SHADE void SetPosition (SHVec3 position) noexcept; void SetType (SH_LIGHT_TYPE type) noexcept; void SetDirection (SHVec3 direction) noexcept; - void SetDiffuseColor (SHVec4 diffuseColor) noexcept; + void SetColor (SHVec4 color) noexcept; void ModifyLayer (uint8_t layerIndex, bool value) noexcept; void SetAllLayers (void) noexcept; void ClearAllLayers (void) noexcept; @@ -49,11 +49,13 @@ namespace SHADE void Unbind (void) noexcept; void SetBound (uint32_t inIndexInBuffer) noexcept; void SetActive (bool flag) noexcept; + void SetStrength (float value) noexcept; SHLightData const& GetLightData (void) const noexcept; bool IsDirty (void) const noexcept; bool GetBound (void) const noexcept; + bool GetActive (void) const noexcept; uint32_t GetIndexInBuffer (void) const noexcept; }; diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightData.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightData.cpp index ba910408..8e8f0783 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightData.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightData.cpp @@ -15,7 +15,7 @@ namespace SHADE direction = SHVec3::Forward; // Diffuse color set to 1 - diffuseColor = SHVec4::One; + color = SHVec4::One; } } \ No newline at end of file diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightData.h b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightData.h index 607978a4..fccc2856 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightData.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightData.h @@ -10,6 +10,7 @@ namespace SHADE DIRECTIONAL = 0, POINT, SPOT, + AMBIENT, NUM_TYPES }; @@ -40,7 +41,10 @@ namespace SHADE uint32_t cullingMask; //! Diffuse color emitted by the light - SHVec4 diffuseColor; + SHVec4 color; + + //! Strength of the light + float strength; void Reset (void) noexcept; //! TODO: diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp index 6e8dd916..97d8b24f 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp @@ -42,13 +42,23 @@ namespace SHADE lightPtr->cullingMask = lightData.cullingMask; lightPtr->direction = lightData.direction; - lightPtr->diffuseColor = lightData.diffuseColor; + lightPtr->diffuseColor = lightData.color; + lightPtr->active = lightComp->GetActive(); break; } case SH_LIGHT_TYPE::POINT: break; case SH_LIGHT_TYPE::SPOT: break; + case SH_LIGHT_TYPE::AMBIENT: + { + SHAmbientLightData* lightPtr = reinterpret_cast(address); + lightPtr->ambientColor = lightData.color; + lightPtr->strength = lightData.strength; + lightPtr->cullingMask = lightData.cullingMask; + lightPtr->active = lightComp->GetActive (); + break; + } case SH_LIGHT_TYPE::NUM_TYPES: break; default: @@ -176,6 +186,9 @@ namespace SHADE case SH_LIGHT_TYPE::SPOT: // TOOD: Change after creating spot light struct return 4; + case SH_LIGHT_TYPE::AMBIENT: + return sizeof(SHAmbientLightData); + return 4; case SH_LIGHT_TYPE::NUM_TYPES: default: return 4; @@ -406,8 +419,8 @@ namespace SHADE { perTypeData[enumValue].AddLight(logicalDevice, &light, expanded); - // add to light count - ++lightCountsData[enumValue]; + //// add to light count + //++lightCountsData[enumValue]; } // if there was modification to the light data @@ -427,6 +440,11 @@ namespace SHADE data.WriteToGPU(frameIndex); } + for (uint32_t i = 0; i < NUM_LIGHT_TYPES; ++i) + { + lightCountsData[i] = perTypeData[i].GetNumLights(); + } + lightCountsBuffer->WriteToMemory(lightCountsData.data(), static_cast(lightCountsData.size()) * sizeof (uint32_t), 0, lightCountsAlignedSize * frameIndex); // If any of the buffers got expanded, the descriptor set is invalid because the expanded buffer @@ -444,8 +462,6 @@ namespace SHADE // so we do it anyway. #NoteToSelf: if at any point it affects performance, do a check before computing. ComputeDynamicOffsets(); - //cmdBuffer->ForceSetPipelineLayout() - // Bind descriptor set (We bind at an offset because the buffer holds NUM_FRAME_BUFFERS sets of data). cmdBuffer->BindDescriptorSet(lightingDataDescSet, SH_PIPELINE_TYPE::COMPUTE, SHGraphicsConstants::DescriptorSetIndex::DYNAMIC_GLOBALS, {dynamicOffsets[frameIndex]}); diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.h b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.h index efc6ddf6..dfb956ec 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.h @@ -35,6 +35,26 @@ namespace SHADE }; + // Represents how the data will be interpreted in GPU. we want to copy to a container of these before passing to GPU. + struct SHAmbientLightData + { + //! Diffuse color emitted by the light + SHVec4 ambientColor; + + //! Strength of the ambient light + float strength; + + //! Represents if the light is active or not + uint32_t active; + + //! Each bit in this 32 bit field will represent a layer. If the bit is set, + //! when a fragment is being evaluated, the shader will use the fragment's + //! layer value to AND with the light's. If result is 1, do lighting calculations. + uint32_t cullingMask; + + + }; + class SH_API SHLightingSubSystem { private: diff --git a/TempShaderFolder/DeferredCompositeCs.glsl b/TempShaderFolder/DeferredCompositeCs.glsl index c707901f..bd482b1a 100644 --- a/TempShaderFolder/DeferredCompositeCs.glsl +++ b/TempShaderFolder/DeferredCompositeCs.glsl @@ -8,6 +8,14 @@ struct DirectionalLightStruct vec4 diffuseColor; }; +struct AmbientLightStruct +{ + vec4 ambientColor; + float strength; + uint isActive; + uint cullingMask; +}; + layout(local_size_x = 16, local_size_y = 16) in; layout(set = 4, binding = 0, rgba32f) uniform image2D positions; layout(set = 4, binding = 1, rgba32f) uniform image2D normals; @@ -19,6 +27,7 @@ layout(set = 1, binding = 0) uniform LightCounts uint directionalLights; uint pointLights; uint spotLights; + uint ambientLights; } lightCounts; @@ -27,6 +36,11 @@ layout(std430, set = 1, binding = 1) buffer DirectionalLightData DirectionalLightStruct dLightData[]; } DirLightData; +layout(std430, set = 1, binding = 4) buffer AmbientLightData +{ + AmbientLightStruct aLightData[]; +} AmbLightData; + void main() { // convenient variables @@ -55,6 +69,13 @@ void main() fragColor += DirLightData.dLightData[i].diffuseColor.rgb * diffuseStrength.rrr * pixelDiffuse; } + for (int i = 0; i < lightCounts.ambientLights; ++i) + { + // Just do some add + //fragColor += pixelDiffuse.rgb * AmbLightData.aLightData[i].ambientColor.rgb * vec3 (0.5f); + fragColor += pixelDiffuse.rgb * AmbLightData.aLightData[i].ambientColor.rgb * vec3 (AmbLightData.aLightData[i].strength); + } + // store result into result image imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(fragColor, 1.0f)); diff --git a/TempShaderFolder/DeferredCompositeCs.spv b/TempShaderFolder/DeferredCompositeCs.spv index 455ab5483f63c9c8c37d786c435e1d7ca6138b50..4ec7ac0f659951dcc4c1a5dcbdfd79bf13eaee50 100644 GIT binary patch delta 1472 zcmYk5%W6|m6oz;1Z8V^u)C(=qj6@N{iBQrK6zf1~MRepOO=FriO*A>FR$EW1X}#22 z8yq?C6_hv=pTUt2(2;K-UJ(4hlfC7f@U!;%*V=3Sd#|1D(NDQdESgIh6ESI%F};tO zKanFzlQQGRn3zypnyr@W-sNg#-fNkDGMbI}F*Bz~RY)lFwrnAkb}^ux3?Sn>chGN!SXqdgTUV0 z5&4_4^ih8AU1~VLMZk0>PbvogM&K@;zpZsdI3=xnWOoE|z;BP!n3$guHM)umj;s z1Ku|ulvI#Y7uZPPw+i9k5)eQ`)-*gQ+Ym;qkASv-fP(%?H)NLuZka<7!?Ksj-4%#W zn<3Tmjk#w@0(@K_nJqTWNx!LOmL- z;Lo=qbgj>WdLm?mX{H9Z^KpB;gOuzufw()&bFC44RbsfA7e>zwlFyMZwT7dR h<6c=VDm$an%<;9L0)~9zTS7^V5lmy^e^uq2@DG4#r_cZZ delta 407 zcmX|-OG*P#5Jhi)l4whV10{+?(CA2U90(#AITCdZCjNhkQ$+{vpr=CCAni=tf%|Zx zD-gkR+in{U^={Rzs`vV({kV`uVY?v(N|fs6IsFdum2feLYU*dL_%-{C-&eO4t1oF8 zVyN^I=cv@9{I34ywrrcfOXY1 zMI3=WW|)0Vj`OFa6W?#rK1XT*UTJOn5u~uIMzQ|5%sKDRqi^x@2Xq3iyLXm&3LCJm vT5;9$GDrB&UHs*Cib0j}vNZagdyH-oufPM`;JV*^z#?DRi(UU=N(X)c55_6? From 0cab0107b2a2f549833942508c1d38177c5b95c6 Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Thu, 27 Oct 2022 19:37:05 +0800 Subject: [PATCH 14/44] Fixed minimizing by resetting command pools and fences --- Assets/Editor/Layouts/UserLayout.ini | 22 +++++++++--------- .../MiddleEnd/Interface/SHGraphicsSystem.cpp | 21 +++++++++++++---- TempShaderFolder/DeferredCompositeCs.glsl | 3 ++- TempShaderFolder/DeferredCompositeCs.spv | Bin 4532 -> 4656 bytes 4 files changed, 30 insertions(+), 16 deletions(-) diff --git a/Assets/Editor/Layouts/UserLayout.ini b/Assets/Editor/Layouts/UserLayout.ini index e27f5cca..664330ba 100644 --- a/Assets/Editor/Layouts/UserLayout.ini +++ b/Assets/Editor/Layouts/UserLayout.ini @@ -10,7 +10,7 @@ Collapsed=0 [Window][Hierarchy Panel] Pos=0,142 -Size=494,690 +Size=382,690 Collapsed=0 DockId=0x00000007,0 @@ -20,14 +20,14 @@ Size=400,400 Collapsed=0 [Window][Inspector] -Pos=1649,48 -Size=271,1012 +Pos=1588,48 +Size=332,1012 Collapsed=0 DockId=0x00000006,0 [Window][Profiler] Pos=0,48 -Size=494,92 +Size=382,92 Collapsed=0 DockId=0x00000003,0 @@ -38,25 +38,25 @@ Collapsed=0 DockId=0x00000002,0 [Window][ Viewport] -Pos=496,48 -Size=1151,1012 +Pos=384,48 +Size=1202,1012 Collapsed=0 DockId=0x00000002,0 [Window][ Asset Browser] Pos=0,834 -Size=494,226 +Size=382,226 Collapsed=0 DockId=0x00000008,0 [Docking][Data] DockSpace ID=0xC5C9B8AB Window=0xBE4044E9 Pos=8,79 Size=1920,1012 Split=X - DockNode ID=0x00000005 Parent=0xC5C9B8AB SizeRef=1992,1036 Split=X - DockNode ID=0x00000001 Parent=0x00000005 SizeRef=494,1036 Split=Y Selected=0x1E6EB881 + DockNode ID=0x00000005 Parent=0xC5C9B8AB SizeRef=1586,1036 Split=X + DockNode ID=0x00000001 Parent=0x00000005 SizeRef=382,1036 Split=Y Selected=0x1E6EB881 DockNode ID=0x00000003 Parent=0x00000001 SizeRef=225,94 Selected=0x1E6EB881 DockNode ID=0x00000004 Parent=0x00000001 SizeRef=225,940 Split=Y Selected=0xE096E5AE DockNode ID=0x00000007 Parent=0x00000004 SizeRef=494,690 Selected=0xE096E5AE DockNode ID=0x00000008 Parent=0x00000004 SizeRef=494,226 Selected=0xB128252A - DockNode ID=0x00000002 Parent=0x00000005 SizeRef=1151,1036 CentralNode=1 Selected=0xB41284E7 - DockNode ID=0x00000006 Parent=0xC5C9B8AB SizeRef=271,1036 Selected=0xE7039252 + DockNode ID=0x00000002 Parent=0x00000005 SizeRef=1202,1036 CentralNode=1 Selected=0xB41284E7 + DockNode ID=0x00000006 Parent=0xC5C9B8AB SizeRef=332,1036 Selected=0xE7039252 diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp index df884f57..ad040cd9 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp @@ -183,10 +183,10 @@ namespace SHADE worldRenderGraph->Init(device, swapchain); worldRenderGraph->AddResource("Position", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second, vk::Format::eR32G32B32A32Sfloat); worldRenderGraph->AddResource("Normals", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second, vk::Format::eR32G32B32A32Sfloat); - worldRenderGraph->AddResource("Albedo", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second); + worldRenderGraph->AddResource("Albedo", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second); worldRenderGraph->AddResource("Depth Buffer", { SH_ATT_DESC_TYPE_FLAGS::DEPTH_STENCIL }, windowDims.first, windowDims.second, vk::Format::eD32SfloatS8Uint); - worldRenderGraph->AddResource("Entity ID", { SH_ATT_DESC_TYPE_FLAGS::COLOR }, windowDims.first, windowDims.second, vk::Format::eR32Uint, 1, vk::ImageUsageFlagBits::eTransferSrc); - worldRenderGraph->AddResource("Light Layer Indices", { SH_ATT_DESC_TYPE_FLAGS::COLOR }, windowDims.first, windowDims.second, vk::Format::eR32Uint, 1, vk::ImageUsageFlagBits::eTransferSrc); + worldRenderGraph->AddResource("Entity ID", { SH_ATT_DESC_TYPE_FLAGS::COLOR }, windowDims.first, windowDims.second, vk::Format::eR32Uint, 1, vk::ImageUsageFlagBits::eTransferSrc); + worldRenderGraph->AddResource("Light Layer Indices", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second, vk::Format::eR32Uint, 1, vk::ImageUsageFlagBits::eTransferSrc); worldRenderGraph->AddResource("Scene", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second); auto gBufferNode = worldRenderGraph->AddNode("G-Buffer", @@ -219,7 +219,7 @@ namespace SHADE // deferred composite auto deferredCompositeShader = shaderModuleLibrary.GetShaderModule("DeferredCompositeCs.glsl"); - gBufferNode->AddNodeCompute(deferredCompositeShader, { "Position", "Normals", "Albedo", "Scene" }); + gBufferNode->AddNodeCompute(deferredCompositeShader, { "Position", "Normals", "Albedo", "Light Layer Indices", "Scene" }); auto dummyNode = worldRenderGraph->AddNode("Dummy Pass", { "Scene" }, {"G-Buffer"}); // no predecessors @@ -486,7 +486,20 @@ namespace SHADE void SHGraphicsSystem::BeginRender() { if (window->IsMinimized() || renderContext.GetWindowIsDead()) + { + // #BackEndTest: For for the fence initialized by queue submit + renderContext.WaitForFence(); + + // #BackEndTest: Get the current frame from frame manager + auto& currFrameData = renderContext.GetCurrentFrameData(); + + // #BackEndTest: Reset command pool + if (currFrameData.cmdPoolHdls.empty()) + throw std::runtime_error("No command pools available!"); + currFrameData.cmdPoolHdls[0]->Reset(); + return; + } // Finalise all batches for (auto vp : viewports) diff --git a/TempShaderFolder/DeferredCompositeCs.glsl b/TempShaderFolder/DeferredCompositeCs.glsl index bd482b1a..c1caf0aa 100644 --- a/TempShaderFolder/DeferredCompositeCs.glsl +++ b/TempShaderFolder/DeferredCompositeCs.glsl @@ -20,7 +20,8 @@ layout(local_size_x = 16, local_size_y = 16) in; layout(set = 4, binding = 0, rgba32f) uniform image2D positions; layout(set = 4, binding = 1, rgba32f) uniform image2D normals; layout(set = 4, binding = 2, rgba8) uniform image2D albedo; -layout(set = 4, binding = 3, rgba8) uniform image2D targetImage; +layout(set = 4, binding = 3, r32ui) uniform uimage2D lightLayerData; +layout(set = 4, binding = 4, rgba8) uniform image2D targetImage; layout(set = 1, binding = 0) uniform LightCounts { diff --git a/TempShaderFolder/DeferredCompositeCs.spv b/TempShaderFolder/DeferredCompositeCs.spv index 4ec7ac0f659951dcc4c1a5dcbdfd79bf13eaee50..03ef7ac5b615ad4dd42a57f4cad2daf5876ceb6a 100644 GIT binary patch delta 159 zcmdm@yg`MRnMs+Qfq{{Mi-DJ6+D2Y^7I9VvHioGT3=BD$=@}(HiIu5EE{P?H44buC zJedqxfD-NuEDV!?G&c}SLir#KN=W%ubnvxd` delta 55 zcmdm>vPGGfnMs+Qfq{{Mi-DJ6@ Date: Fri, 28 Oct 2022 12:47:17 +0800 Subject: [PATCH 15/44] fix hierarchy panel menu bar padding --- .../Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp b/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp index fff0a188..6f65b734 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp +++ b/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp @@ -93,7 +93,9 @@ namespace SHADE { if (ImGui::BeginMenuBar()) { - ImGui::SetCursorPosX(ImGui::GetContentRegionAvail().x * 0.75f); + auto size = ImGui::GetWindowSize(); + auto g = ImGui::GetCurrentContext(); + ImGui::SetCursorPosX(size.x - g->Style.FramePadding.x * 15.0f); if(ImGui::SmallButton(ICON_MD_DESELECT)) { auto editor = SHSystemManager::GetSystem(); From 5ab2ebbff45263cce8c513a692458a28bbc9c718 Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Fri, 28 Oct 2022 13:54:46 +0800 Subject: [PATCH 16/44] Getters for light --- .../MiddleEnd/Lights/SHLightComponent.cpp | 32 ++++++++++++++++-- .../MiddleEnd/Lights/SHLightComponent.h | 33 ++++++++++--------- .../Graphics/MiddleEnd/Lights/SHLightData.h | 3 ++ 3 files changed, 50 insertions(+), 18 deletions(-) diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.cpp index 6800e955..39bfccd9 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.cpp @@ -10,7 +10,7 @@ namespace SHADE lightData.Reset(); SetType(SH_LIGHT_TYPE::DIRECTIONAL); indexInBuffer = std::numeric_limits::max(); - active = true; + lightData.active = true; Unbind(); } @@ -96,7 +96,7 @@ namespace SHADE void SHLightComponent::SetActive(bool flag) noexcept { MakeDirty(); - active = flag; + lightData.active = flag; } @@ -111,6 +111,32 @@ namespace SHADE return lightData; } + SHVec3 const& SHLightComponent::GetPosition(void) const noexcept + { + return lightData.position; + } + + SH_LIGHT_TYPE SHLightComponent::GetType(void) const noexcept + { + return lightData.type; + } + + SHVec3 const& SHLightComponent::GetDirection(void) const noexcept + { + return lightData.direction; + } + + SHVec4 const& SHLightComponent::GetColor(void) const noexcept + { + return lightData.color; + } + + uint32_t const& SHLightComponent::GetCullingMask(void) const noexcept + { + return lightData.cullingMask; + } + + bool SHLightComponent::IsDirty(void) const noexcept { return dirty; @@ -123,7 +149,7 @@ namespace SHADE bool SHLightComponent::GetActive(void) const noexcept { - return active; + return lightData.active; } uint32_t SHLightComponent::GetIndexInBuffer(void) const noexcept diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.h b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.h index d267d2d4..45c205c2 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.h @@ -24,8 +24,6 @@ namespace SHADE //! If the light's data is already in the buffers, this will be set to true. bool bound; - //! If the light is active, this is true. - bool active; public: /*-----------------------------------------------------------------------*/ @@ -37,25 +35,30 @@ namespace SHADE /*-----------------------------------------------------------------------*/ /* SETTERS AND GETTERS */ /*-----------------------------------------------------------------------*/ - void SetPosition (SHVec3 position) noexcept; - void SetType (SH_LIGHT_TYPE type) noexcept; - void SetDirection (SHVec3 direction) noexcept; - void SetColor (SHVec4 color) noexcept; - void ModifyLayer (uint8_t layerIndex, bool value) noexcept; - void SetAllLayers (void) noexcept; - void ClearAllLayers (void) noexcept; - void MakeDirty (void) noexcept; + void SetPosition (SHVec3 position) noexcept; // serialized + void SetType (SH_LIGHT_TYPE type) noexcept; // serialized + void SetDirection (SHVec3 direction) noexcept; // serialized + void SetColor (SHVec4 color) noexcept; // serialized + void ModifyLayer (uint8_t layerIndex, bool value) noexcept; // serialized + void SetAllLayers (void) noexcept; // serialized + void ClearAllLayers (void) noexcept; // serialized + void MakeDirty (void) noexcept; void ClearDirtyFlag (void) noexcept; - void Unbind (void) noexcept; + void Unbind (void) noexcept; void SetBound (uint32_t inIndexInBuffer) noexcept; - void SetActive (bool flag) noexcept; - void SetStrength (float value) noexcept; + void SetActive (bool flag) noexcept; // serialized + void SetStrength (float value) noexcept; // serialized - SHLightData const& GetLightData (void) const noexcept; + SHLightData const& GetLightData (void) const noexcept; + SHVec3 const& GetPosition (void) const noexcept; // serialized + SH_LIGHT_TYPE GetType (void) const noexcept; // serialized + SHVec3 const& GetDirection (void) const noexcept; // serialized + SHVec4 const& GetColor (void) const noexcept; // serialized + uint32_t const& GetCullingMask (void) const noexcept; // serialized bool IsDirty (void) const noexcept; bool GetBound (void) const noexcept; - bool GetActive (void) const noexcept; + bool GetActive (void) const noexcept; // serialized uint32_t GetIndexInBuffer (void) const noexcept; }; diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightData.h b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightData.h index fccc2856..05938647 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightData.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightData.h @@ -46,6 +46,9 @@ namespace SHADE //! Strength of the light float strength; + //! If the light is active, this is true. + bool active; + void Reset (void) noexcept; //! TODO: //! - Add cut off. (inner and outer). From baa77e5d37e4af2a95607067ce0259f4f0f1293b Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Fri, 28 Oct 2022 14:10:08 +0800 Subject: [PATCH 17/44] setter for culling mask --- .../MiddleEnd/Lights/SHLightComponent.cpp | 7 ++++- .../MiddleEnd/Lights/SHLightComponent.h | 27 ++++++++++--------- 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.cpp index 39bfccd9..e8d7b6f7 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.cpp @@ -47,7 +47,7 @@ namespace SHADE MakeDirty(); } - void SHLightComponent::ModifyLayer(uint8_t layerIndex, bool value) noexcept + void SHLightComponent::ModifyCullingMask(uint8_t layerIndex, bool value) noexcept { if (value) lightData.cullingMask |= (1u << layerIndex); @@ -58,6 +58,11 @@ namespace SHADE } + void SHLightComponent::SetCullingMask(uint32_t value) noexcept + { + lightData.cullingMask = value; + } + void SHLightComponent::SetAllLayers(void) noexcept { lightData.cullingMask = std::numeric_limits::max(); diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.h b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.h index 45c205c2..951e6071 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.h @@ -35,19 +35,20 @@ namespace SHADE /*-----------------------------------------------------------------------*/ /* SETTERS AND GETTERS */ /*-----------------------------------------------------------------------*/ - void SetPosition (SHVec3 position) noexcept; // serialized - void SetType (SH_LIGHT_TYPE type) noexcept; // serialized - void SetDirection (SHVec3 direction) noexcept; // serialized - void SetColor (SHVec4 color) noexcept; // serialized - void ModifyLayer (uint8_t layerIndex, bool value) noexcept; // serialized - void SetAllLayers (void) noexcept; // serialized - void ClearAllLayers (void) noexcept; // serialized - void MakeDirty (void) noexcept; - void ClearDirtyFlag (void) noexcept; - void Unbind (void) noexcept; - void SetBound (uint32_t inIndexInBuffer) noexcept; - void SetActive (bool flag) noexcept; // serialized - void SetStrength (float value) noexcept; // serialized + void SetPosition (SHVec3 position) noexcept; // serialized + void SetType (SH_LIGHT_TYPE type) noexcept; // serialized + void SetDirection (SHVec3 direction) noexcept; // serialized + void SetColor (SHVec4 color) noexcept; // serialized + void ModifyCullingMask (uint8_t layerIndex, bool value) noexcept; // serialized + void SetCullingMask (uint32_t value) noexcept; + void SetAllLayers (void) noexcept; // serialized + void ClearAllLayers (void) noexcept; // serialized + void MakeDirty (void) noexcept; + void ClearDirtyFlag (void) noexcept; + void Unbind (void) noexcept; + void SetBound (uint32_t inIndexInBuffer) noexcept; + void SetActive (bool flag) noexcept; // serialized + void SetStrength (float value) noexcept; // serialized SHLightData const& GetLightData (void) const noexcept; From f110f9b16ba64aa9d90fe68886b3b76c13f6cb0e Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Fri, 28 Oct 2022 15:56:22 +0800 Subject: [PATCH 18/44] Removed isActive from component --- .../Graphics/MiddleEnd/Lights/SHLightComponent.cpp | 13 +------------ .../Graphics/MiddleEnd/Lights/SHLightComponent.h | 2 -- .../src/Graphics/MiddleEnd/Lights/SHLightData.h | 2 -- .../MiddleEnd/Lights/SHLightingSubSystem.cpp | 4 ++-- 4 files changed, 3 insertions(+), 18 deletions(-) diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.cpp index e8d7b6f7..35278a81 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.cpp @@ -10,7 +10,7 @@ namespace SHADE lightData.Reset(); SetType(SH_LIGHT_TYPE::DIRECTIONAL); indexInBuffer = std::numeric_limits::max(); - lightData.active = true; + isActive = true; Unbind(); } @@ -98,12 +98,6 @@ namespace SHADE indexInBuffer = inIndexInBuffer; } - void SHLightComponent::SetActive(bool flag) noexcept - { - MakeDirty(); - lightData.active = flag; - - } void SHLightComponent::SetStrength(float value) noexcept { @@ -152,11 +146,6 @@ namespace SHADE return bound; } - bool SHLightComponent::GetActive(void) const noexcept - { - return lightData.active; - } - uint32_t SHLightComponent::GetIndexInBuffer(void) const noexcept { return indexInBuffer; diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.h b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.h index 951e6071..2cea9f1a 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.h @@ -47,7 +47,6 @@ namespace SHADE void ClearDirtyFlag (void) noexcept; void Unbind (void) noexcept; void SetBound (uint32_t inIndexInBuffer) noexcept; - void SetActive (bool flag) noexcept; // serialized void SetStrength (float value) noexcept; // serialized @@ -59,7 +58,6 @@ namespace SHADE uint32_t const& GetCullingMask (void) const noexcept; // serialized bool IsDirty (void) const noexcept; bool GetBound (void) const noexcept; - bool GetActive (void) const noexcept; // serialized uint32_t GetIndexInBuffer (void) const noexcept; }; diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightData.h b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightData.h index 05938647..e9a02c1a 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightData.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightData.h @@ -46,8 +46,6 @@ namespace SHADE //! Strength of the light float strength; - //! If the light is active, this is true. - bool active; void Reset (void) noexcept; //! TODO: diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp index 97d8b24f..e8d85dd1 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp @@ -43,7 +43,7 @@ namespace SHADE lightPtr->cullingMask = lightData.cullingMask; lightPtr->direction = lightData.direction; lightPtr->diffuseColor = lightData.color; - lightPtr->active = lightComp->GetActive(); + lightPtr->active = lightComp->isActive; break; } case SH_LIGHT_TYPE::POINT: @@ -56,7 +56,7 @@ namespace SHADE lightPtr->ambientColor = lightData.color; lightPtr->strength = lightData.strength; lightPtr->cullingMask = lightData.cullingMask; - lightPtr->active = lightComp->GetActive (); + lightPtr->active = lightComp->isActive; break; } case SH_LIGHT_TYPE::NUM_TYPES: From fa6e3cf1df1e7a8e2ed851c4f90d24ea93c53049 Mon Sep 17 00:00:00 2001 From: Sri Sham Haran Date: Fri, 28 Oct 2022 17:58:16 +0800 Subject: [PATCH 19/44] Light Component Serialization & Inspector --- Assets/Editor/Layouts/UserLayout.ini | 62 ------------------- .../Inspector/SHEditorComponentView.hpp | 44 +++++++++++++ .../Inspector/SHEditorInspector.cpp | 5 ++ SHADE_Engine/src/Editor/SHEditorWidgets.hpp | 40 +++++++++++- .../MiddleEnd/Lights/SHLightComponent.cpp | 37 +++++++++-- .../MiddleEnd/Lights/SHLightComponent.h | 12 ++-- .../src/Serialization/SHSerialization.cpp | 10 +++ .../Serialization/SHSerializationHelper.hpp | 4 +- 8 files changed, 139 insertions(+), 75 deletions(-) delete mode 100644 Assets/Editor/Layouts/UserLayout.ini diff --git a/Assets/Editor/Layouts/UserLayout.ini b/Assets/Editor/Layouts/UserLayout.ini deleted file mode 100644 index 664330ba..00000000 --- a/Assets/Editor/Layouts/UserLayout.ini +++ /dev/null @@ -1,62 +0,0 @@ -[Window][MainStatusBar] -Pos=0,1060 -Size=1920,20 -Collapsed=0 - -[Window][SHEditorMenuBar] -Pos=0,48 -Size=1920,1012 -Collapsed=0 - -[Window][Hierarchy Panel] -Pos=0,142 -Size=382,690 -Collapsed=0 -DockId=0x00000007,0 - -[Window][Debug##Default] -Pos=60,60 -Size=400,400 -Collapsed=0 - -[Window][Inspector] -Pos=1588,48 -Size=332,1012 -Collapsed=0 -DockId=0x00000006,0 - -[Window][Profiler] -Pos=0,48 -Size=382,92 -Collapsed=0 -DockId=0x00000003,0 - -[Window][Viewport] -Pos=648,48 -Size=2519,1319 -Collapsed=0 -DockId=0x00000002,0 - -[Window][ Viewport] -Pos=384,48 -Size=1202,1012 -Collapsed=0 -DockId=0x00000002,0 - -[Window][ Asset Browser] -Pos=0,834 -Size=382,226 -Collapsed=0 -DockId=0x00000008,0 - -[Docking][Data] -DockSpace ID=0xC5C9B8AB Window=0xBE4044E9 Pos=8,79 Size=1920,1012 Split=X - DockNode ID=0x00000005 Parent=0xC5C9B8AB SizeRef=1586,1036 Split=X - DockNode ID=0x00000001 Parent=0x00000005 SizeRef=382,1036 Split=Y Selected=0x1E6EB881 - DockNode ID=0x00000003 Parent=0x00000001 SizeRef=225,94 Selected=0x1E6EB881 - DockNode ID=0x00000004 Parent=0x00000001 SizeRef=225,940 Split=Y Selected=0xE096E5AE - DockNode ID=0x00000007 Parent=0x00000004 SizeRef=494,690 Selected=0xE096E5AE - DockNode ID=0x00000008 Parent=0x00000004 SizeRef=494,226 Selected=0xB128252A - DockNode ID=0x00000002 Parent=0x00000005 SizeRef=1202,1036 CentralNode=1 Selected=0xB41284E7 - DockNode ID=0x00000006 Parent=0xC5C9B8AB SizeRef=332,1036 Selected=0xE7039252 - diff --git a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp index 7fa39d74..043eba0a 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp +++ b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp @@ -13,10 +13,24 @@ #include "Editor/IconsFontAwesome6.h" #include "ECS_Base/Components/SHComponent.h" #include "Editor/SHEditorWidgets.hpp" +#include "Graphics/MiddleEnd/Lights/SHLightComponent.h" #include "Physics/Components/SHColliderComponent.h" #include "Reflection/SHReflectionMetadata.h" namespace SHADE { + template + std::vector GetRTTREnumNames() + { + auto const rttrType = rttr::type::get(); + if(!rttrType.is_enumeration()) + return {}; + auto const enumAlign = rttrType.get_enumeration(); + auto const names = enumAlign.get_names(); + std::vector result; + std::transform(names.begin(), names.end(), std::back_inserter(result), [](rttr::string_view const& name){return name.data();}); + return result; + } + template::value, bool> = true> static void DrawContextMenu(T* component) { @@ -273,4 +287,34 @@ namespace SHADE } else DrawContextMenu(component); } + + template<> + static void DrawComponent(SHLightComponent* component) + { + if (!component) + return; + const auto componentType = rttr::type::get(*component); + SHEditorWidgets::CheckBox("##IsActive", [component]() {return component->isActive; }, [component](bool const& active) {component->isActive = active; }); + ImGui::SameLine(); + if (ImGui::CollapsingHeader(componentType.get_name().data())) + { + DrawContextMenu(component); + + static auto const enumAlign = rttr::type::get().get_enumeration(); + static std::vector list(GetRTTREnumNames()); + + SHEditorWidgets::ComboBox("Type", list, [component] {return static_cast(component->GetType()); }, [component](int const& idx) + { + component->SetType(static_cast(idx)); + }); + SHEditorWidgets::DragVec3("Position", {"X", "Y", "Z"}, [component](){return component->GetPosition();}, [component](SHVec3 const& vec){component->SetPosition(vec);}); + SHEditorWidgets::DragVec3("Direction", {"X", "Y", "Z"}, [component](){return component->GetDirection();}, [component](SHVec3 const& vec){component->SetDirection(vec);}); + SHEditorWidgets::ColorPicker("Color", [component](){return component->GetColor();}, [component](SHVec4 const& rgba){component->SetColor(rgba);}); + SHEditorWidgets::DragFloat("Strength", [component](){return component->GetStrength();}, [component](float const& value){component->SetStrength(value);}); + } + else + { + DrawContextMenu(component); + } + } } \ No newline at end of file diff --git a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorInspector.cpp b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorInspector.cpp index ada5a35a..92ccbbc9 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorInspector.cpp +++ b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorInspector.cpp @@ -82,6 +82,10 @@ namespace SHADE { DrawComponent(rigidbodyComponent); } + if(auto lightComponent = SHComponentManager::GetComponent_s(eid)) + { + DrawComponent(lightComponent); + } ImGui::Separator(); // Render Scripts SHScriptEngine* scriptEngine = static_cast(SHSystemManager::GetSystem()); @@ -92,6 +96,7 @@ namespace SHADE DrawAddComponentButton(eid); DrawAddComponentButton(eid); DrawAddComponentButton(eid); + DrawAddComponentButton(eid); if(DrawAddComponentButton(eid)) { if(SHComponentManager::GetComponent_s(eid) == nullptr) diff --git a/SHADE_Engine/src/Editor/SHEditorWidgets.hpp b/SHADE_Engine/src/Editor/SHEditorWidgets.hpp index b54a6799..46538827 100644 --- a/SHADE_Engine/src/Editor/SHEditorWidgets.hpp +++ b/SHADE_Engine/src/Editor/SHEditorWidgets.hpp @@ -192,8 +192,8 @@ namespace SHADE ImGuiColors::colors[i], 4); ImGui::SameLine(0, g.Style.ItemInnerSpacing.x); - ImGui::PopID(); ImGui::PopItemWidth(); + ImGui::PopID(); } ImGui::EndColumns(); ImGui::PopID(); @@ -615,5 +615,43 @@ namespace SHADE } return edited; } + + static bool ColorPicker(const std::string_view& label, std::function get, std::function set, std::string_view const& tooltip = {}, float speed = 0.1f, const char* displayFormat = "%.3f", float valueMin = 0.0f, float valueMax = 0.0f, + ImGuiSliderFlags flags = 0) + { + bool changed = false; + ImGui::BeginGroup(); + ImGui::PushID(label.data()); + + SHVec4 values = get(); + //changed |= DragN(label.data(), {"R", "G", "B", "A"}, { &values.x, &values.y, &values.z, &values.w }, speed, displayFormat, valueMin, valueMax, flags); + //ImGui::SameLine(); + TextLabel(label); + changed = ImGui::ColorEdit4("##Col4", &values.x, ImGuiColorEditFlags_AlphaPreviewHalf | ImGuiColorEditFlags_AlphaBar | ImGuiColorEditFlags_DisplayRGB ); + static bool startRecording = false; + if(changed) + { + SHCommandManager::PerformCommand(std::reinterpret_pointer_cast(std::make_shared>(get(), values, set)), startRecording); + if(!startRecording) + startRecording = true; + } + if (startRecording && ImGui::IsMouseReleased(ImGuiMouseButton_Left)) + { + startRecording = false; + } + ImGui::PopID(); + ImGui::EndGroup(); + if (!tooltip.empty()) + { + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::Text(tooltip.data()); + ImGui::EndTooltip(); + } + } + return changed; + } }; + }//namespace SHADE diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.cpp index 35278a81..fb8795fa 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.cpp @@ -20,7 +20,7 @@ namespace SHADE } - void SHLightComponent::SetPosition(SHVec3 position) noexcept + void SHLightComponent::SetPosition(SHVec3 const& position) noexcept { lightData.position = position; MakeDirty(); @@ -34,14 +34,14 @@ namespace SHADE } - void SHLightComponent::SetDirection(SHVec3 direction) noexcept + void SHLightComponent::SetDirection(SHVec3 const& direction) noexcept { lightData.direction = direction; MakeDirty(); } - void SHLightComponent::SetColor(SHVec4 color) noexcept + void SHLightComponent::SetColor(SHVec4 const& color) noexcept { lightData.color = color; MakeDirty(); @@ -57,8 +57,7 @@ namespace SHADE MakeDirty(); } - - void SHLightComponent::SetCullingMask(uint32_t value) noexcept + void SHLightComponent::SetCullingMask(uint32_t const& value) noexcept { lightData.cullingMask = value; } @@ -151,4 +150,32 @@ namespace SHADE return indexInBuffer; } + float SHLightComponent::GetStrength(void) const noexcept + { + return lightData.strength; + } + +} + +RTTR_REGISTRATION +{ + using namespace SHADE; + using namespace rttr; + + registration::enumeration("Light Type") + ( + value("Directional", SH_LIGHT_TYPE::DIRECTIONAL), + value("Point", SH_LIGHT_TYPE::POINT), + value("Spot", SH_LIGHT_TYPE::SPOT), + value("Ambient", SH_LIGHT_TYPE::AMBIENT) + ); + + registration::class_("Light Component") + .property("Position", &SHLightComponent::GetPosition, &SHLightComponent::SetPosition) + .property("Type", &SHLightComponent::GetType, &SHLightComponent::SetType) + .property("Direction", &SHLightComponent::GetDirection, &SHLightComponent::SetDirection) + .property("Color", &SHLightComponent::GetColor, &SHLightComponent::SetColor) + .property("Layer", &SHLightComponent::GetCullingMask, &SHLightComponent::SetCullingMask) + .property("Strength", &SHLightComponent::GetStrength, &SHLightComponent::SetStrength) + ; } diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.h b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.h index 2cea9f1a..81eb80f5 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.h @@ -1,5 +1,6 @@ #pragma once +#include #include "ECS_Base/Components/SHComponent.h" #include "SHLightData.h" @@ -35,12 +36,12 @@ namespace SHADE /*-----------------------------------------------------------------------*/ /* SETTERS AND GETTERS */ /*-----------------------------------------------------------------------*/ - void SetPosition (SHVec3 position) noexcept; // serialized + void SetPosition (SHVec3 const& position) noexcept; // serialized void SetType (SH_LIGHT_TYPE type) noexcept; // serialized - void SetDirection (SHVec3 direction) noexcept; // serialized - void SetColor (SHVec4 color) noexcept; // serialized + void SetDirection (SHVec3 const& direction) noexcept; // serialized + void SetColor (SHVec4 const& color) noexcept; // serialized void ModifyCullingMask (uint8_t layerIndex, bool value) noexcept; // serialized - void SetCullingMask (uint32_t value) noexcept; + void SetCullingMask (uint32_t const& value) noexcept; void SetAllLayers (void) noexcept; // serialized void ClearAllLayers (void) noexcept; // serialized void MakeDirty (void) noexcept; @@ -59,6 +60,7 @@ namespace SHADE bool IsDirty (void) const noexcept; bool GetBound (void) const noexcept; uint32_t GetIndexInBuffer (void) const noexcept; - + float GetStrength (void) const noexcept; + RTTR_ENABLE() }; } diff --git a/SHADE_Engine/src/Serialization/SHSerialization.cpp b/SHADE_Engine/src/Serialization/SHSerialization.cpp index 3804db95..73442092 100644 --- a/SHADE_Engine/src/Serialization/SHSerialization.cpp +++ b/SHADE_Engine/src/Serialization/SHSerialization.cpp @@ -14,6 +14,7 @@ #include "Math/Transform/SHTransformComponent.h" #include "Physics/Components/SHRigidBodyComponent.h" #include "ECS_Base/Managers/SHSystemManager.h" +#include "Graphics/MiddleEnd/Lights/SHLightComponent.h" #include "Scripting/SHScriptEngine.h" namespace SHADE @@ -192,6 +193,10 @@ namespace SHADE { components[rttr::type::get().get_name().data()] = SHSerializationHelper::SerializeComponentToNode(rigidbody); } + if(const auto light = SHComponentManager::GetComponent_s(eid)) + { + components[rttr::type::get().get_name().data()] = SHSerializationHelper::SerializeComponentToNode(light); + } node[ComponentsNode] = components; YAML::Node scripts; @@ -250,6 +255,10 @@ namespace SHADE if (id.has_value()) componentIDList.push_back(id.value()); + id = GetComponentID(componentsNode); + if(id.has_value()) + componentIDList.push_back(id.value()); + return componentIDList; } @@ -259,5 +268,6 @@ namespace SHADE if (!componentsNode) return; SHSerializationHelper::InitializeComponentFromNode(componentsNode, eid); + SHSerializationHelper::InitializeComponentFromNode(componentsNode, eid); } } diff --git a/SHADE_Engine/src/Serialization/SHSerializationHelper.hpp b/SHADE_Engine/src/Serialization/SHSerializationHelper.hpp index da98c885..fddd330c 100644 --- a/SHADE_Engine/src/Serialization/SHSerializationHelper.hpp +++ b/SHADE_Engine/src/Serialization/SHSerializationHelper.hpp @@ -188,12 +188,12 @@ namespace SHADE return; auto rttrType = rttr::type::get(); auto componentNode = componentsNode[rttrType.get_name().data()]; - if (componentsNode.IsNull()) + if(!componentNode.IsDefined()) return; auto properties = rttrType.get_properties(); for (auto const& prop : properties) { - if (componentNode[prop.get_name().data()]) + if (componentNode[prop.get_name().data()].IsDefined()) { InitializeProperty(component, prop, componentNode[prop.get_name().data()]); } From 017cbf90c5497b5b01644b1cfdcd70c7c709b79a Mon Sep 17 00:00:00 2001 From: Xiao Qi Date: Fri, 28 Oct 2022 19:07:48 +0800 Subject: [PATCH 20/44] Changed filesystem interface in preparation for asset browser functionalities --- SHADE_Engine/src/Assets/SHAsset.h | 1 - SHADE_Engine/src/Assets/SHAssetManager.cpp | 14 +- SHADE_Engine/src/Assets/SHAssetManager.h | 2 +- SHADE_Engine/src/Filesystem/SHFileSystem.cpp | 128 +++---------------- SHADE_Engine/src/Filesystem/SHFileSystem.h | 71 +++------- SHADE_Engine/src/Filesystem/SHFolder.h | 58 +++++++++ 6 files changed, 99 insertions(+), 175 deletions(-) create mode 100644 SHADE_Engine/src/Filesystem/SHFolder.h diff --git a/SHADE_Engine/src/Assets/SHAsset.h b/SHADE_Engine/src/Assets/SHAsset.h index 86e8a722..e8a0d629 100644 --- a/SHADE_Engine/src/Assets/SHAsset.h +++ b/SHADE_Engine/src/Assets/SHAsset.h @@ -23,6 +23,5 @@ namespace SHADE AssetID id; AssetType type; AssetPath path; - FolderLocation location; }; } \ No newline at end of file diff --git a/SHADE_Engine/src/Assets/SHAssetManager.cpp b/SHADE_Engine/src/Assets/SHAssetManager.cpp index 228f3fdc..61ee09c4 100644 --- a/SHADE_Engine/src/Assets/SHAssetManager.cpp +++ b/SHADE_Engine/src/Assets/SHAssetManager.cpp @@ -12,7 +12,6 @@ #include #include "SHAssetManager.h" #include "SHAssetMetaHandler.h" -#include "Filesystem/SHFileSystem.h" #include "Libraries/Loaders/SHMeshLoader.h" #include "Libraries/Loaders/SHTextureLoader.h" @@ -178,8 +177,7 @@ namespace SHADE name, id, type, - GenerateNewPath(name, type), - 0 + GenerateNewPath(name, type) ); return id; } @@ -250,8 +248,7 @@ namespace SHADE { SHAsset newAsset { - .name = path.stem().string(), - .location = 0 + .name = path.stem().string() }; auto const ext{ path.extension().string() }; @@ -289,7 +286,6 @@ namespace SHADE result.type = SHAssetMetaHandler::GetTypeFromExtension(path.extension().string()); result.id = GenerateAssetID(result.type); result.path = path; - result.location = 0; return result; } @@ -316,8 +312,7 @@ namespace SHADE { SHAsset newAsset { - .name = path.stem().string(), - .location = 0 + .name = path.stem().string() }; auto const ext{ path.extension().string() }; @@ -342,8 +337,7 @@ namespace SHADE for (auto const& mesh : meshes) { SHAsset meshAsset{ - .name = mesh->header.name, - .location = 0 + .name = mesh->header.name }; meshAsset.path = SHMeshCompiler::CompileMeshBinary(*mesh, path).value(); meshAsset.id = GenerateAssetID(AssetType::MESH); diff --git a/SHADE_Engine/src/Assets/SHAssetManager.h b/SHADE_Engine/src/Assets/SHAssetManager.h index bc6f8878..aa08ab9c 100644 --- a/SHADE_Engine/src/Assets/SHAssetManager.h +++ b/SHADE_Engine/src/Assets/SHAssetManager.h @@ -13,7 +13,7 @@ #include "SHAsset.h" #include "Asset Types/SHAssetData.h" #include "Assets/Libraries/Loaders/SHAssetLoader.h" -#include +#include "Filesystem/SHFileSystem.h" #include "SH_API.h" diff --git a/SHADE_Engine/src/Filesystem/SHFileSystem.cpp b/SHADE_Engine/src/Filesystem/SHFileSystem.cpp index bd34ed71..8e3432ad 100644 --- a/SHADE_Engine/src/Filesystem/SHFileSystem.cpp +++ b/SHADE_Engine/src/Filesystem/SHFileSystem.cpp @@ -6,81 +6,39 @@ namespace SHADE { - char const FOLDER_MAX_COUNT {15}; - - std::unordered_map> SHFileSystem::folders; - FolderPointer SHFileSystem::root {nullptr}; - - SHFolder::SHFolder(FolderHandle id, FolderName name) - :id{ id }, name{ name }, subFolders(0), folded{ false }, path{""} + SHFolder::SHFolder(FolderName name) + :name{ name }, subFolders(0), folded{ false }, path{""} { } - FolderLocation SHFileSystem::CreateNewFolderHere(FolderName name, FolderLocation here) noexcept + FolderPointer SHFileSystem::CreateNewFolderHere(FolderPointer parent, FolderName name) noexcept { - if (here == 0) - { - if (!folders.contains(0)) - { - folders[0] = std::make_unique(0, "root"); - } + for (auto const& folder : parent->subFolders) + { + if (name == folder->name) + { + SHLOG_ERROR("Unable to create subfolder {} at {} as it already exists", name, folder->name); + return nullptr; + } + } - auto const count = static_cast(folders[here]->subFolders.size()); - - if (count >= FOLDER_MAX_COUNT) - { - SHLOG_ERROR("Max subfolder reached: {}\n", name); - } + auto result = new SHFolder(name); + parent->subFolders.push_back(result); - auto const location = static_cast(count); - - CreateFolder(folders[0]->path, here, location, name); - - return location; - } - - if (!folders.contains(here)) - { - SHLOG_ERROR("Folder creation location does not exist/invalid: {}\n", here); - } - - auto const count = static_cast(folders[here]->subFolders.size()); - - FolderHandle location = here; - location <<= FOLDER_BIT_ALLOCATE; - location |= count; - - if (count >= FOLDER_MAX_COUNT) - { - SHLOG_ERROR("Max subfolder reached: {}\n", name); - } - - CreateFolder(folders[0]->path, here, location, name); - - return location; + return result; } bool SHFileSystem::DeleteFolder(FolderPointer location) noexcept { - if (!folders.contains(location->id)) - { - SHLOG_ERROR("Delete target does not exist/invalid: {}\n", location->name); - } - - for (auto const& subFolder : folders[location->id]->subFolders) - { - DeleteFolder(subFolder); - } - - RemoveDirectoryA(folders[location->id]->path.c_str()); + //TODO IMPLEMENT return true; } - void SHFileSystem::StartupFillDirectories(FolderPath path) noexcept + FolderPointer SHFileSystem::BuildDirectory(FolderPath path) noexcept { std::queue folderQueue; - - folderQueue.push(RegisterFolder(path, 0, 0, "Root")); + auto result = new SHFolder("root"); + folderQueue.push(result); while (!folderQueue.empty()) { @@ -101,59 +59,15 @@ namespace SHADE continue; } - FolderLocation location = folder->id; - location <<= FOLDER_BIT_ALLOCATE; - location |= ++count; + std::string name = dirEntry.path().stem().string(); - std::string name = dirEntry.path().string(); - name = name.substr(name.find_last_of('/') + 1, name.length() - name.find_last_of('/')); - - FolderPointer newFolder{ RegisterFolder( - dirEntry.path().string(), - folder->id, - location, - name) - }; + FolderPointer newFolder{ new SHFolder(name) }; folderQueue.push(newFolder); folder->subFolders.push_back(newFolder); } } - } - FolderPointer SHFileSystem::GetRoot() noexcept - { - return root; - } - - FolderPointer SHFileSystem::CreateFolder(FolderPath path, FolderLocation parent, FolderHandle location, FolderName name) noexcept - { - - if (!CreateDirectoryA(path.c_str(), nullptr)) - { - SHLOG_ERROR("Failed to create folder: {}\n", path); - } - - folders[location] = std::make_unique(location, name); - folders[location]->path = path; - folders[parent]->subFolders.push_back(folders[location].get()); - - return FolderMakeHelper(path, parent, location, name); - } - - FolderPointer SHFileSystem::RegisterFolder(FolderPath path, FolderLocation parent, FolderHandle location, - FolderName name) noexcept - { - return FolderMakeHelper(path, parent, location, name); - } - - FolderPointer SHFileSystem::FolderMakeHelper(FolderPath path, FolderLocation parent, FolderHandle location, - FolderName name) noexcept - { - folders[location] = std::make_unique(location, name); - folders[location]->path = path; - folders[parent]->subFolders.push_back(folders[location].get()); - - return folders[location].get(); + return result; } } diff --git a/SHADE_Engine/src/Filesystem/SHFileSystem.h b/SHADE_Engine/src/Filesystem/SHFileSystem.h index 8df794fd..b4f0b0a7 100644 --- a/SHADE_Engine/src/Filesystem/SHFileSystem.h +++ b/SHADE_Engine/src/Filesystem/SHFileSystem.h @@ -1,70 +1,29 @@ +/****************************************************************************** + * \file SHFileSystem.h + * \author Loh Xiao Qi + * \date 28 October 2022 + * \brief + * + * \copyright 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 -#include -#include -#include +#include "SHFolder.h" namespace SHADE { - class SHFolder; - - typedef unsigned char FolderCounter; - typedef unsigned char FileCounter; - typedef uint64_t FolderLocation; - typedef uint64_t FolderHandle; - typedef std::string FolderName; - typedef std::string FileName; - typedef std::string FolderPath; - typedef std::string FilePath; - typedef std::string FileExt; - typedef SHFolder* FolderPointer; - - constexpr char FOLDER_BIT_ALLOCATE{ 4 }; - constexpr char FOLDER_MAX_DEPTH{ 16 }; - - struct SHFile - { - FileName name; - FilePath path; - FileExt ext; - }; - - class SHFolder - { - public: - SHFolder(FolderHandle id, FolderName name); - - FolderHandle id; - FolderName name; - std::vector subFolders; - std::vector files; - - bool folded; - - private: - FolderPath path; - friend class SHFileSystem; - }; class SHFileSystem { public: - static FolderLocation CreateNewFolderHere(FolderName name, FolderLocation here = 0) noexcept; - - static bool DeleteFolder(FolderPointer location) noexcept; - - static void StartupFillDirectories(FolderPath path) noexcept; - - static FolderPointer GetRoot() noexcept; + static FolderPointer BuildDirectory(FolderPath path) noexcept; private: - static FolderPointer root; + static FolderPointer CreateNewFolderHere(FolderPointer parent, FolderName name) noexcept; + static bool DeleteFolder(FolderPointer location) noexcept; - static std::unordered_map> folders; - - static FolderPointer CreateFolder(FolderPath path, FolderLocation parent, FolderHandle location, FolderName name) noexcept; - static FolderPointer RegisterFolder(FolderPath path, FolderLocation parent, FolderHandle location, FolderName name) noexcept; - static FolderPointer FolderMakeHelper(FolderPath path, FolderLocation parent, FolderHandle location, FolderName name) noexcept; + friend class SHFolder; }; } \ No newline at end of file diff --git a/SHADE_Engine/src/Filesystem/SHFolder.h b/SHADE_Engine/src/Filesystem/SHFolder.h new file mode 100644 index 00000000..86cdc008 --- /dev/null +++ b/SHADE_Engine/src/Filesystem/SHFolder.h @@ -0,0 +1,58 @@ +/****************************************************************************** + * \file SHFolder.h + * \author Loh Xiao Qi + * \date 28 October 2022 + * \brief + * + * \copyright 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 +#include +#include "Assets/SHAssetMacros.h" + +namespace SHADE +{ + class SHFolder; + + typedef unsigned char FolderCounter; + typedef unsigned char FileCounter; + typedef std::string FolderName; + typedef std::string FileName; + typedef std::string FolderPath; + typedef std::string FilePath; + typedef std::string FileExt; + typedef SHFolder* FolderPointer; + + // Forward Declare + class SHFileSystem; + + struct SHFile + { + FileName name; + FilePath path; + FileExt ext; + + }; + + class SHFolder + { + public: + SHFolder(FolderName name); + + FolderName name; + std::vector subFolders; + std::vector files; + + bool folded; + + FolderPointer CreateSubFolderHere(FolderName name); + + private: + FolderPath path; + friend class SHFileSystem; + }; +} From ea9f90f60de8e22ebfc320708b6188ec9ec7bcdd Mon Sep 17 00:00:00 2001 From: Sri Sham Haran Date: Fri, 28 Oct 2022 19:39:39 +0800 Subject: [PATCH 21/44] Serialize Collider Component done --- .../Components/SHColliderComponent.cpp | 10 ++++++- .../Physics/Components/SHColliderComponent.h | 1 + .../Serialization/SHSerializationHelper.hpp | 27 ++++++------------- 3 files changed, 18 insertions(+), 20 deletions(-) diff --git a/SHADE_Engine/src/Physics/Components/SHColliderComponent.cpp b/SHADE_Engine/src/Physics/Components/SHColliderComponent.cpp index fb999847..c7e327fa 100644 --- a/SHADE_Engine/src/Physics/Components/SHColliderComponent.cpp +++ b/SHADE_Engine/src/Physics/Components/SHColliderComponent.cpp @@ -146,4 +146,12 @@ namespace SHADE system->RemoveCollisionShape(GetEID(), index); } -} // namespace SHADE \ No newline at end of file +} // namespace SHADE + +RTTR_REGISTRATION +{ + using namespace rttr; + using namespace SHADE; + + registration::class_("Collider Component"); +} \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/Components/SHColliderComponent.h b/SHADE_Engine/src/Physics/Components/SHColliderComponent.h index af726b51..7ce272a9 100644 --- a/SHADE_Engine/src/Physics/Components/SHColliderComponent.h +++ b/SHADE_Engine/src/Physics/Components/SHColliderComponent.h @@ -100,5 +100,6 @@ namespace SHADE SHQuaternion orientation; Colliders colliders; + RTTR_ENABLE() }; } // namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/Serialization/SHSerializationHelper.hpp b/SHADE_Engine/src/Serialization/SHSerializationHelper.hpp index b81a6e46..80362e8d 100644 --- a/SHADE_Engine/src/Serialization/SHSerializationHelper.hpp +++ b/SHADE_Engine/src/Serialization/SHSerializationHelper.hpp @@ -169,24 +169,12 @@ namespace YAML { case SHCollider::Type::BOX: { - if(auto const bb = dynamic_cast(rhs.GetShape()); bb) - { - if (node[HalfExtents]) - { - bb->SetHalfExtents(node[HalfExtents].as()); - } - } + rhs.SetBoundingBox(node[HalfExtents].as()); } break; case SHCollider::Type::SPHERE: { - if(auto const bs = dynamic_cast(rhs.GetShape()); bs) - { - if (node[Radius]) - { - bs->SetRadius(node[Radius].as()); - } - } + rhs.SetBoundingSphere(node[Radius].as()); } break; case SHCollider::Type::CAPSULE: break; @@ -200,7 +188,7 @@ namespace YAML rhs.SetDensity(node[Density].as()); if (node[PositionOffset]) rhs.SetPositionOffset(node[PositionOffset].as()); - + return true; } }; @@ -237,6 +225,7 @@ namespace YAML const SHCollider::Type colliderType = enumAlign.name_to_value(colliderNode[convert::Type].as()).convert(&ok); if (!ok) return false; + switch (colliderType) { case SHCollider::Type::BOX: rhs.AddBoundingBox(); break; @@ -244,7 +233,7 @@ namespace YAML case SHCollider::Type::CAPSULE: break; default:; } - rhs.GetCollider(numColliders++) = colliderNode.as(); + YAML::convert::decode(colliderNode, rhs.GetCollider(numColliders++)); } } } @@ -279,13 +268,13 @@ namespace YAML propNode = rhs.GetProperty(VARIABLE->offset); break; case SHADE::SHShaderBlockInterface::Variable::Type::VECTOR2: - propNode = SHSerializationTools::ValToYAML(rhs.GetProperty(VARIABLE->offset)); + propNode = rhs.GetProperty(VARIABLE->offset); break; case SHADE::SHShaderBlockInterface::Variable::Type::VECTOR3: - propNode = SHSerializationTools::ValToYAML(rhs.GetProperty(VARIABLE->offset)); + propNode = rhs.GetProperty(VARIABLE->offset); break; case SHADE::SHShaderBlockInterface::Variable::Type::VECTOR4: - propNode = SHSerializationTools::ValToYAML(rhs.GetProperty(VARIABLE->offset)); + propNode = rhs.GetProperty(VARIABLE->offset); break; case SHADE::SHShaderBlockInterface::Variable::Type::OTHER: default: From 001c25f5544f5cd6a06df9e78886570a4b0125b8 Mon Sep 17 00:00:00 2001 From: Sri Sham Haran Date: Fri, 28 Oct 2022 20:47:28 +0800 Subject: [PATCH 22/44] fix camera not updating when undock/dock --- .../ViewportWindow/SHEditorViewport.cpp | 70 ++++++++++--------- .../ViewportWindow/SHEditorViewport.h | 3 +- 2 files changed, 39 insertions(+), 34 deletions(-) diff --git a/SHADE_Engine/src/Editor/EditorWindow/ViewportWindow/SHEditorViewport.cpp b/SHADE_Engine/src/Editor/EditorWindow/ViewportWindow/SHEditorViewport.cpp index 17bf6fa5..d6ef8d19 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/ViewportWindow/SHEditorViewport.cpp +++ b/SHADE_Engine/src/Editor/EditorWindow/ViewportWindow/SHEditorViewport.cpp @@ -13,6 +13,7 @@ #include #include "Camera/SHCameraSystem.h" +#include "FRC/SHFramerateController.h" constexpr std::string_view windowName = "\xef\x80\x95 Viewport"; @@ -27,15 +28,20 @@ namespace SHADE { SHEditorWindow::Init(); transformGizmo.Init(); - auto camSystem = SHSystemManager::GetSystem(); - camSystem->UpdateEditorCamera(0.016f); } void SHEditorViewport::Update() { SHEditorWindow::Update(); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f,0.0f)); - if(Begin()) + if (shouldUpdateCamera) + { + auto camSystem = SHSystemManager::GetSystem(); + camSystem->UpdateEditorCamera(SHFrameRateController::GetRawDeltaTime()); + shouldUpdateCamera = false; + } + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); + + if (Begin()) { ImGuizmo::SetDrawlist(); DrawMenuBar(); @@ -43,39 +49,38 @@ namespace SHADE auto const& descriptorSet = gfxSystem->GetPostOffscreenRenderSystem()->GetDescriptorSetGroup()->GetVkHandle()[0]; auto mousePos = ImGui::GetMousePos(); beginCursorPos = ImGui::GetCursorScreenPos(); - viewportMousePos = {mousePos.x - beginCursorPos.x, mousePos.y - beginCursorPos.y}; - gfxSystem->GetMousePickSystem ()->SetViewportMousePos (viewportMousePos); + viewportMousePos = { mousePos.x - beginCursorPos.x, mousePos.y - beginCursorPos.y }; + gfxSystem->GetMousePickSystem()->SetViewportMousePos(viewportMousePos); - ImGui::Image((ImTextureID)descriptorSet, {beginContentRegionAvailable.x, beginContentRegionAvailable.y}); + ImGui::Image((ImTextureID)descriptorSet, { beginContentRegionAvailable.x, beginContentRegionAvailable.y }); - if(ImGui::IsWindowHovered() && ImGui::IsMouseDown(ImGuiMouseButton_Right)) + if (ImGui::IsWindowHovered() && ImGui::IsMouseDown(ImGuiMouseButton_Right)) { ImGui::SetMouseCursor(ImGuiMouseCursor_None); ImGui::SetCursorScreenPos(ImGui::GetMousePos()); ImGui::PushStyleColor(ImGuiCol_Text, ImGuiColors::green); ImGui::Text(ICON_FA_EYE); ImGui::PopStyleColor(); - - auto camSystem = SHSystemManager::GetSystem(); - camSystem->UpdateEditorCamera(0.016f); + + shouldUpdateCamera = true; } - if(ImGui::IsWindowFocused() && !ImGui::IsMouseDown(ImGuiMouseButton_Right)) + if (ImGui::IsWindowFocused() && !ImGui::IsMouseDown(ImGuiMouseButton_Right)) { - if(ImGui::IsKeyReleased(ImGuiKey_Q)) + if (ImGui::IsKeyReleased(ImGuiKey_Q)) { transformGizmo.operation = SHTransformGizmo::Operation::TRANSLATE; } - if(ImGui::IsKeyReleased(ImGuiKey_W)) + if (ImGui::IsKeyReleased(ImGuiKey_W)) { transformGizmo.operation = SHTransformGizmo::Operation::ROTATE; } - if(ImGui::IsKeyReleased(ImGuiKey_E)) + if (ImGui::IsKeyReleased(ImGuiKey_E)) { transformGizmo.operation = SHTransformGizmo::Operation::SCALE; } } } - ImGuizmo::SetRect(beginCursorPos.x , beginCursorPos.y, beginContentRegionAvailable.x, beginContentRegionAvailable.y); + ImGuizmo::SetRect(beginCursorPos.x, beginCursorPos.y, beginContentRegionAvailable.x, beginContentRegionAvailable.y); transformGizmo.Draw(); ImGui::End(); ImGui::PopStyleVar(); @@ -94,13 +99,12 @@ namespace SHADE //auto pos = ImGui::GetCursorPos(); //windowCursorPos = {} - if(beginContentRegionAvailable.x == 0 || beginContentRegionAvailable.y == 0) + if (beginContentRegionAvailable.x == 0 || beginContentRegionAvailable.y == 0) { - beginContentRegionAvailable = windowSize; + beginContentRegionAvailable = windowSize; } gfxSystem->PrepareResize(static_cast(beginContentRegionAvailable.x), static_cast(beginContentRegionAvailable.y)); - auto camSystem = SHSystemManager::GetSystem(); - camSystem->UpdateEditorCamera(0.016f); + shouldUpdateCamera = true; } void SHEditorViewport::OnPosChange() @@ -110,61 +114,61 @@ namespace SHADE void SHEditorViewport::DrawMenuBar() noexcept { - if(ImGui::BeginMenuBar()) + if (ImGui::BeginMenuBar()) { ImGui::BeginDisabled(ImGui::IsWindowFocused() && ImGui::IsMouseDown(ImGuiMouseButton_Right)); bool const isTranslate = transformGizmo.operation == SHTransformGizmo::Operation::TRANSLATE; ImGui::BeginDisabled(isTranslate); - if(isTranslate) + if (isTranslate) ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyle().Colors[ImGuiCol_CheckMark]); - if(ImGui::Button(ICON_MD_OPEN_WITH)) + if (ImGui::Button(ICON_MD_OPEN_WITH)) { transformGizmo.operation = SHTransformGizmo::Operation::TRANSLATE; } ImGui::EndDisabled(); - if(ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) { ImGui::BeginTooltip(); ImGui::Text("Translate [Q]"); ImGui::EndTooltip(); } - if(isTranslate) + if (isTranslate) ImGui::PopStyleColor(); bool const isRotate = transformGizmo.operation == SHTransformGizmo::Operation::ROTATE; ImGui::BeginDisabled(isRotate); - if(isRotate) + if (isRotate) ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyle().Colors[ImGuiCol_CheckMark]); - if(ImGui::Button(ICON_MD_AUTORENEW)) + if (ImGui::Button(ICON_MD_AUTORENEW)) { transformGizmo.operation = SHTransformGizmo::Operation::ROTATE; } ImGui::EndDisabled(); - if(ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) { ImGui::BeginTooltip(); ImGui::Text("Rotate [W]"); ImGui::EndTooltip(); } - if(isRotate) + if (isRotate) ImGui::PopStyleColor(); bool const isScale = transformGizmo.operation == SHTransformGizmo::Operation::SCALE; ImGui::BeginDisabled(isScale); - if(isScale) + if (isScale) ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyle().Colors[ImGuiCol_CheckMark]); - if(ImGui::Button(ICON_MD_EXPAND)) + if (ImGui::Button(ICON_MD_EXPAND)) { transformGizmo.operation = SHTransformGizmo::Operation::SCALE; } ImGui::EndDisabled(); - if(ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) { ImGui::BeginTooltip(); ImGui::Text("Scale [E]"); ImGui::EndTooltip(); } - if(isScale) + if (isScale) ImGui::PopStyleColor(); ImGui::EndDisabled(); ImGui::EndMenuBar(); diff --git a/SHADE_Engine/src/Editor/EditorWindow/ViewportWindow/SHEditorViewport.h b/SHADE_Engine/src/Editor/EditorWindow/ViewportWindow/SHEditorViewport.h index 80b13285..0fae4317 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/ViewportWindow/SHEditorViewport.h +++ b/SHADE_Engine/src/Editor/EditorWindow/ViewportWindow/SHEditorViewport.h @@ -14,7 +14,7 @@ namespace SHADE { - class SHEditorViewport final : public SHEditorWindow + class SHEditorViewport final : public SHEditorWindow { public: SHEditorViewport(); @@ -28,5 +28,6 @@ namespace SHADE private: void DrawMenuBar() noexcept; SHVec2 beginCursorPos; + bool shouldUpdateCamera = false; };//class SHEditorViewport }//namespace SHADE From 6ce143665a5a5e9faadd0e93c492f2dda015684f Mon Sep 17 00:00:00 2001 From: Xiao Qi Date: Fri, 28 Oct 2022 20:48:50 +0800 Subject: [PATCH 23/44] Added scene and prefab asset classes Added scene and prefab text based loaders Added write functions to all asset loaders to overwrite data --- .../src/Assets/Asset Types/SHPrefabAsset.h | 23 ++++ .../src/Assets/Asset Types/SHSceneAsset.h | 23 ++++ .../Assets/Libraries/Loaders/SHAssetLoader.h | 1 + .../Assets/Libraries/Loaders/SHMeshLoader.cpp | 52 +++++++++ .../Assets/Libraries/Loaders/SHMeshLoader.h | 2 +- .../Loaders/SHShaderSourceLoader.cpp | 23 ++++ .../Libraries/Loaders/SHShaderSourceLoader.h | 2 +- .../Libraries/Loaders/SHTextBasedLoader.cpp | 82 +++++++++++++ .../Libraries/Loaders/SHTextBasedLoader.h | 21 ++++ .../Libraries/Loaders/SHTextureLoader.cpp | 110 +++++++++++++----- .../Libraries/Loaders/SHTextureLoader.h | 3 +- SHADE_Engine/src/Assets/SHAssetMacros.h | 2 + SHADE_Engine/src/Assets/SHAssetManager.cpp | 5 +- SHADE_Engine/src/Assets/SHAssetManager.h | 5 +- SHADE_Engine/src/Assets/SHAssetManager.hpp | 27 ++++- 15 files changed, 343 insertions(+), 38 deletions(-) create mode 100644 SHADE_Engine/src/Assets/Asset Types/SHPrefabAsset.h create mode 100644 SHADE_Engine/src/Assets/Asset Types/SHSceneAsset.h create mode 100644 SHADE_Engine/src/Assets/Libraries/Loaders/SHTextBasedLoader.cpp create mode 100644 SHADE_Engine/src/Assets/Libraries/Loaders/SHTextBasedLoader.h diff --git a/SHADE_Engine/src/Assets/Asset Types/SHPrefabAsset.h b/SHADE_Engine/src/Assets/Asset Types/SHPrefabAsset.h new file mode 100644 index 00000000..0db299b2 --- /dev/null +++ b/SHADE_Engine/src/Assets/Asset Types/SHPrefabAsset.h @@ -0,0 +1,23 @@ +/****************************************************************************** + * \file SHPrefabAsset.h + * \author Loh Xiao Qi + * \date 28 October 2022 + * \brief + * + * \copyright 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 "SHAssetData.h" +#include + +namespace SHADE +{ + struct SHPrefabAsset : SHAssetData + { + std::string name; + std::string data; + }; +} diff --git a/SHADE_Engine/src/Assets/Asset Types/SHSceneAsset.h b/SHADE_Engine/src/Assets/Asset Types/SHSceneAsset.h new file mode 100644 index 00000000..0f7061b1 --- /dev/null +++ b/SHADE_Engine/src/Assets/Asset Types/SHSceneAsset.h @@ -0,0 +1,23 @@ +/****************************************************************************** + * \file SHSceneAsset.h + * \author Loh Xiao Qi + * \date 28 October 2022 + * \brief + * + * \copyright 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 "SHAssetData.h" +#include + +namespace SHADE +{ + struct SHSceneAsset : SHAssetData + { + std::string name; + std::string data; + }; +} diff --git a/SHADE_Engine/src/Assets/Libraries/Loaders/SHAssetLoader.h b/SHADE_Engine/src/Assets/Libraries/Loaders/SHAssetLoader.h index 63e081af..b6b7656b 100644 --- a/SHADE_Engine/src/Assets/Libraries/Loaders/SHAssetLoader.h +++ b/SHADE_Engine/src/Assets/Libraries/Loaders/SHAssetLoader.h @@ -18,5 +18,6 @@ namespace SHADE struct SHAssetLoader { virtual SHAssetData* Load(AssetPath path) = 0; + virtual void Write(SHAssetData const* data, AssetPath path) = 0; }; } diff --git a/SHADE_Engine/src/Assets/Libraries/Loaders/SHMeshLoader.cpp b/SHADE_Engine/src/Assets/Libraries/Loaders/SHMeshLoader.cpp index 90dd58d4..52134440 100644 --- a/SHADE_Engine/src/Assets/Libraries/Loaders/SHMeshLoader.cpp +++ b/SHADE_Engine/src/Assets/Libraries/Loaders/SHMeshLoader.cpp @@ -22,6 +22,7 @@ namespace SHADE if (!file.is_open()) { SHLOG_ERROR("Unable to open SHMesh File: {}", path.string()); + return; } const std::string name{ path.stem().string() }; @@ -75,4 +76,55 @@ namespace SHADE return result; } + + void SHMeshLoader::Write(SHAssetData const* data, AssetPath path) + { + std::ofstream file{ path, std::ios::out | std::ios::binary | std::ios::trunc }; + if (!file.is_open()) + { + SHLOG_ERROR("Unable to open file for writing mesh file: {}", path.string()); + } + + auto asset = *dynamic_cast(data); + + file.write( + reinterpret_cast(&(asset.header.vertexCount)), + sizeof(uint32_t) + ); + + file.write( + reinterpret_cast(&(asset.header.indexCount)), + sizeof(uint32_t) + ); + + auto const vertexVec3Byte{ sizeof(SHVec3) * asset.header.vertexCount }; + auto const vertexVec2Byte{ sizeof(SHVec2) * asset.header.vertexCount }; + + file.write( + reinterpret_cast(asset.vertexPosition.data()), + vertexVec3Byte + ); + + file.write( + reinterpret_cast(asset.vertexTangent.data()), + vertexVec3Byte + ); + + file.write( + reinterpret_cast(asset.vertexNormal.data()), + vertexVec3Byte + ); + + file.write( + reinterpret_cast(asset.texCoords.data()), + vertexVec2Byte + ); + + file.write( + reinterpret_cast(asset.indices.data()), + sizeof(uint32_t) * asset.header.indexCount + ); + + file.close(); + } } diff --git a/SHADE_Engine/src/Assets/Libraries/Loaders/SHMeshLoader.h b/SHADE_Engine/src/Assets/Libraries/Loaders/SHMeshLoader.h index bf65851a..03a111ce 100644 --- a/SHADE_Engine/src/Assets/Libraries/Loaders/SHMeshLoader.h +++ b/SHADE_Engine/src/Assets/Libraries/Loaders/SHMeshLoader.h @@ -10,7 +10,6 @@ * of DigiPen Institute of Technology is prohibited. *****************************************************************************/ #pragma once -#include "Assets/SHAssetMacros.h" #include "Assets/Asset Types/SHMeshAsset.h" #include "SHAssetLoader.h" @@ -20,5 +19,6 @@ namespace SHADE { void LoadSHMesh(AssetPath path, SHMeshAsset& meshes) noexcept; SHAssetData* Load(AssetPath path) override; + void Write(SHAssetData const* data, AssetPath path) override; }; } \ No newline at end of file diff --git a/SHADE_Engine/src/Assets/Libraries/Loaders/SHShaderSourceLoader.cpp b/SHADE_Engine/src/Assets/Libraries/Loaders/SHShaderSourceLoader.cpp index 824995d6..f0d9a29b 100644 --- a/SHADE_Engine/src/Assets/Libraries/Loaders/SHShaderSourceLoader.cpp +++ b/SHADE_Engine/src/Assets/Libraries/Loaders/SHShaderSourceLoader.cpp @@ -43,4 +43,27 @@ namespace SHADE return result; } + + void SHShaderSourceLoader::Write(SHAssetData const* data, AssetPath path) + { + std::ofstream file{ path, std::ios::binary | std::ios::out | std::ios::trunc }; + + auto asset = *dynamic_cast(data); + + file.write( + reinterpret_cast(&asset.shaderType), sizeof(uint8_t) + ); + + size_t const byteCount = sizeof(uint32_t) * asset.spirvBinary.size(); + + file.write( + reinterpret_cast(&byteCount), sizeof(size_t) + ); + + file.write( + reinterpret_cast(asset.spirvBinary.data()), byteCount + ); + + file.close(); + } } diff --git a/SHADE_Engine/src/Assets/Libraries/Loaders/SHShaderSourceLoader.h b/SHADE_Engine/src/Assets/Libraries/Loaders/SHShaderSourceLoader.h index befdade5..0a4b614f 100644 --- a/SHADE_Engine/src/Assets/Libraries/Loaders/SHShaderSourceLoader.h +++ b/SHADE_Engine/src/Assets/Libraries/Loaders/SHShaderSourceLoader.h @@ -11,12 +11,12 @@ #pragma once #include "Assets/Libraries/Loaders/SHAssetLoader.h" -#include "Assets/SHAssetMacros.h" namespace SHADE { struct SHShaderSourceLoader : SHAssetLoader { SHAssetData* Load(AssetPath path) override; + void Write(SHAssetData const* data, AssetPath path) override; }; } diff --git a/SHADE_Engine/src/Assets/Libraries/Loaders/SHTextBasedLoader.cpp b/SHADE_Engine/src/Assets/Libraries/Loaders/SHTextBasedLoader.cpp new file mode 100644 index 00000000..60ea80f6 --- /dev/null +++ b/SHADE_Engine/src/Assets/Libraries/Loaders/SHTextBasedLoader.cpp @@ -0,0 +1,82 @@ +/****************************************************************************** + * \file SHTextBasedLoader.cpp + * \author Loh Xiao Qi + * \date 28 October 2022 + * \brief + * + * \copyright 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. + ******************************************************************************/ +#include "SHpch.h" +#include "SHTextBasedLoader.h" + +#include "Assets/Asset Types/SHSceneAsset.h" +#include "Assets/Asset Types/SHPrefabAsset.h" + +#include +#include + +namespace SHADE +{ + SHAssetData* SHTextBasedLoader::Load(AssetPath path) + { + std::ifstream file{ path, std::ios::in }; + + if (!file.is_open()) + { + SHLOG_ERROR("Unable to open text File: {}", path.string()); + return nullptr; + } + std::stringstream stream; + + stream << file.rdbuf(); + + std::string content = stream.str(); + + SHAssetData* result; + + if (path.extension().string() == SCENE_EXTENSION) + { + auto data = new SHSceneAsset(); + data->name = path.stem().string(); + data->data = std::move(content); + result = data; + } + else if (path.extension().string() == PREFAB_EXTENSION) + { + auto data = new SHPrefabAsset(); + data->name = path.stem().string(); + data->data = std::move(content); + result = data; + } + + file.close(); + + return result; + } + + void SHTextBasedLoader::Write(SHAssetData const* data, AssetPath path) + { + std::ofstream file{ path, std::ios::out | std::ios::trunc }; + + if (!file.is_open()) + { + SHLOG_ERROR("Unable to open text File: {}", path.string()); + return; + } + + if (path.extension().string() == SCENE_EXTENSION) + { + auto scene = dynamic_cast(data); + file << scene->data; + } + else if (path.extension().string() == PREFAB_EXTENSION) + { + auto prefab = dynamic_cast(data); + file << prefab->data; + } + + file.close(); + } +} diff --git a/SHADE_Engine/src/Assets/Libraries/Loaders/SHTextBasedLoader.h b/SHADE_Engine/src/Assets/Libraries/Loaders/SHTextBasedLoader.h new file mode 100644 index 00000000..80771058 --- /dev/null +++ b/SHADE_Engine/src/Assets/Libraries/Loaders/SHTextBasedLoader.h @@ -0,0 +1,21 @@ +/****************************************************************************** + * \file Header.h + * \author Loh Xiao Qi + * \date 28 October 2022 + * \brief + * + * \copyright 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 "SHAssetLoader.h" + +namespace SHADE +{ + struct SHTextBasedLoader : SHAssetLoader + { + SHAssetData* Load(AssetPath path) override; + void Write(SHAssetData const* data, AssetPath path) override; + }; +} diff --git a/SHADE_Engine/src/Assets/Libraries/Loaders/SHTextureLoader.cpp b/SHADE_Engine/src/Assets/Libraries/Loaders/SHTextureLoader.cpp index 74c08230..423301dd 100644 --- a/SHADE_Engine/src/Assets/Libraries/Loaders/SHTextureLoader.cpp +++ b/SHADE_Engine/src/Assets/Libraries/Loaders/SHTextureLoader.cpp @@ -17,42 +17,94 @@ namespace SHADE { - void SHTextureLoader::LoadSHTexture(AssetPath path, SHTextureAsset& asset) noexcept - { - std::ifstream file{ path.string(), std::ios::in | std::ios::binary }; - if (!file.is_open()) - { - SHLOG_ERROR("Error opening SHTexture file: {}", path.string()); - } + void SHTextureLoader::LoadSHTexture(AssetPath path, SHTextureAsset& asset) noexcept + { + std::ifstream file{ path.string(), std::ios::in | std::ios::binary }; + if (!file.is_open()) + { + SHLOG_ERROR("Error opening SHTexture file: {}", path.string()); + } - auto const intBytes{ sizeof(uint32_t) }; - uint32_t mipCount; + auto const intBytes{ sizeof(uint32_t) }; + uint32_t mipCount; - file.read(reinterpret_cast(&asset.numBytes), intBytes); - file.read(reinterpret_cast(&asset.width), intBytes); - file.read(reinterpret_cast(&asset.height), intBytes); - file.read(reinterpret_cast(&asset.format), sizeof(SHTexture::TextureFormat)); + file.read(reinterpret_cast(&asset.numBytes), intBytes); + file.read(reinterpret_cast(&asset.width), intBytes); + file.read(reinterpret_cast(&asset.height), intBytes); + file.read(reinterpret_cast(&asset.format), sizeof(SHTexture::TextureFormat)); - file.read(reinterpret_cast(&mipCount), intBytes); - std::vector mips(mipCount); - file.read(reinterpret_cast(mips.data()), intBytes * mipCount); + file.read(reinterpret_cast(&mipCount), intBytes); + std::vector mips(mipCount); + file.read(reinterpret_cast(mips.data()), intBytes * mipCount); - auto pixel = new SHTexture::PixelChannel[asset.numBytes]; - file.read(reinterpret_cast(pixel), asset.numBytes); + auto pixel = new SHTexture::PixelChannel[asset.numBytes]; + file.read(reinterpret_cast(pixel), asset.numBytes); - asset.mipOffsets = std::move(mips); - asset.pixelData = std::move(pixel); + asset.mipOffsets = std::move(mips); + asset.pixelData = std::move(pixel); - asset.compiled = true; - file.close(); - } + asset.compiled = true; + file.close(); + } - SHAssetData* SHTextureLoader::Load(AssetPath path) - { - auto result = new SHTextureAsset(); + SHAssetData* SHTextureLoader::Load(AssetPath path) + { + auto result = new SHTextureAsset(); - LoadSHTexture(path, *result); + LoadSHTexture(path, *result); - return result; - } + return result; + } + + void SHTextureLoader::Write(SHAssetData const* data, AssetPath path) + { + std::ofstream file{ path, std::ios::out | std::ios::binary }; + if (!file.is_open()) + { + SHLOG_ERROR("Unable to open file for writing texture file: {}", path.string()); + } + + auto asset = *dynamic_cast(data); + + constexpr auto intBytes{ sizeof(uint32_t) }; + + uint32_t const mipOffsetCount{ static_cast(asset.mipOffsets.size()) }; + + file.write( + reinterpret_cast(&asset.numBytes), + intBytes + ); + + file.write( + reinterpret_cast(&asset.width), + intBytes + ); + + file.write( + reinterpret_cast(&asset.height), + intBytes + ); + + file.write( + reinterpret_cast(&asset.format), + sizeof(SHTexture::TextureFormat) + ); + + file.write( + reinterpret_cast(&mipOffsetCount), + intBytes + ); + + file.write( + reinterpret_cast(asset.mipOffsets.data()), + intBytes * asset.mipOffsets.size() + ); + + file.write( + reinterpret_cast(asset.pixelData), + asset.numBytes + ); + + file.close(); + } } diff --git a/SHADE_Engine/src/Assets/Libraries/Loaders/SHTextureLoader.h b/SHADE_Engine/src/Assets/Libraries/Loaders/SHTextureLoader.h index 00b060ec..27f7b844 100644 --- a/SHADE_Engine/src/Assets/Libraries/Loaders/SHTextureLoader.h +++ b/SHADE_Engine/src/Assets/Libraries/Loaders/SHTextureLoader.h @@ -10,8 +10,6 @@ * of DigiPen Institute of Technology is prohibited. *****************************************************************************/ #pragma once - -#include "Assets/SHAssetMacros.h" #include "Assets/Asset Types/SHTextureAsset.h" #include "SHAssetLoader.h" @@ -21,5 +19,6 @@ namespace SHADE { void LoadSHTexture(AssetPath path, SHTextureAsset& asset) noexcept; SHAssetData* Load(AssetPath path) override; + void Write(SHAssetData const* data, AssetPath path) override; }; } diff --git a/SHADE_Engine/src/Assets/SHAssetMacros.h b/SHADE_Engine/src/Assets/SHAssetMacros.h index 1df4e30b..ff154810 100644 --- a/SHADE_Engine/src/Assets/SHAssetMacros.h +++ b/SHADE_Engine/src/Assets/SHAssetMacros.h @@ -47,6 +47,8 @@ enum class AssetType : AssetTypeMeta SHADER_BUILT_IN, TEXTURE, MESH, + SCENE, + PREFAB, MAX_COUNT }; constexpr size_t TYPE_COUNT{ static_cast(AssetType::MAX_COUNT) }; diff --git a/SHADE_Engine/src/Assets/SHAssetManager.cpp b/SHADE_Engine/src/Assets/SHAssetManager.cpp index 61ee09c4..06acf7de 100644 --- a/SHADE_Engine/src/Assets/SHAssetManager.cpp +++ b/SHADE_Engine/src/Assets/SHAssetManager.cpp @@ -16,6 +16,7 @@ #include "Libraries/Loaders/SHMeshLoader.h" #include "Libraries/Loaders/SHTextureLoader.h" #include "Libraries/Loaders/SHShaderSourceLoader.h" +#include "Libraries/Loaders/SHTextBasedLoader.h" #include "Libraries/Compilers/SHMeshCompiler.h" #include "Libraries/Compilers/SHTextureCompiler.h" @@ -353,12 +354,14 @@ namespace SHADE } } - void SHAssetManager::InitLoaders() noexcept + void SHAssetManager:: InitLoaders() noexcept { loaders[static_cast(AssetType::SHADER)] = dynamic_cast(new SHShaderSourceLoader()); loaders[static_cast(AssetType::SHADER_BUILT_IN)] = loaders[static_cast(AssetType::SHADER)]; loaders[static_cast(AssetType::TEXTURE)] = dynamic_cast(new SHTextureLoader()); loaders[static_cast(AssetType::MESH)] = dynamic_cast(new SHMeshLoader()); + loaders[static_cast(AssetType::SCENE)] = dynamic_cast(new SHTextBasedLoader()); + loaders[static_cast(AssetType::PREFAB)] = loaders[static_cast(AssetType::SCENE)]; } /**************************************************************************** diff --git a/SHADE_Engine/src/Assets/SHAssetManager.h b/SHADE_Engine/src/Assets/SHAssetManager.h index aa08ab9c..7521e356 100644 --- a/SHADE_Engine/src/Assets/SHAssetManager.h +++ b/SHADE_Engine/src/Assets/SHAssetManager.h @@ -78,7 +78,10 @@ namespace SHADE // -------------------------------------------------------------------------/ template - static std::enable_if_t, T const* const> GetData(AssetID id) noexcept; + static std::enable_if_t, T* const> GetData(AssetID id) noexcept; + + template + static std::enable_if_t, T const* const> GetConstData(AssetID id) noexcept; static std::vector GetAllDataOfType(AssetType type) noexcept; static std::vector GetAllRecordOfType(AssetType type) noexcept; diff --git a/SHADE_Engine/src/Assets/SHAssetManager.hpp b/SHADE_Engine/src/Assets/SHAssetManager.hpp index 6c420778..baf8a2f3 100644 --- a/SHADE_Engine/src/Assets/SHAssetManager.hpp +++ b/SHADE_Engine/src/Assets/SHAssetManager.hpp @@ -4,7 +4,7 @@ namespace SHADE { template - std::enable_if_t, T const* const> SHAssetManager::GetData(AssetID id) noexcept + std::enable_if_t, T* const> SHAssetManager::GetData(AssetID id) noexcept { if (!assetData.contains(id)) { @@ -13,7 +13,7 @@ namespace SHADE if (asset.id == id) { assetData.emplace(id, LoadData(asset)); - return dynamic_cast(assetData[id]); + return dynamic_cast(assetData[id]); } } @@ -21,6 +21,27 @@ namespace SHADE return nullptr; } - return dynamic_cast(assetData[id]); + return dynamic_cast(assetData[id]); } + + template + std::enable_if_t, T const * const> SHAssetManager::GetConstData(AssetID id) noexcept + { + if (!assetData.contains(id)) + { + for (auto const& asset : assetCollection) + { + if (asset.id == id) + { + assetData.emplace(id, LoadData(asset)); + return dynamic_cast(assetData[id]); + } + } + + SHLOG_ERROR("Asset ID provided does not exist: {}", id); + return nullptr; + } + + return dynamic_cast(assetData[id]); + } } From 22b0a2f97b6740dcc45a0558896c3d280befa555 Mon Sep 17 00:00:00 2001 From: Xiao Qi Date: Fri, 28 Oct 2022 21:20:59 +0800 Subject: [PATCH 24/44] Changed tabs/spacing --- SHADE_Engine/src/Assets/SHAssetManager.cpp | 184 ++++++++++----------- 1 file changed, 92 insertions(+), 92 deletions(-) diff --git a/SHADE_Engine/src/Assets/SHAssetManager.cpp b/SHADE_Engine/src/Assets/SHAssetManager.cpp index 06acf7de..967f9a18 100644 --- a/SHADE_Engine/src/Assets/SHAssetManager.cpp +++ b/SHADE_Engine/src/Assets/SHAssetManager.cpp @@ -113,8 +113,8 @@ namespace SHADE { case AssetType::SHADER: case AssetType::SHADER_BUILT_IN: - folder = "Shaders/"; - break; + folder = "Shaders/"; + break; default: folder = "/"; @@ -172,16 +172,16 @@ namespace SHADE AssetID SHAssetManager::CreateAsset(AssetName name, AssetType type) noexcept { - AssetID id = GenerateAssetID(type); + AssetID id = GenerateAssetID(type); - assetCollection.emplace_back( - name, - id, - type, - GenerateNewPath(name, type) - ); - return id; - } + assetCollection.emplace_back( + name, + id, + type, + GenerateNewPath(name, type) + ); + return id; + } /**************************************************************************** * \brief Import new asset from outside editor window. * @@ -245,28 +245,28 @@ namespace SHADE return result; } - AssetID SHAssetManager::CompileAsset(AssetPath path) noexcept - { - SHAsset newAsset - { - .name = path.stem().string() - }; + AssetID SHAssetManager::CompileAsset(AssetPath path) noexcept + { + SHAsset newAsset + { + .name = path.stem().string() + }; - auto const ext{ path.extension().string() }; - if (ext == GLSL_EXTENSION.data()) - { - newAsset.path = SHShaderSourceCompiler::LoadAndCompileShader(path).value(); - newAsset.id = GenerateAssetID(AssetType::SHADER_BUILT_IN); - newAsset.type = AssetType::SHADER_BUILT_IN; - } + auto const ext{ path.extension().string() }; + if (ext == GLSL_EXTENSION.data()) + { + newAsset.path = SHShaderSourceCompiler::LoadAndCompileShader(path).value(); + newAsset.id = GenerateAssetID(AssetType::SHADER_BUILT_IN); + newAsset.type = AssetType::SHADER_BUILT_IN; + } - assetCollection.push_back(newAsset); - SHAssetMetaHandler::WriteMetaData(newAsset); + assetCollection.push_back(newAsset); + SHAssetMetaHandler::WriteMetaData(newAsset); - return newAsset.id; - } + return newAsset.id; + } - bool SHAssetManager::IsRecognised(char const* ext) noexcept + bool SHAssetManager::IsRecognised(char const* ext) noexcept { for (auto const& e : EXTENSIONS) { @@ -291,77 +291,77 @@ namespace SHADE return result; } - void SHAssetManager::CompileAll() noexcept - { - std::vector paths; + void SHAssetManager::CompileAll() noexcept + { + std::vector paths; - for (auto const& dir : std::filesystem::recursive_directory_iterator{ ASSET_ROOT }) - { - if (dir.is_regular_file()) - { - for (auto const& ext : EXTERNALS) - { - if (dir.path().extension().string() == ext.data()) - { - paths.push_back(dir.path()); - } - } - } - } + for (auto const& dir : std::filesystem::recursive_directory_iterator{ ASSET_ROOT }) + { + if (dir.is_regular_file()) + { + for (auto const& ext : EXTERNALS) + { + if (dir.path().extension().string() == ext.data()) + { + paths.push_back(dir.path()); + } + } + } + } - for (auto const& path : paths) - { - SHAsset newAsset - { - .name = path.stem().string() - }; + for (auto const& path : paths) + { + SHAsset newAsset + { + .name = path.stem().string() + }; - auto const ext{ path.extension().string() }; - if (ext == GLSL_EXTENSION.data()) - { - newAsset.path = SHShaderSourceCompiler::LoadAndCompileShader(path).value(); - newAsset.id = GenerateAssetID(AssetType::SHADER_BUILT_IN); - newAsset.type = AssetType::SHADER_BUILT_IN; - } - else if (ext == DDS_EXTENSION.data()) - { - newAsset.path = SHTextureCompiler::CompileTextureAsset(path).value(); - newAsset.id = GenerateAssetID(AssetType::TEXTURE); - newAsset.type = AssetType::TEXTURE; - } - else if (ext == GLTF_EXTENSION.data() || ext == FBX_EXTENSION.data()) - { - std::vector meshes; - std::vector anims; - SHMeshCompiler::LoadFromFile(path, meshes, anims); + auto const ext{ path.extension().string() }; + if (ext == GLSL_EXTENSION.data()) + { + newAsset.path = SHShaderSourceCompiler::LoadAndCompileShader(path).value(); + newAsset.id = GenerateAssetID(AssetType::SHADER_BUILT_IN); + newAsset.type = AssetType::SHADER_BUILT_IN; + } + else if (ext == DDS_EXTENSION.data()) + { + newAsset.path = SHTextureCompiler::CompileTextureAsset(path).value(); + newAsset.id = GenerateAssetID(AssetType::TEXTURE); + newAsset.type = AssetType::TEXTURE; + } + else if (ext == GLTF_EXTENSION.data() || ext == FBX_EXTENSION.data()) + { + std::vector meshes; + std::vector anims; + SHMeshCompiler::LoadFromFile(path, meshes, anims); - for (auto const& mesh : meshes) - { - SHAsset meshAsset{ - .name = mesh->header.name - }; - meshAsset.path = SHMeshCompiler::CompileMeshBinary(*mesh, path).value(); - meshAsset.id = GenerateAssetID(AssetType::MESH); - meshAsset.type = AssetType::MESH; - assetCollection.push_back(meshAsset); - SHAssetMetaHandler::WriteMetaData(meshAsset); - } - continue; - } + for (auto const& mesh : meshes) + { + SHAsset meshAsset{ + .name = mesh->header.name + }; + meshAsset.path = SHMeshCompiler::CompileMeshBinary(*mesh, path).value(); + meshAsset.id = GenerateAssetID(AssetType::MESH); + meshAsset.type = AssetType::MESH; + assetCollection.push_back(meshAsset); + SHAssetMetaHandler::WriteMetaData(meshAsset); + } + continue; + } - assetCollection.push_back(newAsset); - SHAssetMetaHandler::WriteMetaData(newAsset); - } - } + assetCollection.push_back(newAsset); + SHAssetMetaHandler::WriteMetaData(newAsset); + } + } - void SHAssetManager:: InitLoaders() noexcept + void SHAssetManager:: InitLoaders() noexcept { loaders[static_cast(AssetType::SHADER)] = dynamic_cast(new SHShaderSourceLoader()); loaders[static_cast(AssetType::SHADER_BUILT_IN)] = loaders[static_cast(AssetType::SHADER)]; - loaders[static_cast(AssetType::TEXTURE)] = dynamic_cast(new SHTextureLoader()); - loaders[static_cast(AssetType::MESH)] = dynamic_cast(new SHMeshLoader()); - loaders[static_cast(AssetType::SCENE)] = dynamic_cast(new SHTextBasedLoader()); - loaders[static_cast(AssetType::PREFAB)] = loaders[static_cast(AssetType::SCENE)]; + loaders[static_cast(AssetType::TEXTURE)] = dynamic_cast(new SHTextureLoader()); + loaders[static_cast(AssetType::MESH)] = dynamic_cast(new SHMeshLoader()); + loaders[static_cast(AssetType::SCENE)] = dynamic_cast(new SHTextBasedLoader()); + loaders[static_cast(AssetType::PREFAB)] = loaders[static_cast(AssetType::SCENE)]; } /**************************************************************************** @@ -369,7 +369,7 @@ namespace SHADE ****************************************************************************/ void SHAssetManager::Load() noexcept { - //CompileAll(); + //CompileAll(); InitLoaders(); BuildAssetCollection(); //LoadAllData(); From cd62dbbb2515771616c783078fa97994a9a778a4 Mon Sep 17 00:00:00 2001 From: Xiao Qi Date: Sat, 29 Oct 2022 11:58:14 +0800 Subject: [PATCH 25/44] Material WIP --- .../src/Assets/Libraries/Loaders/SHTextBasedLoader.cpp | 8 ++++++++ SHADE_Engine/src/Assets/SHAssetMacros.h | 1 + SHADE_Engine/src/Assets/SHAssetManager.cpp | 1 + 3 files changed, 10 insertions(+) diff --git a/SHADE_Engine/src/Assets/Libraries/Loaders/SHTextBasedLoader.cpp b/SHADE_Engine/src/Assets/Libraries/Loaders/SHTextBasedLoader.cpp index 60ea80f6..0dca981e 100644 --- a/SHADE_Engine/src/Assets/Libraries/Loaders/SHTextBasedLoader.cpp +++ b/SHADE_Engine/src/Assets/Libraries/Loaders/SHTextBasedLoader.cpp @@ -50,6 +50,10 @@ namespace SHADE data->data = std::move(content); result = data; } + else if (path.extension().string() == MATERIAL_EXTENSION) + { + auto data = //TODO make material class + } file.close(); @@ -76,6 +80,10 @@ namespace SHADE auto prefab = dynamic_cast(data); file << prefab->data; } + else if (path.extension().string() == MATERIAL_EXTENSION) + { + auto material = //todo + } file.close(); } diff --git a/SHADE_Engine/src/Assets/SHAssetMacros.h b/SHADE_Engine/src/Assets/SHAssetMacros.h index ff154810..91d8658a 100644 --- a/SHADE_Engine/src/Assets/SHAssetMacros.h +++ b/SHADE_Engine/src/Assets/SHAssetMacros.h @@ -49,6 +49,7 @@ enum class AssetType : AssetTypeMeta MESH, SCENE, PREFAB, + MATERIAL, MAX_COUNT }; constexpr size_t TYPE_COUNT{ static_cast(AssetType::MAX_COUNT) }; diff --git a/SHADE_Engine/src/Assets/SHAssetManager.cpp b/SHADE_Engine/src/Assets/SHAssetManager.cpp index 967f9a18..7b75f508 100644 --- a/SHADE_Engine/src/Assets/SHAssetManager.cpp +++ b/SHADE_Engine/src/Assets/SHAssetManager.cpp @@ -362,6 +362,7 @@ namespace SHADE loaders[static_cast(AssetType::MESH)] = dynamic_cast(new SHMeshLoader()); loaders[static_cast(AssetType::SCENE)] = dynamic_cast(new SHTextBasedLoader()); loaders[static_cast(AssetType::PREFAB)] = loaders[static_cast(AssetType::SCENE)]; + loaders[static_cast(AssetType::MATERIAL)] = loaders[static_cast(AssetType::SCENE)]; } /**************************************************************************** From 0182c90a21e8e59904efb8b29e5b47a8a14860bd Mon Sep 17 00:00:00 2001 From: Xiao Qi Date: Sat, 29 Oct 2022 14:42:38 +0800 Subject: [PATCH 26/44] Interface to create and save new assets that are internal: Prefabs, Scenes, Materials --- .../src/Assets/Asset Types/SHMaterialAsset.h | 23 +++++ .../Libraries/Loaders/SHTextBasedLoader.cpp | 9 +- SHADE_Engine/src/Assets/SHAssetMacros.h | 5 ++ SHADE_Engine/src/Assets/SHAssetManager.cpp | 86 +++++++++++++------ SHADE_Engine/src/Assets/SHAssetManager.h | 7 +- 5 files changed, 100 insertions(+), 30 deletions(-) create mode 100644 SHADE_Engine/src/Assets/Asset Types/SHMaterialAsset.h diff --git a/SHADE_Engine/src/Assets/Asset Types/SHMaterialAsset.h b/SHADE_Engine/src/Assets/Asset Types/SHMaterialAsset.h new file mode 100644 index 00000000..a130fc07 --- /dev/null +++ b/SHADE_Engine/src/Assets/Asset Types/SHMaterialAsset.h @@ -0,0 +1,23 @@ +/****************************************************************************** + * \file SHMaterialAsset.h + * \author Loh Xiao Qi + * \date 29 October 2022 + * \brief + * + * \copyright 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 "Assets/Asset Types/SHAssetData.h" +#include + +namespace SHADE +{ + struct SHMaterialAsset : SHAssetData + { + std::string name; + std::string data; + }; +} diff --git a/SHADE_Engine/src/Assets/Libraries/Loaders/SHTextBasedLoader.cpp b/SHADE_Engine/src/Assets/Libraries/Loaders/SHTextBasedLoader.cpp index 0dca981e..b23130f3 100644 --- a/SHADE_Engine/src/Assets/Libraries/Loaders/SHTextBasedLoader.cpp +++ b/SHADE_Engine/src/Assets/Libraries/Loaders/SHTextBasedLoader.cpp @@ -13,6 +13,7 @@ #include "Assets/Asset Types/SHSceneAsset.h" #include "Assets/Asset Types/SHPrefabAsset.h" +#include "Assets/Asset Types/SHMaterialAsset.h" #include #include @@ -52,7 +53,10 @@ namespace SHADE } else if (path.extension().string() == MATERIAL_EXTENSION) { - auto data = //TODO make material class + auto data = new SHMaterialAsset(); + data->name = path.stem().string(); + data->data = std::move(content); + result = data; } file.close(); @@ -82,7 +86,8 @@ namespace SHADE } else if (path.extension().string() == MATERIAL_EXTENSION) { - auto material = //todo + auto material = dynamic_cast(data); + file << material->data; } file.close(); diff --git a/SHADE_Engine/src/Assets/SHAssetMacros.h b/SHADE_Engine/src/Assets/SHAssetMacros.h index 91d8658a..4489e807 100644 --- a/SHADE_Engine/src/Assets/SHAssetMacros.h +++ b/SHADE_Engine/src/Assets/SHAssetMacros.h @@ -61,6 +61,11 @@ constexpr std::string_view ASSET_ROOT {"Assets"}; constexpr std::string_view ASSET_ROOT {"../../Assets"}; #endif +// INTERNAL ASSET PATHS +constexpr std::string_view SCENE_FOLDER{ "/Scenes/" }; +constexpr std::string_view PREFAB_FOLDER{ "/Prefabs/" }; +constexpr std::string_view MATERIAL_FOLDER{ "/Materials/" }; + // ASSET EXTENSIONS constexpr std::string_view META_EXTENSION {".shmeta"}; diff --git a/SHADE_Engine/src/Assets/SHAssetManager.cpp b/SHADE_Engine/src/Assets/SHAssetManager.cpp index 7b75f508..989da37b 100644 --- a/SHADE_Engine/src/Assets/SHAssetManager.cpp +++ b/SHADE_Engine/src/Assets/SHAssetManager.cpp @@ -148,40 +148,74 @@ namespace SHADE ****************************************************************************/ AssetID SHAssetManager::CreateNewAsset(AssetType type, AssetName name) noexcept { - AssetID id{ GenerateAssetID(type) }; - SHAsset meta; - meta.id = id; - meta.type = type; + std::string newPath{ ASSET_ROOT }; + switch (type) + { + case AssetType::PREFAB: + newPath += PREFAB_FOLDER; + break; - std::string folder; - //TODO implement folder choosing - //switch (type) - //{ - //default: - // folder = ""; - // break; - //} - AssetPath path{ std::string{ASSET_ROOT} + folder + name + SHAssetMetaHandler::GetExtensionFromType(type) }; + case AssetType::SCENE: + newPath += SCENE_FOLDER; + break; - SHAssetMetaHandler::WriteMetaData(meta); + case AssetType::MATERIAL: + newPath += MATERIAL_FOLDER; + break; - assetCollection.push_back(meta); + default: + SHLOG_ERROR("Asset type of {} not an internal asset type, cannot be created", name); + return 0; + } + + auto id = GenerateAssetID(type); + + assetCollection.emplace_back( + name, + id, + type, + newPath + ); return id; } - AssetID SHAssetManager::CreateAsset(AssetName name, AssetType type) noexcept - { - AssetID id = GenerateAssetID(type); + void SHAssetManager::SaveAsset(AssetID id) noexcept + { + for (auto const& asset : assetCollection) + { + if (asset.id == id) + { + if ( + asset.type == AssetType::SCENE || + asset.type == AssetType::PREFAB || + asset.type == AssetType::MATERIAL + ) + { + auto const data = assetData[id]; + loaders[static_cast(asset.type)]->Write(data, asset.path); + return; + } + } + } + + SHLOG_WARNING("Asset id: {} not an internal asset type, save cannot be triggered", id); + } + + //AssetID SHAssetManager::CreateAsset(AssetName name, AssetType type) noexcept + //{ + // AssetID id = GenerateAssetID(type); + + // assetCollection.emplace_back( + // name, + // id, + // type, + // GenerateNewPath(name, type) + // ); + // return id; + //} + - assetCollection.emplace_back( - name, - id, - type, - GenerateNewPath(name, type) - ); - return id; - } /**************************************************************************** * \brief Import new asset from outside editor window. * diff --git a/SHADE_Engine/src/Assets/SHAssetManager.h b/SHADE_Engine/src/Assets/SHAssetManager.h index 7521e356..c5b9277e 100644 --- a/SHADE_Engine/src/Assets/SHAssetManager.h +++ b/SHADE_Engine/src/Assets/SHAssetManager.h @@ -59,8 +59,8 @@ namespace SHADE * \param name of resource * \return resource id generated for new asset ****************************************************************************/ - static AssetID CreateNewAsset(AssetType, AssetName) noexcept; - static AssetID CreateAsset(AssetName name, AssetType type) noexcept; + static AssetID CreateNewAsset(AssetType type, AssetName name) noexcept; + static void SaveAsset(AssetID id) noexcept; /**************************************************************************** * \brief Import new resource from outside editor window. @@ -101,6 +101,9 @@ namespace SHADE static void CompileAll() noexcept; + //TODO use this function to create asset data internall at all calls to generate id + //static AssetID CreateAsset(AssetName name, AssetType type) noexcept; + static FMOD::System* audioSystem; static std::unordered_map* audioSoundList; From 270205b0ba4a473d2444f59c990c2c4abcbbada1 Mon Sep 17 00:00:00 2001 From: Xiao Qi Date: Sat, 29 Oct 2022 14:50:44 +0800 Subject: [PATCH 27/44] Added line to write asset meta into file when saving Does check for data write before saving --- SHADE_Engine/src/Assets/SHAssetManager.cpp | 19 +++++++++++++++---- SHADE_Engine/src/Assets/SHAssetManager.h | 2 +- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/SHADE_Engine/src/Assets/SHAssetManager.cpp b/SHADE_Engine/src/Assets/SHAssetManager.cpp index 989da37b..90002b3d 100644 --- a/SHADE_Engine/src/Assets/SHAssetManager.cpp +++ b/SHADE_Engine/src/Assets/SHAssetManager.cpp @@ -180,7 +180,7 @@ namespace SHADE return id; } - void SHAssetManager::SaveAsset(AssetID id) noexcept + bool SHAssetManager::SaveAsset(AssetID id) noexcept { for (auto const& asset : assetCollection) { @@ -192,14 +192,25 @@ namespace SHADE asset.type == AssetType::MATERIAL ) { - auto const data = assetData[id]; - loaders[static_cast(asset.type)]->Write(data, asset.path); - return; + if (assetData.contains(id)) + { + auto const data = assetData.at(id); + loaders[static_cast(asset.type)]->Write(data, asset.path); + SHAssetMetaHandler::WriteMetaData(asset); + + return true; + } + + SHLOG_ERROR("Asset data has not been written into, cannot be saved: {}", + asset.path.filename().string()); + + return false; } } } SHLOG_WARNING("Asset id: {} not an internal asset type, save cannot be triggered", id); + return false; } //AssetID SHAssetManager::CreateAsset(AssetName name, AssetType type) noexcept diff --git a/SHADE_Engine/src/Assets/SHAssetManager.h b/SHADE_Engine/src/Assets/SHAssetManager.h index c5b9277e..28950646 100644 --- a/SHADE_Engine/src/Assets/SHAssetManager.h +++ b/SHADE_Engine/src/Assets/SHAssetManager.h @@ -60,7 +60,7 @@ namespace SHADE * \return resource id generated for new asset ****************************************************************************/ static AssetID CreateNewAsset(AssetType type, AssetName name) noexcept; - static void SaveAsset(AssetID id) noexcept; + static bool SaveAsset(AssetID id) noexcept; /**************************************************************************** * \brief Import new resource from outside editor window. From 219492dedd5c97a45a0cff0c7b8c5dc509f0c512 Mon Sep 17 00:00:00 2001 From: Xiao Qi Date: Sat, 29 Oct 2022 15:36:34 +0800 Subject: [PATCH 28/44] Changed asset collection from vector to unordered_map for better id col check Reduce use of for loops to iterate through asset collection --- SHADE_Engine/src/Assets/SHAssetManager.cpp | 91 ++++++++++++---------- SHADE_Engine/src/Assets/SHAssetManager.h | 4 +- SHADE_Engine/src/Assets/SHAssetManager.hpp | 4 +- 3 files changed, 56 insertions(+), 43 deletions(-) diff --git a/SHADE_Engine/src/Assets/SHAssetManager.cpp b/SHADE_Engine/src/Assets/SHAssetManager.cpp index 90002b3d..78c94da7 100644 --- a/SHADE_Engine/src/Assets/SHAssetManager.cpp +++ b/SHADE_Engine/src/Assets/SHAssetManager.cpp @@ -10,6 +10,7 @@ #include "SHpch.h" #include #include +#include #include "SHAssetManager.h" #include "SHAssetMetaHandler.h" @@ -29,8 +30,9 @@ namespace SHADE std::vector SHAssetManager::loaders(TYPE_COUNT); - std::vector SHAssetManager::assetCollection; + std::unordered_map SHAssetManager::assetCollection; std::unordered_map SHAssetManager::assetData; + /**************************************************************************** * \brief Static function to generate asset ID. @@ -45,13 +47,7 @@ namespace SHADE result |= unique; - while (result == 0 || - std::ranges::any_of( - assetCollection.begin(), - assetCollection.end(), - [result](SHAsset const& asset) { return asset.id == result; } - ) - ) + while (result == 0 || assetCollection.contains(result)) { result = GenerateAssetID(type); } @@ -133,9 +129,17 @@ namespace SHADE * * \return const& to unordered_map ****************************************************************************/ - std::vector const& SHAssetManager::GetAllAssets() noexcept + std::vector SHAssetManager::GetAllAssets() noexcept { - return assetCollection; + std::vector result; + result.reserve(assetCollection.size()); + + for (auto const& asset : std::ranges::views::values(assetCollection)) + { + result.push_back(asset); + } + + return result; } /**************************************************************************** @@ -169,43 +173,50 @@ namespace SHADE } auto id = GenerateAssetID(type); - - assetCollection.emplace_back( + SHAsset asset{ name, id, type, newPath - ); + }; + + assetCollection.insert({ + id, + SHAsset( + name, + id, + type, + newPath + ) + }); return id; } bool SHAssetManager::SaveAsset(AssetID id) noexcept { - for (auto const& asset : assetCollection) + if (assetCollection.contains(id)) { - if (asset.id == id) + auto const& asset = assetCollection[id]; + if ( + asset.type == AssetType::SCENE || + asset.type == AssetType::PREFAB || + asset.type == AssetType::MATERIAL + ) { - if ( - asset.type == AssetType::SCENE || - asset.type == AssetType::PREFAB || - asset.type == AssetType::MATERIAL - ) + if (assetData.contains(id)) { - if (assetData.contains(id)) - { - auto const data = assetData.at(id); - loaders[static_cast(asset.type)]->Write(data, asset.path); - SHAssetMetaHandler::WriteMetaData(asset); + auto const data = assetData.at(id); + loaders[static_cast(asset.type)]->Write(data, asset.path); + SHAssetMetaHandler::WriteMetaData(asset); - return true; - } - - SHLOG_ERROR("Asset data has not been written into, cannot be saved: {}", - asset.path.filename().string()); - - return false; + return true; } + + SHLOG_ERROR("Asset data has not been written into, cannot be saved: {}", + asset.path.filename().string()); + + return false; } } @@ -249,7 +260,8 @@ namespace SHADE std::filesystem::copy(path, newPath); - assetCollection.push_back(CreateAssetFromPath(newPath)); + auto asset = CreateAssetFromPath(newPath); + assetCollection.insert({asset.id, asset}); return id; } @@ -279,7 +291,7 @@ namespace SHADE std::vector SHAssetManager::GetAllRecordOfType(AssetType type) noexcept { std::vector result; - for (auto const& asset : assetCollection) + for (auto const& asset : std::ranges::views::values(assetCollection)) { if (asset.type == type) { @@ -305,7 +317,7 @@ namespace SHADE newAsset.type = AssetType::SHADER_BUILT_IN; } - assetCollection.push_back(newAsset); + assetCollection.insert({ newAsset.id, newAsset }); SHAssetMetaHandler::WriteMetaData(newAsset); return newAsset.id; @@ -388,13 +400,13 @@ namespace SHADE meshAsset.path = SHMeshCompiler::CompileMeshBinary(*mesh, path).value(); meshAsset.id = GenerateAssetID(AssetType::MESH); meshAsset.type = AssetType::MESH; - assetCollection.push_back(meshAsset); + assetCollection.insert({ meshAsset.id, meshAsset }); SHAssetMetaHandler::WriteMetaData(meshAsset); } continue; } - assetCollection.push_back(newAsset); + assetCollection.insert({ newAsset.id, newAsset }); SHAssetMetaHandler::WriteMetaData(newAsset); } } @@ -426,7 +438,7 @@ namespace SHADE ****************************************************************************/ void SHAssetManager::LoadAllData() noexcept { - for (auto const& asset : assetCollection) + for (auto const& asset : std::ranges::views::values(assetCollection)) { SHAssetData* data = loaders[static_cast(asset.type)]->Load(asset.path); assetData.emplace(asset.id, data); @@ -457,7 +469,8 @@ namespace SHADE { if (dir.path().extension().string() == META_EXTENSION.data()) { - assetCollection.push_back(SHAssetMetaHandler::RetrieveMetaData(dir.path())); + auto asset = SHAssetMetaHandler::RetrieveMetaData(dir.path()); + assetCollection.insert({ asset.id, asset }); } } } diff --git a/SHADE_Engine/src/Assets/SHAssetManager.h b/SHADE_Engine/src/Assets/SHAssetManager.h index 28950646..fca38865 100644 --- a/SHADE_Engine/src/Assets/SHAssetManager.h +++ b/SHADE_Engine/src/Assets/SHAssetManager.h @@ -49,7 +49,7 @@ namespace SHADE * * \return const& to unordered_map ****************************************************************************/ - static std::vector const& GetAllAssets() noexcept; + static std::vector GetAllAssets() noexcept; /**************************************************************************** * \brief Create record for new resource. CAN ONLY CREATE FOR CUSTOM @@ -110,7 +110,7 @@ namespace SHADE static std::vector loaders; // For all resources - static std::vector assetCollection; + static std::unordered_map assetCollection; static std::unordered_map assetData; }; } diff --git a/SHADE_Engine/src/Assets/SHAssetManager.hpp b/SHADE_Engine/src/Assets/SHAssetManager.hpp index baf8a2f3..4f372938 100644 --- a/SHADE_Engine/src/Assets/SHAssetManager.hpp +++ b/SHADE_Engine/src/Assets/SHAssetManager.hpp @@ -8,7 +8,7 @@ namespace SHADE { if (!assetData.contains(id)) { - for (auto const& asset : assetCollection) + for (auto const& asset : std::ranges::views::values(assetCollection)) { if (asset.id == id) { @@ -29,7 +29,7 @@ namespace SHADE { if (!assetData.contains(id)) { - for (auto const& asset : assetCollection) + for (auto const& asset : std::ranges::views::values(assetCollection)) { if (asset.id == id) { From c71a84cc59cebf14d7c91b326eff2c9ff15379fa Mon Sep 17 00:00:00 2001 From: Xiao Qi Date: Sat, 29 Oct 2022 15:50:26 +0800 Subject: [PATCH 29/44] Simple file deletion --- SHADE_Engine/src/Assets/SHAssetManager.cpp | 38 +++++++++++++++++----- SHADE_Engine/src/Assets/SHAssetManager.h | 11 ++++--- 2 files changed, 36 insertions(+), 13 deletions(-) diff --git a/SHADE_Engine/src/Assets/SHAssetManager.cpp b/SHADE_Engine/src/Assets/SHAssetManager.cpp index 78c94da7..96ea7d1a 100644 --- a/SHADE_Engine/src/Assets/SHAssetManager.cpp +++ b/SHADE_Engine/src/Assets/SHAssetManager.cpp @@ -57,11 +57,6 @@ namespace SHADE /**************************************************************************** * \brief Deallocate all memory used by asset data ****************************************************************************/ - void SHAssetManager::Unload() noexcept - { - - } - void SHAssetManager::Unload(AssetID assetId) noexcept { // TODO @@ -74,9 +69,9 @@ namespace SHADE delete loader; } - for (auto const& data : assetData) + for (auto const& data : std::ranges::views::values(assetData)) { - delete data.second; + delete data; } } @@ -224,6 +219,27 @@ namespace SHADE return false; } + bool SHAssetManager::DeleteAsset(AssetID id) noexcept + { + + if (assetCollection.contains(id)) + { + auto const& asset = assetCollection[id]; + if ( + asset.type == AssetType::SCENE || + asset.type == AssetType::PREFAB || + asset.type == AssetType::MATERIAL + ) + { + return (DeleteLocalFile(asset.path) && DeleteLocalFile(asset.path.string() + META_EXTENSION.data())); + } + SHLOG_WARNING("Asset id: {} not an internal asset type, file deletion not allowed", id); + } + + SHLOG_WARNING("Asset id does not exist, nothing was deleted: {}", id); + return false; + } + //AssetID SHAssetManager::CreateAsset(AssetName name, AssetType type) noexcept //{ // AssetID id = GenerateAssetID(type); @@ -411,7 +427,13 @@ namespace SHADE } } - void SHAssetManager:: InitLoaders() noexcept + bool SHAssetManager::DeleteLocalFile(AssetPath path) noexcept + { + //TODO Move this to dedicated library + return std::filesystem::remove(path); + } + + void SHAssetManager:: InitLoaders() noexcept { loaders[static_cast(AssetType::SHADER)] = dynamic_cast(new SHShaderSourceLoader()); loaders[static_cast(AssetType::SHADER_BUILT_IN)] = loaders[static_cast(AssetType::SHADER)]; diff --git a/SHADE_Engine/src/Assets/SHAssetManager.h b/SHADE_Engine/src/Assets/SHAssetManager.h index fca38865..22e92c7d 100644 --- a/SHADE_Engine/src/Assets/SHAssetManager.h +++ b/SHADE_Engine/src/Assets/SHAssetManager.h @@ -26,19 +26,17 @@ namespace SHADE * \brief Static function to generate resource ID. ****************************************************************************/ static AssetID GenerateAssetID(AssetType type) noexcept; - static AssetPath GenerateLocalPath(AssetPath path) noexcept; - static AssetPath GenerateNewPath(AssetName name, AssetType type); /**************************************************************************** * \brief Deallocate all memory used by resource data ****************************************************************************/ - static void Unload() noexcept; - static void Unload(AssetID assetId) noexcept; - static void Exit() noexcept; + + static void Unload(AssetID assetId) noexcept; + /**************************************************************************** * \brief Load all resources that are in the folder ****************************************************************************/ @@ -61,6 +59,7 @@ namespace SHADE ****************************************************************************/ static AssetID CreateNewAsset(AssetType type, AssetName name) noexcept; static bool SaveAsset(AssetID id) noexcept; + static bool DeleteAsset(AssetID id) noexcept; /**************************************************************************** * \brief Import new resource from outside editor window. @@ -101,6 +100,8 @@ namespace SHADE static void CompileAll() noexcept; + static bool DeleteLocalFile(AssetPath path) noexcept; + //TODO use this function to create asset data internall at all calls to generate id //static AssetID CreateAsset(AssetName name, AssetType type) noexcept; From 70533b17126773e466366a59f6aaa012dab3bace Mon Sep 17 00:00:00 2001 From: Xiao Qi Date: Sat, 29 Oct 2022 15:53:15 +0800 Subject: [PATCH 30/44] Changed Application exit call to asset manager --- SHADE_Application/src/Application/SBApplication.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SHADE_Application/src/Application/SBApplication.cpp b/SHADE_Application/src/Application/SBApplication.cpp index 53393fea..de548060 100644 --- a/SHADE_Application/src/Application/SBApplication.cpp +++ b/SHADE_Application/src/Application/SBApplication.cpp @@ -159,7 +159,7 @@ namespace Sandbox SHSceneManager::Exit(); SHSystemManager::Exit(); - SHAssetManager::Unload(); + SHAssetManager::Exit(); } } From 25db4db99a22b3c71817a598fbf59eb5760fa73e Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Sat, 29 Oct 2022 17:00:35 +0800 Subject: [PATCH 31/44] Catered to light comp deletion and solved minimize bugs Editor can also now shift the viewport around without Vulkan vomiting validation layers --- .../MiddleEnd/Interface/SHGraphicsSystem.cpp | 41 +++++++++-------- .../MiddleEnd/Interface/SHGraphicsSystem.h | 2 + .../MiddleEnd/Lights/SHLightingSubSystem.cpp | 44 +++++++++++++++---- .../MiddleEnd/Lights/SHLightingSubSystem.h | 13 +++++- .../MiddleEnd/PerFrame/SHRenderContext.cpp | 1 + 5 files changed, 71 insertions(+), 30 deletions(-) diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp index ad040cd9..66c41e3e 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp @@ -73,15 +73,7 @@ namespace SHADE if (width == 0 || height == 0) return; -#ifdef SHEDITOR - - //PrepareResize(1, 1, SHVec2(0, 0)); - -#else - - PrepareResize(resizeWidth, resizeHeight, SHVec2(0, 0)); - -#endif + PrepareResize(resizeWidth, resizeHeight); }); window->RegisterWindowCloseCallback([&](void) @@ -352,6 +344,12 @@ namespace SHADE void SHGraphicsSystem::Run(double) noexcept { if (window->IsMinimized() || renderContext.GetWindowIsDead()) + { + restoredFromMinimize = true; + return; + } + + if (restoredFromMinimize) return; // Frame data for the current frame @@ -487,17 +485,12 @@ namespace SHADE { if (window->IsMinimized() || renderContext.GetWindowIsDead()) { - // #BackEndTest: For for the fence initialized by queue submit - renderContext.WaitForFence(); - - // #BackEndTest: Get the current frame from frame manager - auto& currFrameData = renderContext.GetCurrentFrameData(); - - // #BackEndTest: Reset command pool - if (currFrameData.cmdPoolHdls.empty()) - throw std::runtime_error("No command pools available!"); - currFrameData.cmdPoolHdls[0]->Reset(); + restoredFromMinimize = true; + return; + } + if (restoredFromMinimize) + { return; } @@ -548,7 +541,17 @@ namespace SHADE void SHGraphicsSystem::EndRender() { if (window->IsMinimized() || renderContext.GetWindowIsDead()) + { + restoredFromMinimize = true; return; + } + + if (restoredFromMinimize) + { + restoredFromMinimize = false; + return; + } + const uint32_t CURR_FRAME_IDX = renderContext.GetCurrentFrame(); auto& currFrameData = renderContext.GetCurrentFrameData(); diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h index ae93bd78..8830bfa5 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h @@ -356,5 +356,7 @@ namespace SHADE uint32_t resizeWidth; uint32_t resizeHeight; + bool restoredFromMinimize = false; + }; } \ No newline at end of file diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp index e8d85dd1..5ca879c4 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp @@ -67,6 +67,7 @@ namespace SHADE } } + /***************************************************************************/ /*! @@ -88,6 +89,7 @@ namespace SHADE // Get data required for struct lightDataSize = GetLightTypeSize(type); + lightDataAlignedSize = logicalDevice->PadSSBOSize(lightDataSize); // So create some data! Expand(logicalDevice); @@ -123,10 +125,10 @@ namespace SHADE // Initialize the data for lights intermediateData = std::make_unique(lightDataSize * maxLights); - lightDataAlignedSize = logicalDevice->PadSSBOSize(lightDataSize * maxLights); + lightDataTotalAlignedSize = logicalDevice->PadSSBOSize(lightDataAlignedSize * maxLights); // We want to initialize 3 times the amount of data required. - dataBuffer = logicalDevice->CreateBuffer(lightDataAlignedSize * SHGraphicsConstants::NUM_FRAME_BUFFERS, nullptr, lightDataAlignedSize * SHGraphicsConstants::NUM_FRAME_BUFFERS, vk::BufferUsageFlagBits::eStorageBuffer, VMA_MEMORY_USAGE_AUTO, VMA_ALLOCATION_CREATE_MAPPED_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT); + dataBuffer = logicalDevice->CreateBuffer(lightDataTotalAlignedSize * SHGraphicsConstants::NUM_FRAME_BUFFERS, nullptr, lightDataTotalAlignedSize * SHGraphicsConstants::NUM_FRAME_BUFFERS, vk::BufferUsageFlagBits::eStorageBuffer, VMA_MEMORY_USAGE_AUTO, VMA_ALLOCATION_CREATE_MAPPED_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT); } else { @@ -145,7 +147,7 @@ namespace SHADE maxLights *= 2; // calculate total + padding - lightDataAlignedSize = logicalDevice->PadSSBOSize(lightDataSize * maxLights); + lightDataTotalAlignedSize = logicalDevice->PadSSBOSize(lightDataAlignedSize * maxLights); // destroy old data and initialize container for double the amount of data. intermediateData = std::make_unique(lightDataSize * maxLights); @@ -154,7 +156,7 @@ namespace SHADE std::memcpy(intermediateData.get(), oldData.get(), lightDataSize * OLD_MAX_LIGHTS); // Resize the GPU buffer. TODO: Replace with Resize no copy here - dataBuffer->ResizeReplace(maxLights * lightDataAlignedSize * SHGraphicsConstants::NUM_FRAME_BUFFERS, oldData.get(), lightDataAlignedSize * OLD_MAX_LIGHTS); + dataBuffer->ResizeReplace(maxLights * lightDataTotalAlignedSize * SHGraphicsConstants::NUM_FRAME_BUFFERS, oldData.get(), lightDataTotalAlignedSize * OLD_MAX_LIGHTS); } @@ -205,7 +207,7 @@ namespace SHADE uint32_t SHLightingSubSystem::PerTypeData::GetAlignmentSize(void) const noexcept { - return lightDataAlignedSize; + return lightDataTotalAlignedSize; } uint32_t SHLightingSubSystem::PerTypeData::GetDataSize(void) const noexcept @@ -254,7 +256,7 @@ namespace SHADE // Now that the container is big enough, bind the new light // Get address of write location - void* writeLocation = reinterpret_cast(intermediateData.get()) + (lightDataSize * numLights); + void* writeLocation = reinterpret_cast(intermediateData.get()) + (lightDataAlignedSize * numLights); // Write the light data to address WriteLightToAddress(writeLocation, unboundLight); @@ -280,7 +282,7 @@ namespace SHADE /***************************************************************************/ void SHLightingSubSystem::PerTypeData::ModifyLight(SHLightComponent* lightComp) noexcept { - void* writeLocation = reinterpret_cast(intermediateData.get()) + (lightDataSize * lightComp->GetIndexInBuffer()); + void* writeLocation = reinterpret_cast(intermediateData.get()) + (lightDataAlignedSize * lightComp->GetIndexInBuffer()); WriteLightToAddress(writeLocation, lightComp); } @@ -289,10 +291,15 @@ namespace SHADE if (intermediateData) { // we want to write to the offset of the current frame - dataBuffer->WriteToMemory(intermediateData.get(), lightDataSize * numLights, 0, lightDataSize * maxLights * frameIndex); + dataBuffer->WriteToMemory(intermediateData.get(), lightDataAlignedSize * numLights, 0, lightDataAlignedSize * maxLights * frameIndex); } } + void SHLightingSubSystem::PerTypeData::ResetNumLights(void) noexcept + { + numLights = 0; + } + /***************************************************************************/ /*! @@ -343,6 +350,14 @@ namespace SHADE } } + void SHLightingSubSystem::ResetNumLights(void) noexcept + { + for (auto& data : perTypeData) + { + data.ResetNumLights(); + } + } + /***************************************************************************/ /*! @@ -391,6 +406,7 @@ namespace SHADE dynamicOffsets[i].resize(NUM_LIGHT_TYPES + 1); // +1 for the count } + numLightComponents = 0; } /***************************************************************************/ @@ -409,13 +425,23 @@ namespace SHADE auto& lightComps = SHComponentManager::GetDense(); bool expanded = false; + bool rewrite = false; + + if (numLightComponents > lightComps.size()) + { + rewrite = true; + ResetNumLights(); + } + + numLightComponents = lightComps.size(); + for (auto& light : lightComps) { auto enumValue = SHUtilities::ToUnderlying(light.GetLightData().type); // First we want to make sure the light is already bound to the system. if it // isn't, we write it to the correct buffer. - if (!light.GetBound()) + if (!light.GetBound() || rewrite) { perTypeData[enumValue].AddLight(logicalDevice, &light, expanded); diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.h b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.h index dfb956ec..fb7aa2de 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.h @@ -65,7 +65,7 @@ namespace SHADE /*-----------------------------------------------------------------------*/ /* STATIC MEMBER VARIABLES */ /*-----------------------------------------------------------------------*/ - static constexpr uint32_t STARTING_NUM_LIGHTS = 20; + static constexpr uint32_t STARTING_NUM_LIGHTS = 50; /*-----------------------------------------------------------------------*/ /* PRIVATE MEMBER VARIABLES */ @@ -74,11 +74,13 @@ namespace SHADE uint32_t maxLights; //! SSBOs need to be aligned. This is to pad descriptor offset - uint32_t lightDataAlignedSize; + uint32_t lightDataTotalAlignedSize; //! size needed to store 1 struct object uint32_t lightDataSize; + uint32_t lightDataAlignedSize; + //! type of the light. Will be used later when we want to expand SH_LIGHT_TYPE lightType; @@ -103,6 +105,7 @@ namespace SHADE void AddLight (Handle logicalDevice, SHLightComponent* unboundLight, bool expanded) noexcept; void ModifyLight (SHLightComponent* lightComp) noexcept; void WriteToGPU (uint32_t frameIndex) noexcept; + void ResetNumLights (void) noexcept; /*-----------------------------------------------------------------------*/ /* GETTERS */ @@ -138,11 +141,17 @@ namespace SHADE //! For padding in the buffer uint32_t lightCountsAlignedSize; + //! Number of SHLightComponents recorded. If at the beginning of the run function the size returned by the dense + //! set is less than the size recorded, rewrite all light components into the its respective buffers. If its more, + //! don't do anything. + uint32_t numLightComponents; + /*-----------------------------------------------------------------------*/ /* PRIVATE MEMBER FUNCTIONS */ /*-----------------------------------------------------------------------*/ void UpdateDescSet (uint32_t binding) noexcept; void ComputeDynamicOffsets (void) noexcept; + void ResetNumLights (void) noexcept; public: diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/PerFrame/SHRenderContext.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/PerFrame/SHRenderContext.cpp index 8041adfd..45103819 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/PerFrame/SHRenderContext.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/PerFrame/SHRenderContext.cpp @@ -133,6 +133,7 @@ namespace SHADE { SHLOG_ERROR("Frame index retrieved from vkAcquireNextImageKHR is not the same as currentFrame."); } + currentFrame = frameIndex; } From 6f2ca54f7e7cac33473c7c35904d9e5f0a44aa97 Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Sat, 29 Oct 2022 21:36:11 +0800 Subject: [PATCH 32/44] WIP compute barriers --- .../RenderGraph/SHRenderGraphNodeCompute.cpp | 32 ++++++++++++++++++- .../RenderGraph/SHRenderGraphNodeCompute.h | 2 ++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp index 678fc41b..e4d2360e 100644 --- a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp +++ b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp @@ -68,7 +68,7 @@ namespace SHADE cmdBuffer->ComputeDispatch(groupSizeX, groupSizeY, 1); // TODO: barrier - + } void SHRenderGraphNodeCompute::HandleResize(void) noexcept @@ -103,6 +103,36 @@ namespace SHADE groupSizeX = maxWidth / workGroupSizeX; groupSizeY = maxHeight / workGroupSizeY; + + for (uint32_t i = 0; auto& barriers : memoryBarriers) + { + barriers.clear(); + + for (auto& resource : resources) + { + vk::AccessFlags srcAccessMask = (barriers.empty()) ? vk::AccessFlagBits::eInputAttachmentRead : (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite); + barriers.push_back(vk::ImageMemoryBarrier + { + .srcAccessMask = srcAccessMask, + .dstAccessMask = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite, + .oldLayout = vk::ImageLayout::eGeneral, + .newLayout = vk::ImageLayout::eGeneral, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .image = resource->GetImage((resource->resourceTypeFlags & static_cast(SH_ATT_DESC_TYPE_FLAGS::COLOR_PRESENT)) ? i : 0)->GetVkImage(), + .subresourceRange = vk::ImageSubresourceRange + { + .aspectMask = resource->imageAspectFlags, + .baseMipLevel = 0, + .levelCount = resource->mipLevels, + .baseArrayLayer = 0, + .layerCount = 1, + } + }); + } + + ++i; + } } } diff --git a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.h b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.h index ba4cf387..711fb317 100644 --- a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.h +++ b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.h @@ -44,6 +44,8 @@ namespace SHADE float numWorkGroupScale; + std::array, SHGraphicsConstants::NUM_FRAME_BUFFERS> memoryBarriers; + public: SHRenderGraphNodeCompute(Handle graphStorage, Handle computeShaderModule, std::vector>&& subpassComputeResources, float inNumWorkGroupScale = 1.0f) noexcept; From 5da7638c0a5828940753334d809b6408184a1d89 Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Sat, 29 Oct 2022 22:52:15 +0800 Subject: [PATCH 33/44] Compute barriers --- .../src/Graphics/RenderGraph/SHRenderGraphNode.cpp | 2 +- .../Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp | 10 ++++++---- .../Graphics/RenderGraph/SHRenderGraphNodeCompute.h | 5 ++++- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNode.cpp b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNode.cpp index c315bffd..b4590da4 100644 --- a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNode.cpp +++ b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNode.cpp @@ -268,7 +268,7 @@ namespace SHADE } // Create the subpass compute with the resources - auto nodeCompute = graphStorage->resourceManager->Create(graphStorage, computeShaderModule, std::move(nodeComputeResources)); + auto nodeCompute = graphStorage->resourceManager->Create(graphStorage, computeShaderModule, std::move(nodeComputeResources), nodeComputes.empty()); nodeComputes.push_back(nodeCompute); return nodeCompute; diff --git a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp index e4d2360e..5323d706 100644 --- a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp +++ b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp @@ -13,12 +13,13 @@ namespace SHADE { - SHRenderGraphNodeCompute::SHRenderGraphNodeCompute(Handle graphStorage, Handle computeShaderModule, std::vector>&& subpassComputeResources, float inNumWorkGroupScale/* = 1.0f*/) noexcept + SHRenderGraphNodeCompute::SHRenderGraphNodeCompute(Handle graphStorage, Handle computeShaderModule, std::vector>&& subpassComputeResources, bool followingEndRP, float inNumWorkGroupScale/* = 1.0f*/) noexcept : computePipeline{} , pipelineLayout{} , resources{} , groupSizeX{0} , groupSizeY{0} + , followingEndRenderpass {followingEndRP} , numWorkGroupScale {std::clamp(inNumWorkGroupScale, 0.0f, 1.0f)} { SHPipelineLayoutParams pipelineLayoutParams @@ -67,8 +68,9 @@ namespace SHADE // dispatch compute cmdBuffer->ComputeDispatch(groupSizeX, groupSizeY, 1); - // TODO: barrier - + cmdBuffer->PipelineBarrier((followingEndRenderpass) ? vk::PipelineStageFlagBits::eFragmentShader : vk::PipelineStageFlagBits::eComputeShader, + vk::PipelineStageFlagBits::eFragmentShader, + {}, {}, {}, memoryBarriers[frameIndex]); } void SHRenderGraphNodeCompute::HandleResize(void) noexcept @@ -110,7 +112,7 @@ namespace SHADE for (auto& resource : resources) { - vk::AccessFlags srcAccessMask = (barriers.empty()) ? vk::AccessFlagBits::eInputAttachmentRead : (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite); + vk::AccessFlags srcAccessMask = (followingEndRenderpass) ? vk::AccessFlagBits::eInputAttachmentRead : (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite); barriers.push_back(vk::ImageMemoryBarrier { .srcAccessMask = srcAccessMask, diff --git a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.h b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.h index 711fb317..2cd3c948 100644 --- a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.h +++ b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.h @@ -2,6 +2,7 @@ #include "Resource/SHHandle.h" #include "Graphics/MiddleEnd/Interface/SHGraphicsConstants.h" +#include "Graphics/SHVulkanIncludes.h" #include #include #include @@ -44,10 +45,12 @@ namespace SHADE float numWorkGroupScale; + bool followingEndRenderpass; + std::array, SHGraphicsConstants::NUM_FRAME_BUFFERS> memoryBarriers; public: - SHRenderGraphNodeCompute(Handle graphStorage, Handle computeShaderModule, std::vector>&& subpassComputeResources, float inNumWorkGroupScale = 1.0f) noexcept; + SHRenderGraphNodeCompute(Handle graphStorage, Handle computeShaderModule, std::vector>&& subpassComputeResources, bool followingEndRP, float inNumWorkGroupScale = 1.0f) noexcept; void Execute (Handle cmdBuffer, uint32_t frameIndex) noexcept; void HandleResize (void) noexcept; From 5db92996993420b1bb0c96ab50a41e46884303e7 Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Sun, 30 Oct 2022 00:07:02 +0800 Subject: [PATCH 34/44] Reverted back to old asset IDs --- Assets/Cube.003.shmesh.shmeta | 2 +- Assets/Cube.012.shmesh.shmeta | 2 +- Assets/RaccoonBag_Color_Ver4.shtex.shmeta | 2 +- .../RaccoonPreTexturedVer1_Base9.shtex.shmeta | 2 +- Assets/Shaders/Kirsch_CS.shshaderb | Bin 5909 -> 5909 bytes Assets/Shaders/Kirsch_CS.shshaderb.shmeta | 2 +- Assets/Shaders/PureCopy_CS.shshaderb | Bin 1273 -> 1273 bytes Assets/Shaders/PureCopy_CS.shshaderb.shmeta | 2 +- Assets/Shaders/TestCube_FS.glsl | 21 +++++++++--------- Assets/Shaders/TestCube_FS.shshaderb | Bin 2545 -> 2309 bytes Assets/Shaders/TestCube_FS.shshaderb.shmeta | 2 +- Assets/Shaders/TestCube_VS.glsl | 13 ++++------- Assets/Shaders/TestCube_VS.shshaderb | Bin 3305 -> 2501 bytes Assets/Shaders/TestCube_VS.shshaderb.shmeta | 2 +- Assets/TD_Checker_Base_Color.shtex.shmeta | 2 +- 15 files changed, 23 insertions(+), 29 deletions(-) diff --git a/Assets/Cube.003.shmesh.shmeta b/Assets/Cube.003.shmesh.shmeta index 99185bf3..628ecd00 100644 --- a/Assets/Cube.003.shmesh.shmeta +++ b/Assets/Cube.003.shmesh.shmeta @@ -1,3 +1,3 @@ Name: Cube.003 -ID: 77135977 +ID: 71245919 Type: 4 diff --git a/Assets/Cube.012.shmesh.shmeta b/Assets/Cube.012.shmesh.shmeta index b3bf270f..56d2d0f5 100644 --- a/Assets/Cube.012.shmesh.shmeta +++ b/Assets/Cube.012.shmesh.shmeta @@ -1,3 +1,3 @@ Name: Cube.012 -ID: 81876417 +ID: 80365422 Type: 4 diff --git a/Assets/RaccoonBag_Color_Ver4.shtex.shmeta b/Assets/RaccoonBag_Color_Ver4.shtex.shmeta index 70631c1e..d386e9a4 100644 --- a/Assets/RaccoonBag_Color_Ver4.shtex.shmeta +++ b/Assets/RaccoonBag_Color_Ver4.shtex.shmeta @@ -1,3 +1,3 @@ Name: RaccoonBag_Color_Ver4 -ID: 66703095 +ID: 58303057 Type: 3 diff --git a/Assets/RaccoonPreTexturedVer1_Base9.shtex.shmeta b/Assets/RaccoonPreTexturedVer1_Base9.shtex.shmeta index 61be80e0..e1a72340 100644 --- a/Assets/RaccoonPreTexturedVer1_Base9.shtex.shmeta +++ b/Assets/RaccoonPreTexturedVer1_Base9.shtex.shmeta @@ -1,3 +1,3 @@ Name: RaccoonPreTexturedVer1_Base9 -ID: 60820650 +ID: 64651793 Type: 3 diff --git a/Assets/Shaders/Kirsch_CS.shshaderb b/Assets/Shaders/Kirsch_CS.shshaderb index 6219d9a9c9a9e8ae16a498e700cba315f72f58b8..4c54946c91f269b181aa2869965af1861c3cd8c5 100644 GIT binary patch delta 10 RcmbQLH&u^OVI!l6H~a4?u=O&SG&9a-P6xm&HOuMic{M+zu%ZI%(OXVmP^PSHT#5^g8%VV z$^Z2HFY#$JWj5AdL@TeJM*}hkXPqRz8N(b$gSEY58- z-iik{i-xb?+I~L%)JGkQ#h=FcdNv#_$9b&jHnf}a^!??gCIrT8{ry$;fmiTn zc5yP=iYpi!d2JO`r=b|L;>u++7bhgNS?;KW7}z)iiqN5_qz8PF>5V$D zaqo8(gM7XsU)YoD#Vo7yV4mpoN6e1bi8-st@Hxe!9^?~}=%+0@DSy6ebiR$Y{`0eh zFZdm=vjebiw2f(T{K;26K|dwWgEHWEM)H^9=)^uG&H*DfI1*kZ;774xqn%lT;SwK z=l43~|IW+7pLa_vVuX5bdW?9tyi88?yW-57euvX=dc&EpfQ> zkC29VNB^14X%X{c?)T)$9L|WqJF1fTv_APTi(3w;uE(c443 zAEkdDZ%G(9@z~8zq7V-oyQ44mbz6jeUB1Ns*<;{=KKOoq5k`J|-h1qhWctK*U)$n4 r2ctgr{6Iu~VNUG)p$Hs*-UWK_eF(3Bt>>?qn%YN}jvCW4bLNEkZVH(*=7^0nyt+rDGIn`tpSpa<95XZZ`QBh_usp8P<<%S4 zNqy3^>l?^@${aTxNq8@DISxuXAwDa&dzthBZ&H0GHSb#$sXh}V92 z5RdIBDU-^^t`a`&Vt z_u}6sN#>q7TgpF&zxU`-Z?F*$N27RL9b`7nTyEpkmAc98Tkfj!_&Apjvq{f6(`BS#1_$VVxRdj+6ZtG0Y@a*-2(}s$I{ruZ-Nu zOsBqaZ8P5_+qP+eziZx>UD>DAq_mpY6q}d)KB+d#Vzi!ANnHyVG%T{Bl$_CvfKiJ- z-)9eG9>!Bwl8ttg2F50ATO}2Bl_QeWUAA;d#)WFtQ3?IygHnnR(a)l!uT6H_yo*Cb zJwe~|`9eX=4PQ%aU3wTxeVN?~EvM1sWdHj4it=~sJuD{GMqat7YkmIx393_sZE21b8i z`g9NDxECxElm8vb88II!xgtr37^tU8BT3E?Pi=71UXTqD%j{0pdZ*T3^x8Jd!v9n; z#BpEHKRwht^}IRL5_2E_0oe3%R=>yvo#%e^^U|n45?@d}{}b5EGt%#@B(dPPz0Dhe z5kDtMJh|r8Ki?d&;7D>Dm!uwi&jq$hCv zJ+=cN9q-uZzL&>ID0V9pcYPC!QS%@#m$36VEPT z6VI&P7c;+*pSgVC@ipDXygm{yiiyF;JjqS$$71|j-d^??`I#->E;|Iy8RpD43{DL5 z{!C2GAuqFE_4rSUq30W7&Vh&8Z%Ti)_RocZQ#)_>g*eoXFZ4;yFTFqHyDj_Gd|wFz zCm(NrR~+);3v*^4?s@;FV#$BsW8i`R@cpa_!v68{f*b=Xk= diff --git a/Assets/Shaders/TestCube_FS.shshaderb.shmeta b/Assets/Shaders/TestCube_FS.shshaderb.shmeta index 0e7e4bda..42f270af 100644 --- a/Assets/Shaders/TestCube_FS.shshaderb.shmeta +++ b/Assets/Shaders/TestCube_FS.shshaderb.shmeta @@ -1,3 +1,3 @@ Name: TestCube_FS -ID: 47024851 +ID: 37450402 Type: 2 diff --git a/Assets/Shaders/TestCube_VS.glsl b/Assets/Shaders/TestCube_VS.glsl index 49f107dd..7b58d1cf 100644 --- a/Assets/Shaders/TestCube_VS.glsl +++ b/Assets/Shaders/TestCube_VS.glsl @@ -14,14 +14,13 @@ layout(location = 8) in uvec2 integerData; layout(location = 0) out struct { - vec4 vertPos; // location 0 + vec4 vertColor; // location 0 vec2 uv; // location = 1 - vec4 normal; // location = 2 } Out; // material stuff -layout(location = 3) out struct +layout(location = 2) out struct { int materialIndex; uint eid; @@ -37,14 +36,10 @@ layout(set = 2, binding = 0) uniform CameraData void main() { - + Out.uv = aUV; Out2.materialIndex = gl_InstanceIndex; Out2.eid = integerData[0]; Out2.lightLayerIndex = integerData[1]; - - Out.vertPos = worldTransform * vec4(aVertexPos, 1.0f); - Out.uv = aUV; - Out.normal.rgb = mat3(transpose(inverse(worldTransform))) * aNormal.rgb; - Out.normal.rgb = normalize (Out.normal.rgb); gl_Position = cameraData.vpMat * worldTransform * vec4 (aVertexPos, 1.0f); + Out.vertColor = vec4 (aVertexPos, 1.0f); } \ No newline at end of file diff --git a/Assets/Shaders/TestCube_VS.shshaderb b/Assets/Shaders/TestCube_VS.shshaderb index 03e23af37451b6c4c0791110541c7b6e31d07bbe..e070a9a6e4478efc121bc03a322dd966e0b786cd 100644 GIT binary patch literal 2501 zcmZ9M+foxj5QYZ`LB$iIf{GYGMFsJEL_q}&XaFsc+tgID;#Mu2)MmlMm9L=B`rQnNp(&C-GBG=O!ube_hI8!U+>g_F+JvpIcC-~lNmC-vKTXH%5JaLHfwX8 zv^jVG!EGqVO`l`JIiVk`B-yoLj6NvAdRB5ya!E2Lc_euzsY%u(efsrk|D!}DRZy+f zs~a2D+Ut6w-L7}iZ&6T>!Z@fm!z5^=;eG(`P=Oc5jcBh~B=n0>tfgOPg%3Xaw zNYbTN)Jk-ISrKr!&)&W<#Bhg=z0~R4#eUp&`f2H`vKcU5-?eFwgf?1@o55G-D>)ze zg0R`;a@Q!_`JC45w;;*b)XO{Rth?HD#(;aXov6MVcTyWS0-sjCe)pDPoCZ5VvTRc; zOWDjSPW<;lvaMUW5@gNnf9N^AL?fJa=SvzO<64 zxs}+s^Qo2WW?bgUX4lpov6b9>*>zED)LCg`RDh~Y}2WWxmF_>Dw^aRXX zfSF@rW^&9-<3A)>(J8ze3l7WM$cK&H+sKKHxAZo2Y|L&|9^VK2{_UpZW37mVjhy`s zXB;q`lLu`2z@3e}#Q8h%&XWi5gfNRc^XA+!tEuF^T`&uOO?&Z;cxNzo8P+MBGa&>< zKP#=Qy&@S=JavJ|59TewaL0xDCgEVO2p`c-F6{F;_V0K`_^9J$?=q9)W3urs#2?Rf z@(~ZF@7_Noo&5O8H>|xPVU6ph`QAALd*&;Nm&M>CCz#nGkFQ}wI*S@cwR0YM;Debh zU&96I#Ny{oE^6m2-h_DG7cO?jarBzrGKXO7#NW|Q4cLhXGoSw6_j29y z9|}_=7(SSJ#m2im)lS`sgkM2w8 z8)uM%{ydOi_xQ1Ndi6^&_@7ANV24AGo=fP@2XW}lVs6vcwY|t~^uY68<~I8AUfrXA zuO!63kl?4!Kb05Xl7#c&a0mMSTEgu5w+6%WwY`yEtgR}HjpgfDk&dlc+iGqr*7jC5 Y;^E_`Hebg(>CA|)0}TJ4vObpl2LeRA7XSbN literal 3305 zcmZ9O`*svX5XL*%OOODH$VJ7to1mi6cmqU{OUz{xS+a`>@y^=p4$J85Y|iW?f`9o6 z`ba*BkKsR@4h2Rrrc3?+>LX{opjSeoSSv^ zY;U!<+e?#luypD2M^H|`ccVo$t#k#Bo`&`OFomVOYTb`R`fTm z{U0T&Dyr4)wK|^n)NtyW@$lYKBqE{=qX2wZ!9O z)dI%avqGfPM{sI6*t_FX?ZkWS{Zc#_v*&kwJPcxJu2sC} zoOEi!<~?U6i-pZB<7Y70jc=e;hS{1$&+Ix%O&Y-mTQrCI2_GxmI86HC7qw8H_pc@zF6X~Z@q*jKc} zrDo!>`Ch>Af36)qe(JrUowLB~ymjfu-zGbHl;(yfM$aH#^|F$&?3}5cA zx}T+U2Hz&qGs}0%+%xMp6oCx~KQnh$!dxk$};B(h^CCm>t@AiR&`M9eZ8rnaUfUykYKN?{4#;}hI zj6QXBo2GXD0VWkl>@ zyW2JC-0hfNh`W9%p=NU7+bMc*T{=GQLTxuCV62XQ$>_^12{^(c4|lbgW$DC#Tg+F| z!4Vd|a?FZsV!$kBRXRArvY4*!z_+y~xg{YtTzj{c^mPgSrQQt*T<~SZ^4)zcpW0a;_gT%jv9%B2WD{{=@z#o-Qv2^iR0eH!2`27xGUY_ zxL;HDHxh8`({_P@v#d|NHTT~sur=*)t)_d@EqA#GyTXZKQ4>5ci~Cl(#g%*Top3vg zICx+d_kAg@+=CyAIO_pCFnaJndtc%u%(l(*puo)zWM7p0tr+I}p#%=N&Bai9`FnmO z8;oV|5lRQ6hlc%HVAN;d^Ka6LhmXJfJx8)RACA4_NIJjCvl4oP4ezN=x+?h}iWKt; diff --git a/Assets/Shaders/TestCube_VS.shshaderb.shmeta b/Assets/Shaders/TestCube_VS.shshaderb.shmeta index ad3a1725..b133437b 100644 --- a/Assets/Shaders/TestCube_VS.shshaderb.shmeta +++ b/Assets/Shaders/TestCube_VS.shshaderb.shmeta @@ -1,3 +1,3 @@ Name: TestCube_VS -ID: 40523220 +ID: 41688429 Type: 2 diff --git a/Assets/TD_Checker_Base_Color.shtex.shmeta b/Assets/TD_Checker_Base_Color.shtex.shmeta index c25ba444..8c0d5b77 100644 --- a/Assets/TD_Checker_Base_Color.shtex.shmeta +++ b/Assets/TD_Checker_Base_Color.shtex.shmeta @@ -1,3 +1,3 @@ Name: TD_Checker_Base_Color -ID: 55706287 +ID: 51995224 Type: 3 From b46b6b0b85fd959e8cd3797c6f6a0415a0b7e0ec Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Sun, 30 Oct 2022 00:25:49 +0800 Subject: [PATCH 35/44] CompileAll uncommented and asset manager metadata writes commented SHmeta files should now be identical to what's on main Shaders themselves have some changes (binaries also updated) --- Assets/Shaders/Kirsch_CS.shshaderb | Bin 5909 -> 5909 bytes Assets/Shaders/PureCopy_CS.shshaderb | Bin 1273 -> 1273 bytes Assets/Shaders/TestCube_FS.glsl | 21 +++++++++++---------- Assets/Shaders/TestCube_FS.shshaderb | Bin 2309 -> 2545 bytes Assets/Shaders/TestCube_VS.glsl | 13 +++++++++---- Assets/Shaders/TestCube_VS.shshaderb | Bin 2501 -> 3305 bytes SHADE_Engine/src/Assets/SHAssetManager.cpp | 6 +++--- 7 files changed, 23 insertions(+), 17 deletions(-) diff --git a/Assets/Shaders/Kirsch_CS.shshaderb b/Assets/Shaders/Kirsch_CS.shshaderb index 4c54946c91f269b181aa2869965af1861c3cd8c5..6219d9a9c9a9e8ae16a498e700cba315f72f58b8 100644 GIT binary patch delta 10 RcmbQLH&u_3X(OYEH~F(3Bt>>?qn%YN}jvCW4bLNEkZVH(*=7^0nyt+rDGIn`tpSpa<95XZZ`QBh_usp8P<<%S4 zNqy3^>l?^@${aTxNq8@DISxuXAwDa&dzthBZ&H0GHSb#$sXh}V92 z5RdIBDU-^^t`a`&Vt z_u}6sN#>q7TgpF&zxU`-Z?F*$N27RL9b`7nTyEpkmAc98Tkfj!_&Apjvq{f6(`BS#1_$VVxRdj+6ZtG0Y@a*-2(}s$I{ruZ-Nu zOsBqaZ8P5_+qP+eziZx>UD>DAq_mpY6q}d)KB+d#Vzi!ANnHyVG%T{Bl$_CvfKiJ- z-)9eG9>!Bwl8ttg2F50ATO}2Bl_QeWUAA;d#)WFtQ3?IygHnnR(a)l!uT6H_yo*Cb zJwe~|`9eX=4PQ%aU3wTxeVN?~EvM1sWdHj4it=~sJuD{GMqat7YkmIx393_sZE21b8i z`g9NDxECxElm8vb88II!xgtr37^tU8BT3E?Pi=71UXTqD%j{0pdZ*T3^x8Jd!v9n; z#BpEHKRwht^}IRL5_2E_0oe3%R=>yvo#%e^^U|n45?@d}{}b5EGt%#@B(dPPz0Dhe z5kDtMJh|r8Ki?d&;7D>Dm!uwi&jq$hCv zJ+=cN9q-uZzL&>ID0V9pcYPC!QS%@#m$36VEPT z6VI&P7c;+*pSgVC@ipDXygm{yiiyF;JjqS$$71|j-d^??`I#->E;|Iy8RpD43{DL5 z{!C2GAuqFE_4rSUq30W7&Vh&8Z%Ti)_RocZQ#)_>g*eoXFZ4;yFTFqHyDj_Gd|wFz zCm(NrR~+);3v*^4?s@;FV#$BsW8i`R@cpa_!v68{f*b=Xk= literal 2309 zcmZ9MOLG%P5XUFzfiVFL4v+*8GUge;A&wy=JOy?MSBbIa4?u=O&SG&9a-P6xm&HOuMic{M+zu%ZI%(OXVmP^PSHT#5^g8%VV z$^Z2HFY#$JWj5AdL@TeJM*}hkXPqRz8N(b$gSEY58- z-iik{i-xb?+I~L%)JGkQ#h=FcdNv#_$9b&jHnf}a^!??gCIrT8{ry$;fmiTn zc5yP=iYpi!d2JO`r=b|L;>u++7bhgNS?;KW7}z)iiqN5_qz8PF>5V$D zaqo8(gM7XsU)YoD#Vo7yV4mpoN6e1bi8-st@Hxe!9^?~}=%+0@DSy6ebiR$Y{`0eh zFZdm=vjebiw2f(T{K;26K|dwWgEHWEM)H^9=)^uG&H*DfI1*kZ;774xqn%lT;SwK z=l43~|IW+7pLa_vVuX5bdW?9tyi88?yW-57euvX=dc&EpfQ> zkC29VNB^14X%X{c?)T)$9L|WqJF1fTv_APTi(3w;uE(c443 zAEkdDZ%G(9@z~8zq7V-oyQ44mbz6jeUB1Ns*<;{=KKOoq5k`J|-h1qhWctK*U)$n4 r2ctgr{6Iu~VNUG)p$Hs*-UWK_e@y^=p4$J85Y|iW?f`9o6 z`ba*BkKsR@4h2Rrrc3?+>LX{opjSeoSSv^ zY;U!<+e?#luypD2M^H|`ccVo$t#k#Bo`&`OFomVOYTb`R`fTm z{U0T&Dyr4)wK|^n)NtyW@$lYKBqE{=qX2wZ!9O z)dI%avqGfPM{sI6*t_FX?ZkWS{Zc#_v*&kwJPcxJu2sC} zoOEi!<~?U6i-pZB<7Y70jc=e;hS{1$&+Ix%O&Y-mTQrCI2_GxmI86HC7qw8H_pc@zF6X~Z@q*jKc} zrDo!>`Ch>Af36)qe(JrUowLB~ymjfu-zGbHl;(yfM$aH#^|F$&?3}5cA zx}T+U2Hz&qGs}0%+%xMp6oCx~KQnh$!dxk$};B(h^CCm>t@AiR&`M9eZ8rnaUfUykYKN?{4#;}hI zj6QXBo2GXD0VWkl>@ zyW2JC-0hfNh`W9%p=NU7+bMc*T{=GQLTxuCV62XQ$>_^12{^(c4|lbgW$DC#Tg+F| z!4Vd|a?FZsV!$kBRXRArvY4*!z_+y~xg{YtTzj{c^mPgSrQQt*T<~SZ^4)zcpW0a;_gT%jv9%B2WD{{=@z#o-Qv2^iR0eH!2`27xGUY_ zxL;HDHxh8`({_P@v#d|NHTT~sur=*)t)_d@EqA#GyTXZKQ4>5ci~Cl(#g%*Top3vg zICx+d_kAg@+=CyAIO_pCFnaJndtc%u%(l(*puo)zWM7p0tr+I}p#%=N&Bai9`FnmO z8;oV|5lRQ6hlc%HVAN;d^Ka6LhmXJfJx8)RACA4_NIJjCvl4oP4ezN=x+?h}iWKt; literal 2501 zcmZ9M+foxj5QYZ`LB$iIf{GYGMFsJEL_q}&XaFsc+tgID;#Mu2)MmlMm9L=B`rQnNp(&C-GBG=O!ube_hI8!U+>g_F+JvpIcC-~lNmC-vKTXH%5JaLHfwX8 zv^jVG!EGqVO`l`JIiVk`B-yoLj6NvAdRB5ya!E2Lc_euzsY%u(efsrk|D!}DRZy+f zs~a2D+Ut6w-L7}iZ&6T>!Z@fm!z5^=;eG(`P=Oc5jcBh~B=n0>tfgOPg%3Xaw zNYbTN)Jk-ISrKr!&)&W<#Bhg=z0~R4#eUp&`f2H`vKcU5-?eFwgf?1@o55G-D>)ze zg0R`;a@Q!_`JC45w;;*b)XO{Rth?HD#(;aXov6MVcTyWS0-sjCe)pDPoCZ5VvTRc; zOWDjSPW<;lvaMUW5@gNnf9N^AL?fJa=SvzO<64 zxs}+s^Qo2WW?bgUX4lpov6b9>*>zED)LCg`RDh~Y}2WWxmF_>Dw^aRXX zfSF@rW^&9-<3A)>(J8ze3l7WM$cK&H+sKKHxAZo2Y|L&|9^VK2{_UpZW37mVjhy`s zXB;q`lLu`2z@3e}#Q8h%&XWi5gfNRc^XA+!tEuF^T`&uOO?&Z;cxNzo8P+MBGa&>< zKP#=Qy&@S=JavJ|59TewaL0xDCgEVO2p`c-F6{F;_V0K`_^9J$?=q9)W3urs#2?Rf z@(~ZF@7_Noo&5O8H>|xPVU6ph`QAALd*&;Nm&M>CCz#nGkFQ}wI*S@cwR0YM;Debh zU&96I#Ny{oE^6m2-h_DG7cO?jarBzrGKXO7#NW|Q4cLhXGoSw6_j29y z9|}_=7(SSJ#m2im)lS`sgkM2w8 z8)uM%{ydOi_xQ1Ndi6^&_@7ANV24AGo=fP@2XW}lVs6vcwY|t~^uY68<~I8AUfrXA zuO!63kl?4!Kb05Xl7#c&a0mMSTEgu5w+6%WwY`yEtgR}HjpgfDk&dlc+iGqr*7jC5 Y;^E_`Hebg(>CA|)0}TJ4vObpl2LeRA7XSbN diff --git a/SHADE_Engine/src/Assets/SHAssetManager.cpp b/SHADE_Engine/src/Assets/SHAssetManager.cpp index 228f3fdc..76b68e50 100644 --- a/SHADE_Engine/src/Assets/SHAssetManager.cpp +++ b/SHADE_Engine/src/Assets/SHAssetManager.cpp @@ -349,13 +349,13 @@ namespace SHADE meshAsset.id = GenerateAssetID(AssetType::MESH); meshAsset.type = AssetType::MESH; assetCollection.push_back(meshAsset); - SHAssetMetaHandler::WriteMetaData(meshAsset); + //SHAssetMetaHandler::WriteMetaData(meshAsset); } continue; } assetCollection.push_back(newAsset); - SHAssetMetaHandler::WriteMetaData(newAsset); + //SHAssetMetaHandler::WriteMetaData(newAsset); } } @@ -372,7 +372,7 @@ namespace SHADE ****************************************************************************/ void SHAssetManager::Load() noexcept { - //CompileAll(); + CompileAll(); InitLoaders(); BuildAssetCollection(); //LoadAllData(); From da05cb3edc82390865a783a978488178024ac86b Mon Sep 17 00:00:00 2001 From: Kah Wei Date: Sun, 30 Oct 2022 02:37:58 +0800 Subject: [PATCH 36/44] Fixed script error and added support for static functions in CallbackAction --- SHADE_CSharp/src/Events/CallbackAction.cs | 268 ++++++++++++++++++---- SHADE_CSharp/src/Events/CallbackAction.tt | 27 ++- SHADE_Managed/src/Components/Collider.hxx | 2 +- TempScriptsFolder/PhysicsTest.cs | 2 +- 4 files changed, 243 insertions(+), 56 deletions(-) diff --git a/SHADE_CSharp/src/Events/CallbackAction.cs b/SHADE_CSharp/src/Events/CallbackAction.cs index 968302ed..623e4f59 100644 --- a/SHADE_CSharp/src/Events/CallbackAction.cs +++ b/SHADE_CSharp/src/Events/CallbackAction.cs @@ -61,8 +61,25 @@ namespace SHADE /// public CallbackAction() {} /// - /// Constructs a CallbackAction that represents a call to the specified method on the - /// specified target. + /// Constructs a CallbackAction that represents a call to the specified static + /// method. + /// + /// Method to call. + /// + /// Thrown if a method that is not compatible with the target is specified. The method's + /// source type must match the target's type. + /// + public CallbackAction(MethodInfo method) + { + // No errors, assign + targetMethod = method; + + // Create storage for parameters for calling + parameters = new Object[1]; + } + /// + /// Constructs a CallbackAction that represents a call to a specified member + /// method on the specified target. /// /// Object to call the method on. /// Method to call. @@ -86,7 +103,7 @@ namespace SHADE /// /// Constructs a Callback action based on an action. /// - /// + /// Action that wraps a function to be called. public CallbackAction(Action action) { targetAction = action; @@ -103,7 +120,7 @@ namespace SHADE { targetAction.Invoke(t1); } - else if (TargetObject != null && targetMethod != null) + else if (targetMethod != null) { parameters[0] = t1; _ = targetMethod.Invoke(TargetObject, parameters); @@ -138,8 +155,25 @@ namespace SHADE /// public CallbackAction() {} /// - /// Constructs a CallbackAction that represents a call to the specified method on the - /// specified target. + /// Constructs a CallbackAction that represents a call to the specified static + /// method. + /// + /// Method to call. + /// + /// Thrown if a method that is not compatible with the target is specified. The method's + /// source type must match the target's type. + /// + public CallbackAction(MethodInfo method) + { + // No errors, assign + targetMethod = method; + + // Create storage for parameters for calling + parameters = new Object[2]; + } + /// + /// Constructs a CallbackAction that represents a call to a specified member + /// method on the specified target. /// /// Object to call the method on. /// Method to call. @@ -158,12 +192,12 @@ namespace SHADE targetMethod = method; // Create storage for parameters for calling - parameters = new Object[1]; + parameters = new Object[2]; } /// /// Constructs a Callback action based on an action. /// - /// + /// Action that wraps a function to be called. public CallbackAction(Action action) { targetAction = action; @@ -180,7 +214,7 @@ namespace SHADE { targetAction.Invoke(t1, t2); } - else if (TargetObject != null && targetMethod != null) + else if (targetMethod != null) { parameters[0] = t1; parameters[1] = t2; @@ -216,8 +250,25 @@ namespace SHADE /// public CallbackAction() {} /// - /// Constructs a CallbackAction that represents a call to the specified method on the - /// specified target. + /// Constructs a CallbackAction that represents a call to the specified static + /// method. + /// + /// Method to call. + /// + /// Thrown if a method that is not compatible with the target is specified. The method's + /// source type must match the target's type. + /// + public CallbackAction(MethodInfo method) + { + // No errors, assign + targetMethod = method; + + // Create storage for parameters for calling + parameters = new Object[3]; + } + /// + /// Constructs a CallbackAction that represents a call to a specified member + /// method on the specified target. /// /// Object to call the method on. /// Method to call. @@ -236,12 +287,12 @@ namespace SHADE targetMethod = method; // Create storage for parameters for calling - parameters = new Object[1]; + parameters = new Object[3]; } /// /// Constructs a Callback action based on an action. /// - /// + /// Action that wraps a function to be called. public CallbackAction(Action action) { targetAction = action; @@ -258,7 +309,7 @@ namespace SHADE { targetAction.Invoke(t1, t2, t3); } - else if (TargetObject != null && targetMethod != null) + else if (targetMethod != null) { parameters[0] = t1; parameters[1] = t2; @@ -295,8 +346,25 @@ namespace SHADE /// public CallbackAction() {} /// - /// Constructs a CallbackAction that represents a call to the specified method on the - /// specified target. + /// Constructs a CallbackAction that represents a call to the specified static + /// method. + /// + /// Method to call. + /// + /// Thrown if a method that is not compatible with the target is specified. The method's + /// source type must match the target's type. + /// + public CallbackAction(MethodInfo method) + { + // No errors, assign + targetMethod = method; + + // Create storage for parameters for calling + parameters = new Object[4]; + } + /// + /// Constructs a CallbackAction that represents a call to a specified member + /// method on the specified target. /// /// Object to call the method on. /// Method to call. @@ -315,12 +383,12 @@ namespace SHADE targetMethod = method; // Create storage for parameters for calling - parameters = new Object[1]; + parameters = new Object[4]; } /// /// Constructs a Callback action based on an action. /// - /// + /// Action that wraps a function to be called. public CallbackAction(Action action) { targetAction = action; @@ -337,7 +405,7 @@ namespace SHADE { targetAction.Invoke(t1, t2, t3, t4); } - else if (TargetObject != null && targetMethod != null) + else if (targetMethod != null) { parameters[0] = t1; parameters[1] = t2; @@ -375,8 +443,25 @@ namespace SHADE /// public CallbackAction() {} /// - /// Constructs a CallbackAction that represents a call to the specified method on the - /// specified target. + /// Constructs a CallbackAction that represents a call to the specified static + /// method. + /// + /// Method to call. + /// + /// Thrown if a method that is not compatible with the target is specified. The method's + /// source type must match the target's type. + /// + public CallbackAction(MethodInfo method) + { + // No errors, assign + targetMethod = method; + + // Create storage for parameters for calling + parameters = new Object[5]; + } + /// + /// Constructs a CallbackAction that represents a call to a specified member + /// method on the specified target. /// /// Object to call the method on. /// Method to call. @@ -395,12 +480,12 @@ namespace SHADE targetMethod = method; // Create storage for parameters for calling - parameters = new Object[1]; + parameters = new Object[5]; } /// /// Constructs a Callback action based on an action. /// - /// + /// Action that wraps a function to be called. public CallbackAction(Action action) { targetAction = action; @@ -417,7 +502,7 @@ namespace SHADE { targetAction.Invoke(t1, t2, t3, t4, t5); } - else if (TargetObject != null && targetMethod != null) + else if (targetMethod != null) { parameters[0] = t1; parameters[1] = t2; @@ -456,8 +541,25 @@ namespace SHADE /// public CallbackAction() {} /// - /// Constructs a CallbackAction that represents a call to the specified method on the - /// specified target. + /// Constructs a CallbackAction that represents a call to the specified static + /// method. + /// + /// Method to call. + /// + /// Thrown if a method that is not compatible with the target is specified. The method's + /// source type must match the target's type. + /// + public CallbackAction(MethodInfo method) + { + // No errors, assign + targetMethod = method; + + // Create storage for parameters for calling + parameters = new Object[6]; + } + /// + /// Constructs a CallbackAction that represents a call to a specified member + /// method on the specified target. /// /// Object to call the method on. /// Method to call. @@ -476,12 +578,12 @@ namespace SHADE targetMethod = method; // Create storage for parameters for calling - parameters = new Object[1]; + parameters = new Object[6]; } /// /// Constructs a Callback action based on an action. /// - /// + /// Action that wraps a function to be called. public CallbackAction(Action action) { targetAction = action; @@ -498,7 +600,7 @@ namespace SHADE { targetAction.Invoke(t1, t2, t3, t4, t5, t6); } - else if (TargetObject != null && targetMethod != null) + else if (targetMethod != null) { parameters[0] = t1; parameters[1] = t2; @@ -538,8 +640,25 @@ namespace SHADE /// public CallbackAction() {} /// - /// Constructs a CallbackAction that represents a call to the specified method on the - /// specified target. + /// Constructs a CallbackAction that represents a call to the specified static + /// method. + /// + /// Method to call. + /// + /// Thrown if a method that is not compatible with the target is specified. The method's + /// source type must match the target's type. + /// + public CallbackAction(MethodInfo method) + { + // No errors, assign + targetMethod = method; + + // Create storage for parameters for calling + parameters = new Object[7]; + } + /// + /// Constructs a CallbackAction that represents a call to a specified member + /// method on the specified target. /// /// Object to call the method on. /// Method to call. @@ -558,12 +677,12 @@ namespace SHADE targetMethod = method; // Create storage for parameters for calling - parameters = new Object[1]; + parameters = new Object[7]; } /// /// Constructs a Callback action based on an action. /// - /// + /// Action that wraps a function to be called. public CallbackAction(Action action) { targetAction = action; @@ -580,7 +699,7 @@ namespace SHADE { targetAction.Invoke(t1, t2, t3, t4, t5, t6, t7); } - else if (TargetObject != null && targetMethod != null) + else if (targetMethod != null) { parameters[0] = t1; parameters[1] = t2; @@ -621,8 +740,25 @@ namespace SHADE /// public CallbackAction() {} /// - /// Constructs a CallbackAction that represents a call to the specified method on the - /// specified target. + /// Constructs a CallbackAction that represents a call to the specified static + /// method. + /// + /// Method to call. + /// + /// Thrown if a method that is not compatible with the target is specified. The method's + /// source type must match the target's type. + /// + public CallbackAction(MethodInfo method) + { + // No errors, assign + targetMethod = method; + + // Create storage for parameters for calling + parameters = new Object[8]; + } + /// + /// Constructs a CallbackAction that represents a call to a specified member + /// method on the specified target. /// /// Object to call the method on. /// Method to call. @@ -641,12 +777,12 @@ namespace SHADE targetMethod = method; // Create storage for parameters for calling - parameters = new Object[1]; + parameters = new Object[8]; } /// /// Constructs a Callback action based on an action. /// - /// + /// Action that wraps a function to be called. public CallbackAction(Action action) { targetAction = action; @@ -663,7 +799,7 @@ namespace SHADE { targetAction.Invoke(t1, t2, t3, t4, t5, t6, t7, t8); } - else if (TargetObject != null && targetMethod != null) + else if (targetMethod != null) { parameters[0] = t1; parameters[1] = t2; @@ -705,8 +841,25 @@ namespace SHADE /// public CallbackAction() {} /// - /// Constructs a CallbackAction that represents a call to the specified method on the - /// specified target. + /// Constructs a CallbackAction that represents a call to the specified static + /// method. + /// + /// Method to call. + /// + /// Thrown if a method that is not compatible with the target is specified. The method's + /// source type must match the target's type. + /// + public CallbackAction(MethodInfo method) + { + // No errors, assign + targetMethod = method; + + // Create storage for parameters for calling + parameters = new Object[9]; + } + /// + /// Constructs a CallbackAction that represents a call to a specified member + /// method on the specified target. /// /// Object to call the method on. /// Method to call. @@ -725,12 +878,12 @@ namespace SHADE targetMethod = method; // Create storage for parameters for calling - parameters = new Object[1]; + parameters = new Object[9]; } /// /// Constructs a Callback action based on an action. /// - /// + /// Action that wraps a function to be called. public CallbackAction(Action action) { targetAction = action; @@ -747,7 +900,7 @@ namespace SHADE { targetAction.Invoke(t1, t2, t3, t4, t5, t6, t7, t8, t9); } - else if (TargetObject != null && targetMethod != null) + else if (targetMethod != null) { parameters[0] = t1; parameters[1] = t2; @@ -790,8 +943,25 @@ namespace SHADE /// public CallbackAction() {} /// - /// Constructs a CallbackAction that represents a call to the specified method on the - /// specified target. + /// Constructs a CallbackAction that represents a call to the specified static + /// method. + /// + /// Method to call. + /// + /// Thrown if a method that is not compatible with the target is specified. The method's + /// source type must match the target's type. + /// + public CallbackAction(MethodInfo method) + { + // No errors, assign + targetMethod = method; + + // Create storage for parameters for calling + parameters = new Object[10]; + } + /// + /// Constructs a CallbackAction that represents a call to a specified member + /// method on the specified target. /// /// Object to call the method on. /// Method to call. @@ -810,12 +980,12 @@ namespace SHADE targetMethod = method; // Create storage for parameters for calling - parameters = new Object[1]; + parameters = new Object[10]; } /// /// Constructs a Callback action based on an action. /// - /// + /// Action that wraps a function to be called. public CallbackAction(Action action) { targetAction = action; @@ -832,7 +1002,7 @@ namespace SHADE { targetAction.Invoke(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10); } - else if (TargetObject != null && targetMethod != null) + else if (targetMethod != null) { parameters[0] = t1; parameters[1] = t2; diff --git a/SHADE_CSharp/src/Events/CallbackAction.tt b/SHADE_CSharp/src/Events/CallbackAction.tt index fffd4251..34789b67 100644 --- a/SHADE_CSharp/src/Events/CallbackAction.tt +++ b/SHADE_CSharp/src/Events/CallbackAction.tt @@ -78,8 +78,25 @@ namespace SHADE /// public CallbackAction() {} /// - /// Constructs a CallbackAction that represents a call to the specified method on the - /// specified target. + /// Constructs a CallbackAction that represents a call to the specified static + /// method. + /// + /// Method to call. + /// + /// Thrown if a method that is not compatible with the target is specified. The method's + /// source type must match the target's type. + /// + public CallbackAction(MethodInfo method) + { + // No errors, assign + targetMethod = method; + + // Create storage for parameters for calling + parameters = new Object[<#=i#>]; + } + /// + /// Constructs a CallbackAction that represents a call to a specified member + /// method on the specified target. /// /// Object to call the method on. /// Method to call. @@ -98,12 +115,12 @@ namespace SHADE targetMethod = method; // Create storage for parameters for calling - parameters = new Object[1]; + parameters = new Object[<#=i#>]; } /// /// Constructs a Callback action based on an action. /// - /// + /// Action that wraps a function to be called. public CallbackAction(Action<<# for (int t = 1; t < i + 1; ++t) { #>T<#=t#><# if (t != i) { #>, <# } #><# } #>> action) { targetAction = action; @@ -120,7 +137,7 @@ namespace SHADE { targetAction.Invoke(<# for (int t = 1; t < i + 1; ++t) { #>t<#=t#><# if (t != i) { #>, <# } #><# } #>); } - else if (TargetObject != null && targetMethod != null) + else if (targetMethod != null) { <# for (int t = 0; t < i; ++t) {#>parameters[<#=t#>] = t<#=t+1#>; <# } #>_ = targetMethod.Invoke(TargetObject, parameters); diff --git a/SHADE_Managed/src/Components/Collider.hxx b/SHADE_Managed/src/Components/Collider.hxx index 1d1196f5..dc17ae7f 100644 --- a/SHADE_Managed/src/Components/Collider.hxx +++ b/SHADE_Managed/src/Components/Collider.hxx @@ -194,7 +194,7 @@ namespace SHADE /* Properties */ /*-----------------------------------------------------------------------------*/ /// - /// Total number of ColliderBounds in the Collider component. + /// Total number of ColliderShapes in the Collider component. /// property int CollisionShapeCount { diff --git a/TempScriptsFolder/PhysicsTest.cs b/TempScriptsFolder/PhysicsTest.cs index 6f9774c9..add5971d 100644 --- a/TempScriptsFolder/PhysicsTest.cs +++ b/TempScriptsFolder/PhysicsTest.cs @@ -28,7 +28,7 @@ public class PhysicsTest : Script Debug.LogError("Collider is NULL!"); } - var subColider = Collider.ColliderBoundsCount; + var subColider = Collider.CollisionShapeCount; Debug.Log($"There are {subColider} colliders."); } protected override void update() From 00d4d5d91053c2a1c87e1ba4697095658e3fdad8 Mon Sep 17 00:00:00 2001 From: Xiao Qi Date: Sun, 30 Oct 2022 03:06:18 +0800 Subject: [PATCH 37/44] Removed code that accidentally calls delete on freed memory for asset loaders --- SHADE_Engine/src/Assets/SHAssetManager.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/SHADE_Engine/src/Assets/SHAssetManager.cpp b/SHADE_Engine/src/Assets/SHAssetManager.cpp index 96ea7d1a..9890d047 100644 --- a/SHADE_Engine/src/Assets/SHAssetManager.cpp +++ b/SHADE_Engine/src/Assets/SHAssetManager.cpp @@ -64,10 +64,10 @@ namespace SHADE void SHAssetManager::Exit() noexcept { - for (auto const& loader : loaders) - { - delete loader; - } + delete loaders[static_cast(AssetType::SHADER)]; + delete loaders[static_cast(AssetType::TEXTURE)]; + delete loaders[static_cast(AssetType::MESH)]; + delete loaders[static_cast(AssetType::SCENE)]; for (auto const& data : std::ranges::views::values(assetData)) { From 2ebcd3fd4704f726ca279835dd035a253feffa4a Mon Sep 17 00:00:00 2001 From: Xiao Qi Date: Sun, 30 Oct 2022 04:39:16 +0800 Subject: [PATCH 38/44] Filesystem builds directory tree of asset folder to show all files and subfolders --- SHADE_Engine/src/Assets/SHAsset.h | 1 - SHADE_Engine/src/Assets/SHAssetMacros.h | 4 +- SHADE_Engine/src/Assets/SHAssetManager.cpp | 26 +++--- SHADE_Engine/src/Assets/SHAssetManager.h | 8 +- SHADE_Engine/src/Filesystem/SHFileSystem.cpp | 93 +++++++++++--------- SHADE_Engine/src/Filesystem/SHFileSystem.h | 7 +- SHADE_Engine/src/Filesystem/SHFolder.cpp | 38 ++++++++ SHADE_Engine/src/Filesystem/SHFolder.h | 10 +-- 8 files changed, 113 insertions(+), 74 deletions(-) create mode 100644 SHADE_Engine/src/Filesystem/SHFolder.cpp diff --git a/SHADE_Engine/src/Assets/SHAsset.h b/SHADE_Engine/src/Assets/SHAsset.h index e8a0d629..a4e9847c 100644 --- a/SHADE_Engine/src/Assets/SHAsset.h +++ b/SHADE_Engine/src/Assets/SHAsset.h @@ -11,7 +11,6 @@ *****************************************************************************/ #pragma once -#include "Filesystem/SHFileSystem.h" #include "Assets/SHAssetMacros.h" #include "SH_API.h" diff --git a/SHADE_Engine/src/Assets/SHAssetMacros.h b/SHADE_Engine/src/Assets/SHAssetMacros.h index 4489e807..a21a9840 100644 --- a/SHADE_Engine/src/Assets/SHAssetMacros.h +++ b/SHADE_Engine/src/Assets/SHAssetMacros.h @@ -56,9 +56,11 @@ constexpr size_t TYPE_COUNT{ static_cast(AssetType::MAX_COUNT) }; //Directory #ifdef _PUBLISH -constexpr std::string_view ASSET_ROOT {"Assets"}; +constexpr std::string_view ASSET_ROOT{ "Assets" }; +constexpr std::string_view BUILT_IN_ASSET_ROOT {"Built_In"}; #else constexpr std::string_view ASSET_ROOT {"../../Assets"}; +constexpr std::string_view BUILT_IN_ASSET_ROOT{ "../../Built_In" }; #endif // INTERNAL ASSET PATHS diff --git a/SHADE_Engine/src/Assets/SHAssetManager.cpp b/SHADE_Engine/src/Assets/SHAssetManager.cpp index 9890d047..658c80b0 100644 --- a/SHADE_Engine/src/Assets/SHAssetManager.cpp +++ b/SHADE_Engine/src/Assets/SHAssetManager.cpp @@ -23,8 +23,12 @@ #include "Libraries/Compilers/SHTextureCompiler.h" #include "Libraries/Compilers/SHShaderSourceCompiler.h" +#include "Filesystem/SHFileSystem.h" + namespace SHADE { + FolderPointer SHAssetManager::folderRoot{ nullptr }; + FMOD::System* SHAssetManager::audioSystem; std::unordered_map* SHAssetManager::audioSoundList; @@ -318,7 +322,7 @@ namespace SHADE return result; } - AssetID SHAssetManager::CompileAsset(AssetPath path) noexcept + AssetID SHAssetManager::CompileAsset(AssetPath const& path) noexcept { SHAsset newAsset { @@ -450,8 +454,8 @@ namespace SHADE void SHAssetManager::Load() noexcept { //CompileAll(); + BuildAssetCollection(); InitLoaders(); - BuildAssetCollection(); //LoadAllData(); } @@ -483,18 +487,8 @@ namespace SHADE return data; } - void SHAssetManager::BuildAssetCollection() noexcept - { - for (auto const& dir : std::filesystem::recursive_directory_iterator{ASSET_ROOT}) - { - if (dir.is_regular_file()) - { - if (dir.path().extension().string() == META_EXTENSION.data()) - { - auto asset = SHAssetMetaHandler::RetrieveMetaData(dir.path()); - assetCollection.insert({ asset.id, asset }); - } - } - } - } + void SHAssetManager::BuildAssetCollection() noexcept + { + SHFileSystem::BuildDirectory(ASSET_ROOT.data(), folderRoot, assetCollection); + } } diff --git a/SHADE_Engine/src/Assets/SHAssetManager.h b/SHADE_Engine/src/Assets/SHAssetManager.h index 22e92c7d..fea20332 100644 --- a/SHADE_Engine/src/Assets/SHAssetManager.h +++ b/SHADE_Engine/src/Assets/SHAssetManager.h @@ -10,10 +10,12 @@ ******************************************************************************/ #pragma once #include "tinyddsloader.h" + #include "SHAsset.h" #include "Asset Types/SHAssetData.h" #include "Assets/Libraries/Loaders/SHAssetLoader.h" -#include "Filesystem/SHFileSystem.h" + +#include "Filesystem/SHFolder.h" #include "SH_API.h" @@ -85,7 +87,7 @@ namespace SHADE static std::vector GetAllDataOfType(AssetType type) noexcept; static std::vector GetAllRecordOfType(AssetType type) noexcept; - static AssetID CompileAsset(AssetPath path) noexcept; + static AssetID CompileAsset(AssetPath const& path) noexcept; private: @@ -105,6 +107,8 @@ namespace SHADE //TODO use this function to create asset data internall at all calls to generate id //static AssetID CreateAsset(AssetName name, AssetType type) noexcept; + static FolderPointer folderRoot; + static FMOD::System* audioSystem; static std::unordered_map* audioSoundList; diff --git a/SHADE_Engine/src/Filesystem/SHFileSystem.cpp b/SHADE_Engine/src/Filesystem/SHFileSystem.cpp index 8e3432ad..4c0971e6 100644 --- a/SHADE_Engine/src/Filesystem/SHFileSystem.cpp +++ b/SHADE_Engine/src/Filesystem/SHFileSystem.cpp @@ -1,32 +1,22 @@ +/*************************************************************************//** + * \file SHFileSystem.cpp + * \author Loh Xiao Qi + * \date 30 October 2022 + * \brief + * + * 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 "SHFileSystem.h" -#include "fileapi.h" #include #include +#include "Assets/SHAssetMetaHandler.h" + namespace SHADE { - SHFolder::SHFolder(FolderName name) - :name{ name }, subFolders(0), folded{ false }, path{""} - { - } - - FolderPointer SHFileSystem::CreateNewFolderHere(FolderPointer parent, FolderName name) noexcept - { - for (auto const& folder : parent->subFolders) - { - if (name == folder->name) - { - SHLOG_ERROR("Unable to create subfolder {} at {} as it already exists", name, folder->name); - return nullptr; - } - } - - auto result = new SHFolder(name); - parent->subFolders.push_back(result); - - return result; - } bool SHFileSystem::DeleteFolder(FolderPointer location) noexcept { @@ -34,40 +24,59 @@ namespace SHADE return true; } - FolderPointer SHFileSystem::BuildDirectory(FolderPath path) noexcept + void SHFileSystem::BuildDirectory(FolderPath path, FolderPointer& root, std::unordered_map& assetCollection) noexcept { std::queue folderQueue; - auto result = new SHFolder("root"); - folderQueue.push(result); + root = new SHFolder("root"); + root->path = path; + folderQueue.push(root); while (!folderQueue.empty()) { - auto folder = folderQueue.front(); + auto const folder = folderQueue.front(); folderQueue.pop(); - FolderCounter count = 0; + + std::vector assets; for (auto const& dirEntry : std::filesystem::directory_iterator(folder->path)) { + auto const& path = dirEntry.path(); if (!dirEntry.is_directory()) { - folder->files.emplace_back( - dirEntry.path().filename().string(), - dirEntry.path().string(), - dirEntry.path().extension().string() - ); - - continue; + if (path.extension().string() == META_EXTENSION) + { + //auto asset = SHAssetMetaHandler::RetrieveMetaData(path); + //assetCollection.insert({ asset.id, asset }); + assets.push_back(SHAssetMetaHandler::RetrieveMetaData(path)); + } + else + { + folder->files.emplace_back( + path.stem().string(), + path.string(), + path.extension().string(), + nullptr + ); + } + continue; } - std::string name = dirEntry.path().stem().string(); - - FolderPointer newFolder{ new SHFolder(name) }; - - folderQueue.push(newFolder); - folder->subFolders.push_back(newFolder); + auto newFolder{ folder->CreateSubFolderHere(path.stem().string()) }; + folderQueue.push(newFolder); } - } - return result; + for (auto const& asset : assets) + { + assetCollection.emplace(asset.id, asset); + for(auto& file : folder->files) + { + if (file.name == asset.name) + { + file.assetMeta = &assetCollection[asset.id]; + break; + } + } + } + } } } diff --git a/SHADE_Engine/src/Filesystem/SHFileSystem.h b/SHADE_Engine/src/Filesystem/SHFileSystem.h index b4f0b0a7..956d3916 100644 --- a/SHADE_Engine/src/Filesystem/SHFileSystem.h +++ b/SHADE_Engine/src/Filesystem/SHFileSystem.h @@ -11,6 +11,7 @@ #pragma once #include "SHFolder.h" +#include namespace SHADE { @@ -18,12 +19,10 @@ namespace SHADE class SHFileSystem { public: - static FolderPointer BuildDirectory(FolderPath path) noexcept; + static void BuildDirectory(FolderPath path, FolderPointer& root, std::unordered_map& assetCollection) noexcept; private: - static FolderPointer CreateNewFolderHere(FolderPointer parent, FolderName name) noexcept; static bool DeleteFolder(FolderPointer location) noexcept; - - friend class SHFolder; + }; } \ No newline at end of file diff --git a/SHADE_Engine/src/Filesystem/SHFolder.cpp b/SHADE_Engine/src/Filesystem/SHFolder.cpp new file mode 100644 index 00000000..716eec4b --- /dev/null +++ b/SHADE_Engine/src/Filesystem/SHFolder.cpp @@ -0,0 +1,38 @@ +/*************************************************************************//** + * \file SHFolder.cpp + * \author Loh Xiao Qi + * \date 30 October 2022 + * \brief + * + * 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 "SHFolder.h" + +namespace SHADE +{ + SHFolder::SHFolder(FolderName name) + :name{ name }, subFolders(0), folded{ false }, path{ "" } + { + } + + FolderPointer SHFolder::CreateSubFolderHere(FolderName name) + { + for (auto const& folder : subFolders) + { + if (name == folder->name) + { + SHLOG_ERROR("Unable to create subfolder {} at {} as it already exists", name, folder->name); + return nullptr; + } + } + + auto result = new SHFolder(name); + result->path = path + "/" + name; + subFolders.push_back(result); + + return result; + } +} diff --git a/SHADE_Engine/src/Filesystem/SHFolder.h b/SHADE_Engine/src/Filesystem/SHFolder.h index 86cdc008..54e95033 100644 --- a/SHADE_Engine/src/Filesystem/SHFolder.h +++ b/SHADE_Engine/src/Filesystem/SHFolder.h @@ -12,7 +12,7 @@ #include #include -#include "Assets/SHAssetMacros.h" +#include "Assets/SHAsset.h" namespace SHADE { @@ -27,15 +27,12 @@ namespace SHADE typedef std::string FileExt; typedef SHFolder* FolderPointer; - // Forward Declare - class SHFileSystem; - struct SHFile { FileName name; FilePath path; FileExt ext; - + SHAsset const* assetMeta; }; class SHFolder @@ -50,9 +47,6 @@ namespace SHADE bool folded; FolderPointer CreateSubFolderHere(FolderName name); - - private: FolderPath path; - friend class SHFileSystem; }; } From 087cbcabaf94400294c0cfbb1d00f9ed24ba8eda Mon Sep 17 00:00:00 2001 From: Xiao Qi Date: Sun, 30 Oct 2022 04:41:24 +0800 Subject: [PATCH 39/44] Forgot function to actually retrieve root folder pointer hehe --- SHADE_Engine/src/Assets/SHAssetManager.cpp | 7 ++++++- SHADE_Engine/src/Assets/SHAssetManager.h | 2 ++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/SHADE_Engine/src/Assets/SHAssetManager.cpp b/SHADE_Engine/src/Assets/SHAssetManager.cpp index 658c80b0..682eb9ec 100644 --- a/SHADE_Engine/src/Assets/SHAssetManager.cpp +++ b/SHADE_Engine/src/Assets/SHAssetManager.cpp @@ -343,7 +343,12 @@ namespace SHADE return newAsset.id; } - bool SHAssetManager::IsRecognised(char const* ext) noexcept + FolderPointer SHAssetManager::GetRootFolder() noexcept + { + return folderRoot; + } + + bool SHAssetManager::IsRecognised(char const* ext) noexcept { for (auto const& e : EXTENSIONS) { diff --git a/SHADE_Engine/src/Assets/SHAssetManager.h b/SHADE_Engine/src/Assets/SHAssetManager.h index fea20332..64527e01 100644 --- a/SHADE_Engine/src/Assets/SHAssetManager.h +++ b/SHADE_Engine/src/Assets/SHAssetManager.h @@ -88,6 +88,8 @@ namespace SHADE static std::vector GetAllRecordOfType(AssetType type) noexcept; static AssetID CompileAsset(AssetPath const& path) noexcept; + + static FolderPointer GetRootFolder() noexcept; private: From dd8d9130718b4e240986dfa1ce033fb9ab87f679 Mon Sep 17 00:00:00 2001 From: Sri Sham Haran Date: Sun, 30 Oct 2022 14:22:55 +0800 Subject: [PATCH 40/44] Add widget for drag drop read only field Editor tweaks --- .../src/Editor/DragDrop/SHDragDrop.hpp | 6 +- .../AssetBrowser/SHAssetBrowser.cpp | 2 +- .../HierarchyPanel/SHHierarchyPanel.cpp | 4 +- .../Inspector/SHEditorComponentView.h | 12 +++ .../Inspector/SHEditorComponentView.hpp | 85 +++++++++++++------ .../Inspector/SHEditorInspector.cpp | 31 +++++-- SHADE_Engine/src/Editor/SHEditorWidgets.hpp | 32 +++++++ 7 files changed, 132 insertions(+), 40 deletions(-) create mode 100644 SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.h diff --git a/SHADE_Engine/src/Editor/DragDrop/SHDragDrop.hpp b/SHADE_Engine/src/Editor/DragDrop/SHDragDrop.hpp index f9849d78..ce0615e1 100644 --- a/SHADE_Engine/src/Editor/DragDrop/SHDragDrop.hpp +++ b/SHADE_Engine/src/Editor/DragDrop/SHDragDrop.hpp @@ -6,12 +6,12 @@ namespace SHADE { //TODO: Convert to RTTR? - constexpr auto DRAG_EID = "DragEID"; - constexpr auto DRAG_RESOURCE = "DragResource"; - struct SHDragDrop { + using DragDropTag = std::string_view; + static constexpr DragDropTag DRAG_EID = "DragEID"; + static constexpr DragDropTag DRAG_RESOURCE = "DragResource"; static bool BeginSource(ImGuiDragDropFlags const flags = 0); /** * \brief Ends the DragDrop Source. ONLY CALL IF BeginSource returns true diff --git a/SHADE_Engine/src/Editor/EditorWindow/AssetBrowser/SHAssetBrowser.cpp b/SHADE_Engine/src/Editor/EditorWindow/AssetBrowser/SHAssetBrowser.cpp index caad9b10..238ca085 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/AssetBrowser/SHAssetBrowser.cpp +++ b/SHADE_Engine/src/Editor/EditorWindow/AssetBrowser/SHAssetBrowser.cpp @@ -65,7 +65,7 @@ namespace SHADE { auto id = asset.id; ImGui::Text("Moving Asset: %zu", id); - SHDragDrop::SetPayload(DRAG_RESOURCE, &id); + SHDragDrop::SetPayload(SHDragDrop::DRAG_RESOURCE, &id); SHDragDrop::EndSource(); } diff --git a/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp b/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp index 6f65b734..eb0a7fea 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp +++ b/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp @@ -167,12 +167,12 @@ namespace SHADE } } ImGui::Text(moveLabel.c_str()); - SHDragDrop::SetPayload>(DRAG_EID, &editor->selectedEntities); + SHDragDrop::SetPayload>(SHDragDrop::DRAG_EID, &editor->selectedEntities); SHDragDrop::EndSource(); } else if (SHDragDrop::BeginTarget()) //If Received DragDrop { - if (const std::vector* eidPayload = SHDragDrop::AcceptPayload>(DRAG_EID)) //If payload is valid + if (const std::vector* eidPayload = SHDragDrop::AcceptPayload>(SHDragDrop::DRAG_EID)) //If payload is valid { ParentSelectedEntities(eid); SHDragDrop::EndTarget(); diff --git a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.h b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.h new file mode 100644 index 00000000..69f4c145 --- /dev/null +++ b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.h @@ -0,0 +1,12 @@ +#pragma once +#include "ECS_Base/Components/SHComponent.h" + +namespace SHADE +{ + template::value, bool> = true> + static void DrawContextMenu(T* component); + template, bool> = true> + static void DrawComponent(T* component); +} + +#include "SHEditorComponentView.hpp" \ No newline at end of file diff --git a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp index c4dfd674..587ffc48 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp +++ b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp @@ -13,9 +13,11 @@ #include "Editor/IconsFontAwesome6.h" #include "ECS_Base/Components/SHComponent.h" #include "Editor/SHEditorWidgets.hpp" +#include "Graphics/MiddleEnd/Interface/SHRenderable.h" #include "Graphics/MiddleEnd/Lights/SHLightComponent.h" #include "Physics/Components/SHColliderComponent.h" #include "Reflection/SHReflectionMetadata.h" +#include "Resource/SHResourceManager.h" namespace SHADE { @@ -23,16 +25,16 @@ namespace SHADE std::vector GetRTTREnumNames() { auto const rttrType = rttr::type::get(); - if(!rttrType.is_enumeration()) + if (!rttrType.is_enumeration()) return {}; auto const enumAlign = rttrType.get_enumeration(); auto const names = enumAlign.get_names(); std::vector result; - std::transform(names.begin(), names.end(), std::back_inserter(result), [](rttr::string_view const& name){return name.data();}); + std::transform(names.begin(), names.end(), std::back_inserter(result), [](rttr::string_view const& name) {return name.data(); }); return result; } - template::value, bool> = true> + template::value, bool>> static void DrawContextMenu(T* component) { if (!component) @@ -61,7 +63,7 @@ namespace SHADE ImGui::EndPopup(); } } - template, bool> = true> + template, bool>> static void DrawComponent(T* component) { if (!component) @@ -171,9 +173,9 @@ namespace SHADE auto metaMin = property.get_metadata(META::min); auto metaMax = property.get_metadata(META::max); float min{}, max{}; - if(metaMin.is_valid()) + if (metaMin.is_valid()) min = std::max(metaMin.template get_value(), -FLT_MAX * 0.5f); - if(metaMax.is_valid()) + if (metaMax.is_valid()) max = std::min(metaMax.template get_value(), FLT_MAX * 0.5f); if (metaMin.is_valid() && metaMax.is_valid()) { @@ -223,10 +225,10 @@ namespace SHADE return; // Get transform component for extrapolating relative sizes - auto* transformComponent = SHComponentManager::GetComponent(component->GetEID()); + auto* transformComponent = SHComponentManager::GetComponent_s(component->GetEID()); const auto componentType = rttr::type::get(*component); - SHEditorWidgets::CheckBox("##IsActive", [component]() {return component->isActive; }, [component](bool const& active) {component->isActive = active; }); + SHEditorWidgets::CheckBox("##IsActive", [component]() {return component->isActive; }, [component](bool const& active) {component->isActive = active; }, "Is Component Active"); ImGui::SameLine(); if (ImGui::CollapsingHeader(componentType.get_name().data())) { @@ -234,8 +236,8 @@ namespace SHADE auto& colliders = component->GetColliders(); int const size = static_cast(colliders.size()); - ImGui::BeginChild("Colliders", {0.0f, colliders.empty() ? 1.0f : 250.0f}, true); - std::optional colliderToDelete{std::nullopt}; + ImGui::BeginChild("Colliders", { 0.0f, colliders.empty() ? 1.0f : 250.0f }, true); + std::optional colliderToDelete{ std::nullopt }; for (int i{}; i < size; ++i) { ImGui::PushID(i); @@ -244,12 +246,12 @@ namespace SHADE if (collider->GetType() == SHCollider::Type::BOX) { - SHEditorWidgets::BeginPanel( std::format("{} Box Collider #{}", ICON_FA_CUBE, i).data(), { ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y }); + 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, transformComponent] { return (transformComponent->GetWorldScale() * 2.0f) * box->GetHalfExtents(); }, + "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) @@ -258,14 +260,14 @@ namespace SHADE auto sphere = reinterpret_cast(collider->GetShape()); SHEditorWidgets::DragFloat ( - "Radius", + "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);}); + }, + [collider](float const& value) { collider->SetBoundingSphere(value); }); } else if (collider->GetType() == SHCollider::Type::CAPSULE) { @@ -276,14 +278,14 @@ namespace SHADE 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())) + if (ImGui::Button(std::format("{} Remove Collider #{}", ICON_MD_REMOVE, i).data())) { colliderToDelete = i; } SHEditorWidgets::EndPanel(); ImGui::PopID(); } - if(colliderToDelete.has_value()) + if (colliderToDelete.has_value()) { component->RemoveCollider(colliderToDelete.value()); } @@ -291,11 +293,11 @@ namespace SHADE if (ImGui::BeginMenu("Add Collider")) { - if(ImGui::Selectable("Box Collider")) + if (ImGui::Selectable("Box Collider")) { component->AddBoundingBox(); } - if(ImGui::Selectable("Sphere Collider")) + if (ImGui::Selectable("Sphere Collider")) { component->AddBoundingSphere(); } @@ -308,10 +310,10 @@ namespace SHADE template<> static void DrawComponent(SHLightComponent* component) { - if (!component) + if (!component) return; const auto componentType = rttr::type::get(*component); - SHEditorWidgets::CheckBox("##IsActive", [component]() {return component->isActive; }, [component](bool const& active) {component->isActive = active; }); + SHEditorWidgets::CheckBox("##IsActive", [component]() {return component->isActive; }, [component](bool const& active) {component->isActive = active; }, "Is Component Active"); ImGui::SameLine(); if (ImGui::CollapsingHeader(componentType.get_name().data())) { @@ -319,19 +321,46 @@ namespace SHADE static auto const enumAlign = rttr::type::get().get_enumeration(); static std::vector list(GetRTTREnumNames()); - + SHEditorWidgets::ComboBox("Type", list, [component] {return static_cast(component->GetType()); }, [component](int const& idx) { component->SetType(static_cast(idx)); }); - SHEditorWidgets::DragVec3("Position", {"X", "Y", "Z"}, [component](){return component->GetPosition();}, [component](SHVec3 const& vec){component->SetPosition(vec);}); - SHEditorWidgets::DragVec3("Direction", {"X", "Y", "Z"}, [component](){return component->GetDirection();}, [component](SHVec3 const& vec){component->SetDirection(vec);}); - SHEditorWidgets::ColorPicker("Color", [component](){return component->GetColor();}, [component](SHVec4 const& rgba){component->SetColor(rgba);}); - SHEditorWidgets::DragFloat("Strength", [component](){return component->GetStrength();}, [component](float const& value){component->SetStrength(value);}); + SHEditorWidgets::DragVec3("Position", { "X", "Y", "Z" }, [component]() {return component->GetPosition(); }, [component](SHVec3 const& vec) {component->SetPosition(vec); }); + SHEditorWidgets::DragVec3("Direction", { "X", "Y", "Z" }, [component]() {return component->GetDirection(); }, [component](SHVec3 const& vec) {component->SetDirection(vec); }); + SHEditorWidgets::ColorPicker("Color", [component]() {return component->GetColor(); }, [component](SHVec4 const& rgba) {component->SetColor(rgba); }); + SHEditorWidgets::DragFloat("Strength", [component]() {return component->GetStrength(); }, [component](float const& value) {component->SetStrength(value); }); } else { DrawContextMenu(component); } } -} \ No newline at end of file + + template<> + static void DrawComponent(SHRenderable* component) + { + if (!component) + return; + const auto componentType = rttr::type::get(*component); + SHEditorWidgets::CheckBox("##IsActive", [component]() {return component->isActive; }, [component](bool const& active) {component->isActive = active; }, "Is Component Active"); + ImGui::SameLine(); + if (ImGui::CollapsingHeader(componentType.get_name().data())) + { + DrawContextMenu(component); + SHEditorWidgets::DragDropReadOnlyField("Mesh", "Mesh Asset", [component]() + { + Handle const& mesh = component->GetMesh(); + return SHResourceManager::GetAssetID(mesh).value_or(0); + }, + [component](AssetID const& id) + { + //component->SetMesh(SHResourceManager::LoadOrGet(id)); + }, SHDragDrop::DRAG_RESOURCE); + } + else + { + DrawContextMenu(component); + } + } +} diff --git a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorInspector.cpp b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorInspector.cpp index 9a31da60..6309d805 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorInspector.cpp +++ b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorInspector.cpp @@ -10,17 +10,14 @@ #include "Editor/SHImGuiHelpers.hpp" #include "Editor/SHEditorWidgets.hpp" -#include "SHEditorComponentView.hpp" -#include "ECS_Base/UnitTesting/SHTestComponents.h" #include "Graphics/MiddleEnd/Interface/SHRenderable.h" #include "Scripting/SHScriptEngine.h" #include "ECS_Base/Managers/SHSystemManager.h" -#include "ECS_Base/Managers/SHSystemManager.h" -#include "AudioSystem/SHAudioSystem.h" #include "Physics/Components/SHRigidBodyComponent.h" #include "Physics/Components/SHColliderComponent.h" #include "Camera/SHCameraComponent.h" +#include "SHEditorComponentView.h" namespace SHADE { @@ -30,8 +27,17 @@ namespace SHADE bool selected = false; if(!SHComponentManager::HasComponent(eid)) { - if(selected = ImGui::Selectable(std::format("Add {}", rttr::type::get().get_name().data()).data()); selected) + const char* componentName = rttr::type::get().get_name().data(); + if(selected = ImGui::Selectable(std::format("Add {}", componentName).data()); selected) SHComponentManager::AddComponent(eid); + if(ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::Text("Adds", componentName); ImGui::SameLine(); + ImGui::TextColored(ImGuiColors::green, "%s", componentName); ImGui::SameLine(); + ImGui::Text("to this entity", componentName); + ImGui::EndTooltip(); + } } return selected; } @@ -42,13 +48,26 @@ namespace SHADE bool selected = false; if (!SHComponentManager::HasComponent(eid)) { - if(selected = ImGui::Selectable(std::format("Add {}", rttr::type::get().get_name().data()).data()); selected) + const char* componentName = rttr::type::get().get_name().data(); + + if(selected = ImGui::Selectable(std::format("Add {}", componentName).data()); selected) { if(SHComponentManager::GetComponent_s(eid) == nullptr) SHComponentManager::AddComponent(eid); SHComponentManager::AddComponent(eid); } + if(ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::Text("Adds", componentName); ImGui::SameLine(); + ImGui::TextColored(ImGuiColors::green, "%s", componentName); ImGui::SameLine(); + ImGui::Text("to this entity", componentName); + ImGui::Text("Adds"); ImGui::SameLine(); + ImGui::TextColored(ImGuiColors::red, "%s", rttr::type::get().get_name().data()); ImGui::SameLine(); + ImGui::Text("if the entity does not already have it"); + ImGui::EndTooltip(); + } } return selected; } diff --git a/SHADE_Engine/src/Editor/SHEditorWidgets.hpp b/SHADE_Engine/src/Editor/SHEditorWidgets.hpp index 7a71c5f2..053348d7 100644 --- a/SHADE_Engine/src/Editor/SHEditorWidgets.hpp +++ b/SHADE_Engine/src/Editor/SHEditorWidgets.hpp @@ -22,6 +22,8 @@ #include #include +#include "DragDrop/SHDragDrop.hpp" + namespace SHADE { class SH_API SHEditorWidgets @@ -413,6 +415,36 @@ namespace SHADE return changed; } + template + static bool DragDropReadOnlyField(std::string const& label, std::string_view const& fieldVTextValue, std::function const& get, std::function const& set, SHDragDrop::DragDropTag const& dragDropTag, std::string_view const& tooltip = {}) + { + std::string text = fieldVTextValue.data(); + ImGui::BeginGroup(); + ImGui::PushID(label.data()); + TextLabel(label); + bool const changed = ImGui::InputText("##", &text, ImGuiInputTextFlags_ReadOnly, nullptr, nullptr); + if(SHDragDrop::BeginTarget()) + { + if(T* payload = SHDragDrop::AcceptPayload(dragDropTag)) + { + SHCommandManager::PerformCommand(std::reinterpret_pointer_cast(std::make_shared>(get(), *payload, set)), false); + SHDragDrop::EndTarget(); + } + } + ImGui::PopID(); + ImGui::EndGroup(); + if (!tooltip.empty()) + { + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::Text(tooltip.data()); + ImGui::EndTooltip(); + } + } + return changed; + } + template static bool DragScalar(const std::string& label, ImGuiDataType data_type, std::function get, std::function set, float speed = 1.0f, T p_min = T(), T p_max = T(), const char* displayFormat = "%.3f", std::string_view const& tooltip = {}, ImGuiSliderFlags flags = 0) From ca659e272b33c0a2cb1cd30c810582076b799ddf Mon Sep 17 00:00:00 2001 From: Sri Sham Haran Date: Sun, 30 Oct 2022 15:01:36 +0800 Subject: [PATCH 41/44] Designate keys for Copy/Paste of entities in hierarchy panel Change default brush for SHWindow so we don't flashbang everytime we run engine --- .../HierarchyPanel/SHHierarchyPanel.cpp | 34 +++++++++++++++++-- .../HierarchyPanel/SHHierarchyPanel.h | 3 +- .../src/Graphics/Windowing/SHWindow.h | 2 +- 3 files changed, 34 insertions(+), 5 deletions(-) diff --git a/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp b/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp index dbe598ce..44369040 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp +++ b/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp @@ -83,6 +83,23 @@ namespace SHADE editor->selectedEntities.clear(); } ImGui::SeparatorEx(ImGuiSeparatorFlags_Horizontal); + + if(ImGui::IsWindowFocused() && ImGui::IsKeyDown(ImGuiKey_LeftCtrl) && ImGui::IsKeyReleased(ImGuiKey_C)) + { + CopySelectedEntities(); + } + if(ImGui::IsWindowFocused() && ImGui::IsKeyDown(ImGuiKey_LeftCtrl) && !ImGui::IsKeyDown(ImGuiKey_LeftShift) && ImGui::IsKeyReleased(ImGuiKey_V)) + { + PasteEntities(); + } + if(ImGui::IsWindowFocused() && ImGui::IsKeyDown(ImGuiKey_LeftCtrl) && ImGui::IsKeyDown(ImGuiKey_LeftShift) && ImGui::IsKeyReleased(ImGuiKey_V)) + { + const auto editor = SHSystemManager::GetSystem(); + if(editor->selectedEntities.size() == 1) + { + PasteEntities(editor->selectedEntities.back()); + } + } } ImGui::End(); } @@ -204,11 +221,11 @@ namespace SHADE } if(ImGui::Selectable("Copy")) { - SHClipboardUtilities::WriteToClipboard(SHSerialization::SerializeEntitiesToString(editor->selectedEntities)); + CopySelectedEntities(); } if(ImGui::Selectable("Paste")) { - SetScrollTo(SHSerialization::DeserializeEntitiesFromString(SHClipboardUtilities::GetDataFromClipboard())); + PasteEntities(); skipFrame = true; ImGui::EndPopup(); if(isNodeOpen) @@ -217,7 +234,7 @@ namespace SHADE } if(ImGui::Selectable("Paste as Child")) { - SetScrollTo(SHSerialization::DeserializeEntitiesFromString(SHClipboardUtilities::GetDataFromClipboard(), eid)); + PasteEntities(eid); skipFrame = true; } if(ImGui::Selectable(std::format("{} Delete", ICON_MD_DELETE).data())) @@ -345,6 +362,17 @@ namespace SHADE }); } + void SHHierarchyPanel::CopySelectedEntities() + { + const auto editor = SHSystemManager::GetSystem(); + SHClipboardUtilities::WriteToClipboard(SHSerialization::SerializeEntitiesToString(editor->selectedEntities)); + } + + void SHHierarchyPanel::PasteEntities(EntityID parentEID) + { + SetScrollTo(SHSerialization::DeserializeEntitiesFromString(SHClipboardUtilities::GetDataFromClipboard(), parentEID)); + } + void SHCreateEntityCommand::Execute() { EntityID newEID = SHEntityManager::CreateEntity(eid); diff --git a/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.h b/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.h index 8fae5d6d..58931058 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.h +++ b/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.h @@ -30,7 +30,8 @@ namespace SHADE void CreateChildEntity(EntityID parentEID) const noexcept; void ParentSelectedEntities(EntityID parentEID) const noexcept; void SelectRangeOfEntities(EntityID beginEID, EntityID EndEID); - + void CopySelectedEntities(); + void PasteEntities(EntityID parentEID = MAX_EID); bool skipFrame = false; std::string filter; bool isAnyNodeSelected = false; diff --git a/SHADE_Engine/src/Graphics/Windowing/SHWindow.h b/SHADE_Engine/src/Graphics/Windowing/SHWindow.h index 8068c82e..8595ce4b 100644 --- a/SHADE_Engine/src/Graphics/Windowing/SHWindow.h +++ b/SHADE_Engine/src/Graphics/Windowing/SHWindow.h @@ -48,7 +48,7 @@ namespace SHADE //bool canFullscreen = true; - unsigned bgColor = WHITE_BRUSH; + unsigned bgColor = DKGRAY_BRUSH; //bool transparent = false; From 13ad7d46c6fb1d5d1b8833d947cc32d35d30e49b Mon Sep 17 00:00:00 2001 From: Sri Sham Haran Date: Sun, 30 Oct 2022 15:19:42 +0800 Subject: [PATCH 42/44] Fix crash when entity w no transform being set as child of entity w transform Add select all --- .../HierarchyPanel/SHHierarchyPanel.cpp | 145 ++++++++++-------- .../HierarchyPanel/SHHierarchyPanel.h | 1 + .../src/Math/Transform/SHTransformSystem.cpp | 3 + 3 files changed, 86 insertions(+), 63 deletions(-) diff --git a/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp b/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp index 44369040..93232917 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp +++ b/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp @@ -48,7 +48,7 @@ namespace SHADE if (Begin()) { - if(skipFrame) + if (skipFrame) { ImGui::End(); skipFrame = false; @@ -63,9 +63,9 @@ namespace SHADE for (const auto child : children) { - if(child) + if (child) RecursivelyDrawEntityNode(child); - if(skipFrame) + if (skipFrame) { ImGui::End(); return; @@ -77,29 +77,36 @@ namespace SHADE SHLOG_WARNING("Scene Graph root is null! Unable to render hierarchy.") } - if(ImGui::IsWindowHovered() && !SHDragDrop::hasDragDrop && !ImGui::IsAnyItemHovered() && ImGui::IsMouseReleased(ImGuiMouseButton_Left)) + if (ImGui::IsWindowHovered() && !SHDragDrop::hasDragDrop && !ImGui::IsAnyItemHovered() && ImGui::IsMouseReleased(ImGuiMouseButton_Left)) { - if(auto editor = SHSystemManager::GetSystem()) + if (auto editor = SHSystemManager::GetSystem()) editor->selectedEntities.clear(); } ImGui::SeparatorEx(ImGuiSeparatorFlags_Horizontal); - - if(ImGui::IsWindowFocused() && ImGui::IsKeyDown(ImGuiKey_LeftCtrl) && ImGui::IsKeyReleased(ImGuiKey_C)) + if (ImGui::IsWindowFocused()) { - CopySelectedEntities(); - } - if(ImGui::IsWindowFocused() && ImGui::IsKeyDown(ImGuiKey_LeftCtrl) && !ImGui::IsKeyDown(ImGuiKey_LeftShift) && ImGui::IsKeyReleased(ImGuiKey_V)) - { - PasteEntities(); - } - if(ImGui::IsWindowFocused() && ImGui::IsKeyDown(ImGuiKey_LeftCtrl) && ImGui::IsKeyDown(ImGuiKey_LeftShift) && ImGui::IsKeyReleased(ImGuiKey_V)) - { - const auto editor = SHSystemManager::GetSystem(); - if(editor->selectedEntities.size() == 1) + if (ImGui::IsKeyDown(ImGuiKey_LeftCtrl) && ImGui::IsKeyReleased(ImGuiKey_A)) { - PasteEntities(editor->selectedEntities.back()); + SelectAllEntities(); + } + if (ImGui::IsKeyDown(ImGuiKey_LeftCtrl) && ImGui::IsKeyReleased(ImGuiKey_C)) + { + CopySelectedEntities(); + } + if (ImGui::IsKeyDown(ImGuiKey_LeftCtrl) && !ImGui::IsKeyDown(ImGuiKey_LeftShift) && ImGui::IsKeyReleased(ImGuiKey_V)) + { + PasteEntities(); + } + if (ImGui::IsKeyDown(ImGuiKey_LeftCtrl) && ImGui::IsKeyDown(ImGuiKey_LeftShift) && ImGui::IsKeyReleased(ImGuiKey_V)) + { + const auto editor = SHSystemManager::GetSystem(); + if (editor->selectedEntities.size() == 1) + { + PasteEntities(editor->selectedEntities.back()); + } } } + } ImGui::End(); } @@ -111,7 +118,7 @@ namespace SHADE void SHHierarchyPanel::SetScrollTo(EntityID eid) { - if(eid == MAX_EID) + if (eid == MAX_EID) return; scrollTo = eid; } @@ -126,7 +133,7 @@ namespace SHADE auto size = ImGui::GetWindowSize(); auto g = ImGui::GetCurrentContext(); ImGui::SetCursorPosX(size.x - g->Style.FramePadding.x * 15.0f); - if(ImGui::SmallButton(ICON_MD_DESELECT)) + if (ImGui::SmallButton(ICON_MD_DESELECT)) { auto editor = SHSystemManager::GetSystem(); editor->selectedEntities.clear(); @@ -153,7 +160,7 @@ namespace SHADE ImRect SHHierarchyPanel::RecursivelyDrawEntityNode(SHSceneNode* const currentNode) { - if(currentNode == nullptr) + if (currentNode == nullptr) return {}; auto const& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); @@ -161,7 +168,7 @@ namespace SHADE auto& children = currentNode->GetChildren(); EntityID eid = currentNode->GetEntityID(); - if(scrollTo != MAX_EID && eid == scrollTo) + if (scrollTo != MAX_EID && eid == scrollTo) { ImGui::SetScrollHereY(); scrollTo = MAX_EID; @@ -188,12 +195,12 @@ namespace SHADE if (SHDragDrop::BeginSource()) { std::string moveLabel = "Moving EID: "; - if(!isSelected) + if (!isSelected) editor->selectedEntities.push_back(eid); - for(int i = 0; i < static_cast(editor->selectedEntities.size()); ++i) + for (int i = 0; i < static_cast(editor->selectedEntities.size()); ++i) { moveLabel.append(std::to_string(editor->selectedEntities[i])); - if(i + 1 < static_cast(editor->selectedEntities.size())) + if (i + 1 < static_cast(editor->selectedEntities.size())) { moveLabel.append(", "); } @@ -212,43 +219,43 @@ namespace SHADE } //Context menu - if(ImGui::BeginPopupContextItem(std::to_string(eid).c_str())) + if (ImGui::BeginPopupContextItem(std::to_string(eid).c_str())) { - if(!isSelected) + if (!isSelected) { editor->selectedEntities.clear(); editor->selectedEntities.push_back(eid); } - if(ImGui::Selectable("Copy")) + if (ImGui::Selectable("Copy")) { CopySelectedEntities(); } - if(ImGui::Selectable("Paste")) + if (ImGui::Selectable("Paste")) { PasteEntities(); skipFrame = true; ImGui::EndPopup(); - if(isNodeOpen) + if (isNodeOpen) ImGui::TreePop(); return nodeRect; } - if(ImGui::Selectable("Paste as Child")) + if (ImGui::Selectable("Paste as Child")) { PasteEntities(eid); skipFrame = true; } - if(ImGui::Selectable(std::format("{} Delete", ICON_MD_DELETE).data())) + if (ImGui::Selectable(std::format("{} Delete", ICON_MD_DELETE).data())) { SHEntityManager::DestroyEntity(eid); } - - if((currentNode->GetParent() != sceneGraph.GetRoot()) && ImGui::Selectable(std::format("{} Unparent Selected", ICON_MD_NORTH_WEST).data())) + + if ((currentNode->GetParent() != sceneGraph.GetRoot()) && ImGui::Selectable(std::format("{} Unparent Selected", ICON_MD_NORTH_WEST).data())) { ParentSelectedEntities(MAX_EID); } ImGui::EndPopup(); } - + //Handle node selection if (ImGui::IsItemHovered()) { @@ -256,11 +263,11 @@ namespace SHADE { if (!isSelected) { - if(ImGui::IsKeyDown(ImGuiKey_LeftShift)) + if (ImGui::IsKeyDown(ImGuiKey_LeftShift)) { - if(editor->selectedEntities.size() >= 1) + if (editor->selectedEntities.size() >= 1) { - SelectRangeOfEntities(editor->selectedEntities[0], eid); + SelectRangeOfEntities(editor->selectedEntities[0], eid); } else editor->selectedEntities.clear(); } @@ -318,12 +325,12 @@ namespace SHADE auto const editor = SHSystemManager::GetSystem(); SHEntityParentCommand::EntityParentData entityParentData; std::vector parentedEIDS; - for(auto const& eid : editor->selectedEntities) + for (auto const& eid : editor->selectedEntities) { - if(sceneGraph.GetChild(eid, parentEID) == nullptr) + if (sceneGraph.GetChild(eid, parentEID) == nullptr) { parentedEIDS.push_back(eid); - if(auto parent = sceneGraph.GetParent(eid)) + if (auto parent = sceneGraph.GetParent(eid)) entityParentData[eid].oldParentEID = parent->GetEntityID(); entityParentData[eid].newParentEID = parentEID; } @@ -338,28 +345,40 @@ namespace SHADE editor->selectedEntities.clear(); auto const& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); sceneGraph.Traverse([&](SHSceneNode* nodePtr) - { - auto eid = nodePtr->GetEntityID(); - if(!startSelecting) { - if(eid == beginEID || eid == endEID) + auto eid = nodePtr->GetEntityID(); + if (!startSelecting) { - startSelecting = true; - editor->selectedEntities.push_back(eid); - } - } - else - { - if(!endSelecting) - { - editor->selectedEntities.push_back(eid); - if(eid == endEID || eid == beginEID) + if (eid == beginEID || eid == endEID) { - endSelecting = true; + startSelecting = true; + editor->selectedEntities.push_back(eid); } } - } - }); + else + { + if (!endSelecting) + { + editor->selectedEntities.push_back(eid); + if (eid == endEID || eid == beginEID) + { + endSelecting = true; + } + } + } + }); + } + + void SHHierarchyPanel::SelectAllEntities() + { + const auto editor = SHSystemManager::GetSystem(); + editor->selectedEntities.clear(); + auto const& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); + sceneGraph.Traverse([&](SHSceneNode* nodePtr) + { + auto eid = nodePtr->GetEntityID(); + editor->selectedEntities.push_back(eid); + }); } void SHHierarchyPanel::CopySelectedEntities() @@ -376,7 +395,7 @@ namespace SHADE void SHCreateEntityCommand::Execute() { EntityID newEID = SHEntityManager::CreateEntity(eid); - if(eid == MAX_EID) + if (eid == MAX_EID) eid = newEID; } @@ -388,9 +407,9 @@ namespace SHADE void SHEntityParentCommand::Execute() { auto const& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); - for(auto const& eid : entities) + for (auto const& eid : entities) { - if(entityParentData[eid].newParentEID == MAX_EID) + if (entityParentData[eid].newParentEID == MAX_EID) sceneGraph.SetParent(eid, nullptr); else sceneGraph.SetParent(eid, entityParentData[eid].newParentEID); @@ -400,9 +419,9 @@ namespace SHADE void SHEntityParentCommand::Undo() { auto const& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); - for(auto const& eid : entities) + for (auto const& eid : entities) { - if(entityParentData[eid].oldParentEID == MAX_EID) + if (entityParentData[eid].oldParentEID == MAX_EID) sceneGraph.SetParent(eid, nullptr); else sceneGraph.SetParent(eid, entityParentData[eid].oldParentEID); diff --git a/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.h b/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.h index 58931058..9b26e9d6 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.h +++ b/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.h @@ -30,6 +30,7 @@ namespace SHADE void CreateChildEntity(EntityID parentEID) const noexcept; void ParentSelectedEntities(EntityID parentEID) const noexcept; void SelectRangeOfEntities(EntityID beginEID, EntityID EndEID); + void SelectAllEntities(); void CopySelectedEntities(); void PasteEntities(EntityID parentEID = MAX_EID); bool skipFrame = false; diff --git a/SHADE_Engine/src/Math/Transform/SHTransformSystem.cpp b/SHADE_Engine/src/Math/Transform/SHTransformSystem.cpp index a2ab6880..156a47cc 100644 --- a/SHADE_Engine/src/Math/Transform/SHTransformSystem.cpp +++ b/SHADE_Engine/src/Math/Transform/SHTransformSystem.cpp @@ -263,6 +263,9 @@ namespace SHADE auto* node = EVENT_DATA->data->node; auto* tf = SHComponentManager::GetComponent_s(node->GetEntityID()); + if(tf == nullptr) + return EVENT_DATA->handle; + // Recompute local transform and store localToWorld Matrix SHMatrix localToWorld = SHMatrix::Identity; SHMatrix worldToLocal = SHMatrix::Identity; From 0aebc3053fc6094fbc90f7fbdd3c283aebda8c63 Mon Sep 17 00:00:00 2001 From: Sri Sham Haran Date: Sun, 30 Oct 2022 18:26:49 +0800 Subject: [PATCH 43/44] Asset browser (currently only displays asset and can drag drop for setting of mesh. except setting mesh in inspector doesnt work) --- .../AssetBrowser/SHAssetBrowser.cpp | 154 +++++++++++++----- .../AssetBrowser/SHAssetBrowser.h | 13 +- SHADE_Engine/src/Editor/SHEditor.cpp | 2 +- 3 files changed, 128 insertions(+), 41 deletions(-) diff --git a/SHADE_Engine/src/Editor/EditorWindow/AssetBrowser/SHAssetBrowser.cpp b/SHADE_Engine/src/Editor/EditorWindow/AssetBrowser/SHAssetBrowser.cpp index 238ca085..8c71eb8f 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/AssetBrowser/SHAssetBrowser.cpp +++ b/SHADE_Engine/src/Editor/EditorWindow/AssetBrowser/SHAssetBrowser.cpp @@ -4,14 +4,16 @@ #include "Editor/IconsMaterialDesign.h" #include "Editor/SHImGuiHelpers.hpp" #include +#include #include "Assets/SHAssetManager.h" +#include "Editor/IconsFontAwesome6.h" #include "Editor/DragDrop/SHDragDrop.hpp" namespace SHADE { SHAssetBrowser::SHAssetBrowser() - :SHEditorWindow("\xee\x8b\x87 Asset Browser", ImGuiWindowFlags_MenuBar) + :SHEditorWindow("\xee\x8b\x87 Asset Browser", ImGuiWindowFlags_MenuBar), rootFolder(SHAssetManager::GetRootFolder()), prevFolder(rootFolder), currentFolder(rootFolder) { } @@ -23,62 +25,140 @@ namespace SHADE void SHAssetBrowser::Update() { SHEditorWindow::Update(); - if(Begin()) + if (Begin()) { + RecursivelyDrawTree(rootFolder); DrawMenuBar(); - auto const& assets = SHAssetManager::GetAllAssets(); - if(ImGui::BeginTable("AssetBrowserTable", 3)) - { - ImGui::TableNextColumn(); - ImGui::TableHeader("Asset ID"); - ImGui::TableNextColumn(); - ImGui::TableHeader("Name"); - ImGui::TableNextColumn(); - ImGui::TableHeader("Type"); - for(SHAsset const& asset : assets) - { - DrawAsset(asset); - } - ImGui::EndTable(); - } + DrawCurrentFolder(); } ImGui::End(); } void SHAssetBrowser::DrawMenuBar() { - if(ImGui::BeginMenuBar()) + if (ImGui::BeginMenuBar()) { ImGui::EndMenuBar(); } } - void SHAssetBrowser::DrawAsset(SHAsset const& asset) + ImRect SHAssetBrowser::RecursivelyDrawTree(FolderPointer folder) { - ImGui::PushID(asset.id); - ImGui::BeginGroup(); + auto const& subFolders = folder->subFolders; + auto const& files = folder->files; + const bool isSelected = std::ranges::find(selectedFolders, folder) != selectedFolders.end(); + ImGuiTreeNodeFlags flags = (subFolders.empty() && files.empty()) ? ImGuiTreeNodeFlags_Leaf : ImGuiTreeNodeFlags_OpenOnArrow; + if (isSelected) + flags |= ImGuiTreeNodeFlags_Selected; + if (folder == rootFolder) + flags |= ImGuiTreeNodeFlags_DefaultOpen; + + bool isOpen = ImGui::TreeNodeEx(folder, flags, "%s %s", ICON_MD_FOLDER, folder->name.data()); + const ImRect nodeRect = ImRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax()); + if(ImGui::IsItemClicked()) + { + selectedFolders.clear(); + selectedFolders.push_back(folder); + } + if (isOpen) + { + const ImColor treeLineColor = ImGui::GetColorU32(ImGuiCol_CheckMark); + const float horizontalOffset = 0.0f; + ImDrawList* drawList = ImGui::GetWindowDrawList(); + ImVec2 vertLineStart = ImGui::GetCursorScreenPos(); + vertLineStart.x += horizontalOffset; + ImVec2 vertLineEnd = vertLineStart; + for (auto const& subFolder : subFolders) + { + const float horizontalLineSize = 8.0f; + const ImRect childRect = RecursivelyDrawTree(subFolder); + const float midPoint = (childRect.Min.y + childRect.Max.y) * 0.5f; + drawList->AddLine(ImVec2(vertLineStart.x, midPoint), ImVec2(vertLineStart.x + horizontalLineSize, midPoint), treeLineColor, 1); + vertLineEnd.y = midPoint; + } + for (auto const& file : files) + { + const float horizontalLineSize = 25.0f; + const ImRect childRect = DrawFile(file); + const float midPoint = (childRect.Min.y + childRect.Max.y) * 0.5f; + drawList->AddLine(ImVec2(vertLineStart.x, midPoint), ImVec2(vertLineStart.x + horizontalLineSize, midPoint), treeLineColor, 1); + vertLineEnd.y = midPoint; + } + drawList->AddLine(vertLineStart, vertLineEnd, treeLineColor, 1); + ImGui::TreePop(); + } + return nodeRect; + } - ImGui::TableNextColumn(); - ImGui::Selectable(std::format("{}", asset.id).data(), false, ImGuiSelectableFlags_SpanAllColumns); + void SHAssetBrowser::DrawCurrentFolder() + { + //auto const& subFolders = currentFolder->subFolders; + //ImVec2 initialCursorPos = ImGui::GetCursorPos(); + //ImVec2 initialRegionAvail = ImGui::GetContentRegionAvail(); + //int maxTiles = initialRegionAvail.x / tileWidth; + //float maxX = (maxTiles - 1)*tileWidth; + //ImVec2 tilePos = initialCursorPos; + //for (auto const& subFolder : subFolders) + //{ + // ImGui::SetCursorPos(tilePos); + // ImGui::BeginGroup(); + // ImGui::PushStyleVar(ImGuiStyleVar_ItemInnerSpacing, {0.0f, 0.0f}); + // ImGui::Button(ICON_MD_FOLDER, {tileWidth}); + // ImGui::Text(subFolder->name.data()); + // ImGui::PopStyleVar(); + // ImGui::EndGroup(); + // if(tilePos.x >= maxX) + // { + // tilePos.x = initialCursorPos.x; + // } + // else + // { + // ImGui::SameLine(); + // tilePos.x += tileWidth; + // } + //} + } + + ImRect SHAssetBrowser::DrawFile(SHFile const& file) noexcept + { + if (file.assetMeta == nullptr) + return ImRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax()); + const bool isSelected = std::ranges::find(selectedAssets, file.assetMeta->id) != selectedAssets.end(); + ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_Leaf; + if (isSelected) + flags |= ImGuiTreeNodeFlags_Selected; + std::string icon{}; + + switch(file.assetMeta->type) + { + case AssetType::INVALID: break; + case AssetType::SHADER: icon = ICON_FA_FILE_CODE; break; + case AssetType::SHADER_BUILT_IN: icon = ICON_FA_FILE_CODE; break; + case AssetType::TEXTURE: icon = ICON_FA_IMAGES; break; + case AssetType::MESH: icon = ICON_FA_CUBES; break; + case AssetType::SCENE: icon = ICON_MD_IMAGE; break; + case AssetType::PREFAB: icon = ICON_FA_BOX_OPEN; break; + case AssetType::MATERIAL: break; + case AssetType::MAX_COUNT: break; + default: ; + } + + ImGui::TreeNodeEx(file.assetMeta, flags, "%s %s", icon.data(), file.assetMeta->name.data()); + const ImRect nodeRect = ImRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax()); if(SHDragDrop::BeginSource()) { - auto id = asset.id; - ImGui::Text("Moving Asset: %zu", id); + auto id = file.assetMeta->id; + ImGui::Text("Moving Asset: %s [%zu]", file.name.data(), file.assetMeta->id); SHDragDrop::SetPayload(SHDragDrop::DRAG_RESOURCE, &id); SHDragDrop::EndSource(); } - - ImGui::TableNextColumn(); - ImGui::Text("%s", asset.name.c_str()); - - ImGui::TableNextColumn(); - ImGui::Text("%s", "Type"); - - ImGui::EndGroup(); - ImGui::PopID(); - - - + if(ImGui::IsItemClicked()) + { + selectedAssets.clear(); + selectedAssets.push_back(file.assetMeta->id); + } + ImGui::TreePop(); + return nodeRect; } } diff --git a/SHADE_Engine/src/Editor/EditorWindow/AssetBrowser/SHAssetBrowser.h b/SHADE_Engine/src/Editor/EditorWindow/AssetBrowser/SHAssetBrowser.h index 0e3053bc..d56fc029 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/AssetBrowser/SHAssetBrowser.h +++ b/SHADE_Engine/src/Editor/EditorWindow/AssetBrowser/SHAssetBrowser.h @@ -1,7 +1,9 @@ #pragma once +#include "imgui_internal.h" #include "Assets/SHAsset.h" #include "Editor/EditorWindow/SHEditorWindow.h" +#include "Filesystem/SHFolder.h" namespace SHADE { @@ -16,9 +18,14 @@ namespace SHADE void Refresh(); private: void DrawMenuBar(); - void DrawAsset(SHAsset const& asset); + ImRect RecursivelyDrawTree(FolderPointer folder); + void DrawCurrentFolder(); + ImRect DrawFile(SHFile const& file) noexcept; - float idColumnWidth, nameColumnWidth, typeColumnWidth; + FolderPointer rootFolder, prevFolder, currentFolder; + std::vector selectedFolders; + std::vector selectedAssets; + static constexpr float tileWidth = 50.0f; }; -} \ No newline at end of file +} diff --git a/SHADE_Engine/src/Editor/SHEditor.cpp b/SHADE_Engine/src/Editor/SHEditor.cpp index 6ae94cdc..cf5056a5 100644 --- a/SHADE_Engine/src/Editor/SHEditor.cpp +++ b/SHADE_Engine/src/Editor/SHEditor.cpp @@ -175,7 +175,7 @@ namespace SHADE ImFontConfig icons_config{}; icons_config.MergeMode = true; icons_config.GlyphOffset.y = 5.f; constexpr ImWchar icon_ranges_fa[] = { ICON_MIN_FA, ICON_MAX_FA, 0 }; ImFont* UIFontFA = io->Fonts->AddFontFromFileTTF("../../Assets/Editor/Fonts/fa-solid-900.ttf", 20.f, &icons_config, icon_ranges_fa); //TODO: Change to config based assets path - constexpr ImWchar icon_ranges_md[] = { ICON_MIN_MD, ICON_MAX_MD, 0 }; + constexpr ImWchar icon_ranges_md[] = { ICON_MIN_MD, ICON_MAX_16_MD, 0 }; ImFont* UIFontMD = io->Fonts->AddFontFromFileTTF("../../Assets/Editor/Fonts/MaterialIcons-Regular.ttf", 20.f, &icons_config, icon_ranges_md); //TODO: Change to config based assets path io->Fonts->Build(); } From d3dc87accbcdaa7136facab61ddc93446784486c Mon Sep 17 00:00:00 2001 From: Sri Sham Haran Date: Sun, 30 Oct 2022 23:15:41 +0800 Subject: [PATCH 44/44] can assign mesh add bigobj option to command line till we find a better solution --- SHADE_Engine/premake5.lua | 2 +- .../Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp | 2 +- .../Editor/EditorWindow/Inspector/SHEditorComponentView.hpp | 6 ++++-- .../src/Editor/EditorWindow/Inspector/SHEditorInspector.cpp | 1 + SHADE_Engine/src/Serialization/SHSerializationHelper.hpp | 1 + 5 files changed, 8 insertions(+), 4 deletions(-) diff --git a/SHADE_Engine/premake5.lua b/SHADE_Engine/premake5.lua index 18920194..bc1f6a03 100644 --- a/SHADE_Engine/premake5.lua +++ b/SHADE_Engine/premake5.lua @@ -8,7 +8,7 @@ project "SHADE_Engine" pchheader "SHpch.h" pchsource "%{prj.location}/src/SHpch.cpp" staticruntime "off" - + buildoptions{"/bigobj"} files { "%{prj.location}/src/**.h", diff --git a/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp b/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp index 93232917..55d78421 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp +++ b/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp @@ -133,7 +133,7 @@ namespace SHADE auto size = ImGui::GetWindowSize(); auto g = ImGui::GetCurrentContext(); ImGui::SetCursorPosX(size.x - g->Style.FramePadding.x * 15.0f); - if (ImGui::SmallButton(ICON_MD_DESELECT)) + if (ImGui::SmallButton(ICON_MD_CLEAR_ALL)) { auto editor = SHSystemManager::GetSystem(); editor->selectedEntities.clear(); diff --git a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp index 587ffc48..521e1213 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp +++ b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp @@ -348,14 +348,16 @@ namespace SHADE if (ImGui::CollapsingHeader(componentType.get_name().data())) { DrawContextMenu(component); - SHEditorWidgets::DragDropReadOnlyField("Mesh", "Mesh Asset", [component]() + Handle const& mesh = component->GetMesh(); + + SHEditorWidgets::DragDropReadOnlyField("Mesh", std::to_string(SHResourceManager::GetAssetID(mesh).value_or(0)).data(), [component]() { Handle const& mesh = component->GetMesh(); return SHResourceManager::GetAssetID(mesh).value_or(0); }, [component](AssetID const& id) { - //component->SetMesh(SHResourceManager::LoadOrGet(id)); + component->SetMesh(SHResourceManager::LoadOrGet(id)); }, SHDragDrop::DRAG_RESOURCE); } else diff --git a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorInspector.cpp b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorInspector.cpp index 6309d805..c4a86785 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorInspector.cpp +++ b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorInspector.cpp @@ -136,6 +136,7 @@ namespace SHADE { DrawAddComponentButton(eid); DrawAddComponentButton(eid); + DrawAddComponentButton(eid); // Components that require Transforms diff --git a/SHADE_Engine/src/Serialization/SHSerializationHelper.hpp b/SHADE_Engine/src/Serialization/SHSerializationHelper.hpp index bcd378c5..a6f02249 100644 --- a/SHADE_Engine/src/Serialization/SHSerializationHelper.hpp +++ b/SHADE_Engine/src/Serialization/SHSerializationHelper.hpp @@ -239,6 +239,7 @@ namespace YAML YAML::convert::decode(colliderNode, rhs.GetCollider(numColliders++)); } } + return true; } };