Merge branch 'main' into SP3-20-UI-System

This commit is contained in:
maverickdgg 2022-11-18 09:38:42 +08:00
commit 9ac1c01008
154 changed files with 2615 additions and 1056 deletions

27
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@ -0,0 +1,27 @@
---
name: Bug report
about: Report a bug that should be fixed
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Additional context**
Add any other context about the problem here.

View File

@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest a feature for the project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

View File

@ -21,141 +21,6 @@
Layer: 4294967295 Layer: 4294967295
Strength: 0 Strength: 0
Scripts: ~ Scripts: ~
- EID: 1
Name: Floor
IsActive: true
NumberOfChildren: 0
Components:
Transform Component:
Translate: {x: -1.440328, y: -4.41369677, z: -5}
Rotate: {x: -0, y: 0, z: -0}
Scale: {x: 49.4798889, y: 0.5, z: 17.5}
Renderable Component:
Mesh: 149697411
Material: 126974645
RigidBody Component:
Type: Static
Mass: 1
Drag: 0.00999999978
Angular Drag: 0.00999999978
Use Gravity: true
Interpolate: true
Freeze Position X: false
Freeze Position Y: false
Freeze Position Z: false
Freeze Rotation X: false
Freeze Rotation Y: false
Freeze Rotation Z: false
Collider Component:
Colliders:
- Is Trigger: false
Type: Box
Half Extents: {x: 1, y: 1, z: 1}
Friction: 0.400000006
Bounciness: 0
Density: 1
Position Offset: {x: 0, y: 0, z: 0}
Scripts: ~
- EID: 10
Name: Default
IsActive: true
NumberOfChildren: 0
Components:
Transform Component:
Translate: {x: -4.40482807, y: 2.57871056, z: -5.21213436}
Rotate: {x: -0.361265004, y: 1.11661232, z: -0.626627684}
Scale: {x: 0.999982238, y: 0.999987125, z: 0.999981165}
RigidBody Component:
Type: Dynamic
Mass: 1
Drag: 0
Angular Drag: 0
Use Gravity: true
Interpolate: true
Freeze Position X: false
Freeze Position Y: false
Freeze Position Z: false
Freeze Rotation X: false
Freeze Rotation Y: false
Freeze Rotation Z: false
Collider Component:
Colliders:
- Is Trigger: false
Type: Box
Half Extents: {x: 1, y: 1, z: 1}
Friction: 0.400000006
Bounciness: 0
Density: 1
Position Offset: {x: 0, y: 0, z: 0}
Scripts: ~
- EID: 3
Name: Empty
IsActive: true
NumberOfChildren: 0
Components:
Transform Component:
Translate: {x: -0.0094268322, y: 0, z: 0}
Rotate: {x: -0, y: 0, z: -0}
Scale: {x: 1, y: 1, z: 1}
Scripts: ~
- EID: 4
Name: Empty2
IsActive: true
NumberOfChildren: 0
Components:
Transform Component:
Translate: {x: 0, y: 0, z: 0}
Rotate: {x: 0, y: 0, z: 0}
Scale: {x: 1, y: 1, z: 1}
Scripts: ~
- EID: 9
Name: Bag
IsActive: true
NumberOfChildren: 0
Components:
Transform Component:
Translate: {x: 0, y: 0, z: 0}
Rotate: {x: 0, y: 0, z: 0}
Scale: {x: 1, y: 1, z: 1}
Renderable Component:
Mesh: 144838771
Material: 123745521
Scripts: ~
- EID: 6
Name: AI
IsActive: true
NumberOfChildren: 0
Components:
Transform Component:
Translate: {x: -8, y: -2, z: 2.5}
Rotate: {x: 0, y: 0, z: 0}
Scale: {x: 1, y: 1, z: 1}
Renderable Component:
Mesh: 149697411
Material: 126974645
RigidBody Component:
Type: Dynamic
Mass: 1
Drag: 0
Angular Drag: 0
Use Gravity: true
Interpolate: false
Freeze Position X: false
Freeze Position Y: false
Freeze Position Z: false
Freeze Rotation X: true
Freeze Rotation Y: true
Freeze Rotation Z: true
Collider Component:
Colliders:
- Is Trigger: false
Type: Box
Half Extents: {x: 0.5, y: 0.5, z: 0.5}
Friction: 0.400000006
Bounciness: 0
Density: 1
Position Offset: {x: 0, y: 0.5, z: 0}
Scripts: ~
- EID: 7 - EID: 7
Name: BigBoi Name: BigBoi
IsActive: true IsActive: true
@ -181,51 +46,4 @@
Color: {x: 1, y: 1, z: 1, w: 1} Color: {x: 1, y: 1, z: 1, w: 1}
Layer: 4294967295 Layer: 4294967295
Strength: 0.25 Strength: 0.25
Scripts: ~ Scripts: ~
- EID: 5
Name: item
IsActive: true
NumberOfChildren: 0
Components:
Transform Component:
Translate: {x: 0, y: -2, z: -5}
Rotate: {x: 0, y: 0, z: 0}
Scale: {x: 2, y: 2, z: 2}
Renderable Component:
Mesh: 144838771
Material: 123745521
RigidBody Component:
Type: Dynamic
Mass: 1
Drag: 0
Angular Drag: 0
Use Gravity: true
Interpolate: false
Freeze Position X: false
Freeze Position Y: false
Freeze Position Z: false
Freeze Rotation X: true
Freeze Rotation Y: true
Freeze Rotation Z: true
Collider Component:
Colliders:
- Is Trigger: false
Type: Box
Half Extents: {x: 1, y: 1, z: 1}
Friction: 0.400000006
Bounciness: 0
Density: 1
Position Offset: {x: 0, y: 0.5, z: 0}
- Is Trigger: true
Type: Box
Half Extents: {x: 2, y: 2, z: 2}
Friction: 0.400000006
Bounciness: 0
Density: 1
Position Offset: {x: 0, y: 0.5, z: 0}
Scripts:
- Type: Item
currCategory: 0
- Type: PickAndThrow
throwForce: [100, 200, 100]
item: 51000

View File

@ -0,0 +1,50 @@
#version 450
#extension GL_ARB_separate_shader_objects : enable
#extension GL_ARB_shading_language_420pack : enable
#extension GL_EXT_nonuniform_qualifier : require
struct MatPropData
{
vec4 color;
int textureIndex;
float alpha;
vec3 beta;
};
layout(location = 0) in struct
{
vec4 vertPos; // location 0
vec2 uv; // location = 1
vec4 normal; // location = 2
} In;
// material stuff
layout(location = 3) flat in struct
{
int materialIndex;
uint eid;
uint lightLayerIndex;
} In2;
layout (set = 0, binding = 1) uniform sampler2D textures[]; // for textures (global)
layout (std430, set = 3, binding = 0) buffer MaterialProperties // For materials
{
MatPropData data[];
} MatProp;
layout(location = 0) out vec4 position;
layout(location = 1) out uint outEntityID;
layout(location = 2) out uint lightLayerIndices;
layout(location = 3) out vec4 normals;
layout(location = 4) out vec4 albedo;
void main()
{
position = In.vertPos;
normals = In.normal;
albedo = normals * texture(textures[nonuniformEXT(MatProp.data[In2.materialIndex].textureIndex)], In.uv) * MatProp.data[In2.materialIndex].color;
outEntityID = In2.eid;
lightLayerIndices = In2.lightLayerIndex;
}

Binary file not shown.

View File

@ -0,0 +1,3 @@
Name: Normals_FS
ID: 48689301
Type: 2

View File

@ -75,7 +75,8 @@ project "SHADE_Application"
"26439", "26439",
"26451", "26451",
"26437", "26437",
"4275" "4275",
"4635"
} }
linkoptions { "-IGNORE:4006" } linkoptions { "-IGNORE:4006" }

View File

@ -8,8 +8,8 @@
//#include "Scenes/SBEditorScene.h" //#include "Scenes/SBEditorScene.h"
#endif // SHEDITOR #endif // SHEDITOR
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
#include "Tools/SHFileUtilties.h" #include "Tools/Utilities/SHFileUtilties.h"
#include <chrono> #include <chrono>
#include <ratio> #include <ratio>
@ -45,7 +45,7 @@
#include "Scenes/SBMainScene.h" #include "Scenes/SBMainScene.h"
#include "Serialization/Configurations/SHConfigurationManager.h" #include "Serialization/Configurations/SHConfigurationManager.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
#include "Tools/SHDebugDraw.h" #include "Tools/SHDebugDraw.h"
using namespace SHADE; using namespace SHADE;
@ -61,6 +61,8 @@ namespace Sandbox
_In_ INT nCmdShow _In_ INT nCmdShow
) )
{ {
SHLOG_INFO_D("Initialising SHADE engine")
// Set working directory // Set working directory
SHFileUtilities::SetWorkDirToExecDir(); SHFileUtilities::SetWorkDirToExecDir();
WindowData wndData{}; WindowData wndData{};
@ -115,6 +117,7 @@ namespace Sandbox
SHSystemManager::RegisterRoutine<SHDebugDrawSystem, SHDebugDrawSystem::ProcessPointsRoutine>(); SHSystemManager::RegisterRoutine<SHDebugDrawSystem, SHDebugDrawSystem::ProcessPointsRoutine>();
SHSystemManager::RegisterRoutine<SHScriptEngine, SHScriptEngine::GizmosDrawRoutine>(); SHSystemManager::RegisterRoutine<SHScriptEngine, SHScriptEngine::GizmosDrawRoutine>();
SHSystemManager::RegisterRoutine<SHGraphicsSystem, SHGraphicsSystem::PrepareRenderRoutine>();
SHSystemManager::RegisterRoutine<SHGraphicsSystem, SHGraphicsSystem::BatcherDispatcherRoutine>(); SHSystemManager::RegisterRoutine<SHGraphicsSystem, SHGraphicsSystem::BatcherDispatcherRoutine>();
SHSystemManager::RegisterRoutine<SHGraphicsSystem, SHGraphicsSystem::BeginRoutine>(); SHSystemManager::RegisterRoutine<SHGraphicsSystem, SHGraphicsSystem::BeginRoutine>();

View File

@ -1,6 +1,6 @@
#include "SBpch.h" #include "SBpch.h"
#include <Engine/SHEngine.h> #include <Engine/SHEngine.h>
#include <Tools/SHLogger.h> #include <Tools/Logger/SHLogger.h>
#include <Tools/SHExceptionHandler.h> #include <Tools/SHExceptionHandler.h>
#include "Application/SBApplication.h" #include "Application/SBApplication.h"

View File

@ -27,6 +27,12 @@ project "SHADE_CSharp"
warnings 'Extra' warnings 'Extra'
postbuildcommands
{
"xcopy /r /y /q \"%{outputdir}\\net5.0\\SHADE_CSharp.xml\" \"%{outputdir}\"",
"xcopy /r /y /q \"%{outputdir}\\net5.0\\SHADE_CSharp.pdb\" \"%{outputdir}\""
}
filter "configurations:Debug" filter "configurations:Debug"
symbols "On" symbols "On"
defines {"_DEBUG"} defines {"_DEBUG"}
@ -41,12 +47,18 @@ project "SHADE_CSharp"
require "vstudio" require "vstudio"
function platformsElement(cfg) function platformsElementCS(cfg)
_p(2,'<Platforms>x64</Platforms>') _p(2,'<Platforms>x64</Platforms>')
end end
function docsElementCS(cfg)
_p(2,'<GenerateDocumentationFile>true</GenerateDocumentationFile>')
end
function docsLocationElementCS(cfg)
_p(2,'<DocumentationFile>$(OutDir)</DocumentationFile>')
end
premake.override(premake.vstudio.cs2005.elements, "projectProperties", function (oldfn, cfg) premake.override(premake.vstudio.cs2005.elements, "projectProperties", function (oldfn, cfg)
return table.join(oldfn(cfg), { return table.join(oldfn(cfg), {
platformsElement, platformsElementCS, docsElementCS, docsLocationElementCS,
}) })
end) end)

View File

@ -78,7 +78,8 @@ project "SHADE_Engine"
"26439", "26439",
"26451", "26451",
"26437", "26437",
"4275" "4275",
"4635"
} }
linkoptions { "-IGNORE:4006" } linkoptions { "-IGNORE:4006" }

View File

@ -143,7 +143,29 @@ namespace SHADE
return result; return result;
} }
/**************************************************************************** AssetType SHAssetManager::GetType(AssetID id) noexcept
{
if (assetCollection.contains(id))
{
return assetCollection[id].type;
}
SHLOG_WARNING("AssetID {}, does not belong to an asset", id)
return AssetType::INVALID;
}
std::optional<SHADE::SHAsset> SHAssetManager::GetAsset(AssetID id) noexcept
{
if (assetCollection.contains(id))
{
return assetCollection[id];
}
return {};
}
/****************************************************************************
* \brief Create record for new asset. CAN ONLY CREATE FOR CUSTOM * \brief Create record for new asset. CAN ONLY CREATE FOR CUSTOM
* ASSETS CREATED BY THE ENGINE. * ASSETS CREATED BY THE ENGINE.
* *
@ -161,21 +183,39 @@ namespace SHADE
newPath += PREFAB_FOLDER; newPath += PREFAB_FOLDER;
newPath += name; newPath += name;
newPath += PREFAB_EXTENSION; newPath += PREFAB_EXTENSION;
data = new SHPrefabAsset(); {
auto prefab = new SHPrefabAsset();
prefab->name = name;
data = prefab;
}
break; break;
case AssetType::SCENE: case AssetType::SCENE:
newPath += SCENE_FOLDER; newPath += SCENE_FOLDER;
newPath += name; newPath += name;
newPath += SCENE_EXTENSION; newPath += SCENE_EXTENSION;
data = new SHSceneAsset();
{
auto scene = new SHSceneAsset();
scene->name = name;
data = scene;
}
break; break;
case AssetType::MATERIAL: case AssetType::MATERIAL:
newPath += MATERIAL_FOLDER; newPath += MATERIAL_FOLDER;
newPath += name; newPath += name;
newPath += MATERIAL_EXTENSION; newPath += MATERIAL_EXTENSION;
data = new SHMaterialAsset();
{
auto material = new SHMaterialAsset();
material->name = name;
data = material;
}
break; break;
default: default:
@ -192,7 +232,7 @@ namespace SHADE
false false
}; };
assetCollection.insert({ auto result = assetCollection.emplace(
id, id,
SHAsset( SHAsset(
name, name,
@ -201,10 +241,13 @@ namespace SHADE
newPath, newPath,
false false
) )
}); );
assetData.emplace(id, data); assetData.emplace(id, data);
SHAssetMetaHandler::WriteMetaData(asset);
SaveAsset(id);
return id; return id;
} }
@ -361,6 +404,21 @@ namespace SHADE
modelPath += MODEL_EXTENSION; modelPath += MODEL_EXTENSION;
newPath = modelPath; newPath = modelPath;
} }
else if (ext == DDS_EXTENSION.data())
{
auto pathGen = SHTextureCompiler::CompileTextureAsset(path);
if (!pathGen.has_value())
{
SHLOG_ERROR("Texture Compilation Failed for: {}", path.string());
return;
}
newPath = pathGen.value();
}
else
{
SHLOG_WARNING("File Type compilation not yet Implemented: {}", path.string());
return;
}
if (genMeta) if (genMeta)
{ {
@ -376,7 +434,7 @@ namespace SHADE
void SHAssetManager::RefreshDirectory() noexcept void SHAssetManager::RefreshDirectory() noexcept
{ {
SHFileSystem::DestroyDirectory(folderRoot); SHFileSystem::DestroyDirectory(folderRoot);
assetCollection.clear(); //assetCollection.clear();
BuildAssetCollection(); BuildAssetCollection();
} }
@ -507,7 +565,7 @@ namespace SHADE
{ {
SHAsset newAsset{ SHAsset newAsset{
path.stem().string(), path.stem().string(),
GenerateAssetID(AssetType::SHADER_BUILT_IN), GenerateAssetID(AssetType::TEXTURE),
AssetType::SHADER_BUILT_IN, AssetType::SHADER_BUILT_IN,
path, path,
false false
@ -560,6 +618,34 @@ namespace SHADE
assetCollection.emplace(newAsset.id, newAsset); assetCollection.emplace(newAsset.id, newAsset);
SHAssetMetaHandler::WriteMetaData(newAsset); SHAssetMetaHandler::WriteMetaData(newAsset);
return newAsset.id;
}
else if (ext == SCENE_EXTENSION)
{
SHAsset newAsset{
path.stem().string(),
GenerateAssetID(AssetType::SCENE),
AssetType::SCENE,
path,
false
};
assetCollection.emplace(newAsset.id, newAsset);
SHAssetMetaHandler::WriteMetaData(newAsset);
return newAsset.id;
}
else if (ext == FONT_EXTENSION)
{
SHAsset newAsset{
path.stem().string(),
GenerateAssetID(AssetType::FONT),
AssetType::FONT,
path,
false
};
assetCollection.emplace(newAsset.id, newAsset);
SHAssetMetaHandler::WriteMetaData(newAsset);
return newAsset.id; return newAsset.id;
} }
} }
@ -571,8 +657,11 @@ namespace SHADE
for (auto& file : toGenNew) for (auto& file : toGenNew)
{ {
auto newID{ GenerateNewMeta(file->path).value() }; auto newID{ GenerateNewMeta(file->path) };
file->assetMeta = &assetCollection[newID]; if (newID.has_value())
{
file->assetMeta = &assetCollection[newID.value()];
}
} }
for (auto& asset : std::ranges::views::values(assetCollection)) for (auto& asset : std::ranges::views::values(assetCollection))
@ -583,6 +672,12 @@ namespace SHADE
for (auto i{ 0 }; i < asset.subAssets.size(); ++i) for (auto i{ 0 }; i < asset.subAssets.size(); ++i)
{ {
auto const id = asset.subAssets[i]->id; auto const id = asset.subAssets[i]->id;
if (assetCollection.contains(id))
{
continue;
}
assetCollection[id] = *asset.subAssets[i]; assetCollection[id] = *asset.subAssets[i];
delete asset.subAssets[i]; delete asset.subAssets[i];
asset.subAssets[i] = &assetCollection[id]; asset.subAssets[i] = &assetCollection[id];

View File

@ -50,6 +50,9 @@ namespace SHADE
* \return const& to unordered_map<AssetName, AssetID> * \return const& to unordered_map<AssetName, AssetID>
****************************************************************************/ ****************************************************************************/
static std::vector<SHAsset> GetAllAssets() noexcept; static std::vector<SHAsset> GetAllAssets() noexcept;
static std::optional<SHAsset> GetAsset(AssetID id) noexcept;
static AssetType GetType(AssetID id) noexcept;
/**************************************************************************** /****************************************************************************
* \brief Create record for new resource. CAN ONLY CREATE FOR CUSTOM * \brief Create record for new resource. CAN ONLY CREATE FOR CUSTOM

View File

@ -138,6 +138,7 @@ namespace SHADE
metaFile.close(); metaFile.close();
meta.path = path.parent_path().string() + "/" + path.stem().string(); meta.path = path.parent_path().string() + "/" + path.stem().string();
meta.path.make_preferred();
return meta; return meta;
} }

View File

@ -7,7 +7,7 @@
#include "ECS_Base/System/SHSystem.h" #include "ECS_Base/System/SHSystem.h"
#include "ECS_Base/System/SHSystemRoutine.h" #include "ECS_Base/System/SHSystemRoutine.h"
#include "ECS_Base/SHECSMacros.h" #include "ECS_Base/SHECSMacros.h"
#include "Math/SHMath.h" #include "Math/Vector/SHVec3.h"
#include <optional> #include <optional>
#include <FMOD/fmod_studio.hpp> #include <FMOD/fmod_studio.hpp>
#include "SH_API.h" #include "SH_API.h"

View File

@ -5,7 +5,7 @@
#include "ECS_Base/Managers/SHComponentManager.h" #include "ECS_Base/Managers/SHComponentManager.h"
#include "ECS_Base/SHECSMacros.h" #include "ECS_Base/SHECSMacros.h"
#include "ECS_Base/Managers/SHEntityManager.h" #include "ECS_Base/Managers/SHEntityManager.h"
#include "Tools/SHLog.h" #include "Tools/Logger/SHLog.h"
namespace SHADE namespace SHADE
{ {

View File

@ -5,7 +5,7 @@
#include "../Managers/SHSystemManager.h" #include "../Managers/SHSystemManager.h"
#include "SHTestComponents.h" #include "SHTestComponents.h"
#include "SHTestSystems.h" #include "SHTestSystems.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"

View File

@ -5,6 +5,7 @@
namespace SHADE namespace SHADE
{ {
bool SHDragDrop::hasDragDrop = false; bool SHDragDrop::hasDragDrop = false;
SHDragDrop::DragDropTag SHDragDrop::currentDragDropTag{};
bool SHDragDrop::BeginSource(ImGuiDragDropFlags const flags) bool SHDragDrop::BeginSource(ImGuiDragDropFlags const flags)
{ return ImGui::BeginDragDropSource(flags); } { return ImGui::BeginDragDropSource(flags); }
@ -16,6 +17,10 @@ namespace SHADE
{ return ImGui::BeginDragDropTarget(); } { return ImGui::BeginDragDropTarget(); }
void SHDragDrop::EndTarget() void SHDragDrop::EndTarget()
{ ImGui::EndDragDropTarget(); hasDragDrop = false;} {
ImGui::EndDragDropTarget();
hasDragDrop = false;
currentDragDropTag = {};
}
} }

View File

@ -19,9 +19,13 @@ namespace SHADE
static void EndSource(); static void EndSource();
template<typename T> template<typename T>
static bool SetPayload(std::string_view const type, T* object, ImGuiCond const cond = 0) static bool SetPayload(DragDropTag const& type, T* object, ImGuiCond const cond = 0)
{ {
hasDragDrop = ImGui::SetDragDropPayload(type.data(), static_cast<void*>(object), sizeof(T), cond); ImGui::SetDragDropPayload(type.data(), static_cast<void*>(object), sizeof(T), cond);
hasDragDrop = true;
currentDragDropTag = type;
return hasDragDrop; return hasDragDrop;
} }
@ -32,13 +36,16 @@ namespace SHADE
static void EndTarget(); static void EndTarget();
template<typename T> template<typename T>
static T* AcceptPayload(std::string_view const type, ImGuiDragDropFlags const flags = 0) static T* AcceptPayload(DragDropTag const& type, ImGuiDragDropFlags const flags = 0)
{ {
if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(type.data(), flags)) if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(type.data(), flags))
{
return static_cast<T*>(payload->Data); return static_cast<T*>(payload->Data);
}
return nullptr; return nullptr;
} }
static bool hasDragDrop; static bool hasDragDrop;
static DragDropTag currentDragDropTag;
}; };
} }

View File

@ -109,7 +109,7 @@ namespace SHADE
ImVec2 vertLineEnd = vertLineStart; ImVec2 vertLineEnd = vertLineStart;
for (auto const& subFolder : subFolders) for (auto const& subFolder : subFolders)
{ {
const float horizontalLineSize = 8.0f; const float horizontalLineSize = (subFolder->subFolders.empty() && subFolder->files.empty()) ? 25.0f : 8.0f;
const ImRect childRect = RecursivelyDrawTree(subFolder); const ImRect childRect = RecursivelyDrawTree(subFolder);
const float midPoint = (childRect.Min.y + childRect.Max.y) * 0.5f; const float midPoint = (childRect.Min.y + childRect.Max.y) * 0.5f;
drawList->AddLine(ImVec2(vertLineStart.x, midPoint), ImVec2(vertLineStart.x + horizontalLineSize, midPoint), treeLineColor, 1); drawList->AddLine(ImVec2(vertLineStart.x, midPoint), ImVec2(vertLineStart.x + horizontalLineSize, midPoint), treeLineColor, 1);
@ -117,7 +117,7 @@ namespace SHADE
} }
for (auto& file : files) for (auto& file : files)
{ {
const float horizontalLineSize = 25.0f; const float horizontalLineSize = (file.assetMeta && !file.assetMeta->subAssets.empty()) ? 8.0f : 25.0f;
const ImRect childRect = DrawFile(file); const ImRect childRect = DrawFile(file);
const float midPoint = (childRect.Min.y + childRect.Max.y) * 0.5f; const float midPoint = (childRect.Min.y + childRect.Max.y) * 0.5f;
drawList->AddLine(ImVec2(vertLineStart.x, midPoint), ImVec2(vertLineStart.x + horizontalLineSize, midPoint), treeLineColor, 1); drawList->AddLine(ImVec2(vertLineStart.x, midPoint), ImVec2(vertLineStart.x + horizontalLineSize, midPoint), treeLineColor, 1);
@ -182,7 +182,10 @@ namespace SHADE
return nodeRect; return nodeRect;
} }
if(file.assetMeta) if(file.assetMeta)
DrawAsset(file.assetMeta, file.ext); {
const ImRect childRect = DrawAsset(file.assetMeta, file.ext);
return childRect;
}
} }
ImRect SHAssetBrowser::DrawAsset(SHAsset const* const asset, FileExt const& ext /*= ""*/) noexcept ImRect SHAssetBrowser::DrawAsset(SHAsset const* const asset, FileExt const& ext /*= ""*/) noexcept

