From 94f579e8e3345622c0936997b6eb0c356408373c Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Sun, 30 Oct 2022 13:25:15 +0800 Subject: [PATCH 01/27] CompileAsset function from Asset manager is working --- .../src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp index 4983bd48..bc485b40 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp @@ -37,6 +37,7 @@ of DigiPen Institute of Technology is prohibited. #include "Assets/Asset Types/SHTextureAsset.h" #include "Graphics/MiddleEnd/Interface/SHMousePickSystem.h" #include "Graphics/MiddleEnd/Lights/SHLightingSubSystem.h" +#include "Assets/SHAssetManager.h" namespace SHADE { @@ -109,6 +110,7 @@ namespace SHADE transferCmdBuffer = graphicsCmdPool->RequestCommandBuffer(SH_CMD_BUFFER_TYPE::PRIMARY); graphicsTexCmdBuffer = graphicsCmdPool->RequestCommandBuffer(SH_CMD_BUFFER_TYPE::PRIMARY); + SHAssetManager::CompileAsset("../../Assets/Shaders/DeferredComposite_CS.glsl"); shaderModuleLibrary.ImportAllShaderSource(device); shaderModuleLibrary.ReflectAllShaderModules(); From fad9d37cd4ca683d27be892b26334046c62f64b5 Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Sun, 30 Oct 2022 14:17:36 +0800 Subject: [PATCH 02/27] Lighting data is now copied to CPU buffer and GPU buffer every frame Since lighting will be done in view space, the camera's constant movement will make it so that the light data is often changing. Keeping track of these changes for optimization might prove to be counter productive. Copying data every frame might just be more ideal. --- .../MiddleEnd/Interface/SHGraphicsSystem.cpp | 2 + .../MiddleEnd/Interface/SHGraphicsSystem.h | 6 +- .../MiddleEnd/Lights/SHLightComponent.cpp | 82 +++++++++---------- .../MiddleEnd/Lights/SHLightComponent.h | 22 ++--- .../MiddleEnd/Lights/SHLightingSubSystem.cpp | 46 ++++++----- .../MiddleEnd/Lights/SHLightingSubSystem.h | 8 +- 6 files changed, 86 insertions(+), 80 deletions(-) diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp index bc485b40..5deb83a9 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp @@ -110,6 +110,8 @@ namespace SHADE transferCmdBuffer = graphicsCmdPool->RequestCommandBuffer(SH_CMD_BUFFER_TYPE::PRIMARY); graphicsTexCmdBuffer = graphicsCmdPool->RequestCommandBuffer(SH_CMD_BUFFER_TYPE::PRIMARY); + SHAssetManager::CompileAsset("../../Assets/Shaders/TestCube_VS.glsl"); + SHAssetManager::CompileAsset("../../Assets/Shaders/TestCube_FS.glsl"); SHAssetManager::CompileAsset("../../Assets/Shaders/DeferredComposite_CS.glsl"); shaderModuleLibrary.ImportAllShaderSource(device); diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h index 0f9d602a..072a1d99 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h @@ -358,9 +358,9 @@ namespace SHADE Handle postOffscreenRender; Handle lightingSubSystem; - uint32_t resizeWidth; - uint32_t resizeHeight; - bool restoredFromMinimize = false; + uint32_t resizeWidth = 1; + uint32_t resizeHeight = 1; + bool restoredFromMinimize = false; }; } \ No newline at end of file diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.cpp index fb8795fa..2ea6bc8b 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.cpp @@ -9,9 +9,9 @@ namespace SHADE { lightData.Reset(); SetType(SH_LIGHT_TYPE::DIRECTIONAL); - indexInBuffer = std::numeric_limits::max(); + //indexInBuffer = std::numeric_limits::max(); isActive = true; - Unbind(); + //Unbind(); } @@ -23,28 +23,28 @@ namespace SHADE void SHLightComponent::SetPosition(SHVec3 const& position) noexcept { lightData.position = position; - MakeDirty(); + //MakeDirty(); } void SHLightComponent::SetType(SH_LIGHT_TYPE type) noexcept { lightData.type = type; - MakeDirty(); + //MakeDirty(); } void SHLightComponent::SetDirection(SHVec3 const& direction) noexcept { lightData.direction = direction; - MakeDirty(); + //MakeDirty(); } void SHLightComponent::SetColor(SHVec4 const& color) noexcept { lightData.color = color; - MakeDirty(); + //MakeDirty(); } void SHLightComponent::ModifyCullingMask(uint8_t layerIndex, bool value) noexcept @@ -54,7 +54,7 @@ namespace SHADE else lightData.cullingMask &= ~(1u << layerIndex); - MakeDirty(); + //MakeDirty(); } void SHLightComponent::SetCullingMask(uint32_t const& value) noexcept @@ -65,43 +65,43 @@ namespace SHADE void SHLightComponent::SetAllLayers(void) noexcept { lightData.cullingMask = std::numeric_limits::max(); - MakeDirty(); + //MakeDirty(); } void SHLightComponent::ClearAllLayers(void) noexcept { lightData.cullingMask = 0; - MakeDirty(); + //MakeDirty(); } - void SHLightComponent::MakeDirty(void) noexcept - { - dirty = true; - } + //void SHLightComponent::MakeDirty(void) noexcept + //{ + // dirty = true; + //} - void SHLightComponent::ClearDirtyFlag(void) noexcept - { - dirty = false; - } + //void SHLightComponent::ClearDirtyFlag(void) noexcept + //{ + // dirty = false; + //} - void SHLightComponent::Unbind(void) noexcept - { - bound = false; - MakeDirty(); - } - - void SHLightComponent::SetBound(uint32_t inIndexInBuffer) noexcept -{ - bound = true; - indexInBuffer = inIndexInBuffer; - } +// void SHLightComponent::Unbind(void) noexcept +// { +// bound = false; +// MakeDirty(); +// } +// +// void SHLightComponent::SetBound(uint32_t inIndexInBuffer) noexcept +//{ +// bound = true; +// indexInBuffer = inIndexInBuffer; +// } void SHLightComponent::SetStrength(float value) noexcept { lightData.strength = value; - MakeDirty(); + //MakeDirty(); } SHLightData const& SHLightComponent::GetLightData(void) const noexcept @@ -135,20 +135,20 @@ namespace SHADE } - bool SHLightComponent::IsDirty(void) const noexcept - { - return dirty; - } + //bool SHLightComponent::IsDirty(void) const noexcept + //{ + // return dirty; + //} - bool SHLightComponent::GetBound(void) const noexcept - { - return bound; - } + //bool SHLightComponent::GetBound(void) const noexcept + //{ + // return bound; + //} - uint32_t SHLightComponent::GetIndexInBuffer(void) const noexcept - { - return indexInBuffer; - } + //uint32_t SHLightComponent::GetIndexInBuffer(void) const noexcept + //{ + // return indexInBuffer; + //} float SHLightComponent::GetStrength(void) const noexcept { diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.h b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.h index 81eb80f5..6b35559c 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightComponent.h @@ -17,13 +17,13 @@ namespace SHADE //! Since the lighting system is gonna be self contained and light weight, we store this //! so that we only write this to the CPU buffer when this light component change, we don't //! rewrite everything. However we still write to the GPU buffer when everything changes. - uint32_t indexInBuffer; + //uint32_t indexInBuffer; - //! If the light component changed some value we mark this true. - bool dirty; + ////! If the light component changed some value we mark this true. + //bool dirty; - //! If the light's data is already in the buffers, this will be set to true. - bool bound; + ////! If the light's data is already in the buffers, this will be set to true. + //bool bound; public: @@ -44,10 +44,10 @@ namespace SHADE void SetCullingMask (uint32_t const& value) noexcept; void SetAllLayers (void) noexcept; // serialized void ClearAllLayers (void) noexcept; // serialized - void MakeDirty (void) noexcept; - void ClearDirtyFlag (void) noexcept; - void Unbind (void) noexcept; - void SetBound (uint32_t inIndexInBuffer) noexcept; + //void MakeDirty (void) noexcept; + //void ClearDirtyFlag (void) noexcept; + //void Unbind (void) noexcept; + //void SetBound (uint32_t inIndexInBuffer) noexcept; void SetStrength (float value) noexcept; // serialized @@ -57,8 +57,8 @@ namespace SHADE SHVec3 const& GetDirection (void) const noexcept; // serialized SHVec4 const& GetColor (void) const noexcept; // serialized uint32_t const& GetCullingMask (void) const noexcept; // serialized - bool IsDirty (void) const noexcept; - bool GetBound (void) const noexcept; + //bool IsDirty (void) const noexcept; + //bool GetBound (void) const noexcept; uint32_t GetIndexInBuffer (void) const noexcept; float GetStrength (void) const noexcept; RTTR_ENABLE() diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp index 5ca879c4..c4ba9fa1 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp @@ -240,7 +240,7 @@ namespace SHADE */ /***************************************************************************/ - void SHLightingSubSystem::PerTypeData::AddLight(Handle logicalDevice, SHLightComponent* unboundLight, bool expanded) noexcept + void SHLightingSubSystem::PerTypeData::AddLight(Handle logicalDevice, SHLightComponent* unboundLight, bool& expanded) noexcept { if (unboundLight) { @@ -262,7 +262,7 @@ namespace SHADE WriteLightToAddress(writeLocation, unboundLight); // Set the light component to be bound to that location - unboundLight->SetBound(numLights); + //unboundLight->SetBound(numLights); // Increase light count ++numLights; @@ -280,11 +280,11 @@ namespace SHADE */ /***************************************************************************/ - void SHLightingSubSystem::PerTypeData::ModifyLight(SHLightComponent* lightComp) noexcept - { - void* writeLocation = reinterpret_cast(intermediateData.get()) + (lightDataAlignedSize * lightComp->GetIndexInBuffer()); - WriteLightToAddress(writeLocation, lightComp); - } + //void SHLightingSubSystem::PerTypeData::ModifyLight(SHLightComponent* lightComp) noexcept + //{ + // void* writeLocation = reinterpret_cast(intermediateData.get()) + (lightDataAlignedSize * lightComp->GetIndexInBuffer()); + // WriteLightToAddress(writeLocation, lightComp); + //} void SHLightingSubSystem::PerTypeData::WriteToGPU(uint32_t frameIndex) noexcept { @@ -406,7 +406,7 @@ namespace SHADE dynamicOffsets[i].resize(NUM_LIGHT_TYPES + 1); // +1 for the count } - numLightComponents = 0; + //numLightComponents = 0; } /***************************************************************************/ @@ -419,21 +419,25 @@ namespace SHADE */ /***************************************************************************/ - void SHLightingSubSystem::Run(Handle cmdBuffer, uint32_t frameIndex) noexcept + void SHLightingSubSystem::Run(Handle cmdBuffer, /*SHMatrix const& viewMat,*/ uint32_t frameIndex) noexcept { static uint32_t constexpr NUM_LIGHT_TYPES = SHUtilities::ToUnderlying(SH_LIGHT_TYPE::NUM_TYPES); auto& lightComps = SHComponentManager::GetDense(); bool expanded = false; - bool rewrite = false; - if (numLightComponents > lightComps.size()) - { - rewrite = true; - ResetNumLights(); - } + // First we reset the number of lights. We do this every frame so that we can count how many lights we have + ResetNumLights(); - numLightComponents = lightComps.size(); + //bool rewrite = false; + + //if (numLightComponents > lightComps.size()) + //{ + // rewrite = true; + // ResetNumLights(); + //} + + //numLightComponents = lightComps.size(); for (auto& light : lightComps) { @@ -441,22 +445,22 @@ namespace SHADE // First we want to make sure the light is already bound to the system. if it // isn't, we write it to the correct buffer. - if (!light.GetBound() || rewrite) + //if (!light.GetBound() || rewrite) { perTypeData[enumValue].AddLight(logicalDevice, &light, expanded); - //// add to light count + // add to light count //++lightCountsData[enumValue]; } // if there was modification to the light data - if (light.IsDirty()) + //if (light.IsDirty()) { // Write the data to the CPU - perTypeData[enumValue].ModifyLight(&light); + //perTypeData[enumValue].ModifyLight(&light); // Light is now updated in the container - light.ClearDirtyFlag(); + //light.ClearDirtyFlag(); } } diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.h b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.h index fb7aa2de..4a667ec5 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.h @@ -102,8 +102,8 @@ namespace SHADE /*-----------------------------------------------------------------------*/ void InitializeData (Handle logicalDevice, SH_LIGHT_TYPE type) noexcept; void Expand (Handle logicalDevice) noexcept; - void AddLight (Handle logicalDevice, SHLightComponent* unboundLight, bool expanded) noexcept; - void ModifyLight (SHLightComponent* lightComp) noexcept; + void AddLight (Handle logicalDevice, SHLightComponent* unboundLight, bool& expanded) noexcept; + //void ModifyLight (SHLightComponent* lightComp) noexcept; void WriteToGPU (uint32_t frameIndex) noexcept; void ResetNumLights (void) noexcept; @@ -144,7 +144,7 @@ namespace SHADE //! Number of SHLightComponents recorded. If at the beginning of the run function the size returned by the dense //! set is less than the size recorded, rewrite all light components into the its respective buffers. If its more, //! don't do anything. - uint32_t numLightComponents; + //uint32_t numLightComponents; /*-----------------------------------------------------------------------*/ /* PRIVATE MEMBER FUNCTIONS */ @@ -159,7 +159,7 @@ namespace SHADE /* PUBLIC MEMBER FUNCTIONS */ /*-----------------------------------------------------------------------*/ void Init (Handle device, Handle descPool) noexcept; - void Run (Handle cmdBuffer, uint32_t frameIndex) noexcept; + void Run (Handle cmdBuffer, /*SHMatrix const& viewMat,*/ uint32_t frameIndex) noexcept; void Exit (void) noexcept; }; From 4711a131eb875fcb43706834c42960189e6e4fcf Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Sun, 30 Oct 2022 16:35:55 +0800 Subject: [PATCH 03/27] Shifted the lighting system run outside the viewport loop. - Since lighting is only calculated in the world render graph for now, this will do just fine - Renderer takes in a view and projection matrix and does the transpose of the multiplication in the renderer --- Assets/Shaders/TestCube_VS.glsl | 1 + Assets/Shaders/TestCube_VS.shshaderb | Bin 3305 -> 3385 bytes .../MiddleEnd/Interface/SHGraphicsSystem.cpp | 16 ++++++++++--- .../MiddleEnd/Interface/SHRenderer.cpp | 17 ++++++++++---- .../Graphics/MiddleEnd/Interface/SHRenderer.h | 8 ++++--- .../MiddleEnd/Lights/SHLightingSubSystem.cpp | 22 ++++++++++++------ .../MiddleEnd/Lights/SHLightingSubSystem.h | 8 ++++--- 7 files changed, 51 insertions(+), 21 deletions(-) diff --git a/Assets/Shaders/TestCube_VS.glsl b/Assets/Shaders/TestCube_VS.glsl index 49f107dd..44c6e956 100644 --- a/Assets/Shaders/TestCube_VS.glsl +++ b/Assets/Shaders/TestCube_VS.glsl @@ -33,6 +33,7 @@ layout(set = 2, binding = 0) uniform CameraData { vec4 position; mat4 vpMat; + mat4 viewMat; } cameraData; void main() diff --git a/Assets/Shaders/TestCube_VS.shshaderb b/Assets/Shaders/TestCube_VS.shshaderb index 03e23af37451b6c4c0791110541c7b6e31d07bbe..2544abd58b576513f2e8185a0b84ef070e6a42fe 100644 GIT binary patch delta 105 zcmaDUxl@Xn!GL!o^CKo(); + { +#ifdef SHEDITOR + auto editorSystem = SHSystemManager::GetSystem(); + if (editorSystem->editorState != SHEditor::State::PLAY) + lightingSubSystem->Run(cameraSystem->GetEditorCamera()->GetViewMatrix(), frameIndex); + else + lightingSubSystem->Run(worldRenderer->GetCameraDirector()->GetViewMatrix(), frameIndex); +#else + lightingSubSystem->Run(worldRenderer->GetCameraDirector()->GetViewMatrix(), frameIndex); +#endif + } // For every viewport for (int vpIndex = 0; vpIndex < static_cast(viewports.size()); ++vpIndex) @@ -394,8 +405,7 @@ namespace SHADE currentCmdBuffer->BindIndexBuffer(buffer, 0); } - // Bind the descriptor set for lights - lightingSubSystem->Run(currentCmdBuffer, frameIndex); + lightingSubSystem->BindDescSet(currentCmdBuffer, frameIndex); // Bind textures auto textureDescSet = texLibrary.GetTextureDescriptorSetGroup(); @@ -419,7 +429,7 @@ namespace SHADE { auto editorSystem = SHSystemManager::GetSystem(); if (editorSystem->editorState != SHEditor::State::PLAY) - worldRenderer->UpdateDataAndBind(currentCmdBuffer, frameIndex, SHMatrix::Transpose(cameraSystem->GetEditorCamera()->GetProjMatrix() * cameraSystem->GetEditorCamera()->GetViewMatrix())); + worldRenderer->UpdateDataAndBind(currentCmdBuffer, frameIndex, cameraSystem->GetEditorCamera()->GetViewMatrix(), cameraSystem->GetEditorCamera()->GetProjMatrix()); else renderers[renIndex]->UpdateDataAndBind(currentCmdBuffer, frameIndex); } diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHRenderer.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHRenderer.cpp index 962130be..a44e0661 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHRenderer.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHRenderer.cpp @@ -83,13 +83,14 @@ namespace SHADE { if (camera && cameraDirector) { - UpdateDataAndBind(cmdBuffer, frameIndex, SHMatrix::Transpose(cameraDirector->GetVPMatrix())); + //UpdateDataAndBind(cmdBuffer, frameIndex, SHMatrix::Transpose(cameraDirector->GetVPMatrix())); + UpdateDataAndBind(cmdBuffer, frameIndex, cameraDirector->GetViewMatrix(), cameraDirector->GetProjMatrix()); } } - void SHRenderer::UpdateDataAndBind(Handle cmdBuffer, uint32_t frameIndex, SHMatrix exteriorMatrix) noexcept + void SHRenderer::UpdateDataAndBind(Handle cmdBuffer, uint32_t frameIndex, SHMatrix viewMatrix, SHMatrix projMatrix) noexcept { - SetViewProjectionMatrix(exteriorMatrix); + SetViewProjectionMatrix(viewMatrix, projMatrix); //cpuCameraData.viewProjectionMatrix = camera->GetViewProjectionMatrix(); cameraBuffer->WriteToMemory(&cpuCameraData, sizeof(SHShaderCameraData), 0, cameraDataAlignedSize * frameIndex); @@ -103,10 +104,11 @@ namespace SHADE { } - void SHRenderer::SetViewProjectionMatrix(SHMatrix const& vpMatrix) noexcept + void SHRenderer::SetViewProjectionMatrix(SHMatrix viewMatrix, SHMatrix projMatrix) noexcept { //cpuCameraData.viewProjectionMatrix = camera->GetViewMatrix() * camera->GetProjectionMatrix(); - cpuCameraData.viewProjectionMatrix = vpMatrix; + cpuCameraData.viewProjectionMatrix = SHMatrix::Transpose(projMatrix * viewMatrix); + cpuCameraData.viewMatrix = viewMatrix; } Handle SHRenderer::GetRenderGraph(void) const noexcept @@ -119,4 +121,9 @@ namespace SHADE return commandBuffers[frameIndex]; } + Handle SHRenderer::GetCameraDirector(void) const noexcept + { + return cameraDirector; + } + } diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHRenderer.h b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHRenderer.h index 87cf8ee9..b7c6718c 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHRenderer.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHRenderer.h @@ -46,6 +46,7 @@ namespace SHADE { SHVec4 cameraPosition; SHMatrix viewProjectionMatrix; + SHMatrix viewMatrix; }; /*---------------------------------------------------------------------------------*/ @@ -79,15 +80,16 @@ namespace SHADE /*-----------------------------------------------------------------------------*/ void Draw(uint32_t frameIndex, Handle descPool) noexcept; void UpdateDataAndBind(Handle cmdBuffer, uint32_t frameIndex) noexcept; - void UpdateDataAndBind(Handle cmdBuffer, uint32_t frameIndex, SHMatrix exteriorMatrix) noexcept; + void UpdateDataAndBind(Handle cmdBuffer, uint32_t frameIndex, SHMatrix viewMatrix, SHMatrix projMatrix) noexcept; void UpdateCameraDataToBuffer (void) noexcept; - void SetViewProjectionMatrix (SHMatrix const& vpMatrix) noexcept; + void SetViewProjectionMatrix (SHMatrix viewMatrix, SHMatrix projMatrix) noexcept; /*-----------------------------------------------------------------------------*/ /* Setters and Getters */ /*-----------------------------------------------------------------------------*/ - Handle GetRenderGraph (void) const noexcept; + Handle GetRenderGraph (void) const noexcept; Handle GetCommandBuffer(uint32_t frameIndex) const noexcept; + Handle GetCameraDirector (void) const noexcept; private: /*-----------------------------------------------------------------------------*/ diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp index c4ba9fa1..ac7212bf 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp @@ -8,6 +8,7 @@ #include "SHLightComponent.h" #include "ECS_Base/Managers/SHComponentManager.h" #include "SHLightComponent.h" +#include "Math/Vector/SHVec4.h" namespace SHADE { @@ -31,7 +32,7 @@ namespace SHADE */ /***************************************************************************/ - void SHLightingSubSystem::PerTypeData::WriteLightToAddress(void* address, SHLightComponent* lightComp) noexcept + void SHLightingSubSystem::PerTypeData::WriteLightToAddress(void* address, SHMatrix const& viewMat, SHLightComponent* lightComp) noexcept { auto const& lightData = lightComp->GetLightData(); switch (lightData.type) @@ -41,6 +42,7 @@ namespace SHADE SHDirectionalLightData* lightPtr = reinterpret_cast(address); lightPtr->cullingMask = lightData.cullingMask; + //lightPtr->direction = viewMat * SHVec4 (lightData.direction[0], lightData.direction[1], lightData.direction[2], 0.0f); lightPtr->direction = lightData.direction; lightPtr->diffuseColor = lightData.color; lightPtr->active = lightComp->isActive; @@ -240,7 +242,7 @@ namespace SHADE */ /***************************************************************************/ - void SHLightingSubSystem::PerTypeData::AddLight(Handle logicalDevice, SHLightComponent* unboundLight, bool& expanded) noexcept + void SHLightingSubSystem::PerTypeData::AddLight(Handle logicalDevice, SHLightComponent* unboundLight, SHMatrix const& viewMat, bool& expanded) noexcept { if (unboundLight) { @@ -259,7 +261,7 @@ namespace SHADE void* writeLocation = reinterpret_cast(intermediateData.get()) + (lightDataAlignedSize * numLights); // Write the light data to address - WriteLightToAddress(writeLocation, unboundLight); + WriteLightToAddress(writeLocation, viewMat, unboundLight); // Set the light component to be bound to that location //unboundLight->SetBound(numLights); @@ -419,7 +421,7 @@ namespace SHADE */ /***************************************************************************/ - void SHLightingSubSystem::Run(Handle cmdBuffer, /*SHMatrix const& viewMat,*/ uint32_t frameIndex) noexcept + void SHLightingSubSystem::Run(SHMatrix const& viewMat, uint32_t frameIndex) noexcept { static uint32_t constexpr NUM_LIGHT_TYPES = SHUtilities::ToUnderlying(SH_LIGHT_TYPE::NUM_TYPES); @@ -447,7 +449,7 @@ namespace SHADE // isn't, we write it to the correct buffer. //if (!light.GetBound() || rewrite) { - perTypeData[enumValue].AddLight(logicalDevice, &light, expanded); + perTypeData[enumValue].AddLight(logicalDevice, &light, viewMat, expanded); // add to light count //++lightCountsData[enumValue]; @@ -492,8 +494,6 @@ namespace SHADE // so we do it anyway. #NoteToSelf: if at any point it affects performance, do a check before computing. ComputeDynamicOffsets(); - // Bind descriptor set (We bind at an offset because the buffer holds NUM_FRAME_BUFFERS sets of data). - cmdBuffer->BindDescriptorSet(lightingDataDescSet, SH_PIPELINE_TYPE::COMPUTE, SHGraphicsConstants::DescriptorSetIndex::DYNAMIC_GLOBALS, {dynamicOffsets[frameIndex]}); } @@ -509,4 +509,12 @@ namespace SHADE { } + + void SHLightingSubSystem::BindDescSet(Handle cmdBuffer, uint32_t frameIndex) noexcept + { + //Bind descriptor set(We bind at an offset because the buffer holds NUM_FRAME_BUFFERS sets of data). + cmdBuffer->BindDescriptorSet(lightingDataDescSet, SH_PIPELINE_TYPE::COMPUTE, SHGraphicsConstants::DescriptorSetIndex::DYNAMIC_GLOBALS, { dynamicOffsets[frameIndex] }); + + } + } diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.h b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.h index 4a667ec5..ae6caead 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.h @@ -95,14 +95,14 @@ namespace SHADE //! to the GPU that stores NUM_FRAME_BUFFERS copies. std::unique_ptr intermediateData; - void WriteLightToAddress (void* address, SHLightComponent* lightComp) noexcept; + void WriteLightToAddress (void* address, SHMatrix const& viewMat, SHLightComponent* lightComp) noexcept; public: /*-----------------------------------------------------------------------*/ /* PUBLIC MEMBER FUNCTIONS */ /*-----------------------------------------------------------------------*/ void InitializeData (Handle logicalDevice, SH_LIGHT_TYPE type) noexcept; void Expand (Handle logicalDevice) noexcept; - void AddLight (Handle logicalDevice, SHLightComponent* unboundLight, bool& expanded) noexcept; + void AddLight (Handle logicalDevice, SHLightComponent* unboundLight, SHMatrix const& viewMat, bool& expanded) noexcept; //void ModifyLight (SHLightComponent* lightComp) noexcept; void WriteToGPU (uint32_t frameIndex) noexcept; void ResetNumLights (void) noexcept; @@ -159,8 +159,10 @@ namespace SHADE /* PUBLIC MEMBER FUNCTIONS */ /*-----------------------------------------------------------------------*/ void Init (Handle device, Handle descPool) noexcept; - void Run (Handle cmdBuffer, /*SHMatrix const& viewMat,*/ uint32_t frameIndex) noexcept; + void Run (SHMatrix const& viewMat, uint32_t frameIndex) noexcept; void Exit (void) noexcept; + void BindDescSet (Handle cmdBuffer, uint32_t frameIndex) noexcept; + }; } From 39b5ac0774081d9fb9336d6512a1a90b02eea1e7 Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Sun, 30 Oct 2022 16:52:40 +0800 Subject: [PATCH 04/27] LIGHTING NOW DONE IN VIEW SPACE --- Assets/Shaders/TestCube_VS.glsl | 15 ++++++++++++--- Assets/Shaders/TestCube_VS.shshaderb | Bin 3385 -> 3525 bytes .../MiddleEnd/Interface/SHRenderer.cpp | 2 +- .../MiddleEnd/Lights/SHLightingSubSystem.cpp | 7 +++++-- 4 files changed, 18 insertions(+), 6 deletions(-) diff --git a/Assets/Shaders/TestCube_VS.glsl b/Assets/Shaders/TestCube_VS.glsl index 44c6e956..867b945f 100644 --- a/Assets/Shaders/TestCube_VS.glsl +++ b/Assets/Shaders/TestCube_VS.glsl @@ -38,14 +38,23 @@ layout(set = 2, binding = 0) uniform CameraData void main() { - Out2.materialIndex = gl_InstanceIndex; Out2.eid = integerData[0]; Out2.lightLayerIndex = integerData[1]; - Out.vertPos = worldTransform * vec4(aVertexPos, 1.0f); + // for transforming gBuffer position and normal data + mat4 modelViewMat = cameraData.viewMat * worldTransform; + + // gBuffer position will be in view space + Out.vertPos = modelViewMat * vec4(aVertexPos, 1.0f); + + // uvs for texturing in fragment shader Out.uv = aUV; - Out.normal.rgb = mat3(transpose(inverse(worldTransform))) * aNormal.rgb; + + // normals are also in view space + Out.normal.rgb = mat3(transpose(inverse(modelViewMat))) * aNormal.rgb; Out.normal.rgb = normalize (Out.normal.rgb); + + // clip space for rendering gl_Position = cameraData.vpMat * worldTransform * vec4 (aVertexPos, 1.0f); } \ No newline at end of file diff --git a/Assets/Shaders/TestCube_VS.shshaderb b/Assets/Shaders/TestCube_VS.shshaderb index 2544abd58b576513f2e8185a0b84ef070e6a42fe..b7e1294bb1b2fcbe7f31212c0662330feff59f48 100644 GIT binary patch literal 3525 zcmZ9MYj+c65XYb922!q4E-GTuqE)N)28beHY%#3{5^Sk=!lQZX;`OkG{=860JgiBAkv~1uZ zkpq6@C4L-u;bt`OpQJh>(+TJNU~phdePJ-%OWNL3KhCVl!8dkh37_Vwip%#7!`@~z zO}wb@TUhC;X&-_p@rQoA?j@d(n!6(V(Rkp8JAwcBo<}=U+gEk3c_TmeQd3#h92jRZ zo(4%UPJ3LFH8}O|PqF}pQS*Ktmi)_-`-Pa~XD*M&aX8qHy=b~Sjz{D#yL79LWlWr{xChI{q8%4|f*kW|EFg(!F z1NM_c{S3z2_M)L5r88>fv%f4He`IDqFIvgv1>NY`rwzrh`7KH2Y{@spyA{A8*U@ftg=Rm68vPdfA7?Lvlkh2R*w%{k$V&=84Qf<}DXx=84Q4 z&{GF8`KX6EaOe@oFzms&4Z{bF-WmoEmeo^EiK7d+L&p3nxBtut#Puz|iwAi7$HdKO-Lf z1?ivHO>Sz&{;Y0v;KV~_ufXuf_MC`={dwK!to|3olMmVQy(FIa=6^{%KIdgw*9}oi zBj@S&Mahf0!H~(dq?@?l^pD*_j|^e+n(mSa9rYtG=NS6ebKdM%B+rSEu}5YP!KmpS z-E|Q$$;p3HLj=xE%=dKj&FF}M%-w-+X#~ti% ziz8M;g#4*)Y^ec%{oG#w@z(5Oe)Rgg^G^*~LE<7u_upxv}B<*v&g4_TA=y zj2*SHgP)0-DOJOSyuXf!T8NFU&Fz7B z-Xi^_-mgU1f;Z*M+uRn>FZPFBruMq-ha&7b>o>{McXf`&vAH)QBH;VCMI& zc=O|b!2G@wk00NSA9i522j7b~KfbRa`3DiW_36hP1Ls(um^I)3Q;sobY^|oAc#B=^ z!6V`LaHt8pMV_Z-L`%HMLf94 zzltxu^-wZ4;I4xZk$nOR# literal 3385 zcmZ9NdwUaA5XMiNOOXPC$VEj=S}$m|Rs}?nOYJ2sh9=lj@5Dp0gw@R^PqGc*Uw#Gs zNPa5+@p*WEyE|ncPoH_t%scPQnKL^lbt}hRx=OQ)bI#4UqwcsHW{^AOW`#I6@2ctE zXzn(bCrNMl@|6`RCtN9I!g*PLtg>X_!x;Ujg!HdU-jQ6Ad?@)`vMG5WfmqVttoDDD zsH~_)v(sp`8qJMPcQooul4nuSiNZMO^ulq_O~Ppa??{0c#@*Kgesz9^kKvH8aHlBL{czVS0R_?dNV7B+K_%{*fB28w>Z12#3|=WSq9@0Mz!e=N>q z83rGW-7sRnsMRoZu_Tw6jt zgDvGbt^YOI$ApugJn*rZ3o!ir8WM}&;!jD(e@^~av~xB!!#}MZ zA2|82nJX~j;hvGO;Gflw&+30oI_F{Ad2dK3zr|mWPRv;`YuXWNspmTLfxVF1#L}-t z?Qp;|ZrQypo%8TfFE(=zc3$?o+ToIudf(GNBLRnx&AR~O%n!8JB*epC(vA-tJ~rde(JrcowLB~yiMuG-_CtC?bgp7 z>GbG=;(yX!OLcmd{Z7_%3}5CiyI-Vp25*{kupi_Yz2+?tN1qUC{Z%{X;3EdxOTh3y z%ysK6z2cqBNUka;JiY^qv;P&s8@(a4s{Mq7*EvLJ$$a?LLw) zBllE8P5Z|ZFqUB}(!uDBVV~p}eQN7Ab?y8^CmufjWyxR4i|;cDXTzaZX77rG`L~{7 z!=ttZ?bjsCAADx-O9_1I4>laT+jZ&O?U=q0cl}C2&E&$jm-pa?bbQ=}+HOg}SS|gU z(U;p2aD+u3?rJfs(uo1Ln6IUSBP@Kym^InNfLYACbZ~@aF>T#}_q8FpEg?5t`)&>C zn-cmUtRXM5^(F&ZjOPotWSJv?!T8~8`|MoP4}f+?qU!2 zg%iV~CU{^L_nmZ$EB4@f;dT~r@W3qYheBMj2S4U<)&qE8^x&cPuEa~2ZJXy_j+-6G zz9jiuG0gWP2^?^ni@x;Ydwwh%jAh>=lnzD@4f`#}sL$T>@6w5fkH7eyBiWn}$G+o0 SI={>F5_*FT??0V%P4XNphWKOv diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHRenderer.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHRenderer.cpp index a44e0661..655451ec 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHRenderer.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHRenderer.cpp @@ -108,7 +108,7 @@ namespace SHADE { //cpuCameraData.viewProjectionMatrix = camera->GetViewMatrix() * camera->GetProjectionMatrix(); cpuCameraData.viewProjectionMatrix = SHMatrix::Transpose(projMatrix * viewMatrix); - cpuCameraData.viewMatrix = viewMatrix; + cpuCameraData.viewMatrix = SHMatrix::Transpose(viewMatrix); } Handle SHRenderer::GetRenderGraph(void) const noexcept diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp index ac7212bf..35bcc72f 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp @@ -9,6 +9,7 @@ #include "ECS_Base/Managers/SHComponentManager.h" #include "SHLightComponent.h" #include "Math/Vector/SHVec4.h" +#include "Math/SHMatrix.h" namespace SHADE { @@ -41,9 +42,11 @@ namespace SHADE { SHDirectionalLightData* lightPtr = reinterpret_cast(address); + SHVec4 transformedDir = viewMat * SHVec4(lightData.direction[0], lightData.direction[1], lightData.direction[2], 0.0f); + lightPtr->cullingMask = lightData.cullingMask; - //lightPtr->direction = viewMat * SHVec4 (lightData.direction[0], lightData.direction[1], lightData.direction[2], 0.0f); - lightPtr->direction = lightData.direction; + lightPtr->direction = SHVec3 (transformedDir.x, transformedDir.y, transformedDir.z); + //lightPtr->direction = lightData.direction; lightPtr->diffuseColor = lightData.color; lightPtr->active = lightComp->isActive; break; From 647182241efad86d80d5ec63df6a83ea4e0036f3 Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Sun, 30 Oct 2022 19:21:02 +0800 Subject: [PATCH 05/27] Fixed a buy with view space lighting calculations --- Assets/Shaders/DeferredComposite_CS.glsl | 6 +++--- Assets/Shaders/DeferredComposite_CS.shshaderb | Bin 4665 -> 4665 bytes .../MiddleEnd/Interface/SHGraphicsConstants.h | 12 +++++++++++- .../MiddleEnd/Lights/SHLightingSubSystem.cpp | 3 ++- .../RenderGraph/SHRenderGraphNodeCompute.cpp | 14 +++++--------- .../RenderGraph/SHRenderGraphNodeCompute.h | 10 +++++++++- 6 files changed, 30 insertions(+), 15 deletions(-) diff --git a/Assets/Shaders/DeferredComposite_CS.glsl b/Assets/Shaders/DeferredComposite_CS.glsl index c1caf0aa..5f586b9b 100644 --- a/Assets/Shaders/DeferredComposite_CS.glsl +++ b/Assets/Shaders/DeferredComposite_CS.glsl @@ -51,10 +51,10 @@ void main() vec3 pixelDiffuse = imageLoad (albedo, globalThread).rgb; // Get position of fragment in world space - vec3 positionWorld = imageLoad (positions, globalThread).rgb; + vec3 positionView = imageLoad (positions, globalThread).rgb; // normal of fragment - vec3 normalWorld = imageLoad(normals, globalThread).rgb; + vec3 normalView = imageLoad(normals, globalThread).rgb; vec3 fragColor = vec3 (0.0f); @@ -64,7 +64,7 @@ void main() vec3 dLightNormalized = normalize (DirLightData.dLightData[i].direction); // Get diffuse strength - float diffuseStrength = max (0, dot (dLightNormalized, normalWorld)); + float diffuseStrength = max (0, dot (dLightNormalized, normalView)); // Calculate the fragment color fragColor += DirLightData.dLightData[i].diffuseColor.rgb * diffuseStrength.rrr * pixelDiffuse; diff --git a/Assets/Shaders/DeferredComposite_CS.shshaderb b/Assets/Shaders/DeferredComposite_CS.shshaderb index 889de5fb344289c281264b054407d97c317a7fff..aaaa5207fc09134d01b8cdfec1bc483a63024116 100644 GIT binary patch delta 28 fcmdm~vQuS)FC%MMW@2y1f<<6Z#(hieG| delta 28 fcmdm~vQuS)FC%Mseo;=!2y1f<<6Z#(krN5q diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsConstants.h b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsConstants.h index a39ec10e..0257bf3b 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsConstants.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsConstants.h @@ -70,7 +70,17 @@ namespace SHADE */ /***************************************************************************/ static constexpr uint32_t RENDERGRAPH_RESOURCE = 4; - + /***************************************************************************/ + /*! + \brief + DescriptorSet Index for render graph node compute resources. For data + that we wish to pass to compute shaders in the render graph, this is + the set to use. Unlike the sets from 1 to 3, this set index does not have + hard coded bindings and is NOT part of the layouts included in the global + data. + */ + /***************************************************************************/ + static constexpr uint32_t RENDERGRAPH_NODE_COMPUTE_RESOURCE = 5; }; diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp index 35bcc72f..485f859f 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp @@ -42,7 +42,8 @@ namespace SHADE { SHDirectionalLightData* lightPtr = reinterpret_cast(address); - SHVec4 transformedDir = viewMat * SHVec4(lightData.direction[0], lightData.direction[1], lightData.direction[2], 0.0f); + // #NoteToSelf: NEED TO TRANSPOSE HERE BECAUSE MULTIPLICATION IS ROW MAJOR. + SHVec4 transformedDir = SHMatrix::Transpose(viewMat) * SHVec4(lightData.direction[0], lightData.direction[1], lightData.direction[2], 0.0f); lightPtr->cullingMask = lightData.cullingMask; lightPtr->direction = SHVec3 (transformedDir.x, transformedDir.y, transformedDir.z); diff --git a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp index 5323d706..6a9b1c31 100644 --- a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp +++ b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp @@ -42,16 +42,12 @@ namespace SHADE //Get the descriptor set layouts required to allocate. We only want the ones for allocate because //global descriptors are already bound in the main system. - auto const& layouts = computePipeline->GetPipelineLayout()->GetDescriptorSetLayoutsAllocate(); - - //Variable counts for the descriptor sets (all should be 1). - std::vector variableCounts{ static_cast(layouts.size()) }; - std::fill(variableCounts.begin(), variableCounts.end(), 0); + auto const& layouts = computePipeline->GetPipelineLayout()->GetDescriptorSetLayoutsPipeline()[SHGraphicsConstants::DescriptorSetIndex::RENDERGRAPH_RESOURCE]; // Allocate descriptor sets to hold the images for reading (STORAGE_IMAGE) for (uint32_t i = 0; i < SHGraphicsConstants::NUM_FRAME_BUFFERS; ++i) { - descSetGroups[i] = graphStorage->descriptorPool->Allocate(layouts, variableCounts); + graphResourceDescSets[i] = graphStorage->descriptorPool->Allocate({layouts}, { 1 }); } HandleResize(); @@ -63,7 +59,7 @@ namespace SHADE cmdBuffer->BindPipeline(computePipeline); // bind descriptor sets - cmdBuffer->BindDescriptorSet(descSetGroups[frameIndex], SH_PIPELINE_TYPE::COMPUTE, SHGraphicsConstants::DescriptorSetIndex::RENDERGRAPH_RESOURCE, {}); + cmdBuffer->BindDescriptorSet(graphResourceDescSets[frameIndex], SH_PIPELINE_TYPE::COMPUTE, SHGraphicsConstants::DescriptorSetIndex::RENDERGRAPH_RESOURCE, {}); // dispatch compute cmdBuffer->ComputeDispatch(groupSizeX, groupSizeY, 1); @@ -89,8 +85,8 @@ namespace SHADE uint32_t imageIndex = (resources[i]->resourceTypeFlags & static_cast(SH_ATT_DESC_TYPE_FLAGS::COLOR_PRESENT)) ? frameIndex : 0; SHVkDescriptorSetGroup::viewSamplerLayout vsl = std::make_tuple(resources[i]->GetImageView(imageIndex), Handle{}, vk::ImageLayout::eGeneral); - descSetGroups[frameIndex]->ModifyWriteDescImage(SHGraphicsConstants::DescriptorSetIndex::RENDERGRAPH_RESOURCE, binding.BindPoint, { &vsl, 1 }); - descSetGroups[frameIndex]->UpdateDescriptorSetImages(SHGraphicsConstants::DescriptorSetIndex::RENDERGRAPH_RESOURCE, binding.BindPoint); + graphResourceDescSets[frameIndex]->ModifyWriteDescImage(SHGraphicsConstants::DescriptorSetIndex::RENDERGRAPH_RESOURCE, binding.BindPoint, { &vsl, 1 }); + graphResourceDescSets[frameIndex]->UpdateDescriptorSetImages(SHGraphicsConstants::DescriptorSetIndex::RENDERGRAPH_RESOURCE, binding.BindPoint); ++i; } } diff --git a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.h b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.h index 2cd3c948..d7c29f49 100644 --- a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.h +++ b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.h @@ -19,12 +19,15 @@ namespace SHADE class SHVkShaderModule; class SHVkCommandBuffer; + class SHRenderGraphNodeCompute { private: static constexpr uint32_t workGroupSizeX = 16; static constexpr uint32_t workGroupSizeY = 16; + using ExternalDescSetBindCommands = std::function)>; + //! To run the dispatch command Handle computePipeline; @@ -32,7 +35,12 @@ namespace SHADE Handle pipelineLayout; //! Descriptor set group to hold the images for reading (STORAGE_IMAGE) - std::array, SHGraphicsConstants::NUM_FRAME_BUFFERS> descSetGroups; + std::array, SHGraphicsConstants::NUM_FRAME_BUFFERS> graphResourceDescSets; + + //! Sometimes we want to bind descriptor sets for a compute resource (buffers, images, etc). This container + //! helps store functions that call those bind functions. The reason why we dont just have a handle to descriptor + //! sets here is because we dont know how we want to bind the sets (different set each frame, dynamic offsets, etc). + std::vector externalDescriptorSetBindCommands; //! vector of resources needed by the subpass compute std::vector> resources; From 997ce3011a836053440156696817f67c6c95c402 Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Sun, 30 Oct 2022 23:15:52 +0800 Subject: [PATCH 06/27] Screw you SPIRV-Reflect and screw you GLSL - Pipeline layouts now have a parameter to decide if a binding with a buffer descriptor stores a dynamic type instead. - SHRenderGraphNodeCompute has catered for this as well through its ctor params --- .../Descriptors/SHVkDescriptorSetLayout.cpp | 12 ++++++ .../Descriptors/SHVkDescriptorSetLayout.h | 1 + .../MiddleEnd/PostProcessing/SHSSAO.cpp | 7 ++++ .../MiddleEnd/PostProcessing/SHSSAO.h | 15 +++++++ .../Pipeline/SHPipelineLayoutParams.h | 8 ++++ .../Graphics/Pipeline/SHVkPipelineLayout.cpp | 23 +++++++++++ .../Graphics/Pipeline/SHVkPipelineLayout.h | 3 ++ .../RenderGraph/SHRenderGraphNode.cpp | 4 +- .../Graphics/RenderGraph/SHRenderGraphNode.h | 2 +- .../RenderGraph/SHRenderGraphNodeCompute.cpp | 39 +++++++++++++++++-- .../RenderGraph/SHRenderGraphNodeCompute.h | 22 ++++++++--- 11 files changed, 123 insertions(+), 13 deletions(-) create mode 100644 SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.cpp create mode 100644 SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.h diff --git a/SHADE_Engine/src/Graphics/Descriptors/SHVkDescriptorSetLayout.cpp b/SHADE_Engine/src/Graphics/Descriptors/SHVkDescriptorSetLayout.cpp index 0943c489..4be8cc9e 100644 --- a/SHADE_Engine/src/Graphics/Descriptors/SHVkDescriptorSetLayout.cpp +++ b/SHADE_Engine/src/Graphics/Descriptors/SHVkDescriptorSetLayout.cpp @@ -119,6 +119,18 @@ namespace SHADE return setIndex; } + uint32_t SHVkDescriptorSetLayout::GetNumDynamicOffsetsRequired(void) const noexcept + { + uint32_t numDynamicBindings = 0; + for (auto& binding : layoutDesc) + { + if (binding.Type == vk::DescriptorType::eUniformBufferDynamic || binding.Type == vk::DescriptorType::eStorageBufferDynamic) + ++numDynamicBindings; + } + + return numDynamicBindings; + } + SHVkDescriptorSetLayout& SHVkDescriptorSetLayout::operator=(SHVkDescriptorSetLayout&& rhs) noexcept { if (&rhs == this) diff --git a/SHADE_Engine/src/Graphics/Descriptors/SHVkDescriptorSetLayout.h b/SHADE_Engine/src/Graphics/Descriptors/SHVkDescriptorSetLayout.h index 1639901d..caa3c057 100644 --- a/SHADE_Engine/src/Graphics/Descriptors/SHVkDescriptorSetLayout.h +++ b/SHADE_Engine/src/Graphics/Descriptors/SHVkDescriptorSetLayout.h @@ -99,6 +99,7 @@ namespace SHADE inline const vk::DescriptorSetLayout& GetVkHandle() const { return setLayout; } std::vector const& GetBindings (void) const noexcept; SetIndex GetSetIndex (void) const noexcept; + uint32_t GetNumDynamicOffsetsRequired (void) const noexcept; private: /*-----------------------------------------------------------------------------*/ diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.cpp new file mode 100644 index 00000000..fb5ae824 --- /dev/null +++ b/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.cpp @@ -0,0 +1,7 @@ +#include "SHpch.h" +#include "SHSSAO.h" + +namespace SHADE +{ + +} diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.h b/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.h new file mode 100644 index 00000000..17df7200 --- /dev/null +++ b/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.h @@ -0,0 +1,15 @@ +#pragma once + +#include "Resource/SHHandle.h" +#include "Graphics/SHVulkanIncludes.h" + +namespace SHADE +{ + + class SHSSAO + { + private: + + + }; +} diff --git a/SHADE_Engine/src/Graphics/Pipeline/SHPipelineLayoutParams.h b/SHADE_Engine/src/Graphics/Pipeline/SHPipelineLayoutParams.h index d696e4a3..010bed0e 100644 --- a/SHADE_Engine/src/Graphics/Pipeline/SHPipelineLayoutParams.h +++ b/SHADE_Engine/src/Graphics/Pipeline/SHPipelineLayoutParams.h @@ -2,8 +2,10 @@ #define SH_PIPELINE_LAYOUT_PARAMS_H #include "Graphics/SHVulkanIncludes.h" +#include "Graphics/SHVulkanDefines.h" #include "Resource/SHHandle.h" #include "Graphics/Descriptors/SHVkDescriptorSetLayout.h" +#include namespace SHADE { @@ -24,6 +26,12 @@ namespace SHADE //! want to use the layout to initialize the pipeline layout but we do not //! want to use it for allocating descriptor sets. std::vector> const& globalDescSetLayouts = {}; + + //! Since both SPIRV-Reflect and GLSL don't provide ways to describe UBOs or + //! SSBOs as dynamic, we need to do it ourselves. This will store bindings + //! which we will use when parsing for descriptor set layouts. If a parsed + //! binding is in this container, we make that binding's descriptor dynamic. + std::unordered_set dynamicBufferBindings; }; struct SHPipelineLayoutParamsDummy diff --git a/SHADE_Engine/src/Graphics/Pipeline/SHVkPipelineLayout.cpp b/SHADE_Engine/src/Graphics/Pipeline/SHVkPipelineLayout.cpp index 37d00795..47b2e010 100644 --- a/SHADE_Engine/src/Graphics/Pipeline/SHVkPipelineLayout.cpp +++ b/SHADE_Engine/src/Graphics/Pipeline/SHVkPipelineLayout.cpp @@ -165,6 +165,28 @@ namespace SHADE newBinding.Stage = shaderModule->GetShaderStageFlagBits(); newBinding.Type = descBindingInfo.ConvertFromReflectDescType(reflectedBinding->descriptor_type); + // Here we want to check if a binding is supposed to be dynamic. If it is, make it dynamic. + if (newBinding.Type == vk::DescriptorType::eUniformBuffer || newBinding.Type == vk::DescriptorType::eStorageBuffer) + { + for (auto& bsHash : dynamicBufferBindings) + { + uint32_t set = static_cast(bsHash >> 32); + uint32_t binding = static_cast(bsHash & 0xFFFFFFFF); + if (set == CURRENT_SET && binding == newBinding.BindPoint) + { + switch (newBinding.Type) + { + case vk::DescriptorType::eUniformBuffer: + newBinding.Type = vk::DescriptorType::eUniformBufferDynamic; + break; + case vk::DescriptorType::eStorageBuffer: + newBinding.Type = vk::DescriptorType::eStorageBufferDynamic; + break; + } + } + } + } + // In reality, the check for variable descriptor sets do not exists in spirv-reflect. Fortunately, when a shader // defines a boundless descriptor binding in the shader, the information reflected makes the array dimensions // contain a 1 element of value 1. Knowing that having an array [1] doesn't make sense, we can use this to @@ -300,6 +322,7 @@ namespace SHADE , vkDescriptorSetLayoutsAllocate{} , descriptorSetLayoutsPipeline{} , vkDescriptorSetLayoutsPipeline{} + , dynamicBufferBindings{std::move (pipelineLayoutParams.dynamicBufferBindings)} { for (auto& mod : shaderModules) { diff --git a/SHADE_Engine/src/Graphics/Pipeline/SHVkPipelineLayout.h b/SHADE_Engine/src/Graphics/Pipeline/SHVkPipelineLayout.h index b4298e00..e2af02a9 100644 --- a/SHADE_Engine/src/Graphics/Pipeline/SHVkPipelineLayout.h +++ b/SHADE_Engine/src/Graphics/Pipeline/SHVkPipelineLayout.h @@ -29,6 +29,9 @@ namespace SHADE //! Push constant interface SHPushConstantInterface pushConstantInterface; + //! See SHPipelineLayoutParams for details + std::unordered_set dynamicBufferBindings; + //! Push constant ranges std::vector vkPcRanges; diff --git a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNode.cpp b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNode.cpp index aa9c7944..12f0e246 100644 --- a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNode.cpp +++ b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNode.cpp @@ -263,7 +263,7 @@ namespace SHADE return subpass; } - Handle SHRenderGraphNode::AddNodeCompute(Handle computeShaderModule, std::initializer_list resources, float numWorkGroupScale/* = 1.0f*/) noexcept + Handle SHRenderGraphNode::AddNodeCompute(Handle computeShaderModule, std::initializer_list resources, std::unordered_set&& dynamicBufferBindings, float numWorkGroupScale/* = 1.0f*/) noexcept { // Look for the required resources in the graph std::vector> nodeComputeResources{}; @@ -276,7 +276,7 @@ namespace SHADE } // Create the subpass compute with the resources - auto nodeCompute = graphStorage->resourceManager->Create(graphStorage, computeShaderModule, std::move(nodeComputeResources), nodeComputes.empty()); + auto nodeCompute = graphStorage->resourceManager->Create(graphStorage, computeShaderModule, std::move(nodeComputeResources), std::move (dynamicBufferBindings), nodeComputes.empty()); nodeComputes.push_back(nodeCompute); return nodeCompute; diff --git a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNode.h b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNode.h index 16f3f914..695d1c31 100644 --- a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNode.h +++ b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNode.h @@ -100,7 +100,7 @@ namespace SHADE /* PUBLIC MEMBER FUNCTIONS */ /*-----------------------------------------------------------------------*/ Handle AddSubpass(std::string subpassName) noexcept; - Handle AddNodeCompute(Handle computeShaderModule, std::initializer_list resources, float numWorkGroupScale = 1.0f) noexcept; + Handle AddNodeCompute(Handle computeShaderModule, std::initializer_list resources, std::unordered_set&& dynamicBufferBindings = {}, float numWorkGroupScale = 1.0f) noexcept; void AddDummySubpassIfNeeded (void) noexcept; // TODO: RemoveSubpass() diff --git a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp index 6a9b1c31..b5f6f7ab 100644 --- a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp +++ b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp @@ -13,7 +13,7 @@ namespace SHADE { - SHRenderGraphNodeCompute::SHRenderGraphNodeCompute(Handle graphStorage, Handle computeShaderModule, std::vector>&& subpassComputeResources, bool followingEndRP, float inNumWorkGroupScale/* = 1.0f*/) noexcept + SHRenderGraphNodeCompute::SHRenderGraphNodeCompute(Handle graphStorage, Handle computeShaderModule, std::vector>&& subpassComputeResources, std::unordered_set&& dynamicBufferBindings, bool followingEndRP, float inNumWorkGroupScale/* = 1.0f*/) noexcept : computePipeline{} , pipelineLayout{} , resources{} @@ -21,11 +21,13 @@ namespace SHADE , groupSizeY{0} , followingEndRenderpass {followingEndRP} , numWorkGroupScale {std::clamp(inNumWorkGroupScale, 0.0f, 1.0f)} + , computeResource{} { SHPipelineLayoutParams pipelineLayoutParams { .shaderModules = {computeShaderModule}, - .globalDescSetLayouts = SHGraphicsGlobalData::GetDescSetLayouts() + .globalDescSetLayouts = SHGraphicsGlobalData::GetDescSetLayouts(), + .dynamicBufferBindings = std::move(dynamicBufferBindings), }; // Create pipeline layout from parameters @@ -42,12 +44,31 @@ namespace SHADE //Get the descriptor set layouts required to allocate. We only want the ones for allocate because //global descriptors are already bound in the main system. - auto const& layouts = computePipeline->GetPipelineLayout()->GetDescriptorSetLayoutsPipeline()[SHGraphicsConstants::DescriptorSetIndex::RENDERGRAPH_RESOURCE]; + auto const& graphResourceLayout = computePipeline->GetPipelineLayout()->GetDescriptorSetLayoutsPipeline()[SHGraphicsConstants::DescriptorSetIndex::RENDERGRAPH_RESOURCE]; // Allocate descriptor sets to hold the images for reading (STORAGE_IMAGE) for (uint32_t i = 0; i < SHGraphicsConstants::NUM_FRAME_BUFFERS; ++i) { - graphResourceDescSets[i] = graphStorage->descriptorPool->Allocate({layouts}, { 1 }); + graphResourceDescSets[i] = graphStorage->descriptorPool->Allocate({graphResourceLayout}, { 1 }); + } + + + auto const& layouts = computePipeline->GetPipelineLayout()->GetDescriptorSetLayoutsPipeline(); + + if (layouts.size() == SHGraphicsConstants::DescriptorSetIndex::RENDERGRAPH_NODE_COMPUTE_RESOURCE + 1) + { + // create compute resources + computeResource = graphStorage->resourceManager->Create(); + auto computeResourceLayout = layouts[SHGraphicsConstants::DescriptorSetIndex::RENDERGRAPH_NODE_COMPUTE_RESOURCE]; + computeResource->descSet = graphStorage->descriptorPool->Allocate({ computeResourceLayout }, { 1 }); + + // Allocate for descriptor offsets + for (uint32_t i = 0; i < SHGraphicsConstants::NUM_FRAME_BUFFERS; ++i) + computeResource->dynamicOffsets[i].resize(computeResourceLayout->GetNumDynamicOffsetsRequired()); + + // 1st set all start at 0 + for (auto& index : computeResource->dynamicOffsets[0]) + index = 0; } HandleResize(); @@ -133,4 +154,14 @@ namespace SHADE } } + void SHRenderGraphNodeCompute::SetDynamicOffsets(std::span perFrameSizes) noexcept + { + for (uint32_t i = 0; i < SHGraphicsConstants::NUM_FRAME_BUFFERS; ++i) + { + auto dynamicOffsets = computeResource->dynamicOffsets[i]; + for (uint32_t j = 0; j < perFrameSizes.size(); ++j) + dynamicOffsets[j] = perFrameSizes[j] * i; + } + } + } diff --git a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.h b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.h index d7c29f49..1101e276 100644 --- a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.h +++ b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.h @@ -22,11 +22,22 @@ namespace SHADE class SHRenderGraphNodeCompute { + private: + // Binding of set SHGraphicsConstants::DescriptorSetIndex::RENDERGRAPH_NODE_COMPUTE_RESOURCE + struct ComputeResource + { + //! Descriptor set (initialized by parent class) + Handle descSet {}; + + //! Dynamic offsets into these resources (initialized from the outside). + std::array, SHGraphicsConstants::NUM_FRAME_BUFFERS> dynamicOffsets {}; + }; + private: static constexpr uint32_t workGroupSizeX = 16; static constexpr uint32_t workGroupSizeY = 16; - using ExternalDescSetBindCommands = std::function)>; + using ExternalDescSetBindCommands = std::function, Handle)>; //! To run the dispatch command Handle computePipeline; @@ -37,10 +48,7 @@ namespace SHADE //! Descriptor set group to hold the images for reading (STORAGE_IMAGE) std::array, SHGraphicsConstants::NUM_FRAME_BUFFERS> graphResourceDescSets; - //! Sometimes we want to bind descriptor sets for a compute resource (buffers, images, etc). This container - //! helps store functions that call those bind functions. The reason why we dont just have a handle to descriptor - //! sets here is because we dont know how we want to bind the sets (different set each frame, dynamic offsets, etc). - std::vector externalDescriptorSetBindCommands; + Handle computeResource; //! vector of resources needed by the subpass compute std::vector> resources; @@ -58,11 +66,13 @@ namespace SHADE std::array, SHGraphicsConstants::NUM_FRAME_BUFFERS> memoryBarriers; public: - SHRenderGraphNodeCompute(Handle graphStorage, Handle computeShaderModule, std::vector>&& subpassComputeResources, bool followingEndRP, float inNumWorkGroupScale = 1.0f) noexcept; + SHRenderGraphNodeCompute(Handle graphStorage, Handle computeShaderModule, std::vector>&& subpassComputeResources, std::unordered_set&& dynamicBufferBindings, bool followingEndRP, float inNumWorkGroupScale = 1.0f) noexcept; void Execute (Handle cmdBuffer, uint32_t frameIndex) noexcept; void HandleResize (void) noexcept; + void SetDynamicOffsets (std::span perFrameSizes) noexcept; + friend class SHRenderGraph; friend class SHRenderGraphNode; }; From 94a57219da3f1d8ccc53b9dd463758cb029aaa49 Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Mon, 31 Oct 2022 10:32:32 +0800 Subject: [PATCH 07/27] Created CPU and GPU data for SSAO Renderpass for SSAO not yet done (that's next) --- Assets/Shaders/SSAO_CS.glsl | 24 +++++++++ .../MiddleEnd/Interface/SHGraphicsSystem.cpp | 12 +++++ .../MiddleEnd/Interface/SHGraphicsSystem.h | 3 ++ .../MiddleEnd/PostProcessing/SHSSAO.cpp | 53 +++++++++++++++++++ .../MiddleEnd/PostProcessing/SHSSAO.h | 22 ++++++++ .../src/Graphics/Queues/SHVkQueue.cpp | 5 ++ SHADE_Engine/src/Graphics/Queues/SHVkQueue.h | 2 + .../RenderGraph/SHRenderGraphNodeCompute.cpp | 5 ++ .../RenderGraph/SHRenderGraphNodeCompute.h | 6 ++- 9 files changed, 130 insertions(+), 2 deletions(-) create mode 100644 Assets/Shaders/SSAO_CS.glsl diff --git a/Assets/Shaders/SSAO_CS.glsl b/Assets/Shaders/SSAO_CS.glsl new file mode 100644 index 00000000..3759c4b4 --- /dev/null +++ b/Assets/Shaders/SSAO_CS.glsl @@ -0,0 +1,24 @@ +#version 450 + +uint const NUM_SAMPLES = 64; +uint const NUM_ROTATIONS = 16; + +layout(local_size_x = 16, local_size_y = 16) in; +layout(set = 4, binding = 0, rgba32f) uniform image2D positions; +layout(set = 4, binding = 1, rgba32f) uniform image2D normals; +layout(set = 4, binding = 2, rgba32f) uniform image2D outputImage; + + +// SSAO data +layout(std430, set = 5, binding = 0) buffer SSAOData +{ + vec3 samples[NUM_SAMPLES]; + vec3 rotations[NUM_ROTATIONS]; + +} ssaoData; + +void main() +{ + // store result into result image + imageStore(outputImage, ivec2(gl_GlobalInvocationID.xy), vec4(fragColor, 1.0f)); +} \ No newline at end of file diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp index edf0be23..d062b4d6 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp @@ -253,6 +253,18 @@ namespace SHADE lightingSubSystem = resourceManager.Create(); lightingSubSystem->Init(device, descPool); + + ssaoStorage = resourceManager.Create(); + + ssaoTransferCmdBuffer = graphicsCmdPool->RequestCommandBuffer(SH_CMD_BUFFER_TYPE::PRIMARY); + ssaoTransferCmdBuffer->BeginRecording(); + + ssaoStorage->Init(device, ssaoTransferCmdBuffer); + + ssaoTransferCmdBuffer->EndRecording(); + graphicsQueue->SubmitCommandBuffer({ssaoTransferCmdBuffer}); + + graphicsQueue->WaitIdle(); } #ifdef SHEDITOR diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h index 072a1d99..9b95ebe4 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h @@ -32,6 +32,7 @@ of DigiPen Institute of Technology is prohibited. #include "../Textures/SHVkSamplerCache.h" #include "Graphics/MiddleEnd/Interface/SHPostOffscreenRenderSystem.h" #include "Graphics/MiddleEnd/Lights/SHLightingSubSystem.h" +#include "Graphics/MiddleEnd/PostProcessing/SHSSAO.h" namespace SHADE { @@ -313,6 +314,7 @@ namespace SHADE Handle descPool; Handle graphicsCmdPool; Handle transferCmdBuffer; + Handle ssaoTransferCmdBuffer; Handle graphicsTexCmdBuffer; SHRenderContext renderContext; std::array, 2> graphSemaphores; @@ -357,6 +359,7 @@ namespace SHADE Handle mousePickSystem; Handle postOffscreenRender; Handle lightingSubSystem; + Handle ssaoStorage; uint32_t resizeWidth = 1; uint32_t resizeHeight = 1; diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.cpp index fb5ae824..f2894786 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.cpp @@ -1,7 +1,60 @@ #include "SHpch.h" #include "SHSSAO.h" +#include "Graphics/Devices/SHVkLogicalDevice.h" +#include "Graphics/Buffers/SHVkBuffer.h" +#include namespace SHADE { + void SHSSAO::Init(Handle logicalDevice, Handle cmdBuffer) noexcept + { + // create memory on CPU side + ssaoData = std::make_unique(); + + // Initialize a distribution to get values from 0 to 1 + std::uniform_real_distribution distrib{0.0f, 1.0f}; + + // generator for random number + std::default_random_engine generator; + + // generate samples + auto& samples = ssaoData->samples; + for (uint32_t i = 0; i < NUM_SAMPLES; ++i) + { + samples[i] = SHVec4 + { + distrib(generator) * 2.0f - 1.0f, // -1.0f - 1.0f + distrib(generator) * 2.0f - 1.0f, // -1.0f - 1.0f + distrib(generator), // 0.0f - 1.0f so that sample space is a hemisphere + 0.0f + }; + + // This makes sure that most points are closer to fragment's position + float scale = 1.0f / static_cast(NUM_SAMPLES); + scale = std::lerp(0.1f, 1.0f, scale * scale); + samples[i] *= scale; + } + + // generate rotation vector + auto& rotationVectors = ssaoData->rotatationVectors; + for (uint32_t i = 0; i < NUM_ROTATION_VECTORS; ++i) + { + samples[i] = SHVec4 + { + distrib(generator) * 2.0f - 1.0f, // -1.0f - 1.0f + distrib(generator) * 2.0f - 1.0f, // -1.0f - 1.0f + 0.0f, // we want to rotate about the z axis in tangent space + 0.0f + }; + } + + // Get aligned size for buffer + uint32_t alignedSize = logicalDevice->PadSSBOSize(sizeof (SamplesAndKernel)); + + // Create buffer + ssaoDataBuffer = logicalDevice->CreateBuffer(alignedSize, ssaoData.get(), alignedSize, vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferDst, VMA_MEMORY_USAGE_AUTO, {}); + + ssaoDataBuffer->TransferToDeviceResource(cmdBuffer); + } } diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.h b/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.h index 17df7200..32e8eb1a 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.h @@ -2,14 +2,36 @@ #include "Resource/SHHandle.h" #include "Graphics/SHVulkanIncludes.h" +#include "Math/Vector/SHVec4.h" namespace SHADE { + class SHVkBuffer; + class SHVkLogicalDevice; + class SHVkCommandBuffer; class SHSSAO { private: + static constexpr uint32_t NUM_SAMPLES = 64; + static constexpr uint32_t NUM_ROTATION_VECTORS = 16; + struct SamplesAndKernel + { + //! distances from a pixel we want to sample + std::array samples; + std::array rotatationVectors; + }; + + private: + //! Samples and kernel on CPU side + std::unique_ptr ssaoData; + + //! For passing SSAO samples and kernel to GPU + Handle ssaoDataBuffer; + + public: + void Init (Handle logicalDevice, Handle cmdBuffer) noexcept; }; } diff --git a/SHADE_Engine/src/Graphics/Queues/SHVkQueue.cpp b/SHADE_Engine/src/Graphics/Queues/SHVkQueue.cpp index 828f2974..dcb3ff6a 100644 --- a/SHADE_Engine/src/Graphics/Queues/SHVkQueue.cpp +++ b/SHADE_Engine/src/Graphics/Queues/SHVkQueue.cpp @@ -129,4 +129,9 @@ namespace SHADE return vkQueue; } + void SHVkQueue::WaitIdle(void) const noexcept + { + vkQueue.waitIdle(); + } + } \ No newline at end of file diff --git a/SHADE_Engine/src/Graphics/Queues/SHVkQueue.h b/SHADE_Engine/src/Graphics/Queues/SHVkQueue.h index a647cb72..f27f3b0b 100644 --- a/SHADE_Engine/src/Graphics/Queues/SHVkQueue.h +++ b/SHADE_Engine/src/Graphics/Queues/SHVkQueue.h @@ -50,6 +50,8 @@ namespace SHADE void SubmitCommandBuffer (std::initializer_list> cmdBuffers, std::initializer_list> signalSems = {}, std::initializer_list> waitSems = {}, vk::PipelineStageFlags waitDstStageMask = {}, Handle const& fence = {}) noexcept; vk::Result Present (Handle const& swapchain, std::initializer_list> waitSems, uint32_t frameIndex) noexcept; vk::Queue GetVkQueue() noexcept; + + void WaitIdle (void) const noexcept; }; } diff --git a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp index b5f6f7ab..60d76c49 100644 --- a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp +++ b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp @@ -164,4 +164,9 @@ namespace SHADE } } + void SHRenderGraphNodeCompute::ModifyWriteDescBufferComputeResource(uint32_t set, uint32_t binding, std::span> const& buffers, uint32_t offset, uint32_t range) noexcept + { + computeResource->descSet->ModifyWriteDescBuffer(set, binding, buffers, offset, range); + } + } diff --git a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.h b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.h index 1101e276..d61eda33 100644 --- a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.h +++ b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.h @@ -18,6 +18,7 @@ namespace SHADE class SHRenderGraphResource; class SHVkShaderModule; class SHVkCommandBuffer; + class SHVkBuffer; class SHRenderGraphNodeCompute @@ -37,8 +38,6 @@ namespace SHADE static constexpr uint32_t workGroupSizeX = 16; static constexpr uint32_t workGroupSizeY = 16; - using ExternalDescSetBindCommands = std::function, Handle)>; - //! To run the dispatch command Handle computePipeline; @@ -48,6 +47,7 @@ namespace SHADE //! Descriptor set group to hold the images for reading (STORAGE_IMAGE) std::array, SHGraphicsConstants::NUM_FRAME_BUFFERS> graphResourceDescSets; + //! Compute resources Handle computeResource; //! vector of resources needed by the subpass compute @@ -73,6 +73,8 @@ namespace SHADE void SetDynamicOffsets (std::span perFrameSizes) noexcept; + void ModifyWriteDescBufferComputeResource (uint32_t set, uint32_t binding, std::span> const& buffers, uint32_t offset, uint32_t range) noexcept; + friend class SHRenderGraph; friend class SHRenderGraphNode; }; From 2bd3b45ba0a105815aba0c589fc556d4ae66e21b Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Mon, 31 Oct 2022 20:49:28 +0800 Subject: [PATCH 08/27] SSAO sort of working --- Assets/Shaders/DeferredComposite_CS.glsl | 6 +- Assets/Shaders/DeferredComposite_CS.shshaderb | Bin 4665 -> 4801 bytes Assets/Shaders/SSAO_CS.glsl | 78 ++++++++++++++++-- Assets/Shaders/SSAO_CS.shshaderb | Bin 0 -> 6425 bytes Assets/Shaders/TestCube_VS.glsl | 5 +- Assets/Shaders/TestCube_VS.shshaderb | Bin 3525 -> 3689 bytes .../src/Graphics/Buffers/SHVkBuffer.cpp | 5 ++ .../src/Graphics/Buffers/SHVkBuffer.h | 3 +- .../GlobalData/SHGraphicsGlobalData.cpp | 2 +- .../MiddleEnd/Interface/SHGraphicsConstants.h | 1 + .../MiddleEnd/Interface/SHGraphicsSystem.cpp | 73 +++++++++++----- .../MiddleEnd/Interface/SHRenderer.cpp | 6 +- .../Graphics/MiddleEnd/Interface/SHRenderer.h | 5 +- .../MiddleEnd/PostProcessing/SHSSAO.cpp | 7 +- .../MiddleEnd/PostProcessing/SHSSAO.h | 4 + .../RenderGraph/SHRenderGraphNodeCompute.cpp | 6 ++ .../Graphics/Shaders/SHShaderReflected.cpp | 10 +++ 17 files changed, 174 insertions(+), 37 deletions(-) create mode 100644 Assets/Shaders/SSAO_CS.shshaderb diff --git a/Assets/Shaders/DeferredComposite_CS.glsl b/Assets/Shaders/DeferredComposite_CS.glsl index 5f586b9b..4607363b 100644 --- a/Assets/Shaders/DeferredComposite_CS.glsl +++ b/Assets/Shaders/DeferredComposite_CS.glsl @@ -21,7 +21,8 @@ layout(set = 4, binding = 0, rgba32f) uniform image2D positions; layout(set = 4, binding = 1, rgba32f) uniform image2D normals; layout(set = 4, binding = 2, rgba8) uniform image2D albedo; layout(set = 4, binding = 3, r32ui) uniform uimage2D lightLayerData; -layout(set = 4, binding = 4, rgba8) uniform image2D targetImage; +layout(set = 4, binding = 4, rgba32f) uniform image2D ssaoImage; +layout(set = 4, binding = 5, rgba8) uniform image2D targetImage; layout(set = 1, binding = 0) uniform LightCounts { @@ -78,6 +79,7 @@ void main() } // store result into result image - imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(fragColor, 1.0f)); + //imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(fragColor, 1.0f)); + imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(imageLoad(ssaoImage, globalThread).rgb, 1.0f)); } \ No newline at end of file diff --git a/Assets/Shaders/DeferredComposite_CS.shshaderb b/Assets/Shaders/DeferredComposite_CS.shshaderb index aaaa5207fc09134d01b8cdfec1bc483a63024116..d691c168b25040b5ef44acb3432711e65747ca18 100644 GIT binary patch delta 458 zcmYk2y-EX75Jo4P{V^+oh*?Qt5u;U7OHf2og;dd6ETV{&TI2z=u~4H?qbBQH$TqPN zd@#ZDExWJ-hna6??wz^!d-HcIa^@?RTG?p?W+e-4$v(fLy1VAtJ(b~baMimQoSzYU z=3AWXxJORULw3zgTQ-Q@g02_z2k|1*vU-d!_Q%PO-z*>Ra)HvCC~Klu@#9q8>`RBl zZ?FuxekU$Li_J7ff^Rs0huFJxN8fkVz{`Daj%EYH0VE2rKp*Rj_uslx}1*T4zr0v%9YKXJ-( NxA;3y{f}$f@DCT_Ft7js delta 321 zcmX|+y9&ZU5Jhh`F~Nu+qJb0^8Z9IumV$+)m9N^;zYq%>3*V0z|3gz*`b+kLcS7RA z;m+Kdo!NaiUUf%xiinS{JPXiZBai#TsT#V8Fd7*%)il^JfPpJDN8BV2sWp<;!{}rB z`p~CQqP-))sxP_C=u8SE%`c2K(t;U}mGROeNXGNHs8CNt?n}SaR&#)OMayWBWVBt diff --git a/Assets/Shaders/SSAO_CS.glsl b/Assets/Shaders/SSAO_CS.glsl index 3759c4b4..ac84cb81 100644 --- a/Assets/Shaders/SSAO_CS.glsl +++ b/Assets/Shaders/SSAO_CS.glsl @@ -1,7 +1,13 @@ #version 450 -uint const NUM_SAMPLES = 64; -uint const NUM_ROTATIONS = 16; +const uint NUM_SAMPLES = 64; +const uint NUM_ROTATIONS = 16; +const int ROTATION_KERNEL_W = 4; +const int ROTATION_KERNEL_H = 4; + +// can perhaps pass in as push constant. +const float RADIUS = 0.5f; +const float BIAS = 0.025f; layout(local_size_x = 16, local_size_y = 16) in; layout(set = 4, binding = 0, rgba32f) uniform image2D positions; @@ -12,13 +18,75 @@ layout(set = 4, binding = 2, rgba32f) uniform image2D outputImage; // SSAO data layout(std430, set = 5, binding = 0) buffer SSAOData { - vec3 samples[NUM_SAMPLES]; - vec3 rotations[NUM_ROTATIONS]; + vec4 samples[NUM_SAMPLES]; + vec4 rotations[NUM_ROTATIONS]; } ssaoData; +layout(set = 2, binding = 0) uniform CameraData +{ + vec4 position; + mat4 vpMat; + mat4 viewMat; + mat4 projMat; + +} cameraData; + +shared vec4 sharedRotations[NUM_ROTATIONS]; + void main() { + ivec2 size = imageSize (outputImage); + + // load rotations into shared memory + uint localThreadIndex = gl_LocalInvocationIndex; + if (localThreadIndex < NUM_ROTATIONS) + sharedRotations[localThreadIndex] = ssaoData.rotations[localThreadIndex]; + + barrier(); + + ivec2 globalThread = ivec2 (gl_GlobalInvocationID.xy); + + // load all the necessary variables + vec3 viewSpacePos = imageLoad (positions, globalThread).rgb; + vec3 viewSpaceNormal = normalize (imageLoad (normals, globalThread).rgb); + + // Get random vector + uint randomVecXIndex = globalThread.x % ROTATION_KERNEL_W; + uint randomVecYIndex = globalThread.y % ROTATION_KERNEL_H; + vec3 randomVec = (sharedRotations[randomVecYIndex * ROTATION_KERNEL_W + randomVecXIndex].rgb) * 2.0f - 1.0f; + + // Gram schmidt + vec3 tangent = normalize (randomVec - (viewSpaceNormal * dot(viewSpaceNormal, randomVec))); + vec3 bitangent = cross (tangent, viewSpaceNormal); + mat3 TBN = mat3 (tangent, bitangent, viewSpaceNormal); + + float occlusion = 0.0f; + for (int i = 0; i < NUM_SAMPLES; ++i) + { + // We want to get a position at an offset from the view space position. Offset scaled by radius. + vec3 samplePos = TBN * ssaoData.samples[i].rgb; + samplePos = viewSpacePos + samplePos * RADIUS; + + // Now we take that offset position and bring it to clip space + vec4 offsetPos = vec4 (samplePos, 1.0f); + offsetPos = cameraData.projMat * offsetPos; + + // then we do perspective division + offsetPos.xyz /= offsetPos.w; + + // and bring it from [-1, 1] to screen coordinates + offsetPos.xyz = ((offsetPos.xyz * 0.5f) + 0.5f); + offsetPos.xy *= vec2(size.xy); + + float sampleDepth = imageLoad (positions, ivec2 (offsetPos.xy)).z; + + float rangeCheck = smoothstep (0.0f, 1.0f, RADIUS / abs (viewSpacePos.z - sampleDepth)); + occlusion += (sampleDepth >= samplePos.z + BIAS ? 1.0f : 0.0f) * rangeCheck; + } + + occlusion = (occlusion / float(NUM_SAMPLES)); + // store result into result image - imageStore(outputImage, ivec2(gl_GlobalInvocationID.xy), vec4(fragColor, 1.0f)); + imageStore(outputImage, ivec2(gl_GlobalInvocationID.xy), vec4(occlusion.rrr, 0.0f)); } \ No newline at end of file diff --git a/Assets/Shaders/SSAO_CS.shshaderb b/Assets/Shaders/SSAO_CS.shshaderb new file mode 100644 index 0000000000000000000000000000000000000000..78fd5087a76621f421742ffd5f2b9fa21528e843 GIT binary patch literal 6425 zcmZ9P33Oa#6~`ZKlCD6Jttet!YAaF;$Rf5tleU;vLlbD(Tu7&rX)=(^#LP4-qO{T$ zq>4pxK}At&0Tso4M?}S~h%4?2?hEb;#dAEz-|x+L+jsJv^FR0A|6RWO-S@pW$)s6F zW%-&s>DVb*c0e{gJ1~2)MP-L%lVGx3J{LJ7>&Wfyp0z!T8_j{mr<{7Cp$BD?6}j)= zY)aOS-UdcW)tdZa;AAk1eECCiUAvVtnfyuU_p@0W9d!5fclY*o_nh5d9v$s(G_M@4 z^bc2SmHvV1Sf$*oj#rGET8OLG%EOxmiUI9J6noH~#vYC8Rb*%M*v?6_tiGu^x~aK( zq%>H8nUXyPZn$194X+y-tCR*-*9IzAwBo1c=NKIB@6o-wHjZdk>$O%$J7;?afsLWk zSY_b6dNcPm@_pvRuU*^KyRy_QS*rt9&ebT5j1E^Ca2+}4yvO!sxB6UQT%%NveD`wj zgTwU=(I_TWr{;5}$L`!!XmVxl@5q)Q$E%gg*N&FTmA-nTmDipvMH#I(s-8&FJvx#5 zV%OBiMoPo*ZCMw5EjK-1N7ju!R;mruM=q$8FWNtk-Xec-@a@_8MIPOnWn{Bd8?4lt z*zMUc_J(RO#!Sw};MOf)ll!-!*ULQh1`VU@-;S*2dV97L*_v(Zkk-5vuD)?&qte{Z z?SflT8mWwxTGRD8$hl%3>OM1hpU?Q{Ii+TS^X@t)*@*Lv7#*u$D(Bw2vCD;h-uhoZ4WMO-*0<3I@#W*V$a&e_^t_lZT$xT``Lwb z?eDQ|-~8<%VvIM&vlcl%W{GR%Ijdrxwt0OZ^5iDwdH!Oawt3#K$dija=VtHLaxOmi zc@u2U>C(R!>D>GbA4-;abE#oX^}~trSN`a>u9qBhmFAM%S~Ep2NFh zZ(KL@w*3Ce8Ef5RlFxf>U2VUy#z)<`=$*j)dAV%eBW<5k)H?=yKDIIP)_*3_ImlaI z+j}l&eP_H7cn;%_L+Z1p_9A4f_x=4WPBGEn3D{F9;CW9%cLqLN^ZiZ5mGkbe?Rz9= z{3%G|-BbH?r1OgW=cD@^?!Ow{e9sx@?LjZjw-4KX;yf1? z{PuDQV0G%(UaysHUN#$h6wThE-9D^kC8qMz%~T@imv%UovsJJ5~y zdAQ&0Nw@!FIMuFX%LmMRFSaw)@0_%ECocBA13UV@Gx@Bc-)C}n^7~vKK)2_(H|mdq z2lwnbBl>;}JIgjNUqoNtgT26eE}Zdcd}YkHcb9wbg=t6HqwlzXzj$74-$DOY30wb( z1>3vfZ+-Z+I}5h?-4kqouZ!{iP8aR+1bet(`)vJvj`*$U+X}XKZF|ACpPdEUXX)>A zG2h?EqU~>^_L-dDZ`DD-@6-^s{K1Jki|IKlZDW02hXcP!`kb3~_>MrAyN7AdMji#^ zd^S%I|1_lQztqzAR3PW`QI9%v(5(~pvy$D#Gd~Xf*tg>!$mamR zb8~?GY8&$;`^CP>N67bkBTfL;^KP9A{EqZ86~7^;B~ISu`+POA&g^+Wzx#N9w5{WO z&j3r4ZS0xAm<{x4-)8}1#xK%Mn3AF zjV>=-QGX^gcK;V7&N$(|ok)4->pgrSaGzDcUOJF30`fbE(LN_}eh;11EaaNRTeCaa zQS)4EYxaStc^z9Qcn6KuZympf`XaA^UaZr^HYWU=&^y7o>0Fnio8t=Z3UoR5 z3+~FqO)79#pswEL6nQP!49qjed5$6F)wdzXlfE5!9q@a2J<{*6@^S9h4agn9rT?`^ z{YvNVyZt&~jd-tbOk8~bUym&}7x>NBehsj;wbZR;-!}pKjM{HNw|0E<--x~d*snh0 zjz-=L^u_!4ro_p+oV#@Y0R7g8p1z4b@$7rxjCFZ-W8@;| zLG+1d{}!A%adu~jY4+hA$3eLubfihX}Kaq=$f)Y1&Thps>V#``|H_2lDD{QzA) z=J*i0T=e`y^d-RA+mr9xkAQsGKSnpt-)j9o0mjJtTP^ofU~g?ezwem*&w%$#|4jbw zl>0d__9QS4)&t|5>BC6pAqv`Mb6Q>2HzJ{0`(F!FJ%^ zg4%yd+(M-J`s9kgn>S#`{(nYykC^jc(B&QjvA>-0Gmw7;2PWIO{|%fB;{T4nCr;kw z^NIgE{(-JP_Wmcjd&f8BU+8jyxO@MG)8`8AKj?DS5AN~Ac}M$rUwsdr0OlL7-{({2 PES|%D^#6}4r-T0kYfO5x literal 0 HcmV?d00001 diff --git a/Assets/Shaders/TestCube_VS.glsl b/Assets/Shaders/TestCube_VS.glsl index 867b945f..0e055395 100644 --- a/Assets/Shaders/TestCube_VS.glsl +++ b/Assets/Shaders/TestCube_VS.glsl @@ -34,6 +34,7 @@ layout(set = 2, binding = 0) uniform CameraData vec4 position; mat4 vpMat; mat4 viewMat; + mat4 projMat; } cameraData; void main() @@ -51,8 +52,10 @@ void main() // uvs for texturing in fragment shader Out.uv = aUV; + mat3 transposeInv = mat3 (transpose(inverse(modelViewMat))); + // normals are also in view space - Out.normal.rgb = mat3(transpose(inverse(modelViewMat))) * aNormal.rgb; + Out.normal.rgb = transposeInv * aNormal.rgb; Out.normal.rgb = normalize (Out.normal.rgb); // clip space for rendering diff --git a/Assets/Shaders/TestCube_VS.shshaderb b/Assets/Shaders/TestCube_VS.shshaderb index b7e1294bb1b2fcbe7f31212c0662330feff59f48..fb2965a83900e01b2591230c1de83828ad72c658 100644 GIT binary patch delta 1479 zcmYk6%T7~K6o&Wd$j3fl1pa#lC6j5odwH8ZHZHpywa1x(D zJTr&Bfnn^(IC0<;I5KhI6F4&Q|4z>)?B>r}>tFxcd+oK`e#`zD9x|mPCS37Ye!v*V zq|ITovpZB7To(OG=zV@ybB?+uX-+GO3$3=d8T@uWt-Ge6u-h&-J1wtMool{PC}F}- zT%PyZTjhpg*VGl)8XLuGd$ro`R(H_35sy#K>(sk-uPJuG)PwJ_>@-!ees-!+Z{4nU zy5(l2+E<9D8C6bgHyZo7q*&T!CH3hA=i*;4&Z;Ndeo~oPWo(>R{Qe*p{EENzxxt9Q z`KalImFb&(&WSjz)lq|v{w#+Nmk@Bd)H>f@ z_*?1$&5{5|%#>FIrn#%0i0=#1%!G+aZOnKd2v>xxa6;e$IoXE-1uPCj2WRWnf@bEV z|40lf+C{Y{3ujf2<=fqPIJ^53`P6Ym>d?VW>huZOr-H5HI*fE9;_b*v#`qygf@NpM zTXElV#4($aV4Hd--)?^J$`$d{uxJV$oUMB<-_{MwUo?TAas8@XdlY5J;B46o`L^uf z3~EuGodG&HW^h)vA)FD83Cv(jc1wV_ag!Nb5b;4p2s{Ci68qnSmi!xn9sXd})Q=ec%uILU2+1`yeo delta 1294 zcmYk5OKVe66ot>tqls-Ih|nMjl7~g1;=mUbF<7*wK4=r$##c3sF~(?`#PllCNx**) z@7$jtNM@oV@o#kQ%%PKl-@3U+a>8Qoz4l&b@3SxYo%xlXH{X-SKjBazW{hKIP13v@ z%{Pvep&KSk9Xg*EBSu_(tvA@McTCjGn3u$@POaP=RGS00`GF7?-a81Tt|;pS z6}@)X-DvMOClxVY8Jgs7blUx!?LD{NZ8Xu6^Uj6SN%hu=@^igv_@`Hi^oN?@B#?HM zjC$zIP0W8zeZ|SzI%&j(r#SiIBA`S@_o=P~<6_lIHOFD$$Je7hCl)meP`UB9nSwK1 z#l09*T}5>XUsI}cmUtt`WwDFIY}q^n>XISWO0vGMZj+tn0#3O}K4MzafU18Pk{t?=CQYcW|FVmCU?j$0p%)eQ+;m-9LB7hxc|000k52n z?$P{Ka~EIthz~U0-`RzzxR95hE3A~6LYrC#y6qlV1J{^B+p7R=ZNwCc?*r9}Uq-7f zZh8la)Nl(=S)C$}-^7ZuRaN}+APq7=GiI?5fOMKsI@O7@x<~j{r|)BRkMX6`d(jn* z3Pmn+aS{6jSfQSiBi;^pyTGRbx9xpNq)t2|(ir*-%GeQV{sVVlRH36mYuFuNtLpf+ z-}D2Y!`qvsQ=K@gYfR~;ANV5B1rHn=6^hgY&tTi&G&lzIz&!Rf5O3o*_-DZ}4BB{h1@ diff --git a/SHADE_Engine/src/Graphics/Buffers/SHVkBuffer.cpp b/SHADE_Engine/src/Graphics/Buffers/SHVkBuffer.cpp index da4bc292..08481483 100644 --- a/SHADE_Engine/src/Graphics/Buffers/SHVkBuffer.cpp +++ b/SHADE_Engine/src/Graphics/Buffers/SHVkBuffer.cpp @@ -64,6 +64,11 @@ namespace SHADE return bufferUsageFlags; } + uint32_t SHVkBuffer::GetSizeStored(void) const noexcept + { + return sizeStored; + } + /***************************************************************************/ /*! diff --git a/SHADE_Engine/src/Graphics/Buffers/SHVkBuffer.h b/SHADE_Engine/src/Graphics/Buffers/SHVkBuffer.h index aeda7d18..eb24d161 100644 --- a/SHADE_Engine/src/Graphics/Buffers/SHVkBuffer.h +++ b/SHADE_Engine/src/Graphics/Buffers/SHVkBuffer.h @@ -102,8 +102,9 @@ namespace SHADE /*-----------------------------------------------------------------------*/ /* SETTERS AND GETTERS */ /*-----------------------------------------------------------------------*/ - vk::Buffer GetVkBuffer (void) const noexcept; + vk::Buffer GetVkBuffer (void) const noexcept; vk::BufferUsageFlags GetUsageBits(void) const noexcept; + uint32_t GetSizeStored (void) const noexcept; template T GetDataFromMappedPointer(uint32_t index) const noexcept diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/GlobalData/SHGraphicsGlobalData.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/GlobalData/SHGraphicsGlobalData.cpp index d5fb81bd..9717889d 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/GlobalData/SHGraphicsGlobalData.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/GlobalData/SHGraphicsGlobalData.cpp @@ -79,7 +79,7 @@ namespace SHADE SHVkDescriptorSetLayout::Binding cameraDataBinding { .Type = vk::DescriptorType::eUniformBufferDynamic, - .Stage = vk::ShaderStageFlagBits::eVertex, + .Stage = vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eCompute, .BindPoint = SHGraphicsConstants::DescriptorSetBindings::CAMERA_DATA, .DescriptorCount = 1, }; diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsConstants.h b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsConstants.h index 0257bf3b..0a67cd9f 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsConstants.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsConstants.h @@ -129,6 +129,7 @@ namespace SHADE */ /***************************************************************************/ static constexpr uint32_t BATCHED_PER_INST_DATA = 0; + }; struct VertexBufferBindings diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp index d062b4d6..2a59a5d1 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp @@ -37,6 +37,7 @@ of DigiPen Institute of Technology is prohibited. #include "Assets/Asset Types/SHTextureAsset.h" #include "Graphics/MiddleEnd/Interface/SHMousePickSystem.h" #include "Graphics/MiddleEnd/Lights/SHLightingSubSystem.h" +#include "Graphics/RenderGraph/SHRenderGraphNodeCompute.h" #include "Assets/SHAssetManager.h" namespace SHADE @@ -113,6 +114,7 @@ namespace SHADE SHAssetManager::CompileAsset("../../Assets/Shaders/TestCube_VS.glsl"); SHAssetManager::CompileAsset("../../Assets/Shaders/TestCube_FS.glsl"); SHAssetManager::CompileAsset("../../Assets/Shaders/DeferredComposite_CS.glsl"); + SHAssetManager::CompileAsset("../../Assets/Shaders/SSAO_CS.glsl"); shaderModuleLibrary.ImportAllShaderSource(device); shaderModuleLibrary.ReflectAllShaderModules(); @@ -154,57 +156,95 @@ namespace SHADE renderContextCmdPools[i] = renderContext.GetFrameData(i).cmdPoolHdls[0]; } + /*-----------------------------------------------------------------------*/ + /* SCENE RENDER GRAPH RESOURCES */ + /*-----------------------------------------------------------------------*/ // Initialize world render graph worldRenderGraph->Init(device, swapchain); worldRenderGraph->AddResource("Position", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second, vk::Format::eR32G32B32A32Sfloat); worldRenderGraph->AddResource("Normals", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second, vk::Format::eR32G32B32A32Sfloat); + //worldRenderGraph->AddResource("Tangents", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second, vk::Format::eR32G32B32A32Sfloat); worldRenderGraph->AddResource("Albedo", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second); worldRenderGraph->AddResource("Depth Buffer", { SH_ATT_DESC_TYPE_FLAGS::DEPTH_STENCIL }, windowDims.first, windowDims.second, vk::Format::eD32SfloatS8Uint); worldRenderGraph->AddResource("Entity ID", { SH_ATT_DESC_TYPE_FLAGS::COLOR }, windowDims.first, windowDims.second, vk::Format::eR32Uint, 1, vk::ImageUsageFlagBits::eTransferSrc); worldRenderGraph->AddResource("Light Layer Indices", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second, vk::Format::eR32Uint, 1, vk::ImageUsageFlagBits::eTransferSrc); worldRenderGraph->AddResource("Scene", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second); + worldRenderGraph->AddResource("SSAO", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second, vk::Format::eR32G32B32A32Sfloat); + /*-----------------------------------------------------------------------*/ + /* MAIN NODE */ + /*-----------------------------------------------------------------------*/ auto gBufferNode = worldRenderGraph->AddNode("G-Buffer", { "Position", "Entity ID", "Light Layer Indices", "Normals", + //"Tangents", "Albedo", "Depth Buffer", - "Scene" + "Scene", + "SSAO" }, {}); // no predecessors + /*-----------------------------------------------------------------------*/ + /* G-BUFFER SUBPASS INIT */ + /*-----------------------------------------------------------------------*/ auto gBufferSubpass = gBufferNode->AddSubpass("G-Buffer Write"); gBufferSubpass->AddColorOutput("Position"); gBufferSubpass->AddColorOutput("Entity ID"); gBufferSubpass->AddColorOutput("Light Layer Indices"); gBufferSubpass->AddColorOutput("Normals"); + //gBufferSubpass->AddColorOutput("Tangents"); gBufferSubpass->AddColorOutput("Albedo"); gBufferSubpass->AddDepthOutput("Depth Buffer", SH_ATT_DESC_TYPE_FLAGS::DEPTH_STENCIL); - //// kirsch - //auto kirschShader = shaderModuleLibrary.GetShaderModule("KirschCs.glsl"); - //gBufferNode->AddNodeCompute(kirschShader, { "Position", "Scene" }); + /*-----------------------------------------------------------------------*/ + /* SSAO PASS AND DATA INIT */ + /*-----------------------------------------------------------------------*/ + ssaoStorage = resourceManager.Create(); - //// copy - //auto pureCopyShader = shaderModuleLibrary.GetShaderModule("PureCopyCs.glsl"); - //gBufferNode->AddNodeCompute(pureCopyShader, { "Position", "Scene" }); + ssaoTransferCmdBuffer = graphicsCmdPool->RequestCommandBuffer(SH_CMD_BUFFER_TYPE::PRIMARY); + ssaoTransferCmdBuffer->BeginRecording(); - // deferred composite + ssaoStorage->Init(device, ssaoTransferCmdBuffer); + + ssaoTransferCmdBuffer->EndRecording(); + graphicsQueue->SubmitCommandBuffer({ ssaoTransferCmdBuffer }); + + graphicsQueue->WaitIdle(); + + auto ssaoShader = shaderModuleLibrary.GetBuiltInShaderModule("SSAO_CS"); + Handle ssaoPass = gBufferNode->AddNodeCompute(ssaoShader, {"Position", "Normals", "SSAO"}); + auto ssaoDataBuffer = ssaoStorage->GetBuffer(); + ssaoPass->ModifyWriteDescBufferComputeResource(SHGraphicsConstants::DescriptorSetIndex::RENDERGRAPH_NODE_COMPUTE_RESOURCE, SHSSAO::DESC_SET_BINDING, {&ssaoDataBuffer, 1}, 0, ssaoStorage->GetBuffer()->GetSizeStored()); + + + /*-----------------------------------------------------------------------*/ + /* DEFERRED COMPOSITE SUBPASS INIT */ + /*-----------------------------------------------------------------------*/ auto deferredCompositeShader = shaderModuleLibrary.GetBuiltInShaderModule("DeferredComposite_CS"); - gBufferNode->AddNodeCompute(deferredCompositeShader, { "Position", "Normals", "Albedo", "Light Layer Indices", "Scene" }); - + gBufferNode->AddNodeCompute(deferredCompositeShader, { "Position", "Normals", "Albedo", "Light Layer Indices", "SSAO", "Scene" }); + /*-----------------------------------------------------------------------*/ + /* DUMMY SUBPASS TO TRANSITION SCENE FOR PRESENT USAGE */ + /*-----------------------------------------------------------------------*/ + // Dummy to transition scene to be used for shader read auto dummyNode = worldRenderGraph->AddNode("Dummy Pass", { "Scene" }, {"G-Buffer"}); // no predecessors auto dummySubpass = dummyNode->AddSubpass("Dummy Subpass"); dummySubpass->AddInput("Scene"); - + /*-----------------------------------------------------------------------*/ + /* GENERATE RENDER GRAPH */ + /*-----------------------------------------------------------------------*/ // Generate world render graph worldRenderGraph->Generate(); + + /*-----------------------------------------------------------------------*/ + /* BIND RENDER GRAPH TO RENDERER */ + /*-----------------------------------------------------------------------*/ // Add world renderer to default viewport worldRenderer = worldViewport->AddRenderer(resourceManager, swapchain->GetNumImages(), renderContextCmdPools, descPool, SHGraphicsGlobalData::GetDescSetLayouts()[SHGraphicsConstants::DescriptorSetIndex::HIGH_FREQUENCY_GLOBALS], worldRenderGraph); worldRenderer->SetCamera(worldCamera); @@ -254,17 +294,6 @@ namespace SHADE lightingSubSystem = resourceManager.Create(); lightingSubSystem->Init(device, descPool); - ssaoStorage = resourceManager.Create(); - - ssaoTransferCmdBuffer = graphicsCmdPool->RequestCommandBuffer(SH_CMD_BUFFER_TYPE::PRIMARY); - ssaoTransferCmdBuffer->BeginRecording(); - - ssaoStorage->Init(device, ssaoTransferCmdBuffer); - - ssaoTransferCmdBuffer->EndRecording(); - graphicsQueue->SubmitCommandBuffer({ssaoTransferCmdBuffer}); - - graphicsQueue->WaitIdle(); } #ifdef SHEDITOR diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHRenderer.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHRenderer.cpp index 655451ec..d0deb30c 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHRenderer.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHRenderer.cpp @@ -88,7 +88,7 @@ namespace SHADE } } - void SHRenderer::UpdateDataAndBind(Handle cmdBuffer, uint32_t frameIndex, SHMatrix viewMatrix, SHMatrix projMatrix) noexcept + void SHRenderer::UpdateDataAndBind(Handle cmdBuffer, uint32_t frameIndex, SHMatrix const& viewMatrix, SHMatrix const& projMatrix) noexcept { SetViewProjectionMatrix(viewMatrix, projMatrix); @@ -98,17 +98,19 @@ namespace SHADE std::array dynamicOffsets{ frameIndex * cameraDataAlignedSize }; cmdBuffer->BindDescriptorSet(cameraDescriptorSet, SH_PIPELINE_TYPE::GRAPHICS, SHGraphicsConstants::DescriptorSetIndex::HIGH_FREQUENCY_GLOBALS, std::span{ dynamicOffsets.data(), 1 }); + cmdBuffer->BindDescriptorSet(cameraDescriptorSet, SH_PIPELINE_TYPE::COMPUTE, SHGraphicsConstants::DescriptorSetIndex::HIGH_FREQUENCY_GLOBALS, std::span{ dynamicOffsets.data(), 1 }); } void SHRenderer::UpdateCameraDataToBuffer(void) noexcept { } - void SHRenderer::SetViewProjectionMatrix(SHMatrix viewMatrix, SHMatrix projMatrix) noexcept + void SHRenderer::SetViewProjectionMatrix(SHMatrix const& viewMatrix, SHMatrix const& projMatrix) noexcept { //cpuCameraData.viewProjectionMatrix = camera->GetViewMatrix() * camera->GetProjectionMatrix(); cpuCameraData.viewProjectionMatrix = SHMatrix::Transpose(projMatrix * viewMatrix); cpuCameraData.viewMatrix = SHMatrix::Transpose(viewMatrix); + cpuCameraData.projectionMatrix = SHMatrix::Transpose(projMatrix); } Handle SHRenderer::GetRenderGraph(void) const noexcept diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHRenderer.h b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHRenderer.h index b7c6718c..140cf53b 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHRenderer.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHRenderer.h @@ -47,6 +47,7 @@ namespace SHADE SHVec4 cameraPosition; SHMatrix viewProjectionMatrix; SHMatrix viewMatrix; + SHMatrix projectionMatrix; }; /*---------------------------------------------------------------------------------*/ @@ -80,9 +81,9 @@ namespace SHADE /*-----------------------------------------------------------------------------*/ void Draw(uint32_t frameIndex, Handle descPool) noexcept; void UpdateDataAndBind(Handle cmdBuffer, uint32_t frameIndex) noexcept; - void UpdateDataAndBind(Handle cmdBuffer, uint32_t frameIndex, SHMatrix viewMatrix, SHMatrix projMatrix) noexcept; + void UpdateDataAndBind(Handle cmdBuffer, uint32_t frameIndex, SHMatrix const& viewMatrix, SHMatrix const& projMatrix) noexcept; void UpdateCameraDataToBuffer (void) noexcept; - void SetViewProjectionMatrix (SHMatrix viewMatrix, SHMatrix projMatrix) noexcept; + void SetViewProjectionMatrix (SHMatrix const& viewMatrix, SHMatrix const& projMatrix) noexcept; /*-----------------------------------------------------------------------------*/ /* Setters and Getters */ diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.cpp index f2894786..c6aa1978 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.cpp @@ -39,7 +39,7 @@ namespace SHADE auto& rotationVectors = ssaoData->rotatationVectors; for (uint32_t i = 0; i < NUM_ROTATION_VECTORS; ++i) { - samples[i] = SHVec4 + rotationVectors[i] = SHVec4 { distrib(generator) * 2.0f - 1.0f, // -1.0f - 1.0f distrib(generator) * 2.0f - 1.0f, // -1.0f - 1.0f @@ -57,4 +57,9 @@ namespace SHADE ssaoDataBuffer->TransferToDeviceResource(cmdBuffer); } + Handle SHSSAO::GetBuffer(void) const noexcept + { + return ssaoDataBuffer; + } + } diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.h b/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.h index 32e8eb1a..040b4695 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.h @@ -12,6 +12,9 @@ namespace SHADE class SHSSAO { + public: + static constexpr uint32_t DESC_SET_BINDING = 0; + private: static constexpr uint32_t NUM_SAMPLES = 64; static constexpr uint32_t NUM_ROTATION_VECTORS = 16; @@ -33,5 +36,6 @@ namespace SHADE public: void Init (Handle logicalDevice, Handle cmdBuffer) noexcept; + Handle GetBuffer (void) const noexcept; }; } diff --git a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp index 60d76c49..2c471c83 100644 --- a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp +++ b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp @@ -82,6 +82,11 @@ namespace SHADE // bind descriptor sets cmdBuffer->BindDescriptorSet(graphResourceDescSets[frameIndex], SH_PIPELINE_TYPE::COMPUTE, SHGraphicsConstants::DescriptorSetIndex::RENDERGRAPH_RESOURCE, {}); + if (computeResource) + { + cmdBuffer->BindDescriptorSet(computeResource->descSet, SH_PIPELINE_TYPE::COMPUTE, SHGraphicsConstants::DescriptorSetIndex::RENDERGRAPH_NODE_COMPUTE_RESOURCE, computeResource->dynamicOffsets[frameIndex]); + } + // dispatch compute cmdBuffer->ComputeDispatch(groupSizeX, groupSizeY, 1); @@ -167,6 +172,7 @@ namespace SHADE void SHRenderGraphNodeCompute::ModifyWriteDescBufferComputeResource(uint32_t set, uint32_t binding, std::span> const& buffers, uint32_t offset, uint32_t range) noexcept { computeResource->descSet->ModifyWriteDescBuffer(set, binding, buffers, offset, range); + computeResource->descSet->UpdateDescriptorSetBuffer(set, binding); } } diff --git a/SHADE_Engine/src/Graphics/Shaders/SHShaderReflected.cpp b/SHADE_Engine/src/Graphics/Shaders/SHShaderReflected.cpp index f28561c5..96fa77ab 100644 --- a/SHADE_Engine/src/Graphics/Shaders/SHShaderReflected.cpp +++ b/SHADE_Engine/src/Graphics/Shaders/SHShaderReflected.cpp @@ -142,6 +142,16 @@ namespace SHADE case SpvOp::SpvOpTypeRuntimeArray: recurseForInfo(&member, interfaceHdl, member.offset, biggestAlignment, parentVarName + std::string(member.name) + "."); break; + case SpvOp::SpvOpTypeArray: + interfaceHdl->AddVariable(parentVarName + std::string (member.name), + SHShaderBlockInterface::Variable + ( + parentOffset + member.offset, + SHShaderBlockInterface::Variable::Type::OTHER + ) + ); + biggestAlignment = std::max(biggestAlignment, member.size); + break; } } }; From 441207260b9cfd0b50c3cd87cb89bd9aae2cefe7 Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Mon, 31 Oct 2022 20:49:49 +0800 Subject: [PATCH 09/27] shmeta --- Assets/Shaders/SSAO_CS.shshaderb.shmeta | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Assets/Shaders/SSAO_CS.shshaderb.shmeta diff --git a/Assets/Shaders/SSAO_CS.shshaderb.shmeta b/Assets/Shaders/SSAO_CS.shshaderb.shmeta new file mode 100644 index 00000000..a5b5b739 --- /dev/null +++ b/Assets/Shaders/SSAO_CS.shshaderb.shmeta @@ -0,0 +1,3 @@ +Name: SSAO_CS +ID: 48941934 +Type: 2 From 53b9c8f746ad72b98d954d9f57ff41ffbcc7f62e Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Mon, 31 Oct 2022 23:28:46 +0800 Subject: [PATCH 10/27] SSAO WIP --- Assets/Shaders/SSAO_CS.glsl | 24 +++--- Assets/Shaders/SSAO_CS.shshaderb | Bin 6425 -> 6313 bytes .../MiddleEnd/Interface/SHGraphicsSystem.cpp | 7 +- .../MiddleEnd/PostProcessing/SHSSAO.cpp | 70 ++++++++++++++++-- .../MiddleEnd/PostProcessing/SHSSAO.h | 32 +++++--- .../RenderGraph/SHRenderGraphNodeCompute.cpp | 7 ++ .../RenderGraph/SHRenderGraphNodeCompute.h | 4 +- 7 files changed, 109 insertions(+), 35 deletions(-) diff --git a/Assets/Shaders/SSAO_CS.glsl b/Assets/Shaders/SSAO_CS.glsl index ac84cb81..9cc2de7b 100644 --- a/Assets/Shaders/SSAO_CS.glsl +++ b/Assets/Shaders/SSAO_CS.glsl @@ -19,10 +19,11 @@ layout(set = 4, binding = 2, rgba32f) uniform image2D outputImage; layout(std430, set = 5, binding = 0) buffer SSAOData { vec4 samples[NUM_SAMPLES]; - vec4 rotations[NUM_ROTATIONS]; } ssaoData; +layout (set = 5, binding = 1) uniform sampler2D noiseTexture; + layout(set = 2, binding = 0) uniform CameraData { vec4 position; @@ -32,33 +33,28 @@ layout(set = 2, binding = 0) uniform CameraData } cameraData; -shared vec4 sharedRotations[NUM_ROTATIONS]; void main() { ivec2 size = imageSize (outputImage); - // load rotations into shared memory - uint localThreadIndex = gl_LocalInvocationIndex; - if (localThreadIndex < NUM_ROTATIONS) - sharedRotations[localThreadIndex] = ssaoData.rotations[localThreadIndex]; - - barrier(); - ivec2 globalThread = ivec2 (gl_GlobalInvocationID.xy); // load all the necessary variables vec3 viewSpacePos = imageLoad (positions, globalThread).rgb; vec3 viewSpaceNormal = normalize (imageLoad (normals, globalThread).rgb); - // Get random vector - uint randomVecXIndex = globalThread.x % ROTATION_KERNEL_W; - uint randomVecYIndex = globalThread.y % ROTATION_KERNEL_H; - vec3 randomVec = (sharedRotations[randomVecYIndex * ROTATION_KERNEL_W + randomVecXIndex].rgb) * 2.0f - 1.0f; + ivec2 noiseDim = textureSize(noiseTexture, 0); + vec2 threadUV = globalThread / size; + vec2 noiseUV = vec2 (float(size.x)/float(noiseDim.x), float(size.y) / float(noiseDim.y)); + noiseUV *= threadUV; + vec3 randomVec = texture(noiseTexture, noiseUV).rgb * 2.0f - 1.0f; // Gram schmidt vec3 tangent = normalize (randomVec - (viewSpaceNormal * dot(viewSpaceNormal, randomVec))); vec3 bitangent = cross (tangent, viewSpaceNormal); + + // matrix for tangent to view mat3 TBN = mat3 (tangent, bitangent, viewSpaceNormal); float occlusion = 0.0f; @@ -85,7 +81,7 @@ void main() occlusion += (sampleDepth >= samplePos.z + BIAS ? 1.0f : 0.0f) * rangeCheck; } - occlusion = (occlusion / float(NUM_SAMPLES)); + occlusion = 1.0f - (occlusion / float(NUM_SAMPLES)); // store result into result image imageStore(outputImage, ivec2(gl_GlobalInvocationID.xy), vec4(occlusion.rrr, 0.0f)); diff --git a/Assets/Shaders/SSAO_CS.shshaderb b/Assets/Shaders/SSAO_CS.shshaderb index 78fd5087a76621f421742ffd5f2b9fa21528e843..9ba80c93e4334ef6e464462f7f9c384d0a450093 100644 GIT binary patch literal 6313 zcmZvf36zy(8OJ{cW@J-CQ89?MO)*qLQ#4s^ppY3^jh69p=Q3QKxp$g-K?O=k2{R)t zt!Q&XTWGbiz07P6Y@vOzY_n`%O*^M^`u)E9KA!K)={@H;&;R*9>-&E1_uZMc;VD_Z zMz_s5Cd)=;?=|3QR{n zQ(u35bE$vb)}czNw-q}!pTDoar!#l0tZlECOU-J%wsLu1t0S9=-d?R-wRW&nu5{NM zt-SVZ8ep*As2VJ3kJ-i8)%Br)Qa}8dYz}-aHyhaP*=f05ZB&+52Y`9*GlE-Jxw^S+ z=<&TQfN$m#uiwy$9h03Ou~63Q!X7Hsdg}ulDrK-eH=&!QT3@Bs%wyy?SA#KTbXJ91 zw{&&x-wCdlIqe1;0_)#}HpU+N(2df-V1GIUxf|iuu3gf#ywofK^V=ckYQ?tpdy{sf zRF61w55U#8Y-v=QtwWU?hFew|s0@`_ksVZ&bH!PUy@kVQ@9*}(OG?cG=Y8{e$wr(v zcyOqGg`9m3VwVej2)SeU)WfE9EP*tdn!~Zuy+OgJI7C+gIE7 zVFKd)&{h}YwT*Y__ihyZ+WOs_e(#0;_JUpXzY@L!@ts>iRGhzcT%9~eInTg)K8s>K z?U={>VQg3AuOMd_+j*QJVziBkzQbTSJ~WAI<+WiK^R&(DMxvJ7$UNsQ=4qREGZJ}n zk>@^#v90Ak529y}uw$S4AI0Z$Iu$vQEc0ej!P(UUM6k2VM}P09%lH{+%ohW$xOW$J&icuQO{D}bgJEmmb1pI(C$ypGtu^) zj6Ls9*!-CBHZW_E`ELX`lYVEuJz<~ObWUP8+43Rgy&c;g!-##g4}8u^c4`8|pFe}mn}8BF6H_nkFH z@wuMM7s7dsaXIUwFzsmfQe!;e$zs1FR zn?~5>g6(~(7Hsd6zr&I5ecn~Dt-r5e`|J-CZ1WF~u#YDD*__7&@NtOWn623MIX-b0 zaeAJWwy~b~$%x;RE+YMwoRT@(Px@}C7Z zM!rsu`RMZydFy!>wU-d@UAYi3e<5Pcj$F5R^Zia;l(@)Qgza3#oWhyGQFXBGA(U}N^C{MBGN<04e9Y4emJ7QAcD{+6qw{Y; ztl^z8R=;)1Xnm1)1-Mw}N^E1o-w(F#rDO_+qfE^&A9 z9QJ}=k+|#8{~<>EWr(${CAOAx-+(x0)P6PC+DquPAN?BSCd7I588-ucGomlvzgrR~ z@ABL|=UdV{^;)pKjPnfkq2;XSoqQcKwP4>0HYVPW*MsG5L-wSaZvdO8FKWs~%{PIq z5qILvU^!QCZvo2{@5x&e*SaUIZ_nG{%r{>DM#P>6(E9w=-idw(auB%#agN*3??mL| z?A`@7&$IC?-;Ed}A2sEyxdZ(k#P~yqHO8agi^xaK_koRx=kb29oZ^b-5%>55aMlR% zyMHS72N84iNB_IP)?SFjxqS$1tjn2=k&B!UgUwlnM9xRR<~WNv#>hp^N5SUYjYQ7J zz~=ZY%rQnT_Wg0NIkE3gfaMfd>^tt!C*h3o9>rOFD%o<%o^%$U1{<$GX8a7;e#Nu+ zEVi*OXEa7Ga_#|}Q#^~$VVe_YVT@el+zU3Rcov_>HYd*FUa*{JaSZxCWE|pe`h4^k z5*KInMQm&Occ%U?A##e#S>m_)%V7Q1h?%|u9=Z3g!Wrvw@5abQ&ey;r_x^P_b7Jqt z$T{Z(^burQvVA}9M~ZWQBXROB>(tU2d=soc{^tD_*n0ADr@jrAk8?Z>mW!Fc1D=X_ z_Ri${_FY6i?C*ii^S4_6_Yq^{{jHY!0pe_95dHDD)ephmGyN0!JKWeGA;zAKtU)#+ z#(Abk(fXtJkHPkid4B@lhZN`iDYpEcG~ds_at|Q)!0ko<9I=+ZLuuv*!SeQZj_COd zuyc4nocEW=gNS^@{0h7iiJrd(%NgrF^vU_Vwj1qlk=pzY^ly+|$ZmRQ|2AOW^u4pxK}At&0Tso4M?}S~h%4?2?hEb;#dAEz-|x+L+jsJv^FR0A|6RWO-S@pW$)s6F zW%-&s>DVb*c0e{gJ1~2)MP-L%lVGx3J{LJ7>&Wfyp0z!T8_j{mr<{7Cp$BD?6}j)= zY)aOS-UdcW)tdZa;AAk1eECCiUAvVtnfyuU_p@0W9d!5fclY*o_nh5d9v$s(G_M@4 z^bc2SmHvV1Sf$*oj#rGET8OLG%EOxmiUI9J6noH~#vYC8Rb*%M*v?6_tiGu^x~aK( zq%>H8nUXyPZn$194X+y-tCR*-*9IzAwBo1c=NKIB@6o-wHjZdk>$O%$J7;?afsLWk zSY_b6dNcPm@_pvRuU*^KyRy_QS*rt9&ebT5j1E^Ca2+}4yvO!sxB6UQT%%NveD`wj zgTwU=(I_TWr{;5}$L`!!XmVxl@5q)Q$E%gg*N&FTmA-nTmDipvMH#I(s-8&FJvx#5 zV%OBiMoPo*ZCMw5EjK-1N7ju!R;mruM=q$8FWNtk-Xec-@a@_8MIPOnWn{Bd8?4lt z*zMUc_J(RO#!Sw};MOf)ll!-!*ULQh1`VU@-;S*2dV97L*_v(Zkk-5vuD)?&qte{Z z?SflT8mWwxTGRD8$hl%3>OM1hpU?Q{Ii+TS^X@t)*@*Lv7#*u$D(Bw2vCD;h-uhoZ4WMO-*0<3I@#W*V$a&e_^t_lZT$xT``Lwb z?eDQ|-~8<%VvIM&vlcl%W{GR%Ijdrxwt0OZ^5iDwdH!Oawt3#K$dija=VtHLaxOmi zc@u2U>C(R!>D>GbA4-;abE#oX^}~trSN`a>u9qBhmFAM%S~Ep2NFh zZ(KL@w*3Ce8Ef5RlFxf>U2VUy#z)<`=$*j)dAV%eBW<5k)H?=yKDIIP)_*3_ImlaI z+j}l&eP_H7cn;%_L+Z1p_9A4f_x=4WPBGEn3D{F9;CW9%cLqLN^ZiZ5mGkbe?Rz9= z{3%G|-BbH?r1OgW=cD@^?!Ow{e9sx@?LjZjw-4KX;yf1? z{PuDQV0G%(UaysHUN#$h6wThE-9D^kC8qMz%~T@imv%UovsJJ5~y zdAQ&0Nw@!FIMuFX%LmMRFSaw)@0_%ECocBA13UV@Gx@Bc-)C}n^7~vKK)2_(H|mdq z2lwnbBl>;}JIgjNUqoNtgT26eE}Zdcd}YkHcb9wbg=t6HqwlzXzj$74-$DOY30wb( z1>3vfZ+-Z+I}5h?-4kqouZ!{iP8aR+1bet(`)vJvj`*$U+X}XKZF|ACpPdEUXX)>A zG2h?EqU~>^_L-dDZ`DD-@6-^s{K1Jki|IKlZDW02hXcP!`kb3~_>MrAyN7AdMji#^ zd^S%I|1_lQztqzAR3PW`QI9%v(5(~pvy$D#Gd~Xf*tg>!$mamR zb8~?GY8&$;`^CP>N67bkBTfL;^KP9A{EqZ86~7^;B~ISu`+POA&g^+Wzx#N9w5{WO z&j3r4ZS0xAm<{x4-)8}1#xK%Mn3AF zjV>=-QGX^gcK;V7&N$(|ok)4->pgrSaGzDcUOJF30`fbE(LN_}eh;11EaaNRTeCaa zQS)4EYxaStc^z9Qcn6KuZympf`XaA^UaZr^HYWU=&^y7o>0Fnio8t=Z3UoR5 z3+~FqO)79#pswEL6nQP!49qjed5$6F)wdzXlfE5!9q@a2J<{*6@^S9h4agn9rT?`^ z{YvNVyZt&~jd-tbOk8~bUym&}7x>NBehsj;wbZR;-!}pKjM{HNw|0E<--x~d*snh0 zjz-=L^u_!4ro_p+oV#@Y0R7g8p1z4b@$7rxjCFZ-W8@;| zLG+1d{}!A%adu~jY4+hA$3eLubfihX}Kaq=$f)Y1&Thps>V#``|H_2lDD{QzA) z=J*i0T=e`y^d-RA+mr9xkAQsGKSnpt-)j9o0mjJtTP^ofU~g?ezwem*&w%$#|4jbw zl>0d__9QS4)&t|5>BC6pAqv`Mb6Q>2HzJ{0`(F!FJ%^ zg4%yd+(M-J`s9kgn>S#`{(nYykC^jc(B&QjvA>-0Gmw7;2PWIO{|%fB;{T4nCr;kw z^NIgE{(-JP_Wmcjd&f8BU+8jyxO@MG)8`8AKj?DS5AN~Ac}M$rUwsdr0OlL7-{({2 PES|%D^#6}4r-T0kYfO5x diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp index 2a59a5d1..6a3bd916 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp @@ -215,10 +215,15 @@ namespace SHADE graphicsQueue->WaitIdle(); + ssaoStorage->PrepareRotationVectorsVkData(device); + auto ssaoShader = shaderModuleLibrary.GetBuiltInShaderModule("SSAO_CS"); Handle ssaoPass = gBufferNode->AddNodeCompute(ssaoShader, {"Position", "Normals", "SSAO"}); auto ssaoDataBuffer = ssaoStorage->GetBuffer(); - ssaoPass->ModifyWriteDescBufferComputeResource(SHGraphicsConstants::DescriptorSetIndex::RENDERGRAPH_NODE_COMPUTE_RESOURCE, SHSSAO::DESC_SET_BINDING, {&ssaoDataBuffer, 1}, 0, ssaoStorage->GetBuffer()->GetSizeStored()); + ssaoPass->ModifyWriteDescBufferComputeResource(SHGraphicsConstants::DescriptorSetIndex::RENDERGRAPH_NODE_COMPUTE_RESOURCE, SHSSAO::DESC_SET_BUFFER_BINDING, { &ssaoDataBuffer, 1 }, 0, ssaoStorage->GetBuffer()->GetSizeStored()); + + auto viewSamplerLayout = ssaoStorage->GetViewSamplerLayout(); + ssaoPass->ModifyWriteDescImageComputeResource(SHGraphicsConstants::DescriptorSetIndex::RENDERGRAPH_NODE_COMPUTE_RESOURCE, SHSSAO::DESC_SET_IMAGE_BINDING, {&viewSamplerLayout, 1}); /*-----------------------------------------------------------------------*/ diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.cpp index c6aa1978..b145902f 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.cpp @@ -2,15 +2,14 @@ #include "SHSSAO.h" #include "Graphics/Devices/SHVkLogicalDevice.h" #include "Graphics/Buffers/SHVkBuffer.h" +#include "Graphics/Images/SHVkImage.h" +#include "Graphics/Images/SHVkSampler.h" #include namespace SHADE { void SHSSAO::Init(Handle logicalDevice, Handle cmdBuffer) noexcept { - // create memory on CPU side - ssaoData = std::make_unique(); - // Initialize a distribution to get values from 0 to 1 std::uniform_real_distribution distrib{0.0f, 1.0f}; @@ -18,7 +17,6 @@ namespace SHADE std::default_random_engine generator; // generate samples - auto& samples = ssaoData->samples; for (uint32_t i = 0; i < NUM_SAMPLES; ++i) { samples[i] = SHVec4 @@ -36,7 +34,6 @@ namespace SHADE } // generate rotation vector - auto& rotationVectors = ssaoData->rotatationVectors; for (uint32_t i = 0; i < NUM_ROTATION_VECTORS; ++i) { rotationVectors[i] = SHVec4 @@ -48,15 +45,74 @@ namespace SHADE }; } + SHImageCreateParams imageDetails = + { + .imageType = vk::ImageType::e2D, + .width = NUM_ROTATION_VECTORS_W, + .height = NUM_ROTATION_VECTORS_H, + .depth = 1, + .levels = 1, + .arrayLayers = 1, + .imageFormat = vk::Format::eR32G32B32A32Sfloat, + .usageFlags = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferDst, + .createFlags = {} + }; + + uint32_t mipOffset = 0; + rotationVectorsImage = logicalDevice->CreateImage(imageDetails, reinterpret_cast( rotationVectors.data()), static_cast(sizeof(rotationVectors)), {&mipOffset, 1}, VMA_MEMORY_USAGE_AUTO, {}); + + vk::ImageMemoryBarrier transferBarrier{}; + rotationVectorsImage->PrepareImageTransitionInfo(vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal, transferBarrier); + + cmdBuffer->PipelineBarrier(vk::PipelineStageFlagBits::eTopOfPipe, vk::PipelineStageFlagBits::eTransfer, {}, {}, {}, {transferBarrier}); + + rotationVectorsImage->TransferToDeviceResource(cmdBuffer); + + vk::ImageMemoryBarrier shaderReadBarrier{}; + rotationVectorsImage->PrepareImageTransitionInfo(vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eShaderReadOnlyOptimal, shaderReadBarrier); + cmdBuffer->PipelineBarrier(vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eComputeShader, {}, {}, {}, { shaderReadBarrier }); + + // Get aligned size for buffer - uint32_t alignedSize = logicalDevice->PadSSBOSize(sizeof (SamplesAndKernel)); + uint32_t alignedSize = logicalDevice->PadSSBOSize(sizeof (samples)); // Create buffer - ssaoDataBuffer = logicalDevice->CreateBuffer(alignedSize, ssaoData.get(), alignedSize, vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferDst, VMA_MEMORY_USAGE_AUTO, {}); + ssaoDataBuffer = logicalDevice->CreateBuffer(alignedSize, samples.data(), alignedSize, vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferDst, VMA_MEMORY_USAGE_AUTO, {}); ssaoDataBuffer->TransferToDeviceResource(cmdBuffer); } + void SHSSAO::PrepareRotationVectorsVkData(Handle logicalDevice) noexcept + { + SHImageViewDetails DETAILS = + { + .viewType = vk::ImageViewType::e2D, + .format = vk::Format::eR32G32B32A32Sfloat, + .imageAspectFlags = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .mipLevelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1 + }; + rotationVectorsImageView = rotationVectorsImage->CreateImageView(logicalDevice, rotationVectorsImage, DETAILS); + + SHVkSamplerParams samplerParams + { + .minFilter = vk::Filter::eNearest, + .magFilter = vk::Filter::eNearest, + .addressMode = vk::SamplerAddressMode::eRepeat, + .mipmapMode = vk::SamplerMipmapMode::eNearest, + .maxLod = 1u + }; + + rotationVectorsSampler = logicalDevice->CreateSampler(samplerParams); + } + + SHVkDescriptorSetGroup::viewSamplerLayout SHSSAO::GetViewSamplerLayout(void) const noexcept + { + return std::make_tuple(rotationVectorsImageView, rotationVectorsSampler, vk::ImageLayout::eShaderReadOnlyOptimal); + } + Handle SHSSAO::GetBuffer(void) const noexcept { return ssaoDataBuffer; diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.h b/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.h index 040b4695..c7c133c5 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.h @@ -3,39 +3,47 @@ #include "Resource/SHHandle.h" #include "Graphics/SHVulkanIncludes.h" #include "Math/Vector/SHVec4.h" +#include "Graphics/Descriptors/SHVkDescriptorSetGroup.h" namespace SHADE { class SHVkBuffer; class SHVkLogicalDevice; class SHVkCommandBuffer; + class SHVkImage; + class SHVkImageView; + class SHVkSampler; class SHSSAO { public: - static constexpr uint32_t DESC_SET_BINDING = 0; + static constexpr uint32_t DESC_SET_BUFFER_BINDING = 0; + static constexpr uint32_t DESC_SET_IMAGE_BINDING = 1; private: static constexpr uint32_t NUM_SAMPLES = 64; - static constexpr uint32_t NUM_ROTATION_VECTORS = 16; - - struct SamplesAndKernel - { - //! distances from a pixel we want to sample - std::array samples; - - std::array rotatationVectors; - }; + static constexpr uint32_t NUM_ROTATION_VECTORS_W = 4; + static constexpr uint32_t NUM_ROTATION_VECTORS_H = 4; + static constexpr uint32_t NUM_ROTATION_VECTORS = NUM_ROTATION_VECTORS_W * NUM_ROTATION_VECTORS_H; private: - //! Samples and kernel on CPU side - std::unique_ptr ssaoData; + //! distances from a pixel we want to sample + std::array samples; //! For passing SSAO samples and kernel to GPU Handle ssaoDataBuffer; + std::array rotationVectors; + + Handle rotationVectorsImage; + Handle rotationVectorsImageView; + Handle rotationVectorsSampler; + public: void Init (Handle logicalDevice, Handle cmdBuffer) noexcept; + void PrepareRotationVectorsVkData (Handle logicalDevice) noexcept; + SHVkDescriptorSetGroup::viewSamplerLayout GetViewSamplerLayout (void) const noexcept; + Handle GetBuffer (void) const noexcept; }; } diff --git a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp index 2c471c83..a86acbc7 100644 --- a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp +++ b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.cpp @@ -175,4 +175,11 @@ namespace SHADE computeResource->descSet->UpdateDescriptorSetBuffer(set, binding); } + void SHRenderGraphNodeCompute::ModifyWriteDescImageComputeResource(uint32_t set, uint32_t binding, std::span const& viewSamplerLayouts) noexcept + { + computeResource->descSet->ModifyWriteDescImage(set, binding, viewSamplerLayouts); + computeResource->descSet->UpdateDescriptorSetImages(set, binding); + + } + } diff --git a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.h b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.h index d61eda33..81157dc2 100644 --- a/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.h +++ b/SHADE_Engine/src/Graphics/RenderGraph/SHRenderGraphNodeCompute.h @@ -2,6 +2,7 @@ #include "Resource/SHHandle.h" #include "Graphics/MiddleEnd/Interface/SHGraphicsConstants.h" +#include "Graphics/Descriptors/SHVkDescriptorSetGroup.h" #include "Graphics/SHVulkanIncludes.h" #include #include @@ -10,7 +11,6 @@ namespace SHADE { class SHVkPipeline; - class SHVkDescriptorSetGroup; class SHVkDescriptorPool; class SHVkLogicalDevice; class SHVkPipelineLayout; @@ -74,6 +74,8 @@ namespace SHADE void SetDynamicOffsets (std::span perFrameSizes) noexcept; void ModifyWriteDescBufferComputeResource (uint32_t set, uint32_t binding, std::span> const& buffers, uint32_t offset, uint32_t range) noexcept; + void ModifyWriteDescImageComputeResource(uint32_t set, uint32_t binding, std::span const& viewSamplerLayouts) noexcept; + friend class SHRenderGraph; friend class SHRenderGraphNode; From 54a36e147600c5847f66af73768cf2e9ae85abaa Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Tue, 1 Nov 2022 02:32:14 +0800 Subject: [PATCH 11/27] SSAO WIP --- Assets/Shaders/DeferredComposite_CS.glsl | 3 ++- Assets/Shaders/DeferredComposite_CS.shshaderb | Bin 4801 -> 4817 bytes Assets/Shaders/SSAO_CS.glsl | 16 +++++++++------- Assets/Shaders/SSAO_CS.shshaderb | Bin 6313 -> 6433 bytes 4 files changed, 11 insertions(+), 8 deletions(-) diff --git a/Assets/Shaders/DeferredComposite_CS.glsl b/Assets/Shaders/DeferredComposite_CS.glsl index 4607363b..0d29d8e4 100644 --- a/Assets/Shaders/DeferredComposite_CS.glsl +++ b/Assets/Shaders/DeferredComposite_CS.glsl @@ -55,7 +55,7 @@ void main() vec3 positionView = imageLoad (positions, globalThread).rgb; // normal of fragment - vec3 normalView = imageLoad(normals, globalThread).rgb; + vec3 normalView = -imageLoad(normals, globalThread).rgb; vec3 fragColor = vec3 (0.0f); @@ -79,6 +79,7 @@ void main() } // store result into result image + //imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(normalView, 1.0f)); //imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(fragColor, 1.0f)); imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(imageLoad(ssaoImage, globalThread).rgb, 1.0f)); diff --git a/Assets/Shaders/DeferredComposite_CS.shshaderb b/Assets/Shaders/DeferredComposite_CS.shshaderb index d691c168b25040b5ef44acb3432711e65747ca18..cdf5baea792c275a0cb6a28f6bcb400ef788782f 100644 GIT binary patch literal 4817 zcmZve`EwLi5XXmXPVO62zzukSAc6!$ks}aTA`1zEc)Lz^C!3MU?z#t;C_zP3JW%oe zC;S`y$-l@_tE}?-nR&guO8KZxcYnKIcfWr9X6gB3Wst61&z6B8SP(1>mIS|MP_QEC z5fTK8g8q~jisy3`<1Ig@dg~WpuIx+L=@I zAoyKMud)`3rNYESp?JJhZZt}*_SGaRC2=h(RpMq;ZpW7*{02S0xK>U&72lyx9)A8l zWyb>$UN*)ZQPg6K}*do0O$vla-t&6qNeNRcB zZidxk^`zcR_vL~;;&CeX1<#8YuYc^J=Z$(? zYdeeK+(D~RH(1^SsXsRx&Q8TqcSm-vL&6g;f1mv6StX5oCOutzE$a69xNKwD6?W@7 z*KT&o?W{KJtZwa+sSTW(NNaL$f=-CA=Lrt5JJ= zHmpYJoZb=EYK8R-$=<>*!V+eq7+#HK;W3y`UsSk{O_%pM9edyFje)cmjEZc9G)n~Qf zXZ5X?Y<^bXdST?_8%2G25k59s7N7dStUhMUuMeI2Y!;X`?7oh@PeeZE&bOoc`+tyH-xk*6d%#XCe^DzvBtN}i;Y)sW z-XMz{8^wu%KQV`${(mvSh)GXb_!1L+3xJmCyi3-0*@@2#vv%mToNKoT%!s&8OSgWr zkG_nESevBr7U``|>^mroGh-(|I&TvU`(Y=uZ?({);>6=^Qj5i-7aP^>6XMu5NiK+^ z6X&EjF~P`#&Kt8lr<_bo{3paY59hb@T##({`Lbm8lGp5I$qPi($2-Kv{`)oN(szfA z`gmWwL-Mu7i3dh~=pBb)zwTt>VP_V2b1Y`zwm5l+fqk?19TCg!@ouWk9Y)9Zd(m=d zNB==Y{oFG%&zr;t!p4mKB#tkB{vz+Nh+2Pk27IXno%hSyr!NA&%q)w3{w0L(1irk{ zArZYt=iRKEr|0MCTj%NgU(EJ1mwP;&cw?T1s28URF{JeDR7XJy!+ni4Q+eLo- z9n$duxA;#=28UP{|AuPjd^<(>a31a%9hp1c?PTtEMD({#zE_-ig8!))&xr3Av9LcY zjvY?j+~0E|VsO9A_5p{Ds_%S%j)?dsk%K+>jEatkev{8p@na(Pf&U{P^nD`olMmVQ zy&#!U#uFy&WnhP-!2h8#O7^av)W&hY_-2E`4y4Xj_ra7U*`2y5q7)l*Bl1UA|JDg zKQ+8ABHyGt>l+ROhi<8U&iAH>SlI21Z%Jm}&8H+8KXCJTTQYNV)5QrTgW+p41;(5( zGu#`T{mjXfh_laWKYGPsWpVan1M}yQ`^UyNWyIO0#fc4PMrXuh5sSU=h+~Ia?u(L% zVKbUY2D2HRmCTG<{})QGiNI|}>yp_A&Wxg0MdT+Rvh}JVnSNUSOOnaY%yRFSMI8}m z!Uo5ed%q&WZufrGVc;ygce|@=!pMi8<$F)E<-0EVeUatEM$hqOZaxrUx4F6DFmTB7 z%t zmeUuBe=1rcnoyr_i+|=Ya2CB|2Kc^yF2YW%Vev0Scbty>OVN6IiZCviP0SL0?>N#lzVe!ZSwT(2Z^Ro|gY9)A8V z@i>#af&=1Xacw#sZp_uwmMZAYFu{RqRihpznG1Ql^^ZODe6|tS zQ)e-pJ7~=|43>9K=FiQBGm~-D-jSc{pzy@Y-zEQHVbv_|sqA#|)u`QP`Z+cU=CxsGwQHA5ZQ#@#w}#y9-^Z!BGM8vPYA3_ig{)@$skxe8m$gql?G26zUs%IP zn1+J0T-aIp8FCAEdt8|IWhXO#@Nsuait+0_J`CIr|Si)?Kg;%0xp0T7E=R2@O^soq>H?&#Q>FEQKIUn{xao>)P zorRq@!VacuCzQp4GFs)`|xLG{rb?UkNoUsURbu@FssjM z!O!YjBia0{z74|2_ntWQ6-D^iY*~Ej1GD;=F~2@^>a$sxcXnUL&Tk9(m^=2H9o^sm zgLG!?0TKSpr0px z>DF)d(U;vK)+TAZMSANK`(6;nnX!`}owo^w{g9K{w?^oYIPpfrsm0>ai;e0w?+)80 z$;ZUeiBl3MCK!3pd1IF6gp-Mh|0!|K!};wz=Oo*Go|nvC@|t~8@*)xS@eb{N?$=nz z-W@jT<9+cC$;WR#@xZ7LJ#`rNYfh#f?99Tvh{Y`27AFreux}Q>BVyS--p#Zdhtcu9 zCtBg`=--Q|pL=HJd6W1+*qE^&#qq_@U*sJSQR`36fG@S6^L|KZWp} zz?V1LC!+W0yc_;c=j+7<`j!Pc{}(fV=5m*(6K~klx#w|D$G__IgUU}ImWz1z*QNK1 z(=)Kss+u`p=`gW2w#s4jX+nO~vs#2NwnI8O=L91UZ~P$W2U<3H|vz%Bk0lEERCAHOIayTyM}@>Zu) z|2B~yf4g*iz%Bk$lEERCAD?^0&RMwAolfRHcZ>egN%x2|Kkz?v&VAy~idfk9i(`jV zC-?Q7h#1@_v;4fnhSX=iH-|+BMdV-)K1W30zshGw{6!J_j)?x25Bgpa`N@ZD`9>v^ zZ%DU#Li{BW-yY&)vpn4AmL6L{IpRVWSt!FF5h>nGk`Qep)iUyQf;$h`%ht z2Yjh&06QZhE`EH+@gX*E0h`r+Rl+ROhi<8U&iAH>SlI21Z%Jmp&F5{&_<@^GSu%5T)5Up5G8n!#Q((*qGsC^X z+0UGWBF=t8`_U^7n-ph1HZXq8zO%uZaNHKn+Y)Pg*&28aI5np$<%2x@v&qun+a@S{=L(0_HPisC7O5o67f$& z%S7Yq^KJ1@9R|*#cg#SK_-7*Q#2OI)Ty)3j*uN0+*YrV>7xP}qAWBj! zBDE-3$ErmUq&R@Hq9WovTPJWvaTdi90Y&}3_s(|RmE~FMU;E$x*?XUT&OP_Oq-oY; zvica`wCJcT8<$Pare*(WNZItP2_>uBQ?XOBmb%}*ZsWS8)mqQe<)@uu=+W7DO?~bd zVw&L-K!2e;pgsc}i>@}k&h;DdD;-^D@`SiOB+cY9}N`?_dO$RnRuA+EA}C3a=D7@hY2wJHH2Oo_+7fRtx=ued!?7UX8YKV_WB%LahL; z-w-uNBet>U>-4LIO2nCa2(7YnXSGyo9IV<+XsZkTrJ+J2vW1FjjyP|*H&NX?ynAqc zp_bFUb3QZGi1QW?4plBtbDf*3#HxuC$edi)tvRV)Ti@LLFjvj|scFJKRwUp1<#2t!sq=Lhu74a>%^uA^9&0Ui z^Yy)dYR1pR8tc zewQjT)U2oP{dO$I_iUHdy~g^>;nt7yJ`HZa>c%^FCSa^w!fjDM3#bWW+JI0`y(r7QLi8F`Nf&~?Xy0GeUSqwh;jLf>JKKky zL!9ri=k45Fs(H`VtZ^;YGf?x~^nGvRTn;2|e)M<{&MGU-e=E$MoVVv26Zg5!kStIs(Ynl)L_7oF+-iJT=?i*G_z5DU=&*B06 zEE`!B`TxQ@7DW7`aQCreif$U6ZuP@x1K46-3T6;p&mo4p*}eYpey< zQI9&$g1dGHh&s=Pt4E!6aJ9%;4|nZ+&IWw-$mxWu#oAqP>!^37b2$%gPtJKRzT;~4 z;aNWicvj(Wgd4LrP=uPhi9XGkr4{dhB6?I0LUHQxd^&$+0n7B#PjTO;no z+u&-B(B2Ne9^~)I4N0^AuJrAB2i$z)o!V2#Px_W|{&`F^-D@jN~NR}+qS9&wL9h-Qs|-+iCM zhk&`x$NC?JTe}s+xqSp~tizs-QHz|9!p-Rbk@GRQIrd_XF=~#*S$rC9{GA|rybJDntsr{*4BS|U zJsP7HIiH1_lRt~k;hSTB<`|kOnb_%7V}_#66raOQ+A!PQ;gK4Q&Z!|lWS zVZXlt#;QlmZ{eeLG-7@SS2NaqIH%_C+Lc&;i?rsqV1EzxfDzWv|3lL5$C~e)TK;!) zFMh25N4RUmIsXZ+_5g_I^k=wxb1r&Pvxax?FJM~okHh{I%mDGf-rtg@?idH+f4#rM zosWJVgxgPiXZ`_K3&eeV2+cW1Xb;2HtRLDVNo&H!@6tcv<{R(4&#cH^+=u-*|0q?? G0RIKoSZT`u literal 6313 zcmZvf36zy(8OJ{cW@J-CQ89?MO)*qLQ#4s^ppY3^jh69p=Q3QKxp$g-K?O=k2{R)t zt!Q&XTWGbiz07P6Y@vOzY_n`%O*^M^`u)E9KA!K)={@H;&;R*9>-&E1_uZMc;VD_Z zMz_s5Cd)=;?=|3QR{n zQ(u35bE$vb)}czNw-q}!pTDoar!#l0tZlECOU-J%wsLu1t0S9=-d?R-wRW&nu5{NM zt-SVZ8ep*As2VJ3kJ-i8)%Br)Qa}8dYz}-aHyhaP*=f05ZB&+52Y`9*GlE-Jxw^S+ z=<&TQfN$m#uiwy$9h03Ou~63Q!X7Hsdg}ulDrK-eH=&!QT3@Bs%wyy?SA#KTbXJ91 zw{&&x-wCdlIqe1;0_)#}HpU+N(2df-V1GIUxf|iuu3gf#ywofK^V=ckYQ?tpdy{sf zRF61w55U#8Y-v=QtwWU?hFew|s0@`_ksVZ&bH!PUy@kVQ@9*}(OG?cG=Y8{e$wr(v zcyOqGg`9m3VwVej2)SeU)WfE9EP*tdn!~Zuy+OgJI7C+gIE7 zVFKd)&{h}YwT*Y__ihyZ+WOs_e(#0;_JUpXzY@L!@ts>iRGhzcT%9~eInTg)K8s>K z?U={>VQg3AuOMd_+j*QJVziBkzQbTSJ~WAI<+WiK^R&(DMxvJ7$UNsQ=4qREGZJ}n zk>@^#v90Ak529y}uw$S4AI0Z$Iu$vQEc0ej!P(UUM6k2VM}P09%lH{+%ohW$xOW$J&icuQO{D}bgJEmmb1pI(C$ypGtu^) zj6Ls9*!-CBHZW_E`ELX`lYVEuJz<~ObWUP8+43Rgy&c;g!-##g4}8u^c4`8|pFe}mn}8BF6H_nkFH z@wuMM7s7dsaXIUwFzsmfQe!;e$zs1FR zn?~5>g6(~(7Hsd6zr&I5ecn~Dt-r5e`|J-CZ1WF~u#YDD*__7&@NtOWn623MIX-b0 zaeAJWwy~b~$%x;RE+YMwoRT@(Px@}C7Z zM!rsu`RMZydFy!>wU-d@UAYi3e<5Pcj$F5R^Zia;l(@)Qgza3#oWhyGQFXBGA(U}N^C{MBGN<04e9Y4emJ7QAcD{+6qw{Y; ztl^z8R=;)1Xnm1)1-Mw}N^E1o-w(F#rDO_+qfE^&A9 z9QJ}=k+|#8{~<>EWr(${CAOAx-+(x0)P6PC+DquPAN?BSCd7I588-ucGomlvzgrR~ z@ABL|=UdV{^;)pKjPnfkq2;XSoqQcKwP4>0HYVPW*MsG5L-wSaZvdO8FKWs~%{PIq z5qILvU^!QCZvo2{@5x&e*SaUIZ_nG{%r{>DM#P>6(E9w=-idw(auB%#agN*3??mL| z?A`@7&$IC?-;Ed}A2sEyxdZ(k#P~yqHO8agi^xaK_koRx=kb29oZ^b-5%>55aMlR% zyMHS72N84iNB_IP)?SFjxqS$1tjn2=k&B!UgUwlnM9xRR<~WNv#>hp^N5SUYjYQ7J zz~=ZY%rQnT_Wg0NIkE3gfaMfd>^tt!C*h3o9>rOFD%o<%o^%$U1{<$GX8a7;e#Nu+ zEVi*OXEa7Ga_#|}Q#^~$VVe_YVT@el+zU3Rcov_>HYd*FUa*{JaSZxCWE|pe`h4^k z5*KInMQm&Occ%U?A##e#S>m_)%V7Q1h?%|u9=Z3g!Wrvw@5abQ&ey;r_x^P_b7Jqt z$T{Z(^burQvVA}9M~ZWQBXROB>(tU2d=soc{^tD_*n0ADr@jrAk8?Z>mW!Fc1D=X_ z_Ri${_FY6i?C*ii^S4_6_Yq^{{jHY!0pe_95dHDD)ephmGyN0!JKWeGA;zAKtU)#+ z#(Abk(fXtJkHPkid4B@lhZN`iDYpEcG~ds_at|Q)!0ko<9I=+ZLuuv*!SeQZj_COd zuyc4nocEW=gNS^@{0h7iiJrd(%NgrF^vU_Vwj1qlk=pzY^ly+|$ZmRQ|2AOW^u Date: Tue, 1 Nov 2022 11:57:08 +0800 Subject: [PATCH 12/27] SSAO WIP --- Assets/Shaders/DeferredComposite_CS.glsl | 2 +- Assets/Shaders/DeferredComposite_CS.shshaderb | Bin 4817 -> 4789 bytes Assets/Shaders/SSAO_CS.glsl | 18 +++++++++--------- Assets/Shaders/SSAO_CS.shshaderb | Bin 6433 -> 6189 bytes .../MiddleEnd/PostProcessing/SHSSAO.cpp | 17 +++++++++++++++++ 5 files changed, 27 insertions(+), 10 deletions(-) diff --git a/Assets/Shaders/DeferredComposite_CS.glsl b/Assets/Shaders/DeferredComposite_CS.glsl index 0d29d8e4..da13b1b4 100644 --- a/Assets/Shaders/DeferredComposite_CS.glsl +++ b/Assets/Shaders/DeferredComposite_CS.glsl @@ -81,6 +81,6 @@ void main() // store result into result image //imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(normalView, 1.0f)); //imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(fragColor, 1.0f)); - imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(imageLoad(ssaoImage, globalThread).rgb, 1.0f)); + imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(imageLoad(ssaoImage, globalThread).rgba/*, 1.0f*/)); } \ No newline at end of file diff --git a/Assets/Shaders/DeferredComposite_CS.shshaderb b/Assets/Shaders/DeferredComposite_CS.shshaderb index cdf5baea792c275a0cb6a28f6bcb400ef788782f..525f3c4ced3b824db7ef716d0d4f39927b2b018e 100644 GIT binary patch delta 300 zcmYj~u@1pt6ot?Kx7DafL}=2%K+}mGF&J&aGk6P&L1Hi{imGR@(0CB9VwX6#X%jd3 za{qJgz2|=iufWy!IMzQvPI n3h$76`p-M&p20qYjTU=EBvUfvMs^nbdc(dYGXFwZ7%=_^8D=Al delta 328 zcmXw!yAA=)44pM4@oMuFf0C#ye=eieBQJjh*Dn z%$b@0Wd3LEUGvOW4q;ek)d38+NaObKnzrEweS2<}&m5;nk#u3hXRZ)C(!nR*v3hyR z4FP7II)^T+Bgv3RpI95Dfp};sYwZZlib&$JpSab+l}d3TZMsSO!QEXu(*Y7FP_D`9 z4^wDtGLI00j@c6JD5BnuwR$=t>h1qMy&b|qiTObEUi+HsV`HAN0J2z8XyHqn7Wo0{ C%O&Cf diff --git a/Assets/Shaders/SSAO_CS.glsl b/Assets/Shaders/SSAO_CS.glsl index a0fd0bc8..c035adcc 100644 --- a/Assets/Shaders/SSAO_CS.glsl +++ b/Assets/Shaders/SSAO_CS.glsl @@ -7,7 +7,7 @@ const int ROTATION_KERNEL_H = 4; // can perhaps pass in as push constant. const float RADIUS = 0.5f; -const float BIAS = 0.005f; +const float BIAS = 0.025f; layout(local_size_x = 16, local_size_y = 16) in; layout(set = 4, binding = 0, rgba32f) uniform image2D positions; @@ -43,17 +43,17 @@ void main() // load all the necessary variables vec3 viewSpacePos = imageLoad (positions, globalThread).rgb; vec3 viewSpaceNormal = normalize (imageLoad (normals, globalThread).rgb); - viewSpaceNormal = -viewSpaceNormal; + //viewSpaceNormal = -viewSpaceNormal; - ivec2 noiseDim = textureSize(noiseTexture, 0); + vec2 noiseDim = vec2 (textureSize(noiseTexture, 0)); vec2 threadUV = (vec2(globalThread) + vec2 (0.5f)) / vec2(size); - vec2 noiseUVMult = vec2 (float(size.x)/float(noiseDim.x), float(size.y) / float(noiseDim.y)); + vec2 noiseUVMult = vec2 ((vec2(size) / noiseDim); noiseUVMult *= threadUV; - vec3 randomVec = texture(noiseTexture, noiseUVMult).rgb * 2.0f - 1.0f; + vec3 randomVec = texture(noiseTexture, noiseUVMult).rgb; // Gram schmidt vec3 tangent = normalize (randomVec - (viewSpaceNormal * dot(viewSpaceNormal, randomVec))); - vec3 bitangent = cross (viewSpaceNormal, tangent); + vec3 bitangent = normalize (cross (tangent, viewSpaceNormal)); // matrix for tangent to view mat3 TBN = mat3(tangent, bitangent, viewSpaceNormal); @@ -75,16 +75,16 @@ void main() // and bring it from [-1, 1] to screen coordinates offsetPos.xyz = ((offsetPos.xyz * 0.5f) + 0.5f); offsetPos.xy *= vec2(size.xy); - //offsetPos.y = size.y - offsetPos.y; float sampleDepth = imageLoad (positions, ivec2 (offsetPos.xy)).z; float rangeCheck = smoothstep (0.0f, 1.0f, RADIUS / abs (viewSpacePos.z - sampleDepth)); - occlusion += (sampleDepth >= samplePos.z + BIAS ? 1.0f : 0.0f) * rangeCheck; + occlusion += (sampleDepth <= samplePos.z + BIAS ? 1.0f : 0.0f) * rangeCheck; + //occlusion += (sampleDepth <= samplePos.z + BIAS ? 1.0f : 0.0f); } occlusion = 1.0f - (occlusion / float(NUM_SAMPLES)); // store result into result image - imageStore(outputImage, ivec2(gl_GlobalInvocationID.xy), vec4(occlusion.rrr, 0.0f)); + imageStore(outputImage, globalThread, vec4(occlusion.rrr, 1.0f)); } \ No newline at end of file diff --git a/Assets/Shaders/SSAO_CS.shshaderb b/Assets/Shaders/SSAO_CS.shshaderb index ba9a3defde1149ae2025d4b22048dda2dd16a008..e0103cd5dc849c1cf72aaf7c901a6e9fd6af7c0c 100644 GIT binary patch literal 6189 zcmZ9Od30S>6^Acrl8y|OsoGjP-~g?KB4ClBBc_$MN$nuw5MGnloJah_rLN^#e&4-kv+l}SYp?U$zdfFP&%N)pojNDW z*Oa!!Q?u--Y({o;_RoUKW@l|MS-zjeJ~Qjg^{$OuH!f?o`j?%3&Y8L%lTC5UZO7u% z0d7ZzE48}(3CMBqagdb@JdhWdD;uhObD>KoSOxjM7C?BliSRa-|Yebt^u zvxw`+<^e_;&6>`V)>u^b-P{-*t_;DqXN%$Mx!OeU$d=@Ktyx`H8wTdFX9TycdUb1T z^zpNt1K-L!-oB&o?Z_?)-|ag#jSaQ(oR`3jR_gtY;T_dJuywbvw<`64YQ6Be41H%U z7=5N>6}W9{Hs?87;6@)4Z*nNG_Hp)Fjytjm_GV>xWGD^7v%CUs>(nbf%@kjs%r=Caew6L%+C7_g?}m2Yz0k|{eej)#@7;R5V*ciFb@3eK zrsTLi^I4ShsYgG?$GjtcJw3#%?IC>ZPoJn8K74EvSH!iUm*dop>p>!y+~hd>Eyt-F zcOw#UauMe_?ZI5m$!EN1k{;*O{unl&(-V>7i85{>Im{_O5g+He0P(CRqgzW(`vUZ7 z>~hLUM9#>0b5755s~cNh#>yE#D;ezL{G@xoT-NuSxu*hU&uUK*|0J-z%SV0hr%V4+*!B0WhkY^FrTsK^?Jj?^=TH?3d?Sp__X}p|4!ZZL#ioiIX=*pUsGC4tg)U=ZzU$ z4z_3c@UMciZ0|~Y^82pcJnCafw-^1L?{&y3WG(C+~sRnqSTM}BAa5OU=3;R~YPBk19;{ZS;#_O6M1e@FA168`@Hd(Net z(|i6HqK{(jb9wI8)5qmm{te@|!!!GiPDh+y=;jaIcfjBIvc9OKpAKF!N%wa-{I&a= z9J=`~nWS%-q+eFjF9%mjy7$fBv&iRt^LIFO^G}p??}opnVK@HJB>hOzFJvBmYmPzu z&J3a(cWmM=VtUR>U0>&Y65=9yOl~_S>Rv&H0Ev zJ9$#YJaQ{!_t=lWzW}Am#i|Mb}3@@;?nMuedym z`Dbz0tpD`HUCgepb-f$%*7ZAeCUOSSkM4Kuti%m)F8g?9;+C^F@bMdUcH+(F-BORa zoC~(^@O>6oZi0NqJ{yrc4~dxb!9KT$xd1G8AjMn=HcsA}-e0+hUkNV9uR@pWN%5<} zE0RPXYtUCA+RS5bYZ1>Ab=QIQlixxv-*;yz?+WfYU^(X>HM_w2YO`nGF}bL<9$cKG zsJ$Wg%lMWSb9yeioPH56XS~mCBjR(5e4D`5xRj^nee6c`k#9r%4T*cxljFh%`1rlC zj_0D z9JSk@-y-?w=Y?Ro&|d_$zgf(|S}#V-;q%c~d*pu!IP&Xfe!p$K8l#jIDMRFgZQ|rz&fPiRleL{2$#Hrd~a z=zlk2jv4IlLgXXoyTSUz^LP(fPH}m@;ylIg<9pG~5#o2>nZ6G(R(sTcKiJ#{k(kj3 z!1}uESs%HG`5@Ssdyt6v5ZD-dF-9M`h`A4J%)Lm&d>Cwuy&I#CT%7wOU}NIk9|g-P zt~htxqmRMqvjT~C`r}ELQzp_ZJ^|KWd-V88u=UEb_!PRnE_>8RE@D0nHl{p_&!8I< zv(QH_Vm=EtraX)L(T#~&=p*MWrm}wynU2JNiO(l4X7vShbNYYqH1-D&ImKl!@f-X_ z@B@fBqNfMJlh6JoIDK87T_3rK`7(I&*}np3jP;DsN6tQHvVRqsm-JKEzlN0i{(9o% zUFNB$8GHk*J^q`16Kp>DxKoG0@-fFlV7ch|TVTIM&fcD8uzwqo5B)n}K+668 z7`@<&nm<98dkDFoKK8Kx6fu{!gQ@4ACEoh>5jB4fwh!-z{r&>cS3Z1x32q@1$>&#K zIek5cHaUOS{EhRs$ldr(_J@&iWH0gRzeXNL9zl%PCRhI5+>IXfe*?Bg%=x!qxkr(B zPQL?tHf_<9oH@LEzekQv`c(EmAjc)$bN>;sMtnQ|lsI`M?%1Ef+FZf?1uW-t4(_js e^Dg%AUV7jEh8VBEcKhw4KYOzu?f)ao3grLsf+*YrV>7xP}qAWBj! zBDE-3$ErmUq&R@Hq9WovTPJWvaTdi90Y&}3_s(|RmE~FMU;E$x*?XUT&OP_Oq-oY; zvica`wCJcT8<$Pare*(WNZItP2_>uBQ?XOBmb%}*ZsWS8)mqQe<)@uu=+W7DO?~bd zVw&L-K!2e;pgsc}i>@}k&h;DdD;-^D@`SiOB+cY9}N`?_dO$RnRuA+EA}C3a=D7@hY2wJHH2Oo_+7fRtx=ued!?7UX8YKV_WB%LahL; z-w-uNBet>U>-4LIO2nCa2(7YnXSGyo9IV<+XsZkTrJ+J2vW1FjjyP|*H&NX?ynAqc zp_bFUb3QZGi1QW?4plBtbDf*3#HxuC$edi)tvRV)Ti@LLFjvj|scFJKRwUp1<#2t!sq=Lhu74a>%^uA^9&0Ui z^Yy)dYR1pR8tc zewQjT)U2oP{dO$I_iUHdy~g^>;nt7yJ`HZa>c%^FCSa^w!fjDM3#bWW+JI0`y(r7QLi8F`Nf&~?Xy0GeUSqwh;jLf>JKKky zL!9ri=k45Fs(H`VtZ^;YGf?x~^nGvRTn;2|e)M<{&MGU-e=E$MoVVv26Zg5!kStIs(Ynl)L_7oF+-iJT=?i*G_z5DU=&*B06 zEE`!B`TxQ@7DW7`aQCreif$U6ZuP@x1K46-3T6;p&mo4p*}eYpey< zQI9&$g1dGHh&s=Pt4E!6aJ9%;4|nZ+&IWw-$mxWu#oAqP>!^37b2$%gPtJKRzT;~4 z;aNWicvj(Wgd4LrP=uPhi9XGkr4{dhB6?I0LUHQxd^&$+0n7B#PjTO;no z+u&-B(B2Ne9^~)I4N0^AuJrAB2i$z)o!V2#Px_W|{&`F^-D@jN~NR}+qS9&wL9h-Qs|-+iCM zhk&`x$NC?JTe}s+xqSp~tizs-QHz|9!p-Rbk@GRQIrd_XF=~#*S$rC9{GA|rybJDntsr{*4BS|U zJsP7HIiH1_lRt~k;hSTB<`|kOnb_%7V}_#66raOQ+A!PQ;gK4Q&Z!|lWS zVZXlt#;QlmZ{eeLG-7@SS2NaqIH%_C+Lc&;i?rsqV1EzxfDzWv|3lL5$C~e)TK;!) zFMh25N4RUmIsXZ+_5g_I^k=wxb1r&Pvxax?FJM~okHh{I%mDGf-rtg@?idH+f4#rM zosWJVgxgPiXZ`_K3&eeV2+cW1Xb;2HtRLDVNo&H!@6tcv<{R(4&#cH^+=u-*|0q?? G0RIKoSZT`u diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.cpp index b145902f..2bf32fd8 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/PostProcessing/SHSSAO.cpp @@ -19,6 +19,23 @@ namespace SHADE // generate samples for (uint32_t i = 0; i < NUM_SAMPLES; ++i) { + //SHVec3 temp + //{ + // distrib(generator) * 2.0f - 1.0f, // -1.0f - 1.0f + // distrib(generator) * 2.0f - 1.0f, // -1.0f - 1.0f + // distrib(generator), // 0.0f - 1.0f so that sample space is a hemisphere + //}; + + //temp = SHVec3::Normalise(temp); + //temp *= distrib(generator); + + //// This makes sure that most points are closer to fragment's position + //float scale = 1.0f / static_cast(NUM_SAMPLES); + //scale = std::lerp(0.1f, 1.0f, scale * scale); + //temp *= scale; + //samples[i] = SHVec4 (temp.x, temp.y, temp.z, 0.0f); + + samples[i] = SHVec4 { distrib(generator) * 2.0f - 1.0f, // -1.0f - 1.0f From 53fc1fce953f58766116d2ffcb52fdda01aa32dc Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Tue, 1 Nov 2022 12:10:15 +0800 Subject: [PATCH 13/27] WIP --- Assets/Shaders/SSAO_CS.glsl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Assets/Shaders/SSAO_CS.glsl b/Assets/Shaders/SSAO_CS.glsl index c035adcc..2f44763c 100644 --- a/Assets/Shaders/SSAO_CS.glsl +++ b/Assets/Shaders/SSAO_CS.glsl @@ -47,7 +47,7 @@ void main() vec2 noiseDim = vec2 (textureSize(noiseTexture, 0)); vec2 threadUV = (vec2(globalThread) + vec2 (0.5f)) / vec2(size); - vec2 noiseUVMult = vec2 ((vec2(size) / noiseDim); + vec2 noiseUVMult = vec2 (vec2(size) / noiseDim); noiseUVMult *= threadUV; vec3 randomVec = texture(noiseTexture, noiseUVMult).rgb; From 78545889da8ee22fd71924b002e927448de81bfa Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Tue, 1 Nov 2022 12:47:50 +0800 Subject: [PATCH 14/27] SHSHSHAO --- Assets/Shaders/SSAO_CS.glsl | 5 ++++- Assets/Shaders/SSAO_CS.shshaderb | Bin 6189 -> 6237 bytes 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/Assets/Shaders/SSAO_CS.glsl b/Assets/Shaders/SSAO_CS.glsl index 2f44763c..a359a3e8 100644 --- a/Assets/Shaders/SSAO_CS.glsl +++ b/Assets/Shaders/SSAO_CS.glsl @@ -78,8 +78,11 @@ void main() float sampleDepth = imageLoad (positions, ivec2 (offsetPos.xy)).z; + if (sampleDepth == 0.0f) + continue; + float rangeCheck = smoothstep (0.0f, 1.0f, RADIUS / abs (viewSpacePos.z - sampleDepth)); - occlusion += (sampleDepth <= samplePos.z + BIAS ? 1.0f : 0.0f) * rangeCheck; + occlusion += (sampleDepth <= samplePos.z - BIAS ? 1.0f : 0.0f) * rangeCheck; //occlusion += (sampleDepth <= samplePos.z + BIAS ? 1.0f : 0.0f); } diff --git a/Assets/Shaders/SSAO_CS.shshaderb b/Assets/Shaders/SSAO_CS.shshaderb index e0103cd5dc849c1cf72aaf7c901a6e9fd6af7c0c..a419165f53608005e3b2fbbadff33153e4be7f19 100644 GIT binary patch literal 6237 zcmZ9O2b5f86~|vT*-fQHS~M}F*dP%I0tP9mxLMs~7gLM{HfOBq-FM@I*mt*eGB1H;u?Wni${ zsFYjP9Toki6#S~S^6=PT(V-KMVtw_g)M!?(COV_PPHvfH^|99ISgU8GG*kiU%6l3b zu5T?3Z`j_blm^?rQ}X_Yh6lQHQ%`M2y$RTMd9JQ(Hhf35vUB}tsa)x=H`{TY z*&Kw?db6stpfwg0eb?0+Bc);RN!dd1TCO(HJF`W(UTs!ZS4R-@*fRs$P}$WQYyAH% z=YqHLjyG;<`*vm*hwsKsYsZFLdCnfNMyWPfAK6qXBU`r*-YV6GDz&!HX7sJqK=hfI z4S;P}xh~JqK(3dWc#}&ZYj44;x!jrUg*Qthqr+(s-sJ$;`t>XNR+m~O#C$`_M>lwr$Nyt36n;*MqGpjZ_+?wr3X^#XK=@Wj9gW9o{jzwq&1yxpO`< z(ZJl|(MJ7pG3y*cFBj^F9R_Rnyt*>l+MfFz1!Jy5l~vm-ZfN)23%zLH58eg&-mSsw0Ni69PdCp|%o!N( zvnb|MH=oD&n0LglAtq*R58-2f`b6FE;bW7qc3cN~F;3mMekgK@jgPb6Vw}2h2cd`) zi#YFT59acoKH~-B^th+?zhUz^Jr+8FDC6dn!<@<|;p1HALEiNgbZd!epNBpLE+(B! zHh7PI{wKlp zx2C#xwWo-G9J0NOM}7CxqyMRJ{oVDjFGTieKMk%u=5ac*`NW;UVz_quDW1@0)5%jY z=;wXTNKRtbQ+NM8i_o3@l3Z)+=3d&?mn~*ntb2aK#EsFX7xK(PzYOkuV+JomwrBD1 zFC%B!zGe1wC6adYsQbNFw-^1L?`~*0bRv`31D^xFAMX6L&86A_xR^PvfjcuX@2T#4 zD5m}TBpa{(YPdDky~8a@_PNZZ6Zc-5c#v^#KsTp$>!=?}Sj_WQ^q9qM$!3nY+wI97 z`W@(=(Coks}wXJF`ci@Ynt*lx6!?M!vtG`ArG`zao3j#YDU3 zzPI{F);^EtZasZG-sN8)emlIg@90#>`Gs!&(0vE|oiFMO3i|2Di^l2xE{DH%f0IKu zU(Yz*-{PWub3u3i1`4|S)+p%iTdSa(e{Vr|H~c0>e&Y|1(~l+8HvhWw`V;pz9}l!S?Ue3rXYo>|D+&Et&Kqvqq0{kEuEb1tOMR-Tl* zI}g%FypN~mJ31elmk5^E@>!eTXQn;!KLL4R(#`)wsF?pr==z99{wE`gOP&dk`Dd_e z)_+REE`jT7U3Wv=x_+n5g3g2n(fy8{ov@hV8%6WD5GG3VN!dU2NeYO@#L9kHnOOyqWd?b_YBUzS~$;@6;y=@;>0 z#``>;1^GN8-?Ndev6-jgo~?!S5$}NfZHRqXhpb)l#6DQ32VJ{)-Hm=oEc8o}7Zmj8 zjMLYn>wj~a*9K&L#BT&M=SIjp+OA31CS+@Ai@kggV#U~M!iuq%gV~EGVy{3JE5;5d%-H_){*NHrw|&}I;5B4>vIlDh zUPrc``OPPO8GIBnmvQ$Vd9+^z*DiPN zUGS?RbNEf334d|I?qQ$yAipGGyW#)AM|}rmZgVM{%f9zP_8GaaLpJvcDqRnMDReDl zzuNTk9lHV27Vp)|5+?3(?#}t9wBs*F-UsRD4EDms%;&DY0-9aWUx}Dc>;SavRH9XZcbQxPuky<*MS+YzxFa@&4X}lE9mJq z_#2@^(5;Yt+yZ|SBp$PSGqQ2c##z1v(nmaUikb6D_*)_UZ->k=4gNMrJaWDrS)X_w z??4ulJn=kYkKYMqjv&AL&h%Z7vD%~lyOGU(2NZL=6Iox6J?kSDG4DY(<}N5=-ivIE zy%?j9Sj4;!*_gYbh_&H zd(rjR9zA{-*?PrUd<0!zk3H%m7BL@1Hl{d>kD(hAv(QH@Vm^*+OmP;UKsP34p^uoe zm<<0UG!=^f2=^r{X7wp_bNWB;H29|>G09^u@f-XZWbNjNp6*8;fA`OV>Fe?C_rt{^ z<^kmKcmEuiF>!Z&#O!lA{PWP9q@N1^0#xk#iwP6=n5ULz@FisJ@t^a{$mSD|o%#y0 zc+BxIvY7R!!M_TL-OD?%2Yw`Bz3_i>$FIRXep|IY2#NV^Rrb5RE9v4fi?1X5jq{mC zt#2TUhyG1uYy028UcLqCBkpgv*ta3?JPFe7yDR=3$o_d>;fe}FC?{rwPG>>=pBG_M~an@iiBsplUfi(B75qUKMK?ZdsZ z--jW6#lz>P$PH+J^7$FE*u#+b&?Z)#yYn}`3;uJc1??kV{TB&)1a7=GvEuLXPV}h% zOJr-roPUKZ_9zr{_%*V3(-u96nZup_4RlP>C&PaW9iMdX{X57S@lE=D!o;Q6-9I2} q^91%sWHFy}V1G)OJKoRx?tAoS$awv=+i#iv?9G0(|CcOFq5lCYGEJEP literal 6189 zcmZ9Od30S>6^Acrl8y|OsoGjP-~g?KB4ClBBc_$MN$nuw5MGnloJah_rLN^#e&4-kv+l}SYp?U$zdfFP&%N)pojNDW z*Oa!!Q?u--Y({o;_RoUKW@l|MS-zjeJ~Qjg^{$OuH!f?o`j?%3&Y8L%lTC5UZO7u% z0d7ZzE48}(3CMBqagdb@JdhWdD;uhObD>KoSOxjM7C?BliSRa-|Yebt^u zvxw`+<^e_;&6>`V)>u^b-P{-*t_;DqXN%$Mx!OeU$d=@Ktyx`H8wTdFX9TycdUb1T z^zpNt1K-L!-oB&o?Z_?)-|ag#jSaQ(oR`3jR_gtY;T_dJuywbvw<`64YQ6Be41H%U z7=5N>6}W9{Hs?87;6@)4Z*nNG_Hp)Fjytjm_GV>xWGD^7v%CUs>(nbf%@kjs%r=Caew6L%+C7_g?}m2Yz0k|{eej)#@7;R5V*ciFb@3eK zrsTLi^I4ShsYgG?$GjtcJw3#%?IC>ZPoJn8K74EvSH!iUm*dop>p>!y+~hd>Eyt-F zcOw#UauMe_?ZI5m$!EN1k{;*O{unl&(-V>7i85{>Im{_O5g+He0P(CRqgzW(`vUZ7 z>~hLUM9#>0b5755s~cNh#>yE#D;ezL{G@xoT-NuSxu*hU&uUK*|0J-z%SV0hr%V4+*!B0WhkY^FrTsK^?Jj?^=TH?3d?Sp__X}p|4!ZZL#ioiIX=*pUsGC4tg)U=ZzU$ z4z_3c@UMciZ0|~Y^82pcJnCafw-^1L?{&y3WG(C+~sRnqSTM}BAa5OU=3;R~YPBk19;{ZS;#_O6M1e@FA168`@Hd(Net z(|i6HqK{(jb9wI8)5qmm{te@|!!!GiPDh+y=;jaIcfjBIvc9OKpAKF!N%wa-{I&a= z9J=`~nWS%-q+eFjF9%mjy7$fBv&iRt^LIFO^G}p??}opnVK@HJB>hOzFJvBmYmPzu z&J3a(cWmM=VtUR>U0>&Y65=9yOl~_S>Rv&H0Ev zJ9$#YJaQ{!_t=lWzW}Am#i|Mb}3@@;?nMuedym z`Dbz0tpD`HUCgepb-f$%*7ZAeCUOSSkM4Kuti%m)F8g?9;+C^F@bMdUcH+(F-BORa zoC~(^@O>6oZi0NqJ{yrc4~dxb!9KT$xd1G8AjMn=HcsA}-e0+hUkNV9uR@pWN%5<} zE0RPXYtUCA+RS5bYZ1>Ab=QIQlixxv-*;yz?+WfYU^(X>HM_w2YO`nGF}bL<9$cKG zsJ$Wg%lMWSb9yeioPH56XS~mCBjR(5e4D`5xRj^nee6c`k#9r%4T*cxljFh%`1rlC zj_0D z9JSk@-y-?w=Y?Ro&|d_$zgf(|S}#V-;q%c~d*pu!IP&Xfe!p$K8l#jIDMRFgZQ|rz&fPiRleL{2$#Hrd~a z=zlk2jv4IlLgXXoyTSUz^LP(fPH}m@;ylIg<9pG~5#o2>nZ6G(R(sTcKiJ#{k(kj3 z!1}uESs%HG`5@Ssdyt6v5ZD-dF-9M`h`A4J%)Lm&d>Cwuy&I#CT%7wOU}NIk9|g-P zt~htxqmRMqvjT~C`r}ELQzp_ZJ^|KWd-V88u=UEb_!PRnE_>8RE@D0nHl{p_&!8I< zv(QH_Vm=EtraX)L(T#~&=p*MWrm}wynU2JNiO(l4X7vShbNYYqH1-D&ImKl!@f-X_ z@B@fBqNfMJlh6JoIDK87T_3rK`7(I&*}np3jP;DsN6tQHvVRqsm-JKEzlN0i{(9o% zUFNB$8GHk*J^q`16Kp>DxKoG0@-fFlV7ch|TVTIM&fcD8uzwqo5B)n}K+668 z7`@<&nm<98dkDFoKK8Kx6fu{!gQ@4ACEoh>5jB4fwh!-z{r&>cS3Z1x32q@1$>&#K zIek5cHaUOS{EhRs$ldr(_J@&iWH0gRzeXNL9zl%PCRhI5+>IXfe*?Bg%=x!qxkr(B zPQL?tHf_<9oH@LEzekQv`c(EmAjc)$bN>;sMtnQ|lsI`M?%1Ef+FZf?1uW-t4(_js e^Dg%AUV7jEh8VBEcKhw4KYOzu?f)ao3grLsf Date: Tue, 1 Nov 2022 20:10:59 +0800 Subject: [PATCH 15/27] SSAO is fully implemented --- Assets/Shaders/DeferredComposite_CS.glsl | 12 ++-- Assets/Shaders/DeferredComposite_CS.shshaderb | Bin 4789 -> 4997 bytes Assets/Shaders/SSAOBlur_CS.glsl | 58 ++++++++++++++++++ Assets/Shaders/SSAOBlur_CS.shshaderb | Bin 0 -> 4669 bytes Assets/Shaders/SSAO_CS.glsl | 35 +++++++---- Assets/Shaders/SSAO_CS.shshaderb | Bin 6237 -> 6125 bytes .../MiddleEnd/Interface/SHGraphicsSystem.cpp | 12 +++- 7 files changed, 97 insertions(+), 20 deletions(-) create mode 100644 Assets/Shaders/SSAOBlur_CS.glsl create mode 100644 Assets/Shaders/SSAOBlur_CS.shshaderb diff --git a/Assets/Shaders/DeferredComposite_CS.glsl b/Assets/Shaders/DeferredComposite_CS.glsl index da13b1b4..833180e7 100644 --- a/Assets/Shaders/DeferredComposite_CS.glsl +++ b/Assets/Shaders/DeferredComposite_CS.glsl @@ -21,7 +21,7 @@ layout(set = 4, binding = 0, rgba32f) uniform image2D positions; layout(set = 4, binding = 1, rgba32f) uniform image2D normals; layout(set = 4, binding = 2, rgba8) uniform image2D albedo; layout(set = 4, binding = 3, r32ui) uniform uimage2D lightLayerData; -layout(set = 4, binding = 4, rgba32f) uniform image2D ssaoImage; +layout(set = 4, binding = 4, r8) uniform image2D ssaoBlurredImage; layout(set = 4, binding = 5, rgba8) uniform image2D targetImage; layout(set = 1, binding = 0) uniform LightCounts @@ -55,7 +55,7 @@ void main() vec3 positionView = imageLoad (positions, globalThread).rgb; // normal of fragment - vec3 normalView = -imageLoad(normals, globalThread).rgb; + vec3 normalView = imageLoad(normals, globalThread).rgb; vec3 fragColor = vec3 (0.0f); @@ -78,9 +78,11 @@ void main() fragColor += pixelDiffuse.rgb * AmbLightData.aLightData[i].ambientColor.rgb * vec3 (AmbLightData.aLightData[i].strength); } + float ssaoVal = imageLoad (ssaoBlurredImage, globalThread).r; + fragColor *= ssaoVal; + // store result into result image - //imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(normalView, 1.0f)); - //imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(fragColor, 1.0f)); - imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(imageLoad(ssaoImage, globalThread).rgba/*, 1.0f*/)); + imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(fragColor.rgb, 1.0f)); + //imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(ssaoVal.rrr, 1.0f)); } \ No newline at end of file diff --git a/Assets/Shaders/DeferredComposite_CS.shshaderb b/Assets/Shaders/DeferredComposite_CS.shshaderb index 525f3c4ced3b824db7ef716d0d4f39927b2b018e..8d7a83271b3d684965b4a639eba7e74329c9469d 100644 GIT binary patch literal 4997 zcmZve33n7l5XUFS=HL*JQw7`*4-kxzOB6Xm0!uKEAP{fkWOuU}ne4{h3AYLg;)#eT z-h!XN&)|phsqguo|KChkX!B@ZQC0t{uBz^;o^11lr9rw{n!DSBpedLaEDV0jpkPVR zEF?(z)8g}kwp1?+9UJOtB&D9M+j?=mFKB_Kwng&ENp2NQg;5oJp=hyiuqCOCp82+t-dYB8QE`3^aG z`1y0n-KiXvxHcZf$0zIMuq0J=cBHjc;;}+%8mykG6~iQ|RR;%Bdt0zld^$Q)jt8QN ziJ6A7v#&LHP&|ys%cUB6TacGNU28;a9*xSUr3%jl-5%a>*n075tv(gTnJ4i!%wmmn zUyt;OdRXbN#kG36uO-+l9;I?F*eN~~RVI`E+DtWRsDh3Z6CAj!s#U`{bs=w?{;`LC zPS>Jp;w*;KgT{2tV0pKv{&Y5+8js4eJF;`_5*~Z`bMo&OR!ZX@NlzD@E6?6D_c@TY zaJH^vNqwf6WVK;u&DJiN+Q6wfYV^78-^Ho9I1_6;Du=_y$+TwtskxN3%dSs%+7TQO zKDUN}FbM^xxv;acGh`Nedr+A6r6)6g@L_zjJUU9bT1h6ArzI!}&-&CJOiS+b?(goI zGn>qIzq7S+ZuW8Rh6R>vIOm>wANX@_|32smv*YKt`iX^&6?!M*Txtn>JT#m6%fcIt zur?aTI%j)u)#>}lk8k`C%?tSEf>#`+by;4pxn7DU@#mvl5c(z>6Dk*68`991S ztrns4w$_PSJ-tgZ=f>VG?%UC^v#|4)d^>S?;_r;_nx46ZMMNXERLAEb0Se zAO6g;UmrU4k)Qp{5zF=)X7yPu_*s3+B%7brw@MiK-Vvw1ya*qgIg3wyU{)Wq=huf$ zeKrfs9Cly#?bqkn(Xr=5)bootv-W_~?}+>H(DA39r8*&J?2?9#yj(HtJWbM9O4lFG z6vLjE&a8kz_|Hpm{ilUL`N4>ZKRqWF_)e$uCM^CU$>hX;h5qNh^CDs`7e}{PDo9PLxcm;W`(_{avPHyND~-3v-TK77=Y?@*?Bqx1ZGvIn?PT^X z6WS+Eya91)v3T6Y8r?SU4%=GE2gK2dQxGR67BwIg6 zC9{{jW*?W_B%(gvq4no(jVf_$@#@FzQ239ESb8lc|SZUlB(ppTCH~ zT(ajQXTX=3=vN&^&D8ao)3GyOyh|4IbweBafe_>b&59e zB@Ppt#qM_)_ckIw>RT$p7u#;#1m^}L58sW4M0_*Q@n0>%XI%T4&$S|az=w5n%>Tn8 zaEL`d?wk1BBX;6-i9aIZ`(g1PmF&lV%=v&@{KqAOLo7djUOIM*|AgcXPN)8jB0v5n z>G*(K{3j)YLo7c&ea6mNdc=F3On3b{x0A{Y~BVotNplSt9?}ROCqZs+X)fA%;(D@?AF^?90ty^-r`RUuZqYw;?DY- z!@!{{s-N?{E+Q6oJL4OYnQ!xXQ!;+w<})Ulxw+)xyd@b7Uz;f~=7gD{Z*cZAC!vV5 zU(|l|qQl0;*^dp(pF{eOjc*El#a0$4Hk=u)h);@G*duZ5aLfI+WMbHio|Ft`Ga5@~ zM(zHY(J2wQ&1h9J`@oq|^a&C9$%kxrRg=tpTK*ZyLT!XN8duKg)McvgJE3`GUyuVdKv6Wp3UTVYj(?&tc$@<#}H+xv;aBS-L3l zXX28>@U@u$qc8M`dxBe?A4sN7n~4u4gV{`A1M~aNeY5|H_{XBFPHz|gMARv=Z~Ui{ z@d4-W3+Me@1kR$y%i>^mA74lYvol_k%o(q_x&Jbig8)A}BN+ax#J>_B2gJiq%Pzg&_DLj^JXKi zcbvs=?x5Xl7%cC>)SsIT=V#)mw<9~(A>oOaKQDiJR!!rcN>3MGje32akZnA>!d_ix zI<0P{lhuZu)vH}HwSiM}+#Ykce-EeTN;lDX)J}%&3u(>xQ*$-DE^D89s+keKu!ixl z6ADgqVP|D$$SmCLq%iGEPiFq$)A(k2bd;!G>&z)nE{KF@_cR#1D|yW8-@P+uHkqxz zy;?ap`#5*o0!ucWb1&=%{+!$I2Y15V`}wVYVqs&2-pM#uSD5yAXm;nfgm=PLE$U3p zhqWl3(>uc2?XZy{*<1KUSi)?S!YffL%UINm^Bq_s+9*Qj4Q&zid-{lE&WD}1uKA-Pf__MdV}dd^@_o|3~S} z+WjK@nMvOt9e?UstrPa8I=@EQdDm)>ooA7-_0k8$!SF3eXI8)<{1>OV{%GM(elTL< z&z%zs{D9MW6Bd7kWa8t$PJiilK}4*z;^-D@o#ZSpXB-Z=2kgZ17q!wu^3w|zzT`*e z4YJ6wNt_t?6LZAr{}&UCnDmr|FEP=#0%)1eyJYQ2{mzJtOzGj{T$^ESb-zu;u{tr2=eoOrxVYO#3qVw1XkOdQ*0$whH= z;v5$zCK!3pd1IF6gp-Mh|CBiA;rw=~1I{uN<4=O)>ST5q7Uz5%or)OZNRW)ba-ZMJ>8%6lcXg{;FS%eSxlsd(1J|qH%SmdL> z#HVlAiO1bMEaGij{6{4F@gH?Q;1>Te$>0#nk6)0E-QqtkdArl8e}~AAzf(Fs;1>T0 z$>0#n;$K(IoNt#1AI`%)qa$<2yPeGaj*9-)$@hvgPw+n#;~DY&A{O>%#j(SwoBMlC zL=5hi**@T~G4-AA&0!JWAabw=pE1#4(eLs(B7RiFKJb6!gT7Bhe)1t(z858vZ%ns* zLcAoJ6cHbr<>CA%Mc9|BQuI?IdNd)zMlYCWaN^^0S_EeLOOol`UDdiq{EP@6@TIB& z?5v2m`0*XbhuFLgY*zcrlCAdhl3x*7?byzV@MT_K6=Ao#e$8RvEb=j{_*28{BJxeU zv%cXlaOjrm=X`I9h=twG_?Bem-F(WD@dG!XwFQ?$zV34 z^OBiS>;GcObrHDDXhSmlz?o6>nuz@5L$+QuCDTvKe^D~|nOW}rlBg@^3*o9R?0ro*R*(I>do`H^Jmw3+x=GMLQ-HZbH9Ok%JHpNi_^oYaf`Uq#+8`VRpBvEcv! diff --git a/Assets/Shaders/SSAOBlur_CS.glsl b/Assets/Shaders/SSAOBlur_CS.glsl new file mode 100644 index 00000000..64066525 --- /dev/null +++ b/Assets/Shaders/SSAOBlur_CS.glsl @@ -0,0 +1,58 @@ +#version 450 + +#define BLUR_WIDTH 5 +#define BLUR_HALF_WIDTH BLUR_WIDTH / 2 +#define SHM_WIDTH BLUR_WIDTH + 16 - 1 + +layout(local_size_x = 16, local_size_y = 16) in; +layout(set = 4, binding = 0, r8) uniform image2D ssaoImage; +layout(set = 4, binding = 1, r8) uniform image2D ssaoBlurImage; + + +float GetSSAOValue(ivec2 uv, ivec2 imageSize) +{ + if (uv.x >= 0 && uv.y >= 0 && uv.x < imageSize.x && uv.y < imageSize.y) + { + return imageLoad (ssaoImage, uv).r; + } + + return 0.0f; +} + +shared float sharedPixels[16 + BLUR_WIDTH - 1][16 + BLUR_WIDTH - 1]; + +void main() +{ + ivec2 globalThread = ivec2 (gl_GlobalInvocationID.xy); + ivec2 localThread = ivec2 (gl_LocalInvocationID.xy); + ivec2 inputImageSize = imageSize(ssaoImage); + + // Load color into shared memory + ivec2 start = ivec2 (gl_WorkGroupID) * ivec2 (gl_WorkGroupSize) - (BLUR_HALF_WIDTH); + for (int i = localThread.x; i < SHM_WIDTH; i += int (gl_WorkGroupSize.x)) + { + for (int j = localThread.y; j < SHM_WIDTH; j += int (gl_WorkGroupSize.y)) + { + float value = GetSSAOValue (start + ivec2 (i, j), inputImageSize); + sharedPixels[i][j] = value; + } + } + + // wait for all shared memory to load + barrier(); + + ivec2 shmStart = ivec2 (localThread + (BLUR_HALF_WIDTH)); + + float sum = 0; + for (int i = -BLUR_HALF_WIDTH; i <= BLUR_HALF_WIDTH; ++i) + { + for (int j = -BLUR_HALF_WIDTH; j <= BLUR_HALF_WIDTH; ++j) + { + float sharedVal = sharedPixels[shmStart.x + i][shmStart.y + j]; + sum += sharedVal; + } + } + + sum /= (BLUR_WIDTH * BLUR_WIDTH); + imageStore(ssaoBlurImage, globalThread, vec4(sum.rrr, 1.0f)); +} \ No newline at end of file diff --git a/Assets/Shaders/SSAOBlur_CS.shshaderb b/Assets/Shaders/SSAOBlur_CS.shshaderb new file mode 100644 index 0000000000000000000000000000000000000000..680cb8d5f8bd787a251d73bf38d4d814202e13e0 GIT binary patch literal 4669 zcmZ9O2X~ZJ5QaYj8={B^0*a!7y&@v09BUL^qtQfzy~HJ1VRcj7Y+_f$hF!7ug1uu$ z#jeMn;h(Ucqxd{u?sz_P&w0F!;)NroR+obe7UoybJ0k%f6>xqi=DE4Hd>W@K$y34IC}sMH4Kj|V4%Gr$hy z&^I&Jwa4d8CPxeUcPu=GYRa9x<*u%B=gGZ&!^6EJ&1>t`-g<4Y+S^}iRQsB>v8r)x zg}B;aUwyQ{7*HajSVxKY>8w$%HhX&7yUwlDN2~jf)s`GB;7imn4LLfdUdpyZuMJdI zS9@yLv0TpChmn!WP=|cZwPwd4SJ#JDRq89(G^&+;Ok&&eeXp+fmUCCf;Mh=KrCA#q z>{yZeOPR6`8Pl9&pP17rJz)wtTeA-QwZY-hW?sN}VeYdNexzAxG?B*HYx0~o)VQ+T z7#baRQTKPD^YfU=ne|_h>r=8}WS{=0kF$1G&BdJ=T93eSG~=wlSY)K8^+5J#3bv*C*CT8`1AFd-V+V z1XDoR3(+0g-Z#&2ezNVU_O8jcH`==-+jWZhw9V%mFyD_zdS#c|FKBxwm;@O z4(WRG=F|3!e%g<7fSib!^Uz%*>^}6_ zz#4~;&T}vN&2=5nKOg&gq&_+A8<29^&c6|9Kjf`h+czSoe_hgx`PaimJ+5~bXk(L6 z-^1AdY~8vw><_SU=YI2i0)W^ho_{kY#I+kNy3CHQuw<{A|4E za>6@v1iiFA_uw$sA221PYkF7x_Sv_vS4^-wCfI(bBHp`u;RL%{usxIEg6(>KmtwxQ z-=(7M_a|)U`|Sza^)^hf{RV~K_>IXvmi>8O+ktnri>MQjCjvR)@H}oH)*L4R{m0QM z`=T9rPC@rhN1igeoNyHLoQkdAJoZ!DJd2U1fhAx~TJ!Y88Edb#W6d+seK*$Eh3p1$ zXK{kQpR*E&_>Vg~an{qF-cnEQ&oX_tCGK2wdEZ&YosaGt6YEmk1?a}=vqsNft{wj@ zSCIOZk!uyYIX1E03}io$>jQt0 zL;F%-F6XL8ZI`24n{OfVtwxu(Ht(voYp+2%UukXru3ZTn`u$DQuZ&#&wwfbq^Uso8 z)TUhn=5nsObEhJ&0`@X;HPGE>*#01!JI~PDSf^( z?d6=%Hppwibl@C)#`sp{qlTN&i#4sqwkG}NxCJ<;ot*2Cw*tSJ&RYx2DQBELw4e4t z8Ef2zZcg{)-MJmetpv{3Cs#Zp`>A~y(tOIucL%yPN4`7J-7Xh;z6XJ>E#1!+j}EU%bux(d8Y%J%BDZ2}HgJ(T&yTe(y%gsXv5Vp7agK zhkg2+>7r>`%z#n=c-$S-`808ndDQt z?sLfJfx~rQKsr|$>%NF?j#&34bh%hp`&nQv=c>p1eHq<;6u&L6V9Q7TSJB;9ocC+! z#>hvW*U`;055&AT(B;E^6Wux^&s*rm$jAMD8{PZu8v320b2fD50tn))`xeq{`mz?wCyzH&Ecf@?k$oCO?v40<9 z%SAqYa?X!?=N*ate2VUV)~Ee^hA#IBi2cYJzZm&B*qm(N*B9WJWZRD~f%&@m8f-y+ zl{k6fTQcq&pwAK9x9D=dui(B*Tnnep##+j#bsuzVv3}#N!&>)4I;_>0eSw^{sz)9B zqfhMF0dVpWb0E647W;Y-wtUojFuL>Ptu@wCMy-dSTZ{D@ZynZpDAHlA#w-GI)~X)w qAa9wU;Bk)Bghe^~S>h literal 0 HcmV?d00001 diff --git a/Assets/Shaders/SSAO_CS.glsl b/Assets/Shaders/SSAO_CS.glsl index a359a3e8..1a572521 100644 --- a/Assets/Shaders/SSAO_CS.glsl +++ b/Assets/Shaders/SSAO_CS.glsl @@ -36,37 +36,45 @@ layout(set = 2, binding = 0) uniform CameraData void main() { - ivec2 size = imageSize (outputImage); + // image size of the SSAO image + ivec2 ssaoSize = imageSize (outputImage); + // global thread ivec2 globalThread = ivec2 (gl_GlobalInvocationID.xy); // load all the necessary variables vec3 viewSpacePos = imageLoad (positions, globalThread).rgb; vec3 viewSpaceNormal = normalize (imageLoad (normals, globalThread).rgb); - //viewSpaceNormal = -viewSpaceNormal; + // Get the noise dimension. This should be 4x4 vec2 noiseDim = vec2 (textureSize(noiseTexture, 0)); - vec2 threadUV = (vec2(globalThread) + vec2 (0.5f)) / vec2(size); - vec2 noiseUVMult = vec2 (vec2(size) / noiseDim); + + // Get normlized thread UV coordinates + vec2 threadUV = (vec2(globalThread)) / vec2(ssaoSize); + vec2 noiseUVMult = vec2 (vec2(ssaoSize) / noiseDim); noiseUVMult *= threadUV; + + // sample from the noise vec3 randomVec = texture(noiseTexture, noiseUVMult).rgb; // Gram schmidt vec3 tangent = normalize (randomVec - (viewSpaceNormal * dot(viewSpaceNormal, randomVec))); vec3 bitangent = normalize (cross (tangent, viewSpaceNormal)); - // matrix for tangent to view + // matrix for tangent space to view space mat3 TBN = mat3(tangent, bitangent, viewSpaceNormal); float occlusion = 0.0f; for (int i = 0; i < NUM_SAMPLES; ++i) { // We want to get a position at an offset from the view space position. Offset scaled by radius. - vec3 samplePos = TBN * ssaoData.samples[i].rgb; - samplePos = viewSpacePos + samplePos * RADIUS; + vec3 displacementVector = TBN * ssaoData.samples[i].rgb; + + // Why are we adding positions? + displacementVector = viewSpacePos + displacementVector * RADIUS; // Now we take that offset position and bring it to clip space - vec4 offsetPos = vec4 (samplePos, 1.0f); + vec4 offsetPos = vec4 (displacementVector, 1.0f); offsetPos = cameraData.projMat * offsetPos; // then we do perspective division @@ -74,20 +82,23 @@ void main() // and bring it from [-1, 1] to screen coordinates offsetPos.xyz = ((offsetPos.xyz * 0.5f) + 0.5f); - offsetPos.xy *= vec2(size.xy); + offsetPos.xy *= vec2(ssaoSize.xy); + // Now we attempt to get a position at that point. float sampleDepth = imageLoad (positions, ivec2 (offsetPos.xy)).z; + // skip checks if (sampleDepth == 0.0f) continue; + // if sampled fragment is in front of current fragment, just occlude float rangeCheck = smoothstep (0.0f, 1.0f, RADIUS / abs (viewSpacePos.z - sampleDepth)); - occlusion += (sampleDepth <= samplePos.z - BIAS ? 1.0f : 0.0f) * rangeCheck; - //occlusion += (sampleDepth <= samplePos.z + BIAS ? 1.0f : 0.0f); + occlusion += (sampleDepth <= displacementVector.z - BIAS ? 1.0f : 0.0f) * rangeCheck; } occlusion = 1.0f - (occlusion / float(NUM_SAMPLES)); // store result into result image - imageStore(outputImage, globalThread, vec4(occlusion.rrr, 1.0f)); + imageStore(outputImage, globalThread, occlusion.rrrr); + } \ No newline at end of file diff --git a/Assets/Shaders/SSAO_CS.shshaderb b/Assets/Shaders/SSAO_CS.shshaderb index a419165f53608005e3b2fbbadff33153e4be7f19..6bb4abcd8018cac584ecc8f8b59b86984eb528d7 100644 GIT binary patch literal 6125 zcmZ9Od5~OH6^CCYnaK`B5*8C7iyI_FK!PY+Hkgb~GJ}&u#OS2c)0s5Pba$qE0*O&F zMiiq)&?w-7xS${|sJP=6ca3pha76_7N3@4naF@#v{p zzNU68o1SG;vRT>O?C)(Vo0oOKWchwR`|PYM*SmWMdRI1ELn|*>b*`=_WK-R8+llye zf~O&)rD{!nK5`Pg+`JsCxBaIQ+W|gGp=ng_?j7vz>+9~lVzAt33^rSPM=FCO)mmk6 zs5(|Dx2k(8`pqc#Rcqyu@u8waCmzN6opdyl8qH>@K2Y69h76{YlV(|cywweNVM={XnBs zuJqTN?YPct5uj0TR&|!N#?qqirux`uX#{>+whX?Ot4;LIY_%(@ z18e%$ms%xYep}>R&C+ONq|!e7ggVbF{ER&eSKqm_S!uNgEcZsZb*0hDSgGyVMMgPS z%w6oQl=nXGX>2UD3Y_=PXD1te-sr|y{aQKe+=gB*)R8+1*Y0_JrP11z`yGd4zQdJu zyDH`DvaFl=de403-pSCHfUT?U`!O5wuBf{g{nhn%Y4@HK?dsY+n|AMrcHhI$i}sho zcOkxm8}N$xo5$77^OSQ2#!s*p^QoK9Wqiy#;x`Zzv$luunF7`)>V^*=p2W4|I?#)8 z>c;gWkxOoJoc$K#)Q!6Zi8#54^PKizF3;&RUOGvSb87z^HlNe!$jL+*w}c$#6feNX zxh_UL>#6A0lGDBzeFnRnate{Na^9RX^W5sj7MHPd#?MIx`?xsi-Y=K+{k|?%VOjri z>~i*K{K@R*k~d!6`zNRW0(SkasqR_rDdHawws-lc@BMV?ed|^3GrdyLS62uFx0K$vGJG^E@k)lbrR`z5lM|=+6GUTx;v*?n(M-*slS5mN?%F z!1g0=y#CvfEIV+y^=csP^6HJGTStFqw-;HB%;%K**cZY3&N&-xXHd=eOU@hz*qw)* zXHcI&VnzoOHa>bf1ZL$uy%u0k+C9^egnb5QFahtlHu(_iz6sqL+O4bZJ0KUcyB!>} zxg*)k5of(K*+ah@-4*&h;3)-%`-MkJ}2m_s`$o$mjjrUC`}!e?j+d94_d_ADyHhPx__I!|%!o z$XsL>x^+%W++|G9S*h#myiY;qBYk)-VE6B&oZ|9X?oWA618X;rGggn9PXPNJQMcw9 zh(0@bQr_Lgh(7XtJhju=mmrIiu;sOU*5>z_X^;F*1TRav`JaRo^FJ9~ANk1t6tKMF znu3^r4tLG^Pfgqv?D|^QyCHAgbJ)*C{2mRVuV6nval@R;KAxU9zfpC3{0?4_c=LI; z)MG9eg6%tep8=K&`$b@%QP`gemb;mH=6)7pjJ)~1t8x*43Ah-4DY~3?<1a((De_&O z+uHn9)bO2MjmW!#TLYGJhW)9Rwcyo=Hhb|sk&9aE!1fpVdayn>rFiEqr(eX&>F?~j z5oaIq8^Fe2&E&mP&qnl-??8Hxc=pc$Ygb(H?5*SbtKGcbgN=w>=$pVx3wqxqy&qlw zBWYe&f%TC;3}?>gBIeO{FmVH5YiWx+xEXA3o?E;9`8|=3ezt<;LVq6E{^l?TYh8_) z!&&O9J@P*v9QpM#zuzbM$oE2UG5?Fu^$GhR*m`jnN?>DL!R-LcSu415;yMc45ZL^# z@T-93im^KrSBxEovlmyy?gGmdW2=cXwm-e=*MjZaKJ6>`>%jJ857rER1Z+L?n@|24 z_EE%K#_8icx3SBM>+Ie`vEOyS3;*VJjaumwmqkvCqi;GO)SVQ0XB1%aIAhezoc6J9ZPI zE#9kFBu?Jt+@15S>5jh=Y%Tqq!G3l*^LbZqMiv(ISAq43_vY1LxkJcA%J~|waoQrM zT;zNm*c@>uZUM`=g1Z$gSG*^$Pn`Ytr*Fy|z{cyZeLG^!!|dAD(9<34Z$@rIZb$6n z2>V+Q`Iy~X!NxfoXZbcnANj~BXU-b?+Y$ZmM9eXZ{Vqg4a=rtsPdtxzg5?yK=WCy* z{Tuf#^t%e;ci-pmZp2vaQU5()bKi}`+};b;*JaQ8$VJS(U}NqS+@w!u|08lz(mnT|5NpKm&7Tt|A5tcld5qQmU!Lqm G$o~MNH$(FP literal 6237 zcmZ9O2b5f86~|vT*-fQHS~M}F*dP%I0tP9mxLMs~7gLM{HfOBq-FM@I*mt*eGB1H;u?Wni${ zsFYjP9Toki6#S~S^6=PT(V-KMVtw_g)M!?(COV_PPHvfH^|99ISgU8GG*kiU%6l3b zu5T?3Z`j_blm^?rQ}X_Yh6lQHQ%`M2y$RTMd9JQ(Hhf35vUB}tsa)x=H`{TY z*&Kw?db6stpfwg0eb?0+Bc);RN!dd1TCO(HJF`W(UTs!ZS4R-@*fRs$P}$WQYyAH% z=YqHLjyG;<`*vm*hwsKsYsZFLdCnfNMyWPfAK6qXBU`r*-YV6GDz&!HX7sJqK=hfI z4S;P}xh~JqK(3dWc#}&ZYj44;x!jrUg*Qthqr+(s-sJ$;`t>XNR+m~O#C$`_M>lwr$Nyt36n;*MqGpjZ_+?wr3X^#XK=@Wj9gW9o{jzwq&1yxpO`< z(ZJl|(MJ7pG3y*cFBj^F9R_Rnyt*>l+MfFz1!Jy5l~vm-ZfN)23%zLH58eg&-mSsw0Ni69PdCp|%o!N( zvnb|MH=oD&n0LglAtq*R58-2f`b6FE;bW7qc3cN~F;3mMekgK@jgPb6Vw}2h2cd`) zi#YFT59acoKH~-B^th+?zhUz^Jr+8FDC6dn!<@<|;p1HALEiNgbZd!epNBpLE+(B! zHh7PI{wKlp zx2C#xwWo-G9J0NOM}7CxqyMRJ{oVDjFGTieKMk%u=5ac*`NW;UVz_quDW1@0)5%jY z=;wXTNKRtbQ+NM8i_o3@l3Z)+=3d&?mn~*ntb2aK#EsFX7xK(PzYOkuV+JomwrBD1 zFC%B!zGe1wC6adYsQbNFw-^1L?`~*0bRv`31D^xFAMX6L&86A_xR^PvfjcuX@2T#4 zD5m}TBpa{(YPdDky~8a@_PNZZ6Zc-5c#v^#KsTp$>!=?}Sj_WQ^q9qM$!3nY+wI97 z`W@(=(Coks}wXJF`ci@Ynt*lx6!?M!vtG`ArG`zao3j#YDU3 zzPI{F);^EtZasZG-sN8)emlIg@90#>`Gs!&(0vE|oiFMO3i|2Di^l2xE{DH%f0IKu zU(Yz*-{PWub3u3i1`4|S)+p%iTdSa(e{Vr|H~c0>e&Y|1(~l+8HvhWw`V;pz9}l!S?Ue3rXYo>|D+&Et&Kqvqq0{kEuEb1tOMR-Tl* zI}g%FypN~mJ31elmk5^E@>!eTXQn;!KLL4R(#`)wsF?pr==z99{wE`gOP&dk`Dd_e z)_+REE`jT7U3Wv=x_+n5g3g2n(fy8{ov@hV8%6WD5GG3VN!dU2NeYO@#L9kHnOOyqWd?b_YBUzS~$;@6;y=@;>0 z#``>;1^GN8-?Ndev6-jgo~?!S5$}NfZHRqXhpb)l#6DQ32VJ{)-Hm=oEc8o}7Zmj8 zjMLYn>wj~a*9K&L#BT&M=SIjp+OA31CS+@Ai@kggV#U~M!iuq%gV~EGVy{3JE5;5d%-H_){*NHrw|&}I;5B4>vIlDh zUPrc``OPPO8GIBnmvQ$Vd9+^z*DiPN zUGS?RbNEf334d|I?qQ$yAipGGyW#)AM|}rmZgVM{%f9zP_8GaaLpJvcDqRnMDReDl zzuNTk9lHV27Vp)|5+?3(?#}t9wBs*F-UsRD4EDms%;&DY0-9aWUx}Dc>;SavRH9XZcbQxPuky<*MS+YzxFa@&4X}lE9mJq z_#2@^(5;Yt+yZ|SBp$PSGqQ2c##z1v(nmaUikb6D_*)_UZ->k=4gNMrJaWDrS)X_w z??4ulJn=kYkKYMqjv&AL&h%Z7vD%~lyOGU(2NZL=6Iox6J?kSDG4DY(<}N5=-ivIE zy%?j9Sj4;!*_gYbh_&H zd(rjR9zA{-*?PrUd<0!zk3H%m7BL@1Hl{d>kD(hAv(QH@Vm^*+OmP;UKsP34p^uoe zm<<0UG!=^f2=^r{X7wp_bNWB;H29|>G09^u@f-XZWbNjNp6*8;fA`OV>Fe?C_rt{^ z<^kmKcmEuiF>!Z&#O!lA{PWP9q@N1^0#xk#iwP6=n5ULz@FisJ@t^a{$mSD|o%#y0 zc+BxIvY7R!!M_TL-OD?%2Yw`Bz3_i>$FIRXep|IY2#NV^Rrb5RE9v4fi?1X5jq{mC zt#2TUhyG1uYy028UcLqCBkpgv*ta3?JPFe7yDR=3$o_d>;fe}FC?{rwPG>>=pBG_M~an@iiBsplUfi(B75qUKMK?ZdsZ z--jW6#lz>P$PH+J^7$FE*u#+b&?Z)#yYn}`3;uJc1??kV{TB&)1a7=GvEuLXPV}h% zOJr-roPUKZ_9zr{_%*V3(-u96nZup_4RlP>C&PaW9iMdX{X57S@lE=D!o;Q6-9I2} q^91%sWHFy}V1G)OJKoRx?tAoS$awv=+i#iv?9G0(|CcOFq5lCYGEJEP diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp index 6a3bd916..af3b46e1 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp @@ -115,6 +115,7 @@ namespace SHADE SHAssetManager::CompileAsset("../../Assets/Shaders/TestCube_FS.glsl"); SHAssetManager::CompileAsset("../../Assets/Shaders/DeferredComposite_CS.glsl"); SHAssetManager::CompileAsset("../../Assets/Shaders/SSAO_CS.glsl"); + SHAssetManager::CompileAsset("../../Assets/Shaders/SSAOBlur_CS.glsl"); shaderModuleLibrary.ImportAllShaderSource(device); shaderModuleLibrary.ReflectAllShaderModules(); @@ -169,7 +170,8 @@ namespace SHADE worldRenderGraph->AddResource("Entity ID", { SH_ATT_DESC_TYPE_FLAGS::COLOR }, windowDims.first, windowDims.second, vk::Format::eR32Uint, 1, vk::ImageUsageFlagBits::eTransferSrc); worldRenderGraph->AddResource("Light Layer Indices", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second, vk::Format::eR32Uint, 1, vk::ImageUsageFlagBits::eTransferSrc); worldRenderGraph->AddResource("Scene", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second); - worldRenderGraph->AddResource("SSAO", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second, vk::Format::eR32G32B32A32Sfloat); + worldRenderGraph->AddResource("SSAO", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second, vk::Format::eR8Unorm); + worldRenderGraph->AddResource("SSAO Blur", { SH_ATT_DESC_TYPE_FLAGS::COLOR, SH_ATT_DESC_TYPE_FLAGS::INPUT, SH_ATT_DESC_TYPE_FLAGS::STORAGE }, windowDims.first, windowDims.second, vk::Format::eR8Unorm); /*-----------------------------------------------------------------------*/ /* MAIN NODE */ @@ -184,7 +186,8 @@ namespace SHADE "Albedo", "Depth Buffer", "Scene", - "SSAO" + "SSAO", + "SSAO Blur" }, {}); // no predecessors @@ -225,12 +228,15 @@ namespace SHADE auto viewSamplerLayout = ssaoStorage->GetViewSamplerLayout(); ssaoPass->ModifyWriteDescImageComputeResource(SHGraphicsConstants::DescriptorSetIndex::RENDERGRAPH_NODE_COMPUTE_RESOURCE, SHSSAO::DESC_SET_IMAGE_BINDING, {&viewSamplerLayout, 1}); + auto ssaoBlurShader = shaderModuleLibrary.GetBuiltInShaderModule("SSAOBlur_CS"); + Handle ssaoBlurPass = gBufferNode->AddNodeCompute(ssaoBlurShader, { "SSAO", "SSAO Blur"}); + /*-----------------------------------------------------------------------*/ /* DEFERRED COMPOSITE SUBPASS INIT */ /*-----------------------------------------------------------------------*/ auto deferredCompositeShader = shaderModuleLibrary.GetBuiltInShaderModule("DeferredComposite_CS"); - gBufferNode->AddNodeCompute(deferredCompositeShader, { "Position", "Normals", "Albedo", "Light Layer Indices", "SSAO", "Scene" }); + gBufferNode->AddNodeCompute(deferredCompositeShader, { "Position", "Normals", "Albedo", "Light Layer Indices", "SSAO Blur", "Scene" }); /*-----------------------------------------------------------------------*/ /* DUMMY SUBPASS TO TRANSITION SCENE FOR PRESENT USAGE */ From 674b4d5155e70751f54dbba888649de5a4473e01 Mon Sep 17 00:00:00 2001 From: Kah Wei Date: Tue, 1 Nov 2022 20:29:03 +0800 Subject: [PATCH 16/27] Fixed extra # appearing on all names of script variables --- SHADE_Engine/src/Editor/SHEditorUI.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/SHADE_Engine/src/Editor/SHEditorUI.cpp b/SHADE_Engine/src/Editor/SHEditorUI.cpp index f3760b4d..cc63c565 100644 --- a/SHADE_Engine/src/Editor/SHEditorUI.cpp +++ b/SHADE_Engine/src/Editor/SHEditorUI.cpp @@ -157,7 +157,7 @@ namespace SHADE if (isHovered) *isHovered = ImGui::IsItemHovered(); ImGui::SameLine(); - return ImGui::Checkbox("#", &value); + return ImGui::Checkbox("##", &value); } bool SHEditorUI::InputInt(const std::string& label, int& value, bool* isHovered) { @@ -165,7 +165,7 @@ namespace SHADE if (isHovered) *isHovered = ImGui::IsItemHovered(); ImGui::SameLine(); - return ImGui::InputInt("#", &value, + return ImGui::InputInt("##", &value, 1, 10, ImGuiInputTextFlags_EnterReturnsTrue); } @@ -176,7 +176,7 @@ namespace SHADE if (isHovered) *isHovered = ImGui::IsItemHovered(); ImGui::SameLine(); - const bool CHANGED = InputInt("#", signedVal); + const bool CHANGED = InputInt("##", signedVal); if (CHANGED) { signedVal = std::clamp(signedVal, 0, std::numeric_limits::max()); @@ -190,7 +190,7 @@ namespace SHADE if (isHovered) *isHovered = ImGui::IsItemHovered(); ImGui::SameLine(); - return ImGui::InputFloat("#", &value, + return ImGui::InputFloat("##", &value, 0.1f, 1.0f, "%.3f", ImGuiInputTextFlags_EnterReturnsTrue); } @@ -200,7 +200,7 @@ namespace SHADE if (isHovered) *isHovered = ImGui::IsItemHovered(); ImGui::SameLine(); - return ImGui::InputDouble("#", &value, + return ImGui::InputDouble("##", &value, 0.1, 1.0, "%.3f", ImGuiInputTextFlags_EnterReturnsTrue); } @@ -210,7 +210,7 @@ namespace SHADE if (isHovered) *isHovered = ImGui::IsItemHovered(); ImGui::SameLine(); - return ImGui::InputDouble("#", &value, + return ImGui::InputDouble("##", &value, 1.0, 45.0, "%.3f", ImGuiInputTextFlags_EnterReturnsTrue); } @@ -280,7 +280,7 @@ namespace SHADE if (isHovered) *isHovered = ImGui::IsItemHovered(); ImGui::SameLine(); - const bool CHANGED = ImGui::InputText("#", &buffer[0], TEXT_FIELD_MAX_LENGTH); + const bool CHANGED = ImGui::InputText("##", &buffer[0], TEXT_FIELD_MAX_LENGTH); if (CHANGED) { value = std::string(buffer.data(), buffer.data() + TEXT_FIELD_MAX_LENGTH); @@ -327,7 +327,7 @@ namespace SHADE if (isHovered) *isHovered = ImGui::IsItemHovered(); ImGui::SameLine(); - if (ImGui::BeginCombo("#", INITIAL_NAME.c_str(), ImGuiComboFlags_None)) + if (ImGui::BeginCombo("##", INITIAL_NAME.c_str(), ImGuiComboFlags_None)) { for (int i = 0; i < enumNames.size(); ++i) { From 1371302a40602daba1c94f10a4e819521b6fd192 Mon Sep 17 00:00:00 2001 From: Kah Wei Date: Wed, 2 Nov 2022 09:34:36 +0800 Subject: [PATCH 17/27] Generalised Draw functions in SHDebugDrawSystem for potentially any number of draw queues --- .../MiddleEnd/Interface/SHDebugDrawSystem.cpp | 89 ++++++++++++------- .../MiddleEnd/Interface/SHDebugDrawSystem.h | 11 +++ .../MiddleEnd/Interface/SHDebugDrawSystem.hpp | 13 ++- 3 files changed, 77 insertions(+), 36 deletions(-) diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.cpp index 08019665..715b7d69 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.cpp @@ -117,54 +117,75 @@ namespace SHADE /*---------------------------------------------------------------------------------*/ void SHDebugDrawSystem::DrawLine(const SHVec4& color, const SHVec3& startPt, const SHVec3& endPt) { - if (points.size() > MAX_POINTS) + drawLine(points, color, startPt, endPt); + } + + void SHDebugDrawSystem::DrawTri(const SHVec4& color, const SHVec3& pt1, const SHVec3& pt2, const SHVec3& pt3) + { + drawPoly(points, color, { pt1, pt2, pt3 }); + } + + void SHDebugDrawSystem::DrawQuad(const SHVec4& color, const SHVec3& pt1, const SHVec3& pt2, const SHVec3& pt3, const SHVec3& pt4) + { + drawPoly(points, color, { pt1, pt2, pt3, pt4 }); + } + + void SHDebugDrawSystem::DrawPoly(const SHVec4& color, std::initializer_list pointList) + { + drawPoly(points, color, pointList.begin(), pointList.end()); + } + + void SHDebugDrawSystem::DrawCube(const SHVec4& color, const SHVec3& pos, const SHVec3& size) + { + drawCube(points, color, pos, size); + } + + void SHDebugDrawSystem::DrawSphere(const SHVec4& color, const SHVec3& pos, double radius) + { + drawSphere(points, color, pos, radius); + } + + void SHDebugDrawSystem::drawLine(std::vector& storage, const SHVec4& color, const SHVec3& startPt, const SHVec3& endPt) + { + if (storage.size() > MAX_POINTS) { SHLOG_WARNING("[DebugDraw] Exceeded maximum size of drawable debug elements."); return; } - points.emplace_back(PointVertex{ startPt, color }); - points.emplace_back(PointVertex{ endPt, color }); + storage.emplace_back(PointVertex{ startPt, color }); + storage.emplace_back(PointVertex{ endPt, color }); } - void SHDebugDrawSystem::DrawTri(const SHVec4& color, const SHVec3& pt1, const SHVec3& pt2, const SHVec3& pt3) + void SHDebugDrawSystem::drawPoly(std::vector& storage, const SHVec4& color, std::initializer_list pointList) { - DrawPoly(color, { pt1, pt2, pt3 }); + drawPoly(storage, color, pointList.begin(), pointList.end()); } - void SHDebugDrawSystem::DrawQuad(const SHVec4& color, const SHVec3& pt1, const SHVec3& pt2, const SHVec3& pt3, const SHVec3& pt4) + void SHDebugDrawSystem::drawCube(std::vector& storage, const SHVec4& color, const SHVec3& pos, const SHVec3& size) { - DrawPoly(color, { pt1, pt2, pt3, pt4 }); - } + static const SHVec3 EXTENTS = SHVec3{ 0.5f, 0.5f, 0.5f }; + static const SHVec3 UNIT_BOT_LEFT_FRONT = SHVec3{ pos - EXTENTS }; + static const SHVec3 UNIT_BOT_RIGHT_FRONT = SHVec3{ pos + SHVec3 { EXTENTS.x, -EXTENTS.y, -EXTENTS.z } }; + static const SHVec3 UNIT_BOT_RIGHT_BACK = SHVec3{ pos + SHVec3 { EXTENTS.x, -EXTENTS.y, EXTENTS.z } }; + static const SHVec3 UNIT_BOT_LEFT_BACK = SHVec3{ pos + SHVec3 { -EXTENTS.x, -EXTENTS.y, EXTENTS.z } }; + static const SHVec3 UNIT_TOP_LEFT_BACK = SHVec3{ pos + SHVec3 { -EXTENTS.x, EXTENTS.y, EXTENTS.z } }; + static const SHVec3 UNIT_TOP_RIGHT_FRONT = SHVec3{ pos + SHVec3 { EXTENTS.x, EXTENTS.y, -EXTENTS.z } }; + static const SHVec3 UNIT_TOP_LEFT_FRONT = SHVec3{ pos + SHVec3 { -EXTENTS.x, EXTENTS.y, -EXTENTS.z } }; + static const SHVec3 UNIT_TOP_RIGHT_BACK = SHVec3{ pos + EXTENTS }; - void SHDebugDrawSystem::DrawPoly(const SHVec4& color, std::initializer_list pointList) - { - DrawPoly(color, pointList.begin(), pointList.end()); - } - - void SHDebugDrawSystem::DrawCube(const SHVec4& color, const SHVec3& pos, const SHVec3& size) - { - static const SHVec3 EXTENTS = SHVec3 { 0.5f, 0.5f, 0.5f }; - static const SHVec3 UNIT_BOT_LEFT_FRONT = SHVec3 { pos - EXTENTS }; - static const SHVec3 UNIT_BOT_RIGHT_FRONT = SHVec3 { pos + SHVec3 { EXTENTS.x, -EXTENTS.y, -EXTENTS.z } }; - static const SHVec3 UNIT_BOT_RIGHT_BACK = SHVec3 { pos + SHVec3 { EXTENTS.x, -EXTENTS.y, EXTENTS.z } }; - static const SHVec3 UNIT_BOT_LEFT_BACK = SHVec3 { pos + SHVec3 { -EXTENTS.x, -EXTENTS.y, EXTENTS.z } }; - static const SHVec3 UNIT_TOP_LEFT_BACK = SHVec3 { pos + SHVec3 { -EXTENTS.x, EXTENTS.y, EXTENTS.z } }; - static const SHVec3 UNIT_TOP_RIGHT_FRONT = SHVec3 { pos + SHVec3 { EXTENTS.x, EXTENTS.y, -EXTENTS.z } }; - static const SHVec3 UNIT_TOP_LEFT_FRONT = SHVec3 { pos + SHVec3 { -EXTENTS.x, EXTENTS.y, -EXTENTS.z } }; - static const SHVec3 UNIT_TOP_RIGHT_BACK = SHVec3 { pos + EXTENTS }; - - const SHVec3 BOT_LEFT_BACK = UNIT_BOT_LEFT_BACK * size; - const SHVec3 BOT_RIGHT_BACK = UNIT_BOT_RIGHT_BACK * size; - const SHVec3 BOT_LEFT_FRONT = UNIT_BOT_LEFT_FRONT * size; + const SHVec3 BOT_LEFT_BACK = UNIT_BOT_LEFT_BACK * size; + const SHVec3 BOT_RIGHT_BACK = UNIT_BOT_RIGHT_BACK * size; + const SHVec3 BOT_LEFT_FRONT = UNIT_BOT_LEFT_FRONT * size; const SHVec3 BOT_RIGHT_FRONT = UNIT_BOT_RIGHT_FRONT * size; - const SHVec3 TOP_LEFT_BACK = UNIT_TOP_LEFT_BACK * size; - const SHVec3 TOP_RIGHT_BACK = UNIT_TOP_RIGHT_BACK * size; - const SHVec3 TOP_LEFT_FRONT = UNIT_TOP_LEFT_FRONT * size; + const SHVec3 TOP_LEFT_BACK = UNIT_TOP_LEFT_BACK * size; + const SHVec3 TOP_RIGHT_BACK = UNIT_TOP_RIGHT_BACK * size; + const SHVec3 TOP_LEFT_FRONT = UNIT_TOP_LEFT_FRONT * size; const SHVec3 TOP_RIGHT_FRONT = UNIT_TOP_RIGHT_FRONT * size; - DrawPoly + drawPoly ( + storage, color, { // Bottom Square @@ -186,7 +207,7 @@ namespace SHADE ); } - void SHDebugDrawSystem::DrawSphere(const SHVec4& color, const SHVec3& pos, double radius) + void SHDebugDrawSystem::drawSphere(std::vector& storage, const SHVec4& color, const SHVec3& pos, double radius) { if (spherePoints.empty()) { @@ -197,6 +218,6 @@ namespace SHADE spherePoints.emplace_back(SPHERE.VertexPositions[idx]); } } - DrawPoly(color, spherePoints.begin(), spherePoints.end()); + drawPoly(storage, color, spherePoints.begin(), spherePoints.end()); } } \ No newline at end of file diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.h b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.h index 4b83958d..41a0dd77 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.h @@ -148,11 +148,22 @@ namespace SHADE /*---------------------------------------------------------------------------------*/ // CPU Buffers std::vector points; + std::vector persistentPoints; // GPU Buffers TripleBuffer vertexBuffers; TripleUInt numPoints; // Cached Points for polygon drawing std::vector spherePoints; + + /*---------------------------------------------------------------------------------*/ + /* Helper Draw Functions */ + /*---------------------------------------------------------------------------------*/ + void drawLine(std::vector& storage, const SHVec4& color, const SHVec3& startPt, const SHVec3& endPt); + void drawPoly(std::vector& storage, const SHVec4& color, std::initializer_list pointList); + template + void drawPoly(std::vector& storage, const SHVec4& color, IterType pointListBegin, IterType pointListEnd); + void drawCube(std::vector& storage, const SHVec4& color, const SHVec3& pos, const SHVec3& size); + void drawSphere(std::vector& storage, const SHVec4& color, const SHVec3& pos, double radius); }; } diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.hpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.hpp index 14fbb42f..953b1cb3 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.hpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.hpp @@ -20,12 +20,21 @@ namespace SHADE /*-----------------------------------------------------------------------------------*/ template void SHDebugDrawSystem::DrawPoly(const SHVec4& color, IterType pointListBegin, IterType pointListEnd) + { + drawPoly(points, color, pointListBegin, pointListEnd); + } + + /*-----------------------------------------------------------------------------------*/ + /* Helper Draw Functions */ + /*-----------------------------------------------------------------------------------*/ + template + void SHDebugDrawSystem::drawPoly(std::vector& storage, const SHVec4& color, IterType pointListBegin, IterType pointListEnd) { // Ensure dereferenced type is SHVec3 static_assert(std::is_same_v>, "Parameters to DrawPoly must be SHVec3."); // Check if points exceeded max - if (points.size() > MAX_POINTS) + if (storage.size() > MAX_POINTS) { SHLOG_WARNING("[DebugDraw] Exceeded maximum size of drawable debug elements."); return; @@ -42,7 +51,7 @@ namespace SHADE const size_t POINTS_ROUNDED_COUNT = POINTS_COUNT / 2 * 2; for (auto pointIter = pointListBegin; pointIter != (pointListBegin + POINTS_ROUNDED_COUNT); ++pointIter) { - points.emplace_back(PointVertex{ *pointIter, color }); + storage.emplace_back(PointVertex{ *pointIter, color }); } } } \ No newline at end of file From 41e1f01f29174fbfaa8cc700bbef9e79b07e5173 Mon Sep 17 00:00:00 2001 From: Kah Wei Date: Wed, 2 Nov 2022 10:06:39 +0800 Subject: [PATCH 18/27] Added support for persistent debug draw --- .../src/Application/SBApplication.cpp | 4 + .../MiddleEnd/Interface/SHDebugDrawSystem.cpp | 126 +++++++++++++++--- .../MiddleEnd/Interface/SHDebugDrawSystem.h | 85 +++++++++++- SHADE_Engine/src/Tools/SHDebugDraw.cpp | 38 +++++- SHADE_Engine/src/Tools/SHDebugDraw.h | 58 ++++++++ 5 files changed, 291 insertions(+), 20 deletions(-) diff --git a/SHADE_Application/src/Application/SBApplication.cpp b/SHADE_Application/src/Application/SBApplication.cpp index b865f028..8b437584 100644 --- a/SHADE_Application/src/Application/SBApplication.cpp +++ b/SHADE_Application/src/Application/SBApplication.cpp @@ -146,6 +146,10 @@ namespace Sandbox if(editor->editorState == SHEditor::State::PLAY) SHSceneManager::SceneUpdate(0.016f); #endif + SHDebugDraw::Line(SHVec4(1.0f, 1.0f, 1.0f, 1.0f), SHVec3(-5.0f, 0.0f, 0.0f), SHVec3(5.0f, 0.0f, 0.0f)); + SHDebugDraw::Line(SHVec4(1.0f, 1.0f, 1.0f, 1.0f), SHVec3(-5.0f, 1.0f, 0.0f), SHVec3(5.0f, 1.0f, 0.0f)); + SHDebugDraw::Cube(SHVec4(1.0f, 1.0f, 1.0f, 1.0f), {}, SHVec3(1.0f, 1.0f, 1.0f)); + SHDebugDraw::Sphere(SHVec4(1.0f, 1.0f, 1.0f, 1.0f), {}, 3.0f); SHSystemManager::RunRoutines(editor->editorState != SHEditor::State::PLAY, 0.016f); editor->PollPicking(); } diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.cpp index 715b7d69..16069564 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.cpp @@ -43,20 +43,41 @@ namespace SHADE return; } + // Get the system + SHDebugDrawSystem* system = static_cast(GetSystem()); + // Get current frame index const uint32_t FRAME_IDX = gfxSys->GetCurrentFrameIndex(); - // Create the buffer if it doesn't exist or just update it - SHDebugDrawSystem* system = static_cast(GetSystem()); + /* Non-Persistent Buffer */ + // Update the buffer system->numPoints[FRAME_IDX] = system->points.size(); const uint32_t DATA_SIZE = sizeof(PointVertex) * system->points.size(); if (DATA_SIZE > 0) { - system->vertexBuffers[FRAME_IDX]->WriteToMemory(system->points.data(), DATA_SIZE, 0, 0); + system->vertexBuffers[FRAME_IDX]->WriteToMemory(system->points.data(), DATA_SIZE, 0, 0); } // Reset for next frame system->points.clear(); + + /* Persistent Buffer */ + // Check if there are changes + if (system->persistentBuffersCleared[FRAME_IDX] + || + system->numPersistentPoints[FRAME_IDX] != system->persistentPoints.size()) + { + // Update Buffer + system->numPersistentPoints[FRAME_IDX] = system->persistentPoints.size(); + const uint32_t DATA_SIZE = sizeof(PointVertex) * system->persistentPoints.size(); + if (DATA_SIZE > 0) + { + system->persistentVertexBuffers[FRAME_IDX]->WriteToMemory(system->persistentPoints.data(), DATA_SIZE, 0, 0); + } + + // Reset Flag + system->persistentBuffersCleared[FRAME_IDX] = false; + } } /*---------------------------------------------------------------------------------*/ @@ -74,32 +95,56 @@ namespace SHADE // Get Current frame index const uint32_t FRAME_IDX = GFX_SYSTEM->GetCurrentFrameIndex(); - // Don't draw if no points - if (numPoints[FRAME_IDX] <= 0) - return; - + // Set Pipeline cmdBuffer->BindPipeline(GFX_SYSTEM->GetDebugDrawPipeline()); cmdBuffer->SetLineWidth(LineWidth); - cmdBuffer->BindVertexBuffer(0, vertexBuffers[FRAME_IDX], 0); - cmdBuffer->DrawArrays(numPoints[FRAME_IDX], 1, 0, 0); + + // Don't draw if no points + if (numPoints[FRAME_IDX] > 0) + { + cmdBuffer->BindVertexBuffer(0, vertexBuffers[FRAME_IDX], 0); + cmdBuffer->DrawArrays(numPoints[FRAME_IDX], 1, 0, 0); + } + if (numPersistentPoints[FRAME_IDX] > 0) + { + cmdBuffer->BindVertexBuffer(0, persistentVertexBuffers[FRAME_IDX], 0); + cmdBuffer->DrawArrays(numPersistentPoints[FRAME_IDX], 1, 0, 0); + } }); // Reset trackers std::fill_n(numPoints.begin(), numPoints.size(), 0); + std::fill_n(numPersistentPoints.begin(), numPersistentPoints.size(), 0); + for (bool& cleared : persistentBuffersCleared) + cleared = true; // Allocate buffers + // - Non-Persistent Draws static constexpr uint32_t BUFFER_SIZE = MAX_POINTS * sizeof(PointVertex); for (Handle& bufHandle : vertexBuffers) { - bufHandle = GFX_SYSTEM->GetDevice()->CreateBuffer - ( - BUFFER_SIZE, - nullptr, - 0, - vk::BufferUsageFlagBits::eVertexBuffer, - VmaMemoryUsage::VMA_MEMORY_USAGE_AUTO, - VmaAllocationCreateFlagBits::VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VmaAllocationCreateFlagBits::VMA_ALLOCATION_CREATE_MAPPED_BIT - ); + bufHandle = GFX_SYSTEM->GetDevice()->CreateBuffer + ( + BUFFER_SIZE, + nullptr, + 0, + vk::BufferUsageFlagBits::eVertexBuffer, + VmaMemoryUsage::VMA_MEMORY_USAGE_AUTO, + VmaAllocationCreateFlagBits::VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VmaAllocationCreateFlagBits::VMA_ALLOCATION_CREATE_MAPPED_BIT + ); + } + // - Persistent Draws + for (Handle& bufHandle : persistentVertexBuffers) + { + bufHandle = GFX_SYSTEM->GetDevice()->CreateBuffer + ( + BUFFER_SIZE, + nullptr, + 0, + vk::BufferUsageFlagBits::eVertexBuffer, + VmaMemoryUsage::VMA_MEMORY_USAGE_AUTO, + VmaAllocationCreateFlagBits::VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VmaAllocationCreateFlagBits::VMA_ALLOCATION_CREATE_MAPPED_BIT + ); } } @@ -110,6 +155,11 @@ namespace SHADE if (vertexBuffer) vertexBuffer.Free(); } + for (auto vertexBuffer : persistentVertexBuffers) + { + if (vertexBuffer) + vertexBuffer.Free(); + } } /*---------------------------------------------------------------------------------*/ @@ -145,6 +195,46 @@ namespace SHADE drawSphere(points, color, pos, radius); } + /*---------------------------------------------------------------------------------*/ + /* Persistent Draw Functions */ + /*---------------------------------------------------------------------------------*/ + void SHDebugDrawSystem::DrawPersistentLine(const SHVec4& color, const SHVec3& startPt, const SHVec3& endPt) + { + drawLine(persistentPoints, color, startPt, endPt); + } + + void SHDebugDrawSystem::DrawPersistentTri(const SHVec4& color, const SHVec3& pt1, const SHVec3& pt2, const SHVec3& pt3) + { + drawPoly(persistentPoints, color, { pt1, pt2, pt3 }); + } + + void SHDebugDrawSystem::DrawPersistentQuad(const SHVec4& color, const SHVec3& pt1, const SHVec3& pt2, const SHVec3& pt3, const SHVec3& pt4) + { + drawPoly(persistentPoints, color, { pt1, pt2, pt3, pt4 }); + } + + void SHDebugDrawSystem::DrawPersistentPoly(const SHVec4& color, std::initializer_list pointList) + { + drawPoly(persistentPoints, color, pointList.begin(), pointList.end()); + } + + void SHDebugDrawSystem::DrawPersistentCube(const SHVec4& color, const SHVec3& pos, const SHVec3& size) + { + drawCube(persistentPoints, color, pos, size); + } + + void SHDebugDrawSystem::DrawPersistentSphere(const SHVec4& color, const SHVec3& pos, double radius) + { + drawSphere(persistentPoints, color, pos, radius); + } + + void SHDebugDrawSystem::ClearPersistentDraws() + { + persistentPoints.clear(); + for (bool& cleared : persistentBuffersCleared) + cleared = true; + } + void SHDebugDrawSystem::drawLine(std::vector& storage, const SHVec4& color, const SHVec3& startPt, const SHVec3& endPt) { if (storage.size() > MAX_POINTS) diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.h b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.h index 41a0dd77..7c9e7c81 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.h @@ -126,6 +126,78 @@ namespace SHADE /// Size of the rendered sphere. void DrawSphere(const SHVec4& color, const SHVec3& pos, double radius); + /*---------------------------------------------------------------------------------*/ + /* Persistent Draw Functions */ + /*---------------------------------------------------------------------------------*/ + /// + /// Renders a line between two points in world space that will persist until + /// ClearPersistentDraws() is called. + /// + /// Colour of the line. + /// First point of the line. + /// Second point of the line. + void DrawPersistentLine(const SHVec4& color, const SHVec3& startPt, const SHVec3& endPt); + /// + /// Renders a triangle indicated by three points in world space that will persist + /// until ClearPersistentDraws() is called. + /// + /// Colour of the triangle. + /// First point of the triangle. + /// Second point of the triangle. + /// Third point of the triangle. + void DrawPersistentTri(const SHVec4& color, const SHVec3& pt1, const SHVec3& pt2, const SHVec3& pt3); + /// + /// Renders a quadrilateral indicated by four points in world space that will persist + /// until ClearPersistentDraws() is called. + /// + /// Colour of the quadrilateral. + /// First point of the triangle. + /// Second point of the quadrilateral. + /// Third point of the quadrilateral. + /// Third point of the quadrilateral. + void DrawPersistentQuad(const SHVec4& color, const SHVec3& pt1, const SHVec3& pt2, const SHVec3& pt3, const SHVec3& pt4); + /// + /// Renders a polygon indicated by the specified set of points in world space that + /// will persist until ClearPersistentDraws() is called. + /// + /// Colour of the polygon. + /// List of points for the polygon. + void DrawPersistentPoly(const SHVec4& color, std::initializer_list pointList); + /// + /// Renders a polygon indicated by the specified set of points in world space that + /// will persist until ClearPersistentDraws() is called. + /// + /// Iterator for a STL-like container. + /// Colour of the polygon. + /// + /// Iterator to the first point of the point container. + /// + /// + /// One past last iterator of the point container. + /// + template + void DrawPersistentPoly(const SHVec4& color, IterType pointListBegin, IterType pointListEnd); + /// + /// Renders a wireframe cube centered around the position specified in world space + /// that will persist until ClearPersistentDraws() is called. + /// + /// Colour of the cube. + /// Position where the cube wil be centered at. + /// Size of the rendered cube. + void DrawPersistentCube(const SHVec4& color, const SHVec3& pos, const SHVec3& size); + /// + /// Renders a wireframe sphere centered around the position specified in world space + /// that will persist until ClearPersistentDraws() is called. + /// + /// Colour of the sphere. + /// Position where the sphere wil be centered at. + /// Size of the rendered sphere. + void DrawPersistentSphere(const SHVec4& color, const SHVec3& pos, double radius); + /// + /// Clears any persistent drawn debug primitives. + /// + void ClearPersistentDraws(); + private: /*---------------------------------------------------------------------------------*/ /* Type Definitions */ @@ -136,7 +208,8 @@ namespace SHADE SHVec4 Color; }; using TripleBuffer = std::array, SHGraphicsConstants::NUM_FRAME_BUFFERS>; - using TripleUInt = std::array; + using TripleUInt = std::array; + using TripleBool = std::array; /*---------------------------------------------------------------------------------*/ /* Constants */ @@ -152,6 +225,9 @@ namespace SHADE // GPU Buffers TripleBuffer vertexBuffers; TripleUInt numPoints; + TripleBuffer persistentVertexBuffers; + TripleUInt numPersistentPoints; + TripleBool persistentBuffersCleared; // Cached Points for polygon drawing std::vector spherePoints; @@ -165,6 +241,13 @@ namespace SHADE void drawCube(std::vector& storage, const SHVec4& color, const SHVec3& pos, const SHVec3& size); void drawSphere(std::vector& storage, const SHVec4& color, const SHVec3& pos, double radius); }; + + template + void SHADE::SHDebugDrawSystem::DrawPersistentPoly(const SHVec4& color, IterType pointListBegin, IterType pointListEnd) + { + + } + } #include "SHDebugDrawSystem.hpp" \ No newline at end of file diff --git a/SHADE_Engine/src/Tools/SHDebugDraw.cpp b/SHADE_Engine/src/Tools/SHDebugDraw.cpp index a5b86c42..b8aa8b0e 100644 --- a/SHADE_Engine/src/Tools/SHDebugDraw.cpp +++ b/SHADE_Engine/src/Tools/SHDebugDraw.cpp @@ -25,7 +25,7 @@ namespace SHADE /* Static Member Definitions */ /*-----------------------------------------------------------------------------------*/ SHDebugDrawSystem* SHDebugDraw::dbgDrawSys = nullptr; - + /*-----------------------------------------------------------------------------------*/ /* Lifecycle Functions */ /*-----------------------------------------------------------------------------------*/ @@ -70,4 +70,40 @@ namespace SHADE { dbgDrawSys->DrawSphere(color, pos, radius); } + + void SHDebugDraw::PersistentLine(const SHVec4& color, const SHVec3& startPt, const SHVec3& endPt) + { + dbgDrawSys->DrawPersistentLine(color, startPt, endPt); + } + + void SHDebugDraw::PersistentTri(const SHVec4& color, const SHVec3& pt1, const SHVec3& pt2, const SHVec3& pt3) + { + dbgDrawSys->DrawPersistentTri(color, pt1, pt2, pt3); + } + + void SHDebugDraw::PersistentQuad(const SHVec4& color, const SHVec3& pt1, const SHVec3& pt2, const SHVec3& pt3, const SHVec3& pt4) + { + dbgDrawSys->DrawPersistentQuad(color, pt1, pt2, pt3, pt4); + } + + void SHDebugDraw::PersistentPoly(const SHVec4& color, std::initializer_list pointList) + { + dbgDrawSys->DrawPersistentPoly(color, pointList); + } + + void SHDebugDraw::PersistentCube(const SHVec4& color, const SHVec3& pos, const SHVec3& size) + { + dbgDrawSys->DrawPersistentCube(color, pos, size); + } + + void SHDebugDraw::PersistentSphere(const SHVec4& color, const SHVec3& pos, double radius) + { + dbgDrawSys->DrawPersistentSphere(color, pos, radius); + } + + void SHDebugDraw::ClearPersistentDraws() + { + dbgDrawSys->ClearPersistentDraws(); + } + } \ No newline at end of file diff --git a/SHADE_Engine/src/Tools/SHDebugDraw.h b/SHADE_Engine/src/Tools/SHDebugDraw.h index 7ce44ec2..04504c3a 100644 --- a/SHADE_Engine/src/Tools/SHDebugDraw.h +++ b/SHADE_Engine/src/Tools/SHDebugDraw.h @@ -92,6 +92,64 @@ namespace SHADE /// Size of the rendered sphere. static void Sphere(const SHVec4& color, const SHVec3& pos, double radius); + /*---------------------------------------------------------------------------------*/ + /* Persistent Draw Functions */ + /*---------------------------------------------------------------------------------*/ + /// + /// Renders a line between two points in world space that will persist until + /// ClearPersistentDraws() is called. + /// + /// Colour of the line. + /// First point of the line. + /// Second point of the line. + static void PersistentLine(const SHVec4& color, const SHVec3& startPt, const SHVec3& endPt); + /// + /// Renders a triangle indicated by three points in world space that will persist + /// until ClearPersistentDraws() is called. + /// + /// Colour of the triangle. + /// First point of the triangle. + /// Second point of the triangle. + /// Third point of the triangle. + static void PersistentTri(const SHVec4& color, const SHVec3& pt1, const SHVec3& pt2, const SHVec3& pt3); + /// + /// Renders a quadrilateral indicated by four points in world space that will persist + /// until ClearPersistentDraws() is called. + /// + /// Colour of the quadrilateral. + /// First point of the triangle. + /// Second point of the quadrilateral. + /// Third point of the quadrilateral. + /// Third point of the quadrilateral. + static void PersistentQuad(const SHVec4& color, const SHVec3& pt1, const SHVec3& pt2, const SHVec3& pt3, const SHVec3& pt4); + /// + /// Renders a polygon indicated by the specified set of points in world space that + /// will persist until ClearPersistentDraws() is called. + /// + /// Colour of the polygon. + /// List of points for the polygon. + static void PersistentPoly(const SHVec4& color, std::initializer_list pointList); + /// + /// Renders a wireframe cube centered around the position specified in world space + /// that will persist until ClearPersistentDraws() is called. + /// + /// Colour of the cube. + /// Position where the cube wil be centered at. + /// Size of the rendered cube. + static void PersistentCube(const SHVec4& color, const SHVec3& pos, const SHVec3& size); + /// + /// Renders a wireframe sphere centered around the position specified in world space + /// that will persist until ClearPersistentDraws() is called. + /// + /// Colour of the sphere. + /// Position where the sphere wil be centered at. + /// Size of the rendered sphere. + static void PersistentSphere(const SHVec4& color, const SHVec3& pos, double radius); + /// + /// Clears any persistent drawn debug primitives. + /// + static void ClearPersistentDraws(); + private: /*---------------------------------------------------------------------------------*/ /* Static Data Members */ From 82e0e4df5ce8ec81619bd1463e3ec94dce216c71 Mon Sep 17 00:00:00 2001 From: Kah Wei Date: Wed, 2 Nov 2022 10:33:17 +0800 Subject: [PATCH 19/27] Added editor gridlines and cardinal axes --- .../src/Application/SBApplication.cpp | 10 +- SHADE_Engine/src/Editor/SHEditor.cpp | 104 +++++++++++++++++- SHADE_Engine/src/Editor/SHEditor.h | 9 +- .../MiddleEnd/Interface/SHDebugDrawSystem.cpp | 2 +- 4 files changed, 114 insertions(+), 11 deletions(-) diff --git a/SHADE_Application/src/Application/SBApplication.cpp b/SHADE_Application/src/Application/SBApplication.cpp index 8b437584..10cc09b3 100644 --- a/SHADE_Application/src/Application/SBApplication.cpp +++ b/SHADE_Application/src/Application/SBApplication.cpp @@ -72,6 +72,9 @@ namespace Sandbox SHSystemManager::CreateSystem(); SHSystemManager::CreateSystem(); SHSystemManager::CreateSystem(); + + // Link up SHDebugDraw + SHDebugDraw::Init(SHSystemManager::GetSystem()); #ifdef SHEDITOR SDL_Init(SDL_INIT_VIDEO); @@ -127,9 +130,6 @@ namespace Sandbox SHSceneManager::InitSceneManager("TestScene"); SHFrameRateController::UpdateFRC(); - - // Link up SHDebugDraw - SHDebugDraw::Init(SHSystemManager::GetSystem()); } void SBApplication::Update(void) @@ -146,10 +146,6 @@ namespace Sandbox if(editor->editorState == SHEditor::State::PLAY) SHSceneManager::SceneUpdate(0.016f); #endif - SHDebugDraw::Line(SHVec4(1.0f, 1.0f, 1.0f, 1.0f), SHVec3(-5.0f, 0.0f, 0.0f), SHVec3(5.0f, 0.0f, 0.0f)); - SHDebugDraw::Line(SHVec4(1.0f, 1.0f, 1.0f, 1.0f), SHVec3(-5.0f, 1.0f, 0.0f), SHVec3(5.0f, 1.0f, 0.0f)); - SHDebugDraw::Cube(SHVec4(1.0f, 1.0f, 1.0f, 1.0f), {}, SHVec3(1.0f, 1.0f, 1.0f)); - SHDebugDraw::Sphere(SHVec4(1.0f, 1.0f, 1.0f, 1.0f), {}, 3.0f); SHSystemManager::RunRoutines(editor->editorState != SHEditor::State::PLAY, 0.016f); editor->PollPicking(); } diff --git a/SHADE_Engine/src/Editor/SHEditor.cpp b/SHADE_Engine/src/Editor/SHEditor.cpp index cf5056a5..6259a7c6 100644 --- a/SHADE_Engine/src/Editor/SHEditor.cpp +++ b/SHADE_Engine/src/Editor/SHEditor.cpp @@ -46,6 +46,7 @@ #include #include "Graphics/MiddleEnd/Interface/SHMousePickSystem.h" +#include "Tools/SHDebugDraw.h" RTTR_REGISTRATION { @@ -77,7 +78,6 @@ namespace SHADE //#==============================================================# void SHEditor::Init() { - IMGUI_CHECKVERSION(); if(auto context = ImGui::CreateContext()) { @@ -120,6 +120,17 @@ namespace SHADE window->Init(); } + /* Editor View Gridlines */ + SetUpGridLines(true, true); + // Handle state changes so that we only show in edit mode + std::shared_ptr> stateChangeEventReceiver + { + std::make_shared>(this, &SHEditor::onEditorStateChanged) + }; + SHEventManager::SubscribeTo(SH_EDITOR_ON_PLAY_EVENT, std::dynamic_pointer_cast(stateChangeEventReceiver)); + SHEventManager::SubscribeTo(SH_EDITOR_ON_PAUSE_EVENT, std::dynamic_pointer_cast(stateChangeEventReceiver)); + SHEventManager::SubscribeTo(SH_EDITOR_ON_STOP_EVENT, std::dynamic_pointer_cast(stateChangeEventReceiver)); + SHLOG_INFO("Successfully initialised SHADE Engine Editor") } @@ -180,6 +191,97 @@ namespace SHADE io->Fonts->Build(); } + void SHEditor::SetUpGridLines(bool drawGrid, bool drawAxes) + { + // Clear existing lines + SHDebugDraw::ClearPersistentDraws(); + + static constexpr float DELTA = 1.0f; + static constexpr int EXTENT_COUNT = static_cast(500.0f /* TODO: Remove hard code */ / DELTA); + static constexpr float LINE_HALF_LENGTH = (DELTA * static_cast(EXTENT_COUNT)) * 0.5f; + + // Render Grid + static const SHColour GRID_COL = { 0.2f, 0.2f, 0.2f, 1.0f }; + if (drawGrid) + { + for (int i = 1; i < EXTENT_COUNT; ++i) + { + // X-Axis Lines + SHDebugDraw::PersistentLine + ( + GRID_COL, + SHVec3 { -LINE_HALF_LENGTH, 0.0f, i * DELTA }, + SHVec3 { LINE_HALF_LENGTH, 0.0f, i * DELTA } + ); + SHDebugDraw::PersistentLine + ( + GRID_COL, + SHVec3 { -LINE_HALF_LENGTH, 0.0f, i * -DELTA }, + SHVec3 { LINE_HALF_LENGTH, 0.0f, i * -DELTA } + ); + // Y-Axis Lines + SHDebugDraw::PersistentLine + ( + GRID_COL, + SHVec3 { i * DELTA, 0.0f, -LINE_HALF_LENGTH }, + SHVec3 { i * DELTA, 0.0f, LINE_HALF_LENGTH } + ); + SHDebugDraw::PersistentLine + ( + GRID_COL, + SHVec3 { -i * DELTA, 0.0f, -LINE_HALF_LENGTH }, + SHVec3 { -i * DELTA, 0.0f, LINE_HALF_LENGTH } + ); + } + } + + // Render World Axes + if (drawAxes || drawGrid) + { + const SHColour X_AXIS_COL = drawAxes ? SHColour::RED : GRID_COL; + const SHColour Y_AXIS_COL = drawAxes ? SHColour::GREEN : GRID_COL; + const SHColour Z_AXIS_COL = drawAxes ? SHColour::BLUE : GRID_COL; + // X + SHDebugDraw::PersistentLine + ( + X_AXIS_COL, + SHVec3 { -LINE_HALF_LENGTH, 0.0f, 0.0f }, + SHVec3 { LINE_HALF_LENGTH, 0.0f, 0.0f } + ); + // Y + SHDebugDraw::PersistentLine + ( + Y_AXIS_COL, + SHVec3 { 0.0f, -LINE_HALF_LENGTH, 0.0f }, + SHVec3 { 0.0f, LINE_HALF_LENGTH, 0.0f } + ); + // Z + SHDebugDraw::PersistentLine + ( + Z_AXIS_COL, + SHVec3 { 0.0f, 0.0f, -LINE_HALF_LENGTH }, + SHVec3 { 0.0f, 0.0f, LINE_HALF_LENGTH } + ); + } + } + + SHEventHandle SHEditor::onEditorStateChanged(SHEventPtr eventPtr) + { + auto eventData = reinterpret_cast*>(eventPtr.get()); + switch (editorState) + { + case State::PAUSE: + case State::STOP: + SetUpGridLines(true, true); + break; + case State::PLAY: + default: + SHDebugDraw::ClearPersistentDraws(); + break; + } + return eventData->handle; + } + void SHEditor::Exit() { for (const auto& window : SHEditorWindowManager::editorWindows | std::views::values) diff --git a/SHADE_Engine/src/Editor/SHEditor.h b/SHADE_Engine/src/Editor/SHEditor.h index 624069db..6e0ef5ae 100644 --- a/SHADE_Engine/src/Editor/SHEditor.h +++ b/SHADE_Engine/src/Editor/SHEditor.h @@ -16,8 +16,9 @@ #include "Resource/SHHandle.h" #include "EditorWindow/SHEditorWindow.h" #include "Tools/SHLog.h" -#include "Gizmos/SHTransformGizmo.h" - +#include "Gizmos/SHTransformGizmo.h"` +#include "Events/SHEventDefines.h" +#include "Events/SHEvent.h" //#==============================================================# //|| Library Includes || @@ -194,6 +195,10 @@ namespace SHADE void InitFonts() noexcept; + void SetUpGridLines(bool drawGrid, bool drawAxes); + + SHEventHandle onEditorStateChanged(SHEventPtr eventPtr); + // Handle to command pool used for ImGui Vulkan Backend Handle imguiCommandPool; // Handle to command buffer used for ImGui Vulkan Backend diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.cpp index 16069564..90fe51d5 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.cpp @@ -95,7 +95,7 @@ namespace SHADE // Get Current frame index const uint32_t FRAME_IDX = GFX_SYSTEM->GetCurrentFrameIndex(); - // Set Pipeline + // Set Pipelin cmdBuffer->BindPipeline(GFX_SYSTEM->GetDebugDrawPipeline()); cmdBuffer->SetLineWidth(LineWidth); From 7bda8b39986d3807f30bf0ebdc173a551b106402 Mon Sep 17 00:00:00 2001 From: Kah Wei Date: Wed, 2 Nov 2022 13:48:53 +0800 Subject: [PATCH 20/27] Added IsInterpolating to RigidBody in C# --- SHADE_Managed/src/Components/RigidBody.cxx | 8 ++++++++ SHADE_Managed/src/Components/RigidBody.hxx | 5 +++++ 2 files changed, 13 insertions(+) diff --git a/SHADE_Managed/src/Components/RigidBody.cxx b/SHADE_Managed/src/Components/RigidBody.cxx index 172b928b..12861600 100644 --- a/SHADE_Managed/src/Components/RigidBody.cxx +++ b/SHADE_Managed/src/Components/RigidBody.cxx @@ -148,6 +148,14 @@ namespace SHADE { return Convert::ToCLI(GetNativeComponent()->GetTorque()); } + bool RigidBody::Interpolating::get() + { + return GetNativeComponent()->IsInterpolating(); + } + void RigidBody::Interpolating::set(bool value) + { + GetNativeComponent()->SetInterpolate(value); + } /*---------------------------------------------------------------------------------*/ /* Force Functions */ diff --git a/SHADE_Managed/src/Components/RigidBody.hxx b/SHADE_Managed/src/Components/RigidBody.hxx index b3e031ba..d3a30612 100644 --- a/SHADE_Managed/src/Components/RigidBody.hxx +++ b/SHADE_Managed/src/Components/RigidBody.hxx @@ -129,6 +129,11 @@ namespace SHADE { Vector3 get(); } + property bool Interpolating + { + bool get(); + void set(bool value); + } /*-----------------------------------------------------------------------------*/ /* Force Functions */ From eb569a4263a267140aabdbdc8e73f411e27156b8 Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Wed, 2 Nov 2022 14:21:27 +0800 Subject: [PATCH 21/27] Shader updates --- Assets/Shaders/DeferredComposite_CS.glsl | 27 ++++++++++++------ Assets/Shaders/DeferredComposite_CS.shshaderb | Bin 4997 -> 5501 bytes 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/Assets/Shaders/DeferredComposite_CS.glsl b/Assets/Shaders/DeferredComposite_CS.glsl index 833180e7..5af585ba 100644 --- a/Assets/Shaders/DeferredComposite_CS.glsl +++ b/Assets/Shaders/DeferredComposite_CS.glsl @@ -57,25 +57,34 @@ void main() // normal of fragment vec3 normalView = imageLoad(normals, globalThread).rgb; + // light layer index + uint lightLayer = imageLoad (lightLayerData, globalThread).r; + vec3 fragColor = vec3 (0.0f); for (int i = 0; i < lightCounts.directionalLights; ++i) { - // get normalized direction of light - vec3 dLightNormalized = normalize (DirLightData.dLightData[i].direction); + if ((lightLayer & DirLightData.dLightData[i].cullingMask) != 0) + { + // get normalized direction of light + vec3 dLightNormalized = normalize (DirLightData.dLightData[i].direction); - // Get diffuse strength - float diffuseStrength = max (0, dot (dLightNormalized, normalView)); + // Get diffuse strength + float diffuseStrength = max (0, dot (dLightNormalized, normalView)); - // Calculate the fragment color - fragColor += DirLightData.dLightData[i].diffuseColor.rgb * diffuseStrength.rrr * pixelDiffuse; + // Calculate the fragment color + fragColor += DirLightData.dLightData[i].diffuseColor.rgb * diffuseStrength.rrr * pixelDiffuse; + } } for (int i = 0; i < lightCounts.ambientLights; ++i) { - // Just do some add - //fragColor += pixelDiffuse.rgb * AmbLightData.aLightData[i].ambientColor.rgb * vec3 (0.5f); - fragColor += pixelDiffuse.rgb * AmbLightData.aLightData[i].ambientColor.rgb * vec3 (AmbLightData.aLightData[i].strength); + if ((lightLayer & AmbLightData.aLightData[i].cullingMask) != 0) + { + // Just do some add + //fragColor += pixelDiffuse.rgb * AmbLightData.aLightData[i].ambientColor.rgb * vec3 (0.5f); + fragColor += pixelDiffuse.rgb * AmbLightData.aLightData[i].ambientColor.rgb * vec3 (AmbLightData.aLightData[i].strength); + } } float ssaoVal = imageLoad (ssaoBlurredImage, globalThread).r; diff --git a/Assets/Shaders/DeferredComposite_CS.shshaderb b/Assets/Shaders/DeferredComposite_CS.shshaderb index 8d7a83271b3d684965b4a639eba7e74329c9469d..6e0ff2a40f9907e1126db4f89f94de2523310b2a 100644 GIT binary patch literal 5501 zcmZve`IlT(5yxL<4@rPXAgClx7#9!>iv);BaLB-9bYKR9ac6kb)9Jj>(>-?ggalE8 zLc|R>6nBGhk0|1bKl+RRk=r?*O?xw{G3n85&%fm1}rtYCOv} zWtU{zvcFVNwmlmH$x40;d`mV~>a+8Q=lAvpD|>I-ceAdSX2Y`5b{RgS$Rp5dUUbB_ zL6?JzZ7*f@%72)>L&$$6(FoaR=a*&|7G~$~TWYMWE%gVd+RdeQ(P=KN6uo9+P@HJ$ zH&OE|I*s=FO5I@;k9z)5a&IO_tKD7B+YcY>HS-lz>YONRYqghVOVeEEM7NO-if(6a zrnHY`JK<}^$!2?|IC^xwPj>f>WUqtg?d9f5SA8s-L|^On3pXDrnvbJ`k7iRfyq~b^ z;GJ%7HE&m*#=Cw4>zDg(LT?wXV}tqpRI^v*xb=UqnS78}Irf7e?d7e5-F6pO_77)w z!;4ZL&F+WK8|z?qy))=j?L>(IXQ{2-PTnqEtZ|Hg?(y!|xr9Tr@X!RP`MKFVB+l+xG>qnd(Y6avvV_)*FK=zjoI~eaPk)x2~c;ou=UeZe5M_ zHsjKIAn!j`)}_C7tyI?+Euu#g*+bwL*HCq}imBbTQl3BhJ(e8?V_yyRoa5O?Hhdo} zZ?|}&ndWRPYiO%#;F!%$YjCW*r<35-J&k8iBTv`*ccCAZ4RiE&;~e(HefFdufsq5Z zCl~ihe|u8zmGz$itLLxxLYphEo!Ys77K}YL)Lx8aXTkgZyn7^Xm%TZc^n2Uuy&PDXW8#JV+(W*r0#pW78k7=8#3pK(am2PlvqUwXe&+Ulm^*4wH@C}}@fO_g z3M_IPGqA|*_cgG{Jqc#MMfe!x$6KG6^N4SKV(!!5d9T-}Zhhu=zw_jZ{eeY&QHy?2 z-wx#Pi~6nxGv70C>zjo1IRke^eCrd7`kcXfed^X1vvMxk>w4Yp{JB5u>e@#k>vFN>dD!XV{$CXYIzSFKe|2=J%{Fea)}#8+4gt7u*>7 z8*@+6|6fcoV_pk)>1#~&DFIgKzDt+>d*Rk?U(DgWDjTo9tlOCGxg{C&HKw|6*=61P z;Ks1-8~Cey2jo)sOz$YQEW42o+snHWCN7!hop5XO4%{a{0J(Of-48c*o!mDIX1&_2 zPu=$}rhP8S?%M%64>z9Q0BebO_J0>Qya?B}8`(FjZk+eRjVWdxb>FR6)cd}q>;FiS z&7r;w_k8vv{0romspH7TvW~EyK;8sd@6*ZV{tGn^mv38}^`3$I*3I`>xbeiSSKW6k zru~H^8_!vI5w2{$`qJOG;hrBQgTBU8KbJ6dXWF;!ayDLqTdOfVlks1Hvh4Id>e~JU zT@Ho*XJl(|R(z|kLi$MBZs#jvJm<}2|NaT$x5XO#E^LPEwYqP0=SBMDMf!C$-8XVm zO?UtPn(mzXf5Ccu|DO{2GIFD)>wmJQYd@RxyQ$AJUJCgwdJ^4U+YhmaIMo<@d%|EF z*lQAIuNLt${}qtF+78ee`ygf>zdNso{N||Ze+{J1GW(so-H<-w3v|-ieFG#exy)z( zjc;GI8*dN%jnGumjsGU79{mwfV z--awMx$5z~ckRZ%8UA+Y)}$N%HYnonL%to-N8Gz{e(!|DUG~J;5mR<<{MIQuGY6o5 z(Y<@%&aC|J#|%GHdR_r8QpQ^y?gyP-pnIozYqdm!pEkdJvG@JR+W(e%^Z{h!iJwok zd=Odu4(K2B=fiN9b!qz$BxYU8QO8G1xvJw459kIpqD@gGV9n z#kVVNe0^3RvCx~y&dKxCy#sy}(nowNy%1|b#?{Z?GkuKRfNP7|kCk#&`*GyQpr~D2 zQQE8j3$&9x=6DrdOmdmecW7*D=s@OMOlR#TOk8?~`aRzoWGwA*#*ZQUmcyrqte<%J z^pTzCr&62&vY5Ux>tfDt+?!n8+4dgg(Tnv`&a%_QbG{#k#7;o*Uc~C}WjfhTmb|i^ zLN>PCxAbxNlaR~3pMYzZNA6D|8^iCd@8naESiGgv$cLb~4}G43PDAmQK8@@?ac5Tj z3CR5BQ#PM_KLgd@(&y04A8+aN$j?H~uC{vKFQ99WxAaA1N<}6H7M%R7H?}8^4F6+=JWZ4iMwJxW2U|VW7eV+T)zxL*5U??0z3vOy8JYG3O=vBv*Hq z?3+C5{sFRe$L#(PSuAE(o0$7g!QJm%xc^1?kD+r(_jl$e&}JxphkuH!kGQ`xp8sc% zxXYT)!o{LLKSvgeGyekFGe4K!>o1YT^oui#>3=o+SJ3&SZ-M_B+6FD~je80Hn}mtG zykFms^}h^hkKDgSHh0wiJ7h6eV82HeGfrTCNZ1g3k;u;3A0hYaul*IML0;=MulD~C H+t-dYB8QE`3^aG z`1y0n-KiXvxHcZf$0zIMuq0J=cBHjc;;}+%8mykG6~iQ|RR;%Bdt0zld^$Q)jt8QN ziJ6A7v#&LHP&|ys%cUB6TacGNU28;a9*xSUr3%jl-5%a>*n075tv(gTnJ4i!%wmmn zUyt;OdRXbN#kG36uO-+l9;I?F*eN~~RVI`E+DtWRsDh3Z6CAj!s#U`{bs=w?{;`LC zPS>Jp;w*;KgT{2tV0pKv{&Y5+8js4eJF;`_5*~Z`bMo&OR!ZX@NlzD@E6?6D_c@TY zaJH^vNqwf6WVK;u&DJiN+Q6wfYV^78-^Ho9I1_6;Du=_y$+TwtskxN3%dSs%+7TQO zKDUN}FbM^xxv;acGh`Nedr+A6r6)6g@L_zjJUU9bT1h6ArzI!}&-&CJOiS+b?(goI zGn>qIzq7S+ZuW8Rh6R>vIOm>wANX@_|32smv*YKt`iX^&6?!M*Txtn>JT#m6%fcIt zur?aTI%j)u)#>}lk8k`C%?tSEf>#`+by;4pxn7DU@#mvl5c(z>6Dk*68`991S ztrns4w$_PSJ-tgZ=f>VG?%UC^v#|4)d^>S?;_r;_nx46ZMMNXERLAEb0Se zAO6g;UmrU4k)Qp{5zF=)X7yPu_*s3+B%7brw@MiK-Vvw1ya*qgIg3wyU{)Wq=huf$ zeKrfs9Cly#?bqkn(Xr=5)bootv-W_~?}+>H(DA39r8*&J?2?9#yj(HtJWbM9O4lFG z6vLjE&a8kz_|Hpm{ilUL`N4>ZKRqWF_)e$uCM^CU$>hX;h5qNh^CDs`7e}{PDo9PLxcm;W`(_{avPHyND~-3v-TK77=Y?@*?Bqx1ZGvIn?PT^X z6WS+Eya91)v3T6Y8r?SU4%=GE2gK2dQxGR67BwIg6 zC9{{jW*?W_B%(gvq4no(jVf_$@#@FzQ239ESb8lc|SZUlB(ppTCH~ zT(ajQXTX=3=vN&^&D8ao)3GyOyh|4IbweBafe_>b&59e zB@Ppt#qM_)_ckIw>RT$p7u#;#1m^}L58sW4M0_*Q@n0>%XI%T4&$S|az=w5n%>Tn8 zaEL`d?wk1BBX;6-i9aIZ`(g1PmF&lV%=v&@{KqAOLo7djUOIM*|AgcXPN)8jB0v5n z>G*(K{3j)YLo7c&ea6mNdc=F3On3b{x0A{Y~BVotNplSt9?}ROCqZs+X)fA%;(D@?AF^?90ty^-r`RUuZqYw;?DY- z!@!{{s-N?{E+Q6oJL4OYnQ!xXQ!;+w<})Ulxw+)xyd@b7Uz;f~=7gD{Z*cZAC!vV5 zU(|l|qQl0;*^dp(pF{eOjc*El#a0$4Hk=u)h);@G*duZ5aLfI+WMbHio|Ft`Ga5@~ zM(zHY(J2wQ&1h9J`@oq|^a&C9$%kxrRg=tpTK*ZyLT!XN8duKg)McvgJE3`GUyuVdKv6Wp3UTVYj(?&tc$@<#}H+xv;aBS-L3l zXX28>@U@u$qc8M`dxBe?A4sN7n~4u4gV{`A1M~aNeY5|H_{XBFPHz|gMARv=Z~Ui{ z@d4-W3+Me@1kR$y%i>^mA74lYvol_k%o(q_x&Jbig8)A}BN+ax#J>_ Date: Wed, 2 Nov 2022 15:05:34 +0800 Subject: [PATCH 22/27] new SHMETA --- Assets/Shaders/SSAOBlur_CS.shshaderb.shmeta | 3 +++ Assets/Shaders/SSAO_CS.shshaderb.shmeta | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) create mode 100644 Assets/Shaders/SSAOBlur_CS.shshaderb.shmeta diff --git a/Assets/Shaders/SSAOBlur_CS.shshaderb.shmeta b/Assets/Shaders/SSAOBlur_CS.shshaderb.shmeta new file mode 100644 index 00000000..57bdb72b --- /dev/null +++ b/Assets/Shaders/SSAOBlur_CS.shshaderb.shmeta @@ -0,0 +1,3 @@ +Name: SSAOBlur_CS +ID: 39760835 +Type: 2 diff --git a/Assets/Shaders/SSAO_CS.shshaderb.shmeta b/Assets/Shaders/SSAO_CS.shshaderb.shmeta index a5b5b739..9a477b24 100644 --- a/Assets/Shaders/SSAO_CS.shshaderb.shmeta +++ b/Assets/Shaders/SSAO_CS.shshaderb.shmeta @@ -1,3 +1,3 @@ Name: SSAO_CS -ID: 48941934 +ID: 38430899 Type: 2 From f0ef9fc0cf411b494ec1e44c380fc3a48c89e138 Mon Sep 17 00:00:00 2001 From: Kah Wei Date: Wed, 2 Nov 2022 15:13:12 +0800 Subject: [PATCH 23/27] Fixed validation errors due to debug draw --- .../MiddleEnd/Interface/SHDebugDrawSystem.cpp | 16 ++- .../MiddleEnd/Interface/SHDebugDrawSystem.h | 25 ++-- .../MiddleEnd/Interface/SHGraphicsSystem.cpp | 113 ++++++++++-------- .../MiddleEnd/Interface/SHGraphicsSystem.h | 6 + 4 files changed, 92 insertions(+), 68 deletions(-) diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.cpp index 90fe51d5..74effb6d 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.cpp @@ -95,18 +95,26 @@ namespace SHADE // Get Current frame index const uint32_t FRAME_IDX = GFX_SYSTEM->GetCurrentFrameIndex(); - // Set Pipelin - cmdBuffer->BindPipeline(GFX_SYSTEM->GetDebugDrawPipeline()); - cmdBuffer->SetLineWidth(LineWidth); - // Don't draw if no points if (numPoints[FRAME_IDX] > 0) { + cmdBuffer->BindPipeline(GFX_SYSTEM->GetDebugDrawPipeline()); + cmdBuffer->SetLineWidth(LineWidth); cmdBuffer->BindVertexBuffer(0, vertexBuffers[FRAME_IDX], 0); cmdBuffer->DrawArrays(numPoints[FRAME_IDX], 1, 0, 0); } + }); + auto subPassWithDepth = renderGraph->GetNode("Debug Draw with Depth")->GetSubpass("Debug Draw with Depth"); + subPassWithDepth->AddExteriorDrawCalls([this, GFX_SYSTEM](Handle& cmdBuffer) + { + // Get Current frame index + const uint32_t FRAME_IDX = GFX_SYSTEM->GetCurrentFrameIndex(); + + // Don't draw if no points if (numPersistentPoints[FRAME_IDX] > 0) { + cmdBuffer->BindPipeline(GFX_SYSTEM->GetDebugDrawDepthPipeline()); + cmdBuffer->SetLineWidth(LineWidth); cmdBuffer->BindVertexBuffer(0, persistentVertexBuffers[FRAME_IDX], 0); cmdBuffer->DrawArrays(numPersistentPoints[FRAME_IDX], 1, 0, 0); } diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.h b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.h index 7c9e7c81..2a9709ed 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.h @@ -131,7 +131,7 @@ namespace SHADE /*---------------------------------------------------------------------------------*/ /// /// Renders a line between two points in world space that will persist until - /// ClearPersistentDraws() is called. + /// ClearPersistentDraws() is called. These lines are depth tested. /// /// Colour of the line. /// First point of the line. @@ -139,7 +139,7 @@ namespace SHADE void DrawPersistentLine(const SHVec4& color, const SHVec3& startPt, const SHVec3& endPt); /// /// Renders a triangle indicated by three points in world space that will persist - /// until ClearPersistentDraws() is called. + /// until ClearPersistentDraws() is called. These lines are depth tested. /// /// Colour of the triangle. /// First point of the triangle. @@ -148,7 +148,7 @@ namespace SHADE void DrawPersistentTri(const SHVec4& color, const SHVec3& pt1, const SHVec3& pt2, const SHVec3& pt3); /// /// Renders a quadrilateral indicated by four points in world space that will persist - /// until ClearPersistentDraws() is called. + /// until ClearPersistentDraws() is called. These lines are depth tested. /// /// Colour of the quadrilateral. /// First point of the triangle. @@ -158,14 +158,16 @@ namespace SHADE void DrawPersistentQuad(const SHVec4& color, const SHVec3& pt1, const SHVec3& pt2, const SHVec3& pt3, const SHVec3& pt4); /// /// Renders a polygon indicated by the specified set of points in world space that - /// will persist until ClearPersistentDraws() is called. + /// will persist until ClearPersistentDraws() is called. These lines are depth + /// tested. /// /// Colour of the polygon. /// List of points for the polygon. void DrawPersistentPoly(const SHVec4& color, std::initializer_list pointList); /// /// Renders a polygon indicated by the specified set of points in world space that - /// will persist until ClearPersistentDraws() is called. + /// will persist until ClearPersistentDraws() is called. These lines are depth + /// tested. /// /// Iterator for a STL-like container. /// Colour of the polygon. @@ -179,7 +181,8 @@ namespace SHADE void DrawPersistentPoly(const SHVec4& color, IterType pointListBegin, IterType pointListEnd); /// /// Renders a wireframe cube centered around the position specified in world space - /// that will persist until ClearPersistentDraws() is called. + /// that will persist until ClearPersistentDraws() is called. These lines are depth + /// tested. /// /// Colour of the cube. /// Position where the cube wil be centered at. @@ -187,7 +190,8 @@ namespace SHADE void DrawPersistentCube(const SHVec4& color, const SHVec3& pos, const SHVec3& size); /// /// Renders a wireframe sphere centered around the position specified in world space - /// that will persist until ClearPersistentDraws() is called. + /// that will persist until ClearPersistentDraws() is called. These lines are depth + /// tested. /// /// Colour of the sphere. /// Position where the sphere wil be centered at. @@ -241,13 +245,6 @@ namespace SHADE void drawCube(std::vector& storage, const SHVec4& color, const SHVec3& pos, const SHVec3& size); void drawSphere(std::vector& storage, const SHVec4& color, const SHVec3& pos, double radius); }; - - template - void SHADE::SHDebugDrawSystem::DrawPersistentPoly(const SHVec4& color, IterType pointListBegin, IterType pointListEnd) - { - - } - } #include "SHDebugDrawSystem.hpp" \ No newline at end of file diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp index 2bc2b7de..4d551cee 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp @@ -171,7 +171,7 @@ namespace SHADE "Normals", "Albedo", "Depth Buffer", - "Scene" + "Scene" }, {}); // no predecessors @@ -186,8 +186,14 @@ namespace SHADE // deferred composite gBufferNode->AddNodeCompute(deferredCompositeShader, { "Position", "Normals", "Albedo", "Light Layer Indices", "Scene" }); - // Set up Debug Draw Pass - auto debugDrawNode = worldRenderGraph->AddNode("Debug Draw", { "Scene" }, {"G-Buffer"}); + // Set up Debug Draw Passes + // - Depth Tested + auto debugDrawNodeDepth = worldRenderGraph->AddNode("Debug Draw with Depth", { "Scene", "Depth Buffer" }, {"G-Buffer"}); + auto debugDrawDepthSubpass = debugDrawNodeDepth->AddSubpass("Debug Draw with Depth"); + debugDrawDepthSubpass->AddColorOutput("Scene"); + debugDrawDepthSubpass->AddDepthOutput("Depth Buffer"); + // - No Depth Test + auto debugDrawNode = worldRenderGraph->AddNode("Debug Draw", { "Scene" }, { "Debug Draw with Depth" }); auto debugDrawSubpass = debugDrawNode->AddSubpass("Debug Draw"); debugDrawSubpass->AddColorOutput("Scene"); @@ -209,53 +215,8 @@ namespace SHADE defaultMaterial = AddMaterial(defaultVertShader, defaultFragShader, gBufferSubpass); // Create debug draw pipeline - auto debugDrawPipelineLayout = resourceManager.Create - ( - device, SHPipelineLayoutParams - { - .shaderModules = { debugVertShader, debugFragShader }, - .globalDescSetLayouts = SHGraphicsGlobalData::GetDescSetLayouts() - } - ); - debugDrawPipeline = resourceManager.Create(device, debugDrawPipelineLayout, nullptr, debugDrawNode->GetRenderpass(), debugDrawSubpass); - debugDrawPipeline->GetPipelineState().SetRasterizationState(SHRasterizationState - { - .polygonMode = vk::PolygonMode::eLine, - .cull_mode = vk::CullModeFlagBits::eNone - }); - debugDrawPipeline->GetPipelineState().SetInputAssemblyState(SHInputAssemblyState - { - .topology = vk::PrimitiveTopology::eLineList - }); - - SHVertexInputState debugDrawVertexInputState; - debugDrawVertexInputState.AddBinding(false, true, { SHVertexAttribute(SHAttribFormat::FLOAT_4D), SHVertexAttribute(SHAttribFormat::FLOAT_4D) }); - debugDrawPipeline->GetPipelineState().SetVertexInputState(debugDrawVertexInputState); - SHColorBlendState colorBlendState{}; - colorBlendState.logic_op_enable = VK_FALSE; - colorBlendState.logic_op = vk::LogicOp::eCopy; - - auto const& subpassColorReferences = debugDrawSubpass->GetColorAttachmentReferences(); - colorBlendState.attachments.reserve(subpassColorReferences.size()); - - for (auto& att : subpassColorReferences) - { - colorBlendState.attachments.push_back(vk::PipelineColorBlendAttachmentState - { - .blendEnable = SHVkUtil::IsBlendCompatible(debugDrawSubpass->GetFormatFromAttachmentReference(att.attachment)), - .srcColorBlendFactor = vk::BlendFactor::eSrcAlpha, - .dstColorBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha, - .colorBlendOp = vk::BlendOp::eAdd, - .srcAlphaBlendFactor = vk::BlendFactor::eOne, - .dstAlphaBlendFactor = vk::BlendFactor::eZero, - .alphaBlendOp = vk::BlendOp::eAdd, - .colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA, - } - ); - } - - debugDrawPipeline->GetPipelineState().SetColorBlenState(colorBlendState); - debugDrawPipeline->ConstructPipeline(); + debugDrawPipeline = createDebugDrawPipeline(debugDrawNode->GetRenderpass(), debugDrawSubpass); + debugDrawDepthPipeline = createDebugDrawPipeline(debugDrawNodeDepth->GetRenderpass(), debugDrawDepthSubpass); } void SHGraphicsSystem::InitMiddleEnd(void) noexcept @@ -867,5 +828,57 @@ namespace SHADE return worldRenderGraph->GetNode(G_BUFFER_RENDER_GRAPH_NODE_NAME.data()); } + Handle SHGraphicsSystem::createDebugDrawPipeline(Handle renderPass, Handle subpass) + { + auto pipelineLayout = resourceManager.Create + ( + device, SHPipelineLayoutParams + { + .shaderModules = { debugVertShader, debugFragShader }, + .globalDescSetLayouts = SHGraphicsGlobalData::GetDescSetLayouts() + } + ); + auto pipeline = resourceManager.Create(device, pipelineLayout, nullptr, renderPass, subpass); + pipeline->GetPipelineState().SetRasterizationState(SHRasterizationState + { + .polygonMode = vk::PolygonMode::eLine, + .cull_mode = vk::CullModeFlagBits::eNone + }); + pipeline->GetPipelineState().SetInputAssemblyState(SHInputAssemblyState + { + .topology = vk::PrimitiveTopology::eLineList + }); + + SHVertexInputState debugDrawVertexInputState; + debugDrawVertexInputState.AddBinding(false, true, { SHVertexAttribute(SHAttribFormat::FLOAT_4D), SHVertexAttribute(SHAttribFormat::FLOAT_4D) }); + pipeline->GetPipelineState().SetVertexInputState(debugDrawVertexInputState); + SHColorBlendState colorBlendState{}; + colorBlendState.logic_op_enable = VK_FALSE; + colorBlendState.logic_op = vk::LogicOp::eCopy; + + auto const& subpassColorReferences = subpass->GetColorAttachmentReferences(); + colorBlendState.attachments.reserve(subpassColorReferences.size()); + + for (auto& att : subpassColorReferences) + { + colorBlendState.attachments.push_back(vk::PipelineColorBlendAttachmentState + { + .blendEnable = SHVkUtil::IsBlendCompatible(subpass->GetFormatFromAttachmentReference(att.attachment)), + .srcColorBlendFactor = vk::BlendFactor::eSrcAlpha, + .dstColorBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha, + .colorBlendOp = vk::BlendOp::eAdd, + .srcAlphaBlendFactor = vk::BlendFactor::eOne, + .dstAlphaBlendFactor = vk::BlendFactor::eZero, + .alphaBlendOp = vk::BlendOp::eAdd, + .colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA, + }); + } + + pipeline->GetPipelineState().SetColorBlenState(colorBlendState); + pipeline->ConstructPipeline(); + + return pipeline; + } + #pragma endregion MISC } diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h index b307dc92..07e5fbab 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h @@ -289,6 +289,7 @@ namespace SHADE Handle GetPostOffscreenRenderSystem(void) const noexcept {return postOffscreenRender;}; Handle GetPrimaryRenderpass() const noexcept; Handle GetDebugDrawPipeline(void) const noexcept { return debugDrawPipeline; } + Handle GetDebugDrawDepthPipeline(void) const noexcept { return debugDrawDepthPipeline; } uint32_t GetCurrentFrameIndex(void) const noexcept { return renderContext.GetCurrentFrame(); } /*-----------------------------------------------------------------------------*/ @@ -355,6 +356,7 @@ namespace SHADE // Built-In Materials Handle defaultMaterial; Handle debugDrawPipeline; + Handle debugDrawDepthPipeline; Handle worldRenderGraph; @@ -367,5 +369,9 @@ namespace SHADE uint32_t resizeHeight; bool restoredFromMinimize = false; + /*---------------------------------------------------------------------------------*/ + /* Helper Functions */ + /*---------------------------------------------------------------------------------*/ + Handle createDebugDrawPipeline(Handle renderPass, Handle subpass); }; } \ No newline at end of file From d818adf2a20a87ec374ba2f81bba58953e53987b Mon Sep 17 00:00:00 2001 From: Kah Wei Date: Wed, 2 Nov 2022 15:34:35 +0800 Subject: [PATCH 24/27] Fixed DrawPoly() --- .../MiddleEnd/Interface/SHDebugDrawSystem.cpp | 9 +++-- .../MiddleEnd/Interface/SHDebugDrawSystem.h | 3 ++ .../MiddleEnd/Interface/SHDebugDrawSystem.hpp | 34 ++++++++++++++++++- 3 files changed, 43 insertions(+), 3 deletions(-) diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.cpp index 74effb6d..37d15808 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.cpp @@ -255,6 +255,11 @@ namespace SHADE storage.emplace_back(PointVertex{ endPt, color }); } + void SHDebugDrawSystem::drawLineSet(std::vector& storage, const SHVec4& color, std::initializer_list pointList) + { + drawLineSet(storage, color, pointList.begin(), pointList.end()); + } + void SHDebugDrawSystem::drawPoly(std::vector& storage, const SHVec4& color, std::initializer_list pointList) { drawPoly(storage, color, pointList.begin(), pointList.end()); @@ -281,7 +286,7 @@ namespace SHADE const SHVec3 TOP_LEFT_FRONT = UNIT_TOP_LEFT_FRONT * size; const SHVec3 TOP_RIGHT_FRONT = UNIT_TOP_RIGHT_FRONT * size; - drawPoly + drawLineSet ( storage, color, @@ -316,6 +321,6 @@ namespace SHADE spherePoints.emplace_back(SPHERE.VertexPositions[idx]); } } - drawPoly(storage, color, spherePoints.begin(), spherePoints.end()); + drawLineSet(storage, color, spherePoints.begin(), spherePoints.end()); } } \ No newline at end of file diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.h b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.h index 2a9709ed..20ddcd42 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.h @@ -239,6 +239,9 @@ namespace SHADE /* Helper Draw Functions */ /*---------------------------------------------------------------------------------*/ void drawLine(std::vector& storage, const SHVec4& color, const SHVec3& startPt, const SHVec3& endPt); + void drawLineSet(std::vector& storage, const SHVec4& color, std::initializer_list pointList); + template + void drawLineSet(std::vector& storage, const SHVec4& color, IterType pointListBegin, IterType pointListEnd); void drawPoly(std::vector& storage, const SHVec4& color, std::initializer_list pointList); template void drawPoly(std::vector& storage, const SHVec4& color, IterType pointListBegin, IterType pointListEnd); diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.hpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.hpp index 953b1cb3..2a171e73 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.hpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.hpp @@ -28,7 +28,7 @@ namespace SHADE /* Helper Draw Functions */ /*-----------------------------------------------------------------------------------*/ template - void SHDebugDrawSystem::drawPoly(std::vector& storage, const SHVec4& color, IterType pointListBegin, IterType pointListEnd) + void SHDebugDrawSystem::drawLineSet(std::vector& storage, const SHVec4& color, IterType pointListBegin, IterType pointListEnd) { // Ensure dereferenced type is SHVec3 static_assert(std::is_same_v>, "Parameters to DrawPoly must be SHVec3."); @@ -54,4 +54,36 @@ namespace SHADE storage.emplace_back(PointVertex{ *pointIter, color }); } } + template + void SHDebugDrawSystem::drawPoly(std::vector& storage, const SHVec4& color, IterType pointListBegin, IterType pointListEnd) + { + // Ensure dereferenced type is SHVec3 + static_assert(std::is_same_v>, "Parameters to DrawPoly must be SHVec3."); + + // Check if points exceeded max + if (storage.size() > MAX_POINTS) + { + SHLOG_WARNING("[DebugDraw] Exceeded maximum size of drawable debug elements."); + return; + } + + const size_t POINTS_COUNT = pointListEnd - pointListBegin; + // Invalid polygon + if (POINTS_COUNT < 2) + { + SHLOG_WARNING("[SHDebugDraw] Invalid polygon provided to DrawPoly()."); + return; + } + + // Trace the polygon + for (auto pointIter = pointListBegin + 1; pointIter != pointListEnd; ++pointIter) + { + storage.emplace_back(PointVertex{ *(pointIter - 1), color }); + storage.emplace_back(PointVertex{ *pointIter , color }); + } + + // Close the line loop + storage.emplace_back(PointVertex{ *(pointListEnd - 1), color }); + storage.emplace_back(PointVertex{ *pointListBegin , color }); + } } \ No newline at end of file From 02c79b4cc48f5d606c9ed6fcaaf75be1fc5718da Mon Sep 17 00:00:00 2001 From: Diren D Bharwani Date: Wed, 2 Nov 2022 15:44:24 +0800 Subject: [PATCH 25/27] Added Debug Drawing for Colliders (wonk) and Trigger checkbox to Colldiers Press space to toggle debug draw. Does not work until you press play, then it can be toggled on and off. --- .../src/Application/SBApplication.cpp | 8 + .../Inspector/SHEditorComponentView.hpp | 4 + SHADE_Engine/src/Math/SHColour.cpp | 11 ++ SHADE_Engine/src/Math/SHColour.h | 7 + SHADE_Engine/src/Physics/SHPhysicsSystem.cpp | 162 +++++++++++++++++- SHADE_Engine/src/Physics/SHPhysicsSystem.h | 52 +++--- SHADE_Engine/src/Tools/SHUtilities.h | 2 +- 7 files changed, 220 insertions(+), 26 deletions(-) diff --git a/SHADE_Application/src/Application/SBApplication.cpp b/SHADE_Application/src/Application/SBApplication.cpp index b865f028..81926359 100644 --- a/SHADE_Application/src/Application/SBApplication.cpp +++ b/SHADE_Application/src/Application/SBApplication.cpp @@ -91,6 +91,7 @@ namespace Sandbox SHSystemManager::RegisterRoutine(); SHSystemManager::RegisterRoutine(); SHSystemManager::RegisterRoutine(); + SHSystemManager::RegisterRoutine(); SHSystemManager::RegisterRoutine(); SHSystemManager::RegisterRoutine(); @@ -148,6 +149,13 @@ namespace Sandbox #endif SHSystemManager::RunRoutines(editor->editorState != SHEditor::State::PLAY, 0.016f); editor->PollPicking(); + + static bool drawColliders = false; + if (SHInputManager::GetKeyDown(SHInputManager::SH_KEYCODE::SPACE)) + { + drawColliders = !drawColliders; + SHSystemManager::GetSystem()->SetDrawColliders(drawColliders); + } } // Finish all graphics jobs first graphicsSystem->AwaitGraphicsExecution(); diff --git a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp index 4777fc6a..6f03a55e 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp +++ b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp @@ -273,6 +273,7 @@ namespace SHADE { } + { SHEditorWidgets::BeginPanel("Offsets",{ ImGui::GetContentRegionAvail().x, 30.0f }); SHEditorWidgets::DragVec3("Position", { "X", "Y", "Z" }, [&collider] {return collider->GetPositionOffset(); }, [&collider](SHVec3 const& vec) {collider->SetPositionOffset(vec); }); @@ -297,6 +298,9 @@ namespace SHADE }); SHEditorWidgets::EndPanel(); } + + SHEditorWidgets::CheckBox("Is Trigger", [collider] { return collider->IsTrigger(); }, [collider](bool value) { collider->SetIsTrigger(value); }); + if (ImGui::Button(std::format("{} Remove Collider #{}", ICON_MD_REMOVE, i).data())) { colliderToDelete = i; diff --git a/SHADE_Engine/src/Math/SHColour.cpp b/SHADE_Engine/src/Math/SHColour.cpp index 944c37cb..fc2f2a08 100644 --- a/SHADE_Engine/src/Math/SHColour.cpp +++ b/SHADE_Engine/src/Math/SHColour.cpp @@ -118,6 +118,17 @@ namespace SHADE } {} + SHColour::SHColour(uint32_t rgba) noexcept + : XMFLOAT4 { 0.0f, 0.0f, 0.0f, 1.0f } + { + const SHColour32 TMP { ._32bitValue = rgba }; + + x = static_cast(TMP._8bitValues[0]) / 255.0f; + y = static_cast(TMP._8bitValues[1]) / 255.0f; + z = static_cast(TMP._8bitValues[2]) / 255.0f; + w = static_cast(TMP._8bitValues[3]) / 255.0f; + } + SHColour::SHColour(const SHVec3& rgb) noexcept : XMFLOAT4 { rgb.x, rgb.y, rgb.z, 1.0f } {} diff --git a/SHADE_Engine/src/Math/SHColour.h b/SHADE_Engine/src/Math/SHColour.h index a6adf7bb..5dac0edd 100644 --- a/SHADE_Engine/src/Math/SHColour.h +++ b/SHADE_Engine/src/Math/SHColour.h @@ -34,6 +34,12 @@ namespace SHADE float v = 0.0f; }; + union SH_API SHColour32 + { + uint32_t _32bitValue; + uint8_t _8bitValues[4]; + }; + class SH_API SHColour : public DirectX::XMFLOAT4 { public: @@ -46,6 +52,7 @@ namespace SHADE SHColour (float r, float g, float b, float a) noexcept; SHColour (uint8_t r, uint8_t g, uint8_t b) noexcept; SHColour (uint8_t r, uint8_t g, uint8_t b, uint8_t a) noexcept; + SHColour (uint32_t rgba) noexcept; SHColour (const SHVec3& rgb) noexcept; SHColour (const SHVec4& rgba) noexcept; diff --git a/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp b/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp index e1acccd9..bdee8ba1 100644 --- a/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp +++ b/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp @@ -17,10 +17,12 @@ #include "ECS_Base/Managers/SHComponentManager.h" #include "ECS_Base/Managers/SHEntityManager.h" #include "ECS_Base/Managers/SHSystemManager.h" +#include "Graphics/MiddleEnd/Interface/SHDebugDrawSystem.h" #include "Math/SHMathHelpers.h" #include "Math/Transform/SHTransformComponent.h" #include "Scene/SHSceneManager.h" #include "Scripting/SHScriptEngine.h" +#include "Tools/SHUtilities.h" namespace SHADE { @@ -30,6 +32,7 @@ namespace SHADE SHPhysicsSystem::SHPhysicsSystem() : worldUpdated { false } + , debugDrawFlags { 0 } , interpolationFactor { 0.0 } , fixedDT { 60.0 } , world { nullptr } @@ -47,6 +50,11 @@ namespace SHADE : SHSystemRoutine { "Physics PostUpdate", false } {} + SHPhysicsSystem::PhysicsDebugDraw::PhysicsDebugDraw() + : SHSystemRoutine { "Physics DebugDraw", true } + {} + + /*-----------------------------------------------------------------------------------*/ /* Getter Function Definitions */ /*-----------------------------------------------------------------------------------*/ @@ -99,6 +107,31 @@ namespace SHADE return 0; } + bool SHPhysicsSystem::GetDrawColliders() const noexcept + { + return debugDrawFlags & SHUtilities::ConvertEnum(DebugDrawFlags::COLLIDER); + } + + bool SHPhysicsSystem::GetDrawColliderAABBs() const noexcept + { + return debugDrawFlags & SHUtilities::ConvertEnum(DebugDrawFlags::COLLIDER_AABB); + } + + bool SHPhysicsSystem::GetDrawBroadPhase() const noexcept + { + return debugDrawFlags & SHUtilities::ConvertEnum(DebugDrawFlags::BROAD_PHASE_AABB); + } + + bool SHPhysicsSystem::GetDrawContactPoints() const noexcept + { + return debugDrawFlags & SHUtilities::ConvertEnum(DebugDrawFlags::CONTACT_POINTS); + } + + bool SHPhysicsSystem::GetDrawContactNormals() const noexcept + { + return debugDrawFlags & SHUtilities::ConvertEnum(DebugDrawFlags::CONTACT_NORMALS); + } + const SHPhysicsSystem::CollisionEvents& SHPhysicsSystem::GetCollisionInfo() const noexcept { return collisionInfo; @@ -181,6 +214,96 @@ namespace SHADE } } + void SHPhysicsSystem::SetDrawColliders(bool shouldDraw) noexcept + { + static constexpr auto FLAG_VALUE = SHUtilities::ConvertEnum(DebugDrawFlags::COLLIDER); + shouldDraw ? debugDrawFlags |= FLAG_VALUE : debugDrawFlags &= ~(FLAG_VALUE); + + if (world == nullptr) + { + SHLOGV_WARNING("No physics world has been initialised!") + return; + } + + world->getDebugRenderer().setIsDebugItemDisplayed + ( + rp3d::DebugRenderer::DebugItem::COLLISION_SHAPE, + shouldDraw + ); + } + + void SHPhysicsSystem::SetDrawColliderAABBs(bool shouldDraw) noexcept + { + static constexpr auto FLAG_VALUE = SHUtilities::ConvertEnum(DebugDrawFlags::COLLIDER_AABB); + shouldDraw ? debugDrawFlags |= FLAG_VALUE : debugDrawFlags &= ~(FLAG_VALUE); + + if (world == nullptr) + { + SHLOGV_WARNING("No physics world has been initialised!") + return; + } + + world->getDebugRenderer().setIsDebugItemDisplayed + ( + rp3d::DebugRenderer::DebugItem::COLLIDER_AABB, + shouldDraw + ); + } + + void SHPhysicsSystem::SetDrawBroadPhase(bool shouldDraw) noexcept + { + static constexpr auto FLAG_VALUE = SHUtilities::ConvertEnum(DebugDrawFlags::BROAD_PHASE_AABB); + shouldDraw ? debugDrawFlags |= FLAG_VALUE : debugDrawFlags &= ~(FLAG_VALUE); + + if (world == nullptr) + { + SHLOGV_WARNING("No physics world has been initialised!") + return; + } + + world->getDebugRenderer().setIsDebugItemDisplayed + ( + rp3d::DebugRenderer::DebugItem::COLLIDER_BROADPHASE_AABB, + shouldDraw + ); + } + + void SHPhysicsSystem::SetDrawContactPoints(bool shouldDraw) noexcept + { + static constexpr auto FLAG_VALUE = SHUtilities::ConvertEnum(DebugDrawFlags::CONTACT_POINTS); + shouldDraw ? debugDrawFlags |= FLAG_VALUE : debugDrawFlags &= ~(FLAG_VALUE); + + if (world == nullptr) + { + SHLOGV_WARNING("No physics world has been initialised!") + return; + } + + world->getDebugRenderer().setIsDebugItemDisplayed + ( + rp3d::DebugRenderer::DebugItem::CONTACT_POINT, + shouldDraw + ); + } + + void SHPhysicsSystem::SetDrawContactNormals(bool shouldDraw) noexcept + { + static constexpr auto FLAG_VALUE = SHUtilities::ConvertEnum(DebugDrawFlags::CONTACT_NORMALS); + shouldDraw ? debugDrawFlags |= FLAG_VALUE : debugDrawFlags &= ~(FLAG_VALUE); + + if (world == nullptr) + { + SHLOGV_WARNING("No physics world has been initialised!") + return; + } + + world->getDebugRenderer().setIsDebugItemDisplayed + ( + rp3d::DebugRenderer::DebugItem::CONTACT_NORMAL, + shouldDraw + ); + } + /*-----------------------------------------------------------------------------------*/ /* Public Function Member Definitions */ /*-----------------------------------------------------------------------------------*/ @@ -198,6 +321,7 @@ namespace SHADE world = factory.createPhysicsWorld(settings); world->setEventListener(this); + world->setIsDebugRenderingEnabled(true); // Set up solvers world->setContactsPositionCorrectionTechnique(rp3d::ContactsPositionCorrectionTechnique::SPLIT_IMPULSES); @@ -323,7 +447,7 @@ namespace SHADE auto* scriptingSystem = SHSystemManager::GetSystem(); if (scriptingSystem == nullptr) { - SHLOGV_WARNING("Unable to invoke FixedUpdate() on scripts due to missing SHScriptEngine!"); + SHLOGV_ERROR("Unable to invoke FixedUpdate() on scripts due to missing SHScriptEngine!"); } fixedTimeStep = 1.0 / physicsSystem->fixedDT; @@ -353,7 +477,7 @@ namespace SHADE auto* scriptingSystem = SHSystemManager::GetSystem(); if (scriptingSystem == nullptr) { - SHLOGV_WARNING("Unable to invoke collision and trigger script events due to missing SHScriptEngine!"); + SHLOGV_ERROR("Unable to invoke collision and trigger script events due to missing SHScriptEngine!"); } // Interpolate transforms for rendering @@ -369,6 +493,40 @@ namespace SHADE } } + void SHPhysicsSystem::PhysicsDebugDraw::Execute(double) noexcept + { + const auto* PHYSICS_SYSTEM = reinterpret_cast(GetSystem()); + if (PHYSICS_SYSTEM->debugDrawFlags == 0) + return; + + auto* debugDrawSystem = SHSystemManager::GetSystem(); + if (debugDrawSystem == nullptr) + { + SHLOGV_ERROR("Unable to debug draw physics objects due to missing SHDebugDrawSystem!"); + return; + } + + const auto& RP3D_DEBUG_RENDERER = PHYSICS_SYSTEM->world->getDebugRenderer(); + + const auto& LINES = RP3D_DEBUG_RENDERER.getLines(); + const auto& TRIANGLES = RP3D_DEBUG_RENDERER.getTriangles(); + + // Draw all lines + for (uint32_t i = 0; i < RP3D_DEBUG_RENDERER.getNbLines(); ++i) + { + const auto& LINE = LINES[i]; + debugDrawSystem->DrawLine(SHColour{ LINE.color1 }, LINE.point1, LINE.point2); + } + + for (uint32_t i = 0; i < RP3D_DEBUG_RENDERER.getNbTriangles(); ++i) + { + const auto& TRIANGLE = TRIANGLES[i]; + SHColour triColour{ TRIANGLE.color1 }; + triColour.a() = 1.0f; + debugDrawSystem->DrawTri(triColour, TRIANGLE.point1, TRIANGLE.point2, TRIANGLE.point3); + } + } + void SHPhysicsSystem::onContact(const CallbackData& callbackData) { for (uint32_t i = 0; i < callbackData.getNbContactPairs(); ++i) diff --git a/SHADE_Engine/src/Physics/SHPhysicsSystem.h b/SHADE_Engine/src/Physics/SHPhysicsSystem.h index 1d773618..05e6e57e 100644 --- a/SHADE_Engine/src/Physics/SHPhysicsSystem.h +++ b/SHADE_Engine/src/Physics/SHPhysicsSystem.h @@ -51,6 +51,15 @@ namespace SHADE using CollisionEvents = std::vector; + enum class DebugDrawFlags : uint8_t + { + COLLIDER = 1 + , COLLIDER_AABB = 2 + , BROAD_PHASE_AABB = 4 + , CONTACT_POINTS = 8 + , CONTACT_NORMALS = 16 + }; + /*---------------------------------------------------------------------------------*/ /* Constructors & Destructor */ /*---------------------------------------------------------------------------------*/ @@ -69,6 +78,12 @@ namespace SHADE [[nodiscard]] uint16_t GetNumberVelocityIterations () const noexcept; [[nodiscard]] uint16_t GetNumberPositionIterations () const noexcept; + [[nodiscard]] bool GetDrawColliders () const noexcept; + [[nodiscard]] bool GetDrawColliderAABBs () const noexcept; + [[nodiscard]] bool GetDrawBroadPhase () const noexcept; + [[nodiscard]] bool GetDrawContactPoints () const noexcept; + [[nodiscard]] bool GetDrawContactNormals () const noexcept; + [[nodiscard]] const CollisionEvents& GetCollisionInfo () const noexcept; [[nodiscard]] const CollisionEvents& GetTriggerInfo () const noexcept; @@ -85,6 +100,13 @@ namespace SHADE void SetWorldSettings (const WorldSettings& settings) const noexcept; + // TODO(Diren): Can the debug draw flags be done through an enum? + void SetDrawColliders (bool shouldDraw) noexcept; + void SetDrawColliderAABBs (bool shouldDraw) noexcept; + void SetDrawBroadPhase (bool shouldDraw) noexcept; + void SetDrawContactPoints (bool shouldDraw) noexcept; + void SetDrawContactNormals (bool shouldDraw) noexcept; + /*---------------------------------------------------------------------------------*/ /* Function Members */ /*---------------------------------------------------------------------------------*/ @@ -105,48 +127,31 @@ namespace SHADE class SH_API PhysicsPreUpdate final : public SHSystemRoutine { public: - /*-------------------------------------------------------------------------------*/ - /* Constructors & Destructor */ - /*-------------------------------------------------------------------------------*/ PhysicsPreUpdate(); - - /*-------------------------------------------------------------------------------*/ - /* Function Members */ - /*-------------------------------------------------------------------------------*/ - void Execute(double dt) noexcept override; }; class SH_API PhysicsFixedUpdate final : public SHFixedSystemRoutine { public: - /*-------------------------------------------------------------------------------*/ - /* Constructors & Destructor */ - /*-------------------------------------------------------------------------------*/ PhysicsFixedUpdate(); - - /*-------------------------------------------------------------------------------*/ - /* Function Members */ - /*-------------------------------------------------------------------------------*/ - void Execute (double dt) noexcept override; }; class SH_API PhysicsPostUpdate final : public SHSystemRoutine { public: - /*-------------------------------------------------------------------------------*/ - /* Constructors & Destructor */ - /*-------------------------------------------------------------------------------*/ PhysicsPostUpdate(); + void Execute(double dt) noexcept override; + }; - /*-------------------------------------------------------------------------------*/ - /* Function Members */ - /*-------------------------------------------------------------------------------*/ - + class SH_API PhysicsDebugDraw final : public SHSystemRoutine + { + public: + PhysicsDebugDraw(); void Execute(double dt) noexcept override; }; @@ -162,6 +167,7 @@ namespace SHADE /*---------------------------------------------------------------------------------*/ bool worldUpdated; + uint8_t debugDrawFlags; double interpolationFactor; double fixedDT; diff --git a/SHADE_Engine/src/Tools/SHUtilities.h b/SHADE_Engine/src/Tools/SHUtilities.h index b3d840e7..287a827e 100644 --- a/SHADE_Engine/src/Tools/SHUtilities.h +++ b/SHADE_Engine/src/Tools/SHUtilities.h @@ -39,7 +39,7 @@ namespace SHADE * @param[in] enumClassMember A member of the specified enum class. * @returns The value of the enum class member in the output type. */ - template + template > static constexpr OutputType ConvertEnum(InputType enumClassMember) noexcept; /** From 27526dfd92dfa820f2eb72d7afac3f0fb6496e2f Mon Sep 17 00:00:00 2001 From: Diren D Bharwani Date: Wed, 2 Nov 2022 16:12:47 +0800 Subject: [PATCH 26/27] Fixed relative size for sphere colliders --- .../Editor/EditorWindow/Inspector/SHEditorComponentView.hpp | 4 ++-- SHADE_Engine/src/Physics/SHCollider.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp index 6f03a55e..20615fdc 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp +++ b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp @@ -265,9 +265,9 @@ namespace SHADE { const SHVec3& TF_WORLD_SCALE = transformComponent->GetWorldScale(); const float MAX_SCALE = SHMath::Max({ TF_WORLD_SCALE.x, TF_WORLD_SCALE.y, TF_WORLD_SCALE.z }); - return sphere->GetRadius() / MAX_SCALE; + return (sphere->GetRadius() / MAX_SCALE) * 2.0f; }, - [collider](float const& value) { collider->SetBoundingSphere(value); }); + [collider](float const& value) { collider->SetBoundingSphere(value); }); } else if (collider->GetType() == SHCollider::Type::CAPSULE) { diff --git a/SHADE_Engine/src/Physics/SHCollider.cpp b/SHADE_Engine/src/Physics/SHCollider.cpp index 6cea3dc1..6d455d67 100644 --- a/SHADE_Engine/src/Physics/SHCollider.cpp +++ b/SHADE_Engine/src/Physics/SHCollider.cpp @@ -212,7 +212,7 @@ namespace SHADE const SHVec3 TF_WORLD_SCALE = transformComponent->GetWorldScale(); const float MAX_SCALE = SHMath::Max({ TF_WORLD_SCALE.x, TF_WORLD_SCALE.y, TF_WORLD_SCALE.z }); - worldRadius *= MAX_SCALE; + worldRadius *= MAX_SCALE * 0.5f; } if (type == Type::SPHERE) From ebc94225e76f1c0ff29b042f90c2342a52ac32c9 Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Wed, 2 Nov 2022 17:04:31 +0800 Subject: [PATCH 27/27] Merge remote-tracking branch 'origin/main' into SP3-1-Rendering --- Assets/Shaders/DebugDraw_FS.glsl | 17 + Assets/Shaders/DebugDraw_FS.shshaderb | Bin 0 -> 673 bytes Assets/Shaders/DebugDraw_FS.shshaderb.shmeta | 3 + Assets/Shaders/DebugDraw_VS.glsl | 24 + Assets/Shaders/DebugDraw_VS.shshaderb | Bin 0 -> 1513 bytes Assets/Shaders/DebugDraw_VS.shshaderb.shmeta | 3 + Assets/Shaders/DeferredComposite_CS.shshaderb | Bin 5501 -> 5501 bytes .../DeferredComposite_CS.shshaderb.shmeta | 2 +- Assets/Shaders/Kirsch_CS.shshaderb | Bin 5909 -> 5909 bytes Assets/Shaders/PureCopy_CS.shshaderb | Bin 1273 -> 1273 bytes Assets/Shaders/SSAOBlur_CS.shshaderb | Bin 4669 -> 4669 bytes Assets/Shaders/SSAO_CS.shshaderb | Bin 6125 -> 6125 bytes Assets/Shaders/TestCube_FS.shshaderb | Bin 2545 -> 2545 bytes Assets/Shaders/TestCube_FS.shshaderb.shmeta | 2 +- Assets/Shaders/TestCube_VS.shshaderb | Bin 3689 -> 3689 bytes Assets/Shaders/TestCube_VS.shshaderb.shmeta | 2 +- .../src/Application/SBApplication.cpp | 16 +- SHADE_Application/src/Scenes/SBTestScene.cpp | 8 +- SHADE_Engine/premake5.lua | 2 +- .../src/Assets/Asset Types/SHShaderAsset.h | 11 +- .../Compilers/SHShaderSourceCompiler.cpp | 201 +- .../Libraries/Loaders/SHTextBasedLoader.h | 4 + SHADE_Engine/src/Assets/SHAssetMacros.h | 9 +- SHADE_Engine/src/Assets/SHAssetManager.cpp | 6 + .../src/Camera/SHCameraArmComponent.cpp | 68 + .../src/Camera/SHCameraArmComponent.h | 44 + SHADE_Engine/src/Camera/SHCameraComponent.cpp | 2 +- SHADE_Engine/src/Camera/SHCameraComponent.h | 4 +- SHADE_Engine/src/Camera/SHCameraDirector.cpp | 2 + SHADE_Engine/src/Camera/SHCameraDirector.h | 3 +- SHADE_Engine/src/Camera/SHCameraSystem.cpp | 168 +- SHADE_Engine/src/Camera/SHCameraSystem.h | 20 +- .../ECS_Base/Managers/SHComponentManager.cpp | 13 + .../src/ECS_Base/Managers/SHEntityManager.cpp | 11 +- .../src/ECS_Base/Managers/SHEntityManager.h | 2 + .../src/ECS_Base/Managers/SHSystemManager.cpp | 2 +- .../src/Editor/DragDrop/SHDragDrop.hpp | 6 +- .../AssetBrowser/SHAssetBrowser.cpp | 160 +- .../AssetBrowser/SHAssetBrowser.h | 13 +- .../HierarchyPanel/SHHierarchyPanel.cpp | 190 +- .../HierarchyPanel/SHHierarchyPanel.h | 6 +- .../Inspector/SHEditorComponentView.h | 12 + .../Inspector/SHEditorComponentView.hpp | 159 +- .../Inspector/SHEditorInspector.cpp | 39 +- .../EditorWindow/MenuBar/SHEditorMenuBar.cpp | 20 +- .../EditorWindow/MenuBar/SHEditorMenuBar.h | 6 + .../ViewportWindow/SHEditorViewport.cpp | 89 +- .../ViewportWindow/SHEditorViewport.h | 3 +- .../src/Editor/Gizmos/SHTransformGizmo.cpp | 5 +- SHADE_Engine/src/Editor/SHEditor.cpp | 6 +- .../src/Editor/{SHEditor.hpp => SHEditor.h} | 4 +- SHADE_Engine/src/Editor/SHEditorUI.cpp | 46 +- SHADE_Engine/src/Editor/SHEditorUI.h | 8 + SHADE_Engine/src/Editor/SHEditorWidgets.hpp | 122 +- SHADE_Engine/src/Events/SHEventDefines.h | 3 + .../Graphics/Commands/SHVkCommandBuffer.cpp | 5 + .../src/Graphics/Commands/SHVkCommandBuffer.h | 1 + .../Graphics/MiddleEnd/Batching/SHBatch.cpp | 11 +- .../MiddleEnd/Batching/SHSuperBatch.cpp | 6 +- .../MiddleEnd/Interface/SHDebugDrawSystem.cpp | 202 + .../MiddleEnd/Interface/SHDebugDrawSystem.h | 159 + .../MiddleEnd/Interface/SHDebugDrawSystem.hpp | 48 + .../MiddleEnd/Interface/SHGraphicsSystem.cpp | 111 +- .../MiddleEnd/Interface/SHGraphicsSystem.h | 32 +- .../Interface/SHGraphicsSystemInterface.cpp | 77 + .../Interface/SHGraphicsSystemInterface.h | 52 + .../MiddleEnd/Materials/SHMaterialSpec.h | 36 + .../MiddleEnd/Meshes/SHPrimitiveGenerator.cpp | 165 +- .../MiddleEnd/Meshes/SHPrimitiveGenerator.h | 65 +- .../Shaders/SHShaderModuleLibrary.cpp | 139 - .../MiddleEnd/Shaders/SHShaderModuleLibrary.h | 44 - .../src/Graphics/Pipeline/SHVkPipeline.h | 3 +- .../src/Graphics/Windowing/SHWindow.cpp | 41 +- .../src/Graphics/Windowing/SHWindow.h | 9 +- SHADE_Engine/src/Math/SHColour.cpp | 172 +- SHADE_Engine/src/Math/SHColour.h | 50 +- SHADE_Engine/src/Math/SHMath.h | 2 + .../Math/Transform/SHTransformComponent.cpp | 7 +- .../src/Math/Transform/SHTransformSystem.cpp | 6 +- SHADE_Engine/src/Math/Vector/SHVec4.cpp | 1 + SHADE_Engine/src/Math/Vector/SHVec4.h | 2 + .../Components/SHColliderComponent.cpp | 10 +- .../Physics/Components/SHColliderComponent.h | 1 + .../Components/SHRigidBodyComponent.cpp | 317 +- .../Physics/Components/SHRigidBodyComponent.h | 31 +- SHADE_Engine/src/Physics/SHCollider.cpp | 15 +- SHADE_Engine/src/Physics/SHCollider.h | 5 +- SHADE_Engine/src/Physics/SHPhysicsObject.cpp | 106 +- SHADE_Engine/src/Physics/SHPhysicsObject.h | 1 - SHADE_Engine/src/Physics/SHPhysicsSystem.cpp | 276 +- SHADE_Engine/src/Physics/SHPhysicsSystem.h | 91 +- SHADE_Engine/src/Physics/SHPhysicsSystem.hpp | 84 + .../src/Physics/SHPhysicsSystemInterface.cpp | 65 + .../src/Physics/SHPhysicsSystemInterface.h | 46 + SHADE_Engine/src/Physics/SHPhysicsUtils.cpp | 93 + SHADE_Engine/src/Physics/SHPhysicsUtils.h | 116 + .../src/Reflection/SHReflectionMetadata.h | 1 + .../src/Resource/SHResourceManager.cpp | 17 +- SHADE_Engine/src/Resource/SHResourceManager.h | 31 +- .../src/Resource/SHResourceManager.hpp | 206 +- SHADE_Engine/src/Scripting/SHScriptEngine.cpp | 11 +- SHADE_Engine/src/Scripting/SHScriptEngine.h | 6 + .../src/Scripting/SHScriptEngineRoutines.cpp | 2 +- .../Serialization/Prefab/SHPrefabManager.cpp | 56 + .../Serialization/Prefab/SHPrefabManager.h | 28 + .../src/Serialization/SHSerialization.cpp | 107 +- .../Serialization/SHSerializationHelper.hpp | 432 +- SHADE_Engine/src/Tools/Dialog/SHWinDialog.cpp | 71 + SHADE_Engine/src/Tools/Dialog/SHWinDialog.h | 36 + SHADE_Engine/src/Tools/SHDebugDraw.cpp | 73 + SHADE_Engine/src/Tools/SHDebugDraw.h | 101 + SHADE_Engine/src/Tools/SHLog.h | 2 +- SHADE_Managed/premake5.lua | 10 +- SHADE_Managed/src/Components/Camera.cxx | 127 + SHADE_Managed/src/Components/Camera.hxx | 70 + SHADE_Managed/src/Components/CameraArm.cxx | 51 + SHADE_Managed/src/Components/CameraArm.hxx | 40 + SHADE_Managed/src/Components/Component.cxx | 5 + SHADE_Managed/src/Components/Component.hxx | 9 + SHADE_Managed/src/Components/RigidBody.cxx | 8 + SHADE_Managed/src/Components/RigidBody.hxx | 5 + SHADE_Managed/src/Components/Transform.cxx | 26 - SHADE_Managed/src/Components/Transform.hxx | 24 - SHADE_Managed/src/Editor/Editor.cxx | 15 +- SHADE_Managed/src/Engine/Application.cxx | 71 + SHADE_Managed/src/Engine/Application.hxx | 77 + SHADE_Managed/src/Engine/ECS.cxx | 4 + SHADE_Managed/src/Engine/GameObject.cxx | 50 +- SHADE_Managed/src/Engine/GameObject.hxx | 19 +- SHADE_Managed/src/Engine/Time.cxx | 13 + SHADE_Managed/src/Engine/Time.hxx | 23 +- SHADE_Managed/src/Input/Input.cxx | 7 + SHADE_Managed/src/Input/Input.hxx | 154 +- SHADE_Managed/src/Math/Vector2.cxx | 16 + SHADE_Managed/src/Math/Vector2.hxx | 16 + SHADE_Managed/src/Math/Vector3.cxx | 18 + SHADE_Managed/src/Math/Vector3.hxx | 16 + SHADE_Managed/src/Physics/CollisionInfo.cxx | 36 + SHADE_Managed/src/Physics/CollisionInfo.hxx | 66 + SHADE_Managed/src/Scripts/Script.cxx | 81 +- SHADE_Managed/src/Scripts/Script.hxx | 92 +- SHADE_Managed/src/Scripts/ScriptStore.cxx | 132 +- SHADE_Managed/src/Scripts/ScriptStore.hxx | 4 + .../src/Serialisation/ReflectionUtilities.cxx | 10 + TempScriptsFolder/CameraControl.cs | 22 + TempScriptsFolder/PhysicsTest.cs | 31 +- TempScriptsFolder/PrintWhenActive.cs | 11 + TempScriptsFolder/ThirdPersonCamera.cs | 55 + TempShaderFolder/DeferredCompositeCs.glsl | 83 - TempShaderFolder/DeferredCompositeCs.spv | Bin 4656 -> 0 bytes TempShaderFolder/TestCubeFs.spv | Bin 2536 -> 0 bytes TempShaderFolder/TestCubeVs.spv | Bin 3296 -> 0 bytes bin/Debug/SHADE_CSharp.xml | 1029 +++ bin/Debug/SHADE_Managed.xml | 6250 +++++++++++++++++ bin/Release/SHADE_CSharp.xml | 1029 +++ bin/Release/SHADE_Managed.xml | 6250 +++++++++++++++++ 156 files changed, 20008 insertions(+), 1476 deletions(-) create mode 100644 Assets/Shaders/DebugDraw_FS.glsl create mode 100644 Assets/Shaders/DebugDraw_FS.shshaderb create mode 100644 Assets/Shaders/DebugDraw_FS.shshaderb.shmeta create mode 100644 Assets/Shaders/DebugDraw_VS.glsl create mode 100644 Assets/Shaders/DebugDraw_VS.shshaderb create mode 100644 Assets/Shaders/DebugDraw_VS.shshaderb.shmeta create mode 100644 SHADE_Engine/src/Camera/SHCameraArmComponent.cpp create mode 100644 SHADE_Engine/src/Camera/SHCameraArmComponent.h create mode 100644 SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.h rename SHADE_Engine/src/Editor/{SHEditor.hpp => SHEditor.h} (98%) create mode 100644 SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.cpp create mode 100644 SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.h create mode 100644 SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.hpp create mode 100644 SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystemInterface.cpp create mode 100644 SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystemInterface.h create mode 100644 SHADE_Engine/src/Graphics/MiddleEnd/Materials/SHMaterialSpec.h delete mode 100644 SHADE_Engine/src/Graphics/MiddleEnd/Shaders/SHShaderModuleLibrary.cpp delete mode 100644 SHADE_Engine/src/Graphics/MiddleEnd/Shaders/SHShaderModuleLibrary.h create mode 100644 SHADE_Engine/src/Physics/SHPhysicsSystem.hpp create mode 100644 SHADE_Engine/src/Physics/SHPhysicsSystemInterface.cpp create mode 100644 SHADE_Engine/src/Physics/SHPhysicsSystemInterface.h create mode 100644 SHADE_Engine/src/Physics/SHPhysicsUtils.cpp create mode 100644 SHADE_Engine/src/Physics/SHPhysicsUtils.h create mode 100644 SHADE_Engine/src/Serialization/Prefab/SHPrefabManager.cpp create mode 100644 SHADE_Engine/src/Serialization/Prefab/SHPrefabManager.h create mode 100644 SHADE_Engine/src/Tools/Dialog/SHWinDialog.cpp create mode 100644 SHADE_Engine/src/Tools/Dialog/SHWinDialog.h create mode 100644 SHADE_Engine/src/Tools/SHDebugDraw.cpp create mode 100644 SHADE_Engine/src/Tools/SHDebugDraw.h create mode 100644 SHADE_Managed/src/Components/Camera.cxx create mode 100644 SHADE_Managed/src/Components/Camera.hxx create mode 100644 SHADE_Managed/src/Components/CameraArm.cxx create mode 100644 SHADE_Managed/src/Components/CameraArm.hxx create mode 100644 SHADE_Managed/src/Engine/Application.cxx create mode 100644 SHADE_Managed/src/Engine/Application.hxx create mode 100644 SHADE_Managed/src/Physics/CollisionInfo.cxx create mode 100644 SHADE_Managed/src/Physics/CollisionInfo.hxx create mode 100644 TempScriptsFolder/CameraControl.cs create mode 100644 TempScriptsFolder/PrintWhenActive.cs create mode 100644 TempScriptsFolder/ThirdPersonCamera.cs delete mode 100644 TempShaderFolder/DeferredCompositeCs.glsl delete mode 100644 TempShaderFolder/DeferredCompositeCs.spv delete mode 100644 TempShaderFolder/TestCubeFs.spv delete mode 100644 TempShaderFolder/TestCubeVs.spv create mode 100644 bin/Debug/SHADE_CSharp.xml create mode 100644 bin/Debug/SHADE_Managed.xml create mode 100644 bin/Release/SHADE_CSharp.xml create mode 100644 bin/Release/SHADE_Managed.xml diff --git a/Assets/Shaders/DebugDraw_FS.glsl b/Assets/Shaders/DebugDraw_FS.glsl new file mode 100644 index 00000000..266f8ad4 --- /dev/null +++ b/Assets/Shaders/DebugDraw_FS.glsl @@ -0,0 +1,17 @@ +#version 450 +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable +#extension GL_EXT_nonuniform_qualifier : require + +layout(location = 0) in struct +{ + vec4 vertColor; +} In; + + +layout(location = 0) out vec4 outColor; + +void main() +{ + outColor = In.vertColor; +} \ No newline at end of file diff --git a/Assets/Shaders/DebugDraw_FS.shshaderb b/Assets/Shaders/DebugDraw_FS.shshaderb new file mode 100644 index 0000000000000000000000000000000000000000..7b59688597046295970cf20f6afdc8f52cb72e81 GIT binary patch literal 673 zcmY*W%Sr=55Nz`{F)u~Eg@{KX1c@SuLX@xw3jy`uZCH~@9Np}$`v~|aeve<}MX+kK zkvP!PQ`OboGd-=(oTMwCJ1&cCNmc5yyP~8mIWQtMDW%@BAM9QfPkV#2J|zvwr%Gy? zQkDWdZQ&S?fo<3htOXr;G{7m3sv=)VDnMb`YIuL6A{{uP6KfT{I8z-e|M^u<;^@By zA>+-J>v;3TnQJvT?FY`}4RtE4GkSVdp6?}|nfc*Dy(f-qW=4mIR~fg)W6K_?Nf4+g z{&2N&ji=Srgy>|Jn!VCGna+3TBS*XZ4b+Q~{#@2Wb)8f32(#c7BKESyIt_wSao^vJU-MZK-@cbF_ml&r1ts&^F!I;P;5~_dQ1t@#3!m>%egFUf literal 0 HcmV?d00001 diff --git a/Assets/Shaders/DebugDraw_FS.shshaderb.shmeta b/Assets/Shaders/DebugDraw_FS.shshaderb.shmeta new file mode 100644 index 00000000..58f62b44 --- /dev/null +++ b/Assets/Shaders/DebugDraw_FS.shshaderb.shmeta @@ -0,0 +1,3 @@ +Name: DebugDraw_FS +ID: 36671027 +Type: 2 diff --git a/Assets/Shaders/DebugDraw_VS.glsl b/Assets/Shaders/DebugDraw_VS.glsl new file mode 100644 index 00000000..cb0886d1 --- /dev/null +++ b/Assets/Shaders/DebugDraw_VS.glsl @@ -0,0 +1,24 @@ +#version 450 +#extension GL_KHR_vulkan_glsl : enable + +layout(location = 0) in vec4 aVertexPos; +layout(location = 1) in vec4 aVertColor; + + +layout(location = 0) out struct +{ + vec4 vertColor; // location 0 + +} Out; + +layout(set = 2, binding = 0) uniform CameraData +{ + vec4 position; + mat4 vpMat; +} cameraData; + +void main() +{ + gl_Position = cameraData.vpMat * vec4 (aVertexPos.xyz, 1.0f); + Out.vertColor = aVertColor; +} \ No newline at end of file diff --git a/Assets/Shaders/DebugDraw_VS.shshaderb b/Assets/Shaders/DebugDraw_VS.shshaderb new file mode 100644 index 0000000000000000000000000000000000000000..2d8cd0edd9ff60919d7c1931f06ee0ea6390bff0 GIT binary patch literal 1513 zcmZ9L-)a*<6vn4XH?6I0t+jvD8k0t?S}0zq2%;jXY%d~dDR{dqn?(k;n~-dRdgUwl zN(;o82j)6VA>#-}&bJo5{kTz_?Yfb(V}-Fe_%w9F>sSG&Lc{teS?~!`?;j zcv1|GU%q+)W!=;r6V8UY;q*m)FJqfytV!-l4kb?|b^U7Ef9t@aGKIY;?DxaorzjbX zqDk>ROQX!@X*96oG%4&Xg||G%vw4zD2lIqLjQN~_YF$;1uUT}Kj=!YiBK;;)Xo;ia z8%}Ithq=%t$EOE}+q}52Ka`m>rH`8B>t=RzVkbqMC+U@s3E-P%*_AI)pY+ZO^xM?l zjW5%2d=eLNSqm6z zhGXGyxQqU@kRG@@aWN{wsW4{8^1H{V35?xi%ms`YcnlqkI|=1Mhlk(y+>y;X6$^}* zfwM~vHk@16Fg;L*5tnns4Hbj=99*;8vRU|%IU diff --git a/Assets/Shaders/SSAO_CS.shshaderb b/Assets/Shaders/SSAO_CS.shshaderb index 6bb4abcd8018cac584ecc8f8b59b86984eb528d7..69f7a44f1a9f7144e912c70a533a67027a7e737b 100644 GIT binary patch delta 10 RcmaE>|5l$-VI$)kaR3|5l%oX(QtsaR3-<1MvU= diff --git a/Assets/Shaders/TestCube_FS.shshaderb b/Assets/Shaders/TestCube_FS.shshaderb index b0113dc7799a94fb1c40720187c05a9b26a2617c..95b4f62ae89c1bd3dc23f684757a7298c60833a3 100644 GIT binary patch delta 10 Rcmew;{85-uU?bxPP5>7&1H}LU delta 10 Rcmew;{85;ZaU6?1GWGF diff --git a/Assets/Shaders/TestCube_FS.shshaderb.shmeta b/Assets/Shaders/TestCube_FS.shshaderb.shmeta index 42f270af..fbe098b1 100644 --- a/Assets/Shaders/TestCube_FS.shshaderb.shmeta +++ b/Assets/Shaders/TestCube_FS.shshaderb.shmeta @@ -1,3 +1,3 @@ Name: TestCube_FS -ID: 37450402 +ID: 46377769 Type: 2 diff --git a/Assets/Shaders/TestCube_VS.shshaderb b/Assets/Shaders/TestCube_VS.shshaderb index fb2965a83900e01b2591230c1de83828ad72c658..fb282b4df95c458e637710753ab4b5beb88c23e2 100644 GIT binary patch delta 10 RcmaDU^HPS9aU){}9{?5H12q5u delta 10 RcmaDU^HPS9VIyM(9{?5C12g~t diff --git a/Assets/Shaders/TestCube_VS.shshaderb.shmeta b/Assets/Shaders/TestCube_VS.shshaderb.shmeta index b133437b..5c9f895f 100644 --- a/Assets/Shaders/TestCube_VS.shshaderb.shmeta +++ b/Assets/Shaders/TestCube_VS.shshaderb.shmeta @@ -1,3 +1,3 @@ Name: TestCube_VS -ID: 41688429 +ID: 39210065 Type: 2 diff --git a/SHADE_Application/src/Application/SBApplication.cpp b/SHADE_Application/src/Application/SBApplication.cpp index de548060..b865f028 100644 --- a/SHADE_Application/src/Application/SBApplication.cpp +++ b/SHADE_Application/src/Application/SBApplication.cpp @@ -4,7 +4,7 @@ //#define SHEDITOR #ifdef SHEDITOR -#include "Editor/SHEditor.hpp" +#include "Editor/SHEditor.h" //#include "Scenes/SBEditorScene.h" #endif // SHEDITOR @@ -31,6 +31,7 @@ #include "FRC/SHFramerateController.h" #include "AudioSystem/SHAudioSystem.h" #include "Camera/SHCameraSystem.h" +#include "Graphics/MiddleEnd/Interface/SHDebugDrawSystem.h" // Components #include "Graphics/MiddleEnd/Interface/SHRenderable.h" @@ -42,6 +43,7 @@ #include "Assets/SHAssetManager.h" #include "Tools/SHLogger.h" +#include "Tools/SHDebugDraw.h" using namespace SHADE; @@ -69,6 +71,7 @@ namespace Sandbox SHGraphicsSystem* graphicsSystem = static_cast(SHSystemManager::GetSystem()); SHSystemManager::CreateSystem(); SHSystemManager::CreateSystem(); + SHSystemManager::CreateSystem(); #ifdef SHEDITOR SDL_Init(SDL_INIT_VIDEO); @@ -90,11 +93,12 @@ namespace Sandbox SHSystemManager::RegisterRoutine(); SHSystemManager::RegisterRoutine(); + SHSystemManager::RegisterRoutine(); SHSystemManager::RegisterRoutine(); SHSystemManager::RegisterRoutine(); - SHSystemManager::RegisterRoutine(); + //SHSystemManager::RegisterRoutine(); SHSystemManager::RegisterRoutine(); #ifdef SHEDITOR @@ -108,13 +112,10 @@ namespace Sandbox SHComponentManager::CreateComponentSparseSet(); SHComponentManager::CreateComponentSparseSet(); SHComponentManager::CreateComponentSparseSet(); - SHComponentManager::CreateComponentSparseSet(); + //SHComponentManager::CreateComponentSparseSet(); SHAssetManager::Load(); - auto id = SHFamilyID::GetID(); - auto id2 = SHFamilyID::GetID(); - auto id3 = SHFamilyID::GetID(); SHSystemManager::RegisterRoutine(); @@ -126,6 +127,9 @@ namespace Sandbox SHSceneManager::InitSceneManager("TestScene"); SHFrameRateController::UpdateFRC(); + + // Link up SHDebugDraw + SHDebugDraw::Init(SHSystemManager::GetSystem()); } void SBApplication::Update(void) diff --git a/SHADE_Application/src/Scenes/SBTestScene.cpp b/SHADE_Application/src/Scenes/SBTestScene.cpp index 23b57dfc..a5b3b546 100644 --- a/SHADE_Application/src/Scenes/SBTestScene.cpp +++ b/SHADE_Application/src/Scenes/SBTestScene.cpp @@ -16,7 +16,10 @@ #include "Assets/SHAssetManager.h" #include "Camera/SHCameraComponent.h" +#include "Math/SHColour.h" #include "Resource/SHResourceManager.h" +#include "Graphics/MiddleEnd/Interface/SHDebugDrawSystem.h" +#include "Tools/SHDebugDraw.h" using namespace SHADE; @@ -128,7 +131,6 @@ namespace Sandbox floorRigidBody.SetType(SHRigidBodyComponent::Type::STATIC); auto* floorBox = floorCollider.AddBoundingBox(); - floorBox->SetHalfExtents(floorTransform.GetWorldScale() * 0.5f); // Create blank entity with a script //testObj = SHADE::SHEntityManager::CreateEntity(); @@ -160,7 +162,7 @@ namespace Sandbox SHComponentManager::RemoveComponent (0); auto ambientLight = SHEntityManager::CreateEntity(); - SHComponentManager::GetComponent(ambientLight)->SetColor(SHVec4(1.0f, 1.0f, 1.0f, 1.0f)); + SHComponentManager::GetComponent(ambientLight)->SetColor(SHColour::WHITE); SHComponentManager::GetComponent(ambientLight)->SetStrength(0.25f); SHComponentManager::GetComponent(ambientLight)->SetType(SH_LIGHT_TYPE::AMBIENT); } @@ -187,6 +189,8 @@ namespace Sandbox SHADE::SHScriptEngine* scriptEngine = static_cast(SHADE::SHSystemManager::GetSystem()); scriptEngine->RemoveAllScripts(testObj); } + + SHDebugDraw::Cube(SHColour::CRIMSON, SHVec3(1.0f, 0.0f, 0.0f), SHVec3(1.0f, 1.0f, 1.0f)); } void SBTestScene::Render() diff --git a/SHADE_Engine/premake5.lua b/SHADE_Engine/premake5.lua index 18920194..bc1f6a03 100644 --- a/SHADE_Engine/premake5.lua +++ b/SHADE_Engine/premake5.lua @@ -8,7 +8,7 @@ project "SHADE_Engine" pchheader "SHpch.h" pchsource "%{prj.location}/src/SHpch.cpp" staticruntime "off" - + buildoptions{"/bigobj"} files { "%{prj.location}/src/**.h", diff --git a/SHADE_Engine/src/Assets/Asset Types/SHShaderAsset.h b/SHADE_Engine/src/Assets/Asset Types/SHShaderAsset.h index adcd215a..d71c1bb3 100644 --- a/SHADE_Engine/src/Assets/Asset Types/SHShaderAsset.h +++ b/SHADE_Engine/src/Assets/Asset Types/SHShaderAsset.h @@ -10,6 +10,7 @@ *****************************************************************************/ #pragma once +#include #include "SHAssetData.h" #include "SH_API.h" #include @@ -17,12 +18,14 @@ namespace SHADE { + //! Tighter control over types of shaders. Maps directly to their + //! equivalent vk::ShaderStageFlagBits. enum class SH_SHADER_TYPE : uint8_t { - VERTEX, - FRAGMENT, - COMPUTE, - INAVLID_TYPE + VERTEX = static_cast(vk::ShaderStageFlagBits::eVertex), + FRAGMENT = static_cast(vk::ShaderStageFlagBits::eFragment), + COMPUTE = static_cast(vk::ShaderStageFlagBits::eCompute), + INAVLID_TYPE = std::numeric_limits::max() }; struct SH_API SHShaderAsset : SHAssetData diff --git a/SHADE_Engine/src/Assets/Libraries/Compilers/SHShaderSourceCompiler.cpp b/SHADE_Engine/src/Assets/Libraries/Compilers/SHShaderSourceCompiler.cpp index 329e34e9..fd1f6d8a 100644 --- a/SHADE_Engine/src/Assets/Libraries/Compilers/SHShaderSourceCompiler.cpp +++ b/SHADE_Engine/src/Assets/Libraries/Compilers/SHShaderSourceCompiler.cpp @@ -19,144 +19,145 @@ namespace SHADE { - std::string SHShaderSourceCompiler::CompileShaderSourceToBinary(AssetPath path, SHShaderAsset const& data) noexcept - { - std::string newPath{ path.string() }; + std::string SHShaderSourceCompiler::CompileShaderSourceToBinary(AssetPath path, SHShaderAsset const& data) noexcept + { + std::string newPath{ path.string() }; newPath = newPath.substr(0, newPath.find_last_of('.')); newPath += SHADER_BUILT_IN_EXTENSION.data(); - std::ofstream file{ newPath, std::ios::binary | std::ios::out | std::ios::trunc }; + std::ofstream file{ newPath, std::ios::binary | std::ios::out | std::ios::trunc }; - file.write( - reinterpret_cast(& data.shaderType), sizeof(uint8_t) - ); + file.write( + reinterpret_cast(& data.shaderType), sizeof(uint8_t) + ); - size_t const byteCount = sizeof(uint32_t) * data.spirvBinary.size(); + size_t const byteCount = sizeof(uint32_t) * data.spirvBinary.size(); - file.write( - reinterpret_cast(&byteCount), sizeof(size_t) - ); + file.write( + reinterpret_cast(&byteCount), sizeof(size_t) + ); - file.write( - reinterpret_cast(data.spirvBinary.data()), byteCount - ); + file.write( + reinterpret_cast(data.spirvBinary.data()), byteCount + ); - file.close(); + file.close(); - return newPath; - } + return newPath; + } - SHShaderAsset const* SHShaderSourceCompiler::CompileShaderSourceToMemory(std::string const& data, std::string const& name, SH_SHADER_TYPE type) noexcept - { - // shaderc compiler - shaderc::Compiler compiler; - shaderc::CompileOptions options; + SHShaderAsset const* SHShaderSourceCompiler::CompileShaderSourceToMemory(std::string const& data, std::string const& name, SH_SHADER_TYPE type) noexcept + { + // shaderc compiler + shaderc::Compiler compiler; + shaderc::CompileOptions options; - options.AddMacroDefinition("MY_DEFINE", "1"); + options.AddMacroDefinition("MY_DEFINE", "1"); - //TODO: Check if we need optimisation levels when compiling into spirv - // Set optimization levels - //if (opLevel != shaderc_optimization_level_zero) - // options.SetOptimizationLevel(opLevel); + //TODO: Check if we need optimisation levels when compiling into spirv + // Set optimization levels + //if (opLevel != shaderc_optimization_level_zero) + // options.SetOptimizationLevel(opLevel); - // Attempt to get the shaderc equivalent shader stage - shaderc_shader_kind shaderKind; - switch (type) - { - case SH_SHADER_TYPE::VERTEX: - shaderKind = shaderc_shader_kind::shaderc_glsl_vertex_shader; - break; - case SH_SHADER_TYPE::FRAGMENT: - shaderKind = shaderc_shader_kind::shaderc_glsl_fragment_shader; - break; - case SH_SHADER_TYPE::COMPUTE: - shaderKind = shaderc_shader_kind::shaderc_glsl_compute_shader; - break; - default: - shaderKind = shaderc_shader_kind::shaderc_glsl_vertex_shader; - break; - } + // Attempt to get the shaderc equivalent shader stage + shaderc_shader_kind shaderKind; + switch (type) + { + case SH_SHADER_TYPE::VERTEX: + shaderKind = shaderc_shader_kind::shaderc_glsl_vertex_shader; + break; + case SH_SHADER_TYPE::FRAGMENT: + shaderKind = shaderc_shader_kind::shaderc_glsl_fragment_shader; + break; + case SH_SHADER_TYPE::COMPUTE: + shaderKind = shaderc_shader_kind::shaderc_glsl_compute_shader; + break; + default: + shaderKind = shaderc_shader_kind::shaderc_glsl_vertex_shader; + break; + } - // Compile the shader and get the result - shaderc::SpvCompilationResult compileResult = compiler.CompileGlslToSpv(data, shaderKind, name.c_str(), options); + // Compile the shader and get the result + shaderc::SpvCompilationResult compileResult = compiler.CompileGlslToSpv(data, shaderKind, name.c_str(), options); - if (compileResult.GetCompilationStatus() != shaderc_compilation_status_success) - { - SHLOG_ERROR("Shaderc failed to compile GLSL shader to binary | " + compileResult.GetErrorMessage()); - return nullptr; - } + if (compileResult.GetCompilationStatus() != shaderc_compilation_status_success) + { + SHLOG_ERROR("Shaderc failed to compile GLSL shader to binary | " + compileResult.GetErrorMessage()); + return nullptr; + } - auto result = new SHShaderAsset(); - result->spirvBinary.resize(compileResult.end() - compileResult.begin()); + auto result = new SHShaderAsset(); + result->spirvBinary.resize(compileResult.end() - compileResult.begin()); - std::ranges::copy(compileResult.begin(), compileResult.end(), result->spirvBinary.data()); + std::ranges::copy(compileResult.begin(), compileResult.end(), result->spirvBinary.data()); result->name = name; result->shaderType = type; - return result; - } + return result; + } - SH_SHADER_TYPE SHShaderSourceCompiler::GetShaderTypeFromFilename(std::string name) noexcept - { - for (auto i { 0}; i < SHADER_TYPE_MAX_COUNT; ++i) - { - if (name.find(SHADER_IDENTIFIERS[i].data()) != std::string::npos) - { - return static_cast(i); - } - } + SH_SHADER_TYPE SHShaderSourceCompiler::GetShaderTypeFromFilename(std::string name) noexcept + { + for (auto i { 0 }; i < SHADER_TYPE_MAX_COUNT; ++i) + { + const auto& [SHADER_SUFFIX, SHADER_TYPE] = SHADER_IDENTIFIERS[i]; + if (name.find(SHADER_SUFFIX.data()) != std::string::npos) + { + return SHADER_TYPE; + } + } - return SH_SHADER_TYPE::INAVLID_TYPE; - } + return SH_SHADER_TYPE::INAVLID_TYPE; + } std::optional SHShaderSourceCompiler::LoadAndCompileShader(AssetPath path) noexcept - { - auto type = GetShaderTypeFromFilename(path.filename().string()); + { + auto type = GetShaderTypeFromFilename(path.filename().string()); - if (type == SH_SHADER_TYPE::INAVLID_TYPE) - { - SHLOG_ERROR("Invalid filename for shaders, follow suffix in SHAssetMacros.h: {}", path.string()); - return {}; - } + if (type == SH_SHADER_TYPE::INAVLID_TYPE) + { + SHLOG_ERROR("Invalid filename for shaders, follow suffix in SHAssetMacros.h: {}", path.string()); + return {}; + } path.make_preferred(); - std::ifstream file{ path.string(), std::ios::in }; + std::ifstream file{ path.string(), std::ios::in }; - if (file.is_open()) - { - std::stringstream stream; + if (file.is_open()) + { + std::stringstream stream; - stream << file.rdbuf(); + stream << file.rdbuf(); - std::string const content = stream.str(); + std::string const content = stream.str(); - auto data = CompileShaderSourceToMemory(content, path.filename().string(), type); + auto data = CompileShaderSourceToMemory(content, path.filename().string(), type); - if (data == nullptr) - { - return{}; - } + if (data == nullptr) + { + return{}; + } - return CompileShaderSourceToBinary(path, *data); - } + return CompileShaderSourceToBinary(path, *data); + } - SHLOG_ERROR("Unable to open shader file: {}", path.string()); + SHLOG_ERROR("Unable to open shader file: {}", path.string()); - return {}; - } + return {}; + } - std::optional SHShaderSourceCompiler::CompileShaderFromString - (std::string const& string, AssetPath path, SH_SHADER_TYPE type) noexcept - { - auto const data = CompileShaderSourceToMemory(string, path.filename().string(), type); + std::optional SHShaderSourceCompiler::CompileShaderFromString + (std::string const& string, AssetPath path, SH_SHADER_TYPE type) noexcept + { + auto const data = CompileShaderSourceToMemory(string, path.filename().string(), type); - if (data == nullptr) - { - return{}; - } + if (data == nullptr) + { + return{}; + } - return CompileShaderSourceToBinary(path, *data); - } + return CompileShaderSourceToBinary(path, *data); + } } diff --git a/SHADE_Engine/src/Assets/Libraries/Loaders/SHTextBasedLoader.h b/SHADE_Engine/src/Assets/Libraries/Loaders/SHTextBasedLoader.h index 80771058..b74c6c94 100644 --- a/SHADE_Engine/src/Assets/Libraries/Loaders/SHTextBasedLoader.h +++ b/SHADE_Engine/src/Assets/Libraries/Loaders/SHTextBasedLoader.h @@ -11,6 +11,10 @@ #pragma once #include "SHAssetLoader.h" +#include "Assets/Asset Types/SHPrefabAsset.h" +#include "Assets/Asset Types/SHSceneAsset.h" +#include "Assets/Asset Types/SHMaterialAsset.h" + namespace SHADE { struct SHTextBasedLoader : SHAssetLoader diff --git a/SHADE_Engine/src/Assets/SHAssetMacros.h b/SHADE_Engine/src/Assets/SHAssetMacros.h index a21a9840..3376a2d5 100644 --- a/SHADE_Engine/src/Assets/SHAssetMacros.h +++ b/SHADE_Engine/src/Assets/SHAssetMacros.h @@ -13,6 +13,7 @@ #include #include #include +#include "Asset Types/SHShaderAsset.h" // FMOD Fwd Declare namespace FMOD @@ -113,10 +114,10 @@ constexpr std::string_view VERTEX_SHADER{ "_VS" }; constexpr std::string_view FRAGMENT_SHADER{ "_FS" }; constexpr std::string_view COMPUTER_SHADER{ "_CS" }; -constexpr std::string_view SHADER_IDENTIFIERS[] = { - VERTEX_SHADER, - FRAGMENT_SHADER, - COMPUTER_SHADER +constexpr std::pair SHADER_IDENTIFIERS[] = { + std::make_pair(VERTEX_SHADER, SHADE::SH_SHADER_TYPE::VERTEX), + std::make_pair(FRAGMENT_SHADER, SHADE::SH_SHADER_TYPE::FRAGMENT), + std::make_pair(COMPUTER_SHADER, SHADE::SH_SHADER_TYPE::COMPUTE) }; constexpr size_t SHADER_TYPE_MAX_COUNT{ 3 }; diff --git a/SHADE_Engine/src/Assets/SHAssetManager.cpp b/SHADE_Engine/src/Assets/SHAssetManager.cpp index 682eb9ec..4897fc42 100644 --- a/SHADE_Engine/src/Assets/SHAssetManager.cpp +++ b/SHADE_Engine/src/Assets/SHAssetManager.cpp @@ -151,19 +151,23 @@ namespace SHADE ****************************************************************************/ AssetID SHAssetManager::CreateNewAsset(AssetType type, AssetName name) noexcept { + SHAssetData* data = nullptr; std::string newPath{ ASSET_ROOT }; switch (type) { case AssetType::PREFAB: newPath += PREFAB_FOLDER; + data = new SHPrefabAsset(); break; case AssetType::SCENE: newPath += SCENE_FOLDER; + data = new SHSceneAsset(); break; case AssetType::MATERIAL: newPath += MATERIAL_FOLDER; + data = new SHMaterialAsset(); break; default: @@ -189,6 +193,8 @@ namespace SHADE ) }); + assetData.emplace(id, data); + return id; } diff --git a/SHADE_Engine/src/Camera/SHCameraArmComponent.cpp b/SHADE_Engine/src/Camera/SHCameraArmComponent.cpp new file mode 100644 index 00000000..9cb221ff --- /dev/null +++ b/SHADE_Engine/src/Camera/SHCameraArmComponent.cpp @@ -0,0 +1,68 @@ +#include "SHpch.h" +#include "SHCameraArmComponent.h" + + + +namespace SHADE +{ + + SHCameraArmComponent::SHCameraArmComponent() + :pitch(0.0f), yaw(0.0f), armLength(1.0f),offset(), dirty(true), lookAtCameraOrigin(true) + { + + } + + + SHVec3 const& SHCameraArmComponent::GetOffset() const noexcept + { + return offset; + } + + float SHCameraArmComponent::GetPitch() const noexcept + { + return pitch; + } + + float SHCameraArmComponent::GetYaw() const noexcept + { + return yaw; + } + + float SHCameraArmComponent::GetArmLength() const noexcept + { + return armLength; + } + + void SHCameraArmComponent::SetPitch(float pitch) noexcept + { + this->pitch = pitch; + dirty = true; + } + + void SHCameraArmComponent::SetYaw(float yaw) noexcept + { + this->yaw = yaw; + dirty = true; + } + + void SHCameraArmComponent::SetArmLength(float length) noexcept + { + this->armLength = length; + dirty = true; + } + +}//namespace SHADE + + +RTTR_REGISTRATION +{ + using namespace SHADE; + using namespace rttr; + + registration::class_("Camera Arm Component") + .property("Arm Pitch", &SHCameraArmComponent::GetPitch, &SHCameraArmComponent::SetPitch) + .property("Arm Yaw", &SHCameraArmComponent::GetYaw, &SHCameraArmComponent::SetYaw) + .property("Arm Length", &SHCameraArmComponent::GetArmLength, &SHCameraArmComponent::SetArmLength) + .property("Look At Camera Origin", &SHCameraArmComponent::lookAtCameraOrigin); + +} \ No newline at end of file diff --git a/SHADE_Engine/src/Camera/SHCameraArmComponent.h b/SHADE_Engine/src/Camera/SHCameraArmComponent.h new file mode 100644 index 00000000..2b81a808 --- /dev/null +++ b/SHADE_Engine/src/Camera/SHCameraArmComponent.h @@ -0,0 +1,44 @@ +#pragma once + + +#include +#include "ECS_Base/Components/SHComponent.h" +#include "Math/SHMatrix.h" +#include "SH_API.h" + +namespace SHADE +{ + class SH_API SHCameraArmComponent final: public SHComponent + { + private: + float pitch; + float yaw; + float armLength; + + bool dirty; + SHVec3 offset; + + public: + friend class SHCameraSystem; + SHCameraArmComponent(); + virtual ~SHCameraArmComponent() = default; + + bool lookAtCameraOrigin; + //Getters + //SHMatrix const& GetMatrix() const noexcept; + SHVec3 const& GetOffset() const noexcept; + float GetPitch() const noexcept; + float GetYaw() const noexcept; + float GetArmLength() const noexcept; + + //Setters + void SetPitch(float pitch) noexcept; + void SetYaw(float yaw) noexcept; + void SetArmLength(float length) noexcept; + + protected: + + + }; + +}//namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/Camera/SHCameraComponent.cpp b/SHADE_Engine/src/Camera/SHCameraComponent.cpp index 31afe2ac..ac451df5 100644 --- a/SHADE_Engine/src/Camera/SHCameraComponent.cpp +++ b/SHADE_Engine/src/Camera/SHCameraComponent.cpp @@ -13,7 +13,7 @@ namespace SHADE , width(1920.0f), height(1080.0f), zNear(0.01f), zFar(10000.0f), fov(90.0f), movementSpeed(1.0f), turnSpeed(0.5f) , perspProj(true), dirtyView(true), dirtyProj(true) , viewMatrix(), projMatrix() - , position() + , position(), offset() { ComponentFamily::GetID(); } diff --git a/SHADE_Engine/src/Camera/SHCameraComponent.h b/SHADE_Engine/src/Camera/SHCameraComponent.h index f5e08af4..b778b8fa 100644 --- a/SHADE_Engine/src/Camera/SHCameraComponent.h +++ b/SHADE_Engine/src/Camera/SHCameraComponent.h @@ -33,7 +33,7 @@ namespace SHADE SHVec3 position; bool perspProj; - + SHVec3 offset; @@ -41,7 +41,7 @@ namespace SHADE friend class SHCameraSystem; SHCameraComponent(); - ~SHCameraComponent(); + virtual ~SHCameraComponent(); //Getters and setters. diff --git a/SHADE_Engine/src/Camera/SHCameraDirector.cpp b/SHADE_Engine/src/Camera/SHCameraDirector.cpp index 559897c0..98341098 100644 --- a/SHADE_Engine/src/Camera/SHCameraDirector.cpp +++ b/SHADE_Engine/src/Camera/SHCameraDirector.cpp @@ -1,6 +1,7 @@ #include "SHpch.h" #include "SHCameraDirector.h" #include "SHCameraComponent.h" +#include "SHCameraArmComponent.h" #include "ECS_Base/Managers/SHComponentManager.h" #include "ECS_Base/SHECSMacros.h" #include "ECS_Base/Managers/SHEntityManager.h" @@ -48,6 +49,7 @@ namespace SHADE viewMatrix = camComponent->GetViewMatrix(); projMatrix = camComponent->GetProjMatrix(); } + } void SHCameraDirector::SetMainCamera(SHCameraComponent& camera) noexcept diff --git a/SHADE_Engine/src/Camera/SHCameraDirector.h b/SHADE_Engine/src/Camera/SHCameraDirector.h index 5d09788b..6d5404c5 100644 --- a/SHADE_Engine/src/Camera/SHCameraDirector.h +++ b/SHADE_Engine/src/Camera/SHCameraDirector.h @@ -21,6 +21,7 @@ namespace SHADE EntityID mainCameraEID; EntityID transitionCameraEID; + SHMatrix GetViewMatrix() const noexcept; SHMatrix GetProjMatrix() const noexcept; @@ -35,7 +36,7 @@ namespace SHADE protected: SHMatrix viewMatrix; SHMatrix projMatrix; - + }; typedef Handle DirectorHandle; diff --git a/SHADE_Engine/src/Camera/SHCameraSystem.cpp b/SHADE_Engine/src/Camera/SHCameraSystem.cpp index 609805f8..d5bd414d 100644 --- a/SHADE_Engine/src/Camera/SHCameraSystem.cpp +++ b/SHADE_Engine/src/Camera/SHCameraSystem.cpp @@ -1,10 +1,12 @@ #include "SHpch.h" #include "SHCameraSystem.h" +#include "SHCameraArmComponent.h" #include "Math/SHMathHelpers.h" #include "Input/SHInputManager.h" #include "Math/Vector/SHVec2.h" #include "ECS_Base/Managers/SHComponentManager.h" #include "Math/Transform/SHTransformComponent.h" +#include namespace SHADE @@ -59,6 +61,7 @@ namespace SHADE } UpdateCameraComponent(editorCamera); + } void SHCameraSystem::EditorCameraUpdate::Execute(double dt) noexcept { @@ -112,6 +115,8 @@ namespace SHADE //std::cout << "Camera position: " << camera.position.x << " " << camera.position.y << std::endl; system->UpdateCameraComponent(system->editorCamera); + + system->DecomposeViewMatrix(camera.viewMatrix, camera.pitch, camera.yaw, camera.roll, camera.position); } void SHCameraSystem::Init(void) @@ -121,6 +126,9 @@ namespace SHADE editorCamera.SetYaw(0.0f); editorCamera.SetRoll(0.0f); editorCamera.movementSpeed = 2.0f; + + SHComponentManager::CreateComponentSparseSet(); + SHComponentManager::CreateComponentSparseSet(); } @@ -134,6 +142,26 @@ namespace SHADE return &editorCamera; } + void SHCameraSystem::UpdatePivotArmComponent(SHCameraArmComponent& pivot) noexcept + { + if (pivot.dirty) + { + + SHVec3 offset{ 0.0f,0.0f, pivot.GetArmLength() }; + offset = SHVec3::RotateX(offset, -(SHMath::DegreesToRadians(pivot.GetPitch()))); + offset = SHVec3::RotateY(offset, (SHMath::DegreesToRadians(pivot.GetYaw()))); + + + //pivot.rtMatrix = SHMatrix::RotateX(SHMath::DegreesToRadians(pivot.GetPitch())) + // * SHMatrix::RotateY(SHMath::DegreesToRadians(pivot.GetYaw())) + // * SHMatrix::Translate(SHVec3(0.0f , 0.0f, pivot.GetArmLength())); + + pivot.offset = offset; + // pivot.rtMatrix = SHMatrix::Inverse(pivot.rtMatrix); + } + } + + void SHCameraSystem::UpdateCameraComponent(SHCameraComponent& camera) noexcept { if (SHComponentManager::HasComponent(camera.GetEID()) == true && &camera != &editorCamera) @@ -151,6 +179,15 @@ namespace SHADE if (camera.dirtyView) { + camera.offset = SHVec3{ 0.0f }; + if (SHComponentManager::HasComponent(camera.GetEID())) + { + auto arm = SHComponentManager::GetComponent(camera.GetEID()); + camera.offset = arm->GetOffset(); + if(arm->lookAtCameraOrigin) + CameraLookAt(camera, camera.position); + } + SHVec3 view, right, UP; @@ -171,9 +208,12 @@ namespace SHADE camera.viewMatrix(2, 1) = view[1]; camera.viewMatrix(2, 2) = view[2]; - camera.viewMatrix(0, 3) = -right.Dot(camera.position); - camera.viewMatrix(1, 3) = -UP.Dot(camera.position); - camera.viewMatrix(2, 3) = -view.Dot(camera.position); + camera.viewMatrix(0, 3) = -right.Dot(camera.position + camera.offset); + camera.viewMatrix(1, 3) = -UP.Dot(camera.position + camera.offset); + camera.viewMatrix(2, 3) = -view.Dot(camera.position + camera.offset); + + + camera.dirtyView = false; } @@ -221,6 +261,8 @@ namespace SHADE SHVec3 up = { 0.0f,1.0f,0.0f }; + + target = SHVec3::RotateX(target, SHMath::DegreesToRadians(camera.pitch)); target = SHVec3::RotateY(target, SHMath::DegreesToRadians(camera.yaw)); target += camera.position; @@ -241,6 +283,13 @@ namespace SHADE { SHCameraSystem* system = static_cast(GetSystem()); auto& dense = SHComponentManager::GetDense(); + auto& pivotDense = SHComponentManager::GetDense(); + + for (auto& pivot : pivotDense) + { + system->UpdatePivotArmComponent(pivot); + } + for (auto& cam : dense) { system->UpdateCameraComponent(cam); @@ -274,18 +323,115 @@ namespace SHADE } void SHCameraSystem::ClampCameraRotation(SHCameraComponent& camera) noexcept { + constexpr float clampVal = 85.0f; + if (camera.pitch > clampVal) + camera.SetPitch(clampVal); + if (camera.pitch < -clampVal) + camera.SetPitch(-clampVal); + if (camera.roll > clampVal) + camera.SetRoll(clampVal); + if (camera.roll < -clampVal) + camera.SetRoll(-clampVal); - if (camera.pitch > 85) - camera.SetPitch(85); - if (camera.pitch < -85) - camera.SetPitch(-85); - if (camera.roll > 85) - camera.SetRoll(85); - if (camera.roll < -85) - camera.SetRoll(-85); + while (camera.yaw > 360) + camera.yaw -= 360; + while (camera.yaw < -360) + camera.yaw += 360; } + void SHCameraSystem::SetMainCamera(EntityID eid, size_t directorIndex) noexcept + { + if (SHComponentManager::HasComponent(eid) && directorIndex < directorHandleList.size()) + directorHandleList[directorIndex]->SetMainCamera(*SHComponentManager::GetComponent(eid)); + else + { + SHLOG_WARNING("Set Main Camera warning: Entity does not have camera component or director does not exist.") + } + } + + void SHCameraSystem::DecomposeViewMatrix(SHMatrix const& viewMatrix, float& pitch, float& yaw, float& roll, SHVec3& pos) noexcept + { + + float initPitch = pitch; + SHVec3 initPos = pos; + SHVec3 translate3, scale; + SHQuaternion quat; + + //SHMatrix viewInverse = viewMatrix; + + viewMatrix.Decompose(translate3, quat, scale); + yaw = 180+ SHMath::RadiansToDegrees(quat.ToEuler().y); + pitch = -SHMath::RadiansToDegrees(quat.ToEuler().x); + + SHVec4 dotPos{ -viewMatrix(0,3),-viewMatrix(1,3), -viewMatrix(2,3), 1.0f }; + SHMatrix mtx = viewMatrix; + mtx(0, 3) = 0.0f; + mtx(1, 3) = 0.0f; + mtx(2, 3) = 0.0f; + mtx.Transpose(); + mtx = SHMatrix::Inverse(mtx); + SHVec4 translate = mtx* dotPos; + + pos.x = translate.x; + pos.y = translate.y; + pos.z = translate.z; + + } + void SHCameraSystem::SetCameraViewMatrix(SHCameraComponent& camera, SHMatrix const& viewMatrix) noexcept + { + DecomposeViewMatrix(viewMatrix, camera.pitch, camera.yaw, camera.roll, camera.position); + camera.dirtyView = true; + } + + void SHCameraSystem::CameraLookAt(SHCameraComponent& camera, SHVec3 target) noexcept + { + + if (camera.position == target) + { + //lets off set it abit so the view is nt fked + target.z -= 0.0001f; + } + SHVec3 forward, right, upVec; + + SHVec3 up = { 0.0f,1.0f,0.0f }; + + + ////SHVec3::RotateZ(target, SHMath::DegreesToRadians(camera.roll)); + + //target = SHVec3::Normalise(target); + + SHVec3::RotateZ(up, camera.roll); + up = SHVec3::Normalise(up); + + + forward = target - (camera.position + camera.offset); forward = SHVec3::Normalise(forward); + right = SHVec3::Cross(forward, up); right = SHVec3::Normalise(right); + upVec = SHVec3::Cross(forward, right); + + + SHMatrix viewMtx; + viewMtx = SHMatrix::Identity; + viewMtx(0, 0) = right[0]; + viewMtx(0, 1) = right[1]; + viewMtx(0, 2) = right[2]; + + viewMtx(1, 0) = upVec[0]; + viewMtx(1, 1) = upVec[1]; + viewMtx(1, 2) = upVec[2]; + + viewMtx(2, 0) = forward[0]; + viewMtx(2, 1) = forward[1]; + viewMtx(2, 2) = forward[2]; + + viewMtx(0, 3) = -right.Dot(camera.position + camera.offset); + viewMtx(1, 3) = -upVec.Dot(camera.position + camera.offset); + viewMtx(2, 3) = -forward.Dot(camera.position + camera.offset); + + + SetCameraViewMatrix(camera, viewMtx); + } + } diff --git a/SHADE_Engine/src/Camera/SHCameraSystem.h b/SHADE_Engine/src/Camera/SHCameraSystem.h index 68071160..98fd442f 100644 --- a/SHADE_Engine/src/Camera/SHCameraSystem.h +++ b/SHADE_Engine/src/Camera/SHCameraSystem.h @@ -9,6 +9,9 @@ namespace SHADE { + + class SHCameraArmComponent; + class SH_API SHCameraSystem final : public SHSystem { private: @@ -19,6 +22,11 @@ namespace SHADE SHResourceLibrary directorLibrary; std::vector directorHandleList; + + void UpdateCameraComponent(SHCameraComponent& camera) noexcept; + void UpdatePivotArmComponent(SHCameraArmComponent& pivot) noexcept; + + public: SHCameraSystem(void) = default; virtual ~SHCameraSystem(void) = default; @@ -39,7 +47,7 @@ namespace SHADE class SH_API CameraSystemUpdate final: public SHSystemRoutine { public: - CameraSystemUpdate() : SHSystemRoutine("Camera System Update", false) {}; + CameraSystemUpdate() : SHSystemRoutine("Camera System Update", true) {}; virtual void Execute(double dt)noexcept override final; }; friend class CameraSystemUpdate; @@ -51,12 +59,10 @@ namespace SHADE DirectorHandle GetDirector(size_t index) noexcept; void ClampCameraRotation(SHCameraComponent& camera) noexcept; void UpdateEditorCamera(double dt) noexcept; - protected: - - void UpdateCameraComponent(SHCameraComponent& camera) noexcept; - - - + void SetMainCamera(EntityID eid, size_t directorIndex) noexcept; + void DecomposeViewMatrix(SHMatrix const& matrix, float& pitch, float& yaw, float& roll, SHVec3& pos) noexcept; + void SetCameraViewMatrix(SHCameraComponent& camera, SHMatrix const& viewMatrix) noexcept; + void CameraLookAt(SHCameraComponent& camera, SHVec3 target) noexcept; }; diff --git a/SHADE_Engine/src/ECS_Base/Managers/SHComponentManager.cpp b/SHADE_Engine/src/ECS_Base/Managers/SHComponentManager.cpp index be78a146..8a715a49 100644 --- a/SHADE_Engine/src/ECS_Base/Managers/SHComponentManager.cpp +++ b/SHADE_Engine/src/ECS_Base/Managers/SHComponentManager.cpp @@ -33,12 +33,18 @@ namespace SHADE return; } + std::vector eventVec; + for (uint32_t i = 0; i < componentSet.Size(); ++i) { SHComponent* comp = (SHComponent*) componentSet.GetElement(i, EntityHandleGenerator::GetIndex(entityID)); if (comp) { comp->OnDestroy(); + SHComponentRemovedEvent eventData; + eventData.eid = entityID; + eventData.removedComponentType = i; + eventVec.push_back(eventData); } } @@ -51,8 +57,15 @@ namespace SHADE componentSet.RemoveElements(EntityHandleGenerator::GetIndex(entityID)); + for (auto& eventData : eventVec) + { + SHEventManager::BroadcastEvent(eventData, SH_COMPONENT_REMOVED_EVENT); + } + + //entityHandle.RemoveHandle(entityID); + } diff --git a/SHADE_Engine/src/ECS_Base/Managers/SHEntityManager.cpp b/SHADE_Engine/src/ECS_Base/Managers/SHEntityManager.cpp index bbf8d400..6ce4f277 100644 --- a/SHADE_Engine/src/ECS_Base/Managers/SHEntityManager.cpp +++ b/SHADE_Engine/src/ECS_Base/Managers/SHEntityManager.cpp @@ -213,5 +213,14 @@ namespace SHADE return SHSerialization::DeserializeEntityToSceneFromString(data); }*/ - + EntityID SHEntityManager::GetEntityByName(std::string const& name) noexcept + { + EntityID result = MAX_EID; + for (auto& entity : entityVec) + { + if (entity->name == name) + result = entity->GetEID(); + } + return result; + } } diff --git a/SHADE_Engine/src/ECS_Base/Managers/SHEntityManager.h b/SHADE_Engine/src/ECS_Base/Managers/SHEntityManager.h index f32ab2c4..911748bd 100644 --- a/SHADE_Engine/src/ECS_Base/Managers/SHEntityManager.h +++ b/SHADE_Engine/src/ECS_Base/Managers/SHEntityManager.h @@ -209,6 +209,8 @@ namespace SHADE //static EntityID DuplicateEntity(EntityID eid) noexcept; + static EntityID GetEntityByName(std::string const& name) noexcept; + protected: diff --git a/SHADE_Engine/src/ECS_Base/Managers/SHSystemManager.cpp b/SHADE_Engine/src/ECS_Base/Managers/SHSystemManager.cpp index 551233db..057568d6 100644 --- a/SHADE_Engine/src/ECS_Base/Managers/SHSystemManager.cpp +++ b/SHADE_Engine/src/ECS_Base/Managers/SHSystemManager.cpp @@ -29,7 +29,7 @@ namespace SHADE { system.second->Init(); #ifdef _DEBUG - std::cout << system.first << " Init" << std::endl; + SHLOG_INFO("Initialising System {}...", system.first) #endif } } diff --git a/SHADE_Engine/src/Editor/DragDrop/SHDragDrop.hpp b/SHADE_Engine/src/Editor/DragDrop/SHDragDrop.hpp index f9849d78..ce0615e1 100644 --- a/SHADE_Engine/src/Editor/DragDrop/SHDragDrop.hpp +++ b/SHADE_Engine/src/Editor/DragDrop/SHDragDrop.hpp @@ -6,12 +6,12 @@ namespace SHADE { //TODO: Convert to RTTR? - constexpr auto DRAG_EID = "DragEID"; - constexpr auto DRAG_RESOURCE = "DragResource"; - struct SHDragDrop { + using DragDropTag = std::string_view; + static constexpr DragDropTag DRAG_EID = "DragEID"; + static constexpr DragDropTag DRAG_RESOURCE = "DragResource"; static bool BeginSource(ImGuiDragDropFlags const flags = 0); /** * \brief Ends the DragDrop Source. ONLY CALL IF BeginSource returns true diff --git a/SHADE_Engine/src/Editor/EditorWindow/AssetBrowser/SHAssetBrowser.cpp b/SHADE_Engine/src/Editor/EditorWindow/AssetBrowser/SHAssetBrowser.cpp index caad9b10..8c71eb8f 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/AssetBrowser/SHAssetBrowser.cpp +++ b/SHADE_Engine/src/Editor/EditorWindow/AssetBrowser/SHAssetBrowser.cpp @@ -4,14 +4,16 @@ #include "Editor/IconsMaterialDesign.h" #include "Editor/SHImGuiHelpers.hpp" #include +#include #include "Assets/SHAssetManager.h" +#include "Editor/IconsFontAwesome6.h" #include "Editor/DragDrop/SHDragDrop.hpp" namespace SHADE { SHAssetBrowser::SHAssetBrowser() - :SHEditorWindow("\xee\x8b\x87 Asset Browser", ImGuiWindowFlags_MenuBar) + :SHEditorWindow("\xee\x8b\x87 Asset Browser", ImGuiWindowFlags_MenuBar), rootFolder(SHAssetManager::GetRootFolder()), prevFolder(rootFolder), currentFolder(rootFolder) { } @@ -23,62 +25,140 @@ namespace SHADE void SHAssetBrowser::Update() { SHEditorWindow::Update(); - if(Begin()) + if (Begin()) { + RecursivelyDrawTree(rootFolder); DrawMenuBar(); - auto const& assets = SHAssetManager::GetAllAssets(); - if(ImGui::BeginTable("AssetBrowserTable", 3)) - { - ImGui::TableNextColumn(); - ImGui::TableHeader("Asset ID"); - ImGui::TableNextColumn(); - ImGui::TableHeader("Name"); - ImGui::TableNextColumn(); - ImGui::TableHeader("Type"); - for(SHAsset const& asset : assets) - { - DrawAsset(asset); - } - ImGui::EndTable(); - } + DrawCurrentFolder(); } ImGui::End(); } void SHAssetBrowser::DrawMenuBar() { - if(ImGui::BeginMenuBar()) + if (ImGui::BeginMenuBar()) { ImGui::EndMenuBar(); } } - void SHAssetBrowser::DrawAsset(SHAsset const& asset) + ImRect SHAssetBrowser::RecursivelyDrawTree(FolderPointer folder) { - ImGui::PushID(asset.id); - ImGui::BeginGroup(); - - ImGui::TableNextColumn(); - ImGui::Selectable(std::format("{}", asset.id).data(), false, ImGuiSelectableFlags_SpanAllColumns); - if(SHDragDrop::BeginSource()) + auto const& subFolders = folder->subFolders; + auto const& files = folder->files; + const bool isSelected = std::ranges::find(selectedFolders, folder) != selectedFolders.end(); + ImGuiTreeNodeFlags flags = (subFolders.empty() && files.empty()) ? ImGuiTreeNodeFlags_Leaf : ImGuiTreeNodeFlags_OpenOnArrow; + if (isSelected) + flags |= ImGuiTreeNodeFlags_Selected; + if (folder == rootFolder) + flags |= ImGuiTreeNodeFlags_DefaultOpen; + + bool isOpen = ImGui::TreeNodeEx(folder, flags, "%s %s", ICON_MD_FOLDER, folder->name.data()); + const ImRect nodeRect = ImRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax()); + if(ImGui::IsItemClicked()) { - auto id = asset.id; - ImGui::Text("Moving Asset: %zu", id); - SHDragDrop::SetPayload(DRAG_RESOURCE, &id); - SHDragDrop::EndSource(); + selectedFolders.clear(); + selectedFolders.push_back(folder); + } + if (isOpen) + { + const ImColor treeLineColor = ImGui::GetColorU32(ImGuiCol_CheckMark); + const float horizontalOffset = 0.0f; + ImDrawList* drawList = ImGui::GetWindowDrawList(); + ImVec2 vertLineStart = ImGui::GetCursorScreenPos(); + vertLineStart.x += horizontalOffset; + ImVec2 vertLineEnd = vertLineStart; + for (auto const& subFolder : subFolders) + { + const float horizontalLineSize = 8.0f; + const ImRect childRect = RecursivelyDrawTree(subFolder); + const float midPoint = (childRect.Min.y + childRect.Max.y) * 0.5f; + drawList->AddLine(ImVec2(vertLineStart.x, midPoint), ImVec2(vertLineStart.x + horizontalLineSize, midPoint), treeLineColor, 1); + vertLineEnd.y = midPoint; + } + for (auto const& file : files) + { + const float horizontalLineSize = 25.0f; + const ImRect childRect = DrawFile(file); + const float midPoint = (childRect.Min.y + childRect.Max.y) * 0.5f; + drawList->AddLine(ImVec2(vertLineStart.x, midPoint), ImVec2(vertLineStart.x + horizontalLineSize, midPoint), treeLineColor, 1); + vertLineEnd.y = midPoint; + } + drawList->AddLine(vertLineStart, vertLineEnd, treeLineColor, 1); + ImGui::TreePop(); + } + return nodeRect; + } + + void SHAssetBrowser::DrawCurrentFolder() + { + //auto const& subFolders = currentFolder->subFolders; + //ImVec2 initialCursorPos = ImGui::GetCursorPos(); + //ImVec2 initialRegionAvail = ImGui::GetContentRegionAvail(); + //int maxTiles = initialRegionAvail.x / tileWidth; + //float maxX = (maxTiles - 1)*tileWidth; + //ImVec2 tilePos = initialCursorPos; + //for (auto const& subFolder : subFolders) + //{ + // ImGui::SetCursorPos(tilePos); + // ImGui::BeginGroup(); + // ImGui::PushStyleVar(ImGuiStyleVar_ItemInnerSpacing, {0.0f, 0.0f}); + // ImGui::Button(ICON_MD_FOLDER, {tileWidth}); + // ImGui::Text(subFolder->name.data()); + // ImGui::PopStyleVar(); + // ImGui::EndGroup(); + // if(tilePos.x >= maxX) + // { + // tilePos.x = initialCursorPos.x; + // } + // else + // { + // ImGui::SameLine(); + // tilePos.x += tileWidth; + // } + //} + } + + ImRect SHAssetBrowser::DrawFile(SHFile const& file) noexcept + { + if (file.assetMeta == nullptr) + return ImRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax()); + const bool isSelected = std::ranges::find(selectedAssets, file.assetMeta->id) != selectedAssets.end(); + ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_Leaf; + if (isSelected) + flags |= ImGuiTreeNodeFlags_Selected; + std::string icon{}; + + switch(file.assetMeta->type) + { + case AssetType::INVALID: break; + case AssetType::SHADER: icon = ICON_FA_FILE_CODE; break; + case AssetType::SHADER_BUILT_IN: icon = ICON_FA_FILE_CODE; break; + case AssetType::TEXTURE: icon = ICON_FA_IMAGES; break; + case AssetType::MESH: icon = ICON_FA_CUBES; break; + case AssetType::SCENE: icon = ICON_MD_IMAGE; break; + case AssetType::PREFAB: icon = ICON_FA_BOX_OPEN; break; + case AssetType::MATERIAL: break; + case AssetType::MAX_COUNT: break; + default: ; } - ImGui::TableNextColumn(); - ImGui::Text("%s", asset.name.c_str()); - - ImGui::TableNextColumn(); - ImGui::Text("%s", "Type"); - - ImGui::EndGroup(); - ImGui::PopID(); - - - + ImGui::TreeNodeEx(file.assetMeta, flags, "%s %s", icon.data(), file.assetMeta->name.data()); + const ImRect nodeRect = ImRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax()); + if(SHDragDrop::BeginSource()) + { + auto id = file.assetMeta->id; + ImGui::Text("Moving Asset: %s [%zu]", file.name.data(), file.assetMeta->id); + SHDragDrop::SetPayload(SHDragDrop::DRAG_RESOURCE, &id); + SHDragDrop::EndSource(); + } + if(ImGui::IsItemClicked()) + { + selectedAssets.clear(); + selectedAssets.push_back(file.assetMeta->id); + } + ImGui::TreePop(); + return nodeRect; } } diff --git a/SHADE_Engine/src/Editor/EditorWindow/AssetBrowser/SHAssetBrowser.h b/SHADE_Engine/src/Editor/EditorWindow/AssetBrowser/SHAssetBrowser.h index 0e3053bc..d56fc029 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/AssetBrowser/SHAssetBrowser.h +++ b/SHADE_Engine/src/Editor/EditorWindow/AssetBrowser/SHAssetBrowser.h @@ -1,7 +1,9 @@ #pragma once +#include "imgui_internal.h" #include "Assets/SHAsset.h" #include "Editor/EditorWindow/SHEditorWindow.h" +#include "Filesystem/SHFolder.h" namespace SHADE { @@ -16,9 +18,14 @@ namespace SHADE void Refresh(); private: void DrawMenuBar(); - void DrawAsset(SHAsset const& asset); + ImRect RecursivelyDrawTree(FolderPointer folder); + void DrawCurrentFolder(); + ImRect DrawFile(SHFile const& file) noexcept; - float idColumnWidth, nameColumnWidth, typeColumnWidth; + FolderPointer rootFolder, prevFolder, currentFolder; + std::vector selectedFolders; + std::vector selectedAssets; + static constexpr float tileWidth = 50.0f; }; -} \ No newline at end of file +} diff --git a/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp b/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp index f2f8d927..1b289a90 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp +++ b/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp @@ -6,7 +6,7 @@ //#==============================================================# //|| SHADE Includes || //#==============================================================# -#include "Editor/SHEditor.hpp" +#include "Editor/SHEditor.h" #include "Editor/SHImGuiHelpers.hpp" #include "Editor/SHEditorWidgets.hpp" #include "SHHierarchyPanel.h" @@ -48,15 +48,28 @@ namespace SHADE if (Begin()) { + if (skipFrame) + { + ImGui::End(); + skipFrame = false; + return; + } DrawMenuBar(); auto const& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); - if(const auto root = sceneGraph.GetRoot()) + + if (const auto root = sceneGraph.GetRoot()) { auto const& children = root->GetChildren(); - + for (const auto child : children) { - RecursivelyDrawEntityNode(child); + if (child) + RecursivelyDrawEntityNode(child); + if (skipFrame) + { + ImGui::End(); + return; + } } } else @@ -64,12 +77,36 @@ namespace SHADE SHLOG_WARNING("Scene Graph root is null! Unable to render hierarchy.") } - if(ImGui::IsWindowHovered() && !SHDragDrop::hasDragDrop && !ImGui::IsAnyItemHovered() && ImGui::IsMouseReleased(ImGuiMouseButton_Left)) + if (ImGui::IsWindowHovered() && !SHDragDrop::hasDragDrop && !ImGui::IsAnyItemHovered() && ImGui::IsMouseReleased(ImGuiMouseButton_Left)) { - if(auto editor = SHSystemManager::GetSystem()) + if (auto editor = SHSystemManager::GetSystem()) editor->selectedEntities.clear(); } ImGui::SeparatorEx(ImGuiSeparatorFlags_Horizontal); + if (ImGui::IsWindowFocused()) + { + if (ImGui::IsKeyDown(ImGuiKey_LeftCtrl) && ImGui::IsKeyReleased(ImGuiKey_A)) + { + SelectAllEntities(); + } + if (ImGui::IsKeyDown(ImGuiKey_LeftCtrl) && ImGui::IsKeyReleased(ImGuiKey_C)) + { + CopySelectedEntities(); + } + if (ImGui::IsKeyDown(ImGuiKey_LeftCtrl) && !ImGui::IsKeyDown(ImGuiKey_LeftShift) && ImGui::IsKeyReleased(ImGuiKey_V)) + { + PasteEntities(); + } + if (ImGui::IsKeyDown(ImGuiKey_LeftCtrl) && ImGui::IsKeyDown(ImGuiKey_LeftShift) && ImGui::IsKeyReleased(ImGuiKey_V)) + { + const auto editor = SHSystemManager::GetSystem(); + if (editor->selectedEntities.size() == 1) + { + PasteEntities(editor->selectedEntities.back()); + } + } + } + } ImGui::End(); } @@ -81,7 +118,7 @@ namespace SHADE void SHHierarchyPanel::SetScrollTo(EntityID eid) { - if(eid == MAX_EID) + if (eid == MAX_EID) return; scrollTo = eid; } @@ -93,8 +130,10 @@ namespace SHADE { if (ImGui::BeginMenuBar()) { - ImGui::SetCursorPosX(ImGui::GetContentRegionAvail().x * 0.75f); - if(ImGui::SmallButton(ICON_MD_DESELECT)) + auto size = ImGui::GetWindowSize(); + auto g = ImGui::GetCurrentContext(); + ImGui::SetCursorPosX(size.x - g->Style.FramePadding.x * 15.0f); + if (ImGui::SmallButton(ICON_MD_CLEAR_ALL)) { auto editor = SHSystemManager::GetSystem(); editor->selectedEntities.clear(); @@ -119,15 +158,17 @@ namespace SHADE } } - ImRect SHHierarchyPanel::RecursivelyDrawEntityNode(SHSceneNode* currentNode) + ImRect SHHierarchyPanel::RecursivelyDrawEntityNode(SHSceneNode* const currentNode) { + if (currentNode == nullptr) + return {}; auto const& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); //Get node data (Children, eid, selected) auto& children = currentNode->GetChildren(); EntityID eid = currentNode->GetEntityID(); - if(scrollTo != MAX_EID && eid == scrollTo) + if (scrollTo != MAX_EID && eid == scrollTo) { ImGui::SetScrollHereY(); scrollTo = MAX_EID; @@ -154,23 +195,27 @@ namespace SHADE if (SHDragDrop::BeginSource()) { std::string moveLabel = "Moving EID: "; - if(!isSelected) - editor->selectedEntities.push_back(eid); - for(int i = 0; i < static_cast(editor->selectedEntities.size()); ++i) + static std::vector draggingEntities = editor->selectedEntities; + if (!isSelected) { - moveLabel.append(std::to_string(editor->selectedEntities[i])); - if(i + 1 < static_cast(editor->selectedEntities.size())) + draggingEntities.clear(); + draggingEntities.push_back(eid); + } + for (int i = 0; i < static_cast(draggingEntities.size()); ++i) + { + moveLabel.append(std::to_string(draggingEntities[i])); + if (i + 1 < static_cast(draggingEntities.size())) { moveLabel.append(", "); } } ImGui::Text(moveLabel.c_str()); - SHDragDrop::SetPayload>(DRAG_EID, &editor->selectedEntities); + SHDragDrop::SetPayload>(SHDragDrop::DRAG_EID, &draggingEntities); SHDragDrop::EndSource(); } else if (SHDragDrop::BeginTarget()) //If Received DragDrop { - if (const std::vector* eidPayload = SHDragDrop::AcceptPayload>(DRAG_EID)) //If payload is valid + if (const std::vector* eidPayload = SHDragDrop::AcceptPayload>(SHDragDrop::DRAG_EID)) //If payload is valid { ParentSelectedEntities(eid); SHDragDrop::EndTarget(); @@ -178,37 +223,43 @@ namespace SHADE } //Context menu - if(ImGui::BeginPopupContextItem(std::to_string(eid).c_str())) + if (ImGui::BeginPopupContextItem(std::to_string(eid).c_str())) { - if(!isSelected) + if (!isSelected) { editor->selectedEntities.clear(); editor->selectedEntities.push_back(eid); } - if(ImGui::Selectable("Copy")) + if (ImGui::Selectable("Copy")) { - SHClipboardUtilities::WriteToClipboard(SHSerialization::SerializeEntitiesToString(editor->selectedEntities)); + CopySelectedEntities(); } - if(ImGui::Selectable("Paste")) + if (ImGui::Selectable("Paste")) { - SetScrollTo(SHSerialization::DeserializeEntitiesFromString(SHClipboardUtilities::GetDataFromClipboard())); + PasteEntities(); + skipFrame = true; + ImGui::EndPopup(); + if (isNodeOpen) + ImGui::TreePop(); + return nodeRect; } - if(ImGui::Selectable("Paste as Child")) + if (ImGui::Selectable("Paste as Child")) { - SetScrollTo(SHSerialization::DeserializeEntitiesFromString(SHClipboardUtilities::GetDataFromClipboard(), eid)); + PasteEntities(eid); + skipFrame = true; } - if(ImGui::Selectable(std::format("{} Delete", ICON_MD_DELETE).data())) + if (ImGui::Selectable(std::format("{} Delete", ICON_MD_DELETE).data())) { SHEntityManager::DestroyEntity(eid); } - - if((currentNode->GetParent() != sceneGraph.GetRoot()) && ImGui::Selectable(std::format("{} Unparent Selected", ICON_MD_NORTH_WEST).data())) + + if ((currentNode->GetParent() != sceneGraph.GetRoot()) && ImGui::Selectable(std::format("{} Unparent Selected", ICON_MD_NORTH_WEST).data())) { ParentSelectedEntities(MAX_EID); } ImGui::EndPopup(); } - + //Handle node selection if (ImGui::IsItemHovered()) { @@ -216,11 +267,11 @@ namespace SHADE { if (!isSelected) { - if(ImGui::IsKeyDown(ImGuiKey_LeftShift)) + if (ImGui::IsKeyDown(ImGuiKey_LeftShift)) { - if(editor->selectedEntities.size() >= 1) + if (editor->selectedEntities.size() >= 1) { - SelectRangeOfEntities(editor->selectedEntities[0], eid); + SelectRangeOfEntities(editor->selectedEntities[0], eid); } else editor->selectedEntities.clear(); } @@ -278,12 +329,12 @@ namespace SHADE auto const editor = SHSystemManager::GetSystem(); SHEntityParentCommand::EntityParentData entityParentData; std::vector parentedEIDS; - for(auto const& eid : editor->selectedEntities) + for (auto const& eid : editor->selectedEntities) { - if(sceneGraph.GetChild(eid, parentEID) == nullptr) + if (sceneGraph.GetChild(eid, parentEID) == nullptr) { parentedEIDS.push_back(eid); - if(auto parent = sceneGraph.GetParent(eid)) + if (auto parent = sceneGraph.GetParent(eid)) entityParentData[eid].oldParentEID = parent->GetEntityID(); entityParentData[eid].newParentEID = parentEID; } @@ -298,34 +349,57 @@ namespace SHADE editor->selectedEntities.clear(); auto const& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); sceneGraph.Traverse([&](SHSceneNode* nodePtr) - { - auto eid = nodePtr->GetEntityID(); - if(!startSelecting) { - if(eid == beginEID || eid == endEID) + auto eid = nodePtr->GetEntityID(); + if (!startSelecting) { - startSelecting = true; - editor->selectedEntities.push_back(eid); - } - } - else - { - if(!endSelecting) - { - editor->selectedEntities.push_back(eid); - if(eid == endEID || eid == beginEID) + if (eid == beginEID || eid == endEID) { - endSelecting = true; + startSelecting = true; + editor->selectedEntities.push_back(eid); } } - } - }); + else + { + if (!endSelecting) + { + editor->selectedEntities.push_back(eid); + if (eid == endEID || eid == beginEID) + { + endSelecting = true; + } + } + } + }); + } + + void SHHierarchyPanel::SelectAllEntities() + { + const auto editor = SHSystemManager::GetSystem(); + editor->selectedEntities.clear(); + auto const& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); + sceneGraph.Traverse([&](SHSceneNode* nodePtr) + { + auto eid = nodePtr->GetEntityID(); + editor->selectedEntities.push_back(eid); + }); + } + + void SHHierarchyPanel::CopySelectedEntities() + { + const auto editor = SHSystemManager::GetSystem(); + SHClipboardUtilities::WriteToClipboard(SHSerialization::SerializeEntitiesToString(editor->selectedEntities)); + } + + void SHHierarchyPanel::PasteEntities(EntityID parentEID) + { + SetScrollTo(SHSerialization::DeserializeEntitiesFromString(SHClipboardUtilities::GetDataFromClipboard(), parentEID)); } void SHCreateEntityCommand::Execute() { EntityID newEID = SHEntityManager::CreateEntity(eid); - if(eid == MAX_EID) + if (eid == MAX_EID) eid = newEID; } @@ -337,9 +411,9 @@ namespace SHADE void SHEntityParentCommand::Execute() { auto const& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); - for(auto const& eid : entities) + for (auto const& eid : entities) { - if(entityParentData[eid].newParentEID == MAX_EID) + if (entityParentData[eid].newParentEID == MAX_EID) sceneGraph.SetParent(eid, nullptr); else sceneGraph.SetParent(eid, entityParentData[eid].newParentEID); @@ -349,9 +423,9 @@ namespace SHADE void SHEntityParentCommand::Undo() { auto const& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); - for(auto const& eid : entities) + for (auto const& eid : entities) { - if(entityParentData[eid].oldParentEID == MAX_EID) + if (entityParentData[eid].oldParentEID == MAX_EID) sceneGraph.SetParent(eid, nullptr); else sceneGraph.SetParent(eid, entityParentData[eid].oldParentEID); diff --git a/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.h b/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.h index 0cfe6474..9b26e9d6 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.h +++ b/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.h @@ -26,10 +26,14 @@ namespace SHADE void SetScrollTo(EntityID eid); private: void DrawMenuBar() const noexcept; - ImRect RecursivelyDrawEntityNode(SHSceneNode*); + ImRect RecursivelyDrawEntityNode(SHSceneNode* const); void CreateChildEntity(EntityID parentEID) const noexcept; void ParentSelectedEntities(EntityID parentEID) const noexcept; void SelectRangeOfEntities(EntityID beginEID, EntityID EndEID); + void SelectAllEntities(); + void CopySelectedEntities(); + void PasteEntities(EntityID parentEID = MAX_EID); + bool skipFrame = false; std::string filter; bool isAnyNodeSelected = false; EntityID scrollTo = MAX_EID; diff --git a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.h b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.h new file mode 100644 index 00000000..69f4c145 --- /dev/null +++ b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.h @@ -0,0 +1,12 @@ +#pragma once +#include "ECS_Base/Components/SHComponent.h" + +namespace SHADE +{ + template::value, bool> = true> + static void DrawContextMenu(T* component); + template, bool> = true> + static void DrawComponent(T* component); +} + +#include "SHEditorComponentView.hpp" \ No newline at end of file diff --git a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp index 9899d4a4..4777fc6a 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp +++ b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorComponentView.hpp @@ -13,25 +13,28 @@ #include "Editor/IconsFontAwesome6.h" #include "ECS_Base/Components/SHComponent.h" #include "Editor/SHEditorWidgets.hpp" +#include "Graphics/MiddleEnd/Interface/SHRenderable.h" #include "Graphics/MiddleEnd/Lights/SHLightComponent.h" #include "Physics/Components/SHColliderComponent.h" #include "Reflection/SHReflectionMetadata.h" +#include "Resource/SHResourceManager.h" + namespace SHADE { template std::vector GetRTTREnumNames() { auto const rttrType = rttr::type::get(); - if(!rttrType.is_enumeration()) + if (!rttrType.is_enumeration()) return {}; auto const enumAlign = rttrType.get_enumeration(); auto const names = enumAlign.get_names(); std::vector result; - std::transform(names.begin(), names.end(), std::back_inserter(result), [](rttr::string_view const& name){return name.data();}); + std::transform(names.begin(), names.end(), std::back_inserter(result), [](rttr::string_view const& name) {return name.data(); }); return result; } - template::value, bool> = true> + template::value, bool>> static void DrawContextMenu(T* component) { if (!component) @@ -60,13 +63,15 @@ namespace SHADE ImGui::EndPopup(); } } - template, bool> = true> + template, bool>> static void DrawComponent(T* component) { if (!component) return; - const auto componentType = rttr::type::get(*component); + const auto componentType = rttr::type::get(); + ImGui::PushID(SHFamilyID::GetID()); SHEditorWidgets::CheckBox("##IsActive", [component]() {return component->isActive; }, [component](bool const& active) {component->isActive = active; }, "Is Component Active"); + ImGui::PopID(); ImGui::SameLine(); if (ImGui::CollapsingHeader(componentType.get_name().data())) { @@ -75,7 +80,8 @@ namespace SHADE for (auto const& property : properties) { auto const& type = property.get_type(); - + auto tooltip = property.get_metadata(META::tooltip); + bool const& isAngleInRad = property.get_metadata(META::angleInRad).is_valid() ? property.get_metadata(META::angleInRad).template get_value() : false; if (type.is_enumeration()) { auto enumAlign = type.get_enumeration(); @@ -89,29 +95,25 @@ namespace SHADE auto values = enumAlign.get_values(); auto it = std::next(values.begin(), idx); property.set_value(component, *it); - }); + }, tooltip.is_valid() ? tooltip.template get_value() : std::string()); } else if (type.is_arithmetic()) { if (type == rttr::type::get()) { - SHEditorWidgets::CheckBox(property.get_name().data(), [component, property] {return property.get_value(component).to_bool(); }, [component, property](bool const& result) {property.set_value(component, result); }); + SHEditorWidgets::CheckBox(property.get_name().data(), [component, property] {return property.get_value(component).to_bool(); }, [component, property](bool const& result) {property.set_value(component, result); }, tooltip.is_valid() ? tooltip.template get_value() : std::string()); } - //else if (type == rttr::type::get()) - //{ - // - //} else if (type == rttr::type::get() || type == rttr::type::get() || type == rttr::type::get() || type == rttr::type::get()) { auto metaMin = property.get_metadata(META::min); auto metaMax = property.get_metadata(META::max); if (metaMin && metaMax) { - SHEditorWidgets::SliderInt(property.get_name().data(), metaMin.template get_value(), metaMax.template get_value(), [component, property] {return property.get_value(component).to_int(); }, [component, property](int const& result) {property.set_value(component, result); }); + SHEditorWidgets::SliderInt(property.get_name().data(), metaMin.template get_value(), metaMax.template get_value(), [component, property] {return property.get_value(component).to_int(); }, [component, property](int const& result) {property.set_value(component, result); }, tooltip.is_valid() ? tooltip.template get_value() : std::string()); } else { - SHEditorWidgets::DragInt(property.get_name().data(), [component, property] {return property.get_value(component).to_int(); }, [component, property](int const& result) {property.set_value(component, result); }); + SHEditorWidgets::DragInt(property.get_name().data(), [component, property] {return property.get_value(component).to_int(); }, [component, property](int const& result) {property.set_value(component, result); }, tooltip.is_valid() ? tooltip.template get_value() : std::string()); } } else if (type == rttr::type::get()) @@ -120,11 +122,11 @@ namespace SHADE auto metaMax = property.get_metadata(META::max); if (metaMin.is_valid() && metaMax.is_valid()) { - SHEditorWidgets::SliderScalar(property.get_name().data(), ImGuiDataType_U8, metaMin.template get_value(), metaMax.template get_value(), [component, property] {return property.get_value(component).to_uint8(); }, [component, property](uint8_t const& result) {property.set_value(component, result); }, "%zu"); + SHEditorWidgets::SliderScalar(property.get_name().data(), ImGuiDataType_U8, metaMin.template get_value(), metaMax.template get_value(), [component, property] {return property.get_value(component).to_uint8(); }, [component, property](uint8_t const& result) {property.set_value(component, result); }, tooltip.is_valid() ? tooltip.template get_value() : std::string(), "%zu"); } else { - SHEditorWidgets::DragScalar(property.get_name().data(), ImGuiDataType_U8, [component, property] {return property.get_value(component).to_uint8(); }, [component, property](uint8_t const& result) {property.set_value(component, result); }, 0.1f, 0, 0, "%zu"); + SHEditorWidgets::DragScalar(property.get_name().data(), ImGuiDataType_U8, [component, property] {return property.get_value(component).to_uint8(); }, [component, property](uint8_t const& result) {property.set_value(component, result); }, 0.1f, 0, 0, "%zu", tooltip.is_valid() ? tooltip.template get_value() : std::string()); } } else if (type == rttr::type::get()) @@ -133,11 +135,11 @@ namespace SHADE auto metaMax = property.get_metadata(META::max); if (metaMin.is_valid() && metaMax.is_valid()) { - SHEditorWidgets::SliderScalar(property.get_name().data(), ImGuiDataType_U16, metaMin.template get_value(), metaMax.template get_value(), [component, property] {return property.get_value(component).to_uint16(); }, [component, property](uint16_t const& result) {property.set_value(component, result); }, "%zu"); + SHEditorWidgets::SliderScalar(property.get_name().data(), ImGuiDataType_U16, metaMin.template get_value(), metaMax.template get_value(), [component, property] {return property.get_value(component).to_uint16(); }, [component, property](uint16_t const& result) {property.set_value(component, result); }, tooltip.is_valid() ? tooltip.template get_value() : std::string(), "%zu"); } else { - SHEditorWidgets::DragScalar(property.get_name().data(), ImGuiDataType_U16, [component, property] {return property.get_value(component).to_uint16(); }, [component, property](uint16_t const& result) {property.set_value(component, result); }, 0.1f, 0, 0, "%zu"); + SHEditorWidgets::DragScalar(property.get_name().data(), ImGuiDataType_U16, [component, property] {return property.get_value(component).to_uint16(); }, [component, property](uint16_t const& result) {property.set_value(component, result); }, 0.1f, 0, 0, "%zu", tooltip.is_valid() ? tooltip.template get_value() : std::string()); } } else if (type == rttr::type::get()) @@ -146,11 +148,11 @@ namespace SHADE auto metaMax = property.get_metadata(META::max); if (metaMin.is_valid() && metaMax.is_valid()) { - SHEditorWidgets::SliderScalar(property.get_name().data(), ImGuiDataType_U32, metaMin.template get_value(), metaMax.template get_value(), [component, property] { return property.get_value(component).to_uint32(); }, [component, property](uint32_t const& result) {property.set_value(component, result); }, "%zu"); + SHEditorWidgets::SliderScalar(property.get_name().data(), ImGuiDataType_U32, metaMin.template get_value(), metaMax.template get_value(), [component, property] { return property.get_value(component).to_uint32(); }, [component, property](uint32_t const& result) {property.set_value(component, result); }, tooltip.is_valid() ? tooltip.template get_value() : std::string(), "%zu"); } else { - SHEditorWidgets::DragScalar(property.get_name().data(), ImGuiDataType_U32, [component, property] { return property.get_value(component).to_uint32(); }, [component, property](uint32_t const& result) {property.set_value(component, result); }, 0.1f, 0, 0, "%zu"); + SHEditorWidgets::DragScalar(property.get_name().data(), ImGuiDataType_U32, [component, property] { return property.get_value(component).to_uint32(); }, [component, property](uint32_t const& result) {property.set_value(component, result); }, 0.1f, 0, 0, "%zu", tooltip.is_valid() ? tooltip.template get_value() : std::string()); } } else if (type == rttr::type::get()) @@ -159,11 +161,11 @@ namespace SHADE auto metaMax = property.get_metadata(META::max); if (metaMin.is_valid() && metaMax.is_valid()) { - SHEditorWidgets::SliderScalar(property.get_name().data(), ImGuiDataType_U64, metaMin.template get_value(), metaMax.template get_value(), [component, property] {return property.get_value(component).to_uint64(); }, [component, property](uint64_t const& result) {property.set_value(component, result); }, "%zu"); + SHEditorWidgets::SliderScalar(property.get_name().data(), ImGuiDataType_U64, metaMin.template get_value(), metaMax.template get_value(), [component, property] {return property.get_value(component).to_uint64(); }, [component, property](uint64_t const& result) {property.set_value(component, result); }, tooltip.is_valid() ? tooltip.template get_value() : std::string(), "%zu"); } else { - SHEditorWidgets::DragScalar(property.get_name().data(), ImGuiDataType_U64, [component, property] {return property.get_value(component).to_uint64(); }, [component, property](uint64_t const& result) {property.set_value(component, result); }, 0.1f, 0, 0, "%zu"); + SHEditorWidgets::DragScalar(property.get_name().data(), ImGuiDataType_U64, [component, property] {return property.get_value(component).to_uint64(); }, [component, property](uint64_t const& result) {property.set_value(component, result); }, 0.1f, 0, 0, "%zu", tooltip.is_valid() ? tooltip.template get_value() : std::string()); } } else if (type == rttr::type::get()) @@ -171,17 +173,17 @@ namespace SHADE auto metaMin = property.get_metadata(META::min); auto metaMax = property.get_metadata(META::max); float min{}, max{}; - if(metaMin.is_valid()) + if (metaMin.is_valid()) min = std::max(metaMin.template get_value(), -FLT_MAX * 0.5f); - if(metaMax.is_valid()) + if (metaMax.is_valid()) max = std::min(metaMax.template get_value(), FLT_MAX * 0.5f); if (metaMin.is_valid() && metaMax.is_valid()) { - SHEditorWidgets::SliderFloat(property.get_name().data(), min, max, [component, property] {return property.get_value(component).to_float(); }, [component, property](float const& result) {property.set_value(component, result); }); + SHEditorWidgets::SliderFloat(property.get_name().data(), min, max, [component, property] {return property.get_value(component).to_float(); }, [component, property](float const& result) {property.set_value(component, result); }, tooltip.is_valid() ? tooltip.template get_value() : std::string()); } else { - SHEditorWidgets::DragFloat(property.get_name().data(), [component, property] {return property.get_value(component).to_float(); }, [component, property](float const& result) {property.set_value(component, result); }, "Test"); + SHEditorWidgets::DragFloat(property.get_name().data(), [component, property] {return property.get_value(component).to_float(); }, [component, property](float const& result) {property.set_value(component, result); }, tooltip.is_valid() ? tooltip.template get_value() : std::string()); } } else if (type == rttr::type::get()) @@ -190,25 +192,25 @@ namespace SHADE auto metaMax = property.get_metadata(META::max); if (metaMin.is_valid() && metaMax.is_valid()) { - SHEditorWidgets::SliderScalar(property.get_name().data(), ImGuiDataType_Double, metaMin.template get_value(), metaMax.template get_value(), [component, property] {return property.get_value(component).to_double(); }, [component, property](double const& result) {property.set_value(component, result); }); + SHEditorWidgets::SliderScalar(property.get_name().data(), ImGuiDataType_Double, metaMin.template get_value(), metaMax.template get_value(), [component, property] {return property.get_value(component).to_double(); }, [component, property](double const& result) {property.set_value(component, result); }, tooltip.is_valid() ? tooltip.template get_value() : std::string()); } else { - SHEditorWidgets::DragScalar(property.get_name().data(), ImGuiDataType_Double, [component, property] {return property.get_value(component).to_double(); }, [component, property](double const& result) {property.set_value(component, result); }, 0.1f); + SHEditorWidgets::DragScalar(property.get_name().data(), ImGuiDataType_Double, [component, property] {return property.get_value(component).to_double(); }, [component, property](double const& result) {property.set_value(component, result); }, 0.1f, {}, {}, "%.3f", tooltip.is_valid() ? tooltip.template get_value() : std::string()); } } } else if (type == rttr::type::get()) { - SHEditorWidgets::DragVec4(property.get_name().data(), { "X", "Y", "Z", "W" }, [component, property]() {return property.get_value(component).template convert(); }, [component, property](SHVec4 vec) {return property.set_value(component, vec); }); + SHEditorWidgets::DragVec4(property.get_name().data(), { "X", "Y", "Z", "W" }, [component, property]() {return property.get_value(component).template convert(); }, [component, property](SHVec4 vec) {return property.set_value(component, vec); }, isAngleInRad, tooltip.is_valid() ? tooltip.template get_value() : std::string()); } else if (type == rttr::type::get()) { - SHEditorWidgets::DragVec3(property.get_name().data(), { "X", "Y", "Z" }, [component, property]() {return property.get_value(component).template convert(); }, [component, property](SHVec3 vec) {return property.set_value(component, vec); }); + SHEditorWidgets::DragVec3(property.get_name().data(), { "X", "Y", "Z" }, [component, property]() {return property.get_value(component).template convert(); }, [component, property](SHVec3 vec) {return property.set_value(component, vec); }, isAngleInRad, tooltip.is_valid() ? tooltip.template get_value() : std::string()); } else if (type == rttr::type::get()) { - SHEditorWidgets::DragVec2(property.get_name().data(), { "X", "Y" }, [component, property]() {return property.get_value(component).template convert(); }, [component, property](SHVec2 vec) {return property.set_value(component, vec); }); + SHEditorWidgets::DragVec2(property.get_name().data(), { "X", "Y" }, [component, property]() {return property.get_value(component).template convert(); }, [component, property](SHVec2 vec) {return property.set_value(component, vec); }, isAngleInRad, tooltip.is_valid() ? tooltip.template get_value() : std::string()); } } @@ -223,10 +225,10 @@ namespace SHADE return; // Get transform component for extrapolating relative sizes - auto* transformComponent = SHComponentManager::GetComponent(component->GetEID()); + auto* transformComponent = SHComponentManager::GetComponent_s(component->GetEID()); const auto componentType = rttr::type::get(*component); - SHEditorWidgets::CheckBox("##IsActive", [component]() {return component->isActive; }, [component](bool const& active) {component->isActive = active; }); + SHEditorWidgets::CheckBox("##IsActive", [component]() {return component->isActive; }, [component](bool const& active) {component->isActive = active; }, "Is Component Active"); ImGui::SameLine(); if (ImGui::CollapsingHeader(componentType.get_name().data())) { @@ -234,8 +236,8 @@ namespace SHADE auto& colliders = component->GetColliders(); int const size = static_cast(colliders.size()); - ImGui::BeginChild("Colliders", {0.0f, colliders.empty() ? 1.0f : 250.0f}, true); - std::optional colliderToDelete{std::nullopt}; + ImGui::BeginChild("Colliders", { 0.0f, colliders.empty() ? 1.0f : 250.0f }, true); + std::optional colliderToDelete{ std::nullopt }; for (int i{}; i < size; ++i) { ImGui::PushID(i); @@ -244,12 +246,12 @@ namespace SHADE if (collider->GetType() == SHCollider::Type::BOX) { - SHEditorWidgets::BeginPanel( std::format("{} Box Collider #{}", ICON_FA_CUBE, i).data(), { ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y }); + SHEditorWidgets::BeginPanel(std::format("{} Box Collider #{}", ICON_FA_CUBE, i).data(), { ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y }); auto box = reinterpret_cast(collider->GetShape()); SHEditorWidgets::DragVec3 ( - "Half Extents", { "X", "Y", "Z" }, - [box, transformComponent] { return (transformComponent->GetWorldScale() * 2.0f) * box->GetHalfExtents(); }, + "Half Extents", { "X", "Y", "Z" }, + [box, transformComponent] { return (box->GetHalfExtents() * 2.0f) / transformComponent->GetWorldScale(); }, [collider](SHVec3 const& vec) { collider->SetBoundingBox(vec); }); } else if (collider->GetType() == SHCollider::Type::SPHERE) @@ -258,32 +260,51 @@ namespace SHADE auto sphere = reinterpret_cast(collider->GetShape()); SHEditorWidgets::DragFloat ( - "Radius", + "Radius", [sphere, transformComponent] { const SHVec3& TF_WORLD_SCALE = transformComponent->GetWorldScale(); const float MAX_SCALE = SHMath::Max({ TF_WORLD_SCALE.x, TF_WORLD_SCALE.y, TF_WORLD_SCALE.z }); return sphere->GetRadius() / MAX_SCALE; - }, - [collider](float const& value) { collider->SetBoundingSphere(value);}); + }, + [collider](float const& value) { collider->SetBoundingSphere(value); }); } else if (collider->GetType() == SHCollider::Type::CAPSULE) { } { - SHEditorWidgets::BeginPanel("Offset", { ImGui::GetContentRegionAvail().x, 30.0f }); + SHEditorWidgets::BeginPanel("Offsets",{ ImGui::GetContentRegionAvail().x, 30.0f }); SHEditorWidgets::DragVec3("Position", { "X", "Y", "Z" }, [&collider] {return collider->GetPositionOffset(); }, [&collider](SHVec3 const& vec) {collider->SetPositionOffset(vec); }); + SHEditorWidgets::DragVec3("Rotation", { "X", "Y", "Z" }, + [&collider] + { + auto offset = collider->GetRotationOffset(); + offset.x = SHMath::RadiansToDegrees(offset.x); + offset.y = SHMath::RadiansToDegrees(offset.y); + offset.z = SHMath::RadiansToDegrees(offset.z); + return offset; + }, + [&collider](SHVec3 const& vec) + { + const SHVec3 vecInRad + { + SHMath::DegreesToRadians(vec.x) + , SHMath::DegreesToRadians(vec.y) + , SHMath::DegreesToRadians(vec.z) + }; + collider->SetRotationOffset(vecInRad); + }); SHEditorWidgets::EndPanel(); } - if(ImGui::Button(std::format("{} Remove Collider #{}", ICON_MD_REMOVE, i).data())) + if (ImGui::Button(std::format("{} Remove Collider #{}", ICON_MD_REMOVE, i).data())) { colliderToDelete = i; } SHEditorWidgets::EndPanel(); ImGui::PopID(); } - if(colliderToDelete.has_value()) + if (colliderToDelete.has_value()) { component->RemoveCollider(colliderToDelete.value()); } @@ -291,11 +312,11 @@ namespace SHADE if (ImGui::BeginMenu("Add Collider")) { - if(ImGui::Selectable("Box Collider")) + if (ImGui::Selectable("Box Collider")) { component->AddBoundingBox(); } - if(ImGui::Selectable("Sphere Collider")) + if (ImGui::Selectable("Sphere Collider")) { component->AddBoundingSphere(); } @@ -308,10 +329,10 @@ namespace SHADE template<> static void DrawComponent(SHLightComponent* component) { - if (!component) + if (!component) return; const auto componentType = rttr::type::get(*component); - SHEditorWidgets::CheckBox("##IsActive", [component]() {return component->isActive; }, [component](bool const& active) {component->isActive = active; }); + SHEditorWidgets::CheckBox("##IsActive", [component]() {return component->isActive; }, [component](bool const& active) {component->isActive = active; }, "Is Component Active"); ImGui::SameLine(); if (ImGui::CollapsingHeader(componentType.get_name().data())) { @@ -319,19 +340,49 @@ namespace SHADE static auto const enumAlign = rttr::type::get().get_enumeration(); static std::vector list(GetRTTREnumNames()); - + SHEditorWidgets::ComboBox("Type", list, [component] {return static_cast(component->GetType()); }, [component](int const& idx) { component->SetType(static_cast(idx)); }); - SHEditorWidgets::DragVec3("Position", {"X", "Y", "Z"}, [component](){return component->GetPosition();}, [component](SHVec3 const& vec){component->SetPosition(vec);}); - SHEditorWidgets::DragVec3("Direction", {"X", "Y", "Z"}, [component](){return component->GetDirection();}, [component](SHVec3 const& vec){component->SetDirection(vec);}); - SHEditorWidgets::ColorPicker("Color", [component](){return component->GetColor();}, [component](SHVec4 const& rgba){component->SetColor(rgba);}); - SHEditorWidgets::DragFloat("Strength", [component](){return component->GetStrength();}, [component](float const& value){component->SetStrength(value);}); + SHEditorWidgets::DragVec3("Position", { "X", "Y", "Z" }, [component]() {return component->GetPosition(); }, [component](SHVec3 const& vec) {component->SetPosition(vec); }); + SHEditorWidgets::DragVec3("Direction", { "X", "Y", "Z" }, [component]() {return component->GetDirection(); }, [component](SHVec3 const& vec) {component->SetDirection(vec); }); + SHEditorWidgets::ColorPicker("Color", [component]() {return component->GetColor(); }, [component](SHVec4 const& rgba) {component->SetColor(rgba); }); + SHEditorWidgets::DragFloat("Strength", [component]() {return component->GetStrength(); }, [component](float const& value) {component->SetStrength(value); }); } else { DrawContextMenu(component); } } -} \ No newline at end of file + + template<> + static void DrawComponent(SHRenderable* component) + { + if (!component) + return; + const auto componentType = rttr::type::get(*component); + SHEditorWidgets::CheckBox("##IsActive", [component]() {return component->isActive; }, [component](bool const& active) {component->isActive = active; }, "Is Component Active"); + ImGui::SameLine(); + if (ImGui::CollapsingHeader(componentType.get_name().data())) + { + DrawContextMenu(component); + Handle const& mesh = component->GetMesh(); + + SHEditorWidgets::DragDropReadOnlyField("Mesh", std::to_string(SHResourceManager::GetAssetID(mesh).value_or(0)).data(), [component]() + { + Handle const& mesh = component->GetMesh(); + return SHResourceManager::GetAssetID(mesh).value_or(0); + }, + [component](AssetID const& id) + { + component->SetMesh(SHResourceManager::LoadOrGet(id)); + SHResourceManager::FinaliseChanges(); + }, SHDragDrop::DRAG_RESOURCE); + } + else + { + DrawContextMenu(component); + } + } +} diff --git a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorInspector.cpp b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorInspector.cpp index ebb241ef..2fecae25 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorInspector.cpp +++ b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorInspector.cpp @@ -1,6 +1,6 @@ #include "SHpch.h" -#include "Editor/SHEditor.hpp" +#include "Editor/SHEditor.h" #include "SHEditorInspector.h" #include "ECS_Base/SHECSMacros.h" @@ -10,17 +10,15 @@ #include "Editor/SHImGuiHelpers.hpp" #include "Editor/SHEditorWidgets.hpp" -#include "SHEditorComponentView.hpp" -#include "ECS_Base/UnitTesting/SHTestComponents.h" #include "Graphics/MiddleEnd/Interface/SHRenderable.h" #include "Scripting/SHScriptEngine.h" #include "ECS_Base/Managers/SHSystemManager.h" -#include "ECS_Base/Managers/SHSystemManager.h" -#include "AudioSystem/SHAudioSystem.h" #include "Physics/Components/SHRigidBodyComponent.h" #include "Physics/Components/SHColliderComponent.h" #include "Camera/SHCameraComponent.h" +#include "Camera/SHCameraArmComponent.h" +#include "SHEditorComponentView.h" namespace SHADE { @@ -30,8 +28,17 @@ namespace SHADE bool selected = false; if(!SHComponentManager::HasComponent(eid)) { - if(selected = ImGui::Selectable(std::format("Add {}", rttr::type::get().get_name().data()).data()); selected) + const char* componentName = rttr::type::get().get_name().data(); + if(selected = ImGui::Selectable(std::format("Add {}", componentName).data()); selected) SHComponentManager::AddComponent(eid); + if(ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::Text("Adds", componentName); ImGui::SameLine(); + ImGui::TextColored(ImGuiColors::green, "%s", componentName); ImGui::SameLine(); + ImGui::Text("to this entity", componentName); + ImGui::EndTooltip(); + } } return selected; } @@ -42,13 +49,26 @@ namespace SHADE bool selected = false; if (!SHComponentManager::HasComponent(eid)) { - if(selected = ImGui::Selectable(std::format("Add {}", rttr::type::get().get_name().data()).data()); selected) + const char* componentName = rttr::type::get().get_name().data(); + + if(selected = ImGui::Selectable(std::format("Add {}", componentName).data()); selected) { if(SHComponentManager::GetComponent_s(eid) == nullptr) SHComponentManager::AddComponent(eid); SHComponentManager::AddComponent(eid); } + if(ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::Text("Adds", componentName); ImGui::SameLine(); + ImGui::TextColored(ImGuiColors::green, "%s", componentName); ImGui::SameLine(); + ImGui::Text("to this entity", componentName); + ImGui::Text("Adds"); ImGui::SameLine(); + ImGui::TextColored(ImGuiColors::red, "%s", rttr::type::get().get_name().data()); ImGui::SameLine(); + ImGui::Text("if the entity does not already have it"); + ImGui::EndTooltip(); + } } return selected; } @@ -107,6 +127,9 @@ namespace SHADE if (auto cameraComponent = SHComponentManager::GetComponent_s(eid)) { DrawComponent(cameraComponent); + }if (auto cameraArmComponent = SHComponentManager::GetComponent_s(eid)) + { + DrawComponent(cameraArmComponent); } ImGui::Separator(); // Render Scripts @@ -117,6 +140,8 @@ namespace SHADE { DrawAddComponentButton(eid); DrawAddComponentButton(eid); + DrawAddComponentButton(eid); + DrawAddComponentButton(eid); // Components that require Transforms diff --git a/SHADE_Engine/src/Editor/EditorWindow/MenuBar/SHEditorMenuBar.cpp b/SHADE_Engine/src/Editor/EditorWindow/MenuBar/SHEditorMenuBar.cpp index c33f4fb6..06c0c2ae 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/MenuBar/SHEditorMenuBar.cpp +++ b/SHADE_Engine/src/Editor/EditorWindow/MenuBar/SHEditorMenuBar.cpp @@ -3,7 +3,7 @@ //#==============================================================# //|| SHADE Includes || //#==============================================================# -#include "Editor/SHEditor.hpp" +#include "Editor/SHEditor.h" #include "SHEditorMenuBar.h" #include "Editor/IconsMaterialDesign.h" #include "Editor/Command/SHCommandManager.h" @@ -175,19 +175,37 @@ namespace SHADE ImGui::BeginDisabled(editor->editorState == SHEditor::State::PLAY); if(ImGui::SmallButton(ICON_MD_PLAY_ARROW)) { + const SHEditorStateChangeEvent STATE_CHANGE_EVENT + { + .previousState = editor->editorState + }; editor->editorState = SHEditor::State::PLAY; + + SHEventManager::BroadcastEvent(STATE_CHANGE_EVENT, SH_EDITOR_ON_PLAY_EVENT); } ImGui::EndDisabled(); ImGui::BeginDisabled(editor->editorState == SHEditor::State::PAUSE); if(ImGui::SmallButton(ICON_MD_PAUSE)) { + const SHEditorStateChangeEvent STATE_CHANGE_EVENT + { + .previousState = editor->editorState + }; editor->editorState = SHEditor::State::PAUSE; + + SHEventManager::BroadcastEvent(STATE_CHANGE_EVENT, SH_EDITOR_ON_PAUSE_EVENT); } ImGui::EndDisabled(); ImGui::BeginDisabled(editor->editorState == SHEditor::State::STOP); if(ImGui::SmallButton(ICON_MD_STOP)) { + const SHEditorStateChangeEvent STATE_CHANGE_EVENT + { + .previousState = editor->editorState + }; editor->editorState = SHEditor::State::STOP; + + SHEventManager::BroadcastEvent(STATE_CHANGE_EVENT, SH_EDITOR_ON_STOP_EVENT); } ImGui::EndDisabled(); ImGui::EndMenuBar(); diff --git a/SHADE_Engine/src/Editor/EditorWindow/MenuBar/SHEditorMenuBar.h b/SHADE_Engine/src/Editor/EditorWindow/MenuBar/SHEditorMenuBar.h index 7cbcd696..e4f1d20b 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/MenuBar/SHEditorMenuBar.h +++ b/SHADE_Engine/src/Editor/EditorWindow/MenuBar/SHEditorMenuBar.h @@ -20,4 +20,10 @@ namespace SHADE float menuBarHeight = 20.0f; std::vector layoutPaths; };//class SHEditorMenuBar + + struct SHEditorStateChangeEvent + { + SHEditor::State previousState; + }; + }//namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/Editor/EditorWindow/ViewportWindow/SHEditorViewport.cpp b/SHADE_Engine/src/Editor/EditorWindow/ViewportWindow/SHEditorViewport.cpp index f5170999..d6ef8d19 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/ViewportWindow/SHEditorViewport.cpp +++ b/SHADE_Engine/src/Editor/EditorWindow/ViewportWindow/SHEditorViewport.cpp @@ -5,13 +5,16 @@ #include "ImGuizmo.h" #include "ECS_Base/Managers/SHSystemManager.h" #include "Editor/IconsMaterialDesign.h" -#include "Editor/SHEditor.hpp" +#include "Editor/SHEditor.h" #include "Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.h" #include "Graphics/MiddleEnd/Interface/SHGraphicsSystem.h" #include "Graphics/Descriptors/SHVkDescriptorSetGroup.h" #include "Graphics/MiddleEnd/Interface/SHMousePickSystem.h" #include +#include "Camera/SHCameraSystem.h" +#include "FRC/SHFramerateController.h" + constexpr std::string_view windowName = "\xef\x80\x95 Viewport"; namespace SHADE @@ -30,8 +33,15 @@ namespace SHADE void SHEditorViewport::Update() { SHEditorWindow::Update(); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f,0.0f)); - if(Begin()) + if (shouldUpdateCamera) + { + auto camSystem = SHSystemManager::GetSystem(); + camSystem->UpdateEditorCamera(SHFrameRateController::GetRawDeltaTime()); + shouldUpdateCamera = false; + } + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); + + if (Begin()) { ImGuizmo::SetDrawlist(); DrawMenuBar(); @@ -39,21 +49,38 @@ namespace SHADE auto const& descriptorSet = gfxSystem->GetPostOffscreenRenderSystem()->GetDescriptorSetGroup()->GetVkHandle()[0]; auto mousePos = ImGui::GetMousePos(); beginCursorPos = ImGui::GetCursorScreenPos(); - viewportMousePos = {mousePos.x - beginCursorPos.x, mousePos.y - beginCursorPos.y}; - gfxSystem->GetMousePickSystem ()->SetViewportMousePos (viewportMousePos); + viewportMousePos = { mousePos.x - beginCursorPos.x, mousePos.y - beginCursorPos.y }; + gfxSystem->GetMousePickSystem()->SetViewportMousePos(viewportMousePos); - ImGui::Image((ImTextureID)descriptorSet, {beginContentRegionAvailable.x, beginContentRegionAvailable.y}); + ImGui::Image((ImTextureID)descriptorSet, { beginContentRegionAvailable.x, beginContentRegionAvailable.y }); - if(ImGui::IsWindowHovered() && ImGui::IsMouseDown(ImGuiMouseButton_Right)) + if (ImGui::IsWindowHovered() && ImGui::IsMouseDown(ImGuiMouseButton_Right)) { ImGui::SetMouseCursor(ImGuiMouseCursor_None); ImGui::SetCursorScreenPos(ImGui::GetMousePos()); ImGui::PushStyleColor(ImGuiCol_Text, ImGuiColors::green); ImGui::Text(ICON_FA_EYE); ImGui::PopStyleColor(); + + shouldUpdateCamera = true; + } + if (ImGui::IsWindowFocused() && !ImGui::IsMouseDown(ImGuiMouseButton_Right)) + { + if (ImGui::IsKeyReleased(ImGuiKey_Q)) + { + transformGizmo.operation = SHTransformGizmo::Operation::TRANSLATE; + } + if (ImGui::IsKeyReleased(ImGuiKey_W)) + { + transformGizmo.operation = SHTransformGizmo::Operation::ROTATE; + } + if (ImGui::IsKeyReleased(ImGuiKey_E)) + { + transformGizmo.operation = SHTransformGizmo::Operation::SCALE; + } } } - ImGuizmo::SetRect(beginCursorPos.x , beginCursorPos.y, beginContentRegionAvailable.x, beginContentRegionAvailable.y); + ImGuizmo::SetRect(beginCursorPos.x, beginCursorPos.y, beginContentRegionAvailable.x, beginContentRegionAvailable.y); transformGizmo.Draw(); ImGui::End(); ImGui::PopStyleVar(); @@ -72,11 +99,12 @@ namespace SHADE //auto pos = ImGui::GetCursorPos(); //windowCursorPos = {} - if(beginContentRegionAvailable.x == 0 || beginContentRegionAvailable.y == 0) + if (beginContentRegionAvailable.x == 0 || beginContentRegionAvailable.y == 0) { - beginContentRegionAvailable = windowSize; + beginContentRegionAvailable = windowSize; } gfxSystem->PrepareResize(static_cast(beginContentRegionAvailable.x), static_cast(beginContentRegionAvailable.y)); + shouldUpdateCamera = true; } void SHEditorViewport::OnPosChange() @@ -86,44 +114,63 @@ namespace SHADE void SHEditorViewport::DrawMenuBar() noexcept { - if(ImGui::BeginMenuBar()) + if (ImGui::BeginMenuBar()) { + ImGui::BeginDisabled(ImGui::IsWindowFocused() && ImGui::IsMouseDown(ImGuiMouseButton_Right)); bool const isTranslate = transformGizmo.operation == SHTransformGizmo::Operation::TRANSLATE; ImGui::BeginDisabled(isTranslate); - if(isTranslate) + if (isTranslate) ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyle().Colors[ImGuiCol_CheckMark]); - if(ImGui::Button(ICON_MD_OPEN_WITH)) + if (ImGui::Button(ICON_MD_OPEN_WITH)) { transformGizmo.operation = SHTransformGizmo::Operation::TRANSLATE; } ImGui::EndDisabled(); - if(isTranslate) + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + { + ImGui::BeginTooltip(); + ImGui::Text("Translate [Q]"); + ImGui::EndTooltip(); + } + if (isTranslate) ImGui::PopStyleColor(); bool const isRotate = transformGizmo.operation == SHTransformGizmo::Operation::ROTATE; ImGui::BeginDisabled(isRotate); - if(isRotate) + if (isRotate) ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyle().Colors[ImGuiCol_CheckMark]); - if(ImGui::Button(ICON_MD_AUTORENEW)) + if (ImGui::Button(ICON_MD_AUTORENEW)) { transformGizmo.operation = SHTransformGizmo::Operation::ROTATE; } ImGui::EndDisabled(); - if(isRotate) + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + { + ImGui::BeginTooltip(); + ImGui::Text("Rotate [W]"); + ImGui::EndTooltip(); + } + if (isRotate) ImGui::PopStyleColor(); bool const isScale = transformGizmo.operation == SHTransformGizmo::Operation::SCALE; ImGui::BeginDisabled(isScale); - if(isScale) + if (isScale) ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyle().Colors[ImGuiCol_CheckMark]); - if(ImGui::Button(ICON_MD_EXPAND)) + if (ImGui::Button(ICON_MD_EXPAND)) { transformGizmo.operation = SHTransformGizmo::Operation::SCALE; } ImGui::EndDisabled(); - if(isScale) + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + { + ImGui::BeginTooltip(); + ImGui::Text("Scale [E]"); + ImGui::EndTooltip(); + } + if (isScale) ImGui::PopStyleColor(); - + ImGui::EndDisabled(); ImGui::EndMenuBar(); } } diff --git a/SHADE_Engine/src/Editor/EditorWindow/ViewportWindow/SHEditorViewport.h b/SHADE_Engine/src/Editor/EditorWindow/ViewportWindow/SHEditorViewport.h index 80b13285..0fae4317 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/ViewportWindow/SHEditorViewport.h +++ b/SHADE_Engine/src/Editor/EditorWindow/ViewportWindow/SHEditorViewport.h @@ -14,7 +14,7 @@ namespace SHADE { - class SHEditorViewport final : public SHEditorWindow + class SHEditorViewport final : public SHEditorWindow { public: SHEditorViewport(); @@ -28,5 +28,6 @@ namespace SHADE private: void DrawMenuBar() noexcept; SHVec2 beginCursorPos; + bool shouldUpdateCamera = false; };//class SHEditorViewport }//namespace SHADE diff --git a/SHADE_Engine/src/Editor/Gizmos/SHTransformGizmo.cpp b/SHADE_Engine/src/Editor/Gizmos/SHTransformGizmo.cpp index 3c984051..e3bbc809 100644 --- a/SHADE_Engine/src/Editor/Gizmos/SHTransformGizmo.cpp +++ b/SHADE_Engine/src/Editor/Gizmos/SHTransformGizmo.cpp @@ -3,7 +3,7 @@ #include "ECS_Base/Managers/SHComponentManager.h" #include "ECS_Base/Managers/SHSystemManager.h" -#include "Editor/SHEditor.hpp" +#include "Editor/SHEditor.h" #include "Editor/SHImGuiHelpers.hpp" #include #include @@ -63,6 +63,9 @@ namespace SHADE if (selectedEntityTransformComponent == nullptr) return; + if(!selectedEntityTransformComponent->isActive) + return; + SHMatrix mat = selectedEntityTransformComponent->GetTRS(); useSnap = ImGui::IsKeyDown(ImGuiKey_LeftCtrl); if(useSnap) diff --git a/SHADE_Engine/src/Editor/SHEditor.cpp b/SHADE_Engine/src/Editor/SHEditor.cpp index 06fadfee..cf5056a5 100644 --- a/SHADE_Engine/src/Editor/SHEditor.cpp +++ b/SHADE_Engine/src/Editor/SHEditor.cpp @@ -21,7 +21,7 @@ #include "Graphics/MiddleEnd/Interface/SHViewport.h" #include "Graphics/MiddleEnd/Interface/SHRenderer.h" -#include "SHEditor.hpp" +#include "SHEditor.h" #include "SHEditorWidgets.hpp" #include "Math/Transform/SHTransformSystem.h" @@ -175,7 +175,7 @@ namespace SHADE ImFontConfig icons_config{}; icons_config.MergeMode = true; icons_config.GlyphOffset.y = 5.f; constexpr ImWchar icon_ranges_fa[] = { ICON_MIN_FA, ICON_MAX_FA, 0 }; ImFont* UIFontFA = io->Fonts->AddFontFromFileTTF("../../Assets/Editor/Fonts/fa-solid-900.ttf", 20.f, &icons_config, icon_ranges_fa); //TODO: Change to config based assets path - constexpr ImWchar icon_ranges_md[] = { ICON_MIN_MD, ICON_MAX_MD, 0 }; + constexpr ImWchar icon_ranges_md[] = { ICON_MIN_MD, ICON_MAX_16_MD, 0 }; ImFont* UIFontMD = io->Fonts->AddFontFromFileTTF("../../Assets/Editor/Fonts/MaterialIcons-Regular.ttf", 20.f, &icons_config, icon_ranges_md); //TODO: Change to config based assets path io->Fonts->Build(); } @@ -293,6 +293,7 @@ namespace SHADE //#==============================================================# void SHEditor::InitBackend() { +#ifdef SHEDITOR if(ImGui_ImplSDL2_InitForVulkan(sdlWindow) == false) { SHLOG_CRITICAL("Editor backend initialisation; Failed to perform SDL initialisation for Vulkan") @@ -339,6 +340,7 @@ namespace SHADE renderGraph->GetNode("ImGui Node")->GetSubpass("ImGui Draw")->AddExteriorDrawCalls([](Handle& cmd) { ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), cmd->GetVkCommandBuffer()); }); +#endif } void SHEditor::PollPicking() diff --git a/SHADE_Engine/src/Editor/SHEditor.hpp b/SHADE_Engine/src/Editor/SHEditor.h similarity index 98% rename from SHADE_Engine/src/Editor/SHEditor.hpp rename to SHADE_Engine/src/Editor/SHEditor.h index 34405390..624069db 100644 --- a/SHADE_Engine/src/Editor/SHEditor.hpp +++ b/SHADE_Engine/src/Editor/SHEditor.h @@ -15,7 +15,7 @@ #include "ECS_Base/System/SHSystemRoutine.h" #include "Resource/SHHandle.h" #include "EditorWindow/SHEditorWindow.h" -#include "Tools/SHLogger.h" +#include "Tools/SHLog.h" #include "Gizmos/SHTransformGizmo.h" @@ -76,7 +76,7 @@ namespace SHADE } else { - SHLOG_WARNING("Attempt to create duplicate of Editor window type") + SHLog::Warning("Attempt to create duplicate of Editor window type"); } } diff --git a/SHADE_Engine/src/Editor/SHEditorUI.cpp b/SHADE_Engine/src/Editor/SHEditorUI.cpp index 0137b951..cc63c565 100644 --- a/SHADE_Engine/src/Editor/SHEditorUI.cpp +++ b/SHADE_Engine/src/Editor/SHEditorUI.cpp @@ -16,6 +16,7 @@ of DigiPen Institute of Technology is prohibited. // External Dependencies #include #include "SHEditorWidgets.hpp" +#include "ECS_Base/Managers/SHEntityManager.h" namespace SHADE { @@ -156,7 +157,7 @@ namespace SHADE if (isHovered) *isHovered = ImGui::IsItemHovered(); ImGui::SameLine(); - return ImGui::Checkbox("#", &value); + return ImGui::Checkbox("##", &value); } bool SHEditorUI::InputInt(const std::string& label, int& value, bool* isHovered) { @@ -164,7 +165,7 @@ namespace SHADE if (isHovered) *isHovered = ImGui::IsItemHovered(); ImGui::SameLine(); - return ImGui::InputInt("#", &value, + return ImGui::InputInt("##", &value, 1, 10, ImGuiInputTextFlags_EnterReturnsTrue); } @@ -175,7 +176,7 @@ namespace SHADE if (isHovered) *isHovered = ImGui::IsItemHovered(); ImGui::SameLine(); - const bool CHANGED = InputInt("#", signedVal); + const bool CHANGED = InputInt("##", signedVal); if (CHANGED) { signedVal = std::clamp(signedVal, 0, std::numeric_limits::max()); @@ -189,7 +190,7 @@ namespace SHADE if (isHovered) *isHovered = ImGui::IsItemHovered(); ImGui::SameLine(); - return ImGui::InputFloat("#", &value, + return ImGui::InputFloat("##", &value, 0.1f, 1.0f, "%.3f", ImGuiInputTextFlags_EnterReturnsTrue); } @@ -199,7 +200,7 @@ namespace SHADE if (isHovered) *isHovered = ImGui::IsItemHovered(); ImGui::SameLine(); - return ImGui::InputDouble("#", &value, + return ImGui::InputDouble("##", &value, 0.1, 1.0, "%.3f", ImGuiInputTextFlags_EnterReturnsTrue); } @@ -209,7 +210,7 @@ namespace SHADE if (isHovered) *isHovered = ImGui::IsItemHovered(); ImGui::SameLine(); - return ImGui::InputDouble("#", &value, + return ImGui::InputDouble("##", &value, 1.0, 45.0, "%.3f", ImGuiInputTextFlags_EnterReturnsTrue); } @@ -279,7 +280,7 @@ namespace SHADE if (isHovered) *isHovered = ImGui::IsItemHovered(); ImGui::SameLine(); - const bool CHANGED = ImGui::InputText("#", &buffer[0], TEXT_FIELD_MAX_LENGTH); + const bool CHANGED = ImGui::InputText("##", &buffer[0], TEXT_FIELD_MAX_LENGTH); if (CHANGED) { value = std::string(buffer.data(), buffer.data() + TEXT_FIELD_MAX_LENGTH); @@ -287,6 +288,35 @@ namespace SHADE return CHANGED; } + bool SHEditorUI::InputGameObjectField(const std::string& label, uint32_t& value, bool* isHovered) + { + ImGui::Text(label.c_str()); + if (isHovered) + *isHovered = ImGui::IsItemHovered(); + ImGui::SameLine(); + SHEntity* entity = SHEntityManager::GetEntityByID(value); + std::ostringstream oss; + if (entity) + { + oss << value << ": " << entity->name; + } + std::string entityName = oss.str(); + bool changed = ImGui::InputText("##", &entityName, ImGuiInputTextFlags_ReadOnly); + if (SHDragDrop::BeginTarget()) + { + if (const std::vector* payload = SHDragDrop::AcceptPayload>(SHDragDrop::DRAG_EID)) + { + if (!payload->empty()) + { + value = payload->at(0); + changed = true; + } + SHDragDrop::EndTarget(); + } + } + return changed; + } + bool SHEditorUI::InputEnumCombo(const std::string& label, int& v, const std::vector& enumNames, bool* isHovered) { // Clamp input value @@ -297,7 +327,7 @@ namespace SHADE if (isHovered) *isHovered = ImGui::IsItemHovered(); ImGui::SameLine(); - if (ImGui::BeginCombo("#", INITIAL_NAME.c_str(), ImGuiComboFlags_None)) + if (ImGui::BeginCombo("##", INITIAL_NAME.c_str(), ImGuiComboFlags_None)) { for (int i = 0; i < enumNames.size(); ++i) { diff --git a/SHADE_Engine/src/Editor/SHEditorUI.h b/SHADE_Engine/src/Editor/SHEditorUI.h index f3051aa1..d4104639 100644 --- a/SHADE_Engine/src/Editor/SHEditorUI.h +++ b/SHADE_Engine/src/Editor/SHEditorUI.h @@ -308,6 +308,14 @@ namespace SHADE /// True if the value was changed. static bool InputTextField(const std::string& label, std::string& value, bool* isHovered = nullptr); /// + /// Creates a drag field widget for int input. + /// + /// Label used to identify this widget. + /// Reference to the variable to store the result. + /// The type of enum to input. diff --git a/SHADE_Engine/src/Editor/SHEditorWidgets.hpp b/SHADE_Engine/src/Editor/SHEditorWidgets.hpp index 46538827..053348d7 100644 --- a/SHADE_Engine/src/Editor/SHEditorWidgets.hpp +++ b/SHADE_Engine/src/Editor/SHEditorWidgets.hpp @@ -22,6 +22,8 @@ #include #include +#include "DragDrop/SHDragDrop.hpp" + namespace SHADE { class SH_API SHEditorWidgets @@ -41,7 +43,7 @@ namespace SHADE ImGui::BeginGroup(); auto itemSpacing = ImGui::GetStyle().ItemSpacing; - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f)); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.2f)); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 0.0f)); auto frameHeight = ImGui::GetFrameHeight(); @@ -86,7 +88,7 @@ namespace SHADE auto itemSpacing = ImGui::GetStyle().ItemSpacing; - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f)); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.2f)); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 0.0f)); auto frameHeight = ImGui::GetFrameHeight(); @@ -127,7 +129,7 @@ namespace SHADE ImGui::GetWindowDrawList()->AddRect( frameRect.Min, frameRect.Max, - ImColor(ImGui::GetStyleColorVec4(ImGuiCol_Button)), + ImColor(ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled)), halfFrame.x); ImGui::PopClipRect(); @@ -174,15 +176,19 @@ namespace SHADE ImGui::SetColumnWidth(-1, 80.0f); ImGui::Text(label.c_str()); if (isHovered) - *isHovered = ImGui::IsItemHovered(); + *isHovered |= ImGui::IsItemHovered(); ImGui::NextColumn(); for (std::size_t i = 0; i < N; ++i) { ImGui::PushID(static_cast(i)); - ImGui::TextUnformatted(componentLabels[i].c_str(), ImGui::FindRenderedTextEnd(componentLabels[i].c_str())); ImGui::SameLine(); + ImGui::TextUnformatted(componentLabels[i].c_str(), ImGui::FindRenderedTextEnd(componentLabels[i].c_str())); + if (isHovered) + *isHovered |= ImGui::IsItemHovered(); + ImGui::SameLine(); ImGui::SetNextItemWidth(80.0f); valueChanged |= ImGui::DragFloat("##v", values[i], speed, valueMin, valueMax, displayFormat, flags); - + if (isHovered) + *isHovered |= ImGui::IsItemHovered(); const ImVec2 min = ImGui::GetItemRectMin(); const ImVec2 max = ImGui::GetItemRectMax(); const float spacing = g.Style.FrameRounding; @@ -203,23 +209,31 @@ namespace SHADE } static bool DragVec2(const std::string& label, std::vectorconst& componentLabels, std::function get, - std::function set, float speed = 0.1f, const char* displayFormat = "%.3f", std::string_view const& tooltip = {}, float valueMin = 0.0f, float valueMax = 0.0f, + std::function set, bool const& isAnAngleInRad = false, std::string_view const& tooltip = {}, float speed = 0.1f, const char* displayFormat = "%.3f", float valueMin = 0.0f, float valueMax = 0.0f, ImGuiSliderFlags flags = 0) { SHVec2 values = get(); + if(isAnAngleInRad) + { + values = {SHMath::RadiansToDegrees(values.x), SHMath::RadiansToDegrees(values.y)}; + } bool const changed = DragN(label, componentLabels, { &values.x, &values.y }, speed, displayFormat, valueMin, valueMax, flags); static bool startRecording = false; if (changed) { + if(isAnAngleInRad) + { + values = {SHMath::DegreesToRadians(values.x), SHMath::DegreesToRadians(values.y)}; + } SHCommandManager::PerformCommand(std::reinterpret_pointer_cast(std::make_shared>(get(), values, set)), startRecording); if (!startRecording) startRecording = true; } if (startRecording && ImGui::IsMouseReleased(ImGuiMouseButton_Left)) startRecording = false; - if(!tooltip.empty()) + if (!tooltip.empty()) { - if(ImGui::IsItemHovered()) + if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); ImGui::Text(tooltip.data()); @@ -230,17 +244,24 @@ namespace SHADE } static bool DragVec3(const std::string& label, std::vectorconst& componentLabels, std::function get, - std::function set, float speed = 0.1f, const char* displayFormat = "%.3f", std::string_view const& tooltip = {}, float valueMin = 0.0f, float valueMax = 0.0f, + std::function set, bool const& isAnAngleInRad = false, std::string_view const& tooltip = {}, float speed = 0.1f, const char* displayFormat = "%.3f", float valueMin = 0.0f, float valueMax = 0.0f, ImGuiSliderFlags flags = 0) { SHVec3 values = get(); - bool const changed = DragN(label, componentLabels, { &values.x, &values.y, &values.z }, speed, displayFormat, valueMin, valueMax, flags); - - + if(isAnAngleInRad) + { + values = {SHMath::RadiansToDegrees(values.x), SHMath::RadiansToDegrees(values.y), SHMath::RadiansToDegrees(values.z)}; + } + bool isHovered = false; + bool const changed = DragN(label, componentLabels, { &values.x, &values.y, &values.z }, speed, displayFormat, valueMin, valueMax, flags, &isHovered); static bool startRecording = false; if (changed) { SHVec3 old = get(); + if(isAnAngleInRad) + { + values = {SHMath::DegreesToRadians(values.x), SHMath::DegreesToRadians(values.y), SHMath::DegreesToRadians(values.z)}; + } SHCommandManager::PerformCommand(std::reinterpret_pointer_cast(std::make_shared>(old, values, set)), startRecording); if (!startRecording) startRecording = true; @@ -249,9 +270,9 @@ namespace SHADE { startRecording = false; } - if(!tooltip.empty()) + if (!tooltip.empty()) { - if(ImGui::IsItemHovered()) + if (isHovered) { ImGui::BeginTooltip(); ImGui::Text(tooltip.data()); @@ -262,14 +283,22 @@ namespace SHADE } static bool DragVec4(const std::string& label, std::vectorconst& componentLabels, std::function get, - std::function set, float speed = 0.1f, const char* displayFormat = "%.3f", std::string_view const& tooltip = {}, float valueMin = 0.0f, float valueMax = 0.0f, + std::function set, bool const& isAnAngleInRad = false, std::string_view const& tooltip = {}, float speed = 0.1f, const char* displayFormat = "%.3f", float valueMin = 0.0f, float valueMax = 0.0f, ImGuiSliderFlags flags = 0) { SHVec4 values = get(); + if(isAnAngleInRad) + { + values = {SHMath::RadiansToDegrees(values.x), SHMath::RadiansToDegrees(values.y), SHMath::RadiansToDegrees(values.z), SHMath::RadiansToDegrees(values.w)}; + } bool const changed = DragN(label, componentLabels, { &values.x, &values.y, &values.z, &values.w }, speed, displayFormat, valueMin, valueMax, flags); static bool startRecording = false; if (changed) { + if(isAnAngleInRad) + { + values = {SHMath::DegreesToRadians(values.x), SHMath::DegreesToRadians(values.y), SHMath::DegreesToRadians(values.z), SHMath::DegreesToRadians(values.w)}; + } SHCommandManager::PerformCommand(std::reinterpret_pointer_cast(std::make_shared>(get(), values, set)), startRecording); if (!startRecording) startRecording = true; @@ -278,9 +307,9 @@ namespace SHADE { startRecording = false; } - if(!tooltip.empty()) + if (!tooltip.empty()) { - if(ImGui::IsItemHovered()) + if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); ImGui::Text(tooltip.data()); @@ -297,7 +326,7 @@ namespace SHADE static void TextLabel(std::string_view const& text, bool sameLine = true) { const ImVec2 textSize = ImGui::CalcTextSize(text.data(), NULL, true); - if(textSize.x > 0.0f) + if (textSize.x > 0.0f) { ImGui::Text(text.data()); ImGui::SameLine(); @@ -310,32 +339,32 @@ namespace SHADE ImGui::BeginGroup(); ImGui::PushID(label.data()); TextLabel(label); - if (ImGui::Checkbox("##", &value)) + bool const changed = ImGui::Checkbox("##", &value); + if (changed) { SHCommandManager::PerformCommand(std::reinterpret_pointer_cast(std::make_shared>(get(), value, set)), false); - return true; } ImGui::PopID(); ImGui::EndGroup(); - if(!tooltip.empty()) + if (!tooltip.empty()) { - if(ImGui::IsItemHovered()) + if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); ImGui::Text(tooltip.data()); ImGui::EndTooltip(); } } - return false; + return changed; } template - static bool RadioButton(std::vector const& label, std::vector const& listTypes, std::function get, std::function set ,std::string_view const& tooltip = {}) + static bool RadioButton(std::vector const& label, std::vector const& listTypes, std::function get, std::function set, std::string_view const& tooltip = {}) { T type = get(); ImGui::BeginGroup(); ImGui::PushID(label.data()); - TextLabel(label); + //TextLabel(label); for (size_t i = 0; i < listTypes.size(); i++) { if (ImGui::RadioButton(label[i].c_str(), type == listTypes[i])) @@ -366,12 +395,11 @@ namespace SHADE ImGui::BeginGroup(); ImGui::PushID(label.data()); TextLabel(label); - if (ImGui::InputText("##", &text, flag, callback, userData)) + bool const changed = ImGui::InputText("##", &text, flag, callback, userData); + if (changed) { if (ImGui::IsItemDeactivatedAfterEdit()) SHCommandManager::PerformCommand(std::reinterpret_pointer_cast(std::make_shared>(get(), text, set)), false); - - return true; } ImGui::PopID(); ImGui::EndGroup(); @@ -384,7 +412,37 @@ namespace SHADE ImGui::EndTooltip(); } } - return false; + return changed; + } + + template + static bool DragDropReadOnlyField(std::string const& label, std::string_view const& fieldVTextValue, std::function const& get, std::function const& set, SHDragDrop::DragDropTag const& dragDropTag, std::string_view const& tooltip = {}) + { + std::string text = fieldVTextValue.data(); + ImGui::BeginGroup(); + ImGui::PushID(label.data()); + TextLabel(label); + bool const changed = ImGui::InputText("##", &text, ImGuiInputTextFlags_ReadOnly, nullptr, nullptr); + if(SHDragDrop::BeginTarget()) + { + if(T* payload = SHDragDrop::AcceptPayload(dragDropTag)) + { + SHCommandManager::PerformCommand(std::reinterpret_pointer_cast(std::make_shared>(get(), *payload, set)), false); + SHDragDrop::EndTarget(); + } + } + ImGui::PopID(); + ImGui::EndGroup(); + if (!tooltip.empty()) + { + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::Text(tooltip.data()); + ImGui::EndTooltip(); + } + } + return changed; } template @@ -442,9 +500,9 @@ namespace SHADE } ImGui::PopID(); ImGui::EndGroup(); - if(!tooltip.empty()) + if (!tooltip.empty()) { - if(ImGui::IsItemHovered()) + if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); ImGui::Text(tooltip.data()); diff --git a/SHADE_Engine/src/Events/SHEventDefines.h b/SHADE_Engine/src/Events/SHEventDefines.h index 804fbfec..d649fabf 100644 --- a/SHADE_Engine/src/Events/SHEventDefines.h +++ b/SHADE_Engine/src/Events/SHEventDefines.h @@ -13,4 +13,7 @@ constexpr SHEventIdentifier SH_COMPONENT_REMOVED_EVENT { 4 }; constexpr SHEventIdentifier SH_SCENEGRAPH_CHANGE_PARENT_EVENT { 5 }; constexpr SHEventIdentifier SH_PHYSICS_COLLIDER_ADDED_EVENT { 6 }; constexpr SHEventIdentifier SH_PHYSICS_COLLIDER_REMOVED_EVENT { 7 }; +constexpr SHEventIdentifier SH_EDITOR_ON_PLAY_EVENT { 8 }; +constexpr SHEventIdentifier SH_EDITOR_ON_PAUSE_EVENT { 9 }; +constexpr SHEventIdentifier SH_EDITOR_ON_STOP_EVENT { 10 }; diff --git a/SHADE_Engine/src/Graphics/Commands/SHVkCommandBuffer.cpp b/SHADE_Engine/src/Graphics/Commands/SHVkCommandBuffer.cpp index a744c795..fb64bcc2 100644 --- a/SHADE_Engine/src/Graphics/Commands/SHVkCommandBuffer.cpp +++ b/SHADE_Engine/src/Graphics/Commands/SHVkCommandBuffer.cpp @@ -282,6 +282,11 @@ namespace SHADE } + void SHVkCommandBuffer::SetLineWidth(float lineWidth) noexcept + { + vkCommandBuffer.setLineWidth(lineWidth); + } + /***************************************************************************/ /*! diff --git a/SHADE_Engine/src/Graphics/Commands/SHVkCommandBuffer.h b/SHADE_Engine/src/Graphics/Commands/SHVkCommandBuffer.h index 4c978c34..bc0d4b04 100644 --- a/SHADE_Engine/src/Graphics/Commands/SHVkCommandBuffer.h +++ b/SHADE_Engine/src/Graphics/Commands/SHVkCommandBuffer.h @@ -115,6 +115,7 @@ namespace SHADE // 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; + void SetLineWidth (float lineWidth) noexcept; // Binding Commands void BindPipeline (Handle const& pipelineHdl) noexcept; diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Batching/SHBatch.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Batching/SHBatch.cpp index 1bda7c90..22d1875b 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Batching/SHBatch.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Batching/SHBatch.cpp @@ -74,11 +74,12 @@ namespace SHADE void SHBatch::Remove(const SHRenderable* renderable) { - // Check if we have a SubBatch with the same mesh yet + // Check if we have a SubBatch with the existing mesh yet (if changed, we use the old mesh) + Handle prevSubBatchMesh = renderable->HasMeshChanged() ? renderable->GetPrevMesh() : renderable->GetMesh(); auto subBatch = std::find_if(subBatches.begin(), subBatches.end(), [&](const SHSubBatch& batch) - { - return batch.Mesh == renderable->GetMesh(); - }); + { + return batch.Mesh == prevSubBatchMesh; + }); // Attempt to remove if it exists if (subBatch == subBatches.end()) @@ -88,9 +89,7 @@ namespace SHADE // Check if other renderables in subBatches contain the same material instance bool matUnused = true; - Handle matToCheck = renderable->HasMaterialChanged() ? renderable->GetPrevMaterial() : renderable->GetMaterial(); - for (const auto& sb : subBatches) { // Check material usage diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Batching/SHSuperBatch.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Batching/SHSuperBatch.cpp index 434e7163..df389879 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Batching/SHSuperBatch.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Batching/SHSuperBatch.cpp @@ -37,9 +37,9 @@ namespace SHADE // Check if we have a batch with the same pipeline first auto batch = std::find_if(batches.begin(), batches.end(), [&](const SHBatch& batch) - { - return batch.GetPipeline() == PIPELINE; - }); + { + return batch.GetPipeline() == PIPELINE; + }); // Create one if not found diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.cpp new file mode 100644 index 00000000..08019665 --- /dev/null +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.cpp @@ -0,0 +1,202 @@ +/************************************************************************************//*! +\file SHDebugDrawSystem.cpp +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Oct 16, 2022 +\brief Contains the definition of functions of the SHDebugDrawSystem 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. +*//*************************************************************************************/ +#include "SHpch.h" +#include "SHDebugDrawSystem.h" +// STL Includes +#include +// Project Includes +#include "../Meshes/SHMeshData.h" +#include "../Meshes/SHPrimitiveGenerator.h" +#include "ECS_Base/Managers/SHSystemManager.h" +#include "SHGraphicsSystem.h" +#include "Graphics/Devices/SHVkLogicalDevice.h" +#include "../../SHVkUtil.h" +#include "Graphics/MiddleEnd/Interface/SHViewport.h" +#include "Graphics/MiddleEnd/Interface/SHRenderer.h" + +namespace SHADE +{ + /*---------------------------------------------------------------------------------*/ + /* DrawRoutine */ + /*---------------------------------------------------------------------------------*/ + SHDebugDrawSystem::ProcessPointsRoutine::ProcessPointsRoutine() + : SHSystemRoutine("Debug Draw", true) + { + SystemFamily::GetID(); + } + + void SHDebugDrawSystem::ProcessPointsRoutine::Execute(double dt) noexcept + { + auto gfxSys = SHSystemManager::GetSystem(); + if (!gfxSys) + { + SHLOG_WARNING("[DebugDraw] Attempted to do debug draw without a graphics system."); + return; + } + + // Get current frame index + const uint32_t FRAME_IDX = gfxSys->GetCurrentFrameIndex(); + + // Create the buffer if it doesn't exist or just update it + SHDebugDrawSystem* system = static_cast(GetSystem()); + system->numPoints[FRAME_IDX] = system->points.size(); + const uint32_t DATA_SIZE = sizeof(PointVertex) * system->points.size(); + if (DATA_SIZE > 0) + { + system->vertexBuffers[FRAME_IDX]->WriteToMemory(system->points.data(), DATA_SIZE, 0, 0); + } + + // Reset for next frame + system->points.clear(); + } + + /*---------------------------------------------------------------------------------*/ + /* SHSystem overrides */ + /*---------------------------------------------------------------------------------*/ + void SHDebugDrawSystem::Init() + { + // Register function for subpass + const auto* GFX_SYSTEM = SHSystemManager::GetSystem(); + auto const& RENDERERS = GFX_SYSTEM->GetDefaultViewport()->GetRenderers(); + auto renderGraph = RENDERERS[SHGraphicsConstants::RenderGraphIndices::WORLD]->GetRenderGraph(); + auto subPass = renderGraph->GetNode("Debug Draw")->GetSubpass("Debug Draw"); + subPass->AddExteriorDrawCalls([this, GFX_SYSTEM](Handle& cmdBuffer) + { + // Get Current frame index + const uint32_t FRAME_IDX = GFX_SYSTEM->GetCurrentFrameIndex(); + + // Don't draw if no points + if (numPoints[FRAME_IDX] <= 0) + return; + + cmdBuffer->BindPipeline(GFX_SYSTEM->GetDebugDrawPipeline()); + cmdBuffer->SetLineWidth(LineWidth); + cmdBuffer->BindVertexBuffer(0, vertexBuffers[FRAME_IDX], 0); + cmdBuffer->DrawArrays(numPoints[FRAME_IDX], 1, 0, 0); + }); + + // Reset trackers + std::fill_n(numPoints.begin(), numPoints.size(), 0); + + // Allocate buffers + static constexpr uint32_t BUFFER_SIZE = MAX_POINTS * sizeof(PointVertex); + for (Handle& bufHandle : vertexBuffers) + { + bufHandle = GFX_SYSTEM->GetDevice()->CreateBuffer + ( + BUFFER_SIZE, + nullptr, + 0, + vk::BufferUsageFlagBits::eVertexBuffer, + VmaMemoryUsage::VMA_MEMORY_USAGE_AUTO, + VmaAllocationCreateFlagBits::VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VmaAllocationCreateFlagBits::VMA_ALLOCATION_CREATE_MAPPED_BIT + ); + } + } + + void SHDebugDrawSystem::Exit() + { + for (auto vertexBuffer : vertexBuffers) + { + if (vertexBuffer) + vertexBuffer.Free(); + } + } + + /*---------------------------------------------------------------------------------*/ + /* Draw Functions */ + /*---------------------------------------------------------------------------------*/ + void SHDebugDrawSystem::DrawLine(const SHVec4& color, const SHVec3& startPt, const SHVec3& endPt) + { + if (points.size() > MAX_POINTS) + { + SHLOG_WARNING("[DebugDraw] Exceeded maximum size of drawable debug elements."); + return; + } + + points.emplace_back(PointVertex{ startPt, color }); + points.emplace_back(PointVertex{ endPt, color }); + } + + void SHDebugDrawSystem::DrawTri(const SHVec4& color, const SHVec3& pt1, const SHVec3& pt2, const SHVec3& pt3) + { + DrawPoly(color, { pt1, pt2, pt3 }); + } + + void SHDebugDrawSystem::DrawQuad(const SHVec4& color, const SHVec3& pt1, const SHVec3& pt2, const SHVec3& pt3, const SHVec3& pt4) + { + DrawPoly(color, { pt1, pt2, pt3, pt4 }); + } + + void SHDebugDrawSystem::DrawPoly(const SHVec4& color, std::initializer_list pointList) + { + DrawPoly(color, pointList.begin(), pointList.end()); + } + + void SHDebugDrawSystem::DrawCube(const SHVec4& color, const SHVec3& pos, const SHVec3& size) + { + static const SHVec3 EXTENTS = SHVec3 { 0.5f, 0.5f, 0.5f }; + static const SHVec3 UNIT_BOT_LEFT_FRONT = SHVec3 { pos - EXTENTS }; + static const SHVec3 UNIT_BOT_RIGHT_FRONT = SHVec3 { pos + SHVec3 { EXTENTS.x, -EXTENTS.y, -EXTENTS.z } }; + static const SHVec3 UNIT_BOT_RIGHT_BACK = SHVec3 { pos + SHVec3 { EXTENTS.x, -EXTENTS.y, EXTENTS.z } }; + static const SHVec3 UNIT_BOT_LEFT_BACK = SHVec3 { pos + SHVec3 { -EXTENTS.x, -EXTENTS.y, EXTENTS.z } }; + static const SHVec3 UNIT_TOP_LEFT_BACK = SHVec3 { pos + SHVec3 { -EXTENTS.x, EXTENTS.y, EXTENTS.z } }; + static const SHVec3 UNIT_TOP_RIGHT_FRONT = SHVec3 { pos + SHVec3 { EXTENTS.x, EXTENTS.y, -EXTENTS.z } }; + static const SHVec3 UNIT_TOP_LEFT_FRONT = SHVec3 { pos + SHVec3 { -EXTENTS.x, EXTENTS.y, -EXTENTS.z } }; + static const SHVec3 UNIT_TOP_RIGHT_BACK = SHVec3 { pos + EXTENTS }; + + const SHVec3 BOT_LEFT_BACK = UNIT_BOT_LEFT_BACK * size; + const SHVec3 BOT_RIGHT_BACK = UNIT_BOT_RIGHT_BACK * size; + const SHVec3 BOT_LEFT_FRONT = UNIT_BOT_LEFT_FRONT * size; + const SHVec3 BOT_RIGHT_FRONT = UNIT_BOT_RIGHT_FRONT * size; + const SHVec3 TOP_LEFT_BACK = UNIT_TOP_LEFT_BACK * size; + const SHVec3 TOP_RIGHT_BACK = UNIT_TOP_RIGHT_BACK * size; + const SHVec3 TOP_LEFT_FRONT = UNIT_TOP_LEFT_FRONT * size; + const SHVec3 TOP_RIGHT_FRONT = UNIT_TOP_RIGHT_FRONT * size; + + DrawPoly + ( + color, + { + // Bottom Square + BOT_LEFT_BACK , BOT_RIGHT_BACK, + BOT_RIGHT_BACK , BOT_RIGHT_FRONT, + BOT_RIGHT_FRONT, BOT_LEFT_FRONT, + BOT_LEFT_FRONT , BOT_LEFT_BACK, + // Top Square + TOP_LEFT_BACK , TOP_RIGHT_BACK, + TOP_RIGHT_BACK , TOP_RIGHT_FRONT, + TOP_RIGHT_FRONT, TOP_LEFT_FRONT, + TOP_LEFT_FRONT , TOP_LEFT_BACK, + // Middle Lines + TOP_LEFT_BACK , BOT_LEFT_BACK, + TOP_RIGHT_BACK , BOT_RIGHT_BACK, + TOP_RIGHT_FRONT, BOT_RIGHT_FRONT, + TOP_LEFT_FRONT , BOT_LEFT_FRONT + } + ); + } + + void SHDebugDrawSystem::DrawSphere(const SHVec4& color, const SHVec3& pos, double radius) + { + if (spherePoints.empty()) + { + // Generate + static const SHMeshData SPHERE = SHPrimitiveGenerator::Sphere(); + for (const auto& idx : SPHERE.Indices) + { + spherePoints.emplace_back(SPHERE.VertexPositions[idx]); + } + } + DrawPoly(color, spherePoints.begin(), spherePoints.end()); + } +} \ No newline at end of file diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.h b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.h new file mode 100644 index 00000000..4b83958d --- /dev/null +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.h @@ -0,0 +1,159 @@ +/************************************************************************************//*! +\file SHDebugDrawSystem.h +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Oct 16, 2022 +\brief Contains the definition of the SHDebugDrawSystem 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. +*//*************************************************************************************/ +#pragma once + +// STL Includes +#include +// Project Includes +#include "SH_API.h" +#include "Math/Vector/SHVec2.h" +#include "Math/Vector/SHVec3.h" +#include "Math/Vector/SHVec4.h" +#include "ECS_Base/System/SHSystem.h" +#include "ECS_Base/System/SHSystemRoutine.h" +#include "Resource/SHHandle.h" +#include "Graphics/Buffers/SHVkBuffer.h" +#include "SHGraphicsConstants.h" +#include "Math/SHColour.h" + +namespace SHADE +{ + /*-----------------------------------------------------------------------------------*/ + /* Forward Declarations */ + /*-----------------------------------------------------------------------------------*/ + class SHVkBuffer; + + /*-----------------------------------------------------------------------------------*/ + /* Type Definitions */ + /*-----------------------------------------------------------------------------------*/ + /// + /// Manages the Debug Draw system. + /// + class SH_API SHDebugDrawSystem final : public SHSystem + { + public: + /*---------------------------------------------------------------------------------*/ + /* System Routines */ + /*---------------------------------------------------------------------------------*/ + class SH_API ProcessPointsRoutine final : public SHSystemRoutine + { + public: + ProcessPointsRoutine(); + virtual void Execute(double dt) noexcept override final; + }; + + /*---------------------------------------------------------------------------------*/ + /* SHSystem overrides */ + /*---------------------------------------------------------------------------------*/ + virtual void Init() override final; + virtual void Exit() override final; + + /*---------------------------------------------------------------------------------*/ + /* Configuration Functions */ + /*---------------------------------------------------------------------------------*/ + /// + /// Configures the line width used to draw all lines in the Debug Draw system. + /// + float LineWidth = 1.0f; + + /*---------------------------------------------------------------------------------*/ + /* Draw Functions */ + /*---------------------------------------------------------------------------------*/ + /// + /// Renders a line between two points in world space. + /// + /// Colour of the line. + /// First point of the line. + /// Second point of the line. + void DrawLine(const SHVec4& color, const SHVec3& startPt, const SHVec3& endPt); + /// + /// Renders a triangle indicated by three points in world space. + /// + /// Colour of the triangle. + /// First point of the triangle. + /// Second point of the triangle. + /// Third point of the triangle. + void DrawTri(const SHVec4& color, const SHVec3& pt1, const SHVec3& pt2, const SHVec3& pt3); + /// + /// Renders a quadrilateral indicated by four points in world space. + /// + /// Colour of the quadrilateral. + /// First point of the triangle. + /// Second point of the quadrilateral. + /// Third point of the quadrilateral. + /// Third point of the quadrilateral. + void DrawQuad(const SHVec4& color, const SHVec3& pt1, const SHVec3& pt2, const SHVec3& pt3, const SHVec3& pt4); + /// + /// Renders a polygon indicated by the specified set of points in world space. + /// + /// Colour of the polygon. + /// List of points for the polygon. + void DrawPoly(const SHVec4& color, std::initializer_list pointList); + /// + /// Renders a polygon indicated by the specified set of points in world space. + /// + /// Iterator for a STL-like container. + /// Colour of the polygon. + /// + /// Iterator to the first point of the point container. + /// + /// + /// One past last iterator of the point container. + /// + template + void DrawPoly(const SHVec4& color, IterType pointListBegin, IterType pointListEnd); + /// + /// Renders a wireframe cube centered around the position specified in world space. + /// + /// Colour of the cube. + /// Position where the cube wil be centered at. + /// Size of the rendered cube. + void DrawCube(const SHVec4& color, const SHVec3& pos, const SHVec3& size); + /// + /// Renders a wireframe sphere centered around the position specified in world space. + /// + /// Colour of the sphere. + /// Position where the sphere wil be centered at. + /// Size of the rendered sphere. + void DrawSphere(const SHVec4& color, const SHVec3& pos, double radius); + + private: + /*---------------------------------------------------------------------------------*/ + /* Type Definitions */ + /*---------------------------------------------------------------------------------*/ + struct SH_API PointVertex + { + SHVec4 Position; + SHVec4 Color; + }; + using TripleBuffer = std::array, SHGraphicsConstants::NUM_FRAME_BUFFERS>; + using TripleUInt = std::array; + + /*---------------------------------------------------------------------------------*/ + /* Constants */ + /*---------------------------------------------------------------------------------*/ + static constexpr uint32_t MAX_POINTS = 100'000; + + /*---------------------------------------------------------------------------------*/ + /* Data Members */ + /*---------------------------------------------------------------------------------*/ + // CPU Buffers + std::vector points; + // GPU Buffers + TripleBuffer vertexBuffers; + TripleUInt numPoints; + // Cached Points for polygon drawing + std::vector spherePoints; + }; +} + +#include "SHDebugDrawSystem.hpp" \ No newline at end of file diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.hpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.hpp new file mode 100644 index 00000000..14fbb42f --- /dev/null +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHDebugDrawSystem.hpp @@ -0,0 +1,48 @@ +/************************************************************************************//*! +\file SHDebugDrawSystem.hpp +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Oct 16, 2022 +\brief Contains the definition of template functions the SHDebugDrawSystem + 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. +*//*************************************************************************************/ +#pragma once +#include "SHDebugDrawSystem.h" + +namespace SHADE +{ + /*-----------------------------------------------------------------------------------*/ + /* Draw Functions */ + /*-----------------------------------------------------------------------------------*/ + template + void SHDebugDrawSystem::DrawPoly(const SHVec4& color, IterType pointListBegin, IterType pointListEnd) + { + // Ensure dereferenced type is SHVec3 + static_assert(std::is_same_v>, "Parameters to DrawPoly must be SHVec3."); + + // Check if points exceeded max + if (points.size() > MAX_POINTS) + { + SHLOG_WARNING("[DebugDraw] Exceeded maximum size of drawable debug elements."); + return; + } + + const size_t POINTS_COUNT = pointListEnd - pointListBegin; + // Invalid polygon + if (POINTS_COUNT < 2) + { + SHLOG_WARNING("[SHDebugDraw] Invalid polygon provided to DrawPoly()."); + return; + } + + const size_t POINTS_ROUNDED_COUNT = POINTS_COUNT / 2 * 2; + for (auto pointIter = pointListBegin; pointIter != (pointListBegin + POINTS_ROUNDED_COUNT); ++pointIter) + { + points.emplace_back(PointVertex{ *pointIter, color }); + } + } +} \ No newline at end of file diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp index af3b46e1..eb9269e6 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp @@ -17,7 +17,7 @@ of DigiPen Institute of Technology is prohibited. #include "Graphics/Windowing/Surface/SHVkSurface.h" #include "Graphics/Swapchain/SHVkSwapchain.h" #include "Camera/SHCameraSystem.h" -#include "Editor/SHEditor.hpp" +#include "Editor/SHEditor.h" #include "ECS_Base/Managers/SHSystemManager.h" //#include "SHRenderer.h" #include "Graphics/Windowing/SHWindow.h" @@ -37,8 +37,10 @@ of DigiPen Institute of Technology is prohibited. #include "Assets/Asset Types/SHTextureAsset.h" #include "Graphics/MiddleEnd/Interface/SHMousePickSystem.h" #include "Graphics/MiddleEnd/Lights/SHLightingSubSystem.h" -#include "Graphics/RenderGraph/SHRenderGraphNodeCompute.h" #include "Assets/SHAssetManager.h" +#include "Resource/SHResourceManager.h" +#include "Graphics/SHVkUtil.h" +#include "Graphics/RenderGraph/SHRenderGraphNodeCompute.h" namespace SHADE { @@ -106,19 +108,16 @@ namespace SHADE descPool = device->CreateDescriptorPools(); // Create generic command buffer - //transferCmdPool = device->CreateCommandPool(SH_QUEUE_FAMILY_ARRAY_INDEX::GRAPHICS, SH_CMD_POOL_RESET::POOL_BASED, true); graphicsCmdPool = device->CreateCommandPool(SH_QUEUE_FAMILY_ARRAY_INDEX::GRAPHICS, SH_CMD_POOL_RESET::POOL_BASED, true); - transferCmdBuffer = graphicsCmdPool->RequestCommandBuffer(SH_CMD_BUFFER_TYPE::PRIMARY); - graphicsTexCmdBuffer = graphicsCmdPool->RequestCommandBuffer(SH_CMD_BUFFER_TYPE::PRIMARY); - SHAssetManager::CompileAsset("../../Assets/Shaders/TestCube_VS.glsl"); - SHAssetManager::CompileAsset("../../Assets/Shaders/TestCube_FS.glsl"); - SHAssetManager::CompileAsset("../../Assets/Shaders/DeferredComposite_CS.glsl"); - SHAssetManager::CompileAsset("../../Assets/Shaders/SSAO_CS.glsl"); - SHAssetManager::CompileAsset("../../Assets/Shaders/SSAOBlur_CS.glsl"); - - shaderModuleLibrary.ImportAllShaderSource(device); - shaderModuleLibrary.ReflectAllShaderModules(); + // Load Built In Shaders + static constexpr AssetID VS_DEFAULT = 39210065; defaultVertShader = SHResourceManager::LoadOrGet(VS_DEFAULT); + static constexpr AssetID FS_DEFAULT = 46377769; defaultFragShader = SHResourceManager::LoadOrGet(FS_DEFAULT); + static constexpr AssetID VS_DEBUG = 48002439; debugVertShader = SHResourceManager::LoadOrGet(VS_DEBUG); + static constexpr AssetID FS_DEBUG = 36671027; debugFragShader = SHResourceManager::LoadOrGet(FS_DEBUG); + static constexpr AssetID CS_COMPOSITE = 45072428; deferredCompositeShader = SHResourceManager::LoadOrGet(CS_COMPOSITE); + static constexpr AssetID SSAO = 38430899; ssaoShader = SHResourceManager::LoadOrGet(SSAO); + static constexpr AssetID SSAO_BLUR = 39760835; ssaoBlurShader = SHResourceManager::LoadOrGet(SSAO_BLUR); } void SHGraphicsSystem::InitSceneRenderGraph(void) noexcept @@ -220,7 +219,6 @@ namespace SHADE ssaoStorage->PrepareRotationVectorsVkData(device); - auto ssaoShader = shaderModuleLibrary.GetBuiltInShaderModule("SSAO_CS"); Handle ssaoPass = gBufferNode->AddNodeCompute(ssaoShader, {"Position", "Normals", "SSAO"}); auto ssaoDataBuffer = ssaoStorage->GetBuffer(); ssaoPass->ModifyWriteDescBufferComputeResource(SHGraphicsConstants::DescriptorSetIndex::RENDERGRAPH_NODE_COMPUTE_RESOURCE, SHSSAO::DESC_SET_BUFFER_BINDING, { &ssaoDataBuffer, 1 }, 0, ssaoStorage->GetBuffer()->GetSizeStored()); @@ -228,21 +226,21 @@ namespace SHADE auto viewSamplerLayout = ssaoStorage->GetViewSamplerLayout(); ssaoPass->ModifyWriteDescImageComputeResource(SHGraphicsConstants::DescriptorSetIndex::RENDERGRAPH_NODE_COMPUTE_RESOURCE, SHSSAO::DESC_SET_IMAGE_BINDING, {&viewSamplerLayout, 1}); - auto ssaoBlurShader = shaderModuleLibrary.GetBuiltInShaderModule("SSAOBlur_CS"); Handle ssaoBlurPass = gBufferNode->AddNodeCompute(ssaoBlurShader, { "SSAO", "SSAO Blur"}); /*-----------------------------------------------------------------------*/ /* DEFERRED COMPOSITE SUBPASS INIT */ /*-----------------------------------------------------------------------*/ - auto deferredCompositeShader = shaderModuleLibrary.GetBuiltInShaderModule("DeferredComposite_CS"); gBufferNode->AddNodeCompute(deferredCompositeShader, { "Position", "Normals", "Albedo", "Light Layer Indices", "SSAO Blur", "Scene" }); - /*-----------------------------------------------------------------------*/ - /* DUMMY SUBPASS TO TRANSITION SCENE FOR PRESENT USAGE */ - /*-----------------------------------------------------------------------*/ - // Dummy to transition scene to be used for shader read - auto dummyNode = worldRenderGraph->AddNode("Dummy Pass", { "Scene" }, {"G-Buffer"}); // no predecessors + // Set up Debug Draw Pass + auto debugDrawNode = worldRenderGraph->AddNode("Debug Draw", { "Scene" }, {"G-Buffer"}); + auto debugDrawSubpass = debugDrawNode->AddSubpass("Debug Draw"); + debugDrawSubpass->AddColorOutput("Scene"); + + // Dummy Node + auto dummyNode = worldRenderGraph->AddNode("Dummy Pass", { "Scene" }, { "Debug Draw" }); // no predecessors auto dummySubpass = dummyNode->AddSubpass("Dummy Subpass"); dummySubpass->AddInput("Scene"); @@ -262,10 +260,57 @@ namespace SHADE worldRenderer->SetCameraDirector(cameraSystem->CreateDirector()); - auto cubeVS = shaderModuleLibrary.GetBuiltInShaderModule("TestCube_VS"); - auto cubeFS = shaderModuleLibrary.GetBuiltInShaderModule("TestCube_FS"); + // Create default materials + defaultMaterial = AddMaterial(defaultVertShader, defaultFragShader, gBufferSubpass); - defaultMaterial = AddMaterial(cubeVS, cubeFS, gBufferSubpass); + // Create debug draw pipeline + auto debugDrawPipelineLayout = resourceManager.Create + ( + device, SHPipelineLayoutParams + { + .shaderModules = { debugVertShader, debugFragShader }, + .globalDescSetLayouts = SHGraphicsGlobalData::GetDescSetLayouts() + } + ); + debugDrawPipeline = resourceManager.Create(device, debugDrawPipelineLayout, nullptr, debugDrawNode->GetRenderpass(), debugDrawSubpass); + debugDrawPipeline->GetPipelineState().SetRasterizationState(SHRasterizationState + { + .polygonMode = vk::PolygonMode::eLine, + .cull_mode = vk::CullModeFlagBits::eNone + }); + debugDrawPipeline->GetPipelineState().SetInputAssemblyState(SHInputAssemblyState + { + .topology = vk::PrimitiveTopology::eLineList + }); + + SHVertexInputState debugDrawVertexInputState; + debugDrawVertexInputState.AddBinding(false, true, { SHVertexAttribute(SHAttribFormat::FLOAT_4D), SHVertexAttribute(SHAttribFormat::FLOAT_4D) }); + debugDrawPipeline->GetPipelineState().SetVertexInputState(debugDrawVertexInputState); + SHColorBlendState colorBlendState{}; + colorBlendState.logic_op_enable = VK_FALSE; + colorBlendState.logic_op = vk::LogicOp::eCopy; + + auto const& subpassColorReferences = debugDrawSubpass->GetColorAttachmentReferences(); + colorBlendState.attachments.reserve(subpassColorReferences.size()); + + for (auto& att : subpassColorReferences) + { + colorBlendState.attachments.push_back(vk::PipelineColorBlendAttachmentState + { + .blendEnable = SHVkUtil::IsBlendCompatible(debugDrawSubpass->GetFormatFromAttachmentReference(att.attachment)), + .srcColorBlendFactor = vk::BlendFactor::eSrcAlpha, + .dstColorBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha, + .colorBlendOp = vk::BlendOp::eAdd, + .srcAlphaBlendFactor = vk::BlendFactor::eOne, + .dstAlphaBlendFactor = vk::BlendFactor::eZero, + .alphaBlendOp = vk::BlendOp::eAdd, + .colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA, + } + ); + } + + debugDrawPipeline->GetPipelineState().SetColorBlenState(colorBlendState); + debugDrawPipeline->ConstructPipeline(); } void SHGraphicsSystem::InitMiddleEnd(void) noexcept @@ -696,10 +741,14 @@ namespace SHADE void SHGraphicsSystem::BuildMeshBuffers() { + transferCmdBuffer = graphicsCmdPool->RequestCommandBuffer(SH_CMD_BUFFER_TYPE::PRIMARY); + device->WaitIdle(); transferCmdBuffer->BeginRecording(); meshLibrary.BuildBuffers(device, transferCmdBuffer); transferCmdBuffer->EndRecording(); graphicsQueue->SubmitCommandBuffer({ transferCmdBuffer }); + device->WaitIdle(); + transferCmdBuffer.Free(); transferCmdBuffer = {}; } /*---------------------------------------------------------------------------------*/ @@ -724,10 +773,14 @@ namespace SHADE void SHGraphicsSystem::BuildTextures() { + graphicsTexCmdBuffer = graphicsCmdPool->RequestCommandBuffer(SH_CMD_BUFFER_TYPE::PRIMARY); + device->WaitIdle(); texLibrary.BuildTextures ( device, graphicsTexCmdBuffer, graphicsQueue, descPool ); + device->WaitIdle(); + graphicsTexCmdBuffer.Free(); graphicsTexCmdBuffer = {}; } #pragma endregion ADD_REMOVE @@ -767,6 +820,7 @@ namespace SHADE void SHGraphicsSystem::EndRoutine::Execute(double) noexcept { reinterpret_cast(system)->EndRender(); + SHResourceManager::FinaliseChanges(); } /*-----------------------------------------------------------------------------------*/ @@ -784,8 +838,13 @@ namespace SHADE if (!renderable.HasChanged()) continue; - // Remove from old material's SuperBatch - Handle prevMaterial = renderable.GetPrevMaterial(); + if (!renderable.GetMesh()) + { + SHLOG_CRITICAL("NULL Mesh provided!"); + } + + // Remove from the SuperBatch it is previously in (prevMat if mat has changed) + Handle prevMaterial = renderable.HasMaterialChanged() ? renderable.GetPrevMaterial() : renderable.GetMaterial(); if (prevMaterial) { Handle oldSuperBatch = prevMaterial->GetBaseMaterial()->GetPipeline()->GetPipelineState().GetSubpass()->GetSuperBatch(); diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h index 9b95ebe4..d8b4650e 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h @@ -25,7 +25,6 @@ of DigiPen Institute of Technology is prohibited. #include "ECS_Base/System/SHSystemRoutine.h" #include "Graphics/Descriptors/SHVkDescriptorPool.h" #include "Graphics/RenderGraph/SHRenderGraph.h" -#include "Graphics/MiddleEnd/Shaders/SHShaderModuleLibrary.h" #include "SHMeshLibrary.h" #include "Graphics/MiddleEnd/Materials/SHMaterialInstanceCache.h" #include "../Textures/SHTextureLibrary.h" @@ -290,10 +289,13 @@ namespace SHADE Handle GetMousePickSystem(void) const noexcept {return mousePickSystem;}; Handle GetPostOffscreenRenderSystem(void) const noexcept {return postOffscreenRender;}; Handle GetPrimaryRenderpass() const noexcept; - //SHRenderGraph const& GetRenderGraph(void) const noexcept; - - //Handle GetRenderPass() const { return renderPass; } + Handle GetDebugDrawPipeline(void) const noexcept { return debugDrawPipeline; } + uint32_t GetCurrentFrameIndex(void) const noexcept { return renderContext.GetCurrentFrame(); } + /*-----------------------------------------------------------------------------*/ + /* Getters */ + /*-----------------------------------------------------------------------------*/ + SHWindow* GetWindow() noexcept { return window; } private: /*-----------------------------------------------------------------------------*/ @@ -322,11 +324,12 @@ namespace SHADE SHWindow* window = nullptr; // Middle End Resources - SHResourceHub resourceManager; + SHResourceHub resourceManager; SHMeshLibrary meshLibrary; SHTextureLibrary texLibrary; SHSamplerCache samplerCache; SHMaterialInstanceCache materialInstanceCache; + // Viewports #ifdef SHEDITOR Handle editorViewport; @@ -337,21 +340,26 @@ namespace SHADE Handle worldViewport; // Whole screen std::vector> viewports; // Additional viewports - // Debug Renderers - Handle debugWorldRenderer; - Handle debugScreenRenderer; - // Temp renderers Handle worldRenderer; // Temp Cameras Handle worldCamera; Handle screenCamera; - - SHShaderModuleLibrary shaderModuleLibrary; - // Temp Materials + // Built-In Shaders + Handle defaultVertShader; + Handle defaultFragShader; + Handle debugVertShader; + Handle debugFragShader; + Handle deferredCompositeShader; + Handle ssaoShader; + Handle ssaoBlurShader; + + + // Built-In Materials Handle defaultMaterial; + Handle debugDrawPipeline; Handle worldRenderGraph; diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystemInterface.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystemInterface.cpp new file mode 100644 index 00000000..1ad46e04 --- /dev/null +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystemInterface.cpp @@ -0,0 +1,77 @@ +/************************************************************************************//*! +\file SHGraphicsSystemInterface.cpp +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Oct 31, 2022 +\brief Contains the definitions of the functions of the static + SHGraphicsSystemInterface 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. +*//*************************************************************************************/ +// Precompiled Headers +#include "SHpch.h" +// Primary Header +#include "SHGraphicsSystemInterface.h" +// Project Includes +#include "ECS_Base/Managers/SHSystemManager.h" +#include "Graphics/MiddleEnd/Interface/SHGraphicsSystem.h" +#include "Graphics/Windowing/SHWindow.h" + +namespace SHADE +{ + /*-----------------------------------------------------------------------------------*/ + /* Static Usage Functions */ + /*-----------------------------------------------------------------------------------*/ + uint32_t SHGraphicsSystemInterface::GetWindowWidth() + { + auto gfxSystem = SHSystemManager::GetSystem(); + if (gfxSystem) + { + const auto WND = gfxSystem->GetWindow(); + return WND->GetWindowSize().first; + } + + SHLOG_WARNING("[SHGraphicsSystemInterface] Failed to get window width. Value of 0 returned instead."); + return 0; + } + + uint32_t SHGraphicsSystemInterface::GetWindowHeight() + { + auto gfxSystem = SHSystemManager::GetSystem(); + if (gfxSystem) + { + const auto WND = gfxSystem->GetWindow(); + return WND->GetWindowSize().second; + } + + SHLOG_WARNING("[SHGraphicsSystemInterface] Failed to get window height. Value of 0 returned instead."); + return 0; + } + + bool SHGraphicsSystemInterface::IsFullscreen() + { + auto gfxSystem = SHSystemManager::GetSystem(); + if (gfxSystem) + { + const auto WND = gfxSystem->GetWindow(); + return WND->GetWindowData().isFullscreen; + } + + SHLOG_WARNING("[SHGraphicsSystemInterface] Failed to get window fullscreen status. Value of false returned instead."); + return false; + } + + void SHGraphicsSystemInterface::CloseWindow() + { + auto gfxSystem = SHSystemManager::GetSystem(); + if (gfxSystem) + { + auto WND = gfxSystem->GetWindow(); + return WND->Close(); + } + + SHLOG_WARNING("[SHGraphicsSystemInterface] Failed to close window."); + } +} diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystemInterface.h b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystemInterface.h new file mode 100644 index 00000000..5bc77ed9 --- /dev/null +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystemInterface.h @@ -0,0 +1,52 @@ +/************************************************************************************//*! +\file SHGraphicsSystemInterface.h +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Oct 31, 2022 +\brief Contains the definition of the SHGraphicsSystemInterface static 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. +*//*************************************************************************************/ +#pragma once + +namespace SHADE +{ + /// + /// Static class that wraps up certain functions in the SHGraphicsSystem so that + /// accessing it from SHADE_Managed would not cause issues due to C++20 features. + /// + class SH_API SHGraphicsSystemInterface final + { + public: + /*---------------------------------------------------------------------------------*/ + /* Constructor */ + /*---------------------------------------------------------------------------------*/ + SHGraphicsSystemInterface() = delete; + + /*---------------------------------------------------------------------------------*/ + /* Static Usage Functions */ + /*---------------------------------------------------------------------------------*/ + /// + /// Retrieves the current window width. + /// + /// The current window width. + static uint32_t GetWindowWidth(); + /// + /// Retrieves the current window height. + /// + /// The current window height. + static uint32_t GetWindowHeight(); + /// + /// Retrieves the current window fullscreen status. + /// + /// The current window fullscreen status.. + static bool IsFullscreen(); + /// + /// Closes the current window, and depending on the implementation, should also + /// close the application. + /// + static void CloseWindow(); + }; +} diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Materials/SHMaterialSpec.h b/SHADE_Engine/src/Graphics/MiddleEnd/Materials/SHMaterialSpec.h new file mode 100644 index 00000000..338c34b2 --- /dev/null +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Materials/SHMaterialSpec.h @@ -0,0 +1,36 @@ +/************************************************************************************//*! +\file SHMaterialSpec.h +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Oct 31, 2022 +\brief Contains the struct definition of SHMaterialSpec. + +Copyright (C) 2022 DigiPen Institute of Technology. +Reproduction or disclosure of this file or its contents without the prior written consent +of DigiPen Institute of Technology is prohibited. +*//*************************************************************************************/ +#pragma once +// Standard Library +#include +#include +#include +// Project Includes +#include "Assets/SHAssetMacros.h" + +namespace SHADE +{ + /*************************************************************************************/ + /*! + \brief + Describes a Material's serialized properties. A representation of a material that is + independent of GPU resources. + */ + /*************************************************************************************/ + struct SHMaterialSpec + { + AssetID vertexShader; + AssetID fragShader; + std::string subpassName; + YAML::Node properties; + }; +} diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Meshes/SHPrimitiveGenerator.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Meshes/SHPrimitiveGenerator.cpp index be181beb..c9a3f6c5 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Meshes/SHPrimitiveGenerator.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Meshes/SHPrimitiveGenerator.cpp @@ -3,7 +3,7 @@ \author Tng Kah Wei, kahwei.tng, 390009620 \par email: kahwei.tng\@digipen.edu \date Aug 30, 2022 -\brief Contains definitions for all of the functions of the classes that deal +\brief Contains definitions for all of the functions of the classes that deal with storage and management of vertex and index buffers of meshes. Copyright (C) 2022 DigiPen Institute of Technology. @@ -18,50 +18,59 @@ of DigiPen Institute of Technology is prohibited. namespace SHADE { + /*-----------------------------------------------------------------------------------*/ + /* Static Member Definitions */ + /*-----------------------------------------------------------------------------------*/ + SHMeshData SHPrimitiveGenerator::cubeMesh; + SHMeshData SHPrimitiveGenerator::sphereMesh; + + /*-----------------------------------------------------------------------------------*/ + /* Primitive Generation Functions */ + /*-----------------------------------------------------------------------------------*/ SHMeshData SHPrimitiveGenerator::Cube() noexcept { SHMeshData mesh; - mesh.VertexPositions = + mesh.VertexPositions = { // front - SHVec3(-0.5f, -0.5f, 0.5f), - SHVec3( 0.5f, -0.5f, 0.5f), - SHVec3( 0.5f, 0.5f, 0.5f), - SHVec3(-0.5f, 0.5f, 0.5f), + SHVec3(-0.5f, -0.5f, 0.5f), + SHVec3(0.5f, -0.5f, 0.5f), + SHVec3(0.5f, 0.5f, 0.5f), + SHVec3(-0.5f, 0.5f, 0.5f), // back - SHVec3(-0.5f, -0.5f, -0.5f), - SHVec3(-0.5f, 0.5f, -0.5f), - SHVec3( 0.5f, 0.5f, -0.5f), - SHVec3( 0.5f, -0.5f, -0.5f), + SHVec3(-0.5f, -0.5f, -0.5f), + SHVec3(-0.5f, 0.5f, -0.5f), + SHVec3(0.5f, 0.5f, -0.5f), + SHVec3(0.5f, -0.5f, -0.5f), - // top + // top SHVec3(-0.5f, 0.5f, -0.5f), SHVec3(-0.5f, 0.5f, 0.5f), - SHVec3( 0.5f, 0.5f, 0.5f), - SHVec3( 0.5f, 0.5f, -0.5f), - + SHVec3(0.5f, 0.5f, 0.5f), + SHVec3(0.5f, 0.5f, -0.5f), + // bottom - SHVec3(-0.5f, -0.5f, -0.5f), - SHVec3( 0.5f, -0.5f, -0.5f), - SHVec3( 0.5f, -0.5f, 0.5f), - SHVec3(-0.5f, -0.5f, 0.5f), - + SHVec3(-0.5f, -0.5f, -0.5f), + SHVec3(0.5f, -0.5f, -0.5f), + SHVec3(0.5f, -0.5f, 0.5f), + SHVec3(-0.5f, -0.5f, 0.5f), + // right - SHVec3(0.5f, -0.5f, -0.5f), - SHVec3(0.5f, 0.5f, -0.5f), - SHVec3(0.5f, 0.5f, 0.5f), - SHVec3(0.5f, -0.5f, 0.5f), - + SHVec3(0.5f, -0.5f, -0.5f), + SHVec3(0.5f, 0.5f, -0.5f), + SHVec3(0.5f, 0.5f, 0.5f), + SHVec3(0.5f, -0.5f, 0.5f), + // left - SHVec3(-0.5f, -0.5f, -0.5f), - SHVec3(-0.5f, -0.5f, 0.5f), - SHVec3(-0.5f, 0.5f, 0.5f), - SHVec3(-0.5f, 0.5f, -0.5f) + SHVec3(-0.5f, -0.5f, -0.5f), + SHVec3(-0.5f, -0.5f, 0.5f), + SHVec3(-0.5f, 0.5f, 0.5f), + SHVec3(-0.5f, 0.5f, -0.5f) }; - mesh.VertexTexCoords = + mesh.VertexTexCoords = { SHVec2(0.0f, 1.0f), SHVec2(1.0f, 1.0f), @@ -99,7 +108,7 @@ namespace SHADE SHVec2(0.0f, 0.0f) }; - mesh.VertexTangents = + mesh.VertexTangents = { // front SHVec3(1.0f, 0.0f, 0.0f), @@ -118,7 +127,7 @@ namespace SHADE SHVec3(1.0f, 0.0f, 0.0f), SHVec3(1.0f, 0.0f, 0.0f), SHVec3(1.0f, 0.0f, 0.0f), - + // bottom SHVec3(1.0f, 0.0f, 0.0f), SHVec3(1.0f, 0.0f, 0.0f), @@ -193,10 +202,93 @@ namespace SHADE Handle SHPrimitiveGenerator::Cube(SHMeshLibrary& meshLibrary) noexcept { - static SHMeshData meshData = Cube(); + if (cubeMesh.VertexPositions.empty()) + cubeMesh = Cube(); + return addMeshDataTo(cubeMesh, meshLibrary); + } + + Handle SHPrimitiveGenerator::Cube(SHGraphicsSystem& gfxSystem) noexcept + { + if (cubeMesh.VertexPositions.empty()) + cubeMesh = Cube(); + return addMeshDataTo(cubeMesh, gfxSystem); + } + + SHADE::SHMeshData SHPrimitiveGenerator::Sphere() noexcept + { + SHMeshData meshData; + + const int LAT_SLICES = 12; + const int LONG_SLICES = 12; + float radius = 1; + for (int latNum = 0; latNum <= LAT_SLICES; ++latNum) + { + float theta = static_cast(latNum * std::numbers::pi / LAT_SLICES); + float sinTheta = sin(theta); + float cosTheta = cos(theta); + + for (int longNum = 0; longNum <= LONG_SLICES; ++longNum) + { + float phi = static_cast(longNum * 2 * std::numbers::pi / LONG_SLICES); + float sinPhi = sin(phi); + float cosPhi = cos(phi); + + const SHVec3 NORMAL = SHVec3(cosPhi * sinTheta, cosTheta, sinPhi * sinTheta); + meshData.VertexNormals.emplace_back(NORMAL); + meshData.VertexTangents.emplace_back(/* TODO */); + meshData.VertexTexCoords.emplace_back + ( + 1.0f - (longNum / static_cast(LONG_SLICES)), + 1.0f - (latNum / static_cast(LAT_SLICES)) + ); + meshData.VertexPositions.emplace_back(radius * NORMAL.x, radius * NORMAL.y, radius * NORMAL.z); + } + } + + for (int latNumber{}; latNumber < LAT_SLICES; latNumber++) + { + for (int longNumber{}; longNumber < LONG_SLICES; longNumber++) + { + const auto FIRST = (latNumber * (LONG_SLICES + 1)) + longNumber; + const auto SECOND = (FIRST + LONG_SLICES + 1); + + meshData.Indices.emplace_back(FIRST); + meshData.Indices.emplace_back(SECOND); + meshData.Indices.emplace_back(FIRST + 1); + + meshData.Indices.emplace_back(SECOND); + meshData.Indices.emplace_back(SECOND + 1); + meshData.Indices.emplace_back(FIRST + 1); + } + } + + return meshData; + } + + SHADE::Handle SHPrimitiveGenerator::Sphere(SHMeshLibrary& meshLibrary) noexcept + { + if (sphereMesh.VertexPositions.empty()) + sphereMesh = Sphere(); + + return addMeshDataTo(sphereMesh, meshLibrary); + } + + SHADE::Handle SHPrimitiveGenerator::Sphere(SHGraphicsSystem& gfxSystem) noexcept + { + if (sphereMesh.VertexPositions.empty()) + sphereMesh = Sphere(); + + return addMeshDataTo(sphereMesh, gfxSystem); + } + + /*-----------------------------------------------------------------------------------*/ + /* Helper Functions */ + /*-----------------------------------------------------------------------------------*/ + SHADE::Handle SHPrimitiveGenerator::addMeshDataTo(const SHMeshData& meshData, SHMeshLibrary& meshLibrary) noexcept + { return meshLibrary.AddMesh ( - static_cast(meshData.VertexPositions.size()), + static_cast(meshData.VertexPositions.size()), meshData.VertexPositions.data(), meshData.VertexTexCoords.data(), meshData.VertexTangents.data(), @@ -206,17 +298,16 @@ namespace SHADE ); } - Handle SHPrimitiveGenerator::Cube(SHGraphicsSystem& gfxSystem) noexcept + SHADE::Handle SHPrimitiveGenerator::addMeshDataTo(const SHMeshData& meshData, SHGraphicsSystem& gfxSystem) noexcept { - static SHMeshData meshData = Cube(); return gfxSystem.AddMesh ( - static_cast(meshData.VertexPositions.size()), + static_cast(meshData.VertexPositions.size()), meshData.VertexPositions.data(), meshData.VertexTexCoords.data(), meshData.VertexTangents.data(), meshData.VertexNormals.data(), - static_cast(meshData.Indices.size()), + static_cast(meshData.Indices.size()), meshData.Indices.data() ); } diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Meshes/SHPrimitiveGenerator.h b/SHADE_Engine/src/Graphics/MiddleEnd/Meshes/SHPrimitiveGenerator.h index dd059a29..ef4e26a6 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Meshes/SHPrimitiveGenerator.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Meshes/SHPrimitiveGenerator.h @@ -4,9 +4,9 @@ \par email: kahwei.tng\@digipen.edu \date Sep 18, 2022 \brief Contains the static class definition of SHPrimitiveGenerator. - + Copyright (C) 2022 DigiPen Institute of Technology. -Reproduction or disclosure of this file or its contents without the prior written consent +Reproduction or disclosure of this file or its contents without the prior written consent of DigiPen Institute of Technology is prohibited. *//*************************************************************************************/ #pragma once @@ -29,12 +29,12 @@ namespace SHADE /*************************************************************************************/ /*! \brief - Static class that contains functions for generating 3D primitives. + Static class that contains functions for generating 3D primitives. */ /*************************************************************************************/ class SH_API SHPrimitiveGenerator { - public: + public: /*---------------------------------------------------------------------------------*/ /* Constructors */ /*---------------------------------------------------------------------------------*/ @@ -42,7 +42,7 @@ namespace SHADE /*---------------------------------------------------------------------------------*/ /* Primitive Generation Functions */ - /*---------------------------------------------------------------------------------*/ + /*---------------------------------------------------------------------------------*/ /***********************************************************************************/ /*! \brief @@ -52,20 +52,20 @@ namespace SHADE SHMeshData object containing vertex data for the cube. */ /***********************************************************************************/ - [[nodiscard]] static SHMeshData Cube() noexcept; + [[nodiscard]] static SHMeshData Cube() noexcept; /***********************************************************************************/ /*! \brief Produces a cube and constructs a SHMesh using the SHMeshLibrary provided. \param meshLibrary - Reference to the SHMeshLibrary to procude and store a cube mesh in. + Reference to the SHMeshLibrary to produce and store a cube mesh in. \return SHMesh object that points to the generated cube mesh in the SHMeshLibrary. */ /***********************************************************************************/ - [[nodiscard]] static Handle Cube(SHMeshLibrary& meshLibrary) noexcept; + [[nodiscard]] static Handle Cube(SHMeshLibrary& meshLibrary) noexcept; /***********************************************************************************/ /*! \brief @@ -78,12 +78,55 @@ namespace SHADE SHMesh object that points to the generated cube mesh in the SHGraphicsSystem. */ /***********************************************************************************/ - [[nodiscard]] static Handle Cube(SHGraphicsSystem& gfxSystem) noexcept; + [[nodiscard]] static Handle Cube(SHGraphicsSystem& gfxSystem) noexcept; + /***********************************************************************************/ + /*! + \brief + Produces a sphere and stores the data in a SHMeshData object. - private: + \return + SHMeshData object containing vertex data for the sphere. + */ + /***********************************************************************************/ + [[nodiscard]] static SHMeshData Sphere() noexcept; + /***********************************************************************************/ + /*! + \brief + Produces a sphere and constructs a SHMesh using the SHMeshLibrary provided. + + \param meshLibrary + Reference to the SHMeshLibrary to produce and store a sphere mesh in. + + \return + SHMesh object that points to the generated sphere mesh in the SHMeshLibrary. + */ + /***********************************************************************************/ + [[nodiscard]] static Handle Sphere(SHMeshLibrary& meshLibrary) noexcept; + /***********************************************************************************/ + /*! + \brief + Produces a sphere and constructs a SHMesh using the SHGraphicsSystem provided. + + \param gfxSystem + Reference to the SHGraphicsSystem to produce and store a sphere mesh in. + + \return + SHMesh object that points to the generated sphere mesh in the SHGraphicsSystem. + */ + /***********************************************************************************/ + [[nodiscard]] static Handle Sphere(SHGraphicsSystem& gfxSystem) noexcept; + + private: /*---------------------------------------------------------------------------------*/ /* Helper Functions */ /*---------------------------------------------------------------------------------*/ - [[nodiscard]] static SHMeshData genCubeData() noexcept; + static Handle addMeshDataTo(const SHMeshData& meshData, SHMeshLibrary& meshLibrary) noexcept; + static Handle addMeshDataTo(const SHMeshData& meshData, SHGraphicsSystem& gfxSystem) noexcept; + + /*---------------------------------------------------------------------------------*/ + /* Data Members */ + /*---------------------------------------------------------------------------------*/ + static SHMeshData cubeMesh; + static SHMeshData sphereMesh; }; } \ No newline at end of file diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Shaders/SHShaderModuleLibrary.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Shaders/SHShaderModuleLibrary.cpp deleted file mode 100644 index d0b160df..00000000 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Shaders/SHShaderModuleLibrary.cpp +++ /dev/null @@ -1,139 +0,0 @@ -#include "SHPch.h" -#include "SHShaderModuleLibrary.h" -#include "Graphics/Devices/SHVkLogicalDevice.h" -#include "Assets/SHAssetManager.h" - -namespace SHADE -{ - /***************************************************************************/ - /*! - - \brief - Imports all shader binaries from the source library. - - \param logicalDeviceHdl - For creating shader modules. - - \param sourceLib - The source library class that stores the container of shader binary data. - - */ - /***************************************************************************/ - //void SHShaderModuleLibrary::ImportFromSourceLibrary(Handle& logicalDeviceHdl, SHShaderSourceLibrary const& sourceLib) noexcept - //{ - // auto const& sources = sourceLib.GetSourceLibrary(); - // for (auto const& source : sources) - // { - // vk::ShaderStageFlagBits shaderType{}; - // switch (source.shaderType) - // { - // case SH_SHADER_TYPE::VERTEX: - // shaderType = vk::ShaderStageFlagBits::eVertex; - // break; - // case SH_SHADER_TYPE::FRAGMENT: - // shaderType = vk::ShaderStageFlagBits::eFragment; - // break; - // case SH_SHADER_TYPE::COMPUTE: - // shaderType = vk::ShaderStageFlagBits::eCompute; - // break; - // default: - // shaderType = vk::ShaderStageFlagBits::eVertex; - // break; - // } - - // Handle newShaderModule = logicalDeviceHdl->CreateShaderModule(source.spirvBinary, "main", shaderType, source.name); - // shaderModules.emplace(source.id, newShaderModule); - // stringToID.emplace(source.name, source.id); - // } - //} - - /***************************************************************************/ - /*! - - \brief - Gets the shader module based on module name. - - \param shaderName - - \return - - */ - /***************************************************************************/ - //Handle SHShaderModuleLibrary::GetShaderModule(std::string shaderName) const noexcept - //{ - // if (stringToID.contains(shaderName)) - // return shaderModules.at(stringToID.at(shaderName)); - // else - // return {}; - //} - - vk::ShaderStageFlagBits SHShaderModuleLibrary::GetVkShaderFlag(SH_SHADER_TYPE type) noexcept - { - vk::ShaderStageFlagBits shaderType{}; - switch (type) - { - case SH_SHADER_TYPE::VERTEX: - shaderType = vk::ShaderStageFlagBits::eVertex; - break; - case SH_SHADER_TYPE::FRAGMENT: - shaderType = vk::ShaderStageFlagBits::eFragment; - break; - case SH_SHADER_TYPE::COMPUTE: - shaderType = vk::ShaderStageFlagBits::eCompute; - break; - default: - shaderType = vk::ShaderStageFlagBits::eVertex; - break; - } - - return shaderType; - } - - Handle SHShaderModuleLibrary::GetBuiltInShaderModule(std::string shaderName) const noexcept - { - if (builtInShaderModules.contains(shaderName)) - return builtInShaderModules.at(shaderName); - else - return {}; - } - - void SHShaderModuleLibrary::ImportAllShaderSource(Handle& logicalDeviceHdl) noexcept - { - uint32_t idCounter{ 0 }; - - auto const data = SHAssetManager::GetAllDataOfType(AssetType::SHADER); - for (auto const& dataPtr : data) - { - auto const shader = dynamic_cast(dataPtr); - - Handle newShaderModule = - logicalDeviceHdl->CreateShaderModule(shader->spirvBinary, "main", GetVkShaderFlag(shader->shaderType), shader->name); - - shaderModules.emplace(idCounter++, newShaderModule); - } - - auto const builtIn = SHAssetManager::GetAllDataOfType(AssetType::SHADER_BUILT_IN); - for (auto const& dataPtr : builtIn) - { - auto const shader = dynamic_cast(dataPtr); - - Handle newShaderModule = - logicalDeviceHdl->CreateShaderModule(shader->spirvBinary, "main", GetVkShaderFlag(shader->shaderType), shader->name); - - builtInShaderModules.emplace(shader->name, newShaderModule); - } - } - - void SHShaderModuleLibrary::ReflectAllShaderModules() noexcept - { - for (auto& module : shaderModules) - { - module.second->Reflect(); - } - - for (auto& module : builtInShaderModules) - { - module.second->Reflect(); - } - } -} diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Shaders/SHShaderModuleLibrary.h b/SHADE_Engine/src/Graphics/MiddleEnd/Shaders/SHShaderModuleLibrary.h deleted file mode 100644 index 9daae816..00000000 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Shaders/SHShaderModuleLibrary.h +++ /dev/null @@ -1,44 +0,0 @@ -#ifndef SH_SHADER_MODULE_LIBRARY_H -#define SH_SHADER_MODULE_LIBRARY_H - -#include "Graphics/Shaders/SHVkShaderModule.h" -#include "Assets/Asset Types/SHShaderAsset.h" - -namespace SHADE -{ - class SHVkLogicalDevice; - - /* - * The purpose of this shader module library is to be separate from the source library. The source library contains - * pure shader binary data that contains no vulkan related objects. Every time we load on unload a scene/level, - * this class and the source library class is cleared of its modules and recreated. - */ - class SHShaderModuleLibrary - { - private: - /*-----------------------------------------------------------------------*/ - /* PRIVATE MEMBER VARIABLES */ - /*-----------------------------------------------------------------------*/ - //! Stored shader modules - std::unordered_map> shaderModules; - std::unordered_map> builtInShaderModules; - - inline vk::ShaderStageFlagBits GetVkShaderFlag(SH_SHADER_TYPE type) noexcept; - - public: - /*-----------------------------------------------------------------------*/ - /* PUBLIC MEMBER FUNCTIONS */ - /*-----------------------------------------------------------------------*/ - //void ImportFromSourceLibrary(Handle& logicalDeviceHdl, SHShaderSourceLibrary const& sourceLib) noexcept; - - /*-----------------------------------------------------------------------*/ - /* SETTERS AND GETTERS */ - /*-----------------------------------------------------------------------*/ - Handle GetBuiltInShaderModule(std::string shaderName) const noexcept; - - void ImportAllShaderSource(Handle& logicalDeviceHdl) noexcept; - void ReflectAllShaderModules() noexcept; - }; -} - -#endif \ No newline at end of file diff --git a/SHADE_Engine/src/Graphics/Pipeline/SHVkPipeline.h b/SHADE_Engine/src/Graphics/Pipeline/SHVkPipeline.h index 7378cc48..7e313ed6 100644 --- a/SHADE_Engine/src/Graphics/Pipeline/SHVkPipeline.h +++ b/SHADE_Engine/src/Graphics/Pipeline/SHVkPipeline.h @@ -47,12 +47,13 @@ namespace SHADE /*-----------------------------------------------------------------------*/ /* CTORS AND DTORS */ /*-----------------------------------------------------------------------*/ + //! For constructing a graphics pipeline SHVkPipeline (Handle const& inLogicalDeviceHdl, Handle const& inPipelineLayout, SHVkPipelineState const* const state, Handle const& renderpassHdl, Handle subpass) noexcept; - + //! For constructing a compute pipeline SHVkPipeline(Handle const& inLogicalDeviceHdl, Handle const& inPipelineLayout) noexcept; diff --git a/SHADE_Engine/src/Graphics/Windowing/SHWindow.cpp b/SHADE_Engine/src/Graphics/Windowing/SHWindow.cpp index 44a1cb0e..e0dbc1a4 100644 --- a/SHADE_Engine/src/Graphics/Windowing/SHWindow.cpp +++ b/SHADE_Engine/src/Graphics/Windowing/SHWindow.cpp @@ -54,13 +54,14 @@ namespace SHADE if (wndData.isFullscreen) { - dwExStyle = WS_EX_APPWINDOW | WS_EX_ACCEPTFILES; + dwExStyle = WS_EX_APPWINDOW; dwStyle = WS_POPUP | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; + dwExStyle |= WS_EX_ACCEPTFILES; } else { - dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE | WS_EX_ACCEPTFILES; - + dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; + dwExStyle |= WS_EX_ACCEPTFILES; if (wndData.frameEnabled) { dwStyle = WNDSTYLE::SHWS_WINDOWED; @@ -87,7 +88,7 @@ namespace SHADE } } - //DPI_AWARENESS_CONTEXT prevDPIContext = SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); + DPI_AWARENESS_CONTEXT prevDPIContext = SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); RECT windowRect; windowRect.left = wndData.x; //or CW_USEDEFAULT ? @@ -97,13 +98,16 @@ namespace SHADE AdjustWindowRectEx(&windowRect, dwStyle, false, dwExStyle); //Create window - wndHWND = CreateWindowEx(0, (LPWSTR) wndData.name.c_str(), (LPWSTR)wndData.title.c_str(), dwStyle, 0, 0, windowRect.right - windowRect.left, windowRect.bottom - windowRect.top, parent, NULL, hInstance, NULL); - + wndHWND = CreateWindowEx(dwExStyle, (LPWSTR) wndData.name.c_str(), (LPWSTR)wndData.title.c_str(), dwStyle, 0, 0, windowRect.right - windowRect.left, windowRect.bottom - windowRect.top, parent, NULL, hInstance, NULL); + if (!wndHWND) { //DWORD err = GetLastError(); return false; } + BOOL help = ChangeWindowMessageFilter (WM_DROPFILES, MSGFLT_ADD); + help &= ChangeWindowMessageFilter (WM_COPYDATA, MSGFLT_ADD); + help &= ChangeWindowMessageFilter (0x0049, MSGFLT_ADD); if (wndData.isVisible) { @@ -256,7 +260,7 @@ namespace SHADE return wndHWND; } - const WindowData SHWindow::GetWindowData() + const WindowData SHWindow::GetWindowData() const { return wndData; } @@ -318,13 +322,13 @@ namespace SHADE case WM_CREATE: OnCreate(hwnd, reinterpret_cast(wparam)); break; + case WM_QUIT: case WM_CLOSE: - case WM_DESTROY: OnDestroy(); return 0; case WM_DROPFILES: - //OnFileDrop(reinterpret_cast(wparam)); + OnFileDrop(reinterpret_cast(wparam)); break; case WM_ENTERSIZEMOVE: case WM_EXITSIZEMOVE: @@ -386,12 +390,25 @@ namespace SHADE void SHWindow::OnDestroy() { OnClose(); + DragAcceptFiles(wndHWND, false); this->Destroy(); } - //void SHWindow::OnFileDrop(HDROP drop) - //{ - //} + void SHWindow::OnFileDrop(HDROP drop) + { + + int const numFiles = static_cast(DragQueryFile(drop, 0xFFFFFFFF, nullptr, 0)); + for(int i = 0; i < numFiles; ++i) + { + //char fileNameBuffer[MAX_PATH]; + std::wstring fileNameBuffer; + fileNameBuffer.reserve(MAX_PATH); + DragQueryFile(drop, static_cast(i), fileNameBuffer.data(), MAX_PATH); + std::string name(fileNameBuffer.begin(), fileNameBuffer.end()); + SHLOG_INFO("Dropped: {}", name) + } + DragFinish(drop); + } void SHWindow::OnSize([[maybe_unused]] UINT msg,[[maybe_unused]] UINT type, SIZE size) { diff --git a/SHADE_Engine/src/Graphics/Windowing/SHWindow.h b/SHADE_Engine/src/Graphics/Windowing/SHWindow.h index 0a180285..11308d90 100644 --- a/SHADE_Engine/src/Graphics/Windowing/SHWindow.h +++ b/SHADE_Engine/src/Graphics/Windowing/SHWindow.h @@ -2,6 +2,7 @@ #define SH_WINDOW_H #include +#include #include #include #include "SHWindowMap.h" @@ -10,7 +11,7 @@ namespace SHADE { constexpr uint16_t MAX_BUFFER = 1024; - + enum WNDSTYLE : DWORD { SHWS_WINDOWED = WS_OVERLAPPEDWINDOW, @@ -47,7 +48,7 @@ namespace SHADE //bool canFullscreen = true; - unsigned bgColor = WHITE_BRUSH; + unsigned bgColor = DKGRAY_BRUSH; //bool transparent = false; @@ -122,7 +123,7 @@ namespace SHADE HWND GetHWND(); - const WindowData GetWindowData(); + const WindowData GetWindowData() const; CALLBACKID RegisterWindowSizeCallback(WindowResizeCallbackFn); void UnregisterWindowSizeCallback(CALLBACKID const& callbackid); @@ -168,7 +169,7 @@ namespace SHADE void OnCreate(HWND hwnd, LPCREATESTRUCT create_struct); void OnClose(); void OnDestroy(); - //void OnFileDrop(HDROP drop); + void OnFileDrop(HDROP drop); void OnSize(UINT msg, UINT type, SIZE size); void OnPosChange(LPWINDOWPOS pos); void OnPaint(HDC hdc, LPPAINTSTRUCT paint); diff --git a/SHADE_Engine/src/Math/SHColour.cpp b/SHADE_Engine/src/Math/SHColour.cpp index 8aae2cb3..944c37cb 100644 --- a/SHADE_Engine/src/Math/SHColour.cpp +++ b/SHADE_Engine/src/Math/SHColour.cpp @@ -87,19 +87,19 @@ namespace SHADE /*-----------------------------------------------------------------------------------*/ SHColour::SHColour() noexcept - : SHVec4 { 0.0f, 0.0f, 0.0f, 1.0f } + : XMFLOAT4 { 0.0f, 0.0f, 0.0f, 1.0f } {} SHColour::SHColour(float r, float g, float b) noexcept - : SHVec4 { r, g, b, 1.0f } + : XMFLOAT4 { r, g, b, 1.0f } {} SHColour::SHColour(float r, float g, float b, float a) noexcept - : SHVec4 { r, g, b, a } + : XMFLOAT4 { r, g, b, a } {} SHColour::SHColour(uint8_t r, uint8_t g, uint8_t b) noexcept - : SHVec4 + : XMFLOAT4 { static_cast(r) / 255.0f, static_cast(g) / 255.0f, @@ -109,7 +109,7 @@ namespace SHADE {} SHColour::SHColour(uint8_t r, uint8_t g, uint8_t b, uint8_t a) noexcept - : SHVec4 + : XMFLOAT4 { static_cast(r) / 255.0f, static_cast(g) / 255.0f, @@ -118,12 +118,24 @@ namespace SHADE } {} - SHColour::SHColour(const DirectX::XMFLOAT3& colour) noexcept - : SHVec4 { colour.x, colour.y, colour.z, 1.0f } + SHColour::SHColour(const SHVec3& rgb) noexcept + : XMFLOAT4 { rgb.x, rgb.y, rgb.z, 1.0f } + {} + + SHColour::SHColour(const SHVec4& rgba) noexcept + : XMFLOAT4 { rgba.x, rgba.y, rgba.z, rgba.w } + {} + + SHColour::SHColour(const DirectX::XMFLOAT3& rgb) noexcept + : XMFLOAT4 { rgb.x, rgb.y, rgb.z, 1.0f } + {} + + SHColour::SHColour(const DirectX::XMFLOAT4& rgba) noexcept + : XMFLOAT4 { rgba.x, rgba.y, rgba.z, rgba.w } {} SHColour::SHColour(const DirectX::XMVECTORF32& colour) noexcept - : SHVec4 + : XMFLOAT4 { XMVectorGetX(colour), XMVectorGetY(colour), @@ -136,6 +148,86 @@ namespace SHADE /* Operator Overload Definitions */ /*-----------------------------------------------------------------------------------*/ + SHColour::operator XMVECTOR() const noexcept + { + return XMLoadFloat4(this); + } + + SHColour::operator SHVec4() const noexcept + { + return SHVec4{ *this }; + } + + SHColour& SHColour::operator+=(const SHColour& rhs) noexcept + { + return *this = *this + rhs; + } + + SHColour& SHColour::operator-=(const SHColour& rhs) noexcept + { + return *this = *this - rhs; + } + + SHColour& SHColour::operator*=(const SHColour& rhs) noexcept + { + return *this = *this * rhs; + } + + SHColour& SHColour::operator*=(float rhs) noexcept + { + return *this = *this * rhs; + } + + SHColour& SHColour::operator/=(const SHColour& rhs) noexcept + { + return *this = *this / rhs; + } + + SHColour SHColour::operator+(const SHColour& rhs) const noexcept + { + SHColour result; + + XMStoreFloat4(&result, XMVectorAdd(*this, rhs)); + return result; + } + + SHColour SHColour::operator-(const SHColour& rhs) const noexcept + { + SHColour result; + + XMStoreFloat4(&result, XMVectorSubtract(*this, rhs)); + return result; + } + + SHColour SHColour::operator-() const noexcept + { + return SHColour{ -x, -y, -z, -w }; + } + + SHColour SHColour::operator*(const SHColour& rhs) const noexcept + { + SHColour result; + + XMStoreFloat4(&result, XMVectorMultiply(*this, rhs)); + return result; + } + + SHColour SHColour::operator*(float rhs) const noexcept + { + SHColour result; + + XMStoreFloat4(&result, XMVectorScale(*this, rhs)); + return result; + } + + SHColour SHColour::operator/(const SHColour& rhs) const noexcept + { + SHColour result; + + XMStoreFloat4(&result, XMVectorDivide(*this, rhs)); + return result; + } + bool SHColour::operator==(const SHColour& rhs) const noexcept { return XMColorEqual(*this, rhs); @@ -146,6 +238,70 @@ namespace SHADE return XMColorNotEqual(*this, rhs); } + float& SHColour::operator[](int index) + { + if (index >= SIZE || index < 0) + throw std::invalid_argument("Index out of range!"); + + switch (index) + { + case 0: return x; + case 1: return y; + case 2: return z; + case 3: return w; + } + } + + float& SHColour::operator[](size_t index) + { + if (index >= SIZE || index < 0) + throw std::invalid_argument("Index out of range!"); + + switch (index) + { + case 0: return x; + case 1: return y; + case 2: return z; + case 3: return w; + } + } + + float SHColour::operator[](int index) const + { + if (index >= SIZE || index < 0) + throw std::invalid_argument("Index out of range!"); + + switch (index) + { + case 0: return x; + case 1: return y; + case 2: return z; + case 3: return w; + } + } + + float SHColour::operator[](size_t index) const + { + if (index >= SIZE || index < 0) + throw std::invalid_argument("Index out of range!"); + + switch (index) + { + case 0: return x; + case 1: return y; + case 2: return z; + case 3: return w; + } + } + + SHColour operator* (float lhs, const SHColour& rhs) noexcept + { + SHColour result; + + XMStoreFloat4(&result, XMVectorScale(rhs, lhs)); + return result; + } + /*-----------------------------------------------------------------------------------*/ /* Function Member Definitions */ /*-----------------------------------------------------------------------------------*/ diff --git a/SHADE_Engine/src/Math/SHColour.h b/SHADE_Engine/src/Math/SHColour.h index bd2bc9e7..a6adf7bb 100644 --- a/SHADE_Engine/src/Math/SHColour.h +++ b/SHADE_Engine/src/Math/SHColour.h @@ -19,12 +19,6 @@ namespace SHADE { - /*-----------------------------------------------------------------------------------*/ - /* Forward Declarations */ - /*-----------------------------------------------------------------------------------*/ - - class SHColour; - /*-----------------------------------------------------------------------------------*/ /* Type Definitions */ /*-----------------------------------------------------------------------------------*/ @@ -40,7 +34,7 @@ namespace SHADE float v = 0.0f; }; - class SH_API SHColour : private SHVec4 + class SH_API SHColour : public DirectX::XMFLOAT4 { public: /*---------------------------------------------------------------------------------*/ @@ -53,9 +47,11 @@ namespace SHADE SHColour (uint8_t r, uint8_t g, uint8_t b) noexcept; SHColour (uint8_t r, uint8_t g, uint8_t b, uint8_t a) noexcept; - SHColour (const SHVec3& colour) noexcept; - SHColour (const DirectX::XMFLOAT3& colour) noexcept; - SHColour (const DirectX::XMVECTORF32& colour) noexcept; + SHColour (const SHVec3& rgb) noexcept; + SHColour (const SHVec4& rgba) noexcept; + SHColour (const DirectX::XMFLOAT3& rgb) noexcept; + SHColour (const DirectX::XMFLOAT4& rgba) noexcept; + SHColour (const DirectX::XMVECTORF32& rgba) noexcept; SHColour (const SHColour&) = default; SHColour (SHColour&&) = default; @@ -66,11 +62,32 @@ namespace SHADE /* Operator Overloads */ /*---------------------------------------------------------------------------------*/ - SHColour& operator= (const SHColour&) = default; - SHColour& operator= (SHColour&&) = default; + SHColour& operator= (const SHColour&) = default; + SHColour& operator= (SHColour&&) = default; - bool operator== (const SHColour& rhs) const noexcept; - bool operator!= (const SHColour& rhs) const noexcept; + operator DirectX::XMVECTOR () const noexcept; + operator SHVec4 () const noexcept; + + SHColour& operator+= (const SHColour& rhs) noexcept; + SHColour& operator-= (const SHColour& rhs) noexcept; + SHColour& operator*= (const SHColour& rhs) noexcept; + SHColour& operator*= (float rhs) noexcept; + SHColour& operator/= (const SHColour& rhs) noexcept; + + [[nodiscard]] SHColour operator+ (const SHColour& rhs) const noexcept; + [[nodiscard]] SHColour operator- (const SHColour& rhs) const noexcept; + [[nodiscard]] SHColour operator- () const noexcept; + [[nodiscard]] SHColour operator* (const SHColour& rhs) const noexcept; + [[nodiscard]] SHColour operator* (float rhs) const noexcept; + [[nodiscard]] SHColour operator/ (const SHColour& rhs) const noexcept; + + [[nodiscard]] bool operator== (const SHColour& rhs) const noexcept; + [[nodiscard]] bool operator!= (const SHColour& rhs) const noexcept; + + [[nodiscard]] float& operator[] (int index); + [[nodiscard]] float& operator[] (size_t index); + [[nodiscard]] float operator[] (int index) const; + [[nodiscard]] float operator[] (size_t index) const; /*---------------------------------------------------------------------------------*/ /* Properties */ @@ -105,6 +122,8 @@ namespace SHADE /* Static Data Members */ /*---------------------------------------------------------------------------------*/ + static constexpr size_t SIZE = 4U; + static const SHColour BEIGE ; static const SHColour BLACK ; static const SHColour BLUE ; @@ -159,8 +178,9 @@ namespace SHADE static const SHColour TURQUOISE ; static const SHColour VIOLET ; static const SHColour WHITE ; - static const SHColour YELLOW; + static const SHColour YELLOW ; }; + SHColour operator* (float lhs, const SHColour& rhs) noexcept; } // namespace SHADE diff --git a/SHADE_Engine/src/Math/SHMath.h b/SHADE_Engine/src/Math/SHMath.h index 5fcea9fc..3a24d6ef 100644 --- a/SHADE_Engine/src/Math/SHMath.h +++ b/SHADE_Engine/src/Math/SHMath.h @@ -9,4 +9,6 @@ #include "SHQuaternion.h" #include "SHMatrix.h" +#include "SHColour.h" + #include "Transform/SHTransform.h" \ No newline at end of file diff --git a/SHADE_Engine/src/Math/Transform/SHTransformComponent.cpp b/SHADE_Engine/src/Math/Transform/SHTransformComponent.cpp index e56cbc8d..fa0befa3 100644 --- a/SHADE_Engine/src/Math/Transform/SHTransformComponent.cpp +++ b/SHADE_Engine/src/Math/Transform/SHTransformComponent.cpp @@ -14,6 +14,7 @@ #include "SHTransformComponent.h" // Project Headers #include "Math/SHMathHelpers.h" +#include "Reflection/SHReflectionMetadata.h" namespace SHADE { @@ -184,7 +185,7 @@ RTTR_REGISTRATION using namespace rttr; registration::class_("Transform Component") - .property("Translate" , &SHTransformComponent::GetLocalPosition , &SHTransformComponent::SetLocalPosition ) - .property("Rotate" , &SHTransformComponent::GetLocalRotation , select_overload(&SHTransformComponent::SetLocalRotation) ) - .property("Scale" , &SHTransformComponent::GetLocalScale , &SHTransformComponent::SetLocalScale ); + .property("Translate" ,&SHTransformComponent::GetLocalPosition ,&SHTransformComponent::SetLocalPosition ) (metadata(META::tooltip, "Translate")) + .property("Rotate" ,&SHTransformComponent::GetLocalRotation ,select_overload(&SHTransformComponent::SetLocalRotation)) (metadata(META::tooltip, "Rotate"), metadata(META::angleInRad, true)) + .property("Scale" ,&SHTransformComponent::GetLocalScale ,&SHTransformComponent::SetLocalScale ) (metadata(META::tooltip, "Scale")); } \ No newline at end of file diff --git a/SHADE_Engine/src/Math/Transform/SHTransformSystem.cpp b/SHADE_Engine/src/Math/Transform/SHTransformSystem.cpp index c90e4431..f000aa5b 100644 --- a/SHADE_Engine/src/Math/Transform/SHTransformSystem.cpp +++ b/SHADE_Engine/src/Math/Transform/SHTransformSystem.cpp @@ -47,16 +47,14 @@ namespace SHADE { // Get the current scene graph to traverse and update const auto& SCENE_GRAPH = SHSceneManager::GetCurrentSceneGraph(); - - // TODO(Diren): Consider how to clear dirty in pause / stop mode and update physics, but do not clear in play mode. - UpdateEntity(SCENE_GRAPH.GetRoot(), false); + UpdateEntity(SCENE_GRAPH.GetRoot(), !IsRunInEditorPause); } void SHTransformSystem::TransformPostPhysicsUpdate::Execute(double) noexcept { // Get the current scene graph to traverse and update const auto& SCENE_GRAPH = SHSceneManager::GetCurrentSceneGraph(); - UpdateEntity(SCENE_GRAPH.GetRoot(), true); + UpdateEntity(SCENE_GRAPH.GetRoot(), IsRunInEditorPause); } void SHTransformSystem::Init() diff --git a/SHADE_Engine/src/Math/Vector/SHVec4.cpp b/SHADE_Engine/src/Math/Vector/SHVec4.cpp index 88e7f5c9..943d540e 100644 --- a/SHADE_Engine/src/Math/Vector/SHVec4.cpp +++ b/SHADE_Engine/src/Math/Vector/SHVec4.cpp @@ -14,6 +14,7 @@ #include "SHVec4.h" // Project Headers #include "Math/SHMatrix.h" +#include "Math/SHColour.h" #include "Tools/SHLogger.h" using namespace DirectX; diff --git a/SHADE_Engine/src/Math/Vector/SHVec4.h b/SHADE_Engine/src/Math/Vector/SHVec4.h index db8ef860..3c509039 100644 --- a/SHADE_Engine/src/Math/Vector/SHVec4.h +++ b/SHADE_Engine/src/Math/Vector/SHVec4.h @@ -23,7 +23,9 @@ namespace SHADE /*-----------------------------------------------------------------------------------*/ /* Forward Declarations */ /*-----------------------------------------------------------------------------------*/ + class SHMatrix; + class SHColour; /*-----------------------------------------------------------------------------------*/ /* Type Definitions */ diff --git a/SHADE_Engine/src/Physics/Components/SHColliderComponent.cpp b/SHADE_Engine/src/Physics/Components/SHColliderComponent.cpp index fb999847..c7e327fa 100644 --- a/SHADE_Engine/src/Physics/Components/SHColliderComponent.cpp +++ b/SHADE_Engine/src/Physics/Components/SHColliderComponent.cpp @@ -146,4 +146,12 @@ namespace SHADE system->RemoveCollisionShape(GetEID(), index); } -} // namespace SHADE \ No newline at end of file +} // namespace SHADE + +RTTR_REGISTRATION +{ + using namespace rttr; + using namespace SHADE; + + registration::class_("Collider Component"); +} \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/Components/SHColliderComponent.h b/SHADE_Engine/src/Physics/Components/SHColliderComponent.h index af726b51..7ce272a9 100644 --- a/SHADE_Engine/src/Physics/Components/SHColliderComponent.h +++ b/SHADE_Engine/src/Physics/Components/SHColliderComponent.h @@ -100,5 +100,6 @@ namespace SHADE SHQuaternion orientation; Colliders colliders; + RTTR_ENABLE() }; } // namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.cpp b/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.cpp index c1969557..369d26a5 100644 --- a/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.cpp +++ b/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.cpp @@ -18,6 +18,7 @@ // Project Headers #include "ECS_Base/Managers/SHSystemManager.h" +#include "Math/SHMathHelpers.h" #include "Physics/SHPhysicsSystem.h" namespace SHADE @@ -28,21 +29,9 @@ namespace SHADE SHRigidBodyComponent::SHRigidBodyComponent() noexcept : type { Type::DYNAMIC } - , flags { 0 } - , dirtyFlags { 0 } , interpolate { true } , rp3dBody { nullptr } - , mass { 1.0f } - , drag { 0.01f } - , angularDrag { 0.01f } - { - // Set default flags: Gravity & Sleeping enabled - flags |= 1U << 0; - flags |= 1U << 1; - - // Set all dirty flags to true - dirtyFlags = 1023; - } + {} /*-----------------------------------------------------------------------------------*/ /* Getter Function Definitions */ @@ -50,12 +39,24 @@ namespace SHADE bool SHRigidBodyComponent::IsGravityEnabled() const noexcept { - return flags & (1U << 0); + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return false; + } + + return rp3dBody->isGravityEnabled(); } bool SHRigidBodyComponent::IsAllowedToSleep() const noexcept { - return flags & (1U << 1); + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return false; + } + + return rp3dBody->isAllowedToSleep(); } bool SHRigidBodyComponent::IsInterpolating() const noexcept @@ -70,67 +71,151 @@ namespace SHADE float SHRigidBodyComponent::GetMass() const noexcept { - return mass; + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return 0.0f; + } + + return rp3dBody->getMass(); } float SHRigidBodyComponent::GetDrag() const noexcept { - return drag; + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return 0.0f; + } + + return rp3dBody->getLinearDamping(); } float SHRigidBodyComponent::GetAngularDrag() const noexcept { - return angularDrag; + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return 0.0f; + } + + return rp3dBody->getAngularDamping(); } bool SHRigidBodyComponent::GetFreezePositionX() const noexcept { - return flags & (1U << 2); + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return false; + } + + const auto& LINEAR_CONSTRAINTS = rp3dBody->getLinearLockAxisFactor(); + return SHMath::CompareFloat(LINEAR_CONSTRAINTS.x, 0.0f); } bool SHRigidBodyComponent::GetFreezePositionY() const noexcept { - return flags & (1U << 3); + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return false; + } + + const auto& LINEAR_CONSTRAINTS = rp3dBody->getLinearLockAxisFactor(); + return SHMath::CompareFloat(LINEAR_CONSTRAINTS.y, 0.0f); } bool SHRigidBodyComponent::GetFreezePositionZ() const noexcept { - return flags & (1U << 4); + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return false; + } + + const auto& LINEAR_CONSTRAINTS = rp3dBody->getLinearLockAxisFactor(); + return SHMath::CompareFloat(LINEAR_CONSTRAINTS.z, 0.0f); } bool SHRigidBodyComponent::GetFreezeRotationX() const noexcept { - return flags & (1U << 5); + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return false; + } + + const auto& ANGULAR_CONSTRAINTS = rp3dBody->getAngularLockAxisFactor(); + return SHMath::CompareFloat(ANGULAR_CONSTRAINTS.x, 0.0f); } bool SHRigidBodyComponent::GetFreezeRotationY() const noexcept { - return flags & (1U << 6); + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return false; + } + + const auto& ANGULAR_CONSTRAINTS = rp3dBody->getAngularLockAxisFactor(); + return SHMath::CompareFloat(ANGULAR_CONSTRAINTS.y, 0.0f); } bool SHRigidBodyComponent::GetFreezeRotationZ() const noexcept { - return flags & (1U << 7); + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return false; + } + + const auto& ANGULAR_CONSTRAINTS = rp3dBody->getAngularLockAxisFactor(); + return SHMath::CompareFloat(ANGULAR_CONSTRAINTS.z, 0.0f); } - const SHVec3& SHRigidBodyComponent::GetForce() const noexcept + SHVec3 SHRigidBodyComponent::GetForce() const noexcept { - return force; + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return false; + } + + return rp3dBody->getForce(); } - const SHVec3& SHRigidBodyComponent::GetTorque() const noexcept + SHVec3 SHRigidBodyComponent::GetTorque() const noexcept { - return torque; + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return SHVec3::Zero; + } + + return rp3dBody->getTorque(); } - const SHVec3& SHRigidBodyComponent::GetLinearVelocity() const noexcept + SHVec3 SHRigidBodyComponent::GetLinearVelocity() const noexcept { - return linearVelocity; + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return SHVec3::Zero; + } + + return rp3dBody->getLinearVelocity(); } - const SHVec3& SHRigidBodyComponent::GetAngularVelocity() const noexcept + SHVec3 SHRigidBodyComponent::GetAngularVelocity() const noexcept { - return angularVelocity; + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return SHVec3::Zero; + } + + return rp3dBody->getAngularVelocity(); } const SHVec3& SHRigidBodyComponent::GetPosition() const noexcept @@ -157,8 +242,15 @@ namespace SHADE if (type == newType) return; - dirtyFlags |= 1U << 4; type = newType; + + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return; + } + + rp3dBody->setType(static_cast(type)); } void SHRigidBodyComponent::SetGravityEnabled(bool enableGravity) noexcept @@ -171,8 +263,13 @@ namespace SHADE return; } - dirtyFlags |= 1U << FLAG_POS; - enableGravity ? flags |= (1U << FLAG_POS) : flags &= ~(1U << FLAG_POS); + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return; + } + + rp3dBody->enableGravity(enableGravity); } void SHRigidBodyComponent::SetIsAllowedToSleep(bool isAllowedToSleep) noexcept @@ -185,92 +282,127 @@ namespace SHADE return; } - dirtyFlags |= 1U << 1; - isAllowedToSleep ? flags |= (1U << FLAG_POS) : flags &= ~(1U << FLAG_POS); + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return; + } + + rp3dBody->setIsAllowedToSleep(isAllowedToSleep); } void SHRigidBodyComponent::SetFreezePositionX(bool freezePositionX) noexcept { - static constexpr int FLAG_POS = 2; - if (type == Type::STATIC) { SHLOG_WARNING("Cannot set linear constraints of a static object {}", GetEID()) return; } - dirtyFlags |= 1U << 2; - freezePositionX ? flags |= (1U << FLAG_POS) : flags &= ~(1U << FLAG_POS); + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return; + } + + auto linearConstraints = rp3dBody->getLinearLockAxisFactor(); + linearConstraints.x = freezePositionX ? 0.0f : 1.0f; + rp3dBody->setLinearLockAxisFactor(linearConstraints); } void SHRigidBodyComponent::SetFreezePositionY(bool freezePositionY) noexcept { - static constexpr int FLAG_POS = 3; - if (type == Type::STATIC) { SHLOG_WARNING("Cannot set linear constraints of a static object {}", GetEID()) return; } - dirtyFlags |= 1U << 2; - freezePositionY ? flags |= (1U << FLAG_POS) : flags &= ~(1U << FLAG_POS); + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return; + } + + auto linearConstraints = rp3dBody->getLinearLockAxisFactor(); + linearConstraints.y = freezePositionY ? 0.0f : 1.0f; + rp3dBody->setLinearLockAxisFactor(linearConstraints); } void SHRigidBodyComponent::SetFreezePositionZ(bool freezePositionZ) noexcept { - static constexpr int FLAG_POS = 4; - if (type == Type::STATIC) { SHLOG_WARNING("Cannot set linear constraints of a static object {}", GetEID()) return; } - dirtyFlags |= 1U << 2; - freezePositionZ ? flags |= (1U << FLAG_POS) : flags &= ~(1U << FLAG_POS); + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return; + } + + auto linearConstraints = rp3dBody->getLinearLockAxisFactor(); + linearConstraints.z = freezePositionZ ? 0.0f : 1.0f; + rp3dBody->setLinearLockAxisFactor(linearConstraints); } void SHRigidBodyComponent::SetFreezeRotationX(bool freezeRotationX) noexcept { - static constexpr int FLAG_POS = 5; - if (type == Type::STATIC) { SHLOG_WARNING("Cannot set angular constraints of a static object {}", GetEID()) return; } - dirtyFlags |= 1U << 3; - freezeRotationX ? flags |= (1U << FLAG_POS) : flags &= ~(1U << FLAG_POS); + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return; + } + + auto angularConstraints = rp3dBody->getAngularLockAxisFactor(); + angularConstraints.x = freezeRotationX ? 0.0f : 1.0f; + rp3dBody->setAngularLockAxisFactor(angularConstraints); } void SHRigidBodyComponent::SetFreezeRotationY(bool freezeRotationY) noexcept { - static constexpr int FLAG_POS = 6; - if (type == Type::STATIC) { SHLOG_WARNING("Cannot set angular constraints of a static object {}", GetEID()) return; } - dirtyFlags |= 1U << 3; - freezeRotationY ? flags |= (1U << FLAG_POS) : flags &= ~(1U << FLAG_POS); + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return; + } + + auto angularConstraints = rp3dBody->getAngularLockAxisFactor(); + angularConstraints.y = freezeRotationY ? 0.0f : 1.0f; + rp3dBody->setAngularLockAxisFactor(angularConstraints); } void SHRigidBodyComponent::SetFreezeRotationZ(bool freezeRotationZ) noexcept { - static constexpr int FLAG_POS = 7; - if (type == Type::STATIC) { SHLOG_WARNING("Cannot set angular constraints of a static object {}", GetEID()) return; } - dirtyFlags |= 1U << 3; - freezeRotationZ ? flags |= (1U << FLAG_POS) : flags &= ~(1U << FLAG_POS); + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return; + } + + auto angularConstraints = rp3dBody->getAngularLockAxisFactor(); + angularConstraints.z = freezeRotationZ ? 0.0f : 1.0f; + rp3dBody->setAngularLockAxisFactor(angularConstraints); } void SHRigidBodyComponent::SetInterpolate(bool allowInterpolation) noexcept @@ -283,11 +415,16 @@ namespace SHADE if (type != Type::DYNAMIC) { SHLOG_WARNING("Cannot set mass of a non-dynamic object {}", GetEID()) - return; + return; } - dirtyFlags |= 1U << 5; - mass = newMass; + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return; + } + + rp3dBody->setMass(newMass); } void SHRigidBodyComponent::SetDrag(float newDrag) noexcept @@ -298,8 +435,13 @@ namespace SHADE return; } - dirtyFlags |= 1U << 6; - drag = newDrag; + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return; + } + + rp3dBody->setLinearDamping(newDrag); } void SHRigidBodyComponent::SetAngularDrag(float newAngularDrag) noexcept @@ -310,8 +452,13 @@ namespace SHADE return; } - dirtyFlags |= 1U << 7; - angularDrag = newAngularDrag; + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return; + } + + rp3dBody->setLinearDamping(newAngularDrag); } void SHRigidBodyComponent::SetLinearVelocity(const SHVec3& newLinearVelocity) noexcept @@ -322,8 +469,13 @@ namespace SHADE return; } - dirtyFlags |= 1U << 8; - linearVelocity = newLinearVelocity; + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return; + } + + rp3dBody->setLinearVelocity(newLinearVelocity); } void SHRigidBodyComponent::SetAngularVelocity(const SHVec3& newAngularVelocity) noexcept @@ -334,8 +486,13 @@ namespace SHADE return; } - dirtyFlags |= 1U << 9; - angularVelocity = newAngularVelocity; + if (rp3dBody == nullptr) + { + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) + return; + } + + rp3dBody->setAngularVelocity(newAngularVelocity); } /*-----------------------------------------------------------------------------------*/ @@ -346,7 +503,7 @@ namespace SHADE { if (rp3dBody == nullptr) { - SHLOGV_ERROR("Entity {} is missing an rp3dBody!", GetEID()) + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) return; } @@ -357,7 +514,7 @@ namespace SHADE { if (rp3dBody == nullptr) { - SHLOGV_ERROR("Entity {} is missing an rp3dBody!", GetEID()) + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) return; } @@ -368,7 +525,7 @@ namespace SHADE { if (rp3dBody == nullptr) { - SHLOGV_ERROR("Entity {} is missing an rp3dBody!", GetEID()) + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) return; } @@ -379,7 +536,7 @@ namespace SHADE { if (rp3dBody == nullptr) { - SHLOGV_ERROR("Entity {} is missing an rp3dBody!", GetEID()) + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) return; } @@ -390,7 +547,7 @@ namespace SHADE { if (rp3dBody == nullptr) { - SHLOGV_ERROR("Entity {} is missing an rp3dBody!", GetEID()) + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) return; } @@ -401,7 +558,7 @@ namespace SHADE { if (rp3dBody == nullptr) { - SHLOGV_ERROR("Entity {} is missing an rp3dBody!", GetEID()) + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) return; } @@ -412,7 +569,7 @@ namespace SHADE { if (rp3dBody == nullptr) { - SHLOGV_ERROR("Entity {} is missing an rp3dBody!", GetEID()) + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) return; } @@ -423,7 +580,7 @@ namespace SHADE { if (rp3dBody == nullptr) { - SHLOGV_ERROR("Entity {} is missing an rp3dBody!", GetEID()) + SHLOG_ERROR("Missing rp3dBody from Entity {}", GetEID()) return; } diff --git a/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.h b/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.h index 3c5dd4f9..ba7d2dd9 100644 --- a/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.h +++ b/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.h @@ -94,10 +94,10 @@ namespace SHADE [[nodiscard]] bool GetFreezeRotationY () const noexcept; [[nodiscard]] bool GetFreezeRotationZ () const noexcept; - [[nodiscard]] const SHVec3& GetForce () const noexcept; - [[nodiscard]] const SHVec3& GetTorque () const noexcept; - [[nodiscard]] const SHVec3& GetLinearVelocity () const noexcept; - [[nodiscard]] const SHVec3& GetAngularVelocity () const noexcept; + [[nodiscard]] SHVec3 GetForce () const noexcept; + [[nodiscard]] SHVec3 GetTorque () const noexcept; + [[nodiscard]] SHVec3 GetLinearVelocity () const noexcept; + [[nodiscard]] SHVec3 GetAngularVelocity () const noexcept; [[nodiscard]] const SHVec3& GetPosition () const noexcept; [[nodiscard]] const SHQuaternion& GetOrientation () const noexcept; @@ -149,28 +149,13 @@ namespace SHADE static constexpr size_t NUM_FLAGS = 8; static constexpr size_t NUM_DIRTY_FLAGS = 16; - Type type; - - // rX rY rZ pX pY pZ slp g - uint8_t flags; - // 0 0 0 0 0 0 aV lV aD d m t ag lc slp g - uint16_t dirtyFlags; - bool interpolate; + Type type; + bool interpolate; reactphysics3d::RigidBody* rp3dBody; - float mass; - float drag; - float angularDrag; - - SHVec3 force; - SHVec3 linearVelocity; - - SHVec3 torque; - SHVec3 angularVelocity; - - SHVec3 position; - SHQuaternion orientation; + SHVec3 position; + SHQuaternion orientation; RTTR_ENABLE() }; diff --git a/SHADE_Engine/src/Physics/SHCollider.cpp b/SHADE_Engine/src/Physics/SHCollider.cpp index 9488042d..6cea3dc1 100644 --- a/SHADE_Engine/src/Physics/SHCollider.cpp +++ b/SHADE_Engine/src/Physics/SHCollider.cpp @@ -17,6 +17,7 @@ #include "Math/Geometry/SHBoundingSphere.h" #include "Math/Transform/SHTransformComponent.h" #include "Math/SHMathHelpers.h" +#include "Reflection/SHReflectionMetadata.h" namespace SHADE { @@ -158,6 +159,11 @@ namespace SHADE return positionOffset; } + const SHVec3& SHCollider::GetRotationOffset() const noexcept + { + return rotationOffset; + } + SHShape* SHCollider::GetShape() noexcept { dirty = true; @@ -275,6 +281,12 @@ namespace SHADE } } + void SHCollider::SetRotationOffset(const SHVec3& rotOffset) noexcept + { + dirty = true; + rotationOffset = rotOffset; + } + /*-----------------------------------------------------------------------------------*/ /* Private Function Member Definitions */ /*-----------------------------------------------------------------------------------*/ @@ -316,5 +328,6 @@ RTTR_REGISTRATION ); registration::class_("Collider") - .property("Position Offset", &SHCollider::GetPositionOffset, &SHCollider::SetPositionOffset); + .property("Position Offset", &SHCollider::GetPositionOffset, &SHCollider::SetPositionOffset) + .property("Rotation Offset", &SHCollider::GetRotationOffset, &SHCollider::SetRotationOffset) (metadata(META::angleInRad, true)); } \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/SHCollider.h b/SHADE_Engine/src/Physics/SHCollider.h index f760ffd0..8cc233c4 100644 --- a/SHADE_Engine/src/Physics/SHCollider.h +++ b/SHADE_Engine/src/Physics/SHCollider.h @@ -80,6 +80,7 @@ namespace SHADE [[nodiscard]] const SHPhysicsMaterial& GetMaterial () const noexcept; [[nodiscard]] const SHVec3& GetPositionOffset () const noexcept; + [[nodiscard]] const SHVec3& GetRotationOffset () const noexcept; [[nodiscard]] SHShape* GetShape () noexcept; @@ -96,7 +97,8 @@ namespace SHADE void SetDensity (float density) noexcept; void SetMaterial (const SHPhysicsMaterial& newMaterial) noexcept; - void SetPositionOffset (const SHVec3& positionOffset) noexcept; + void SetPositionOffset (const SHVec3& posOffset) noexcept; + void SetRotationOffset (const SHVec3& rotOffset) noexcept; private: /*---------------------------------------------------------------------------------*/ @@ -110,6 +112,7 @@ namespace SHADE SHShape* shape; SHPhysicsMaterial material; SHVec3 positionOffset; + SHVec3 rotationOffset; /*---------------------------------------------------------------------------------*/ /* Function Members */ diff --git a/SHADE_Engine/src/Physics/SHPhysicsObject.cpp b/SHADE_Engine/src/Physics/SHPhysicsObject.cpp index 4d4d8cd7..37c1269e 100644 --- a/SHADE_Engine/src/Physics/SHPhysicsObject.cpp +++ b/SHADE_Engine/src/Physics/SHPhysicsObject.cpp @@ -130,6 +130,8 @@ namespace SHADE int SHPhysicsObject::AddCollider(SHCollider* collider) { + const rp3d::Transform OFFSETS{ collider->GetPositionOffset(), collider->GetRotationOffset() }; + switch (collider->GetType()) { case SHCollider::Type::BOX: @@ -137,7 +139,7 @@ namespace SHADE const auto* box = reinterpret_cast(collider->GetShape()); rp3d::BoxShape* newBox = factory->createBoxShape(box->GetHalfExtents()); - rp3dBody->addCollider(newBox, rp3d::Transform{ collider->GetPositionOffset(), SHQuaternion::Identity }); + rp3dBody->addCollider(newBox, OFFSETS); break; } case SHCollider::Type::SPHERE: @@ -145,7 +147,7 @@ namespace SHADE const auto* sphere = reinterpret_cast(collider->GetShape()); rp3d::SphereShape* newSphere = factory->createSphereShape(sphere->GetRadius()); - rp3dBody->addCollider(newSphere, rp3d::Transform{ collider->GetPositionOffset(), SHQuaternion::Identity }); + rp3dBody->addCollider(newSphere, OFFSETS); break; } // TODO(Diren): Add more collider shapes @@ -168,96 +170,6 @@ namespace SHADE rp3dBody->removeCollider(collider); } - void SHPhysicsObject::SyncRigidBody(SHRigidBodyComponent* rb) const noexcept - { - SHASSERT(rp3dBody != nullptr, "ReactPhysics body does not exist!") - - if (rb->dirtyFlags == 0) - return; - - auto* rigidBody = reinterpret_cast(rp3dBody); - - const uint16_t RB_FLAGS = rb->dirtyFlags; - for (size_t i = 0; i < SHRigidBodyComponent::NUM_DIRTY_FLAGS; ++i) - { - // Check if current dirty flag has been set to true - if (RB_FLAGS & 1U << i) - { - switch (i) - { - case 0: // Gravity - { - rigidBody->enableGravity(rb->IsGravityEnabled()); - break; - } - case 1: // Sleeping - { - rigidBody->setIsAllowedToSleep(rb->IsAllowedToSleep()); - break; - } - case 2: // Linear Constraints - { - const rp3d::Vector3 CONSTRAINTS - { - rb->flags & 1U << 2 ? 0.0f : 1.0f, - rb->flags & 1U << 3 ? 0.0f : 1.0f, - rb->flags & 1U << 4 ? 0.0f : 1.0f - }; - - - rigidBody->setLinearLockAxisFactor(CONSTRAINTS); - break; - } - case 3: // Angular Constraints - { - const rp3d::Vector3 CONSTRAINTS - { - rb->flags & 1U << 5 ? 0.0f : 1.0f, - rb->flags & 1U << 6 ? 0.0f : 1.0f, - rb->flags & 1U << 7 ? 0.0f : 1.0f - }; - - rigidBody->setAngularLockAxisFactor(CONSTRAINTS); - break; - } - case 4: // Type - { - rigidBody->setType(static_cast(rb->GetType())); - break; - } - case 5: // Mass - { - rigidBody->setMass(rb->GetMass()); - break; - } - case 6: // Drag - { - rigidBody->setLinearDamping(rb->GetDrag()); - break; - } - case 7: // Angular Drag - { - rigidBody->setAngularDamping(rb->GetAngularDrag()); - break; - } - case 8: // Linear Velocity - { - rigidBody->setLinearVelocity(rb->GetLinearVelocity()); - break; - } - case 9: // Angular Velocity - { - rigidBody->setAngularVelocity(rb->GetAngularVelocity()); - break; - } - default: break; - } - } - } - - rb->dirtyFlags = 0; - } - void SHPhysicsObject::SyncColliders(SHColliderComponent* c) const noexcept { int index = 0; @@ -266,9 +178,13 @@ namespace SHADE if (!collider.dirty) continue; - // Update offsets auto* rp3dCollider = rp3dBody->getCollider(index); - rp3dCollider->setLocalToBodyTransform(rp3d::Transform(collider.GetPositionOffset(), SHQuaternion::Identity)); + + // Update trigger flag + rp3dCollider->setIsTrigger(collider.IsTrigger()); + + // Update offsets + rp3dCollider->setLocalToBodyTransform(rp3d::Transform(collider.GetPositionOffset(), collider.GetRotationOffset())); switch (collider.GetType()) { @@ -293,6 +209,8 @@ namespace SHADE default: break; } + // TODO(Diren): Update Material + collider.dirty = false; ++index; } diff --git a/SHADE_Engine/src/Physics/SHPhysicsObject.h b/SHADE_Engine/src/Physics/SHPhysicsObject.h index 67e5ec64..64caacdb 100644 --- a/SHADE_Engine/src/Physics/SHPhysicsObject.h +++ b/SHADE_Engine/src/Physics/SHPhysicsObject.h @@ -72,7 +72,6 @@ namespace SHADE int AddCollider (SHCollider* collider); void RemoveCollider (int index); - void SyncRigidBody (SHRigidBodyComponent* rb) const noexcept; void SyncColliders (SHColliderComponent* c) const noexcept; private: diff --git a/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp b/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp index 44142aaf..e1acccd9 100644 --- a/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp +++ b/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp @@ -17,10 +17,10 @@ #include "ECS_Base/Managers/SHComponentManager.h" #include "ECS_Base/Managers/SHEntityManager.h" #include "ECS_Base/Managers/SHSystemManager.h" -#include "Editor/SHEditor.hpp" #include "Math/SHMathHelpers.h" -#include "Scene/SHSceneManager.h" #include "Math/Transform/SHTransformComponent.h" +#include "Scene/SHSceneManager.h" +#include "Scripting/SHScriptEngine.h" namespace SHADE { @@ -99,6 +99,16 @@ namespace SHADE return 0; } + const SHPhysicsSystem::CollisionEvents& SHPhysicsSystem::GetCollisionInfo() const noexcept + { + return collisionInfo; + } + + const SHPhysicsSystem::CollisionEvents& SHPhysicsSystem::GetTriggerInfo() const noexcept + { + return triggerInfo; + } + /*-----------------------------------------------------------------------------------*/ /* Setter Function Definitions */ /*-----------------------------------------------------------------------------------*/ @@ -187,6 +197,7 @@ namespace SHADE settings.defaultBounciness = 0.0f; world = factory.createPhysicsWorld(settings); + world->setEventListener(this); // Set up solvers world->setContactsPositionCorrectionTechnique(rp3d::ContactsPositionCorrectionTechnique::SPLIT_IMPULSES); @@ -200,6 +211,12 @@ namespace SHADE const std::shared_ptr REMOVE_COMPONENT_RECEIVER { std::make_shared>(this, &SHPhysicsSystem::RemovePhysicsComponent) }; const ReceiverPtr REMOVE_COMPONENT_RECEIVER_PTR = std::dynamic_pointer_cast(REMOVE_COMPONENT_RECEIVER); SHEventManager::SubscribeTo(SH_COMPONENT_REMOVED_EVENT, REMOVE_COMPONENT_RECEIVER_PTR); + + #ifdef SHEDITOR + const std::shared_ptr EDITOR_STOP_RECEIVER { std::make_shared>(this, &SHPhysicsSystem::ResetWorld) }; + const ReceiverPtr EDITOR_STOP_RECEIVER_PTR = std::dynamic_pointer_cast(EDITOR_STOP_RECEIVER); + SHEventManager::SubscribeTo(SH_EDITOR_ON_STOP_EVENT, EDITOR_STOP_RECEIVER_PTR); + #endif } void SHPhysicsSystem::Exit() @@ -246,7 +263,10 @@ namespace SHADE if (physicsObject.rp3dBody == nullptr) continue; - const auto* transformComponent = SHComponentManager::GetComponent_s(entityID); + const auto* transformComponent = SHComponentManager::GetComponent_s(entityID); + auto* rigidBodyComponent = SHComponentManager::GetComponent_s(entityID); + auto* colliderComponent = SHComponentManager::GetComponent_s(entityID); + if (transformComponent && transformComponent->HasChanged()) { const auto WORLD_POS = transformComponent->GetWorldPosition(); @@ -255,68 +275,119 @@ namespace SHADE physicsObject.SetPosition(WORLD_POS); physicsObject.SetOrientation(WORLD_ROT); - auto* rigidBodyComponent = SHComponentManager::GetComponent_s(entityID); + // Sync physics component transforms + if (rigidBodyComponent) { rigidBodyComponent->position = WORLD_POS; rigidBodyComponent->orientation = WORLD_ROT; - - // Clear all forces and velocities if editor is stopped - if (SHSystemManager::GetSystem()->editorState == SHEditor::State::STOP) - { - auto* rp3dRigidBody = reinterpret_cast(physicsObject.rp3dBody); - rp3dRigidBody->resetForce(); - rp3dRigidBody->resetTorque(); - rp3dRigidBody->setLinearVelocity(SHVec3::Zero); - rp3dRigidBody->setAngularVelocity(SHVec3::Zero); - } } - auto* colliderComponent = SHComponentManager::GetComponent_s(entityID); if (colliderComponent) { colliderComponent->position = WORLD_POS; colliderComponent->orientation = WORLD_ROT; } } - } - // Update bodies and colliders if component is dirty - system->SyncRigidBodyComponents(SHComponentManager::GetDense()); - system->SyncColliderComponents(SHComponentManager::GetDense()); + // Sync rigid bodies + + if (rigidBodyComponent) + { + // Sync active states + const bool COMPONENT_ACTIVE = rigidBodyComponent->isActive; + SyncActiveStates(physicsObject, COMPONENT_ACTIVE); + + if (!COMPONENT_ACTIVE) + continue; + } + + // Sync colliders + + if (colliderComponent) + { + const bool COMPONENT_ACTIVE = colliderComponent->isActive; + SyncActiveStates(physicsObject, colliderComponent->isActive); + + if (!COMPONENT_ACTIVE) + continue; + + physicsObject.SyncColliders(colliderComponent); + } + } } void SHPhysicsSystem::PhysicsFixedUpdate::Execute(double dt) noexcept { - auto* system = reinterpret_cast(GetSystem()); - fixedTimeStep = 1.0 / system->fixedDT; + auto* physicsSystem = reinterpret_cast(GetSystem()); + auto* scriptingSystem = SHSystemManager::GetSystem(); + if (scriptingSystem == nullptr) + { + SHLOGV_WARNING("Unable to invoke FixedUpdate() on scripts due to missing SHScriptEngine!"); + } + + fixedTimeStep = 1.0 / physicsSystem->fixedDT; accumulatedTime += dt; int count = 0; while (accumulatedTime > fixedTimeStep) { - system->world->update(static_cast(fixedTimeStep)); + if (scriptingSystem != nullptr) + scriptingSystem->ExecuteFixedUpdates(); + + physicsSystem->world->update(static_cast(fixedTimeStep)); accumulatedTime -= fixedTimeStep; ++count; } stats.numSteps = count; - system->worldUpdated = count > 0; + physicsSystem->worldUpdated = count > 0; - system->interpolationFactor = accumulatedTime / fixedTimeStep; + physicsSystem->interpolationFactor = accumulatedTime / fixedTimeStep; } void SHPhysicsSystem::PhysicsPostUpdate::Execute(double) noexcept { - auto* system = reinterpret_cast(GetSystem()); + auto* physicsSystem = reinterpret_cast(GetSystem()); + auto* scriptingSystem = SHSystemManager::GetSystem(); + if (scriptingSystem == nullptr) + { + SHLOGV_WARNING("Unable to invoke collision and trigger script events due to missing SHScriptEngine!"); + } // Interpolate transforms for rendering - if (system->worldUpdated) + if (physicsSystem->worldUpdated) { - system->SyncTransforms(); + physicsSystem->SyncTransforms(); - // TODO(Diren): Handle trigger messages for scripting + // Collision & Trigger messages + if (scriptingSystem != nullptr) + scriptingSystem->ExecuteCollisionFunctions(); + + physicsSystem->ClearInvalidCollisions(); + } + } + + void SHPhysicsSystem::onContact(const CallbackData& callbackData) + { + for (uint32_t i = 0; i < callbackData.getNbContactPairs(); ++i) + { + const auto CONTACT_PAIR = callbackData.getContactPair(i); + const SHCollisionEvent NEW_EVENT = GenerateCollisionEvent(CONTACT_PAIR); + + UpdateEventContainers(NEW_EVENT, collisionInfo); + } + } + + void SHPhysicsSystem::onTrigger(const rp3d::OverlapCallback::CallbackData& callbackData) + { + for (uint32_t i = 0; i < callbackData.getNbOverlappingPairs(); ++i) + { + const auto& OVERLAP_PAIR = callbackData.getOverlappingPair(i); + const SHCollisionEvent NEW_EVENT = GenerateCollisionEvent(OVERLAP_PAIR); + + UpdateEventContainers(NEW_EVENT, triggerInfo); } } @@ -353,58 +424,11 @@ namespace SHADE map.erase(entityID); } - void SHPhysicsSystem::SyncActiveStates(SHPhysicsObject* physicsObject, bool componentActive) noexcept + void SHPhysicsSystem::SyncActiveStates(SHPhysicsObject& physicsObject, bool componentActive) noexcept { - const bool RP3D_ACTIVE = physicsObject->rp3dBody->isActive(); + const bool RP3D_ACTIVE = physicsObject.rp3dBody->isActive(); if (RP3D_ACTIVE != componentActive) - physicsObject->rp3dBody->setIsActive(componentActive); - } - - - void SHPhysicsSystem::SyncRigidBodyComponents(std::vector& denseArray) noexcept - { - if (denseArray.empty()) - return; - - for (auto& comp : denseArray) - { - const EntityID ENTITY_ID = comp.GetEID(); - - // Get physicsObject - auto* physicsObject = GetPhysicsObject(ENTITY_ID); - - // TODO(Diren): Check if active in hierarchy - const bool COMPONENT_ACTIVE = comp.isActive; - SyncActiveStates(physicsObject, COMPONENT_ACTIVE); - - if (!COMPONENT_ACTIVE) - continue; - - physicsObject->SyncRigidBody(&comp); - } - } - - void SHPhysicsSystem::SyncColliderComponents(std::vector& denseArray) noexcept - { - if (denseArray.empty()) - return; - - for (auto& comp : denseArray) - { - const EntityID ENTITY_ID = comp.GetEID(); - - // Get physicsObject - auto* physicsObject = GetPhysicsObject(ENTITY_ID); - - // TODO(Diren): Check if active in hierarchy - const bool COMPONENT_ACTIVE = comp.isActive; - SyncActiveStates(physicsObject, COMPONENT_ACTIVE); - - if (!COMPONENT_ACTIVE) - continue; - - physicsObject->SyncColliders(&comp); - } + physicsObject.rp3dBody->setIsActive(componentActive); } void SHPhysicsSystem::SyncTransforms() noexcept @@ -459,15 +483,54 @@ namespace SHADE } // Convert RP3D Transform to SHADE - auto* transformComponent = SHComponentManager::GetComponent(entityID); - transformComponent->SetWorldPosition(rp3dPos); - transformComponent->SetWorldOrientation(rp3dRot); + auto* transformComponent = SHComponentManager::GetComponent_s(entityID); + + if (transformComponent != nullptr) + { + transformComponent->SetWorldPosition(rp3dPos); + transformComponent->SetWorldOrientation(rp3dRot); + } // Cache transforms physicsObject.prevTransform = CURRENT_TF; } } + void SHPhysicsSystem::UpdateEventContainers(const SHCollisionEvent& collisionEvent, CollisionEvents& container) noexcept + { + const auto IT = std::ranges::find_if(container.begin(), container.end(), [&](const SHCollisionEvent& e) + { + const bool ENTITY_MATCH = e.value[0] == collisionEvent.value[0]; + const bool COLLIDERS_MATCH = e.value[1] == collisionEvent.value[1]; + return ENTITY_MATCH && COLLIDERS_MATCH; + }); + + if (IT == container.end()) + container.emplace_back(collisionEvent); + else + IT->collisionState = collisionEvent.collisionState; + } + + void SHPhysicsSystem::ClearInvalidCollisions() noexcept + { + static const auto CLEAR = [](CollisionEvents& container) + { + for (auto eventIter = container.begin(); eventIter != container.end();) + { + const bool CLEAR_EVENT = eventIter->GetCollisionState() == SHCollisionEvent::State::EXIT + || eventIter->GetCollisionState() == SHCollisionEvent::State::INVALID; + + if (CLEAR_EVENT) + eventIter = container.erase(eventIter); + else + ++eventIter; + } + }; + + CLEAR(collisionInfo); + CLEAR(triggerInfo); + } + SHEventHandle SHPhysicsSystem::AddPhysicsComponent(SHEventPtr addComponentEvent) { const auto& EVENT_DATA = reinterpret_cast*>(addComponentEvent.get()); @@ -556,14 +619,21 @@ namespace SHADE const EntityID ENTITY_ID = EVENT_DATA->data->eid; auto* physicsObject = GetPhysicsObject(ENTITY_ID); - SHASSERT(physicsObject != nullptr, "Physics object has been lost from the world!") + auto* rigidBodyComponent = SHComponentManager::GetComponent_s(ENTITY_ID); + auto* colliderComponent = SHComponentManager::GetComponent_s(ENTITY_ID); - if (REMOVED_ID == RIGID_BODY_ID) + // Wake up all physics objects + for (auto& [entityID, object] : map) + { + if (SHComponentManager::HasComponent(entityID)) + reinterpret_cast(object.rp3dBody)->setIsSleeping(false); + } + + if (REMOVED_ID == RIGID_BODY_ID && physicsObject != nullptr) { world->destroyRigidBody(reinterpret_cast(physicsObject->rp3dBody)); - physicsObject->rp3dBody = nullptr; + physicsObject->rp3dBody = nullptr; - auto* colliderComponent = SHComponentManager::GetComponent_s(ENTITY_ID); if (colliderComponent != nullptr) { // Preserve colliders as a collision body @@ -575,16 +645,9 @@ namespace SHADE for (auto& collider : colliderComponent->colliders) physicsObject->AddCollider(&collider); } - - // Wake up all physics objects - for (auto& [entityID, object] : map) - { - if (SHComponentManager::HasComponent(entityID)) - reinterpret_cast(object.rp3dBody)->setIsSleeping(false); - } } - if (REMOVED_ID == COLLIDER_ID) + if (REMOVED_ID == COLLIDER_ID && physicsObject != nullptr) { // Remove all colliders const int NUM_COLLIDERS = static_cast(physicsObject->rp3dBody->getNbColliders()); @@ -594,13 +657,36 @@ namespace SHADE auto* collider = physicsObject->rp3dBody->getCollider(i); physicsObject->rp3dBody->removeCollider(collider); } + + // Check for a rigidbody component + if (rigidBodyComponent == nullptr) + physicsObject->rp3dBody = nullptr; } - if (physicsObject->rp3dBody == nullptr) - DestroyPhysicsObject(ENTITY_ID); + if (physicsObject != nullptr && physicsObject->rp3dBody == nullptr) + DestroyPhysicsObject(ENTITY_ID); } return EVENT_DATA->handle; } + SHEventHandle SHPhysicsSystem::ResetWorld(SHEventPtr editorStopEvent) + { + // TODO(Diren): Rebuild world based on how scene reloading is done + + for (auto& [entityID, physicsObject] : map) + { + if (SHComponentManager::HasComponent(entityID)) + { + auto* rp3dRigidBody = reinterpret_cast(physicsObject.rp3dBody); + rp3dRigidBody->resetForce(); + rp3dRigidBody->resetTorque(); + rp3dRigidBody->setLinearVelocity(SHVec3::Zero); + rp3dRigidBody->setAngularVelocity(SHVec3::Zero); + } + } + + return editorStopEvent->handle; + } + } // namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/SHPhysicsSystem.h b/SHADE_Engine/src/Physics/SHPhysicsSystem.h index a3c3bea1..1d773618 100644 --- a/SHADE_Engine/src/Physics/SHPhysicsSystem.h +++ b/SHADE_Engine/src/Physics/SHPhysicsSystem.h @@ -23,16 +23,18 @@ #include "Math/Transform/SHTransformComponent.h" #include "Scene/SHSceneGraph.h" #include "SHPhysicsObject.h" - +#include "SHPhysicsUtils.h" namespace SHADE { + /*-----------------------------------------------------------------------------------*/ /* Type Definitions */ /*-----------------------------------------------------------------------------------*/ - class SH_API SHPhysicsSystem final : public SHSystem + class SH_API SHPhysicsSystem final : public SHSystem + , public rp3d::EventListener { public: /*---------------------------------------------------------------------------------*/ @@ -47,6 +49,8 @@ namespace SHADE bool sleepingEnabled; }; + using CollisionEvents = std::vector; + /*---------------------------------------------------------------------------------*/ /* Constructors & Destructor */ /*---------------------------------------------------------------------------------*/ @@ -57,13 +61,16 @@ namespace SHADE /* Getter Functions */ /*---------------------------------------------------------------------------------*/ - [[nodiscard]] double GetFixedDT () const noexcept; + [[nodiscard]] double GetFixedDT () const noexcept; - [[nodiscard]] bool IsSleepingEnabled () const noexcept; + [[nodiscard]] bool IsSleepingEnabled () const noexcept; - [[nodiscard]] SHVec3 GetWorldGravity () const noexcept; - [[nodiscard]] uint16_t GetNumberVelocityIterations () const noexcept; - [[nodiscard]] uint16_t GetNumberPositionIterations () const noexcept; + [[nodiscard]] SHVec3 GetWorldGravity () const noexcept; + [[nodiscard]] uint16_t GetNumberVelocityIterations () const noexcept; + [[nodiscard]] uint16_t GetNumberPositionIterations () const noexcept; + + [[nodiscard]] const CollisionEvents& GetCollisionInfo () const noexcept; + [[nodiscard]] const CollisionEvents& GetTriggerInfo () const noexcept; /*---------------------------------------------------------------------------------*/ @@ -82,16 +89,14 @@ namespace SHADE /* Function Members */ /*---------------------------------------------------------------------------------*/ - void Init () override; - void Exit () override; + void Init () override; + void Exit () override; - //void AddRigidBody (EntityID entityID) noexcept; - //void AddCollider (EntityID entityID) noexcept; - //void RemoveRigidBody (EntityID entityID) noexcept; - //void RemoveCollider (EntityID entityID) noexcept; + void AddCollisionShape (EntityID entityID, SHCollider* collider); + void RemoveCollisionShape (EntityID entityID, int index); - void AddCollisionShape (EntityID entityID, SHCollider* collider); - void RemoveCollisionShape (EntityID entityID, int index); + void onContact (const rp3d::CollisionCallback::CallbackData& callbackData) override; + void onTrigger (const rp3d::OverlapCallback::CallbackData& callbackData) override; /*---------------------------------------------------------------------------------*/ /* System Routines */ @@ -156,49 +161,41 @@ namespace SHADE /* Data Members */ /*---------------------------------------------------------------------------------*/ - bool worldUpdated; + bool worldUpdated; - double interpolationFactor; - double fixedDT; - - rp3d::PhysicsWorld* world; - rp3d::PhysicsCommon factory; - - EntityObjectMap map; + double interpolationFactor; + double fixedDT; + rp3d::PhysicsWorld* world; + rp3d::PhysicsCommon factory; + EntityObjectMap map; + CollisionEvents collisionInfo; + CollisionEvents triggerInfo; /*---------------------------------------------------------------------------------*/ /* Function Members */ /*---------------------------------------------------------------------------------*/ - SHPhysicsObject* EnsurePhysicsObject (EntityID entityID) noexcept; - SHPhysicsObject* GetPhysicsObject (EntityID entityID) noexcept; - void DestroyPhysicsObject (EntityID entityID) noexcept; - void SyncActiveStates (SHPhysicsObject* physicsObject, bool componentActive) noexcept; - void SyncRigidBodyComponents (std::vector& denseArray) noexcept; - void SyncColliderComponents (std::vector& denseArray) noexcept; + SHPhysicsObject* EnsurePhysicsObject (EntityID entityID) noexcept; + SHPhysicsObject* GetPhysicsObject (EntityID entityID) noexcept; + void DestroyPhysicsObject (EntityID entityID) noexcept; + + static void SyncActiveStates (SHPhysicsObject& physicsObject, bool componentActive) noexcept; void SyncTransforms () noexcept; + static void UpdateEventContainers (const SHCollisionEvent& collisionEvent, CollisionEvents& container) noexcept; + void ClearInvalidCollisions () noexcept; + SHEventHandle AddPhysicsComponent (SHEventPtr addComponentEvent); SHEventHandle RemovePhysicsComponent (SHEventPtr removeComponentEvent); + SHEventHandle ResetWorld (SHEventPtr editorStopEvent); + + template + || std::is_same_v>> + SHCollisionEvent GenerateCollisionEvent (const RP3DCollisionPair& cp) noexcept; }; +} // namespace SHADE - /*-----------------------------------------------------------------------------------*/ - /* Event Data Definitions */ - /*-----------------------------------------------------------------------------------*/ - - struct SHPhysicsColliderAddedEvent - { - EntityID entityID; - SHCollider::Type colliderType; - int colliderIndex; - }; - - struct SHPhysicsColliderRemovedEvent - { - EntityID entityID; - int colliderIndex; - }; - -} // namespace SHADE \ No newline at end of file +#include "SHPhysicsSystem.hpp" \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/SHPhysicsSystem.hpp b/SHADE_Engine/src/Physics/SHPhysicsSystem.hpp new file mode 100644 index 00000000..957fb3aa --- /dev/null +++ b/SHADE_Engine/src/Physics/SHPhysicsSystem.hpp @@ -0,0 +1,84 @@ +/**************************************************************************************** + * \file SHPhysicsSystem.hpp + * \author Diren D Bharwani, diren.dbharwani, 390002520 + * \brief Implementation for templated functions the Physics System + * + * \copyright Copyright (C) 2022 DigiPen Institute of Technology. Reproduction or + * disclosure of this file or its contents without the prior written consent + * of DigiPen Institute of Technology is prohibited. +****************************************************************************************/ + +#pragma once + +#include + +// Primary Header +#include "SHPhysicsSystem.h" + +namespace SHADE +{ + /*-----------------------------------------------------------------------------------*/ + /* Private Function Member Definitions */ + /*-----------------------------------------------------------------------------------*/ + + template + SHCollisionEvent SHPhysicsSystem::GenerateCollisionEvent(const RP3DCollisionPair& cp) noexcept + { + static const auto MATCH_COLLIDER = [] + ( + const SHPhysicsObject& physicsObject + , const rp3d::Entity colliderID + )->uint32_t + { + for (uint32_t i = 0; i < physicsObject.rp3dBody->getNbColliders(); ++i) + { + const auto* collider = physicsObject.rp3dBody->getCollider(i); + if (collider->getEntity() == colliderID) + return i; + } + + return std::numeric_limits::max(); + }; + + SHCollisionEvent cInfo; + + // Update collision state + cInfo.collisionState = static_cast(cp.getEventType()); + + // Match body and collider for collision event + const rp3d::Entity body1 = cp.getBody1()->getEntity(); + const rp3d::Entity body2 = cp.getBody2()->getEntity(); + const rp3d::Entity collider1 = cp.getCollider1()->getEntity(); + const rp3d::Entity collider2 = cp.getCollider2()->getEntity(); + + // Find and match both ids + bool matched[2] = { false, false }; + + + for (auto& [entityID, physicsObject] : map) + { + // Match body 1 + if (matched[SHCollisionEvent::ENTITY_A] == false && physicsObject.rp3dBody->getEntity() == body1) + { + cInfo.ids[SHCollisionEvent::ENTITY_A] = entityID; + cInfo.ids[SHCollisionEvent::COLLIDER_A] = MATCH_COLLIDER(physicsObject, collider1); + + matched[SHCollisionEvent::ENTITY_A] = true; + } + + // Match body 2 + if (matched[SHCollisionEvent::ENTITY_B] == false && physicsObject.rp3dBody->getEntity() == body2) + { + cInfo.ids[SHCollisionEvent::ENTITY_B] = entityID; + cInfo.ids[SHCollisionEvent::COLLIDER_B] = MATCH_COLLIDER(physicsObject, collider2); + + matched[SHCollisionEvent::ENTITY_B] = true; + } + + if (matched[SHCollisionEvent::ENTITY_A] == true && matched[SHCollisionEvent::ENTITY_B] == true) + return cInfo; + } + + return cInfo; + } +} // namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/SHPhysicsSystemInterface.cpp b/SHADE_Engine/src/Physics/SHPhysicsSystemInterface.cpp new file mode 100644 index 00000000..4b292340 --- /dev/null +++ b/SHADE_Engine/src/Physics/SHPhysicsSystemInterface.cpp @@ -0,0 +1,65 @@ +/************************************************************************************//*! +\file SHPhysicsSystemInterface.cpp +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Oct 31, 2022 +\brief Contains the definitions of the functions of the static + SHPhysicsSystemInterface 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. +*//*************************************************************************************/ +// Precompiled Headers +#include "SHpch.h" +// Primary Header +#include "SHPhysicsSystemInterface.h" +// Project Includes +#include "ECS_Base/Managers/SHSystemManager.h" +#include "Physics/SHPhysicsSystem.h" +#include "Physics/SHPhysicsUtils.h" + +namespace SHADE +{ + /*-----------------------------------------------------------------------------------*/ + /* Static Usage Functions */ + /*-----------------------------------------------------------------------------------*/ + const std::vector& SHPhysicsSystemInterface::GetCollisionInfo() noexcept + { + static std::vector emptyVec; + + auto phySystem = SHSystemManager::GetSystem(); + if (phySystem) + { + return phySystem->GetCollisionInfo(); + } + + SHLOG_WARNING("[SHPhysicsSystemInterface] Failed to get collision events. Empty vector returned instead."); + return emptyVec; + } + const std::vector& SHPhysicsSystemInterface::GetTriggerInfo() noexcept + { + static std::vector emptyVec; + + auto phySystem = SHSystemManager::GetSystem(); + if (phySystem) + { + return phySystem->GetTriggerInfo(); + } + + SHLOG_WARNING("[SHPhysicsSystemInterface] Failed to get trigger events. Empty vector returned instead."); + return emptyVec; + } + + double SHPhysicsSystemInterface::GetFixedDT() noexcept + { + auto phySystem = SHSystemManager::GetSystem(); + if (phySystem) + { + return phySystem->GetFixedDT(); + } + + SHLOG_WARNING("[SHPhysicsSystemInterface] Failed to get fixed delta time. 0.0 returned instead."); + return 0.0; + } +} diff --git a/SHADE_Engine/src/Physics/SHPhysicsSystemInterface.h b/SHADE_Engine/src/Physics/SHPhysicsSystemInterface.h new file mode 100644 index 00000000..da6a0433 --- /dev/null +++ b/SHADE_Engine/src/Physics/SHPhysicsSystemInterface.h @@ -0,0 +1,46 @@ +/************************************************************************************//*! +\file SHPhysicsSystemInterface.h +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Oct 31, 2022 +\brief Contains the definition of the SHGraphicsSystemInterface static 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. +*//*************************************************************************************/ +#pragma once + +// STL Includes +#include + +namespace SHADE +{ + /*-----------------------------------------------------------------------------------*/ + /* Forward Declarations */ + /*-----------------------------------------------------------------------------------*/ + class SHCollisionEvent; + + /*-----------------------------------------------------------------------------------*/ + /* Type Definitions */ + /*-----------------------------------------------------------------------------------*/ + /// + /// Static class that wraps up certain functions in the SHPhysicsSystem so that + /// accessing it from SHADE_Managed would not cause issues due to C++20 features. + /// + class SH_API SHPhysicsSystemInterface final + { + public: + /*---------------------------------------------------------------------------------*/ + /* Constructor */ + /*---------------------------------------------------------------------------------*/ + SHPhysicsSystemInterface() = delete; + + /*---------------------------------------------------------------------------------*/ + /* Static Usage Functions */ + /*---------------------------------------------------------------------------------*/ + [[nodiscard]] static const std::vector& GetCollisionInfo() noexcept; + [[nodiscard]] static const std::vector& GetTriggerInfo() noexcept; + [[nodiscard]] static double GetFixedDT() noexcept; + }; +} diff --git a/SHADE_Engine/src/Physics/SHPhysicsUtils.cpp b/SHADE_Engine/src/Physics/SHPhysicsUtils.cpp new file mode 100644 index 00000000..8d5bc956 --- /dev/null +++ b/SHADE_Engine/src/Physics/SHPhysicsUtils.cpp @@ -0,0 +1,93 @@ +/**************************************************************************************** + * \file SHPhysicsUtils.cpp + * \author Diren D Bharwani, diren.dbharwani, 390002520 + * \brief Implementation for some Physics Utilities + * + * \copyright Copyright (C) 2022 DigiPen Institute of Technology. Reproduction or + * disclosure of this file or its contents without the prior written consent + * of DigiPen Institute of Technology is prohibited. +****************************************************************************************/ + +#include + +// Primary Header +#include "SHPhysicsUtils.h" + +namespace SHADE +{ + /*-----------------------------------------------------------------------------------*/ + /* Constructors & Destructor Definitions */ + /*-----------------------------------------------------------------------------------*/ + + SHCollisionEvent::SHCollisionEvent() noexcept + : collisionState { State::INVALID } + { + ids[ENTITY_A] = MAX_EID; + ids[ENTITY_B] = MAX_EID; + ids[COLLIDER_A] = std::numeric_limits::max(); + ids[COLLIDER_B] = std::numeric_limits::max(); + } + + SHCollisionEvent::SHCollisionEvent(EntityID entityA, EntityID entityB) noexcept + : collisionState { State::INVALID } + { + ids[ENTITY_A] = entityA; + ids[ENTITY_B] = entityB; + ids[COLLIDER_A] = std::numeric_limits::max(); + ids[COLLIDER_B] = std::numeric_limits::max(); + } + + /*-----------------------------------------------------------------------------------*/ + /* Operator Overload Definitions */ + /*-----------------------------------------------------------------------------------*/ + + bool SHCollisionEvent::operator==(const SHCollisionEvent& rhs) const noexcept + { + return value[0] == rhs.value[0] && value[1] == rhs.value[1]; + } + + bool SHCollisionEvent::operator!=(const SHCollisionEvent& rhs) const noexcept + { + return value[0] != rhs.value[0] || value[1] != rhs.value[1]; + } + + /*-----------------------------------------------------------------------------------*/ + /* Getter Function Definitions */ + /*-----------------------------------------------------------------------------------*/ + + EntityID SHCollisionEvent::GetEntityA() const noexcept + { + return ids[ENTITY_A]; + } + + EntityID SHCollisionEvent::GetEntityB() const noexcept + { + return ids[ENTITY_B]; + } + + const SHRigidBodyComponent* SHCollisionEvent::GetRigidBodyA() const noexcept + { + return SHComponentManager::GetComponent_s(ids[ENTITY_A]); + } + + const SHRigidBodyComponent* SHCollisionEvent::GetRigidBodyB() const noexcept + { + return SHComponentManager::GetComponent_s(ids[ENTITY_B]); + } + + const SHCollider* SHCollisionEvent::GetColliderA() const noexcept + { + return &SHComponentManager::GetComponent(ids[ENTITY_A])->GetCollider(ids[COLLIDER_A]); + } + + const SHCollider* SHCollisionEvent::GetColliderB() const noexcept + { + return &SHComponentManager::GetComponent(ids[ENTITY_B])->GetCollider(ids[COLLIDER_B]); + } + + SHCollisionEvent::State SHCollisionEvent::GetCollisionState() const noexcept + { + return collisionState; + } + +} // namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/SHPhysicsUtils.h b/SHADE_Engine/src/Physics/SHPhysicsUtils.h new file mode 100644 index 00000000..57f9c6fc --- /dev/null +++ b/SHADE_Engine/src/Physics/SHPhysicsUtils.h @@ -0,0 +1,116 @@ +/**************************************************************************************** + * \file SHPhysicsUtils.h + * \author Diren D Bharwani, diren.dbharwani, 390002520 + * \brief Interface for some Physics Utilities + * + * \copyright Copyright (C) 2022 DigiPen Institute of Technology. Reproduction or + * disclosure of this file or its contents without the prior written consent + * of DigiPen Institute of Technology is prohibited. +****************************************************************************************/ + +#pragma once + +// Project Headers +#include "Components/SHColliderComponent.h" +#include "Components/SHRigidBodyComponent.h" + + +namespace SHADE +{ + /*-----------------------------------------------------------------------------------*/ + /* Type Definitions */ + /*-----------------------------------------------------------------------------------*/ + + struct SHPhysicsColliderAddedEvent + { + EntityID entityID; + SHCollider::Type colliderType; + int colliderIndex; + }; + + struct SHPhysicsColliderRemovedEvent + { + EntityID entityID; + int colliderIndex; + }; + + class SH_API SHCollisionEvent + { + private: + /*---------------------------------------------------------------------------------*/ + /* Friends */ + /*---------------------------------------------------------------------------------*/ + + friend class SHPhysicsSystem; + + public: + /*---------------------------------------------------------------------------------*/ + /* Type Definitions */ + /*---------------------------------------------------------------------------------*/ + + enum class State + { + ENTER + , STAY + , EXIT + + , TOTAL + , INVALID = -1 + }; + + /*---------------------------------------------------------------------------------*/ + /* Constructors & Destructor */ + /*---------------------------------------------------------------------------------*/ + + SHCollisionEvent () noexcept; + SHCollisionEvent (EntityID entityA, EntityID entityB) noexcept; + + + SHCollisionEvent (const SHCollisionEvent& rhs) = default; + SHCollisionEvent (SHCollisionEvent&& rhs) = default; + ~SHCollisionEvent () = default; + + /*---------------------------------------------------------------------------------*/ + /* Operator Overloads */ + /*---------------------------------------------------------------------------------*/ + + bool operator== (const SHCollisionEvent& rhs) const noexcept; + bool operator!= (const SHCollisionEvent& rhs) const noexcept; + + SHCollisionEvent& operator= (const SHCollisionEvent& rhs) = default; + SHCollisionEvent& operator= (SHCollisionEvent&& rhs) = default; + + /*---------------------------------------------------------------------------------*/ + /* Getter Functions */ + /*---------------------------------------------------------------------------------*/ + + [[nodiscard]] EntityID GetEntityA () const noexcept; + [[nodiscard]] EntityID GetEntityB () const noexcept; + [[nodiscard]] const SHRigidBodyComponent* GetRigidBodyA () const noexcept; + [[nodiscard]] const SHRigidBodyComponent* GetRigidBodyB () const noexcept; + [[nodiscard]] const SHCollider* GetColliderA () const noexcept; + [[nodiscard]] const SHCollider* GetColliderB () const noexcept; + [[nodiscard]] State GetCollisionState () const noexcept; + + private: + + static constexpr uint32_t ENTITY_A = 0; + static constexpr uint32_t ENTITY_B = 1; + static constexpr uint32_t COLLIDER_A = 2; + static constexpr uint32_t COLLIDER_B = 3; + + /*---------------------------------------------------------------------------------*/ + /* Data Members */ + /*---------------------------------------------------------------------------------*/ + + union + { + uint64_t value[2]; // EntityValue, ColliderIndexValue + uint32_t ids [4]; // EntityA, EntityB, ColliderIndexA, ColliderIndexB + }; + + State collisionState; + }; + + +} // namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/Reflection/SHReflectionMetadata.h b/SHADE_Engine/src/Reflection/SHReflectionMetadata.h index 0cc6d8a5..b4dc009c 100644 --- a/SHADE_Engine/src/Reflection/SHReflectionMetadata.h +++ b/SHADE_Engine/src/Reflection/SHReflectionMetadata.h @@ -7,5 +7,6 @@ namespace SHADE constexpr const char* min = "MIN"; constexpr const char* max = "MAX"; constexpr const char* tooltip = "tooltip"; + constexpr const char* angleInRad = "angleInRad"; } } diff --git a/SHADE_Engine/src/Resource/SHResourceManager.cpp b/SHADE_Engine/src/Resource/SHResourceManager.cpp index 156c31c7..dad9fd9f 100644 --- a/SHADE_Engine/src/Resource/SHResourceManager.cpp +++ b/SHADE_Engine/src/Resource/SHResourceManager.cpp @@ -21,9 +21,11 @@ namespace SHADE /*-----------------------------------------------------------------------------------*/ SHResourceHub SHResourceManager::resourceHub; std::unordered_map>> SHResourceManager::handlesMap; - std::unordered_map SHResourceManager::assetIdMap; + std::unordered_map SHResourceManager::assetIdMap; std::unordered_map> SHResourceManager::typedFreeFuncMap; std::vector SHResourceManager::loadedAssetData; + bool SHResourceManager::textureChanged = false; + bool SHResourceManager::meshChanged = false; /*-----------------------------------------------------------------------------------*/ /* Function Definitions */ @@ -63,8 +65,17 @@ namespace SHADE SHGraphicsSystem* gfxSystem = SHSystemManager::GetSystem(); if (gfxSystem == nullptr) throw std::runtime_error("[SHResourceManager] Attempted to load graphics resource without a SHGraphicsSystem installed."); - gfxSystem->BuildMeshBuffers(); - gfxSystem->BuildTextures(); + + if (meshChanged) + { + gfxSystem->BuildMeshBuffers(); + meshChanged = false; + } + if (textureChanged) + { + gfxSystem->BuildTextures(); + textureChanged = false; + } // Free CPU Resources for (auto assetId : loadedAssetData) diff --git a/SHADE_Engine/src/Resource/SHResourceManager.h b/SHADE_Engine/src/Resource/SHResourceManager.h index 84f93b10..e5e303e1 100644 --- a/SHADE_Engine/src/Resource/SHResourceManager.h +++ b/SHADE_Engine/src/Resource/SHResourceManager.h @@ -17,9 +17,27 @@ of DigiPen Institute of Technology is prohibited. #include "SH_API.h" #include "SHResourceLibrary.h" #include "Assets/SHAssetMacros.h" +#include "Assets/Asset Types/SHMeshAsset.h" +#include "Assets/Asset Types/SHTextureAsset.h" +#include "Assets/Asset Types/SHShaderAsset.h" +#include "Graphics/Shaders/SHVkShaderModule.h" +#include "Graphics/MiddleEnd/Textures/SHTextureLibrary.h" +#include "Graphics/MiddleEnd/Interface/SHMeshLibrary.h" +#include "Graphics/MiddleEnd/Interface/SHMaterial.h" +#include "Assets/Asset Types/SHMaterialAsset.h" namespace SHADE { + /// + /// Template structs that maps a resource to their loaded asset representation type. + /// + template + struct SHResourceLoader { using AssetType = void; }; + template<> struct SHResourceLoader { using AssetType = SHMeshAsset; }; + template<> struct SHResourceLoader { using AssetType = SHTextureAsset; }; + template<> struct SHResourceLoader { using AssetType = SHShaderAsset; }; + template<> struct SHResourceLoader { using AssetType = SHMaterialAsset; }; + /// /// Static class responsible for loading and caching runtime resources from their /// serialised Asset IDs. @@ -61,7 +79,7 @@ namespace SHADE /// Handle to the resource to unload. static void Unload(AssetID assetId); /// - /// Needs to be called to finalise all changes to loads. + /// Needs to be called to finalise all changes to loads, unless at runtime. /// static void FinaliseChanges(); @@ -111,6 +129,9 @@ namespace SHADE static std::unordered_map> typedFreeFuncMap; // Pointers to temp CPU resources static std::vector loadedAssetData; + // Dirty Flags + static bool meshChanged; + static bool textureChanged; /*---------------------------------------------------------------------------------*/ /* Helper Functions */ @@ -124,6 +145,14 @@ namespace SHADE /// Reference to the AssetHandleMap of the specified type. template static std::pair getAssetHandleMap(); + /// + /// + /// + /// + /// + /// + template + static Handle load(AssetID assetId, const typename SHResourceLoader::AssetType& assetData); }; } diff --git a/SHADE_Engine/src/Resource/SHResourceManager.hpp b/SHADE_Engine/src/Resource/SHResourceManager.hpp index 072adaa2..1623d70a 100644 --- a/SHADE_Engine/src/Resource/SHResourceManager.hpp +++ b/SHADE_Engine/src/Resource/SHResourceManager.hpp @@ -3,7 +3,7 @@ \author Tng Kah Wei, kahwei.tng, 390009620 \par email: kahwei.tng\@digipen.edu \date Oct 21, 2022 -\brief Contains the definition of the function templates of the +\brief Contains the definition of the function templates of the SHResourceManager static class. Copyright (C) 2022 DigiPen Institute of Technology. @@ -13,12 +13,17 @@ of DigiPen Institute of Technology is prohibited. #pragma once // Primary Include #include "SHResourceManager.h" +// External Dependencies +#include // Project Includes #include "Assets/SHAssetManager.h" #include "Assets/Asset Types/SHAssetIncludes.h" #include "Graphics/MiddleEnd/Interface/SHGraphicsSystem.h" #include "ECS_Base/Managers/SHSystemManager.h" #include "Tools/SHLog.h" +#include "Graphics/Shaders/SHVkShaderModule.h" +#include "Graphics/Devices/SHVkLogicalDevice.h" +#include "Graphics/MiddleEnd/Materials/SHMaterialSpec.h" namespace SHADE { @@ -40,67 +45,19 @@ namespace SHADE return Handle(typedHandleMap.get()[assetId]); /* Otherwise, we need to load it! */ - // Meshes - if constexpr (std::is_same_v) + // Load Asset Data + const auto* assetData = SHAssetManager::GetData::AssetType>(assetId); + if (assetData == nullptr) { - // Get system - SHGraphicsSystem* gfxSystem = SHSystemManager::GetSystem(); - if (gfxSystem == nullptr) - throw std::runtime_error("[SHResourceManager] Attempted to load graphics resource without a SHGraphicsSystem installed."); - - // Load - const SHMeshAsset* assetData = SHAssetManager::GetData(assetId); - if (assetData == nullptr) - { - SHLog::Warning("[SHResourceManager] Attempted to load an asset with an invalid Asset ID."); - return {}; - } - loadedAssetData.emplace_back(assetId); - - Handle meshHandle = gfxSystem->AddMesh - ( - assetData->vertexPosition.size(), - assetData->vertexPosition.data(), - assetData->texCoords.data(), - assetData->vertexTangent.data(), - assetData->vertexNormal.data(), - assetData->indices.size(), - assetData->indices.data() - ); - Handle genericHandle = Handle(meshHandle); - typedHandleMap.get().emplace(assetId, genericHandle); - typedAssetIdMap.get().emplace(genericHandle, assetId); - return meshHandle; + SHLog::Warning("[SHResourceManager] Attempted to load an asset with an invalid Asset ID."); + return {}; } - // Textures - else if constexpr (std::is_same_v) - { - // Get system - SHGraphicsSystem* gfxSystem = SHSystemManager::GetSystem(); - if (gfxSystem == nullptr) - throw std::runtime_error("[SHResourceManager] Attempted to load graphics resource without a SHGraphicsSystem installed."); - // Load - const SHTextureAsset* assetData = SHAssetManager::GetData(assetId); - if (assetData == nullptr) - { - SHLog::Warning("[SHResourceManager] Attempted to load an asset with an invalid Asset ID."); - return {}; - } - loadedAssetData.emplace_back(assetId); - - Handle texHandle = gfxSystem->AddTexture - ( - assetData->numBytes, - assetData->pixelData, - assetData->width, - assetData->height, - assetData->format, - assetData->mipOffsets - ); - typedHandleMap.get().emplace(assetId, Handle(texHandle)); - return texHandle; - } + auto handle = load(assetId, *assetData); + Handle genericHandle = Handle(handle); + typedHandleMap.get().emplace(assetId, genericHandle); + typedAssetIdMap.get().emplace(genericHandle, assetId); + return handle; } template @@ -152,7 +109,7 @@ namespace SHADE template std::pair SHResourceManager::getAssetHandleMap() { - const std::type_index TYPE = typeid(ResourceType); + const std::type_index TYPE = typeid(ResourceType); if (!handlesMap.contains(TYPE)) { @@ -160,7 +117,7 @@ namespace SHADE assetIdMap.emplace(TYPE, HandleAssetMap{}); typedFreeFuncMap.emplace ( - TYPE, + TYPE, [TYPE](AssetID assetId) { static_cast>(SHResourceManager::handlesMap[TYPE][assetId]).Free(); @@ -169,4 +126,131 @@ namespace SHADE } return std::make_pair(std::ref(handlesMap[TYPE]), std::ref(assetIdMap[TYPE])); } + + template + Handle SHResourceManager::load(AssetID assetId, const typename SHResourceLoader::AssetType& assetData) + { + // Get system + SHGraphicsSystem* gfxSystem = SHSystemManager::GetSystem(); + if (gfxSystem == nullptr) + throw std::runtime_error("[SHResourceManager] Attempted to load graphics resource without a SHGraphicsSystem installed."); + + // Meshes + if constexpr (std::is_same_v) + { + loadedAssetData.emplace_back(assetId); + meshChanged = true; + + return gfxSystem->AddMesh + ( + assetData.vertexPosition.size(), + assetData.vertexPosition.data(), + assetData.texCoords.data(), + assetData.vertexTangent.data(), + assetData.vertexNormal.data(), + assetData.indices.size(), + assetData.indices.data() + ); + } + // Textures + else if constexpr (std::is_same_v) + { + loadedAssetData.emplace_back(assetId); + textureChanged = true; + + return gfxSystem->AddTexture + ( + assetData.numBytes, + assetData.pixelData, + assetData.width, + assetData.height, + assetData.format, + assetData.mipOffsets + ); + } + // Shaders + else if constexpr (std::is_same_v) + { + auto shader = gfxSystem->GetDevice()->CreateShaderModule + ( + assetData.spirvBinary, + "main", + static_cast(assetData.shaderType), + assetData.name + ); + shader->Reflect(); + return shader; + } + // Materials + else if constexpr (std::is_same_v) + { + // Get the data we need to construct + SHMaterialSpec matSpec = YAML::Node(assetData.data).as(); + + // Load shaders + auto vertexShader = SHResourceManager::LoadOrGet(matSpec.vertexShader); + auto fragShader = SHResourceManager::LoadOrGet(matSpec.fragShader); + + // Ensure that both shaders are present + if (!(vertexShader && fragShader)) + { + SHLOG_ERROR("[SHResourceManager] Failed to load material as shaders failed to be loaded."); + return {}; + } + + // Grab subpass from worldRenderer + auto renderPass = gfxSystem->GetPrimaryRenderpass(); + if (!renderPass) + { + SHLOG_ERROR("[SHResourceManager] Failed to load material as RenderPass could not be found."); + return {}; + } + auto subPass = renderPass->GetSubpass(matSpec.subpassName); + if (!subPass) + { + SHLOG_ERROR("[SHResourceManager] Failed to load material as SubPass could not be found."); + return {}; + } + + // Create material + auto matHandle = gfxSystem->AddMaterial(vertexShader, fragShader, subPass); + + // Set properties for the material + Handle pipelineProperties = matHandle->GetShaderBlockInterface(); + for (int i = 0; i < static_cast(pipelineProperties->GetVariableCount()); ++i) + { + const std::string& PROP_NAME = pipelineProperties->GetVariableName(i); + const auto& PROP_NODE = matSpec.properties; + if (PROP_NODE) + { + const std::string& VAR_NAME = pipelineProperties->GetVariableName(i); + const SHShaderBlockInterface::Variable* VARIABLE = pipelineProperties->GetVariable(i); + switch (VARIABLE->type) + { + case SHADE::SHShaderBlockInterface::Variable::Type::FLOAT: + matHandle->SetProperty(VARIABLE->offset, PROP_NODE.as()); + break; + case SHADE::SHShaderBlockInterface::Variable::Type::INT: + matHandle->SetProperty(VARIABLE->offset, PROP_NODE.as()); + break; + case SHADE::SHShaderBlockInterface::Variable::Type::VECTOR2: + matHandle->SetProperty(VARIABLE->offset, PROP_NODE.as()); + break; + case SHADE::SHShaderBlockInterface::Variable::Type::VECTOR3: + matHandle->SetProperty(VARIABLE->offset, PROP_NODE.as()); + break; + case SHADE::SHShaderBlockInterface::Variable::Type::VECTOR4: + matHandle->SetProperty(VARIABLE->offset, PROP_NODE.as()); + break; + case SHADE::SHShaderBlockInterface::Variable::Type::OTHER: + default: + continue; + break; + } + } + } + + return matHandle; + } + } } diff --git a/SHADE_Engine/src/Scripting/SHScriptEngine.cpp b/SHADE_Engine/src/Scripting/SHScriptEngine.cpp index 21ce7b82..4a73342e 100644 --- a/SHADE_Engine/src/Scripting/SHScriptEngine.cpp +++ b/SHADE_Engine/src/Scripting/SHScriptEngine.cpp @@ -80,7 +80,10 @@ namespace SHADE { csScriptsExecuteFixedUpdate(); } - + void SHScriptEngine::ExecuteCollisionFunctions() + { + csScriptsExecutePhysicsEvents(); + } void SHScriptEngine::Exit() { // Do not allow deinitialization if not initialised @@ -377,6 +380,12 @@ namespace SHADE DEFAULT_CSHARP_NAMESPACE + ".ScriptStore", "ExecuteLateUpdate" ); + csScriptsExecutePhysicsEvents = dotNet.GetFunctionPtr + ( + DEFAULT_CSHARP_LIB_NAME, + DEFAULT_CSHARP_NAMESPACE + ".ScriptStore", + "ExecuteCollisionFunctions" + ); csScriptsFrameCleanUp = dotNet.GetFunctionPtr ( DEFAULT_CSHARP_LIB_NAME, diff --git a/SHADE_Engine/src/Scripting/SHScriptEngine.h b/SHADE_Engine/src/Scripting/SHScriptEngine.h index c38e3618..9ddd617a 100644 --- a/SHADE_Engine/src/Scripting/SHScriptEngine.h +++ b/SHADE_Engine/src/Scripting/SHScriptEngine.h @@ -98,6 +98,11 @@ namespace SHADE /// void ExecuteFixedUpdates(); /// + /// Executes the OnCollision*()s and OnTrigger*()s of the Scripts that are attached + /// to Entities. + /// + void ExecuteCollisionFunctions(); + /// /// Shuts down the DotNetRuntime. /// void Exit() override; @@ -245,6 +250,7 @@ namespace SHADE CsFuncPtr csScriptsExecuteFixedUpdate = nullptr; CsFuncPtr csScriptsExecuteUpdate = nullptr; CsFuncPtr csScriptsExecuteLateUpdate = nullptr; + CsFuncPtr csScriptsExecutePhysicsEvents = nullptr; CsFuncPtr csScriptsFrameCleanUp = nullptr; CsScriptManipFuncPtr csScriptsAdd = nullptr; CsScriptBasicFuncPtr csScriptsRemoveAll = nullptr; diff --git a/SHADE_Engine/src/Scripting/SHScriptEngineRoutines.cpp b/SHADE_Engine/src/Scripting/SHScriptEngineRoutines.cpp index 5467fc56..a2981c06 100644 --- a/SHADE_Engine/src/Scripting/SHScriptEngineRoutines.cpp +++ b/SHADE_Engine/src/Scripting/SHScriptEngineRoutines.cpp @@ -54,7 +54,7 @@ namespace SHADE /* System Routine Functions - FrameCleanUpRoutine */ /*-----------------------------------------------------------------------------------*/ SHScriptEngine::FrameCleanUpRoutine::FrameCleanUpRoutine() - : SHSystemRoutine("Script Engine Frame Clean Up", false) + : SHSystemRoutine("Script Engine Frame Clean Up", true) {} void SHScriptEngine::FrameCleanUpRoutine::Execute(double) noexcept { diff --git a/SHADE_Engine/src/Serialization/Prefab/SHPrefabManager.cpp b/SHADE_Engine/src/Serialization/Prefab/SHPrefabManager.cpp new file mode 100644 index 00000000..8ab098b8 --- /dev/null +++ b/SHADE_Engine/src/Serialization/Prefab/SHPrefabManager.cpp @@ -0,0 +1,56 @@ +#include "SHpch.h" +#include "SHPrefabManager.h" + +namespace SHADE +{ + SHPrefabManager::PrefabMap SHPrefabManager::prefabMap{}; + + void SHPrefabManager::AddPrefab(AssetID const& prefabAssetID) noexcept + { + prefabMap.insert({ prefabAssetID, {} }); + } + + void SHPrefabManager::RemovePrefab(AssetID const& prefabAssetID) noexcept + { + prefabMap.erase(prefabAssetID); + } + + void SHPrefabManager::ClearPrefab(AssetID const& prefabAssetID) noexcept + { + if (prefabMap.contains(prefabAssetID)) + { + prefabMap[prefabAssetID].clear(); + } + } + + void SHPrefabManager::UpdateAllPrefabEntities(AssetID const& prefabAssetID) noexcept + { + //Loop through all entities and deserialize new data + } + + void SHPrefabManager::AddEntity(AssetID const& prefabAssetID, EntityID const& eid) noexcept + { + if (prefabMap.contains(prefabAssetID)) + { + prefabMap[prefabAssetID].insert(eid); + } + } + + void SHPrefabManager::RemoveEntity(AssetID const& prefabAssetID, EntityID const& eid) noexcept + { + if (prefabMap.contains(prefabAssetID)) + { + prefabMap[prefabAssetID].erase(eid); + } + } + + void SHPrefabManager::Clear() noexcept + { + prefabMap.clear(); + } + + bool SHPrefabManager::Empty() noexcept + { + return prefabMap.empty(); + } +} diff --git a/SHADE_Engine/src/Serialization/Prefab/SHPrefabManager.h b/SHADE_Engine/src/Serialization/Prefab/SHPrefabManager.h new file mode 100644 index 00000000..37c317ed --- /dev/null +++ b/SHADE_Engine/src/Serialization/Prefab/SHPrefabManager.h @@ -0,0 +1,28 @@ +#pragma once + +#include "Assets/SHAssetMacros.h" +#include "ECS_Base/SHECSMacros.h" +#include +#include + + +namespace SHADE +{ + class SHPrefabManager + { + public: + using PrefabMap = std::unordered_map>; + + static void AddPrefab(AssetID const& prefabAssetID) noexcept; + static void RemovePrefab(AssetID const& prefabAssetID) noexcept; + static void ClearPrefab(AssetID const& prefabAssetID) noexcept; + static void UpdateAllPrefabEntities(AssetID const& prefabAssetID) noexcept; + static void AddEntity(AssetID const& prefabAssetID, EntityID const& eid) noexcept; + static void RemoveEntity(AssetID const& prefabAssetID, EntityID const& eid) noexcept; + static void Clear() noexcept; + static bool Empty() noexcept; + + private: + static PrefabMap prefabMap; + }; +} diff --git a/SHADE_Engine/src/Serialization/SHSerialization.cpp b/SHADE_Engine/src/Serialization/SHSerialization.cpp index f8913d8d..03498951 100644 --- a/SHADE_Engine/src/Serialization/SHSerialization.cpp +++ b/SHADE_Engine/src/Serialization/SHSerialization.cpp @@ -10,6 +10,7 @@ #include "Assets/SHAssetManager.h" #include +#include "Camera/SHCameraComponent.h" #include "Graphics/MiddleEnd/Interface/SHRenderable.h" #include "Math/Transform/SHTransformComponent.h" #include "Physics/Components/SHRigidBodyComponent.h" @@ -58,7 +59,7 @@ namespace SHADE static EntityID DeserializeEntity(YAML::iterator& it, YAML::Node const& node, std::vector& createdEntities, EntityID parentEID = MAX_EID) { EntityID eid = MAX_EID; - if(!node) + if (!node) return eid; if (node[EIDNode]) eid = node[EIDNode].as(); @@ -71,13 +72,13 @@ namespace SHADE createdEntities.push_back(eid); if (node[NumberOfChildrenNode]) { - if(const int numOfChildren = node[NumberOfChildrenNode].as(); numOfChildren > 0) + if (const int numOfChildren = node[NumberOfChildrenNode].as(); numOfChildren > 0) { ++it; for (int i = 0; i < numOfChildren; ++i) { DeserializeEntity(it, (*it), createdEntities, eid); - if((i + 1) < numOfChildren) + if ((i + 1) < numOfChildren) ++it; } } @@ -85,7 +86,9 @@ namespace SHADE // Deserialise scripts if (node[ScriptsNode]) - SHSystemManager::GetSystem()->DeserialiseScripts(eid, node[ScriptsNode]); + SHSystemManager::GetSystem()->DeserialiseScripts(eid, node[ScriptsNode]); + + return eid; } void SHSerialization::DeserializeSceneFromFile(std::filesystem::path const& path) @@ -120,10 +123,10 @@ namespace SHADE { DeserializeEntity(it, (*it), createdEntities); } - if(createdEntities.empty()) + if (createdEntities.empty()) { SHLOG_ERROR("Failed to create entities from deserializaiton") - return; + return; } //Initialize Entity auto entityVecIt = createdEntities.begin(); @@ -137,7 +140,7 @@ namespace SHADE { out << SerializeEntityToNode(entityNode); auto const& children = entityNode->GetChildren(); - for(auto const& child : children) + for (auto const& child : children) { EmitEntity(child, out); } @@ -162,17 +165,36 @@ namespace SHADE { } + template, bool> = true> + static void AddComponentToComponentNode(YAML::Node& componentsNode, EntityID const& eid) + { + if (const ComponentType* component = SHComponentManager::GetComponent_s(eid)) + { + componentsNode[rttr::type::get().get_name().data()] = SHSerializationHelper::SerializeComponentToNode(component); + } + } + + template, bool> = true> + static void AddConvComponentToComponentNode(YAML::Node& componentsNode, EntityID const& eid) + { + if (ComponentType* component = SHComponentManager::GetComponent_s(eid)) + { + componentsNode[rttr::type::get().get_name().data()] = YAML::convert::encode(*component); + } + } + + YAML::Node SHSerialization::SerializeEntityToNode(SHSceneNode* sceneNode) { YAML::Node node; auto eid = sceneNode->GetEntityID(); auto entity = SHEntityManager::GetEntityByID(eid); - if (!sceneNode || !entity) + if (!sceneNode && !entity) { node = YAML::Null; return node; } - node.SetStyle(YAML::EmitterStyle::Block); + node.SetStyle(YAML::EmitterStyle::Block); node[EIDNode] = eid; node[EntityNameNode] = entity->name; node[IsActiveNode] = sceneNode->IsActive(); @@ -181,22 +203,13 @@ namespace SHADE YAML::Node components; - if (const auto transform = SHComponentManager::GetComponent_s(eid)) - { - components[rttr::type::get().get_name().data()] = SHSerializationHelper::SerializeComponentToNode(transform); - } - if (const auto renderable = SHComponentManager::GetComponent_s(eid)) - { - components[rttr::type::get().get_name().data()] = *renderable; - } - if (const auto rigidbody = SHComponentManager::GetComponent_s(eid)) - { - components[rttr::type::get().get_name().data()] = SHSerializationHelper::SerializeComponentToNode(rigidbody); - } - if(const auto light = SHComponentManager::GetComponent_s(eid)) - { - components[rttr::type::get().get_name().data()] = SHSerializationHelper::SerializeComponentToNode(light); - } + AddComponentToComponentNode(components, eid); + AddComponentToComponentNode(components, eid); + AddConvComponentToComponentNode(components, eid); + AddComponentToComponentNode(components, eid); + AddComponentToComponentNode(components, eid); + AddConvComponentToComponentNode(components, eid); + node[ComponentsNode] = components; YAML::Node scripts; @@ -208,22 +221,22 @@ namespace SHADE EntityID SHSerialization::DeserializeEntitiesFromString(std::string const& data, EntityID const& parentEID) noexcept { - if(data.empty()) + if (data.empty()) return MAX_EID; YAML::Node entities = YAML::Load(data.c_str()); - EntityID eid{MAX_EID}; + EntityID eid{ MAX_EID }; std::vector createdEntities; - for(auto it = entities.begin(); it != entities.end(); ++it) + for (auto it = entities.begin(); it != entities.end(); ++it) { eid = DeserializeEntity(it, *it, createdEntities, parentEID); } - if(createdEntities.empty()) + if (createdEntities.empty()) { SHLOG_ERROR("Failed to create entities from deserializaiton") - return MAX_EID; + return MAX_EID; } auto entityVecIt = createdEntities.begin(); - for(auto it = entities.begin(); it != entities.end(); ++it) + for (auto it = entities.begin(); it != entities.end(); ++it) { InitializeEntity(*it, *entityVecIt++); } @@ -231,33 +244,22 @@ namespace SHADE } template, bool> = true> - std::optional GetComponentID(YAML::Node const& componentNode) + static void AddComponentID(std::vector& idList, YAML::Node const& componentNode) { if (componentNode[rttr::type::get().get_name().data()]) - return { SHFamilyID::GetID() }; - else - return std::nullopt; + idList.push_back(SHFamilyID::GetID()); } std::vector SHSerialization::GetComponentIDList(YAML::Node const& componentsNode) { std::vector componentIDList; - - auto id = GetComponentID(componentsNode); - if (id.has_value()) - componentIDList.push_back(id.value()); - - id = GetComponentID(componentsNode); - if (id.has_value()) - componentIDList.push_back(id.value()); - - id = GetComponentID(componentsNode); - if (id.has_value()) - componentIDList.push_back(id.value()); - - id = GetComponentID(componentsNode); - if(id.has_value()) - componentIDList.push_back(id.value()); + + AddComponentID(componentIDList, componentsNode); + AddComponentID(componentIDList, componentsNode); + AddComponentID(componentIDList, componentsNode); + AddComponentID(componentIDList, componentsNode); + AddComponentID(componentIDList, componentsNode); + AddComponentID(componentIDList, componentsNode); return componentIDList; } @@ -268,7 +270,10 @@ namespace SHADE if (!componentsNode) return; SHSerializationHelper::InitializeComponentFromNode(componentsNode, eid); + SHSerializationHelper::InitializeComponentFromNode(componentsNode, eid); + SHSerializationHelper::InitializeComponentFromNode(componentsNode, eid); SHSerializationHelper::ConvertNodeToComponent(componentsNode, eid); + SHSerializationHelper::ConvertNodeToComponent(componentsNode, eid); SHSerializationHelper::InitializeComponentFromNode(componentsNode, eid); } } diff --git a/SHADE_Engine/src/Serialization/SHSerializationHelper.hpp b/SHADE_Engine/src/Serialization/SHSerializationHelper.hpp index 047232a0..2179d1cf 100644 --- a/SHADE_Engine/src/Serialization/SHSerializationHelper.hpp +++ b/SHADE_Engine/src/Serialization/SHSerializationHelper.hpp @@ -12,11 +12,240 @@ #include "Resource/SHResourceManager.h" #include "Graphics/MiddleEnd/Interface/SHRenderable.h" #include "Graphics/MiddleEnd/Interface/SHMaterial.h" +#include "Graphics/MiddleEnd/Interface/SHMaterialInstance.h" #include "SHSerializationTools.h" +#include "Physics/Components/SHColliderComponent.h" +#include "Graphics/MiddleEnd/Materials/SHMaterialSpec.h" +#include "Tools/SHLog.h" namespace YAML { using namespace SHADE; + + template<> + struct convert + { + static constexpr const char* x = "x"; + static constexpr const char* y = "y"; + static constexpr const char* z = "z"; + static constexpr const char* w = "w"; + + static Node encode(SHVec4 const& rhs) + { + Node node; + node.SetStyle(EmitterStyle::Flow); + node[x] = rhs.x; + node[y] = rhs.y; + node[z] = rhs.z; + node[w] = rhs.w; + return node; + } + static bool decode(Node const& node, SHVec4& rhs) + { + if (node[x].IsDefined()) + rhs.x = node[x].as(); + if (node[y].IsDefined()) + rhs.y = node[y].as(); + if (node[z].IsDefined()) + rhs.z = node[z].as(); + if (node[w].IsDefined()) + rhs.w = node[w].as(); + return true; + } + }; + + template<> + struct convert + { + static constexpr const char* x = "x"; + static constexpr const char* y = "y"; + static constexpr const char* z = "z"; + + static Node encode(SHVec3 const& rhs) + { + Node node; + node.SetStyle(EmitterStyle::Flow); + node[x] = rhs.x; + node[y] = rhs.y; + node[z] = rhs.z; + return node; + } + static bool decode(Node const& node, SHVec3& rhs) + { + if (node[x].IsDefined()) + rhs.x = node[x].as(); + if (node[y].IsDefined()) + rhs.y = node[y].as(); + if (node[z].IsDefined()) + rhs.z = node[z].as(); + return true; + } + }; + + template<> + struct convert + { + static constexpr const char* x = "x"; + static constexpr const char* y = "y"; + + static Node encode(SHVec2 const& rhs) + { + Node node; + node.SetStyle(EmitterStyle::Flow); + node[x] = rhs.x; + node[y] = rhs.y; + return node; + } + static bool decode(Node const& node, SHVec2& rhs) + { + if (node[x].IsDefined()) + rhs.x = node[x].as(); + if (node[y].IsDefined()) + rhs.y = node[y].as(); + return true; + } + }; + + template<> + struct convert + { + static constexpr const char* IsTrigger = "Is Trigger"; + + static constexpr const char* Type = "Type"; + static constexpr const char* HalfExtents = "Half Extents"; + static constexpr const char* Radius = "Radius"; + + static constexpr const char* Friction = "Friction"; + static constexpr const char* Bounciness = "Bounciness"; + static constexpr const char* Density = "Density"; + static constexpr const char* PositionOffset = "Position Offset"; + + static Node encode(SHCollider& rhs) + { + Node node; + + node[IsTrigger] = rhs.IsTrigger(); + + rttr::type const shapeRttrType = rttr::type::get(); + rttr::enumeration const enumAlign = shapeRttrType.get_enumeration(); + SHCollider::Type colliderType = rhs.GetType(); + + node[Type] = enumAlign.value_to_name(colliderType).data(); + + switch (colliderType) + { + case SHCollider::Type::BOX: + { + auto const bb = reinterpret_cast(rhs.GetShape()); + node[HalfExtents] = bb->GetHalfExtents(); + } + break; + case SHCollider::Type::SPHERE: + { + auto const bs = reinterpret_cast(rhs.GetShape()); + node[Radius] = bs->GetRadius(); + } + break; + case SHCollider::Type::CAPSULE: break; + default:; + } + + node[Friction] = rhs.GetFriction(); + node[Bounciness] = rhs.GetBounciness(); + node[Density] = rhs.GetDensity(); + node[PositionOffset] = rhs.GetPositionOffset(); + + return node; + } + static bool decode(Node const& node, SHCollider& rhs) + { + if (node[IsTrigger].IsDefined()) + rhs.SetIsTrigger(node[IsTrigger].as()); + if (!node[Type].IsDefined()) + return false; + rttr::type const shapeRttrType = rttr::type::get(); + rttr::enumeration const enumAlign = shapeRttrType.get_enumeration(); + bool ok; + const SHCollider::Type colliderType = enumAlign.name_to_value(node[Type].as()).convert(&ok); + if (!ok) + return false; + switch (colliderType) + { + case SHCollider::Type::BOX: + { + if(node[HalfExtents].IsDefined()) + rhs.SetBoundingBox(node[HalfExtents].as()); + } + break; + case SHCollider::Type::SPHERE: + { + if(node[Radius].IsDefined()) + rhs.SetBoundingSphere(node[Radius].as()); + } + break; + case SHCollider::Type::CAPSULE: break; + default:; + } + if (node[Friction].IsDefined()) + rhs.SetFriction(node[Friction].as()); + if (node[Bounciness].IsDefined()) + rhs.SetBounciness(rhs.GetBounciness()); + if (node[Density].IsDefined()) + rhs.SetDensity(node[Density].as()); + if (node[PositionOffset].IsDefined()) + rhs.SetPositionOffset(node[PositionOffset].as()); + + return true; + } + }; + + template<> + struct convert + { + static constexpr const char* Colliders = "Colliders"; + static Node encode(SHColliderComponent& rhs) + { + Node node, collidersNode; + auto const& colliders = rhs.GetColliders(); + int const numColliders = static_cast(colliders.size()); + for (int i = 0; i < numColliders; ++i) + { + auto& collider = rhs.GetCollider(i); + Node colliderNode = convert::encode(collider); + if (colliderNode.IsDefined()) + collidersNode[i] = colliderNode; + } + node[Colliders] = collidersNode; + return node; + } + static bool decode(Node const& node, SHColliderComponent& rhs) + { + if (node[Colliders].IsDefined()) + { + int numColliders{}; + for (auto const& colliderNode : node[Colliders]) + { + rttr::type const shapeRttrType = rttr::type::get(); + rttr::enumeration const enumAlign = shapeRttrType.get_enumeration(); + bool ok = false; + const SHCollider::Type colliderType = enumAlign.name_to_value(colliderNode[convert::Type].as()).convert(&ok); + if (!ok) + return false; + + switch (colliderType) + { + case SHCollider::Type::BOX: rhs.AddBoundingBox(); break; + case SHCollider::Type::SPHERE: rhs.AddBoundingSphere(); break; + case SHCollider::Type::CAPSULE: break; + default:; + } + YAML::convert::decode(colliderNode, rhs.GetCollider(numColliders++)); + } + } + return true; + } + }; + template<> struct convert { @@ -46,13 +275,13 @@ namespace YAML propNode = rhs.GetProperty(VARIABLE->offset); break; case SHADE::SHShaderBlockInterface::Variable::Type::VECTOR2: - propNode = SHSerializationTools::ValToYAML(rhs.GetProperty(VARIABLE->offset)); + propNode = rhs.GetProperty(VARIABLE->offset); break; case SHADE::SHShaderBlockInterface::Variable::Type::VECTOR3: - propNode = SHSerializationTools::ValToYAML(rhs.GetProperty(VARIABLE->offset)); + propNode = rhs.GetProperty(VARIABLE->offset); break; case SHADE::SHShaderBlockInterface::Variable::Type::VECTOR4: - propNode = SHSerializationTools::ValToYAML(rhs.GetProperty(VARIABLE->offset)); + propNode = rhs.GetProperty(VARIABLE->offset); break; case SHADE::SHShaderBlockInterface::Variable::Type::OTHER: default: @@ -77,104 +306,45 @@ namespace YAML // Write Material YAML::Node node; - node[VERT_SHADER_YAML_TAG.data()] = 0; // SHResourceManager::GetAssetID(vertexShader).value_or(0); - node[FRAG_SHADER_YAML_TAG.data()] = 0; // SHResourceManager::GetAssetID(fragShader).value_or(0); - node[SUBPASS_YAML_TAG.data()] = rhs.GetPipeline()->GetPipelineState().GetSubpass()->GetName(); + node[VERT_SHADER_YAML_TAG.data()] = SHResourceManager::GetAssetID(vertexShader).value_or(0); + node[FRAG_SHADER_YAML_TAG.data()] = SHResourceManager::GetAssetID(fragShader).value_or(0); + node[SUBPASS_YAML_TAG.data()] = rhs.GetPipeline()->GetPipelineState().GetSubpass()->GetName(); node[PROPS_YAML_TAG.data()] = propertiesNode; return node; } - static bool decode(YAML::Node const& node, SHMaterial& rhs) - { - /* - // Retrieve Shader Asset IDs - AssetID vertShaderId = 0; - AssetID fragShaderId = 0; - if (node[VERT_SHADER_YAML_TAG.data()]) - vertShaderId = node[VERT_SHADER_YAML_TAG.data()].as(); - if (node[FRAG_SHADER_YAML_TAG.data()]) - fragShaderId = node[FRAG_SHADER_YAML_TAG.data()].as(); + }; - // Ensure that both shaders are present - if (vertShaderId == 0 || fragShaderId == 0) - return false; // No pipeline + template<> + struct convert + { + static constexpr std::string_view VERT_SHADER_YAML_TAG = "VertexShader"; + static constexpr std::string_view FRAG_SHADER_YAML_TAG = "FragmentShader"; + static constexpr std::string_view SUBPASS_YAML_TAG = "SubPass"; + static constexpr std::string_view PROPS_YAML_TAG = "Properties"; - // Get Shader Modules - Handle vertexShader, fragShader; - vertexShader = SHResourceManager::LoadOrGet(vertShaderId); - fragShader = SHResourceManager::LoadOrGet(fragShaderId); + static bool decode(YAML::Node const& node, SHMaterialSpec& rhs) + { + // Retrieve Shader Asset IDs + if (!node[VERT_SHADER_YAML_TAG.data()]) + return false; + rhs.vertexShader = node[VERT_SHADER_YAML_TAG.data()].as(); + if (!node[FRAG_SHADER_YAML_TAG.data()]) + return false; + rhs.fragShader = node[FRAG_SHADER_YAML_TAG.data()].as(); - // Get Pipeline Library - if (node[SUBPASS_YAML_TAG.data()]) - { - auto gfxSystem = SHSystemManager::GetSystem(); - if (!gfxSystem) - return false; + // Retrieve Subpass + if (!node[SUBPASS_YAML_TAG.data()]) + return false; + rhs.subpassName = node[SUBPASS_YAML_TAG.data()].as(); - // Grab subpass from worldRenderer - auto renderPass = gfxSystem->GetPrimaryRenderpass(); - if (!renderPass) - return false; - auto subPass = renderPass->GetSubpass(node[SUBPASS_YAML_TAG.data()].as()); - if (!subPass) - return false; + // Retrieve + if (!node[PROPS_YAML_TAG.data()]) + return false; + rhs.properties = node[PROPS_YAML_TAG.data()]; - // Set Pipeline - rhs.SetPipeline(renderPass->GetOrCreatePipeline - ( - std::make_pair(vertexShader, fragShader), - subPass - )); - } - */ - - // TODO: Load Proper Material! - // Set default material - auto gfxSystem = SHSystemManager::GetSystem(); - if (!gfxSystem) - return false; - rhs.SetPipeline(gfxSystem->GetDefaultMaterial()->GetPipeline()); - - if (node[PROPS_YAML_TAG.data()]) - { - // Loop through all properties - Handle pipelineProperties = rhs.GetShaderBlockInterface(); - const YAML::Node& PROPS_NODE = node[PROPS_YAML_TAG.data()]; - for (int i = 0; i < static_cast(pipelineProperties->GetVariableCount()); ++i) - { - const std::string& PROP_NAME = pipelineProperties->GetVariableName(i); - const auto& PROP_NODE = PROPS_NODE[PROP_NAME.data()]; - if (PROP_NODE) - { - const std::string& VAR_NAME = pipelineProperties->GetVariableName(i); - const SHShaderBlockInterface::Variable* VARIABLE = pipelineProperties->GetVariable(i); - switch (VARIABLE->type) - { - case SHADE::SHShaderBlockInterface::Variable::Type::FLOAT: - rhs.SetProperty(VARIABLE->offset, PROP_NODE.as()); - break; - case SHADE::SHShaderBlockInterface::Variable::Type::INT: - rhs.SetProperty(VARIABLE->offset, PROP_NODE.as()); - break; - case SHADE::SHShaderBlockInterface::Variable::Type::VECTOR2: - rhs.SetProperty(VARIABLE->offset, SHSerializationTools::YAMLToVec2(PROP_NODE)); - break; - case SHADE::SHShaderBlockInterface::Variable::Type::VECTOR3: - rhs.SetProperty(VARIABLE->offset, SHSerializationTools::YAMLToVec3(PROP_NODE)); - break; - case SHADE::SHShaderBlockInterface::Variable::Type::VECTOR4: - rhs.SetProperty(VARIABLE->offset, SHSerializationTools::YAMLToVec4(PROP_NODE)); - break; - case SHADE::SHShaderBlockInterface::Variable::Type::OTHER: - default: - continue; - break; - } - } - } - } - return true; - } + return true; + } }; template<> @@ -187,69 +357,62 @@ namespace YAML { YAML::Node node; node[MESH_YAML_TAG.data()] = SHResourceManager::GetAssetID(rhs.GetMesh()).value_or(0); - node[MAT_YAML_TAG.data()] = 0; // TODO: Asset ID + node[MAT_YAML_TAG.data()] = SHResourceManager::GetAssetID(rhs.GetMaterial()->GetBaseMaterial()).value_or(0); return node; } static bool decode(YAML::Node const& node, SHRenderable& rhs) { - if (node[MESH_YAML_TAG.data()]) + if (node[MESH_YAML_TAG.data()].IsDefined()) { rhs.SetMesh(SHResourceManager::LoadOrGet(node[MESH_YAML_TAG.data()].as())); } - if (node[MAT_YAML_TAG.data()]) + if (node[MAT_YAML_TAG.data()].IsDefined()) { - // TODO: Convert Asset ID To Material HAndle // Temporarily, use default material auto gfxSystem = SHSystemManager::GetSystem(); if (!gfxSystem) return false; - rhs.SetMaterial(gfxSystem->AddOrGetBaseMaterialInstance(gfxSystem->GetDefaultMaterial())); + Handle baseMat = SHResourceManager::LoadOrGet(node[MAT_YAML_TAG.data()].as()); + if (!baseMat) + { + baseMat = gfxSystem->GetDefaultMaterial(); + SHLog::Warning("[SHSerializationHelper] Unable to load specified material. Falling back to default material."); + } + rhs.SetMaterial(gfxSystem->AddOrGetBaseMaterialInstance(baseMat)); } return true; } }; } - namespace SHADE { struct SHSerializationHelper { - template , bool> = true> - static std::string SerializeComponentToString(ComponentType* component) - { - return std::string(); - } - template , bool> = true> - static void SerializeComponentToFile(ComponentType* component, std::filesystem::path const& path) - { - } static YAML::Node RTTRToNode(const rttr::variant& var) { YAML::Node node; auto varType = var.get_type(); + if (varType.is_sequential_container()) + { + for (auto const& elem : var.create_sequential_view()) + { + node.push_back(RTTRToNode(elem)); + } + } if (varType == rttr::type::get()) { - node.SetStyle(YAML::EmitterStyle::Flow); - node["X"] = var.convert().x; - node["Y"] = var.convert().y; - node["Z"] = var.convert().z; - node["W"] = var.convert().w; + node = YAML::convert::encode(var.convert()); } else if (varType == rttr::type::get()) { - node.SetStyle(YAML::EmitterStyle::Flow); - node["X"] = var.convert().x; - node["Y"] = var.convert().y; - node["Z"] = var.convert().z; + node = YAML::convert::encode(var.convert()); } else if (varType == rttr::type::get()) { - node.SetStyle(YAML::EmitterStyle::Flow); - node["X"] = var.convert().x; - node["Y"] = var.convert().y; + node = YAML::convert::encode(var.convert()); } else if (varType.is_arithmetic()) { @@ -300,7 +463,7 @@ namespace SHADE else { auto properties = var.get_type().get_properties(); - for (auto property : properties) + for (auto const& property : properties) { node[property.get_name().data()] = RTTRToNode(property.get_value(var)); } @@ -308,6 +471,17 @@ namespace SHADE return node; } + template , bool> = true> + static std::string SerializeComponentToString(ComponentType* component) + { + return std::string(); + } + + template , bool> = true> + static void SerializeComponentToFile(ComponentType* component, std::filesystem::path const& path) + { + } + template , bool> = true> static YAML::Node SerializeComponentToNode(ComponentType* component) { @@ -327,15 +501,18 @@ namespace SHADE auto propType = prop.get_type(); if (propType == rttr::type::get()) { - prop.set_value(component, SHSerializationTools::YAMLToVec4(propertyNode)); + SHVec4 vec = propertyNode.as(); + prop.set_value(component, vec); } else if (propType == rttr::type::get()) { - prop.set_value(component, SHSerializationTools::YAMLToVec3(propertyNode)); + SHVec3 vec = propertyNode.as(); + prop.set_value(component, vec); } else if (propType == rttr::type::get()) { - prop.set_value(component, SHSerializationTools::YAMLToVec2(propertyNode)); + SHVec2 vec = propertyNode.as(); + prop.set_value(component, vec); } else if (propType.is_arithmetic()) { @@ -371,9 +548,10 @@ namespace SHADE else { auto properties = propType.get_properties(); - for (auto property : properties) + for (auto const& property : properties) { - InitializeProperty(component, property, propertyNode[property.get_name().data()]); + if(propertyNode[property.get_name().data()].IsDefined()) + InitializeProperty(component, property, propertyNode[property.get_name().data()]); } } } @@ -381,7 +559,7 @@ namespace SHADE template , bool> = true> static void InitializeComponentFromNode(YAML::Node const& componentsNode, EntityID const& eid) { - auto component = SHComponentManager::GetComponent_s(eid); + ComponentType* component = SHComponentManager::GetComponent_s(eid); if (componentsNode.IsNull() && !component) return; auto rttrType = rttr::type::get(); @@ -406,7 +584,7 @@ namespace SHADE return; auto rttrType = rttr::type::get(); auto componentNode = componentsNode[rttrType.get_name().data()]; - if (componentsNode.IsNull()) + if (!componentNode.IsDefined()) return; YAML::convert::decode(componentNode, *component); } diff --git a/SHADE_Engine/src/Tools/Dialog/SHWinDialog.cpp b/SHADE_Engine/src/Tools/Dialog/SHWinDialog.cpp new file mode 100644 index 00000000..bd13801a --- /dev/null +++ b/SHADE_Engine/src/Tools/Dialog/SHWinDialog.cpp @@ -0,0 +1,71 @@ +#include "SHpch.h" +#include "SHWinDialog.h" +#include +#include + +namespace SHADE +{ + void SHWinDialog::DisplayMessageBox(MessageBoxType const& messageBoxType, std::string const& title, std::string const& text) + { + if(messageBoxType == MessageBoxType::MB_MAX) + return; + + UINT flags = MB_APPLMODAL | MB_SETFOREGROUND | MB_OK; + flags |= static_cast(messageBoxType); + + const std::wstring wTitle(title.begin(), title.end()); + const std::wstring wText(text.begin(), text.end()); + + MessageBox(GetDesktopWindow(), wText.data(), wTitle.data(), flags); + } + + std::vector SHWinDialog::DisplayOpenDialog(OpenSaveConfig const& openSaveConfig) + { + const HWND hwnd = GetDesktopWindow(); + HRESULT hResult = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); + if(SUCCEEDED(hResult)) + { + IFileOpenDialog* pFileOpen; + + //Create Dialog object + hResult = CoCreateInstance(CLSID_FileOpenDialog, nullptr, CLSCTX_ALL, IID_IFileOpenDialog, reinterpret_cast(pFileOpen)); + + if(SUCCEEDED(hResult)) + { + //Show the open dialog box + hResult = pFileOpen->Show(hwnd); + + //Get file name from the dialoh box + if(SUCCEEDED(hResult)) + { + if(openSaveConfig.openMultiple) + { + IShellItemArray* pItemArray; + hResult = pFileOpen->GetResults(&pItemArray); + if(SUCCEEDED(hResult)) + { + + } + } + else + { + IShellItem* pItem; + hResult = pFileOpen->GetResult(&pItem); + if(SUCCEEDED(hResult)) + { + PWSTR pszFilePath; + hResult = pItem->GetDisplayName(SIGDN_FILESYSPATH, &pszFilePath); + } + } + + } + } + } + return {}; + } + + std::vector SHWinDialog::DisplaySaveAsDialog(OpenSaveConfig const& openSaveConfig) + { + return{}; + } +} diff --git a/SHADE_Engine/src/Tools/Dialog/SHWinDialog.h b/SHADE_Engine/src/Tools/Dialog/SHWinDialog.h new file mode 100644 index 00000000..02fe07b9 --- /dev/null +++ b/SHADE_Engine/src/Tools/Dialog/SHWinDialog.h @@ -0,0 +1,36 @@ +#pragma once +#include +#include + +namespace SHADE +{ + //https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-messagebox + enum class MessageBoxType + { + MB_ERROR = 0x00000010L, + MB_QUESTION = 0x00000020L, + MB_WARNING = 0x00000030L, + MB_INFO = 0x00000040L, + MB_MAX = 0 + }; + + struct OpenSaveConfig + { + using Extension = std::string; + using Extensions = std::vector; + using FileTypeDesc = std::pair; + using FilterList = std::vector; + + std::string title = "Open"; + bool openFolders = false; + bool openMultiple = false; + FilterList filterList{}; + }; + + struct SHWinDialog + { + static void DisplayMessageBox(MessageBoxType const& messageBoxType, std::string const& title, std::string const& text); + static std::vector DisplayOpenDialog(OpenSaveConfig const& openSaveConfig); + static std::vector DisplaySaveAsDialog(OpenSaveConfig const& openSaveConfig); + }; +} diff --git a/SHADE_Engine/src/Tools/SHDebugDraw.cpp b/SHADE_Engine/src/Tools/SHDebugDraw.cpp new file mode 100644 index 00000000..a5b86c42 --- /dev/null +++ b/SHADE_Engine/src/Tools/SHDebugDraw.cpp @@ -0,0 +1,73 @@ +/************************************************************************************//*! +\file SHDebugDrawSystem.cpp +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Nov 2, 2022 +\brief Contains the definition of functions of the SHDebugDrawSystem 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. +*//*************************************************************************************/ +// Precompiled Header +#include "SHpch.h" +// Primary Include +#include "SHDebugDraw.h" +// Project Includes +#include "Math/Vector/SHVec4.h" +#include "Math/SHColour.h" +#include "Graphics/MiddleEnd/Interface/SHDebugDrawSystem.h" +#include "ECS_Base/Managers/SHSystemManager.h" + +namespace SHADE +{ + /*-----------------------------------------------------------------------------------*/ + /* Static Member Definitions */ + /*-----------------------------------------------------------------------------------*/ + SHDebugDrawSystem* SHDebugDraw::dbgDrawSys = nullptr; + + /*-----------------------------------------------------------------------------------*/ + /* Lifecycle Functions */ + /*-----------------------------------------------------------------------------------*/ + void SHDebugDraw::Init(SHDebugDrawSystem* sys) + { + dbgDrawSys = sys; + if (dbgDrawSys == nullptr) + { + SHLOG_ERROR("[SHDebugDraw] Invalid SHDebugDrawSystem provided for initialization!"); + } + } + + /*-----------------------------------------------------------------------------------*/ + /* Draw Functions */ + /*-----------------------------------------------------------------------------------*/ + void SHDebugDraw::Line(const SHVec4& color, const SHVec3& startPt, const SHVec3& endPt) + { + dbgDrawSys->DrawLine(color, startPt, endPt); + } + + void SHDebugDraw::Tri(const SHVec4& color, const SHVec3& pt1, const SHVec3& pt2, const SHVec3& pt3) + { + dbgDrawSys->DrawTri(color, pt1, pt2, pt3); + } + + void SHDebugDraw::Quad(const SHVec4& color, const SHVec3& pt1, const SHVec3& pt2, const SHVec3& pt3, const SHVec3& pt4) + { + dbgDrawSys->DrawQuad(color, pt1, pt2, pt3, pt4); + } + + void SHDebugDraw::Poly(const SHVec4& color, std::initializer_list pointList) + { + dbgDrawSys->DrawPoly(color, pointList); + } + + void SHDebugDraw::Cube(const SHVec4& color, const SHVec3& pos, const SHVec3& size) + { + dbgDrawSys->DrawCube(color, pos, size); + } + + void SHDebugDraw::Sphere(const SHVec4& color, const SHVec3& pos, double radius) + { + dbgDrawSys->DrawSphere(color, pos, radius); + } +} \ No newline at end of file diff --git a/SHADE_Engine/src/Tools/SHDebugDraw.h b/SHADE_Engine/src/Tools/SHDebugDraw.h new file mode 100644 index 00000000..7ce44ec2 --- /dev/null +++ b/SHADE_Engine/src/Tools/SHDebugDraw.h @@ -0,0 +1,101 @@ +/************************************************************************************//*! +\file SHDebugDraw.h +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Nov 2, 2022 +\brief Contains the definition of the SHDebugDraw static 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. +*//*************************************************************************************/ +#pragma once + +// Project Includes +#include "SH_API.h" + +namespace SHADE +{ + /*-----------------------------------------------------------------------------------*/ + /* Forward Declarations */ + /*-----------------------------------------------------------------------------------*/ + class SHDebugDrawSystem; + class SHVec4; + class SHVec3; + class SHColour; + + /*-----------------------------------------------------------------------------------*/ + /* Type Definitions */ + /*-----------------------------------------------------------------------------------*/ + /// + /// Static helper class to make it easier to do debug drawing and enable support for + /// managed code to execute it withot dependency hell due to graphics system + /// dependencies. + /// + class SH_API SHDebugDraw final + { + public: + /*---------------------------------------------------------------------------------*/ + /* Lifecycle Functions */ + /*---------------------------------------------------------------------------------*/ + /// + /// Sets up the link with the SHDebugDrawSystem. Must be called after the + /// SHDebugDrawSystem is spawned. + /// + static void Init(SHDebugDrawSystem* sys); + + /*---------------------------------------------------------------------------------*/ + /* Draw Functions */ + /*---------------------------------------------------------------------------------*/ + /// + /// Renders a line between two points in world space. + /// + /// Colour of the line. + /// First point of the line. + /// Second point of the line. + static void Line(const SHVec4& color, const SHVec3& startPt, const SHVec3& endPt); + /// + /// Renders a triangle indicated by three points in world space. + /// + /// Colour of the triangle. + /// First point of the triangle. + /// Second point of the triangle. + /// Third point of the triangle. + static void Tri(const SHVec4& color, const SHVec3& pt1, const SHVec3& pt2, const SHVec3& pt3); + /// + /// Renders a quadrilateral indicated by four points in world space. + /// + /// Colour of the quadrilateral. + /// First point of the triangle. + /// Second point of the quadrilateral. + /// Third point of the quadrilateral. + /// Third point of the quadrilateral. + static void Quad(const SHVec4& color, const SHVec3& pt1, const SHVec3& pt2, const SHVec3& pt3, const SHVec3& pt4); + /// + /// Renders a polygon indicated by the specified set of points in world space. + /// + /// Colour of the polygon. + /// List of points for the polygon. + static void Poly(const SHVec4& color, std::initializer_list pointList); + /// + /// Renders a wireframe cube centered around the position specified in world space. + /// + /// Colour of the cube. + /// Position where the cube wil be centered at. + /// Size of the rendered cube. + static void Cube(const SHVec4& color, const SHVec3& pos, const SHVec3& size); + /// + /// Renders a wireframe sphere centered around the position specified in world space. + /// + /// Colour of the sphere. + /// Position where the sphere wil be centered at. + /// Size of the rendered sphere. + static void Sphere(const SHVec4& color, const SHVec3& pos, double radius); + + private: + /*---------------------------------------------------------------------------------*/ + /* Static Data Members */ + /*---------------------------------------------------------------------------------*/ + static SHDebugDrawSystem* dbgDrawSys; + }; +} \ No newline at end of file diff --git a/SHADE_Engine/src/Tools/SHLog.h b/SHADE_Engine/src/Tools/SHLog.h index 89dd9206..91117da6 100644 --- a/SHADE_Engine/src/Tools/SHLog.h +++ b/SHADE_Engine/src/Tools/SHLog.h @@ -9,7 +9,7 @@ Copyright (C) 2022 DigiPen Institute of Technology. Reproduction or disclosure of this file or its contents without the prior written consent of DigiPen Institute of Technology is prohibited. *//*************************************************************************************/ - +#pragma once // Standard Library #include // Project Headers diff --git a/SHADE_Managed/premake5.lua b/SHADE_Managed/premake5.lua index 906511c1..b383f002 100644 --- a/SHADE_Managed/premake5.lua +++ b/SHADE_Managed/premake5.lua @@ -25,11 +25,16 @@ project "SHADE_Managed" includedirs { "%{prj.location}/src", + } + + externalincludedirs + { "%{IncludeDir.spdlog}/include", "%{IncludeDir.imgui}", "%{IncludeDir.imguizmo}", "%{IncludeDir.imnodes}", "%{IncludeDir.yamlcpp}", + "%{IncludeDir.SDL}\\include", "%{IncludeDir.RTTR}/include", "%{IncludeDir.dotnet}\\include", "%{IncludeDir.reactphysics3d}\\include", @@ -38,13 +43,16 @@ project "SHADE_Managed" libdirs { - "%{IncludeDir.RTTR}/lib" + "%{IncludeDir.RTTR}/lib", + "%{IncludeDir.SDL}/lib" } links { "yaml-cpp", "imgui", + "SDL2.lib", + "SDL2main.lib", "SHADE_Engine", "SHADE_CSharp" } diff --git a/SHADE_Managed/src/Components/Camera.cxx b/SHADE_Managed/src/Components/Camera.cxx new file mode 100644 index 00000000..5e570cc1 --- /dev/null +++ b/SHADE_Managed/src/Components/Camera.cxx @@ -0,0 +1,127 @@ +#include "SHpch.h" + +#include "Camera.hxx" +#include "ECS_Base/Managers/SHSystemManager.h" +#include "Camera/SHCameraSystem.h" + + +namespace SHADE +{ + Camera::Camera(Entity entity) + :Component(entity) + { + + } + + + float Camera::Pitch::get() + { + return (GetNativeComponent()->GetPitch()); + } + + void Camera::Pitch::set(float val) + { + GetNativeComponent()->SetPitch(val); + } + float Camera::Yaw::get() + { + return (GetNativeComponent()->GetYaw()); + } + + void Camera::Yaw::set(float val) + { + GetNativeComponent()->SetYaw(val); + } + float Camera::Roll::get() + { + return (GetNativeComponent()->GetRoll()); + } + + void Camera::Roll::set(float val) + { + GetNativeComponent()->SetRoll(val); + } + float Camera::Width::get() + { + return (GetNativeComponent()->GetWidth()); + } + + void Camera::Width::set(float val) + { + GetNativeComponent()->SetWidth(val); + } + float Camera::Height::get() + { + return (GetNativeComponent()->GetHeight()); + } + + void Camera::Height::set(float val) + { + GetNativeComponent()->SetHeight(val); + } + float Camera::Near::get() + { + return (GetNativeComponent()->GetNear()); + } + + void Camera::Near::set(float val) + { + GetNativeComponent()->SetNear(val); + } + float Camera::Far::get() + { + return (GetNativeComponent()->GetFar()); + } + + void Camera::Far::set(float val) + { + GetNativeComponent()->SetFar(val); + } + float Camera::FOV::get() + { + return (GetNativeComponent()->GetFOV()); + } + + void Camera::FOV::set(float val) + { + GetNativeComponent()->SetFOV(val); + } + + Vector3 Camera::Position::get() + { + return Convert::ToCLI(GetNativeComponent()->GetPosition()); + } + + void Camera::Position::set(Vector3 val) + { + GetNativeComponent()->SetPosition(Convert::ToNative(val)); + } + + void Camera::SetMainCamera(size_t directorIndex) + { + auto system = SHSystemManager::GetSystem(); + system->SetMainCamera(GetNativeComponent()->GetEID(), directorIndex); + } + + void Camera::SetMainCamera() + { + SetMainCamera(0); + } + + void Camera::LookAt(Vector3 targetPosition) + { + auto system = SHSystemManager::GetSystem(); + system->CameraLookAt(*GetNativeComponent(), Convert::ToNative(targetPosition)); + } + + Vector3 Camera::GetForward() + { + auto system = SHSystemManager::GetSystem(); + SHVec3 forward, up, right; + system->GetCameraAxis(*GetNativeComponent(), forward, right, up); + return Convert::ToCLI(forward); + + } + + +} \ No newline at end of file diff --git a/SHADE_Managed/src/Components/Camera.hxx b/SHADE_Managed/src/Components/Camera.hxx new file mode 100644 index 00000000..257bff11 --- /dev/null +++ b/SHADE_Managed/src/Components/Camera.hxx @@ -0,0 +1,70 @@ +#pragma once + +// Project Includes +#include "Components/Component.hxx" +#include "Math/Vector3.hxx" +#include "Math/Quaternion.hxx" +// External Dependencies +#include "Camera/SHCameraComponent.h" + +namespace SHADE +{ + public ref class Camera : public Component + { + internal: + Camera(Entity entity); + + public: + property float Pitch + { + float get(); + void set(float val); + } + property float Yaw + { + float get(); + void set(float val); + } + property float Roll + { + float get(); + void set(float val); + } + property float Width + { + float get(); + void set(float val); + } + property float Height + { + float get(); + void set(float val); + } + property float Near + { + float get(); + void set(float val); + } + property float Far + { + float get(); + void set(float val); + } + property float FOV + { + float get(); + void set(float val); + } + property Vector3 Position + { + Vector3 get(); + void set(Vector3 val); + } + + + void SetMainCamera(size_t directorIndex); + void SetMainCamera(); + void LookAt(Vector3 targetPosition); + Vector3 GetForward(); + }; +} \ No newline at end of file diff --git a/SHADE_Managed/src/Components/CameraArm.cxx b/SHADE_Managed/src/Components/CameraArm.cxx new file mode 100644 index 00000000..67fcf6cf --- /dev/null +++ b/SHADE_Managed/src/Components/CameraArm.cxx @@ -0,0 +1,51 @@ +#include "SHpch.h" +#include "CameraArm.hxx" + + +namespace SHADE +{ + CameraArm::CameraArm(Entity entity) + :Component(entity) + { + + } + + float CameraArm::Pitch::get() + { + return (GetNativeComponent()->GetPitch()); + } + + void CameraArm::Pitch::set(float val) + { + GetNativeComponent()->SetPitch(val); + } + float CameraArm::Yaw::get() + { + return (GetNativeComponent()->GetYaw()); + } + + void CameraArm::Yaw::set(float val) + { + GetNativeComponent()->SetYaw(val); + } + + float CameraArm::ArmLength::get() + { + return (GetNativeComponent()->GetArmLength()); + } + + void CameraArm::ArmLength::set(float val) + { + GetNativeComponent()->SetArmLength(val); + } + + bool CameraArm::LookAtCameraOrigin::get() + { + return GetNativeComponent()->lookAtCameraOrigin; + } + + void CameraArm::LookAtCameraOrigin::set(bool val) + { + GetNativeComponent()->lookAtCameraOrigin = val; + } +} \ No newline at end of file diff --git a/SHADE_Managed/src/Components/CameraArm.hxx b/SHADE_Managed/src/Components/CameraArm.hxx new file mode 100644 index 00000000..771771cf --- /dev/null +++ b/SHADE_Managed/src/Components/CameraArm.hxx @@ -0,0 +1,40 @@ +#pragma once + +// Project Includes +#include "Components/Component.hxx" +#include "Math/Vector3.hxx" + +// External Dependencies +#include "Camera/SHCameraArmComponent.h" + + +namespace SHADE +{ + public ref class CameraArm : public Component + { + internal: + CameraArm(Entity entity); + public: + property float Pitch + { + float get(); + void set(float val); + } + property float Yaw + { + float get(); + void set(float val); + } + property float ArmLength + { + float get(); + void set(float val); + } + property bool LookAtCameraOrigin + { + bool get(); + void set(bool val); + } + + }; +} \ No newline at end of file diff --git a/SHADE_Managed/src/Components/Component.cxx b/SHADE_Managed/src/Components/Component.cxx index a6afc5cc..7f56fad3 100644 --- a/SHADE_Managed/src/Components/Component.cxx +++ b/SHADE_Managed/src/Components/Component.cxx @@ -67,6 +67,11 @@ namespace SHADE ScriptStore::RemoveScript(owner.GetEntity()); } + BaseComponent::operator bool(BaseComponent^ c) + { + return c != nullptr; + } + /*---------------------------------------------------------------------------------*/ /* Constructors */ /*---------------------------------------------------------------------------------*/ diff --git a/SHADE_Managed/src/Components/Component.hxx b/SHADE_Managed/src/Components/Component.hxx index 670e4e21..5ffa3952 100644 --- a/SHADE_Managed/src/Components/Component.hxx +++ b/SHADE_Managed/src/Components/Component.hxx @@ -101,6 +101,15 @@ namespace SHADE generic where T : ref class, Script void RemoveScript(); + /*-----------------------------------------------------------------------------*/ + /* Operator Overloads */ + /*-----------------------------------------------------------------------------*/ + /// + /// Implicit conversion operator to enable checking if a component is null. + /// + /// Component to check. + static operator bool(BaseComponent^ c); + protected: /*-----------------------------------------------------------------------------*/ /* Constructors */ diff --git a/SHADE_Managed/src/Components/RigidBody.cxx b/SHADE_Managed/src/Components/RigidBody.cxx index 172b928b..12861600 100644 --- a/SHADE_Managed/src/Components/RigidBody.cxx +++ b/SHADE_Managed/src/Components/RigidBody.cxx @@ -148,6 +148,14 @@ namespace SHADE { return Convert::ToCLI(GetNativeComponent()->GetTorque()); } + bool RigidBody::Interpolating::get() + { + return GetNativeComponent()->IsInterpolating(); + } + void RigidBody::Interpolating::set(bool value) + { + GetNativeComponent()->SetInterpolate(value); + } /*---------------------------------------------------------------------------------*/ /* Force Functions */ diff --git a/SHADE_Managed/src/Components/RigidBody.hxx b/SHADE_Managed/src/Components/RigidBody.hxx index b3e031ba..d3a30612 100644 --- a/SHADE_Managed/src/Components/RigidBody.hxx +++ b/SHADE_Managed/src/Components/RigidBody.hxx @@ -129,6 +129,11 @@ namespace SHADE { Vector3 get(); } + property bool Interpolating + { + bool get(); + void set(bool value); + } /*-----------------------------------------------------------------------------*/ /* Force Functions */ diff --git a/SHADE_Managed/src/Components/Transform.cxx b/SHADE_Managed/src/Components/Transform.cxx index 98f0da4f..927ce87f 100644 --- a/SHADE_Managed/src/Components/Transform.cxx +++ b/SHADE_Managed/src/Components/Transform.cxx @@ -87,15 +87,6 @@ namespace SHADE { GetNativeComponent()->SetWorldScale(Convert::ToNative(val)); } - Transform^ Transform::Parent::get() - { - auto node = SHSceneManager::GetCurrentSceneGraph().GetNode(owner.GetEntity()); - if (!node) - throw gcnew System::InvalidOperationException("[Transform] Unable to retrieve SceneGraphNode for an Entity."); - - const auto PARENT = node->GetParent(); - return PARENT ? gcnew Transform(PARENT->GetEntityID()) : nullptr; - } /*---------------------------------------------------------------------------------*/ /* Constructors */ @@ -103,21 +94,4 @@ namespace SHADE Transform::Transform(Entity entity) : Component(entity) {} - - /*---------------------------------------------------------------------------------*/ - /* Usage Functions */ - /*---------------------------------------------------------------------------------*/ - - void Transform::SetParent(Transform^ parent, bool worldPositionStays) - { - auto& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); - auto node = sceneGraph.GetNode(owner.GetEntity()); - if (!node) - throw gcnew System::InvalidOperationException("[Transform] Unable to retrieve SceneGraphNode for an Entity."); - - if (parent) - node->SetParent(sceneGraph.GetNode(parent->owner.GetEntity())); - else - sceneGraph.SetParent(parent->owner.GetEntity(), nullptr); - } } diff --git a/SHADE_Managed/src/Components/Transform.hxx b/SHADE_Managed/src/Components/Transform.hxx index bbe9fd19..942c6224 100644 --- a/SHADE_Managed/src/Components/Transform.hxx +++ b/SHADE_Managed/src/Components/Transform.hxx @@ -107,30 +107,6 @@ namespace SHADE Vector3 get(); void set(Vector3 val); } - /// - /// Parent Transform that affects this Transform. - /// - property Transform^ Parent - { - Transform^ get(); - } - - /*-----------------------------------------------------------------------------*/ - /* Usage Functions */ - /*-----------------------------------------------------------------------------*/ - /// - /// Sets the parent of this Transform component. - /// - /// - /// Entity that contains the Transform component that this Transform will be - /// parented to. If null, unparenting will occur. - /// - /// - /// If true, the transform values of this Transform component will retain their - /// pre-parent-change global transforms. The local transform values will be - /// modified to ensure that the global transforms do not change. - /// - void SetParent(Transform^ parent, bool worldPositionStays); }; } diff --git a/SHADE_Managed/src/Editor/Editor.cxx b/SHADE_Managed/src/Editor/Editor.cxx index 1097e203..55fe91da 100644 --- a/SHADE_Managed/src/Editor/Editor.cxx +++ b/SHADE_Managed/src/Editor/Editor.cxx @@ -260,7 +260,7 @@ namespace SHADE int val = safe_cast(field->GetValue(object)); int oldVal = val; - if (SHEditorUI::InputEnumCombo(Convert::ToNative(field->Name), val, nativeEnumNames)) + if (SHEditorUI::InputEnumCombo(Convert::ToNative(field->Name), val, nativeEnumNames, &isHovered)) { field->SetValue(object, val); registerUndoAction(object, field, val, oldVal); @@ -280,12 +280,23 @@ namespace SHADE // Actual Field std::string val = Convert::ToNative(stringVal); std::string oldVal = val; - if (SHEditorUI::InputTextField(Convert::ToNative(field->Name), val)) + if (SHEditorUI::InputTextField(Convert::ToNative(field->Name), val, &isHovered)) { field->SetValue(object, Convert::ToCLI(val)); registerUndoAction(object, field, Convert::ToCLI(val), Convert::ToCLI(oldVal)); } } + else if (field->FieldType == GameObject::typeid) + { + GameObject gameObj = safe_cast(field->GetValue(object)); + uint32_t entityId = gameObj.GetEntity(); + if (SHEditorUI::InputGameObjectField(Convert::ToNative(field->Name), entityId, &isHovered)) + { + GameObject newVal = GameObject(entityId); + field->SetValue(object, newVal); + registerUndoAction(object, field, newVal, gameObj); + } + } else { array^ interfaces = field->FieldType->GetInterfaces(); diff --git a/SHADE_Managed/src/Engine/Application.cxx b/SHADE_Managed/src/Engine/Application.cxx new file mode 100644 index 00000000..c19bafa6 --- /dev/null +++ b/SHADE_Managed/src/Engine/Application.cxx @@ -0,0 +1,71 @@ +/************************************************************************************//*! +\file Application.cxx +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Oct 31, 2022 +\brief Contains the definitions of the functions in the static managed + Application class. + + Note: This file is written in C++17/CLI. + +Copyright (C) 2022 DigiPen Institute of Technology. +Reproduction or disclosure of this file or its contents without the prior written consent +of DigiPen Institute of Technology is prohibited. +*//*************************************************************************************/ +// Precompiled Headers +#include "SHpch.h" +// Primary Header +#include "Application.hxx" +// External Dependencies +#include "ECS_Base/Managers/SHSystemManager.h" +#include "Editor/SHEditor.h" +#include "Graphics/MiddleEnd/Interface/SHGraphicsSystemInterface.h" + +namespace SHADE +{ + /*---------------------------------------------------------------------------------*/ + /* Properties */ + /*---------------------------------------------------------------------------------*/ + bool Application::IsPlaying::get() + { + auto editor = SHSystemManager::GetSystem(); + if (editor) + return editor->editorState == SHEditor::State::PLAY + || + editor->editorState == SHEditor::State::PAUSE; + + return true; + } + bool Application::IsPaused::get() + { + auto editor = SHSystemManager::GetSystem(); + if (editor) + return editor->editorState == SHEditor::State::PAUSE; + + return false; + } + int Application::WindowWidth::get() + { + return SHGraphicsSystemInterface::GetWindowWidth(); + } + int Application::WindowHeight::get() + { + return SHGraphicsSystemInterface::GetWindowWidth(); + } + bool Application::IsFullscreen::get() + { + return SHGraphicsSystemInterface::IsFullscreen(); + } + /*void Application::IsFullscreen::set(bool value) + { + return SHGraphicsSystemInterface::SetFullscreen(value); + }*/ + + /*---------------------------------------------------------------------------------*/ + /* Usage Functions */ + /*---------------------------------------------------------------------------------*/ + void Application::Quit() + { + SHGraphicsSystemInterface::CloseWindow(); + } +} diff --git a/SHADE_Managed/src/Engine/Application.hxx b/SHADE_Managed/src/Engine/Application.hxx new file mode 100644 index 00000000..8629cf75 --- /dev/null +++ b/SHADE_Managed/src/Engine/Application.hxx @@ -0,0 +1,77 @@ +/************************************************************************************//*! +\file Application.hxx +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Oct 31, 2022 +\brief Contains the definitions of a managed static Application class. + + Note: This file is written in C++17/CLI. + +Copyright (C) 2022 DigiPen Institute of Technology. +Reproduction or disclosure of this file or its contents without the prior written consent +of DigiPen Institute of Technology is prohibited. +*//*************************************************************************************/ +#pragma once + +namespace SHADE +{ + /// + /// Static class that contains useful properties for querying the state of the + /// engine. + /// + public ref class Application abstract sealed + { + public: + /*-----------------------------------------------------------------------------*/ + /* Properties */ + /*-----------------------------------------------------------------------------*/ + /// + /// Whether or not the engine is playing. This will always be true on Publish. + /// On Debug/Release builds, this is true when the editor is in Play Mode. It + /// will also be true even if the editor is in Play Mode but is paused. + /// + static property bool IsPlaying + { + bool get(); + } + /// + /// Whether or not the engine is in a paused state where script updates and + /// physics are not in play. + /// + static property bool IsPaused + { + bool get(); + } + /// + /// Retrieves the designated width of the current window. + /// + static property int WindowWidth + { + int get(); + } + /// + /// Retrieves the designated height of the current window. + /// + static property int WindowHeight + { + int get(); + } + /// + /// Whether or not the application is currently in fullscreen mode or not. + /// + static property bool IsFullscreen + { + bool get(); + // TODO: once implemented on SHADE_Engine + //void set(bool value); + } + + /*-----------------------------------------------------------------------------*/ + /* Usage Functions */ + /*-----------------------------------------------------------------------------*/ + /// + /// Marks the application to stop at the end of the current frame. + /// + static void Quit(); + }; +} diff --git a/SHADE_Managed/src/Engine/ECS.cxx b/SHADE_Managed/src/Engine/ECS.cxx index df67c788..3da39394 100644 --- a/SHADE_Managed/src/Engine/ECS.cxx +++ b/SHADE_Managed/src/Engine/ECS.cxx @@ -33,6 +33,8 @@ of DigiPen Institute of Technology is prohibited. #include "Components/Transform.hxx" #include "Components\RigidBody.hxx" #include "Components\Collider.hxx" +#include "Components/Camera.hxx" +#include "Components/CameraArm.hxx" namespace SHADE { @@ -248,6 +250,8 @@ namespace SHADE componentMap.Add(createComponentSet()); componentMap.Add(createComponentSet()); componentMap.Add(createComponentSet()); + componentMap.Add(createComponentSet()); + componentMap.Add(createComponentSet()); } /*---------------------------------------------------------------------------------*/ diff --git a/SHADE_Managed/src/Engine/GameObject.cxx b/SHADE_Managed/src/Engine/GameObject.cxx index 8c78e399..7ceabfed 100644 --- a/SHADE_Managed/src/Engine/GameObject.cxx +++ b/SHADE_Managed/src/Engine/GameObject.cxx @@ -17,9 +17,12 @@ of DigiPen Institute of Technology is prohibited. #include "GameObject.hxx" // External Dependencies #include "ECS_Base/Managers/SHEntityManager.h" +#include "Scene/SHSceneGraph.h" // Project Headers #include "ECS.hxx" +#include "Utility/Convert.hxx" #include "Scripts/ScriptStore.hxx" +#include "Utility/Debug.hxx" namespace SHADE { @@ -39,7 +42,13 @@ namespace SHADE System::Nullable GameObject::Find(System::String ^ name) { // Search the GameObjectLibrary for an Entity with the specified name - throw gcnew System::NotImplementedException(); + const auto ENTITY_ID = SHEntityManager::GetEntityByName(Convert::ToNative(name)); + if (ENTITY_ID == MAX_EID) + { + return {}; + } + + return GameObject(ENTITY_ID); } /*---------------------------------------------------------------------------------*/ @@ -56,7 +65,38 @@ namespace SHADE } bool GameObject::IsActiveInHierarchy::get() { - return true; // TODO: Update once we have an equivalent on the Entity object + auto node = SHSceneManager::GetCurrentSceneGraph().GetNode(GetEntity()); + if (!node) + { + Debug::LogWarning("Attempting to access a GameObject's ActiveInHierarchy state which does not exist. Assuming inactive."); + return false; + } + return node->IsActive(); + } + Entity GameObject::EntityId::get() + { + return entity; + } + GameObject^ GameObject::Parent::get() + { + const auto& SCENE_GRAPH = SHSceneManager::GetCurrentSceneGraph(); + const auto* ROOT = SCENE_GRAPH.GetRoot(); + + const auto* NODE = SCENE_GRAPH.GetNode(entity); + if (NODE == nullptr) + throw gcnew System::InvalidOperationException("Unable to retrieve SceneGraphNode for Entity " + entity.ToString()); + + const auto* PARENT = NODE->GetParent(); + return PARENT != ROOT ? gcnew GameObject(PARENT->GetEntityID()) : nullptr; + } + void GameObject::Parent::set(GameObject^ newParent) + { + const auto& SCENE_GRAPH = SHSceneManager::GetCurrentSceneGraph(); + + if (newParent == nullptr) + SCENE_GRAPH.SetParent(entity, nullptr); + else + SCENE_GRAPH.SetParent(entity, newParent->EntityId); } /*---------------------------------------------------------------------------------*/ @@ -141,11 +181,13 @@ namespace SHADE /* Constructors */ /*---------------------------------------------------------------------------------*/ GameObject::GameObject(const SHEntity& entity) - : entity { entity.GetEID() } + : entity { entity.GetEID() } + , children{ gcnew System::Collections::ArrayList } {} GameObject::GameObject(Entity entity) - : entity { entity } + : entity { entity } + , children{ gcnew System::Collections::ArrayList } {} /*---------------------------------------------------------------------------------*/ diff --git a/SHADE_Managed/src/Engine/GameObject.hxx b/SHADE_Managed/src/Engine/GameObject.hxx index 723d9cec..99296a91 100644 --- a/SHADE_Managed/src/Engine/GameObject.hxx +++ b/SHADE_Managed/src/Engine/GameObject.hxx @@ -86,6 +86,21 @@ namespace SHADE { bool get(); } + /// + /// Native Entity ID value for this GameObject. + /// + property Entity EntityId + { + Entity get(); + } + /// + /// The parent entity for this GameObject. + /// + property GameObject^ Parent + { + GameObject^ get(); + void set(GameObject^); + } /*-----------------------------------------------------------------------------*/ /* GameObject Property Functions */ @@ -105,6 +120,7 @@ namespace SHADE /// Whether to activate or deactivate this GameObject. /// void SetActive(bool active); + /*-----------------------------------------------------------------------------*/ /* Component Access Functions */ @@ -235,7 +251,8 @@ namespace SHADE /*-----------------------------------------------------------------------------*/ /* Data Members */ /*-----------------------------------------------------------------------------*/ - Entity entity; + Entity entity; + System::Collections::ArrayList^ children; public: /*-----------------------------------------------------------------------------*/ diff --git a/SHADE_Managed/src/Engine/Time.cxx b/SHADE_Managed/src/Engine/Time.cxx index ff0628e7..36032e00 100644 --- a/SHADE_Managed/src/Engine/Time.cxx +++ b/SHADE_Managed/src/Engine/Time.cxx @@ -14,6 +14,9 @@ of DigiPen Institute of Technology is prohibited. *//*************************************************************************************/ // Precompiled Headers #include "SHpch.h" +// External Dependencies +#include "FRC/SHFramerateController.h" +#include "Physics/SHPhysicsSystemInterface.h" // Primary Header #include "Time.hxx" @@ -26,4 +29,14 @@ namespace SHADE { return SHFrameRateController::GetRawDeltaTime(); } + + + float Time::DeltaTimeF::get() + { + return static_cast(SHFrameRateController::GetRawDeltaTime()); + } + double Time::FixedDeltaTime::get() + { + return SHPhysicsSystemInterface::GetFixedDT(); + } } \ No newline at end of file diff --git a/SHADE_Managed/src/Engine/Time.hxx b/SHADE_Managed/src/Engine/Time.hxx index 969eea03..c0f0ed62 100644 --- a/SHADE_Managed/src/Engine/Time.hxx +++ b/SHADE_Managed/src/Engine/Time.hxx @@ -14,8 +14,6 @@ of DigiPen Institute of Technology is prohibited. *//*************************************************************************************/ #pragma once -#include "FRC/SHFramerateController.h" - namespace SHADE { /// @@ -29,13 +27,28 @@ namespace SHADE /*-----------------------------------------------------------------------------*/ /// /// Time taken to process the previous frame. - /// Note, is affected by TimeScale. Use UnscaledDeltaTime if you wish to retrieve - /// real world time. This is also affected by MaxDeltaTime clamping that - /// UnscaledDeltaTime is subject to. /// static property double DeltaTime { double get(); } + /*-----------------------------------------------------------------------------*/ + /* Properties */ + /*-----------------------------------------------------------------------------*/ + /// + /// Time taken to process the previous frame. + /// + static property float DeltaTimeF + { + float get(); + } + /// + /// Time taken for Physics simulations. You should use this for operations + /// within Script.FixedUpdate() + /// + static property double FixedDeltaTime + { + double get(); + } }; } \ No newline at end of file diff --git a/SHADE_Managed/src/Input/Input.cxx b/SHADE_Managed/src/Input/Input.cxx index 0a386f3a..f0ea0edc 100644 --- a/SHADE_Managed/src/Input/Input.cxx +++ b/SHADE_Managed/src/Input/Input.cxx @@ -99,4 +99,11 @@ namespace SHADE return SHInputManager::GetKeyReleasedTime(static_cast(key)); } + Vector2 Input::GetMouseVelocity() + { + double velX, velY; + SHInputManager::GetMouseVelocity(&velX, &velY); + + return Convert::ToCLI(SHVec2{ (float)velX,(float)velY }); + } } \ No newline at end of file diff --git a/SHADE_Managed/src/Input/Input.hxx b/SHADE_Managed/src/Input/Input.hxx index f281e4c8..875054cc 100644 --- a/SHADE_Managed/src/Input/Input.hxx +++ b/SHADE_Managed/src/Input/Input.hxx @@ -31,10 +31,159 @@ namespace SHADE /// /// Represents the available supported keycodes that can be passed into the /// key-based Input functions. + /// + /// Attempting to follow https://docs.unity3d.com/ScriptReference/KeyCode.html + /// Win32 keycodes are shift-insensitive, i.e. 'A' and 'a' are the same keycode and '1' and '!' are the same keycode /// enum class KeyCode : int { + Backspace = static_cast(SHInputManager::SH_KEYCODE::BACKSPACE), + Delete = static_cast(SHInputManager::SH_KEYCODE::DEL), + Tab = static_cast(SHInputManager::SH_KEYCODE::TAB), + Clear = static_cast(SHInputManager::SH_KEYCODE::CLEAR), + Return = static_cast(SHInputManager::SH_KEYCODE::ENTER), + Pause = static_cast(SHInputManager::SH_KEYCODE::PAUSE), + Escape = static_cast(SHInputManager::SH_KEYCODE::ESCAPE), Space = static_cast(SHInputManager::SH_KEYCODE::SPACE), + Keypad0 = static_cast(SHInputManager::SH_KEYCODE::NUMPAD_0), + Keypad1 = static_cast(SHInputManager::SH_KEYCODE::NUMPAD_1), + Keypad2 = static_cast(SHInputManager::SH_KEYCODE::NUMPAD_2), + Keypad3 = static_cast(SHInputManager::SH_KEYCODE::NUMPAD_3), + Keypad4 = static_cast(SHInputManager::SH_KEYCODE::NUMPAD_4), + Keypad5 = static_cast(SHInputManager::SH_KEYCODE::NUMPAD_5), + Keypad6 = static_cast(SHInputManager::SH_KEYCODE::NUMPAD_6), + Keypad7 = static_cast(SHInputManager::SH_KEYCODE::NUMPAD_7), + Keypad8 = static_cast(SHInputManager::SH_KEYCODE::NUMPAD_8), + Keypad9 = static_cast(SHInputManager::SH_KEYCODE::NUMPAD_9), + KeypadPeriod = static_cast(SHInputManager::SH_KEYCODE::DECIMAL), + KeypadDivide = static_cast(SHInputManager::SH_KEYCODE::DIVIDE), + KeypadMultiply = static_cast(SHInputManager::SH_KEYCODE::MULTIPLY), + KeypadMinus = static_cast(SHInputManager::SH_KEYCODE::SUBTRACT), + KeypadPlus = static_cast(SHInputManager::SH_KEYCODE::ADD), + KeypadEnter = static_cast(SHInputManager::SH_KEYCODE::ENTER), + //KeypadEquals + UpArrow = static_cast(SHInputManager::SH_KEYCODE::UP_ARROW), + DownArrow = static_cast(SHInputManager::SH_KEYCODE::DOWN_ARROW), + RightArrow = static_cast(SHInputManager::SH_KEYCODE::RIGHT_ARROW), + LeftArrow = static_cast(SHInputManager::SH_KEYCODE::LEFT_ARROW), + Insert = static_cast(SHInputManager::SH_KEYCODE::INSERT), + Home = static_cast(SHInputManager::SH_KEYCODE::HOME), + End = static_cast(SHInputManager::SH_KEYCODE::END), + PageUp = static_cast(SHInputManager::SH_KEYCODE::PAGE_UP), + PageDown = static_cast(SHInputManager::SH_KEYCODE::PAGE_DOWN), + F1 = static_cast(SHInputManager::SH_KEYCODE::F1), + F2 = static_cast(SHInputManager::SH_KEYCODE::F2), + F3 = static_cast(SHInputManager::SH_KEYCODE::F3), + F4 = static_cast(SHInputManager::SH_KEYCODE::F4), + F5 = static_cast(SHInputManager::SH_KEYCODE::F5), + F6 = static_cast(SHInputManager::SH_KEYCODE::F6), + F7 = static_cast(SHInputManager::SH_KEYCODE::F7), + F8 = static_cast(SHInputManager::SH_KEYCODE::F8), + F9 = static_cast(SHInputManager::SH_KEYCODE::F9), + F10 = static_cast(SHInputManager::SH_KEYCODE::F10), + F11 = static_cast(SHInputManager::SH_KEYCODE::F11), + F12 = static_cast(SHInputManager::SH_KEYCODE::F12), + F13 = static_cast(SHInputManager::SH_KEYCODE::F13), + F14 = static_cast(SHInputManager::SH_KEYCODE::F14), + F15 = static_cast(SHInputManager::SH_KEYCODE::F15), + F16 = static_cast(SHInputManager::SH_KEYCODE::F16), + F17 = static_cast(SHInputManager::SH_KEYCODE::F17), + F18 = static_cast(SHInputManager::SH_KEYCODE::F18), + F19 = static_cast(SHInputManager::SH_KEYCODE::F19), + F20 = static_cast(SHInputManager::SH_KEYCODE::F20), + F21 = static_cast(SHInputManager::SH_KEYCODE::F21), + F22 = static_cast(SHInputManager::SH_KEYCODE::F22), + F23 = static_cast(SHInputManager::SH_KEYCODE::F23), + F24 = static_cast(SHInputManager::SH_KEYCODE::F24), + Alpha0 = static_cast(SHInputManager::SH_KEYCODE::NUMBER_0), + Alpha1 = static_cast(SHInputManager::SH_KEYCODE::NUMBER_1), + Alpha2 = static_cast(SHInputManager::SH_KEYCODE::NUMBER_2), + Alpha3 = static_cast(SHInputManager::SH_KEYCODE::NUMBER_3), + Alpha4 = static_cast(SHInputManager::SH_KEYCODE::NUMBER_4), + Alpha5 = static_cast(SHInputManager::SH_KEYCODE::NUMBER_5), + Alpha6 = static_cast(SHInputManager::SH_KEYCODE::NUMBER_6), + Alpha7 = static_cast(SHInputManager::SH_KEYCODE::NUMBER_7), + Alpha8 = static_cast(SHInputManager::SH_KEYCODE::NUMBER_8), + Alpha9 = static_cast(SHInputManager::SH_KEYCODE::NUMBER_9), + //Exclaim + //DoubleQuote + //Hash + //Dollar + //Percent + //Ampersand + Quote = static_cast(SHInputManager::SH_KEYCODE::OEM_7), + //LeftParen + //RightParen + //Asterisk + //Plus + Comma = static_cast(SHInputManager::SH_KEYCODE::OEM_COMMA), + Minus = static_cast(SHInputManager::SH_KEYCODE::OEM_MINUS), + Period = static_cast(SHInputManager::SH_KEYCODE::OEM_PERIOD), + Slash = static_cast(SHInputManager::SH_KEYCODE::OEM_2), + //Colon + Semicolon = static_cast(SHInputManager::SH_KEYCODE::OEM_1), + //Less + Equals = static_cast(SHInputManager::SH_KEYCODE::OEM_PLUS), + //Greater + //Question + //At + LeftBracket = static_cast(SHInputManager::SH_KEYCODE::OEM_4), + Backslash = static_cast(SHInputManager::SH_KEYCODE::OEM_5), + RightBracket = static_cast(SHInputManager::SH_KEYCODE::OEM_6), + //Caret + //Underscore + BackQuote = static_cast(SHInputManager::SH_KEYCODE::OEM_3), + A = static_cast(SHInputManager::SH_KEYCODE::A), + B = static_cast(SHInputManager::SH_KEYCODE::B), + C = static_cast(SHInputManager::SH_KEYCODE::C), + D = static_cast(SHInputManager::SH_KEYCODE::D), + E = static_cast(SHInputManager::SH_KEYCODE::E), + F = static_cast(SHInputManager::SH_KEYCODE::F), + G = static_cast(SHInputManager::SH_KEYCODE::G), + H = static_cast(SHInputManager::SH_KEYCODE::H), + I = static_cast(SHInputManager::SH_KEYCODE::I), + J = static_cast(SHInputManager::SH_KEYCODE::J), + K = static_cast(SHInputManager::SH_KEYCODE::K), + L = static_cast(SHInputManager::SH_KEYCODE::L), + M = static_cast(SHInputManager::SH_KEYCODE::M), + N = static_cast(SHInputManager::SH_KEYCODE::N), + O = static_cast(SHInputManager::SH_KEYCODE::O), + P = static_cast(SHInputManager::SH_KEYCODE::P), + Q = static_cast(SHInputManager::SH_KEYCODE::Q), + R = static_cast(SHInputManager::SH_KEYCODE::R), + S = static_cast(SHInputManager::SH_KEYCODE::S), + T = static_cast(SHInputManager::SH_KEYCODE::T), + U = static_cast(SHInputManager::SH_KEYCODE::U), + V = static_cast(SHInputManager::SH_KEYCODE::V), + W = static_cast(SHInputManager::SH_KEYCODE::W), + X = static_cast(SHInputManager::SH_KEYCODE::X), + Y = static_cast(SHInputManager::SH_KEYCODE::Y), + Z = static_cast(SHInputManager::SH_KEYCODE::Z), + //LeftCurlyBracket + //Pipe + //RightCurlyBracket + //Tilde + NumLock = static_cast(SHInputManager::SH_KEYCODE::NUM_LOCK), + CapsLock = static_cast(SHInputManager::SH_KEYCODE::CAPS_LOCK), + ScrollLock = static_cast(SHInputManager::SH_KEYCODE::SCROLL_LOCK), + RightShift = static_cast(SHInputManager::SH_KEYCODE::RIGHT_SHIFT), + LeftShift = static_cast(SHInputManager::SH_KEYCODE::LEFT_SHIFT), + RightControl = static_cast(SHInputManager::SH_KEYCODE::RIGHT_CTRL), + LeftControl = static_cast(SHInputManager::SH_KEYCODE::LEFT_CTRL), + RightAlt = static_cast(SHInputManager::SH_KEYCODE::RIGHT_ALT), + LeftAlt = static_cast(SHInputManager::SH_KEYCODE::LEFT_ALT), + LeftWindows = static_cast(SHInputManager::SH_KEYCODE::LEFT_WINDOWS), + RightWindows = static_cast(SHInputManager::SH_KEYCODE::RIGHT_WINDOWS), + //AltGr + Help = static_cast(SHInputManager::SH_KEYCODE::HELP), + Print = static_cast(SHInputManager::SH_KEYCODE::PRINT), + SysReq = static_cast(SHInputManager::SH_KEYCODE::PRINT_SCREEN), + //Break + //Menu + //Mouse buttons use mouse codes, which are enums declared later + //TODO Controller input +#if 0 + Space = static_cast(SHInputManager::SH_KEYCODE::SPACE), //Apostrophe = static_cast(SHInputManager::SH_KEYCODE::APOSTROPHE), Comma = static_cast(SHInputManager::SH_KEYCODE::OEM_COMMA), Minus = static_cast(SHInputManager::SH_KEYCODE::OEM_MINUS), @@ -190,7 +339,8 @@ namespace SHADE JoystickButton6 = JoystickView, JoystickButton7 = JoystickMenu, JoystickButton8 = JoystickLeftStick, - JoystickButton9 = JoystickRightStick + JoystickButton9 = JoystickRightStick +#endif }; /// @@ -321,5 +471,7 @@ namespace SHADE /// The key to check. /// Time in seconds that the key was held. static double GetMouseReleasedTime(MouseCode mouseButton); + + static Vector2 GetMouseVelocity(); }; } \ No newline at end of file diff --git a/SHADE_Managed/src/Math/Vector2.cxx b/SHADE_Managed/src/Math/Vector2.cxx index b110d4f8..42080d60 100644 --- a/SHADE_Managed/src/Math/Vector2.cxx +++ b/SHADE_Managed/src/Math/Vector2.cxx @@ -236,6 +236,22 @@ namespace SHADE lhs.y * rhs.y ); } + Vector2 Vector2::operator*(Vector2 lhs, double rhs) + { + return Vector2 + ( + lhs.x * static_cast(rhs), + lhs.y * static_cast(rhs) + ); + } + Vector2 Vector2::operator/(Vector2 lhs, double rhs) + { + return Vector2 + ( + lhs.x / static_cast(rhs), + lhs.y / static_cast(rhs) + ); + } Vector2 Vector2::operator*(Vector2 lhs, float rhs) { return Vector2 diff --git a/SHADE_Managed/src/Math/Vector2.hxx b/SHADE_Managed/src/Math/Vector2.hxx index 94b1989f..4877696b 100644 --- a/SHADE_Managed/src/Math/Vector2.hxx +++ b/SHADE_Managed/src/Math/Vector2.hxx @@ -361,6 +361,22 @@ namespace SHADE /// Vector2 to multiply with. /// Scalar to multiply with. /// The result of the scalar multiplication. + static Vector2 operator*(Vector2 lhs, double rhs); + /// + /// Calculates the division of a Vector2 with a scalar value and returns + /// the result. + /// + /// Scalar to divide with. + /// Vector2 to divide with. + /// The result of the scalar division. + static Vector2 operator/(Vector2 lhs, double rhs); + /// + /// Calculates the multiplication of a Vector2 with a scalar value and returns + /// the result. + /// + /// Vector2 to multiply with. + /// Scalar to multiply with. + /// The result of the scalar multiplication. static Vector2 operator*(Vector2 lhs, float rhs); /// /// Calculates the division of a Vector2 with a scalar value and returns diff --git a/SHADE_Managed/src/Math/Vector3.cxx b/SHADE_Managed/src/Math/Vector3.cxx index adbb4d3a..83adbb38 100644 --- a/SHADE_Managed/src/Math/Vector3.cxx +++ b/SHADE_Managed/src/Math/Vector3.cxx @@ -237,6 +237,24 @@ namespace SHADE lhs.z * rhs.z ); } + Vector3 Vector3::operator*(Vector3 lhs, double rhs) + { + return Vector3 + ( + lhs.x * static_cast(rhs), + lhs.y * static_cast(rhs), + lhs.z * static_cast(rhs) + ); + } + Vector3 Vector3::operator/(Vector3 lhs, double rhs) + { + return Vector3 + ( + lhs.x / static_cast(rhs), + lhs.y / static_cast(rhs), + lhs.z / static_cast(rhs) + ); + } Vector3 Vector3::operator*(Vector3 lhs, float rhs) { return Vector3 diff --git a/SHADE_Managed/src/Math/Vector3.hxx b/SHADE_Managed/src/Math/Vector3.hxx index 70cff88f..4cdf653e 100644 --- a/SHADE_Managed/src/Math/Vector3.hxx +++ b/SHADE_Managed/src/Math/Vector3.hxx @@ -375,6 +375,22 @@ namespace SHADE /// Vector3 to multiply with. /// Scalar to multiply with. /// The result of the scalar multiplication. + static Vector3 operator*(Vector3 lhs, double rhs); + /// + /// Calculates the division of a Vector3 with a scalar value and returns + /// the result. + /// + /// Scalar to divide with. + /// Vector3 to divide with. + /// The result of the scalar division. + static Vector3 operator/(Vector3 lhs, double rhs); + /// + /// Calculates the multiplication of a Vector3 with a scalar value and returns + /// the result. + /// + /// Vector3 to multiply with. + /// Scalar to multiply with. + /// The result of the scalar multiplication. static Vector3 operator*(Vector3 lhs, float rhs); /// /// Calculates the division of a Vector3 with a scalar value and returns diff --git a/SHADE_Managed/src/Physics/CollisionInfo.cxx b/SHADE_Managed/src/Physics/CollisionInfo.cxx new file mode 100644 index 00000000..135760db --- /dev/null +++ b/SHADE_Managed/src/Physics/CollisionInfo.cxx @@ -0,0 +1,36 @@ +/************************************************************************************//*! +\file CollisionInfo.cxx +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Oct 31, 2022 +\brief Contains the definition of the functions of the managed CollisionInfo + struct. + + Note: This file is written in C++17/CLI. + +Copyright (C) 2022 DigiPen Institute of Technology. +Reproduction or disclosure of this file or its contents without the prior written consent +of DigiPen Institute of Technology is prohibited. +*//*************************************************************************************/ +#include "SHpch.h" +#include "CollisionInfo.hxx" +#include "Components/RigidBody.hxx" +#include "Components/Collider.hxx" + +namespace SHADE +{ + Collider^ CollisionInfo::Collider::get() + { + return GameObject.GetComponent(); + } + + CollisionShape^ CollisionInfo::CollisionShape::get() + { + throw gcnew System::NotImplementedException(); + } + + RigidBody^ CollisionInfo::RigidBody::get() + { + return GameObject.GetComponent(); + } +} diff --git a/SHADE_Managed/src/Physics/CollisionInfo.hxx b/SHADE_Managed/src/Physics/CollisionInfo.hxx new file mode 100644 index 00000000..40cb9ccc --- /dev/null +++ b/SHADE_Managed/src/Physics/CollisionInfo.hxx @@ -0,0 +1,66 @@ +/************************************************************************************//*! +\file CollisionInfo.hxx +\author Tng Kah Wei, kahwei.tng, 390009620 +\par email: kahwei.tng\@digipen.edu +\date Oct 31, 2022 +\brief Contains the definition of the managed CollisionInfo struct with the + definition of its properties and declaration of functions. + + Note: This file is written in C++17/CLI. + +Copyright (C) 2022 DigiPen Institute of Technology. +Reproduction or disclosure of this file or its contents without the prior written consent +of DigiPen Institute of Technology is prohibited. +*//*************************************************************************************/ +#pragma once +// Project Includes +#include "Engine/GameObject.hxx" + +namespace SHADE +{ + /*---------------------------------------------------------------------------------*/ + /* Forward Declarations */ + /*---------------------------------------------------------------------------------*/ + ref class RigidBody; + ref class Collider; + ref class CollisionShape; + + /*---------------------------------------------------------------------------------*/ + /* Type Definitions */ + /*---------------------------------------------------------------------------------*/ + /// + /// Struct that describes a collision + /// + public value struct CollisionInfo + { + public: + /*-----------------------------------------------------------------------------*/ + /* Properties */ + /*-----------------------------------------------------------------------------*/ + /// + /// The GameObject whose collider you are colliding with. + /// + property GameObject GameObject; + /// + /// The Collider that you are colliding with. + /// + property Collider^ Collider + { + SHADE::Collider^ get(); + } + /// + /// The CollisionShape of the Collider that you are colliding with. + /// + property CollisionShape^ CollisionShape + { + SHADE::CollisionShape^ get(); + } + /// + /// The RigidBody that you are colliding with. + /// + property RigidBody^ RigidBody + { + SHADE::RigidBody^ get(); + } + }; +} diff --git a/SHADE_Managed/src/Scripts/Script.cxx b/SHADE_Managed/src/Scripts/Script.cxx index ecd27325..e476d69d 100644 --- a/SHADE_Managed/src/Scripts/Script.cxx +++ b/SHADE_Managed/src/Scripts/Script.cxx @@ -18,6 +18,8 @@ of DigiPen Institute of Technology is prohibited. #include "Script.hxx" // Project Headers #include "Utility/Debug.hxx" +#include "ScriptStore.hxx" +#include "Engine/ECS.hxx" namespace SHADE { @@ -49,8 +51,7 @@ namespace SHADE generic void Script::RemoveComponent() { - throw gcnew System::NotImplementedException; - //ECS::RemoveComponent(owner.GetNativeEntity()); + owner.RemoveComponent(); } /*---------------------------------------------------------------------------------*/ @@ -59,37 +60,37 @@ namespace SHADE generic T Script::AddScript() { - throw gcnew System::NotImplementedException; - //return ScriptStore::AddScript(owner.GetEntity()); + return ScriptStore::AddScript(owner.GetEntity()); } generic T Script::GetScript() { - throw gcnew System::NotImplementedException; - //return ScriptStore::GetScript(owner.GetEntity()); + return ScriptStore::GetScript(owner.GetEntity()); } generic T Script::GetScriptInChildren() { - throw gcnew System::NotImplementedException; - //return ScriptStore::GetScriptInChildren(owner.GetEntity()); + return ScriptStore::GetScriptInChildren(owner.GetEntity()); } generic System::Collections::Generic::IEnumerable^ Script::GetScripts() { - throw gcnew System::NotImplementedException; - //return ScriptStore::GetScripts(owner.GetEntity()); + return ScriptStore::GetScripts(owner.GetEntity()); } generic void Script::RemoveScript() { - throw gcnew System::NotImplementedException; - //ScriptStore::RemoveScript(owner.GetEntity()); + ScriptStore::RemoveScript(owner.GetEntity()); } - + + Script::operator bool(Script^ s) + { + return s != nullptr; + } + /*---------------------------------------------------------------------------------*/ /* "All-time" Lifecycle Functions */ /*---------------------------------------------------------------------------------*/ @@ -146,6 +147,48 @@ namespace SHADE SAFE_NATIVE_CALL_END(this) } + void Script::OnCollisionEnter(CollisionInfo collision) + { + SAFE_NATIVE_CALL_BEGIN + onCollisionEnter(collision); + SAFE_NATIVE_CALL_END(this) + } + + void Script::OnCollisionStay(CollisionInfo collision) + { + SAFE_NATIVE_CALL_BEGIN + onCollisionStay(collision); + SAFE_NATIVE_CALL_END(this) + } + + void Script::OnCollisionExit(CollisionInfo collision) + { + SAFE_NATIVE_CALL_BEGIN + onCollisionExit(collision); + SAFE_NATIVE_CALL_END(this) + } + + void Script::OnTriggerEnter(CollisionInfo collision) + { + SAFE_NATIVE_CALL_BEGIN + onTriggerEnter(collision); + SAFE_NATIVE_CALL_END(this) + } + + void Script::OnTriggerStay(CollisionInfo collision) + { + SAFE_NATIVE_CALL_BEGIN + onTriggerStay(collision); + SAFE_NATIVE_CALL_END(this) + } + + void Script::OnTriggerExit(CollisionInfo collision) + { + SAFE_NATIVE_CALL_BEGIN + onTriggerExit(collision); + SAFE_NATIVE_CALL_END(this) + } + /*---------------------------------------------------------------------------------*/ /* Constructors */ /*---------------------------------------------------------------------------------*/ @@ -168,4 +211,14 @@ namespace SHADE void Script::update() {} void Script::lateUpdate() {} void Script::onDestroy() {} -}// namespace PlushieAPI + + /*---------------------------------------------------------------------------------*/ + /* Virtual Event Functions */ + /*---------------------------------------------------------------------------------*/ + void Script::onTriggerEnter(CollisionInfo) {} + void Script::onTriggerStay(CollisionInfo) {} + void Script::onTriggerExit(CollisionInfo) {} + void Script::onCollisionEnter(CollisionInfo) {} + void Script::onCollisionStay(CollisionInfo) {} + void Script::onCollisionExit(CollisionInfo) {} +} diff --git a/SHADE_Managed/src/Scripts/Script.hxx b/SHADE_Managed/src/Scripts/Script.hxx index cef9f4cd..afeaa8a0 100644 --- a/SHADE_Managed/src/Scripts/Script.hxx +++ b/SHADE_Managed/src/Scripts/Script.hxx @@ -15,6 +15,7 @@ of DigiPen Institute of Technology is prohibited. // Project Includes #include "Engine/GameObject.hxx" +#include "Physics/CollisionInfo.hxx" namespace SHADE { @@ -153,6 +154,15 @@ namespace SHADE generic where T : ref class, Script void RemoveScript(); + /*-----------------------------------------------------------------------------*/ + /* Operator Overloads */ + /*-----------------------------------------------------------------------------*/ + /// + /// Implicit conversion operator to enable checking if a component is null. + /// + /// Component to check. + static operator bool(Script^ s); + internal: /*-----------------------------------------------------------------------------*/ /* "All-Time" Lifecycle Functions */ @@ -204,6 +214,46 @@ namespace SHADE /// void OnDestroy(); + /*-----------------------------------------------------------------------------*/ + /* Event Functions */ + /*-----------------------------------------------------------------------------*/ + /// + /// Used to call onCollisionEnter(). This should be called when a collision is + /// detected between the attached GameObject and another GameObject. + /// + /// Information on the collision event. + void OnCollisionEnter(CollisionInfo collision); + /// + /// Used to call onCollisionStay(). This should be called when a collision is + /// persistent between the attached GameObject and another GameObject. + /// + /// Information on the collision event. + void OnCollisionStay(CollisionInfo collision); + /// + /// Used to call onCollisionExit(). This should be called when a collision ends + /// between the attached GameObject and another GameObject. + /// + /// Information on the collision event. + void OnCollisionExit(CollisionInfo collision); + /// + /// Used to call onTriggerEnter(). This should be called when a trigger-type + /// collision is detected between the attached GameObject and another GameObject. + /// + /// Information on the collision event. + void OnTriggerEnter(CollisionInfo collision); + /// + /// Used to call onTriggerStay(). This should be called when a trigger-type + /// collision is detected between the attached GameObject and another GameObject. + /// + /// Information on the collision event. + void OnTriggerStay(CollisionInfo collision); + /// + /// Used to call onTriggerExit(). This should be called when a trigger-type + /// collision is detected between the attached GameObject and another GameObject. + /// + /// Information on the collision event. + void OnTriggerExit(CollisionInfo collision); + protected: /*-----------------------------------------------------------------------------*/ /* Constructors */ @@ -264,6 +314,46 @@ namespace SHADE /// virtual void onDestroy(); + /*-----------------------------------------------------------------------------*/ + /* Virtual Event Functions */ + /*-----------------------------------------------------------------------------*/ + /// + /// Called when the attached GameObject has a trigger Collider and collides with + /// another GameObject with a Collider in the first frame of collision. + /// + /// Information on the collision event. + virtual void onTriggerEnter(CollisionInfo info); + /// + /// Called when the attached GameObject has a trigger Collider and collides with + /// another GameObject with a Collider in subsequent frames of collision. + /// + /// Information on the collision event. + virtual void onTriggerStay(CollisionInfo info); + /// + /// Called when the attached GameObject has a trigger Collider and leaves a + /// collision with another GameObject with a Collider2D. + /// + /// Information on the collision event. + virtual void onTriggerExit(CollisionInfo info); + /// + /// Called when the attached GameObject has a Collider and collides with + /// another GameObject with a Collider in the first frame of collision. + /// + /// Information on the collision event. + virtual void onCollisionEnter(CollisionInfo info); + /// + /// Called when the attached GameObject has a Collider and collides with + /// another GameObject with a Collider in subsequent frames of collision. + /// + /// Information on the collision event. + virtual void onCollisionStay(CollisionInfo info); + /// + /// Called when the attached GameObject has a Collider and leaves a + /// collision with another GameObject with a Collider2D. + /// + /// Information on the collision event. + virtual void onCollisionExit(CollisionInfo info); + private: /*-----------------------------------------------------------------------------*/ /* Data Members */ @@ -271,4 +361,4 @@ namespace SHADE GameObject owner; }; -} // namespace PlushieAPI +} diff --git a/SHADE_Managed/src/Scripts/ScriptStore.cxx b/SHADE_Managed/src/Scripts/ScriptStore.cxx index b6bc1815..407d0fa8 100644 --- a/SHADE_Managed/src/Scripts/ScriptStore.cxx +++ b/SHADE_Managed/src/Scripts/ScriptStore.cxx @@ -27,6 +27,9 @@ of DigiPen Institute of Technology is prohibited. #include "Script.hxx" #include "Engine/Entity.hxx" #include "Serialisation/ReflectionUtilities.hxx" +#include "Engine/Application.hxx" +#include "Physics/SHPhysicsSystemInterface.h" +#include "Physics/SHPhysicsUtils.h" namespace SHADE { @@ -70,7 +73,7 @@ namespace SHADE SAFE_NATIVE_CALL_BEGIN Script^ script; return AddScriptViaNameWithRef(entity, scriptName, script); - SAFE_NATIVE_CALL_END_N("SHADE.ScriptStore") + SAFE_NATIVE_CALL_END_N("SHADE_Managed.ScriptStore") return false; } @@ -300,7 +303,7 @@ namespace SHADE removeScript(script); } scriptList->Clear(); - SAFE_NATIVE_CALL_END_N("SHADE.ScriptStore") + SAFE_NATIVE_CALL_END_N("SHADE_Managed.ScriptStore") } void ScriptStore::RemoveAllScriptsImmediately(Entity entity, bool callOnDestroy) { @@ -325,7 +328,7 @@ namespace SHADE startList.Remove(script); } scriptList->Clear(); - SAFE_NATIVE_CALL_END_N("SHADE.ScriptStore") + SAFE_NATIVE_CALL_END_N("SHADE_Managed.ScriptStore") } /*---------------------------------------------------------------------------------*/ @@ -364,7 +367,7 @@ namespace SHADE startList.AddRange(%inactiveStartList); inactiveStartList.Clear(); - SAFE_NATIVE_CALL_END_N("SHADE.ScriptStore") + SAFE_NATIVE_CALL_END_N("SHADE_Managed.ScriptStore") } void ScriptStore::FrameCleanUp() { @@ -372,8 +375,11 @@ namespace SHADE // Clear the queue while (disposalQueue.Count > 0) { - Script^ script = disposalQueue.Dequeue(); - script->OnDestroy(); + Script^ script = disposalQueue.Dequeue(); + if (Application::IsPlaying) + { + script->OnDestroy(); + } auto entity = script->Owner.GetEntity(); auto scriptList = scripts[script->Owner.GetEntity()]; scriptList->Remove(script); @@ -382,13 +388,13 @@ namespace SHADE scripts.Remove(entity); } } - SAFE_NATIVE_CALL_END_N("SHADE.ScriptStore") + SAFE_NATIVE_CALL_END_N("SHADE_Managed.ScriptStore") } void ScriptStore::Exit() { SAFE_NATIVE_CALL_BEGIN // Run the deinit all scripts if needed - //if (Application::IsPlaying) + if (Application::IsPlaying) { Debug::Log("Running OnDestroy() for scripts."); for each (System::Collections::Generic::KeyValuePair entity in scripts) @@ -406,7 +412,7 @@ namespace SHADE startList.Clear(); disposalQueue.Clear(); scriptTypeList = nullptr; - SAFE_NATIVE_CALL_END_N("SHADE.ScriptStore") + SAFE_NATIVE_CALL_END_N("SHADE_Managed.ScriptStore") } /*---------------------------------------------------------------------------------*/ @@ -435,7 +441,7 @@ namespace SHADE script->FixedUpdate(); } } - SAFE_NATIVE_CALL_END_N("SHADE.ScriptStore") + SAFE_NATIVE_CALL_END_N("SHADE_Managed.ScriptStore") } void ScriptStore::ExecuteUpdate() { @@ -452,7 +458,7 @@ namespace SHADE script->Update(); } } - SAFE_NATIVE_CALL_END_N("SHADE.ScriptStore") + SAFE_NATIVE_CALL_END_N("SHADE_Managed.ScriptStore") } void ScriptStore::ExecuteLateUpdate() { @@ -469,7 +475,95 @@ namespace SHADE script->LateUpdate(); } } - SAFE_NATIVE_CALL_END_N("SHADE.ScriptStore") + SAFE_NATIVE_CALL_END_N("SHADE_Managed.ScriptStore") + } + + void ScriptStore::ExecuteCollisionFunctions() + { + SAFE_NATIVE_CALL_BEGIN + /* Collisions */ + const auto& collisions = SHPhysicsSystemInterface::GetCollisionInfo(); + for (const auto& collisionInfo : collisions) + { + auto entities = + { + std::make_pair(collisionInfo.GetEntityA(), collisionInfo.GetEntityB()), + std::make_pair(collisionInfo.GetEntityB(), collisionInfo.GetEntityA()) + }; + for (auto entity : entities) + { + // Don't bother if this object has no scripts or is inactive + if (!isEntityActive(entity.first) || !scripts.ContainsKey(entity.first)) + continue; + + // Construct the collision state object + CollisionInfo info; + info.GameObject = GameObject(entity.second); + + // Call all of the script's functions + auto entityScripts = scripts[entity.first]; + if (entityScripts->Count > 0) + { + for each (Script ^ script in entityScripts) + { + switch (collisionInfo.GetCollisionState()) + { + case SHCollisionEvent::State::ENTER: + script->OnCollisionEnter(info); + break; + case SHCollisionEvent::State::STAY: + script->OnCollisionStay(info); + break; + case SHCollisionEvent::State::EXIT: + script->OnCollisionExit(info); + break; + } + } + } + } + } + /* Triggers */ + const auto& triggers = SHPhysicsSystemInterface::GetTriggerInfo(); + for (const auto& triggerInfo : triggers) + { + auto entities = + { + std::make_pair(triggerInfo.GetEntityA(), triggerInfo.GetEntityB()), + std::make_pair(triggerInfo.GetEntityB(), triggerInfo.GetEntityA()) + }; + for (auto entity : entities) + { + // Don't bother if this object has no scripts or is inactive + if (!isEntityActive(entity.first) || !scripts.ContainsKey(entity.first)) + continue; + + // Construct the collision state object + CollisionInfo info; + info.GameObject = GameObject(entity.second); + + // Call all of the script's functions + auto entityScripts = scripts[entity.first]; + if (entityScripts->Count > 0) + { + for each (Script ^ script in entityScripts) + { + switch (triggerInfo.GetCollisionState()) + { + case SHCollisionEvent::State::ENTER: + script->OnTriggerEnter(info); + break; + case SHCollisionEvent::State::STAY: + script->OnTriggerStay(info); + break; + case SHCollisionEvent::State::EXIT: + script->OnTriggerExit(info); + break; + } + } + } + } + } + SAFE_NATIVE_CALL_END_N("SHADE_Managed.ScriptStore") } bool ScriptStore::SerialiseScripts(Entity entity, System::IntPtr yamlNodePtr) @@ -505,7 +599,7 @@ namespace SHADE } return true; - SAFE_NATIVE_CALL_END_N("SHADE.ScriptStore") + SAFE_NATIVE_CALL_END_N("SHADE_Managed.ScriptStore") return false; } @@ -555,7 +649,7 @@ namespace SHADE } return true; - SAFE_NATIVE_CALL_END_N("SHADE.ScriptStore") + SAFE_NATIVE_CALL_END_N("SHADE_Managed.ScriptStore") return false; } @@ -663,14 +757,10 @@ namespace SHADE bool ScriptStore::isEntityActive(Entity entity) { - // Get native Entity - SHEntity* nativeEntity = SHEntityManager::GetEntityByID(entity); - - // Entity Validity Check - if (nativeEntity == nullptr) + // Invalid entity + if (!EntityUtils::IsValid(entity)) return false; - // Check active state - return nativeEntity->GetActive(); + return GameObject(entity).IsActiveInHierarchy; } } diff --git a/SHADE_Managed/src/Scripts/ScriptStore.hxx b/SHADE_Managed/src/Scripts/ScriptStore.hxx index 9aa66fcd..a4c6e824 100644 --- a/SHADE_Managed/src/Scripts/ScriptStore.hxx +++ b/SHADE_Managed/src/Scripts/ScriptStore.hxx @@ -233,6 +233,10 @@ namespace SHADE /// Executes LateUpdate() for all scripts. /// static void ExecuteLateUpdate(); + /// + /// Executes OnCollision*() and OnTrigger*() for all scripts. + /// + static void ExecuteCollisionFunctions(); /*-----------------------------------------------------------------------------*/ /* Serialisation Functions */ diff --git a/SHADE_Managed/src/Serialisation/ReflectionUtilities.cxx b/SHADE_Managed/src/Serialisation/ReflectionUtilities.cxx index f114d01b..4b4e44fc 100644 --- a/SHADE_Managed/src/Serialisation/ReflectionUtilities.cxx +++ b/SHADE_Managed/src/Serialisation/ReflectionUtilities.cxx @@ -22,6 +22,7 @@ of DigiPen Institute of Technology is prohibited. #include "Math/Vector2.hxx" #include "Math/Vector3.hxx" #include "Utility/Debug.hxx" +#include "Engine/GameObject.hxx" /*-------------------------------------------------------------------------------------*/ /* Macro Functions */ @@ -167,6 +168,11 @@ namespace SHADE fieldNode.push_back(vec.y); fieldNode.push_back(vec.z); } + else if (fieldInfo->FieldType == GameObject::typeid) + { + GameObject gameObj = safe_cast(fieldInfo->GetValue(object)); + fieldNode = gameObj.GetEntity(); + } else // Not any of the supported types { Debug::LogWarning(Convert::ToNative(System::String::Format @@ -242,6 +248,10 @@ namespace SHADE ); } } + else if (fieldInfo->FieldType == GameObject::typeid) + { + fieldInfo->SetValue(object, GameObject(node.as())); + } else // Not any of the supported types { Debug::LogWarning(Convert::ToNative(System::String::Format diff --git a/TempScriptsFolder/CameraControl.cs b/TempScriptsFolder/CameraControl.cs new file mode 100644 index 00000000..fc900f46 --- /dev/null +++ b/TempScriptsFolder/CameraControl.cs @@ -0,0 +1,22 @@ +using System; +using SHADE; + +namespace SHADE_Scripting +{ + public class CameraControl :Script + { + public float turnSpeed = 0.5f; + + public CameraControl(GameObject go) : base(go) { } + protected override void update() + { + //Camera + Camera cam = GetComponent(); + Vector2 mouseVel = Input.GetMouseVelocity(); + + cam.Pitch -= mouseVel.y * turnSpeed * (float)Time.DeltaTime; + cam.Yaw += mouseVel.x * turnSpeed * (float)Time.DeltaTime; + + } + } +} diff --git a/TempScriptsFolder/PhysicsTest.cs b/TempScriptsFolder/PhysicsTest.cs index add5971d..cc01615d 100644 --- a/TempScriptsFolder/PhysicsTest.cs +++ b/TempScriptsFolder/PhysicsTest.cs @@ -38,6 +38,35 @@ public class PhysicsTest : Script RigidBody.AddForce(Force); Debug.Log($"Jump!"); } - Debug.Log($"{Transform.LocalPosition.y}"); + } + + protected override void fixedUpdate() + { + Debug.Log("Fixed Update"); + } + + protected override void onCollisionEnter(CollisionInfo info) + { + Debug.Log($"Collision Enter: {info.GameObject.Name}"); + } + protected override void onCollisionStay(CollisionInfo info) + { + Debug.Log($"Collision Stay: {info.GameObject.Name}"); + } + protected override void onCollisionExit(CollisionInfo info) + { + Debug.Log($"Collision Exit: {info.GameObject.Name}"); + } + protected override void onTriggerEnter(CollisionInfo info) + { + Debug.Log($"Trigger Enter: {info.GameObject.Name}"); + } + protected override void onTriggerStay(CollisionInfo info) + { + Debug.Log($"Trigger Stay: {info.GameObject.Name}"); + } + protected override void onTriggerExit(CollisionInfo info) + { + Debug.Log($"Trigger Exit: {info.GameObject.Name}"); } } \ No newline at end of file diff --git a/TempScriptsFolder/PrintWhenActive.cs b/TempScriptsFolder/PrintWhenActive.cs new file mode 100644 index 00000000..41afdd58 --- /dev/null +++ b/TempScriptsFolder/PrintWhenActive.cs @@ -0,0 +1,11 @@ +using SHADE; + +public class PrintWhenActive : Script +{ + public PrintWhenActive(GameObject gameObj) : base(gameObj) { } + + protected override void update() + { + Debug.Log("Active!"); + } +} \ No newline at end of file diff --git a/TempScriptsFolder/ThirdPersonCamera.cs b/TempScriptsFolder/ThirdPersonCamera.cs new file mode 100644 index 00000000..e3b043bd --- /dev/null +++ b/TempScriptsFolder/ThirdPersonCamera.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SHADE; + + +namespace SHADE_Scripting +{ + public class ThirdPersonCamera: Script + { + + public float armLength = 4.0f; + public float turnSpeedPitch = 0.3f; + public float turnSpeedYaw = 0.5f; + public float pitchClamp = 45.0f; + public ThirdPersonCamera(GameObject go) : base(go) { } + + protected override void awake() + { + if(!GetComponent()) + { + AddComponent(); + } + if (!GetComponent()) + { + AddComponent(); + } + GetComponent().ArmLength = armLength; + } + + protected override void update() + { + CameraArm arm = GetComponent(); + if(arm) + { + Vector2 vel = Input.GetMouseVelocity(); + arm.Pitch -= vel.y * turnSpeedPitch * Time.DeltaTimeF; + arm.Yaw += vel.x * turnSpeedYaw * Time.DeltaTimeF; + + if(arm.Pitch > pitchClamp) + { + arm.Pitch = pitchClamp; + } + else if(arm.Pitch < -pitchClamp) + { + arm.Pitch = -pitchClamp; + } + + } + } + + } +} diff --git a/TempShaderFolder/DeferredCompositeCs.glsl b/TempShaderFolder/DeferredCompositeCs.glsl deleted file mode 100644 index c1caf0aa..00000000 --- a/TempShaderFolder/DeferredCompositeCs.glsl +++ /dev/null @@ -1,83 +0,0 @@ -#version 450 - -struct DirectionalLightStruct -{ - vec3 direction; - uint isActive; - uint cullingMask; - vec4 diffuseColor; -}; - -struct AmbientLightStruct -{ - vec4 ambientColor; - float strength; - uint isActive; - uint cullingMask; -}; - -layout(local_size_x = 16, local_size_y = 16) in; -layout(set = 4, binding = 0, rgba32f) uniform image2D positions; -layout(set = 4, binding = 1, rgba32f) uniform image2D normals; -layout(set = 4, binding = 2, rgba8) uniform image2D albedo; -layout(set = 4, binding = 3, r32ui) uniform uimage2D lightLayerData; -layout(set = 4, binding = 4, rgba8) uniform image2D targetImage; - -layout(set = 1, binding = 0) uniform LightCounts -{ - uint directionalLights; - uint pointLights; - uint spotLights; - uint ambientLights; - -} lightCounts; - -layout(std430, set = 1, binding = 1) buffer DirectionalLightData -{ - DirectionalLightStruct dLightData[]; -} DirLightData; - -layout(std430, set = 1, binding = 4) buffer AmbientLightData -{ - AmbientLightStruct aLightData[]; -} AmbLightData; - -void main() -{ - // convenient variables - ivec2 globalThread = ivec2(gl_GlobalInvocationID); - - // Get the diffuse color of the pixel - vec3 pixelDiffuse = imageLoad (albedo, globalThread).rgb; - - // Get position of fragment in world space - vec3 positionWorld = imageLoad (positions, globalThread).rgb; - - // normal of fragment - vec3 normalWorld = imageLoad(normals, globalThread).rgb; - - vec3 fragColor = vec3 (0.0f); - - for (int i = 0; i < lightCounts.directionalLights; ++i) - { - // get normalized direction of light - vec3 dLightNormalized = normalize (DirLightData.dLightData[i].direction); - - // Get diffuse strength - float diffuseStrength = max (0, dot (dLightNormalized, normalWorld)); - - // Calculate the fragment color - fragColor += DirLightData.dLightData[i].diffuseColor.rgb * diffuseStrength.rrr * pixelDiffuse; - } - - for (int i = 0; i < lightCounts.ambientLights; ++i) - { - // Just do some add - //fragColor += pixelDiffuse.rgb * AmbLightData.aLightData[i].ambientColor.rgb * vec3 (0.5f); - fragColor += pixelDiffuse.rgb * AmbLightData.aLightData[i].ambientColor.rgb * vec3 (AmbLightData.aLightData[i].strength); - } - - // store result into result image - imageStore(targetImage, ivec2(gl_GlobalInvocationID.xy), vec4(fragColor, 1.0f)); - -} \ No newline at end of file diff --git a/TempShaderFolder/DeferredCompositeCs.spv b/TempShaderFolder/DeferredCompositeCs.spv deleted file mode 100644 index 03ef7ac5b615ad4dd42a57f4cad2daf5876ceb6a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4656 zcmZve33F6M5XT2Ln}i$W^Z+-+0|XJdM3EyVuml$pgRRMAbh0?@EGW8jzf0*+)^cT{ zJT_LY9G|Gp&Q5gFYe{_~iJSF_THLNz)A&jqzy824ZdQ}ITIf)eN0`5;+)I?Bk+deG z)-RX76?0QyI3dNw@dm|J8BHKl2$w0 zS8#j8<4i8PL*kXVF`W*#=9+0o74&DAVCP%aYDP)sLf&5eu!o+{w&G^$ErxRko!OSb z^6tz0x!GuDGOl-b1joi4s!@AjE~j^tO^t?OLco~x#LZP;1e z+9gvPI5o$eA%FW1acZv4B^r;$>8Nu#s~LZ4uI1Nd?Nd+t-3j3fYZ!^rNN|=5J1aj! zZsBfE3e&#qWabY(hHsunN2xa(>9q0`Tupd>PknAy@=(yfhiA@hGFyMUwQ_Fuaqf-< zmTWlZUf2)(Id|9(?u6M1^IQGI!p4e%lW{Ix33~!Gzw>$FY1D4i)6tozQP){}-2-6> zb5Mz{)!TXWvgVmLzfAOm2%Yz`Rn!yc1Clul_CfK`j*gv$o%a#i(XrE`ld6Q-X0eZD z7}NJuw%;(T&uYQX>RTt-{H(rB!pQfLIQ5l8 z_}Cm-eCh+U`k1G%K6L7{S(x|sP!H`t%g!u4Dk48KM?CXK$De#_bpp;XAPpUPy*#bn zMbbA)*B`kI!(NikEPz4yFU@fM(!!toV8q0qJ0%wQA+Iy@7Jrpwa^k;1zv*X5M6C7V z=oV{(-d4@}u*{Smf9&P7M5sIpFpGiwQ=|t>P?viHSZ4 zpk+Gmj¥*5B%csRCr(+Mm|)~V=M7n&Q(h(}{%6EF59hb@ zT##({c~LTZ$!qpW$%{nP$2+t8d01m1dso<~kN3knBOiaii3dh~=&8rB-|#Z^U}qNQ zMJ#6Ft~hy!VfS`VvU9hNqGS6}v|42PPm-yZdu7IXgZMz$n5kdH*^6Je$TJ|Kw)@_I zFSVgR@Yn%;JMd*jS@iEuAw_X~d6P>-^ctOa!vABTURt1UTcGoQl=(Azk6YFA+c#J-c%a3~2itxpDL?`E*VC3OV zKQ7`uqvOxtQG6z~pV`?W!Uudzonkhh6oEr5^3h-7(>LtI<8Gc3@wP4g(~`sZ&v+kj zi~p=-aEKMgFG2t-Rso9Llnl}DIFhhi~qc2aEKMg=U%aM7VdPnm$}cqqQ7*~ zed5dy{12V;fcQ%y7WRYU*x}U4eZ4Fq2KUJQPE)$IoN~GF%kH0@);6; zO~k%qqQB*XzF$Os@*!KkQOV>R(yg8ne_h14hWOYl5BFISVPCFF(NBx$3EwSj^n&>X zCq6#oA~4g>N~U-BRqHzOH$?b=FINp<=S0NCkMA}<#O5tvv)a!~w%RXBz9h2Rv0V`1 z%Y42m!fto_mdC(ZcDMLb!`mYAjr+5{<1ujPj_T)p?}~_p-Ol))Wais^-j|FYxcN*- zW^Qi#I3Gv`!`EgCj5%RuxHmZanUhGw*>7n-devi-;_Sx;7S18}kBx5#_lm79PHZ?c z+7O=>v9QPD*x{D@L&?Oj8NDnS%w{x^%#2$9nb8>$xXox&GW)=pQS>Ph`N@ZDy=qCO zpO$}4GWnTV?){1=6>%nPaD2Ja>~oLNb`m z1U9hn-sv~{H;La7&3k>B_?My;qA~UPuJ~6T1831YW}r{}YY}!k%Quoa3x9{`%eNvh pmSNvX1|yDP-+OGa__!i-hd+qek3aT%qN?&zFL|;5qbLVO{{oeIr1Jm( diff --git a/TempShaderFolder/TestCubeFs.spv b/TempShaderFolder/TestCubeFs.spv deleted file mode 100644 index 2381b8347c412e9f822330db717bd1f1e41c24b0..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2536 zcmZ9M-*Xg25XUFnU5Meg2#84BB#1xIh%q3FAi>1r@GMfsQs1^Vw?i_z**$mnQsmJ$ z{~-0nH~%VMtn&NWn+XeD)z{tM?&<07>AlXe<>SW8n0a%`d}F3`&KwhB4D!#{rt&W@ z|CXFLb7p(%hj{a+@8i@~qtcD*qKsXh+Gj4`H7Cq$bG|>^9F30hT_>}m(_>%a#ctiY1d{$?PRk6}Ks?3;wl&Gsy{b9WR-NU%DctqjRAQVZ`R*jywei~O&2cjNMS14PLrZy)PjdIPDEH%ECrRd> zI$O#=kH7!qNq@K*kH+J;st+?8XD+vK>Pp?@4lH*yd3>D9N7*E82lN!t?zv}rP2c09 zaZZIwS3&ld_} zZun-z)}=?W)R(#4y?U4&+Hx9APWEq*uPT49*~4N|Z|1eD4+k4UjyHSx!Z|l;hS%3U z>~feDHhbN+c@J#nfS>okW;d{T4|;@xy(pd9AL;gxYncF1!0>~eZDI5Wrcd`Mj(fo( zG5Oz;oE7t-k}Hygh=Ka5G?L^T@ze&l?M2xTvCQstqjwwqd9NL_BK!{(Lmc-7{o^CO z+svCYGh*)JKLDFv&g&PssPo*9eo-3rN8(G0=YIm5c}Du3lOz`WuD5w3FyiMWi6_^B z`sbS?792^Alakbfj~v*%E7%3u^c#8mhPThihB(ig5ZkVSJ)njV&l^!gsFA(Ee_0## zx+FD{qfNoSqR7i~5O-Dj8U z_f6lSYd(?=g&C|$CqHjWzB`h{hxfhbZTiLkm1IXuebj@!;W7N1(#hBMv!|T7tscqE z{y|{>3h7C%>z7?PCuV=xk$Z}yj#tIt_jQ8(#18Qnq!Z7Mg!qfn!HH*=u!(0@?~0jU z$j@Bf^Z2@MV_qMKm&C;2W1i$D_CqoLZEvr5jQq@&ZGcOz^R?L`%D~a#~1n}=jYxZ^4*pFa=tHwfs>E7zb_8? z@P#?E4_|u!mSV~Oz+>QnfA{^Y3*-I=;@>>>P&$3$2@1M5QW>;;t(f+5V8QlNH$BrV74R#LKfpiHYk>Y9kWMtq=_;x8tIJ2CgB&a z0FT5|@rQG`-^`RVC+$0I|u2<+FVU}x$iLQZO7Bp z$Nj+4%2&(!5XNaR43c%9dLb3JM4(n(mg$EaVbu(ymV?8m9BPTj$;d~XS;=~< z8l=~=9{)a0qQPF`Esnph#y=_5F`98T`|R6Frrd%qM9#_ah$9}j~VnrjvBxgedIuzAmU z$#P*c%lMfQ{LD2r3!53oX7;d|_p+a!V^be~z5{Ifv!$Bo6^k=jhQSA8H;foCYBdZU zEI+@J<+I$@uO<0eTVh$SYMK4CcW_>K2Gb8jhP8AeapdI=^mg$XyD6K6pFVR(YCEGS z;+nFs(a(xg*WQqDKWxszW-X{M^cxO%?yI`zq>}^Rb;V%wJ%TM4IjxTk*(ZdPpFHrf zd0#O6{DKjS-{Mb8$A4b_7qxRXHN!un9UnOPu$d1q;^Cf^u;8E5j?e0USvu!o+j*}_ zC%?sClupb!F&o+uYH1ca?~J`z*u>JWCGBv)b8gkWA)WK^Q7<<03wA;FTiW50lX~CQ zJ|h8#kIj68apt?)8xrE-FKfpK4j-HO2je~s?JE-J{=5bMvNU3w66~wm;Zig4*nBTw z_&?JQA3ycp)XrI8cHX9R<8K$fhIZ@cj&yo-QSm=&Z)7?>%YWON1%@y8SKZIjIfHML zbFl9h*n(`n1>)!vb^fBAGr-|vdkGl+2Ze5ZrB8e#Gm@)%J9xYSi*x@K!uNSYXkGg$ z33IzDl$qr_W$u~vn~K1OgP)l@FJUg3MRG827bM_tn8Q~jW9+oJYs5@ruRbN9IfzV!zij@|9LbnbRS zFT`EHkWe$Z@a+{nxFH=MccHdh5-?Urzhv~~wgenuk%zll%&K%^z%AxW>EH+pUpZz? zHZfopvo0MRVOdO9ci`LFkldD#8?L=uOZujS{!;Ij1TOfhV)^dAlF%<^fw`mhhW4)| z@L9|VJTQxEOSd>?&EoDzCypA4g9m1D9qAUgBi-V<(uw2V#K8lzIk+p`;<#T^_BRr6 z>(g$5fwQbnyfydVE3ggiaIL0$(k*wn2m8W_VNnx2FpK+Ey2X`y@SSiwi#T{-7WaKA zuH1tkia6^5JTQ9jKzm=}CCs+X^Ps@Z4rE`F{H++~`=JC5xXr~-dii^PBpZxn?-5D| sqlbq5T42;?-}7(MiHDEB{5?mqIUkO_<48Kc$@3C=gAMOLopep|Kcj>49{>OV diff --git a/bin/Debug/SHADE_CSharp.xml b/bin/Debug/SHADE_CSharp.xml new file mode 100644 index 00000000..daeaa3c5 --- /dev/null +++ b/bin/Debug/SHADE_CSharp.xml @@ -0,0 +1,1029 @@ + + + + SHADE_CSharp + + + + + Interface for a CallbackAction that all variants inherit from. + + + + + Whether or not this CallbackAction is runtime assigned. If it is, then the + TargetMethodName and TargetObject properties are invalid. + + + + + Name of the method that this CallbackAction is using. + + + + + Object which the specified target method is called on. + + + + + Represents a function call that can be serialised and put togetheer with scripts. + This variant accepts functions with 1 parameter. + + + + + + + + + + + + + + Constructs an empty Callback action. + + + + + Constructs a CallbackAction that represents a call to the specified static + method. + + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a CallbackAction that represents a call to a specified member + method on the specified target. + + Object to call the method on. + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a Callback action based on an action. + + Action that wraps a function to be called. + + + + Invokes the CallbackAction's stored method/action with the specified parameters. + + + + + Represents a function call that can be serialised and put togetheer with scripts. + This variant accepts functions with 2 parameters. + + + + + + + + + + + + + + Constructs an empty Callback action. + + + + + Constructs a CallbackAction that represents a call to the specified static + method. + + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a CallbackAction that represents a call to a specified member + method on the specified target. + + Object to call the method on. + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a Callback action based on an action. + + Action that wraps a function to be called. + + + + Invokes the CallbackAction's stored method/action with the specified parameters. + + + + + Represents a function call that can be serialised and put togetheer with scripts. + This variant accepts functions with 3 parameters. + + + + + + + + + + + + + + Constructs an empty Callback action. + + + + + Constructs a CallbackAction that represents a call to the specified static + method. + + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a CallbackAction that represents a call to a specified member + method on the specified target. + + Object to call the method on. + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a Callback action based on an action. + + Action that wraps a function to be called. + + + + Invokes the CallbackAction's stored method/action with the specified parameters. + + + + + Represents a function call that can be serialised and put togetheer with scripts. + This variant accepts functions with 4 parameters. + + + + + + + + + + + + + + Constructs an empty Callback action. + + + + + Constructs a CallbackAction that represents a call to the specified static + method. + + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a CallbackAction that represents a call to a specified member + method on the specified target. + + Object to call the method on. + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a Callback action based on an action. + + Action that wraps a function to be called. + + + + Invokes the CallbackAction's stored method/action with the specified parameters. + + + + + Represents a function call that can be serialised and put togetheer with scripts. + This variant accepts functions with 5 parameters. + + + + + + + + + + + + + + Constructs an empty Callback action. + + + + + Constructs a CallbackAction that represents a call to the specified static + method. + + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a CallbackAction that represents a call to a specified member + method on the specified target. + + Object to call the method on. + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a Callback action based on an action. + + Action that wraps a function to be called. + + + + Invokes the CallbackAction's stored method/action with the specified parameters. + + + + + Represents a function call that can be serialised and put togetheer with scripts. + This variant accepts functions with 6 parameters. + + + + + + + + + + + + + + Constructs an empty Callback action. + + + + + Constructs a CallbackAction that represents a call to the specified static + method. + + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a CallbackAction that represents a call to a specified member + method on the specified target. + + Object to call the method on. + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a Callback action based on an action. + + Action that wraps a function to be called. + + + + Invokes the CallbackAction's stored method/action with the specified parameters. + + + + + Represents a function call that can be serialised and put togetheer with scripts. + This variant accepts functions with 7 parameters. + + + + + + + + + + + + + + Constructs an empty Callback action. + + + + + Constructs a CallbackAction that represents a call to the specified static + method. + + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a CallbackAction that represents a call to a specified member + method on the specified target. + + Object to call the method on. + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a Callback action based on an action. + + Action that wraps a function to be called. + + + + Invokes the CallbackAction's stored method/action with the specified parameters. + + + + + Represents a function call that can be serialised and put togetheer with scripts. + This variant accepts functions with 8 parameters. + + + + + + + + + + + + + + Constructs an empty Callback action. + + + + + Constructs a CallbackAction that represents a call to the specified static + method. + + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a CallbackAction that represents a call to a specified member + method on the specified target. + + Object to call the method on. + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a Callback action based on an action. + + Action that wraps a function to be called. + + + + Invokes the CallbackAction's stored method/action with the specified parameters. + + + + + Represents a function call that can be serialised and put togetheer with scripts. + This variant accepts functions with 9 parameters. + + + + + + + + + + + + + + Constructs an empty Callback action. + + + + + Constructs a CallbackAction that represents a call to the specified static + method. + + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a CallbackAction that represents a call to a specified member + method on the specified target. + + Object to call the method on. + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a Callback action based on an action. + + Action that wraps a function to be called. + + + + Invokes the CallbackAction's stored method/action with the specified parameters. + + + + + Represents a function call that can be serialised and put togetheer with scripts. + This variant accepts functions with 10 parameters. + + + + + + + + + + + + + + Constructs an empty Callback action. + + + + + Constructs a CallbackAction that represents a call to the specified static + method. + + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a CallbackAction that represents a call to a specified member + method on the specified target. + + Object to call the method on. + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a Callback action based on an action. + + Action that wraps a function to be called. + + + + Invokes the CallbackAction's stored method/action with the specified parameters. + + + + + Interface for a CallbackEvent that all variants inherit from. + + + + + Registers an empty ICallbackAction. + + + + + Registers an ICallbackAction with the event such that it will be called in + future + + ICallbackAction to register with. + + + + Deregisters an ICallbackAction that was previously added. This should + only emit a warning if an action that was not previous added was + provided. + + ICallbackAction to remove. + + + + Iterable set of ICallbackActions that were registered to this event. + + + + + A container of CallbackActions that is correlated to a specific scenario as + specified by the user of this class. + This variant accepts CallbackEvents with 1 generic parameter. + + + + + + + + + + + + + + Adds a CallbackAction into the event. + + CallbackAction to add. + + + + Constructs and adds a CallbackACtion into the event. + + System.Action to add as a CallbackAction. + + + + Constructs and adds a CallbackACtion into the event. + + Object to call the method on. + Method to call. + + + + + + + Invokes all stored CallbackActions with the specified parameters. + + + + + A container of CallbackActions that is correlated to a specific scenario as + specified by the user of this class. + This variant accepts CallbackEvents with 1 generic parameter. + + + + + + + + + + + + + + Adds a CallbackAction into the event. + + CallbackAction to add. + + + + Constructs and adds a CallbackACtion into the event. + + System.Action to add as a CallbackAction. + + + + Constructs and adds a CallbackACtion into the event. + + Object to call the method on. + Method to call. + + + + + + + Invokes all stored CallbackActions with the specified parameters. + + + + + A container of CallbackActions that is correlated to a specific scenario as + specified by the user of this class. + This variant accepts CallbackEvents with 1 generic parameter. + + + + + + + + + + + + + + Adds a CallbackAction into the event. + + CallbackAction to add. + + + + Constructs and adds a CallbackACtion into the event. + + System.Action to add as a CallbackAction. + + + + Constructs and adds a CallbackACtion into the event. + + Object to call the method on. + Method to call. + + + + + + + Invokes all stored CallbackActions with the specified parameters. + + + + + A container of CallbackActions that is correlated to a specific scenario as + specified by the user of this class. + This variant accepts CallbackEvents with 1 generic parameter. + + + + + + + + + + + + + + Adds a CallbackAction into the event. + + CallbackAction to add. + + + + Constructs and adds a CallbackACtion into the event. + + System.Action to add as a CallbackAction. + + + + Constructs and adds a CallbackACtion into the event. + + Object to call the method on. + Method to call. + + + + + + + Invokes all stored CallbackActions with the specified parameters. + + + + + A container of CallbackActions that is correlated to a specific scenario as + specified by the user of this class. + This variant accepts CallbackEvents with 1 generic parameter. + + + + + + + + + + + + + + Adds a CallbackAction into the event. + + CallbackAction to add. + + + + Constructs and adds a CallbackACtion into the event. + + System.Action to add as a CallbackAction. + + + + Constructs and adds a CallbackACtion into the event. + + Object to call the method on. + Method to call. + + + + + + + Invokes all stored CallbackActions with the specified parameters. + + + + + A container of CallbackActions that is correlated to a specific scenario as + specified by the user of this class. + This variant accepts CallbackEvents with 1 generic parameter. + + + + + + + + + + + + + + Adds a CallbackAction into the event. + + CallbackAction to add. + + + + Constructs and adds a CallbackACtion into the event. + + System.Action to add as a CallbackAction. + + + + Constructs and adds a CallbackACtion into the event. + + Object to call the method on. + Method to call. + + + + + + + Invokes all stored CallbackActions with the specified parameters. + + + + + A container of CallbackActions that is correlated to a specific scenario as + specified by the user of this class. + This variant accepts CallbackEvents with 1 generic parameter. + + + + + + + + + + + + + + Adds a CallbackAction into the event. + + CallbackAction to add. + + + + Constructs and adds a CallbackACtion into the event. + + System.Action to add as a CallbackAction. + + + + Constructs and adds a CallbackACtion into the event. + + Object to call the method on. + Method to call. + + + + + + + Invokes all stored CallbackActions with the specified parameters. + + + + + A container of CallbackActions that is correlated to a specific scenario as + specified by the user of this class. + This variant accepts CallbackEvents with 1 generic parameter. + + + + + + + + + + + + + + Adds a CallbackAction into the event. + + CallbackAction to add. + + + + Constructs and adds a CallbackACtion into the event. + + System.Action to add as a CallbackAction. + + + + Constructs and adds a CallbackACtion into the event. + + Object to call the method on. + Method to call. + + + + + + + Invokes all stored CallbackActions with the specified parameters. + + + + + A container of CallbackActions that is correlated to a specific scenario as + specified by the user of this class. + This variant accepts CallbackEvents with 1 generic parameter. + + + + + + + + + + + + + + Adds a CallbackAction into the event. + + CallbackAction to add. + + + + Constructs and adds a CallbackACtion into the event. + + System.Action to add as a CallbackAction. + + + + Constructs and adds a CallbackACtion into the event. + + Object to call the method on. + Method to call. + + + + + + + Invokes all stored CallbackActions with the specified parameters. + + + + + A container of CallbackActions that is correlated to a specific scenario as + specified by the user of this class. + This variant accepts CallbackEvents with 1 generic parameter. + + + + + + + + + + + + + + Adds a CallbackAction into the event. + + CallbackAction to add. + + + + Constructs and adds a CallbackACtion into the event. + + System.Action to add as a CallbackAction. + + + + Constructs and adds a CallbackACtion into the event. + + Object to call the method on. + Method to call. + + + + + + + Invokes all stored CallbackActions with the specified parameters. + + + + diff --git a/bin/Debug/SHADE_Managed.xml b/bin/Debug/SHADE_Managed.xml new file mode 100644 index 00000000..7b653116 --- /dev/null +++ b/bin/Debug/SHADE_Managed.xml @@ -0,0 +1,6250 @@ + + + + "SHADE_Managed" + + + + +Retrieves the duration that the specified key has not been held or was last +not been held for. + + The key to check. + Time in seconds that the key was held. + + + +Retrieves the duration that the specified key has been held or was last held +for. + + The key to check. + Time in seconds that the key was held. + + + +Retrieves the duration that the specified key has not been held or was last +not been held for. + + The key to check. + Time in seconds that the key was held. + + + +Retrieves the duration that the specified key has been held or was last held +for. + + The key to check. + Time in seconds that the key was held. + + + +Sets the position of the mouse cursor relative to the top left corner of the +window. + + +Position of the mouse in window pixel coordinates to set. + + + + +Checks if a specified mouse button is no longer pressed and was pressed +before. + + MouseCode of the mouse button to check. + +True during the frame the user releases the given mouse button. + + + + +Checks if a specified mouse button is pressed and was not pressed before. + + MouseCode of the mouse button to check. + +True during the frame the user pressed the given mouse button. + + + + +Checks if a specified mouse button is being held down. +This will also be true if GetMouseButtonDown() is true. + + MouseCode of the mouse button to check. + True while the user holds down the mouse button specified. + + + +Checks if a specified key is no longer pressed pressed and was pressed +before. + + KeyCode of the key to check. + +True during the frame the user releases the key identified by name. + + + + +Checks if a specified key is pressed and was not pressed before. + + KeyCode of the key to check. + +True during the frame the user starts pressing down the key specified. + + + + +Checks if a specified key is being held down. +This will also be true if GetKeyDown() is true. + + KeyCode of the key to check. + True while the user holds down the key specified. + + + +Amnount of vertical mouse scroll in this frame. + + + + +Mouse position in screen coordinates relative to the top left of the window. +This value is a Vector3 for compatibility with functions that have Vector3 +arguments. The z component of the Vector3 is always 0 + + + + +Represents the available supported mouse keycodes that can be passed into the +mouse-button-based Input functions. + + + + +Represents the available supported keycodes that can be passed into the +key-based Input functions. + +Attempting to follow https://docs.unity3d.com/ScriptReference/KeyCode.html +Win32 keycodes are shift-insensitive, i.e. 'A' and 'a' are the same keycode and '1' and '!' are the same keycode + + + + +Static class responsible for providing access to Input-related functionality. + + + + +Simple attribute to mark that a field in a Script should be serialised. + + + + +Cleans up all required components for managed code. + + + + +Reloads the managed script assembly. +Take note that this will clear all existing scripts, ensure that the scene +is saved before doing so. +Equivalent to calling UnloadScriptAssembly() and then LoadScriptAssembly(). + + + + +Loads the managed script assembly. Ensure this is only called after +UnloadScriptAssembly() has been called. + + + + +Unloads the managed script assembly. +Take note that this will clear all existing scripts, ensure that the scene +is saved before doing so. + + + + +Initialises all required components for managed code. + + + + +Name of the Managed Library that contains the C# scripts written externally. + + + + +Static class that contains the functions for interfacing with the core +PlushieEngine written in C++ for managing the lifecycle of managed code. + + + + +Default Constructor + + + + +Custom AssemblyLoadContext marked as collectible so that it can be unloaded. + + + + +Time taken for Physics simulations. You should use this for operations +within Script.FixedUpdate() + + + + +Time taken to process the previous frame. + + + + +Static class that contains the functions for working with time. + + + + +Static class that wraps up certain functions in the SHPhysicsSystem so that +accessing it from SHADE_Managed would not cause issues due to C++20 features. + + + + +Constructor for a Tooltip attribute that fills in the description. + + Text to be shown when a field is hovered. + + + +Description that is to be shown in the Tooltip. + + + + +Simple attribute to provide a field in a script with a tooltip. + + + + +Checks if a specified file exists. + + File path to the file to check. + True if the file exists + + + +Deletes the folder and all files in it as specified by the file path. + + File path to the file to delete. + + + +Deletes the file as specified by the file path. + + File path to the file to delete. + + + +Reads the file via the specified path that represents a build log of error +and warning messages. + + +File path to the build log of script builds done by BuildScriptAssembly() to +dump and process. + + + + +Registers events for the scripting system + + + + +Loads all the function pointers to CLR code that we need to execute. + + + + +Generates a .csproj file for editing and compiling the C# scripts. + + File path to the generated file. + + + +Utilises execution of a external batch file for invoking the dotnet build +tool to compile C# scripts in the Assets folder into the SHADE_Scripting +C# assembly DLL. + + +Whether or not a debug build will be built. Only debug built C# assemblies +can be debugged. + + +Whether or not we are reloading the assembly, if so, unload and then reload it. + + Whether or not the build succeeded. + + + +Performs a redo for script inspector changes if it exists. + + + + +Performs an undo for script inspector changes if it exists. + + + + +Renders the set of attached Scripts for the specified Entity into the +inspector. +
+This function is meant for consumption from native code in the inspector +rendering code. +
+ The Entity to render the Scripts of. +
+ + +Creates scripts and sets fields for the specified Entity based on the specified +YAML node. + + The Entity to deserialise a Script on to. + +YAML Node that contains the serialised script data. + + True if successfully deserialised. + + + +Performs serialization of all scripts for the specified entity into the +YAML::Node specified. This node will contain all serialised scripts after +calling this function. + + The Entity to Serialise. + +YAML Node that will store the serialised scripts. + + True if successfully serialised. + + + +Removes all Scripts attached to the specified Entity. Unlike +RemoveAllScripts(), this removes all the scripts immediately. +Does not do anything if the specified Entity is invalid or does not have any +Scripts attached. + + The entity to remove the scripts from. + +Whether or not to call OnDestroy on the scripts. This is ignored if not in +play mode. + + + + +Removes all Scripts attached to the specified Entity. Does not do anything +if the specified Entity is invalid or does not have any Scripts +attached. + + The entity to remove the scripts from. + + + +Adds a Script to a specified Entity. Note that while you can call this +multiple times on a specified Entity, it will work for all intents and +purposes but GetScript<T>() (C# only) currently only +gives you the first Script added of the specified type. + + The entity to add a script to. + Type name of the script to add. + +True if successfully added. False otherwise with the error logged to the +console. + + + + +Shuts down the DotNetRuntime. + + + + +Executes the OnCollision*()s and OnTrigger*()s of the Scripts that are attached +to Entities. + + + + +Executes the FixedUpdate()s of the Scripts that are attached to +Entities. + + + + +Reloads the managed script assembly. +Take note that this will clear all existing scripts, ensure that the scene +is saved before doing so. + + + + +Unloads the managed script assembly. +Take note that this will clear all existing scripts, ensure that the scene +is saved before doing so. + + + + +Loads the managed script assembly. Ensure this is only called after +UnloadScriptAssembly() has been called. + + + + +Initialises the DotNetRuntime and retrieves function pointers to all +functions on the CLR used to interface with the engine. + + + + +Manages initialisation of the DotNetRuntime and interfacing with CLR code written +and executed on .NET. + + + + +Deserialises a YAML node that contains a map of Scripts and copies the +deserialised data into the specified object if there are matching fields. + + +The JSON string that contains the data to copy into this Script object. + + The object to copy deserialised data into. + + + +Creates a JSON node that represents the specified object and its associated +serialisable fields. Public fields and fields marked with the SerialiseField +attribute will be serialised. + + The object to serialise. + + + +Checks if a specified field is a candidate for serialisation. This means that +the field is public or private with the [SerialiseField] attribute. + + The field to check. + +True if the specified field is a candidate for serialisation. + + + + +Retrieves a set of all non-static (instance) fields from a specified object. + + The object to get non-static fields from. + Immutable list of non-static fields. + + + +Contains useful static functions for working with Reflection. + + + +Converts the node to a YAML string. + + +Emits the node to the given output stream. + + +Emits the node to the given {@link Emitter}. If there is an error in writing, +{@link Emitter#good} will return false. + + + + Loads the input file as a list of YAML documents. + + @throws {@link ParserException} if it is malformed. + @throws {@link BadFile} if the file cannot be loaded. + + + + Loads the input stream as a list of YAML documents. + + @throws {@link ParserException} if it is malformed. + + + + Loads the input string as a list of YAML documents. + + @throws {@link ParserException} if it is malformed. + + + + Loads the input string as a list of YAML documents. + + @throws {@link ParserException} if it is malformed. + + + + Loads the input file as a single YAML document. + + @throws {@link ParserException} if it is malformed. + @throws {@link BadFile} if the file cannot be loaded. + + + + Loads the input stream as a single YAML document. + + @throws {@link ParserException} if it is malformed. + + + + Loads the input string as a single YAML document. + + @throws {@link ParserException} if it is malformed. + + + + Loads the input string as a single YAML document. + + @throws {@link ParserException} if it is malformed. + + + +Handles a "TAG" directive, which should be of the form 'handle prefix', +where 'handle' is converted to 'prefix' in the file. + + + +Handles a "YAML" directive, which should be of the form 'major.minor' (like +a version number). + + + +Reads any directives that are next in the queue, setting the internal +{@code m_pDirectives} state. + + + + Handles the next document by calling events on the {@code eventHandler}. + + @throw a ParserException on error. + @return false if there are no more documents + + + +Resets the parser with the given input stream. Any existing state is +erased. + + + +Evaluates to true if the parser has some valid input to be read. + + +Constructs a parser from the given input stream. The input stream must +live as long as the parser. + + + +Constructs an empty parser (with no input. + + +A parser turns a stream of bytes into one stream of "events" per YAML +document in the input stream. + + + + +Renders a context menu when right clicked for the scripts + + The Entity to render the Scripts of. + The Script to render the inspector for. + + + +Renders a field specified into the inspector. + + The field to render. + +The object that contains the data of the field to render. + + + + +Renders a single specified Script's inspector. + + The Entity to render the Scripts of. + The Script to render the inspector for. + +Indices used internally to differentiate each rendered Script +inspector. This is required to open and close each Script's inspector +independently from each other. + + + + +Redoes the last script inspector change if there is any. + + + + +Undoes the last script inspector change if there is any. + + + + +Renders a dropdown button that allows for the addition of PlushieScripts +onto the specified Entity. + + The Entity to add PlushieScripts to. + + + +Renders the set of attached Scripts for the specified Entity into the +inspector. +
+This function is meant for consumption from native code in the inspector +rendering code. +
+ The Entity to render the Scripts of. +
+ + +Static class for Editor-related functions + + + + +Processes a YAML node that contains a list of multiple scripts to be loaded +into the specified Entity. +

+This function should only be called from native unmanaged code. +
+ +The Entity to attach the deserialised Scripts to. + + +Pointer to the YAML::Node that contains serialized script data. + + +
+ + +Populates a YAML node with the scripts for a specified Entity. +

+This function should only be called from native unmanaged code. +
+ The Entity to Serialise. + +Pointer to a YAML::Node that will be populated with all of the serialised +scripts and their associated fields. + + +True if serialisation is successful. False if the buffer is too small for +the serialised output. + +
+ + +Executes OnCollision*() and OnTrigger*() for all scripts. + + + + +Executes LateUpdate() for all scripts. + + + + +Executes Update() for all scripts. + + + + +Executes FixedUpdate() for all scripts. + + + + +Retrieves a immutable list of available scripts that can be added. + + Immutable list of available scripts that can be added. + + + +Cleans up data stored in the ScriptStore to free up memory for garbage +collection. + + + + +Cleans up scripts that were marked for deletion. This calls the OnDestroy() +for these Scripts. + + + + +Sets up scripts that were marked for initialization. This calls the Awake() +and Start() for Scripts that have yet to have done so. + + + + +Initializes the ScriptStore to allocate and pre-populate reflection data. + + + + +Removes all Scripts attached to the specified Entity. Unlike +RemoveAllScripts(), this removes all the scripts immediately. +Does not do anything if the specified Entity is invalid or does not have any +Scripts attached. + + The entity to remove the scripts from. + +Whether or not to call OnDestroy on the scripts.This is ignored if not in +play mode. + + + + +Removes all Scripts attached to the specified Entity. Does not do anything +if the specified Entity is invalid or does not have any Scripts +attached. + + The entity to remove the scripts from. + + + +Removes a specific script from the + + The entity to remove the script from. + The script to remove. + True if successfully removed. False otherwise. + + + +Removes all Scripts of the specified type from the specified Entity. + + +Type of script to remove. +This needs to be a default constructable Script. + + The entity to remove the script from. + +If the specified Entity is invalid. + + + + +Retrieves an immutable list of all scripts attached to a specified Entity. + + +The entity which the scripts to retrieve are attached. + + +Immutable list of references to scripts attached to the specified Entity. +This can also be null if there are no scripts at all or an invalid Entity +was specified. + + + + +Retrieves a immutable list of scripts from the specified Entity that +matches the specified type. +
+Note that this function allocates. It should be used sparingly. +
+ +Type of scripts to get. +This needs to be a default constructable Script. + + +The entity which the scripts to retrieve are attached. + + +Immutable list of references to scripts of the specified type. + +
+ + +Retrieves the first Script from the specified Entity's children that matches +the specified type. + + +Type of script to get. +This needs to be a default constructable Script. + + +The entity which the script to retrieve is attached. + + +Reference to the script. This can be null if no script of the specified +type is attached. + + +If the specified Entity is invalid. + + + + +Retrieves the first Script from the specified Entity that matches the +specified type. + + +Type of script to get. +This needs to be a default constructable Script. + + +The entity which the script to retrieve is attached. + + +Reference to the script. This can be null if no script of the specified +type is attached. + + +If the specified Entity is invalid. + + + + +Adds a Script to a specified Entity. +
+This function is meant for consumption from native code or for serialisation +purposes. If you are writing in C# or C++/CLI and not doing serialisation, +use AddScript<T>() instead as it is faster. +
+ The entity to add a script to. + The entity to add a script to. + +Out parameter handle to the Script that was created. + + +True if successfully added. False otherwise with the error logged to the +console. + +
+ + +Adds a Script to a specified Entity. +
+This function is meant for consumption from native code. If you are writing +in C# or C++/CLI, use AddScript<T>() instead as it is faster. +
+ The entity to add a script to. + The entity to add a script to. + +True if successfully added. False otherwise with the error logged to the +console. + +
+ + +Adds a Script to a specified Entity. + + +Type of script to add. +This needs to be a default constructable PlushieScript. + + The entity to add a script to. + Reference to the script added. + +If the specified Entity is invalid. + + + + +Responsible for managing all scripts attached to Entities as well as executing +all lifecycle functions of scripts. + + + + +Checks if two Colors are not approximately equal. + + Color to compare. + Another Color to compare. + +True if all components are not approximately equal within the default +tolerance value. + + + + +Checks if two Colors are approximately equal. + + Color to compare. + Another Color to compare. + +True if all components are approximately equal within the default +tolerance value. + + + + +Calculates the division of a Color with a scalar value and returns +the result. + + Scalar to divide with. + Color to divide with. + The result of the scalar division. + + + +Calculates the multiplication of a Color with a scalar value and returns +the result. + + Color to multiply with. + Scalar to multiply with. + The result of the scalar multiplication. + + + +Calculates the component-wise multiplication of two Colors and returns the +result. + + Color to multiply with. + Another Color to multiply with. + The result of rhs subtracted from lhs. + + + +Subtracts a Color from another Color and returns the result. + + Color to subtract from. + Another Color to subtract. + The result of rhs subtracted from lhs. + + + +Adds two Colors together and returns the result. + + Color to add. + Another Color to add. + The result of lhs added to rhs + + + +Linearly interpolates between two specified points. +This is most commonly used to find a point some fraction of the way along a +line between two endpoints. +Unlike Lerp(), t is not clamped to a range at all. + + The start Color, returned when t = 0.0. + The end Color, returned when t = 1.0. + Value used to interpolate between a and b. + The interpolated Color. + + + +Linearly interpolates between two specified points. +This is most commonly used to find a point some fraction of the way along a +line between two endpoints. + + The start Color, returned when t = 0.0. + The end Color, returned when t = 1.0. + +Value used to interpolate between a and b which is clamped to +the range[0, 1]. + + The interpolated Vector3. + + + +Gets a unique hash for this object. + + Unique hash for this object. + + + +Compares equality with another unboxed object. + + The unboxed object to compare with. + True if both objects are the same. + + + +Compares equality with an object of the same type. + + The object to compare with. + True if both objects are the same. + + + +Alpha component of the colour. Ranges from 0.0f to 1.0f. + + + + +Blue component of the colour. Ranges from 0.0f to 1.0f. + + + + +Green component of the colour. Ranges from 0.0f to 1.0f. + + + + +Red component of the colour. Ranges from 0.0f to 1.0f. + + + + +Constructor to construct a Color with the specified components. + + Red component to set. + Green component to set. + Blue component to set. + Alpha component to set. + + + +Constructor to construct a Color with the specified components with the +alpha component set to 1.0f. + + Red component to set. + Green component to set. + Blue component to set. + + + +Constructor to construct a Color with the specified components with the +blue and alpha component set to 1.0f. + + Red component to set. + Green component to set. + + + +Constructor to construct a Color with the specified components with the +green, blue and alpha component set to 1.0f. + + Red component to set. + + + +Pure yellow, mix of pure red and green. + + + + +Pure magenta, mix of pure red and blue. + + + + +Pure cyan, mix of pure green and blue. + + + + +Pure blue. + + + + +Pure green. + + + + +Pure red. + + + + +Pure white. + + + + +Dark Gray, darker than gray. + + + + +Gray, halfway between black and white. + + + + +Light Gray, lighter than gray. + + + + +Pure black. + + + + +A static class that contains a set of default Colors. + + + + +CLR version of the the SHADE Engine's Color struct which describes a Color +encoded using floating point numbers that range from 0.0f to 1.0f. + + + + +Creates a inline button widget. +
+Wraps up ImGui::Button(). +
+ Text to display. + True if button was pressed. +
+ + +Creates a small inline button widget. +
+Wraps up ImGui::SmallButton(). +
+ Text to display. + True if button was pressed. +
+ + +Creates a visual text widget. +
+Wraps up ImGui::Text(). +
+ Text to display. +
+ + +Creates a menu item in the list of items for a mini popup. +
+Wraps up ImGui::MenuItem(). +
+ Label used to identify this widget. + Whether or not the menu item was selected. +
+ + +Opens the popup that was defined with the specified label. +
+Wraps up ImGui::OpenPopup(). +
+
+ + +Marks the end of a definition of a mini pop up that can show options. +
+Wraps up ImGui::EndPopup(). +
+
+ + +Marks the start of a definition of a mini pop up that can show options. +
+Wraps up ImGui::BeginPopup(). +
+ Label used to identify this widget. + Whether or not the pop up is open. +
+ + +Creates a collapsing title header. +
+Wraps up ImGui::CollapsingHeader(). +
+ Label for the header. + True if the header is open, false otherwise. +
+ + +Unindents the widgets rendered after this call. +
+Wraps up ImGui::Unindent(). +
+
+ + +Indents the widgets rendered after this call. +
+Wraps up ImGui::Indent(). +
+
+ + +Marks the end of a stack of ImGui widgets from the last PushID() call. +
+Wraps up ImGui::PopID(). +
+
+ + +Marks the start of a stack of ImGui widgets with the specified id. +
+Wraps up ImGui::PushID(). +
+ Integer-based ID. +
+ + +Marks the start of a stack of ImGui widgets with the specified id. +
+Wraps up ImGui::PushID(). +
+ String-based ID. +
+ + +Maximum length of a string supported by InputTextField() + + + + +Static class that contains useful functions for Editor UI using ImGui. + + + + +Redoes the last undo-ed command if it exists. + + + + +Undos the last added command if it exists. + + + + +Adds a command onto the stack. + + + + + +True if there is a redoable action in the stack. + + + + +True if there is an undoable action in the stack. + + + + +Command for the stack that represents a data modification. + + + + +Class that is able to store a stack of actions that can be done and redone. + + + + +To be called from native code when a Collision Shape has been changed. + + +The entity which has it's collision shape changed. + + + + +To be called from native code when a collision shape has been removed. + + The entity which has it's collision shape removed. + + + +Retrieves a ColliderBound at the specified index in the ColliderBound list +and casts it to the appropriate type. + + Type of the ColliderBound to cast to. + Index to retrieve a ColliderBound from. + ColliderBound for the specified index. + + + +Retrieves a ColliderBound at the specified index in the ColliderBound list. + + Index to retrieve a ColliderBound from. + ColliderBound for the specified index. + + + +Total number of ColliderShapes in the Collider component. + + + + +Constructs a Collider Component that represents a native SHColliderComponent +component tied to the specified Entity. + + Entity that this Component will be tied to. + + + +CLR version of the the SHADE Engine's SHColliderComponent. +A single Collider component can contain one or multiple Collider Bounds. + + + + + + + + + + +Radius of the Bounding Sphere formed by this bound. + + + + +Center of the Bounding Sphere formed by this bound. + + + + +Sphere-shaped Collider Bound. + + + + + + + + + + +Position of the top right front corner of the Bounding Box formed by this +bound. + + + + +Position of the bottom left back corner of the Bounding Box formed by this +bound. + + + + +Half of the scale of the Bounding Box formed by this bound. + + + + +Center of the Bounding Box formed by this bound. + + + + +Box-shaped Collider Bound. + + + + +Computes a Raycast and checks if there is a collision with any object. + + The ray to cast. + Maximum distance for the raycast check. + True if the ray intersects with an object in the scene. + + + +Checks if the specified point is within this shape's bounds. + + Point to test with. + True if the point is in the shape's bounds. + + + +Base interface for all Collider Shapes. + + + +@brief The density of the collider that determines the mass of the collision shape + if it is automatically computed. Must be a positive number. + + + +@brief The bounciness factor of the physics object., clamped between [0,1].
+ 0 means the object will never bounce. + 1 means the object never loses energy on a bounce. + +
+ +@brief The friction coefficient of the physics object., clamped between [0,1].
+ 0 means the object will never experience friction. + 1 means the friction force against the object is equal to the applied force. + +
+ +@brief Sets the mass density of the physics material. +@param newDensity The density value to set. Always made positive. + + + +@brief Sets the bounciness factor of the physics material. +@param newBounciness The bounciness value to set. Clamped between [0,1]. + + + +@brief Sets the friction coefficient of the physics material. +@param newFriction The friction value to set. Clamped between [0,1]. + + + +@brief Default constructor for a physics material. +@param friction The friction of the material. Clamped between [0,1]. Defaults to 0.4. +@param bounciness The bounciness of the material. Clamped between [0,1]. +@param density The mass density of the material. Always made positive. + + + + +Closes the current window, and depending on the implementation, should also +close the application. + + + + +Retrieves the current window fullscreen status. + + The current window fullscreen status.. + + + +Retrieves the current window height. + + The current window height. + + + +Retrieves the current window width. + + The current window width. + + + +Static class that wraps up certain functions in the SHGraphicsSystem so that +accessing it from SHADE_Managed would not cause issues due to C++20 features. + + + + @brief Perform ImGui and ImGui Backend Render + + + + + @brief Start new frame for editor + + + + + @brief Initialise Backend for ImGui (SDL and Vulkan backend) + + @param sdlWindow Pointer to SDL_Window + + + + @brief Set the Style for the editor + + @param style Desired style + + + + @brief Safely shutdown the editor + + + + + @brief Update the editor and add to ImGui DrawList + + @param dt Delta-time of the frame + + + + @brief Initialise the editor + + @param sdlWindow pointer to SDL_Window object created in application + + + + @brief Style options + + + + + @brief SHEditor static class contains editor variables and implementation of editor functions. + + + + + Get the YUV conversion mode, returning the correct mode for the resolution + when the current conversion mode is SDL_YUV_CONVERSION_AUTOMATIC + + \since This function is available since SDL 2.0.8. + + + + Get the YUV conversion mode + + \since This function is available since SDL 2.0.8. + + + + Set the YUV conversion mode + + \since This function is available since SDL 2.0.8. + + + + Perform low-level surface scaled blitting only. + + This is a semi-private function and it performs low-level surface blitting, + assuming the input rectangles have already been clipped. + + \param src the SDL_Surface structure to be copied from + \param srcrect the SDL_Rect structure representing the rectangle to be + copied + \param dst the SDL_Surface structure that is the blit target + \param dstrect the SDL_Rect structure representing the rectangle that is + copied into + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_BlitScaled + + + + Perform a scaled surface copy to a destination surface. + + SDL_UpperBlitScaled() has been replaced by SDL_BlitScaled(), which is + merely a macro for this function with a less confusing name. + + \since This function is available since SDL 2.0.0. + + \sa SDL_BlitScaled + + + + Perform bilinear scaling between two surfaces of the same format, 32BPP. + + \since This function is available since SDL 2.0.16. + + + + Perform a fast, low quality, stretch blit between two surfaces of the same + format. + + Please use SDL_BlitScaled() instead. + + \since This function is available since SDL 2.0.0. + + + + Perform low-level surface blitting only. + + This is a semi-private blit function and it performs low-level surface + blitting, assuming the input rectangles have already been clipped. + + Unless you know what you're doing, you should be using SDL_BlitSurface() + instead. + + \param src the SDL_Surface structure to be copied from + \param srcrect the SDL_Rect structure representing the rectangle to be + copied, or NULL to copy the entire surface + \param dst the SDL_Surface structure that is the blit target + \param dstrect the SDL_Rect structure representing the rectangle that is + copied into + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_BlitSurface + + + + * Performs a fast blit from the source surface to the destination surface. + * + * This assumes that the source and destination rectangles are + * the same size. If either \c srcrect or \c dstrect are NULL, the entire + * surface (\c src or \c dst) is copied. The final blit rectangles are saved + * in \c srcrect and \c dstrect after all clipping is performed. + * + * \returns 0 if the blit is successful, otherwise it returns -1. + * + * The blit function should not be called on a locked surface. + * + * The blit semantics for surfaces with and without blending and colorkey + * are defined as follows: + * \verbatim + RGBA->RGB: + Source surface blend mode set to SDL_BLENDMODE_BLEND: + alpha-blend (using the source alpha-channel and per-surface alpha) + SDL_SRCCOLORKEY ignored. + Source surface blend mode set to SDL_BLENDMODE_NONE: + copy RGB. + if SDL_SRCCOLORKEY set, only copy the pixels matching the + RGB values of the source color key, ignoring alpha in the + comparison. + + RGB->RGBA: + Source surface blend mode set to SDL_BLENDMODE_BLEND: + alpha-blend (using the source per-surface alpha) + Source surface blend mode set to SDL_BLENDMODE_NONE: + copy RGB, set destination alpha to source per-surface alpha value. + both: + if SDL_SRCCOLORKEY set, only copy the pixels matching the + source color key. + + RGBA->RGBA: + Source surface blend mode set to SDL_BLENDMODE_BLEND: + alpha-blend (using the source alpha-channel and per-surface alpha) + SDL_SRCCOLORKEY ignored. + Source surface blend mode set to SDL_BLENDMODE_NONE: + copy all of RGBA to the destination. + if SDL_SRCCOLORKEY set, only copy the pixels matching the + RGB values of the source color key, ignoring alpha in the + comparison. + + RGB->RGB: + Source surface blend mode set to SDL_BLENDMODE_BLEND: + alpha-blend (using the source per-surface alpha) + Source surface blend mode set to SDL_BLENDMODE_NONE: + copy RGB. + both: + if SDL_SRCCOLORKEY set, only copy the pixels matching the + source color key. + \endverbatim + * + * You should call SDL_BlitSurface() unless you know exactly how SDL + * blitting works internally and how to use the other blit functions. + + Perform a fast blit from the source surface to the destination surface. + + SDL_UpperBlit() has been replaced by SDL_BlitSurface(), which is merely a + macro for this function with a less confusing name. + + \since This function is available since SDL 2.0.0. + + \sa SDL_BlitSurface + + + + Perform a fast fill of a set of rectangles with a specific color. + + `color` should be a pixel of the format used by the surface, and can be + generated by SDL_MapRGB() or SDL_MapRGBA(). If the color value contains an + alpha component then the destination is simply filled with that alpha + information, no blending takes place. + + If there is a clip rectangle set on the destination (set via + SDL_SetClipRect()), then this function will fill based on the intersection + of the clip rectangle and `rect`. + + \param dst the SDL_Surface structure that is the drawing target + \param rects an array of SDL_Rects representing the rectangles to fill. + \param count the number of rectangles in the array + \param color the color to fill with + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_FillRect + + + + Perform a fast fill of a rectangle with a specific color. + + `color` should be a pixel of the format used by the surface, and can be + generated by SDL_MapRGB() or SDL_MapRGBA(). If the color value contains an + alpha component then the destination is simply filled with that alpha + information, no blending takes place. + + If there is a clip rectangle set on the destination (set via + SDL_SetClipRect()), then this function will fill based on the intersection + of the clip rectangle and `rect`. + + \param dst the SDL_Surface structure that is the drawing target + \param rect the SDL_Rect structure representing the rectangle to fill, or + NULL to fill the entire surface + \param color the color to fill with + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_FillRects + + + + Premultiply the alpha on a block of pixels. + + This is safe to use with src == dst, but not for other overlapping areas. + + This function is currently only implemented for SDL_PIXELFORMAT_ARGB8888. + + \param width the width of the block to convert, in pixels + \param height the height of the block to convert, in pixels + \param src_format an SDL_PixelFormatEnum value of the `src` pixels format + \param src a pointer to the source pixels + \param src_pitch the pitch of the source pixels, in bytes + \param dst_format an SDL_PixelFormatEnum value of the `dst` pixels format + \param dst a pointer to be filled in with premultiplied pixel data + \param dst_pitch the pitch of the destination pixels, in bytes + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.18. + + + + Copy a block of pixels of one format to another format. + + \param width the width of the block to copy, in pixels + \param height the height of the block to copy, in pixels + \param src_format an SDL_PixelFormatEnum value of the `src` pixels format + \param src a pointer to the source pixels + \param src_pitch the pitch of the source pixels, in bytes + \param dst_format an SDL_PixelFormatEnum value of the `dst` pixels format + \param dst a pointer to be filled in with new pixel data + \param dst_pitch the pitch of the destination pixels, in bytes + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + + + Copy an existing surface to a new surface of the specified format enum. + + This function operates just like SDL_ConvertSurface(), but accepts an + SDL_PixelFormatEnum value instead of an SDL_PixelFormat structure. As such, + it might be easier to call but it doesn't have access to palette + information for the destination surface, in case that would be important. + + \param src the existing SDL_Surface structure to convert + \param pixel_format the SDL_PixelFormatEnum that the new surface is + optimized for + \param flags the flags are unused and should be set to 0; this is a + leftover from SDL 1.2's API + \returns the new SDL_Surface structure that is created or NULL if it fails; + call SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_AllocFormat + \sa SDL_ConvertSurface + \sa SDL_CreateRGBSurface + + + + Copy an existing surface to a new surface of the specified format. + + This function is used to optimize images for faster *repeat* blitting. This + is accomplished by converting the original and storing the result as a new + surface. The new, optimized surface can then be used as the source for + future blits, making them faster. + + \param src the existing SDL_Surface structure to convert + \param fmt the SDL_PixelFormat structure that the new surface is optimized + for + \param flags the flags are unused and should be set to 0; this is a + leftover from SDL 1.2's API + \returns the new SDL_Surface structure that is created or NULL if it fails; + call SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_AllocFormat + \sa SDL_ConvertSurfaceFormat + \sa SDL_CreateRGBSurface + + + + Get the clipping rectangle for a surface. + + When `surface` is the destination of a blit, only the area within the clip + rectangle is drawn into. + + \param surface the SDL_Surface structure representing the surface to be + clipped + \param rect an SDL_Rect structure filled in with the clipping rectangle for + the surface + + \since This function is available since SDL 2.0.0. + + \sa SDL_BlitSurface + \sa SDL_SetClipRect + + + + Set the clipping rectangle for a surface. + + When `surface` is the destination of a blit, only the area within the clip + rectangle is drawn into. + + Note that blits are automatically clipped to the edges of the source and + destination surfaces. + + \param surface the SDL_Surface structure to be clipped + \param rect the SDL_Rect structure representing the clipping rectangle, or + NULL to disable clipping + \returns SDL_TRUE if the rectangle intersects the surface, otherwise + SDL_FALSE and blits will be completely clipped. + + \since This function is available since SDL 2.0.0. + + \sa SDL_BlitSurface + \sa SDL_GetClipRect + + + + Get the blend mode used for blit operations. + + \param surface the SDL_Surface structure to query + \param blendMode a pointer filled in with the current SDL_BlendMode + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_SetSurfaceBlendMode + + + + Set the blend mode used for blit operations. + + To copy a surface to another surface (or texture) without blending with the + existing data, the blendmode of the SOURCE surface should be set to + `SDL_BLENDMODE_NONE`. + + \param surface the SDL_Surface structure to update + \param blendMode the SDL_BlendMode to use for blit blending + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_GetSurfaceBlendMode + + + + Get the additional alpha value used in blit operations. + + \param surface the SDL_Surface structure to query + \param alpha a pointer filled in with the current alpha value + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_GetSurfaceColorMod + \sa SDL_SetSurfaceAlphaMod + + + + Set an additional alpha value used in blit operations. + + When this surface is blitted, during the blit operation the source alpha + value is modulated by this alpha value according to the following formula: + + `srcA = srcA * (alpha / 255)` + + \param surface the SDL_Surface structure to update + \param alpha the alpha value multiplied into blit operations + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_GetSurfaceAlphaMod + \sa SDL_SetSurfaceColorMod + + + + Get the additional color value multiplied into blit operations. + + \param surface the SDL_Surface structure to query + \param r a pointer filled in with the current red color value + \param g a pointer filled in with the current green color value + \param b a pointer filled in with the current blue color value + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_GetSurfaceAlphaMod + \sa SDL_SetSurfaceColorMod + + + + Set an additional color value multiplied into blit operations. + + When this surface is blitted, during the blit operation each source color + channel is modulated by the appropriate color value according to the + following formula: + + `srcC = srcC * (color / 255)` + + \param surface the SDL_Surface structure to update + \param r the red color value multiplied into blit operations + \param g the green color value multiplied into blit operations + \param b the blue color value multiplied into blit operations + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_GetSurfaceColorMod + \sa SDL_SetSurfaceAlphaMod + + + + Get the color key (transparent pixel) for a surface. + + The color key is a pixel of the format used by the surface, as generated by + SDL_MapRGB(). + + If the surface doesn't have color key enabled this function returns -1. + + \param surface the SDL_Surface structure to query + \param key a pointer filled in with the transparent pixel + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_BlitSurface + \sa SDL_SetColorKey + + + + Returns whether the surface has a color key + + It is safe to pass a NULL `surface` here; it will return SDL_FALSE. + + \param surface the SDL_Surface structure to query + \return SDL_TRUE if the surface has a color key, SDL_FALSE otherwise. + + \since This function is available since SDL 2.0.9. + + \sa SDL_SetColorKey + \sa SDL_GetColorKey + + + + Set the color key (transparent pixel) in a surface. + + The color key defines a pixel value that will be treated as transparent in + a blit. For example, one can use this to specify that cyan pixels should be + considered transparent, and therefore not rendered. + + It is a pixel of the format used by the surface, as generated by + SDL_MapRGB(). + + RLE acceleration can substantially speed up blitting of images with large + horizontal runs of transparent pixels. See SDL_SetSurfaceRLE() for details. + + \param surface the SDL_Surface structure to update + \param flag SDL_TRUE to enable color key, SDL_FALSE to disable color key + \param key the transparent pixel + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_BlitSurface + \sa SDL_GetColorKey + + + + Returns whether the surface is RLE enabled + + It is safe to pass a NULL `surface` here; it will return SDL_FALSE. + + \param surface the SDL_Surface structure to query + \returns SDL_TRUE if the surface is RLE enabled, SDL_FALSE otherwise. + + \since This function is available since SDL 2.0.14. + + \sa SDL_SetSurfaceRLE + + + + Save a surface to a file. + + Convenience macro. + + Set the RLE acceleration hint for a surface. + + If RLE is enabled, color key and alpha blending blits are much faster, but + the surface must be locked before directly accessing the pixels. + + \param surface the SDL_Surface structure to optimize + \param flag 0 to disable, non-zero to enable RLE acceleration + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_BlitSurface + \sa SDL_LockSurface + \sa SDL_UnlockSurface + + + + Load a surface from a file. + + Convenience macro. + + Save a surface to a seekable SDL data stream in BMP format. + + Surfaces with a 24-bit, 32-bit and paletted 8-bit format get saved in the + BMP directly. Other RGB formats with 8-bit or higher get converted to a + 24-bit surface or, if they have an alpha mask or a colorkey, to a 32-bit + surface before they are saved. YUV and paletted 1-bit and 4-bit formats are + not supported. + + \param surface the SDL_Surface structure containing the image to be saved + \param dst a data stream to save to + \param freedst non-zero to close the stream after being written + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_LoadBMP_RW + \sa SDL_SaveBMP + + + + Load a BMP image from a seekable SDL data stream. + + The new surface should be freed with SDL_FreeSurface(). Not doing so will + result in a memory leak. + + src is an open SDL_RWops buffer, typically loaded with SDL_RWFromFile. + Alternitavely, you might also use the macro SDL_LoadBMP to load a bitmap + from a file, convert it to an SDL_Surface and then close the file. + + \param src the data stream for the surface + \param freesrc non-zero to close the stream after being read + \returns a pointer to a new SDL_Surface structure or NULL if there was an + error; call SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_FreeSurface + \sa SDL_RWFromFile + \sa SDL_LoadBMP + \sa SDL_SaveBMP_RW + + + + Release a surface after directly accessing the pixels. + + \param surface the SDL_Surface structure to be unlocked + + \since This function is available since SDL 2.0.0. + + \sa SDL_LockSurface + + + + Set up a surface for directly accessing the pixels. + + Between calls to SDL_LockSurface() / SDL_UnlockSurface(), you can write to + and read from `surface->pixels`, using the pixel format stored in + `surface->format`. Once you are done accessing the surface, you should use + SDL_UnlockSurface() to release it. + + Not all surfaces require locking. If `SDL_MUSTLOCK(surface)` evaluates to + 0, then you can read and write to the surface at any time, and the pixel + format of the surface will not change. + + \param surface the SDL_Surface structure to be locked + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_MUSTLOCK + \sa SDL_UnlockSurface + + + + Set the palette used by a surface. + + A single palette can be shared with many surfaces. + + \param surface the SDL_Surface structure to update + \param palette the SDL_Palette structure to use + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + + + Free an RGB surface. + + It is safe to pass NULL to this function. + + \param surface the SDL_Surface to free. + + \since This function is available since SDL 2.0.0. + + \sa SDL_CreateRGBSurface + \sa SDL_CreateRGBSurfaceFrom + \sa SDL_LoadBMP + \sa SDL_LoadBMP_RW + + + + Allocate a new RGB surface with with a specific pixel format and existing + pixel data. + + This function operates mostly like SDL_CreateRGBSurfaceFrom(), except + instead of providing pixel color masks, you provide it with a predefined + format from SDL_PixelFormatEnum. + + No copy is made of the pixel data. Pixel data is not managed automatically; + you must free the surface before you free the pixel data. + + \param pixels a pointer to existing pixel data + \param width the width of the surface + \param height the height of the surface + \param depth the depth of the surface in bits + \param pitch the pitch of the surface in bytes + \param format the SDL_PixelFormatEnum for the new surface's pixel format. + \returns the new SDL_Surface structure that is created or NULL if it fails; + call SDL_GetError() for more information. + + \since This function is available since SDL 2.0.5. + + \sa SDL_CreateRGBSurfaceFrom + \sa SDL_CreateRGBSurfaceWithFormat + \sa SDL_FreeSurface + + + + Allocate a new RGB surface with existing pixel data. + + This function operates mostly like SDL_CreateRGBSurface(), except it does + not allocate memory for the pixel data, instead the caller provides an + existing buffer of data for the surface to use. + + No copy is made of the pixel data. Pixel data is not managed automatically; + you must free the surface before you free the pixel data. + + \param pixels a pointer to existing pixel data + \param width the width of the surface + \param height the height of the surface + \param depth the depth of the surface in bits + \param pitch the pitch of the surface in bytes + \param Rmask the red mask for the pixels + \param Gmask the green mask for the pixels + \param Bmask the blue mask for the pixels + \param Amask the alpha mask for the pixels + \returns the new SDL_Surface structure that is created or NULL if it fails; + call SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_CreateRGBSurface + \sa SDL_CreateRGBSurfaceWithFormat + \sa SDL_FreeSurface + + + + Allocate a new RGB surface with a specific pixel format. + + This function operates mostly like SDL_CreateRGBSurface(), except instead + of providing pixel color masks, you provide it with a predefined format + from SDL_PixelFormatEnum. + + \param flags the flags are unused and should be set to 0 + \param width the width of the surface + \param height the height of the surface + \param depth the depth of the surface in bits + \param format the SDL_PixelFormatEnum for the new surface's pixel format. + \returns the new SDL_Surface structure that is created or NULL if it fails; + call SDL_GetError() for more information. + + \since This function is available since SDL 2.0.5. + + \sa SDL_CreateRGBSurface + \sa SDL_CreateRGBSurfaceFrom + \sa SDL_FreeSurface + + + + Allocate a new RGB surface. + + If `depth` is 4 or 8 bits, an empty palette is allocated for the surface. + If `depth` is greater than 8 bits, the pixel format is set using the + [RGBA]mask parameters. + + The [RGBA]mask parameters are the bitmasks used to extract that color from + a pixel. For instance, `Rmask` being 0xFF000000 means the red data is + stored in the most significant byte. Using zeros for the RGB masks sets a + default value, based on the depth. For example: + + ```c++ + SDL_CreateRGBSurface(0,w,h,32,0,0,0,0); + ``` + + However, using zero for the Amask results in an Amask of 0. + + By default surfaces with an alpha mask are set up for blending as with: + + ```c++ + SDL_SetSurfaceBlendMode(surface, SDL_BLENDMODE_BLEND) + ``` + + You can change this by calling SDL_SetSurfaceBlendMode() and selecting a + different `blendMode`. + + \param flags the flags are unused and should be set to 0 + \param width the width of the surface + \param height the height of the surface + \param depth the depth of the surface in bits + \param Rmask the red mask for the pixels + \param Gmask the green mask for the pixels + \param Bmask the blue mask for the pixels + \param Amask the alpha mask for the pixels + \returns the new SDL_Surface structure that is created or NULL if it fails; + call SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_CreateRGBSurfaceFrom + \sa SDL_CreateRGBSurfaceWithFormat + \sa SDL_FreeSurface + + + +Reference count -- used when freeing surface + + +info for fast blit mapping to other surfaces + + +clipping information + + +list of BlitMap that hold a reference to this surface + + +information needed for surfaces requiring locks + + +Application data associated with the surface + + + \brief A collection of pixels used in software blitting. + + \note This structure should be treated as read-only, except for \c pixels, + which, if not NULL, contains the raw pixel data for the surface. + + +\brief The type of function used for surface blitting functions. + + + + Compose a custom blend mode for renderers. + + The functions SDL_SetRenderDrawBlendMode and SDL_SetTextureBlendMode accept + the SDL_BlendMode returned by this function if the renderer supports it. + + A blend mode controls how the pixels from a drawing operation (source) get + combined with the pixels from the render target (destination). First, the + components of the source and destination pixels get multiplied with their + blend factors. Then, the blend operation takes the two products and + calculates the result that will get stored in the render target. + + Expressed in pseudocode, it would look like this: + + ```c + dstRGB = colorOperation(srcRGB * srcColorFactor, dstRGB * dstColorFactor); + dstA = alphaOperation(srcA * srcAlphaFactor, dstA * dstAlphaFactor); + ``` + + Where the functions `colorOperation(src, dst)` and `alphaOperation(src, + dst)` can return one of the following: + + - `src + dst` + - `src - dst` + - `dst - src` + - `min(src, dst)` + - `max(src, dst)` + + The red, green, and blue components are always multiplied with the first, + second, and third components of the SDL_BlendFactor, respectively. The + fourth component is not used. + + The alpha component is always multiplied with the fourth component of the + SDL_BlendFactor. The other components are not used in the alpha + calculation. + + Support for these blend modes varies for each renderer. To check if a + specific SDL_BlendMode is supported, create a renderer and pass it to + either SDL_SetRenderDrawBlendMode or SDL_SetTextureBlendMode. They will + return with an error if the blend mode is not supported. + + This list describes the support of custom blend modes for each renderer in + SDL 2.0.6. All renderers support the four blend modes listed in the + SDL_BlendMode enumeration. + + - **direct3d**: Supports all operations with all factors. However, some + factors produce unexpected results with `SDL_BLENDOPERATION_MINIMUM` and + `SDL_BLENDOPERATION_MAXIMUM`. + - **direct3d11**: Same as Direct3D 9. + - **opengl**: Supports the `SDL_BLENDOPERATION_ADD` operation with all + factors. OpenGL versions 1.1, 1.2, and 1.3 do not work correctly with SDL + 2.0.6. + - **opengles**: Supports the `SDL_BLENDOPERATION_ADD` operation with all + factors. Color and alpha factors need to be the same. OpenGL ES 1 + implementation specific: May also support `SDL_BLENDOPERATION_SUBTRACT` + and `SDL_BLENDOPERATION_REV_SUBTRACT`. May support color and alpha + operations being different from each other. May support color and alpha + factors being different from each other. + - **opengles2**: Supports the `SDL_BLENDOPERATION_ADD`, + `SDL_BLENDOPERATION_SUBTRACT`, `SDL_BLENDOPERATION_REV_SUBTRACT` + operations with all factors. + - **psp**: No custom blend mode support. + - **software**: No custom blend mode support. + + Some renderers do not provide an alpha component for the default render + target. The `SDL_BLENDFACTOR_DST_ALPHA` and + `SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA` factors do not have an effect in this + case. + + \param srcColorFactor the SDL_BlendFactor applied to the red, green, and + blue components of the source pixels + \param dstColorFactor the SDL_BlendFactor applied to the red, green, and + blue components of the destination pixels + \param colorOperation the SDL_BlendOperation used to combine the red, + green, and blue components of the source and + destination pixels + \param srcAlphaFactor the SDL_BlendFactor applied to the alpha component of + the source pixels + \param dstAlphaFactor the SDL_BlendFactor applied to the alpha component of + the destination pixels + \param alphaOperation the SDL_BlendOperation used to combine the alpha + component of the source and destination pixels + \returns an SDL_BlendMode that represents the chosen factors and + operations. + + \since This function is available since SDL 2.0.6. + + \sa SDL_SetRenderDrawBlendMode + \sa SDL_GetRenderDrawBlendMode + \sa SDL_SetTextureBlendMode + \sa SDL_GetTextureBlendMode + + + + Calculate the intersection of a rectangle and line segment with float + precision. + + This function is used to clip a line segment to a rectangle. A line segment + contained entirely within the rectangle or that does not intersect will + remain unchanged. A line segment that crosses the rectangle at either or + both ends will be clipped to the boundary of the rectangle and the new + coordinates saved in `X1`, `Y1`, `X2`, and/or `Y2` as necessary. + + \param rect an SDL_FRect structure representing the rectangle to intersect + \param X1 a pointer to the starting X-coordinate of the line + \param Y1 a pointer to the starting Y-coordinate of the line + \param X2 a pointer to the ending X-coordinate of the line + \param Y2 a pointer to the ending Y-coordinate of the line + \returns SDL_TRUE if there is an intersection, SDL_FALSE otherwise. + + \since This function is available since SDL 2.0.22. + + + + Calculate a minimal rectangle enclosing a set of points with float + precision. + + If `clip` is not NULL then only points inside of the clipping rectangle are + considered. + + \param points an array of SDL_FPoint structures representing points to be + enclosed + \param count the number of structures in the `points` array + \param clip an SDL_FRect used for clipping or NULL to enclose all points + \param result an SDL_FRect structure filled in with the minimal enclosing + rectangle + \returns SDL_TRUE if any points were enclosed or SDL_FALSE if all the + points were outside of the clipping rectangle. + + \since This function is available since SDL 2.0.22. + + + + Calculate the union of two rectangles with float precision. + + \param A an SDL_FRect structure representing the first rectangle + \param B an SDL_FRect structure representing the second rectangle + \param result an SDL_FRect structure filled in with the union of rectangles + `A` and `B` + + \since This function is available since SDL 2.0.22. + + + + Calculate the intersection of two rectangles with float precision. + + If `result` is NULL then this function will return SDL_FALSE. + + \param A an SDL_FRect structure representing the first rectangle + \param B an SDL_FRect structure representing the second rectangle + \param result an SDL_FRect structure filled in with the intersection of + rectangles `A` and `B` + \returns SDL_TRUE if there is an intersection, SDL_FALSE otherwise. + + \since This function is available since SDL 2.0.22. + + \sa SDL_HasIntersectionF + + + + Determine whether two rectangles intersect with float precision. + + If either pointer is NULL the function will return SDL_FALSE. + + \param A an SDL_FRect structure representing the first rectangle + \param B an SDL_FRect structure representing the second rectangle + \returns SDL_TRUE if there is an intersection, SDL_FALSE otherwise. + + \since This function is available since SDL 2.0.22. + + \sa SDL_IntersectRect + + + + Returns true if the two rectangles are equal, using a default epsilon. + + \since This function is available since SDL 2.0.22. + + + + Returns true if the two rectangles are equal, within some given epsilon. + + \since This function is available since SDL 2.0.22. + + + +Returns true if the rectangle has no area. + + + +Returns true if point resides inside a rectangle. + + + + Calculate the intersection of a rectangle and line segment. + + This function is used to clip a line segment to a rectangle. A line segment + contained entirely within the rectangle or that does not intersect will + remain unchanged. A line segment that crosses the rectangle at either or + both ends will be clipped to the boundary of the rectangle and the new + coordinates saved in `X1`, `Y1`, `X2`, and/or `Y2` as necessary. + + \param rect an SDL_Rect structure representing the rectangle to intersect + \param X1 a pointer to the starting X-coordinate of the line + \param Y1 a pointer to the starting Y-coordinate of the line + \param X2 a pointer to the ending X-coordinate of the line + \param Y2 a pointer to the ending Y-coordinate of the line + \returns SDL_TRUE if there is an intersection, SDL_FALSE otherwise. + + \since This function is available since SDL 2.0.0. + + + + Calculate a minimal rectangle enclosing a set of points. + + If `clip` is not NULL then only points inside of the clipping rectangle are + considered. + + \param points an array of SDL_Point structures representing points to be + enclosed + \param count the number of structures in the `points` array + \param clip an SDL_Rect used for clipping or NULL to enclose all points + \param result an SDL_Rect structure filled in with the minimal enclosing + rectangle + \returns SDL_TRUE if any points were enclosed or SDL_FALSE if all the + points were outside of the clipping rectangle. + + \since This function is available since SDL 2.0.0. + + + + Calculate the union of two rectangles. + + \param A an SDL_Rect structure representing the first rectangle + \param B an SDL_Rect structure representing the second rectangle + \param result an SDL_Rect structure filled in with the union of rectangles + `A` and `B` + + \since This function is available since SDL 2.0.0. + + + + Calculate the intersection of two rectangles. + + If `result` is NULL then this function will return SDL_FALSE. + + \param A an SDL_Rect structure representing the first rectangle + \param B an SDL_Rect structure representing the second rectangle + \param result an SDL_Rect structure filled in with the intersection of + rectangles `A` and `B` + \returns SDL_TRUE if there is an intersection, SDL_FALSE otherwise. + + \since This function is available since SDL 2.0.0. + + \sa SDL_HasIntersection + + + + Determine whether two rectangles intersect. + + If either pointer is NULL the function will return SDL_FALSE. + + \param A an SDL_Rect structure representing the first rectangle + \param B an SDL_Rect structure representing the second rectangle + \returns SDL_TRUE if there is an intersection, SDL_FALSE otherwise. + + \since This function is available since SDL 2.0.0. + + \sa SDL_IntersectRect + + + +Returns true if the two rectangles are equal. + + + +Returns true if the rectangle has no area. + + + +Returns true if point resides inside a rectangle. + + + + A rectangle, with the origin at the upper left (floating point). + + \sa SDL_FRectEmpty + \sa SDL_FRectEquals + \sa SDL_FRectEqualsEpsilon + \sa SDL_HasIntersectionF + \sa SDL_IntersectFRect + \sa SDL_IntersectFRectAndLine + \sa SDL_UnionFRect + \sa SDL_EncloseFPoints + \sa SDL_PointInFRect + + + + A rectangle, with the origin at the upper left (integer). + + \sa SDL_RectEmpty + \sa SDL_RectEquals + \sa SDL_HasIntersection + \sa SDL_IntersectRect + \sa SDL_IntersectRectAndLine + \sa SDL_UnionRect + \sa SDL_EnclosePoints + + + + The structure that defines a point (floating point) + + \sa SDL_EncloseFPoints + \sa SDL_PointInFRect + + + + Use this function to write 64 bits in native format to a SDL_RWops as + big-endian data. + + SDL byteswaps the data only if necessary, so the application always + specifies native format, and the data written will be in big-endian format. + + \param dst the stream to which data will be written + \param value the data to be written, in native format + \returns 1 on successful write, 0 on error. + + \since This function is available since SDL 2.0.0. + + \sa SDL_WriteLE64 + + + + Use this function to write 64 bits in native format to a SDL_RWops as + little-endian data. + + SDL byteswaps the data only if necessary, so the application always + specifies native format, and the data written will be in little-endian + format. + + \param dst the stream to which data will be written + \param value the data to be written, in native format + \returns 1 on successful write, 0 on error. + + \since This function is available since SDL 2.0.0. + + \sa SDL_WriteBE64 + + + + Use this function to write 32 bits in native format to a SDL_RWops as + big-endian data. + + SDL byteswaps the data only if necessary, so the application always + specifies native format, and the data written will be in big-endian format. + + \param dst the stream to which data will be written + \param value the data to be written, in native format + \returns 1 on successful write, 0 on error. + + \since This function is available since SDL 2.0.0. + + \sa SDL_WriteLE32 + + + + Use this function to write 32 bits in native format to a SDL_RWops as + little-endian data. + + SDL byteswaps the data only if necessary, so the application always + specifies native format, and the data written will be in little-endian + format. + + \param dst the stream to which data will be written + \param value the data to be written, in native format + \returns 1 on successful write, 0 on error. + + \since This function is available since SDL 2.0.0. + + \sa SDL_WriteBE32 + + + + Use this function to write 16 bits in native format to a SDL_RWops as + big-endian data. + + SDL byteswaps the data only if necessary, so the application always + specifies native format, and the data written will be in big-endian format. + + \param dst the stream to which data will be written + \param value the data to be written, in native format + \returns 1 on successful write, 0 on error. + + \since This function is available since SDL 2.0.0. + + \sa SDL_WriteLE16 + + + + Use this function to write 16 bits in native format to a SDL_RWops as + little-endian data. + + SDL byteswaps the data only if necessary, so the application always + specifies native format, and the data written will be in little-endian + format. + + \param dst the stream to which data will be written + \param value the data to be written, in native format + \returns 1 on successful write, 0 on error. + + \since This function is available since SDL 2.0.0. + + \sa SDL_WriteBE16 + + + + \name Write endian functions + + Write an item of native format to the specified endianness. + + Use this function to write a byte to an SDL_RWops. + + \param dst the SDL_RWops to write to + \param value the byte value to write + \returns 1 on success or 0 on failure; call SDL_GetError() for more + information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_ReadU8 + + + + Use this function to read 64 bits of big-endian data from an SDL_RWops and + return in native format. + + SDL byteswaps the data only if necessary, so the data returned will be in + the native byte order. + + \param src the stream from which to read data + \returns 64 bits of data in the native byte order of the platform. + + \since This function is available since SDL 2.0.0. + + \sa SDL_ReadLE64 + + + + Use this function to read 64 bits of little-endian data from an SDL_RWops + and return in native format. + + SDL byteswaps the data only if necessary, so the data returned will be in + the native byte order. + + \param src the stream from which to read data + \returns 64 bits of data in the native byte order of the platform. + + \since This function is available since SDL 2.0.0. + + \sa SDL_ReadBE64 + + + + Use this function to read 32 bits of big-endian data from an SDL_RWops and + return in native format. + + SDL byteswaps the data only if necessary, so the data returned will be in + the native byte order. + + \param src the stream from which to read data + \returns 32 bits of data in the native byte order of the platform. + + \since This function is available since SDL 2.0.0. + + \sa SDL_ReadLE32 + + + + Use this function to read 32 bits of little-endian data from an SDL_RWops + and return in native format. + + SDL byteswaps the data only if necessary, so the data returned will be in + the native byte order. + + \param src the stream from which to read data + \returns 32 bits of data in the native byte order of the platform. + + \since This function is available since SDL 2.0.0. + + \sa SDL_ReadBE32 + + + + Use this function to read 16 bits of big-endian data from an SDL_RWops and + return in native format. + + SDL byteswaps the data only if necessary, so the data returned will be in + the native byte order. + + \param src the stream from which to read data + \returns 16 bits of data in the native byte order of the platform. + + \since This function is available since SDL 2.0.0. + + \sa SDL_ReadLE16 + + + + Use this function to read 16 bits of little-endian data from an SDL_RWops + and return in native format. + + SDL byteswaps the data only if necessary, so the data returned will be in + the native byte order. + + \param src the stream from which to read data + \returns 16 bits of data in the native byte order of the platform. + + \since This function is available since SDL 2.0.0. + + \sa SDL_ReadBE16 + + + + \name Read endian functions + + Read an item of the specified endianness and return in native format. + + Use this function to read a byte from an SDL_RWops. + + \param src the SDL_RWops to read from + \returns the read byte on success or 0 on failure; call SDL_GetError() for + more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_WriteU8 + + + + Load all the data from a file path. + + The data is allocated with a zero byte at the end (null terminated) for + convenience. This extra byte is not included in the value reported via + `datasize`. + + The data should be freed with SDL_free(). + + Prior to SDL 2.0.10, this function was a macro wrapping around + SDL_LoadFile_RW. + + \param file the path to read all available data from + \param datasize if not NULL, will store the number of bytes read + \returns the data, or NULL if there was an error. + + \since This function is available since SDL 2.0.10. + + + + Load all the data from an SDL data stream. + + The data is allocated with a zero byte at the end (null terminated) for + convenience. This extra byte is not included in the value reported via + `datasize`. + + The data should be freed with SDL_free(). + + \param src the SDL_RWops to read all available data from + \param datasize if not NULL, will store the number of bytes read + \param freesrc if non-zero, calls SDL_RWclose() on `src` before returning + \returns the data, or NULL if there was an error. + + \since This function is available since SDL 2.0.6. + + + + Close and free an allocated SDL_RWops structure. + + SDL_RWclose() closes and cleans up the SDL_RWops stream. It releases any + resources used by the stream and frees the SDL_RWops itself with + SDL_FreeRW(). This returns 0 on success, or -1 if the stream failed to + flush to its output (e.g. to disk). + + Note that if this fails to flush the stream to disk, this function reports + an error, but the SDL_RWops is still invalid once this function returns. + + Prior to SDL 2.0.10, this function was a macro. + + \param context SDL_RWops structure to close + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.10. + + \sa SDL_RWFromConstMem + \sa SDL_RWFromFile + \sa SDL_RWFromFP + \sa SDL_RWFromMem + \sa SDL_RWread + \sa SDL_RWseek + \sa SDL_RWwrite + + + + Write to an SDL_RWops data stream. + + This function writes exactly `num` objects each of size `size` from the + area pointed at by `ptr` to the stream. If this fails for any reason, it'll + return less than `num` to demonstrate how far the write progressed. On + success, it returns `num`. + + SDL_RWwrite is actually a function wrapper that calls the SDL_RWops's + `write` method appropriately, to simplify application development. + + Prior to SDL 2.0.10, this function was a macro. + + \param context a pointer to an SDL_RWops structure + \param ptr a pointer to a buffer containing data to write + \param size the size of an object to write, in bytes + \param num the number of objects to write + \returns the number of objects written, which will be less than **num** on + error; call SDL_GetError() for more information. + + \since This function is available since SDL 2.0.10. + + \sa SDL_RWclose + \sa SDL_RWFromConstMem + \sa SDL_RWFromFile + \sa SDL_RWFromFP + \sa SDL_RWFromMem + \sa SDL_RWread + \sa SDL_RWseek + + + + Read from a data source. + + This function reads up to `maxnum` objects each of size `size` from the + data source to the area pointed at by `ptr`. This function may read less + objects than requested. It will return zero when there has been an error or + the data stream is completely read. + + SDL_RWread() is actually a function wrapper that calls the SDL_RWops's + `read` method appropriately, to simplify application development. + + Prior to SDL 2.0.10, this function was a macro. + + \param context a pointer to an SDL_RWops structure + \param ptr a pointer to a buffer to read data into + \param size the size of each object to read, in bytes + \param maxnum the maximum number of objects to be read + \returns the number of objects read, or 0 at error or end of file; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.10. + + \sa SDL_RWclose + \sa SDL_RWFromConstMem + \sa SDL_RWFromFile + \sa SDL_RWFromFP + \sa SDL_RWFromMem + \sa SDL_RWseek + \sa SDL_RWwrite + + + + Determine the current read/write offset in an SDL_RWops data stream. + + SDL_RWtell is actually a wrapper function that calls the SDL_RWops's `seek` + method, with an offset of 0 bytes from `RW_SEEK_CUR`, to simplify + application development. + + Prior to SDL 2.0.10, this function was a macro. + + \param context a SDL_RWops data stream object from which to get the current + offset + \returns the current offset in the stream, or -1 if the information can not + be determined. + + \since This function is available since SDL 2.0.10. + + \sa SDL_RWclose + \sa SDL_RWFromConstMem + \sa SDL_RWFromFile + \sa SDL_RWFromFP + \sa SDL_RWFromMem + \sa SDL_RWread + \sa SDL_RWseek + \sa SDL_RWwrite + + + + Seek within an SDL_RWops data stream. + + This function seeks to byte `offset`, relative to `whence`. + + `whence` may be any of the following values: + + - `RW_SEEK_SET`: seek from the beginning of data + - `RW_SEEK_CUR`: seek relative to current read point + - `RW_SEEK_END`: seek relative to the end of data + + If this stream can not seek, it will return -1. + + SDL_RWseek() is actually a wrapper function that calls the SDL_RWops's + `seek` method appropriately, to simplify application development. + + Prior to SDL 2.0.10, this function was a macro. + + \param context a pointer to an SDL_RWops structure + \param offset an offset in bytes, relative to **whence** location; can be + negative + \param whence any of `RW_SEEK_SET`, `RW_SEEK_CUR`, `RW_SEEK_END` + \returns the final offset in the data stream after the seek or -1 on error. + + \since This function is available since SDL 2.0.10. + + \sa SDL_RWclose + \sa SDL_RWFromConstMem + \sa SDL_RWFromFile + \sa SDL_RWFromFP + \sa SDL_RWFromMem + \sa SDL_RWread + \sa SDL_RWtell + \sa SDL_RWwrite + + + + Use this function to get the size of the data stream in an SDL_RWops. + + Prior to SDL 2.0.10, this function was a macro. + + \param context the SDL_RWops to get the size of the data stream from + \returns the size of the data stream in the SDL_RWops on success, -1 if + unknown or a negative error code on failure; call SDL_GetError() + for more information. + + \since This function is available since SDL 2.0.10. + + + + Use this function to free an SDL_RWops structure allocated by + SDL_AllocRW(). + + Applications do not need to use this function unless they are providing + their own SDL_RWops implementation. If you just need a SDL_RWops to + read/write a common data source, you should use the built-in + implementations in SDL, like SDL_RWFromFile() or SDL_RWFromMem(), etc, and + call the **close** method on those SDL_RWops pointers when you are done + with them. + + Only use SDL_FreeRW() on pointers returned by SDL_AllocRW(). The pointer is + invalid as soon as this function returns. Any extra memory allocated during + creation of the SDL_RWops is not freed by SDL_FreeRW(); the programmer must + be responsible for managing that memory in their **close** method. + + \param area the SDL_RWops structure to be freed + + \since This function is available since SDL 2.0.0. + + \sa SDL_AllocRW + + + + Use this function to allocate an empty, unpopulated SDL_RWops structure. + + Applications do not need to use this function unless they are providing + their own SDL_RWops implementation. If you just need a SDL_RWops to + read/write a common data source, you should use the built-in + implementations in SDL, like SDL_RWFromFile() or SDL_RWFromMem(), etc. + + You must free the returned pointer with SDL_FreeRW(). Depending on your + operating system and compiler, there may be a difference between the + malloc() and free() your program uses and the versions SDL calls + internally. Trying to mix the two can cause crashing such as segmentation + faults. Since all SDL_RWops must free themselves when their **close** + method is called, all SDL_RWops must be allocated through this function, so + they can all be freed correctly with SDL_FreeRW(). + + \returns a pointer to the allocated memory on success, or NULL on failure; + call SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_FreeRW + + + + Use this function to prepare a read-only memory buffer for use with RWops. + + This function sets up an SDL_RWops struct based on a memory area of a + certain size. It assumes the memory area is not writable. + + Attempting to write to this RWops stream will report an error without + writing to the memory buffer. + + This memory buffer is not copied by the RWops; the pointer you provide must + remain valid until you close the stream. Closing the stream will not free + the original buffer. + + If you need to write to a memory buffer, you should use SDL_RWFromMem() + with a writable buffer of memory instead. + + \param mem a pointer to a read-only buffer to feed an SDL_RWops stream + \param size the buffer size, in bytes + \returns a pointer to a new SDL_RWops structure, or NULL if it fails; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_RWclose + \sa SDL_RWFromConstMem + \sa SDL_RWFromFile + \sa SDL_RWFromFP + \sa SDL_RWFromMem + \sa SDL_RWread + \sa SDL_RWseek + \sa SDL_RWtell + + + + Use this function to prepare a read-write memory buffer for use with + SDL_RWops. + + This function sets up an SDL_RWops struct based on a memory area of a + certain size, for both read and write access. + + This memory buffer is not copied by the RWops; the pointer you provide must + remain valid until you close the stream. Closing the stream will not free + the original buffer. + + If you need to make sure the RWops never writes to the memory buffer, you + should use SDL_RWFromConstMem() with a read-only buffer of memory instead. + + \param mem a pointer to a buffer to feed an SDL_RWops stream + \param size the buffer size, in bytes + \returns a pointer to a new SDL_RWops structure, or NULL if it fails; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_RWclose + \sa SDL_RWFromConstMem + \sa SDL_RWFromFile + \sa SDL_RWFromFP + \sa SDL_RWFromMem + \sa SDL_RWread + \sa SDL_RWseek + \sa SDL_RWtell + \sa SDL_RWwrite + + + + Use this function to create an SDL_RWops structure from a standard I/O file + pointer (stdio.h's `FILE*`). + + This function is not available on Windows, since files opened in an + application on that platform cannot be used by a dynamically linked + library. + + On some platforms, the first parameter is a `void*`, on others, it's a + `FILE*`, depending on what system headers are available to SDL. It is + always intended to be the `FILE*` type from the C runtime's stdio.h. + + \param fp the `FILE*` that feeds the SDL_RWops stream + \param autoclose SDL_TRUE to close the `FILE*` when closing the SDL_RWops, + SDL_FALSE to leave the `FILE*` open when the RWops is + closed + \returns a pointer to the SDL_RWops structure that is created, or NULL on + failure; call SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_RWclose + \sa SDL_RWFromConstMem + \sa SDL_RWFromFile + \sa SDL_RWFromMem + \sa SDL_RWread + \sa SDL_RWseek + \sa SDL_RWtell + \sa SDL_RWwrite + + + + \name RWFrom functions + + Functions to create SDL_RWops structures from various data streams. + + Use this function to create a new SDL_RWops structure for reading from + and/or writing to a named file. + + The `mode` string is treated roughly the same as in a call to the C + library's fopen(), even if SDL doesn't happen to use fopen() behind the + scenes. + + Available `mode` strings: + + - "r": Open a file for reading. The file must exist. + - "w": Create an empty file for writing. If a file with the same name + already exists its content is erased and the file is treated as a new + empty file. + - "a": Append to a file. Writing operations append data at the end of the + file. The file is created if it does not exist. + - "r+": Open a file for update both reading and writing. The file must + exist. + - "w+": Create an empty file for both reading and writing. If a file with + the same name already exists its content is erased and the file is + treated as a new empty file. + - "a+": Open a file for reading and appending. All writing operations are + performed at the end of the file, protecting the previous content to be + overwritten. You can reposition (fseek, rewind) the internal pointer to + anywhere in the file for reading, but writing operations will move it + back to the end of file. The file is created if it does not exist. + + **NOTE**: In order to open a file as a binary file, a "b" character has to + be included in the `mode` string. This additional "b" character can either + be appended at the end of the string (thus making the following compound + modes: "rb", "wb", "ab", "r+b", "w+b", "a+b") or be inserted between the + letter and the "+" sign for the mixed modes ("rb+", "wb+", "ab+"). + Additional characters may follow the sequence, although they should have no + effect. For example, "t" is sometimes appended to make explicit the file is + a text file. + + This function supports Unicode filenames, but they must be encoded in UTF-8 + format, regardless of the underlying operating system. + + As a fallback, SDL_RWFromFile() will transparently open a matching filename + in an Android app's `assets`. + + Closing the SDL_RWops will close the file handle SDL is holding internally. + + \param file a UTF-8 string representing the filename to open + \param mode an ASCII string representing the mode to be used for opening + the file. + \returns a pointer to the SDL_RWops structure that is created, or NULL on + failure; call SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_RWclose + \sa SDL_RWFromConstMem + \sa SDL_RWFromFP + \sa SDL_RWFromMem + \sa SDL_RWread + \sa SDL_RWseek + \sa SDL_RWtell + \sa SDL_RWwrite + + + +Return the size of the file in this rwops, or -1 if unknown + + + Seek to \c offset relative to \c whence, one of stdio's whence values: + RW_SEEK_SET, RW_SEEK_CUR, RW_SEEK_END + + \return the final offset in the data stream, or -1 on error. + + + Read up to \c maxnum objects each of size \c size from the data + stream to the area pointed at by \c ptr. + + \return the number of objects read, or 0 at error or end of file. + + + Write exactly \c num objects each of size \c size from the area + pointed at by \c ptr to data stream. + + \return the number of objects written, or 0 at error or end of file. + + + Close and free an allocated SDL_RWops structure. + + \return 0 if successful or -1 on write error when flushing data. + + + + Clear any previous error message for this thread. + + \since This function is available since SDL 2.0.0. + + \sa SDL_GetError + \sa SDL_SetError + + + + Get the last error message that was set for the current thread. + + This allows the caller to copy the error string into a provided buffer, but + otherwise operates exactly the same as SDL_GetError(). + + \param errstr A buffer to fill with the last error message that was set for + the current thread + \param maxlen The size of the buffer pointed to by the errstr parameter + \returns the pointer passed in as the `errstr` parameter. + + \since This function is available since SDL 2.0.14. + + \sa SDL_GetError + + + + Retrieve a message about the last error that occurred on the current + thread. + + It is possible for multiple errors to occur before calling SDL_GetError(). + Only the last error is returned. + + The message is only applicable when an SDL function has signaled an error. + You must check the return values of SDL function calls to determine when to + appropriately call SDL_GetError(). You should *not* use the results of + SDL_GetError() to decide if an error has occurred! Sometimes SDL will set + an error string even when reporting success. + + SDL will *not* clear the error string for successful API calls. You *must* + check return values for failure cases before you can assume the error + string applies. + + Error strings are set per-thread, so an error set in a different thread + will not interfere with the current thread's operation. + + The returned string is internally allocated and must not be freed by the + application. + + \returns a message with information about the specific error that occurred, + or an empty string if there hasn't been an error message set since + the last call to SDL_ClearError(). The message is only applicable + when an SDL function has signaled an error. You must check the + return values of SDL function calls to determine when to + appropriately call SDL_GetError(). + + \since This function is available since SDL 2.0.0. + + \sa SDL_ClearError + \sa SDL_SetError + + + + Calculate a 256 entry gamma ramp for a gamma value. + + \param gamma a gamma value where 0.0 is black and 1.0 is identity + \param ramp an array of 256 values filled in with the gamma ramp + + \since This function is available since SDL 2.0.0. + + \sa SDL_SetWindowGammaRamp + + + + Get RGBA values from a pixel in the specified format. + + This function uses the entire 8-bit [0..255] range when converting color + components from pixel formats with less than 8-bits per RGB component + (e.g., a completely white pixel in 16-bit RGB565 format would return [0xff, + 0xff, 0xff] not [0xf8, 0xfc, 0xf8]). + + If the surface has no alpha component, the alpha will be returned as 0xff + (100% opaque). + + \param pixel a pixel value + \param format an SDL_PixelFormat structure describing the format of the + pixel + \param r a pointer filled in with the red component + \param g a pointer filled in with the green component + \param b a pointer filled in with the blue component + \param a a pointer filled in with the alpha component + + \since This function is available since SDL 2.0.0. + + \sa SDL_GetRGB + \sa SDL_MapRGB + \sa SDL_MapRGBA + + + + Get RGB values from a pixel in the specified format. + + This function uses the entire 8-bit [0..255] range when converting color + components from pixel formats with less than 8-bits per RGB component + (e.g., a completely white pixel in 16-bit RGB565 format would return [0xff, + 0xff, 0xff] not [0xf8, 0xfc, 0xf8]). + + \param pixel a pixel value + \param format an SDL_PixelFormat structure describing the format of the + pixel + \param r a pointer filled in with the red component + \param g a pointer filled in with the green component + \param b a pointer filled in with the blue component + + \since This function is available since SDL 2.0.0. + + \sa SDL_GetRGBA + \sa SDL_MapRGB + \sa SDL_MapRGBA + + + + Map an RGBA quadruple to a pixel value for a given pixel format. + + This function maps the RGBA color value to the specified pixel format and + returns the pixel value best approximating the given RGBA color value for + the given pixel format. + + If the specified pixel format has no alpha component the alpha value will + be ignored (as it will be in formats with a palette). + + If the format has a palette (8-bit) the index of the closest matching color + in the palette will be returned. + + If the pixel format bpp (color depth) is less than 32-bpp then the unused + upper bits of the return value can safely be ignored (e.g., with a 16-bpp + format the return value can be assigned to a Uint16, and similarly a Uint8 + for an 8-bpp format). + + \param format an SDL_PixelFormat structure describing the format of the + pixel + \param r the red component of the pixel in the range 0-255 + \param g the green component of the pixel in the range 0-255 + \param b the blue component of the pixel in the range 0-255 + \param a the alpha component of the pixel in the range 0-255 + \returns a pixel value + + \since This function is available since SDL 2.0.0. + + \sa SDL_GetRGB + \sa SDL_GetRGBA + \sa SDL_MapRGB + + + + Map an RGB triple to an opaque pixel value for a given pixel format. + + This function maps the RGB color value to the specified pixel format and + returns the pixel value best approximating the given RGB color value for + the given pixel format. + + If the format has a palette (8-bit) the index of the closest matching color + in the palette will be returned. + + If the specified pixel format has an alpha component it will be returned as + all 1 bits (fully opaque). + + If the pixel format bpp (color depth) is less than 32-bpp then the unused + upper bits of the return value can safely be ignored (e.g., with a 16-bpp + format the return value can be assigned to a Uint16, and similarly a Uint8 + for an 8-bpp format). + + \param format an SDL_PixelFormat structure describing the pixel format + \param r the red component of the pixel in the range 0-255 + \param g the green component of the pixel in the range 0-255 + \param b the blue component of the pixel in the range 0-255 + \returns a pixel value + + \since This function is available since SDL 2.0.0. + + \sa SDL_GetRGB + \sa SDL_GetRGBA + \sa SDL_MapRGBA + + + + Free a palette created with SDL_AllocPalette(). + + \param palette the SDL_Palette structure to be freed + + \since This function is available since SDL 2.0.0. + + \sa SDL_AllocPalette + + + + Set a range of colors in a palette. + + \param palette the SDL_Palette structure to modify + \param colors an array of SDL_Color structures to copy into the palette + \param firstcolor the index of the first palette entry to modify + \param ncolors the number of entries to modify + \returns 0 on success or a negative error code if not all of the colors + could be set; call SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_AllocPalette + \sa SDL_CreateRGBSurface + + + + Set the palette for a pixel format structure. + + \param format the SDL_PixelFormat structure that will use the palette + \param palette the SDL_Palette structure that will be used + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_AllocPalette + \sa SDL_FreePalette + + + + Create a palette structure with the specified number of color entries. + + The palette entries are initialized to white. + + \param ncolors represents the number of color entries in the color palette + \returns a new SDL_Palette structure on success or NULL on failure (e.g. if + there wasn't enough memory); call SDL_GetError() for more + information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_FreePalette + + + + Free an SDL_PixelFormat structure allocated by SDL_AllocFormat(). + + \param format the SDL_PixelFormat structure to free + + \since This function is available since SDL 2.0.0. + + \sa SDL_AllocFormat + + + + Create an SDL_PixelFormat structure corresponding to a pixel format. + + Returned structure may come from a shared global cache (i.e. not newly + allocated), and hence should not be modified, especially the palette. Weird + errors such as `Blit combination not supported` may occur. + + \param pixel_format one of the SDL_PixelFormatEnum values + \returns the new SDL_PixelFormat structure or NULL on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_FreeFormat + + + + Convert a bpp value and RGBA masks to an enumerated pixel format. + + This will return `SDL_PIXELFORMAT_UNKNOWN` if the conversion wasn't + possible. + + \param bpp a bits per pixel value; usually 15, 16, or 32 + \param Rmask the red mask for the format + \param Gmask the green mask for the format + \param Bmask the blue mask for the format + \param Amask the alpha mask for the format + \returns one of the SDL_PixelFormatEnum values + + \since This function is available since SDL 2.0.0. + + \sa SDL_PixelFormatEnumToMasks + + + + Convert one of the enumerated pixel formats to a bpp value and RGBA masks. + + \param format one of the SDL_PixelFormatEnum values + \param bpp a bits per pixel value; usually 15, 16, or 32 + \param Rmask a pointer filled in with the red mask for the format + \param Gmask a pointer filled in with the green mask for the format + \param Bmask a pointer filled in with the blue mask for the format + \param Amask a pointer filled in with the alpha mask for the format + \returns SDL_TRUE on success or SDL_FALSE if the conversion wasn't + possible; call SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_MasksToPixelFormatEnum + + + + Get the human readable name of a pixel format. + + \param format the pixel format to query + \returns the human readable name of the specified pixel format or + `SDL_PIXELFORMAT_UNKNOWN` if the format isn't recognized. + + \since This function is available since SDL 2.0.0. + + + +\note Everything in the pixel format structure is read-only. + + + +The bits of this structure can be directly reinterpreted as an integer-packed +color which uses the SDL_PIXELFORMAT_RGBA32 format (SDL_PIXELFORMAT_ABGR8888 +on little-endian systems and SDL_PIXELFORMAT_RGBA8888 on big-endian systems). + + + + If a + b would overflow, return -1. Otherwise store a + b via ret + and return 0. + + \since This function is available since SDL 2.24.0. + + + + If a * b would overflow, return -1. Otherwise store a * b via ret + and return 0. + + \since This function is available since SDL 2.24.0. + + + + This function converts a string between encodings in one pass, returning a + string that must be freed with SDL_free() or NULL on error. + + \since This function is available since SDL 2.0.0. + + + + Get the number of outstanding (unfreed) allocations + + \since This function is available since SDL 2.0.7. + + + + Replace SDL's memory allocation functions with a custom set + + \since This function is available since SDL 2.0.7. + + + + Get the current set of SDL memory functions + + \since This function is available since SDL 2.0.7. + + + + Get the original set of SDL memory functions + + \since This function is available since SDL 2.24.0. + + + +\endcond + \file begin_code.h + + This file sets things up for C dynamic library function definitions, + static inlined functions, and structures aligned at 4-byte alignment. + If you don't like ugly C preprocessor code, don't look at this file. :) + + + +\name Floating-point constants + +\cond + + +\brief An unsigned 64-bit integer type. + + + +\brief A signed 64-bit integer type. + + + +\brief An unsigned 32-bit integer type. + + + +\brief A signed 32-bit integer type. + + + +\brief An unsigned 16-bit integer type. + + + +\brief A signed 16-bit integer type. + + + +\brief An unsigned 8-bit integer type. + + + +\brief A signed 8-bit integer type. + + + + \file close_code.h + + This file reverses the effects of begin_code.h and should be included + after you finish any function and structure declarations in your headers + + + + \file SDL_stdinc.h + + This is a general header that includes C language support. + + \file SDL_platform.h + + Try to get a standard set of platform defines. + + \file begin_code.h + + This file sets things up for C dynamic library function definitions, + static inlined functions, and structures aligned at 4-byte alignment. + If you don't like ugly C preprocessor code, don't look at this file. :) + + Get the name of the platform. + + Here are the names returned for some (but not all) supported platforms: + + - "Windows" + - "Mac OS X" + - "Linux" + - "iOS" + - "Android" + + \returns the name of the platform. If the correct platform name is not + available, returns a string beginning with the text "Unknown". + + \since This function is available since SDL 2.0.0. + + + +*!************************************************************************* + + + +Marks the application to stop at the end of the current frame. + + + + +Whether or not the application is currently in fullscreen mode or not. + + + + +Retrieves the designated height of the current window. + + + + +Retrieves the designated width of the current window. + + + + +Whether or not the engine is in a paused state where script updates and +physics are not in play. + + + + +Whether or not the engine is playing. This will always be true on Publish. +On Debug/Release builds, this is true when the editor is in Play Mode. It +will also be true even if the editor is in Play Mode but is paused. + + + + +Static class that contains useful properties for querying the state of the +engine. + + + + +Sets the parent of this Transform component. + + +Entity that contains the Transform component that this Transform will be +parented to. If null, unparenting will occur. + + +If true, the transform values of this Transform component will retain their +pre-parent-change global transforms. The local transform values will be +modified to ensure that the global transforms do not change. + + + + +Parent Transform that affects this Transform. + + + + +Global scale stored by this Transform. + + + + +Global euler angle rotations stored by this Transform. + + + + +Global rotation quaternion stored by this Transform. + + + + +Global position stored by this Transform. + + + + +Local scale stored by this Transform. + + + + +Local euler angle rotations stored by this Transform. + + + + +Local rotation quaternion stored by this Transform. + + + + +Local position stored by this Transform. + + + + +Constructs a Transform Component that represents a native Transform component +tied to the specified Entity. + + Entity that this Component will be tied to. + + + +CLR version of the SHADE Engine's TransformComponent. + + + + +Compares if two float values are close enough to be the same with the +specified tolerance value. + + One of the values to compare. + The other value to compare. + Tolerance for floating point comparison. + True if a and b are practically the same. + + + +Compares if two float values are close enough to be the same with a tolerance +of Epsilon. + + One of the values to compare. + The other value to compare. + True if a and b are practically the same. + + + +Calculates the linear parameter t that produces the interpolant value within +the range [a, b]. + + Start value. + End value. + Value between start and end. + Percentage of value between start and end. + + + +Linearly interpolates between a and b by t. +The parameter t is not clamped and a value based on a and b is supported. +If t is less than zero, or greater than one, then LerpUnclamped will result +in a return value outside the range a to b. + + The start value. + The end value. + The interpolation value between the two float. + The interpolated float result between the two float values. + + + +Linearly interpolates between a and b by t. +The parameter t is clamped to the range [0, 1]. + + The start value. + The end value. + The interpolation value between the two float. + The interpolated float result between the two float values. + + + +Converts an angle from radian representation to degree representation. + + Radian-based angle to convert. + The specified angle in degrees. + + + +Converts an angle from degree representation to radian representation. + + Degree-based angle to convert. + The specified angle in radians. + + + +Wraps a value if they get to low or too high. + + Value to wrap. + Minimum value to wrap at. + Maximum value to wrap at. + Wrapped value. + + + +Small value used for single precision floating point comparisons. + + + + +Radians-to-degrees conversion constant + + + + +Degrees-to-radians conversion constant + + + + +Contains utility Math functions. + + + + +Logs a native exception that is formatted nicely to the output. + + Native exception to log. + Name of the one responsible for the exception. + + + +Logs an exception that is formatted nicely to the output. + + Name of the one responsible for the exception. + Exception to log. + + + +Logs a native exception that is formatted nicely to the output. +Equivalent to calling +LogException(exception, Convert::ToNative(thrower->GetType()->Name)); + + Native exception to log. + +Object that threw the exception to label the exception message. +The name of the object will be used. + + + + +Logs an exception that is formatted nicely to the output. + + Exception to log. + +Object that threw the exception to label the exception message. +The name of the object will be used. + + + + +Logs an exception that is formatted nicely to the output. + + Exception to log. + + + +Logs a error message to the output with a label such that it looks like this: +"[Label] Message" + + The string to output. + +Name of the object that threw the error to label the error message. +The name of the object will be used. + + + + +Logs a error message to the output with a label such that it looks like this: +"[Label] Message" + + The string to output. + +Name of the object that threw the error to label the error message. +The name of the object will be used. + + + + +Logs a error message to the output with a label such that it looks like this: +"[Label] Message" + + The string to output. + +Object that threw the error to label the error message. +The name of the object will be used. + + + + +Logs a error message to the output. + + The string to output. + + + +Logs a error message to the output. + + The string to output. + + + +Logs a warning message to the output with a label such that it looks like this: +"[Label] Message" + + The string to output. + +Name of the object that threw the warning to label the warning message. +The name of the object will be used. + + + + +Logs a warning message to the output with a label such that it looks like this: +"[Label] Message" + + The string to output. + +Name of the object that threw the warning to label the warning message. +The name of the object will be used. + + + + +Logs a warning message to the output with a label such that it looks like this: +"[Label] Message" + + The string to output. + +Object that threw the warning to label the warning message. +The name of the object will be used. + + + + +Logs a warning message to the output. + + The string to output. + + + +Logs a warning message to the output. + + The string to output. + + + +Logs a message to the output with a label such that it looks like this: +"[Label] Message" + + The string to output. + +Name of the object that sent the message to label the message. +The name of the object will be used. + + + + +Logs a message to the output with a label such that it looks like this: +"[Label] Message" + + The string to output. + +Name of the object that sent the message to label the message. +The name of the object will be used. + + + + +Logs a message to the output with a label such that it looks like this: +"[Label] Message" + + The string to output. + +Object that sent the message to label the message. +The name of the object will be used. + + + + +Logs a message to the output. + + The string to output. + + + +Logs a message to the output. + + The string to output. + + + +Static class that contains the functions for working with time. + + + + +Material used to render this Renderable. + + + + +Material used to render this Renderable. + + + + +Mesh used to render this Renderable. + + + + +Constructs a Renderable Component that represents a native Renderable +component tied to the specified Entity. + + Entity that this Component will be tied to. + + + +CLR version of the SHADE Engine's SHRenderableComponent. + + + + +Retrieves the value of a specified property on the material. + + Type of property to get. + Name of the property to get. + Value of that property on the material. + +If this Material object is invalid. + + +If the name or type was specified that does not match the material's shader's +defined properties. + + + + +Set the value of a specific property. + + Type of property to set. + Name of the property to set. + Value to set te property to. + +If this Material object is invalid. + + +If the name or type was specified that does not match the material's shader's +defined properties. + + + + +Constructor for the Material + + Handle to the native material object. + + + +Managed counterpart of the native MaterialInstance object containing material +data that can be fed to Renderables for rendering. + + + + +Constructor for the Mesh + + Handle to the mesh object. + + + +Managed counterpart of the native Mesh object containing vertex data that can +be fed to Renderables for rendering. + + + +@brief Decomposes a transformation matrix into translation, orientation and scale. +@param[out] scale The scaling factor of the matrix. +@param[out] orientation The orientation of the matrix. +@param[out] translation The translation of the matrix. +@return True if decomposition was successful. + + + +@brief Decomposes a transformation matrix into translation, euler angles and scale. +@param[out] scale The scaling factor of the matrix. +@param[out] rotation The euler angles of the matrix. +@param[out] translation The translation of the matrix. +@return True if decomposition was successful. + + + +@brief Interface for a Column-Major Row Vector 4x4 Matrix. + + + + +Constructs a RigidBody Component that represents a native +SHRigidBodyComponent component tied to the specified Entity. + + Entity that this Component will be tied to. + + + +CLR version of the the SHADE Engine's SHRigidBodyComponent. + + + + +Creates an instance of the Managed representation of a Component with a +native Entity. + + Type of Component to create. + Native Entity that this Component is tied to. + The created Managed representation of the Component. + + + +Static constructor to initialize static data + + + + +Pointer to a function for Component manipulation operations. + + +Contains a set of Component related data used for resolving operations for +each Component. + + + + +Removes a Component from the specified Entity. + + Type of the Component to remove. + +Entity object that should have the specified Component removed from/ + + + + +Checks if the specified Entity has the specified Component. + + Type of the Component to check for. + Entity object to check for the Component. + +True if the specified Entity has the specified Component. False otherwise. + + + + +Ensures a Component on the specified Entity. + + Type of the Component to ensure. + Entity object to ensure the Component on. + Reference to the Component. + + + +Retrieves the first Component from the specified GameObjectt's children that +matches the specified type. + + Type of the Component to get. + Entity object to get the Component from. + +Reference to the Component or null if the Entity does not have the +specified Component. + + + + +Gets a Component from the specified Entity. + + Type of the Component to get. + Entity object to get the Component from. + +Reference to the Component or null if the Entity does not have the +specified Component. + + + + +Adds a Component to the specified Entity. + + Type of the Component to add. + +Entity object that should have the specified Component added to. + + Reference to the Component that was added. + + + +Static class which contains functions that map Pls::ECS's Component manipulation +functions to managed generic functions. + + + + +Gets a unique hash for this object. + + Unique hash for this object. + + + +Compares equality with another unboxed object. + + The unboxed object to compare with. + True if both objects are the same. + + + +Compares equality with an object of the same type. + + The object to compare with. + True if both objects are the same. + + + +Entity that this Component belongs to. + + + + +Constructor for BaseComponent to tie it to a specific Entity. +Constructors of derived Components should call this Constructor. + + Entity that this Component will be tied to. + + + +Implicit conversion operator to enable checking if a component is null. + + Component to check. + + + +Removes all Scripts of the specified type from this GameObject. + + Type of PLushieScripts to remove. + + + +Retrieves a immutable list of Scripts of the specified type from this +GameObject. + + Type of Scripts to Get. + Immutable list of Scripts of the specified type. + + + +Retrieves a Script of the specified type from this GameObject. +If multiple Scripts of the same specified type are added on the same +GameObject, this will retrieve the first one added. + + Type of Script to add. + Reference to the Script to retrieve. + + + +Adds a Script of the specified type to this GameObject. + + Type of Script to add. + Reference to the created Script. + + + +Removes a Component from this GameObject. If no Component exists to begin +with, nothing happens. + + Type of the Component to get. + + + +Gets a Component from this GameObject. + + Type of the Component to get. + +Reference to the Component or null if this GameObject does not have the +specified Component. + + + + +Adds a Component to this GameObject. + + Type of the Component to add. + Reference to the Component that was added. + + + +Retrieves the GameObject that this Component belongs to. + + + + +Class that serves as the base for a wrapper class to Components in native code. + + + + +Called when the attached GameObject has a Collider and leaves a +collision with another GameObject with a Collider2D. + + Information on the collision event. + + + +Called when the attached GameObject has a Collider and collides with +another GameObject with a Collider in subsequent frames of collision. + + Information on the collision event. + + + +Called when the attached GameObject has a Collider and collides with +another GameObject with a Collider in the first frame of collision. + + Information on the collision event. + + + +Called when the attached GameObject has a trigger Collider and leaves a +collision with another GameObject with a Collider2D. + + Information on the collision event. + + + +Called when the attached GameObject has a trigger Collider and collides with +another GameObject with a Collider in subsequent frames of collision. + + Information on the collision event. + + + +Called when the attached GameObject has a trigger Collider and collides with +another GameObject with a Collider in the first frame of collision. + + Information on the collision event. + + + +Called just before the end of the frame where the attached GameObject or +this script is destroyed directly or indirectly due to destruction of the +owner. + + + + +Called every frame after physics and collision resolution but before +rendering. + + + + +Called every frame before physics and collision resolution. + + + + +Called every frame in sync with Physics update steps and thus in most cases +will execute more than update() will. This will be called immediately before +a Physics update step. + + + + +Called on the first frame that the attached GameObject is active but always +after Awake(). + + + + +Called on the first frame that the attached GameObject is active if they are +a part of the scene. + + + + +Called immediately once this script is detached from a GameObject. + + + + +Called immediately once this script is attached to a GameObject. + + + + +Constructor for Script to tie it to a specific GameObject. +Constructors of derived Scripts should call this Constructor. + + +GameObject that this Script will be tied to. + + + + +Used to call onTriggerExit(). This should be called when a trigger-type +collision is detected between the attached GameObject and another GameObject. + + Information on the collision event. + + + +Used to call onTriggerStay(). This should be called when a trigger-type +collision is detected between the attached GameObject and another GameObject. + + Information on the collision event. + + + +Used to call onTriggerEnter(). This should be called when a trigger-type +collision is detected between the attached GameObject and another GameObject. + + Information on the collision event. + + + +Used to call onCollisionExit(). This should be called when a collision ends +between the attached GameObject and another GameObject. + + Information on the collision event. + + + +Used to call onCollisionStay(). This should be called when a collision is +persistent between the attached GameObject and another GameObject. + + Information on the collision event. + + + +Used to call onCollisionEnter(). This should be called when a collision is +detected between the attached GameObject and another GameObject. + + Information on the collision event. + + + +Used to call onDestroy(). This should be called at the end of the frame +where the attached GameObject or this script is destroyed directly or +indirectly due to destruction of the owner. + + + + +Used to call lateUpdate(). This should be called every frame after physics +and collision resolution but before rendering. + + + + +Used to call update(). This should be called every frame before physics and +collision resolution. + + + + +Used to call fixedUpdate(). This should be called in sync with Physics +update steps and thus in most cases will execute more than Update() will. +This will be called immediately before a Physics update step. + + + + +Used to call start(). This should be called on the first frame that the +attached GameObject is active but always after Awake(). + + + + +Used to call awake(). This should be called on the first frame that the +attached GameObject is active if they are a part of the scene. + + + + +Used to call onDetached(). This is called immediately when this script is +detached from a GameObject. + + + + +Used to call onAttached(). This is called immediately when this script is +attached to a GameObject. + + + + +Implicit conversion operator to enable checking if a component is null. + + Component to check. + + + +Removes all Scripts of the specified type from this GameObject. + + +Type of script to remove. +This needs to be a default constructable Script. + + + + +Retrieves a immutable list of scripts from the specified Entity that +matches the specified type. +
+Note that this function allocates. It should be used sparingly. +
+ +Type of scripts to get. +This needs to be a default constructable Script. + + +Immutable list of references to scripts of the specified type. + +
+ + +Retrieves the first Script from this GameObject's children that matches the +specified type. + + +Type of script to get. +This needs to be a default constructable Script. + + Reference to the script added + + + +Retrieves the first Script from this GameObject that matches the specified +type. + + +Type of script to get. +This needs to be a default constructable Script. + + Reference to the script added + + + +Adds a Script to this GameObject. + + +Type of script to add. +This needs to be a default constructable Script. + + Reference to the script added + + + +Removes a Component from the GameObject that this Script belongs to. + + +Type of the Component to remove. Must be derived from BaseComponent. + + + + +Ensures a Component on the GameObject that this Script belongs to. + + +Type of the Component to ensure. Must be derived from BaseComponent. + + Reference to the Component. + + + +Retrieves the first Component from this GameObject's children that matches +the specified type. + + +Type of the Component to get. Must be derived from BaseComponent. + + Reference to the Component that was retrieved. + + + +Gets a Component from the GameObject that this Script belongs to. + + +Type of the Component to get. Must be derived from BaseComponent. + + Reference to the Component that was retrieved. + + + +Adds a Component to the GameObject that this Script belongs to. + + +Type of the Component to add. Must be derived from BaseComponent. + + Reference to the Component that was added. + + + +GameObject that this Script belongs to. + + + + +Class that forms the basis of all "script"-objects that can be attached to +Entities to update each Entity's Components via C# code. + + + + +The RigidBody that you are colliding with. + + + + +The CollisionShape of the Collider that you are colliding with. + + + + +The Collider that you are colliding with. + + + + +The GameObject whose collider you are colliding with. + + + + +Struct that describes a collision + + + + +Checks if two GameObject references are different. + + GameObject to check. + Another GameObject to check with. + True if both Components are different. + + + +Checks if two GameObject references are the same. + + GameObject to check. + Another GameObject to check with. + True if both Components are the same. + + + +Gets a unique hash for this object. + + Unique hash for this object. + + + +Compares equality with another unboxed object. + + The unboxed object to compare with. + True if both objects are the same. + + + +Compares equality with an object of the same type. + + The object to compare with. + True if both objects are the same. + + + +Retrieves the native Entity object that this GameObject represents. + + Native Entity object that this GameObject represents. + + + +Retrieves the CLR Entity object that this GameObject represents. + + Entity object that this GameObject represents. + + + +Constructor for the GameObject. + + +Managed numerical representation of the ECS Entity that this GameObject +should represent. + + + + +Constructor for the GameObject. + + +The ECS Entity that this GameObject should represent. + + + + +Removes all Scripts of the specified type from this GameObject. + + Type of PLushieScripts to remove. + + + +Retrieves a immutable list of Scripts of the specified type from this +GameObject. + + Type of Scripts to retrieve. + Immutable list of Scripts of the specified type. + + + +Retrieves a Script of the specified type from child GameObjects. +If multiple Scripts of the same specified type are added on the same +child GameObject, this will retrieve the first one added. + + Type of Script to retrieve. + Reference to the Script to retrieve. + + + +Retrieves a Script of the specified type from this GameObject. +If multiple Scripts of the same specified type are added on the same +GameObject, this will retrieve the first one added. + + Type of Script to retrieve. + Reference to the Script to retrieve. + + + +Adds a Script of the specified type to this GameObject. + + Type of Script to add. + Reference to the created Script. + + + +Removes a Component from this GameObject. If no Component exists to begin +with, nothing happens. + + Type of the Component to get. + + + +Ensures a Component on this GameObject. + + Type of the Component to ensure. + +Reference to the Component. + + + + +Retrieves the first Component from this GameObject's children that matches +the specified type. + + Type of the Component to get. + +Reference to the Component or null if neither of this GameObject's children +does not have the specified Component. + + + + +Gets a Component from this GameObject. + + Type of the Component to get. + +Reference to the Component or null if this GameObject does not have the +specified Component. + + + + +Adds a Component to this GameObject. + + Type of the Component to add. + Reference to the Component that was added. + + + +Sets the active state of this GameObject. +
+The actual "activeness" of this GameObject is still dependent on the parents' +active states. +
+ +Whether to activate or deactivate this GameObject. + +
+ + +Sets the name of this GameObject. + + The name to set. + + + +Native Entity ID value for this GameObject. + + + + +Whether or not this Entity is active in the Scene hierarchy. + + + + +Whether or not this Entity alone, is active. This does not mean that this +object is active in the scene. For example, if this Entity's parent is not +active, then this Entity would also be not active. + + + + +Name of the object that this Entity represents. + + + + +Retrieves a GameObject with the specified name. If there are multiple +GameObjects with the same name, the first found GameObject will be retrieved. +There is no guaranteed order of which GameObject is considered "first". + + Name of the GameObject to find. + GameObject that has the specified name. Null if not found. + + + +Destroys the specified GameObject. Note that the specified GameObject will no +longer be a valid GameObject after this function is called. + + The GameObject to be destroyed. + + + +Creates a new GameObject in the current Scene. If multiple Scenes are loaded, +and you would like to create an object in a specific Scene, call the Scene's +CreateGameObject(). + + GameObject that represents the newly created GameObject. + + + +Lightweight object for an PlushieEngine Entity that allows for easy access +to Component and Script operations. + + + + +Constructor for a Tooltip attribute that fills in the description. + + Text to be shown when a field is hovered. + + + +Maximum value for the Ranged field. + + + + +Minimum value for the Ranged field. + + + + +Simple attribute to constrain the range of values for a field on the editor. + + + + +Converts from a native std::Stringto a managed String. + + The native std::string to convert from. + Managed copy of a native std::string. + + + +Converts from a managed String to a native std::string. + + The managed String to convert from. + Native copy of a managed String. + + + +Converts from a native Vector2 to a managed Vector2. + + The native Vector2 to convert from. + Managed copy of a native Vector2. + + + +Converts from a native Quaternion to a managed Quaternion. + + The native Quaternion to convert from. + Managed copy of a native Quaternion. + + + +Converts from a managed Quaternion to a native Quaternion. + + The managed Quaternion to convert from. + Native copy of a managed Quaternion. + + + +Converts from a native Vector2 to a managed Vector2. + + The native Vector2 to convert from. + Managed copy of a native Vector2. + + + +Converts from a managed Vector2 to a native Vector2. + + The managed Vector2 to convert from. + Native copy of a managed Vector2. + + + +Converts from a native Vector3 to a managed Vector3. + + The native Vector3 to convert from. + Managed copy of a native Vector3. + + + +Converts from a managed Vector3 to a native Vector3. + + The managed Vector3 to convert from. + Native copy of a managed Vector3. + + + +Converts from a native Entity to a managed Entity (UInt32). + + Native Entity to convert from. + Managed representation of the specified Entity. + + + +Provides functions easy and consistent syntax for converting between custom +managed and native types that are aligned. + + + + +Converts to true if this is a valid Handle. + + + + +The library that the handle was issued by. + + + + +The internal ID of the handle. + + + + +Creates a ray starting at origin along direction. + + Source of the ray. + Direction the ray travels in. + + + +The direction that a ray travels in. + + + + +The start point of the ray. + + + + +CLR version of the the SHADE Engine's Ray class that represents a ray in +3-Dimensional space. + + + + +Are two quaternions equal to each other? + + Left-hand side quaternion. + Right-hand side quaternion. + + + +Combines rotations lhs and rhs. + + Left-hand side quaternion. + Right-hand side quaternion. + + + +Spherically interpolates between a and b by t. The parameter t is not clamped. + + + + +Spherically interpolates between quaternions a and b by ratio t. The parameter t is clamped to the range [0, 1]. + + Start value, returned when t = 0. + End value, returned when t = 1. + Interpolation ratio. + A quaternion spherically interpolated between quaternions a and b. + + + +Rotates a rotation from towards to.
+The from quaternion is rotated towards to by an angular step of maxDegreesDelta (but note that the rotation will not overshoot). +Negative values of maxDegreesDelta will move away from to until the rotation is exactly the opposite direction. +
+
+ + +Converts this quaternion to one with the same orientation but with a magnitude of 1. + + + + +Creates a rotation with the specified forward and upwards directions.
+Z axis will be aligned with forward, X axis aligned with cross product between forward and upwards, and Y axis aligned with cross product between Z and X. +
+
+ + +Interpolates between a and b by t and normalizes the result afterwards. The parameter t is not clamped. + + + + +Interpolates between a and b by t and normalizes the result afterwards. The parameter t is clamped to the range [0, 1]. + + Start value, returned when t = 0. + End value, returned when t = 1. + Interpolation ratio. + A quaternion interpolated between quaternions a and b. + + + +Returns the Inverse of rotation. + + + + +Creates a rotation which rotates from fromDirection to toDirection. + + + + +Returns a rotation that rotates y degrees around the y axis, x degrees around the x axis, and z degrees around the z axis; applied in that order. + + + + +The dot product between two rotations. + + + + +Creates a rotation which rotates angle degrees around axis. + + + + +Returns the angle in degrees between two rotations a and b.
+ The angle in degrees between the two vectors. +
+ + +Gets a unique hash for this object. + + Unique hash for this object. + + + +Compares equality with another unboxed object. + + The unboxed object to compare with. + True if both objects are the same. + + + +Compares equality with an object of the same type. + + The object to compare with. + True if both objects are the same. + + + +Converts a rotation to angle-axis representation (angles in degrees). + + + + +Creates a rotation with the specified forward and upwards directions.
+The result is applied to this quaternion. +If used to orient a Transform, the Z axis will be aligned with forward and the Y axis with upwards, assuming these vectors are orthogonal. +Logs an error if the forward direction is zero. +
+ The direction to look in. + The vector that defines in which direction up is. +
+ + +Creates a rotation which rotates from fromDirection to toDirection.
+Use this to create a rotation which starts at the first Vector (fromDirection) and rotates to the second Vector (toDirection). +These Vectors must be set up in a script. +
+
+ + +Constructor to construct a Quaternion with the specified components. + + X-coordinate to set. + Y-coordinate to set. + Z-coordinate to set. + W-coordinate to set. + + + +W-component of the Quaternion. Do not directly modify quaternions. + + + + +Z-component of the Quaternion. +Don't modify this directly unless you know quaternions inside out. + + + + +Y-component of the Quaternion. +Don't modify this directly unless you know quaternions inside out. + + + + +X-component of the Quaternion. +Don't modify this directly unless you know quaternions inside out. + + + + +Shorthand for writing Quaternion(0, 0, 0, 1). + + + + +CLR version of SHADE's Quaternion class that represents an orientation. +Designed to closely match Unity's Quaternion struct. + + + + +Explicit conversion operator to enable explicit casting from a Vector2 to a +Vector3. + + Vector2 to convert from. + + + +Explicit conversion operator to enable explicit casting from a Vector3 to a +Vector2. + + Vector3 to convert from. + + + +Checks if two Vector3s are not approximately equal. This is equivalent to +calling !Vector3.IsNear() with default tolerance values. + + Vector3 to compare. + Another Vector3 to compare. + +True if all components are not approximately equal within the default +tolerance value. + + + + +Checks if two Vector3s are approximately equal. This is equivalent to +calling Vector3.IsNear() with default tolerance values. + + Vector3 to compare. + Another Vector3 to compare. + +True if all components are approximately equal within the default +tolerance value. + + + + +Calculates the division of a Vector3 with a scalar value and returns +the result. + + Scalar to divide with. + Vector3 to divide with. + The result of the scalar division. + + + +Calculates the multiplication of a Vector3 with a scalar value and returns +the result. + + Vector3 to multiply with. + Scalar to multiply with. + The result of the scalar multiplication. + + + +Calculates the division of a Vector3 with a scalar value and returns +the result. + + Scalar to divide with. + Vector3 to divide with. + The result of the scalar division. + + + +Calculates the multiplication of a Vector3 with a scalar value and returns +the result. + + Vector3 to multiply with. + Scalar to multiply with. + The result of the scalar multiplication. + + + +Calculates the component-wise multiplication of two Vector3s and returns the +result. + + Vector3 to multiply with. + Another Vector3 to multiply with. + The result of rhs subtracted from lhs. + + + +Subtracts a Vector3 from another Vector3 and returns the result. + + Vector3 to subtract from. + Another Vector3 to subtract. + The result of rhs subtracted from lhs. + + + +Adds two Vector3s together and returns the result. + + Vector3 to add. + Another Vector3 to add. + The result of lhs added to rhs + + + +Moves a point current towards target. +Similar to Lerp(), however, the function will ensure that the distance never +exceeds maxDistanceDelta. Negative values of maxDistanceDelta pushes the +vector away from target + + The current position of the point. + The target position to move to. + Maximum distance moved per call. + Vector representing the moved point. + + + +Linearly interpolates between two specified points. +This is most commonly used to find a point some fraction of the way along a +line between two endpoints. +Unlike Lerp(), t is not clamped to a range at all. + + The start Vector3, returned when t = 0.0f. + The end Vector3, returned when t = 1.0f. + Value used to interpolate between a and b. + The interpolated Vector3. + + + +Linearly interpolates between two specified points. +This is most commonly used to find a point some fraction of the way along a +line between two endpoints. + + The start Vector3, returned when t = 0.0f. + The end Vector3, returned when t = 1.0f. + +Value used to interpolate between a and b which is clamped to +the range[0, 1]. + + The interpolated Vector3. + + + +Computes and returns a Vector3 that is made from the largest components of +the two specified Vector3s. + + Vector3 to calculate maximum Vector3 with. + Another Vector3 to calculate maximum Vector3 with. + +The Vector3 that contains the largest components of the two specified +Vector3s. + + + + +Computes and returns a Vector3 that is made from the smallest components of +the two specified Vector3s. + + Vector3 to calculate minimum Vector3 with. + Another Vector3 to calculate minimum Vector3 with. + +The Vector3 that contains the smallest components of the two specified +Vector3s. + + + + +Rotates a Vector3 on the Z-axis by a specified angle in an anti-clockwise +direction. + + A Vector3 to rotate. + +Angle to rotate the vector by in an anti-clockwise direction in degrees. + + The Vector3 that represents the rotated vector. + + + +Rotates a Vector3 on the Z-axis by a specified angle in an anti-clockwise +direction. + + A Vector3 to rotate. + +Angle to rotate the vector by in an anti-clockwise direction in radians. + + The Vector3 that represents the rotated vector. + + + +Reflects a Vector3 across another Vector3. + + A Vector3 to reflect. + A normal to reflect the Vector3 across. + The Vector3 that represents vec reflected across normal. + + + +Computes and returns a Vector3 projection. + + Vector3 to project. + Vector3 to project onto. + The Vector3 that represents the projected vec onto direction. + + + +Computes and returns the cross product of 2 specified Vector3s. + + Vector3 to calculate cross product with. + Another Vector3 to calculate cross product with. + The cross product of the two Vector3s. + + + +Computes and returns the dot product of 2 specified Vector3s. + + Vector3 to calculate dot product with. + Another Vector3 to calculate dot product with. + Scalar value representing the dot product of the two Vector3s. + + + +Checks if two specified Vector3s are near in value. + + Vector3 to check if is near in value. + Another Vector3 to check if is near in value. + Amount of tolerance to do the comparison with. + +True if the two Vector3s are within the tolerance value specified + + + + +Checks if two specified Vector3s are near in value. + + Vector3 to check if is near in value. + Another Vector3 to check if is near in value. + +True if the two Vector3s are within the tolerance value specified + + + + +Gets a unique hash for this object. + + Unique hash for this object. + + + +Compares equality with another unboxed object. + + The unboxed object to compare with. + True if both objects are the same. + + + +Compares equality with an object of the same type. + + The object to compare with. + True if both objects are the same. + + + +Checks if a specified point is near this Vector3 that represents a point. + + The other point to check if we are near. + +The amount of tolerance before we consider these points as "near". + + +True if this Vector3 representing a point and the specified point are within +the range of the specified tolerance. False otherwise. + + + + +Checks if a specified point is near this Vector3 that represents a point with +a tolerance value of PLS_EPSILON. + + The other point to check if we are near. + +True if this Vector3 representing a point and the specified point are within +the range of the specified tolerance. False otherwise. + + + + +Calculates and returns the angle of this vector from the right vector. This +function returns values between -180.0f and 180.0f. + + Returns the angle of this vector from the right vector in degrees. + + + +Calculates and returns the angle of this vector from the right vector. This +function returns values between -Math.PI and Math.PI. + + Returns the angle of this vector from the right vector in radians. + + + +Calculates and returns the squared magnitude of this Vector3. + + Returns the squared length of this Vector3. + + + +Calculates and returns the magnitude of this Vector3. Note that this function +incurs a performance cost from the square root calculation. If you do not +need the precise magnitude, consider using GetSqrMagnitude() instead. + + Returns the length of this Vector3. + + + +Creates a copy of this Vector3 and returns a normalized version. + + +Returns a normalised copy of this Vector3. +If this Vector3 is a zero vector, a zero vector will be returned. + + + + +Normalises this current Vector3. This changes the data of this Vector3. +If you would like to get a copy, use GetNormalised() instead. +This function does nothing to a zero vector. + + + + +Conversion constructor to construct a Vector3 using a Vector2. + + + + + +Constructor to construct a Vector3 with the specified components. + + X-coordinate to set. + Y-coordinate to set. + Z-coordinate to set. + + + +Constructor to construct a Vector3 with the specified components with the +Z-component set to 0.0f. + + X-coordinate to set. + Y-coordinate to set. + + + +Constructor to construct a Vector3 with the specified components with the +Y and Z-component set to 0.0f. + + X-coordinate to set. + + + +Z-component of the Vector3. + + + + +Y-component of the Vector3. + + + + +X-component of the Vector3. + + + + +Shorthand for writing Vector3(0, 0, 0). + + + + +Shorthand for writing Vector3(0, 1, 0). + + + + +Shorthand for writing Vector3(1, 0, 0). + + + + +Shorthand for writing Vector3(float.PositiveInfinity, +float.PositiveInfinity, float.PositiveInfinity). + + + + +Shorthand for writing Vector3(1, 1, 1). + + + + +Shorthand for writing Vector3(float.NegativeInfinity, +float.NegativeInfinity, float.NegativeInfinity). + + + + +Shorthand for writing Vector3(-1, 0, 0). + + + + +Shorthand for writing Vector3(0, 0, 1). + + + + +Shorthand for writing Vector3(0, -1, 0). + + + + +Shorthand for writing Vector3(0, 0, -1). + + + + +CLR version of SHADE Engine's Vector3 class that represents a 3-Dimensional Vector. +Designed to closely match Unity's Vector3 struct. + + + + +Checks if two Vector2s are not approximately equal. This is equivalent to +calling !Vector2.IsNear() with default tolerance values. + + Vector2 to compare. + Another Vector2 to compare. + +True if all components are not approximately equal within the default +tolerance value. + + + + +Checks if two Vector2s are approximately equal. This is equivalent to +calling Vector2.IsNear() with default tolerance values. + + Vector2 to compare. + Another Vector2 to compare. + +True if all components are approximately equal within the default +tolerance value. + + + + +Calculates the division of a Vector2 with a scalar value and returns +the result. + + Scalar to divide with. + Vector2 to divide with. + The result of the scalar division. + + + +Calculates the multiplication of a Vector2 with a scalar value and returns +the result. + + Vector2 to multiply with. + Scalar to multiply with. + The result of the scalar multiplication. + + + +Calculates the division of a Vector2 with a scalar value and returns +the result. + + Scalar to divide with. + Vector2 to divide with. + The result of the scalar division. + + + +Calculates the multiplication of a Vector2 with a scalar value and returns +the result. + + Vector2 to multiply with. + Scalar to multiply with. + The result of the scalar multiplication. + + + +Calculates the component-wise multiplication of two Vector2s and returns the +result. + + Vector2 to multiply with. + Another Vector2 to multiply with. + The result of rhs subtracted from lhs. + + + +Subtracts a Vector2 from another Vector2 and returns the result. + + Vector2 to subtract from. + Another Vector2 to subtract. + The result of rhs subtracted from lhs. + + + +Adds two Vector2s together and returns the result. + + Vector2 to add. + Another Vector2 to add. + The result of lhs added to rhs + + + +Moves a point current towards target. +Similar to Lerp(), however, the function will ensure that the distance never +exceeds maxDistanceDelta. Negative values of maxDistanceDelta pushes the +vector away from target + + The current position of the point. + The target position to move to. + Maximum distance moved per call. + Vector representing the moved point. + + + +Linearly interpolates between two specified points. +This is most commonly used to find a point some fraction of the way along a +line between two endpoints. +Unlike Lerp(), t is not clamped to a range at all. + + The start Vector2, returned when t = 0.0f. + The end Vector2, returned when t = 1.0f. + Value used to interpolate between a and b. + The interpolated Vector2. + + + +Linearly interpolates between two specified points. +This is most commonly used to find a point some fraction of the way along a +line between two endpoints. + + The start Vector2, returned when t = 0.0f. + The end Vector2, returned when t = 1.0f. + +Value used to interpolate between a and b which is clamped to +the range[0, 1]. + + The interpolated Vector2. + + + +Computes and returns a Vector2 that is made from the largest components of +the two specified Vector2s. + + Vector2 to calculate maximum Vector2 with. + Another Vector2 to calculate maximum Vector2 with. + +The Vector2 that contains the largest components of the two specified +Vector2s. + + + + +Computes and returns a Vector2 that is made from the smallest components of +the two specified Vector2s. + + Vector2 to calculate minimum Vector2 with. + Another Vector2 to calculate minimum Vector2 with. + +The Vector2 that contains the smallest components of the two specified +Vector2s. + + + + +Rotates a Vector2 on the Z-axis by a specified angle in an anti-clockwise +direction. + + A Vector2 to rotate. + +Angle to rotate the vector by in an anti-clockwise direction in degrees. + + The Vector2 that represents the rotated vector. + + + +Rotates a Vector2 on the Z-axis by a specified angle in an anti-clockwise +direction. + + A Vector2 to rotate. + +Angle to rotate the vector by in an anti-clockwise direction in radians. + + The Vector2 that represents the rotated vector. + + + +Reflects a Vector2 across another Vector2. + + A Vector2 to reflect. + A normal to reflect the Vector2 across. + The Vector2 that represents vec reflected across normal. + + + +Computes and returns a Vector2 projection. + + Vector2 to project. + Vector2 to project onto. + The Vector2 that represents the projected vec onto direction. + + + +Computes a perpendicular Vector2 to the specified Vector2. + + Vector2 to find a perpendicular of. + +Whether the inward perpendicular Vector is retrieved. If true, the +resultant vector is rotated 90-degrees in a counter-clockwise. + + The perpendicular Vector2 relative to the specified Vector2. + + + + +Computes the inward perpendicular Vector2 to the specified Vector2. +Equivalent to calling Perpendicular(lhs, true). This means, the +resultant Vector2 is rotated 90-degrees in a counter-clockwise. + + Vector2 to find a perpendicular of. + +The perpendicular Vector2 relative to the specified Vector2. + + + + +Computes and returns the dot product of 2 specified Vector2s. + + Vector2 to calculate dot product with. + Another Vector2 to calculate dot product with. + +Scalar value representing the dot product of the two Vector2s. + + + + +Checks if two specified Vector2s are near in value. + + Vector2 to check if is near in value. + Another Vector2 to check if is near in value. + +Amount of tolerance to do the comparison with. + + +True if the two Vector2s are within the tolerance value specified + + + + +Checks if two specified Vector2s are near in value. + + Vector2 to check if is near in value. + Another Vector2 to check if is near in value. + +True if the two Vector2s are within the tolerance value specified + + + + +Gets a unique hash for this object. + + Unique hash for this object. + + + +Compares equality with another unboxed object. + + The unboxed object to compare with. + True if both objects are the same. + + + +Compares equality with an object of the same type. + + The object to compare with. + True if both objects are the same. + + + +Checks if a specified point is near this Vector2 that represents a point. + + The other point to check if we are near. + +The amount of tolerance before we consider these points as "near". + + +True if this Vector2 representing a point and the specified point are within +the range of the specified tolerance. False otherwise. + + + + +Checks if a specified point is near this Vector2 that represents a point with +a tolerance value of PLS_EPSILON. + + The other point to check if we are near. + +True if this Vector2 representing a point and the specified point are within +the range of the specified tolerance. False otherwise. + + + + +Calculates and returns the angle of this vector from the right vector. This +function returns values between -180.0f and 180.0f. + + Returns the angle of this vector from the right vector in degrees. + + + +Calculates and returns the angle of this vector from the right vector. This +function returns values between -Math.PI and Math.PI. + + Returns the angle of this vector from the right vector in radians. + + + +Calculates and returns the squared magnitude of this Vector2. + + Returns the squared length of this Vector2. + + + +Calculates and returns the magnitude of this Vector2. Note that this function +incurs a performance cost from the square root calculation. If you do not +need the precise magnitude, consider using GetSqrMagnitude() instead. + + Returns the length of this Vector2. + + + +Creates a copy of this Vector2 and returns a normalized version. + + +Returns a normalised copy of this Vector2. +If this Vector2 is a zero vector, a zero vector will be returned. + + + + +Normalises this current Vector2. This changes the data of this Vector2. +If you would like to get a copy, use GetNormalised() instead. +This function does nothing to a zero vector. + + + + +Constructor to construct a Vector2 with the specified components.. + + X-coordinate to set. + Y-coordinate to set. + + + +Constructor to construct a Vector2 with the specified components with the +Y-component set to 0.0f. + + X-coordinate to set. + + + +Y-component of the Vector2. + + + + +X-component of the Vector2. + + + + +Shorthand for writing Vector2(0, 0). + + + + +Shorthand for writing Vector2(0, 1). + + + + +Shorthand for writing Vector2(1, 0). + + + + +Shorthand for writing Vector2(float.PositiveInfinity, +float.PositiveInfinity). + + + + +Shorthand for writing Vector2(1, 1). + + + + +Shorthand for writing Vector2(float.NegativeInfinity, +float.NegativeInfinity). + + + + +Shorthand for writing Vector2(-1, 0). + + + + +Shorthand for writing Vector2(0, -1). + + + + +CLR version of SHADE Engine's Vector2 class that represents a 2-Dimensional Vector. +Designed to closely match Unity's Vector2 struct. + + + + +Checks if the specified entity is valid. This is done by checking if it +matches Pls::Entity::INVALID. + + The Entity to check. + True if the specified Entity is valid. + + + +Static class that contains useful utility functions for working with Entity. + + + + +Manages all resources in multiple ResourceLibraries. + + + + +Base class for SHResourceLibrary that holds information about the library type. + + + + +Template Specialization for Handle that represents a type-less Handle. + + + + +Converts to true if this is a valid Handle. + + + + +Native ID type of a handle + + + + +Base implementation of the Handle that is not templated to allow for holding +generic non-type-specific Handles. + + + + +Exception thrown when a generic Handle is being casted to the wrong type. + + + + +Exception thrown when an invalid Handle was dereferenced. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
\ No newline at end of file diff --git a/bin/Release/SHADE_CSharp.xml b/bin/Release/SHADE_CSharp.xml new file mode 100644 index 00000000..daeaa3c5 --- /dev/null +++ b/bin/Release/SHADE_CSharp.xml @@ -0,0 +1,1029 @@ + + + + SHADE_CSharp + + + + + Interface for a CallbackAction that all variants inherit from. + + + + + Whether or not this CallbackAction is runtime assigned. If it is, then the + TargetMethodName and TargetObject properties are invalid. + + + + + Name of the method that this CallbackAction is using. + + + + + Object which the specified target method is called on. + + + + + Represents a function call that can be serialised and put togetheer with scripts. + This variant accepts functions with 1 parameter. + + + + + + + + + + + + + + Constructs an empty Callback action. + + + + + Constructs a CallbackAction that represents a call to the specified static + method. + + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a CallbackAction that represents a call to a specified member + method on the specified target. + + Object to call the method on. + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a Callback action based on an action. + + Action that wraps a function to be called. + + + + Invokes the CallbackAction's stored method/action with the specified parameters. + + + + + Represents a function call that can be serialised and put togetheer with scripts. + This variant accepts functions with 2 parameters. + + + + + + + + + + + + + + Constructs an empty Callback action. + + + + + Constructs a CallbackAction that represents a call to the specified static + method. + + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a CallbackAction that represents a call to a specified member + method on the specified target. + + Object to call the method on. + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a Callback action based on an action. + + Action that wraps a function to be called. + + + + Invokes the CallbackAction's stored method/action with the specified parameters. + + + + + Represents a function call that can be serialised and put togetheer with scripts. + This variant accepts functions with 3 parameters. + + + + + + + + + + + + + + Constructs an empty Callback action. + + + + + Constructs a CallbackAction that represents a call to the specified static + method. + + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a CallbackAction that represents a call to a specified member + method on the specified target. + + Object to call the method on. + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a Callback action based on an action. + + Action that wraps a function to be called. + + + + Invokes the CallbackAction's stored method/action with the specified parameters. + + + + + Represents a function call that can be serialised and put togetheer with scripts. + This variant accepts functions with 4 parameters. + + + + + + + + + + + + + + Constructs an empty Callback action. + + + + + Constructs a CallbackAction that represents a call to the specified static + method. + + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a CallbackAction that represents a call to a specified member + method on the specified target. + + Object to call the method on. + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a Callback action based on an action. + + Action that wraps a function to be called. + + + + Invokes the CallbackAction's stored method/action with the specified parameters. + + + + + Represents a function call that can be serialised and put togetheer with scripts. + This variant accepts functions with 5 parameters. + + + + + + + + + + + + + + Constructs an empty Callback action. + + + + + Constructs a CallbackAction that represents a call to the specified static + method. + + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a CallbackAction that represents a call to a specified member + method on the specified target. + + Object to call the method on. + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a Callback action based on an action. + + Action that wraps a function to be called. + + + + Invokes the CallbackAction's stored method/action with the specified parameters. + + + + + Represents a function call that can be serialised and put togetheer with scripts. + This variant accepts functions with 6 parameters. + + + + + + + + + + + + + + Constructs an empty Callback action. + + + + + Constructs a CallbackAction that represents a call to the specified static + method. + + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a CallbackAction that represents a call to a specified member + method on the specified target. + + Object to call the method on. + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a Callback action based on an action. + + Action that wraps a function to be called. + + + + Invokes the CallbackAction's stored method/action with the specified parameters. + + + + + Represents a function call that can be serialised and put togetheer with scripts. + This variant accepts functions with 7 parameters. + + + + + + + + + + + + + + Constructs an empty Callback action. + + + + + Constructs a CallbackAction that represents a call to the specified static + method. + + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a CallbackAction that represents a call to a specified member + method on the specified target. + + Object to call the method on. + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a Callback action based on an action. + + Action that wraps a function to be called. + + + + Invokes the CallbackAction's stored method/action with the specified parameters. + + + + + Represents a function call that can be serialised and put togetheer with scripts. + This variant accepts functions with 8 parameters. + + + + + + + + + + + + + + Constructs an empty Callback action. + + + + + Constructs a CallbackAction that represents a call to the specified static + method. + + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a CallbackAction that represents a call to a specified member + method on the specified target. + + Object to call the method on. + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a Callback action based on an action. + + Action that wraps a function to be called. + + + + Invokes the CallbackAction's stored method/action with the specified parameters. + + + + + Represents a function call that can be serialised and put togetheer with scripts. + This variant accepts functions with 9 parameters. + + + + + + + + + + + + + + Constructs an empty Callback action. + + + + + Constructs a CallbackAction that represents a call to the specified static + method. + + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a CallbackAction that represents a call to a specified member + method on the specified target. + + Object to call the method on. + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a Callback action based on an action. + + Action that wraps a function to be called. + + + + Invokes the CallbackAction's stored method/action with the specified parameters. + + + + + Represents a function call that can be serialised and put togetheer with scripts. + This variant accepts functions with 10 parameters. + + + + + + + + + + + + + + Constructs an empty Callback action. + + + + + Constructs a CallbackAction that represents a call to the specified static + method. + + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a CallbackAction that represents a call to a specified member + method on the specified target. + + Object to call the method on. + Method to call. + + Thrown if a method that is not compatible with the target is specified. The method's + source type must match the target's type. + + + + + Constructs a Callback action based on an action. + + Action that wraps a function to be called. + + + + Invokes the CallbackAction's stored method/action with the specified parameters. + + + + + Interface for a CallbackEvent that all variants inherit from. + + + + + Registers an empty ICallbackAction. + + + + + Registers an ICallbackAction with the event such that it will be called in + future + + ICallbackAction to register with. + + + + Deregisters an ICallbackAction that was previously added. This should + only emit a warning if an action that was not previous added was + provided. + + ICallbackAction to remove. + + + + Iterable set of ICallbackActions that were registered to this event. + + + + + A container of CallbackActions that is correlated to a specific scenario as + specified by the user of this class. + This variant accepts CallbackEvents with 1 generic parameter. + + + + + + + + + + + + + + Adds a CallbackAction into the event. + + CallbackAction to add. + + + + Constructs and adds a CallbackACtion into the event. + + System.Action to add as a CallbackAction. + + + + Constructs and adds a CallbackACtion into the event. + + Object to call the method on. + Method to call. + + + + + + + Invokes all stored CallbackActions with the specified parameters. + + + + + A container of CallbackActions that is correlated to a specific scenario as + specified by the user of this class. + This variant accepts CallbackEvents with 1 generic parameter. + + + + + + + + + + + + + + Adds a CallbackAction into the event. + + CallbackAction to add. + + + + Constructs and adds a CallbackACtion into the event. + + System.Action to add as a CallbackAction. + + + + Constructs and adds a CallbackACtion into the event. + + Object to call the method on. + Method to call. + + + + + + + Invokes all stored CallbackActions with the specified parameters. + + + + + A container of CallbackActions that is correlated to a specific scenario as + specified by the user of this class. + This variant accepts CallbackEvents with 1 generic parameter. + + + + + + + + + + + + + + Adds a CallbackAction into the event. + + CallbackAction to add. + + + + Constructs and adds a CallbackACtion into the event. + + System.Action to add as a CallbackAction. + + + + Constructs and adds a CallbackACtion into the event. + + Object to call the method on. + Method to call. + + + + + + + Invokes all stored CallbackActions with the specified parameters. + + + + + A container of CallbackActions that is correlated to a specific scenario as + specified by the user of this class. + This variant accepts CallbackEvents with 1 generic parameter. + + + + + + + + + + + + + + Adds a CallbackAction into the event. + + CallbackAction to add. + + + + Constructs and adds a CallbackACtion into the event. + + System.Action to add as a CallbackAction. + + + + Constructs and adds a CallbackACtion into the event. + + Object to call the method on. + Method to call. + + + + + + + Invokes all stored CallbackActions with the specified parameters. + + + + + A container of CallbackActions that is correlated to a specific scenario as + specified by the user of this class. + This variant accepts CallbackEvents with 1 generic parameter. + + + + + + + + + + + + + + Adds a CallbackAction into the event. + + CallbackAction to add. + + + + Constructs and adds a CallbackACtion into the event. + + System.Action to add as a CallbackAction. + + + + Constructs and adds a CallbackACtion into the event. + + Object to call the method on. + Method to call. + + + + + + + Invokes all stored CallbackActions with the specified parameters. + + + + + A container of CallbackActions that is correlated to a specific scenario as + specified by the user of this class. + This variant accepts CallbackEvents with 1 generic parameter. + + + + + + + + + + + + + + Adds a CallbackAction into the event. + + CallbackAction to add. + + + + Constructs and adds a CallbackACtion into the event. + + System.Action to add as a CallbackAction. + + + + Constructs and adds a CallbackACtion into the event. + + Object to call the method on. + Method to call. + + + + + + + Invokes all stored CallbackActions with the specified parameters. + + + + + A container of CallbackActions that is correlated to a specific scenario as + specified by the user of this class. + This variant accepts CallbackEvents with 1 generic parameter. + + + + + + + + + + + + + + Adds a CallbackAction into the event. + + CallbackAction to add. + + + + Constructs and adds a CallbackACtion into the event. + + System.Action to add as a CallbackAction. + + + + Constructs and adds a CallbackACtion into the event. + + Object to call the method on. + Method to call. + + + + + + + Invokes all stored CallbackActions with the specified parameters. + + + + + A container of CallbackActions that is correlated to a specific scenario as + specified by the user of this class. + This variant accepts CallbackEvents with 1 generic parameter. + + + + + + + + + + + + + + Adds a CallbackAction into the event. + + CallbackAction to add. + + + + Constructs and adds a CallbackACtion into the event. + + System.Action to add as a CallbackAction. + + + + Constructs and adds a CallbackACtion into the event. + + Object to call the method on. + Method to call. + + + + + + + Invokes all stored CallbackActions with the specified parameters. + + + + + A container of CallbackActions that is correlated to a specific scenario as + specified by the user of this class. + This variant accepts CallbackEvents with 1 generic parameter. + + + + + + + + + + + + + + Adds a CallbackAction into the event. + + CallbackAction to add. + + + + Constructs and adds a CallbackACtion into the event. + + System.Action to add as a CallbackAction. + + + + Constructs and adds a CallbackACtion into the event. + + Object to call the method on. + Method to call. + + + + + + + Invokes all stored CallbackActions with the specified parameters. + + + + + A container of CallbackActions that is correlated to a specific scenario as + specified by the user of this class. + This variant accepts CallbackEvents with 1 generic parameter. + + + + + + + + + + + + + + Adds a CallbackAction into the event. + + CallbackAction to add. + + + + Constructs and adds a CallbackACtion into the event. + + System.Action to add as a CallbackAction. + + + + Constructs and adds a CallbackACtion into the event. + + Object to call the method on. + Method to call. + + + + + + + Invokes all stored CallbackActions with the specified parameters. + + + + diff --git a/bin/Release/SHADE_Managed.xml b/bin/Release/SHADE_Managed.xml new file mode 100644 index 00000000..7b653116 --- /dev/null +++ b/bin/Release/SHADE_Managed.xml @@ -0,0 +1,6250 @@ + + + + "SHADE_Managed" + + + + +Retrieves the duration that the specified key has not been held or was last +not been held for. + + The key to check. + Time in seconds that the key was held. + + + +Retrieves the duration that the specified key has been held or was last held +for. + + The key to check. + Time in seconds that the key was held. + + + +Retrieves the duration that the specified key has not been held or was last +not been held for. + + The key to check. + Time in seconds that the key was held. + + + +Retrieves the duration that the specified key has been held or was last held +for. + + The key to check. + Time in seconds that the key was held. + + + +Sets the position of the mouse cursor relative to the top left corner of the +window. + + +Position of the mouse in window pixel coordinates to set. + + + + +Checks if a specified mouse button is no longer pressed and was pressed +before. + + MouseCode of the mouse button to check. + +True during the frame the user releases the given mouse button. + + + + +Checks if a specified mouse button is pressed and was not pressed before. + + MouseCode of the mouse button to check. + +True during the frame the user pressed the given mouse button. + + + + +Checks if a specified mouse button is being held down. +This will also be true if GetMouseButtonDown() is true. + + MouseCode of the mouse button to check. + True while the user holds down the mouse button specified. + + + +Checks if a specified key is no longer pressed pressed and was pressed +before. + + KeyCode of the key to check. + +True during the frame the user releases the key identified by name. + + + + +Checks if a specified key is pressed and was not pressed before. + + KeyCode of the key to check. + +True during the frame the user starts pressing down the key specified. + + + + +Checks if a specified key is being held down. +This will also be true if GetKeyDown() is true. + + KeyCode of the key to check. + True while the user holds down the key specified. + + + +Amnount of vertical mouse scroll in this frame. + + + + +Mouse position in screen coordinates relative to the top left of the window. +This value is a Vector3 for compatibility with functions that have Vector3 +arguments. The z component of the Vector3 is always 0 + + + + +Represents the available supported mouse keycodes that can be passed into the +mouse-button-based Input functions. + + + + +Represents the available supported keycodes that can be passed into the +key-based Input functions. + +Attempting to follow https://docs.unity3d.com/ScriptReference/KeyCode.html +Win32 keycodes are shift-insensitive, i.e. 'A' and 'a' are the same keycode and '1' and '!' are the same keycode + + + + +Static class responsible for providing access to Input-related functionality. + + + + +Simple attribute to mark that a field in a Script should be serialised. + + + + +Cleans up all required components for managed code. + + + + +Reloads the managed script assembly. +Take note that this will clear all existing scripts, ensure that the scene +is saved before doing so. +Equivalent to calling UnloadScriptAssembly() and then LoadScriptAssembly(). + + + + +Loads the managed script assembly. Ensure this is only called after +UnloadScriptAssembly() has been called. + + + + +Unloads the managed script assembly. +Take note that this will clear all existing scripts, ensure that the scene +is saved before doing so. + + + + +Initialises all required components for managed code. + + + + +Name of the Managed Library that contains the C# scripts written externally. + + + + +Static class that contains the functions for interfacing with the core +PlushieEngine written in C++ for managing the lifecycle of managed code. + + + + +Default Constructor + + + + +Custom AssemblyLoadContext marked as collectible so that it can be unloaded. + + + + +Time taken for Physics simulations. You should use this for operations +within Script.FixedUpdate() + + + + +Time taken to process the previous frame. + + + + +Static class that contains the functions for working with time. + + + + +Static class that wraps up certain functions in the SHPhysicsSystem so that +accessing it from SHADE_Managed would not cause issues due to C++20 features. + + + + +Constructor for a Tooltip attribute that fills in the description. + + Text to be shown when a field is hovered. + + + +Description that is to be shown in the Tooltip. + + + + +Simple attribute to provide a field in a script with a tooltip. + + + + +Checks if a specified file exists. + + File path to the file to check. + True if the file exists + + + +Deletes the folder and all files in it as specified by the file path. + + File path to the file to delete. + + + +Deletes the file as specified by the file path. + + File path to the file to delete. + + + +Reads the file via the specified path that represents a build log of error +and warning messages. + + +File path to the build log of script builds done by BuildScriptAssembly() to +dump and process. + + + + +Registers events for the scripting system + + + + +Loads all the function pointers to CLR code that we need to execute. + + + + +Generates a .csproj file for editing and compiling the C# scripts. + + File path to the generated file. + + + +Utilises execution of a external batch file for invoking the dotnet build +tool to compile C# scripts in the Assets folder into the SHADE_Scripting +C# assembly DLL. + + +Whether or not a debug build will be built. Only debug built C# assemblies +can be debugged. + + +Whether or not we are reloading the assembly, if so, unload and then reload it. + + Whether or not the build succeeded. + + + +Performs a redo for script inspector changes if it exists. + + + + +Performs an undo for script inspector changes if it exists. + + + + +Renders the set of attached Scripts for the specified Entity into the +inspector. +
+This function is meant for consumption from native code in the inspector +rendering code. +
+ The Entity to render the Scripts of. +
+ + +Creates scripts and sets fields for the specified Entity based on the specified +YAML node. + + The Entity to deserialise a Script on to. + +YAML Node that contains the serialised script data. + + True if successfully deserialised. + + + +Performs serialization of all scripts for the specified entity into the +YAML::Node specified. This node will contain all serialised scripts after +calling this function. + + The Entity to Serialise. + +YAML Node that will store the serialised scripts. + + True if successfully serialised. + + + +Removes all Scripts attached to the specified Entity. Unlike +RemoveAllScripts(), this removes all the scripts immediately. +Does not do anything if the specified Entity is invalid or does not have any +Scripts attached. + + The entity to remove the scripts from. + +Whether or not to call OnDestroy on the scripts. This is ignored if not in +play mode. + + + + +Removes all Scripts attached to the specified Entity. Does not do anything +if the specified Entity is invalid or does not have any Scripts +attached. + + The entity to remove the scripts from. + + + +Adds a Script to a specified Entity. Note that while you can call this +multiple times on a specified Entity, it will work for all intents and +purposes but GetScript<T>() (C# only) currently only +gives you the first Script added of the specified type. + + The entity to add a script to. + Type name of the script to add. + +True if successfully added. False otherwise with the error logged to the +console. + + + + +Shuts down the DotNetRuntime. + + + + +Executes the OnCollision*()s and OnTrigger*()s of the Scripts that are attached +to Entities. + + + + +Executes the FixedUpdate()s of the Scripts that are attached to +Entities. + + + + +Reloads the managed script assembly. +Take note that this will clear all existing scripts, ensure that the scene +is saved before doing so. + + + + +Unloads the managed script assembly. +Take note that this will clear all existing scripts, ensure that the scene +is saved before doing so. + + + + +Loads the managed script assembly. Ensure this is only called after +UnloadScriptAssembly() has been called. + + + + +Initialises the DotNetRuntime and retrieves function pointers to all +functions on the CLR used to interface with the engine. + + + + +Manages initialisation of the DotNetRuntime and interfacing with CLR code written +and executed on .NET. + + + + +Deserialises a YAML node that contains a map of Scripts and copies the +deserialised data into the specified object if there are matching fields. + + +The JSON string that contains the data to copy into this Script object. + + The object to copy deserialised data into. + + + +Creates a JSON node that represents the specified object and its associated +serialisable fields. Public fields and fields marked with the SerialiseField +attribute will be serialised. + + The object to serialise. + + + +Checks if a specified field is a candidate for serialisation. This means that +the field is public or private with the [SerialiseField] attribute. + + The field to check. + +True if the specified field is a candidate for serialisation. + + + + +Retrieves a set of all non-static (instance) fields from a specified object. + + The object to get non-static fields from. + Immutable list of non-static fields. + + + +Contains useful static functions for working with Reflection. + + + +Converts the node to a YAML string. + + +Emits the node to the given output stream. + + +Emits the node to the given {@link Emitter}. If there is an error in writing, +{@link Emitter#good} will return false. + + + + Loads the input file as a list of YAML documents. + + @throws {@link ParserException} if it is malformed. + @throws {@link BadFile} if the file cannot be loaded. + + + + Loads the input stream as a list of YAML documents. + + @throws {@link ParserException} if it is malformed. + + + + Loads the input string as a list of YAML documents. + + @throws {@link ParserException} if it is malformed. + + + + Loads the input string as a list of YAML documents. + + @throws {@link ParserException} if it is malformed. + + + + Loads the input file as a single YAML document. + + @throws {@link ParserException} if it is malformed. + @throws {@link BadFile} if the file cannot be loaded. + + + + Loads the input stream as a single YAML document. + + @throws {@link ParserException} if it is malformed. + + + + Loads the input string as a single YAML document. + + @throws {@link ParserException} if it is malformed. + + + + Loads the input string as a single YAML document. + + @throws {@link ParserException} if it is malformed. + + + +Handles a "TAG" directive, which should be of the form 'handle prefix', +where 'handle' is converted to 'prefix' in the file. + + + +Handles a "YAML" directive, which should be of the form 'major.minor' (like +a version number). + + + +Reads any directives that are next in the queue, setting the internal +{@code m_pDirectives} state. + + + + Handles the next document by calling events on the {@code eventHandler}. + + @throw a ParserException on error. + @return false if there are no more documents + + + +Resets the parser with the given input stream. Any existing state is +erased. + + + +Evaluates to true if the parser has some valid input to be read. + + +Constructs a parser from the given input stream. The input stream must +live as long as the parser. + + + +Constructs an empty parser (with no input. + + +A parser turns a stream of bytes into one stream of "events" per YAML +document in the input stream. + + + + +Renders a context menu when right clicked for the scripts + + The Entity to render the Scripts of. + The Script to render the inspector for. + + + +Renders a field specified into the inspector. + + The field to render. + +The object that contains the data of the field to render. + + + + +Renders a single specified Script's inspector. + + The Entity to render the Scripts of. + The Script to render the inspector for. + +Indices used internally to differentiate each rendered Script +inspector. This is required to open and close each Script's inspector +independently from each other. + + + + +Redoes the last script inspector change if there is any. + + + + +Undoes the last script inspector change if there is any. + + + + +Renders a dropdown button that allows for the addition of PlushieScripts +onto the specified Entity. + + The Entity to add PlushieScripts to. + + + +Renders the set of attached Scripts for the specified Entity into the +inspector. +
+This function is meant for consumption from native code in the inspector +rendering code. +
+ The Entity to render the Scripts of. +
+ + +Static class for Editor-related functions + + + + +Processes a YAML node that contains a list of multiple scripts to be loaded +into the specified Entity. +

+This function should only be called from native unmanaged code. +
+ +The Entity to attach the deserialised Scripts to. + + +Pointer to the YAML::Node that contains serialized script data. + + +
+ + +Populates a YAML node with the scripts for a specified Entity. +

+This function should only be called from native unmanaged code. +
+ The Entity to Serialise. + +Pointer to a YAML::Node that will be populated with all of the serialised +scripts and their associated fields. + + +True if serialisation is successful. False if the buffer is too small for +the serialised output. + +
+ + +Executes OnCollision*() and OnTrigger*() for all scripts. + + + + +Executes LateUpdate() for all scripts. + + + + +Executes Update() for all scripts. + + + + +Executes FixedUpdate() for all scripts. + + + + +Retrieves a immutable list of available scripts that can be added. + + Immutable list of available scripts that can be added. + + + +Cleans up data stored in the ScriptStore to free up memory for garbage +collection. + + + + +Cleans up scripts that were marked for deletion. This calls the OnDestroy() +for these Scripts. + + + + +Sets up scripts that were marked for initialization. This calls the Awake() +and Start() for Scripts that have yet to have done so. + + + + +Initializes the ScriptStore to allocate and pre-populate reflection data. + + + + +Removes all Scripts attached to the specified Entity. Unlike +RemoveAllScripts(), this removes all the scripts immediately. +Does not do anything if the specified Entity is invalid or does not have any +Scripts attached. + + The entity to remove the scripts from. + +Whether or not to call OnDestroy on the scripts.This is ignored if not in +play mode. + + + + +Removes all Scripts attached to the specified Entity. Does not do anything +if the specified Entity is invalid or does not have any Scripts +attached. + + The entity to remove the scripts from. + + + +Removes a specific script from the + + The entity to remove the script from. + The script to remove. + True if successfully removed. False otherwise. + + + +Removes all Scripts of the specified type from the specified Entity. + + +Type of script to remove. +This needs to be a default constructable Script. + + The entity to remove the script from. + +If the specified Entity is invalid. + + + + +Retrieves an immutable list of all scripts attached to a specified Entity. + + +The entity which the scripts to retrieve are attached. + + +Immutable list of references to scripts attached to the specified Entity. +This can also be null if there are no scripts at all or an invalid Entity +was specified. + + + + +Retrieves a immutable list of scripts from the specified Entity that +matches the specified type. +
+Note that this function allocates. It should be used sparingly. +
+ +Type of scripts to get. +This needs to be a default constructable Script. + + +The entity which the scripts to retrieve are attached. + + +Immutable list of references to scripts of the specified type. + +
+ + +Retrieves the first Script from the specified Entity's children that matches +the specified type. + + +Type of script to get. +This needs to be a default constructable Script. + + +The entity which the script to retrieve is attached. + + +Reference to the script. This can be null if no script of the specified +type is attached. + + +If the specified Entity is invalid. + + + + +Retrieves the first Script from the specified Entity that matches the +specified type. + + +Type of script to get. +This needs to be a default constructable Script. + + +The entity which the script to retrieve is attached. + + +Reference to the script. This can be null if no script of the specified +type is attached. + + +If the specified Entity is invalid. + + + + +Adds a Script to a specified Entity. +
+This function is meant for consumption from native code or for serialisation +purposes. If you are writing in C# or C++/CLI and not doing serialisation, +use AddScript<T>() instead as it is faster. +
+ The entity to add a script to. + The entity to add a script to. + +Out parameter handle to the Script that was created. + + +True if successfully added. False otherwise with the error logged to the +console. + +
+ + +Adds a Script to a specified Entity. +
+This function is meant for consumption from native code. If you are writing +in C# or C++/CLI, use AddScript<T>() instead as it is faster. +
+ The entity to add a script to. + The entity to add a script to. + +True if successfully added. False otherwise with the error logged to the +console. + +
+ + +Adds a Script to a specified Entity. + + +Type of script to add. +This needs to be a default constructable PlushieScript. + + The entity to add a script to. + Reference to the script added. + +If the specified Entity is invalid. + + + + +Responsible for managing all scripts attached to Entities as well as executing +all lifecycle functions of scripts. + + + + +Checks if two Colors are not approximately equal. + + Color to compare. + Another Color to compare. + +True if all components are not approximately equal within the default +tolerance value. + + + + +Checks if two Colors are approximately equal. + + Color to compare. + Another Color to compare. + +True if all components are approximately equal within the default +tolerance value. + + + + +Calculates the division of a Color with a scalar value and returns +the result. + + Scalar to divide with. + Color to divide with. + The result of the scalar division. + + + +Calculates the multiplication of a Color with a scalar value and returns +the result. + + Color to multiply with. + Scalar to multiply with. + The result of the scalar multiplication. + + + +Calculates the component-wise multiplication of two Colors and returns the +result. + + Color to multiply with. + Another Color to multiply with. + The result of rhs subtracted from lhs. + + + +Subtracts a Color from another Color and returns the result. + + Color to subtract from. + Another Color to subtract. + The result of rhs subtracted from lhs. + + + +Adds two Colors together and returns the result. + + Color to add. + Another Color to add. + The result of lhs added to rhs + + + +Linearly interpolates between two specified points. +This is most commonly used to find a point some fraction of the way along a +line between two endpoints. +Unlike Lerp(), t is not clamped to a range at all. + + The start Color, returned when t = 0.0. + The end Color, returned when t = 1.0. + Value used to interpolate between a and b. + The interpolated Color. + + + +Linearly interpolates between two specified points. +This is most commonly used to find a point some fraction of the way along a +line between two endpoints. + + The start Color, returned when t = 0.0. + The end Color, returned when t = 1.0. + +Value used to interpolate between a and b which is clamped to +the range[0, 1]. + + The interpolated Vector3. + + + +Gets a unique hash for this object. + + Unique hash for this object. + + + +Compares equality with another unboxed object. + + The unboxed object to compare with. + True if both objects are the same. + + + +Compares equality with an object of the same type. + + The object to compare with. + True if both objects are the same. + + + +Alpha component of the colour. Ranges from 0.0f to 1.0f. + + + + +Blue component of the colour. Ranges from 0.0f to 1.0f. + + + + +Green component of the colour. Ranges from 0.0f to 1.0f. + + + + +Red component of the colour. Ranges from 0.0f to 1.0f. + + + + +Constructor to construct a Color with the specified components. + + Red component to set. + Green component to set. + Blue component to set. + Alpha component to set. + + + +Constructor to construct a Color with the specified components with the +alpha component set to 1.0f. + + Red component to set. + Green component to set. + Blue component to set. + + + +Constructor to construct a Color with the specified components with the +blue and alpha component set to 1.0f. + + Red component to set. + Green component to set. + + + +Constructor to construct a Color with the specified components with the +green, blue and alpha component set to 1.0f. + + Red component to set. + + + +Pure yellow, mix of pure red and green. + + + + +Pure magenta, mix of pure red and blue. + + + + +Pure cyan, mix of pure green and blue. + + + + +Pure blue. + + + + +Pure green. + + + + +Pure red. + + + + +Pure white. + + + + +Dark Gray, darker than gray. + + + + +Gray, halfway between black and white. + + + + +Light Gray, lighter than gray. + + + + +Pure black. + + + + +A static class that contains a set of default Colors. + + + + +CLR version of the the SHADE Engine's Color struct which describes a Color +encoded using floating point numbers that range from 0.0f to 1.0f. + + + + +Creates a inline button widget. +
+Wraps up ImGui::Button(). +
+ Text to display. + True if button was pressed. +
+ + +Creates a small inline button widget. +
+Wraps up ImGui::SmallButton(). +
+ Text to display. + True if button was pressed. +
+ + +Creates a visual text widget. +
+Wraps up ImGui::Text(). +
+ Text to display. +
+ + +Creates a menu item in the list of items for a mini popup. +
+Wraps up ImGui::MenuItem(). +
+ Label used to identify this widget. + Whether or not the menu item was selected. +
+ + +Opens the popup that was defined with the specified label. +
+Wraps up ImGui::OpenPopup(). +
+
+ + +Marks the end of a definition of a mini pop up that can show options. +
+Wraps up ImGui::EndPopup(). +
+
+ + +Marks the start of a definition of a mini pop up that can show options. +
+Wraps up ImGui::BeginPopup(). +
+ Label used to identify this widget. + Whether or not the pop up is open. +
+ + +Creates a collapsing title header. +
+Wraps up ImGui::CollapsingHeader(). +
+ Label for the header. + True if the header is open, false otherwise. +
+ + +Unindents the widgets rendered after this call. +
+Wraps up ImGui::Unindent(). +
+
+ + +Indents the widgets rendered after this call. +
+Wraps up ImGui::Indent(). +
+
+ + +Marks the end of a stack of ImGui widgets from the last PushID() call. +
+Wraps up ImGui::PopID(). +
+
+ + +Marks the start of a stack of ImGui widgets with the specified id. +
+Wraps up ImGui::PushID(). +
+ Integer-based ID. +
+ + +Marks the start of a stack of ImGui widgets with the specified id. +
+Wraps up ImGui::PushID(). +
+ String-based ID. +
+ + +Maximum length of a string supported by InputTextField() + + + + +Static class that contains useful functions for Editor UI using ImGui. + + + + +Redoes the last undo-ed command if it exists. + + + + +Undos the last added command if it exists. + + + + +Adds a command onto the stack. + + + + + +True if there is a redoable action in the stack. + + + + +True if there is an undoable action in the stack. + + + + +Command for the stack that represents a data modification. + + + + +Class that is able to store a stack of actions that can be done and redone. + + + + +To be called from native code when a Collision Shape has been changed. + + +The entity which has it's collision shape changed. + + + + +To be called from native code when a collision shape has been removed. + + The entity which has it's collision shape removed. + + + +Retrieves a ColliderBound at the specified index in the ColliderBound list +and casts it to the appropriate type. + + Type of the ColliderBound to cast to. + Index to retrieve a ColliderBound from. + ColliderBound for the specified index. + + + +Retrieves a ColliderBound at the specified index in the ColliderBound list. + + Index to retrieve a ColliderBound from. + ColliderBound for the specified index. + + + +Total number of ColliderShapes in the Collider component. + + + + +Constructs a Collider Component that represents a native SHColliderComponent +component tied to the specified Entity. + + Entity that this Component will be tied to. + + + +CLR version of the the SHADE Engine's SHColliderComponent. +A single Collider component can contain one or multiple Collider Bounds. + + + + + + + + + + +Radius of the Bounding Sphere formed by this bound. + + + + +Center of the Bounding Sphere formed by this bound. + + + + +Sphere-shaped Collider Bound. + + + + + + + + + + +Position of the top right front corner of the Bounding Box formed by this +bound. + + + + +Position of the bottom left back corner of the Bounding Box formed by this +bound. + + + + +Half of the scale of the Bounding Box formed by this bound. + + + + +Center of the Bounding Box formed by this bound. + + + + +Box-shaped Collider Bound. + + + + +Computes a Raycast and checks if there is a collision with any object. + + The ray to cast. + Maximum distance for the raycast check. + True if the ray intersects with an object in the scene. + + + +Checks if the specified point is within this shape's bounds. + + Point to test with. + True if the point is in the shape's bounds. + + + +Base interface for all Collider Shapes. + + + +@brief The density of the collider that determines the mass of the collision shape + if it is automatically computed. Must be a positive number. + + + +@brief The bounciness factor of the physics object., clamped between [0,1].
+ 0 means the object will never bounce. + 1 means the object never loses energy on a bounce. + +
+ +@brief The friction coefficient of the physics object., clamped between [0,1].
+ 0 means the object will never experience friction. + 1 means the friction force against the object is equal to the applied force. + +
+ +@brief Sets the mass density of the physics material. +@param newDensity The density value to set. Always made positive. + + + +@brief Sets the bounciness factor of the physics material. +@param newBounciness The bounciness value to set. Clamped between [0,1]. + + + +@brief Sets the friction coefficient of the physics material. +@param newFriction The friction value to set. Clamped between [0,1]. + + + +@brief Default constructor for a physics material. +@param friction The friction of the material. Clamped between [0,1]. Defaults to 0.4. +@param bounciness The bounciness of the material. Clamped between [0,1]. +@param density The mass density of the material. Always made positive. + + + + +Closes the current window, and depending on the implementation, should also +close the application. + + + + +Retrieves the current window fullscreen status. + + The current window fullscreen status.. + + + +Retrieves the current window height. + + The current window height. + + + +Retrieves the current window width. + + The current window width. + + + +Static class that wraps up certain functions in the SHGraphicsSystem so that +accessing it from SHADE_Managed would not cause issues due to C++20 features. + + + + @brief Perform ImGui and ImGui Backend Render + + + + + @brief Start new frame for editor + + + + + @brief Initialise Backend for ImGui (SDL and Vulkan backend) + + @param sdlWindow Pointer to SDL_Window + + + + @brief Set the Style for the editor + + @param style Desired style + + + + @brief Safely shutdown the editor + + + + + @brief Update the editor and add to ImGui DrawList + + @param dt Delta-time of the frame + + + + @brief Initialise the editor + + @param sdlWindow pointer to SDL_Window object created in application + + + + @brief Style options + + + + + @brief SHEditor static class contains editor variables and implementation of editor functions. + + + + + Get the YUV conversion mode, returning the correct mode for the resolution + when the current conversion mode is SDL_YUV_CONVERSION_AUTOMATIC + + \since This function is available since SDL 2.0.8. + + + + Get the YUV conversion mode + + \since This function is available since SDL 2.0.8. + + + + Set the YUV conversion mode + + \since This function is available since SDL 2.0.8. + + + + Perform low-level surface scaled blitting only. + + This is a semi-private function and it performs low-level surface blitting, + assuming the input rectangles have already been clipped. + + \param src the SDL_Surface structure to be copied from + \param srcrect the SDL_Rect structure representing the rectangle to be + copied + \param dst the SDL_Surface structure that is the blit target + \param dstrect the SDL_Rect structure representing the rectangle that is + copied into + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_BlitScaled + + + + Perform a scaled surface copy to a destination surface. + + SDL_UpperBlitScaled() has been replaced by SDL_BlitScaled(), which is + merely a macro for this function with a less confusing name. + + \since This function is available since SDL 2.0.0. + + \sa SDL_BlitScaled + + + + Perform bilinear scaling between two surfaces of the same format, 32BPP. + + \since This function is available since SDL 2.0.16. + + + + Perform a fast, low quality, stretch blit between two surfaces of the same + format. + + Please use SDL_BlitScaled() instead. + + \since This function is available since SDL 2.0.0. + + + + Perform low-level surface blitting only. + + This is a semi-private blit function and it performs low-level surface + blitting, assuming the input rectangles have already been clipped. + + Unless you know what you're doing, you should be using SDL_BlitSurface() + instead. + + \param src the SDL_Surface structure to be copied from + \param srcrect the SDL_Rect structure representing the rectangle to be + copied, or NULL to copy the entire surface + \param dst the SDL_Surface structure that is the blit target + \param dstrect the SDL_Rect structure representing the rectangle that is + copied into + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_BlitSurface + + + + * Performs a fast blit from the source surface to the destination surface. + * + * This assumes that the source and destination rectangles are + * the same size. If either \c srcrect or \c dstrect are NULL, the entire + * surface (\c src or \c dst) is copied. The final blit rectangles are saved + * in \c srcrect and \c dstrect after all clipping is performed. + * + * \returns 0 if the blit is successful, otherwise it returns -1. + * + * The blit function should not be called on a locked surface. + * + * The blit semantics for surfaces with and without blending and colorkey + * are defined as follows: + * \verbatim + RGBA->RGB: + Source surface blend mode set to SDL_BLENDMODE_BLEND: + alpha-blend (using the source alpha-channel and per-surface alpha) + SDL_SRCCOLORKEY ignored. + Source surface blend mode set to SDL_BLENDMODE_NONE: + copy RGB. + if SDL_SRCCOLORKEY set, only copy the pixels matching the + RGB values of the source color key, ignoring alpha in the + comparison. + + RGB->RGBA: + Source surface blend mode set to SDL_BLENDMODE_BLEND: + alpha-blend (using the source per-surface alpha) + Source surface blend mode set to SDL_BLENDMODE_NONE: + copy RGB, set destination alpha to source per-surface alpha value. + both: + if SDL_SRCCOLORKEY set, only copy the pixels matching the + source color key. + + RGBA->RGBA: + Source surface blend mode set to SDL_BLENDMODE_BLEND: + alpha-blend (using the source alpha-channel and per-surface alpha) + SDL_SRCCOLORKEY ignored. + Source surface blend mode set to SDL_BLENDMODE_NONE: + copy all of RGBA to the destination. + if SDL_SRCCOLORKEY set, only copy the pixels matching the + RGB values of the source color key, ignoring alpha in the + comparison. + + RGB->RGB: + Source surface blend mode set to SDL_BLENDMODE_BLEND: + alpha-blend (using the source per-surface alpha) + Source surface blend mode set to SDL_BLENDMODE_NONE: + copy RGB. + both: + if SDL_SRCCOLORKEY set, only copy the pixels matching the + source color key. + \endverbatim + * + * You should call SDL_BlitSurface() unless you know exactly how SDL + * blitting works internally and how to use the other blit functions. + + Perform a fast blit from the source surface to the destination surface. + + SDL_UpperBlit() has been replaced by SDL_BlitSurface(), which is merely a + macro for this function with a less confusing name. + + \since This function is available since SDL 2.0.0. + + \sa SDL_BlitSurface + + + + Perform a fast fill of a set of rectangles with a specific color. + + `color` should be a pixel of the format used by the surface, and can be + generated by SDL_MapRGB() or SDL_MapRGBA(). If the color value contains an + alpha component then the destination is simply filled with that alpha + information, no blending takes place. + + If there is a clip rectangle set on the destination (set via + SDL_SetClipRect()), then this function will fill based on the intersection + of the clip rectangle and `rect`. + + \param dst the SDL_Surface structure that is the drawing target + \param rects an array of SDL_Rects representing the rectangles to fill. + \param count the number of rectangles in the array + \param color the color to fill with + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_FillRect + + + + Perform a fast fill of a rectangle with a specific color. + + `color` should be a pixel of the format used by the surface, and can be + generated by SDL_MapRGB() or SDL_MapRGBA(). If the color value contains an + alpha component then the destination is simply filled with that alpha + information, no blending takes place. + + If there is a clip rectangle set on the destination (set via + SDL_SetClipRect()), then this function will fill based on the intersection + of the clip rectangle and `rect`. + + \param dst the SDL_Surface structure that is the drawing target + \param rect the SDL_Rect structure representing the rectangle to fill, or + NULL to fill the entire surface + \param color the color to fill with + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_FillRects + + + + Premultiply the alpha on a block of pixels. + + This is safe to use with src == dst, but not for other overlapping areas. + + This function is currently only implemented for SDL_PIXELFORMAT_ARGB8888. + + \param width the width of the block to convert, in pixels + \param height the height of the block to convert, in pixels + \param src_format an SDL_PixelFormatEnum value of the `src` pixels format + \param src a pointer to the source pixels + \param src_pitch the pitch of the source pixels, in bytes + \param dst_format an SDL_PixelFormatEnum value of the `dst` pixels format + \param dst a pointer to be filled in with premultiplied pixel data + \param dst_pitch the pitch of the destination pixels, in bytes + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.18. + + + + Copy a block of pixels of one format to another format. + + \param width the width of the block to copy, in pixels + \param height the height of the block to copy, in pixels + \param src_format an SDL_PixelFormatEnum value of the `src` pixels format + \param src a pointer to the source pixels + \param src_pitch the pitch of the source pixels, in bytes + \param dst_format an SDL_PixelFormatEnum value of the `dst` pixels format + \param dst a pointer to be filled in with new pixel data + \param dst_pitch the pitch of the destination pixels, in bytes + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + + + Copy an existing surface to a new surface of the specified format enum. + + This function operates just like SDL_ConvertSurface(), but accepts an + SDL_PixelFormatEnum value instead of an SDL_PixelFormat structure. As such, + it might be easier to call but it doesn't have access to palette + information for the destination surface, in case that would be important. + + \param src the existing SDL_Surface structure to convert + \param pixel_format the SDL_PixelFormatEnum that the new surface is + optimized for + \param flags the flags are unused and should be set to 0; this is a + leftover from SDL 1.2's API + \returns the new SDL_Surface structure that is created or NULL if it fails; + call SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_AllocFormat + \sa SDL_ConvertSurface + \sa SDL_CreateRGBSurface + + + + Copy an existing surface to a new surface of the specified format. + + This function is used to optimize images for faster *repeat* blitting. This + is accomplished by converting the original and storing the result as a new + surface. The new, optimized surface can then be used as the source for + future blits, making them faster. + + \param src the existing SDL_Surface structure to convert + \param fmt the SDL_PixelFormat structure that the new surface is optimized + for + \param flags the flags are unused and should be set to 0; this is a + leftover from SDL 1.2's API + \returns the new SDL_Surface structure that is created or NULL if it fails; + call SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_AllocFormat + \sa SDL_ConvertSurfaceFormat + \sa SDL_CreateRGBSurface + + + + Get the clipping rectangle for a surface. + + When `surface` is the destination of a blit, only the area within the clip + rectangle is drawn into. + + \param surface the SDL_Surface structure representing the surface to be + clipped + \param rect an SDL_Rect structure filled in with the clipping rectangle for + the surface + + \since This function is available since SDL 2.0.0. + + \sa SDL_BlitSurface + \sa SDL_SetClipRect + + + + Set the clipping rectangle for a surface. + + When `surface` is the destination of a blit, only the area within the clip + rectangle is drawn into. + + Note that blits are automatically clipped to the edges of the source and + destination surfaces. + + \param surface the SDL_Surface structure to be clipped + \param rect the SDL_Rect structure representing the clipping rectangle, or + NULL to disable clipping + \returns SDL_TRUE if the rectangle intersects the surface, otherwise + SDL_FALSE and blits will be completely clipped. + + \since This function is available since SDL 2.0.0. + + \sa SDL_BlitSurface + \sa SDL_GetClipRect + + + + Get the blend mode used for blit operations. + + \param surface the SDL_Surface structure to query + \param blendMode a pointer filled in with the current SDL_BlendMode + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_SetSurfaceBlendMode + + + + Set the blend mode used for blit operations. + + To copy a surface to another surface (or texture) without blending with the + existing data, the blendmode of the SOURCE surface should be set to + `SDL_BLENDMODE_NONE`. + + \param surface the SDL_Surface structure to update + \param blendMode the SDL_BlendMode to use for blit blending + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_GetSurfaceBlendMode + + + + Get the additional alpha value used in blit operations. + + \param surface the SDL_Surface structure to query + \param alpha a pointer filled in with the current alpha value + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_GetSurfaceColorMod + \sa SDL_SetSurfaceAlphaMod + + + + Set an additional alpha value used in blit operations. + + When this surface is blitted, during the blit operation the source alpha + value is modulated by this alpha value according to the following formula: + + `srcA = srcA * (alpha / 255)` + + \param surface the SDL_Surface structure to update + \param alpha the alpha value multiplied into blit operations + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_GetSurfaceAlphaMod + \sa SDL_SetSurfaceColorMod + + + + Get the additional color value multiplied into blit operations. + + \param surface the SDL_Surface structure to query + \param r a pointer filled in with the current red color value + \param g a pointer filled in with the current green color value + \param b a pointer filled in with the current blue color value + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_GetSurfaceAlphaMod + \sa SDL_SetSurfaceColorMod + + + + Set an additional color value multiplied into blit operations. + + When this surface is blitted, during the blit operation each source color + channel is modulated by the appropriate color value according to the + following formula: + + `srcC = srcC * (color / 255)` + + \param surface the SDL_Surface structure to update + \param r the red color value multiplied into blit operations + \param g the green color value multiplied into blit operations + \param b the blue color value multiplied into blit operations + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_GetSurfaceColorMod + \sa SDL_SetSurfaceAlphaMod + + + + Get the color key (transparent pixel) for a surface. + + The color key is a pixel of the format used by the surface, as generated by + SDL_MapRGB(). + + If the surface doesn't have color key enabled this function returns -1. + + \param surface the SDL_Surface structure to query + \param key a pointer filled in with the transparent pixel + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_BlitSurface + \sa SDL_SetColorKey + + + + Returns whether the surface has a color key + + It is safe to pass a NULL `surface` here; it will return SDL_FALSE. + + \param surface the SDL_Surface structure to query + \return SDL_TRUE if the surface has a color key, SDL_FALSE otherwise. + + \since This function is available since SDL 2.0.9. + + \sa SDL_SetColorKey + \sa SDL_GetColorKey + + + + Set the color key (transparent pixel) in a surface. + + The color key defines a pixel value that will be treated as transparent in + a blit. For example, one can use this to specify that cyan pixels should be + considered transparent, and therefore not rendered. + + It is a pixel of the format used by the surface, as generated by + SDL_MapRGB(). + + RLE acceleration can substantially speed up blitting of images with large + horizontal runs of transparent pixels. See SDL_SetSurfaceRLE() for details. + + \param surface the SDL_Surface structure to update + \param flag SDL_TRUE to enable color key, SDL_FALSE to disable color key + \param key the transparent pixel + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_BlitSurface + \sa SDL_GetColorKey + + + + Returns whether the surface is RLE enabled + + It is safe to pass a NULL `surface` here; it will return SDL_FALSE. + + \param surface the SDL_Surface structure to query + \returns SDL_TRUE if the surface is RLE enabled, SDL_FALSE otherwise. + + \since This function is available since SDL 2.0.14. + + \sa SDL_SetSurfaceRLE + + + + Save a surface to a file. + + Convenience macro. + + Set the RLE acceleration hint for a surface. + + If RLE is enabled, color key and alpha blending blits are much faster, but + the surface must be locked before directly accessing the pixels. + + \param surface the SDL_Surface structure to optimize + \param flag 0 to disable, non-zero to enable RLE acceleration + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_BlitSurface + \sa SDL_LockSurface + \sa SDL_UnlockSurface + + + + Load a surface from a file. + + Convenience macro. + + Save a surface to a seekable SDL data stream in BMP format. + + Surfaces with a 24-bit, 32-bit and paletted 8-bit format get saved in the + BMP directly. Other RGB formats with 8-bit or higher get converted to a + 24-bit surface or, if they have an alpha mask or a colorkey, to a 32-bit + surface before they are saved. YUV and paletted 1-bit and 4-bit formats are + not supported. + + \param surface the SDL_Surface structure containing the image to be saved + \param dst a data stream to save to + \param freedst non-zero to close the stream after being written + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_LoadBMP_RW + \sa SDL_SaveBMP + + + + Load a BMP image from a seekable SDL data stream. + + The new surface should be freed with SDL_FreeSurface(). Not doing so will + result in a memory leak. + + src is an open SDL_RWops buffer, typically loaded with SDL_RWFromFile. + Alternitavely, you might also use the macro SDL_LoadBMP to load a bitmap + from a file, convert it to an SDL_Surface and then close the file. + + \param src the data stream for the surface + \param freesrc non-zero to close the stream after being read + \returns a pointer to a new SDL_Surface structure or NULL if there was an + error; call SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_FreeSurface + \sa SDL_RWFromFile + \sa SDL_LoadBMP + \sa SDL_SaveBMP_RW + + + + Release a surface after directly accessing the pixels. + + \param surface the SDL_Surface structure to be unlocked + + \since This function is available since SDL 2.0.0. + + \sa SDL_LockSurface + + + + Set up a surface for directly accessing the pixels. + + Between calls to SDL_LockSurface() / SDL_UnlockSurface(), you can write to + and read from `surface->pixels`, using the pixel format stored in + `surface->format`. Once you are done accessing the surface, you should use + SDL_UnlockSurface() to release it. + + Not all surfaces require locking. If `SDL_MUSTLOCK(surface)` evaluates to + 0, then you can read and write to the surface at any time, and the pixel + format of the surface will not change. + + \param surface the SDL_Surface structure to be locked + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_MUSTLOCK + \sa SDL_UnlockSurface + + + + Set the palette used by a surface. + + A single palette can be shared with many surfaces. + + \param surface the SDL_Surface structure to update + \param palette the SDL_Palette structure to use + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + + + Free an RGB surface. + + It is safe to pass NULL to this function. + + \param surface the SDL_Surface to free. + + \since This function is available since SDL 2.0.0. + + \sa SDL_CreateRGBSurface + \sa SDL_CreateRGBSurfaceFrom + \sa SDL_LoadBMP + \sa SDL_LoadBMP_RW + + + + Allocate a new RGB surface with with a specific pixel format and existing + pixel data. + + This function operates mostly like SDL_CreateRGBSurfaceFrom(), except + instead of providing pixel color masks, you provide it with a predefined + format from SDL_PixelFormatEnum. + + No copy is made of the pixel data. Pixel data is not managed automatically; + you must free the surface before you free the pixel data. + + \param pixels a pointer to existing pixel data + \param width the width of the surface + \param height the height of the surface + \param depth the depth of the surface in bits + \param pitch the pitch of the surface in bytes + \param format the SDL_PixelFormatEnum for the new surface's pixel format. + \returns the new SDL_Surface structure that is created or NULL if it fails; + call SDL_GetError() for more information. + + \since This function is available since SDL 2.0.5. + + \sa SDL_CreateRGBSurfaceFrom + \sa SDL_CreateRGBSurfaceWithFormat + \sa SDL_FreeSurface + + + + Allocate a new RGB surface with existing pixel data. + + This function operates mostly like SDL_CreateRGBSurface(), except it does + not allocate memory for the pixel data, instead the caller provides an + existing buffer of data for the surface to use. + + No copy is made of the pixel data. Pixel data is not managed automatically; + you must free the surface before you free the pixel data. + + \param pixels a pointer to existing pixel data + \param width the width of the surface + \param height the height of the surface + \param depth the depth of the surface in bits + \param pitch the pitch of the surface in bytes + \param Rmask the red mask for the pixels + \param Gmask the green mask for the pixels + \param Bmask the blue mask for the pixels + \param Amask the alpha mask for the pixels + \returns the new SDL_Surface structure that is created or NULL if it fails; + call SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_CreateRGBSurface + \sa SDL_CreateRGBSurfaceWithFormat + \sa SDL_FreeSurface + + + + Allocate a new RGB surface with a specific pixel format. + + This function operates mostly like SDL_CreateRGBSurface(), except instead + of providing pixel color masks, you provide it with a predefined format + from SDL_PixelFormatEnum. + + \param flags the flags are unused and should be set to 0 + \param width the width of the surface + \param height the height of the surface + \param depth the depth of the surface in bits + \param format the SDL_PixelFormatEnum for the new surface's pixel format. + \returns the new SDL_Surface structure that is created or NULL if it fails; + call SDL_GetError() for more information. + + \since This function is available since SDL 2.0.5. + + \sa SDL_CreateRGBSurface + \sa SDL_CreateRGBSurfaceFrom + \sa SDL_FreeSurface + + + + Allocate a new RGB surface. + + If `depth` is 4 or 8 bits, an empty palette is allocated for the surface. + If `depth` is greater than 8 bits, the pixel format is set using the + [RGBA]mask parameters. + + The [RGBA]mask parameters are the bitmasks used to extract that color from + a pixel. For instance, `Rmask` being 0xFF000000 means the red data is + stored in the most significant byte. Using zeros for the RGB masks sets a + default value, based on the depth. For example: + + ```c++ + SDL_CreateRGBSurface(0,w,h,32,0,0,0,0); + ``` + + However, using zero for the Amask results in an Amask of 0. + + By default surfaces with an alpha mask are set up for blending as with: + + ```c++ + SDL_SetSurfaceBlendMode(surface, SDL_BLENDMODE_BLEND) + ``` + + You can change this by calling SDL_SetSurfaceBlendMode() and selecting a + different `blendMode`. + + \param flags the flags are unused and should be set to 0 + \param width the width of the surface + \param height the height of the surface + \param depth the depth of the surface in bits + \param Rmask the red mask for the pixels + \param Gmask the green mask for the pixels + \param Bmask the blue mask for the pixels + \param Amask the alpha mask for the pixels + \returns the new SDL_Surface structure that is created or NULL if it fails; + call SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_CreateRGBSurfaceFrom + \sa SDL_CreateRGBSurfaceWithFormat + \sa SDL_FreeSurface + + + +Reference count -- used when freeing surface + + +info for fast blit mapping to other surfaces + + +clipping information + + +list of BlitMap that hold a reference to this surface + + +information needed for surfaces requiring locks + + +Application data associated with the surface + + + \brief A collection of pixels used in software blitting. + + \note This structure should be treated as read-only, except for \c pixels, + which, if not NULL, contains the raw pixel data for the surface. + + +\brief The type of function used for surface blitting functions. + + + + Compose a custom blend mode for renderers. + + The functions SDL_SetRenderDrawBlendMode and SDL_SetTextureBlendMode accept + the SDL_BlendMode returned by this function if the renderer supports it. + + A blend mode controls how the pixels from a drawing operation (source) get + combined with the pixels from the render target (destination). First, the + components of the source and destination pixels get multiplied with their + blend factors. Then, the blend operation takes the two products and + calculates the result that will get stored in the render target. + + Expressed in pseudocode, it would look like this: + + ```c + dstRGB = colorOperation(srcRGB * srcColorFactor, dstRGB * dstColorFactor); + dstA = alphaOperation(srcA * srcAlphaFactor, dstA * dstAlphaFactor); + ``` + + Where the functions `colorOperation(src, dst)` and `alphaOperation(src, + dst)` can return one of the following: + + - `src + dst` + - `src - dst` + - `dst - src` + - `min(src, dst)` + - `max(src, dst)` + + The red, green, and blue components are always multiplied with the first, + second, and third components of the SDL_BlendFactor, respectively. The + fourth component is not used. + + The alpha component is always multiplied with the fourth component of the + SDL_BlendFactor. The other components are not used in the alpha + calculation. + + Support for these blend modes varies for each renderer. To check if a + specific SDL_BlendMode is supported, create a renderer and pass it to + either SDL_SetRenderDrawBlendMode or SDL_SetTextureBlendMode. They will + return with an error if the blend mode is not supported. + + This list describes the support of custom blend modes for each renderer in + SDL 2.0.6. All renderers support the four blend modes listed in the + SDL_BlendMode enumeration. + + - **direct3d**: Supports all operations with all factors. However, some + factors produce unexpected results with `SDL_BLENDOPERATION_MINIMUM` and + `SDL_BLENDOPERATION_MAXIMUM`. + - **direct3d11**: Same as Direct3D 9. + - **opengl**: Supports the `SDL_BLENDOPERATION_ADD` operation with all + factors. OpenGL versions 1.1, 1.2, and 1.3 do not work correctly with SDL + 2.0.6. + - **opengles**: Supports the `SDL_BLENDOPERATION_ADD` operation with all + factors. Color and alpha factors need to be the same. OpenGL ES 1 + implementation specific: May also support `SDL_BLENDOPERATION_SUBTRACT` + and `SDL_BLENDOPERATION_REV_SUBTRACT`. May support color and alpha + operations being different from each other. May support color and alpha + factors being different from each other. + - **opengles2**: Supports the `SDL_BLENDOPERATION_ADD`, + `SDL_BLENDOPERATION_SUBTRACT`, `SDL_BLENDOPERATION_REV_SUBTRACT` + operations with all factors. + - **psp**: No custom blend mode support. + - **software**: No custom blend mode support. + + Some renderers do not provide an alpha component for the default render + target. The `SDL_BLENDFACTOR_DST_ALPHA` and + `SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA` factors do not have an effect in this + case. + + \param srcColorFactor the SDL_BlendFactor applied to the red, green, and + blue components of the source pixels + \param dstColorFactor the SDL_BlendFactor applied to the red, green, and + blue components of the destination pixels + \param colorOperation the SDL_BlendOperation used to combine the red, + green, and blue components of the source and + destination pixels + \param srcAlphaFactor the SDL_BlendFactor applied to the alpha component of + the source pixels + \param dstAlphaFactor the SDL_BlendFactor applied to the alpha component of + the destination pixels + \param alphaOperation the SDL_BlendOperation used to combine the alpha + component of the source and destination pixels + \returns an SDL_BlendMode that represents the chosen factors and + operations. + + \since This function is available since SDL 2.0.6. + + \sa SDL_SetRenderDrawBlendMode + \sa SDL_GetRenderDrawBlendMode + \sa SDL_SetTextureBlendMode + \sa SDL_GetTextureBlendMode + + + + Calculate the intersection of a rectangle and line segment with float + precision. + + This function is used to clip a line segment to a rectangle. A line segment + contained entirely within the rectangle or that does not intersect will + remain unchanged. A line segment that crosses the rectangle at either or + both ends will be clipped to the boundary of the rectangle and the new + coordinates saved in `X1`, `Y1`, `X2`, and/or `Y2` as necessary. + + \param rect an SDL_FRect structure representing the rectangle to intersect + \param X1 a pointer to the starting X-coordinate of the line + \param Y1 a pointer to the starting Y-coordinate of the line + \param X2 a pointer to the ending X-coordinate of the line + \param Y2 a pointer to the ending Y-coordinate of the line + \returns SDL_TRUE if there is an intersection, SDL_FALSE otherwise. + + \since This function is available since SDL 2.0.22. + + + + Calculate a minimal rectangle enclosing a set of points with float + precision. + + If `clip` is not NULL then only points inside of the clipping rectangle are + considered. + + \param points an array of SDL_FPoint structures representing points to be + enclosed + \param count the number of structures in the `points` array + \param clip an SDL_FRect used for clipping or NULL to enclose all points + \param result an SDL_FRect structure filled in with the minimal enclosing + rectangle + \returns SDL_TRUE if any points were enclosed or SDL_FALSE if all the + points were outside of the clipping rectangle. + + \since This function is available since SDL 2.0.22. + + + + Calculate the union of two rectangles with float precision. + + \param A an SDL_FRect structure representing the first rectangle + \param B an SDL_FRect structure representing the second rectangle + \param result an SDL_FRect structure filled in with the union of rectangles + `A` and `B` + + \since This function is available since SDL 2.0.22. + + + + Calculate the intersection of two rectangles with float precision. + + If `result` is NULL then this function will return SDL_FALSE. + + \param A an SDL_FRect structure representing the first rectangle + \param B an SDL_FRect structure representing the second rectangle + \param result an SDL_FRect structure filled in with the intersection of + rectangles `A` and `B` + \returns SDL_TRUE if there is an intersection, SDL_FALSE otherwise. + + \since This function is available since SDL 2.0.22. + + \sa SDL_HasIntersectionF + + + + Determine whether two rectangles intersect with float precision. + + If either pointer is NULL the function will return SDL_FALSE. + + \param A an SDL_FRect structure representing the first rectangle + \param B an SDL_FRect structure representing the second rectangle + \returns SDL_TRUE if there is an intersection, SDL_FALSE otherwise. + + \since This function is available since SDL 2.0.22. + + \sa SDL_IntersectRect + + + + Returns true if the two rectangles are equal, using a default epsilon. + + \since This function is available since SDL 2.0.22. + + + + Returns true if the two rectangles are equal, within some given epsilon. + + \since This function is available since SDL 2.0.22. + + + +Returns true if the rectangle has no area. + + + +Returns true if point resides inside a rectangle. + + + + Calculate the intersection of a rectangle and line segment. + + This function is used to clip a line segment to a rectangle. A line segment + contained entirely within the rectangle or that does not intersect will + remain unchanged. A line segment that crosses the rectangle at either or + both ends will be clipped to the boundary of the rectangle and the new + coordinates saved in `X1`, `Y1`, `X2`, and/or `Y2` as necessary. + + \param rect an SDL_Rect structure representing the rectangle to intersect + \param X1 a pointer to the starting X-coordinate of the line + \param Y1 a pointer to the starting Y-coordinate of the line + \param X2 a pointer to the ending X-coordinate of the line + \param Y2 a pointer to the ending Y-coordinate of the line + \returns SDL_TRUE if there is an intersection, SDL_FALSE otherwise. + + \since This function is available since SDL 2.0.0. + + + + Calculate a minimal rectangle enclosing a set of points. + + If `clip` is not NULL then only points inside of the clipping rectangle are + considered. + + \param points an array of SDL_Point structures representing points to be + enclosed + \param count the number of structures in the `points` array + \param clip an SDL_Rect used for clipping or NULL to enclose all points + \param result an SDL_Rect structure filled in with the minimal enclosing + rectangle + \returns SDL_TRUE if any points were enclosed or SDL_FALSE if all the + points were outside of the clipping rectangle. + + \since This function is available since SDL 2.0.0. + + + + Calculate the union of two rectangles. + + \param A an SDL_Rect structure representing the first rectangle + \param B an SDL_Rect structure representing the second rectangle + \param result an SDL_Rect structure filled in with the union of rectangles + `A` and `B` + + \since This function is available since SDL 2.0.0. + + + + Calculate the intersection of two rectangles. + + If `result` is NULL then this function will return SDL_FALSE. + + \param A an SDL_Rect structure representing the first rectangle + \param B an SDL_Rect structure representing the second rectangle + \param result an SDL_Rect structure filled in with the intersection of + rectangles `A` and `B` + \returns SDL_TRUE if there is an intersection, SDL_FALSE otherwise. + + \since This function is available since SDL 2.0.0. + + \sa SDL_HasIntersection + + + + Determine whether two rectangles intersect. + + If either pointer is NULL the function will return SDL_FALSE. + + \param A an SDL_Rect structure representing the first rectangle + \param B an SDL_Rect structure representing the second rectangle + \returns SDL_TRUE if there is an intersection, SDL_FALSE otherwise. + + \since This function is available since SDL 2.0.0. + + \sa SDL_IntersectRect + + + +Returns true if the two rectangles are equal. + + + +Returns true if the rectangle has no area. + + + +Returns true if point resides inside a rectangle. + + + + A rectangle, with the origin at the upper left (floating point). + + \sa SDL_FRectEmpty + \sa SDL_FRectEquals + \sa SDL_FRectEqualsEpsilon + \sa SDL_HasIntersectionF + \sa SDL_IntersectFRect + \sa SDL_IntersectFRectAndLine + \sa SDL_UnionFRect + \sa SDL_EncloseFPoints + \sa SDL_PointInFRect + + + + A rectangle, with the origin at the upper left (integer). + + \sa SDL_RectEmpty + \sa SDL_RectEquals + \sa SDL_HasIntersection + \sa SDL_IntersectRect + \sa SDL_IntersectRectAndLine + \sa SDL_UnionRect + \sa SDL_EnclosePoints + + + + The structure that defines a point (floating point) + + \sa SDL_EncloseFPoints + \sa SDL_PointInFRect + + + + Use this function to write 64 bits in native format to a SDL_RWops as + big-endian data. + + SDL byteswaps the data only if necessary, so the application always + specifies native format, and the data written will be in big-endian format. + + \param dst the stream to which data will be written + \param value the data to be written, in native format + \returns 1 on successful write, 0 on error. + + \since This function is available since SDL 2.0.0. + + \sa SDL_WriteLE64 + + + + Use this function to write 64 bits in native format to a SDL_RWops as + little-endian data. + + SDL byteswaps the data only if necessary, so the application always + specifies native format, and the data written will be in little-endian + format. + + \param dst the stream to which data will be written + \param value the data to be written, in native format + \returns 1 on successful write, 0 on error. + + \since This function is available since SDL 2.0.0. + + \sa SDL_WriteBE64 + + + + Use this function to write 32 bits in native format to a SDL_RWops as + big-endian data. + + SDL byteswaps the data only if necessary, so the application always + specifies native format, and the data written will be in big-endian format. + + \param dst the stream to which data will be written + \param value the data to be written, in native format + \returns 1 on successful write, 0 on error. + + \since This function is available since SDL 2.0.0. + + \sa SDL_WriteLE32 + + + + Use this function to write 32 bits in native format to a SDL_RWops as + little-endian data. + + SDL byteswaps the data only if necessary, so the application always + specifies native format, and the data written will be in little-endian + format. + + \param dst the stream to which data will be written + \param value the data to be written, in native format + \returns 1 on successful write, 0 on error. + + \since This function is available since SDL 2.0.0. + + \sa SDL_WriteBE32 + + + + Use this function to write 16 bits in native format to a SDL_RWops as + big-endian data. + + SDL byteswaps the data only if necessary, so the application always + specifies native format, and the data written will be in big-endian format. + + \param dst the stream to which data will be written + \param value the data to be written, in native format + \returns 1 on successful write, 0 on error. + + \since This function is available since SDL 2.0.0. + + \sa SDL_WriteLE16 + + + + Use this function to write 16 bits in native format to a SDL_RWops as + little-endian data. + + SDL byteswaps the data only if necessary, so the application always + specifies native format, and the data written will be in little-endian + format. + + \param dst the stream to which data will be written + \param value the data to be written, in native format + \returns 1 on successful write, 0 on error. + + \since This function is available since SDL 2.0.0. + + \sa SDL_WriteBE16 + + + + \name Write endian functions + + Write an item of native format to the specified endianness. + + Use this function to write a byte to an SDL_RWops. + + \param dst the SDL_RWops to write to + \param value the byte value to write + \returns 1 on success or 0 on failure; call SDL_GetError() for more + information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_ReadU8 + + + + Use this function to read 64 bits of big-endian data from an SDL_RWops and + return in native format. + + SDL byteswaps the data only if necessary, so the data returned will be in + the native byte order. + + \param src the stream from which to read data + \returns 64 bits of data in the native byte order of the platform. + + \since This function is available since SDL 2.0.0. + + \sa SDL_ReadLE64 + + + + Use this function to read 64 bits of little-endian data from an SDL_RWops + and return in native format. + + SDL byteswaps the data only if necessary, so the data returned will be in + the native byte order. + + \param src the stream from which to read data + \returns 64 bits of data in the native byte order of the platform. + + \since This function is available since SDL 2.0.0. + + \sa SDL_ReadBE64 + + + + Use this function to read 32 bits of big-endian data from an SDL_RWops and + return in native format. + + SDL byteswaps the data only if necessary, so the data returned will be in + the native byte order. + + \param src the stream from which to read data + \returns 32 bits of data in the native byte order of the platform. + + \since This function is available since SDL 2.0.0. + + \sa SDL_ReadLE32 + + + + Use this function to read 32 bits of little-endian data from an SDL_RWops + and return in native format. + + SDL byteswaps the data only if necessary, so the data returned will be in + the native byte order. + + \param src the stream from which to read data + \returns 32 bits of data in the native byte order of the platform. + + \since This function is available since SDL 2.0.0. + + \sa SDL_ReadBE32 + + + + Use this function to read 16 bits of big-endian data from an SDL_RWops and + return in native format. + + SDL byteswaps the data only if necessary, so the data returned will be in + the native byte order. + + \param src the stream from which to read data + \returns 16 bits of data in the native byte order of the platform. + + \since This function is available since SDL 2.0.0. + + \sa SDL_ReadLE16 + + + + Use this function to read 16 bits of little-endian data from an SDL_RWops + and return in native format. + + SDL byteswaps the data only if necessary, so the data returned will be in + the native byte order. + + \param src the stream from which to read data + \returns 16 bits of data in the native byte order of the platform. + + \since This function is available since SDL 2.0.0. + + \sa SDL_ReadBE16 + + + + \name Read endian functions + + Read an item of the specified endianness and return in native format. + + Use this function to read a byte from an SDL_RWops. + + \param src the SDL_RWops to read from + \returns the read byte on success or 0 on failure; call SDL_GetError() for + more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_WriteU8 + + + + Load all the data from a file path. + + The data is allocated with a zero byte at the end (null terminated) for + convenience. This extra byte is not included in the value reported via + `datasize`. + + The data should be freed with SDL_free(). + + Prior to SDL 2.0.10, this function was a macro wrapping around + SDL_LoadFile_RW. + + \param file the path to read all available data from + \param datasize if not NULL, will store the number of bytes read + \returns the data, or NULL if there was an error. + + \since This function is available since SDL 2.0.10. + + + + Load all the data from an SDL data stream. + + The data is allocated with a zero byte at the end (null terminated) for + convenience. This extra byte is not included in the value reported via + `datasize`. + + The data should be freed with SDL_free(). + + \param src the SDL_RWops to read all available data from + \param datasize if not NULL, will store the number of bytes read + \param freesrc if non-zero, calls SDL_RWclose() on `src` before returning + \returns the data, or NULL if there was an error. + + \since This function is available since SDL 2.0.6. + + + + Close and free an allocated SDL_RWops structure. + + SDL_RWclose() closes and cleans up the SDL_RWops stream. It releases any + resources used by the stream and frees the SDL_RWops itself with + SDL_FreeRW(). This returns 0 on success, or -1 if the stream failed to + flush to its output (e.g. to disk). + + Note that if this fails to flush the stream to disk, this function reports + an error, but the SDL_RWops is still invalid once this function returns. + + Prior to SDL 2.0.10, this function was a macro. + + \param context SDL_RWops structure to close + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.10. + + \sa SDL_RWFromConstMem + \sa SDL_RWFromFile + \sa SDL_RWFromFP + \sa SDL_RWFromMem + \sa SDL_RWread + \sa SDL_RWseek + \sa SDL_RWwrite + + + + Write to an SDL_RWops data stream. + + This function writes exactly `num` objects each of size `size` from the + area pointed at by `ptr` to the stream. If this fails for any reason, it'll + return less than `num` to demonstrate how far the write progressed. On + success, it returns `num`. + + SDL_RWwrite is actually a function wrapper that calls the SDL_RWops's + `write` method appropriately, to simplify application development. + + Prior to SDL 2.0.10, this function was a macro. + + \param context a pointer to an SDL_RWops structure + \param ptr a pointer to a buffer containing data to write + \param size the size of an object to write, in bytes + \param num the number of objects to write + \returns the number of objects written, which will be less than **num** on + error; call SDL_GetError() for more information. + + \since This function is available since SDL 2.0.10. + + \sa SDL_RWclose + \sa SDL_RWFromConstMem + \sa SDL_RWFromFile + \sa SDL_RWFromFP + \sa SDL_RWFromMem + \sa SDL_RWread + \sa SDL_RWseek + + + + Read from a data source. + + This function reads up to `maxnum` objects each of size `size` from the + data source to the area pointed at by `ptr`. This function may read less + objects than requested. It will return zero when there has been an error or + the data stream is completely read. + + SDL_RWread() is actually a function wrapper that calls the SDL_RWops's + `read` method appropriately, to simplify application development. + + Prior to SDL 2.0.10, this function was a macro. + + \param context a pointer to an SDL_RWops structure + \param ptr a pointer to a buffer to read data into + \param size the size of each object to read, in bytes + \param maxnum the maximum number of objects to be read + \returns the number of objects read, or 0 at error or end of file; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.10. + + \sa SDL_RWclose + \sa SDL_RWFromConstMem + \sa SDL_RWFromFile + \sa SDL_RWFromFP + \sa SDL_RWFromMem + \sa SDL_RWseek + \sa SDL_RWwrite + + + + Determine the current read/write offset in an SDL_RWops data stream. + + SDL_RWtell is actually a wrapper function that calls the SDL_RWops's `seek` + method, with an offset of 0 bytes from `RW_SEEK_CUR`, to simplify + application development. + + Prior to SDL 2.0.10, this function was a macro. + + \param context a SDL_RWops data stream object from which to get the current + offset + \returns the current offset in the stream, or -1 if the information can not + be determined. + + \since This function is available since SDL 2.0.10. + + \sa SDL_RWclose + \sa SDL_RWFromConstMem + \sa SDL_RWFromFile + \sa SDL_RWFromFP + \sa SDL_RWFromMem + \sa SDL_RWread + \sa SDL_RWseek + \sa SDL_RWwrite + + + + Seek within an SDL_RWops data stream. + + This function seeks to byte `offset`, relative to `whence`. + + `whence` may be any of the following values: + + - `RW_SEEK_SET`: seek from the beginning of data + - `RW_SEEK_CUR`: seek relative to current read point + - `RW_SEEK_END`: seek relative to the end of data + + If this stream can not seek, it will return -1. + + SDL_RWseek() is actually a wrapper function that calls the SDL_RWops's + `seek` method appropriately, to simplify application development. + + Prior to SDL 2.0.10, this function was a macro. + + \param context a pointer to an SDL_RWops structure + \param offset an offset in bytes, relative to **whence** location; can be + negative + \param whence any of `RW_SEEK_SET`, `RW_SEEK_CUR`, `RW_SEEK_END` + \returns the final offset in the data stream after the seek or -1 on error. + + \since This function is available since SDL 2.0.10. + + \sa SDL_RWclose + \sa SDL_RWFromConstMem + \sa SDL_RWFromFile + \sa SDL_RWFromFP + \sa SDL_RWFromMem + \sa SDL_RWread + \sa SDL_RWtell + \sa SDL_RWwrite + + + + Use this function to get the size of the data stream in an SDL_RWops. + + Prior to SDL 2.0.10, this function was a macro. + + \param context the SDL_RWops to get the size of the data stream from + \returns the size of the data stream in the SDL_RWops on success, -1 if + unknown or a negative error code on failure; call SDL_GetError() + for more information. + + \since This function is available since SDL 2.0.10. + + + + Use this function to free an SDL_RWops structure allocated by + SDL_AllocRW(). + + Applications do not need to use this function unless they are providing + their own SDL_RWops implementation. If you just need a SDL_RWops to + read/write a common data source, you should use the built-in + implementations in SDL, like SDL_RWFromFile() or SDL_RWFromMem(), etc, and + call the **close** method on those SDL_RWops pointers when you are done + with them. + + Only use SDL_FreeRW() on pointers returned by SDL_AllocRW(). The pointer is + invalid as soon as this function returns. Any extra memory allocated during + creation of the SDL_RWops is not freed by SDL_FreeRW(); the programmer must + be responsible for managing that memory in their **close** method. + + \param area the SDL_RWops structure to be freed + + \since This function is available since SDL 2.0.0. + + \sa SDL_AllocRW + + + + Use this function to allocate an empty, unpopulated SDL_RWops structure. + + Applications do not need to use this function unless they are providing + their own SDL_RWops implementation. If you just need a SDL_RWops to + read/write a common data source, you should use the built-in + implementations in SDL, like SDL_RWFromFile() or SDL_RWFromMem(), etc. + + You must free the returned pointer with SDL_FreeRW(). Depending on your + operating system and compiler, there may be a difference between the + malloc() and free() your program uses and the versions SDL calls + internally. Trying to mix the two can cause crashing such as segmentation + faults. Since all SDL_RWops must free themselves when their **close** + method is called, all SDL_RWops must be allocated through this function, so + they can all be freed correctly with SDL_FreeRW(). + + \returns a pointer to the allocated memory on success, or NULL on failure; + call SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_FreeRW + + + + Use this function to prepare a read-only memory buffer for use with RWops. + + This function sets up an SDL_RWops struct based on a memory area of a + certain size. It assumes the memory area is not writable. + + Attempting to write to this RWops stream will report an error without + writing to the memory buffer. + + This memory buffer is not copied by the RWops; the pointer you provide must + remain valid until you close the stream. Closing the stream will not free + the original buffer. + + If you need to write to a memory buffer, you should use SDL_RWFromMem() + with a writable buffer of memory instead. + + \param mem a pointer to a read-only buffer to feed an SDL_RWops stream + \param size the buffer size, in bytes + \returns a pointer to a new SDL_RWops structure, or NULL if it fails; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_RWclose + \sa SDL_RWFromConstMem + \sa SDL_RWFromFile + \sa SDL_RWFromFP + \sa SDL_RWFromMem + \sa SDL_RWread + \sa SDL_RWseek + \sa SDL_RWtell + + + + Use this function to prepare a read-write memory buffer for use with + SDL_RWops. + + This function sets up an SDL_RWops struct based on a memory area of a + certain size, for both read and write access. + + This memory buffer is not copied by the RWops; the pointer you provide must + remain valid until you close the stream. Closing the stream will not free + the original buffer. + + If you need to make sure the RWops never writes to the memory buffer, you + should use SDL_RWFromConstMem() with a read-only buffer of memory instead. + + \param mem a pointer to a buffer to feed an SDL_RWops stream + \param size the buffer size, in bytes + \returns a pointer to a new SDL_RWops structure, or NULL if it fails; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_RWclose + \sa SDL_RWFromConstMem + \sa SDL_RWFromFile + \sa SDL_RWFromFP + \sa SDL_RWFromMem + \sa SDL_RWread + \sa SDL_RWseek + \sa SDL_RWtell + \sa SDL_RWwrite + + + + Use this function to create an SDL_RWops structure from a standard I/O file + pointer (stdio.h's `FILE*`). + + This function is not available on Windows, since files opened in an + application on that platform cannot be used by a dynamically linked + library. + + On some platforms, the first parameter is a `void*`, on others, it's a + `FILE*`, depending on what system headers are available to SDL. It is + always intended to be the `FILE*` type from the C runtime's stdio.h. + + \param fp the `FILE*` that feeds the SDL_RWops stream + \param autoclose SDL_TRUE to close the `FILE*` when closing the SDL_RWops, + SDL_FALSE to leave the `FILE*` open when the RWops is + closed + \returns a pointer to the SDL_RWops structure that is created, or NULL on + failure; call SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_RWclose + \sa SDL_RWFromConstMem + \sa SDL_RWFromFile + \sa SDL_RWFromMem + \sa SDL_RWread + \sa SDL_RWseek + \sa SDL_RWtell + \sa SDL_RWwrite + + + + \name RWFrom functions + + Functions to create SDL_RWops structures from various data streams. + + Use this function to create a new SDL_RWops structure for reading from + and/or writing to a named file. + + The `mode` string is treated roughly the same as in a call to the C + library's fopen(), even if SDL doesn't happen to use fopen() behind the + scenes. + + Available `mode` strings: + + - "r": Open a file for reading. The file must exist. + - "w": Create an empty file for writing. If a file with the same name + already exists its content is erased and the file is treated as a new + empty file. + - "a": Append to a file. Writing operations append data at the end of the + file. The file is created if it does not exist. + - "r+": Open a file for update both reading and writing. The file must + exist. + - "w+": Create an empty file for both reading and writing. If a file with + the same name already exists its content is erased and the file is + treated as a new empty file. + - "a+": Open a file for reading and appending. All writing operations are + performed at the end of the file, protecting the previous content to be + overwritten. You can reposition (fseek, rewind) the internal pointer to + anywhere in the file for reading, but writing operations will move it + back to the end of file. The file is created if it does not exist. + + **NOTE**: In order to open a file as a binary file, a "b" character has to + be included in the `mode` string. This additional "b" character can either + be appended at the end of the string (thus making the following compound + modes: "rb", "wb", "ab", "r+b", "w+b", "a+b") or be inserted between the + letter and the "+" sign for the mixed modes ("rb+", "wb+", "ab+"). + Additional characters may follow the sequence, although they should have no + effect. For example, "t" is sometimes appended to make explicit the file is + a text file. + + This function supports Unicode filenames, but they must be encoded in UTF-8 + format, regardless of the underlying operating system. + + As a fallback, SDL_RWFromFile() will transparently open a matching filename + in an Android app's `assets`. + + Closing the SDL_RWops will close the file handle SDL is holding internally. + + \param file a UTF-8 string representing the filename to open + \param mode an ASCII string representing the mode to be used for opening + the file. + \returns a pointer to the SDL_RWops structure that is created, or NULL on + failure; call SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_RWclose + \sa SDL_RWFromConstMem + \sa SDL_RWFromFP + \sa SDL_RWFromMem + \sa SDL_RWread + \sa SDL_RWseek + \sa SDL_RWtell + \sa SDL_RWwrite + + + +Return the size of the file in this rwops, or -1 if unknown + + + Seek to \c offset relative to \c whence, one of stdio's whence values: + RW_SEEK_SET, RW_SEEK_CUR, RW_SEEK_END + + \return the final offset in the data stream, or -1 on error. + + + Read up to \c maxnum objects each of size \c size from the data + stream to the area pointed at by \c ptr. + + \return the number of objects read, or 0 at error or end of file. + + + Write exactly \c num objects each of size \c size from the area + pointed at by \c ptr to data stream. + + \return the number of objects written, or 0 at error or end of file. + + + Close and free an allocated SDL_RWops structure. + + \return 0 if successful or -1 on write error when flushing data. + + + + Clear any previous error message for this thread. + + \since This function is available since SDL 2.0.0. + + \sa SDL_GetError + \sa SDL_SetError + + + + Get the last error message that was set for the current thread. + + This allows the caller to copy the error string into a provided buffer, but + otherwise operates exactly the same as SDL_GetError(). + + \param errstr A buffer to fill with the last error message that was set for + the current thread + \param maxlen The size of the buffer pointed to by the errstr parameter + \returns the pointer passed in as the `errstr` parameter. + + \since This function is available since SDL 2.0.14. + + \sa SDL_GetError + + + + Retrieve a message about the last error that occurred on the current + thread. + + It is possible for multiple errors to occur before calling SDL_GetError(). + Only the last error is returned. + + The message is only applicable when an SDL function has signaled an error. + You must check the return values of SDL function calls to determine when to + appropriately call SDL_GetError(). You should *not* use the results of + SDL_GetError() to decide if an error has occurred! Sometimes SDL will set + an error string even when reporting success. + + SDL will *not* clear the error string for successful API calls. You *must* + check return values for failure cases before you can assume the error + string applies. + + Error strings are set per-thread, so an error set in a different thread + will not interfere with the current thread's operation. + + The returned string is internally allocated and must not be freed by the + application. + + \returns a message with information about the specific error that occurred, + or an empty string if there hasn't been an error message set since + the last call to SDL_ClearError(). The message is only applicable + when an SDL function has signaled an error. You must check the + return values of SDL function calls to determine when to + appropriately call SDL_GetError(). + + \since This function is available since SDL 2.0.0. + + \sa SDL_ClearError + \sa SDL_SetError + + + + Calculate a 256 entry gamma ramp for a gamma value. + + \param gamma a gamma value where 0.0 is black and 1.0 is identity + \param ramp an array of 256 values filled in with the gamma ramp + + \since This function is available since SDL 2.0.0. + + \sa SDL_SetWindowGammaRamp + + + + Get RGBA values from a pixel in the specified format. + + This function uses the entire 8-bit [0..255] range when converting color + components from pixel formats with less than 8-bits per RGB component + (e.g., a completely white pixel in 16-bit RGB565 format would return [0xff, + 0xff, 0xff] not [0xf8, 0xfc, 0xf8]). + + If the surface has no alpha component, the alpha will be returned as 0xff + (100% opaque). + + \param pixel a pixel value + \param format an SDL_PixelFormat structure describing the format of the + pixel + \param r a pointer filled in with the red component + \param g a pointer filled in with the green component + \param b a pointer filled in with the blue component + \param a a pointer filled in with the alpha component + + \since This function is available since SDL 2.0.0. + + \sa SDL_GetRGB + \sa SDL_MapRGB + \sa SDL_MapRGBA + + + + Get RGB values from a pixel in the specified format. + + This function uses the entire 8-bit [0..255] range when converting color + components from pixel formats with less than 8-bits per RGB component + (e.g., a completely white pixel in 16-bit RGB565 format would return [0xff, + 0xff, 0xff] not [0xf8, 0xfc, 0xf8]). + + \param pixel a pixel value + \param format an SDL_PixelFormat structure describing the format of the + pixel + \param r a pointer filled in with the red component + \param g a pointer filled in with the green component + \param b a pointer filled in with the blue component + + \since This function is available since SDL 2.0.0. + + \sa SDL_GetRGBA + \sa SDL_MapRGB + \sa SDL_MapRGBA + + + + Map an RGBA quadruple to a pixel value for a given pixel format. + + This function maps the RGBA color value to the specified pixel format and + returns the pixel value best approximating the given RGBA color value for + the given pixel format. + + If the specified pixel format has no alpha component the alpha value will + be ignored (as it will be in formats with a palette). + + If the format has a palette (8-bit) the index of the closest matching color + in the palette will be returned. + + If the pixel format bpp (color depth) is less than 32-bpp then the unused + upper bits of the return value can safely be ignored (e.g., with a 16-bpp + format the return value can be assigned to a Uint16, and similarly a Uint8 + for an 8-bpp format). + + \param format an SDL_PixelFormat structure describing the format of the + pixel + \param r the red component of the pixel in the range 0-255 + \param g the green component of the pixel in the range 0-255 + \param b the blue component of the pixel in the range 0-255 + \param a the alpha component of the pixel in the range 0-255 + \returns a pixel value + + \since This function is available since SDL 2.0.0. + + \sa SDL_GetRGB + \sa SDL_GetRGBA + \sa SDL_MapRGB + + + + Map an RGB triple to an opaque pixel value for a given pixel format. + + This function maps the RGB color value to the specified pixel format and + returns the pixel value best approximating the given RGB color value for + the given pixel format. + + If the format has a palette (8-bit) the index of the closest matching color + in the palette will be returned. + + If the specified pixel format has an alpha component it will be returned as + all 1 bits (fully opaque). + + If the pixel format bpp (color depth) is less than 32-bpp then the unused + upper bits of the return value can safely be ignored (e.g., with a 16-bpp + format the return value can be assigned to a Uint16, and similarly a Uint8 + for an 8-bpp format). + + \param format an SDL_PixelFormat structure describing the pixel format + \param r the red component of the pixel in the range 0-255 + \param g the green component of the pixel in the range 0-255 + \param b the blue component of the pixel in the range 0-255 + \returns a pixel value + + \since This function is available since SDL 2.0.0. + + \sa SDL_GetRGB + \sa SDL_GetRGBA + \sa SDL_MapRGBA + + + + Free a palette created with SDL_AllocPalette(). + + \param palette the SDL_Palette structure to be freed + + \since This function is available since SDL 2.0.0. + + \sa SDL_AllocPalette + + + + Set a range of colors in a palette. + + \param palette the SDL_Palette structure to modify + \param colors an array of SDL_Color structures to copy into the palette + \param firstcolor the index of the first palette entry to modify + \param ncolors the number of entries to modify + \returns 0 on success or a negative error code if not all of the colors + could be set; call SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_AllocPalette + \sa SDL_CreateRGBSurface + + + + Set the palette for a pixel format structure. + + \param format the SDL_PixelFormat structure that will use the palette + \param palette the SDL_Palette structure that will be used + \returns 0 on success or a negative error code on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_AllocPalette + \sa SDL_FreePalette + + + + Create a palette structure with the specified number of color entries. + + The palette entries are initialized to white. + + \param ncolors represents the number of color entries in the color palette + \returns a new SDL_Palette structure on success or NULL on failure (e.g. if + there wasn't enough memory); call SDL_GetError() for more + information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_FreePalette + + + + Free an SDL_PixelFormat structure allocated by SDL_AllocFormat(). + + \param format the SDL_PixelFormat structure to free + + \since This function is available since SDL 2.0.0. + + \sa SDL_AllocFormat + + + + Create an SDL_PixelFormat structure corresponding to a pixel format. + + Returned structure may come from a shared global cache (i.e. not newly + allocated), and hence should not be modified, especially the palette. Weird + errors such as `Blit combination not supported` may occur. + + \param pixel_format one of the SDL_PixelFormatEnum values + \returns the new SDL_PixelFormat structure or NULL on failure; call + SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_FreeFormat + + + + Convert a bpp value and RGBA masks to an enumerated pixel format. + + This will return `SDL_PIXELFORMAT_UNKNOWN` if the conversion wasn't + possible. + + \param bpp a bits per pixel value; usually 15, 16, or 32 + \param Rmask the red mask for the format + \param Gmask the green mask for the format + \param Bmask the blue mask for the format + \param Amask the alpha mask for the format + \returns one of the SDL_PixelFormatEnum values + + \since This function is available since SDL 2.0.0. + + \sa SDL_PixelFormatEnumToMasks + + + + Convert one of the enumerated pixel formats to a bpp value and RGBA masks. + + \param format one of the SDL_PixelFormatEnum values + \param bpp a bits per pixel value; usually 15, 16, or 32 + \param Rmask a pointer filled in with the red mask for the format + \param Gmask a pointer filled in with the green mask for the format + \param Bmask a pointer filled in with the blue mask for the format + \param Amask a pointer filled in with the alpha mask for the format + \returns SDL_TRUE on success or SDL_FALSE if the conversion wasn't + possible; call SDL_GetError() for more information. + + \since This function is available since SDL 2.0.0. + + \sa SDL_MasksToPixelFormatEnum + + + + Get the human readable name of a pixel format. + + \param format the pixel format to query + \returns the human readable name of the specified pixel format or + `SDL_PIXELFORMAT_UNKNOWN` if the format isn't recognized. + + \since This function is available since SDL 2.0.0. + + + +\note Everything in the pixel format structure is read-only. + + + +The bits of this structure can be directly reinterpreted as an integer-packed +color which uses the SDL_PIXELFORMAT_RGBA32 format (SDL_PIXELFORMAT_ABGR8888 +on little-endian systems and SDL_PIXELFORMAT_RGBA8888 on big-endian systems). + + + + If a + b would overflow, return -1. Otherwise store a + b via ret + and return 0. + + \since This function is available since SDL 2.24.0. + + + + If a * b would overflow, return -1. Otherwise store a * b via ret + and return 0. + + \since This function is available since SDL 2.24.0. + + + + This function converts a string between encodings in one pass, returning a + string that must be freed with SDL_free() or NULL on error. + + \since This function is available since SDL 2.0.0. + + + + Get the number of outstanding (unfreed) allocations + + \since This function is available since SDL 2.0.7. + + + + Replace SDL's memory allocation functions with a custom set + + \since This function is available since SDL 2.0.7. + + + + Get the current set of SDL memory functions + + \since This function is available since SDL 2.0.7. + + + + Get the original set of SDL memory functions + + \since This function is available since SDL 2.24.0. + + + +\endcond + \file begin_code.h + + This file sets things up for C dynamic library function definitions, + static inlined functions, and structures aligned at 4-byte alignment. + If you don't like ugly C preprocessor code, don't look at this file. :) + + + +\name Floating-point constants + +\cond + + +\brief An unsigned 64-bit integer type. + + + +\brief A signed 64-bit integer type. + + + +\brief An unsigned 32-bit integer type. + + + +\brief A signed 32-bit integer type. + + + +\brief An unsigned 16-bit integer type. + + + +\brief A signed 16-bit integer type. + + + +\brief An unsigned 8-bit integer type. + + + +\brief A signed 8-bit integer type. + + + + \file close_code.h + + This file reverses the effects of begin_code.h and should be included + after you finish any function and structure declarations in your headers + + + + \file SDL_stdinc.h + + This is a general header that includes C language support. + + \file SDL_platform.h + + Try to get a standard set of platform defines. + + \file begin_code.h + + This file sets things up for C dynamic library function definitions, + static inlined functions, and structures aligned at 4-byte alignment. + If you don't like ugly C preprocessor code, don't look at this file. :) + + Get the name of the platform. + + Here are the names returned for some (but not all) supported platforms: + + - "Windows" + - "Mac OS X" + - "Linux" + - "iOS" + - "Android" + + \returns the name of the platform. If the correct platform name is not + available, returns a string beginning with the text "Unknown". + + \since This function is available since SDL 2.0.0. + + + +*!************************************************************************* + + + +Marks the application to stop at the end of the current frame. + + + + +Whether or not the application is currently in fullscreen mode or not. + + + + +Retrieves the designated height of the current window. + + + + +Retrieves the designated width of the current window. + + + + +Whether or not the engine is in a paused state where script updates and +physics are not in play. + + + + +Whether or not the engine is playing. This will always be true on Publish. +On Debug/Release builds, this is true when the editor is in Play Mode. It +will also be true even if the editor is in Play Mode but is paused. + + + + +Static class that contains useful properties for querying the state of the +engine. + + + + +Sets the parent of this Transform component. + + +Entity that contains the Transform component that this Transform will be +parented to. If null, unparenting will occur. + + +If true, the transform values of this Transform component will retain their +pre-parent-change global transforms. The local transform values will be +modified to ensure that the global transforms do not change. + + + + +Parent Transform that affects this Transform. + + + + +Global scale stored by this Transform. + + + + +Global euler angle rotations stored by this Transform. + + + + +Global rotation quaternion stored by this Transform. + + + + +Global position stored by this Transform. + + + + +Local scale stored by this Transform. + + + + +Local euler angle rotations stored by this Transform. + + + + +Local rotation quaternion stored by this Transform. + + + + +Local position stored by this Transform. + + + + +Constructs a Transform Component that represents a native Transform component +tied to the specified Entity. + + Entity that this Component will be tied to. + + + +CLR version of the SHADE Engine's TransformComponent. + + + + +Compares if two float values are close enough to be the same with the +specified tolerance value. + + One of the values to compare. + The other value to compare. + Tolerance for floating point comparison. + True if a and b are practically the same. + + + +Compares if two float values are close enough to be the same with a tolerance +of Epsilon. + + One of the values to compare. + The other value to compare. + True if a and b are practically the same. + + + +Calculates the linear parameter t that produces the interpolant value within +the range [a, b]. + + Start value. + End value. + Value between start and end. + Percentage of value between start and end. + + + +Linearly interpolates between a and b by t. +The parameter t is not clamped and a value based on a and b is supported. +If t is less than zero, or greater than one, then LerpUnclamped will result +in a return value outside the range a to b. + + The start value. + The end value. + The interpolation value between the two float. + The interpolated float result between the two float values. + + + +Linearly interpolates between a and b by t. +The parameter t is clamped to the range [0, 1]. + + The start value. + The end value. + The interpolation value between the two float. + The interpolated float result between the two float values. + + + +Converts an angle from radian representation to degree representation. + + Radian-based angle to convert. + The specified angle in degrees. + + + +Converts an angle from degree representation to radian representation. + + Degree-based angle to convert. + The specified angle in radians. + + + +Wraps a value if they get to low or too high. + + Value to wrap. + Minimum value to wrap at. + Maximum value to wrap at. + Wrapped value. + + + +Small value used for single precision floating point comparisons. + + + + +Radians-to-degrees conversion constant + + + + +Degrees-to-radians conversion constant + + + + +Contains utility Math functions. + + + + +Logs a native exception that is formatted nicely to the output. + + Native exception to log. + Name of the one responsible for the exception. + + + +Logs an exception that is formatted nicely to the output. + + Name of the one responsible for the exception. + Exception to log. + + + +Logs a native exception that is formatted nicely to the output. +Equivalent to calling +LogException(exception, Convert::ToNative(thrower->GetType()->Name)); + + Native exception to log. + +Object that threw the exception to label the exception message. +The name of the object will be used. + + + + +Logs an exception that is formatted nicely to the output. + + Exception to log. + +Object that threw the exception to label the exception message. +The name of the object will be used. + + + + +Logs an exception that is formatted nicely to the output. + + Exception to log. + + + +Logs a error message to the output with a label such that it looks like this: +"[Label] Message" + + The string to output. + +Name of the object that threw the error to label the error message. +The name of the object will be used. + + + + +Logs a error message to the output with a label such that it looks like this: +"[Label] Message" + + The string to output. + +Name of the object that threw the error to label the error message. +The name of the object will be used. + + + + +Logs a error message to the output with a label such that it looks like this: +"[Label] Message" + + The string to output. + +Object that threw the error to label the error message. +The name of the object will be used. + + + + +Logs a error message to the output. + + The string to output. + + + +Logs a error message to the output. + + The string to output. + + + +Logs a warning message to the output with a label such that it looks like this: +"[Label] Message" + + The string to output. + +Name of the object that threw the warning to label the warning message. +The name of the object will be used. + + + + +Logs a warning message to the output with a label such that it looks like this: +"[Label] Message" + + The string to output. + +Name of the object that threw the warning to label the warning message. +The name of the object will be used. + + + + +Logs a warning message to the output with a label such that it looks like this: +"[Label] Message" + + The string to output. + +Object that threw the warning to label the warning message. +The name of the object will be used. + + + + +Logs a warning message to the output. + + The string to output. + + + +Logs a warning message to the output. + + The string to output. + + + +Logs a message to the output with a label such that it looks like this: +"[Label] Message" + + The string to output. + +Name of the object that sent the message to label the message. +The name of the object will be used. + + + + +Logs a message to the output with a label such that it looks like this: +"[Label] Message" + + The string to output. + +Name of the object that sent the message to label the message. +The name of the object will be used. + + + + +Logs a message to the output with a label such that it looks like this: +"[Label] Message" + + The string to output. + +Object that sent the message to label the message. +The name of the object will be used. + + + + +Logs a message to the output. + + The string to output. + + + +Logs a message to the output. + + The string to output. + + + +Static class that contains the functions for working with time. + + + + +Material used to render this Renderable. + + + + +Material used to render this Renderable. + + + + +Mesh used to render this Renderable. + + + + +Constructs a Renderable Component that represents a native Renderable +component tied to the specified Entity. + + Entity that this Component will be tied to. + + + +CLR version of the SHADE Engine's SHRenderableComponent. + + + + +Retrieves the value of a specified property on the material. + + Type of property to get. + Name of the property to get. + Value of that property on the material. + +If this Material object is invalid. + + +If the name or type was specified that does not match the material's shader's +defined properties. + + + + +Set the value of a specific property. + + Type of property to set. + Name of the property to set. + Value to set te property to. + +If this Material object is invalid. + + +If the name or type was specified that does not match the material's shader's +defined properties. + + + + +Constructor for the Material + + Handle to the native material object. + + + +Managed counterpart of the native MaterialInstance object containing material +data that can be fed to Renderables for rendering. + + + + +Constructor for the Mesh + + Handle to the mesh object. + + + +Managed counterpart of the native Mesh object containing vertex data that can +be fed to Renderables for rendering. + + + +@brief Decomposes a transformation matrix into translation, orientation and scale. +@param[out] scale The scaling factor of the matrix. +@param[out] orientation The orientation of the matrix. +@param[out] translation The translation of the matrix. +@return True if decomposition was successful. + + + +@brief Decomposes a transformation matrix into translation, euler angles and scale. +@param[out] scale The scaling factor of the matrix. +@param[out] rotation The euler angles of the matrix. +@param[out] translation The translation of the matrix. +@return True if decomposition was successful. + + + +@brief Interface for a Column-Major Row Vector 4x4 Matrix. + + + + +Constructs a RigidBody Component that represents a native +SHRigidBodyComponent component tied to the specified Entity. + + Entity that this Component will be tied to. + + + +CLR version of the the SHADE Engine's SHRigidBodyComponent. + + + + +Creates an instance of the Managed representation of a Component with a +native Entity. + + Type of Component to create. + Native Entity that this Component is tied to. + The created Managed representation of the Component. + + + +Static constructor to initialize static data + + + + +Pointer to a function for Component manipulation operations. + + +Contains a set of Component related data used for resolving operations for +each Component. + + + + +Removes a Component from the specified Entity. + + Type of the Component to remove. + +Entity object that should have the specified Component removed from/ + + + + +Checks if the specified Entity has the specified Component. + + Type of the Component to check for. + Entity object to check for the Component. + +True if the specified Entity has the specified Component. False otherwise. + + + + +Ensures a Component on the specified Entity. + + Type of the Component to ensure. + Entity object to ensure the Component on. + Reference to the Component. + + + +Retrieves the first Component from the specified GameObjectt's children that +matches the specified type. + + Type of the Component to get. + Entity object to get the Component from. + +Reference to the Component or null if the Entity does not have the +specified Component. + + + + +Gets a Component from the specified Entity. + + Type of the Component to get. + Entity object to get the Component from. + +Reference to the Component or null if the Entity does not have the +specified Component. + + + + +Adds a Component to the specified Entity. + + Type of the Component to add. + +Entity object that should have the specified Component added to. + + Reference to the Component that was added. + + + +Static class which contains functions that map Pls::ECS's Component manipulation +functions to managed generic functions. + + + + +Gets a unique hash for this object. + + Unique hash for this object. + + + +Compares equality with another unboxed object. + + The unboxed object to compare with. + True if both objects are the same. + + + +Compares equality with an object of the same type. + + The object to compare with. + True if both objects are the same. + + + +Entity that this Component belongs to. + + + + +Constructor for BaseComponent to tie it to a specific Entity. +Constructors of derived Components should call this Constructor. + + Entity that this Component will be tied to. + + + +Implicit conversion operator to enable checking if a component is null. + + Component to check. + + + +Removes all Scripts of the specified type from this GameObject. + + Type of PLushieScripts to remove. + + + +Retrieves a immutable list of Scripts of the specified type from this +GameObject. + + Type of Scripts to Get. + Immutable list of Scripts of the specified type. + + + +Retrieves a Script of the specified type from this GameObject. +If multiple Scripts of the same specified type are added on the same +GameObject, this will retrieve the first one added. + + Type of Script to add. + Reference to the Script to retrieve. + + + +Adds a Script of the specified type to this GameObject. + + Type of Script to add. + Reference to the created Script. + + + +Removes a Component from this GameObject. If no Component exists to begin +with, nothing happens. + + Type of the Component to get. + + + +Gets a Component from this GameObject. + + Type of the Component to get. + +Reference to the Component or null if this GameObject does not have the +specified Component. + + + + +Adds a Component to this GameObject. + + Type of the Component to add. + Reference to the Component that was added. + + + +Retrieves the GameObject that this Component belongs to. + + + + +Class that serves as the base for a wrapper class to Components in native code. + + + + +Called when the attached GameObject has a Collider and leaves a +collision with another GameObject with a Collider2D. + + Information on the collision event. + + + +Called when the attached GameObject has a Collider and collides with +another GameObject with a Collider in subsequent frames of collision. + + Information on the collision event. + + + +Called when the attached GameObject has a Collider and collides with +another GameObject with a Collider in the first frame of collision. + + Information on the collision event. + + + +Called when the attached GameObject has a trigger Collider and leaves a +collision with another GameObject with a Collider2D. + + Information on the collision event. + + + +Called when the attached GameObject has a trigger Collider and collides with +another GameObject with a Collider in subsequent frames of collision. + + Information on the collision event. + + + +Called when the attached GameObject has a trigger Collider and collides with +another GameObject with a Collider in the first frame of collision. + + Information on the collision event. + + + +Called just before the end of the frame where the attached GameObject or +this script is destroyed directly or indirectly due to destruction of the +owner. + + + + +Called every frame after physics and collision resolution but before +rendering. + + + + +Called every frame before physics and collision resolution. + + + + +Called every frame in sync with Physics update steps and thus in most cases +will execute more than update() will. This will be called immediately before +a Physics update step. + + + + +Called on the first frame that the attached GameObject is active but always +after Awake(). + + + + +Called on the first frame that the attached GameObject is active if they are +a part of the scene. + + + + +Called immediately once this script is detached from a GameObject. + + + + +Called immediately once this script is attached to a GameObject. + + + + +Constructor for Script to tie it to a specific GameObject. +Constructors of derived Scripts should call this Constructor. + + +GameObject that this Script will be tied to. + + + + +Used to call onTriggerExit(). This should be called when a trigger-type +collision is detected between the attached GameObject and another GameObject. + + Information on the collision event. + + + +Used to call onTriggerStay(). This should be called when a trigger-type +collision is detected between the attached GameObject and another GameObject. + + Information on the collision event. + + + +Used to call onTriggerEnter(). This should be called when a trigger-type +collision is detected between the attached GameObject and another GameObject. + + Information on the collision event. + + + +Used to call onCollisionExit(). This should be called when a collision ends +between the attached GameObject and another GameObject. + + Information on the collision event. + + + +Used to call onCollisionStay(). This should be called when a collision is +persistent between the attached GameObject and another GameObject. + + Information on the collision event. + + + +Used to call onCollisionEnter(). This should be called when a collision is +detected between the attached GameObject and another GameObject. + + Information on the collision event. + + + +Used to call onDestroy(). This should be called at the end of the frame +where the attached GameObject or this script is destroyed directly or +indirectly due to destruction of the owner. + + + + +Used to call lateUpdate(). This should be called every frame after physics +and collision resolution but before rendering. + + + + +Used to call update(). This should be called every frame before physics and +collision resolution. + + + + +Used to call fixedUpdate(). This should be called in sync with Physics +update steps and thus in most cases will execute more than Update() will. +This will be called immediately before a Physics update step. + + + + +Used to call start(). This should be called on the first frame that the +attached GameObject is active but always after Awake(). + + + + +Used to call awake(). This should be called on the first frame that the +attached GameObject is active if they are a part of the scene. + + + + +Used to call onDetached(). This is called immediately when this script is +detached from a GameObject. + + + + +Used to call onAttached(). This is called immediately when this script is +attached to a GameObject. + + + + +Implicit conversion operator to enable checking if a component is null. + + Component to check. + + + +Removes all Scripts of the specified type from this GameObject. + + +Type of script to remove. +This needs to be a default constructable Script. + + + + +Retrieves a immutable list of scripts from the specified Entity that +matches the specified type. +
+Note that this function allocates. It should be used sparingly. +
+ +Type of scripts to get. +This needs to be a default constructable Script. + + +Immutable list of references to scripts of the specified type. + +
+ + +Retrieves the first Script from this GameObject's children that matches the +specified type. + + +Type of script to get. +This needs to be a default constructable Script. + + Reference to the script added + + + +Retrieves the first Script from this GameObject that matches the specified +type. + + +Type of script to get. +This needs to be a default constructable Script. + + Reference to the script added + + + +Adds a Script to this GameObject. + + +Type of script to add. +This needs to be a default constructable Script. + + Reference to the script added + + + +Removes a Component from the GameObject that this Script belongs to. + + +Type of the Component to remove. Must be derived from BaseComponent. + + + + +Ensures a Component on the GameObject that this Script belongs to. + + +Type of the Component to ensure. Must be derived from BaseComponent. + + Reference to the Component. + + + +Retrieves the first Component from this GameObject's children that matches +the specified type. + + +Type of the Component to get. Must be derived from BaseComponent. + + Reference to the Component that was retrieved. + + + +Gets a Component from the GameObject that this Script belongs to. + + +Type of the Component to get. Must be derived from BaseComponent. + + Reference to the Component that was retrieved. + + + +Adds a Component to the GameObject that this Script belongs to. + + +Type of the Component to add. Must be derived from BaseComponent. + + Reference to the Component that was added. + + + +GameObject that this Script belongs to. + + + + +Class that forms the basis of all "script"-objects that can be attached to +Entities to update each Entity's Components via C# code. + + + + +The RigidBody that you are colliding with. + + + + +The CollisionShape of the Collider that you are colliding with. + + + + +The Collider that you are colliding with. + + + + +The GameObject whose collider you are colliding with. + + + + +Struct that describes a collision + + + + +Checks if two GameObject references are different. + + GameObject to check. + Another GameObject to check with. + True if both Components are different. + + + +Checks if two GameObject references are the same. + + GameObject to check. + Another GameObject to check with. + True if both Components are the same. + + + +Gets a unique hash for this object. + + Unique hash for this object. + + + +Compares equality with another unboxed object. + + The unboxed object to compare with. + True if both objects are the same. + + + +Compares equality with an object of the same type. + + The object to compare with. + True if both objects are the same. + + + +Retrieves the native Entity object that this GameObject represents. + + Native Entity object that this GameObject represents. + + + +Retrieves the CLR Entity object that this GameObject represents. + + Entity object that this GameObject represents. + + + +Constructor for the GameObject. + + +Managed numerical representation of the ECS Entity that this GameObject +should represent. + + + + +Constructor for the GameObject. + + +The ECS Entity that this GameObject should represent. + + + + +Removes all Scripts of the specified type from this GameObject. + + Type of PLushieScripts to remove. + + + +Retrieves a immutable list of Scripts of the specified type from this +GameObject. + + Type of Scripts to retrieve. + Immutable list of Scripts of the specified type. + + + +Retrieves a Script of the specified type from child GameObjects. +If multiple Scripts of the same specified type are added on the same +child GameObject, this will retrieve the first one added. + + Type of Script to retrieve. + Reference to the Script to retrieve. + + + +Retrieves a Script of the specified type from this GameObject. +If multiple Scripts of the same specified type are added on the same +GameObject, this will retrieve the first one added. + + Type of Script to retrieve. + Reference to the Script to retrieve. + + + +Adds a Script of the specified type to this GameObject. + + Type of Script to add. + Reference to the created Script. + + + +Removes a Component from this GameObject. If no Component exists to begin +with, nothing happens. + + Type of the Component to get. + + + +Ensures a Component on this GameObject. + + Type of the Component to ensure. + +Reference to the Component. + + + + +Retrieves the first Component from this GameObject's children that matches +the specified type. + + Type of the Component to get. + +Reference to the Component or null if neither of this GameObject's children +does not have the specified Component. + + + + +Gets a Component from this GameObject. + + Type of the Component to get. + +Reference to the Component or null if this GameObject does not have the +specified Component. + + + + +Adds a Component to this GameObject. + + Type of the Component to add. + Reference to the Component that was added. + + + +Sets the active state of this GameObject. +
+The actual "activeness" of this GameObject is still dependent on the parents' +active states. +
+ +Whether to activate or deactivate this GameObject. + +
+ + +Sets the name of this GameObject. + + The name to set. + + + +Native Entity ID value for this GameObject. + + + + +Whether or not this Entity is active in the Scene hierarchy. + + + + +Whether or not this Entity alone, is active. This does not mean that this +object is active in the scene. For example, if this Entity's parent is not +active, then this Entity would also be not active. + + + + +Name of the object that this Entity represents. + + + + +Retrieves a GameObject with the specified name. If there are multiple +GameObjects with the same name, the first found GameObject will be retrieved. +There is no guaranteed order of which GameObject is considered "first". + + Name of the GameObject to find. + GameObject that has the specified name. Null if not found. + + + +Destroys the specified GameObject. Note that the specified GameObject will no +longer be a valid GameObject after this function is called. + + The GameObject to be destroyed. + + + +Creates a new GameObject in the current Scene. If multiple Scenes are loaded, +and you would like to create an object in a specific Scene, call the Scene's +CreateGameObject(). + + GameObject that represents the newly created GameObject. + + + +Lightweight object for an PlushieEngine Entity that allows for easy access +to Component and Script operations. + + + + +Constructor for a Tooltip attribute that fills in the description. + + Text to be shown when a field is hovered. + + + +Maximum value for the Ranged field. + + + + +Minimum value for the Ranged field. + + + + +Simple attribute to constrain the range of values for a field on the editor. + + + + +Converts from a native std::Stringto a managed String. + + The native std::string to convert from. + Managed copy of a native std::string. + + + +Converts from a managed String to a native std::string. + + The managed String to convert from. + Native copy of a managed String. + + + +Converts from a native Vector2 to a managed Vector2. + + The native Vector2 to convert from. + Managed copy of a native Vector2. + + + +Converts from a native Quaternion to a managed Quaternion. + + The native Quaternion to convert from. + Managed copy of a native Quaternion. + + + +Converts from a managed Quaternion to a native Quaternion. + + The managed Quaternion to convert from. + Native copy of a managed Quaternion. + + + +Converts from a native Vector2 to a managed Vector2. + + The native Vector2 to convert from. + Managed copy of a native Vector2. + + + +Converts from a managed Vector2 to a native Vector2. + + The managed Vector2 to convert from. + Native copy of a managed Vector2. + + + +Converts from a native Vector3 to a managed Vector3. + + The native Vector3 to convert from. + Managed copy of a native Vector3. + + + +Converts from a managed Vector3 to a native Vector3. + + The managed Vector3 to convert from. + Native copy of a managed Vector3. + + + +Converts from a native Entity to a managed Entity (UInt32). + + Native Entity to convert from. + Managed representation of the specified Entity. + + + +Provides functions easy and consistent syntax for converting between custom +managed and native types that are aligned. + + + + +Converts to true if this is a valid Handle. + + + + +The library that the handle was issued by. + + + + +The internal ID of the handle. + + + + +Creates a ray starting at origin along direction. + + Source of the ray. + Direction the ray travels in. + + + +The direction that a ray travels in. + + + + +The start point of the ray. + + + + +CLR version of the the SHADE Engine's Ray class that represents a ray in +3-Dimensional space. + + + + +Are two quaternions equal to each other? + + Left-hand side quaternion. + Right-hand side quaternion. + + + +Combines rotations lhs and rhs. + + Left-hand side quaternion. + Right-hand side quaternion. + + + +Spherically interpolates between a and b by t. The parameter t is not clamped. + + + + +Spherically interpolates between quaternions a and b by ratio t. The parameter t is clamped to the range [0, 1]. + + Start value, returned when t = 0. + End value, returned when t = 1. + Interpolation ratio. + A quaternion spherically interpolated between quaternions a and b. + + + +Rotates a rotation from towards to.
+The from quaternion is rotated towards to by an angular step of maxDegreesDelta (but note that the rotation will not overshoot). +Negative values of maxDegreesDelta will move away from to until the rotation is exactly the opposite direction. +
+
+ + +Converts this quaternion to one with the same orientation but with a magnitude of 1. + + + + +Creates a rotation with the specified forward and upwards directions.
+Z axis will be aligned with forward, X axis aligned with cross product between forward and upwards, and Y axis aligned with cross product between Z and X. +
+
+ + +Interpolates between a and b by t and normalizes the result afterwards. The parameter t is not clamped. + + + + +Interpolates between a and b by t and normalizes the result afterwards. The parameter t is clamped to the range [0, 1]. + + Start value, returned when t = 0. + End value, returned when t = 1. + Interpolation ratio. + A quaternion interpolated between quaternions a and b. + + + +Returns the Inverse of rotation. + + + + +Creates a rotation which rotates from fromDirection to toDirection. + + + + +Returns a rotation that rotates y degrees around the y axis, x degrees around the x axis, and z degrees around the z axis; applied in that order. + + + + +The dot product between two rotations. + + + + +Creates a rotation which rotates angle degrees around axis. + + + + +Returns the angle in degrees between two rotations a and b.
+ The angle in degrees between the two vectors. +
+ + +Gets a unique hash for this object. + + Unique hash for this object. + + + +Compares equality with another unboxed object. + + The unboxed object to compare with. + True if both objects are the same. + + + +Compares equality with an object of the same type. + + The object to compare with. + True if both objects are the same. + + + +Converts a rotation to angle-axis representation (angles in degrees). + + + + +Creates a rotation with the specified forward and upwards directions.
+The result is applied to this quaternion. +If used to orient a Transform, the Z axis will be aligned with forward and the Y axis with upwards, assuming these vectors are orthogonal. +Logs an error if the forward direction is zero. +
+ The direction to look in. + The vector that defines in which direction up is. +
+ + +Creates a rotation which rotates from fromDirection to toDirection.
+Use this to create a rotation which starts at the first Vector (fromDirection) and rotates to the second Vector (toDirection). +These Vectors must be set up in a script. +
+
+ + +Constructor to construct a Quaternion with the specified components. + + X-coordinate to set. + Y-coordinate to set. + Z-coordinate to set. + W-coordinate to set. + + + +W-component of the Quaternion. Do not directly modify quaternions. + + + + +Z-component of the Quaternion. +Don't modify this directly unless you know quaternions inside out. + + + + +Y-component of the Quaternion. +Don't modify this directly unless you know quaternions inside out. + + + + +X-component of the Quaternion. +Don't modify this directly unless you know quaternions inside out. + + + + +Shorthand for writing Quaternion(0, 0, 0, 1). + + + + +CLR version of SHADE's Quaternion class that represents an orientation. +Designed to closely match Unity's Quaternion struct. + + + + +Explicit conversion operator to enable explicit casting from a Vector2 to a +Vector3. + + Vector2 to convert from. + + + +Explicit conversion operator to enable explicit casting from a Vector3 to a +Vector2. + + Vector3 to convert from. + + + +Checks if two Vector3s are not approximately equal. This is equivalent to +calling !Vector3.IsNear() with default tolerance values. + + Vector3 to compare. + Another Vector3 to compare. + +True if all components are not approximately equal within the default +tolerance value. + + + + +Checks if two Vector3s are approximately equal. This is equivalent to +calling Vector3.IsNear() with default tolerance values. + + Vector3 to compare. + Another Vector3 to compare. + +True if all components are approximately equal within the default +tolerance value. + + + + +Calculates the division of a Vector3 with a scalar value and returns +the result. + + Scalar to divide with. + Vector3 to divide with. + The result of the scalar division. + + + +Calculates the multiplication of a Vector3 with a scalar value and returns +the result. + + Vector3 to multiply with. + Scalar to multiply with. + The result of the scalar multiplication. + + + +Calculates the division of a Vector3 with a scalar value and returns +the result. + + Scalar to divide with. + Vector3 to divide with. + The result of the scalar division. + + + +Calculates the multiplication of a Vector3 with a scalar value and returns +the result. + + Vector3 to multiply with. + Scalar to multiply with. + The result of the scalar multiplication. + + + +Calculates the component-wise multiplication of two Vector3s and returns the +result. + + Vector3 to multiply with. + Another Vector3 to multiply with. + The result of rhs subtracted from lhs. + + + +Subtracts a Vector3 from another Vector3 and returns the result. + + Vector3 to subtract from. + Another Vector3 to subtract. + The result of rhs subtracted from lhs. + + + +Adds two Vector3s together and returns the result. + + Vector3 to add. + Another Vector3 to add. + The result of lhs added to rhs + + + +Moves a point current towards target. +Similar to Lerp(), however, the function will ensure that the distance never +exceeds maxDistanceDelta. Negative values of maxDistanceDelta pushes the +vector away from target + + The current position of the point. + The target position to move to. + Maximum distance moved per call. + Vector representing the moved point. + + + +Linearly interpolates between two specified points. +This is most commonly used to find a point some fraction of the way along a +line between two endpoints. +Unlike Lerp(), t is not clamped to a range at all. + + The start Vector3, returned when t = 0.0f. + The end Vector3, returned when t = 1.0f. + Value used to interpolate between a and b. + The interpolated Vector3. + + + +Linearly interpolates between two specified points. +This is most commonly used to find a point some fraction of the way along a +line between two endpoints. + + The start Vector3, returned when t = 0.0f. + The end Vector3, returned when t = 1.0f. + +Value used to interpolate between a and b which is clamped to +the range[0, 1]. + + The interpolated Vector3. + + + +Computes and returns a Vector3 that is made from the largest components of +the two specified Vector3s. + + Vector3 to calculate maximum Vector3 with. + Another Vector3 to calculate maximum Vector3 with. + +The Vector3 that contains the largest components of the two specified +Vector3s. + + + + +Computes and returns a Vector3 that is made from the smallest components of +the two specified Vector3s. + + Vector3 to calculate minimum Vector3 with. + Another Vector3 to calculate minimum Vector3 with. + +The Vector3 that contains the smallest components of the two specified +Vector3s. + + + + +Rotates a Vector3 on the Z-axis by a specified angle in an anti-clockwise +direction. + + A Vector3 to rotate. + +Angle to rotate the vector by in an anti-clockwise direction in degrees. + + The Vector3 that represents the rotated vector. + + + +Rotates a Vector3 on the Z-axis by a specified angle in an anti-clockwise +direction. + + A Vector3 to rotate. + +Angle to rotate the vector by in an anti-clockwise direction in radians. + + The Vector3 that represents the rotated vector. + + + +Reflects a Vector3 across another Vector3. + + A Vector3 to reflect. + A normal to reflect the Vector3 across. + The Vector3 that represents vec reflected across normal. + + + +Computes and returns a Vector3 projection. + + Vector3 to project. + Vector3 to project onto. + The Vector3 that represents the projected vec onto direction. + + + +Computes and returns the cross product of 2 specified Vector3s. + + Vector3 to calculate cross product with. + Another Vector3 to calculate cross product with. + The cross product of the two Vector3s. + + + +Computes and returns the dot product of 2 specified Vector3s. + + Vector3 to calculate dot product with. + Another Vector3 to calculate dot product with. + Scalar value representing the dot product of the two Vector3s. + + + +Checks if two specified Vector3s are near in value. + + Vector3 to check if is near in value. + Another Vector3 to check if is near in value. + Amount of tolerance to do the comparison with. + +True if the two Vector3s are within the tolerance value specified + + + + +Checks if two specified Vector3s are near in value. + + Vector3 to check if is near in value. + Another Vector3 to check if is near in value. + +True if the two Vector3s are within the tolerance value specified + + + + +Gets a unique hash for this object. + + Unique hash for this object. + + + +Compares equality with another unboxed object. + + The unboxed object to compare with. + True if both objects are the same. + + + +Compares equality with an object of the same type. + + The object to compare with. + True if both objects are the same. + + + +Checks if a specified point is near this Vector3 that represents a point. + + The other point to check if we are near. + +The amount of tolerance before we consider these points as "near". + + +True if this Vector3 representing a point and the specified point are within +the range of the specified tolerance. False otherwise. + + + + +Checks if a specified point is near this Vector3 that represents a point with +a tolerance value of PLS_EPSILON. + + The other point to check if we are near. + +True if this Vector3 representing a point and the specified point are within +the range of the specified tolerance. False otherwise. + + + + +Calculates and returns the angle of this vector from the right vector. This +function returns values between -180.0f and 180.0f. + + Returns the angle of this vector from the right vector in degrees. + + + +Calculates and returns the angle of this vector from the right vector. This +function returns values between -Math.PI and Math.PI. + + Returns the angle of this vector from the right vector in radians. + + + +Calculates and returns the squared magnitude of this Vector3. + + Returns the squared length of this Vector3. + + + +Calculates and returns the magnitude of this Vector3. Note that this function +incurs a performance cost from the square root calculation. If you do not +need the precise magnitude, consider using GetSqrMagnitude() instead. + + Returns the length of this Vector3. + + + +Creates a copy of this Vector3 and returns a normalized version. + + +Returns a normalised copy of this Vector3. +If this Vector3 is a zero vector, a zero vector will be returned. + + + + +Normalises this current Vector3. This changes the data of this Vector3. +If you would like to get a copy, use GetNormalised() instead. +This function does nothing to a zero vector. + + + + +Conversion constructor to construct a Vector3 using a Vector2. + + + + + +Constructor to construct a Vector3 with the specified components. + + X-coordinate to set. + Y-coordinate to set. + Z-coordinate to set. + + + +Constructor to construct a Vector3 with the specified components with the +Z-component set to 0.0f. + + X-coordinate to set. + Y-coordinate to set. + + + +Constructor to construct a Vector3 with the specified components with the +Y and Z-component set to 0.0f. + + X-coordinate to set. + + + +Z-component of the Vector3. + + + + +Y-component of the Vector3. + + + + +X-component of the Vector3. + + + + +Shorthand for writing Vector3(0, 0, 0). + + + + +Shorthand for writing Vector3(0, 1, 0). + + + + +Shorthand for writing Vector3(1, 0, 0). + + + + +Shorthand for writing Vector3(float.PositiveInfinity, +float.PositiveInfinity, float.PositiveInfinity). + + + + +Shorthand for writing Vector3(1, 1, 1). + + + + +Shorthand for writing Vector3(float.NegativeInfinity, +float.NegativeInfinity, float.NegativeInfinity). + + + + +Shorthand for writing Vector3(-1, 0, 0). + + + + +Shorthand for writing Vector3(0, 0, 1). + + + + +Shorthand for writing Vector3(0, -1, 0). + + + + +Shorthand for writing Vector3(0, 0, -1). + + + + +CLR version of SHADE Engine's Vector3 class that represents a 3-Dimensional Vector. +Designed to closely match Unity's Vector3 struct. + + + + +Checks if two Vector2s are not approximately equal. This is equivalent to +calling !Vector2.IsNear() with default tolerance values. + + Vector2 to compare. + Another Vector2 to compare. + +True if all components are not approximately equal within the default +tolerance value. + + + + +Checks if two Vector2s are approximately equal. This is equivalent to +calling Vector2.IsNear() with default tolerance values. + + Vector2 to compare. + Another Vector2 to compare. + +True if all components are approximately equal within the default +tolerance value. + + + + +Calculates the division of a Vector2 with a scalar value and returns +the result. + + Scalar to divide with. + Vector2 to divide with. + The result of the scalar division. + + + +Calculates the multiplication of a Vector2 with a scalar value and returns +the result. + + Vector2 to multiply with. + Scalar to multiply with. + The result of the scalar multiplication. + + + +Calculates the division of a Vector2 with a scalar value and returns +the result. + + Scalar to divide with. + Vector2 to divide with. + The result of the scalar division. + + + +Calculates the multiplication of a Vector2 with a scalar value and returns +the result. + + Vector2 to multiply with. + Scalar to multiply with. + The result of the scalar multiplication. + + + +Calculates the component-wise multiplication of two Vector2s and returns the +result. + + Vector2 to multiply with. + Another Vector2 to multiply with. + The result of rhs subtracted from lhs. + + + +Subtracts a Vector2 from another Vector2 and returns the result. + + Vector2 to subtract from. + Another Vector2 to subtract. + The result of rhs subtracted from lhs. + + + +Adds two Vector2s together and returns the result. + + Vector2 to add. + Another Vector2 to add. + The result of lhs added to rhs + + + +Moves a point current towards target. +Similar to Lerp(), however, the function will ensure that the distance never +exceeds maxDistanceDelta. Negative values of maxDistanceDelta pushes the +vector away from target + + The current position of the point. + The target position to move to. + Maximum distance moved per call. + Vector representing the moved point. + + + +Linearly interpolates between two specified points. +This is most commonly used to find a point some fraction of the way along a +line between two endpoints. +Unlike Lerp(), t is not clamped to a range at all. + + The start Vector2, returned when t = 0.0f. + The end Vector2, returned when t = 1.0f. + Value used to interpolate between a and b. + The interpolated Vector2. + + + +Linearly interpolates between two specified points. +This is most commonly used to find a point some fraction of the way along a +line between two endpoints. + + The start Vector2, returned when t = 0.0f. + The end Vector2, returned when t = 1.0f. + +Value used to interpolate between a and b which is clamped to +the range[0, 1]. + + The interpolated Vector2. + + + +Computes and returns a Vector2 that is made from the largest components of +the two specified Vector2s. + + Vector2 to calculate maximum Vector2 with. + Another Vector2 to calculate maximum Vector2 with. + +The Vector2 that contains the largest components of the two specified +Vector2s. + + + + +Computes and returns a Vector2 that is made from the smallest components of +the two specified Vector2s. + + Vector2 to calculate minimum Vector2 with. + Another Vector2 to calculate minimum Vector2 with. + +The Vector2 that contains the smallest components of the two specified +Vector2s. + + + + +Rotates a Vector2 on the Z-axis by a specified angle in an anti-clockwise +direction. + + A Vector2 to rotate. + +Angle to rotate the vector by in an anti-clockwise direction in degrees. + + The Vector2 that represents the rotated vector. + + + +Rotates a Vector2 on the Z-axis by a specified angle in an anti-clockwise +direction. + + A Vector2 to rotate. + +Angle to rotate the vector by in an anti-clockwise direction in radians. + + The Vector2 that represents the rotated vector. + + + +Reflects a Vector2 across another Vector2. + + A Vector2 to reflect. + A normal to reflect the Vector2 across. + The Vector2 that represents vec reflected across normal. + + + +Computes and returns a Vector2 projection. + + Vector2 to project. + Vector2 to project onto. + The Vector2 that represents the projected vec onto direction. + + + +Computes a perpendicular Vector2 to the specified Vector2. + + Vector2 to find a perpendicular of. + +Whether the inward perpendicular Vector is retrieved. If true, the +resultant vector is rotated 90-degrees in a counter-clockwise. + + The perpendicular Vector2 relative to the specified Vector2. + + + + +Computes the inward perpendicular Vector2 to the specified Vector2. +Equivalent to calling Perpendicular(lhs, true). This means, the +resultant Vector2 is rotated 90-degrees in a counter-clockwise. + + Vector2 to find a perpendicular of. + +The perpendicular Vector2 relative to the specified Vector2. + + + + +Computes and returns the dot product of 2 specified Vector2s. + + Vector2 to calculate dot product with. + Another Vector2 to calculate dot product with. + +Scalar value representing the dot product of the two Vector2s. + + + + +Checks if two specified Vector2s are near in value. + + Vector2 to check if is near in value. + Another Vector2 to check if is near in value. + +Amount of tolerance to do the comparison with. + + +True if the two Vector2s are within the tolerance value specified + + + + +Checks if two specified Vector2s are near in value. + + Vector2 to check if is near in value. + Another Vector2 to check if is near in value. + +True if the two Vector2s are within the tolerance value specified + + + + +Gets a unique hash for this object. + + Unique hash for this object. + + + +Compares equality with another unboxed object. + + The unboxed object to compare with. + True if both objects are the same. + + + +Compares equality with an object of the same type. + + The object to compare with. + True if both objects are the same. + + + +Checks if a specified point is near this Vector2 that represents a point. + + The other point to check if we are near. + +The amount of tolerance before we consider these points as "near". + + +True if this Vector2 representing a point and the specified point are within +the range of the specified tolerance. False otherwise. + + + + +Checks if a specified point is near this Vector2 that represents a point with +a tolerance value of PLS_EPSILON. + + The other point to check if we are near. + +True if this Vector2 representing a point and the specified point are within +the range of the specified tolerance. False otherwise. + + + + +Calculates and returns the angle of this vector from the right vector. This +function returns values between -180.0f and 180.0f. + + Returns the angle of this vector from the right vector in degrees. + + + +Calculates and returns the angle of this vector from the right vector. This +function returns values between -Math.PI and Math.PI. + + Returns the angle of this vector from the right vector in radians. + + + +Calculates and returns the squared magnitude of this Vector2. + + Returns the squared length of this Vector2. + + + +Calculates and returns the magnitude of this Vector2. Note that this function +incurs a performance cost from the square root calculation. If you do not +need the precise magnitude, consider using GetSqrMagnitude() instead. + + Returns the length of this Vector2. + + + +Creates a copy of this Vector2 and returns a normalized version. + + +Returns a normalised copy of this Vector2. +If this Vector2 is a zero vector, a zero vector will be returned. + + + + +Normalises this current Vector2. This changes the data of this Vector2. +If you would like to get a copy, use GetNormalised() instead. +This function does nothing to a zero vector. + + + + +Constructor to construct a Vector2 with the specified components.. + + X-coordinate to set. + Y-coordinate to set. + + + +Constructor to construct a Vector2 with the specified components with the +Y-component set to 0.0f. + + X-coordinate to set. + + + +Y-component of the Vector2. + + + + +X-component of the Vector2. + + + + +Shorthand for writing Vector2(0, 0). + + + + +Shorthand for writing Vector2(0, 1). + + + + +Shorthand for writing Vector2(1, 0). + + + + +Shorthand for writing Vector2(float.PositiveInfinity, +float.PositiveInfinity). + + + + +Shorthand for writing Vector2(1, 1). + + + + +Shorthand for writing Vector2(float.NegativeInfinity, +float.NegativeInfinity). + + + + +Shorthand for writing Vector2(-1, 0). + + + + +Shorthand for writing Vector2(0, -1). + + + + +CLR version of SHADE Engine's Vector2 class that represents a 2-Dimensional Vector. +Designed to closely match Unity's Vector2 struct. + + + + +Checks if the specified entity is valid. This is done by checking if it +matches Pls::Entity::INVALID. + + The Entity to check. + True if the specified Entity is valid. + + + +Static class that contains useful utility functions for working with Entity. + + + + +Manages all resources in multiple ResourceLibraries. + + + + +Base class for SHResourceLibrary that holds information about the library type. + + + + +Template Specialization for Handle that represents a type-less Handle. + + + + +Converts to true if this is a valid Handle. + + + + +Native ID type of a handle + + + + +Base implementation of the Handle that is not templated to allow for holding +generic non-type-specific Handles. + + + + +Exception thrown when a generic Handle is being casted to the wrong type. + + + + +Exception thrown when an invalid Handle was dereferenced. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
\ No newline at end of file