diff --git a/SHADE_Application/SHADE_Application.vcxproj b/SHADE_Application/SHADE_Application.vcxproj
index 3d9cfd1a..11bbb48f 100644
--- a/SHADE_Application/SHADE_Application.vcxproj
+++ b/SHADE_Application/SHADE_Application.vcxproj
@@ -60,7 +60,7 @@
SBpch.h
Level4
_DEBUG;%(PreprocessorDefinitions)
- .;..\SHADE_Engine\src;src;%(AdditionalIncludeDirectories)
+ ..\Dependencies\spdlog\include;..\SHADE_Engine\src;src;%(AdditionalIncludeDirectories)
EditAndContinue
Disabled
false
@@ -71,7 +71,7 @@
Windows
true
- WinMainCRTStartup
+ wWinMainCRTStartup
@@ -80,7 +80,7 @@
SBpch.h
Level4
_RELEASE;%(PreprocessorDefinitions)
- .;..\SHADE_Engine\src;src;%(AdditionalIncludeDirectories)
+ ..\Dependencies\spdlog\include;..\SHADE_Engine\src;src;%(AdditionalIncludeDirectories)
Full
true
true
@@ -94,16 +94,20 @@
Windows
true
true
- WinMainCRTStartup
+ wWinMainCRTStartup
+
+
+
Create
+
diff --git a/SHADE_Application/SHADE_Application.vcxproj.filters b/SHADE_Application/SHADE_Application.vcxproj.filters
new file mode 100644
index 00000000..1234632d
--- /dev/null
+++ b/SHADE_Application/SHADE_Application.vcxproj.filters
@@ -0,0 +1,30 @@
+
+
+
+
+ {D9DE78AF-4594-F1A4-CE88-EB7B3A3DE8A8}
+
+
+ {86EEB3D0-7290-DEA6-5B4B-F2FA478C65F7}
+
+
+
+
+ Application
+
+
+
+ Scenes
+
+
+
+
+ Application
+
+
+
+ Scenes
+
+
+
+
\ No newline at end of file
diff --git a/SHADE_Application/premake5.lua b/SHADE_Application/premake5.lua
index 60a87928..c10b1002 100644
--- a/SHADE_Application/premake5.lua
+++ b/SHADE_Application/premake5.lua
@@ -8,7 +8,7 @@ project "SHADE_Application"
pchheader "SBpch.h"
pchsource "%{prj.location}/src/SBpch.cpp"
staticruntime "on"
- entrypoint "WinMainCRTStartup"
+ entrypoint "wWinMainCRTStartup"
system ("windows")
files
@@ -21,8 +21,7 @@ project "SHADE_Application"
includedirs
{
- "%{IncludeDir.GLFW}",
- "%{IncludeDir.GLAD}",
+ "%{IncludeDir.spdlog}/include",
"../SHADE_Engine/src",
"src"
}
diff --git a/SHADE_Application/src/Application/SBApplication.cpp b/SHADE_Application/src/Application/SBApplication.cpp
new file mode 100644
index 00000000..184b9611
--- /dev/null
+++ b/SHADE_Application/src/Application/SBApplication.cpp
@@ -0,0 +1,52 @@
+#include "SBpch.h"
+#include "SBApplication.h"
+
+#ifdef SHEDITOR
+#include "Editor/SHEditor.h"
+#include "Scenes/SBEditorScene.h"
+#endif // SHEDITOR
+
+#include
+#include
+#include
+
+namespace Sandbox
+{
+ bool paused = false;
+ void SBApplication::Initialize
+ (
+ _In_ HINSTANCE hInstance,
+ _In_opt_ HINSTANCE hPrevInstance,
+ _In_ LPWSTR lpCmdLine,
+ _In_ INT nCmdShow
+ )
+ {
+
+ window.Create(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
+
+ #ifdef SHEDITOR
+ #else
+ #endif
+
+ }
+
+ void SBApplication::Update(void)
+ {
+ //TODO: Change true to window is open
+ while (!window.WindowShouldClose())
+ {
+ #ifdef SHEDITOR
+ #else
+ #endif
+ }
+ }
+
+
+ void SBApplication::Exit(void)
+ {
+ #ifdef SHEDITOR
+ #else
+ #endif
+ }
+}
+
diff --git a/SHADE_Application/src/Application/SBApplication.h b/SHADE_Application/src/Application/SBApplication.h
new file mode 100644
index 00000000..a1bf11eb
--- /dev/null
+++ b/SHADE_Application/src/Application/SBApplication.h
@@ -0,0 +1,27 @@
+#ifndef SB_APPLICATION_H
+#define SB_APPLICATION_H
+#include
+//using namespace SHADE;
+
+namespace Sandbox
+{
+ class SBApplication
+ {
+ private:
+ SHADE::SHWindow window;
+ //SHAppConfig config;
+ public:
+ SBApplication() = default;
+ void Initialize(_In_ HINSTANCE /*hInstance*/,
+ _In_opt_ HINSTANCE /*hPrevInstance*/,
+ _In_ LPWSTR /*lpCmdLine*/,
+ _In_ INT /*nCmdShow*/);
+ void Update(void);
+ void Exit(void);
+ private:
+ //std::common_type_t collisionSystemTime, physicsSystemTime, transformSystemTime, audioSystemTime, renderSystemTime, gameTime;
+ //std::chrono::high_resolution_clock::time_point audioStart, audioEnd, transformStart, transformEnd, physicsStart, physicsEnd, collisionStart, collisionEnd, renderStart, renderEnd, gameStart, gameEnd;
+ };
+}
+
+#endif
diff --git a/SHADE_Application/src/Scenes/SBTestScene.cpp b/SHADE_Application/src/Scenes/SBTestScene.cpp
new file mode 100644
index 00000000..46b1bb84
--- /dev/null
+++ b/SHADE_Application/src/Scenes/SBTestScene.cpp
@@ -0,0 +1,48 @@
+#include "SBpch.h"
+#include "SBTestScene.h"
+
+using namespace SHADE;
+
+namespace Sandbox
+{
+
+ void SBTestScene::WindowFocusFunc([[maybe_unused]]void* window, int focused)
+ {
+ if(focused)
+ {
+ }
+ else
+ {
+ }
+ }
+
+ void SBTestScene::Load()
+ {
+ }
+ void SBTestScene::Init()
+ {
+
+ }
+ void SBTestScene::Update(float dt)
+ {
+ (void)dt;
+
+ }
+
+ void SBTestScene::Render()
+ {
+ }
+
+ void SBTestScene::Unload()
+ {
+ }
+
+ void SBTestScene::Free()
+ {
+ //SHSerialization::SerializeScene("resources/scenes/Scene01.SHADE");
+ }
+
+}
+
+
+
diff --git a/SHADE_Application/src/Scenes/SBTestScene.h b/SHADE_Application/src/Scenes/SBTestScene.h
new file mode 100644
index 00000000..6776c671
--- /dev/null
+++ b/SHADE_Application/src/Scenes/SBTestScene.h
@@ -0,0 +1,29 @@
+#pragma once
+
+#include "Scene/SHScene.h"
+#include "Scene/SHSceneManager.h"
+
+namespace Sandbox
+{
+ class SBTestScene : public SHADE::SHScene
+ {
+ private:
+ EntityID camera;
+
+
+ public:
+ virtual void Load();
+ virtual void Init();
+ virtual void Update(float dt);
+ virtual void Render();
+ virtual void Free();
+ virtual void Unload();
+
+ //TODO: Change to new window DO IT IN CPP TOO
+ void WindowFocusFunc(void* window, int focused);
+
+ SBTestScene(void) = default;
+ };
+
+}
+
diff --git a/SHADE_Application/src/WinMain.cpp b/SHADE_Application/src/WinMain.cpp
index 21fb268a..ea1ac5fe 100644
--- a/SHADE_Application/src/WinMain.cpp
+++ b/SHADE_Application/src/WinMain.cpp
@@ -1,7 +1,51 @@
#include "SBpch.h"
+#include
+#include
+#include
+#include "Application/SBApplication.h"
-INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
- PSTR lpCmdLine, INT nCmdShow)
+
+#define _CRTDBG_MAP_ALLOC
+#include
+#include
+
+#ifdef _DEBUG
+#define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )
+// Replace _NORMAL_BLOCK with _CLIENT_BLOCK if you want the
+// allocations to be of _CLIENT_BLOCK type
+#else
+#define DBG_NEW new
+#endif
+
+INT WINAPI wWinMain
+(
+ _In_ HINSTANCE hInstance,
+ _In_opt_ HINSTANCE hPrevInstance,
+ _In_ LPWSTR lpCmdLine,
+ _In_ INT nCmdShow
+)
{
+ const SHADE::SHLogger::Config LOGGER_CONFIG{ .directoryPath = "./logs/" };
+ SHADE::SHLogger::Initialise(LOGGER_CONFIG);
+
+ try
+ {
+ #ifndef SHEDITOR
+ //ShowWindow(::GetConsoleWindow(), SW_HIDE);
+ #endif
+
+ SHLOG_INFO("sup")
+
+ SHADE::SHEngine::Run(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
+ _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
+ }
+ catch(...)
+ {
+ SHADE::SHExceptionHandler::HandleException(std::current_exception());
+ SHADE::SHLogger::Shutdown();
+ }
+
+ SHADE::SHLogger::Shutdown();
+
return 0;
}
\ No newline at end of file
diff --git a/SHADE_Engine/SHADE_Engine.vcxproj b/SHADE_Engine/SHADE_Engine.vcxproj
index ba1be338..aa4e8ff4 100644
--- a/SHADE_Engine/SHADE_Engine.vcxproj
+++ b/SHADE_Engine/SHADE_Engine.vcxproj
@@ -57,8 +57,8 @@
Use
SHpch.h
Level4
- _LIB;_GLFW_INCLUDE_NONE;MSDFGEN_USE_CPP11;_DEBUG;%(PreprocessorDefinitions)
- src;..\Dependencies\assimp\include;..\Dependencies\imgui;..\Dependencies\imguizmo;..\Dependencies\imnodes;..\Dependencies\msdf;..\Dependencies\msdf\msdfgen;..\Dependencies\spdlog\include;..\Dependencies\tracy;..\Dependencies\VMA\include;..\Dependencies\yamlcpp\include;..\Dependencies\ktx\include;..\Dependencies\RTTR\include;..\Dependencies\reactphysics3d\include;$(VULKAN_SDK)\include;%(AdditionalIncludeDirectories)
+ _LIB;_GLFW_INCLUDE_NONE;MSDFGEN_USE_CPP11;NOMINMAX;_DEBUG;%(PreprocessorDefinitions)
+ src;..\Dependencies\assimp\include;..\Dependencies\imgui;..\Dependencies\imguizmo;..\Dependencies\imnodes;..\Dependencies\msdf;..\Dependencies\msdf\msdfgen;..\Dependencies\spdlog\include;..\Dependencies\tracy;..\Dependencies\VMA\include;..\Dependencies\yamlcpp\include;..\Dependencies\ktx\include;..\Dependencies\RTTR\include;..\Dependencies\reactphysics3d\include;$(VULKAN_SDK)\include;$(VULKAN_SDK)\Source\SPIRV-Reflect;%(AdditionalIncludeDirectories)
EditAndContinue
Disabled
false
@@ -71,7 +71,7 @@
true
- vulkan-1.lib;assimp-vc142-mtd.lib;ktxd.lib;librttr_core_d.lib;%(AdditionalDependencies)
+ vulkan-1.lib;shaderc_shared.lib;assimp-vc142-mtd.lib;ktxd.lib;librttr_core_d.lib;%(AdditionalDependencies)
libs;$(VULKAN_SDK)\Lib;..\Dependencies\assimp\lib\Debug;..\Dependencies\assimp\lib\Release;..\Dependencies\RTTR\lib;..\Dependencies\ktx\lib\Debug;..\Dependencies\ktx\lib\Release;%(AdditionalLibraryDirectories)
@@ -80,8 +80,8 @@
Use
SHpch.h
Level4
- _LIB;_GLFW_INCLUDE_NONE;MSDFGEN_USE_CPP11;_RELEASE;%(PreprocessorDefinitions)
- src;..\Dependencies\assimp\include;..\Dependencies\imgui;..\Dependencies\imguizmo;..\Dependencies\imnodes;..\Dependencies\msdf;..\Dependencies\msdf\msdfgen;..\Dependencies\spdlog\include;..\Dependencies\tracy;..\Dependencies\VMA\include;..\Dependencies\yamlcpp\include;..\Dependencies\ktx\include;..\Dependencies\RTTR\include;..\Dependencies\reactphysics3d\include;$(VULKAN_SDK)\include;%(AdditionalIncludeDirectories)
+ _LIB;_GLFW_INCLUDE_NONE;MSDFGEN_USE_CPP11;NOMINMAX;_RELEASE;%(PreprocessorDefinitions)
+ src;..\Dependencies\assimp\include;..\Dependencies\imgui;..\Dependencies\imguizmo;..\Dependencies\imnodes;..\Dependencies\msdf;..\Dependencies\msdf\msdfgen;..\Dependencies\spdlog\include;..\Dependencies\tracy;..\Dependencies\VMA\include;..\Dependencies\yamlcpp\include;..\Dependencies\ktx\include;..\Dependencies\RTTR\include;..\Dependencies\reactphysics3d\include;$(VULKAN_SDK)\include;$(VULKAN_SDK)\Source\SPIRV-Reflect;%(AdditionalIncludeDirectories)
Full
true
true
@@ -97,21 +97,169 @@
true
- vulkan-1.lib;assimp-vc142-mt.lib;ktx.lib;librttr_core.lib;%(AdditionalDependencies)
+ vulkan-1.lib;shaderc_shared.lib;assimp-vc142-mt.lib;ktx.lib;librttr_core.lib;%(AdditionalDependencies)
libs;$(VULKAN_SDK)\Lib;..\Dependencies\assimp\lib\Debug;..\Dependencies\assimp\lib\Release;..\Dependencies\RTTR\lib;..\Dependencies\ktx\lib\Debug;..\Dependencies\ktx\lib\Release;%(AdditionalLibraryDirectories)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Create
+
+
+
+
diff --git a/SHADE_Engine/SHADE_Engine.vcxproj.filters b/SHADE_Engine/SHADE_Engine.vcxproj.filters
index 6ca01248..a9b0f4c4 100644
--- a/SHADE_Engine/SHADE_Engine.vcxproj.filters
+++ b/SHADE_Engine/SHADE_Engine.vcxproj.filters
@@ -4,19 +4,578 @@
{DBC7D3B0-C769-FE86-B024-12DB9C6585D7}
+
+ {7FF59BF8-EB80-09BD-F491-8CB1609C65BD}
+
+
+ {340D0110-201D-ADE0-89D6-11FF75059C79}
+
+
+ {EBFC8BDC-D7F6-B42E-C063-4B3FACFC1A9B}
+
+
+ {6CD692F2-D80D-DB89-E117-3FAD4DCE0183}
+
+
+ {B3E3FAFD-9FDD-2350-884A-BA6074E389BC}
+
+
+ {8A8E2B37-7646-6D84-DF4D-46E0CB240875}
+
+
+ {1653CE33-0220-293F-2B39-17E717655ECD}
+
+
+ {92C817CE-7EC1-3620-A7F3-1BA5934B162C}
+
+
+ {17C745C0-83DD-4356-CC54-CF7738AA14DE}
+
+
+ {51443AC7-3D28-FB1C-A688-F56F928BE59E}
+
+
+ {573A6CF2-43C9-F5BB-ECE7-09B7D8550662}
+
+
+ {08DBDC43-F4D3-FB95-1D06-E11A095EDBA1}
+
+
+ {4AD5CA42-3664-540C-DF82-6807CBF064B2}
+
+
+ {FB5EE099-67EA-4D5E-70FB-D052DC05AA5E}
+
+
+ {BA26540B-263D-52A1-6FB4-DDC2DB092329}
+
+
+ {4B204703-3704-0859-A064-02AC8C67F2DA}
+
+
+ {EBA1D3FF-D75C-C3AB-8014-3CF66CAE0D3C}
+
+
+ {8CDBA7C9-F8E8-D5AF-81CF-D19AEDDBA166}
+
+
+ {2460C057-1070-6C28-7929-D14665585BC1}
+
+
+ {FBD334F8-67EA-328E-B061-BEAF1CB70316}
+
+
+ {1DD51CAD-8960-8A71-9271-0D66FE7BE671}
+
+
+ {57DAB30C-4369-3DD6-EC87-51D1D8F54D7C}
+
+
+ {9C0DAFD9-086F-8CE7-91DC-D299FD3CC3A6}
+
+
+ {EF2D07CC-DB26-261E-0459-0BA3F0B0052A}
+
+
+ {3AEF06DD-A6D2-151D-AFD5-43591B38DC6D}
+
+
+ {245F5AB0-1085-2417-F9CA-A9E2E58F49E3}
+
+
+ {03DB39DE-EFBE-FA33-581F-F5864422E5B5}
+
+
+ {576DF841-4392-47C2-6CDD-2C52586146E0}
+
+
+ {75F29FE5-6102-4CB6-CABB-B0D4B6EA3A4F}
+
+
+ {5BAB2A92-478F-EBE7-B0EF-E53A9CF2D569}
+
+
+ {B3B14D12-9FC1-F9E2-087B-5E01F4A9E87B}
+
+
+ {AFF4887C-9B2B-8A0D-4418-7010302E060F}
+
+
+ {F1B75745-5D6D-D03A-E661-CA115216C73E}
+
+
+ {AC05897C-983C-8A0D-4129-70102D3F060F}
+
+
+ {ED6CDF9B-D939-3AA7-0253-284FEE7E6F35}
+
+
+ {B3F7140E-1F0C-3DBF-E88D-E01E546139F0}
+
+
+ {16CF2D0E-82E3-55BF-4B65-F91EB73852F0}
+
+
+ Engine\ECS_Base\Components
+
+
+ Engine\ECS_Base\Components
+
+
+ Engine\ECS_Base\Entity
+
+
+ Engine\ECS_Base\General
+
+
+ Engine\ECS_Base\General
+
+
+ Engine\ECS_Base\General
+
+
+ Engine\ECS_Base\General
+
+
+ Engine\ECS_Base\General
+
+
+ Engine\ECS_Base
+
+
+ Engine\ECS_Base\System
+
+
+ Engine\ECS_Base\System
+
+
+ Engine\ECS_Base\System
+
+
+ Engine\ECS_Base\System
+
Engine
+
+ Filesystem
+
+
+ Graphics\Buffers
+
+
+ Graphics\Commands
+
+
+ Graphics\Commands
+
+
+ Graphics\Commands
+
+
+ Graphics\Debugging
+
+
+ Graphics\Debugging
+
+
+ Graphics\Debugging
+
+
+ Graphics\Descriptors
+
+
+ Graphics\Descriptors
+
+
+ Graphics\Descriptors
+
+
+ Graphics\Descriptors
+
+
+ Graphics\Descriptors
+
+
+ Graphics\Devices
+
+
+ Graphics\Devices
+
+
+ Graphics\Devices
+
+
+ Graphics\Framebuffer
+
+
+ Graphics\Images
+
+
+ Graphics\Images
+
+
+ Graphics\Images
+
+
+ Graphics\Instance
+
+
+ Graphics\MiddleEnd\Interface
+
+
+ Graphics\MiddleEnd\Interface
+
+
+ Graphics\MiddleEnd\PerFrame
+
+
+ Graphics\MiddleEnd\PerFrame
+
+
+ Graphics\MiddleEnd\Shaders
+
+
+ Graphics\MiddleEnd\Shaders
+
+
+ Graphics\MiddleEnd\Shaders
+
+
+ Graphics\Pipeline
+
+
+ Graphics\Pipeline
+
+
+ Graphics\Pipeline
+
+
+ Graphics\Pipeline
+
+
+ Graphics\Pipeline
+
+
+ Graphics\Pipeline
+
+
+ Graphics\Queues
+
+
+ Graphics\RenderGraph
+
+
+ Graphics\Renderpass
+
+
+ Graphics\Renderpass
+
+
+ Graphics\Renderpass
+
+
+ Graphics\Renderpass
+
+
+ Graphics\Renderpass
+
+
+ Graphics
+
+
+ Graphics
+
+
+ Graphics
+
+
+ Graphics\Shaders\BlockInterface
+
+
+ Graphics\Shaders
+
+
+ Graphics\Shaders
+
+
+ Graphics\Shaders\spirv-reflect
+
+
+ Graphics\Swapchain
+
+
+ Graphics\Swapchain
+
+
+ Graphics\Synchronization
+
+
+ Graphics\Synchronization
+
+
+ Graphics\VertexDescriptors
+
+
+ Graphics\Windowing
+
+
+ Graphics\Windowing
+
+
+ Graphics\Windowing\Surface
+
+
+ Math
+
+
+ Math
+
+
+ Math
+
+
+ Math
+
+
+ Math\Vector
+
+
+ Math\Vector
+
+
+ Math\Vector
+
+
+ Meta
+
+
+ Resource
+
+
+ Resource
+
+
+ Resource
+
-
+
+ Scene
+
+
+ Scene
+
+
+ Tools
+
+
+ Tools
+
+
+ Tools
+
+
+ Tools
+
+
+ Engine\ECS_Base\Components
+
+
+ Engine\ECS_Base\Components
+
+
+ Engine\ECS_Base\Entity
+
+
+ Engine\ECS_Base\System
+
+
+ Engine\ECS_Base\System
+
+
+ Engine\ECS_Base\System
+
Engine
+
+ Filesystem
+
+
+ Graphics\Buffers
+
+
+ Graphics\Commands
+
+
+ Graphics\Commands
+
+
+ Graphics\Debugging
+
+
+ Graphics\Debugging
+
+
+ Graphics\Debugging
+
+
+ Graphics\Descriptors
+
+
+ Graphics\Descriptors
+
+
+ Graphics\Descriptors
+
+
+ Graphics\Descriptors
+
+
+ Graphics\Descriptors
+
+
+ Graphics\Devices
+
+
+ Graphics\Devices
+
+
+ Graphics\Devices
+
+
+ Graphics\Framebuffer
+
+
+ Graphics\Images
+
+
+ Graphics\Images
+
+
+ Graphics\Instance
+
+
+ Graphics\MiddleEnd\Interface
+
+
+ Graphics\MiddleEnd\Interface
+
+
+ Graphics\MiddleEnd\PerFrame
+
+
+ Graphics\MiddleEnd\PerFrame
+
+
+ Graphics\MiddleEnd\Shaders
+
+
+ Graphics\MiddleEnd\Shaders
+
+
+ Graphics\Pipeline
+
+
+ Graphics\Pipeline
+
+
+ Graphics\Pipeline
+
+
+ Graphics\Pipeline
+
+
+ Graphics\Queues
+
+
+ Graphics\RenderGraph
+
+
+ Graphics\Renderpass
+
+
+ Graphics\Renderpass
+
+
+ Graphics\Renderpass
+
+
+ Graphics
+
+
+ Graphics
+
+
+ Graphics\Shaders\BlockInterface
+
+
+ Graphics\Shaders
+
+
+ Graphics\Shaders
+
+
+ Graphics\Shaders\spirv-reflect
+
+
+ Graphics\Swapchain
+
+
+ Graphics\Synchronization
+
+
+ Graphics\Synchronization
+
+
+ Graphics\VertexDescriptors
+
+
+ Graphics\Windowing
+
+
+ Graphics\Windowing
+
+
+ Graphics\Windowing\Surface
+
+
+ Math
+
+
+ Math
+
+
+ Math
+
+
+ Math\Vector
+
+
+ Math\Vector
+
+
+ Math\Vector
+
+
+ Resource
+
-
+
+ Scene
+
+
+ Tools
+
+
+ Tools
+
+
+ Tools
+
\ No newline at end of file
diff --git a/SHADE_Engine/premake5.lua b/SHADE_Engine/premake5.lua
index 39d5039f..8ed16abd 100644
--- a/SHADE_Engine/premake5.lua
+++ b/SHADE_Engine/premake5.lua
@@ -34,7 +34,8 @@ project "SHADE_Engine"
"%{IncludeDir.ktx}/include",
"%{IncludeDir.RTTR}/include",
"%{IncludeDir.reactphysics3d}/include",
- "%{IncludeDir.VULKAN}/include"
+ "%{IncludeDir.VULKAN}/include",
+ "%{IncludeDir.VULKAN}/Source/SPIRV-Reflect"
}
libdirs
@@ -56,14 +57,16 @@ project "SHADE_Engine"
"reactphysics3d",
"imgui",
"spdlog",
- "vulkan-1.lib"
+ "vulkan-1.lib",
+ "shaderc_shared.lib"
}
defines
{
"_LIB",
"_GLFW_INCLUDE_NONE",
- "MSDFGEN_USE_CPP11"
+ "MSDFGEN_USE_CPP11",
+ "NOMINMAX"
}
flags
diff --git a/SHADE_Engine/src/Engine/ECS_Base/Components/SHComponent.cpp b/SHADE_Engine/src/Engine/ECS_Base/Components/SHComponent.cpp
new file mode 100644
index 00000000..b544df72
--- /dev/null
+++ b/SHADE_Engine/src/Engine/ECS_Base/Components/SHComponent.cpp
@@ -0,0 +1,9 @@
+#include "SHpch.h"
+#include "SHComponent.h"
+
+namespace SHADE
+{
+ SHComponent::~SHComponent()
+ {
+ }
+}
diff --git a/SHADE_Engine/src/Engine/ECS_Base/Components/SHComponent.h b/SHADE_Engine/src/Engine/ECS_Base/Components/SHComponent.h
new file mode 100644
index 00000000..c9c5e6f1
--- /dev/null
+++ b/SHADE_Engine/src/Engine/ECS_Base/Components/SHComponent.h
@@ -0,0 +1,121 @@
+/*********************************************************************
+ * \file SHComponent.h
+ * \author Daniel Chua Yee Chen
+ * \brief Declaration for the Component abstract base class.
+ *
+ * \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.
+ *********************************************************************/
+
+
+#ifndef SH_COMPONENT_H
+#define SH_COMPONENT_H
+
+#include "SHpch.h"
+#include "../SHECSMacros.h"
+
+namespace SHADE
+{
+
+ class SHComponentManager;
+
+ class SHComponent
+ {
+ friend SHComponentManager;
+
+ private:
+ //The ID of the entity this component belongs to.
+ EntityID entityID;
+ //Whether this entity ID has been set once.
+ //This prevents the Set function from being able to change the entityID once it has been set
+
+
+ protected:
+
+ /*!*************************************************************************
+ * \brief Construct a new SHComponent object
+ * Protected default constructor to make this an abstract base class.
+ ***************************************************************************/
+ SHComponent()
+ :entityID(0),isActive(true)
+ {
+ }
+
+ SHComponent(SHComponent const& other)
+ :entityID(other.entityID), isActive(other.isActive)
+ {
+ }
+
+ public:
+ //Whether or not this component is active.
+ //Systems using this component should are responsible for checking the active state of the component before running their functionality.
+ bool isActive;
+
+ /*!*************************************************************************
+ * \brief
+ * Getter function for the entityID
+ * \return uint32_t
+ * The entityID that this component belongs to.
+ ***************************************************************************/
+ uint32_t GetEID()const
+ {
+ return this->entityID;
+ }
+
+
+ /*!*************************************************************************
+ * \brief Destroy the SHComponent object
+ * Default destructor for Component Base class
+ ***************************************************************************/
+ virtual ~SHComponent();
+
+ /*!*************************************************************************
+ * \brief
+ * A function that is called when the entity changes its parent.
+ * This can remain empty if nothing has to be done before the parent changes.
+ * This does not change the component that the entity belongs to
+ * The old parent is not passed in here as the old parent might be the root node
+ * in which case there will be no parent.
+ * If needed, the old parent should be deduced using this entityID
+ * \param newParent
+ * EntityID of the new parent.
+ ***************************************************************************/
+ virtual void ChangeParent(EntityID newParent)
+ {
+ (void)newParent;
+ }
+
+ /**************************************************************************
+ * \brief
+ * This is an overloaded function of Change parent when the entity
+ * changes its parent to the root node. (No parent)
+ *
+ ***************************************************************************/
+ virtual void ChangeParent()
+ {
+ }
+
+
+ virtual void OnDestroy()
+ {
+ }
+
+
+ virtual void OnCreate()
+ {
+ }
+
+ SHComponent& operator=(SHComponent const& other)
+ {
+ this->entityID = other.GetEID();
+ this->isActive = other.isActive;
+ return *this;
+ }
+
+
+
+
+ };
+}
+#endif
diff --git a/SHADE_Engine/src/Engine/ECS_Base/Components/SHComponentGroup.cpp b/SHADE_Engine/src/Engine/ECS_Base/Components/SHComponentGroup.cpp
new file mode 100644
index 00000000..3ccb7778
--- /dev/null
+++ b/SHADE_Engine/src/Engine/ECS_Base/Components/SHComponentGroup.cpp
@@ -0,0 +1,136 @@
+/*********************************************************************
+ * \file SHComponent.h
+ * \author Daniel Chua Yee Chen
+ * \brief Implementation for the SHComponentGroup class.
+ * The Component Group aids the engine to sort the components to align
+ * different component type’s data that corresponds to a single entity
+ * in the same index. The component group also ensure that all components
+ * data belonging to the group is moved to the start of the dense array.
+ *
+ * \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 "SHComponentGroup.h"
+#include "../System/SHComponentManager.h"
+
+
+namespace SHADE
+{
+ SHComponentGroup::SHComponentGroup()
+ :ownershipType(OWNERSHIP_TYPE::FULL_OWNERSHIP)
+ {
+ componentTypeIDs.reserve(MAX_EID);
+ ownedComponentTypes.reserve(MAX_EID);
+ entityInGroup.reserve(MAX_EID);
+ }
+
+ EntityIndex SHComponentGroup::size() noexcept
+ {
+ return (EntityIndex)entityInGroup.size();
+ }
+
+ bool SHComponentGroup::IsEntityInGroup(EntityID entityID) noexcept
+ {
+ for (auto const& eid : entityInGroup)
+ {
+ if (entityID == eid)
+ {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ bool SHComponentGroup::RemoveEntity(EntityID entityID) noexcept
+ {
+ if (!IsEntityInGroup(entityID))
+ {
+ // This entity has not been added to the group. Ignore it.
+ return false;
+ }
+
+ //This entity is in the group.
+ //Move the placement of the components in all owned component types to the relevant position and remove it from the group.
+ for (auto const& ownedID : ownedComponentTypes)
+ {
+ if (SHComponentManager::ComponentCount_ID(ownedID) > 2)
+ {
+ // There are components that do not belong in the group. Need to swap to the last element
+ SHComponentManager::SwapInDenseByIndexHash_ID((EntityIndex)entityInGroup.size() - 1, entityID, ownedID);
+ }
+ }
+
+ for (std::vector::iterator it = entityInGroup.begin(); it != entityInGroup.end(); ++it)
+ {
+ if (*it == entityID)
+ {
+ entityInGroup.erase(it);
+ break;
+ }
+ }
+
+ return true;
+ }
+
+ void SHComponentGroup::Clear() noexcept
+ {
+ entityInGroup.clear();
+
+ }
+
+ bool SHComponentGroup::AddComponentCheck(EntityID entityID, uint32_t componentTypeID) noexcept
+ {
+ if (IsEntityInGroup(entityID))
+ {
+ return false;
+ }
+
+ //uint32_t componentID = SHFamilyID::template GetID();
+
+ //Loops to check if this is one of the owned component type
+ for (auto const& id : componentTypeIDs)
+ {
+ //found it
+ if (id == componentTypeID)
+ {
+ for (auto const& typeID : componentTypeIDs)
+ {
+ if (typeID != componentTypeID && !SHComponentManager::HasComponent_ID(entityID, typeID))
+ {
+ //This entity does not contain all other component types in this group so we don't do anything yet
+ return false;
+ }
+ }
+ //This entity contains all required component types. Add to group and swap in dense
+ //auto& dense = SHComponentManager::GetDense();
+
+ //Loop through all the owned component and sort them.
+ for (auto const& ownedID : ownedComponentTypes)
+ {
+ if (SHComponentManager::ComponentCount_ID(ownedID) > entityInGroup.size() + 1)
+ {
+ // There are components that do not belong in the group. Need to swap to the last element
+ SHComponentManager::SwapInDenseByIndexHash_ID((EntityIndex)entityInGroup.size(), entityID, ownedID);
+
+ }
+ }
+
+ // If dense.size() == entityInGroup.size() + 1.
+ // There is no component that is not in this group for this component type.
+ // Hence no sorting required.
+
+ //Add this entityID to group
+ entityInGroup.push_back(entityID);
+
+ return true;
+ }
+ }
+ //This component type is not in this group.
+ return false;
+ }
+
+}
+
diff --git a/SHADE_Engine/src/Engine/ECS_Base/Components/SHComponentGroup.h b/SHADE_Engine/src/Engine/ECS_Base/Components/SHComponentGroup.h
new file mode 100644
index 00000000..3f67aff0
--- /dev/null
+++ b/SHADE_Engine/src/Engine/ECS_Base/Components/SHComponentGroup.h
@@ -0,0 +1,185 @@
+/*********************************************************************
+ * \file SHComponent.h
+ * \author Daniel Chua Yee Chen
+ * \brief Definition for the SHComponentGroup class.
+ * The Component Group aids the engine to sort the components to align
+ * different component type’s data that corresponds to a single entity
+ * in the same index. The component group also ensure that all components
+ * data belonging to the group is moved to the start of the dense array.
+ *
+ * \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.
+ *********************************************************************/
+
+
+#ifndef SH_COMPONENT_GROUP
+#define SH_COMPONENT_GROUP
+
+#include "../SHECSMacros.h"
+#include "../General/SHFamily.h"
+#include "SHComponent.h"
+
+#include
+#include
+#include
+
+namespace SHADE
+{
+ enum class OWNERSHIP_TYPE
+ {
+ FULL_OWNERSHIP = 0,
+ PARTIAL_OWNERSHIP,
+ NON_OWNERSHIP,
+ OWNERSHIP_MAX
+ };
+
+
+ //template
+ class SHComponentGroup
+ {
+ public:
+
+
+ //This vector store the Entity IDs of all entity that belongs to this group.
+ std::vector entityInGroup;
+
+
+ //template<>
+ //bool CheckAddComponent();
+ SHComponentGroup();
+ ~SHComponentGroup() = default;
+
+ //friends SHComponentManager to allow ECSCore to create componentgroups
+ friend class SHComponentManager;
+
+ /**************************************************************************
+ * \brief
+ * Get the number of entity in the group.
+ * \return
+ * Number of entity in the group.
+ ***************************************************************************/
+ EntityIndex size() noexcept;
+
+ /**************************************************************************
+ * \brief
+ * Check if a entity is already in the group.
+ * \param entityID
+ * The entity ID of the entity
+ * \return
+ * true if the entity belongs to the group
+ ***************************************************************************/
+ bool IsEntityInGroup(EntityID entityID) noexcept;
+
+
+ /*!*************************************************************************
+ * \brief
+ * Checks whether the entity has fulfilled the requirements to be added into
+ * the Component Group after adding a specified Component Type.
+ * @tparam T
+ * Component type to be added
+ * \param entityID
+ * EntityID of the entity to be added
+ ***************************************************************************/
+ bool AddComponentCheck(EntityID entityID, uint32_t componentTypeID) noexcept;
+
+
+ /*!*************************************************************************
+ * \brief
+ * Check if the Component type is in the component group and if the entity is in the group
+ * Remove it from the group if found.
+ * This does not handle the removal from the dense array in the sparse set.
+ * @tparam T
+ * Component type to be removed
+ * \param entityID
+ * EntityID of the entity
+ ***************************************************************************/
+ template
+ std::enable_if_t, bool> RemoveComponentCheck(EntityID entityID) noexcept
+ {
+
+ if (!IsEntityInGroup(entityID))
+ {
+ // This entity has not been added to the group. Ignore it.
+ return false;
+ }
+ bool typeFound = false;
+ uint32_t componentID = SHFamilyID::template GetID();
+ for (auto const& id : componentTypeIDs)
+ {
+ if (id == componentID)
+ {
+ typeFound = true;
+ break;
+ }
+ }
+ if (typeFound == false)
+ {
+ return false; //This type is not something this group needs to care about.
+ }
+
+ //This entity is in the group.
+ //Move the placement of the components in all owned component types to the relevant position and remove it from the group.
+ for (auto const& ownedID : ownedComponentTypes)
+ {
+ if (SHComponentManager::ComponentCount_ID(ownedID) > entityInGroup.size() + 1)
+ {
+ // There are components that do not belong in the group. Need to swap to the last element
+ SHComponentManager::SwapInDenseByIndexHash_ID((EntityIndex)entityInGroup.size() - 1, entityID, ownedID);
+ }
+ }
+
+ for (std::vector::iterator it = entityInGroup.begin(); it != entityInGroup.end(); ++it)
+ {
+ if (*it == entityID)
+ {
+ entityInGroup.erase(it);
+ break;
+ }
+ }
+
+ return true;
+
+ }
+
+ /*!*************************************************************************
+ * \brief
+ * Checks if this entity is in the Component Group and remove it if found.
+ * This does not handle the removal from the dense array in the sparse set.
+ * \param entityID
+ * EntityID of the entity
+ ***************************************************************************/
+ bool RemoveEntity(EntityID entityID) noexcept;
+
+
+ /*!*************************************************************************
+ * \brief
+ * Resets the Component Group by clearing all entity in group.
+ * This will not change the Component Types that belong in the group but
+ * only clear the entity that belongs to the group.
+ * This is used for scene transition where all entities are cleared.
+ ***************************************************************************/
+ void Clear() noexcept;
+
+
+ private:
+ OWNERSHIP_TYPE ownershipType;
+
+ protected:
+
+ //This vector stores all IDs of all the component type that belongs to this group.
+ //This will be assigned when the group gets created and used by the group themselves when they for add/remove components.
+ std::vector componentTypeIDs;
+
+ //This vector stores the IDs of all the component type that this group owns.
+ //Each component type can only be owned by one group.
+ std::vector ownedComponentTypes;
+
+
+
+ };
+
+}
+
+
+#endif
diff --git a/SHADE_Engine/src/Engine/ECS_Base/Entity/SHEntity.cpp b/SHADE_Engine/src/Engine/ECS_Base/Entity/SHEntity.cpp
new file mode 100644
index 00000000..6005fb01
--- /dev/null
+++ b/SHADE_Engine/src/Engine/ECS_Base/Entity/SHEntity.cpp
@@ -0,0 +1,74 @@
+/*********************************************************************
+ * \file SHEntity.cpp
+ * \author Daniel Chua Yee Chen
+ * \brief Definition of function used in SHEntity class.
+ *
+ * \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 "SHEntity.h"
+#include "../System/SHEntityManager.h"
+//#include "Scene/SHSceneGraph.h"
+#include "../System/SHComponentManager.h"
+
+namespace SHADE
+{
+
+ SHEntity::SHEntity()
+ :entityID(),isActive(true)
+ {
+
+ }
+
+ SHEntity::~SHEntity()
+ {
+
+ //SHEntityManager::RemoveEntity(this->entityID);
+ }
+
+ EntityID SHEntity::GetEID() noexcept
+ {
+ return this->entityID;
+ }
+
+ void SHEntity::SetActive(bool active) noexcept
+ {
+ isActive = active;
+ SHComponentManager::SetActive(entityID, active);
+ }
+
+
+
+ void SHEntity::SetParent(SHEntity* newParent) noexcept
+ {
+ (void)newParent;
+ //TODO
+ }
+
+ void SHEntity::SetParent(EntityID newParentID) noexcept
+ {
+ (void)newParentID;
+ //TODO
+ }
+
+ SHEntity* SHEntity::GetParent() noexcept
+ {
+ //TODO
+ return nullptr;
+ }
+
+
+ std::vectorconst& SHEntity::GetChildren() noexcept
+ {
+ //TODO
+ return std::vector{};
+ }
+
+ std::vectorconst& SHEntity::GetChildrenID() noexcept
+ {
+ return std::vector{};
+ }
+
+}
diff --git a/SHADE_Engine/src/Engine/ECS_Base/Entity/SHEntity.h b/SHADE_Engine/src/Engine/ECS_Base/Entity/SHEntity.h
new file mode 100644
index 00000000..d499042c
--- /dev/null
+++ b/SHADE_Engine/src/Engine/ECS_Base/Entity/SHEntity.h
@@ -0,0 +1,163 @@
+/*********************************************************************
+ * \file SHEntity.h
+ * \author Daniel Chua Yee Chen
+ * \brief Declaration for the Entity abstract base class.
+ *
+ * \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.
+ *********************************************************************/
+
+#ifndef SH_ENTITY_H
+#define SH_ENTITY_H
+
+#include "../SHECSMacros.h"
+#include "../Components/SHComponent.h"
+#include "../System/SHComponentManager.h"
+//#include "../../Scene/SHSceneNode.h"
+
+
+
+namespace SHADE
+{
+ class SHComponentManager;
+ class SHEntityManager;
+
+ class SHEntity
+ {
+ public:
+
+
+ /**************************************************************************
+ * Friends with SHEntityManger.
+ * This allows SHEntityManager to generate a unique entityID for the entity
+ * upon creation.
+ * .
+ ***************************************************************************/
+ friend SHEntityManager;
+
+
+ /*!*************************************************************************
+ * \brief Construct a new SHEntity object
+ * Default constructor for the Entity Object.
+ * Entities are given their entityID here.
+ ***************************************************************************/
+ SHEntity();
+
+ /*!*************************************************************************
+ * \brief Destroy the SHEntity object
+ * Default destructor for the Entity object.
+ * Removes the entityID and queue it for recycling.
+ ***************************************************************************/
+ virtual ~SHEntity();
+
+
+ /*!*************************************************************************
+ * \brief Get the Component object
+ * A templated GetComponent_s function that calls GetComponent_s from SHComponentManager.
+ * This is for ease of use.
+ * @tparam T
+ * The type of the Component we are trying to get.
+ * \return
+ * A pointer to the Component we are trying to get.
+ * Returns nullptr if the entity does not have such Component.
+ ***************************************************************************/
+ template
+ std::enable_if_t, T*> GetComponent() noexcept
+ {
+
+ return SHComponentManager::GetComponent_s(entityID);
+ //return nullptr;
+ }
+
+
+ /*!*************************************************************************
+ * \brief
+ * Getter function for the entityID
+ * \return uint32_t
+ * The entityID of this Entity object.
+ ***************************************************************************/
+ EntityID GetEID() noexcept;
+
+ /*!*************************************************************************
+ * \brief Set the Active object
+ * Sets the isActive of all Components in this entity.
+ * This is done through SHComponentManager and this function is for ease of use.
+ * If derived classes of Entity overloads this function, they are expected to
+ * call this function using SHEntity::SetActive(active) to change the active of
+ * all components
+ * \param active
+ * The active state to change all components in this entity.
+ ***************************************************************************/
+ virtual void SetActive(bool active) noexcept;
+
+
+
+ /**************************************************************************
+ * \brief
+ * Change the parent of the entity object in the scene graph.
+ * This command will be stored in a queue and only applied when
+ * SHSceneGraph::UpdateHierachy is called.
+ * \param newParent
+ * A pointer to the new parent entity.
+ * Pass a nullptr to attach this entity to the root node instead.
+ ***************************************************************************/
+ void SetParent(SHEntity* newParent = nullptr) noexcept;
+
+
+ /**************************************************************************
+ * \brief
+ * Change the parent of the entity object in the scene graphj.
+ * This command will be stored in a queue and only applied when
+ * SHSceneGraph::UpdateHierachy is called
+ * This is the overloaded version of the function that takes in a
+ * EntityID instead. This cannot be used to attach to the root node.
+ * \param newParentID
+ * The entityID of the new parent.
+ ***************************************************************************/
+ void SetParent(EntityID newParentID) noexcept;
+
+ /**************************************************************************
+ * \brief
+ * Get a pointer to the parent entity.
+ * \return
+ * Returns a pointer to the parent entity.
+ * Returns a nullptr if the parent node is the root node.
+ ***************************************************************************/
+ SHEntity* GetParent() noexcept;
+
+
+ /**************************************************************************
+ * \brief
+ * Get a vector of SHEntity pointers of the children belonging to this entity.
+ * \return
+ * Return a vector of SHEntity pointers of the children belonging to this entity.
+ ***************************************************************************/
+ std::vectorconst& GetChildren() noexcept;
+
+ /**************************************************************************
+ * \brief
+ * Get a vector of EntityID of the children belonging to this entity.
+ * \return
+ * return a vector of EntityID of the children belonging to this entity.
+ ***************************************************************************/
+ std::vectorconst& GetChildrenID() noexcept;
+
+
+ std::string name;
+ bool isActive;
+
+
+ private:
+ //The identifier of the entity.
+ //This is split into 2 x 16-bits that represents version and index respectively
+ //Index is used by the engine to index the entity.
+ //Version is used by the engine to recycle the index of the entity.
+ EntityID entityID;
+
+
+ };
+}
+
+
+#endif
diff --git a/SHADE_Engine/src/Engine/ECS_Base/General/SHFamily.h b/SHADE_Engine/src/Engine/ECS_Base/General/SHFamily.h
new file mode 100644
index 00000000..f97bbe0e
--- /dev/null
+++ b/SHADE_Engine/src/Engine/ECS_Base/General/SHFamily.h
@@ -0,0 +1,88 @@
+/*********************************************************************
+ * \file SHFamily.h
+ * \author Daniel Chua Yee Chen
+ * \brief Declaration for the SHFamily template class.
+ * This class is to create a unique identifier for each derived class type.
+ * Example: Each Component type (SHTransformComponent / SHRenderableComponent)
+ * will have a different identifier generated by this class.
+ *
+ * \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.
+ *********************************************************************/
+
+#ifndef SH_FAMILY_H
+#define SH_FAMILY_H
+
+#include "../SHECSMacros.h"
+
+
+namespace SHADE
+{
+ template
+ class SHFamilyID
+ {
+ private:
+ //this is used to keep track of the new current ID to be assign to a new Derived class type.
+ static ComponentTypeID currentID;
+
+ /*!*************************************************************************
+ * \brief Construct a new SHFamilyID object
+ * Private constructor.
+ * No objects of this type should be made.
+ * Only use the static functions of this class
+ ***************************************************************************/
+ SHFamilyID()
+ {
+ }
+
+ /*!*************************************************************************
+ * \brief Destroy the SHFamilyID object
+ * Private destructor.
+ * No objects of this type should be made.
+ * Only use the static functions of this class
+ ***************************************************************************/
+ virtual ~SHFamilyID()
+ {
+ }
+ public:
+
+ /*!*************************************************************************
+ * \brief
+ * Checks if this identifier is cuurrently in use / valid.
+ * \param id
+ * Identifier to check for.
+ * \return bool
+ * true if the identifier is currently in use.
+ * false if the identifier is not in use.
+ ***************************************************************************/
+ static bool IsValidID(ComponentTypeID id) noexcept
+ {
+ return(id < currentID);
+ }
+
+ /*!*************************************************************************
+ * \brief
+ * Get the ID of a derived class type.
+ * Example of function call to this function should be:
+ * SHFamily::GetID();
+ * @tparam DerivedClass
+ * The derived class type that we are trying to get the ID of.
+ ***************************************************************************/
+ template
+ static ENABLE_IF_DERIVED(ComponentTypeID, BaseClass, DerivedClass) GetID() noexcept
+ {
+ //The first time a new derived class type call this get id, it will initialize id using the currentID from familyID class.
+ static ComponentTypeID id = currentID++;
+ return id;
+ }
+ };
+ //initialize currentID as 0
+ template
+ ComponentTypeID SHFamilyID::currentID = 0;
+
+}
+
+
+
+#endif
\ No newline at end of file
diff --git a/SHADE_Engine/src/Engine/ECS_Base/General/SHHandleGenerator.h b/SHADE_Engine/src/Engine/ECS_Base/General/SHHandleGenerator.h
new file mode 100644
index 00000000..48ae2132
--- /dev/null
+++ b/SHADE_Engine/src/Engine/ECS_Base/General/SHHandleGenerator.h
@@ -0,0 +1,305 @@
+/*********************************************************************
+ * \file SHHandleGenerator.h
+ * \author Daniel Chua Yee Chen
+ *
+ * \brief Declaration for the SHHandleGenerator class.
+ * Generates a unique identifier/handle for objects.
+ * This is different from SHFamily which is meant to generate identifier for object types.
+ *
+ *
+ * \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.
+ *********************************************************************/
+#ifndef SH_HANDLE_GENERATOR_H
+#define SH_HANDLE_GENERATOR_H
+
+#include
+#include
+
+#include "../SHECSMacros.h"
+
+
+
+namespace SHADE
+{
+ /*********************************************************************
+ * \brief
+ * Generates a unique handle of HandleType type.
+ * The first half of the bits will be used for version. This is used for recyling the IDs.
+ * The second half of the bits will be used for the index, this is also used as its ID.
+ *
+ * HandleType should always be twice the size of IndexType
+ *********************************************************************/
+
+ template
+ class SHHandleGenerator
+ {
+ private:
+ //List of all the handles in use. Handles that are deleted are still stored here.
+ std::vector handleList;
+ //The next handle to be used.
+ HandleType nextRecycle;
+ //The total number of handles that are currently deleted and waiting to be recycled.
+ HandleType recycleCounter;
+
+ //The Mask is variable is used to easily separate the version and index via bit masking (bitwise &).
+
+
+ //The index mask is used to identify the index.
+ //(1<<16) - 1. Shift 1 bit to the left 16 times and -1. This leaves the first 16 bits as 0 and the -1 makes the second 16 bits all 1.
+ static const HandleType indexMask = (1 << sizeof(IndexType) * 8) - 1;
+
+ //using the bitwise NOT, invert the index mask to get the version mask.
+ static const HandleType versionMask = ~indexMask;
+
+ public:
+ /*!*************************************************************************
+ * \brief Construct a new SHHandleGenerator object
+ * default constructor for the HandleGenerator object.
+ ***************************************************************************/
+ SHHandleGenerator()
+ :nextRecycle(0),recycleCounter(0)
+ {
+ }
+
+ /*!*************************************************************************
+ * \brief Destroy the SHHandleGenerator object
+ * Default destructor for the HandleGenerator object.
+ ***************************************************************************/
+ ~SHHandleGenerator() = default;
+
+
+ /*!*************************************************************************
+ * \brief
+ * Combines the 16-bit version and 16-bit index to make a 32-bit handle.
+ * \param verison
+ * The 16-bit version
+ * \param index
+ * The 16-bit index
+ * \return HandleType
+ * The resultant Handle
+ ***************************************************************************/
+ static HandleType GetHandle(IndexType version, IndexType index) noexcept
+ {
+ return (version << sizeof(IndexType) * 8) | index;
+ }
+
+ /*!*************************************************************************
+ * \brief
+ * Gets the 16-bit version from the 32-bit handle
+ * \param handle
+ * The 32-bit handle
+ * \return IndexType
+ * The 16-bit version
+ ***************************************************************************/
+ static IndexType GetVersion(HandleType handle) noexcept
+ {
+ return handle >> sizeof(IndexType) * 8;
+ }
+
+ /*!*************************************************************************
+ * \brief
+ * Gets the 16-bit index from the 32-bit handle
+ * \param handle
+ * The 32-bit handle
+ * \return IndexType
+ * The 16-bit index
+ ***************************************************************************/
+ static IndexType GetIndex(HandleType handle) noexcept
+ {
+ return handle & indexMask;
+ }
+
+ /*!*************************************************************************
+ * \brief
+ * Checks if the current handle is still valid. This checks if the index
+ * of the handle is in use, then checks if the version of the current index
+ * matches the handle we are checking for.
+ * \param handle
+ * The handle to check for.
+ * \return bool
+ * True if the handle is still valid. False if the handle has been removed
+ * or not in use.
+ ***************************************************************************/
+ bool IsValid(HandleType handle) noexcept
+ {
+ IndexType index = GetIndex(handle);
+ if (index >= (IndexType)handleList.size()) // handle is out of range of intialized index
+ {
+ return false;
+ }
+
+ return (handleList[index] == handle); // this will check if the current handle at that index has been removed.
+ }
+
+ /**************************************************************************
+ * \brief
+ * Get the number of active handles.
+ * \return
+ * Number of active handles.
+ ***************************************************************************/
+ IndexType GetActiveHandleCount() noexcept
+ {
+ return (IndexType)(handleList.size() - recycleCounter);
+ }
+
+ /*!*************************************************************************
+ * \brief
+ * Request the Generator for a new handle. This will provide recycled index
+ * if available
+ * \return HandleType
+ * The new handle.
+ ***************************************************************************/
+ HandleType GetNewHandle() noexcept
+ {
+ HandleType result;
+
+ //Check if there is any index waiting to be recycled
+ if (recycleCounter == 0) // nothing to be recycled. Make a new one
+ {
+ result = GetHandle(0, (IndexType)handleList.size());
+ handleList.push_back(result);
+ return result;
+ }
+ //There is a index waiting to be recycled.
+ result = nextRecycle;
+ IndexType index = GetIndex(nextRecycle);
+ //updates the next recycle.
+ nextRecycle = handleList[index];
+ handleList[index] = result;
+ --recycleCounter;
+ return result;
+
+ }
+
+ /*!*************************************************************************
+ * \brief
+ * Removes a handle and make it invalid and queue it for recycling.
+ * \param handle
+ * The handle to remove.
+ ***************************************************************************/
+ void RemoveHandle(HandleType handle) noexcept
+ {
+ if (!IsValid(handle))
+ {
+ return;
+ }
+
+ IndexType index = GetIndex(handle);
+ IndexType version = GetVersion(handle);
+
+ //set the handle at the current index to the next thing to be recycled.
+ handleList[index] = nextRecycle;
+
+ //set the next recycle to be the thing that was just deleted with its version incremented.
+ nextRecycle = GetHandle(version + 1, index);
+ ++recycleCounter;
+
+ }
+
+ /*!*************************************************************************
+ * \brief
+ * Clears all the handles in use and Resets the handle generation.
+ ***************************************************************************/
+ void ClearAllHandles() noexcept
+ {
+ handleList.clear();
+ nextRecycle = 0;
+ recycleCounter = 0;
+ }
+
+ /**************************************************************************
+ * \brief
+ * Attempts to claim a specified handle. If the handle is available, the
+ * generator will mark it as claimed and return true.
+ * Updates recycles accordingly when adding extra padding to the handle list.
+ *
+ * \param handle
+ * The handle to claim
+ *
+ * \return
+ * true if the handle is available to claim.
+ ***************************************************************************/
+ bool ClaimHandle(HandleType handle) noexcept
+ {
+ IndexType index = GetIndex(handle);
+
+ if (handleList.size() <= index || GetIndex(handleList[index]) != index)
+ {
+ //This index is currently not in use
+
+ if (index >= handleList.size())
+ {
+ IndexType size = (IndexType)handleList.size();
+
+ for (IndexType i = 0; i < index - size; ++i)
+ {
+ handleList.push_back((IndexType)handleList.size());
+
+ HandleType back = handleList.back();
+ //set the handle at the current index to the next thing to be recycled.
+ if (recycleCounter > 0)
+ handleList.back() = nextRecycle;
+ else
+ {
+ handleList.back() = (HandleType)-1;
+ }
+
+ //set the next recycle to be the thing that was just deleted with its version incremented.
+ nextRecycle = GetHandle(0, GetIndex(back));
+ ++recycleCounter;
+ }
+ handleList.push_back(handle);
+
+ }
+ else
+ {
+ if (index == GetIndex(nextRecycle))
+ {
+ index = GetIndex(nextRecycle);
+ //updates the next recycle.
+ nextRecycle = handleList[index];
+ handleList[index] = handle;
+ --recycleCounter;
+ return true;
+ }
+
+ if (recycleCounter > 0)
+ {
+ HandleType recycle = handleList[index];
+ IndexType recycleIndex = GetIndex(nextRecycle);
+ HandleType i = 0;
+ while (i < recycleCounter)
+ {
+ if (GetIndex(handleList[recycleIndex]) == index)
+ break;
+ recycleIndex = GetIndex(handleList[recycleIndex]);
+ ++i;
+ }
+ --recycleCounter;
+ if (recycleCounter > 0 && recycleIndex < handleList.size())
+ handleList[recycleIndex] = recycle;
+ }
+ handleList[index] = handle;
+ }
+
+
+ return true;
+ }
+
+ return false;
+
+ }
+
+
+ };
+
+
+
+ typedef SHHandleGenerator EntityHandleGenerator;
+
+}
+
+
+#endif
diff --git a/SHADE_Engine/src/Engine/ECS_Base/General/SHSparseBase.h b/SHADE_Engine/src/Engine/ECS_Base/General/SHSparseBase.h
new file mode 100644
index 00000000..2deebe74
--- /dev/null
+++ b/SHADE_Engine/src/Engine/ECS_Base/General/SHSparseBase.h
@@ -0,0 +1,50 @@
+/*********************************************************************
+ * \file SHSparseBase.h
+ * \author Daniel Chua Yee Chen
+ * \brief Declaration for the SHSparseBase class.
+ * This is an abstract class for the SHSparseSet template class.
+ * This allows the SHSparseSetContainer class to store SparseSet of different types.
+ *
+ * \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.
+ *********************************************************************/
+
+#ifndef SH_SPARSE_BASE_H
+#define SH_SPARSE_BASE_H
+
+#include "../SHECSMacros.h"
+
+namespace SHADE
+{
+
+ class SHSparseBase
+ {
+ protected:
+ SHSparseBase() = default;
+
+ public:
+ virtual ~SHSparseBase() = default;
+
+ virtual void Remove(EntityIndex hash) { (void)hash; };
+
+ virtual void Clear() {};
+
+ virtual void Swap(EntityIndex hash1, EntityIndex hash2) { (void)hash1; (void)hash2; };
+
+ virtual void SwapIndexHash(EntityIndex index1, EntityIndex hash) { (void)index1; (void)hash; };
+
+ virtual bool Has(EntityIndex hash) = 0;
+
+ virtual void* Get(EntityIndex hash) { (void)hash; return nullptr; };
+
+ virtual void Add(EntityIndex hash) { (void)hash; };
+
+ virtual EntityIndex Count() = 0;
+
+ };
+
+}
+
+
+#endif
\ No newline at end of file
diff --git a/SHADE_Engine/src/Engine/ECS_Base/General/SHSparseSet.h b/SHADE_Engine/src/Engine/ECS_Base/General/SHSparseSet.h
new file mode 100644
index 00000000..3473eb37
--- /dev/null
+++ b/SHADE_Engine/src/Engine/ECS_Base/General/SHSparseSet.h
@@ -0,0 +1,356 @@
+/*********************************************************************
+ * \file SHSparseSet.h
+ * \author Daniel Chua Yee Chen
+ * \brief Declaration for the SHSparseSet template class
+ * This is a container that allows for fast iteration due to contiguous memory
+ * storage while having fast lookup time at the cost of memory usage.
+ *
+ * \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.
+ *********************************************************************/
+#ifndef SH_SPARSE_SET_H
+#define SH_SPARSE_SET_H
+
+#include "../SHECSMacros.h"
+#include "../General/SHSparseBase.h"
+#include "../General/SHHandleGenerator.h"
+#include
+#include
+#include
+
+namespace SHADE
+{
+ template
+ class SHSparseSet: public SHSparseBase
+ {
+ private:
+ //Dense array of type T
+ std::vector denseArray;
+ //This array stores the key of the corresponding element in the dense array. (eg. entity ID)
+ std::vector denseIndexArray;
+
+ //Sparse Array. This array helps with look up
+ EntityIndex sparseArray[MAX];
+
+ public:
+
+ /*!*************************************************************************
+ * \brief Construct a new SHSparseSet object
+ * Default constructor for the SparseSet class.
+ ***************************************************************************/
+ SHSparseSet()
+ {
+ for (EntityIndex i = 0; i < MAX; ++i)
+ {
+ sparseArray[i] = UINT16_MAX;
+ }
+
+ denseArray.reserve(MAX);
+ denseIndexArray.reserve(MAX);
+ }
+
+ /*!*************************************************************************
+ * \brief Destroy the SHSparseSet object
+ * Default destructor for the SparseSet class.
+ ***************************************************************************/
+ virtual ~SHSparseSet()
+ {
+ Clear();
+ }
+
+ /*!*************************************************************************
+ * \brief
+ * Clears all elements in the current SparseSet and resets the sparseArray.
+ ***************************************************************************/
+ void Clear() noexcept
+ {
+ denseArray.clear();
+ denseIndexArray.clear();
+ for (EntityIndex i = 0; i < MAX; ++i)
+ {
+ sparseArray[i] = UINT16_MAX;
+ }
+ }
+
+ /*!*************************************************************************
+ * \brief
+ * Check is the specified hash is in range of the sparseSet.
+ * \param hash
+ * Hash to check for.
+ * \return bool
+ * true if the specified hash is in range of the spraseSet.
+ ***************************************************************************/
+ bool IsValid(EntityIndex hash) noexcept
+ {
+ return (hash < MAX);
+ }
+
+ /*!*************************************************************************
+ * \brief
+ * Checks if this sparseSet contains an element with specified hash.
+ * \param hash
+ * The hash to check for.
+ * \return bool
+ * true if the element with this hash is found. false if no such element is found.
+ ***************************************************************************/
+ virtual bool Has(EntityIndex hash) noexcept
+ {
+ //Check if the hash passed in is within range.
+ if (!IsValid(hash) || sparseArray[hash] == UINT16_MAX)
+ {
+ return false;
+ }
+ return (denseIndexArray[sparseArray[hash]] == hash);
+ }
+
+ /*!*************************************************************************
+ * \brief
+ * Get a pointer to the element with the specified hash.
+
+ * This is the safe version which does a Has() check and return a nullptr
+ * if it does not have such an Element
+ *
+ * \param hash
+ * The hash of the element to look for.
+ * \return T*
+ * returns a pointer to the element with the specified hash if found.
+ * returns a nullptr if no such element is found.
+ ***************************************************************************/
+ T* GetElement_s(EntityIndex hash) noexcept
+ {
+ if (!Has(hash))
+ {
+ return nullptr;
+ }
+
+ return &denseArray[sparseArray[hash]];
+ }
+
+ /*!*************************************************************************
+ * \brief
+ * Get a pointer to the element with the specified hash.
+
+ * This bypasses the Has() check and assumes that the hash has a Element
+ * in the dense array.
+ *
+ * \param hash
+ * The hash of the element to look for.
+ * \return T*
+ * returns a pointer to the element with the specified hash if found.
+ * returns a nullptr if no such element is found.
+ ***************************************************************************/
+ T* GetElement(EntityIndex hash) noexcept
+ {
+ return &denseArray[sparseArray[hash]];
+ }
+
+
+
+ /*!*************************************************************************
+ * \brief
+ * Operator overload for the subscript operator.
+ * Gets the element by reference with the hash specified in the subscript.
+ * This does not handle out of range exceptions.
+ * \param hash
+ * The hash of the element we are trying to get
+ * \return T&
+ * A reference to the element found.
+ ***************************************************************************/
+ T& operator[](EntityIndex hash) noexcept
+ {
+ return denseArray[sparseArray[hash]];
+ }
+
+ /*!*************************************************************************
+ * \brief
+ * Get the number of elements in the current SparseSet
+ * \return uint16_t
+ * The number of elements in the SparseSet.
+ ***************************************************************************/
+ virtual EntityIndex Count() noexcept
+ {
+ return (EntityIndex)denseArray.size();
+ }
+
+ /*!*************************************************************************
+ * \brief
+ * Getter function for the dense array.
+ * \return std::vector&
+ * return a reference to the dense array.
+ ***************************************************************************/
+ std::vector& GetDense() noexcept
+ {
+ return denseArray;
+ }
+
+ /*!*************************************************************************
+ * \brief
+ * Const getter function for the dense array.
+ * \return std::vector&
+ * return a const reference to the dense array.
+ ***************************************************************************/
+ const std::vector GetDense() const noexcept
+ {
+ return denseArray;
+ }
+
+ /*!*************************************************************************
+ * \brief
+ * Swaps two elements in the dense array.
+ * This only swaps their position in the dense array and updates their
+ * Sparse index reference in the sprase array accordingly.
+ * This DOES NOT change the hash of the elements.
+ * \param hash1
+ * Hash of the first element
+ * \param hash2
+ * Hash of the second element
+ ***************************************************************************/
+ virtual void Swap(EntityIndex hash1, EntityIndex hash2) noexcept
+ {
+ if (!Has(hash1) || !Has(hash2) || hash1 == hash2)
+ {
+ return;
+ }
+ T tempElement = denseArray[sparseArray[hash1]];
+ EntityIndex tempIndex = denseIndexArray[sparseArray[hash1]];
+ EntityIndex tempSparse = sparseArray[hash1];
+
+ denseArray[sparseArray[hash1]] = denseArray[sparseArray[hash2]];
+ denseIndexArray[sparseArray[hash1]] = denseIndexArray[sparseArray[hash2]];
+ sparseArray[hash1] = sparseArray[hash2];
+
+ denseArray[sparseArray[hash2]] = tempElement;
+ denseIndexArray[sparseArray[hash2]] = tempIndex;
+ sparseArray[hash2] = tempSparse;
+
+ }
+
+ /*!*************************************************************************
+ * \brief
+ * Swaps two elements in the dense array.
+ * This only swaps their position in the dense array and updates their
+ * Sparse index reference in the sprase array accordingly.
+ * This swaps using a index(position in the dense array) and a hash (EntityID)
+ * This DOES NOT change the hash of the elements.
+ * \param index1
+ * The position in the dense array of the first element
+ * \param hash
+ * Hash of the second element
+ ***************************************************************************/
+ virtual void SwapIndexHash(EntityIndex index1, EntityIndex hash) noexcept
+ {
+ if (index1 >= denseArray.size() || !Has(hash))
+ {
+ return;
+ }
+ Swap(denseIndexArray[index1], hash);
+ }
+
+ /*!*************************************************************************
+ * \brief
+ * Adds a new element to the SparseSet.
+ * \param hash
+ * The hash of the new element.
+ * Nothing is added if the SparseSet already contains an element with
+ * the same hash.
+ * \param element
+ * A reference to the element to be added. This will be passed in as a
+ * copy and the default copy constructor will be used to copy the element
+ * into the dense array.
+ ***************************************************************************/
+ void Add(EntityIndex hash, T& element) noexcept
+ {
+ if (!IsValid(hash) || Has(hash))
+ {
+ return;
+ }
+
+ denseArray.emplace_back(element);
+ denseIndexArray.emplace_back (hash);
+ sparseArray[hash] = EntityIndex(denseIndexArray.size() - 1);
+ }
+
+ /**************************************************************************
+ * \brief
+ * Adds a new element to the SparseSet.
+ * \param hash
+ * The hash of the new element.
+ * Nothing is added if the SparseSet already contains an element with
+ * the same hash.
+ * \return
+ * None
+ ***************************************************************************/
+ void Add(EntityIndex hash) noexcept
+ {
+ if (!IsValid(hash) || Has(hash))
+ {
+ return;
+ }
+
+ denseArray.emplace_back(T());
+ denseIndexArray.emplace_back(hash);
+ sparseArray[hash] = EntityIndex(denseIndexArray.size() - 1);
+ }
+
+
+
+ /*!*************************************************************************
+ * \brief
+ * Removes an element from the Sparse Set
+ * \param hash
+ *
+ ***************************************************************************/
+ virtual void Remove(EntityIndex hash) noexcept
+ {
+ if (!Has(hash))
+ {
+ return;
+ }
+
+ //Get the index of the item to be removed.
+ EntityIndex index = sparseArray[hash];
+
+ //Get the sparse index of the last element in the dense array.
+ EntityIndex lastSparse = denseIndexArray.back();
+
+ //Copy the contents of the last elements to the replace the element we are trying to remove
+ //denseArray[index] = denseArray.back();
+ //denseIndexArray[index] = denseIndexArray.back();
+
+ //denseArray.erase(denseArray.begin() + index);
+ //denseIndexArray.erase(denseIndexArray.begin() + index);
+ Swap(hash, lastSparse);
+
+ //update the sparse array with the new index of our last element.
+ sparseArray[lastSparse] = index;
+ sparseArray[hash] = UINT16_MAX;
+
+ //Pop out the last element since we no longer need it
+ denseArray.pop_back();
+ denseIndexArray.pop_back();
+ }
+
+ /**************************************************************************
+ * \brief
+ * Get the element specified by a hash. This will be casted to a void
+ * pointer
+ * \param hash
+ * The Index of the element.
+ * \return
+ * A void pointer to the element.
+ ***************************************************************************/
+ virtual void* Get(EntityIndex hash) noexcept
+ {
+ if (!Has(hash))
+ {
+ //no such element in this sparse set.
+ return nullptr;
+ }
+ return (void*) &denseArray[sparseArray[hash]];
+ }
+
+ };
+}
+
+#endif
diff --git a/SHADE_Engine/src/Engine/ECS_Base/General/SHSparseSetContainer.h b/SHADE_Engine/src/Engine/ECS_Base/General/SHSparseSetContainer.h
new file mode 100644
index 00000000..8698d1f5
--- /dev/null
+++ b/SHADE_Engine/src/Engine/ECS_Base/General/SHSparseSetContainer.h
@@ -0,0 +1,248 @@
+/*********************************************************************
+ * \file SHSparseSetContainer.h
+ * \author Daniel Chua Yee Chen
+ * \brief Declaration for SHSparseSetContainer template class.
+ * This is a container for SHSparseSets meant to contain SparseSets of
+ * different types that are derived from a shared Base class.
+ *
+ * \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.
+ *********************************************************************/
+
+#ifndef SH_SPARSE_SET_CONTAINER_H
+#define SH_SPARSE_SET_CONTAINER_H
+
+#include "SHSparseSet.h"
+#include "SHFamily.h"
+#include "../Components/SHComponent.h"
+#include
+
+namespace SHADE
+{
+ template
+ class SHSparseSetContainer
+ {
+ private:
+
+
+
+ public:
+
+ //The container of SparseSets.
+ std::vector container;
+
+ /*!*************************************************************************
+ * \brief
+ * Default constructor for the SHSparseSetContainer class
+ ***************************************************************************/
+ SHSparseSetContainer() = default;
+
+ /*!*************************************************************************
+ * \brief
+ * Default destructor for the SHSparseSetContainer class.
+ ***************************************************************************/
+ ~SHSparseSetContainer()
+ {
+ for (std::vector::iterator it = container.begin(); it != container.end(); ++it)
+ {
+ delete (*it);
+ }
+ };
+
+ /*!*************************************************************************
+ * \brief
+ * Attempts to create a SparseSet for the specified derived class.
+ * If a SparseSet of the same class type has already been created,
+ * nothing is re-created.
+ * @tparam Derived
+ * The type of the SparseSet to create.
+ ***************************************************************************/
+ template
+ ENABLE_IF_DERIVED(void, Base, Derived) CreateSparseSet() noexcept
+ {
+ EntityID typeID = SHFamilyID::template GetID();
+
+ if (container.size() > typeID)
+ {
+ if (container[typeID] == nullptr)
+ {
+ container[typeID] = (SHSparseBase*)new SHSparseSet();
+ }
+ return;
+ }
+ while (container.size() <= typeID)
+ {
+ container.push_back(nullptr);
+ }
+ container[typeID] = (SHSparseBase*)new SHSparseSet();
+ }
+
+ //Cant use ENABLE_IF_DERIVED here because the macro is defined before template is defined.
+ //Hence the return type that is a templated class will be an issue.
+
+
+ /**************************************************************************
+ * \brief
+ * Get the sparse set specified by a type. This converts the type to
+ * a type ID using SHFamilyID and use that as the index.
+ * This will attempt to Create a sparse set if it doesn't exist.
+ * \return
+ * The base class pointer to the sparse set.
+ ***************************************************************************/
+ template
+ std::enable_if_t< std::is_base_of_v,SHSparseSet* > GetSparseSet() noexcept
+ {
+ EntityID typeID = SHFamilyID::template GetID();
+ if (container.size() <= typeID || container[typeID] == nullptr)
+ {
+ CreateSparseSet();
+ }
+
+ return (SHSparseSet*)container[typeID];
+
+ }
+
+
+ /**************************************************************************
+ * \brief
+ * Get the sparse set at the specified index.
+ * \param typeID
+ * The index of the sparse set to get.
+ * \return
+ * The base class pointer to the sparse set.
+ ***************************************************************************/
+ SHSparseBase* GetSparseSet_ID(uint32_t typeID) noexcept
+ {
+ //assert(typeID >= container.size());
+
+ return container[typeID];
+ }
+
+
+ /*!*************************************************************************
+ * \brief
+ * Get the number of elements in the specified SparseSet
+ * @tparam Derived
+ * The type of the SparseSet
+ ***************************************************************************/
+ template
+ inline ENABLE_IF_DERIVED(EntityID, Base, Derived)Count() noexcept
+ {
+ return GetSparseSet()->Count();
+ }
+
+ /*!*************************************************************************
+ * \brief
+ * Get the dense array of the specified SparseSet
+ * @tparam Derived
+ * The type of the SparseSet
+ * \return
+ * Returns a reference to the dense array of the specified SparseSet
+ ***************************************************************************/
+ template
+ inline std::enable_if_t < std::is_base_of_v, std::vector& > GetDense() noexcept
+ {
+ return GetSparseSet()->GetDense();
+ }
+
+ /*!*************************************************************************
+ * \brief
+ * Remove all elements with the specified hash from all the SparseSets in
+ * the container.
+ * \param hash
+ * The hash of the elements to remove.
+ ***************************************************************************/
+ void RemoveElements(EntityIndex hash) noexcept
+ {
+ for (std::vector::iterator it = container.begin(); it != container.end(); ++it)
+ {
+
+ if (*it)
+ {
+ (*it)->Remove(hash);
+ }
+
+ }
+ }
+
+ /*!*************************************************************************
+ * \brief
+ * Clear all SparseSets in the container.
+ ***************************************************************************/
+ void ClearAllElements() noexcept
+ {
+ for (std::vector::iterator it = container.begin(); it != container.end(); ++it)
+ {
+ (*it)->Clear();
+ }
+ }
+
+ /*!*************************************************************************
+ * \brief
+ * Sets the isActive variable in the elements with the specified hash
+ * in all the SparseSets in the container.
+ * This assuumes that the element types has a isActive boolean.
+ * \param hash
+ * hash of the elements
+ * \param active
+ * The active state to set to.
+ ***************************************************************************/
+ void SetElementActive(EntityIndex hash, bool active) noexcept
+ {
+ (void)active;
+ for (std::vector::iterator it = container.begin(); it != container.end(); ++it)
+ {
+
+ if (*it)
+ {
+ SHComponent* comp = static_cast((*it)->Get(hash));
+ if (comp)
+ {
+ comp->isActive = active;
+ }
+
+ }
+
+ }
+ }
+
+
+
+ /**************************************************************************
+ * \brief
+ * Get the element of a specified hash from the Sparse set of indicated index.
+ * \param typeIndex
+ * The index of the sparse set which we are trying to get from
+ * \param hash
+ * The hash that the element belongs to.
+ * \return
+ * The address of the element casted to a void*
+ ***************************************************************************/
+ void* GetElement(uint32_t typeIndex, EntityIndex hash) noexcept
+ {
+ if (typeIndex >= container.size())
+ {
+ return nullptr;
+ }
+ return container[typeIndex]->Get(hash);
+ }
+
+ /**************************************************************************
+ * \brief
+ * Get the size of the SparseSetContainer.
+ * \return
+ * The number of sparse sets in this container.
+ ***************************************************************************/
+
+ size_t Size() noexcept
+ {
+ return container.size();
+ }
+
+
+ };
+}
+
+
+#endif
diff --git a/SHADE_Engine/src/Engine/ECS_Base/SHECSMacros.h b/SHADE_Engine/src/Engine/ECS_Base/SHECSMacros.h
new file mode 100644
index 00000000..5243e20f
--- /dev/null
+++ b/SHADE_Engine/src/Engine/ECS_Base/SHECSMacros.h
@@ -0,0 +1,25 @@
+#ifndef SH_MACROS_H
+#define SH_MACROS_H
+
+#include
+#include
+
+
+
+typedef uint32_t EntityID;
+typedef uint16_t EntityIndex;
+typedef uint32_t ComponentTypeID;
+
+
+const EntityIndex MAX_EID = 51000;
+
+
+
+#define ENABLE_IF_DERIVED(__RETURN__, __BASE__, __DERIVED__)\
+ std::enable_if_t,__RETURN__>
+
+
+#define ENABLE_IF_UINT(_TYPE, _RETURN)\
+ typename std::enable_if<(std::is_integral<_TYPE>::value && !std::is_signed<_TYPE>::value),_RETURN>::type
+
+#endif
\ No newline at end of file
diff --git a/SHADE_Engine/src/Engine/ECS_Base/System/SHComponentManager.cpp b/SHADE_Engine/src/Engine/ECS_Base/System/SHComponentManager.cpp
new file mode 100644
index 00000000..be78a146
--- /dev/null
+++ b/SHADE_Engine/src/Engine/ECS_Base/System/SHComponentManager.cpp
@@ -0,0 +1,102 @@
+/*********************************************************************
+ * \file SHComponentManager.cpp
+ * \author Daniel Chua Yee Chen
+ * \brief Definition of functions for the SHComponentManager class.
+ * This is the interface that the systems are going to use to interacte with
+ * the components. The SparseSetContainer of components is stored and managed
+ * here.
+ *
+ * \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 "SHComponentManager.h"
+#include "SHEntityManager.h"
+#include "SHSystemManager.h"
+
+namespace SHADE
+{
+
+ SHSparseSetContainer SHComponentManager::componentSet;
+ std::vector SHComponentManager::componentGroups;
+
+ void SHComponentManager::Exit() noexcept
+ {
+ }
+
+ void SHComponentManager::RemoveComponentsOfEntity(EntityID entityID) noexcept
+ {
+
+ if (!SHEntityManager::IsValidEID(entityID))
+ {
+ return;
+ }
+
+ for (uint32_t i = 0; i < componentSet.Size(); ++i)
+ {
+ SHComponent* comp = (SHComponent*) componentSet.GetElement(i, EntityHandleGenerator::GetIndex(entityID));
+ if (comp)
+ {
+ comp->OnDestroy();
+ }
+ }
+
+
+
+ for (auto & grp : componentGroups)
+ {
+ grp.RemoveEntity(entityID);
+ }
+
+ componentSet.RemoveElements(EntityHandleGenerator::GetIndex(entityID));
+
+ //entityHandle.RemoveHandle(entityID);
+
+ }
+
+
+ bool SHComponentManager::HasComponent_ID(EntityID entityID, uint32_t componentTypeID) noexcept
+ {
+ return componentSet.GetSparseSet_ID(componentTypeID)->Has(EntityHandleGenerator::GetIndex(entityID));
+ }
+
+
+ void SHComponentManager::SetActive(EntityID entityID, bool active) noexcept
+ {
+ componentSet.SetElementActive(EntityHandleGenerator::GetIndex(entityID), active);
+ }
+
+ void SHComponentManager::SwapInDenseByIndexHash_ID(EntityIndex index, EntityID hash, uint32_t componentTypeID) noexcept
+ {
+ componentSet.GetSparseSet_ID(componentTypeID)->SwapIndexHash(index, EntityHandleGenerator::GetIndex(hash));
+ }
+
+ void SHComponentManager::ChangeParent(EntityID entity, EntityID newParent)
+ {
+ for (uint32_t i = 0; i < (uint32_t)componentSet.Size(); ++i)
+ {
+ SHComponent* component = (SHComponent*)componentSet.GetElement(i, EntityHandleGenerator::GetIndex(entity));
+ if (component == nullptr)
+ {
+ continue;
+ }
+ component->ChangeParent(newParent);
+
+ }
+ }
+
+ void SHComponentManager::ChangeParent(EntityID entity)
+ {
+ for (uint32_t i = 0; i < (uint32_t)componentSet.Size(); ++i)
+ {
+ SHComponent* component = (SHComponent*)componentSet.GetElement(i, EntityHandleGenerator::GetIndex(entity));
+ if (component == nullptr)
+ {
+ continue;
+ }
+ component->ChangeParent();
+ }
+ }
+
+}
diff --git a/SHADE_Engine/src/Engine/ECS_Base/System/SHComponentManager.h b/SHADE_Engine/src/Engine/ECS_Base/System/SHComponentManager.h
new file mode 100644
index 00000000..05a3d1ee
--- /dev/null
+++ b/SHADE_Engine/src/Engine/ECS_Base/System/SHComponentManager.h
@@ -0,0 +1,477 @@
+/*********************************************************************
+ * \file SHComponentManager.h
+ * \author Daniel Chua Yee Chen
+ * \brief Declaration for the SHComponentManager class.
+ * This is the interface that the systems are going to use to interacte with
+ * the components.
+ * The SparseSetContainer of components is stored and managed
+ * here.
+ *
+ * \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.
+ *********************************************************************/
+
+#ifndef SH_ENGINE_H
+#define SH_ENGINE_H
+
+#include "../General/SHSparseSetContainer.h"
+#include "../Components/SHComponent.h"
+#include "../Components/SHComponentGroup.h"
+//#include "Scene/SHSceneNode.h"
+
+
+#include
+
+namespace SHADE
+{
+ class SHComponentManager
+ {
+ private:
+
+ //The SparseSetContainer of components.
+ static SHSparseSetContainer componentSet;
+ //The Container of all Componentgroups
+ static std::vector componentGroups;
+
+ friend class SHSceneNode;
+
+
+
+ /**************************************************************************
+ * \brief
+ * This is called by the SHSceneNode friend class to change the parent
+ * of an entity.
+ * This function is privated as it is not for general use.
+ * \param entity
+ * The entityID of the entity which to change the parent of.
+ * \param newParent
+ * The entityID of the new parent.
+ ***************************************************************************/
+ static void ChangeParent(EntityID entity, EntityID newParent);
+
+
+ /**************************************************************************
+ * \brief
+ * Overloaded function of Change parent to change the parent of an entity to
+ * the root node.
+ * This is called by the SHSceneNode friend class to change the parent
+ * of an entity.
+ * This function is privated as it is not for general use.
+ * \param entity
+ * The entityID of the entity which to change the parent of.
+ ***************************************************************************/
+ static void ChangeParent(EntityID entity);
+
+
+ protected:
+
+ public:
+ /*!*************************************************************************
+ * This class is used as a static class.
+ * No objects of this type should be created
+ ***************************************************************************/
+ SHComponentManager() = delete;
+ ~SHComponentManager() = delete;
+
+
+
+ /*!*************************************************************************
+ * \brief
+ * Cleans up the memory used in the Engine.
+ ***************************************************************************/
+ static void Exit() noexcept;
+
+
+
+ /*!*************************************************************************
+ * \brief
+ * Creates the SparseSet for the specified Component type
+ * @tparam T
+ * Component Type to create.
+ ***************************************************************************/
+ template
+ static void CreateComponentSparseSet() noexcept
+ {
+ componentSet.CreateSparseSet();
+ }
+
+ /*!*************************************************************************
+ * \brief
+ * Getter for the dense array of a specified Component Type.
+ * @tparam T
+ * Component Type
+ * \return std::vector&
+ * reference to the dense array from the SparseSet of the Component Type T.
+ ***************************************************************************/
+ template
+ static std::vector& GetDense() noexcept
+ {
+ return componentSet.GetDense();
+ }
+
+
+ /*!*************************************************************************
+ * \brief
+ * Gets the Component of the entity with the specified entityID
+ *
+ * This is the safe version of GetComponent_s which does a HasComponent to make
+ * sure that the entity has such a component and returns nullptr if it doesn't
+ *
+ * This safe version also checks if the sparse set of this component type
+ * has been created in SHComponentManager and creates one if it doesn't
+ *
+ * @tparam T
+ * Type of Component to get.
+ * \param entityID
+ * EntityID of the entity that we are trying to get the component of.
+ * \return
+ * A pointer to the component of the entity.
+ * Returns nullptr if the entity does not contain such a component.
+ ***************************************************************************/
+ template
+ static ENABLE_IF_DERIVED(T*, SHComponent, T) GetComponent_s(EntityID entityID) noexcept
+ {
+ EntityID typeID = SHFamilyID::template GetID();
+
+ if (componentSet.container.size() <= typeID)
+ {
+ componentSet.CreateSparseSet();
+ return nullptr;
+ }
+
+
+ return (componentSet.GetSparseSet()->GetElement_s(EntityHandleGenerator::GetIndex(entityID)));
+ }
+
+ /*!*************************************************************************
+ * \brief
+ * Gets the Component of the entity with the specified entityID
+ *
+ * This is the faster unsafe version.
+ * Use only when sure that the entity has such a Component type. This could
+ * give garbage value or the component of a different entity if the entity
+ * does not have the specified component type. This is usually used with
+ * ComponentGroups
+ *
+ * This unsafe version bypass the HasComponent check.
+ *
+ * This unsafe version bypass the check for sparseSet creation.
+ *
+ * @tparam T
+ * Type of Component to get.
+ * \param entityID
+ * EntityID of the entity that we are trying to get the component of.
+ * \return
+ * A pointer to the component of the entity.
+ ***************************************************************************/
+ template
+ static ENABLE_IF_DERIVED(T*,SHComponent, T) GetComponent(EntityID entityID) noexcept
+ {
+ //EntityID typeID = SHFamilyID::template GetID();
+
+ return (componentSet.GetSparseSet()->GetElement(EntityHandleGenerator::GetIndex(entityID)));
+ }
+
+
+
+ /*!*************************************************************************
+ * \brief
+ * Add a component to the specified entityID
+ * Nothing is added if the entityID already have a component of the same type.
+ * @tparam T
+ * Type of Component to be added.
+ * @tparam Args
+ * The args types to pass to the constructor of the Component
+ * \param entityID
+ * EntityID to add this component to.
+ * \param args
+ * The args to pass to the constructor of the Component
+ * \return
+ * None.
+ ***************************************************************************/
+ template
+ static ENABLE_IF_DERIVED(void,SHComponent,T) AddComponent(EntityID entityID) noexcept
+ {
+ T element{};
+
+ componentSet.GetSparseSet_ID(SHFamilyID::GetID())->Add(EntityHandleGenerator::GetIndex(entityID));
+
+
+ SHComponent* comp = (SHComponent*)componentSet.GetElement(SHFamilyID::GetID(), EntityHandleGenerator::GetIndex(entityID));
+ comp->entityID = entityID;
+
+ for (auto& grp : componentGroups)
+ {
+ grp.AddComponentCheck(entityID, SHFamilyID::GetID());
+ }
+
+
+ if (comp)
+ {
+ comp->OnCreate();
+ }
+
+ }
+
+ /**************************************************************************
+ * \brief
+ * Add Component using a component type ID. This assumes that the sparse
+ * set is already created for the component type ID.
+ * \param entityID
+ * The entity ID of the entity
+ * \param componentTypeID
+ * The Type ID of the Component Type.
+ * \return
+ * none
+ ***************************************************************************/
+ static void AddComponent(EntityID entityID, uint32_t componentTypeID) noexcept
+ {
+ componentSet.GetSparseSet_ID(componentTypeID)->Add(EntityHandleGenerator::GetIndex(entityID));
+
+
+ SHComponent* comp = (SHComponent*)componentSet.GetElement(componentTypeID, EntityHandleGenerator::GetIndex(entityID));
+ comp->entityID = entityID;
+
+ for (auto& grp : componentGroups)
+ {
+ grp.AddComponentCheck(entityID,componentTypeID);
+ }
+
+
+ if (comp)
+ {
+ comp->OnCreate();
+ }
+ }
+
+
+ /*!*************************************************************************
+ * \brief
+ * Checks if the specified entityID has a component of specified type.
+ * @tparam T
+ * Type of Component to check for.
+ * \param entityID
+ * EntityID to check for.
+ * \return bool
+ * True if the entity has a component of specified type.
+ ***************************************************************************/
+ template
+ static ENABLE_IF_DERIVED(bool, SHComponent, T) HasComponent(EntityID entityID) noexcept
+ {
+ return componentSet.GetSparseSet()->Has(EntityHandleGenerator::GetIndex(entityID));
+ }
+
+
+
+ /*!*************************************************************************
+ * \brief
+ * Checks if the specified entityID has a component of specified type.
+ * The component type is specified by a component type ID
+ * @tparam T
+ * Type of Component to check for.
+ * \param entityID
+ * EntityID to check for.
+ * \param componentTypeID
+ * The component type ID to look for
+ * \return bool
+ * True if the entity has a component of specified type.
+ ***************************************************************************/
+ static bool HasComponent_ID(EntityID entityID, uint32_t componentTypeID) noexcept;
+
+
+ /*!*************************************************************************
+ * \brief
+ * Remove the Component of specified type from the entity.
+ * @tparam T
+ * Component type to be removed
+ * \param entityID
+ * EntityID of the object to remove the component from.
+ ***************************************************************************/
+ template
+ static ENABLE_IF_DERIVED(void, SHComponent, T) RemoveComponent(EntityID entityID) noexcept
+ {
+ if (!HasComponent(entityID))
+ {
+ return;
+ }
+
+ SHComponent* comp = (SHComponent*)componentSet.GetElement(SHFamilyID::GetID(), EntityHandleGenerator::GetIndex(entityID));
+ if (comp)
+ {
+ comp->OnDestroy();
+ }
+
+ for (auto& grp : componentGroups)
+ {
+ grp.RemoveComponentCheck(entityID);
+ }
+
+
+ componentSet.GetSparseSet()->Remove(EntityHandleGenerator::GetIndex(entityID));
+ }
+
+ /*!*************************************************************************
+ * \brief
+ * Swaps to positioning of two components in their dense array.
+ * This does not swap the entity that the components belong to
+ * @tparam T
+ * Type of the Component to swap.
+ * \param entityID1
+ * entityID of the first entity.
+ * \param entityID2
+ * entityID of the second entity.
+ * \return
+ * None.
+ ***************************************************************************/
+ template
+ static ENABLE_IF_DERIVED(void, SHComponent, T) SwapInDense(EntityID entityID1, EntityID entityID2) noexcept
+ {
+ componentSet.GetSparseSet()->Swap(EntityHandleGenerator::GetIndex(entityID1), EntityHandleGenerator::GetIndex(entityID2));
+ }
+
+ /**************************************************************************
+ * \brief
+ * Swaps to positioning of two components in their dense array.
+ * This does not swap the entity that the components belong to.
+ * This is the overloaded function that takes 2 Entity Index
+ * \param index
+ * The entity Index of the first entity.
+ * \param hash
+ * The entity Index of the second entity.
+ * \return
+ * none
+ ***************************************************************************/
+ template
+ static ENABLE_IF_DERIVED(void, SHComponent, T) SwapInDenseByIndex(EntityIndex index, EntityIndex hash) noexcept
+ {
+ componentSet.GetSparseSet()->SwapIndexHash(index, EntityHandleGenerator::GetIndex(hash));
+ }
+
+ /**************************************************************************
+ * \brief
+ * Swaps to positioning of two components in their dense array.
+ * This does not swap the entity that the components belong to.
+ * This swap using a component type ID
+ * \param index
+ * The entity Index of the first entity
+ * \param hash
+ * The entity ID of the second entity
+ * \param componentTypeID
+ * The Type ID of the component type ID
+ * \return
+ *
+ ***************************************************************************/
+ static void SwapInDenseByIndexHash_ID(EntityIndex index, EntityID hash, uint32_t componentTypeID) noexcept;
+
+
+
+ /*!*************************************************************************
+ * \brief
+ * Removes and destroy all components tied to an entity.
+ * entityID
+ * \param entityID
+ * entityID of the entity to be removed.
+ ***************************************************************************/
+ static void RemoveComponentsOfEntity(EntityID entityID) noexcept;
+
+
+
+ /**************************************************************************
+ * \brief
+ * Get the number of components in a component sparse set.
+ * \param componentTypeID
+ * The type ID of the Component Type.
+ * \return
+ * The number of components in the component sparse set.
+ ***************************************************************************/
+ static EntityIndex ComponentCount_ID(uint32_t componentTypeID)
+ {
+ return componentSet.GetSparseSet_ID(componentTypeID)->Count();
+ }
+
+
+ /*!*************************************************************************
+ * \brief
+ * Set the isActive boolean of all Components that the entity has
+ * \param entityID
+ * The entityID of the entity
+ * \param active
+ * The active state to set to
+ ***************************************************************************/
+ static void SetActive(EntityID entityID, bool active) noexcept;
+
+ template
+ static std::enable_if_t<(... && std::is_base_of_v), uint32_t> CreateComponentGroup(uint32_t numOwningComponents)
+ {
+ std::vector templateIDs{ (SHFamilyID::GetID())... };
+
+ for (auto& g : componentGroups)
+ {
+ for (auto const& oID : g.ownedComponentTypes)
+ {
+ for (uint32_t i = 0; i < numOwningComponents; ++i)
+ {
+ if ((templateIDs[i] == oID))
+ {
+ assert("This Component is owned by another group");
+ }
+ }
+ }
+ }
+
+ SHComponentGroup grp;
+ for (uint32_t i = 0; i < numOwningComponents; ++i)
+ {
+ grp.ownedComponentTypes.push_back(templateIDs[i]);
+ }
+ for (uint32_t i = 0; i < templateIDs.size(); ++i)
+ {
+ grp.componentTypeIDs.push_back(templateIDs[i]);
+ }
+
+ if (grp.ownedComponentTypes.size() != grp.componentTypeIDs.size())
+ {
+ if (grp.ownedComponentTypes.empty())
+ {
+ grp.ownershipType = OWNERSHIP_TYPE::NON_OWNERSHIP;
+ }
+ else
+ {
+ grp.ownershipType = OWNERSHIP_TYPE::PARTIAL_OWNERSHIP;
+ }
+ }
+
+ componentGroups.push_back(grp);
+ return (uint32_t)componentGroups.size() - 1;
+
+ }
+
+ /**************************************************************************
+ * \brief
+ * Get a reference to the component group.
+ * \param index
+ * The index of the component group
+ * \return
+ * A reference to the component group.
+ ***************************************************************************/
+ static SHComponentGroup& GetComponentGroup(uint16_t index) noexcept
+ {
+ return componentGroups[index];
+ }
+
+ static void AddScriptComponent(EntityID eid, std::string const& scriptClassName) noexcept;
+
+ static void RemoveScriptComponent(EntityID eid, std::string const& scriptClassName) noexcept;
+
+
+ };// end SHComponentManager
+
+
+
+
+
+}
+
+
+#endif
diff --git a/SHADE_Engine/src/Engine/ECS_Base/System/SHEntityManager.cpp b/SHADE_Engine/src/Engine/ECS_Base/System/SHEntityManager.cpp
new file mode 100644
index 00000000..4aa38112
--- /dev/null
+++ b/SHADE_Engine/src/Engine/ECS_Base/System/SHEntityManager.cpp
@@ -0,0 +1,232 @@
+/*********************************************************************
+ * \file SHEntityManager.cpp
+ * \author Daniel Chua Yee Chen
+ * \brief Implementation for the SHEntityManager class.
+ * Entity Manager is the interface class where users of the engine
+ * and its systems interact with entity data in the engine. This
+ * includes Creation and Destruction of entities and getting Entity by
+ * an ID. This manager also ensures that each entity have a unique
+ * handle using SHHandleGenerator.
+ *
+ * \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 "SHEntityManager.h"
+//#include "Scene/SHSceneGraph.h"
+//#include "Serialization/SHSerialization.h"
+
+namespace SHADE
+{
+ std::vector> SHEntityManager::entityVec;
+ EntityHandleGenerator SHEntityManager::entityHandle;
+
+ SHEntity* SHEntityManager::GetEntityByID(EntityID entityID) noexcept
+ {
+ if (!IsValidEID(entityID))
+ {
+ return nullptr;
+ }
+
+ EntityIndex eIndex = entityHandle.GetIndex(entityID);
+ return entityVec[eIndex].get();
+
+ }
+
+ bool SHEntityManager::IsValidEID(EntityID entityID) noexcept
+ {
+ if (!entityHandle.IsValid(entityID))
+ return false;
+
+ EntityIndex eIndex = entityHandle.GetIndex(entityID);
+ if (entityVec.size() <= eIndex || !entityVec[eIndex])
+ return false;
+
+ return true;
+
+ }
+
+ EntityIndex SHEntityManager::GetEntityIndex(EntityID entityID) noexcept
+ {
+ return entityHandle.GetIndex(entityID);
+ }
+
+ EntityID SHEntityManager::CreateEntity(std::vectorconst& componentTypeIDs, std::string const& name,EntityID parentEID)
+ {
+ EntityID eID = entityHandle.GetNewHandle();
+ EntityIndex eIndex = entityHandle.GetIndex(eID);
+ if (eIndex > entityVec.size())
+ {
+ assert("FATAL ERROR: EntityIndex out of range in Entity Creation");
+ }
+ else if (eIndex == entityVec.size())
+ {
+ entityVec.emplace_back(std::make_unique());
+ }
+ else
+ {
+ if (!entityVec[eIndex])
+ {
+ //There is still an entity stored there.Something went wrong
+ assert("FATAL ERROR: Entity Creation error. Entity Index Conflict");
+ }
+
+ //Reset it to a newly constructed entity
+ entityVec[eIndex].reset(new SHEntity());
+ }
+
+
+ entityVec[eIndex]->entityID = eID;
+ entityVec[eIndex]->name = name;
+ for (auto& id : componentTypeIDs)
+ {
+ SHComponentManager::AddComponent(eID, id);
+ }
+
+ //(SHComponentManager::AddComponent(eID), ...);
+ /*if (entityHandle.IsValid(parentEID) == false)
+ {
+ entityVec[eIndex]->sceneNode.ConnectToRoot();
+ }
+ else
+ {
+ entityVec[eIndex]->SetParent(parentEID);
+ }*/
+
+
+ //TODO Link to Scene graph.
+
+ return eID;
+
+ }
+
+ EntityID SHEntityManager::CreateEntity(std::vectorconst& componentTypeIDs, EntityID desiredEID, std::string const& name, EntityID parentEID)
+ {
+ EntityID eID ;
+
+ if (entityHandle.ClaimHandle(desiredEID) == true)
+ eID = desiredEID;
+ else
+ eID = entityHandle.GetNewHandle();
+
+
+ EntityIndex eIndex = entityHandle.GetIndex(eID);
+ if (eIndex > entityVec.size())
+ {
+ EntityIndex size = (EntityIndex)entityVec.size();
+ for (EntityIndex i = 0; i <= eIndex - size; ++i)
+ {
+ entityVec.push_back(nullptr);
+
+ }
+ entityVec[eIndex].reset(new SHEntity());
+ }
+ else if (eIndex == entityVec.size())
+ {
+ entityVec.emplace_back(std::make_unique());
+ }
+ else
+ {
+ if (!entityVec[eIndex])
+ {
+ //There is still an entity stored there.Something went wrong
+ assert("FATAL ERROR: Entity Creation error. Entity Index Conflict");
+ }
+
+ //Reset it to a newly constructed entity
+ entityVec[eIndex].reset(new SHEntity());
+ }
+
+
+ entityVec[eIndex]->entityID = eID;
+ entityVec[eIndex]->name = name;
+ for (auto& id : componentTypeIDs)
+ {
+ SHComponentManager::AddComponent(eID, id);
+ }
+
+ //(SHComponentManager::AddComponent(eID), ...);
+
+ //if (entityHandle.IsValid(parentEID) == false)
+ //{
+ // entityVec[eIndex]->sceneNode.ConnectToRoot();
+ //}
+ //else
+ //{
+ // entityVec[eIndex]->SetParent(parentEID);
+ //}
+
+ //TODO Link to scene graph.
+
+
+ return eID;
+
+ }
+
+
+ void SHEntityManager::DestroyEntity(EntityID eID) noexcept
+ {
+ if (!IsValidEID(eID))
+ {
+ //Entity does not exist or already destroyed.
+ return;
+ }
+ EntityIndex eIndex = entityHandle.GetIndex(eID);
+
+ //Call all the children to Destroy themselves first before the parent is destroyed.
+ if (entityVec[eIndex])
+ {
+ //auto& children = entityVec[eIndex]->GetChildrenID();
+ //while(!children.empty())
+ //{
+ // DestroyEntity(children[0]);
+ //}
+
+ //SHSceneNode* parentNode = entityVec[eIndex]->GetSceneNode()->GetParent();
+
+ //SHSceneGraph::RemoveChild(parentNode,entityVec[eIndex].get());
+
+ //TODO remove from parent and recursively delete child.
+
+
+
+ SHComponentManager::RemoveComponentsOfEntity(eID);
+
+ entityHandle.RemoveHandle(eID);
+
+ entityVec[eIndex].reset(nullptr);
+ }
+
+ }
+
+ void SHEntityManager::DestroyAllEntity() noexcept
+ {
+ for (auto& entity : entityVec)
+ {
+
+ if (entity)
+ {
+ DestroyEntity(entity->GetEID());
+ }
+ }
+ entityHandle.ClearAllHandles();
+ }
+
+ EntityIndex SHEntityManager::GetEntityCount() noexcept
+ {
+ return entityHandle.GetActiveHandleCount();
+ }
+
+
+ /*EntityID SHEntityManager::DuplicateEntity(EntityID eid) noexcept
+ {
+ if (entityHandle.IsValid(eid) == false)
+ return MAX_EID;
+
+ std::string data = SHSerialization::SerializeEntityToString(eid);
+ return SHSerialization::DeserializeEntityToSceneFromString(data);
+ }*/
+
+
+}
diff --git a/SHADE_Engine/src/Engine/ECS_Base/System/SHEntityManager.h b/SHADE_Engine/src/Engine/ECS_Base/System/SHEntityManager.h
new file mode 100644
index 00000000..11e896d5
--- /dev/null
+++ b/SHADE_Engine/src/Engine/ECS_Base/System/SHEntityManager.h
@@ -0,0 +1,253 @@
+/*********************************************************************
+ * \file SHEntityManger.h
+ * \author Daniel Chua Yee Chen
+ * \brief Definition for the SHEntityManager class.
+ * Entity Manager is the interface class where users of the engine
+ * and its systems interact with entity data in the engine. This
+ * includes Creation and Destruction of entities and getting Entity by
+ * an ID. This manager also ensures that each entity have a unique
+ * handle using SHHandleGenerator.
+ *
+ * \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.
+ *********************************************************************/
+
+#ifndef SH_ENTITY_MANAGER_H
+#define SH_ENTITY_MANAGER_H
+
+#include
+#include
+#include "../Entity/SHEntity.h"
+#include "../Components/SHComponent.h"
+#include "../General/SHHandleGenerator.h"
+#include "../SHECSMacros.h"
+
+namespace SHADE
+{
+
+ class SHEntityManager
+ {
+ private:
+ static std::vector> entityVec;
+ //The handle generator to generate entityIDs.
+ static EntityHandleGenerator entityHandle;
+
+ public:
+ SHEntityManager() = delete;
+ ~SHEntityManager() = delete;
+
+ /**************************************************************************
+ * \brief
+ * Get a pointer to the entity using the entityID.
+ * \param entityID
+ * The entity ID of the entity
+ * \return
+ * A pointer to the entity.
+ * A nullptr is returned if there is no such entity or if it is destroyed.
+ ***************************************************************************/
+ static SHEntity* GetEntityByID(EntityID entityID) noexcept;
+
+ /**************************************************************************
+ * \brief
+ * Checks if the current Entity ID is in use and alive.
+ * \param entityID
+ * The entity ID of the entity
+ * \return
+ * true if the entity ID is in use and alive.
+ ***************************************************************************/
+ static bool IsValidEID(EntityID entityID) noexcept;
+
+ /**************************************************************************
+ * \brief
+ * Get the index portion of the Entity ID.
+ * \param entityID
+ * The entity ID of the entity
+ * \return
+ * The index of the entity
+ ***************************************************************************/
+ static EntityIndex GetEntityIndex(EntityID entityID) noexcept;
+
+ /**************************************************************************
+ * \brief
+ * Template function to Create a new Entity with Components specified
+ * by the template arguements.
+ * \param name
+ * Name of the entity (This is not unique)
+ * \param parentEID
+ * The entity ID of the parent. This does not call UpdateHierarchy hence
+ * the parent of the entity is not updated until UpdateHierarchy is called.
+ * \return
+ * EntityID of the new Entity
+ ***************************************************************************/
+ template
+ static std::enable_if_t<(... && std::is_base_of_v), EntityID> CreateEntity(std::string const& name = "Default", EntityID parentEID = MAX_EID)
+ {
+ EntityID eID = entityHandle.GetNewHandle();
+ EntityIndex eIndex = entityHandle.GetIndex(eID);
+ if (eIndex > entityVec.size())
+ {
+ assert("FATAL ERROR: EntityIndex out of range in Entity Creation");
+ }
+ else if (eIndex == entityVec.size())
+ {
+ entityVec.emplace_back(std::make_unique());
+ }
+ else
+ {
+ if (!entityVec[eIndex])
+ {
+ //There is still an entity stored there.Something went wrong
+ assert("FATAL ERROR: Entity Creation error. Entity Index Conflict");
+ }
+
+ //Reset it to a newly constructed entity
+ entityVec[eIndex].reset(new SHEntity());
+ }
+ entityVec[eIndex]->entityID = eID;
+ entityVec[eIndex]->name = name;
+ (SHComponentManager::AddComponent(eID),...);
+
+ /*if (entityHandle.IsValid(parentEID) == false)
+ {
+ entityVec[eIndex]->sceneNode.ConnectToRoot();
+ }
+ else
+ {
+ entityVec[eIndex]->SetParent(parentEID);
+ }*/
+
+ //TODO Link up with Scene graph
+
+ return eID;
+ }
+
+ template
+ static std::enable_if_t<(... && std::is_base_of_v), EntityID> CreateEntity(EntityID desiredEID, std::string const& name = "Default", EntityID parentEID = MAX_EID)
+ {
+ EntityID eID;
+ if (entityHandle.ClaimHandle(desiredEID) == true)
+ eID = desiredEID;
+ else
+ eID = entityHandle.GetNewHandle();
+ EntityIndex eIndex = entityHandle.GetIndex(eID);
+ if (eIndex > entityVec.size())
+ {
+ EntityIndex size = (EntityIndex)entityVec.size();
+ for (EntityIndex i = 0; i <= eIndex - size; ++i)
+ {
+ entityVec.push_back(nullptr);
+
+ }
+ entityVec[eIndex].reset(new SHEntity());
+ }
+ else if (eIndex == entityVec.size())
+ {
+ entityVec.emplace_back(std::make_unique());
+ }
+ else
+ {
+ if (!entityVec[eIndex])
+ {
+ //There is still an entity stored there.Something went wrong
+ assert("FATAL ERROR: Entity Creation error. Entity Index Conflict");
+ }
+
+ //Reset it to a newly constructed entity
+ entityVec[eIndex].reset(new SHEntity());
+ }
+ entityVec[eIndex]->entityID = eID;
+ entityVec[eIndex]->name = name;
+ (SHComponentManager::AddComponent(eID), ...);
+
+ /*if (entityHandle.IsValid(parentEID) == false)
+ {
+ entityVec[eIndex]->sceneNode.ConnectToRoot();
+ }
+ else
+ {
+ entityVec[eIndex]->SetParent(parentEID);
+ }*/
+
+
+ //Link up with scene graph.
+
+
+ return eID;
+ }
+
+
+
+
+ /**************************************************************************
+ * \brief
+ * Create Entity using a vector of ComponentTypeIDs.
+ * \param componentTypeIDs
+ * Vector of ComponentTypeIDs. This assumes that CreateSparseSet is called
+ * for these ComponentTypes.
+ * \param name
+ * Name of the Entity (this is not unique)
+ * \param parentEID
+ * The entity ID of the parent. This does not call UpdateHierarchy hence
+ * the parent of the entity is not updated until UpdateHierarchy is called.
+ * \return
+ * EntityID of the new Entity
+ ***************************************************************************/
+ static EntityID CreateEntity(std::vectorconst& componentTypeIDs,std::string const& name = "Default", EntityID parentEID = MAX_EID);
+
+ /**************************************************************************
+ * \brief
+ * Create Entity using a vector of ComponentTypeIDs.
+ * \param componentTypeIDs
+ * Vector of ComponentTypeIDs. This assumes that CreateSparseSet is called
+ * for these ComponentTypes.
+ * \param name
+ * Name of the Entity (this is not unique)
+ * \param parentEID
+ * The entity ID of the parent. This does not call UpdateHierarchy hence
+ * the parent of the entity is not updated until UpdateHierarchy is called.
+ * \return
+ * EntityID of the new Entity
+ ***************************************************************************/
+ static EntityID CreateEntity(std::vectorconst& componentTypeIDs, EntityID desiredEID, std::string const& name = "Default", EntityID parentEID = MAX_EID);
+
+ /**************************************************************************
+ * \brief
+ * Destroy the entity and all components tied to this entity.
+ * This calls Destroy Entity for all of its children as well.
+ * \param eID
+ * The entity ID of the entity
+ * \return
+ * none
+ ***************************************************************************/
+ static void DestroyEntity(EntityID eID) noexcept;
+
+ /**************************************************************************
+ * \brief
+ * Destroy all Entities.
+ * \return
+ * none
+ ***************************************************************************/
+ static void DestroyAllEntity() noexcept;
+
+ /**************************************************************************
+ * \brief
+ * Get the current number of entities.
+ * \return
+ * Number of entities.
+ ***************************************************************************/
+ static EntityIndex GetEntityCount() noexcept;
+
+ //static EntityID DuplicateEntity(EntityID eid) noexcept;
+
+ protected:
+
+
+ };
+
+
+}
+
+
+
+#endif
diff --git a/SHADE_Engine/src/Engine/ECS_Base/System/SHSystem.h b/SHADE_Engine/src/Engine/ECS_Base/System/SHSystem.h
new file mode 100644
index 00000000..1a304605
--- /dev/null
+++ b/SHADE_Engine/src/Engine/ECS_Base/System/SHSystem.h
@@ -0,0 +1,55 @@
+/*********************************************************************
+ * \file SHSystem.h
+ * \author Daniel Chua Yee Chen
+ * \brief Declaration for the SHSytem abstract base class
+ *
+ * \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.
+ *********************************************************************/
+
+#ifndef SH_SYSTEM_H
+#define SH_SYSTEM_H
+
+namespace SHADE
+{
+ class SHSystem
+ {
+ protected:
+ /*!*************************************************************************
+ * \brief
+ * Protected default constructor for SHSytem class
+ ***************************************************************************/
+ SHSystem()= default;
+
+ public:
+ /*!*************************************************************************
+ * \brief
+ * Destructor for SHSytem class
+ ***************************************************************************/
+ virtual ~SHSystem() = default;
+
+ /*!*************************************************************************
+ * \brief
+ * Pure virtual Init function. Derived class must implement this
+ ***************************************************************************/
+ virtual void Init() = 0;
+
+ /*!*************************************************************************
+ * \brief
+ * Pure virtual Run function. Derived class must implement this
+ * \param dt
+ * Delta time
+ ***************************************************************************/
+ virtual void Run(float dt) = 0;
+
+ /*!*************************************************************************
+ * \brief
+ * Pure virtual Exit function. Derived class must implement this
+ ***************************************************************************/
+ virtual void Exit() = 0;
+
+ };
+}
+
+#endif
\ No newline at end of file
diff --git a/SHADE_Engine/src/Engine/ECS_Base/System/SHSystemManager.cpp b/SHADE_Engine/src/Engine/ECS_Base/System/SHSystemManager.cpp
new file mode 100644
index 00000000..67d6f781
--- /dev/null
+++ b/SHADE_Engine/src/Engine/ECS_Base/System/SHSystemManager.cpp
@@ -0,0 +1,57 @@
+/*********************************************************************
+ * \file SHSystemManager.cpp
+ * \author Daniel Chua Yee Chen
+ * \brief Implementation for the SHSystemManager class.
+ * SHSystemManager is the interface class where users of the engine create
+ * the systems that gives the components their functionality. This also
+ * ensures that the Init and Exit functions are ran at the appropriate time
+ *
+ * \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 "SHSystemManager.h"
+#include
+
+namespace SHADE
+{
+ SHSystemManager::SystemContainer SHSystemManager::systemContainer;
+
+
+ SHSystem* SHSystemManager::GetSystem(std::string name)
+ {
+ if (systemContainer.find(name) == systemContainer.end())
+ {
+ assert("Get System Error: No system with such name exist.");
+ return nullptr;
+ }
+
+ return systemContainer.find(name)->second.get();
+ }
+
+ void SHSystemManager::Init() noexcept
+ {
+ for (auto& system : systemContainer)
+ {
+ system.second->Init();
+#ifdef _DEBUG
+ std::cout << system.first << " Init" << std::endl;
+#endif
+ }
+ }
+
+ void SHSystemManager::Exit() noexcept
+ {
+ for (auto& system : systemContainer)
+ {
+ system.second->Exit();
+ //delete system.second;
+ }
+
+ systemContainer.clear();
+
+ }
+
+
+}
diff --git a/SHADE_Engine/src/Engine/ECS_Base/System/SHSystemManager.h b/SHADE_Engine/src/Engine/ECS_Base/System/SHSystemManager.h
new file mode 100644
index 00000000..d5a4866d
--- /dev/null
+++ b/SHADE_Engine/src/Engine/ECS_Base/System/SHSystemManager.h
@@ -0,0 +1,102 @@
+/*********************************************************************
+ * \file SHSystemManager.h
+ * \author Daniel Chua Yee Chen
+ * \brief Declaration for the SHSystemManager class.
+ * SHSystemManager is the interface class where users of the engine create
+ * the systems that gives the components their functionality. This also ensures that the Init and Exit functions are ran at the appropriate time
+ *
+ * \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.
+ *********************************************************************/
+
+
+#ifndef SH_SYSTEM_MANAGER_H
+#define SH_SYSTEM_MANAGER_H
+
+
+#include
+#include
+#include
+#include
+#include "../System/SHSystem.h"
+
+
+namespace SHADE
+{
+
+ class SHSystemManager
+ {
+ //type definition for the container we use to store our system
+ using SystemContainer = std::unordered_map>;
+
+ private:
+ static SystemContainer systemContainer;
+
+
+ public:
+ /*!*************************************************************************
+ * This class is used as a static class.
+ * No objects of this type should be created
+ ***************************************************************************/
+ SHSystemManager() = delete;
+ ~SHSystemManager() = delete;
+
+ /**************************************************************************
+ * \brief
+ * Create a system of type T and map it to a name.
+ * throws an error if a system with the same name already exists.
+ * \param name
+ * name of the system
+ * \return
+ * none
+ ***************************************************************************/
+ template
+ static std::enable_if_t, void> CreateSystem(std::string const& name)
+ {
+ if (systemContainer.find(name) != systemContainer.end())
+ {
+ assert("System Creation Error: System with the same name already exist.");
+ }
+
+ systemContainer.emplace(name, std::make_unique());
+
+
+ }
+
+ /**************************************************************************
+ * \brief
+ * Get a pointer to the System with a specified name.
+ * \param name
+ * Name of the system in the map
+ * \return
+ * Base System pointer.
+ ***************************************************************************/
+ static SHSystem* GetSystem(std::string name);
+
+ /**************************************************************************
+ * \brief
+ * Call the Init function of all systems.
+ * \return
+ * none
+ ***************************************************************************/
+ static void Init() noexcept;
+
+ /**************************************************************************
+ * \brief
+ * Call the Exit function of all systems.
+ * \return
+ ***************************************************************************/
+ static void Exit() noexcept;
+
+
+ protected:
+
+
+ };
+
+}
+
+
+
+#endif
diff --git a/SHADE_Engine/src/Engine/SHEngine.cpp b/SHADE_Engine/src/Engine/SHEngine.cpp
index f65a5402..a7fec85b 100644
--- a/SHADE_Engine/src/Engine/SHEngine.cpp
+++ b/SHADE_Engine/src/Engine/SHEngine.cpp
@@ -1,2 +1 @@
-#include "SHpch.h"
-#include "SHEngine.h"
\ No newline at end of file
+#include "SHpch.h"
\ No newline at end of file
diff --git a/SHADE_Engine/src/Engine/SHEngine.h b/SHADE_Engine/src/Engine/SHEngine.h
index 7d723425..d6a50b32 100644
--- a/SHADE_Engine/src/Engine/SHEngine.h
+++ b/SHADE_Engine/src/Engine/SHEngine.h
@@ -1,9 +1,39 @@
-#pragma once
+#ifndef SH_ENGINE_H
+#define SH_ENGINE_H
+
+#include
+#include "Meta/SHIsDetected.h"
namespace SHADE
{
- class SHEngine
- {
-
- };
-}
\ No newline at end of file
+ template
+ using GetInit_t = decltype (std::declval().Initialize());
+
+ template
+ using GetUpdate_t = decltype (std::declval().Update());
+
+ template
+ using GetExit_t = decltype (std::declval().Exit());
+
+
+ class SHEngine
+ {
+
+ public:
+ template
+ static void Run(Args&&...args)
+ {
+ //static_assert(SHIsDetected::value, "Init Not Detected");
+ static_assert(SHIsDetected::value, "Update Not Detected");
+ static_assert(SHIsDetected::value, "Exit Not Detected");
+
+ static Application application;
+
+ application.Initialize(std::forward(args)...);
+ application.Update();
+ application.Exit();
+ };
+ };
+};
+
+#endif
diff --git a/SHADE_Engine/src/Graphics/Buffers/SHVkBuffer.cpp b/SHADE_Engine/src/Graphics/Buffers/SHVkBuffer.cpp
new file mode 100644
index 00000000..4158d3c3
--- /dev/null
+++ b/SHADE_Engine/src/Graphics/Buffers/SHVkBuffer.cpp
@@ -0,0 +1,460 @@
+#include "SHPch.h"
+#include "SHVkBuffer.h"
+#include "Graphics/Instance/SHVkInstance.h"
+#include "Graphics/Commands/SHVkCommandBuffer.h"
+
+namespace SHADE
+{
+ /***************************************************************************/
+ /*!
+
+ \brief
+
+
+ \param data
+ \param sizeToWrite
+ \param srcOffset
+ \param dstOffset
+ \param cmdBufferHdl
+
+ \return
+
+ */
+ /***************************************************************************/
+ void SHVkBuffer::TransferToDeviceResource(Handle const& cmdBufferHdl) noexcept
+ {
+ if (cmdBufferHdl && (bufferUsageFlags & vk::BufferUsageFlagBits::eTransferDst))
+ {
+ vk::BufferCopy copyRegion
+ {
+ .srcOffset = 0,
+ .dstOffset = 0,
+ .size = sizeStored,
+ };
+ cmdBufferHdl->GetVkCommandBuffer().copyBuffer(stagingBuffer, vkBuffer, 1, ©Region);
+ }
+ }
+
+ vk::Buffer SHVkBuffer::GetVkBuffer(void) const noexcept
+ {
+ return vkBuffer;
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Maps the mappedPtr member pointer.
+
+ \param vmaAllocator
+ Required VmaAllocator for mapping.
+
+ */
+ /***************************************************************************/
+ void SHVkBuffer::Map(void) noexcept
+ {
+ if (!boundToCoherent)
+ vmaMapMemory(vmaAllocator, alloc, &mappedPtr);
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Unmaps the mappedPtr member pointer. Does not work if pointer is mapped
+ persistently (i.e. buffer is bound to coherent memory).
+
+ \param vmaAllocator
+ Required VmaAllocator for unmapping.
+
+ */
+ /***************************************************************************/
+ void SHVkBuffer::Unmap(void) noexcept
+ {
+ if (!boundToCoherent)
+ {
+ vmaUnmapMemory(vmaAllocator, alloc);
+ mappedPtr = nullptr;
+ }
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Writes to the mapped pointer.
+
+ \param data
+ Pointer to source data.
+
+ \param sizeToWrite
+ Amount to write to the buffer.
+
+ \param srcOffset
+ byte offset into the source data.
+
+ \param dstOffset
+ byte offset into the destination data.
+
+ */
+ /***************************************************************************/
+ void SHVkBuffer::WriteToMemory(void* data, uint32_t sizeToWrite, uint32_t srcOffset, uint32_t dstOffset) noexcept
+ {
+ if (mappedPtr)
+ std::memcpy(static_cast(mappedPtr) + dstOffset, static_cast(data) + srcOffset, sizeToWrite);
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Simply writes data to a region of memory in the buffer. Mapping and
+ unmapping is also done if memory the buffer is bound to is HOST_VISIBLE.
+ Otherwise, only the copying is carried out.
+
+ In the instance where memory is non-coherent but HOST_VISIBLE, we want to
+ write to data and then unmap and flush it immediately. If you want to write
+ to memory in random-access fashion, consider, mapping, writing a few
+ things, unmapping then flushing.
+
+ \param vmaAllocator
+ The VMA allocator object.
+
+ \param data
+ Pointer to source data.
+
+ \param sizeToWrite
+ Amount to write to the buffer.
+
+ \param srcOffset
+ byte offset into the source data.
+
+ \param dstOffset
+ byte offset into the destination data.
+
+ */
+ /***************************************************************************/
+ void SHVkBuffer::MapWriteUnmap(void* data, uint32_t sizeToWrite, uint32_t srcOffset, uint32_t dstOffset) noexcept
+ {
+ if (!boundToCoherent)
+ {
+ // map from host visible memory to pointer, do a DMA, and then unmap
+ Map();
+ WriteToMemory(data, sizeToWrite, srcOffset, dstOffset);
+ Unmap();
+ }
+ else
+ {
+ if (mappedPtr)
+ std::memcpy(static_cast(mappedPtr) + dstOffset, static_cast(data) + srcOffset, sizeToWrite);
+ }
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Prepares the staging buffer. Called only during initialization when it is
+ known that the buffer will be a GPU only resource. We want to prep the
+ staging buffer in advance so that transfers later will be straightforward.
+
+ \param data
+ The data to write to the staging buffer.
+
+ \param srcSize
+ The amount of data to transfer.
+
+ */
+ /***************************************************************************/
+ void SHVkBuffer::PrepStagingBuffer(void* data, uint32_t srcSize) noexcept
+ {
+ // For creation of buffer
+ vk::BufferCreateInfo bufferInfo{};
+
+ // size stored same as GPU buffer
+ bufferInfo.size = sizeStored;
+
+ // We just want to set the transfer bit
+ bufferInfo.usage = vk::BufferUsageFlagBits::eTransferSrc;
+
+ // sharing mode exclusive
+ bufferInfo.sharingMode = vk::SharingMode::eExclusive;
+
+ // Set to auto detect bits
+ VmaAllocationCreateInfo allocCreateInfo{};
+ allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
+
+ // We want to just write all at once. Using random access bit could make this slow
+ allocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT;
+
+ // parameters of a vmaAllocation retrieved via vmaGetAllocationInfo
+ VmaAllocationInfo allocInfo;
+
+ // results of allocation
+ VmaAllocation stagingAlloc;
+
+ // To get around VMA's usage for C version of vulkan, create a temp first...,
+ VkBuffer tempBuffer{};
+
+ // Create the buffer...
+ vmaCreateBuffer(vmaAllocator,
+ &bufferInfo.operator VkBufferCreateInfo & (), // TODO: Verify if this works (can use renderdoc to check buffer variables?)
+ &allocCreateInfo,
+ &tempBuffer, &stagingAlloc, &allocInfo);
+
+ // then assign it to the hpp version
+ stagingBuffer = tempBuffer;
+
+ // Just map, copy then unmap
+ void* stagingBufferMappedPtr = nullptr;
+ vmaMapMemory(vmaAllocator, stagingAlloc, &stagingBufferMappedPtr);
+
+ if (stagingBufferMappedPtr)
+ std::memcpy(static_cast(stagingBufferMappedPtr), static_cast(data), srcSize);
+
+ const VkDeviceSize offsets = 0;
+ const VkDeviceSize sizes = srcSize;
+ vmaFlushAllocations(vmaAllocator, 1, &stagingAlloc, &offsets, &sizes);
+
+ vmaUnmapMemory(vmaAllocator, stagingAlloc);
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Default ctor. Initializes everything to 0 or false.
+
+ */
+ /***************************************************************************/
+ SHVkBuffer::SHVkBuffer(std::reference_wrapper allocator) noexcept
+ : vkBuffer{}
+ , stagingBuffer{}
+ , sizeStored{ 0 }
+ , mappedPtr{ nullptr }
+ , alloc {nullptr}
+ , randomAccessOptimized{false}
+ , boundToCoherent {false}
+ , vmaAllocator{allocator}
+ {
+
+ }
+
+ SHVkBuffer::SHVkBuffer(
+ uint32_t inSize,
+ void* data,
+ uint32_t srcSize,
+ std::reference_wrapper allocator,
+ vk::BufferUsageFlags bufferUsage,
+ VmaMemoryUsage memUsage,
+ VmaAllocationCreateFlags allocFlags
+ ) noexcept
+ : SHVkBuffer(allocator)
+ {
+ Init(inSize, data, srcSize, bufferUsage, memUsage, allocFlags);
+ }
+
+ SHVkBuffer::SHVkBuffer(SHVkBuffer&& rhs) noexcept
+ : vkBuffer{std::move (rhs.vkBuffer)}
+ , stagingBuffer{ std::move (rhs.stagingBuffer)}
+ , sizeStored{ std::move (rhs.sizeStored) }
+ , mappedPtr{ nullptr }
+ , alloc{ std::move (rhs.alloc) }
+ , randomAccessOptimized{ rhs.randomAccessOptimized }
+ , boundToCoherent{ rhs.boundToCoherent}
+ , vmaAllocator{ rhs.vmaAllocator }
+ , bufferUsageFlags {rhs.bufferUsageFlags}
+
+ {
+ rhs.vkBuffer = VK_NULL_HANDLE;
+ }
+
+ SHVkBuffer& SHVkBuffer::operator=(SHVkBuffer&& rhs) noexcept
+ {
+ if (&rhs == this)
+ return *this;
+
+ vkBuffer = std::move(rhs.vkBuffer);
+ stagingBuffer = std::move(rhs.stagingBuffer);
+ sizeStored = std::move(rhs.sizeStored);
+ mappedPtr = nullptr;
+ alloc = std::move(rhs.alloc);
+ randomAccessOptimized = rhs.randomAccessOptimized;
+ boundToCoherent = rhs.boundToCoherent;
+ vmaAllocator = std::move (rhs.vmaAllocator);
+ rhs.vkBuffer = VK_NULL_HANDLE;
+ bufferUsageFlags = rhs.bufferUsageFlags;
+
+ return *this;
+ }
+
+ SHVkBuffer::~SHVkBuffer(void) noexcept
+ {
+ Destroy();
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Initialize function. Mainly creates a vulkan buffer bound to a certain
+ region in a VMA memory chunk based on the size passed in. What memory
+ chunk this buffer is bound to is also dependent on the flag.
+
+ \param inSize
+ The size of the buffer.
+
+ \param data
+ Optional data for the user to pass in to perform immediate data transfer.
+
+ \param srcSize
+ Amount of (optional) data to copy to the buffer.
+
+ \param vmaAllocator
+ VMA allocator required for allocation to occur.
+
+ \param bufferUsage
+ Simple and easy. Can be used as a combination
+ (e.g. eVertexBuffer | eTransferDst).
+
+ \param memUsage
+ Usually set to VMA_MEMORY_USAGE_AUTO.
+
+ \param allocFlags
+ Most complicated parameter. Using VMA_RANDOM_ACCESS or VMA_SEQUENTIAL
+ would make the buffer bind to HOST_VISIBLE memory. Using
+ VMA_ALLOCATION_CREATE_MAPPED_BIT will map a pointer immediately (TODO:
+ Need to check if this bounds the buffer to coherent virtual memory. To
+ make this task simple, remember to check every instance of a VMA flag,
+ that the Vulkan flags are set accordingly: like if with sequential,
+ will the coherent bit be set).
+
+ */
+ /***************************************************************************/
+ void SHVkBuffer::Init (
+ uint32_t inSize,
+ void* data,
+ uint32_t srcSize,
+ vk::BufferUsageFlags bufferUsage,
+ VmaMemoryUsage memUsage,
+ VmaAllocationCreateFlags allocFlags
+ ) noexcept
+ {
+ sizeStored = inSize;
+
+ // For creation of buffer
+ vk::BufferCreateInfo bufferInfo{};
+
+ // initialize size and usage (vertex, index, uniform, etc)
+ bufferInfo.size = sizeStored;
+ bufferInfo.usage = bufferUsage;
+ bufferInfo.sharingMode = vk::SharingMode::eExclusive;
+
+ // Prepare allocation parameters for call to create buffers later
+ VmaAllocationCreateInfo allocCreateInfo{};
+ allocCreateInfo.usage = memUsage;
+
+ // If vma allocation flags include dedicated bit, immediately activate dst bit
+ if (allocCreateInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT)
+ bufferInfo.usage |= vk::BufferUsageFlagBits::eTransferDst;
+
+ allocCreateInfo.flags = allocFlags;
+
+ // parameters of a vmaAllocation retrieved via vmaGetAllocationInfo
+ VmaAllocationInfo allocInfo;
+
+ // To get around VMA's usage for C version of vulkan, create a temp first...,
+ VkBuffer tempBuffer{};
+
+ // Create the buffer...
+ auto result = vmaCreateBuffer(vmaAllocator,
+ &bufferInfo.operator VkBufferCreateInfo &(),
+ &allocCreateInfo,
+ &tempBuffer, &alloc, &allocInfo);
+
+ if (result != VK_SUCCESS)
+ SHVulkanDebugUtil::ReportVkError(vk::Result (result), "Failed to create vulkan buffer. ");
+ else
+ SHVulkanDebugUtil::ReportVkSuccess("Successfully created buffer. ");
+
+ // ...then assign it to the hpp version
+ vkBuffer = tempBuffer;
+
+ // Set the buffer flags
+ bufferUsageFlags = bufferInfo.usage;
+
+ // This probably means that a HOST_CACHED memory type is used on allocation
+ if (allocFlags & VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)
+ randomAccessOptimized = true;
+
+ /* There are 3 instances where buffers can be a GPU only resource :
+ 1. When its for a DEDICATED large chunk of memory that is usually not touch ever again
+ like images that get destroyed and recreated every time window resizes.
+ 2. When its for a memory type that is BOTH HOST_VISIBLE and DEVICE_LOCAL. This is known
+ base address register (BAR). If this address space is not available (which it should be on
+ most machines), fall back to use DEVICE_LOCAL memory and do the usual staging buffer memory transfer to
+ GPU resource.
+ 3. When the buffer is initialized with a usage dst bit.
+ */
+
+ // Get the memory property flags
+ VkMemoryPropertyFlags memPropFlags;
+ vmaGetAllocationMemoryProperties(vmaAllocator, alloc, &memPropFlags);
+
+ // mainly host visible. Can be cached (need to flush/invalidate), uncached (always coherent) and coherent (virtual).
+ if(memPropFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)
+ {
+ // If memory is marked to be coherent between CPU and GPU (no need flush/invalidate) (TODO: Verify if VMA_ALLOCATION_CREATE_MAPPED_BIT is used when VMA_MEMORY_USAGE_AUTO is set)
+ // TODO: also verify that coherent bit = pointer is already mapped
+ if (memPropFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
+ {
+ boundToCoherent = true;
+ mappedPtr = allocInfo.pMappedData;
+ }
+ else
+ mappedPtr = nullptr;
+
+ if (data)
+ MapWriteUnmap(data, srcSize, 0, 0);
+ }
+ else
+ {
+ // We can prep first so that we can do transfers later via 1 cmd buffer recording
+ PrepStagingBuffer(data, srcSize);
+
+ // #NoteToSelf: Command buffers used to be an optional argument to perform the transfer immediately but it was removed because we
+ // don't want to allow such scenarios. Ideally, we want users to be transferring data to device memory together with
+ // other buffers that perform similar transfers.
+ //if (cmdBufferHdl) // check for null handle
+ //{
+ // // case 1 and case 3
+ // if (bufferInfo.usage & vk::BufferUsageFlagBits::eTransferDst)
+ // {
+ // TransferToDeviceResource(cmdBufferHdl);
+ // }
+ // //case 2
+ // else if (allocCreateInfo.flags & VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT)
+ // {
+ // // Need to check if BAR exists, if it doesn't, fall back to DEVICE_LOCAL, and do regular explicit transfers from staging
+ // }
+ //}
+ }
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Destroys the buffer.
+
+ \param allocator
+ VMA allocator required to destroy the buffer.
+
+ */
+ /***************************************************************************/
+ void SHVkBuffer::Destroy(void) noexcept
+ {
+ vmaDestroyBuffer(vmaAllocator, vkBuffer, alloc);
+ }
+
+}
diff --git a/SHADE_Engine/src/Graphics/Buffers/SHVkBuffer.h b/SHADE_Engine/src/Graphics/Buffers/SHVkBuffer.h
new file mode 100644
index 00000000..2ad3e4e9
--- /dev/null
+++ b/SHADE_Engine/src/Graphics/Buffers/SHVkBuffer.h
@@ -0,0 +1,106 @@
+#ifndef SH_VK_BUFFER_H
+#define SH_VK_BUFFER_H
+
+#include "Graphics/SHVulkanIncludes.h"
+#include "vk_mem_alloc.h"
+#include "Resource/Handle.h"
+
+namespace SHADE
+{
+ // Mainly so that middle end doesn't need to call "vk::"
+ //using SHVkBufferUsage = vk::BufferUsageFlags;
+ //using SHVkBufferUsageBits = vk::BufferUsageFlagBits;
+
+ class SHVkCommandBuffer;
+
+ class SHVkBuffer
+ {
+ private:
+ /*-----------------------------------------------------------------------*/
+ /* PRIVATE MEMBER VARIABLES */
+ /*-----------------------------------------------------------------------*/
+ //! Vulkan handle to a vkBuffer
+ vk::Buffer vkBuffer;
+
+ //! When the buffer initialized to be a GPU only resource, this buffer will
+ //! be necessary to perform transfer to GPU either during initialization
+ //! or whenever the user wants it.
+ vk::Buffer stagingBuffer;
+
+ //! The amount of memory this buffer is bound to in device/host memory
+ uint32_t sizeStored;
+
+ //! Persistently mapped pointer if applicable (will be void if buffer is
+ //! not created with the correct flags). Note that this is only used for
+ //! persistent mapping. One time updates do not use this pointer.
+ void* mappedPtr;
+
+ //! allocation object containing details of an allocation
+ VmaAllocation alloc;
+
+ //! If initialized with vma random access flag, this is true
+ bool randomAccessOptimized;
+
+ //! Whether or not this buffer is bound to coherent memory
+ bool boundToCoherent;
+
+ //! buffer usage info flags
+ vk::BufferUsageFlags bufferUsageFlags;
+
+ //! Reference to the allocator
+ //VmaAllocator const& vmaAllocator;
+ std::reference_wrapper vmaAllocator;
+
+ /*-----------------------------------------------------------------------*/
+ /* PRIVATE MEMBER FUNCTIONS */
+ /*-----------------------------------------------------------------------*/
+ void PrepStagingBuffer (void* data, uint32_t srcSize) noexcept;
+
+ public:
+ /*-----------------------------------------------------------------------*/
+ /* CTORS AND DTORS */
+ /*-----------------------------------------------------------------------*/
+ SHVkBuffer (void) noexcept = delete;
+ SHVkBuffer (std::reference_wrapper allocator) noexcept;
+ SHVkBuffer (
+ uint32_t inSize,
+ void* data,
+ uint32_t srcSize,
+ std::reference_wrapper allocator,
+ vk::BufferUsageFlags bufferUsage,
+ VmaMemoryUsage memUsage,
+ VmaAllocationCreateFlags allocFlags
+ ) noexcept;
+ SHVkBuffer(SHVkBuffer&& rhs) noexcept;
+ SHVkBuffer& operator=(SHVkBuffer&& rhs) noexcept;
+ ~SHVkBuffer(void) noexcept;
+
+
+ /*-----------------------------------------------------------------------*/
+ /* PUBLIC MEMBER VARIABLES */
+ /*-----------------------------------------------------------------------*/
+ void Init (
+ uint32_t inSize,
+ void* data,
+ uint32_t srcSize,
+ vk::BufferUsageFlags bufferUsage,
+ VmaMemoryUsage memUsage,
+ VmaAllocationCreateFlags allocFlags
+ ) noexcept;
+ void Destroy (void) noexcept;
+
+ void Map (void) noexcept;
+ void Unmap (void) noexcept;
+ void WriteToMemory (void* data, uint32_t sizeToWrite, uint32_t srcOffset, uint32_t dstOffset) noexcept;
+ void MapWriteUnmap (void* data, uint32_t sizeToWrite, uint32_t srcOffset, uint32_t dstOffset) noexcept;
+ void TransferToDeviceResource(Handle const& cmdBufferHdl) noexcept;
+
+ /*-----------------------------------------------------------------------*/
+ /* SETTERS AND GETTERS */
+ /*-----------------------------------------------------------------------*/
+ vk::Buffer GetVkBuffer (void) const noexcept;
+
+ };
+}
+
+#endif
diff --git a/SHADE_Engine/src/Graphics/Commands/SHCommandPoolResetMode.h b/SHADE_Engine/src/Graphics/Commands/SHCommandPoolResetMode.h
new file mode 100644
index 00000000..4ecc0098
--- /dev/null
+++ b/SHADE_Engine/src/Graphics/Commands/SHCommandPoolResetMode.h
@@ -0,0 +1,13 @@
+#ifndef SH_COMMAND_POOL_RESET_H
+#define SH_COMMAND_POOL_RESET_H
+
+namespace SHADE
+{
+ enum class SH_CMD_POOL_RESET
+ {
+ POOL_BASED,
+ BUFFER_BASED,
+ };
+}
+
+#endif
diff --git a/SHADE_Engine/src/Graphics/Commands/SHVkCommandBuffer.cpp b/SHADE_Engine/src/Graphics/Commands/SHVkCommandBuffer.cpp
new file mode 100644
index 00000000..6a307230
--- /dev/null
+++ b/SHADE_Engine/src/Graphics/Commands/SHVkCommandBuffer.cpp
@@ -0,0 +1,641 @@
+#include "SHPch.h"
+#include "SHVkCommandBuffer.h"
+#include "SHVkCommandPool.h"
+#include "Graphics/Devices/SHVkLogicalDevice.h"
+#include "SHVkCommandPool.h"
+#include "Tools/SHLogger.h"
+#include "Graphics/Renderpass/SHVkRenderpass.h"
+#include "Graphics/Framebuffer/SHVkFramebuffer.h"
+#include "Graphics/Pipeline/SHVkPipeline.h"
+#include "Graphics/Buffers/SHVkBuffer.h"
+
+
+namespace SHADE
+{
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Frees the command buffer.
+
+ */
+ /***************************************************************************/
+ SHVkCommandBuffer::~SHVkCommandBuffer(void) noexcept
+ {
+ if (vkCommandBuffer)
+ parentPool->GetLogicalDevice()->GetVkLogicalDevice().freeCommandBuffers(parentPool->GetVkCommandPool(), commandBufferCount, &vkCommandBuffer);
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Only the command buffer is allocated using
+ VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT bit, is resetting
+ individually permitted. Otherwise, throw exception. IMPORTANT NOTE:
+ the command buffer cannot be in the pending state!!!
+
+ */
+ /***************************************************************************/
+ void SHVkCommandBuffer::Reset(void)
+ {
+ if (cmdBufferState == SH_CMD_BUFFER_STATE::PENDING)
+ {
+ SHLOG_ERROR("Command buffer in pending state, could not reset. ");
+ return;
+ }
+
+ if (parentPool->GetPoolResetMode() != SH_CMD_POOL_RESET::BUFFER_BASED)
+ {
+ SHLOG_ERROR("Parent Command Pool was not initialized with VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT. Cannot reset independently. ");
+ return;
+ }
+
+ vkCommandBuffer.reset(vk::CommandBufferResetFlagBits::eReleaseResources);
+
+ if (cmdBufferState == SH_CMD_BUFFER_STATE::RECORDING || cmdBufferState == SH_CMD_BUFFER_STATE::EXECUTABLE)
+ {
+ cmdBufferState = SH_CMD_BUFFER_STATE::INVALID;
+ return;
+ }
+
+ if (cmdBufferState != SH_CMD_BUFFER_STATE::INVALID)
+ cmdBufferState = SH_CMD_BUFFER_STATE::INITIAL;
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Begins the command buffer.
+
+ */
+ /***************************************************************************/
+ void SHVkCommandBuffer::BeginRecording(void) noexcept
+ {
+ // Check if command buffer is ready to record.
+ if (cmdBufferState != SH_CMD_BUFFER_STATE::INITIAL)
+ {
+ SHLOG_ERROR("Command buffer not in initial state, cannot begin recording. ");
+ return;
+ }
+
+ // Struct for recording
+ vk::CommandBufferBeginInfo beginInfo{};
+
+ beginInfo.flags = usageFlags;
+ // TODO: Allow passing in inheritance info.
+
+ // Attempt to begin recording
+ if (auto result = vkCommandBuffer.begin(&beginInfo); result != vk::Result::eSuccess)
+ {
+ SHVulkanDebugUtil::ReportVkError(result, "Failed to begin command buffer. ");
+ return;
+ }
+
+ // We don't need to print record success
+ //else
+ // SHVulkanDebugUtil::ReportVkSuccess("Command buffer successfully begun recording... ");
+
+ // Set the state to recording if the call above succeeded.
+ cmdBufferState = SH_CMD_BUFFER_STATE::RECORDING;
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ End the recording of a command buffer.
+
+ */
+ /***************************************************************************/
+ void SHVkCommandBuffer::EndRecording(void) noexcept
+ {
+ if (cmdBufferState != SH_CMD_BUFFER_STATE::RECORDING)
+ {
+ SHLOG_ERROR("Command Buffer not in recording state, cannot end recording. ");
+ return;
+ }
+
+ vkCommandBuffer.end();
+ cmdBufferState = SH_CMD_BUFFER_STATE::EXECUTABLE;
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Begins a renderpass in the command buffer. 2 important things to note
+ here, the command buffer used MUST be a primary command buffer and
+ command buffer MUST be in a recording state.
+
+ \param renderpassHdl
+ Renderpass for obvious reasons.
+
+ \param framebufferHdl
+ Framebuffer required in the begin info.
+
+ \param offset
+ Offset of the render area in the framebuffer.
+
+ \param extent
+ Extent of the render area in the framebuffer.
+
+ */
+ /***************************************************************************/
+ void SHVkCommandBuffer::BeginRenderpass(Handle const& renderpassHdl, Handle const& framebufferHdl, vk::Offset2D offset, vk::Extent2D extent) noexcept
+ {
+ // cannot begin renderpass if command buffer is primary
+ if (commandBufferType != SH_CMD_BUFFER_TYPE::PRIMARY)
+ {
+ SHLOG_ERROR("Cannot begin renderpass. Command buffer is not a primary command buffer. ");
+ return;
+ }
+
+ // cannot begin renderpass if command buffer is not recording
+ if (cmdBufferState != SH_CMD_BUFFER_STATE::RECORDING)
+ {
+ SHLOG_ERROR("Command buffer must have started recording before a renderpass instance can begin. ");
+ return;
+ }
+
+ vk::Extent2D framebufferExtent{ framebufferHdl->GetWidth(), framebufferHdl->GetHeight() };
+
+ // Prepare renderpass begin
+ vk::RenderPassBeginInfo renderPassInfo{};
+ renderPassInfo.renderPass = renderpassHdl->GetVkRenderpass();
+ renderPassInfo.framebuffer = framebufferHdl->GetVkFramebuffer();
+
+ // If the extent passed in is 0, use the framebuffer dimensions instead.
+ if (extent.width == 0 && extent.height == 0)
+ renderPassInfo.renderArea.extent = framebufferExtent;
+ else
+ renderPassInfo.renderArea.extent = extent;
+
+ // assign offset
+ renderPassInfo.renderArea.offset = offset;
+
+ // prepare clear colors
+ auto const& clearColors = renderpassHdl->GetClearColors();
+ renderPassInfo.clearValueCount = static_cast(clearColors.size());
+ renderPassInfo.pClearValues = clearColors.data();
+
+ // Check if render area is optimal
+ if (!IsRenderAreaOptimal(renderpassHdl, framebufferExtent, renderPassInfo.renderArea))
+ SHLOG_ERROR("Render area in renderpass begin info is not optimal. See Vulkan vkGetRenderAreaGranularity for details.");
+
+ // Begin the render pass
+ vkCommandBuffer.beginRenderPass (&renderPassInfo, vk::SubpassContents::eInline);
+
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Ends a renderpass.
+
+ */
+ /***************************************************************************/
+ void SHVkCommandBuffer::EndRenderpass(void) noexcept
+ {
+ vkCommandBuffer.endRenderPass();
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Sets the viewport dynamically for the command buffer. #NoteToSelf:
+ Dynamic state will not affect pipelines that don't use dynamic state
+ so there isn't a need to do any checks. Also, setting dynamic state like
+ this only needs to happen ONCE per command buffer UNLESS a different
+ viewport is to be used for different drawing commands.
+
+ \param vpWidth
+ viewport width
+
+ \param vpHeight
+ viewport height
+
+ \param sWidth
+ Scissor extent width
+
+ \param sHeight
+ Scissor extent height
+
+ \param vpX
+ Viewport offset X.
+
+ \param vpY
+ Viewport offset Y.
+
+ \param sX
+ Scissor offset X.
+
+ \param sY
+ Scissor offset Y.
+
+ \param vpMinDepth
+ viewport minimum depth value
+
+ \param vpMaxDepth
+ viewport maximum depth value
+
+
+ */
+ /***************************************************************************/
+ void SHVkCommandBuffer::SetviewportScissor(float vpWidth, float vpHeight, uint32_t sWidth, uint32_t sHeight, float vpX /*= 0.0f*/, float vpY /*= 0.0f*/, int32_t sX /*= 0.0f*/, int32_t sY /*= 0.0f*/, float vpMinDepth /*= 0.0f*/, float vpMaxDepth /*= 1.0f*/) noexcept
+ {
+ vk::Viewport dynamicViewport
+ {
+ .x = vpX,
+ .y = vpY,
+ .width = vpWidth,
+ .height = vpHeight,
+ .minDepth = vpMinDepth,
+ .maxDepth = vpMaxDepth,
+ };
+
+ vk::Rect2D dynamicScissor
+ {
+ .offset = vk::Offset2D{sX, sY},
+ .extent = vk::Extent2D{sWidth, sHeight}
+ };
+
+ // Dynamic state set viewport and scissor
+ vkCommandBuffer.setScissor(0, 1, &dynamicScissor);
+ vkCommandBuffer.setViewport(0, 1, &dynamicViewport);
+
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Binds a pipeline object to the command buffer.
+
+ \param pipelineHdl
+ The pipeline to bind.
+
+ */
+ /***************************************************************************/
+ void SHVkCommandBuffer::BindPipeline(Handle const& pipelineHdl) noexcept
+ {
+ if (cmdBufferState != SH_CMD_BUFFER_STATE::RECORDING)
+ {
+ SHLOG_ERROR("Command buffer must have started recording before a pipeline can be bound. ");
+ return;
+ }
+ boundPipelineLayoutHdl = pipelineHdl->GetPipelineLayout();
+ vkCommandBuffer.bindPipeline(pipelineHdl->GetPipelineBindPoint(), pipelineHdl->GetVkPipeline());
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Binds a buffer to the vertex buffer binding point specified in
+ bindingPoint.
+
+ \param bindingPoint
+ The binding point to initialize a vertex
+
+ \param buffer
+ The buffer to bind
+
+ \param offset
+ The offset to start from in the buffer for the first binding point.
+
+ */
+ /***************************************************************************/
+ void SHVkCommandBuffer::BindVertexBuffer (uint32_t bindingPoint, Handle const& buffer, vk::DeviceSize offset) noexcept
+ {
+ if (cmdBufferState == SH_CMD_BUFFER_STATE::RECORDING)
+ {
+ auto bufferHandle = buffer->GetVkBuffer();
+ vkCommandBuffer.bindVertexBuffers (bindingPoint, 1, &bufferHandle, &offset);
+ }
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Binds an index buffer to the pipeline.
+
+ \param buffer
+ The buffer to bind.
+
+ \param startingIndex
+ The starting index in the index buffer. For example, 0 would mean
+ starting at the beginning. 5 would mean starting at byte offset
+ size(uint32_t) * 5.
+
+ */
+ /***************************************************************************/
+ void SHVkCommandBuffer::BindIndexBuffer(Handle const& buffer, uint32_t startingIndex) const noexcept
+ {
+ if (cmdBufferState == SH_CMD_BUFFER_STATE::RECORDING)
+ {
+ auto bufferHandle = buffer->GetVkBuffer();
+ vkCommandBuffer.bindIndexBuffer (bufferHandle, sizeof (uint32_t) * startingIndex, vk::IndexType::eUint32);
+ }
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Calls vkCmdDraw.
+
+ \param vertexCount
+ How many vertices to draw
+
+ \param instanceCount
+ Number of instances to draw
+
+ \param firstVertex
+ First vertex in the buffer of vertices to start from
+
+ \param firstInstance
+ First instance to start from.
+
+ */
+ /***************************************************************************/
+ void SHVkCommandBuffer::DrawArrays(uint32_t vertexCount, uint32_t instanceCount, uint32_t firstVertex, uint32_t firstInstance) const noexcept
+ {
+ if (cmdBufferState != SH_CMD_BUFFER_STATE::RECORDING)
+ {
+ SHLOG_ERROR("Command buffer must have started recording before a pipeline can be bound. ");
+ return;
+ }
+ vkCommandBuffer.draw (vertexCount, instanceCount, firstVertex, firstInstance);
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Issues a non-instanced indexed draw call.
+
+ \param indexCount
+ Number of indices to draw.
+
+ \param firstIndex
+ Starting index. if the array was 0, 2, 5, 4, and we indicated this to be
+ 1. The draw call would start from index 2.
+
+ \param vertexOffset
+ Starting vertex offset. This would indicate that vertex pulling should
+ start from a certain vertex. So a vertex offset of 3 (for example) would
+ mean an index of 0 would mean the 3rd vertex.
+
+ */
+ /***************************************************************************/
+ void SHVkCommandBuffer::DrawIndexed (uint32_t indexCount, uint32_t firstIndex, uint32_t vertexOffset) const noexcept
+ {
+ if (cmdBufferState != SH_CMD_BUFFER_STATE::RECORDING)
+ {
+ SHLOG_ERROR("Command buffer must have started recording before a pipeline can be bound. ");
+ return;
+ }
+
+ // not an instanced call so we want to make the instanced related stuff hard coded
+ vkCommandBuffer.drawIndexed(indexCount, 1, firstIndex, vertexOffset, 0);
+
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Calls vkCmdPushConstants and submits data stored in command buffer.
+
+ */
+ /***************************************************************************/
+ void SHVkCommandBuffer::SubmitPushConstants(void) const noexcept
+ {
+ vkCommandBuffer.pushConstants(boundPipelineLayoutHdl->GetVkPipelineLayout(),
+ boundPipelineLayoutHdl->GetPushConstantInterface().GetShaderStageFlags(),
+ 0,
+ boundPipelineLayoutHdl->GetPushConstantInterface().GetSize(), pushConstantData);
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Simply returns the command buffer handle.
+
+ \return
+ The command buffer handle.
+
+ */
+ /***************************************************************************/
+ vk::CommandBuffer const& SHVkCommandBuffer::GetVkCommandBuffer(void) const noexcept
+ {
+ return vkCommandBuffer;
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ See https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkGetRenderAreaGranularity.html
+ or look up vkGetRenderAreaGranularity.
+
+ \param renderpassHdl
+ Renderpass to get info from.
+
+ \param framebufferExtent
+ For the comparison. Again, look it up on the webpage.
+
+ \param renderArea
+ For the comparison. Again, look it up on the webpage.
+
+ \return
+ If optimal, true. otherwise false.
+
+ */
+ /***************************************************************************/
+ bool SHVkCommandBuffer::IsRenderAreaOptimal(Handle const& renderpassHdl, vk::Extent2D const& framebufferExtent, vk::Rect2D const& renderArea) const noexcept
+ {
+ vk::Extent2D granularity = parentPool->GetLogicalDevice()->GetVkLogicalDevice().getRenderAreaGranularity(renderpassHdl->GetVkRenderpass());
+
+ return (renderArea.offset.x % granularity.width == 0 && renderArea.offset.y % granularity.height == 0 &&
+ (renderArea.extent.width % granularity.width || renderArea.offset.x + renderArea.extent.width == framebufferExtent.width) &&
+ (renderArea.extent.height % granularity.height || renderArea.offset.y + renderArea.extent.height == framebufferExtent.height));
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Setter for the state of the command buffer.
+
+ \param state
+
+ \return
+
+ */
+ /***************************************************************************/
+ void SHVkCommandBuffer::SetState(SH_CMD_BUFFER_STATE state) noexcept
+ {
+ cmdBufferState = state;
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Returns the state of the command buffer.
+
+ \return
+
+ */
+ /***************************************************************************/
+ SH_CMD_BUFFER_STATE SHVkCommandBuffer::GetState(void) const noexcept
+ {
+ return cmdBufferState;
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Creates a command buffer. Cmd buffer can be primary or secondary. If
+ secondary, flags will automatically have renderpass continue bit. Command
+ pool used to create this command buffer will determine whether or not
+ this buffer will be allocated with
+ VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT using the reset mode.
+
+ \param logicalDevice
+ Need a logical device to create a buffer.
+
+ \param commandPool
+ Command buffer to allocate from.
+
+ \param type
+ Type of the command buffer; primary or secondary.
+
+ */
+ /***************************************************************************/
+ SHVkCommandBuffer::SHVkCommandBuffer(Handle const& commandPool, SH_CMD_BUFFER_TYPE type) noexcept
+ : vkCommandBuffer{ nullptr }
+ , cmdBufferState{ SH_CMD_BUFFER_STATE::INVALID } // Command buffer will be in initial state
+ , commandBufferType{ SH_CMD_BUFFER_TYPE::PRIMARY }
+ , parentPoolResetMode{ SH_CMD_POOL_RESET::POOL_BASED }
+ , usageFlags{}
+ , commandBufferCount{ 0 }
+ , parentPool{commandPool}
+
+ {
+ vk::CommandBufferAllocateInfo allocateInfo{};
+ allocateInfo.commandPool = commandPool->GetVkCommandPool();
+
+ // don't know if there are performance implications if this is set to always be 1. Could be better to create more at once
+ allocateInfo.commandBufferCount = 1;
+
+ // Set the type of command buffer (primary or secondary)
+ switch (type)
+ {
+ case SH_CMD_BUFFER_TYPE::PRIMARY:
+ allocateInfo.level = vk::CommandBufferLevel::ePrimary;
+ break;
+ case SH_CMD_BUFFER_TYPE::SECONDARY:
+ allocateInfo.level = vk::CommandBufferLevel::eSecondary;
+ break;
+ }
+
+ // Attempt to allocate command buffers
+ if (auto result = commandPool->GetLogicalDevice()->GetVkLogicalDevice().allocateCommandBuffers(&allocateInfo, &vkCommandBuffer); result != vk::Result::eSuccess)
+ {
+ SHVulkanDebugUtil::ReportVkError(result, "Failed to create Command Buffer. ");
+ return;
+ }
+ else
+ SHVulkanDebugUtil::ReportVkSuccess("Successfully created Command Buffer.");
+
+ // Set the state only after successfully allocating
+ cmdBufferState = SH_CMD_BUFFER_STATE::INITIAL;
+
+ // Parent command pool
+ parentPool = commandPool;
+
+ // Save some important info
+ parentPoolResetMode = parentPool->GetPoolResetMode();
+ commandBufferType = type;
+ commandBufferCount = allocateInfo.commandBufferCount;
+
+ if (parentPool->GetIsTransient ())
+ usageFlags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
+
+ if (commandBufferType == SH_CMD_BUFFER_TYPE::SECONDARY)
+ usageFlags |= vk::CommandBufferUsageFlagBits::eRenderPassContinue;
+
+ // Reset all the push constant data to 0
+ memset (pushConstantData, 0, PUSH_CONSTANT_SIZE);
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Move ctor. Invalidates Vulkan handles.
+
+ \param rhs
+ the other command buffer.
+
+ */
+ /***************************************************************************/
+ SHVkCommandBuffer::SHVkCommandBuffer(SHVkCommandBuffer&& rhs) noexcept
+ : vkCommandBuffer {std::move (rhs.vkCommandBuffer)}
+ , cmdBufferState {rhs.cmdBufferState}
+ , commandBufferType {rhs.commandBufferType}
+ , parentPoolResetMode {rhs.parentPoolResetMode}
+ , usageFlags {rhs.usageFlags}
+ , commandBufferCount {rhs.commandBufferCount}
+ , parentPool {rhs.parentPool}
+ , boundPipelineLayoutHdl{rhs.boundPipelineLayoutHdl }
+ {
+ memcpy (pushConstantData, rhs.pushConstantData, PUSH_CONSTANT_SIZE);
+
+ rhs.vkCommandBuffer = VK_NULL_HANDLE;
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Move assignment operator. Invalidates Vulkan handles.
+
+ \param rhs
+ The other Vulkan Handle.
+
+ \return
+ a reference itself.
+
+ */
+ /***************************************************************************/
+ SHVkCommandBuffer& SHVkCommandBuffer::operator=(SHVkCommandBuffer&& rhs) noexcept
+ {
+ if (&rhs == this)
+ return *this;
+
+ vkCommandBuffer = std::move(rhs.vkCommandBuffer);
+ cmdBufferState = rhs.cmdBufferState;
+ commandBufferType = rhs.commandBufferType;
+ parentPoolResetMode = rhs.parentPoolResetMode;
+ usageFlags = rhs.usageFlags;
+ commandBufferCount = rhs.commandBufferCount;
+ parentPool = rhs.parentPool;
+ boundPipelineLayoutHdl = rhs.boundPipelineLayoutHdl;
+ memcpy(pushConstantData, rhs.pushConstantData, PUSH_CONSTANT_SIZE);
+
+ rhs.vkCommandBuffer = VK_NULL_HANDLE;
+
+ return *this;
+ }
+
+}
diff --git a/SHADE_Engine/src/Graphics/Commands/SHVkCommandBuffer.h b/SHADE_Engine/src/Graphics/Commands/SHVkCommandBuffer.h
new file mode 100644
index 00000000..08fc45f7
--- /dev/null
+++ b/SHADE_Engine/src/Graphics/Commands/SHVkCommandBuffer.h
@@ -0,0 +1,134 @@
+#ifndef SH_COMMAND_BUFFER_H
+#define SH_COMMAND_BUFFER_H
+
+#include "Graphics/SHVulkanIncludes.h"
+#include "Graphics/SHVulkanDefines.h"
+#include "SHCommandPoolResetMode.h"
+#include "Resource/ResourceLibrary.h"
+#include "Graphics/Pipeline/SHVkPipelineLayout.h"
+
+namespace SHADE
+{
+ class SHVkCommandPool;
+ class SHVkLogicalDevice;
+ class SHVkRenderpass;
+ class SHVkFramebuffer;
+ class SHVkPipeline;
+ class SHVkBuffer;
+
+ enum class SH_CMD_BUFFER_TYPE
+ {
+ PRIMARY,
+ SECONDARY,
+ };
+
+ enum class SH_CMD_BUFFER_STATE
+ {
+ INITIAL, // Can be moved to recording state or freed
+ RECORDING, // vkBeginCommandBuffer changes state from initial state to recording state.
+ EXECUTABLE, // Can be submitted, reset or recorded to another command buffer.
+ INVALID, // Enters invalid state when buffer created with ONE_TIME_SUBMIT_BIT finishes execution. Primaries also enter the invalid state when secondaries enter invalid or initial state
+ PENDING // Cmd buffer enters this state after being submitted to queue.
+ };
+
+ class SHVkCommandBuffer
+ {
+ friend class SHVkCommandPool;
+ friend class ResourceLibrary;
+
+ static constexpr uint16_t PUSH_CONSTANT_SIZE = 512;
+ private:
+ /*-----------------------------------------------------------------------*/
+ /* PRIVATE MEMBER VARIABLES */
+ /*-----------------------------------------------------------------------*/
+ //! Vulkan handle to a command buffer
+ vk::CommandBuffer vkCommandBuffer;
+
+ //! state of the command buffer. TODO: Test some state changes.
+ SH_CMD_BUFFER_STATE cmdBufferState;
+
+ //! Command buffer type
+ SH_CMD_BUFFER_TYPE commandBufferType;
+
+ //! Stores the reset mode of the command pool. This is so that when we
+ //! try to reset command buffers individually, we want to do it only when
+ //! the reset mode is set to COMMAND_BUFFER_RESET only.
+ SH_CMD_POOL_RESET parentPoolResetMode;
+
+ //! Flags of the command buffer (ONE_TIME_USE, RENDERPASS_CONTINUE, SIMULTANEOUS_USAGE)
+ vk::CommandBufferUsageFlags usageFlags;
+
+ //! When allocating, you can specify how many command buffers to allocate
+ uint32_t commandBufferCount;
+
+ //! The command pool that this command buffer belongs to
+ Handle parentPool;
+
+ //! The currently bound pipeline
+ Handle boundPipelineLayoutHdl;
+
+ //! The push constant data for the command buffer
+ uint8_t pushConstantData[PUSH_CONSTANT_SIZE];
+
+ /*-----------------------------------------------------------------------*/
+ /* PRIVATE MEMBER FUNCTIONS */
+ /*-----------------------------------------------------------------------*/
+ bool IsRenderAreaOptimal(Handle const& renderpassHdl, vk::Extent2D const& framebufferExtent, vk::Rect2D const& renderArea) const noexcept;
+
+ /*-----------------------------------------------------------------------*/
+ /* PRIVATE GETTERS AND SETTERS */
+ /*-----------------------------------------------------------------------*/
+ void SetState(SH_CMD_BUFFER_STATE state) noexcept;
+ SH_CMD_BUFFER_STATE GetState(void) const noexcept;
+
+ public:
+ /*-----------------------------------------------------------------------*/
+ /* CTORS AND DTORS */
+ /*-----------------------------------------------------------------------*/
+ SHVkCommandBuffer (Handle const& commandPool, SH_CMD_BUFFER_TYPE type) noexcept;
+ SHVkCommandBuffer (SHVkCommandBuffer&& rhs) noexcept;
+ SHVkCommandBuffer (void) noexcept = delete;
+ ~SHVkCommandBuffer (void) noexcept;
+ SHVkCommandBuffer& operator= (SHVkCommandBuffer&& rhs) noexcept;
+
+ /*-----------------------------------------------------------------------*/
+ /* PUBLIC MEMBER FUNCTIONS */
+ /*-----------------------------------------------------------------------*/
+ void Reset(void);
+
+ // Begins and Ends
+ void BeginRecording (void) noexcept;
+ void EndRecording (void) noexcept;
+ void BeginRenderpass (Handle const& renderpassHdl, Handle const& framebufferHdl, vk::Offset2D offset = {0, 0}, vk::Extent2D extent = {0, 0}) noexcept;
+ void EndRenderpass (void) noexcept;
+
+ // Dynamic State
+ void SetviewportScissor (float vpWidth, float vpHeight, uint32_t sWidth, uint32_t sHeight, float vpX = 0.0f, float vpY = 0.0f, int32_t sX = 0.0f, int32_t sY = 0.0f, float vpMinDepth = 0.0f, float vpMaxDepth = 1.0f) noexcept;
+
+ // Binding Commands
+ void BindPipeline (Handle const& pipelineHdl) noexcept;
+ void BindVertexBuffer (uint32_t bindingPoint, Handle const& buffer, vk::DeviceSize offset) noexcept;
+ void BindIndexBuffer (Handle const& buffer, uint32_t startingIndex) const noexcept;
+
+ // Draw Commands
+ void DrawArrays (uint32_t vertexCount, uint32_t instanceCount, uint32_t firstVertex, uint32_t firstInstance) const noexcept;
+ void DrawIndexed (uint32_t indexCount, uint32_t firstIndex, uint32_t vertexOffset) const noexcept;
+
+ // Push Constant variable setting
+ template
+ void SetPushConstantVariable(std::string variableName, T const& data) noexcept
+ {
+ memcpy (static_cast(pushConstantData) + boundPipelineLayoutHdl->GetPushConstantInterface().GetOffset(variableName), &data, sizeof (T));
+ };
+
+ void SubmitPushConstants (void) const noexcept;
+
+ /*-----------------------------------------------------------------------*/
+ /* GETTERS AND SETTERS */
+ /*-----------------------------------------------------------------------*/
+ vk::CommandBuffer const& GetVkCommandBuffer(void) const noexcept;
+
+ };
+}
+
+#endif
diff --git a/SHADE_Engine/src/Graphics/Commands/SHVkCommandPool.cpp b/SHADE_Engine/src/Graphics/Commands/SHVkCommandPool.cpp
new file mode 100644
index 00000000..5cf4bea4
--- /dev/null
+++ b/SHADE_Engine/src/Graphics/Commands/SHVkCommandPool.cpp
@@ -0,0 +1,269 @@
+#include "SHPch.h"
+#include "SHVkCommandPool.h"
+#include "Graphics/Devices/SHVkLogicalDevice.h"
+#include "Graphics/Instance/SHVkInstance.h"
+#include "Resource/ResourceLibrary.h"
+#include "Tools/SHLogger.h"
+
+namespace SHADE
+{
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Simply creates a command pool. Flags passed in are also saved.
+
+ \param logicalDevice
+ Logical device required to create the pool
+
+ \param queueFamilyType
+ Every pool needs to be created from a queue family
+
+ \param inResetMode
+ Whether or not the reset bit that allows resetting command buffers
+ individually should be set or not.
+
+ \param inTransient
+ Whether or not buffers created from the pool are short-lived. IT IS
+ STRONGLY RECOMMENDED for this to be true. From "Writing an efficient
+ Vulkan renderer: In general approaches that pre-record command buffers for
+ parts of the scene are counter-productive since they can result in
+ excessive GPU load due to inefficient culling required to keep command
+ buffer workload large and can trigger inefficient code paths on some
+ tiled renderers, and instead applications should focus on improving the
+ threading and draw call submission cost on the CPU. NOTE: it is possible
+ to create transient command buffers from pools that are BUFFER_BASED,
+ hence why POOL_BASED != transient.
+
+ */
+ /***************************************************************************/
+ SHVkCommandPool::SHVkCommandPool(Handle const& inLogicalDeviceHdl, SH_QUEUE_FAMILY_ARRAY_INDEX queueFamilyType, SH_CMD_POOL_RESET inResetMode, bool inTransient) noexcept
+ : vkCommandPool{ nullptr }
+ , queueFamilyIndex{ 0 }
+ , resetMode{ SH_CMD_POOL_RESET::POOL_BASED }
+ , primaries{}
+ , secondaries{}
+ , logicalDeviceHdl { inLogicalDeviceHdl }
+ , transient {false}
+ {
+ // Command pool create info
+ vk::CommandPoolCreateInfo poolCreateInfo{};
+
+ // Get the queue family index based on the queue family type passed in
+ poolCreateInfo.queueFamilyIndex = logicalDeviceHdl->GetQueueFamilyIndex(queueFamilyType);
+
+ if (inResetMode == SH_CMD_POOL_RESET::BUFFER_BASED)
+ poolCreateInfo.flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer;
+
+ if (inTransient)
+ poolCreateInfo.flags |= vk::CommandPoolCreateFlagBits::eTransient;
+
+
+ // Actually create the command pool and check for errors
+ if (auto result = logicalDeviceHdl->GetVkLogicalDevice().createCommandPool(&poolCreateInfo, nullptr, &vkCommandPool); result != vk::Result::eSuccess)
+ {
+ SHVulkanDebugUtil::ReportVkError(result, "Failed to create Command Pool! ");
+ return;
+ }
+ else
+ SHVulkanDebugUtil::ReportVkSuccess("Successfully created Command Pool.");
+
+ // Save the queue family index
+ queueFamilyIndex = poolCreateInfo.queueFamilyIndex;
+
+ // Save the reset mode
+ resetMode = inResetMode;
+ transient = inTransient;
+ }
+
+ SHVkCommandPool::SHVkCommandPool(SHVkCommandPool&& rhs) noexcept
+ : ISelfHandle(rhs)
+ , vkCommandPool{ rhs.vkCommandPool }
+ , queueFamilyIndex{ rhs.queueFamilyIndex }
+ , resetMode{ rhs.resetMode }
+ , primaries{ std::move(rhs.primaries) }
+ , secondaries{ std::move(rhs.secondaries) }
+ , logicalDeviceHdl{ rhs.logicalDeviceHdl }
+ , transient{ rhs.transient }
+ {
+ rhs.vkCommandPool = VK_NULL_HANDLE;
+ }
+
+ SHVkCommandPool& SHVkCommandPool::operator=(SHVkCommandPool&& rhs) noexcept
+ {
+ if (&rhs == this)
+ return *this;
+
+ vkCommandPool = rhs.vkCommandPool;
+ queueFamilyIndex = rhs.queueFamilyIndex;
+ resetMode = rhs.resetMode;
+ primaries = std::move(rhs.primaries);
+ secondaries = std::move(rhs.secondaries);
+ logicalDeviceHdl = rhs.logicalDeviceHdl;
+ transient = rhs.transient;
+
+ static_cast&>(*this) = static_cast&>(rhs);
+
+ rhs.vkCommandPool = VK_NULL_HANDLE;
+
+ return *this;
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Destroys the command pool.
+
+ */
+ /***************************************************************************/
+ SHVkCommandPool::~SHVkCommandPool(void) noexcept
+ {
+ // TODO: Destroy all command buffers first. Should implement a check for command buffers that are still recording or pending (submitted to queue)?
+ if (vkCommandPool)
+ {
+
+ for (auto& pri : primaries)
+ pri.Free();
+ for (auto& sec : secondaries)
+ sec.Free();
+
+ vkDestroyCommandPool(logicalDeviceHdl->GetVkLogicalDevice(), vkCommandPool, nullptr);
+ }
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Resets the command pool.
+
+ \param logicalDevice
+ Device required to reset the command pool.
+
+ */
+ /***************************************************************************/
+ void SHVkCommandPool::Reset(void) noexcept
+ {
+ // TODO: hopefully some sort of validation layer pops up here when we attempt to reset while the command buffers
+ // are in the pending state. Need to do a test.
+ logicalDeviceHdl->GetVkLogicalDevice().resetCommandPool(vkCommandPool, vk::CommandPoolResetFlagBits::eReleaseResources);
+ for (auto& primary : primaries)
+ {
+ if (primary->GetState() != SH_CMD_BUFFER_STATE::PENDING)
+ primary->SetState(SH_CMD_BUFFER_STATE::INITIAL);
+ else
+ SHLOG_ERROR("Primary command buffer in pending state, could not reset. ");
+ // From the spec: Any primary command buffer allocated from another VkCommandPool that is in the recording or
+ // executable state and has a secondary command buffer allocated from commandPool recorded into it,
+ // becomes invalid. TODO: Might want to check and throw exception for these conditions after making sure this actually happens using validation layers.
+ }
+ for (auto& secondary : secondaries)
+ {
+ if (secondary->GetState() != SH_CMD_BUFFER_STATE::PENDING)
+ secondary->SetState(SH_CMD_BUFFER_STATE::INITIAL);
+ else
+ SHLOG_ERROR("Secondary command buffer in pending state, could not reset. ");
+
+ // TODO: Ditto from TODO in primary check
+ }
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Request a command buffer from the command pool. User can choose for it
+ to be secondary or primary/
+
+ \param parentPool
+ This is solely for command buffers created to know what command pool
+ they originated from.
+
+ \param type
+ The type of the command buffer.
+
+ */
+ /***************************************************************************/
+ Handle SHVkCommandPool::RequestCommandBuffer(SH_CMD_BUFFER_TYPE type)
+ {
+ // If type requested for is primary
+ if (type == SH_CMD_BUFFER_TYPE::PRIMARY)
+ {
+ primaries.emplace_back(SHVkInstance::GetResourceManager().Create(GetHandle(), type));
+ return primaries.back();
+ }
+ // If type requested for is secondary
+ else
+ {
+ secondaries.emplace_back(SHVkInstance::GetResourceManager().Create(GetHandle(), type));
+ return secondaries.back();
+ }
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Get the reset mode of the command pool.
+
+ \return
+ Returns the reset mode of the command pool.
+
+ */
+ /***************************************************************************/
+ SH_CMD_POOL_RESET SHVkCommandPool::GetPoolResetMode(void) const noexcept
+ {
+ return resetMode;
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Returns the vulkan command pool handle.
+
+ \return
+ The vulkan command pool handle.
+
+ */
+ /***************************************************************************/
+ vk::CommandPool SHVkCommandPool::GetVkCommandPool(void) const noexcept
+ {
+ return vkCommandPool;
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Returns the logical device handle stored in the command pool.
+
+ \return
+ The logical device handle.
+
+ */
+ /***************************************************************************/
+ Handle const& SHVkCommandPool::GetLogicalDevice(void) const noexcept
+ {
+ return logicalDeviceHdl;
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Returns whether or not the buffers created from this pool are
+ short-lived.
+
+ \return
+ The transient flag.
+
+ */
+ /***************************************************************************/
+ bool SHVkCommandPool::GetIsTransient(void) const noexcept
+ {
+ return transient;
+ }
+
+}
diff --git a/SHADE_Engine/src/Graphics/Commands/SHVkCommandPool.h b/SHADE_Engine/src/Graphics/Commands/SHVkCommandPool.h
new file mode 100644
index 00000000..2bb290a7
--- /dev/null
+++ b/SHADE_Engine/src/Graphics/Commands/SHVkCommandPool.h
@@ -0,0 +1,73 @@
+#ifndef SH_COMMAND_POOL_H
+#define SH_COMMAND_POOL_H
+
+#include "Graphics/SHVulkanIncludes.h"
+#include "Graphics/SHVulkanDefines.h"
+#include "Graphics/Queues/SHVkQueue.h"
+#include "SHCommandPoolResetMode.h"
+#include "SHVkCommandBuffer.h"
+#include "Resource/ResourceLibrary.h"
+
+namespace SHADE
+{
+ class SHVkLogicalDevice;
+
+ class SHVkCommandPool : public ISelfHandle
+ {
+ private:
+ /*-----------------------------------------------------------------------*/
+ /* PRIVATE MEMBER VARIABLES */
+ /*-----------------------------------------------------------------------*/
+ //! Vulkan handle to a command pool
+ vk::CommandPool vkCommandPool;
+
+ //! The queue family index that was used to initialize this pool
+ SHQueueFamilyIndex queueFamilyIndex;
+
+ //! The reset mode of the command buffer. For optimal usage, make the reset
+ //! mode POOL_BASED so that pools can recycle buffer memory all at once
+ //! instead of resetting 1 by 1. In general, we also want to re-record
+ //! buffers every frame instead of pre-recording, so resetting pools each
+ //! frame supports this concept.
+ SH_CMD_POOL_RESET resetMode;
+
+ //! primary command buffers
+ std::vector> primaries;
+
+ //! secondary command buffers
+ std::vector> secondaries;
+
+ //! Handle to logical device for convenience
+ Handle logicalDeviceHdl;
+
+ //! Whether or not buffers created from here are to be short lived
+ bool transient;
+
+ public:
+ /*-----------------------------------------------------------------------*/
+ /* CTOR AND DTOR */
+ /*-----------------------------------------------------------------------*/
+ SHVkCommandPool (Handle const& inLogicalDeviceHdl, SH_QUEUE_FAMILY_ARRAY_INDEX queueFamilyType, SH_CMD_POOL_RESET inResetMode, bool inTransient) noexcept;
+ SHVkCommandPool (void) noexcept = delete;
+ SHVkCommandPool(SHVkCommandPool&& rhs) noexcept;
+ SHVkCommandPool& operator=(SHVkCommandPool&& rhs) noexcept;
+ ~SHVkCommandPool(void) noexcept;
+
+ /*-----------------------------------------------------------------------*/
+ /* PUBLIC MEMBER FUNCTIONS */
+ /*-----------------------------------------------------------------------*/
+ void Reset (void) noexcept;
+ Handle RequestCommandBuffer (SH_CMD_BUFFER_TYPE type);
+
+ /*-----------------------------------------------------------------------*/
+ /* SETTERS AND GETTERS */
+ /*-----------------------------------------------------------------------*/
+ SH_CMD_POOL_RESET GetPoolResetMode(void) const noexcept;
+ vk::CommandPool GetVkCommandPool(void) const noexcept;
+ Handle const& GetLogicalDevice(void) const noexcept;
+ bool GetIsTransient (void) const noexcept;
+
+ };
+}
+
+#endif
diff --git a/SHADE_Engine/src/Graphics/Debugging/SHValidationLayersQuery.cpp b/SHADE_Engine/src/Graphics/Debugging/SHValidationLayersQuery.cpp
new file mode 100644
index 00000000..420fa9e5
--- /dev/null
+++ b/SHADE_Engine/src/Graphics/Debugging/SHValidationLayersQuery.cpp
@@ -0,0 +1,86 @@
+#include "SHPch.h"
+#include "SHValidationLayersQuery.h"
+#include "Tools/SHLogger.h"
+
+namespace SHADE
+{
+ /*-------------------------------------------------------------------------*/
+ /* STATIC VARIABLE DECLARATION */
+ /*-------------------------------------------------------------------------*/
+ std::vector SHValidationLayersQuery::queriedLayers;
+ std::vector SHValidationLayersQuery::availableLayers;
+
+ // TODO: Not sure if necessary but it would be nice to load validation layers
+ // from a file.
+ std::vector SHValidationLayersQuery::requiredLayers =
+ {
+ "VK_LAYER_KHRONOS_validation" // standard validation layer
+ };
+
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Uses the hard coded required layer above to check against the validation
+ layers retrieved upon querying from Vulkan. The final list of layers are
+ ones that are both in the required container and the queried container.
+
+ \param printInfo
+ If this is true, validation layer names are printed.
+
+ \param renderdocEnabled
+ Pushes a validation layer for renderdoc support if true.
+
+ */
+ /***************************************************************************/
+ void SHValidationLayersQuery::GenerateAvailableLayers(bool renderdocEnabled) noexcept
+ {
+ availableLayers.clear();
+
+ // Get the layers from vulkan
+ queriedLayers = vk::enumerateInstanceLayerProperties();
+
+ // Cherrypick those we want from the required list
+ for (char const* const requiredLayer : requiredLayers)
+ {
+ bool layerFound = false;
+ for (auto const& layer : queriedLayers)
+ {
+ if (strcmp (requiredLayer, layer.layerName) == 0)
+ {
+ availableLayers.push_back(requiredLayer);
+ layerFound = true;
+ break;
+ }
+ }
+
+ if (!layerFound)
+ {
+ SHLOG_ERROR(std::string("validation Layer: ") + requiredLayer + std::string ("could not be found. "));
+ }
+ }
+
+ // if renderdoc is requested, add to validation layer.
+ if (renderdocEnabled)
+ availableLayers.push_back("VK_LAYER_RENDERDOC_Capture");
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Gets the available layers after using QueryAvailableLayers.
+
+ \return
+ Returns the available layers.
+
+
+ */
+ /***************************************************************************/
+ std::vector const& SHValidationLayersQuery::GetAvailableLayers(void) noexcept
+ {
+ return availableLayers;
+ }
+
+}
diff --git a/SHADE_Engine/src/Graphics/Debugging/SHValidationLayersQuery.h b/SHADE_Engine/src/Graphics/Debugging/SHValidationLayersQuery.h
new file mode 100644
index 00000000..555dc720
--- /dev/null
+++ b/SHADE_Engine/src/Graphics/Debugging/SHValidationLayersQuery.h
@@ -0,0 +1,57 @@
+/**************************************************************************//*!
+\file SHValidationLayersQuery.h
+\author Brandon Mak
+\par email: brandon.hao@digipen.edu
+\date 17th May 2022
+\brief Stores the declaration of SHValidationLayersQuery class.
+
+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.
+
+*//***************************************************************************/
+
+#ifndef SH_VALIDATION_LAYERS_QUERY_H
+#define SH_VALIDATION_LAYERS_QUERY_H
+
+#include // std::vector
+#include "Graphics/SHVulkanIncludes.h"
+
+namespace SHADE
+{
+ /*!**************************************************************************
+
+ \class SHValidationLLayersQuery
+
+ \brief
+ Static class to query for validation layers. Only used during Vulkan
+ instance creation to enable validation layers.
+
+ ***************************************************************************/
+ class SHValidationLayersQuery
+ {
+ private:
+ /*-----------------------------------------------------------------------*/
+ /* STATIC VARIABLES */
+ /*-----------------------------------------------------------------------*/
+
+ //! required validation layers
+ static std::vector requiredLayers;
+
+ //! Queried layers
+ static std::vector queriedLayers;
+
+ //! Final list that should be used to see what validation layers are available
+ static std::vector availableLayers;
+
+ public:
+ /*-----------------------------------------------------------------------*/
+ /* PUBLIC STATIC FUNCTIONS */
+ /*-----------------------------------------------------------------------*/
+ static void GenerateAvailableLayers (bool renderdocEnabled) noexcept;
+ static std::vector const& GetAvailableLayers (void) noexcept;
+
+ };
+}
+
+#endif
diff --git a/SHADE_Engine/src/Graphics/Debugging/SHVkDebugMessenger.cpp b/SHADE_Engine/src/Graphics/Debugging/SHVkDebugMessenger.cpp
new file mode 100644
index 00000000..d5f0dfe0
--- /dev/null
+++ b/SHADE_Engine/src/Graphics/Debugging/SHVkDebugMessenger.cpp
@@ -0,0 +1,84 @@
+#include "SHPch.h"
+#include
+#include "SHVkDebugMessenger.h"
+#include "SHVulkanDebugUtil.h"
+#include "Graphics/Instance/SHVkInstance.h"
+#include "Tools/SHLogger.h"
+//#include "Tools/SHLogger.h"
+
+namespace SHADE
+{
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Initializes a struct for debug messenger creation.
+
+ \param[in, out] createInfo
+ The create info to initialize.
+
+ \param severityFlags
+ The severity flags we want to have for the messenger.
+
+ \param typeFlags
+ The type flags we want to have for the messenger.
+
+ */
+ /***************************************************************************/
+ void SHVkDebugMessenger::InitializeDebugCreateInfo(vk::DebugUtilsMessengerCreateInfoEXT& createInfo,
+ VkDebugUtilsMessageSeverityFlagsEXT severityFlags,
+ VkDebugUtilsMessageTypeFlagsEXT typeFlags) noexcept
+ {
+ createInfo.messageSeverity = vk::DebugUtilsMessageSeverityFlagsEXT (severityFlags);
+ createInfo.messageType = vk::DebugUtilsMessageTypeFlagsEXT (typeFlags);
+ createInfo.pfnUserCallback = SHVulkanDebugUtil::GenericDebugCallback;
+ createInfo.pNext = nullptr;
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Does everything required to create a debug messenger. This includes its
+ create info and calling the function to create a debug messenger.
+
+ \param vulkanInstance
+ Instance is required to create messenger.
+
+ */
+ /***************************************************************************/
+ void SHVkDebugMessenger::Initialize(void) noexcept
+ {
+ vk::DebugUtilsMessengerCreateInfoEXT debMsgCreateInfo;
+ InitializeDebugCreateInfo(debMsgCreateInfo,
+ GenMessengerSeverity(SH_DEBUG_MSG_SEV::S_VERBOSE, SH_DEBUG_MSG_SEV::S_WARNING, SH_DEBUG_MSG_SEV::S_ERROR),
+ GenMessengerType(SH_DEBUG_MSG_TYPE::T_GENERAL, SH_DEBUG_MSG_TYPE::T_VALIDATION, SH_DEBUG_MSG_TYPE::T_PERFORMANCE));
+
+ if (vk::Result result = SHVkInstance::GetVkInstance().createDebugUtilsMessengerEXT(&debMsgCreateInfo, nullptr, &debugMessenger); result != vk::Result::eSuccess)
+ {
+ SHVulkanDebugUtil::ReportVkError(result, "Failed to create Debug Messenger! ");
+ }
+ else
+ {
+ SHVulkanDebugUtil::ReportVkSuccess("Successfully created a Debug Messenger. ");
+ }
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Simply calls a Vulkan function to destroy the debug messenger.
+
+ \param vulkanInstance
+ Instance is required to destroy messenger.
+
+ */
+ /***************************************************************************/
+ void SHVkDebugMessenger::Destroy(void) noexcept
+ {
+ SHVkInstance::GetVkInstance().destroyDebugUtilsMessengerEXT(debugMessenger, nullptr);
+ }
+
+}
\ No newline at end of file
diff --git a/SHADE_Engine/src/Graphics/Debugging/SHVkDebugMessenger.h b/SHADE_Engine/src/Graphics/Debugging/SHVkDebugMessenger.h
new file mode 100644
index 00000000..577090a5
--- /dev/null
+++ b/SHADE_Engine/src/Graphics/Debugging/SHVkDebugMessenger.h
@@ -0,0 +1,111 @@
+#ifndef SH_DEBUG_MESSENGER_H
+#define SH_DEBUG_MESSENGER_H
+
+#include "SHVulkanDebugUtil.h"
+
+namespace SHADE
+{
+ enum class SH_DEBUG_MSG_SEV : VkDebugUtilsMessageSeverityFlagsEXT
+ {
+ S_VERBOSE = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT,
+ S_INFO = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT,
+ S_WARNING = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT,
+ S_ERROR = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT,
+ S_FLAG = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT,
+ };
+
+ enum class SH_DEBUG_MSG_TYPE : VkDebugUtilsMessageTypeFlagsEXT
+ {
+ T_GENERAL = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT,
+ T_VALIDATION = VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT,
+ T_PERFORMANCE = VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT,
+ T_FLAG_BITS = VK_DEBUG_UTILS_MESSAGE_TYPE_FLAG_BITS_MAX_ENUM_EXT,
+ };
+
+ /*!**************************************************************************
+
+ \class SHVkDebugMessenger
+
+ \brief
+ Vulkan provides debugging functionality through a messenger. This class
+ helps to create and initialize one.
+
+ ***************************************************************************/
+ class SHVkDebugMessenger
+ {
+ private:
+ /*-----------------------------------------------------------------------*/
+ /* DATA MEMBERS */
+ /*-----------------------------------------------------------------------*/
+
+ //! The vulkan debug messenger object
+ vk::DebugUtilsMessengerEXT debugMessenger;
+
+ public:
+ /*-----------------------------------------------------------------------*/
+ /* PUBLIC MEMBER FUNCTIONS */
+ /*-----------------------------------------------------------------------*/
+ void Initialize(void) noexcept;
+ void Destroy(void) noexcept;
+
+ /*-----------------------------------------------------------------------*/
+ /* PUBLIC STATIC FUNCTIONS */
+ /*-----------------------------------------------------------------------*/
+ static void InitializeDebugCreateInfo(vk::DebugUtilsMessengerCreateInfoEXT& createInfo,
+ VkDebugUtilsMessageSeverityFlagsEXT severityFlags,
+ VkDebugUtilsMessageTypeFlagsEXT typeFlags) noexcept;
+
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ When using flags to specify debug message severity, the process is
+ extremely cumbersome as each flag has a lengthy name. This function
+ along with the enum SHDebMsgSeverity helps make it more readable. Use
+ this function any time a VkDebugUtilsMessageSeverityFlagsEXT argument
+ is requested.
+
+ \param ...severities
+ The combined severities.
+
+ \return
+ Returns a bitfield indicated the debug severity flags. Gets passed to
+ Vulkan when created debug create info.
+
+ */
+ /***************************************************************************/
+ template && ...)>>
+ static VkDebugUtilsMessageSeverityFlagsEXT GenMessengerSeverity(Sevs... severities)
+ {
+ return (static_cast(severities) | ...);
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ When using flags to specify debug message types, the process is
+ extremely cumbersome as each flag has a lengthy name. This function
+ along with the enum SHDebMsgType helps make it more readable. Use
+ this function any time a VkDebugUtilsMessageTypeFlagsEXT argument
+ is requested.
+
+ \param ...types
+ The combined types.
+
+ \return
+ Returns a bitfield indicated the debug severity flags. Gets passed to
+ Vulkan when created debug create info.
+
+ */
+ /***************************************************************************/
+ template && ...)>>
+ static VkDebugUtilsMessageTypeFlagsEXT GenMessengerType(Types... types)
+ {
+ return (static_cast(types) | ...);
+ }
+ };
+}
+
+#endif
\ No newline at end of file
diff --git a/SHADE_Engine/src/Graphics/Debugging/SHVulkanDebugUtil.cpp b/SHADE_Engine/src/Graphics/Debugging/SHVulkanDebugUtil.cpp
new file mode 100644
index 00000000..d63a65f7
--- /dev/null
+++ b/SHADE_Engine/src/Graphics/Debugging/SHVulkanDebugUtil.cpp
@@ -0,0 +1,154 @@
+#include "SHPch.h"
+#include "SHVulkanDebugUtil.h"
+#include "Tools/SHLogger.h"
+
+namespace SHADE
+{
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Generic debug function callback to print error messages that are warnings
+ or errors.
+
+ \param messageSeverity
+ Severity of the message
+
+ \param messageType
+ Type of the message
+
+ \param pCallbackData
+ Vulkan object containing useful information regarding the message.
+
+ \param pUserData
+ A pointer to any kind of user data.
+
+ \return
+ returns false anyway.
+
+ */
+ /***************************************************************************/
+ VKAPI_ATTR VkBool32 VKAPI_CALL SHVulkanDebugUtil::GenericDebugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
+ [[maybe_unused]] VkDebugUtilsMessageSeverityFlagsEXT messageType,
+ const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
+ [[maybe_unused]] void* pUserData)
+ {
+ if (messageSeverity == VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT)
+ ReportVkWarning(static_cast (pCallbackData->messageIdNumber), pCallbackData->pMessage);
+ else if (messageSeverity == VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT)
+ ReportVkError(static_cast (pCallbackData->messageIdNumber), pCallbackData->pMessage);
+
+ return VK_FALSE;
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Prints warnings in a formatted manner. Includes vkResult.
+
+ \param vkResult
+ The vkResult to display.
+
+ \param message
+ The custom user message to display.
+
+ \param location
+ location contains information about the function that calls this function,
+ the column/row of the callsite and the filename.
+
+ */
+ /***************************************************************************/
+ void SHVulkanDebugUtil::ReportVkWarning(vk::Result vkResult, std::string_view message, std::source_location const& location /*= std::source_location::current()*/) noexcept
+ {
+ //std::cout << location.file_name() << ": " << location.function_name() << "|" << location.line() << "|" <<
+ // location.column() << "|: Warning: " << SHDebugUtil::VkResultToString(vkResult) << " | " << message << std::endl;
+
+ std::string toLogger = "Vulkan Warning: " + std::string(SHVulkanDebugUtil::VkResultToString(vkResult)) + " | " + std::string(message);
+
+ SHLOGV_WARNING(toLogger);
+ }
+
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Prints errors in a formatted manner. Includes vkResult.
+
+ \param vkResult
+ The vkResult to display.
+
+ \param message
+ The custom user message to display.
+
+ \param location
+ location contains information about the function that calls this function,
+ the column/row of the callsite and the filename.
+
+ */
+ /***************************************************************************/
+ void SHVulkanDebugUtil::ReportVkError(vk::Result vkResult, std::string_view message, std::source_location const& location /*= std::source_location::current()*/) noexcept
+ {
+ std::string toLogger = "Vulkan Warning: " + std::string(SHVulkanDebugUtil::VkResultToString(vkResult)) + " | " + std::string(message);
+
+ SHLOGV_ERROR(toLogger);
+ }
+
+
+ void SHVulkanDebugUtil::ReportVkSuccess(std::string_view message, std::source_location const& location /*= std::source_location::current()*/) noexcept
+ {
+ SHLOGV_INFO(message);
+ }
+
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Converts a vkResult enum field to a string. Function is copied entirely
+ from xGPU: https://github.com/LIONant-depot/xGPU/blob/d546fc202d2acddb6beeb79947860fd437046cb3/Src/Details/Vulkan/xgpu_vulkan_instance.cpp#L19
+ Could not find a more straightforward way to convert enum to string.
+
+ \param vkResult
+ The Vulkan result to convert to string.
+
+ \return
+ returns a string_view that represents the vulkan result enum value.
+
+ */
+ /***************************************************************************/
+ std::string_view SHVulkanDebugUtil::VkResultToString(vk::Result vkResult) noexcept
+ {
+ VkResult cStyleResult = static_cast(vkResult);
+ switch (cStyleResult)
+ {
+ // Macro to form the enum value using '##', and stringify the enum using '#'
+#define STR(r) case VK_ ##r : return #r
+ STR(TIMEOUT);
+ STR(EVENT_SET);
+ STR(EVENT_RESET);
+ STR(INCOMPLETE);
+ STR(ERROR_OUT_OF_HOST_MEMORY);
+ STR(ERROR_OUT_OF_DEVICE_MEMORY);
+ STR(ERROR_INITIALIZATION_FAILED);
+ STR(ERROR_DEVICE_LOST);
+ STR(ERROR_MEMORY_MAP_FAILED);
+ STR(ERROR_LAYER_NOT_PRESENT);
+ STR(ERROR_EXTENSION_NOT_PRESENT);
+ STR(ERROR_FEATURE_NOT_PRESENT);
+ STR(ERROR_INCOMPATIBLE_DRIVER);
+ STR(ERROR_TOO_MANY_OBJECTS);
+ STR(ERROR_FORMAT_NOT_SUPPORTED);
+ STR(ERROR_SURFACE_LOST_KHR);
+ STR(ERROR_NATIVE_WINDOW_IN_USE_KHR);
+ STR(SUBOPTIMAL_KHR);
+ STR(ERROR_OUT_OF_DATE_KHR);
+ STR(ERROR_INCOMPATIBLE_DISPLAY_KHR);
+ STR(ERROR_VALIDATION_FAILED_EXT);
+ STR(ERROR_INVALID_SHADER_NV);
+#undef STR
+ default:
+ return "UNKNOWN_ERROR";
+ }
+ }
+}
diff --git a/SHADE_Engine/src/Graphics/Debugging/SHVulkanDebugUtil.h b/SHADE_Engine/src/Graphics/Debugging/SHVulkanDebugUtil.h
new file mode 100644
index 00000000..7bf583bb
--- /dev/null
+++ b/SHADE_Engine/src/Graphics/Debugging/SHVulkanDebugUtil.h
@@ -0,0 +1,30 @@
+#ifndef SH_DEBUG_UTIL_H
+#define SH_DEBUG_UTIL_H
+
+#include "Graphics/SHVulkanIncludes.h"
+//#include
+#include
+
+namespace SHADE
+{
+ class SHVulkanDebugUtil
+ {
+ private:
+ static std::string_view VkResultToString(vk::Result vkResult) noexcept;
+
+ public:
+ static VKAPI_ATTR VkBool32 VKAPI_CALL GenericDebugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageSeverityFlagsEXT messageType, const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* pUserData);
+
+ static void ReportVkWarning(vk::Result vkResult, std::string_view message, std::source_location const& location = std::source_location::current()) noexcept;
+ static void ReportVkError(vk::Result vkResult, std::string_view message, std::source_location const& location = std::source_location::current()) noexcept;
+ static void ReportVkSuccess(std::string_view message, std::source_location const& location = std::source_location::current()) noexcept;
+
+ };
+
+ class SHVkDebugOn
+ {
+
+ };
+}
+
+#endif
diff --git a/SHADE_Engine/src/Graphics/Descriptors/SHDescriptorPoolManager.cpp b/SHADE_Engine/src/Graphics/Descriptors/SHDescriptorPoolManager.cpp
new file mode 100644
index 00000000..fcbedc07
--- /dev/null
+++ b/SHADE_Engine/src/Graphics/Descriptors/SHDescriptorPoolManager.cpp
@@ -0,0 +1,2 @@
+#include "SHPch.h"
+#include "SHDescriptorPoolManager.h"
diff --git a/SHADE_Engine/src/Graphics/Descriptors/SHDescriptorPoolManager.h b/SHADE_Engine/src/Graphics/Descriptors/SHDescriptorPoolManager.h
new file mode 100644
index 00000000..cbd64982
--- /dev/null
+++ b/SHADE_Engine/src/Graphics/Descriptors/SHDescriptorPoolManager.h
@@ -0,0 +1,5 @@
+#pragma once
+class SHDescriptorPoolManager
+{
+};
+
diff --git a/SHADE_Engine/src/Graphics/Descriptors/SHDescriptorPoolStorage.cpp b/SHADE_Engine/src/Graphics/Descriptors/SHDescriptorPoolStorage.cpp
new file mode 100644
index 00000000..e5f7c394
--- /dev/null
+++ b/SHADE_Engine/src/Graphics/Descriptors/SHDescriptorPoolStorage.cpp
@@ -0,0 +1,2 @@
+#include "SHPch.h"
+#include "SHDescriptorPoolStorage.h"
diff --git a/SHADE_Engine/src/Graphics/Descriptors/SHDescriptorPoolStorage.h b/SHADE_Engine/src/Graphics/Descriptors/SHDescriptorPoolStorage.h
new file mode 100644
index 00000000..7e421006
--- /dev/null
+++ b/SHADE_Engine/src/Graphics/Descriptors/SHDescriptorPoolStorage.h
@@ -0,0 +1,5 @@
+#pragma once
+class SHDescriptorPoolStorage
+{
+};
+
diff --git a/SHADE_Engine/src/Graphics/Descriptors/SHVkDescriptorPool.cpp b/SHADE_Engine/src/Graphics/Descriptors/SHVkDescriptorPool.cpp
new file mode 100644
index 00000000..87d43255
--- /dev/null
+++ b/SHADE_Engine/src/Graphics/Descriptors/SHVkDescriptorPool.cpp
@@ -0,0 +1,38 @@
+#include "SHPch.h"
+#include "SHVkDescriptorPool.h"
+
+#include "Graphics/Devices/SHVkLogicalDevice.h"
+#include "Graphics/Instance/SHVkInstance.h"
+#include "Graphics/Descriptors/SHVkDescriptorSetGroup.h"
+
+namespace SHADE
+{
+ /*---------------------------------------------------------------------------------*/
+ /* Constructor/Destructor */
+ /*---------------------------------------------------------------------------------*/
+ SHVkDescriptorPool::SHVkDescriptorPool(Handle device, const Config& config)
+ : device { device }
+ {
+ // Create the Pool
+ const vk::DescriptorPoolCreateInfo POOL_CREATE_INFO
+ {
+ .flags = config.Flags,
+ .maxSets = config.MaxSets,
+ .poolSizeCount = static_cast(config.Limits.size()),
+ .pPoolSizes = config.Limits.data()
+ };
+ pool = device->GetVkLogicalDevice().createDescriptorPool(POOL_CREATE_INFO);
+ }
+
+ SHVkDescriptorPool::~SHVkDescriptorPool() noexcept
+ {
+ if (pool)
+ device->GetVkLogicalDevice().destroyDescriptorPool(pool);
+ }
+
+ std::vector> SHVkDescriptorPool::Allocate(const std::vector>& layouts, std::vector const& variableDescCounts)
+ {
+ SHVkInstance::GetResourceManager().Create(device, GetHandle(), layouts, variableDescCounts);
+ return {};
+ }
+}
diff --git a/SHADE_Engine/src/Graphics/Descriptors/SHVkDescriptorPool.h b/SHADE_Engine/src/Graphics/Descriptors/SHVkDescriptorPool.h
new file mode 100644
index 00000000..c3059b8b
--- /dev/null
+++ b/SHADE_Engine/src/Graphics/Descriptors/SHVkDescriptorPool.h
@@ -0,0 +1,114 @@
+#pragma once
+
+// Project Includes
+#include "Graphics/SHVulkanIncludes.h"
+#include "Resource/Handle.h"
+
+namespace SHADE
+{
+ /*---------------------------------------------------------------------------------*/
+ /* Forward Declarations */
+ /*---------------------------------------------------------------------------------*/
+ class SHVkLogicalDevice;
+ class SHVkDescriptorSetGroup;
+ class SHVkDescriptorSetLayout;
+
+ /*---------------------------------------------------------------------------------*/
+ /* Type Definitions */
+ /*---------------------------------------------------------------------------------*/
+ ///
+ ///
+ ///
+ class SHVkDescriptorPool : public ISelfHandle
+ {
+ public:
+ /*-----------------------------------------------------------------------------*/
+ /* Type Definitions */
+ /*-----------------------------------------------------------------------------*/
+ ///
+ /// Configuration object for the Pool Manager.
+ ///
+ struct Config
+ {
+ public:
+ ///
+ /// Describe the resource limitations of the Descriptor Pool can construct.
+ /// The specified type and count pairs indicate how many Descriptors will be
+ /// constructed in the Descriptor Pool.
+ ///
+ std::vector Limits =
+ {
+ { vk::DescriptorType::eCombinedImageSampler, 100 },
+ { vk::DescriptorType::eUniformBuffer, 100 }
+ };
+ ///
+ /// Maximum number of descriptor sets allowed
+ ///
+ uint32_t MaxSets = 100;
+ ///
+ /// Flags used to create the DescriptorPool
+ ///
+ vk::DescriptorPoolCreateFlags Flags = vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet;
+ };
+
+ /*-----------------------------------------------------------------------------*/
+ /* Constructor/Destructor */
+ /*-----------------------------------------------------------------------------*/
+ ///
+ /// Constructor for a Descriptor Pool.
+ ///
+ ///
+ /// The Vulkan logical device that is used to create a Descriptor Pool.
+ ///
+ ///
+ /// Configuration object that describes how to construct the Descriptor Pool.
+ ///
+ SHVkDescriptorPool(Handle device, const Config& config = {});
+ SHVkDescriptorPool(const SHVkDescriptorPool&) = delete;
+ SHVkDescriptorPool(SHVkDescriptorPool&& rhs) noexcept = default;
+ ///
+ /// Destructor which will unload and deallocate all resources for this Pool.
+ ///
+ ~SHVkDescriptorPool() noexcept;
+
+ /*-----------------------------------------------------------------------------*/
+ /* Overloaded Operators */
+ /*-----------------------------------------------------------------------------*/
+ SHVkDescriptorPool& operator=(const SHVkDescriptorPool&) = delete;
+ SHVkDescriptorPool& operator=(SHVkDescriptorPool&& rhs) noexcept = default;
+
+ /*-----------------------------------------------------------------------------*/
+ /* Getter Functions */
+ /*-----------------------------------------------------------------------------*/
+ ///
+ /// Retrieves the handle to the Vulkan Descriptor Pool handle.
+ ///
+ /// Handle to the Vulkan Descriptor Pool.
+ [[nodiscard]]
+ inline const vk::DescriptorPool& GetVkHandle() const { return pool; }
+
+ /*-----------------------------------------------------------------------------*/
+ /* Usage Functions */
+ /*-----------------------------------------------------------------------------*/
+ ///
+ /// Allocates multiple DescriptorSets based on the provided layouts.
+ ///
+ /// Layouts of DescriptorSets to create.
+ ///
+ /// Thrown if an incompatible layout was provided to this Descriptor Pool.
+ ///
+ ///
+ /// Handles to the created Descriptor Sets. If this DescriptorPool has run out of
+ /// space, lesser number of Handles will be returned.
+ ///
+ std::vector> Allocate(const std::vector>& layouts, std::vector const& variableDescCounts);
+
+ private:
+ /*-----------------------------------------------------------------------------*/
+ /* Data Members */
+ /*-----------------------------------------------------------------------------*/
+ Handle device;
+ vk::DescriptorPool pool;
+ };
+}
+
diff --git a/SHADE_Engine/src/Graphics/Descriptors/SHVkDescriptorSetGroup.cpp b/SHADE_Engine/src/Graphics/Descriptors/SHVkDescriptorSetGroup.cpp
new file mode 100644
index 00000000..6bdc5601
--- /dev/null
+++ b/SHADE_Engine/src/Graphics/Descriptors/SHVkDescriptorSetGroup.cpp
@@ -0,0 +1,85 @@
+#include "SHPch.h"
+#include "SHVkDescriptorSetGroup.h"
+
+#include
+
+#include "SHVkDescriptorPool.h"
+#include "Graphics/Devices/SHVkLogicalDevice.h"
+#include "Graphics/Descriptors/SHVkDescriptorSetLayout.h"
+#include "Tools/SHLogger.h"
+
+namespace SHADE
+{
+ /***************************************************************************/
+ /*!
+
+ \brief
+ Allocates a bunch of descriptor sets based on how many layouts are
+ being passed in.
+
+ \param deviceHdl
+ Logical device required for the descriptor set creation.
+
+
+ \param pool
+ Pool to allocate from.
+
+ \param layouts
+ With N layouts provided, the function will allocate N descriptor sets.
+ All of which will be stored in this class.
+
+ \param variableDescCounts
+ Represents the variable descriptor count for every layout passed in.
+ If the binding used in the layout is not marked as using a variable count,
+ the value for the particular layout is ignored.
+
+ */
+ /***************************************************************************/
+ SHVkDescriptorSetGroup::SHVkDescriptorSetGroup(Handle deviceHdl, Handle pool, std::vector> const& layouts, std::vector const& variableDescCounts)
+ : device{deviceHdl}
+ , descPool {pool}
+ , descSets{}
+ {
+ // Create the layout for each concurrent frame
+ std::vector vkLayouts{ layouts.size() };
+ for (auto& layout : layouts)
+ {
+ vkLayouts.push_back(layout->GetVkHandle());
+ }
+
+ // Check for variable descriptor count
+ if (variableDescCounts.size() != layouts.size())
+ SHLOG_ERROR("Number of variable descriptor counts does not match number of layouts. If a layout does not use variable counts, pass in 0. ");
+
+ // Prepare variable descriptor counts
+ vk::DescriptorSetVariableDescriptorCountAllocateInfo variableAllocInfo{};
+ variableAllocInfo.descriptorSetCount = static_cast(variableDescCounts.size());
+ variableAllocInfo.pDescriptorCounts = variableDescCounts.data();
+
+ // Prepare allocation information
+ const vk::DescriptorSetAllocateInfo DESC_SET_LAYOUT_CREATE_INFO
+ {
+ .pNext = &variableAllocInfo,
+ .descriptorPool = descPool->GetVkHandle(),
+ .descriptorSetCount = static_cast