View File

@ -23,7 +23,7 @@
#include <imgui.h> #include <imgui.h>
#include "Serialization/SHSerialization.h" #include "Serialization/SHSerialization.h"
#include "Tools/SHClipboardUtilities.h" #include "Tools/Utilities/SHClipboardUtilities.h"
namespace SHADE namespace SHADE
@ -117,9 +117,12 @@ namespace SHADE
{ {
if(ImGui::IsDragDropActive()) if(ImGui::IsDragDropActive())
{ {
ParentSelectedEntities(MAX_EID, draggingEntities); if (SHDragDrop::currentDragDropTag == SHDragDrop::DRAG_EID)
draggingEntities.clear(); {
ImGui::ClearDragDrop(); ParentSelectedEntities(MAX_EID, draggingEntities);
draggingEntities.clear();
ImGui::ClearDragDrop();
}
} }
} }
ImGui::End(); ImGui::End();
@ -233,8 +236,9 @@ namespace SHADE
{ {
ParentSelectedEntities(eid, draggingEntities); ParentSelectedEntities(eid, draggingEntities);
draggingEntities.clear(); draggingEntities.clear();
SHDragDrop::EndTarget(); //ImGui::ClearDragDrop();
} }
SHDragDrop::EndTarget();
} }
//Context menu //Context menu
@ -342,13 +346,16 @@ namespace SHADE
SHEntityManager::CreateEntity(MAX_EID, "DefaultChild", parentEID); SHEntityManager::CreateEntity(MAX_EID, "DefaultChild", parentEID);
} }
void SHHierarchyPanel::ParentSelectedEntities(EntityID parentEID, std::vector<EntityID> const& entities) const noexcept void SHHierarchyPanel::ParentSelectedEntities(EntityID parentEID, std::vector<EntityID> const& entities) noexcept
{ {
auto const& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); auto const& sceneGraph = SHSceneManager::GetCurrentSceneGraph();
std::vector<EntityID> entitiesToParent = CleanUpEIDList(entities);
//auto const editor = SHSystemManager::GetSystem<SHEditor>(); //auto const editor = SHSystemManager::GetSystem<SHEditor>();
SHEntityParentCommand::EntityParentData entityParentData; SHEntityParentCommand::EntityParentData entityParentData;
std::vector<EntityID> parentedEIDS; std::vector<EntityID> parentedEIDS;
for (auto const& eid : entities) for (auto const& eid : entitiesToParent)
{ {
if(eid == parentEID) if(eid == parentEID)
continue; continue;
@ -411,14 +418,7 @@ namespace SHADE
void SHHierarchyPanel::CopySelectedEntities() void SHHierarchyPanel::CopySelectedEntities()
{ {
const auto editor = SHSystemManager::GetSystem<SHEditor>(); const auto editor = SHSystemManager::GetSystem<SHEditor>();
auto const& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); std::vector<EntityID> entitiesToCopy = CleanUpEIDList(editor->selectedEntities);
std::vector<EntityID> entitiesToCopy{};
std::ranges::copy_if(editor->selectedEntities, std::back_inserter(entitiesToCopy), [&sceneGraph](EntityID const& eid)
{
if(sceneGraph.GetParent(eid)->GetEntityID() == MAX_EID)
return true;
return false;
});
SHClipboardUtilities::WriteToClipboard(SHSerialization::SerializeEntitiesToString(entitiesToCopy)); SHClipboardUtilities::WriteToClipboard(SHSerialization::SerializeEntitiesToString(entitiesToCopy));
} }
@ -431,19 +431,25 @@ namespace SHADE
void SHHierarchyPanel::DeleteSelectedEntities() void SHHierarchyPanel::DeleteSelectedEntities()
{ {
const auto editor = SHSystemManager::GetSystem<SHEditor>(); const auto editor = SHSystemManager::GetSystem<SHEditor>();
std::vector<EntityID> entitiesToDelete = CleanUpEIDList(editor->selectedEntities);
SHCommandManager::PerformCommand(std::make_shared<SHDeleteEntitiesCommand>(entitiesToDelete));
}
std::vector<EntityID> SHHierarchyPanel::CleanUpEIDList(std::vector<EntityID> const& entities)
{
std::vector<EntityID> result;
auto const& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); auto const& sceneGraph = SHSceneManager::GetCurrentSceneGraph();
std::vector<EntityID> entitiesToDelete{}; std::ranges::copy_if(entities, std::back_inserter(result), [&sceneGraph, &entities](EntityID const& eid)
std::ranges::copy_if(editor->selectedEntities, std::back_inserter(entitiesToDelete), [&sceneGraph, &selectedEntities = editor->selectedEntities](EntityID const& eid)
{ {
EntityID parentEID = sceneGraph.GetParent(eid)->GetEntityID(); EntityID parentEID = sceneGraph.GetParent(eid)->GetEntityID();
if (parentEID == MAX_EID) if (parentEID == MAX_EID)
return true; return true;
else if(std::ranges::find(selectedEntities, parentEID) == selectedEntities.end()) if (std::ranges::find(entities, parentEID) == entities.end())
return true; return true;
return false; return false;
}); });
SHCommandManager::PerformCommand(std::make_shared<SHDeleteEntitiesCommand>(entitiesToDelete)); return result;
} }
}//namespace SHADE }//namespace SHADE

View File

@ -27,12 +27,13 @@ namespace SHADE
void DrawMenuBar() const noexcept; void DrawMenuBar() const noexcept;
ImRect RecursivelyDrawEntityNode(SHSceneNode* const); ImRect RecursivelyDrawEntityNode(SHSceneNode* const);
void CreateChildEntity(EntityID parentEID) const noexcept; void CreateChildEntity(EntityID parentEID) const noexcept;
void ParentSelectedEntities(EntityID parentEID, std::vector<EntityID> const& entities) const noexcept; void ParentSelectedEntities(EntityID parentEID, std::vector<EntityID> const& entities) noexcept;
void SelectRangeOfEntities(EntityID beginEID, EntityID EndEID); void SelectRangeOfEntities(EntityID beginEID, EntityID EndEID);
void SelectAllEntities(); void SelectAllEntities();
void CopySelectedEntities(); void CopySelectedEntities();
void PasteEntities(EntityID parentEID = MAX_EID); void PasteEntities(EntityID parentEID = MAX_EID);
void DeleteSelectedEntities(); void DeleteSelectedEntities();
std::vector<EntityID> CleanUpEIDList(std::vector<EntityID> const& entities);
bool skipFrame = false; bool skipFrame = false;
std::string filter; std::string filter;
bool isAnyNodeSelected = false; bool isAnyNodeSelected = false;

View File

@ -68,10 +68,10 @@ namespace SHADE
{ {
if (!component) if (!component)
return; return;
const auto componentType = rttr::type::get<T>(); const auto componentType = rttr::type::get<T>();
ImGui::PushID(SHFamilyID<SHComponent>::GetID<T>()); ImGui::PushID(SHFamilyID<SHComponent>::GetID<T>());
SHEditorWidgets::CheckBox("##IsActive", [component]() {return component->isActive; }, [component](bool const& active) {component->isActive = active; }, "Is Component Active"); SHEditorWidgets::CheckBox("##IsActive", [component]() {return component->isActive; }, [component](bool const& active) {component->isActive = active; }, "Is Component Active");
ImGui::PopID();
ImGui::SameLine(); ImGui::SameLine();
if (ImGui::CollapsingHeader(componentType.get_name().data())) if (ImGui::CollapsingHeader(componentType.get_name().data()))
{ {
@ -216,6 +216,90 @@ namespace SHADE
} }
} }
else DrawContextMenu(component); else DrawContextMenu(component);
ImGui::PopID();
}
template<>
static void DrawComponent(SHRigidBodyComponent* component)
{
if(!component)
return;
ImGui::PushID(SHFamilyID<SHComponent>::GetID<SHRigidBodyComponent>());
const auto componentType = rttr::type::get<SHRigidBodyComponent>();
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);
SHRigidBodyComponent::Type rbType = component->GetType();
auto enumAlign = rttr::type::get<SHRigidBodyComponent::Type>().get_enumeration();
auto names = enumAlign.get_names();
std::vector<const char*> list;
for (auto const& name : names)
list.push_back(name.data());
SHEditorWidgets::ComboBox("Type", list, [component] {return static_cast<int>(component->GetType()); }, [component, enumAlign](int const& idx)
{
auto values = enumAlign.get_values();
auto it = std::next(values.begin(), idx);
component->SetType((*it).convert<SHRigidBodyComponent::Type>());
}, "RigidBody Type");
if(rbType == SHRigidBodyComponent::Type::DYNAMIC) //Dynamic only fields
{
SHEditorWidgets::CheckBox("Use Gravity", [component]{return component->IsGravityEnabled();}, [component](bool const& value){component->SetGravityEnabled(value);}, "Gravity");
SHEditorWidgets::DragFloat("Mass", [component] {return component->GetMass(); }, [component](float const& value) {component->SetMass(value); }, "Mass");
}
if (rbType == SHRigidBodyComponent::Type::DYNAMIC || rbType == SHRigidBodyComponent::Type::KINEMATIC) //Dynamic or Kinematic only fields
{
SHEditorWidgets::DragFloat("Drag", [component] {return component->GetDrag(); }, [component](float const& value) {component->SetDrag(value); }, "Drag");
SHEditorWidgets::DragFloat("Angular Drag", [component] {return component->GetAngularDrag(); }, [component](float const& value) {component->SetAngularDrag(value); }, "Angular Drag");
SHEditorWidgets::CheckBox("Interpolate", [component] {return component->IsInterpolating(); }, [component](bool const& value) {component->SetInterpolate(value); }, "Interpolate");
SHEditorWidgets::BeginPanel(std::format("{} Constraints", ICON_FA_LOCK).data(), { ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y });
SHEditorWidgets::TextLabel("Freeze Position");
SHEditorWidgets::CheckBox("X", [component] {return component->GetFreezePositionX(); }, [component](bool const& value) {component->SetFreezePositionX(value); }, "Freeze Position - X"); ImGui::SameLine();
SHEditorWidgets::CheckBox("Y", [component] {return component->GetFreezePositionY(); }, [component](bool const& value) {component->SetFreezePositionY(value); }, "Freeze Position - Y"); ImGui::SameLine();
SHEditorWidgets::CheckBox("Z", [component] {return component->GetFreezePositionZ(); }, [component](bool const& value) {component->SetFreezePositionZ(value); }, "Freeze Position - Z");
SHEditorWidgets::TextLabel("Freeze Rotation");
SHEditorWidgets::CheckBox("X", [component] {return component->GetFreezeRotationX(); }, [component](bool const& value) {component->SetFreezeRotationX(value); }, "Freeze Rotation - X"); ImGui::SameLine();
SHEditorWidgets::CheckBox("Y", [component] {return component->GetFreezeRotationY(); }, [component](bool const& value) {component->SetFreezeRotationY(value); }, "Freeze Rotation - Y"); ImGui::SameLine();
SHEditorWidgets::CheckBox("Z", [component] {return component->GetFreezeRotationZ(); }, [component](bool const& value) {component->SetFreezeRotationZ(value); }, "Freeze Rotation - Z");
SHEditorWidgets::EndPanel();
}
//Debug Info (Read-Only)
if(ImGui::CollapsingHeader("Debug Information", ImGuiTreeNodeFlags_DefaultOpen))//Dynamic or Kinematic only fields
{
SHEditorWidgets::DragVec3("Position", { "X", "Y", "Z" }, [component] {return component->GetPosition(); }, [](SHVec3 const& value) {}, false, "Position", 0.1f, "%.3f", 0.0f, 0.0f, ImGuiSliderFlags_ReadOnly);
SHEditorWidgets::DragVec3("Rotation", { "X", "Y", "Z" }, [component] {return component->GetRotation(); }, [](SHVec3 const& value) {}, false, "Rotation", 0.1f, "%.3f", 0.0f, 0.0f, ImGuiSliderFlags_ReadOnly);
if (rbType == SHRigidBodyComponent::Type::DYNAMIC || rbType == SHRigidBodyComponent::Type::KINEMATIC) //Dynamic or Kinematic only fields
{
SHEditorWidgets::DragVec3("Velocity", { "X", "Y", "Z" }, [component] {return component->GetLinearVelocity(); }, [](SHVec3 const& value) {}, false, "Linear Velocity", 0.1f, "%.3f", 0.0f, 0.0f, ImGuiSliderFlags_ReadOnly);
SHEditorWidgets::DragVec3("Angular\nVelocity", { "X", "Y", "Z" }, [component] {return component->GetAngularVelocity(); }, [](SHVec3 const& value) {}, false, "Angular Velocity", 0.1f, "%.3f", 0.0f, 0.0f, ImGuiSliderFlags_ReadOnly);
}
if (rbType == SHRigidBodyComponent::Type::DYNAMIC) //Dynamic only fields
{
SHEditorWidgets::DragVec3("Force", { "X", "Y", "Z" }, [component] {return component->GetForce(); }, [](SHVec3 const& value) {}, false, "Force", 0.1f, "%.3f", 0.0f, 0.0f, ImGuiSliderFlags_ReadOnly);
SHEditorWidgets::DragVec3("Torque", { "X", "Y", "Z" }, [component] {return component->GetTorque(); }, [](SHVec3 const& value) {}, false, "Torque", 0.1f, "%.3f", 0.0f, 0.0f, ImGuiSliderFlags_ReadOnly);
SHEditorWidgets::CheckBox("Is Asleep", [component] {return component->GetIsSleeping(); }, [](bool value) {}, "If the Rigid Body is asleep");
}
}
}
else
{
DrawContextMenu(component);
}
ImGui::PopID();
} }
template<> template<>
@ -223,6 +307,7 @@ namespace SHADE
{ {
if (!component) if (!component)
return; return;
ImGui::PushID(SHFamilyID<SHComponent>::GetID<SHColliderComponent>());
const auto componentType = rttr::type::get(*component); const auto componentType = rttr::type::get(*component);
SHEditorWidgets::CheckBox("##IsActive", [component]() {return component->isActive; }, [component](bool const& active) {component->isActive = active; }, "Is Component Active"); SHEditorWidgets::CheckBox("##IsActive", [component]() {return component->isActive; }, [component](bool const& active) {component->isActive = active; }, "Is Component Active");
@ -246,7 +331,7 @@ namespace SHADE
if (collider->GetType() == SHCollisionShape::Type::BOX) if (collider->GetType() == SHCollisionShape::Type::BOX)
{ {
SHEditorWidgets::BeginPanel(std::format("{} Box #{}", ICON_FA_CUBE, i).data(), { ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y }); SHEditorWidgets::BeginPanel(std::format("{} Box #{}", ICON_FA_CUBE, i).data(), { ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y });
const auto* BOX = reinterpret_cast<const SHBoundingBox*>(collider->GetShape()); const auto* BOX = reinterpret_cast<const SHBox*>(collider->GetShape());
SHEditorWidgets::DragVec3 SHEditorWidgets::DragVec3
( (
"Half Extents", { "X", "Y", "Z" }, "Half Extents", { "X", "Y", "Z" },
@ -256,7 +341,7 @@ namespace SHADE
else if (collider->GetType() == SHCollisionShape::Type::SPHERE) else if (collider->GetType() == SHCollisionShape::Type::SPHERE)
{ {
SHEditorWidgets::BeginPanel(std::format("{} Sphere #{}", ICON_MD_CIRCLE, i).data(), { ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y }); SHEditorWidgets::BeginPanel(std::format("{} Sphere #{}", ICON_MD_CIRCLE, i).data(), { ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y });
const auto* SPHERE = reinterpret_cast<const SHBoundingSphere*>(collider->GetShape()); const auto* SPHERE = reinterpret_cast<const SHSphere*>(collider->GetShape());
SHEditorWidgets::DragFloat SHEditorWidgets::DragFloat
( (
"Radius", "Radius",
@ -275,21 +360,12 @@ namespace SHADE
[&collider] [&collider]
{ {
auto offset = collider->GetRotationOffset(); auto offset = collider->GetRotationOffset();
offset.x = SHMath::RadiansToDegrees(offset.x);
offset.y = SHMath::RadiansToDegrees(offset.y);
offset.z = SHMath::RadiansToDegrees(offset.z);
return offset; return offset;
}, },
[&collider](SHVec3 const& vec) [&collider](SHVec3 const& vec)
{ {
const SHVec3 vecInRad collider->SetRotationOffset(vec);
{ }, true);
SHMath::DegreesToRadians(vec.x)
, SHMath::DegreesToRadians(vec.y)
, SHMath::DegreesToRadians(vec.z)
};
collider->SetRotationOffset(vecInRad);
});
SHEditorWidgets::EndPanel(); SHEditorWidgets::EndPanel();
} }
@ -322,6 +398,7 @@ namespace SHADE
} }
} }
else DrawContextMenu(component); else DrawContextMenu(component);
ImGui::PopID();
} }
template<> template<>
@ -329,6 +406,7 @@ namespace SHADE
{ {
if (!component) if (!component)
return; return;
ImGui::PushID(SHFamilyID<SHComponent>::GetID<SHLightComponent>());
const auto componentType = rttr::type::get(*component); const auto componentType = rttr::type::get(*component);
SHEditorWidgets::CheckBox("##IsActive", [component]() {return component->isActive; }, [component](bool const& active) {component->isActive = active; }, "Is Component Active"); SHEditorWidgets::CheckBox("##IsActive", [component]() {return component->isActive; }, [component](bool const& active) {component->isActive = active; }, "Is Component Active");
ImGui::SameLine(); ImGui::SameLine();
@ -352,6 +430,7 @@ namespace SHADE
{ {
DrawContextMenu(component); DrawContextMenu(component);
} }
ImGui::PopID();
} }
template<> template<>
@ -359,6 +438,7 @@ namespace SHADE
{ {
if (!component) if (!component)
return; return;
ImGui::PushID(SHFamilyID<SHComponent>::GetID<SHRenderable>());
const auto componentType = rttr::type::get(*component); const auto componentType = rttr::type::get(*component);
SHEditorWidgets::CheckBox("##IsActive", [component]() {return component->isActive; }, [component](bool const& active) {component->isActive = active; }, "Is Component Active"); SHEditorWidgets::CheckBox("##IsActive", [component]() {return component->isActive; }, [component](bool const& active) {component->isActive = active; }, "Is Component Active");
ImGui::SameLine(); ImGui::SameLine();
@ -367,27 +447,39 @@ namespace SHADE
DrawContextMenu(component); DrawContextMenu(component);
Handle<SHMesh> const& mesh = component->GetMesh(); Handle<SHMesh> const& mesh = component->GetMesh();
Handle<SHMaterialInstance> const& mat = component->GetMaterial(); Handle<SHMaterialInstance> const& mat = component->GetMaterial();
const auto MESH_NAME = SHResourceManager::GetAssetName<SHMesh>(mesh).value_or("");
SHEditorWidgets::DragDropReadOnlyField<AssetID>("Mesh", std::to_string(SHResourceManager::GetAssetID<SHMesh>(mesh).value_or(0)).data(), [component]() SHEditorWidgets::DragDropReadOnlyField<AssetID>("Mesh", MESH_NAME, [component]()
{ {
Handle<SHMesh> const& mesh = component->GetMesh(); Handle<SHMesh> const& mesh = component->GetMesh();
return SHResourceManager::GetAssetID<SHMesh>(mesh).value_or(0); return SHResourceManager::GetAssetID<SHMesh>(mesh).value_or(0);
}, },
[component](AssetID const& id) [component](AssetID const& id)
{ {
if(SHAssetManager::GetType(id) != AssetType::MESH)
{
SHLOG_WARNING("Attempted to assign non mesh asset to Renderable Mesh property!")
return;
}
component->SetMesh(SHResourceManager::LoadOrGet<SHMesh>(id)); component->SetMesh(SHResourceManager::LoadOrGet<SHMesh>(id));
SHResourceManager::FinaliseChanges(); SHResourceManager::FinaliseChanges();
}, SHDragDrop::DRAG_RESOURCE); }, SHDragDrop::DRAG_RESOURCE);
SHEditorWidgets::DragDropReadOnlyField<AssetID>("Material", mat ? std::to_string(SHResourceManager::GetAssetID<SHMaterial>(mat->GetBaseMaterial()).value_or(0)).data() : "", [component]() const auto MAT_NAME = mat ? SHResourceManager::GetAssetName<SHMaterial>(mat->GetBaseMaterial()).value_or("") : "";
{ SHEditorWidgets::DragDropReadOnlyField<AssetID>("Material", MAT_NAME,
Handle<SHMaterialInstance> const& mat = component->GetMaterial(); [component]()
if(!mat) {
return static_cast<AssetID>(0); Handle<SHMaterialInstance> const& mat = component->GetMaterial();
return SHResourceManager::GetAssetID<SHMaterial>(mat->GetBaseMaterial()).value_or(0); if (!mat)
}, return static_cast<AssetID>(0);
return SHResourceManager::GetAssetID<SHMaterial>(mat->GetBaseMaterial()).value_or(0);
},
[component](AssetID const& id) [component](AssetID const& id)
{ {
if (SHAssetManager::GetType(id) != AssetType::MATERIAL)
{
SHLOG_WARNING("Attempted to assign non material asset to Renderable Mesh property!")
return;
}
auto gfxSystem = SHSystemManager::GetSystem<SHGraphicsSystem>(); auto gfxSystem = SHSystemManager::GetSystem<SHGraphicsSystem>();
component->SetMaterial(gfxSystem->AddOrGetBaseMaterialInstance(SHResourceManager::LoadOrGet<SHMaterial>(id))); component->SetMaterial(gfxSystem->AddOrGetBaseMaterialInstance(SHResourceManager::LoadOrGet<SHMaterial>(id)));
}, SHDragDrop::DRAG_RESOURCE); }, SHDragDrop::DRAG_RESOURCE);
@ -396,5 +488,6 @@ namespace SHADE
{ {
DrawContextMenu(component); DrawContextMenu(component);
} }
ImGui::PopID();
} }
} }

View File

