From 1b7ab9b1f195ac06b6f04a686e546118bde1fb4e Mon Sep 17 00:00:00 2001 From: Dynamitos Date: Mon, 1 Nov 2021 20:25:16 +0100 Subject: [PATCH] Polymorphic Map and threadpool --- CMakeLists.txt | 4 +- res/shaders/LightCulling.slang | 144 +-- src/Engine/Asset/TextureAsset.cpp | 1 + src/Engine/Asset/TextureLoader.cpp | 1 - src/Engine/Containers/Array.h | 78 +- src/Engine/Containers/List.h | 31 +- src/Engine/Containers/Map.h | 1035 ++++++++--------- src/Engine/Graphics/GraphicsResources.h | 939 +++++++-------- .../Graphics/Vulkan/VulkanGraphicsResources.h | 2 + src/Engine/Graphics/Vulkan/VulkanViewport.cpp | 12 + src/Engine/MinimalEngine.h | 4 +- src/Engine/Scene/Scene.cpp | 2 +- src/Engine/ThreadPool.cpp | 85 +- src/Engine/ThreadPool.h | 125 +- src/Engine/Window/SceneView.cpp | 170 +-- src/Engine/Window/Window.cpp | 32 +- src/Engine/Window/Window.h | 9 +- src/Engine/Window/WindowManager.cpp | 43 +- src/Engine/Window/WindowManager.h | 1 + src/Engine/main.cpp | 4 +- 20 files changed, 1442 insertions(+), 1280 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index ecd1c12..0618813 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -21,7 +21,9 @@ set(NSAM_ROOT ${EXTERNAL_ROOT}/aftermath) set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake/) set(Boost_USE_STATIC_LIBS OFF) -set(Boost_LIB_PREFIX lib) +if(WIN32) + set(Boost_LIB_PREFIX lib) +endif() set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/bin/${CMAKE_BUILD_TYPE}) #Workaround for vs, because it places artifacts into an additional subfolder diff --git a/res/shaders/LightCulling.slang b/res/shaders/LightCulling.slang index 18008e3..1f1f32d 100644 --- a/res/shaders/LightCulling.slang +++ b/res/shaders/LightCulling.slang @@ -3,18 +3,18 @@ import Common; struct ComputeShaderInput { - uint3 groupID : SV_GroupID; - uint3 groupThreadID : SV_GroupThreadID; - uint3 dispatchThreadID : SV_DispatchThreadID; - uint groupIndex : SV_GroupIndex; + uint3 groupID : SV_GroupID; + uint3 groupThreadID : SV_GroupThreadID; + uint3 dispatchThreadID : SV_DispatchThreadID; + uint groupIndex : SV_GroupIndex; }; layout(set = INDEX_VIEW_PARAMS, binding = 1) cbuffer DispatchParams { - uint3 numThreadGroups; - uint pad0; - uint3 numThreads; - uint pad1; + uint3 numThreadGroups; + uint pad0; + uint3 numThreads; + uint pad1; } layout(set = INDEX_VIEW_PARAMS, binding = 2) @@ -52,90 +52,90 @@ groupshared uint tLightList[1024]; void oAppendLight(uint lightIndex) { - uint index; - InterlockedAdd(oLightCount, 1, index); - if(index < 1024) - { - oLightList[index] = lightIndex; - } + uint index; + InterlockedAdd(oLightCount, 1, index); + if(index < 1024) + { + oLightList[index] = lightIndex; + } } void tAppendLight(uint lightIndex) { - uint index; - InterlockedAdd(tLightCount, 1, index); - if(index < 1024) - { - tLightList[index] = lightIndex; - } + uint index; + InterlockedAdd(tLightCount, 1, index); + if(index < 1024) + { + tLightList[index] = lightIndex; + } } [numthreads(BLOCK_SIZE, BLOCK_SIZE, 1)] [shader("compute")] void cullLights(ComputeShaderInput in) { - int3 texCoord = int3(in.dispatchThreadID.xy, 0); - float fDepth = depthTextureVS.Load(texCoord).r; + int3 texCoord = int3(in.dispatchThreadID.xy, 0); + float fDepth = depthTextureVS.Load(texCoord).r; - uint uDepth = asuint(fDepth); - if(in.groupIndex == 0) - { - uMinDepth = 0xffffffff; - uMaxDepth = 0x0; - oLightCount = 0; - tLightCount = 0; + uint uDepth = asuint(fDepth); + if(in.groupIndex == 0) + { + uMinDepth = 0xffffffff; + uMaxDepth = 0x0; + oLightCount = 0; + tLightCount = 0; groupFrustum = frustums[in.groupID.x + (in.groupID.y * numThreadGroups.x)]; - } + } - GroupMemoryBarrierWithGroupSync(); - InterlockedMin(uMinDepth, uDepth); - InterlockedMax(uMaxDepth, uDepth); + GroupMemoryBarrierWithGroupSync(); + InterlockedMin(uMinDepth, uDepth); + InterlockedMax(uMaxDepth, uDepth); - GroupMemoryBarrierWithGroupSync(); + GroupMemoryBarrierWithGroupSync(); - float fMinDepth = asfloat(uMinDepth); - float fMaxDepth = asfloat(uMaxDepth); + float fMinDepth = asfloat(uMinDepth); + float fMaxDepth = asfloat(uMaxDepth); - float minDepthVS = clipToView(float4(0, 0, fMinDepth, 1)).z; - float maxDepthVS = clipToView(float4(0, 0, fMaxDepth, 1)).z; - float nearClipVS = clipToView(float4(0, 0, 0, 1.0f)).z; + float minDepthVS = clipToView(float4(0, 0, fMinDepth, 1)).z; + float maxDepthVS = clipToView(float4(0, 0, fMaxDepth, 1)).z; + float nearClipVS = clipToView(float4(0, 0, 0, 1.0f)).z; - Plane minPlane = {float3(0, 0, -1), -minDepthVS}; + Plane minPlane = {float3(0, 0, -1), -minDepthVS}; for ( uint i = in.groupIndex; i < numPointLights; i += BLOCK_SIZE * BLOCK_SIZE ) - { + { PointLight light = pointLights[i]; - //TODO: why doesn't this check go through? - //if(light.insideFrustum(groupFrustum, nearClipVS, maxDepthVS)) - { - tAppendLight(i); + //TODO: why doesn't this check go through? + //if(light.insideFrustum(groupFrustum, nearClipVS, maxDepthVS)) + { + tAppendLight(i); if(!light.insidePlane(minPlane)) - { - oAppendLight(i); - } - } + { + oAppendLight(i); + } + } } - - GroupMemoryBarrierWithGroupSync(); - - if(in.groupIndex == 0) - { - InterlockedAdd(oLightIndexCounter[0], (uint)oLightCount, oLightIndexStartOffset); - oLightGrid[in.groupID.xy] = uint2(oLightIndexStartOffset, oLightCount); - - InterlockedAdd(tLightIndexCounter[0], (uint)tLightCount, tLightIndexStartOffset); - tLightGrid[in.groupID.xy] = uint2(tLightIndexStartOffset, tLightCount); - } - GroupMemoryBarrierWithGroupSync(); - - for (uint j = in.groupIndex; j < (uint)oLightCount; j += BLOCK_SIZE * BLOCK_SIZE) - { - oLightIndexList[oLightIndexStartOffset + j] = oLightList[j]; - } - // For transparent geometry. - for ( uint k = in.groupIndex; k < (uint)tLightCount; k += BLOCK_SIZE * BLOCK_SIZE ) - { - tLightIndexList[tLightIndexStartOffset + k] = tLightList[k]; - } -} \ No newline at end of file + GroupMemoryBarrierWithGroupSync(); + + if(in.groupIndex == 0) + { + InterlockedAdd(oLightIndexCounter[0], (uint)oLightCount, oLightIndexStartOffset); + oLightGrid[in.groupID.xy] = uint2(oLightIndexStartOffset, oLightCount); + + InterlockedAdd(tLightIndexCounter[0], (uint)tLightCount, tLightIndexStartOffset); + tLightGrid[in.groupID.xy] = uint2(tLightIndexStartOffset, tLightCount); + } + GroupMemoryBarrierWithGroupSync(); + + for (uint j = in.groupIndex; j < (uint)oLightCount; j += BLOCK_SIZE * BLOCK_SIZE) + { + oLightIndexList[oLightIndexStartOffset + j] = oLightList[j]; + } + + // For transparent geometry. + for ( uint k = in.groupIndex; k < (uint)tLightCount; k += BLOCK_SIZE * BLOCK_SIZE ) + { + tLightIndexList[tLightIndexStartOffset + k] = tLightList[k]; + } +} diff --git a/src/Engine/Asset/TextureAsset.cpp b/src/Engine/Asset/TextureAsset.cpp index cb804cd..590722c 100644 --- a/src/Engine/Asset/TextureAsset.cpp +++ b/src/Engine/Asset/TextureAsset.cpp @@ -34,6 +34,7 @@ void TextureAsset::load() setStatus(Status::Loading); ktxTexture2* kTexture; // TODO: consider return + std::cout << "Loading texture " << getFullPath() << std::endl; ktxTexture2_CreateFromNamedFile(getFullPath().c_str(), KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT, &kTexture); diff --git a/src/Engine/Asset/TextureLoader.cpp b/src/Engine/Asset/TextureLoader.cpp index ef2b624..ac23c07 100644 --- a/src/Engine/Asset/TextureLoader.cpp +++ b/src/Engine/Asset/TextureLoader.cpp @@ -28,7 +28,6 @@ void TextureLoader::importAsset(const std::filesystem::path& filePath) PTextureAsset asset = new TextureAsset(assetFileName.replace_extension("asset").filename().generic_string()); asset->setStatus(Asset::Status::Loading); asset->setTexture(placeholderAsset->getTexture()); - std::cout << "Loading texture " << asset->getFileName() << std::endl; AssetRegistry::get().registerTexture(asset); futures.add(std::async(std::launch::async, [this, filePath, asset] () mutable { using namespace std::chrono_literals; diff --git a/src/Engine/Containers/Array.h b/src/Engine/Containers/Array.h index 462b5b4..d23c113 100644 --- a/src/Engine/Containers/Array.h +++ b/src/Engine/Containers/Array.h @@ -112,7 +112,7 @@ namespace Seele assert(_data != nullptr); markIteratorDirty(); } - constexpr Array(size_type size, const T& value, const allocator_type& alloc = allocator_type()) + constexpr Array(size_type size, const value_type& value, const allocator_type& alloc = allocator_type()) : arraySize(size) , allocated(size) , allocator(alloc) @@ -169,21 +169,16 @@ namespace Seele { if (this != &other) { - if constexpr (std::allocator_traits::propagate_on_container_copy_assignment::value - && !std::allocator_traits::is_always_equal::value) + if constexpr (std::allocator_traits::propagate_on_container_copy_assignment::value ) { - if(allocator != other.allocator) + if (!std::allocator_traits::is_always_equal::value + && allocator != other.allocator) { deallocateArray(_data, allocated); _data = nullptr; } - } - if constexpr (std::allocator_traits::propagate_on_container_copy_assignment::value) - { allocator = other.allocator; } - else - {} if(other.arraySize > allocated) { if(_data != nullptr) @@ -203,17 +198,14 @@ namespace Seele { if (this != &other) { - if constexpr (std::allocator_traits::propagate_on_container_move_assignment::value - && !std::allocator_traits::is_always_equal::value) + if constexpr (std::allocator_traits::propagate_on_container_move_assignment::value) { - if(allocator != other.allocator) + if (!std::allocator_traits::is_always_equal::value + && allocator != other.allocator) { deallocateArray(_data, allocated); _data = nullptr; } - } - if constexpr (std::allocator_traits::propagate_on_container_move_assignment::value) - { allocator = std::move(other.allocator); } if (_data != nullptr) @@ -248,59 +240,59 @@ namespace Seele return !(*this == other); } - constexpr Iterator find(const T &item) + constexpr iterator find(const value_type &item) { for (uint32 i = 0; i < arraySize; ++i) { if (_data[i] == item) { - return Iterator(&_data[i]); + return iterator(&_data[i]); } } return endIt; } - constexpr Iterator find(T&& item) + constexpr iterator find(value_type&& item) { for (uint32 i = 0; i < arraySize; ++i) { if (_data[i] == item) { - return Iterator(&_data[i]); + return iterator(&_data[i]); } } return endIt; } - constexpr Allocator get_allocator() const + constexpr allocator_type get_allocator() const { return allocator; } - constexpr Iterator begin() const + constexpr iterator begin() const { return beginIt; } - constexpr Iterator end() const + constexpr iterator end() const { return endIt; } - constexpr ConstIterator cbegin() const + constexpr const_iterator cbegin() const { return beginIt; } - constexpr ConstIterator cend() const + constexpr const_iterator cend() const { return endIt; } - constexpr T &add(const T &item = T()) + constexpr reference add(const value_type &item = value_type()) { return addInternal(item); } - constexpr T &add(T&& item) + constexpr reference add(value_type&& item) { return addInternal(std::forward(item)); } - constexpr T &addUnique(const T &item = T()) + constexpr reference addUnique(const value_type &item = value_type()) { - Iterator it; + iterator it; if((it = std::move(find(item))) != endIt) { return *it; @@ -308,7 +300,7 @@ namespace Seele return addInternal(item); } template - constexpr T &emplace(args... arguments) + constexpr reference emplace(args... arguments) { if (arraySize == allocated) { @@ -316,10 +308,8 @@ namespace Seele allocated = calculateGrowth(newSize); T *tempArray = allocateArray(allocated); assert(tempArray != nullptr); - for (size_type i = 0; i < arraySize; ++i) - { - tempArray[i] = std::move(_data[i]); - } + + std::uninitialized_move(begin(), end(), Iterator(tempArray)); deallocateArray(_data, arraySize); _data = tempArray; } @@ -327,7 +317,7 @@ namespace Seele markIteratorDirty(); return _data[arraySize - 1]; } - constexpr void remove(Iterator it, bool keepOrder = true) + constexpr void remove(iterator it, bool keepOrder = true) { remove(it - beginIt, keepOrder); } @@ -351,7 +341,7 @@ namespace Seele { resizeInternal(newSize, std::move(T())); } - constexpr void resize(size_type newSize, const T& value) + constexpr void resize(size_type newSize, const value_type& value) { resizeInternal(newSize, value); } @@ -367,11 +357,11 @@ namespace Seele allocated = 0; markIteratorDirty(); } - inline size_type indexOf(Iterator iterator) + inline size_type indexOf(iterator iterator) { return iterator - beginIt; } - inline size_type indexOf(ConstIterator iterator) const + inline size_type indexOf(const_iterator iterator) const { return iterator.p - beginIt.p; } @@ -395,12 +385,18 @@ namespace Seele { return allocated; } - inline T *data() const + inline pointer data() const { return _data; } - inline T &back() const + inline reference front() const { + assert(arraySize > 0); + return _data[0]; + } + inline reference back() const + { + assert(arraySize > 0); return _data[arraySize - 1]; } void pop() @@ -408,12 +404,12 @@ namespace Seele arraySize--; markIteratorDirty(); } - constexpr inline T &operator[](size_type index) + constexpr inline reference operator[](size_type index) { assert(index < arraySize); return _data[index]; } - constexpr inline const T &operator[](size_type index) const + constexpr inline const reference operator[](size_type index) const { assert(index < arraySize); return _data[index]; diff --git a/src/Engine/Containers/List.h b/src/Engine/Containers/List.h index 354268b..f6a90a3 100644 --- a/src/Engine/Containers/List.h +++ b/src/Engine/Containers/List.h @@ -1,6 +1,6 @@ #pragma once #include "MinimalEngine.h" -#include +#include namespace Seele { @@ -187,11 +187,11 @@ public: return *this; } - T &front() + reference front() { return root->data; } - T &back() + reference back() { return tail->prev->data; } @@ -218,7 +218,7 @@ public: root = allocateNode(); tail = root; } - tail->data = value; + initializeNode(tail, value); Node *newTail = allocateNode(); newTail->prev = tail; newTail->next = nullptr; @@ -236,7 +236,7 @@ public: root = allocateNode(); tail = root; } - tail->data = std::move(value); + initializeNode(tail, std::move(value)); Node *newTail = allocateNode(); newTail->prev = tail; newTail->next = nullptr; @@ -247,6 +247,13 @@ public: _size++; return insertedElement; } + // front + popFront + value_type&& retrieve() + { + auto&& temp = std::move(root->data); + popFront(); + return std::move(temp); + } iterator remove(iterator pos) { _size--; @@ -299,7 +306,7 @@ public: } Node *tmp = pos.node->prev; Node *newNode = allocateNode(); - newNode->data = value; + initializeNode(newNode, value); tmp->next = newNode; newNode->prev = tmp; newNode->next = pos.node; @@ -346,10 +353,20 @@ private: Node* allocateNode() { Node* node = allocator.allocate(1); - std::memset(node, 0, sizeof(Node)); assert(node != nullptr); + node->prev = nullptr; + node->next = nullptr; return node; } + template + void initializeNode(Node* node, Type&& data) + { + std::allocator_traits::construct(allocator, + node, + node->prev, + node->next, + std::forward(data)); + } void deallocateNode(Node* node) { allocator.deallocate(node, 1); diff --git a/src/Engine/Containers/Map.h b/src/Engine/Containers/Map.h index 54e2888..c7808f1 100644 --- a/src/Engine/Containers/Map.h +++ b/src/Engine/Containers/Map.h @@ -8,548 +8,541 @@ template struct Pair { public: - Pair() - : key(K()), value(V()) - {} - template - explicit Pair(KeyType&& key) - : key(key), value(V()) - {} - template - explicit Pair(KeyType&& key, ValueType&& value) - : key(std::move(key)), value(std::move(value)) - {} - K key; - V value; + Pair() + : key(K()), value(V()) + {} + Pair(const Pair& other) = default; + Pair(Pair&& other) = default; + ~Pair(){} + Pair& operator=(const Pair& other) = default; + Pair& operator=(Pair&& other) = default; + template + explicit Pair(KeyType&& key) + : key(std::forward(key)), value(V()) + {} + template + explicit Pair(KeyType&& key, ValueType&& value) + : key(std::forward(key)), value(std::forward(value)) + {} + K key; + V value; }; -template +template , + typename Allocator = std::pmr::polymorphic_allocator>> struct Map { private: - struct Node - { - Node *leftChild; - Node *rightChild; - Pair pair; - Node() - : leftChild(nullptr), rightChild(nullptr), pair() - { - } - template - explicit Node(KeyType&& key, ValueType&& value) - : leftChild(nullptr), rightChild(nullptr), pair(key, value) - { - } - Node(const Node& other) - : pair(other.pair.key, other.pair.value) - { - if(other.leftChild != nullptr) - { - leftChild = new Node(*other.leftChild); - } - if(other.rightChild != nullptr) - { - rightChild = new Node(*other.rightChild); - } - } - Node(Node&& other) - : leftChild(std::move(other.leftChild)), rightChild(std::move(other.rightChild)) - { - } - ~Node() - { - if (leftChild != nullptr) - { - delete leftChild; - } - if (rightChild != nullptr) - { - delete rightChild; - } - } - Node& operator=(const Node& other) - { - if(this != &other) - { - if(leftChild != nullptr) - { - delete leftChild; - } - if(rightChild != nullptr) - { - delete rightChild; - } - if(other.leftChild != nullptr) - { - leftChild = new Node(*other.leftChild); - } - if(other.rightChild != nullptr) - { - rightChild = new Node(*other.rightChild); - } - } - } - Node& operator=(Node&& other) - { - if(this != &other) - { - if(leftChild != nullptr) - { - delete leftChild; - } - if(rightChild != nullptr) - { - delete rightChild; - } - leftChild = std::move(other.leftChild); - rightChild = std::move(other.rightChild); - } - return *this; - } - }; - + struct Node + { + Node *leftChild; + Node *rightChild; + Pair pair; + Node() + : leftChild(nullptr), rightChild(nullptr), pair() + { + } + Node(const Node& other) = default; + Node(Node&& other) = default; + Node& operator=(const Node& other) = default; + Node& operator=(Node&& other) = default; + Node(K key) + : leftChild(nullptr) + , rightChild(nullptr) + , pair(std::move(key)) + { + } + ~Node() + { + } + }; + using NodeAlloc = std::allocator_traits::template rebind_alloc; public: - Map() - : root(nullptr) - , beginIt(nullptr) - , endIt(nullptr) - , iteratorsDirty(false) - , _size(0) - { - } - Map(const Map& other) - : root(new Node(*other.root)) - , _size(other._size) - { - refreshIterators(); - } - Map(Map&& other) - : root(std::move(other.root)) - , _size(other._size) - { - refreshIterators(); - } - ~Map() - { - delete root; - } - Map& operator=(const Map& other) - { - if(this != &other) - { - if(root != nullptr) - { - delete root; - } - root = new Node(*other.root); - _size = other.size; - markIteratorDirty(); - } - return *this; - } - Map& operator=(Map&& other) - { - if(this != &other) - { - if(root != nullptr) - { - delete root; - } - root = new Node(std::move(*other.root)); - _size = std::move(other._size); - markIteratorDirty(); - } - return *this; - } - class Iterator - { - public: - using iterator_category = std::bidirectional_iterator_tag; - using value_type = Pair; - using difference_type = std::ptrdiff_t; - using reference = Pair&; - using pointer = Pair*; + template + class IteratorBase + { + public: + using iterator_category = std::bidirectional_iterator_tag; + using value_type = PairType; + using difference_type = std::ptrdiff_t; + using reference = PairType&; + using pointer = PairType*; - Iterator(Node *x = nullptr) - : node(x) - { - } - Iterator(Node *x, Array &&beginIt) - : node(x), traversal(std::move(beginIt)) - { - } - Iterator(const Iterator &i) - : node(i.node), traversal(i.traversal) - { - } - Iterator(Iterator&& i) - : node(std::move(i.node)), traversal(std::move(i.traversal)) - { - } - Iterator& operator=(const Iterator& other) - { - if(this != &other) - { - node = other.node; // No copy, since no ownership - traversal = other.traversal; - } - return *this; - } - Iterator& operator=(Iterator&& other) - { - if(this != &other) - { - node = std::move(other.node); - traversal = std::move(other.traversal); - } - return *this; - } - reference operator*() const - { - return node->pair; - } - pointer operator->() const - { - return &node->pair; - } - inline bool operator!=(const Iterator &other) - { - return node != other.node; - } - inline bool operator==(const Iterator &other) - { - return node == other.node; - } - Iterator &operator++() - { - node = node->rightChild; - while (node != nullptr && node->leftChild != nullptr) - { - traversal.add(node); - node = node->leftChild; - } - if (node == nullptr && traversal.size() > 0) - { - node = traversal.back(); - traversal.pop(); - } - return *this; - } - Iterator &operator--() - { - node = node->leftChild; - while (node != nullptr && node->rightchild != nullptr) - { - traversal.add(node); - node = node->rightChild; - } - if (node == nullptr && traversal.size() > 0) - { - node = traversal.back(); - traversal.pop(); - } - return *this; - } - Iterator operator--(int) - { - Iterator tmp(*this); - --*this; - return tmp; - } - Iterator operator++(int) - { - Iterator tmp(*this); - ++*this; - return tmp; - } + IteratorBase(Node *x = nullptr) + : node(x) + { + } + IteratorBase(Node *x, Array &&beginIt) + : node(x), traversal(std::move(beginIt)) + { + } + IteratorBase(const IteratorBase &i) + : node(i.node), traversal(i.traversal) + { + } + IteratorBase(IteratorBase&& i) + : node(std::move(i.node)), traversal(std::move(i.traversal)) + { + } + IteratorBase& operator=(const IteratorBase& other) + { + if(this != &other) + { + node = other.node; // No copy, since no ownership + traversal = other.traversal; + } + return *this; + } + IteratorBase& operator=(IteratorBase&& other) + { + if(this != &other) + { + node = std::move(other.node); + traversal = std::move(other.traversal); + } + return *this; + } + reference operator*() const + { + return node->pair; + } + pointer operator->() const + { + return &node->pair; + } + inline bool operator!=(const IteratorBase &other) + { + return node != other.node; + } + inline bool operator==(const IteratorBase &other) + { + return node == other.node; + } + IteratorBase &operator++() + { + node = node->rightChild; + while (node != nullptr && node->leftChild != nullptr) + { + traversal.add(node); + node = node->leftChild; + } + if (node == nullptr && traversal.size() > 0) + { + node = traversal.back(); + traversal.pop(); + } + return *this; + } + IteratorBase &operator--() + { + node = node->leftChild; + while (node != nullptr && node->rightchild != nullptr) + { + traversal.add(node); + node = node->rightChild; + } + if (node == nullptr && traversal.size() > 0) + { + node = traversal.back(); + traversal.pop(); + } + return *this; + } + IteratorBase operator--(int) + { + IteratorBase tmp(*this); + --*this; + return tmp; + } + IteratorBase operator++(int) + { + IteratorBase tmp(*this); + ++*this; + return tmp; + } - private: - Node *node; - Array traversal; - }; - inline V &operator[](const K& key) - { - root = splay(root, key); - markIteratorDirty(); - if (root == nullptr || root->pair.key < key || key < root->pair.key) - { - root = insert(root, key); - _size++; - } - return root->pair.value; - } - inline V &operator[](K&& key) - { - root = splay(root, std::move(key)); - markIteratorDirty(); - if (root == nullptr || root->pair.key < key || key < root->pair.key) - { - root = insert(root, std::move(key)); - _size++; - } - return root->pair.value; - } - Iterator find(const K& key) - { - root = splay(root, key); - markIteratorDirty(); - if (root == nullptr || root->pair.key != key) - { - return endIt; - } - return Iterator(root); - } - Iterator find(K&& key) - { - root = splay(root, std::move(key)); - markIteratorDirty(); - if (root == nullptr || root->pair.key != key) - { - return endIt; - } - return Iterator(root); - } - Iterator erase(const K& key) - { - root = remove(root, key); - markIteratorDirty(); - return Iterator(root); - } - Iterator erase(K&& key) - { - root = remove(root, std::move(key)); - markIteratorDirty(); - return Iterator(root); - } - void clear() - { - delete root; - root = nullptr; - _size = 0; - markIteratorDirty(); - } - bool exists(K&& key) - { - return find(std::forward(key)) != endIt; - } - Iterator begin() - { - if(iteratorsDirty) - { - refreshIterators(); - } - return beginIt; - } - Iterator end() - { - if(iteratorsDirty) - { - refreshIterators(); - } - return endIt; - } - Iterator begin() const - { - if(iteratorsDirty) - { - return calcBeginIterator(); - } - return beginIt; - } - Iterator end() const - { - if(iteratorsDirty) - { - return calcEndIterator(); - } - return endIt; - } - bool empty() const - { - return root == nullptr; - } - uint32 size() const - { - return _size; - } + private: + Node *node; + Array traversal; + }; + using Iterator = IteratorBase>; + using ConstIterator = IteratorBase>; + + using key_type = K; + using mapped_type = V; + using value_type = Pair; + using allocator_type = Allocator; + using size_type = std::size_t; + using difference_type = std::ptrdiff_t; + using reference = value_type&; + using const_reference = const value_type&; + using pointer = std::allocator_traits::pointer; + using const_pointer = std::allocator_traits::const_pointer; + + using iterator = Iterator; + using const_iterator = ConstIterator; + using reverse_iterator = std::reverse_iterator; + using const_reverse_iterator = std::reverse_iterator; + + Map() + : root(nullptr) + , beginIt(nullptr) + , endIt(nullptr) + , iteratorsDirty(false) + , _size(0) + , comp(Compare()) + { + } + explicit Map(const Compare& comp, + const Allocator& alloc = Allocator()) + : nodeContainer(alloc) + , root(nullptr) + , beginIt(nullptr) + , endIt(nullptr) + , iteratorsDirty(false) + , _size(0) + , comp(comp) + { + } + explicit Map(const Allocator& alloc) + : nodeContainer(alloc) + , root(nullptr) + , beginIt(nullptr) + , endIt(nullptr) + , iteratorsDirty(false) + , _size(0) + , comp(Compare()) + { + } + Map(const Map& other) + : nodeContainer(other.nodeContainer) + , _size(other._size) + , comp(other.comp) + { + root = &nodeContainer[nodeContainer.indexOf(other.root)]; + refreshIterators(); + } + Map(Map&& other) + : nodeContainer(other.nodeContainer) + , _size(std::move(other._size)) + , comp(std::move(other.comp)) + { + root = &nodeContainer[nodeContainer.indexOf(other.root)]; + refreshIterators(); + } + ~Map() + { + } + Map& operator=(const Map& other) + { + if(this != &other) + { + nodeContainer = other.nodeContainer; + root = &nodeContainer[nodeContainer.indexOf(other.root)]; + _size = other._size; + comp = other.comp; + refreshIterators(); + } + return *this; + } + Map& operator=(Map&& other) + { + if(this != &other) + { + nodeContainer = std::move(other.nodeContainer); + root = &nodeContainer[nodeContainer.indexOf(other.root)]; + _size = std::move(other._size); + comp = std::move(other.comp); + refreshIterators(); + } + return *this; + } + inline mapped_type& operator[](const key_type& key) + { + root = splay(root, key); + refreshIterators(); + if (root == nullptr || comp(root->pair.key, key) || comp(key, root->pair.key)) + { + root = insert(root, key); + _size++; + } + return root->pair.value; + } + inline mapped_type& operator[](key_type&& key) + { + root = splay(root, std::move(key)); + refreshIterators(); + if (root == nullptr || comp(root->pair.key, key) || comp(key, root->pair.key)) + { + root = insert(root, std::move(key)); + _size++; + } + return root->pair.value; + } + iterator find(const key_type& key) + { + root = splay(root, key); + refreshIterators(); + if (root == nullptr || comp(root->pair.key, key) || comp(key, root->pair.key)) + { + return endIt; + } + return iterator(root); + } + iterator find(key_type&& key) + { + root = splay(root, std::move(key)); + refreshIterators(); + if (root == nullptr || comp(root->pair.key, key) || comp(key, root->pair.key)) + { + return endIt; + } + return iterator(root); + } + iterator erase(const key_type& key) + { + root = remove(root, key); + refreshIterators(); + return iterator(root); + } + iterator erase(K&& key) + { + root = remove(root, std::move(key)); + refreshIterators(); + return iterator(root); + } + void clear() + { + nodeContainer.clear(); + root = nullptr; + _size = 0; + refreshIterators(); + } + bool exists(key_type&& key) + { + return find(std::forward(key)) != endIt; + } + iterator begin() + { + if(iteratorsDirty) + { + refreshIterators(); + } + return beginIt; + } + iterator end() + { + if(iteratorsDirty) + { + refreshIterators(); + } + return endIt; + } + iterator begin() const + { + if(iteratorsDirty) + { + return calcBeginIterator(); + } + return beginIt; + } + iterator end() const + { + if(iteratorsDirty) + { + return calcEndIterator(); + } + return endIt; + } + bool empty() const + { + return nodeContainer.empty(); + } + size_type size() const + { + return _size; + } private: - void markIteratorDirty() - { - iteratorsDirty = true; - } - void refreshIterators() - { - beginIt = calcBeginIterator(); - endIt = calcEndIterator(); - iteratorsDirty = false; - } - inline Iterator calcBeginIterator() const - { - Node *beginNode = root; - if (root == nullptr) - { - return Iterator(nullptr); - } - else - { - Array beginTraversal; - while (beginNode != nullptr) - { - beginTraversal.add(beginNode); - beginNode = beginNode->leftChild; - } - beginNode = beginTraversal.back(); - beginTraversal.pop(); - return Iterator(beginNode, std::move(beginTraversal)); - } - } - inline Iterator calcEndIterator() const - { - Node *endNode = root; - if (root == nullptr) - { - return Iterator(nullptr); - } - else - { - Array endTraversal; - while (endNode != nullptr) - { - endTraversal.add(endNode); - endNode = endNode->rightChild; - } - return Iterator(endNode, std::move(endTraversal)); - } - } - Node *root; - Iterator beginIt; - Iterator endIt; - bool iteratorsDirty; - uint32 _size; - Node *rotateRight(Node *node) - { - Node *y = node->leftChild; - node->leftChild = y->rightChild; - y->rightChild = node; - return y; - } - Node *rotateLeft(Node *node) - { - Node *y = node->rightChild; - node->rightChild = y->leftChild; - y->leftChild = node; - return y; - } - template - Node *insert(Node *r, KeyType&& key) - { - if (r == nullptr) - { - return new Node(std::forward(key), V()); - } - r = splay(r, key); + void markIteratorDirty() + { + iteratorsDirty = true; + } + void refreshIterators() + { + beginIt = calcBeginIterator(); + endIt = calcEndIterator(); + iteratorsDirty = false; + } + inline Iterator calcBeginIterator() const + { + Node *beginNode = root; + if (root == nullptr) + { + return Iterator(nullptr); + } + else + { + Array beginTraversal; + while (beginNode != nullptr) + { + beginTraversal.add(beginNode); + beginNode = beginNode->leftChild; + } + beginNode = beginTraversal.back(); + beginTraversal.pop(); + return Iterator(beginNode, std::move(beginTraversal)); + } + } + inline Iterator calcEndIterator() const + { + Node *endNode = root; + if (root == nullptr) + { + return Iterator(nullptr); + } + else + { + Array endTraversal; + while (endNode != nullptr) + { + endTraversal.add(endNode); + endNode = endNode->rightChild; + } + return Iterator(endNode, std::move(endTraversal)); + } + } + Array nodeContainer; + Node *root; + Iterator beginIt; + Iterator endIt; + bool iteratorsDirty; + uint32 _size; + Compare comp; + Node *rotateRight(Node *node) + { + Node *y = node->leftChild; + node->leftChild = y->rightChild; + y->rightChild = node; + return y; + } + Node *rotateLeft(Node *node) + { + Node *y = node->rightChild; + node->rightChild = y->leftChild; + y->leftChild = node; + return y; + } + template + Node *insert(Node *r, KeyType&& key) + { + if (r == nullptr) + { + return &nodeContainer.emplace(std::forward(key)); + } + r = splay(r, key); - if (!(r->pair.key < key || key < r->pair.key)) - return r; + if (!(comp(r->pair.key, key) || comp(key, r->pair.key))) + return r; - Node *newNode = new Node(std::forward(key), V()); + Node *newNode = &nodeContainer.emplace(std::forward(key)); - if (key < r->pair.key) - { - newNode->rightChild = r; - newNode->leftChild = r->leftChild; - r->leftChild = nullptr; - } - else - { - newNode->leftChild = r; - newNode->rightChild = r->rightChild; - r->rightChild = nullptr; - } - return newNode; - } - template - Node *remove(Node *r, KeyType&& key) - { - Node *temp; - if (!r) - return nullptr; + if (comp(key, r->pair.key)) + { + newNode->rightChild = r; + newNode->leftChild = r->leftChild; + r->leftChild = nullptr; + } + else + { + newNode->leftChild = r; + newNode->rightChild = r->rightChild; + r->rightChild = nullptr; + } + return newNode; + } + template + Node *remove(Node *r, KeyType&& key) + { + Node *temp; + if (!r) + return nullptr; - r = splay(r, key); + r = splay(r, key); - if (r->pair.key < key || key < r->pair.key) - return r; + if (comp(r->pair.key, key) || comp(key, r->pair.key)) + return r; - if (!r->leftChild) - { - temp = r; - r = r->rightChild; - } - else - { - temp = r; + if (!r->leftChild) + { + temp = r; + r = r->rightChild; + } + else + { + temp = r; - r = splay(r->leftChild, key); - r->rightChild = temp->rightChild; - } - temp->leftChild = nullptr; - temp->rightChild = nullptr; - _size--; - delete temp; - return r; - } - template - Node *splay(Node *r, KeyType&& key) - { - if (r == nullptr || !(r->pair.key < key || key < r->pair.key)) - { - return r; - } + r = splay(r->leftChild, key); + r->rightChild = temp->rightChild; + } + temp->leftChild = nullptr; + temp->rightChild = nullptr; + _size--; + delete temp; + return r; + } + template + Node *splay(Node *r, KeyType&& key) + { + if (r == nullptr || !(comp(r->pair.key, key) || comp(key, r->pair.key))) + { + return r; + } - if (key < r->pair.key) - { - if (r->leftChild == nullptr) - return r; + if (comp(key, r->pair.key)) + { + if (r->leftChild == nullptr) + return r; - if (key < r->leftChild->pair.key) - { - r->leftChild->leftChild = splay(r->leftChild->leftChild, key); + if (comp(key, r->leftChild->pair.key)) + { + r->leftChild->leftChild = splay(r->leftChild->leftChild, key); - r = rotateRight(r); - } - else if (r->leftChild->pair.key < key) - { - r->leftChild->rightChild = splay(r->leftChild->rightChild, key); + r = rotateRight(r); + } + else if (comp(r->leftChild->pair.key, key)) + { + r->leftChild->rightChild = splay(r->leftChild->rightChild, key); - if (r->leftChild->rightChild != nullptr) - { - r->leftChild = rotateLeft(r->leftChild); - } - } - return (r->leftChild == nullptr) ? r : rotateRight(r); - } - else - { - if (r->rightChild == nullptr) - return r; + if (r->leftChild->rightChild != nullptr) + { + r->leftChild = rotateLeft(r->leftChild); + } + } + return (r->leftChild == nullptr) ? r : rotateRight(r); + } + else + { + if (r->rightChild == nullptr) + return r; - if (key < r->rightChild->pair.key) - { - r->rightChild->leftChild = splay(r->rightChild->leftChild, key); + if (comp(key, r->rightChild->pair.key)) + { + r->rightChild->leftChild = splay(r->rightChild->leftChild, key); - if (r->rightChild->leftChild != nullptr) - { - r->rightChild = rotateRight(r->rightChild); - } - } - else if (r->rightChild->pair.key < key) - { - r->rightChild->rightChild = splay(r->rightChild->rightChild, key); - r = rotateLeft(r); - } - return (r->rightChild == nullptr) ? r : rotateLeft(r); - } - } + if (r->rightChild->leftChild != nullptr) + { + r->rightChild = rotateRight(r->rightChild); + } + } + else if (comp(r->rightChild->pair.key, key)) + { + r->rightChild->rightChild = splay(r->rightChild->rightChild, key); + r = rotateLeft(r); + } + return (r->rightChild == nullptr) ? r : rotateLeft(r); + } + } }; } // namespace Seele \ No newline at end of file diff --git a/src/Engine/Graphics/GraphicsResources.h b/src/Engine/Graphics/GraphicsResources.h index 265c2bf..ecd3d4b 100644 --- a/src/Engine/Graphics/GraphicsResources.h +++ b/src/Engine/Graphics/GraphicsResources.h @@ -24,9 +24,9 @@ DECLARE_REF(Graphics) class SamplerState { public: - virtual ~SamplerState() - { - } + virtual ~SamplerState() + { + } }; DEFINE_REF(SamplerState) @@ -37,48 +37,48 @@ DEFINE_REF(Shader) class VertexShader { public: - VertexShader() {} - virtual ~VertexShader() {} + VertexShader() {} + virtual ~VertexShader() {} }; DEFINE_REF(VertexShader) class ControlShader { public: - ControlShader() {} - virtual ~ControlShader() {} - uint32 getNumPatches() const { return numPatchPoints; } + ControlShader() {} + virtual ~ControlShader() {} + uint32 getNumPatches() const { return numPatchPoints; } protected: - uint32 numPatchPoints; + uint32 numPatchPoints; }; DEFINE_REF(ControlShader) class EvaluationShader { public: - EvaluationShader() {} - virtual ~EvaluationShader() {} + EvaluationShader() {} + virtual ~EvaluationShader() {} }; DEFINE_REF(EvaluationShader) class GeometryShader { public: - GeometryShader() {} - virtual ~GeometryShader() {} + GeometryShader() {} + virtual ~GeometryShader() {} }; DEFINE_REF(GeometryShader) class FragmentShader { public: - FragmentShader() {} - virtual ~FragmentShader() {} + FragmentShader() {} + virtual ~FragmentShader() {} }; DEFINE_REF(FragmentShader) class ComputeShader { public: - ComputeShader() {} - virtual ~ComputeShader() {} + ComputeShader() {} + virtual ~ComputeShader() {} }; DEFINE_REF(ComputeShader) @@ -86,89 +86,89 @@ DEFINE_REF(ComputeShader) //using the type parameters used to generate it struct ShaderPermutation { - RenderPassType passType; - char vertexInputName[15]; - char materialName[16]; - //TODO: lightmapping etc + RenderPassType passType; + char vertexInputName[15]; + char materialName[16]; + //TODO: lightmapping etc }; //Hashed ShaderPermutation for fast lookup struct PermutationId { - uint32 hash; - PermutationId() - {} - PermutationId(ShaderPermutation permutation) - { - boost::crc_32_type result; - result.process_bytes(&permutation, sizeof(ShaderPermutation)); - hash = result.checksum(); - } - friend inline bool operator==(const PermutationId& lhs, const PermutationId& rhs) - { - return lhs.hash == rhs.hash; - } - friend inline bool operator!=(const PermutationId& lhs, const PermutationId& rhs) - { - return lhs.hash != rhs.hash; - } - friend inline bool operator<(const PermutationId& lhs, const PermutationId& rhs) - { - return lhs.hash < rhs.hash; - } - friend inline bool operator>(const PermutationId& lhs, const PermutationId& rhs) - { - return lhs.hash > rhs.hash; - } + uint32 hash; + PermutationId() + {} + PermutationId(ShaderPermutation permutation) + { + boost::crc_32_type result; + result.process_bytes(&permutation, sizeof(ShaderPermutation)); + hash = result.checksum(); + } + friend inline bool operator==(const PermutationId& lhs, const PermutationId& rhs) + { + return lhs.hash == rhs.hash; + } + friend inline bool operator!=(const PermutationId& lhs, const PermutationId& rhs) + { + return lhs.hash != rhs.hash; + } + friend inline bool operator<(const PermutationId& lhs, const PermutationId& rhs) + { + return lhs.hash < rhs.hash; + } + friend inline bool operator>(const PermutationId& lhs, const PermutationId& rhs) + { + return lhs.hash > rhs.hash; + } }; struct ShaderCollection { - PermutationId id; - //PVertexDeclaration vertexDeclaration; - PVertexShader vertexShader; - PControlShader controlShader; - PEvaluationShader evalutionShader; - PGeometryShader geometryShader; - PFragmentShader fragmentShader; + PermutationId id; + //PVertexDeclaration vertexDeclaration; + PVertexShader vertexShader; + PControlShader controlShader; + PEvaluationShader evalutionShader; + PGeometryShader geometryShader; + PFragmentShader fragmentShader; }; class ShaderMap { public: - ShaderMap(); - ~ShaderMap(); - const ShaderCollection* findShaders(PermutationId&& id) const; - ShaderCollection& createShaders( - PGraphics graphics, - RenderPassType passName, - PMaterialAsset material, - VertexInputType* vertexInput, - bool bPositionOnly); + ShaderMap(); + ~ShaderMap(); + const ShaderCollection* findShaders(PermutationId&& id) const; + ShaderCollection& createShaders( + PGraphics graphics, + RenderPassType passName, + PMaterialAsset material, + VertexInputType* vertexInput, + bool bPositionOnly); private: - Array shaders; + Array shaders; }; DEFINE_REF(ShaderMap) class DescriptorBinding { public: - DescriptorBinding() - : binding(0), descriptorType(SE_DESCRIPTOR_TYPE_MAX_ENUM), descriptorCount(0x7fff), shaderStages(SE_SHADER_STAGE_ALL) - { - } - DescriptorBinding(const DescriptorBinding &other) - : binding(other.binding), descriptorType(other.descriptorType), descriptorCount(other.descriptorCount), shaderStages(other.shaderStages) - { - } - void operator=(const DescriptorBinding &other) - { - binding = other.binding; - descriptorType = other.descriptorType; - descriptorCount = other.descriptorCount; - shaderStages = other.shaderStages; - } - uint32_t binding; - SeDescriptorType descriptorType; - uint32_t descriptorCount; - SeShaderStageFlags shaderStages; + DescriptorBinding() + : binding(0), descriptorType(SE_DESCRIPTOR_TYPE_MAX_ENUM), descriptorCount(0x7fff), shaderStages(SE_SHADER_STAGE_ALL) + { + } + DescriptorBinding(const DescriptorBinding &other) + : binding(other.binding), descriptorType(other.descriptorType), descriptorCount(other.descriptorCount), shaderStages(other.shaderStages) + { + } + void operator=(const DescriptorBinding &other) + { + binding = other.binding; + descriptorType = other.descriptorType; + descriptorCount = other.descriptorCount; + shaderStages = other.shaderStages; + } + uint32_t binding; + SeDescriptorType descriptorType; + uint32_t descriptorCount; + SeShaderStageFlags shaderStages; }; DEFINE_REF(DescriptorBinding) @@ -176,10 +176,10 @@ DECLARE_REF(DescriptorSet) class DescriptorAllocator { public: - DescriptorAllocator() {} - virtual ~DescriptorAllocator() {} - virtual void allocateDescriptorSet(PDescriptorSet &descriptorSet) = 0; - virtual void reset() = 0; + DescriptorAllocator() {} + virtual ~DescriptorAllocator() {} + virtual void allocateDescriptorSet(PDescriptorSet &descriptorSet) = 0; + virtual void reset() = 0; }; DEFINE_REF(DescriptorAllocator) DECLARE_REF(UniformBuffer) @@ -188,119 +188,119 @@ DECLARE_REF(Texture) class DescriptorSet { public: - virtual ~DescriptorSet() {} - virtual void writeChanges() = 0; - virtual void updateBuffer(uint32 binding, PUniformBuffer uniformBuffer) = 0; - virtual void updateBuffer(uint32 binding, PStructuredBuffer structuredBuffer) = 0; - virtual void updateSampler(uint32 binding, PSamplerState samplerState) = 0; - virtual void updateTexture(uint32 binding, PTexture texture, PSamplerState samplerState = nullptr) = 0; - virtual bool operator<(PDescriptorSet other) = 0; + virtual ~DescriptorSet() {} + virtual void writeChanges() = 0; + virtual void updateBuffer(uint32 binding, PUniformBuffer uniformBuffer) = 0; + virtual void updateBuffer(uint32 binding, PStructuredBuffer structuredBuffer) = 0; + virtual void updateSampler(uint32 binding, PSamplerState samplerState) = 0; + virtual void updateTexture(uint32 binding, PTexture texture, PSamplerState samplerState = nullptr) = 0; + virtual bool operator<(PDescriptorSet other) = 0; - virtual uint32 getSetIndex() const = 0; + virtual uint32 getSetIndex() const = 0; }; DEFINE_REF(DescriptorSet) class DescriptorLayout { public: - DescriptorLayout(const std::string& name) - : setIndex(0) - , name(name) - { - } - virtual ~DescriptorLayout() {} - DescriptorLayout& operator=(const DescriptorLayout &other) - { - if(this != &other) - { - descriptorBindings.resize(other.descriptorBindings.size()); - for(uint32 i = 0; i < descriptorBindings.size(); ++i) - { - descriptorBindings[i] = other.descriptorBindings[i]; - } - } - return *this; - } - virtual void create() = 0; - virtual void addDescriptorBinding(uint32 binding, SeDescriptorType type, uint32 arrayCount = 1); - virtual void reset(); - virtual PDescriptorSet allocateDescriptorSet(); - const Array &getBindings() const { return descriptorBindings; } - inline uint32 getSetIndex() const { return setIndex; } + DescriptorLayout(const std::string& name) + : setIndex(0) + , name(name) + { + } + virtual ~DescriptorLayout() {} + DescriptorLayout& operator=(const DescriptorLayout &other) + { + if(this != &other) + { + descriptorBindings.resize(other.descriptorBindings.size()); + for(uint32 i = 0; i < descriptorBindings.size(); ++i) + { + descriptorBindings[i] = other.descriptorBindings[i]; + } + } + return *this; + } + virtual void create() = 0; + virtual void addDescriptorBinding(uint32 binding, SeDescriptorType type, uint32 arrayCount = 1); + virtual void reset(); + virtual PDescriptorSet allocateDescriptorSet(); + const Array &getBindings() const { return descriptorBindings; } + inline uint32 getSetIndex() const { return setIndex; } protected: - Array descriptorBindings; - PDescriptorAllocator allocator; - std::mutex allocatorLock; - uint32 setIndex; - std::string name; - friend class PipelineLayout; - friend class DescriptorAllocator; + Array descriptorBindings; + PDescriptorAllocator allocator; + std::mutex allocatorLock; + uint32 setIndex; + std::string name; + friend class PipelineLayout; + friend class DescriptorAllocator; }; DEFINE_REF(DescriptorLayout) class PipelineLayout { public: - PipelineLayout() {} - virtual ~PipelineLayout() {} - virtual void create() = 0; - virtual void reset() = 0; - void addDescriptorLayout(uint32 setIndex, PDescriptorLayout layout); - void addPushConstants(const SePushConstantRange &pushConstants); - virtual uint32 getHash() const = 0; + PipelineLayout() {} + virtual ~PipelineLayout() {} + virtual void create() = 0; + virtual void reset() = 0; + void addDescriptorLayout(uint32 setIndex, PDescriptorLayout layout); + void addPushConstants(const SePushConstantRange &pushConstants); + virtual uint32 getHash() const = 0; protected: - Array descriptorSetLayouts; - Array pushConstants; + Array descriptorSetLayouts; + Array pushConstants; }; DEFINE_REF(PipelineLayout) struct QueueFamilyMapping { - uint32 graphicsFamily; - uint32 computeFamily; - uint32 transferFamily; - uint32 dedicatedTransferFamily; - uint32 getQueueTypeFamilyIndex(Gfx::QueueType type) const - { - switch (type) - { - case Gfx::QueueType::GRAPHICS: - return graphicsFamily; - case Gfx::QueueType::COMPUTE: - return computeFamily; - case Gfx::QueueType::TRANSFER: - return transferFamily; - case Gfx::QueueType::DEDICATED_TRANSFER: - return dedicatedTransferFamily; - default: - return 0x7fff; - } - } - bool needsTransfer(Gfx::QueueType src, Gfx::QueueType dst) const - { - uint32 srcIndex = getQueueTypeFamilyIndex(src); - uint32 dstIndex = getQueueTypeFamilyIndex(dst); - return srcIndex != dstIndex; - } + uint32 graphicsFamily; + uint32 computeFamily; + uint32 transferFamily; + uint32 dedicatedTransferFamily; + uint32 getQueueTypeFamilyIndex(Gfx::QueueType type) const + { + switch (type) + { + case Gfx::QueueType::GRAPHICS: + return graphicsFamily; + case Gfx::QueueType::COMPUTE: + return computeFamily; + case Gfx::QueueType::TRANSFER: + return transferFamily; + case Gfx::QueueType::DEDICATED_TRANSFER: + return dedicatedTransferFamily; + default: + return 0x7fff; + } + } + bool needsTransfer(Gfx::QueueType src, Gfx::QueueType dst) const + { + uint32 srcIndex = getQueueTypeFamilyIndex(src); + uint32 dstIndex = getQueueTypeFamilyIndex(dst); + return srcIndex != dstIndex; + } }; class QueueOwnedResource { public: - QueueOwnedResource(QueueFamilyMapping mapping, QueueType startQueueType); - virtual ~QueueOwnedResource(); + QueueOwnedResource(QueueFamilyMapping mapping, QueueType startQueueType); + virtual ~QueueOwnedResource(); - //Preliminary checks to see if the barrier should be executed at all - void transferOwnership(QueueType newOwner); - void pipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, SeAccessFlags dstAccess, SePipelineStageFlags dstStage); + //Preliminary checks to see if the barrier should be executed at all + void transferOwnership(QueueType newOwner); + void pipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, SeAccessFlags dstAccess, SePipelineStageFlags dstStage); protected: - virtual void executeOwnershipBarrier(QueueType newOwner) = 0; - virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, - SeAccessFlags dstAccess, SePipelineStageFlags dstStage) = 0; - Gfx::QueueType currentOwner; - QueueFamilyMapping mapping; + virtual void executeOwnershipBarrier(QueueType newOwner) = 0; + virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, + SeAccessFlags dstAccess, SePipelineStageFlags dstStage) = 0; + Gfx::QueueType currentOwner; + QueueFamilyMapping mapping; }; DEFINE_REF(QueueOwnedResource) @@ -313,161 +313,161 @@ DEFINE_REF(QueueOwnedResource) class Buffer : public QueueOwnedResource { public: - Buffer(QueueFamilyMapping mapping, QueueType startQueueType); - virtual ~Buffer(); + Buffer(QueueFamilyMapping mapping, QueueType startQueueType); + virtual ~Buffer(); protected: - // Inherited via QueueOwnedResource - virtual void executeOwnershipBarrier(QueueType newOwner) = 0; + // Inherited via QueueOwnedResource + virtual void executeOwnershipBarrier(QueueType newOwner) = 0; }; class UniformBuffer : public Buffer { public: - UniformBuffer(QueueFamilyMapping mapping, const BulkResourceData& resourceData); - virtual ~UniformBuffer(); - // returns true if an update was performed, false if the old contents == new contents - virtual bool updateContents(const BulkResourceData& resourceData); - bool isDataEquals(UniformBuffer* other) - { - if(other == nullptr) - { - return false; - } - if(contents.size() != other->contents.size()) - { - return false; - } - if(std::memcmp(contents.data(), other->contents.data(), contents.size()) != 0) - { - return false; - } - return true; - } + UniformBuffer(QueueFamilyMapping mapping, const BulkResourceData& resourceData); + virtual ~UniformBuffer(); + // returns true if an update was performed, false if the old contents == new contents + virtual bool updateContents(const BulkResourceData& resourceData); + bool isDataEquals(UniformBuffer* other) + { + if(other == nullptr) + { + return false; + } + if(contents.size() != other->contents.size()) + { + return false; + } + if(std::memcmp(contents.data(), other->contents.data(), contents.size()) != 0) + { + return false; + } + return true; + } protected: - Array contents; - // Inherited via QueueOwnedResource - virtual void executeOwnershipBarrier(QueueType newOwner) = 0; - virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, - SeAccessFlags dstAccess, SePipelineStageFlags dstStage) = 0; + Array contents; + // Inherited via QueueOwnedResource + virtual void executeOwnershipBarrier(QueueType newOwner) = 0; + virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, + SeAccessFlags dstAccess, SePipelineStageFlags dstStage) = 0; }; DEFINE_REF(UniformBuffer) class VertexBuffer : public Buffer { public: - VertexBuffer(QueueFamilyMapping mapping, uint32 numVertices, uint32 vertexSize, QueueType startQueueType); - virtual ~VertexBuffer(); - inline uint32 getNumVertices() - { - return numVertices; - } - // Size of one vertex in bytes - inline uint32 getVertexSize() - { - return vertexSize; - } + VertexBuffer(QueueFamilyMapping mapping, uint32 numVertices, uint32 vertexSize, QueueType startQueueType); + virtual ~VertexBuffer(); + inline uint32 getNumVertices() + { + return numVertices; + } + // Size of one vertex in bytes + inline uint32 getVertexSize() + { + return vertexSize; + } protected: - // Inherited via QueueOwnedResource - virtual void executeOwnershipBarrier(QueueType newOwner) = 0; - virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, - SeAccessFlags dstAccess, SePipelineStageFlags dstStage) = 0; - uint32 numVertices; - uint32 vertexSize; + // Inherited via QueueOwnedResource + virtual void executeOwnershipBarrier(QueueType newOwner) = 0; + virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, + SeAccessFlags dstAccess, SePipelineStageFlags dstStage) = 0; + uint32 numVertices; + uint32 vertexSize; }; DEFINE_REF(VertexBuffer) class IndexBuffer : public Buffer { public: - IndexBuffer(QueueFamilyMapping mapping, uint32 size, Gfx::SeIndexType index, QueueType startQueueType); - virtual ~IndexBuffer(); - inline uint32 getNumIndices() const - { - return numIndices; - } - inline Gfx::SeIndexType getIndexType() const - { - return indexType; - } + IndexBuffer(QueueFamilyMapping mapping, uint32 size, Gfx::SeIndexType index, QueueType startQueueType); + virtual ~IndexBuffer(); + inline uint32 getNumIndices() const + { + return numIndices; + } + inline Gfx::SeIndexType getIndexType() const + { + return indexType; + } protected: - // Inherited via QueueOwnedResource - virtual void executeOwnershipBarrier(QueueType newOwner) = 0; - virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, - SeAccessFlags dstAccess, SePipelineStageFlags dstStage) = 0; - Gfx::SeIndexType indexType; - uint32 numIndices; + // Inherited via QueueOwnedResource + virtual void executeOwnershipBarrier(QueueType newOwner) = 0; + virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, + SeAccessFlags dstAccess, SePipelineStageFlags dstStage) = 0; + Gfx::SeIndexType indexType; + uint32 numIndices; }; DEFINE_REF(IndexBuffer) class StructuredBuffer : public Buffer { public: - StructuredBuffer(QueueFamilyMapping mapping, const BulkResourceData& bulkResourceData); - virtual ~StructuredBuffer(); - virtual bool updateContents(const BulkResourceData& resourceData); - bool isDataEquals(StructuredBuffer* other) - { - if(other == nullptr) - { - return false; - } - if(contents.size() != other->contents.size()) - { - return false; - } - if(std::memcmp(contents.data(), other->contents.data(), contents.size()) != 0) - { - return false; - } - return true; - } + StructuredBuffer(QueueFamilyMapping mapping, const BulkResourceData& bulkResourceData); + virtual ~StructuredBuffer(); + virtual bool updateContents(const BulkResourceData& resourceData); + bool isDataEquals(StructuredBuffer* other) + { + if(other == nullptr) + { + return false; + } + if(contents.size() != other->contents.size()) + { + return false; + } + if(std::memcmp(contents.data(), other->contents.data(), contents.size()) != 0) + { + return false; + } + return true; + } protected: - Array contents; - // Inherited via QueueOwnedResource - virtual void executeOwnershipBarrier(QueueType newOwner) = 0; - virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, - SeAccessFlags dstAccess, SePipelineStageFlags dstStage) = 0; + Array contents; + // Inherited via QueueOwnedResource + virtual void executeOwnershipBarrier(QueueType newOwner) = 0; + virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, + SeAccessFlags dstAccess, SePipelineStageFlags dstStage) = 0; }; DEFINE_REF(StructuredBuffer) class VertexStream { public: - VertexStream(); - VertexStream(uint32 stride, uint32 offset, uint8 instanced); - ~VertexStream(); - void addVertexElement(VertexElement element); - const Array getVertexDescriptions() const; - inline uint8 isInstanced() const { return instanced; } + VertexStream(); + VertexStream(uint32 stride, uint32 offset, uint8 instanced); + ~VertexStream(); + void addVertexElement(VertexElement element); + const Array getVertexDescriptions() const; + inline uint8 isInstanced() const { return instanced; } - uint32 stride; - uint32 offset; - Array vertexDescription; - uint8 instanced; + uint32 stride; + uint32 offset; + Array vertexDescription; + uint8 instanced; }; DEFINE_REF(VertexStream) class VertexDeclaration { public: - VertexDeclaration(); - ~VertexDeclaration(); + VertexDeclaration(); + ~VertexDeclaration(); - static PVertexDeclaration createDeclaration(PGraphics graphics, const Array& elementList); + static PVertexDeclaration createDeclaration(PGraphics graphics, const Array& elementList); private: }; DEFINE_REF(VertexDeclaration) class GraphicsPipeline { public: - GraphicsPipeline(const GraphicsPipelineCreateInfo& createInfo, PPipelineLayout layout) : createInfo(createInfo) , layout(layout) {} - virtual ~GraphicsPipeline(){} - const GraphicsPipelineCreateInfo& getCreateInfo() const {return createInfo;} - PPipelineLayout getPipelineLayout() const { return layout; } + GraphicsPipeline(const GraphicsPipelineCreateInfo& createInfo, PPipelineLayout layout) : createInfo(createInfo) , layout(layout) {} + virtual ~GraphicsPipeline(){} + const GraphicsPipelineCreateInfo& getCreateInfo() const {return createInfo;} + PPipelineLayout getPipelineLayout() const { return layout; } protected: - GraphicsPipelineCreateInfo createInfo; + GraphicsPipelineCreateInfo createInfo; PPipelineLayout layout; }; DEFINE_REF(GraphicsPipeline) @@ -475,13 +475,13 @@ DEFINE_REF(GraphicsPipeline) class ComputePipeline { public: - ComputePipeline(const ComputePipelineCreateInfo& createInfo, PPipelineLayout layout) : createInfo(createInfo), layout(layout) {} - virtual ~ComputePipeline(){} - const ComputePipelineCreateInfo& getCreateInfo() const { return createInfo; } - PPipelineLayout getPipelineLayout() const { return layout; } + ComputePipeline(const ComputePipelineCreateInfo& createInfo, PPipelineLayout layout) : createInfo(createInfo), layout(layout) {} + virtual ~ComputePipeline(){} + const ComputePipelineCreateInfo& getCreateInfo() const { return createInfo; } + PPipelineLayout getPipelineLayout() const { return layout; } protected: - ComputePipelineCreateInfo createInfo; - PPipelineLayout layout; + ComputePipelineCreateInfo createInfo; + PPipelineLayout layout; }; DEFINE_REF(ComputePipeline) @@ -494,44 +494,44 @@ DEFINE_REF(ComputePipeline) class Texture : public QueueOwnedResource { public: - Texture(QueueFamilyMapping mapping, QueueType startQueueType); - virtual ~Texture(); + Texture(QueueFamilyMapping mapping, QueueType startQueueType); + virtual ~Texture(); - virtual SeFormat getFormat() const = 0; - virtual uint32 getSizeX() const = 0; - virtual uint32 getSizeY() const = 0; - virtual uint32 getSizeZ() const = 0; - virtual SeSampleCountFlags getNumSamples() const = 0; - virtual uint32 getMipLevels() const = 0; - virtual void changeLayout(SeImageLayout newLayout) = 0; - virtual class Texture2D* getTexture2D() { return nullptr; } - virtual void* getNativeHandle() { return nullptr; } + virtual SeFormat getFormat() const = 0; + virtual uint32 getSizeX() const = 0; + virtual uint32 getSizeY() const = 0; + virtual uint32 getSizeZ() const = 0; + virtual SeSampleCountFlags getNumSamples() const = 0; + virtual uint32 getMipLevels() const = 0; + virtual void changeLayout(SeImageLayout newLayout) = 0; + virtual class Texture2D* getTexture2D() { return nullptr; } + virtual void* getNativeHandle() { return nullptr; } protected: // Inherited via QueueOwnedResource - virtual void executeOwnershipBarrier(QueueType newOwner) = 0; - virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, - SeAccessFlags dstAccess, SePipelineStageFlags dstStage) = 0; + virtual void executeOwnershipBarrier(QueueType newOwner) = 0; + virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, + SeAccessFlags dstAccess, SePipelineStageFlags dstStage) = 0; }; DEFINE_REF(Texture) class Texture2D : public Texture { public: - Texture2D(QueueFamilyMapping mapping, QueueType startQueueType); - virtual ~Texture2D(); + Texture2D(QueueFamilyMapping mapping, QueueType startQueueType); + virtual ~Texture2D(); - virtual SeFormat getFormat() const = 0; - virtual uint32 getSizeX() const = 0; - virtual uint32 getSizeY() const = 0; - virtual uint32 getSizeZ() const = 0; - virtual SeSampleCountFlags getNumSamples() const = 0; - virtual uint32 getMipLevels() const = 0; - virtual void changeLayout(SeImageLayout newLayout) = 0; - virtual class Texture2D* getTexture2D() { return this; } + virtual SeFormat getFormat() const = 0; + virtual uint32 getSizeX() const = 0; + virtual uint32 getSizeY() const = 0; + virtual uint32 getSizeZ() const = 0; + virtual SeSampleCountFlags getNumSamples() const = 0; + virtual uint32 getMipLevels() const = 0; + virtual void changeLayout(SeImageLayout newLayout) = 0; + virtual class Texture2D* getTexture2D() { return this; } protected: - //Inherited via QueueOwnedResource - virtual void executeOwnershipBarrier(QueueType newOwner) = 0; - virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, - SeAccessFlags dstAccess, SePipelineStageFlags dstStage) = 0; + //Inherited via QueueOwnedResource + virtual void executeOwnershipBarrier(QueueType newOwner) = 0; + virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, + SeAccessFlags dstAccess, SePipelineStageFlags dstStage) = 0; }; DEFINE_REF(Texture2D) @@ -539,215 +539,216 @@ DECLARE_REF(Viewport) class RenderCommand { public: - RenderCommand(); - virtual ~RenderCommand(); - virtual bool isReady() = 0; - virtual void setViewport(Gfx::PViewport viewport) = 0; - virtual void bindPipeline(Gfx::PGraphicsPipeline pipeline) = 0; - virtual void bindDescriptor(Gfx::PDescriptorSet set) = 0; - virtual void bindDescriptor(const Array& sets) = 0; - virtual void bindVertexBuffer(const Array& streams) = 0; - virtual void bindIndexBuffer(Gfx::PIndexBuffer indexBuffer) = 0; - virtual void draw(const MeshBatchElement& data) = 0; - virtual void draw(uint32 vertexCount, uint32 instanceCount, int32 firstVertex, uint32 firstInstance) = 0; - std::string name; + RenderCommand(); + virtual ~RenderCommand(); + virtual bool isReady() = 0; + virtual void setViewport(Gfx::PViewport viewport) = 0; + virtual void bindPipeline(Gfx::PGraphicsPipeline pipeline) = 0; + virtual void bindDescriptor(Gfx::PDescriptorSet set) = 0; + virtual void bindDescriptor(const Array& sets) = 0; + virtual void bindVertexBuffer(const Array& streams) = 0; + virtual void bindIndexBuffer(Gfx::PIndexBuffer indexBuffer) = 0; + virtual void draw(const MeshBatchElement& data) = 0; + virtual void draw(uint32 vertexCount, uint32 instanceCount, int32 firstVertex, uint32 firstInstance) = 0; + std::string name; }; DEFINE_REF(RenderCommand) class ComputeCommand { public: - ComputeCommand(); - virtual ~ComputeCommand(); - virtual bool isReady() = 0; - virtual void bindPipeline(Gfx::PComputePipeline pipeline) = 0; - virtual void bindDescriptor(Gfx::PDescriptorSet set) = 0; - virtual void bindDescriptor(const Array& sets) = 0; - virtual void dispatch(uint32 threadX, uint32 threadY, uint32 threadZ) = 0; - std::string name; + ComputeCommand(); + virtual ~ComputeCommand(); + virtual bool isReady() = 0; + virtual void bindPipeline(Gfx::PComputePipeline pipeline) = 0; + virtual void bindDescriptor(Gfx::PDescriptorSet set) = 0; + virtual void bindDescriptor(const Array& sets) = 0; + virtual void dispatch(uint32 threadX, uint32 threadY, uint32 threadZ) = 0; + std::string name; }; DEFINE_REF(ComputeCommand) class Window { public: - Window(const WindowCreateInfo &createInfo); - virtual ~Window(); - virtual void beginFrame() = 0; - virtual void endFrame() = 0; - virtual void onWindowCloseEvent() = 0; - virtual PTexture2D getBackBuffer() const = 0; - virtual void setKeyCallback(std::function callback) = 0; - virtual void setMouseMoveCallback(std::function callback) = 0; - virtual void setMouseButtonCallback(std::function callback) = 0; - virtual void setScrollCallback(std::function callback) = 0; - virtual void setFileCallback(std::function callback) = 0; - SeFormat getSwapchainFormat() const - { - return pixelFormat; - } - SeSampleCountFlags getNumSamples() const - { - return samples; - } - uint32 getSizeX() const - { - return sizeX; - } - uint32 getSizeY() const - { - return sizeY; - } + Window(const WindowCreateInfo &createInfo); + virtual ~Window(); + virtual void beginFrame() = 0; + virtual void endFrame() = 0; + virtual void onWindowCloseEvent() = 0; + virtual PTexture2D getBackBuffer() const = 0; + virtual void setKeyCallback(std::function callback) = 0; + virtual void setMouseMoveCallback(std::function callback) = 0; + virtual void setMouseButtonCallback(std::function callback) = 0; + virtual void setScrollCallback(std::function callback) = 0; + virtual void setFileCallback(std::function callback) = 0; + virtual void setCloseCallback(std::function callback) = 0; + SeFormat getSwapchainFormat() const + { + return pixelFormat; + } + SeSampleCountFlags getNumSamples() const + { + return samples; + } + uint32 getSizeX() const + { + return sizeX; + } + uint32 getSizeY() const + { + return sizeY; + } protected: - uint32 sizeX; - uint32 sizeY; - bool bFullscreen; - const char *title; - SeFormat pixelFormat; - uint32 samples; + uint32 sizeX; + uint32 sizeY; + bool bFullscreen; + const char *title; + SeFormat pixelFormat; + uint32 samples; }; DEFINE_REF(Window) class Viewport { public: - Viewport(PWindow owner, const ViewportCreateInfo &createInfo); - virtual ~Viewport(); - virtual void resize(uint32 newX, uint32 newY) = 0; - virtual void move(uint32 newOffsetX, uint32 newOffsetY) = 0; - inline PWindow getOwner() const {return owner;} - inline uint32 getSizeX() const {return sizeX;} - inline uint32 getSizeY() const {return sizeY;} - inline uint32 getOffsetX() const {return offsetX;} - inline uint32 getOffsetY() const {return offsetY;} + Viewport(PWindow owner, const ViewportCreateInfo &createInfo); + virtual ~Viewport(); + virtual void resize(uint32 newX, uint32 newY) = 0; + virtual void move(uint32 newOffsetX, uint32 newOffsetY) = 0; + inline PWindow getOwner() const {return owner;} + inline uint32 getSizeX() const {return sizeX;} + inline uint32 getSizeY() const {return sizeY;} + inline uint32 getOffsetX() const {return offsetX;} + inline uint32 getOffsetY() const {return offsetY;} protected: - uint32 sizeX; - uint32 sizeY; - uint32 offsetX; - uint32 offsetY; - PWindow owner; + uint32 sizeX; + uint32 sizeY; + uint32 offsetX; + uint32 offsetY; + PWindow owner; }; DEFINE_REF(Viewport) class RenderTargetAttachment { public: - RenderTargetAttachment(PTexture2D texture, - SeAttachmentLoadOp loadOp = SE_ATTACHMENT_LOAD_OP_LOAD, - SeAttachmentStoreOp storeOp = SE_ATTACHMENT_STORE_OP_STORE, - SeAttachmentLoadOp stencilLoadOp = SE_ATTACHMENT_LOAD_OP_DONT_CARE, - SeAttachmentStoreOp stencilStoreOp = SE_ATTACHMENT_STORE_OP_DONT_CARE) - : loadOp(loadOp) - , storeOp(storeOp) - , stencilLoadOp(stencilLoadOp) - , stencilStoreOp(stencilStoreOp) - , texture(texture) - { - } - virtual ~RenderTargetAttachment() - { - } - virtual PTexture2D getTexture() - { - return texture; - } - virtual SeFormat getFormat() const - { - return texture->getFormat(); - } - virtual SeSampleCountFlags getNumSamples() const - { - return texture->getNumSamples(); - } - virtual uint32 getSizeX() const - { - return texture->getSizeX(); - } - virtual uint32 getSizeY() const - { - return texture->getSizeY(); - } - inline SeAttachmentLoadOp getLoadOp() const { return loadOp; } - inline SeAttachmentStoreOp getStoreOp() const { return storeOp; } - inline SeAttachmentLoadOp getStencilLoadOp() const { return stencilLoadOp; } - inline SeAttachmentStoreOp getStencilStoreOp() const { return stencilStoreOp; } - SeClearValue clear; - SeColorComponentFlags componentFlags; - SeAttachmentLoadOp loadOp; - SeAttachmentStoreOp storeOp; - SeAttachmentLoadOp stencilLoadOp; - SeAttachmentStoreOp stencilStoreOp; + RenderTargetAttachment(PTexture2D texture, + SeAttachmentLoadOp loadOp = SE_ATTACHMENT_LOAD_OP_LOAD, + SeAttachmentStoreOp storeOp = SE_ATTACHMENT_STORE_OP_STORE, + SeAttachmentLoadOp stencilLoadOp = SE_ATTACHMENT_LOAD_OP_DONT_CARE, + SeAttachmentStoreOp stencilStoreOp = SE_ATTACHMENT_STORE_OP_DONT_CARE) + : loadOp(loadOp) + , storeOp(storeOp) + , stencilLoadOp(stencilLoadOp) + , stencilStoreOp(stencilStoreOp) + , texture(texture) + { + } + virtual ~RenderTargetAttachment() + { + } + virtual PTexture2D getTexture() + { + return texture; + } + virtual SeFormat getFormat() const + { + return texture->getFormat(); + } + virtual SeSampleCountFlags getNumSamples() const + { + return texture->getNumSamples(); + } + virtual uint32 getSizeX() const + { + return texture->getSizeX(); + } + virtual uint32 getSizeY() const + { + return texture->getSizeY(); + } + inline SeAttachmentLoadOp getLoadOp() const { return loadOp; } + inline SeAttachmentStoreOp getStoreOp() const { return storeOp; } + inline SeAttachmentLoadOp getStencilLoadOp() const { return stencilLoadOp; } + inline SeAttachmentStoreOp getStencilStoreOp() const { return stencilStoreOp; } + SeClearValue clear; + SeColorComponentFlags componentFlags; + SeAttachmentLoadOp loadOp; + SeAttachmentStoreOp storeOp; + SeAttachmentLoadOp stencilLoadOp; + SeAttachmentStoreOp stencilStoreOp; protected: - PTexture2D texture; + PTexture2D texture; }; DEFINE_REF(RenderTargetAttachment) class SwapchainAttachment : public RenderTargetAttachment { public: - SwapchainAttachment(PWindow owner, - SeAttachmentLoadOp loadOp = SE_ATTACHMENT_LOAD_OP_LOAD, - SeAttachmentStoreOp storeOp = SE_ATTACHMENT_STORE_OP_STORE, - SeAttachmentLoadOp stencilLoadOp = SE_ATTACHMENT_LOAD_OP_DONT_CARE, - SeAttachmentStoreOp stencilStoreOp = SE_ATTACHMENT_STORE_OP_DONT_CARE) - : RenderTargetAttachment(nullptr, loadOp, storeOp, stencilLoadOp, stencilStoreOp), owner(owner) - { - clear.color.float32[0] = 0.0f; - clear.color.float32[1] = 0.0f; - clear.color.float32[2] = 0.0f; - clear.color.float32[3] = 1.0f; - componentFlags = SE_COLOR_COMPONENT_R_BIT | SE_COLOR_COMPONENT_G_BIT | SE_COLOR_COMPONENT_B_BIT | SE_COLOR_COMPONENT_A_BIT; - } - virtual PTexture2D getTexture() override - { - return owner->getBackBuffer(); - } - virtual SeFormat getFormat() const override - { - return owner->getSwapchainFormat(); - } - virtual SeSampleCountFlags getNumSamples() const override - { - return owner->getNumSamples(); - } - virtual uint32 getSizeX() const - { - return owner->getSizeX(); - } - virtual uint32 getSizeY() const - { - return owner->getSizeY(); - } + SwapchainAttachment(PWindow owner, + SeAttachmentLoadOp loadOp = SE_ATTACHMENT_LOAD_OP_LOAD, + SeAttachmentStoreOp storeOp = SE_ATTACHMENT_STORE_OP_STORE, + SeAttachmentLoadOp stencilLoadOp = SE_ATTACHMENT_LOAD_OP_DONT_CARE, + SeAttachmentStoreOp stencilStoreOp = SE_ATTACHMENT_STORE_OP_DONT_CARE) + : RenderTargetAttachment(nullptr, loadOp, storeOp, stencilLoadOp, stencilStoreOp), owner(owner) + { + clear.color.float32[0] = 0.0f; + clear.color.float32[1] = 0.0f; + clear.color.float32[2] = 0.0f; + clear.color.float32[3] = 1.0f; + componentFlags = SE_COLOR_COMPONENT_R_BIT | SE_COLOR_COMPONENT_G_BIT | SE_COLOR_COMPONENT_B_BIT | SE_COLOR_COMPONENT_A_BIT; + } + virtual PTexture2D getTexture() override + { + return owner->getBackBuffer(); + } + virtual SeFormat getFormat() const override + { + return owner->getSwapchainFormat(); + } + virtual SeSampleCountFlags getNumSamples() const override + { + return owner->getNumSamples(); + } + virtual uint32 getSizeX() const + { + return owner->getSizeX(); + } + virtual uint32 getSizeY() const + { + return owner->getSizeY(); + } private: - PWindow owner; + PWindow owner; }; DEFINE_REF(SwapchainAttachment) class RenderTargetLayout { public: - RenderTargetLayout(); - RenderTargetLayout(PRenderTargetAttachment depthAttachment); - RenderTargetLayout(PRenderTargetAttachment colorAttachment, PRenderTargetAttachment depthAttachment); - RenderTargetLayout(Array colorAttachments, PRenderTargetAttachment depthAttachmet); - RenderTargetLayout(Array inputAttachments, Array colorAttachments, PRenderTargetAttachment depthAttachment); - Array inputAttachments; - Array colorAttachments; - PRenderTargetAttachment depthAttachment; - uint32 width; - uint32 height; + RenderTargetLayout(); + RenderTargetLayout(PRenderTargetAttachment depthAttachment); + RenderTargetLayout(PRenderTargetAttachment colorAttachment, PRenderTargetAttachment depthAttachment); + RenderTargetLayout(Array colorAttachments, PRenderTargetAttachment depthAttachmet); + RenderTargetLayout(Array inputAttachments, Array colorAttachments, PRenderTargetAttachment depthAttachment); + Array inputAttachments; + Array colorAttachments; + PRenderTargetAttachment depthAttachment; + uint32 width; + uint32 height; }; DEFINE_REF(RenderTargetLayout) class RenderPass { public: - RenderPass(PRenderTargetLayout layout) : layout(layout) {} - virtual ~RenderPass() {} - inline PRenderTargetLayout getLayout() const { return layout; } + RenderPass(PRenderTargetLayout layout) : layout(layout) {} + virtual ~RenderPass() {} + inline PRenderTargetLayout getLayout() const { return layout; } protected: - PRenderTargetLayout layout; + PRenderTargetLayout layout; }; DEFINE_REF(RenderPass) } // namespace Gfx diff --git a/src/Engine/Graphics/Vulkan/VulkanGraphicsResources.h b/src/Engine/Graphics/Vulkan/VulkanGraphicsResources.h index 63bb7f6..3f2a241 100644 --- a/src/Engine/Graphics/Vulkan/VulkanGraphicsResources.h +++ b/src/Engine/Graphics/Vulkan/VulkanGraphicsResources.h @@ -370,12 +370,14 @@ public: virtual void setMouseButtonCallback(std::function callback) override; virtual void setScrollCallback(std::function callback) override; virtual void setFileCallback(std::function callback) override; + virtual void setCloseCallback(std::function callback); std::function keyCallback; std::function mouseMoveCallback; std::function mouseButtonCallback; std::function scrollCallback; std::function fileCallback; + std::function closeCallback; protected: void advanceBackBuffer(); void recreateSwapchain(const WindowCreateInfo &createInfo); diff --git a/src/Engine/Graphics/Vulkan/VulkanViewport.cpp b/src/Engine/Graphics/Vulkan/VulkanViewport.cpp index caa107a..e42978b 100644 --- a/src/Engine/Graphics/Vulkan/VulkanViewport.cpp +++ b/src/Engine/Graphics/Vulkan/VulkanViewport.cpp @@ -38,6 +38,12 @@ void glfwFileCallback(GLFWwindow* handle, int count, const char** paths) window->fileCallback(count, paths); } +void glfwCloseCallback(GLFWwindow* handle) +{ + Window* window = (Window*)glfwGetWindowUserPointer(handle); + window->closeCallback(); +} + Window::Window(PGraphics graphics, const WindowCreateInfo &createInfo) : Gfx::Window(createInfo) , graphics(graphics) @@ -56,6 +62,7 @@ Window::Window(PGraphics graphics, const WindowCreateInfo &createInfo) glfwSetMouseButtonCallback(handle, &glfwMouseButtonCallback); glfwSetScrollCallback(handle, &glfwScrollCallback); glfwSetDropCallback(handle, &glfwFileCallback); + glfwSetWindowCloseCallback(handle, &glfwCloseCallback); glfwCreateWindowSurface(instance, handle, nullptr, &surface); @@ -134,6 +141,11 @@ void Window::setFileCallback(std::function callback) fileCallback = callback; } +void Window::setCloseCallback(std::function callback) +{ + closeCallback = callback; +} + void Window::advanceBackBuffer() { VkResult res = VK_ERROR_OUT_OF_DATE_KHR; diff --git a/src/Engine/MinimalEngine.h b/src/Engine/MinimalEngine.h index 73e7cd0..dbc81a4 100644 --- a/src/Engine/MinimalEngine.h +++ b/src/Engine/MinimalEngine.h @@ -54,9 +54,9 @@ public: std::unique_lock lock(registeredObjectsLock); registeredObjects.erase(handle); } - #pragma warning( disable: 4150) +// #pragma warning( disable: 4150) delete handle; - #pragma warning( default: 4150) +// #pragma warning( default: 4150) } RefObject &operator=(const RefObject &rhs) { diff --git a/src/Engine/Scene/Scene.cpp b/src/Engine/Scene/Scene.cpp index 504328d..07d8d10 100644 --- a/src/Engine/Scene/Scene.cpp +++ b/src/Engine/Scene/Scene.cpp @@ -18,7 +18,7 @@ Scene::Scene(Gfx::PGraphics graphics) lightEnv.directionalLights[0].color = Vector4(1, 1, 1, 1); lightEnv.directionalLights[0].direction = Vector4(1, 1, 0, 1); lightEnv.directionalLights[0].intensity = Vector4(1, 1, 1, 1); - lightEnv.numDirectionalLights = 0; + lightEnv.numDirectionalLights = 1; srand((unsigned int)time(NULL)); for(uint32 i = 0; i < 16; ++i) { diff --git a/src/Engine/ThreadPool.cpp b/src/Engine/ThreadPool.cpp index e4967ac..9b6f3e5 100644 --- a/src/Engine/ThreadPool.cpp +++ b/src/Engine/ThreadPool.cpp @@ -2,20 +2,38 @@ using namespace Seele; +Event::Event() + : flag(new std::atomic_bool()) +{} -void Event::await_suspend(std::coroutine_handle h) +Event::Event(const std::string& name) + : name(name) + , flag(new std::atomic_bool()) +{} + +void Event::raise() { - getGlobalThreadPool().addJob(Job(h)); + flag->store(1); + getGlobalThreadPool().notify(this); +} +void Event::reset() +{ + flag->store(0); } -Job JobPromise::get_return_object() noexcept { - return Job { std::coroutine_handle::from_promise(*this) }; +bool Event::await_ready() +{ + return flag->load(); } ThreadPool::ThreadPool(uint32 threadCount) : workers(threadCount) { - + running.store(true); + for(uint32 i = 0; i < threadCount; ++i) + { + workers[i] = std::thread(&ThreadPool::threadLoop, this, i == 0); + } } ThreadPool::~ThreadPool() @@ -25,6 +43,63 @@ ThreadPool::~ThreadPool() thread.join(); } } +void ThreadPool::addJob(Job&& job) +{ + std::unique_lock lock(jobQueueLock); + jobQueue.add(job); +} +void ThreadPool::addJob(MainJob&& job) +{ + std::unique_lock lock(mainJobLock); + mainJobs.add(job); +} +void ThreadPool::enqueueWaiting(Event* event, Job&& job) +{ + std::unique_lock lock(waitingLock); + waitingJobs[event].add(std::move(job)); +} +void ThreadPool::enqueueWaiting(Event* event, MainJob&& job) +{ + std::unique_lock lock(waitingMainLock); + waitingMainJobs[event].add(std::move(job)); +} +void ThreadPool::notify(Event* event) +{ + { + std::unique_lock lock(jobQueueLock); + std::unique_lock lock2(waitingLock); + for(auto&& job : waitingJobs[event]) + { + jobQueue.add(job); + } + waitingJobs[event].clear(); + } + { + std::unique_lock lock(mainJobLock); + std::unique_lock lock2(waitingMainLock); + for(auto&& job : waitingMainJobs[event]) + { + mainJobs.add(job); + } + waitingMainJobs[event].clear(); + } + event->reset(); +} +void ThreadPool::threadLoop(const bool mainThread) +{ + while(running.load()) + { + if(mainThread) + { + std::unique_lock lock(mainJobLock); + if(!mainJobs.empty()) + { + MainJob&& job = mainJobs.retrieve(); + job.resume(); + } + } + } +} ThreadPool& Seele::getGlobalThreadPool() { diff --git a/src/Engine/ThreadPool.h b/src/Engine/ThreadPool.h index aadd369..7629a63 100644 --- a/src/Engine/ThreadPool.h +++ b/src/Engine/ThreadPool.h @@ -1,35 +1,20 @@ #pragma once #include -#include #include "Containers/List.h" namespace Seele { -struct JobPromise; -struct Event -{ -public: - void raise() - { - flag.test_and_set(); - flag.notify_all(); - } - void reset() - { - flag.clear(); - } - bool await_ready() { return flag.test(); } - void await_suspend(std::coroutine_handle h); - void await_resume() {} -private: - std::atomic_flag flag; -}; -struct [[nodiscard]] Job; -struct JobPromise -{ - Job get_return_object() noexcept; +extern class ThreadPool& getGlobalThreadPool(); - std::suspend_always initial_suspend() const noexcept { return {}; } +template +struct JobBase; + +template +struct JobPromiseBase +{ + JobBase get_return_object() noexcept; + + inline auto initial_suspend() const noexcept; std::suspend_never final_suspend() const noexcept { return {}; } void return_void() noexcept {} @@ -38,23 +23,47 @@ struct JobPromise exit(1); }; }; -struct [[nodiscard]] Job +template +struct JobBase { public: - using promise_type = JobPromise; + using promise_type = JobPromiseBase; - explicit Job(std::coroutine_handle handle) + explicit JobBase(std::coroutine_handle handle) : handle(handle) {} - ~Job() + ~JobBase() { if(handle) { handle.destroy(); } } + void resume() + { + handle.resume(); + } private: - std::coroutine_handle handle; + std::coroutine_handle handle; +}; + +using MainJob = JobBase; +using Job = JobBase; + +struct Event +{ +public: + Event(); + Event(const std::string& name); + void raise(); + void reset(); + bool await_ready(); + template + constexpr void await_suspend(std::coroutine_handle> h); + constexpr void await_resume() {} +private: + std::string name; + RefPtr flag; }; class ThreadPool @@ -62,14 +71,56 @@ class ThreadPool public: ThreadPool(uint32 threadCount = std::thread::hardware_concurrency()); virtual ~ThreadPool(); - void addJob(Job&& job) - { - jobs.add(std::move(job)); - } + void addJob(Job&& job); + void addJob(MainJob&& job); + void enqueueWaiting(Event* event, Job&& job); + void enqueueWaiting(Event* event, MainJob&& job); + void notify(Event* event); private: + std::atomic_bool running; + std::thread* mainThread; std::vector workers; - List jobs; - void threadLoop(); + + List mainJobs; + std::mutex mainJobLock; + + List jobQueue; + std::mutex jobQueueLock; + + Map> waitingJobs; + std::mutex waitingLock; + + Map> waitingMainJobs; + std::mutex waitingMainLock; + + void threadLoop(const bool isMainThread); }; -extern ThreadPool& getGlobalThreadPool(); + + +template +inline JobBase JobPromiseBase::get_return_object() noexcept { + return JobBase { std::coroutine_handle>::from_promise(*this) }; +} + +template +inline auto JobPromiseBase::initial_suspend() const noexcept +{ + struct JobAwaitable + { + constexpr bool await_ready() { return false; } + constexpr void await_suspend(std::coroutine_handle> h) + { + getGlobalThreadPool().addJob(JobBase(h)); + } + constexpr void await_resume() {} + }; + return JobAwaitable{}; +} + +template +inline constexpr void Event::await_suspend(std::coroutine_handle> h) +{ + getGlobalThreadPool().enqueueWaiting(this, JobBase(h)); +} + } // namespace Seele diff --git a/src/Engine/Window/SceneView.cpp b/src/Engine/Window/SceneView.cpp index 0b0954b..f75f876 100644 --- a/src/Engine/Window/SceneView.cpp +++ b/src/Engine/Window/SceneView.cpp @@ -8,49 +8,49 @@ using namespace Seele; Seele::SceneView::SceneView(Gfx::PGraphics graphics, PWindow owner, const ViewportCreateInfo &createInfo) - : View(graphics, owner, createInfo) - , activeCamera(new CameraActor()) - , depthPrepass(DepthPrepass(graphics, viewport, activeCamera)) - , lightCullingPass(LightCullingPass(graphics, viewport, activeCamera)) - , basePass(BasePass(graphics, viewport, activeCamera)) + : View(graphics, owner, createInfo) + , activeCamera(new CameraActor()) + , depthPrepass(DepthPrepass(graphics, viewport, activeCamera)) + , lightCullingPass(LightCullingPass(graphics, viewport, activeCamera)) + , basePass(BasePass(graphics, viewport, activeCamera)) { - scene = new Scene(graphics); - scene->addActor(activeCamera); - /*AssetRegistry::importFile("/home/dynamitos/Assets/Ayaka/Avatar_Girl_Sword_Ayaka_Tex_Body_Diffuse.png"); - AssetRegistry::importFile("/home/dynamitos/Assets/Ayaka/Avatar_Girl_Sword_Ayaka_Tex_Body_Lightmap.png"); - AssetRegistry::importFile("/home/dynamitos/Assets/Ayaka/Avatar_Girl_Sword_Ayaka_Tex_Face_Diffuse.png"); - AssetRegistry::importFile("/home/dynamitos/Assets/Ayaka/Avatar_Girl_Sword_Ayaka_Tex_Hair_Diffuse.png"); - AssetRegistry::importFile("/home/dynamitos/Assets/Ayaka/Avatar_Girl_Sword_Ayaka_Tex_Hair_Lightmap.png"); - AssetRegistry::importFile("/home/dynamitos/Assets/Ayaka/Avatar_Girl_Tex_FaceLightmap.png"); - AssetRegistry::importFile("/home/dynamitos/Assets/Ayaka/Ayaka.fbx"); - PPrimitiveComponent ayaka = new PrimitiveComponent(AssetRegistry::findMesh("Ayaka")); - ayaka->addWorldTranslation(Vector(0, 0, 100)); - ayaka->setWorldScale(Vector(0.1f, 0.1f, 0.1f)); - scene->addPrimitiveComponent(ayaka);*/ + scene = new Scene(graphics); + scene->addActor(activeCamera); + AssetRegistry::importFile("/home/dynamitos/Assets/Ayaka/Avatar_Girl_Sword_Ayaka_Tex_Body_Diffuse.png"); + AssetRegistry::importFile("/home/dynamitos/Assets/Ayaka/Avatar_Girl_Sword_Ayaka_Tex_Body_Lightmap.png"); + AssetRegistry::importFile("/home/dynamitos/Assets/Ayaka/Avatar_Girl_Sword_Ayaka_Tex_Face_Diffuse.png"); + AssetRegistry::importFile("/home/dynamitos/Assets/Ayaka/Avatar_Girl_Sword_Ayaka_Tex_Hair_Diffuse.png"); + AssetRegistry::importFile("/home/dynamitos/Assets/Ayaka/Avatar_Girl_Sword_Ayaka_Tex_Hair_Lightmap.png"); + AssetRegistry::importFile("/home/dynamitos/Assets/Ayaka/Avatar_Girl_Tex_FaceLightmap.png"); + AssetRegistry::importFile("/home/dynamitos/Assets/Ayaka/Ayaka.fbx"); + PPrimitiveComponent ayaka = new PrimitiveComponent(AssetRegistry::findMesh("Ayaka")); + ayaka->addWorldTranslation(Vector(0, 0, 0)); + ayaka->setWorldScale(Vector(10, 10, 10)); + scene->addPrimitiveComponent(ayaka); - AssetRegistry::importFile("D:\\Private\\Programming\\Unreal Engine\\Assets\\Ely\\Ely.fbx"); - AssetRegistry::importFile("D:\\Private\\Programming\\Unreal Engine\\Assets\\Cube\\cube.obj"); - AssetRegistry::importFile("D:\\Private\\Programming\\Unreal Engine\\Assets\\Plane\\plane.fbx"); - PPrimitiveComponent plane = new PrimitiveComponent(AssetRegistry::findMesh("plane")); - plane->setWorldScale(Vector(100, 100, 100)); - PPrimitiveComponent arissa = new PrimitiveComponent(AssetRegistry::findMesh("Ely")); - arissa->addWorldTranslation(Vector(0, 0, 100)); - arissa->setWorldScale(Vector(0.1f, 0.1f, 0.1f)); - scene->addPrimitiveComponent(plane); - scene->addPrimitiveComponent(arissa); + /*AssetRegistry::importFile("D:\\Private\\Programming\\Unreal Engine\\Assets\\Ely\\Ely.fbx"); + AssetRegistry::importFile("D:\\Private\\Programming\\Unreal Engine\\Assets\\Cube\\cube.obj"); + AssetRegistry::importFile("D:\\Private\\Programming\\Unreal Engine\\Assets\\Plane\\plane.fbx"); + PPrimitiveComponent plane = new PrimitiveComponent(AssetRegistry::findMesh("plane")); + plane->setWorldScale(Vector(100, 100, 100)); + PPrimitiveComponent arissa = new PrimitiveComponent(AssetRegistry::findMesh("Ely")); + arissa->addWorldTranslation(Vector(0, 0, 100)); + arissa->setWorldScale(Vector(0.1f, 0.1f, 0.1f)); + scene->addPrimitiveComponent(plane); + scene->addPrimitiveComponent(arissa);*/ - PRenderGraphResources resources = new RenderGraphResources(); - depthPrepass.setResources(resources); - lightCullingPass.setResources(resources); - basePass.setResources(resources); + PRenderGraphResources resources = new RenderGraphResources(); + depthPrepass.setResources(resources); + lightCullingPass.setResources(resources); + basePass.setResources(resources); - depthPrepass.publishOutputs(); - lightCullingPass.publishOutputs(); - basePass.publishOutputs(); + depthPrepass.publishOutputs(); + lightCullingPass.publishOutputs(); + basePass.publishOutputs(); - depthPrepass.createRenderPass(); - lightCullingPass.createRenderPass(); - basePass.createRenderPass(); + depthPrepass.createRenderPass(); + lightCullingPass.createRenderPass(); + basePass.createRenderPass(); } Seele::SceneView::~SceneView() @@ -59,8 +59,8 @@ Seele::SceneView::~SceneView() void SceneView::beginUpdate() { - View::beginUpdate(); - scene->tick(Gfx::currentFrameDelta); + View::beginUpdate(); + scene->tick(Gfx::currentFrameDelta); } void SceneView::update() @@ -69,81 +69,81 @@ void SceneView::update() void SceneView::commitUpdate() { - depthPrepassData.staticDrawList = scene->getStaticMeshes(); - lightCullingPassData.lightEnv = scene->getLightBuffer(); - basePassData.staticDrawList = scene->getStaticMeshes(); + depthPrepassData.staticDrawList = scene->getStaticMeshes(); + lightCullingPassData.lightEnv = scene->getLightBuffer(); + basePassData.staticDrawList = scene->getStaticMeshes(); } void SceneView::prepareRender() { - depthPrepass.updateViewFrame(depthPrepassData); - lightCullingPass.updateViewFrame(lightCullingPassData); - basePass.updateViewFrame(basePassData); + depthPrepass.updateViewFrame(depthPrepassData); + lightCullingPass.updateViewFrame(lightCullingPassData); + basePass.updateViewFrame(basePassData); } void SceneView::render() { - depthPrepass.beginFrame(); - lightCullingPass.beginFrame(); - basePass.beginFrame(); + depthPrepass.beginFrame(); + lightCullingPass.beginFrame(); + basePass.beginFrame(); - depthPrepass.render(); - lightCullingPass.render(); - basePass.render(); + depthPrepass.render(); + lightCullingPass.render(); + basePass.render(); - depthPrepass.endFrame(); - lightCullingPass.endFrame(); - basePass.endFrame(); + depthPrepass.endFrame(); + lightCullingPass.endFrame(); + basePass.endFrame(); } void SceneView::keyCallback(KeyCode code, InputAction action, KeyModifier) { - if(action != InputAction::RELEASE) - { - if(code == KeyCode::KEY_W) - { - activeCamera->getCameraComponent()->moveOrigin(1); - } - if(code == KeyCode::KEY_S) - { - activeCamera->getCameraComponent()->moveOrigin(-1); - } - } + if(action != InputAction::RELEASE) + { + if(code == KeyCode::KEY_W) + { + activeCamera->getCameraComponent()->moveOrigin(1); + } + if(code == KeyCode::KEY_S) + { + activeCamera->getCameraComponent()->moveOrigin(-1); + } + } } static bool mouseDown = false; void SceneView::mouseMoveCallback(double xPos, double yPos) { - static double prevXPos = 0.0f, prevYPos = 0.0f; - double deltaX = prevXPos - xPos; - double deltaY = prevYPos - yPos; - prevXPos = xPos; - prevYPos = yPos; - if(mouseDown) - { - activeCamera->getCameraComponent()->mouseMove((float)deltaX, (float)deltaY); - } + static double prevXPos = 0.0f, prevYPos = 0.0f; + double deltaX = prevXPos - xPos; + double deltaY = prevYPos - yPos; + prevXPos = xPos; + prevYPos = yPos; + if(mouseDown) + { + activeCamera->getCameraComponent()->mouseMove((float)deltaX, (float)deltaY); + } } void SceneView::mouseButtonCallback(MouseButton button, InputAction action, KeyModifier) { - if(button == MouseButton::MOUSE_BUTTON_1 && action != InputAction::RELEASE) - { - mouseDown = true; - } - else - { - mouseDown = false; - } + if(button == MouseButton::MOUSE_BUTTON_1 && action != InputAction::RELEASE) + { + mouseDown = true; + } + else + { + mouseDown = false; + } } void SceneView::scrollCallback(double, double yOffset) { - activeCamera->getCameraComponent()->mouseScroll(yOffset); + activeCamera->getCameraComponent()->mouseScroll(yOffset); } void SceneView::fileCallback(int, const char**) { - + } diff --git a/src/Engine/Window/Window.cpp b/src/Engine/Window/Window.cpp index e13bd7f..f640c84 100644 --- a/src/Engine/Window/Window.cpp +++ b/src/Engine/Window/Window.cpp @@ -1,10 +1,12 @@ #include "Window.h" +#include "WindowManager.h" #include using namespace Seele; -Window::Window(Gfx::PWindow handle) - : gfxHandle(handle) +Window::Window(PWindowManager owner, Gfx::PWindow handle) + : owner(owner) + , gfxHandle(handle) { } @@ -20,23 +22,17 @@ void Window::addView(PView view) views.add(windowView); } -void Window::render() +MainJob Window::render() { gfxHandle->beginFrame(); for(auto& windowView : views) - { - windowView->view->beginUpdate(); - windowView->view->update(); - { - std::unique_lock lock(windowView->workerMutex); - windowView->view->commitUpdate(); - } - windowView->updateFinished.raise(); + { + viewWorker(windowView); + co_await windowView->updateFinished; { std::unique_lock lock(windowView->workerMutex); windowView->view->prepareRender(); } - windowView->updateFinished.reset(); windowView->view->render(); } gfxHandle->endFrame(); @@ -59,12 +55,22 @@ void Window::setFocused(PView view) gfxHandle->setMouseButtonCallback(mouseButtonFunction); gfxHandle->setScrollCallback(scrollFunction); gfxHandle->setFileCallback(fileFunction); + gfxHandle->setCloseCallback([this](){ + owner->notifyWindowClosed(this); + }); } -void Window::viewWorker(WindowView* windowView) +Job Window::viewWorker(WindowView* windowView) { while(true) { + windowView->view->beginUpdate(); + windowView->view->update(); + { + std::unique_lock lock(windowView->workerMutex); + windowView->view->commitUpdate(); + } + windowView->updateFinished.raise(); } } diff --git a/src/Engine/Window/Window.h b/src/Engine/Window/Window.h index 67d906d..ccd658d 100644 --- a/src/Engine/Window/Window.h +++ b/src/Engine/Window/Window.h @@ -9,26 +9,27 @@ struct WindowView { PView view; Event updateFinished; - std::thread worker; std::mutex workerMutex; }; DEFINE_REF(WindowView) +DECLARE_REF(WindowManager) // The logical window, with the graphics proxy class Window { public: - Window(Gfx::PWindow handle); + Window(PWindowManager owner, Gfx::PWindow handle); ~Window(); void addView(PView view); - void render(); + MainJob render(); Gfx::PWindow getGfxHandle(); void setFocused(PView view); protected: + PWindowManager owner; Array views; Gfx::PWindow gfxHandle; - void viewWorker(WindowView* view); + Job viewWorker(WindowView* view); }; DEFINE_REF(Window) } // namespace Seele \ No newline at end of file diff --git a/src/Engine/Window/WindowManager.cpp b/src/Engine/Window/WindowManager.cpp index 58ba69a..a654c31 100644 --- a/src/Engine/Window/WindowManager.cpp +++ b/src/Engine/Window/WindowManager.cpp @@ -7,21 +7,21 @@ Gfx::PGraphics WindowManager::graphics; WindowManager::WindowManager() { - graphics = new Vulkan::Graphics(); - GraphicsInitializer initializer; - graphics->init(initializer); - TextureCreateInfo info; - info.width = 4096; - info.height = 4096; - Gfx::PTexture2D testTexture = graphics->createTexture2D(info); - UniformBufferCreateInfo uniformInitializer; - uniformInitializer.resourceData.size = 4096; - uniformInitializer.resourceData.data = new uint8[4096]; - for (int i = 0; i < 4096; ++i) - { - uniformInitializer.resourceData.data[i] = (uint8)i; - } - Gfx::PUniformBuffer testUniform = graphics->createUniformBuffer(uniformInitializer); + graphics = new Vulkan::Graphics(); + GraphicsInitializer initializer; + graphics->init(initializer); + TextureCreateInfo info; + info.width = 4096; + info.height = 4096; + Gfx::PTexture2D testTexture = graphics->createTexture2D(info); + UniformBufferCreateInfo uniformInitializer; + uniformInitializer.resourceData.size = 4096; + uniformInitializer.resourceData.data = new uint8[4096]; + for (int i = 0; i < 4096; ++i) + { + uniformInitializer.resourceData.data[i] = (uint8)i; + } + Gfx::PUniformBuffer testUniform = graphics->createUniformBuffer(uniformInitializer); } WindowManager::~WindowManager() @@ -30,8 +30,13 @@ WindowManager::~WindowManager() PWindow WindowManager::addWindow(const WindowCreateInfo &createInfo) { - Gfx::PWindow handle = graphics->createWindow(createInfo); - PWindow window = new Window(handle); - windows.add(window); - return window; + Gfx::PWindow handle = graphics->createWindow(createInfo); + PWindow window = new Window(this, handle); + windows.add(window); + return window; +} + +void WindowManager::notifyWindowClosed(PWindow window) +{ + windows.remove(windows.find(window)); } diff --git a/src/Engine/Window/WindowManager.h b/src/Engine/Window/WindowManager.h index 68cb27d..0ac3171 100644 --- a/src/Engine/Window/WindowManager.h +++ b/src/Engine/Window/WindowManager.h @@ -12,6 +12,7 @@ public: WindowManager(); ~WindowManager(); PWindow addWindow(const WindowCreateInfo &createInfo); + void notifyWindowClosed(PWindow window); static Gfx::PGraphics getGraphics() { return graphics; diff --git a/src/Engine/main.cpp b/src/Engine/main.cpp index 0daa6f0..3be06e0 100644 --- a/src/Engine/main.cpp +++ b/src/Engine/main.cpp @@ -9,7 +9,7 @@ using namespace Seele; int main() { PWindowManager windowManager = new WindowManager(); - AssetRegistry::init("D:\\Private\\Programming\\C++\\TestSeeleProject\\"); + AssetRegistry::init("/home/dynamitos/TestSeeleProject"); WindowCreateInfo mainWindowInfo; mainWindowInfo.title = "SeeleEngine"; mainWindowInfo.width = 1280; @@ -34,7 +34,7 @@ int main() PInspectorView inspectorView = new InspectorView(windowManager->getGraphics(), window, inspectorViewInfo); window->addView(inspectorView); sceneView->setFocused(); - while(true) + while(windowManager->isActive()) { window->render(); }