@ -78,7 +78,26 @@ namespace SHADE
ImGui::BeginDisabled(!isDirty); ImGui::BeginDisabled(!isDirty);
if(ImGui::Button(std::format("{} Save", ICON_MD_SAVE).data())) if(ImGui::Button(std::format("{} Save", ICON_MD_SAVE).data()))
{ {
//save auto gfxSystem = SHSystemManager::GetSystem<SHGraphicsSystem>();
// Replace Material if it's been instantiated
auto matHandle = SHResourceManager::Get<SHMaterial>(currentViewedMaterial);
if (matHandle)
{
// - Get Shader Modules
auto vertShader = SHResourceManager::LoadOrGet<SHVkShaderModule>(currentMatSpec->vertexShader);
auto fragShader = SHResourceManager::LoadOrGet<SHVkShaderModule>(currentMatSpec->fragShader);
if (vertShader && fragShader && gfxSystem)
{
// - Retrieve pipeline from pipeline library
auto renderPass = gfxSystem->GetPrimaryRenderpass();
auto subPass = renderPass->GetSubpass(currentMatSpec->subpassName);
auto pipeline = renderPass->GetOrCreatePipeline({ vertShader, fragShader }, subPass);
// - Set Pipeline
matHandle->SetPipeline(pipeline);
}
}
// Save Properties
if(auto matAsset = SHAssetManager::GetData<SHMaterialAsset>(currentViewedMaterial)) if(auto matAsset = SHAssetManager::GetData<SHMaterialAsset>(currentViewedMaterial))
{ {
YAML::Emitter out; YAML::Emitter out;
@ -102,7 +121,20 @@ namespace SHADE
currentMaterial->SetProperty(VARIABLE->offset, PROP_NODE.as<float>()); currentMaterial->SetProperty(VARIABLE->offset, PROP_NODE.as<float>());
break; break;
case SHADE::SHShaderBlockInterface::Variable::Type::INT: case SHADE::SHShaderBlockInterface::Variable::Type::INT:
currentMaterial->SetProperty(VARIABLE->offset, PROP_NODE.as<int>()); {
Handle<SHTexture> texture = SHResourceManager::LoadOrGet<SHTexture>(PROP_NODE.as<int>());
// HACK: Need to split this out to a separate pass before loading the materials and subsequently, the scenes
gfxSystem->BuildTextures();
if (texture)
{
matHandle->SetProperty(VARIABLE->offset, texture->TextureArrayIndex);
}
else
{
SHLOG_WARNING("[] Attempted to load invalid texture! Setting to 0.");
matHandle->SetProperty(VARIABLE->offset, 0);
}
}
break; break;
case SHADE::SHShaderBlockInterface::Variable::Type::VECTOR2: case SHADE::SHShaderBlockInterface::Variable::Type::VECTOR2:
currentMaterial->SetProperty(VARIABLE->offset, PROP_NODE.as<SHVec2>()); currentMaterial->SetProperty(VARIABLE->offset, PROP_NODE.as<SHVec2>());
@ -136,12 +168,38 @@ namespace SHADE
{ {
/*if(!shaderModule) /*if(!shaderModule)
return;*/ return;*/
auto gfxSystem = SHSystemManager::GetSystem<SHGraphicsSystem>();
auto interface = gfxSystem->GetDefaultMaterialInstance()->GetBaseMaterial()->GetShaderBlockInterface();
//auto interface = shaderModule->GetReflectedData().GetDescriptorBindingInfo().GetShaderBlockInterface(SHGraphicsConstants::DescriptorSetIndex::PER_INSTANCE, SHGraphicsConstants::DescriptorSetBindings::BATCHED_PER_INST_DATA); //auto interface = shaderModule->GetReflectedData().GetDescriptorBindingInfo().GetShaderBlockInterface(SHGraphicsConstants::DescriptorSetIndex::PER_INSTANCE, SHGraphicsConstants::DescriptorSetBindings::BATCHED_PER_INST_DATA);
int const varCount = static_cast<int>(interface->GetVariableCount()); // Shader
bool shaderChanged = false;
const auto* SHADER_INFO = SHAssetManager::GetData<SHShaderAsset>(currentMatSpec->fragShader);
const std::string SHADER_NAME = SHADER_INFO ? SHADER_INFO->name : "Unknown Shader";
ImGui::BeginDisabled();
isDirty |= SHEditorWidgets::DragDropReadOnlyField<AssetID>
(
"Fragment Shader", SHADER_NAME.data(),
[this]() { return currentMatSpec->fragShader; },
[this](const AssetID& id) { currentMatSpec->fragShader = id; },
SHDragDrop::DRAG_RESOURCE
);
ImGui::EndDisabled();
// Load the shader to access it's data
auto fragShader = SHResourceManager::LoadOrGet<SHVkShaderModule>(currentMatSpec->fragShader);
if (!fragShader)
return;
// Get interface for the shader combination
auto interface = fragShader->GetReflectedData().GetDescriptorBindingInfo().GetShaderBlockInterface
(
SHGraphicsConstants::DescriptorSetIndex::PER_INSTANCE,
SHGraphicsConstants::DescriptorSetBindings::BATCHED_PER_INST_DATA
);
if (!interface)
return;
// Properties
int const varCount = static_cast<int>(interface->GetVariableCount());
for (int i = 0; i < varCount; ++i) for (int i = 0; i < varCount; ++i)
{ {
auto variable = interface->GetVariable(i); auto variable = interface->GetVariable(i);

View File

@ -35,7 +35,7 @@ namespace SHADE
constexpr ImGuiWindowFlags dockspaceFlags = ImGuiDockNodeFlags_PassthruCentralNode; constexpr ImGuiWindowFlags dockspaceFlags = ImGuiDockNodeFlags_PassthruCentralNode;
//#==============================================================# //#==============================================================#
//|| Public Member Functions || //|| Public Member Functions ||
//#==============================================================# //#==============================================================#
SHEditorMenuBar::SHEditorMenuBar() SHEditorMenuBar::SHEditorMenuBar()
@ -221,13 +221,20 @@ namespace SHADE
ImGui::BeginDisabled(editor->editorState == SHEditor::State::PLAY); ImGui::BeginDisabled(editor->editorState == SHEditor::State::PLAY);
if(ImGui::SmallButton(ICON_MD_PLAY_ARROW)) if(ImGui::SmallButton(ICON_MD_PLAY_ARROW))
{ {
if(editor->SaveScene()) if(editor->editorState == SHEditor::State::STOP)
{
if (editor->SaveScene())
{
editor->Play();
}
}
else
{ {
editor->Play(); editor->Play();
} }
} }
ImGui::EndDisabled(); ImGui::EndDisabled();
ImGui::BeginDisabled(editor->editorState == SHEditor::State::PAUSE); ImGui::BeginDisabled(editor->editorState == SHEditor::State::STOP || editor->editorState == SHEditor::State::PAUSE);
if(ImGui::SmallButton(ICON_MD_PAUSE)) if(ImGui::SmallButton(ICON_MD_PAUSE))
{ {
editor->Pause(); editor->Pause();

View File

@ -3,7 +3,7 @@
#include <memory> #include <memory>
#include <unordered_map> #include <unordered_map>
#include "SHEditorWindow.h" #include "SHEditorWindow.h"
#include "Tools/SHLog.h" #include "Tools/Logger/SHLog.h"
namespace SHADE namespace SHADE
{ {

View File

@ -14,6 +14,7 @@
#include "Camera/SHCameraSystem.h" #include "Camera/SHCameraSystem.h"
#include "FRC/SHFramerateController.h" #include "FRC/SHFramerateController.h"
#include "../../SHEditorWidgets.hpp"
constexpr std::string_view windowName = "\xef\x80\x95 Viewport"; constexpr std::string_view windowName = "\xef\x80\x95 Viewport";
@ -85,7 +86,7 @@ namespace SHADE
shouldUpdateCamArm = ImGui::IsWindowHovered() && ImGui::IsKeyDown(ImGuiKey_LeftAlt) && ImGui::IsMouseDown(ImGuiMouseButton_Left); shouldUpdateCamArm = ImGui::IsWindowHovered() && ImGui::IsKeyDown(ImGuiKey_LeftAlt) && ImGui::IsMouseDown(ImGuiMouseButton_Left);
if (editor->editorState != SHEditor::State::PLAY && ImGui::IsWindowFocused() && !ImGui::IsMouseDown(ImGuiMouseButton_Right)) if (editor->editorState != SHEditor::State::PLAY && !ImGui::IsAnyItemActive() && !ImGui::IsMouseDown(ImGuiMouseButton_Right))
{ {
if (ImGui::IsKeyReleased(ImGuiKey_W)) if (ImGui::IsKeyReleased(ImGuiKey_W))
{ {
@ -151,7 +152,7 @@ namespace SHADE
if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled))
{ {
ImGui::BeginTooltip(); ImGui::BeginTooltip();
ImGui::Text("Translate [Q]"); ImGui::Text("Translate [W]");
ImGui::EndTooltip(); ImGui::EndTooltip();
} }
if (isTranslate) if (isTranslate)
@ -169,7 +170,7 @@ namespace SHADE
if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled))
{ {
ImGui::BeginTooltip(); ImGui::BeginTooltip();
ImGui::Text("Rotate [W]"); ImGui::Text("Rotate [E]");
ImGui::EndTooltip(); ImGui::EndTooltip();
} }
if (isRotate) if (isRotate)
@ -187,12 +188,19 @@ namespace SHADE
if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled))
{ {
ImGui::BeginTooltip(); ImGui::BeginTooltip();
ImGui::Text("Scale [E]"); ImGui::Text("Scale [R]");
ImGui::EndTooltip(); ImGui::EndTooltip();
} }
if (isScale) if (isScale)
ImGui::PopStyleColor(); ImGui::PopStyleColor();
ImGui::EndDisabled(); ImGui::EndDisabled();
auto camSystem = SHSystemManager::GetSystem<SHCameraSystem>();
auto editorCamera = camSystem->GetEditorCamera();
//ImGui::SetNextItemWidth(10.0f);
SHEditorWidgets::SliderFloat("CamSpeed", 0.0f, 5.0f, [editorCamera] {return editorCamera->movementSpeed; }, [editorCamera](float const& value) {editorCamera->movementSpeed = value; });
SHEditorWidgets::DragVec3("TurnSpeed", { "X", "Y", "Z" }, [editorCamera] {return editorCamera->turnSpeed; }, [editorCamera](SHVec3 const& value) {editorCamera->turnSpeed = value; });
ImGui::EndMenuBar(); ImGui::EndMenuBar();
} }
} }

View File

@ -10,7 +10,7 @@
//#==============================================================# //#==============================================================#
//|| SHADE Includes || //|| SHADE Includes ||
//#==============================================================# //#==============================================================#
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
#include "Tools/SHException.h" #include "Tools/SHException.h"
#include "ECS_Base/Managers/SHSystemManager.h" #include "ECS_Base/Managers/SHSystemManager.h"

View File

@ -15,7 +15,7 @@
#include "ECS_Base/System/SHSystemRoutine.h" #include "ECS_Base/System/SHSystemRoutine.h"
#include "Resource/SHHandle.h" #include "Resource/SHHandle.h"
#include "EditorWindow/SHEditorWindow.h" #include "EditorWindow/SHEditorWindow.h"
#include "Tools/SHLog.h" #include "Tools/Logger/SHLog.h"
#include "Gizmos/SHTransformGizmo.h" #include "Gizmos/SHTransformGizmo.h"
#include "Events/SHEventDefines.h" #include "Events/SHEventDefines.h"
#include "Events/SHEvent.h" #include "Events/SHEvent.h"

View File

@ -166,14 +166,14 @@ namespace SHADE
const ImGuiWindow* const window = ImGui::GetCurrentWindow(); const ImGuiWindow* const window = ImGui::GetCurrentWindow();
if (window->SkipItems) if (window->SkipItems)
return false; return false;
static constexpr float defaultLabelColWidth = 80.0f;
const ImGuiContext& g = *GImGui; const ImGuiContext& g = *GImGui;
bool valueChanged = false; bool valueChanged = false;
ImGui::BeginGroup(); ImGui::BeginGroup();
ImGui::PushID(label.c_str()); ImGui::PushID(label.c_str());
PushMultiItemsWidthsAndLabels(componentLabels, 0.0f); PushMultiItemsWidthsAndLabels(componentLabels, 0.0f);
ImGui::BeginColumns("DragVecCol", 2, ImGuiOldColumnFlags_NoBorder | ImGuiOldColumnFlags_NoResize); ImGui::BeginColumns("DragVecCol", 2, ImGuiOldColumnFlags_NoBorder | ImGuiOldColumnFlags_NoResize);
ImGui::SetColumnWidth(-1, 80.0f); ImGui::SetColumnWidth(-1, defaultLabelColWidth);
ImGui::Text(label.c_str()); ImGui::Text(label.c_str());
if (isHovered) if (isHovered)
*isHovered |= ImGui::IsItemHovered(); *isHovered |= ImGui::IsItemHovered();
@ -219,7 +219,7 @@ namespace SHADE
} }
bool const changed = DragN<float, 2>(label, componentLabels, { &values.x, &values.y }, speed, displayFormat, valueMin, valueMax, flags); bool const changed = DragN<float, 2>(label, componentLabels, { &values.x, &values.y }, speed, displayFormat, valueMin, valueMax, flags);
static bool startRecording = false; static bool startRecording = false;
if (changed) if (!(flags & ImGuiSliderFlags_ReadOnly) && changed)
{ {
if(isAnAngleInRad) if(isAnAngleInRad)
{ {
@ -255,7 +255,7 @@ namespace SHADE
bool isHovered = false; bool isHovered = false;
bool const changed = DragN<float, 3>(label, componentLabels, { &values.x, &values.y, &values.z }, speed, displayFormat, valueMin, valueMax, flags, &isHovered); bool const changed = DragN<float, 3>(label, componentLabels, { &values.x, &values.y, &values.z }, speed, displayFormat, valueMin, valueMax, flags, &isHovered);
static bool startRecording = false; static bool startRecording = false;
if (changed) if (!(flags & ImGuiSliderFlags_ReadOnly) && changed)
{ {
SHVec3 old = get(); SHVec3 old = get();
if(isAnAngleInRad) if(isAnAngleInRad)
@ -293,7 +293,7 @@ namespace SHADE
} }
bool const changed = DragN<float, 4>(label, componentLabels, { &values.x, &values.y, &values.z, &values.w }, speed, displayFormat, valueMin, valueMax, flags); bool const changed = DragN<float, 4>(label, componentLabels, { &values.x, &values.y, &values.z, &values.w }, speed, displayFormat, valueMin, valueMax, flags);
static bool startRecording = false; static bool startRecording = false;
if (changed) if (!(flags & ImGuiSliderFlags_ReadOnly) && changed)
{ {
if(isAnAngleInRad) if(isAnAngleInRad)
{ {
@ -422,7 +422,7 @@ namespace SHADE
ImGui::BeginGroup(); ImGui::BeginGroup();
ImGui::PushID(label.data()); ImGui::PushID(label.data());
TextLabel(label); TextLabel(label);
bool changed = ImGui::InputText("##", &text, ImGuiInputTextFlags_ReadOnly, nullptr, nullptr); bool changed = ImGui::InputText("##inputText", &text, ImGuiInputTextFlags_ReadOnly, nullptr, nullptr);
if(SHDragDrop::BeginTarget()) if(SHDragDrop::BeginTarget())
{ {
if(T* payload = SHDragDrop::AcceptPayload<T>(dragDropTag)) if(T* payload = SHDragDrop::AcceptPayload<T>(dragDropTag))
@ -454,7 +454,7 @@ namespace SHADE
ImGui::BeginGroup(); ImGui::BeginGroup();
ImGui::PushID(label.data()); ImGui::PushID(label.data());
TextLabel(label); TextLabel(label);
const bool hasChange = ImGui::DragScalar("##", data_type, &value, speed, &p_min, &p_max, displayFormat, flags); const bool hasChange = ImGui::DragScalar("##dragScalar", data_type, &value, speed, &p_min, &p_max, displayFormat, flags);
static bool startRecording = false; static bool startRecording = false;
if (hasChange) if (hasChange)
{ {
@ -487,7 +487,7 @@ namespace SHADE
ImGui::BeginGroup(); ImGui::BeginGroup();
ImGui::PushID(label.data()); ImGui::PushID(label.data());
TextLabel(label); TextLabel(label);
const bool hasChange = ImGui::DragFloat("##", &value, speed, p_min, p_max, displayFormat, flags); const bool hasChange = ImGui::DragFloat("##dragFloat", &value, speed, p_min, p_max, displayFormat, flags);
static bool startRecording = false; static bool startRecording = false;
if (hasChange) if (hasChange)
{ {
@ -520,7 +520,7 @@ namespace SHADE
ImGui::BeginGroup(); ImGui::BeginGroup();
ImGui::PushID(label.data()); ImGui::PushID(label.data());
TextLabel(label); TextLabel(label);
const bool hasChange = ImGui::DragInt("##", &value, speed, p_min, p_max, displayFormat, flags); const bool hasChange = ImGui::DragInt("##dragInt", &value, speed, p_min, p_max, displayFormat, flags);
static bool startRecording = false; static bool startRecording = false;
if (hasChange) if (hasChange)
{ {
@ -553,7 +553,7 @@ namespace SHADE
ImGui::BeginGroup(); ImGui::BeginGroup();
ImGui::PushID(label.data()); ImGui::PushID(label.data());
TextLabel(label); TextLabel(label);
bool const hasChange = ImGui::SliderScalar("##", data_type, &value, &min, &max, displayFormat, flags); bool const hasChange = ImGui::SliderScalar("##sliderScalar", data_type, &value, &min, &max, displayFormat, flags);
static bool startRecording = false; static bool startRecording = false;
if (hasChange) if (hasChange)
{ {
@ -587,7 +587,8 @@ namespace SHADE
ImGui::BeginGroup(); ImGui::BeginGroup();
ImGui::PushID(label.data()); ImGui::PushID(label.data());
TextLabel(label); TextLabel(label);
bool const hasChange = ImGui::SliderFloat("##", &value, min, max, displayFormat, flags); ImGui::SetNextItemWidth(ImGui::CalcTextSize(displayFormat).x + ImGui::GetStyle().ItemInnerSpacing.x * 2.0f);
bool const hasChange = ImGui::SliderFloat("##sliderFloat", &value, min, max, displayFormat, flags);
static bool startRecording = false; static bool startRecording = false;
if (hasChange) if (hasChange)
{ {
@ -621,7 +622,7 @@ namespace SHADE
ImGui::BeginGroup(); ImGui::BeginGroup();
ImGui::PushID(label.data()); ImGui::PushID(label.data());
TextLabel(label); TextLabel(label);
bool const hasChange = ImGui::SliderInt("##", &value, min, max, displayFormat, flags); bool const hasChange = ImGui::SliderInt("##sliderInt", &value, min, max, displayFormat, flags);
static bool startRecording = false; static bool startRecording = false;
if (hasChange) if (hasChange)
{ {

View File

@ -12,11 +12,11 @@
//TODO Legacy code. Delete soon //TODO Legacy code. Delete soon
#include <SHpch.h>
#include <chrono> #include <chrono>
#include <cassert> #include <cassert>
#include <SHpch.h>
#include "SHFramerateController.h" #include "SHFramerateController.h"
#include "../Tools/SHLogger.h"
namespace SHADE namespace SHADE
{ {

View File

@ -152,7 +152,10 @@ namespace SHADE
bool found{ false }; bool found{ false };
for (auto const& asset : assets) for (auto const& asset : assets)
{ {
assetCollection.emplace(asset.id, asset); if (!assetCollection.contains(asset.id))
{
assetCollection.emplace(asset.id, asset);
}
if (file.name == asset.name) if (file.name == asset.name)
{ {
AssetPath path{ file.path }; AssetPath path{ file.path };
@ -170,22 +173,6 @@ namespace SHADE
toGenerate.push_back(&file); toGenerate.push_back(&file);
} }
} }
//for (auto const& asset : assets)
//{
// assetCollection.emplace(asset.id, asset);
// for(auto& file : folder->files)
// {
// if (file.name == asset.name)
// {
// AssetPath path{ file.path };
// if (SHAssetMetaHandler::GetTypeFromExtension(path.extension().string()) == asset.type)
// {
// file.assetMeta = &assetCollection[asset.id];
// break;
// }
// }
// }
//}
for (auto i {0}; i < folder->files.size(); ++i) for (auto i {0}; i < folder->files.size(); ++i)
{ {

View File

@ -3,7 +3,7 @@
#include "SHVkCommandPool.h" #include "SHVkCommandPool.h"
#include "Graphics/Devices/SHVkLogicalDevice.h" #include "Graphics/Devices/SHVkLogicalDevice.h"
#include "SHVkCommandPool.h" #include "SHVkCommandPool.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
#include "Graphics/Renderpass/SHVkRenderpass.h" #include "Graphics/Renderpass/SHVkRenderpass.h"
#include "Graphics/Framebuffer/SHVkFramebuffer.h" #include "Graphics/Framebuffer/SHVkFramebuffer.h"
#include "Graphics/Pipeline/SHVkPipeline.h" #include "Graphics/Pipeline/SHVkPipeline.h"

View File

@ -3,7 +3,7 @@
#include "Graphics/Devices/SHVkLogicalDevice.h" #include "Graphics/Devices/SHVkLogicalDevice.h"
#include "Graphics/Instance/SHVkInstance.h" #include "Graphics/Instance/SHVkInstance.h"
#include "Resource/SHResourceLibrary.h" #include "Resource/SHResourceLibrary.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
namespace SHADE namespace SHADE
{ {

View File

@ -1,6 +1,6 @@
#include "SHPch.h" #include "SHPch.h"
#include "SHValidationLayersQuery.h" #include "SHValidationLayersQuery.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
namespace SHADE namespace SHADE
{ {

View File

@ -3,8 +3,8 @@
#include "SHVkDebugMessenger.h" #include "SHVkDebugMessenger.h"
#include "SHVulkanDebugUtil.h" #include "SHVulkanDebugUtil.h"
#include "Graphics/Instance/SHVkInstance.h" #include "Graphics/Instance/SHVkInstance.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
//#include "Tools/SHLogger.h" //#include "Tools/Logger/SHLogger.h"
namespace SHADE namespace SHADE
{ {

View File

@ -1,6 +1,6 @@
#include "SHPch.h" #include "SHPch.h"
#include "SHVulkanDebugUtil.h" #include "SHVulkanDebugUtil.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
namespace SHADE namespace SHADE
{ {

View File

@ -38,11 +38,11 @@ namespace SHADE
/// </summary> /// </summary>
std::vector<vk::DescriptorPoolSize> Limits = std::vector<vk::DescriptorPoolSize> Limits =
{ {
{ vk::DescriptorType::eCombinedImageSampler, 100 }, { vk::DescriptorType::eCombinedImageSampler, 1000 },
{ vk::DescriptorType::eUniformBuffer, 100 }, { vk::DescriptorType::eUniformBuffer, 1000 },
{ vk::DescriptorType::eUniformBufferDynamic, 100 }, { vk::DescriptorType::eUniformBufferDynamic, 1000 },
{ vk::DescriptorType::eStorageImage, 100}, { vk::DescriptorType::eStorageImage, 1000 },
{ vk::DescriptorType::eStorageBufferDynamic, 100 } { vk::DescriptorType::eStorageBufferDynamic, 1000 }
}; };
/// <summary> /// <summary>
/// Maximum number of descriptor sets allowed /// Maximum number of descriptor sets allowed

View File

@ -6,7 +6,7 @@
#include "SHVkDescriptorPool.h" #include "SHVkDescriptorPool.h"
#include "Graphics/Devices/SHVkLogicalDevice.h" #include "Graphics/Devices/SHVkLogicalDevice.h"
#include "Graphics/Descriptors/SHVkDescriptorSetLayout.h" #include "Graphics/Descriptors/SHVkDescriptorSetLayout.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
#include "Graphics/Images/SHVkImage.h" #include "Graphics/Images/SHVkImage.h"
#include "Graphics/Images/SHVkImageView.h" #include "Graphics/Images/SHVkImageView.h"
#include "Graphics/Images/SHVkSampler.h" #include "Graphics/Images/SHVkSampler.h"

View File

@ -2,7 +2,7 @@
#include "SHVkLogicalDevice.h" #include "SHVkLogicalDevice.h"
#include "SHVkPhysicalDevice.h" #include "SHVkPhysicalDevice.h"
#include "Graphics/Instance/SHVkInstance.h" #include "Graphics/Instance/SHVkInstance.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
#include "Graphics/Windowing/Surface/SHVkSurface.h" #include "Graphics/Windowing/Surface/SHVkSurface.h"
#include "Graphics/Swapchain/SHVkSwapchain.h" #include "Graphics/Swapchain/SHVkSwapchain.h"
#include "Graphics/Commands/SHVkCommandPool.h" #include "Graphics/Commands/SHVkCommandPool.h"

View File

@ -3,7 +3,7 @@
#include <iostream> #include <iostream>
#include <vector> #include <vector>
#include <set> #include <set>
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
namespace SHADE namespace SHADE
{ {

View File

@ -3,7 +3,7 @@
#include <unordered_map> #include <unordered_map>
#include "SHVkPhysicalDeviceLibrary.h" #include "SHVkPhysicalDeviceLibrary.h"
#include "Graphics/Instance/SHVkInstance.h" #include "Graphics/Instance/SHVkInstance.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
namespace SHADE namespace SHADE
{ {

View File

@ -3,7 +3,7 @@
#include "Graphics/Images/SHVkImageView.h" #include "Graphics/Images/SHVkImageView.h"
#include "Graphics/Images/SHVkImage.h" #include "Graphics/Images/SHVkImage.h"
#include "Graphics/Renderpass/SHVkRenderpass.h" #include "Graphics/Renderpass/SHVkRenderpass.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
#include "Graphics/Devices/SHVkLogicalDevice.h" #include "Graphics/Devices/SHVkLogicalDevice.h"
namespace SHADE namespace SHADE

View File

@ -2,7 +2,7 @@
#include "SHVkImage.h" #include "SHVkImage.h"
#include "Graphics/Devices/SHVkLogicalDevice.h" #include "Graphics/Devices/SHVkLogicalDevice.h"
#include "Graphics/Debugging/SHVulkanDebugUtil.h" #include "Graphics/Debugging/SHVulkanDebugUtil.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
#include "SHVkImageView.h" #include "SHVkImageView.h"
#include "Graphics/Instance/SHVkInstance.h" #include "Graphics/Instance/SHVkInstance.h"
#include "Graphics/Buffers/SHVkBuffer.h" #include "Graphics/Buffers/SHVkBuffer.h"

View File

@ -2,7 +2,7 @@
#include "SHVkImageView.h" #include "SHVkImageView.h"
#include "SHVkImage.h" #include "SHVkImage.h"
#include "Graphics/Devices/SHVkLogicalDevice.h" #include "Graphics/Devices/SHVkLogicalDevice.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
namespace SHADE namespace SHADE
{ {

View File

@ -3,7 +3,7 @@
#include "Graphics/Debugging/SHValidationLayersQuery.h" #include "Graphics/Debugging/SHValidationLayersQuery.h"
#include "Graphics/Debugging/SHVkDebugMessenger.h" #include "Graphics/Debugging/SHVkDebugMessenger.h"
#include "Graphics/Devices/SHVkPhysicalDeviceLibrary.h" #include "Graphics/Devices/SHVkPhysicalDeviceLibrary.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
#include "Graphics/Devices/SHVkPhysicalDeviceLibrary.h" #include "Graphics/Devices/SHVkPhysicalDeviceLibrary.h"
//#include <vulkan/vulkan_win32.h> //#include <vulkan/vulkan_win32.h>

View File

@ -43,6 +43,85 @@ namespace SHADE
setAllDirtyFlags(); setAllDirtyFlags();
} }
SHBatch::SHBatch(SHBatch&& rhs)
: device { rhs.device }
, pipeline { rhs.pipeline }
, referencedMatInstances { std::move(rhs.referencedMatInstances) }
, matBufferDirty { std::move(rhs.matBufferDirty) }
, subBatches { std::move(rhs.subBatches) }
, drawData { std::move(drawData) }
, transformData { std::move(rhs.transformData) }
, instancedIntegerData { std::move(rhs.instancedIntegerData) }
, matPropsData { std::move(rhs.matPropsData) }
, matPropsDataSize { rhs.matPropsDataSize }
, singleMatPropAlignedSize { rhs.singleMatPropAlignedSize }
, singleMatPropSize { rhs.singleMatPropSize }
, isCPUBuffersDirty { rhs.isCPUBuffersDirty }
, drawDataBuffer { rhs.drawDataBuffer }
, transformDataBuffer { rhs.transformDataBuffer }
, instancedIntegerBuffer { rhs.instancedIntegerBuffer }
, matPropsBuffer { rhs.matPropsBuffer }
, matPropsDescSet { rhs.matPropsDescSet }
{
rhs.drawDataBuffer = {};
rhs.transformDataBuffer = {};
rhs.instancedIntegerBuffer = {};
rhs.matPropsBuffer = {};
rhs.matPropsDescSet = {};
}
SHBatch& SHBatch::operator=(SHBatch&& rhs)
{
if (this == &rhs)
return *this;
device = rhs.device ;
pipeline = rhs.pipeline ;
referencedMatInstances = std::move(rhs.referencedMatInstances);
matBufferDirty = std::move(rhs.matBufferDirty) ;
subBatches = std::move(rhs.subBatches) ;
drawData = std::move(drawData) ;
transformData = std::move(rhs.transformData) ;
instancedIntegerData = std::move(rhs.instancedIntegerData) ;
matPropsData = std::move(rhs.matPropsData) ;
matPropsDataSize = rhs.matPropsDataSize ;
singleMatPropAlignedSize = rhs.singleMatPropAlignedSize ;
singleMatPropSize = rhs.singleMatPropSize ;
isCPUBuffersDirty = rhs.isCPUBuffersDirty ;
drawDataBuffer = rhs.drawDataBuffer ;
transformDataBuffer = rhs.transformDataBuffer ;
instancedIntegerBuffer = rhs.instancedIntegerBuffer ;
matPropsBuffer = rhs.matPropsBuffer ;
matPropsDescSet = rhs.matPropsDescSet ;
// Unset values
rhs.drawDataBuffer = {};
rhs.transformDataBuffer = {};
rhs.instancedIntegerBuffer = {};
rhs.matPropsBuffer = {};
rhs.matPropsDescSet = {};
return *this;
}
SHBatch::~SHBatch()
{
// Free GPU buffers
for (int i = 0; i < SHGraphicsConstants::NUM_FRAME_BUFFERS; ++i)
{
if (drawDataBuffer[i])
drawDataBuffer[i].Free();
if (transformDataBuffer[i])
transformDataBuffer[i].Free();
if (instancedIntegerBuffer[i])
instancedIntegerBuffer[i].Free();
if (matPropsBuffer[i])
matPropsBuffer[i].Free();
if (matPropsDescSet[i])
matPropsDescSet[i].Free();
}
}
void SHBatch::Add(const SHRenderable* renderable) void SHBatch::Add(const SHRenderable* renderable)
{ {
// Ignore if null // Ignore if null

View File

@ -71,6 +71,11 @@ namespace SHADE
/* Constructor/Destructors */ /* Constructor/Destructors */
/*-----------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------*/
SHBatch(Handle<SHVkPipeline> pipeline); SHBatch(Handle<SHVkPipeline> pipeline);
SHBatch(const SHBatch&) = delete;
SHBatch(SHBatch&& rhs);
SHBatch& operator=(const SHBatch&) = delete;
SHBatch& operator=(SHBatch&& rhs);
~SHBatch();
/*-----------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------*/
/* Usage Functions */ /* Usage Functions */
@ -117,7 +122,7 @@ namespace SHADE
std::unique_ptr<char> matPropsData; std::unique_ptr<char> matPropsData;
Byte matPropsDataSize = 0; Byte matPropsDataSize = 0;
Byte singleMatPropAlignedSize = 0; Byte singleMatPropAlignedSize = 0;
Byte singleMatPropSize = 0; Byte singleMatPropSize = 0;
bool isCPUBuffersDirty = true; bool isCPUBuffersDirty = true;
// GPU Buffers // GPU Buffers
TripleBuffer drawDataBuffer; TripleBuffer drawDataBuffer;

View File

@ -22,7 +22,7 @@ of DigiPen Institute of Technology is prohibited.
#include "Graphics/MiddleEnd/Interface/SHMaterialInstance.h" #include "Graphics/MiddleEnd/Interface/SHMaterialInstance.h"
#include "Graphics/Pipeline/SHVkPipeline.h" #include "Graphics/Pipeline/SHVkPipeline.h"
#include "ECS_Base/Managers/SHComponentManager.h" #include "ECS_Base/Managers/SHComponentManager.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
namespace SHADE namespace SHADE
{ {

View File

@ -69,9 +69,9 @@ namespace SHADE
batch->Remove(renderable); batch->Remove(renderable);
// If batch is empty, remove batch // TODO: If the pipeline is unloaded, we remove the batch
if (batch->IsEmpty()) /*if (batch->IsEmpty() && !batch->GetPipeline())
batches.erase(batch); batches.erase(batch);*/
} }
void SHSuperBatch::Clear() noexcept void SHSuperBatch::Clear() noexcept

View File

@ -5,7 +5,7 @@
#include "Graphics/Pipeline/SHVkPipelineLayout.h" #include "Graphics/Pipeline/SHVkPipelineLayout.h"
#include "Graphics/Descriptors/SHVkDescriptorSetLayout.h" #include "Graphics/Descriptors/SHVkDescriptorSetLayout.h"
#include "Graphics/MiddleEnd/Lights/SHLightData.h" #include "Graphics/MiddleEnd/Lights/SHLightData.h"
#include "Tools/SHUtilities.h" #include "Tools/Utilities/SHUtilities.h"
namespace SHADE namespace SHADE
{ {

View File

@ -570,13 +570,6 @@ namespace SHADE
return; return;
} }
// Finalise all batches
for (auto vp : viewports)
for (auto renderer : vp->GetRenderers())
{
renderer->GetRenderGraph()->FinaliseBatch(renderContext.GetCurrentFrame(), descPool);
}
// Resize // Resize
auto windowDims = window->GetWindowSize(); auto windowDims = window->GetWindowSize();
if (renderContext.GetResizeAndReset()) if (renderContext.GetResizeAndReset())
@ -591,6 +584,13 @@ namespace SHADE
// #BackEndTest: For for the fence initialized by queue submit // #BackEndTest: For for the fence initialized by queue submit
renderContext.WaitForFence(); renderContext.WaitForFence();
// Finalise all batches
for (auto vp : viewports)
for (auto renderer : vp->GetRenderers())
{
renderer->GetRenderGraph()->FinaliseBatch(renderContext.GetCurrentFrame(), descPool);
}
// #BackEndTest: Acquire the next image in the swapchain available // #BackEndTest: Acquire the next image in the swapchain available
renderContext.AcquireNextIamge(); renderContext.AcquireNextIamge();
const uint32_t CURR_FRAME_IDX_2 = renderContext.GetCurrentFrame(); const uint32_t CURR_FRAME_IDX_2 = renderContext.GetCurrentFrame();
@ -602,8 +602,6 @@ namespace SHADE
if (currFrameData.cmdPoolHdls.empty()) if (currFrameData.cmdPoolHdls.empty())
throw std::runtime_error("No command pools available!"); throw std::runtime_error("No command pools available!");
currFrameData.cmdPoolHdls[0]->Reset(); currFrameData.cmdPoolHdls[0]->Reset();
} }
/***************************************************************************/ /***************************************************************************/
@ -710,6 +708,11 @@ namespace SHADE
return resourceManager.Create<SHMaterialInstance>(materialInst->GetBaseMaterial()); return resourceManager.Create<SHMaterialInstance>(materialInst->GetBaseMaterial());
} }
std::pair<typename SHResourceHub::dense_iterator<SHMaterialInstance>, typename SHResourceHub::dense_iterator<SHMaterialInstance>> SHGraphicsSystem::GetAllMaterialInstances()
{
return resourceManager.GetDenseAccess<SHMaterialInstance>();
}
void SHGraphicsSystem::RemoveMaterialInstance(Handle<SHMaterialInstance> materialInstance) void SHGraphicsSystem::RemoveMaterialInstance(Handle<SHMaterialInstance> materialInstance)
{ {
resourceManager.Free(materialInstance); resourceManager.Free(materialInstance);
@ -807,7 +810,7 @@ namespace SHADE
void SHGraphicsSystem::BeginRoutine::Execute(double) noexcept void SHGraphicsSystem::BeginRoutine::Execute(double) noexcept
{ {
SHResourceManager::FinaliseChanges(); // Begin rendering
reinterpret_cast<SHGraphicsSystem*>(system)->BeginRender(); reinterpret_cast<SHGraphicsSystem*>(system)->BeginRender();
} }
@ -833,8 +836,38 @@ namespace SHADE
void SHGraphicsSystem::EndRoutine::Execute(double) noexcept void SHGraphicsSystem::EndRoutine::Execute(double) noexcept
{ {
reinterpret_cast<SHGraphicsSystem*>(system)->EndRender(); reinterpret_cast<SHGraphicsSystem*>(system)->EndRender();
// Reset all material isDirty
auto gfxSystem = reinterpret_cast<SHGraphicsSystem*>(system);
auto [matBegin, matEnd] = gfxSystem->resourceManager.GetDenseAccess<SHMaterial>();
for (auto iter = matBegin; iter != matEnd; ++iter)
{
iter->ClearChangeFlag();
}
} }
SHGraphicsSystem::PrepareRenderRoutine::PrepareRenderRoutine()
: SHSystemRoutine("Graphics System Pre-Render", true)
{}
void SHGraphicsSystem::PrepareRenderRoutine::Execute(double) noexcept
{
// Finish up, loading, unloading any resources
SHResourceManager::FinaliseChanges();
// Clean up and update all materials
auto gfxSystem = reinterpret_cast<SHGraphicsSystem*>(system);
auto [matInstBegin, matInstEnd] = gfxSystem->resourceManager.GetDenseAccess<SHMaterialInstance>();
for (auto iter = matInstBegin; iter != matInstEnd; ++iter)
{
auto baseMat = iter->GetBaseMaterial();
if (baseMat && baseMat->HasPipelineChanged())
{
iter->ResetProperties();
}
}
}
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
/* System Routine Functions - BatcherDispatcherRoutine */ /* System Routine Functions - BatcherDispatcherRoutine */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
@ -844,11 +877,14 @@ namespace SHADE
void SHGraphicsSystem::BatcherDispatcherRoutine::Execute(double) noexcept void SHGraphicsSystem::BatcherDispatcherRoutine::Execute(double) noexcept
{ {
auto& renderables = SHComponentManager::GetDense<SHRenderable>(); auto& renderables = SHComponentManager::GetDense<SHRenderable>();
for (auto& renderable : renderables) for (auto& renderable : renderables)
{ {
// Check if the material instance is now unused
renderable.CleanUpMaterials();
if (!renderable.HasChanged()) if (!renderable.HasChanged())
continue; continue;
// Remove from the SuperBatch it is previously in (prevMat if mat has changed) // Remove from the SuperBatch it is previously in (prevMat if mat has changed)
Handle<SHMaterialInstance> prevMaterial = renderable.HasMaterialChanged() ? renderable.GetPrevMaterial() : renderable.GetMaterial(); Handle<SHMaterialInstance> prevMaterial = renderable.HasMaterialChanged() ? renderable.GetPrevMaterial() : renderable.GetMaterial();
@ -857,9 +893,8 @@ namespace SHADE
Handle<SHSuperBatch> oldSuperBatch = prevMaterial->GetBaseMaterial()->GetPipeline()->GetPipelineState().GetSubpass()->GetSuperBatch(); Handle<SHSuperBatch> oldSuperBatch = prevMaterial->GetBaseMaterial()->GetPipeline()->GetPipelineState().GetSubpass()->GetSuperBatch();
oldSuperBatch->Remove(&renderable); oldSuperBatch->Remove(&renderable);
} }
// Add to new SuperBatch if there is a material // Add to new SuperBatch if there is a material and a mesh to render
// Add to new SuperBatch if there is a material and a mesh to render
Handle<SHMaterialInstance> newMatInstance = renderable.GetMaterial(); Handle<SHMaterialInstance> newMatInstance = renderable.GetMaterial();
if (newMatInstance && renderable.GetMesh()) if (newMatInstance && renderable.GetMesh())
{ {

View File

@ -95,25 +95,31 @@ namespace SHADE
class SH_API BeginRoutine final : public SHSystemRoutine class SH_API BeginRoutine final : public SHSystemRoutine
{ {
public: public:
BeginRoutine(); BeginRoutine();
virtual void Execute(double dt) noexcept override final; virtual void Execute(double dt) noexcept override final;
}; };
class SH_API RenderRoutine final : public SHSystemRoutine class SH_API RenderRoutine final : public SHSystemRoutine
{ {
public: public:
RenderRoutine(); RenderRoutine();
virtual void Execute(double dt) noexcept override final; virtual void Execute(double dt) noexcept override final;
}; };
class SH_API EndRoutine final : public SHSystemRoutine class SH_API EndRoutine final : public SHSystemRoutine
{ {
public: public:
EndRoutine(); EndRoutine();
virtual void Execute(double dt) noexcept override final;
};
class SH_API PrepareRenderRoutine final : public SHSystemRoutine
{
public:
PrepareRenderRoutine();
virtual void Execute(double dt) noexcept override final; virtual void Execute(double dt) noexcept override final;
}; };
class SH_API BatcherDispatcherRoutine final : public SHSystemRoutine class SH_API BatcherDispatcherRoutine final : public SHSystemRoutine
{ {
public: public:
BatcherDispatcherRoutine(); BatcherDispatcherRoutine();
virtual void Execute(double dt) noexcept override final; virtual void Execute(double dt) noexcept override final;
}; };
@ -156,6 +162,7 @@ namespace SHADE
Handle<SHMaterialInstance> AddOrGetBaseMaterialInstance(); Handle<SHMaterialInstance> AddOrGetBaseMaterialInstance();
Handle<SHMaterialInstance> AddOrGetBaseMaterialInstance(Handle<SHMaterial> material); Handle<SHMaterialInstance> AddOrGetBaseMaterialInstance(Handle<SHMaterial> material);
Handle<SHMaterialInstance> AddMaterialInstanceCopy(Handle<SHMaterialInstance> materialInst); Handle<SHMaterialInstance> AddMaterialInstanceCopy(Handle<SHMaterialInstance> materialInst);
std::pair<typename SHResourceHub::dense_iterator<SHMaterialInstance>, typename SHResourceHub::dense_iterator<SHMaterialInstance>> GetAllMaterialInstances();
void RemoveMaterialInstance(Handle<SHMaterialInstance> materialInstance); void RemoveMaterialInstance(Handle<SHMaterialInstance> materialInstance);
Handle<SHMaterial> GetDefaultMaterial() { return defaultMaterial; } Handle<SHMaterial> GetDefaultMaterial() { return defaultMaterial; }
Handle<SHMaterialInstance> GetDefaultMaterialInstance() { return AddOrGetBaseMaterialInstance(defaultMaterial); } Handle<SHMaterialInstance> GetDefaultMaterialInstance() { return AddOrGetBaseMaterialInstance(defaultMaterial); }
@ -166,10 +173,10 @@ namespace SHADE
/*******************************************************************************/ /*******************************************************************************/
/*! /*!
\brief \brief
Adds a mesh to the Mesh Library. But this does not mean that the meshes have Adds a mesh to the Mesh Library. But this does not mean that the meshes have
been added yet. A call to "BuildBuffers()" is required to transfer all been added yet. A call to "BuildBuffers()" is required to transfer all
meshes into the GPU. meshes into the GPU.
\param vertexCount \param vertexCount
Number of vertices in this Mesh. Number of vertices in this Mesh.

View File

@ -6,91 +6,109 @@
#include "Graphics/Shaders/BlockInterface/SHShaderBlockInterface.h" #include "Graphics/Shaders/BlockInterface/SHShaderBlockInterface.h"
#include "Math/Vector/SHVec3.h" #include "Math/Vector/SHVec3.h"
#include "Math/Vector/SHVec4.h" #include "Math/Vector/SHVec4.h"
#include "ECS_Base/Managers/SHSystemManager.h"
#include "SHGraphicsSystem.h"
#include "SHMaterialInstance.h"
namespace SHADE namespace SHADE
{ {
/*---------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
/* Pipeline Functions */ /* Pipeline Functions */
/*---------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
void SHMaterial::SetPipeline(Handle<SHVkPipeline> _pipeline) void SHMaterial::SetPipeline(Handle<SHVkPipeline> _pipeline)
{ {
pipeline = _pipeline; // Reassignment, we ignore
if (_pipeline == pipeline)
return;
// Set up properties based on the pipeline pipeline = _pipeline;
if (!pipeline)
{
// Clear memory and all that
propMemory.reset();
return;
}
// Allocate memory for properties // Set up properties based on the pipeline
const Handle<SHShaderBlockInterface> SHADER_INFO = GetShaderBlockInterface(); if (pipeline)
propMemorySize = SHADER_INFO ? SHADER_INFO->GetBytesRequired() : 0;
if (propMemorySize <= 0)
{
propMemory.reset();
}
else
{
propMemory.reset(new char[propMemorySize]);
}
ResetProperties();
}
Handle<SHVkPipeline> SHMaterial::GetPipeline() const
{
return pipeline;
}
/*---------------------------------------------------------------------------------*/
/* Property Functions */
/*---------------------------------------------------------------------------------*/
void SHMaterial::ResetProperties()
{ {
// Reset all the properties to default values // Allocate memory for properties
if (propMemory) const Handle<SHShaderBlockInterface> SHADER_INFO = GetShaderBlockInterface();
memset(propMemory.get(), 0, propMemorySize); propMemorySize = SHADER_INFO ? SHADER_INFO->GetBytesRequired() : 0;
if (propMemorySize <= 0)
{
propMemory.reset();
}
else
{
propMemory.reset(new char[propMemorySize]);
}
}
// Reset since pipeline changed
ResetProperties();
// Initialize Vectors to all 1.0 by default // Mark changed so that we know to update dependent material instances
const Handle<SHShaderBlockInterface> SHADER_INFO = GetShaderBlockInterface(); propertiesChanged = true;
for (int i = 0; i < SHADER_INFO->GetVariableCount(); ++i) }
{
const auto& VAR = SHADER_INFO->GetVariable(i); Handle<SHVkPipeline> SHMaterial::GetPipeline() const
switch (VAR->type) {
{ return pipeline;
case SHShaderBlockInterface::Variable::Type::VECTOR3: }
setPropertyUnsafe(VAR->offset, SHVec3::One);
break; /*-----------------------------------------------------------------------------------*/
case SHShaderBlockInterface::Variable::Type::VECTOR4: /* Property Functions */
setPropertyUnsafe(VAR->offset, SHVec4::One); /*-----------------------------------------------------------------------------------*/
break; void SHMaterial::ResetProperties()
} {
} // Reset all the properties to default values
if (propMemory)
memset(propMemory.get(), 0, propMemorySize);
// Initialize Vectors to all 1.0 by default
const Handle<SHShaderBlockInterface> SHADER_INFO = GetShaderBlockInterface();
for (int i = 0; i < SHADER_INFO->GetVariableCount(); ++i)
{
const auto& VAR = SHADER_INFO->GetVariable(i);
switch (VAR->type)
{
case SHShaderBlockInterface::Variable::Type::VECTOR3:
setPropertyUnsafe(VAR->offset, SHVec3::One);
break;
case SHShaderBlockInterface::Variable::Type::VECTOR4:
setPropertyUnsafe(VAR->offset, SHVec4::One);
break;
}
} }
void SHMaterial::ExportProperties(void* dest) const noexcept propertiesChanged = true;
{ }
if (propMemory)
memcpy(dest, propMemory.get(), propMemorySize);
}
size_t SHMaterial::GetPropertiesMemorySize() const noexcept void SHMaterial::ExportProperties(void* dest) const noexcept
{ {
const Handle<SHShaderBlockInterface> SHADER_INFO = GetShaderBlockInterface(); if (propMemory)
return SHADER_INFO ? SHADER_INFO->GetBytesRequired() : 0; memcpy(dest, propMemory.get(), propMemorySize);
} }
/*---------------------------------------------------------------------------------*/ size_t SHMaterial::GetPropertiesMemorySize() const noexcept
/* Helper Functions */ {
/*---------------------------------------------------------------------------------*/ const Handle<SHShaderBlockInterface> SHADER_INFO = GetShaderBlockInterface();
Handle<SHShaderBlockInterface> SHMaterial::GetShaderBlockInterface() const noexcept return SHADER_INFO ? SHADER_INFO->GetBytesRequired() : 0;
{ }
return pipeline->GetPipelineLayout()->GetShaderBlockInterface
( /*-----------------------------------------------------------------------------------*/
SHGraphicsConstants::DescriptorSetIndex::PER_INSTANCE, /* Helper Functions */
SHGraphicsConstants::DescriptorSetBindings::BATCHED_PER_INST_DATA, /*-----------------------------------------------------------------------------------*/
vk::ShaderStageFlagBits::eFragment Handle<SHShaderBlockInterface> SHMaterial::GetShaderBlockInterface() const noexcept
); {
} return pipeline->GetPipelineLayout()->GetShaderBlockInterface
(
SHGraphicsConstants::DescriptorSetIndex::PER_INSTANCE,
SHGraphicsConstants::DescriptorSetBindings::BATCHED_PER_INST_DATA,
vk::ShaderStageFlagBits::eFragment
);
}
/*-----------------------------------------------------------------------------------*/
/* Query Functions */
/*-----------------------------------------------------------------------------------*/
void SHMaterial::ClearChangeFlag() noexcept
{
propertiesChanged = false;
}
} }

View File

@ -17,6 +17,7 @@ of DigiPen Institute of Technology is prohibited.
// Project Includes // Project Includes
#include "Resource/SHHandle.h" #include "Resource/SHHandle.h"
#include "SHCommonTypes.h" #include "SHCommonTypes.h"
#include "SH_API.h"
namespace SHADE namespace SHADE
{ {
@ -35,7 +36,7 @@ namespace SHADE
Describes a Pipeline along with it's associated properties for this instance. Describes a Pipeline along with it's associated properties for this instance.
*/ */
/***********************************************************************************/ /***********************************************************************************/
class SHMaterial class SH_API SHMaterial : public ISelfHandle<SHMaterial>
{ {
public: public:
/*-----------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------*/
@ -67,6 +68,10 @@ namespace SHADE
/* Query Functions */ /* Query Functions */
/*-----------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------*/
Handle<SHShaderBlockInterface> GetShaderBlockInterface() const noexcept; Handle<SHShaderBlockInterface> GetShaderBlockInterface() const noexcept;
bool HasPipelineChanged() const noexcept { return pipelineChanged; }
bool HasPropertiesChanged() const noexcept { return propertiesChanged; }
bool HasChanged() const noexcept { return pipelineChanged || propertiesChanged; }
void ClearChangeFlag() noexcept;
private: private:
/*-----------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------*/
@ -75,6 +80,8 @@ namespace SHADE
Handle<SHVkPipeline> pipeline; Handle<SHVkPipeline> pipeline;
std::unique_ptr<char> propMemory; std::unique_ptr<char> propMemory;
Byte propMemorySize = 0; Byte propMemorySize = 0;
bool propertiesChanged = true;
bool pipelineChanged = true;
/*-----------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------*/
/* Helper Functions */ /* Helper Functions */

View File

@ -33,8 +33,7 @@ namespace SHADE
} }
// Get offset and modify the memory directly // Get offset and modify the memory directly
T* dataPtr = reinterpret_cast<T*>(propMemory.get() + PROP_INFO->offset); setPropertyUnsafe(PROP_INFO->offset, value);
*dataPtr = value;
} }
template<typename T> template<typename T>
@ -85,6 +84,12 @@ namespace SHADE
template<typename T> template<typename T>
void SHMaterial::setPropertyUnsafe(uint32_t memOffset, const T& value) void SHMaterial::setPropertyUnsafe(uint32_t memOffset, const T& value)
{ {
// Size check
if (memOffset + sizeof(T) > propMemorySize)
{
throw std::runtime_error("Attempted to write to out of bounds MaterialInstance properties memory");
}
(*reinterpret_cast<T*>(propMemory.get() + memOffset)) = value; (*reinterpret_cast<T*>(propMemory.get() + memOffset)) = value;
propertiesChanged = true;
} }
} }

View File

@ -15,7 +15,7 @@ of DigiPen Institute of Technology is prohibited.
#include "SHGraphicsConstants.h" #include "SHGraphicsConstants.h"
#include "SHMaterial.h" #include "SHMaterial.h"
#include "Graphics/Pipeline/SHVkPipeline.h" #include "Graphics/Pipeline/SHVkPipeline.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
namespace SHADE namespace SHADE
{ {
@ -31,11 +31,11 @@ namespace SHADE
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
void SHMaterialInstance::ResetProperties() noexcept void SHMaterialInstance::ResetProperties() noexcept
{ {
// Reset all the properties to default values // Reset all the properties to default values
memset(dataStore.get(), 0, dataStoreSize); memset(dataStore.get(), 0, dataStoreSize);
overrideData.clear(); overrideData.clear();
dataStore.reset(); dataStore.reset();
dataWasChanged = true;
} }
void SHMaterialInstance::ExportProperties(void* dest) void SHMaterialInstance::ExportProperties(void* dest)
@ -65,9 +65,17 @@ namespace SHADE
dataWasChanged = false; dataWasChanged = false;
} }
/*---------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
/* Helper Functions */ /* Query Functions */
/*---------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
bool SHMaterialInstance::HasChanged() const noexcept
{
return dataWasChanged || (baseMaterial && baseMaterial->HasChanged());
}
/*-----------------------------------------------------------------------------------*/
/* Helper Functions */
/*-----------------------------------------------------------------------------------*/
Handle<SHShaderBlockInterface> SHMaterialInstance::getShaderBlockInterface() const noexcept Handle<SHShaderBlockInterface> SHMaterialInstance::getShaderBlockInterface() const noexcept
{ {
return baseMaterial->GetPipeline()->GetPipelineLayout()->GetShaderBlockInterface return baseMaterial->GetPipeline()->GetPipelineLayout()->GetShaderBlockInterface

View File

@ -43,9 +43,9 @@ namespace SHADE
/*-----------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------*/
struct OverrideData struct OverrideData
{ {
size_t Index; uint32_t Index;
size_t DataSize; uint32_t DataSize;
size_t StoredDataOffset; uint32_t StoredDataOffset;
}; };
/*-----------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------*/
@ -69,7 +69,8 @@ namespace SHADE
/* Getter Functions */ /* Getter Functions */
/*-----------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------*/
Handle<SHMaterial> GetBaseMaterial() const noexcept { return baseMaterial; } Handle<SHMaterial> GetBaseMaterial() const noexcept { return baseMaterial; }
bool HasChanged() const noexcept { return dataWasChanged; } bool HasChanged() const noexcept;
bool IsBlank() const noexcept { return overrideData.empty(); } // No overrides
private: private:
/*-----------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------*/

View File

@ -11,6 +11,7 @@ of DigiPen Institute of Technology is prohibited.
*//*************************************************************************************/ *//*************************************************************************************/
#pragma once #pragma once
#include "SHMaterialInstance.h" #include "SHMaterialInstance.h"
#include "SHMaterial.h"
namespace SHADE namespace SHADE
{ {
@ -34,26 +35,45 @@ namespace SHADE
dataStore.reset(new char[dataStoreSize]); dataStore.reset(new char[dataStoreSize]);
} }
OverrideData od; // Check if this was stored before
od.Index = SHADER_INFO->GetVariableIndex(key); const uint32_t VAR_IDX = SHADER_INFO->GetVariableIndex(key);
od.DataSize = sizeof(T); auto existingOverride = std::find_if(overrideData.begin(), overrideData.end(), [&](const OverrideData& od)
if (overrideData.empty())
{ {
od.StoredDataOffset = 0; return od.Index == VAR_IDX;
} });
else
// Otherwise, create it
if (existingOverride == overrideData.end())
{ {
const OverrideData& lastInsertedData = overrideData.back(); OverrideData od;
od.StoredDataOffset = lastInsertedData.StoredDataOffset + lastInsertedData.DataSize; od.Index = VAR_IDX;
od.DataSize = sizeof(T);
if (overrideData.empty())
{
od.StoredDataOffset = 0;
}
else
{
const OverrideData& lastInsertedData = overrideData.back();
od.StoredDataOffset = lastInsertedData.StoredDataOffset + lastInsertedData.DataSize;
}
// Size check
if (od.StoredDataOffset + sizeof(T) > dataStoreSize)
{
throw std::runtime_error("Attempted to write to out of bounds MaterialInstance properties memory");
}
// Save the override data information
overrideData.emplace_back(std::move(od));
existingOverride = overrideData.end() - 1;
} }
// Get offset and modify the memory directly // Get offset and modify the memory directly
T* dataPtr = reinterpret_cast<T*>(dataStore.get() + od.StoredDataOffset); T* dataPtr = reinterpret_cast<T*>(dataStore.get() + existingOverride->StoredDataOffset);
*dataPtr = value; *dataPtr = value;
// Save the override data information
overrideData.emplace_back(std::move(od));
// Flag // Flag
dataWasChanged = true; dataWasChanged = true;
} }
@ -70,11 +90,22 @@ namespace SHADE
// Search Override Data for the property // Search Override Data for the property
uint32_t PROP_IDX = SHADER_INFO->GetVariableIndex(key); uint32_t PROP_IDX = SHADER_INFO->GetVariableIndex(key);
auto prop = std::find_if(overrideData.begin(), overrideData.end(), [&](const OverrideData& data) auto prop = std::find_if(overrideData.begin(), overrideData.end(), [&](const OverrideData& data)
{ {
return PROP_IDX == data.Index; return PROP_IDX == data.Index;
}); });
// No overrides, we get from the base material instead
if (prop == overrideData.end()) if (prop == overrideData.end())
throw std::invalid_argument("Attempted to get an property that was not set previously!"); {
if (baseMaterial)
{
return baseMaterial->GetProperty<T>(key);
}
else
{
throw std::invalid_argument("Attempted to get an property that was not set previously!");
}
}
// Get offset and return the memory directly // Get offset and return the memory directly
T* dataPtr = reinterpret_cast<T*>(dataStore.get() + prop->StoredDataOffset); T* dataPtr = reinterpret_cast<T*>(dataStore.get() + prop->StoredDataOffset);

View File

@ -34,8 +34,11 @@ namespace SHADE
void SHRenderable::OnDestroy() void SHRenderable::OnDestroy()
{ {
// Remove from SuperBatch // Remove from SuperBatch
Handle<SHSuperBatch> superBatch = sharedMaterial->GetBaseMaterial()->GetPipeline()->GetPipelineState().GetSubpass()->GetSuperBatch(); if (sharedMaterial)
superBatch->Remove(this); {
Handle<SHSuperBatch> superBatch = sharedMaterial->GetBaseMaterial()->GetPipeline()->GetPipelineState().GetSubpass()->GetSuperBatch();
superBatch->Remove(this);
}
// Free resources // Free resources
if (material) if (material)
@ -88,11 +91,20 @@ namespace SHADE
{ {
SHGraphicsSystem* gfxSystem = SHSystemManager::GetSystem<SHGraphicsSystem>(); SHGraphicsSystem* gfxSystem = SHSystemManager::GetSystem<SHGraphicsSystem>();
material = gfxSystem->AddMaterialInstanceCopy(sharedMaterial); material = gfxSystem->AddMaterialInstanceCopy(sharedMaterial);
matChanged = true;
} }
return material; return material;
} }
void SHRenderable::CleanUpMaterials() noexcept
{
if (material && material->IsBlank())
{
SetMaterial(sharedMaterial);
}
}
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
/* Mesh Functions */ /* Mesh Functions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
@ -111,6 +123,20 @@ namespace SHADE
return lightLayer; return lightLayer;
} }
bool SHRenderable::HasChanged() const noexcept
{
if (matChanged || meshChanged)
return true;
// If the underlying material has changed
auto mat = GetMaterial();
if (mat)
{
return mat->HasChanged();
}
return false;
}
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
/* Batcher Dispatcher Functions */ /* Batcher Dispatcher Functions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/

View File

@ -53,6 +53,10 @@ namespace SHADE
Handle<SHMaterialInstance> GetModifiableMaterial(); Handle<SHMaterialInstance> GetModifiableMaterial();
Handle<SHMaterialInstance> GetPrevMaterial() const noexcept { return oldMaterial; } Handle<SHMaterialInstance> GetPrevMaterial() const noexcept { return oldMaterial; }
bool HasMaterialChanged() const noexcept { return matChanged; } bool HasMaterialChanged() const noexcept { return matChanged; }
/// <summary>
/// Clears the modifiable material if it is unused.
/// </summary>
void CleanUpMaterials() noexcept;
/*-------------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------------*/
/* Mesh Functions */ /* Mesh Functions */
@ -70,7 +74,7 @@ namespace SHADE
/*-------------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------------*/
/* Batcher Dispatcher Functions */ /* Batcher Dispatcher Functions */
/*-------------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------------*/
bool HasChanged() const noexcept { return matChanged || meshChanged; } // Whether or not the mesh or material has changed bool HasChanged() const noexcept; // Whether or not the mesh or material has changed
void ResetChangedFlag(); // TODO: Lock it so that only SHBatcherDispatcher can access this void ResetChangedFlag(); // TODO: Lock it so that only SHBatcherDispatcher can access this
private: private:

View File

@ -15,7 +15,7 @@ of DigiPen Institute of Technology is prohibited.
#include "Graphics/Commands/SHVkCommandBuffer.h" #include "Graphics/Commands/SHVkCommandBuffer.h"
#include "Graphics/Instance/SHVkInstance.h" #include "Graphics/Instance/SHVkInstance.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
#include "SHRenderer.h" #include "SHRenderer.h"
#include "Resource/SHResourceLibrary.h" #include "Resource/SHResourceLibrary.h"
#include "Graphics/RenderGraph/SHRenderGraph.h" #include "Graphics/RenderGraph/SHRenderGraph.h"

View File

@ -1,7 +1,7 @@
#include "SHpch.h" #include "SHpch.h"
#include "SHLightingSubSystem.h" #include "SHLightingSubSystem.h"
#include "Graphics/MiddleEnd/GlobalData/SHGraphicsGlobalData.h" #include "Graphics/MiddleEnd/GlobalData/SHGraphicsGlobalData.h"
#include "Tools/SHUtilities.h" #include "Tools/Utilities/SHUtilities.h"
#include "Graphics/Devices/SHVkLogicalDevice.h" #include "Graphics/Devices/SHVkLogicalDevice.h"
#include "Graphics/Buffers/SHVkBuffer.h" #include "Graphics/Buffers/SHVkBuffer.h"
#include "Graphics/Descriptors/SHVkDescriptorSetGroup.h" #include "Graphics/Descriptors/SHVkDescriptorSetGroup.h"

View File

@ -1,6 +1,6 @@
#include "SHPch.h" #include "SHPch.h"
#include "SHRenderContext.h" #include "SHRenderContext.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
#include "Graphics/Devices/SHVkLogicalDevice.h" #include "Graphics/Devices/SHVkLogicalDevice.h"
#include "Graphics/Swapchain/SHVkSwapchain.h" #include "Graphics/Swapchain/SHVkSwapchain.h"

View File

@ -34,7 +34,7 @@ namespace SHADE
{ {
colorBlendState.attachments.push_back(vk::PipelineColorBlendAttachmentState colorBlendState.attachments.push_back(vk::PipelineColorBlendAttachmentState
{ {
.blendEnable = SHVkUtil::IsBlendCompatible (subpass->GetFormatFromAttachmentReference(att.attachment)) ? true : false, .blendEnable = SHVkUtil::IsBlendCompatible(subpass->GetFormatFromAttachmentReference(att.attachment)),
.srcColorBlendFactor = vk::BlendFactor::eSrcAlpha, .srcColorBlendFactor = vk::BlendFactor::eSrcAlpha,
.dstColorBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha, .dstColorBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha,
.colorBlendOp = vk::BlendOp::eAdd, .colorBlendOp = vk::BlendOp::eAdd,

View File

@ -19,7 +19,7 @@ of DigiPen Institute of Technology is prohibited.
#include "Graphics/Buffers/SHVkBuffer.h" #include "Graphics/Buffers/SHVkBuffer.h"
#include "Graphics/Commands/SHVkCommandBuffer.h" #include "Graphics/Commands/SHVkCommandBuffer.h"
#include "Graphics/SHVkUtil.h" #include "Graphics/SHVkUtil.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
#include "Graphics/MiddleEnd/Interface/SHGraphicsConstants.h" #include "Graphics/MiddleEnd/Interface/SHGraphicsConstants.h"
#include "Graphics/Descriptors/SHVkDescriptorSetGroup.h" #include "Graphics/Descriptors/SHVkDescriptorSetGroup.h"
#include "Graphics/Images/SHVkImage.h" #include "Graphics/Images/SHVkImage.h"

View File

@ -2,7 +2,7 @@
#include "SHVkPipelineLayout.h" #include "SHVkPipelineLayout.h"
#include "Graphics/Devices/SHVkLogicalDevice.h" #include "Graphics/Devices/SHVkLogicalDevice.h"
#include "Graphics/Shaders/SHVkShaderModule.h" #include "Graphics/Shaders/SHVkShaderModule.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
#include "Graphics/Instance/SHVkInstance.h" #include "Graphics/Instance/SHVkInstance.h"
namespace SHADE namespace SHADE

View File

@ -1,6 +1,6 @@
#include "SHPch.h" #include "SHPch.h"
#include "SHVkQueue.h" #include "SHVkQueue.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
#include "Graphics/Devices/SHVkLogicalDevice.h" #include "Graphics/Devices/SHVkLogicalDevice.h"
#include "Graphics/Synchronization/SHVkSemaphore.h" #include "Graphics/Synchronization/SHVkSemaphore.h"
#include "Graphics/Synchronization/SHVkFence.h" #include "Graphics/Synchronization/SHVkFence.h"

View File

@ -7,7 +7,7 @@
#include "Graphics/Images/SHVkImageView.h" #include "Graphics/Images/SHVkImageView.h"
#include "Graphics/Framebuffer/SHVkFramebuffer.h" #include "Graphics/Framebuffer/SHVkFramebuffer.h"
#include "Graphics/Buffers/SHVkBuffer.h" #include "Graphics/Buffers/SHVkBuffer.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
#include "SHAttachmentDescInitParams.h" #include "SHAttachmentDescInitParams.h"
#include "SHRenderGraphStorage.h" #include "SHRenderGraphStorage.h"
#include "Graphics/RenderGraph/SHRenderGraphNodeCompute.h" #include "Graphics/RenderGraph/SHRenderGraphNodeCompute.h"
@ -129,11 +129,11 @@ namespace SHADE
for (auto& predResource : prereq->attResources) for (auto& predResource : prereq->attResources)
{ {
// if a predecessor's resource is used by this node, we want to copy the final layout from the pred to the initial of this node // if a predecessor's resource is used by this node, we want to copy the final layout from the pred to the initial of this node
if (uint64_t resourceID = predResource.GetId().Raw; node->resourceAttachmentMapping.contains(resourceID)) if (uint64_t resourceID = predResource.GetId().Raw; node->resourceAttachmentMapping->contains(resourceID))
{ {
// Get the resource's attachment index in BOTH the predecessor and the current node // Get the resource's attachment index in BOTH the predecessor and the current node
uint32_t prereqResourceAttIndex = prereq->resourceAttachmentMapping[resourceID]; uint32_t prereqResourceAttIndex = prereq->resourceAttachmentMapping->at(resourceID);
uint32_t resourceAttIndex = node->resourceAttachmentMapping[resourceID]; uint32_t resourceAttIndex = node->resourceAttachmentMapping->at(resourceID);
// Use the resource attachment index to get the attachment description in the renderpass // Use the resource attachment index to get the attachment description in the renderpass
auto& attDesc = node->attachmentDescriptions[resourceAttIndex]; auto& attDesc = node->attachmentDescriptions[resourceAttIndex];

View File

@ -124,7 +124,7 @@ namespace SHADE
, framebuffers{} , framebuffers{}
, prereqNodes{ std::move(predecessors) } , prereqNodes{ std::move(predecessors) }
, attachmentDescriptions{} , attachmentDescriptions{}
, resourceAttachmentMapping{} , resourceAttachmentMapping { new std::unordered_map<uint64_t, uint32_t> }
, attResources{ } , attResources{ }
, subpasses{} , subpasses{}
, executed{ false } , executed{ false }
@ -163,7 +163,7 @@ namespace SHADE
if (attResources[i]->resourceTypeFlags & static_cast<uint32_t>(SH_ATT_DESC_TYPE_FLAGS::COLOR_PRESENT)) if (attResources[i]->resourceTypeFlags & static_cast<uint32_t>(SH_ATT_DESC_TYPE_FLAGS::COLOR_PRESENT))
containsSwapchainImage = true; containsSwapchainImage = true;
resourceAttachmentMapping.try_emplace(attResources[i].GetId().Raw, i); resourceAttachmentMapping->try_emplace(attResources[i].GetId().Raw, i);
} }
if (!containsSwapchainImage) if (!containsSwapchainImage)
@ -254,7 +254,7 @@ namespace SHADE
( (
subpassName, subpassName,
graphStorage, GetHandle(), static_cast<uint32_t>(subpasses.size()), graphStorage, GetHandle(), static_cast<uint32_t>(subpasses.size()),
&resourceAttachmentMapping resourceAttachmentMapping.get()
) )
); );
subpassIndexing.try_emplace(subpassName, static_cast<uint32_t>(subpasses.size()) - 1u); subpassIndexing.try_emplace(subpassName, static_cast<uint32_t>(subpasses.size()) - 1u);

View File

@ -60,7 +60,7 @@ namespace SHADE
std::vector<vk::SubpassDependency> spDeps; std::vector<vk::SubpassDependency> spDeps;
//! For indexing resources fast //! For indexing resources fast
std::unordered_map<uint64_t, uint32_t> resourceAttachmentMapping; std::unique_ptr<std::unordered_map<uint64_t, uint32_t>> resourceAttachmentMapping;
//! For indexing subpasses //! For indexing subpasses
std::map<std::string, uint32_t> subpassIndexing; std::map<std::string, uint32_t> subpassIndexing;

View File

@ -97,7 +97,7 @@ namespace SHADE
colorReferences = std::move(rhs.colorReferences); colorReferences = std::move(rhs.colorReferences);
depthReferences = std::move(rhs.depthReferences); depthReferences = std::move(rhs.depthReferences);
inputReferences = std::move(rhs.inputReferences); inputReferences = std::move(rhs.inputReferences);
resourceAttachmentMapping = rhs.resourceAttachmentMapping; resourceAttachmentMapping = std::move(rhs.resourceAttachmentMapping);
descriptorSetLayout = rhs.descriptorSetLayout; descriptorSetLayout = rhs.descriptorSetLayout;
exteriorDrawCalls = std::move(rhs.exteriorDrawCalls); exteriorDrawCalls = std::move(rhs.exteriorDrawCalls);
graphStorage = rhs.graphStorage; graphStorage = rhs.graphStorage;

View File

@ -86,8 +86,16 @@ namespace SHADE
{ {
if (bufferHandle) if (bufferHandle)
{ {
// Resize // Resize if we need to resize
bufferHandle->ResizeReplace(size, src, size); if (bufferHandle->GetSizeStored() < size)
{
bufferHandle->ResizeReplace(size, src, size);
}
// Otherwise just copy the data over
else
{
bufferHandle->MapWriteUnmap(src, size, 0, 0);
}
} }
else else
{ {
@ -113,8 +121,16 @@ namespace SHADE
{ {
if (bufferHandle) if (bufferHandle)
{ {
// Resize // Resize if we need to resize
bufferHandle->ResizeReplace(size, src, size); // TODO: Set to host visible method? if (bufferHandle->GetSizeStored() < size)
{
bufferHandle->ResizeReplace(size, src, size);
}
// Otherwise just copy the data over
else
{
bufferHandle->MapWriteUnmap(src, size, 0, 0);
}
} }
else else
{ {

View File

@ -1,6 +1,6 @@
#include "SHPch.h" #include "SHPch.h"
#include "SHShaderBlockInterface.h" #include "SHShaderBlockInterface.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
namespace SHADE namespace SHADE
{ {

View File

@ -1,6 +1,6 @@
#include "SHPch.h" #include "SHPch.h"
#include "SHShaderReflected.h" #include "SHShaderReflected.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
#include "Graphics/Instance/SHVkInstance.h" #include "Graphics/Instance/SHVkInstance.h"

View File

@ -2,7 +2,7 @@
#include "SHVkShaderModule.h" #include "SHVkShaderModule.h"
#include "Graphics/Devices/SHVkLogicalDevice.h" #include "Graphics/Devices/SHVkLogicalDevice.h"
#include "Graphics/Debugging/SHVulkanDebugUtil.h" #include "Graphics/Debugging/SHVulkanDebugUtil.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
namespace SHADE namespace SHADE
{ {

View File

@ -3,7 +3,7 @@
#include "Graphics/Devices/SHVkPhysicalDevice.h" #include "Graphics/Devices/SHVkPhysicalDevice.h"
#include "Graphics/Devices/SHVkLogicalDevice.h" #include "Graphics/Devices/SHVkLogicalDevice.h"
#include "Graphics/Windowing/Surface/SHVkSurface.h" #include "Graphics/Windowing/Surface/SHVkSurface.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
#include "Graphics/Images/SHVkImage.h" #include "Graphics/Images/SHVkImage.h"
#include "Graphics/Instance/SHVkInstance.h" #include "Graphics/Instance/SHVkInstance.h"

View File

@ -4,7 +4,7 @@
#include "Graphics/Devices/SHVkLogicalDevice.h" #include "Graphics/Devices/SHVkLogicalDevice.h"
#include "Graphics/Instance/SHVkInstance.h" #include "Graphics/Instance/SHVkInstance.h"
#include "Graphics/Debugging/SHVulkanDebugUtil.h" #include "Graphics/Debugging/SHVulkanDebugUtil.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
namespace SHADE namespace SHADE
{ {

View File

@ -1,5 +1,5 @@
/**************************************************************************************** /****************************************************************************************
* \file SHBoundingBox.cpp * \file SHBox.cpp
* \author Diren D Bharwani, diren.dbharwani, 390002520 * \author Diren D Bharwani, diren.dbharwani, 390002520
* \brief Implementation for a 3-Dimensional Axis Aligned Bounding Box * \brief Implementation for a 3-Dimensional Axis Aligned Bounding Box
* *
@ -11,7 +11,7 @@
#include <SHpch.h> #include <SHpch.h>
// Primary Header // Primary Header
#include "SHBoundingBox.h" #include "SHBox.h"
// Project Headers // Project Headers
#include "Math/SHMathHelpers.h" #include "Math/SHMathHelpers.h"
#include "Math/SHRay.h" #include "Math/SHRay.h"
@ -24,13 +24,13 @@ namespace SHADE
/* Constructors & Destructor Definitions */ /* Constructors & Destructor Definitions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
SHBoundingBox::SHBoundingBox() noexcept SHBox::SHBox() noexcept
: RelativeExtents { SHVec3::One } : RelativeExtents { SHVec3::One }
{ {
type = Type::BOX; type = Type::BOX;
} }
SHBoundingBox::SHBoundingBox(const SHVec3& c, const SHVec3& hE) noexcept SHBox::SHBox(const SHVec3& c, const SHVec3& hE) noexcept
: RelativeExtents { SHVec3::One } : RelativeExtents { SHVec3::One }
{ {
type = Type::BOX; type = Type::BOX;
@ -40,7 +40,7 @@ namespace SHADE
} }
SHBoundingBox::SHBoundingBox(const SHBoundingBox& rhs) noexcept SHBox::SHBox(const SHBox& rhs) noexcept
{ {
if (this == &rhs) if (this == &rhs)
return; return;
@ -52,7 +52,7 @@ namespace SHADE
RelativeExtents = rhs.RelativeExtents; RelativeExtents = rhs.RelativeExtents;
} }
SHBoundingBox::SHBoundingBox(SHBoundingBox&& rhs) noexcept SHBox::SHBox(SHBox&& rhs) noexcept
{ {
type = Type::BOX; type = Type::BOX;
@ -65,7 +65,7 @@ namespace SHADE
/* Operator Overload Definitions */ /* Operator Overload Definitions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
SHBoundingBox& SHBoundingBox::operator=(const SHBoundingBox& rhs) noexcept SHBox& SHBox::operator=(const SHBox& rhs) noexcept
{ {
if (rhs.type != Type::BOX) if (rhs.type != Type::BOX)
{ {
@ -81,7 +81,7 @@ namespace SHADE
return *this; return *this;
} }
SHBoundingBox& SHBoundingBox::operator=(SHBoundingBox&& rhs) noexcept SHBox& SHBox::operator=(SHBox&& rhs) noexcept
{ {
if (rhs.type != Type::BOX) if (rhs.type != Type::BOX)
{ {
@ -101,27 +101,27 @@ namespace SHADE
/* Getter Function Definitions */ /* Getter Function Definitions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
SHVec3 SHBoundingBox::GetCenter() const noexcept SHVec3 SHBox::GetCenter() const noexcept
{ {
return Center; return Center;
} }
SHVec3 SHBoundingBox::GetWorldExtents() const noexcept SHVec3 SHBox::GetWorldExtents() const noexcept
{ {
return Extents; return Extents;
} }
const SHVec3& SHBoundingBox::GetRelativeExtents() const noexcept const SHVec3& SHBox::GetRelativeExtents() const noexcept
{ {
return RelativeExtents; return RelativeExtents;
} }
SHVec3 SHBoundingBox::GetMin() const noexcept SHVec3 SHBox::GetMin() const noexcept
{ {
return SHVec3{ Center.x - Extents.x, Center.y - Extents.y, Center.z - Extents.z }; return SHVec3{ Center.x - Extents.x, Center.y - Extents.y, Center.z - Extents.z };
} }
SHVec3 SHBoundingBox::GetMax() const noexcept SHVec3 SHBox::GetMax() const noexcept
{ {
return SHVec3{ Center.x + Extents.x, Center.y + Extents.y, Center.z + Extents.z }; return SHVec3{ Center.x + Extents.x, Center.y + Extents.y, Center.z + Extents.z };
} }
@ -130,22 +130,22 @@ namespace SHADE
/* Setter Function Definitions */ /* Setter Function Definitions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
void SHBoundingBox::SetCenter(const SHVec3& newCenter) noexcept void SHBox::SetCenter(const SHVec3& newCenter) noexcept
{ {
Center = newCenter; Center = newCenter;
} }
void SHBoundingBox::SetWorldExtents(const SHVec3& newWorldExtents) noexcept void SHBox::SetWorldExtents(const SHVec3& newWorldExtents) noexcept
{ {
Extents = newWorldExtents; Extents = newWorldExtents;
} }
void SHBoundingBox::SetRelativeExtents(const SHVec3& newRelativeExtents) noexcept void SHBox::SetRelativeExtents(const SHVec3& newRelativeExtents) noexcept
{ {
RelativeExtents = newRelativeExtents; RelativeExtents = newRelativeExtents;
} }
void SHBoundingBox::SetMin(const SHVec3& min) noexcept void SHBox::SetMin(const SHVec3& min) noexcept
{ {
const SHVec3 MAX = GetMax(); const SHVec3 MAX = GetMax();
@ -153,7 +153,7 @@ namespace SHADE
Extents = SHVec3::Abs((MAX - min) * 0.5f); Extents = SHVec3::Abs((MAX - min) * 0.5f);
} }
void SHBoundingBox::SetMax(const SHVec3& max) noexcept void SHBox::SetMax(const SHVec3& max) noexcept
{ {
const SHVec3 MIN = GetMin(); const SHVec3 MIN = GetMin();
@ -161,13 +161,13 @@ namespace SHADE
Extents = SHVec3::Abs((max - MIN) * 0.5f); Extents = SHVec3::Abs((max - MIN) * 0.5f);
} }
void SHBoundingBox::SetMinMax(const SHVec3& min, const SHVec3& max) noexcept void SHBox::SetMinMax(const SHVec3& min, const SHVec3& max) noexcept
{ {
Center = SHVec3::Lerp(min, max, 0.5f); Center = SHVec3::Lerp(min, max, 0.5f);
Extents = SHVec3::Abs((max - min) * 0.5f); Extents = SHVec3::Abs((max - min) * 0.5f);
} }
std::vector<SHVec3> SHBoundingBox::GetVertices() const noexcept std::vector<SHVec3> SHBox::GetVertices() const noexcept
{ {
std::vector<SHVec3> vertices{ 8 }; std::vector<SHVec3> vertices{ 8 };
GetCorners(vertices.data()); GetCorners(vertices.data());
@ -178,27 +178,27 @@ namespace SHADE
/* Public Function Member Definitions */ /* Public Function Member Definitions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
bool SHBoundingBox::TestPoint(const SHVec3& point) noexcept bool SHBox::TestPoint(const SHVec3& point) noexcept
{ {
return BoundingBox::Contains(point); return BoundingBox::Contains(point);
} }
bool SHBoundingBox::Raycast(const SHRay& ray, float& distance) noexcept bool SHBox::Raycast(const SHRay& ray, float& distance) noexcept
{ {
return BoundingBox::Intersects(ray.position, ray.direction, distance); return BoundingBox::Intersects(ray.position, ray.direction, distance);
} }
bool SHBoundingBox::Contains(const SHBoundingBox& rhs) const noexcept bool SHBox::Contains(const SHBox& rhs) const noexcept
{ {
return BoundingBox::Contains(rhs); return BoundingBox::Contains(rhs);
} }
float SHBoundingBox::Volume() const noexcept float SHBox::Volume() const noexcept
{ {
return 8.0f * (Extents.x * Extents.y * Extents.z); return 8.0f * (Extents.x * Extents.y * Extents.z);
} }
float SHBoundingBox::SurfaceArea() const noexcept float SHBox::SurfaceArea() const noexcept
{ {
return 8.0f * ((Extents.x * Extents.y) return 8.0f * ((Extents.x * Extents.y)
+ (Extents.x * Extents.z) + (Extents.x * Extents.z)
@ -209,21 +209,21 @@ namespace SHADE
/* Static Function Member Definitions */ /* Static Function Member Definitions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
SHBoundingBox SHBoundingBox::Combine(const SHBoundingBox& lhs, const SHBoundingBox& rhs) noexcept SHBox SHBox::Combine(const SHBox& lhs, const SHBox& rhs) noexcept
{ {
SHBoundingBox result; SHBox result;
CreateMerged(result, lhs, rhs); CreateMerged(result, lhs, rhs);
return result; return result;
} }
bool SHBoundingBox::Intersect(const SHBoundingBox& lhs, const SHBoundingBox& rhs) noexcept bool SHBox::Intersect(const SHBox& lhs, const SHBox& rhs) noexcept
{ {
return lhs.Intersects(rhs); return lhs.Intersects(rhs);
} }
SHBoundingBox SHBoundingBox::BuildFromBoxes(const SHBoundingBox* boxes, size_t numBoxes) noexcept SHBox SHBox::BuildFromBoxes(const SHBox* boxes, size_t numBoxes) noexcept
{ {
SHBoundingBox result; SHBox result;
for (size_t i = 1; i < numBoxes; ++i) for (size_t i = 1; i < numBoxes; ++i)
CreateMerged(result, boxes[i - 1], boxes[i]); CreateMerged(result, boxes[i - 1], boxes[i]);
@ -231,9 +231,9 @@ namespace SHADE
return result; return result;
} }
SHBoundingBox SHBoundingBox::BuildFromVertices(const SHVec3* vertices, size_t numVertices, size_t stride) noexcept SHBox SHBox::BuildFromVertices(const SHVec3* vertices, size_t numVertices, size_t stride) noexcept
{ {
SHBoundingBox result; SHBox result;
CreateFromPoints(result, numVertices, vertices, stride); CreateFromPoints(result, numVertices, vertices, stride);
return result; return result;
} }

View File

@ -1,5 +1,5 @@
/**************************************************************************************** /****************************************************************************************
* \file SHBoundingBox.h * \file SHBox.h
* \author Diren D Bharwani, diren.dbharwani, 390002520 * \author Diren D Bharwani, diren.dbharwani, 390002520
* \brief Interface for a 3-Dimensional Axis Aligned Bounding Box * \brief Interface for a 3-Dimensional Axis Aligned Bounding Box
* *
@ -22,8 +22,8 @@ namespace SHADE
/* Type Definitions */ /* Type Definitions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
class SH_API SHBoundingBox : public SHShape, class SH_API SHBox : public SHShape,
private DirectX::BoundingBox private DirectX::BoundingBox
{ {
public: public:
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
@ -36,19 +36,19 @@ namespace SHADE
/* Constructors & Destructor */ /* Constructors & Destructor */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
~SHBoundingBox () override = default; ~SHBox () override = default;
SHBoundingBox () noexcept; SHBox () noexcept;
SHBoundingBox (const SHVec3& center, const SHVec3& halfExtents) noexcept; SHBox (const SHVec3& center, const SHVec3& halfExtents) noexcept;
SHBoundingBox (const SHBoundingBox& rhs) noexcept; SHBox (const SHBox& rhs) noexcept;
SHBoundingBox (SHBoundingBox&& rhs) noexcept; SHBox (SHBox&& rhs) noexcept;
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Operator Overloads */ /* Operator Overloads */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
SHBoundingBox& operator= (const SHBoundingBox& rhs) noexcept; SHBox& operator= (const SHBox& rhs) noexcept;
SHBoundingBox& operator= (SHBoundingBox&& rhs) noexcept; SHBox& operator= (SHBox&& rhs) noexcept;
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Getter Functions */ /* Getter Functions */
@ -79,18 +79,18 @@ namespace SHADE
[[nodiscard]] bool TestPoint (const SHVec3& point) noexcept override; [[nodiscard]] bool TestPoint (const SHVec3& point) noexcept override;
[[nodiscard]] bool Raycast (const SHRay& ray, float& distance) noexcept override; [[nodiscard]] bool Raycast (const SHRay& ray, float& distance) noexcept override;
[[nodiscard]] bool Contains (const SHBoundingBox& rhs) const noexcept; [[nodiscard]] bool Contains (const SHBox& rhs) const noexcept;
[[nodiscard]] float Volume () const noexcept; [[nodiscard]] float Volume () const noexcept;
[[nodiscard]] float SurfaceArea () const noexcept; [[nodiscard]] float SurfaceArea () const noexcept;
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Static Function Members */ /* Static Function Members */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
[[nodiscard]] static SHBoundingBox Combine (const SHBoundingBox& lhs, const SHBoundingBox& rhs) noexcept; [[nodiscard]] static SHBox Combine (const SHBox& lhs, const SHBox& rhs) noexcept;
[[nodiscard]] static bool Intersect (const SHBoundingBox& lhs, const SHBoundingBox& rhs) noexcept; [[nodiscard]] static bool Intersect (const SHBox& lhs, const SHBox& rhs) noexcept;
[[nodiscard]] static SHBoundingBox BuildFromBoxes (const SHBoundingBox* boxes, size_t numBoxes) noexcept; [[nodiscard]] static SHBox BuildFromBoxes (const SHBox* boxes, size_t numBoxes) noexcept;
[[nodiscard]] static SHBoundingBox BuildFromVertices (const SHVec3* vertices, size_t numVertices, size_t stride = 0) noexcept; [[nodiscard]] static SHBox BuildFromVertices (const SHVec3* vertices, size_t numVertices, size_t stride = 0) noexcept;
private: private:
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/

View File

@ -11,7 +11,7 @@
#include <SHpch.h> #include <SHpch.h>
// Primary Header // Primary Header
#include "SHBoundingSphere.h" #include "SHSphere.h"
// Project Headers // Project Headers
#include "Math/SHMathHelpers.h" #include "Math/SHMathHelpers.h"
#include "Math/SHRay.h" #include "Math/SHRay.h"
@ -24,13 +24,13 @@ namespace SHADE
/* Constructors & Destructor Definitions */ /* Constructors & Destructor Definitions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
SHBoundingSphere::SHBoundingSphere() noexcept SHSphere::SHSphere() noexcept
: RelativeRadius { 1.0f } : RelativeRadius { 1.0f }
{ {
type = Type::SPHERE; type = Type::SPHERE;
} }
SHBoundingSphere::SHBoundingSphere(const SHVec3& center, float radius) noexcept SHSphere::SHSphere(const SHVec3& center, float radius) noexcept
: RelativeRadius { 1.0f } : RelativeRadius { 1.0f }
{ {
type = Type::SPHERE; type = Type::SPHERE;
@ -39,7 +39,7 @@ namespace SHADE
Radius = radius; Radius = radius;
} }
SHBoundingSphere::SHBoundingSphere(const SHBoundingSphere& rhs) noexcept SHSphere::SHSphere(const SHSphere& rhs) noexcept
{ {
if (this == &rhs) if (this == &rhs)
return; return;
@ -51,7 +51,7 @@ namespace SHADE
RelativeRadius = rhs.RelativeRadius; RelativeRadius = rhs.RelativeRadius;
} }
SHBoundingSphere::SHBoundingSphere(SHBoundingSphere&& rhs) noexcept SHSphere::SHSphere(SHSphere&& rhs) noexcept
{ {
type = Type::SPHERE; type = Type::SPHERE;
@ -64,7 +64,7 @@ namespace SHADE
/* Operator Overload Definitions */ /* Operator Overload Definitions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
SHBoundingSphere& SHBoundingSphere::operator=(const SHBoundingSphere& rhs) noexcept SHSphere& SHSphere::operator=(const SHSphere& rhs) noexcept
{ {
if (rhs.type != Type::SPHERE) if (rhs.type != Type::SPHERE)
{ {
@ -80,7 +80,7 @@ namespace SHADE
return *this; return *this;
} }
SHBoundingSphere& SHBoundingSphere::operator=(SHBoundingSphere&& rhs) noexcept SHSphere& SHSphere::operator=(SHSphere&& rhs) noexcept
{ {
if (rhs.type != Type::SPHERE) if (rhs.type != Type::SPHERE)
{ {
@ -100,17 +100,17 @@ namespace SHADE
/* Getter Function Definitions */ /* Getter Function Definitions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
SHVec3 SHBoundingSphere::GetCenter() const noexcept SHVec3 SHSphere::GetCenter() const noexcept
{ {
return Center; return Center;
} }
float SHBoundingSphere::GetWorldRadius() const noexcept float SHSphere::GetWorldRadius() const noexcept
{ {
return Radius; return Radius;
} }
float SHBoundingSphere::GetRelativeRadius() const noexcept float SHSphere::GetRelativeRadius() const noexcept
{ {
return RelativeRadius; return RelativeRadius;
} }
@ -119,17 +119,17 @@ namespace SHADE
/* Setter Function Definitions */ /* Setter Function Definitions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
void SHBoundingSphere::SetCenter(const SHVec3& center) noexcept void SHSphere::SetCenter(const SHVec3& center) noexcept
{ {
Center = center; Center = center;
} }
void SHBoundingSphere::SetWorldRadius(float newWorldRadius) noexcept void SHSphere::SetWorldRadius(float newWorldRadius) noexcept
{ {
Radius = newWorldRadius; Radius = newWorldRadius;
} }
void SHBoundingSphere::SetRelativeRadius(float newRelativeRadius) noexcept void SHSphere::SetRelativeRadius(float newRelativeRadius) noexcept
{ {
RelativeRadius = newRelativeRadius; RelativeRadius = newRelativeRadius;
} }
@ -138,27 +138,27 @@ namespace SHADE
/* Public Function Member Definitions */ /* Public Function Member Definitions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
bool SHBoundingSphere::TestPoint(const SHVec3& point) noexcept bool SHSphere::TestPoint(const SHVec3& point) noexcept
{ {
return BoundingSphere::Contains(point); return BoundingSphere::Contains(point);
} }
bool SHBoundingSphere::Raycast(const SHRay& ray, float& distance) noexcept bool SHSphere::Raycast(const SHRay& ray, float& distance) noexcept
{ {
return Intersects(ray.position, ray.direction, distance); return Intersects(ray.position, ray.direction, distance);
} }
bool SHBoundingSphere::Contains(const SHBoundingSphere& rhs) const noexcept bool SHSphere::Contains(const SHSphere& rhs) const noexcept
{ {
return BoundingSphere::Contains(rhs); return BoundingSphere::Contains(rhs);
} }
float SHBoundingSphere::Volume() const noexcept float SHSphere::Volume() const noexcept
{ {
return (4.0f / 3.0f) * SHMath::PI * (Radius * Radius * Radius); return (4.0f / 3.0f) * SHMath::PI * (Radius * Radius * Radius);
} }
float SHBoundingSphere::SurfaceArea() const noexcept float SHSphere::SurfaceArea() const noexcept
{ {
return 4.0f * SHMath::PI * (Radius * Radius); return 4.0f * SHMath::PI * (Radius * Radius);
} }
@ -167,21 +167,21 @@ namespace SHADE
/* Static Function Member Definitions */ /* Static Function Member Definitions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
SHBoundingSphere SHBoundingSphere::Combine(const SHBoundingSphere& lhs, const SHBoundingSphere& rhs) noexcept SHSphere SHSphere::Combine(const SHSphere& lhs, const SHSphere& rhs) noexcept
{ {
SHBoundingSphere result; SHSphere result;
CreateMerged(result, lhs, rhs); CreateMerged(result, lhs, rhs);
return result; return result;
} }
bool SHBoundingSphere::Intersect(const SHBoundingSphere& lhs, const SHBoundingSphere& rhs) noexcept bool SHSphere::Intersect(const SHSphere& lhs, const SHSphere& rhs) noexcept
{ {
return lhs.Intersects(rhs); return lhs.Intersects(rhs);
} }
SHBoundingSphere SHBoundingSphere::BuildFromSpheres(const SHBoundingSphere* spheres, size_t numSpheres) noexcept SHSphere SHSphere::BuildFromSpheres(const SHSphere* spheres, size_t numSpheres) noexcept
{ {
SHBoundingSphere result; SHSphere result;
for (size_t i = 1; i < numSpheres; ++i) for (size_t i = 1; i < numSpheres; ++i)
CreateMerged(result, spheres[i - 1], spheres[i]); CreateMerged(result, spheres[i - 1], spheres[i]);
@ -189,9 +189,9 @@ namespace SHADE
return result; return result;
} }
SHBoundingSphere SHBoundingSphere::BuildFromVertices(const SHVec3* vertices, size_t numVertices, size_t stride) noexcept SHSphere SHSphere::BuildFromVertices(const SHVec3* vertices, size_t numVertices, size_t stride) noexcept
{ {
SHBoundingSphere result; SHSphere result;
CreateFromPoints(result, numVertices, vertices, stride); CreateFromPoints(result, numVertices, vertices, stride);
return result; return result;
} }

View File

@ -22,27 +22,27 @@ namespace SHADE
/* Type Definitions */ /* Type Definitions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
class SH_API SHBoundingSphere : public SHShape, class SH_API SHSphere : public SHShape,
private DirectX::BoundingSphere private DirectX::BoundingSphere
{ {
public: public:
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Constructors & Destructor */ /* Constructors & Destructor */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
SHBoundingSphere () noexcept; SHSphere () noexcept;
SHBoundingSphere (const SHVec3& center, float radius) noexcept; SHSphere (const SHVec3& center, float radius) noexcept;
SHBoundingSphere (const SHBoundingSphere& rhs) noexcept; SHSphere (const SHSphere& rhs) noexcept;
SHBoundingSphere (SHBoundingSphere&& rhs) noexcept; SHSphere (SHSphere&& rhs) noexcept;
~SHBoundingSphere () override = default; ~SHSphere () override = default;
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Operator Overloads */ /* Operator Overloads */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
SHBoundingSphere& operator= (const SHBoundingSphere& rhs) noexcept; SHSphere& operator= (const SHSphere& rhs) noexcept;
SHBoundingSphere& operator= (SHBoundingSphere&& rhs) noexcept; SHSphere& operator= (SHSphere&& rhs) noexcept;
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Getter Functions */ /* Getter Functions */
@ -67,7 +67,7 @@ namespace SHADE
[[nodiscard]] bool TestPoint (const SHVec3& point) noexcept override; [[nodiscard]] bool TestPoint (const SHVec3& point) noexcept override;
[[nodiscard]] bool Raycast (const SHRay& ray, float& distance) noexcept override; [[nodiscard]] bool Raycast (const SHRay& ray, float& distance) noexcept override;
[[nodiscard]] bool Contains (const SHBoundingSphere& rhs) const noexcept; [[nodiscard]] bool Contains (const SHSphere& rhs) const noexcept;
[[nodiscard]] float Volume () const noexcept; [[nodiscard]] float Volume () const noexcept;
[[nodiscard]] float SurfaceArea () const noexcept; [[nodiscard]] float SurfaceArea () const noexcept;
@ -76,10 +76,10 @@ namespace SHADE
/* Static Function Members */ /* Static Function Members */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
[[nodiscard]] static SHBoundingSphere Combine (const SHBoundingSphere& lhs, const SHBoundingSphere& rhs) noexcept; [[nodiscard]] static SHSphere Combine (const SHSphere& lhs, const SHSphere& rhs) noexcept;
[[nodiscard]] static bool Intersect (const SHBoundingSphere& lhs, const SHBoundingSphere& rhs) noexcept; [[nodiscard]] static bool Intersect (const SHSphere& lhs, const SHSphere& rhs) noexcept;
[[nodiscard]] static SHBoundingSphere BuildFromSpheres (const SHBoundingSphere* spheres, size_t numSpheres) noexcept; [[nodiscard]] static SHSphere BuildFromSpheres (const SHSphere* spheres, size_t numSpheres) noexcept;
[[nodiscard]] static SHBoundingSphere BuildFromVertices (const SHVec3* vertices, size_t numVertices, size_t stride = 0) noexcept; [[nodiscard]] static SHSphere BuildFromVertices (const SHVec3* vertices, size_t numVertices, size_t stride = 0) noexcept;
private: private:
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/

View File

@ -483,6 +483,16 @@ namespace SHADE
return result; return result;
} }
SHMatrix SHMatrix::Transform(const SHVec3& pos, const SHVec3& eulerAngles, const SHVec3& scale) noexcept
{
return Scale(scale) * Rotate(eulerAngles) * Translate(pos);
}
SHMatrix SHMatrix::Transform(const SHVec3& pos, const SHQuaternion& rot, const SHVec3& scale) noexcept
{
return Scale(scale) * Rotate(rot) * Translate(pos);
}
SHMatrix SHMatrix::LookAtRH(const SHVec3& eye, const SHVec3& target, const SHVec3& up) noexcept SHMatrix SHMatrix::LookAtRH(const SHVec3& eye, const SHVec3& target, const SHVec3& up) noexcept
{ {
SHMatrix result; SHMatrix result;

View File

@ -131,34 +131,37 @@ namespace SHADE
/* Static Function Members */ /* Static Function Members */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
[[nodiscard]] static SHMatrix Transpose (const SHMatrix& matrix) noexcept; [[nodiscard]] static SHMatrix Transpose (const SHMatrix& matrix) noexcept;
[[nodiscard]] static SHMatrix Inverse (const SHMatrix& matrix) noexcept; [[nodiscard]] static SHMatrix Inverse (const SHMatrix& matrix) noexcept;
[[nodiscard]] static SHMatrix Translate (float x, float y, float z) noexcept; [[nodiscard]] static SHMatrix Translate (float x, float y, float z) noexcept;
[[nodiscard]] static SHMatrix Translate (const SHVec3& pos) noexcept; [[nodiscard]] static SHMatrix Translate (const SHVec3& pos) noexcept;
[[nodiscard]] static SHMatrix Rotate (const SHVec3& axis, float angleInRad) noexcept; [[nodiscard]] static SHMatrix Rotate (const SHVec3& axis, float angleInRad) noexcept;
[[nodiscard]] static SHMatrix Rotate (float yaw, float pitch, float roll) noexcept; [[nodiscard]] static SHMatrix Rotate (float yaw, float pitch, float roll) noexcept;
[[nodiscard]] static SHMatrix Rotate (const SHVec3& eulerAngles) noexcept; [[nodiscard]] static SHMatrix Rotate (const SHVec3& eulerAngles) noexcept;
[[nodiscard]] static SHMatrix Rotate (const SHQuaternion& q) noexcept; [[nodiscard]] static SHMatrix Rotate (const SHQuaternion& q) noexcept;
[[nodiscard]] static SHMatrix RotateX (float angleInRad) noexcept; [[nodiscard]] static SHMatrix RotateX (float angleInRad) noexcept;
[[nodiscard]] static SHMatrix RotateY (float angleInRad) noexcept; [[nodiscard]] static SHMatrix RotateY (float angleInRad) noexcept;
[[nodiscard]] static SHMatrix RotateZ (float angleInRad) noexcept; [[nodiscard]] static SHMatrix RotateZ (float angleInRad) noexcept;
[[nodiscard]] static SHMatrix Scale (float uniformScaleFactor) noexcept; [[nodiscard]] static SHMatrix Scale (float uniformScaleFactor) noexcept;
[[nodiscard]] static SHMatrix Scale (float x, float y, float z) noexcept; [[nodiscard]] static SHMatrix Scale (float x, float y, float z) noexcept;
[[nodiscard]] static SHMatrix Scale (const SHVec3& scale) noexcept; [[nodiscard]] static SHMatrix Scale (const SHVec3& scale) noexcept;
[[nodiscard]] static SHMatrix LookAtRH (const SHVec3& eye, const SHVec3& target, const SHVec3& up) noexcept; [[nodiscard]] static SHMatrix Transform (const SHVec3& pos, const SHVec3& eulerAngles, const SHVec3& scale) noexcept;
[[nodiscard]] static SHMatrix LookAtLH (const SHVec3& eye, const SHVec3& target, const SHVec3& up) noexcept; [[nodiscard]] static SHMatrix Transform (const SHVec3& pos, const SHQuaternion& rot, const SHVec3& scale) noexcept;
[[nodiscard]] static SHMatrix CamToWorldRH (const SHVec3& pos, const SHVec3& forward, const SHVec3& up) noexcept;
[[nodiscard]] static SHMatrix CamToWorldLH (const SHVec3& pos, const SHVec3& forward, const SHVec3& up) noexcept; [[nodiscard]] static SHMatrix LookAtRH (const SHVec3& eye, const SHVec3& target, const SHVec3& up) noexcept;
[[nodiscard]] static SHMatrix PerspectiveFovRH (float fov, float aspectRatio, float nearPlane, float farPlane) noexcept; [[nodiscard]] static SHMatrix LookAtLH (const SHVec3& eye, const SHVec3& target, const SHVec3& up) noexcept;
[[nodiscard]] static SHMatrix PerspectiveFovLH (float fov, float aspectRatio, float nearPlane, float farPlane) noexcept; [[nodiscard]] static SHMatrix CamToWorldRH (const SHVec3& pos, const SHVec3& forward, const SHVec3& up) noexcept;
[[nodiscard]] static SHMatrix PerspectiveRH (float width, float height, float nearPlane, float farPlane) noexcept; [[nodiscard]] static SHMatrix CamToWorldLH (const SHVec3& pos, const SHVec3& forward, const SHVec3& up) noexcept;
[[nodiscard]] static SHMatrix PerspectiveLH (float width, float height, float nearPlane, float farPlane) noexcept; [[nodiscard]] static SHMatrix PerspectiveFovRH (float fov, float aspectRatio, float nearPlane, float farPlane) noexcept;
[[nodiscard]] static SHMatrix OrthographicRH (float width, float height, float nearPlane, float farPlane) noexcept; [[nodiscard]] static SHMatrix PerspectiveFovLH (float fov, float aspectRatio, float nearPlane, float farPlane) noexcept;
[[nodiscard]] static SHMatrix OrthographicLH (float width, float height, float nearPlane, float farPlane) noexcept; [[nodiscard]] static SHMatrix PerspectiveRH (float width, float height, float nearPlane, float farPlane) noexcept;
[[nodiscard]] static SHMatrix PerspectiveLH (float width, float height, float nearPlane, float farPlane) noexcept;
[[nodiscard]] static SHMatrix OrthographicRH (float width, float height, float nearPlane, float farPlane) noexcept;
[[nodiscard]] static SHMatrix OrthographicLH (float width, float height, float nearPlane, float farPlane) noexcept;
// TODO(Diren): Billboard, Shadow, Projection & Reflection // TODO(Diren): Billboard, Shadow, Projection & Reflection
}; };

View File

@ -16,7 +16,7 @@
#include "Vector/SHVec3.h" #include "Vector/SHVec3.h"
#include "SHMatrix.h" #include "SHMatrix.h"
#include "SHMathHelpers.h" #include "SHMathHelpers.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
using namespace DirectX; using namespace DirectX;

View File

@ -14,7 +14,7 @@
#include "SHVec2.h" #include "SHVec2.h"
// Project Headers // Project Headers
#include "Math/SHMatrix.h" #include "Math/SHMatrix.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
using namespace DirectX; using namespace DirectX;

View File

@ -15,7 +15,7 @@
// Project Headers // Project Headers
#include "Math/SHMatrix.h" #include "Math/SHMatrix.h"
#include "Math/SHQuaternion.h" #include "Math/SHQuaternion.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
using namespace DirectX; using namespace DirectX;

View File

@ -15,7 +15,7 @@
// Project Headers // Project Headers
#include "Math/SHMatrix.h" #include "Math/SHMatrix.h"
#include "Math/SHColour.h" #include "Math/SHColour.h"
#include "Tools/SHLogger.h" #include "Tools/Logger/SHLogger.h"
using namespace DirectX; using namespace DirectX;

View File

@ -16,6 +16,7 @@
// Project Headers // Project Headers
#include "Physics/PhysicsObject/SHPhysicsObject.h" #include "Physics/PhysicsObject/SHPhysicsObject.h"
#include "Physics/System/SHPhysicsSystem.h" #include "Physics/System/SHPhysicsSystem.h"
#include "Scene/SHSceneManager.h"
/*-------------------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------------------*/
/* Local Helper Functions */ /* Local Helper Functions */
@ -80,10 +81,15 @@ namespace SHADE
{ {
for (auto eventIter = container.begin(); eventIter != container.end();) for (auto eventIter = container.begin(); eventIter != container.end();)
{ {
const bool CLEAR_EVENT = eventIter->GetCollisionState() == SHCollisionInfo::State::EXIT const SHCollisionInfo& C_INFO = *eventIter;
|| eventIter->GetCollisionState() == SHCollisionInfo::State::INVALID;
if (CLEAR_EVENT) const bool CLEAR_EVENT = C_INFO.GetCollisionState() == SHCollisionInfo::State::EXIT
|| C_INFO.GetCollisionState() == SHCollisionInfo::State::INVALID;
const bool INACTIVE_OBJECT = !SHSceneManager::CheckNodeAndComponentsActive<SHColliderComponent>(C_INFO.GetEntityA())
|| !SHSceneManager::CheckNodeAndComponentsActive<SHColliderComponent>(C_INFO.GetEntityB());
if (CLEAR_EVENT || INACTIVE_OBJECT)
eventIter = container.erase(eventIter); eventIter = container.erase(eventIter);
else else
++eventIter; ++eventIter;

View File

@ -95,7 +95,7 @@ namespace SHADE
{ {
case SHCollisionShape::Type::BOX: case SHCollisionShape::Type::BOX:
{ {
auto* box = reinterpret_cast<SHBoundingBox*>(collisionShape.shape); auto* box = reinterpret_cast<SHBox*>(collisionShape.shape);
const SHVec3& RELATIVE_EXTENTS = box->GetRelativeExtents(); const SHVec3& RELATIVE_EXTENTS = box->GetRelativeExtents();
// Recompute world extents based on new scale and fixed relative extents // Recompute world extents based on new scale and fixed relative extents
@ -106,7 +106,7 @@ namespace SHADE
} }
case SHCollisionShape::Type::SPHERE: case SHCollisionShape::Type::SPHERE:
{ {
auto* sphere = reinterpret_cast<SHBoundingSphere*>(collisionShape.shape); auto* sphere = reinterpret_cast<SHSphere*>(collisionShape.shape);
const float RELATIVE_RADIUS = sphere->GetRelativeRadius(); const float RELATIVE_RADIUS = sphere->GetRelativeRadius();
// Recompute world radius based on new scale and fixed radius // Recompute world radius based on new scale and fixed radius

View File

@ -14,8 +14,8 @@
// Project Headers // Project Headers
#include "ECS_Base/Components/SHComponent.h" #include "ECS_Base/Components/SHComponent.h"
#include "Math/Geometry/SHBoundingBox.h" #include "Math/Geometry/SHBox.h"
#include "Math/Geometry/SHBoundingSphere.h" #include "Math/Geometry/SHSphere.h"
#include "SHCollisionShape.h" #include "SHCollisionShape.h"
//namespace SHADE //namespace SHADE

View File

@ -13,8 +13,8 @@
// Primary Header // Primary Header
#include "SHCollisionShape.h" #include "SHCollisionShape.h"
// Project Headers // Project Headers
#include "Math/Geometry/SHBoundingBox.h" #include "Math/Geometry/SHBox.h"
#include "Math/Geometry/SHBoundingSphere.h" #include "Math/Geometry/SHSphere.h"
#include "Math/SHMathHelpers.h" #include "Math/SHMathHelpers.h"
#include "Reflection/SHReflectionMetadata.h" #include "Reflection/SHReflectionMetadata.h"
#include "SHColliderComponent.h" #include "SHColliderComponent.h"
@ -37,12 +37,12 @@ namespace SHADE
{ {
case Type::BOX: case Type::BOX:
{ {
shape = new SHBoundingBox{ SHVec3::Zero, SHVec3::One }; shape = new SHBox{ SHVec3::Zero, SHVec3::One };
break; break;
} }
case Type::SPHERE: case Type::SPHERE:
{ {
shape = new SHBoundingSphere{ SHVec3::Zero, 0.5f }; shape = new SHSphere{ SHVec3::Zero, 0.5f };
break; break;
} }
default: break; default: break;
@ -177,30 +177,48 @@ namespace SHADE
{ {
dirty = true; dirty = true;
const auto* colliderComponent = SHComponentManager::GetComponent<SHColliderComponent>(entityID); const auto* COLLIDER = SHComponentManager::GetComponent<SHColliderComponent>(entityID);
auto* box = reinterpret_cast<SHBox*>(shape);
SHVec3 correctedHalfExtents = halfExtents;
// Get current relative halfExtents for error checking. 0 is ignored
const SHVec3& CURRENT_RELATIVE_EXTENTS = box->GetRelativeExtents();
for (size_t i = 0; i < SHVec3::SIZE; ++i)
{
if (SHMath::CompareFloat(halfExtents[i], 0.0f))
correctedHalfExtents[i] = CURRENT_RELATIVE_EXTENTS[i];
}
// Set the half extents relative to world scale // Set the half extents relative to world scale
const SHVec3 WORLD_EXTENTS = halfExtents * colliderComponent->GetScale() * 0.5f; const SHVec3 WORLD_EXTENTS = correctedHalfExtents * COLLIDER->GetScale() * 0.5f;
if (type != Type::BOX) if (type != Type::BOX)
{ {
type = Type::BOX; type = Type::BOX;
delete shape; delete shape;
shape = new SHBoundingBox{ positionOffset, WORLD_EXTENTS }; shape = new SHBox{ positionOffset, WORLD_EXTENTS };
} }
auto* box = reinterpret_cast<SHBoundingBox*>(shape);
box->SetWorldExtents(WORLD_EXTENTS); box->SetWorldExtents(WORLD_EXTENTS);
box->SetRelativeExtents(halfExtents); box->SetRelativeExtents(correctedHalfExtents);
} }
void SHCollisionShape::SetBoundingSphere(float radius) void SHCollisionShape::SetBoundingSphere(float radius)
{ {
dirty = true; dirty = true;
const auto* colliderComponent = SHComponentManager::GetComponent<SHColliderComponent>(entityID); auto* sphere = reinterpret_cast<SHSphere*>(shape);
const auto* COLLIDER = SHComponentManager::GetComponent<SHColliderComponent>(entityID);
// Get current relative halfExtents for error checking. 0 is ignored
const float CURRENT_RELATIVE_RADIUS = sphere->GetRelativeRadius();
if (SHMath::CompareFloat(radius, 0.0f))
radius = CURRENT_RELATIVE_RADIUS;
// Set the radius relative to world scale // Set the radius relative to world scale
const SHVec3 WORLD_SCALE = colliderComponent->GetScale(); const SHVec3 WORLD_SCALE = COLLIDER->GetScale();
const float MAX_SCALE = SHMath::Max({ WORLD_SCALE.x, WORLD_SCALE.y, WORLD_SCALE.z }); const float MAX_SCALE = SHMath::Max({ WORLD_SCALE.x, WORLD_SCALE.y, WORLD_SCALE.z });
const float WORLD_RADIUS = radius * MAX_SCALE * 0.5f; const float WORLD_RADIUS = radius * MAX_SCALE * 0.5f;
@ -209,11 +227,11 @@ namespace SHADE
type = Type::SPHERE; type = Type::SPHERE;
delete shape; delete shape;
shape = new SHBoundingSphere{ positionOffset, WORLD_RADIUS }; shape = new SHSphere{ positionOffset, WORLD_RADIUS };
} }
auto* sphere = reinterpret_cast<SHBoundingSphere*>(shape);
sphere->SetWorldRadius(WORLD_RADIUS); sphere->SetWorldRadius(WORLD_RADIUS);
sphere->SetRelativeRadius(radius);
} }
void SHCollisionShape::SetIsTrigger(bool trigger) noexcept void SHCollisionShape::SetIsTrigger(bool trigger) noexcept
@ -255,12 +273,12 @@ namespace SHADE
{ {
case Type::BOX: case Type::BOX:
{ {
reinterpret_cast<SHBoundingBox*>(shape)->SetCenter(positionOffset); reinterpret_cast<SHBox*>(shape)->SetCenter(positionOffset);
break; break;
} }
case Type::SPHERE: case Type::SPHERE:
{ {
reinterpret_cast<SHBoundingSphere*>(shape)->SetCenter(positionOffset); reinterpret_cast<SHSphere*>(shape)->SetCenter(positionOffset);
break; break;
} }
default: break; default: break;
@ -283,16 +301,22 @@ namespace SHADE
{ {
case Type::BOX: case Type::BOX:
{ {
const auto* RHS_BOX = reinterpret_cast<const SHBoundingBox*>(rhs); const auto* RHS_BOX = reinterpret_cast<const SHBox*>(rhs);
shape = new SHBox{ positionOffset, RHS_BOX->GetWorldExtents() };
auto* lhsBox = reinterpret_cast<SHBox*>(shape);
lhsBox->SetRelativeExtents(RHS_BOX->GetRelativeExtents());
shape = new SHBoundingBox{ positionOffset, RHS_BOX->GetWorldExtents() };
break; break;
} }
case Type::SPHERE: case Type::SPHERE:
{ {
const auto* RHS_SPHERE = reinterpret_cast<const SHBoundingSphere*>(rhs); const auto* RHS_SPHERE = reinterpret_cast<const SHSphere*>(rhs);
shape = new SHSphere{ positionOffset, RHS_SPHERE->GetWorldRadius() };
auto* lhsSphere = reinterpret_cast<SHSphere*>(shape);
lhsSphere->SetRelativeRadius(RHS_SPHERE->GetRelativeRadius());
shape = new SHBoundingSphere{ positionOffset, RHS_SPHERE->GetWorldRadius() };
break; break;
} }
default: break; default: break;

View File

@ -44,7 +44,7 @@ namespace SHADE
&& SHMath::CompareFloat(density, rhs.density); && SHMath::CompareFloat(density, rhs.density);
} }
bool SHPhysicsMaterial::operator!=(const SHPhysicsMaterial& rhs) const noexcept bool SHPhysicsMaterial::operator!=(const SHPhysicsMaterial& rhs) const noexcept
{ {
return !SHMath::CompareFloat(friction, rhs.friction) return !SHMath::CompareFloat(friction, rhs.friction)
|| !SHMath::CompareFloat(bounciness, rhs.bounciness) || !SHMath::CompareFloat(bounciness, rhs.bounciness)

View File

@ -29,7 +29,6 @@ namespace SHADE
SHRigidBodyComponent::SHRigidBodyComponent() noexcept SHRigidBodyComponent::SHRigidBodyComponent() noexcept
: type { Type::DYNAMIC } : type { Type::DYNAMIC }
, interpolate { true }
, flags { 0 } , flags { 0 }
, dirtyFlags { std::numeric_limits<uint16_t>::max() } , dirtyFlags { std::numeric_limits<uint16_t>::max() }
, mass { 1.0f } , mass { 1.0f }
@ -40,6 +39,7 @@ namespace SHADE
// Initialise default flags // Initialise default flags
flags |= 1U << 0; // Gravity set to true flags |= 1U << 0; // Gravity set to true
flags |= 1U << 1; // Sleeping allowed flags |= 1U << 1; // Sleeping allowed
flags |= 1U << 8; // Interpolate by default
} }
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
@ -60,7 +60,16 @@ namespace SHADE
bool SHRigidBodyComponent::IsInterpolating() const noexcept bool SHRigidBodyComponent::IsInterpolating() const noexcept
{ {
return interpolate; static constexpr int FLAG_POS = 8;
return flags & (1U << FLAG_POS);
}
bool SHRigidBodyComponent::GetIsSleeping() const noexcept
{
if (auto* physicsObject = system->GetPhysicsObject(GetEID()); physicsObject)
return physicsObject->GetRigidBody()->isSleeping();
return false;
} }
SHRigidBodyComponent::Type SHRigidBodyComponent::GetType() const noexcept SHRigidBodyComponent::Type SHRigidBodyComponent::GetType() const noexcept
@ -68,21 +77,6 @@ namespace SHADE
return type; return type;
} }
float SHRigidBodyComponent::GetMass() const noexcept
{
return mass;
}
float SHRigidBodyComponent::GetDrag() const noexcept
{
return drag;
}
float SHRigidBodyComponent::GetAngularDrag() const noexcept
{
return angularDrag;
}
bool SHRigidBodyComponent::GetFreezePositionX() const noexcept bool SHRigidBodyComponent::GetFreezePositionX() const noexcept
{ {
static constexpr int FLAG_POS = 2; static constexpr int FLAG_POS = 2;
@ -119,6 +113,27 @@ namespace SHADE
return flags & (1U << FLAG_POS); return flags & (1U << FLAG_POS);
} }
//bool SHRigidBodyComponent::GetAutoMass() const noexcept
//{
// static constexpr int FLAG_POS = 9;
// return flags & (1U << FLAG_POS);
//}
float SHRigidBodyComponent::GetMass() const noexcept
{
return mass;
}
float SHRigidBodyComponent::GetDrag() const noexcept
{
return drag;
}
float SHRigidBodyComponent::GetAngularDrag() const noexcept
{
return angularDrag;
}
SHVec3 SHRigidBodyComponent::GetForce() const noexcept SHVec3 SHRigidBodyComponent::GetForce() const noexcept
{ {
if (auto* physicsObject = system->GetPhysicsObject(GetEID()); physicsObject) if (auto* physicsObject = system->GetPhysicsObject(GetEID()); physicsObject)
@ -295,13 +310,25 @@ namespace SHADE
void SHRigidBodyComponent::SetInterpolate(bool allowInterpolation) noexcept void SHRigidBodyComponent::SetInterpolate(bool allowInterpolation) noexcept
{ {
interpolate = allowInterpolation; static constexpr int FLAG_POS = 8;
allowInterpolation ? flags |= 1U << FLAG_POS : flags &= ~(1U << FLAG_POS);
} }
//void SHRigidBodyComponent::SetAutoMass(bool autoMass) noexcept
//{
// static constexpr int FLAG_POS = 9;
// autoMass ? flags |= 1U << FLAG_POS : flags &= ~(1U << FLAG_POS);
// dirtyFlags |= 1U << FLAG_POS;
//}
void SHRigidBodyComponent::SetMass(float newMass) noexcept void SHRigidBodyComponent::SetMass(float newMass) noexcept
{ {
static constexpr int FLAG_POS = 9; static constexpr int FLAG_POS = 9;
if (newMass < 0.0f)
return;
if (type != Type::DYNAMIC) if (type != Type::DYNAMIC)
{ {
SHLOG_WARNING("Cannot set mass of a non-dynamic object {}", GetEID()) SHLOG_WARNING("Cannot set mass of a non-dynamic object {}", GetEID())
@ -310,6 +337,9 @@ namespace SHADE
dirtyFlags |= 1U << FLAG_POS; dirtyFlags |= 1U << FLAG_POS;
mass = newMass; mass = newMass;
// Turn off automass
flags &= ~(1U << FLAG_POS);
} }
void SHRigidBodyComponent::SetDrag(float newDrag) noexcept void SHRigidBodyComponent::SetDrag(float newDrag) noexcept
@ -385,42 +415,62 @@ namespace SHADE
void SHRigidBodyComponent::AddForce(const SHVec3& force) const noexcept void SHRigidBodyComponent::AddForce(const SHVec3& force) const noexcept
{ {
system->AddForce(GetEID(), force); if (auto* physicsObject = system->GetPhysicsObject(GetEID()); physicsObject)
physicsObject->GetRigidBody()->applyWorldForceAtCenterOfMass(force);
} }
void SHRigidBodyComponent::AddForceAtLocalPos(const SHVec3& force, const SHVec3& localPos) const noexcept void SHRigidBodyComponent::AddForceAtLocalPos(const SHVec3& force, const SHVec3& localPos) const noexcept
{ {
system->AddForceAtLocalPos(GetEID(), force, localPos); if (auto* physicsObject = system->GetPhysicsObject(GetEID()); physicsObject)
physicsObject->GetRigidBody()->applyWorldForceAtLocalPosition(force, localPos);
} }
void SHRigidBodyComponent::AddForceAtWorldPos(const SHVec3& force, const SHVec3& worldPos) const noexcept void SHRigidBodyComponent::AddForceAtWorldPos(const SHVec3& force, const SHVec3& worldPos) const noexcept
{ {
system->AddForceAtWorldPos(GetEID(), force, worldPos); if (auto* physicsObject = system->GetPhysicsObject(GetEID()); physicsObject)
physicsObject->GetRigidBody()->applyWorldForceAtWorldPosition(force, worldPos);
} }
void SHRigidBodyComponent::AddRelativeForce(const SHVec3& relativeForce) const noexcept void SHRigidBodyComponent::AddRelativeForce(const SHVec3& relativeForce) const noexcept
{ {
system->AddRelativeForce(GetEID(), relativeForce); if (auto* physicsObject = system->GetPhysicsObject(GetEID()); physicsObject)
physicsObject->GetRigidBody()->applyLocalForceAtCenterOfMass(relativeForce);
} }
void SHRigidBodyComponent::AddRelativeForceAtLocalPos(const SHVec3& relativeForce, const SHVec3& localPos) const noexcept void SHRigidBodyComponent::AddRelativeForceAtLocalPos(const SHVec3& relativeForce, const SHVec3& localPos) const noexcept
{ {
system->AddRelativeForceAtLocalPos(GetEID(), relativeForce, localPos); if (auto* physicsObject = system->GetPhysicsObject(GetEID()); physicsObject)
physicsObject->GetRigidBody()->applyLocalForceAtLocalPosition(relativeForce, localPos);
} }
void SHRigidBodyComponent::AddRelativeForceAtWorldPos(const SHVec3& relativeForce, const SHVec3& worldPos) const noexcept void SHRigidBodyComponent::AddRelativeForceAtWorldPos(const SHVec3& relativeForce, const SHVec3& worldPos) const noexcept
{ {
system->AddRelativeForceAtWorldPos(GetEID(), relativeForce, worldPos); if (auto* physicsObject = system->GetPhysicsObject(GetEID()); physicsObject)
physicsObject->GetRigidBody()->applyLocalForceAtWorldPosition(relativeForce, worldPos);
} }
void SHRigidBodyComponent::AddTorque(const SHVec3& torque) const noexcept void SHRigidBodyComponent::AddTorque(const SHVec3& torque) const noexcept
{ {
system->AddTorque(GetEID(), torque); if (auto* physicsObject = system->GetPhysicsObject(GetEID()); physicsObject)
physicsObject->GetRigidBody()->applyWorldTorque(torque);
} }
void SHRigidBodyComponent::AddRelativeTorque(const SHVec3& relativeTorque) const noexcept void SHRigidBodyComponent::AddRelativeTorque(const SHVec3& relativeTorque) const noexcept
{ {
system->AddRelativeTorque(GetEID(), relativeTorque); if (auto* physicsObject = system->GetPhysicsObject(GetEID()); physicsObject)
physicsObject->GetRigidBody()->applyLocalTorque(relativeTorque);
}
void SHRigidBodyComponent::ClearForces() const noexcept
{
if (auto* physicsObject = system->GetPhysicsObject(GetEID()); physicsObject)
physicsObject->GetRigidBody()->resetForce();
}
void SHRigidBodyComponent::ClearTorque() const noexcept
{
if (auto* physicsObject = system->GetPhysicsObject(GetEID()); physicsObject)
physicsObject->GetRigidBody()->resetTorque();
} }
} // namespace SHADE } // namespace SHADE
@ -444,6 +494,8 @@ RTTR_REGISTRATION
.property("Angular Drag" , &SHRigidBodyComponent::GetAngularDrag , &SHRigidBodyComponent::SetAngularDrag ) .property("Angular Drag" , &SHRigidBodyComponent::GetAngularDrag , &SHRigidBodyComponent::SetAngularDrag )
.property("Use Gravity" , &SHRigidBodyComponent::IsGravityEnabled , &SHRigidBodyComponent::SetGravityEnabled ) .property("Use Gravity" , &SHRigidBodyComponent::IsGravityEnabled , &SHRigidBodyComponent::SetGravityEnabled )
.property("Interpolate" , &SHRigidBodyComponent::IsInterpolating , &SHRigidBodyComponent::SetInterpolate ) .property("Interpolate" , &SHRigidBodyComponent::IsInterpolating , &SHRigidBodyComponent::SetInterpolate )
.property("Sleeping Enabled" , &SHRigidBodyComponent::IsAllowedToSleep , &SHRigidBodyComponent::SetIsAllowedToSleep)
//.property("Auto Mass" , &SHRigidBodyComponent::GetAutoMass , &SHRigidBodyComponent::SetAutoMass )
.property("Freeze Position X" , &SHRigidBodyComponent::GetFreezePositionX , &SHRigidBodyComponent::SetFreezePositionX ) .property("Freeze Position X" , &SHRigidBodyComponent::GetFreezePositionX , &SHRigidBodyComponent::SetFreezePositionX )
.property("Freeze Position Y" , &SHRigidBodyComponent::GetFreezePositionY , &SHRigidBodyComponent::SetFreezePositionY ) .property("Freeze Position Y" , &SHRigidBodyComponent::GetFreezePositionY , &SHRigidBodyComponent::SetFreezePositionY )
.property("Freeze Position Z" , &SHRigidBodyComponent::GetFreezePositionZ , &SHRigidBodyComponent::SetFreezePositionZ ) .property("Freeze Position Z" , &SHRigidBodyComponent::GetFreezePositionZ , &SHRigidBodyComponent::SetFreezePositionZ )

View File

@ -71,19 +71,23 @@ namespace SHADE
[[nodiscard]] bool IsAllowedToSleep () const noexcept; [[nodiscard]] bool IsAllowedToSleep () const noexcept;
[[nodiscard]] bool IsInterpolating () const noexcept; [[nodiscard]] bool IsInterpolating () const noexcept;
[[nodiscard]] bool GetIsSleeping () const noexcept;
[[nodiscard]] Type GetType () const noexcept; [[nodiscard]] Type GetType () const noexcept;
[[nodiscard]] float GetMass () const noexcept;
[[nodiscard]] float GetDrag () const noexcept;
[[nodiscard]] float GetAngularDrag () const noexcept;
[[nodiscard]] bool GetFreezePositionX () const noexcept; [[nodiscard]] bool GetFreezePositionX () const noexcept;
[[nodiscard]] bool GetFreezePositionY () const noexcept; [[nodiscard]] bool GetFreezePositionY () const noexcept;
[[nodiscard]] bool GetFreezePositionZ () const noexcept; [[nodiscard]] bool GetFreezePositionZ () const noexcept;
[[nodiscard]] bool GetFreezeRotationX () const noexcept; [[nodiscard]] bool GetFreezeRotationX () const noexcept;
[[nodiscard]] bool GetFreezeRotationY () const noexcept; [[nodiscard]] bool GetFreezeRotationY () const noexcept;
[[nodiscard]] bool GetFreezeRotationZ () const noexcept; [[nodiscard]] bool GetFreezeRotationZ () const noexcept;
//[[nodiscard]] bool GetAutoMass () const noexcept;
[[nodiscard]] float GetMass () const noexcept;
[[nodiscard]] float GetDrag () const noexcept;
[[nodiscard]] float GetAngularDrag () const noexcept;
[[nodiscard]] SHVec3 GetForce () const noexcept; [[nodiscard]] SHVec3 GetForce () const noexcept;
[[nodiscard]] SHVec3 GetTorque () const noexcept; [[nodiscard]] SHVec3 GetTorque () const noexcept;
[[nodiscard]] SHVec3 GetLinearVelocity () const noexcept; [[nodiscard]] SHVec3 GetLinearVelocity () const noexcept;
@ -108,6 +112,7 @@ namespace SHADE
void SetFreezeRotationY (bool freezeRotationY) noexcept; void SetFreezeRotationY (bool freezeRotationY) noexcept;
void SetFreezeRotationZ (bool freezeRotationZ) noexcept; void SetFreezeRotationZ (bool freezeRotationZ) noexcept;
void SetInterpolate (bool allowInterpolation) noexcept; void SetInterpolate (bool allowInterpolation) noexcept;
//void SetAutoMass (bool autoMass) noexcept;
void SetMass (float newMass) noexcept; void SetMass (float newMass) noexcept;
void SetDrag (float newDrag) noexcept; void SetDrag (float newDrag) noexcept;
@ -125,14 +130,15 @@ namespace SHADE
void AddForce (const SHVec3& force) const noexcept; void AddForce (const SHVec3& force) const noexcept;
void AddForceAtLocalPos (const SHVec3& force, const SHVec3& localPos) const noexcept; void AddForceAtLocalPos (const SHVec3& force, const SHVec3& localPos) const noexcept;
void AddForceAtWorldPos (const SHVec3& force, const SHVec3& worldPos) const noexcept; void AddForceAtWorldPos (const SHVec3& force, const SHVec3& worldPos) const noexcept;
void AddRelativeForce (const SHVec3& relativeForce) const noexcept; void AddRelativeForce (const SHVec3& relativeForce) const noexcept;
void AddRelativeForceAtLocalPos (const SHVec3& relativeForce, const SHVec3& localPos) const noexcept; void AddRelativeForceAtLocalPos (const SHVec3& relativeForce, const SHVec3& localPos) const noexcept;
void AddRelativeForceAtWorldPos (const SHVec3& relativeForce, const SHVec3& worldPos) const noexcept; void AddRelativeForceAtWorldPos (const SHVec3& relativeForce, const SHVec3& worldPos) const noexcept;
void AddTorque (const SHVec3& torque) const noexcept; void AddTorque (const SHVec3& torque) const noexcept;
void AddRelativeTorque (const SHVec3& relativeTorque) const noexcept; void AddRelativeTorque (const SHVec3& relativeTorque) const noexcept;
void ClearForces () const noexcept;
void ClearTorque () const noexcept;
private: private:
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Data Members */ /* Data Members */
@ -143,8 +149,7 @@ namespace SHADE
Type type; Type type;
bool interpolate; uint16_t flags; // 0 0 0 0 0 0 am ip aZ aY aX lZ lY lX slp g
uint8_t flags; // aZ aY aX lZ lY lX slp g
uint16_t dirtyFlags; // 0 0 0 0 aD d m t aZ aY aX lZ lY lX slp g uint16_t dirtyFlags; // 0 0 0 0 aD d m t aZ aY aX lZ lY lX slp g
float mass; float mass;

View File

@ -16,6 +16,7 @@
// Project Headers // Project Headers
#include "ECS_Base/Managers/SHSystemManager.h" #include "ECS_Base/Managers/SHSystemManager.h"
#include "ECS_Base/Managers/SHComponentManager.h" #include "ECS_Base/Managers/SHComponentManager.h"
#include "Scene/SHSceneManager.h"
namespace SHADE namespace SHADE
@ -25,10 +26,11 @@ namespace SHADE
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
SHPhysicsObject::SHPhysicsObject(EntityID eid, rp3d::PhysicsCommon* physicsFactory, rp3d::PhysicsWorld* physicsWorld) noexcept SHPhysicsObject::SHPhysicsObject(EntityID eid, rp3d::PhysicsCommon* physicsFactory, rp3d::PhysicsWorld* physicsWorld) noexcept
: entityID { eid } : entityID { eid }
, factory { physicsFactory } , collidersActive { true }
, world { physicsWorld } , factory { physicsFactory }
, rp3dBody { nullptr } , world { physicsWorld }
, rp3dBody { nullptr }
{ {
// Implicitly create a static body. // Implicitly create a static body.
@ -107,8 +109,17 @@ namespace SHADE
{ {
// TODO(Diren): Add more collider shapes // TODO(Diren): Add more collider shapes
case SHCollisionShape::Type::BOX: addBoxShape(collisionShape); break; case SHCollisionShape::Type::BOX:
case SHCollisionShape::Type::SPHERE: addSphereShape(collisionShape); break; {
addBoxShape(collisionShape);
break;
}
case SHCollisionShape::Type::SPHERE:
{
addSphereShape(collisionShape);
break;
}
default: break; default: break;
} }
@ -148,6 +159,10 @@ namespace SHADE
void SHPhysicsObject::SyncRigidBody(SHRigidBodyComponent& component) const noexcept void SHPhysicsObject::SyncRigidBody(SHRigidBodyComponent& component) const noexcept
{ {
// This state is synced in the pre-update routine
if (!rp3dBody->isActive())
return;
if (component.dirtyFlags == 0) if (component.dirtyFlags == 0)
return; return;
@ -239,9 +254,17 @@ namespace SHADE
} }
case 9: // Mass case 9: // Mass
{ {
rp3dBody->setMass(component.mass); //if (component.GetAutoMass())
rp3dBody->updateLocalCenterOfMassFromColliders(); //{
rp3dBody->updateLocalInertiaTensorFromColliders(); // rp3dBody->updateMassPropertiesFromColliders();
// component.mass = rp3dBody->getMass();
//}
//else
//{
rp3dBody->setMass(component.mass);
rp3dBody->updateLocalCenterOfMassFromColliders();
rp3dBody->updateLocalInertiaTensorFromColliders();
//}
break; break;
} }
@ -267,23 +290,28 @@ namespace SHADE
void SHPhysicsObject::SyncColliders(SHColliderComponent& component) const noexcept void SHPhysicsObject::SyncColliders(SHColliderComponent& component) const noexcept
{ {
int index = 0; // This state is synced in the pre-update routine
for (auto& collisionShape : component.collisionShapes) if (!rp3dBody->isActive())
return;
const int NUM_SHAPES = static_cast<int>(component.collisionShapes.size());
for (int i = 0; i < NUM_SHAPES; ++i)
{ {
auto& collisionShape = component.collisionShapes[i];
if (!collisionShape.dirty) if (!collisionShape.dirty)
continue; continue;
switch (collisionShape.GetType()) switch (collisionShape.GetType())
{ {
case SHCollisionShape::Type::BOX: syncBoxShape(index, collisionShape); break; case SHCollisionShape::Type::BOX: syncBoxShape(i, collisionShape); break;
case SHCollisionShape::Type::SPHERE: syncSphereShape(index, collisionShape); break; case SHCollisionShape::Type::SPHERE: syncSphereShape(i, collisionShape); break;
default: break; default: break;
} }
// TODO(Diren): Update Material syncMaterial(i, collisionShape);
collisionShape.dirty = false; collisionShape.dirty = false;
++index;
} }
} }
@ -291,6 +319,14 @@ namespace SHADE
/* Private Function Member Definitions */ /* Private Function Member Definitions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
void SHPhysicsObject::syncMaterial(int colliderIndex, SHCollisionShape& collisionShape) const noexcept
{
auto& rp3dMaterial = rp3dBody->getCollider(colliderIndex)->getMaterial();
rp3dMaterial.setFrictionCoefficient(collisionShape.GetFriction());
rp3dMaterial.setBounciness(collisionShape.GetBounciness());
rp3dMaterial.setMassDensity(collisionShape.GetDensity());
}
void SHPhysicsObject::addBoxShape(SHCollisionShape& boxShape) const noexcept void SHPhysicsObject::addBoxShape(SHCollisionShape& boxShape) const noexcept
{ {
const rp3d::Transform OFFSETS const rp3d::Transform OFFSETS
@ -299,7 +335,7 @@ namespace SHADE
, boxShape.GetRotationOffset() , boxShape.GetRotationOffset()
}; };
const auto* BOX = reinterpret_cast<const SHBoundingBox*>(boxShape.GetShape()); const auto* BOX = reinterpret_cast<const SHBox*>(boxShape.GetShape());
rp3d::BoxShape* newBox = factory->createBoxShape(BOX->GetWorldExtents()); rp3d::BoxShape* newBox = factory->createBoxShape(BOX->GetWorldExtents());
rp3dBody->addCollider(newBox, OFFSETS); rp3dBody->addCollider(newBox, OFFSETS);
@ -307,7 +343,7 @@ namespace SHADE
void SHPhysicsObject::syncBoxShape(int index, SHCollisionShape& boxShape) const noexcept void SHPhysicsObject::syncBoxShape(int index, SHCollisionShape& boxShape) const noexcept
{ {
const auto* BOX = reinterpret_cast<const SHBoundingBox*>(boxShape.GetShape()); const auto* BOX = reinterpret_cast<const SHBox*>(boxShape.GetShape());
auto* rp3dCollider = rp3dBody->getCollider(index); auto* rp3dCollider = rp3dBody->getCollider(index);
auto* rp3dBox = reinterpret_cast<rp3d::BoxShape*>(rp3dCollider->getCollisionShape()); auto* rp3dBox = reinterpret_cast<rp3d::BoxShape*>(rp3dCollider->getCollisionShape());
@ -332,7 +368,7 @@ namespace SHADE
, sphereShape.GetRotationOffset() , sphereShape.GetRotationOffset()
}; };
const auto* SPHERE = reinterpret_cast<const SHBoundingSphere*>(sphereShape.GetShape()); const auto* SPHERE = reinterpret_cast<const SHSphere*>(sphereShape.GetShape());
rp3d::SphereShape* newSphere = factory->createSphereShape(SPHERE->GetWorldRadius()); rp3d::SphereShape* newSphere = factory->createSphereShape(SPHERE->GetWorldRadius());
rp3dBody->addCollider(newSphere, OFFSETS); rp3dBody->addCollider(newSphere, OFFSETS);
@ -340,7 +376,7 @@ namespace SHADE
void SHPhysicsObject::syncSphereShape(int index, SHCollisionShape& sphereShape) const noexcept void SHPhysicsObject::syncSphereShape(int index, SHCollisionShape& sphereShape) const noexcept
{ {
const auto* SPHERE = reinterpret_cast<const SHBoundingSphere*>(sphereShape.GetShape()); const auto* SPHERE = reinterpret_cast<const SHSphere*>(sphereShape.GetShape());
auto* rp3dCollider = rp3dBody->getCollider(index); auto* rp3dCollider = rp3dBody->getCollider(index);
auto* rp3dSphere = reinterpret_cast<rp3d::SphereShape*>(rp3dCollider->getCollisionShape()); auto* rp3dSphere = reinterpret_cast<rp3d::SphereShape*>(rp3dCollider->getCollisionShape());

View File

@ -84,17 +84,20 @@ namespace SHADE
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
EntityID entityID; EntityID entityID;
bool collidersActive; // Only used to sync with SHADE components
rp3d::PhysicsCommon* factory; rp3d::PhysicsCommon* factory;
rp3d::PhysicsWorld* world; rp3d::PhysicsWorld* world;
rp3d::RigidBody* rp3dBody; rp3d::RigidBody* rp3dBody;
rp3d::Transform prevTransform; // Cached transform for interpolation rp3d::Transform prevTransform; // Cached transform for interpolation
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Function Members */ /* Function Members */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
void syncMaterial (int colliderIndex, SHCollisionShape& collisionShape) const noexcept;
// Box Shapes // Box Shapes
void addBoxShape (SHCollisionShape& boxShape) const noexcept; void addBoxShape (SHCollisionShape& boxShape) const noexcept;

View File

@ -15,7 +15,7 @@
// Project Headers // Project Headers
#include "ECS_Base/Managers/SHEntityManager.h" #include "ECS_Base/Managers/SHEntityManager.h"
#include "Tools/SHUtilities.h" #include "Tools/Utilities/SHUtilities.h"
namespace SHADE namespace SHADE
{ {
@ -167,6 +167,7 @@ namespace SHADE
if (!COMPONENT_GROUP.rigidBodyComponent && !COMPONENT_GROUP.colliderComponent) if (!COMPONENT_GROUP.rigidBodyComponent && !COMPONENT_GROUP.colliderComponent)
{ {
destroyPhysicsObject(COMMAND.eid); destroyPhysicsObject(COMMAND.eid);
wakeAllObjects();
continue; continue;
} }
@ -176,6 +177,10 @@ namespace SHADE
physicsObject = createPhysicsObject(COMMAND.eid); physicsObject = createPhysicsObject(COMMAND.eid);
componentFunc[SHUtilities::ConvertEnum(COMMAND.command)][SHUtilities::ConvertEnum(COMMAND.component)](COMMAND, physicsObject, COMPONENT_GROUP); componentFunc[SHUtilities::ConvertEnum(COMMAND.command)][SHUtilities::ConvertEnum(COMMAND.component)](COMMAND, physicsObject, COMPONENT_GROUP);
// If any removal was done, wake all objects
if (COMMAND.command == QueueCommand::Command::REMOVE)
wakeAllObjects();
} }
} }
@ -297,5 +302,11 @@ namespace SHADE
physicsObject->RemoveCollisionShape(command.shapeIndex); physicsObject->RemoveCollisionShape(command.shapeIndex);
} }
void SHPhysicsObjectManager::wakeAllObjects() noexcept
{
for (auto& physicsObject : physicsObjects | std::views::values)
physicsObject.GetRigidBody()->setIsSleeping(false);
}
} // namespace SHADE } // namespace SHADE

View File

@ -165,6 +165,8 @@ namespace SHADE
SHPhysicsObject* createPhysicsObject (EntityID eid) noexcept; SHPhysicsObject* createPhysicsObject (EntityID eid) noexcept;
void destroyPhysicsObject (EntityID eid) noexcept; void destroyPhysicsObject (EntityID eid) noexcept;
void wakeAllObjects () noexcept;
static void addRigidBody (const QueueCommand& command, SHPhysicsObject* physicsObject, const PhysicsComponentGroup& componentGroup); static void addRigidBody (const QueueCommand& command, SHPhysicsObject* physicsObject, const PhysicsComponentGroup& componentGroup);
static void addCollider (const QueueCommand& command, SHPhysicsObject* physicsObject, const PhysicsComponentGroup& componentGroup); static void addCollider (const QueueCommand& command, SHPhysicsObject* physicsObject, const PhysicsComponentGroup& componentGroup);
static void removeRigidBody (const QueueCommand& command, SHPhysicsObject* physicsObject, const PhysicsComponentGroup& componentGroup); static void removeRigidBody (const QueueCommand& command, SHPhysicsObject* physicsObject, const PhysicsComponentGroup& componentGroup);
@ -172,6 +174,8 @@ namespace SHADE
static void addCollisionShape (const QueueCommand& command, SHPhysicsObject* physicsObject, const PhysicsComponentGroup& componentGroup); static void addCollisionShape (const QueueCommand& command, SHPhysicsObject* physicsObject, const PhysicsComponentGroup& componentGroup);
static void removeCollisionShape (const QueueCommand& command, SHPhysicsObject* physicsObject, const PhysicsComponentGroup& componentGroup); static void removeCollisionShape (const QueueCommand& command, SHPhysicsObject* physicsObject, const PhysicsComponentGroup& componentGroup);
}; };
} // namespace SHADE } // namespace SHADE

View File

@ -38,8 +38,8 @@ namespace SHADE
/*-------------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------------*/
SHVec3 gravity = SHVec3{ 0.0f, -9.81f, 0.0f }; SHVec3 gravity = SHVec3{ 0.0f, -9.81f, 0.0f };
uint16_t numVelocitySolverIterations = 15; uint16_t numVelocitySolverIterations = 10;
uint16_t numPositionSolverIterations = 8; uint16_t numPositionSolverIterations = 5;
bool sleepingEnabled = true; bool sleepingEnabled = true;
}; };

Some files were not shown because too many files have changed in this diff Show More