basic framegraph (#3303)

This commit is contained in:
Yun Hsiao Wu
2021-03-11 11:15:09 +08:00
committed by GitHub
parent 343768fbe7
commit 6b197934ff
25 changed files with 2767 additions and 20 deletions
+9 -2
View File
@@ -44,7 +44,7 @@ template <bool ThreadSafe>
class StringPool final {
public:
StringPool() noexcept = default;
~StringPool() = default;
~StringPool();
StringPool(StringPool const &) = delete;
StringPool(StringPool &&) = delete;
StringPool &operator=(StringPool const &) = delete;
@@ -66,6 +66,13 @@ private:
using ThreadSafeStringPool = StringPool<true>;
template <bool ThreadSafe>
StringPool<ThreadSafe>::~StringPool() {
for (char const *strCache : _handleToStrings) {
delete[] strCache;
}
}
template <bool ThreadSafe>
inline StringHandle StringPool<ThreadSafe>::stringToHandle(char const *const str) noexcept {
if (ThreadSafe) {
@@ -105,7 +112,7 @@ inline StringHandle StringPool<ThreadSafe>::doStringToHandle(char const *const s
if (it == _stringToHandles.end()) {
size_t const strLength = strlen(str) + 1;
char *const strCache = new char[strLength]; // never freed since we can't invalidate every existing usage
char *const strCache = new char[strLength];
strcpy(strCache, str);
StringHandle name(static_cast<StringHandle::IndexType>(_handleToStrings.size()), strCache);
_handleToStrings.emplace_back(strCache);
@@ -0,0 +1,85 @@
/****************************************************************************
Copyright (c) 2021 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#pragma once
#include "Handle.h"
#include "base/Macros.h"
namespace cc {
namespace framegraph {
template <typename KeyType, typename ValueType, ValueType InvalidValue>
class Blackboard final {
public:
Blackboard() noexcept = default;
~Blackboard() = default;
Blackboard(const Blackboard &) = delete;
Blackboard(Blackboard &&) = delete;
Blackboard &operator=(const Blackboard &) = delete;
Blackboard &operator=(Blackboard &&) = delete;
CC_INLINE ValueType &operator[](const KeyType &name) noexcept;
CC_INLINE void put(const KeyType &name, ValueType const handle) noexcept;
CC_INLINE ValueType get(const KeyType &name) const noexcept;
CC_INLINE void clear() noexcept;
CC_INLINE bool has(const KeyType &name) const noexcept;
private:
using Container = std::map<KeyType, ValueType>;
Container _container{};
};
//////////////////////////////////////////////////////////////////////////
template <typename KeyType, typename ValueType, ValueType InvalidValue>
ValueType &Blackboard<KeyType, ValueType, InvalidValue>::operator[](const KeyType &name) noexcept {
const auto it = _container.find(name);
return (it == _container.end() ? _container.emplace(name, InvalidValue).first : it)->second;
}
template <typename KeyType, typename ValueType, ValueType InvalidValue>
void Blackboard<KeyType, ValueType, InvalidValue>::put(const KeyType &name, ValueType const handle) noexcept {
_container[name] = handle;
}
template <typename KeyType, typename ValueType, ValueType InvalidValue>
ValueType Blackboard<KeyType, ValueType, InvalidValue>::get(const KeyType &name) const noexcept {
const auto it = _container.find(name);
return it == _container.end() ? InvalidValue : it->second;
}
template <typename KeyType, typename ValueType, ValueType InvalidValue>
void Blackboard<KeyType, ValueType, InvalidValue>::clear() noexcept {
_container.clear();
}
template <typename KeyType, typename ValueType, ValueType InvalidValue>
bool Blackboard<KeyType, ValueType, InvalidValue>::has(const KeyType &name) const noexcept {
return _container.find(name) != _container.end();
}
} // namespace framegraph
} // namespace cc
@@ -0,0 +1,72 @@
/****************************************************************************
Copyright (c) 2021 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#pragma once
#include "DevicePassResourceTable.h"
namespace cc {
namespace framegraph {
class Executable {
public:
Executable() noexcept = default;
virtual ~Executable() = default;
Executable(const Executable &) = delete;
Executable(Executable &&) = delete;
Executable &operator=(const Executable &) = delete;
Executable &operator=(Executable &&) = delete;
virtual void execute(const DevicePassResourceTable &resourceTable) noexcept = 0;
};
template <typename Data, typename ExecuteMethod>
class CallbackPass final : public Executable {
public:
explicit CallbackPass(ExecuteMethod &&execute) noexcept;
void execute(const DevicePassResourceTable &resourceTable) noexcept override;
CC_INLINE const Data &getData() const noexcept { return _data; }
CC_INLINE Data &getData() noexcept { return _data; }
private:
Data _data;
ExecuteMethod _execute;
};
//////////////////////////////////////////////////////////////////////////
template <typename Data, typename ExecuteMethod>
CallbackPass<Data, ExecuteMethod>::CallbackPass(ExecuteMethod &&execute) noexcept
: Executable(),
_execute(execute) {
}
template <typename Data, typename ExecuteMethod>
void CallbackPass<Data, ExecuteMethod>::execute(const DevicePassResourceTable &resourceTable) noexcept {
_execute(_data, resourceTable);
}
} // namespace framegraph
} // namespace cc
@@ -0,0 +1,204 @@
/****************************************************************************
Copyright (c) 2021 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "DevicePass.h"
#include "CallbackPass.h"
#include "FrameGraph.h"
#include "PassNode.h"
#include "ResourceNode.h"
#include "gfx-base/GFXCommandBuffer.h"
#include <algorithm>
namespace cc {
namespace framegraph {
DevicePass::DevicePass(const FrameGraph &graph, std::vector<PassNode *> const &subPassNodes) noexcept {
std::vector<RenderTargetAttachment> attachments;
for (const PassNode *const passNode : subPassNodes) {
append(graph, passNode, attachments);
}
std::sort(attachments.begin(), attachments.end(), RenderTargetAttachment::Sorter());
std::vector<const gfx::Texture *> renderTargets;
for (auto &attachment : attachments) {
const ResourceNode &resourceNode = graph.getResourceNode(attachment.textureHandle);
CC_ASSERT(resourceNode.virtualResource);
_attachments.emplace_back();
_attachments.back().attachment = std::move(attachment);
_attachments.back().renderTarget = static_cast<ResourceEntry<Texture> *>(resourceNode.virtualResource)->getDeviceResource();
//CC_ASSERT(_attachments.back().renderTarget); // back buffer doesn't have a device resource instance, for now
renderTargets.emplace_back(_attachments.back().renderTarget);
}
bool const multiSubPass = subPassNodes.size() > 1;
for (PassNode *const passNode : subPassNodes) {
_resourceTable.extract(graph, passNode, multiSubPass, renderTargets);
}
}
void DevicePass::execute() noexcept {
auto cmdBuff = gfx::Device::getInstance()->getCommandBuffer();
begin(cmdBuff);
for (Subpass &subPass : _subpasses) {
for (LogicPass &pass : subPass.logicPasses) {
gfx::Viewport &viewport = pass.customViewport ? pass.viewport : _viewport;
gfx::Rect & scissor = pass.customViewport ? pass.scissor : _scissor;
if (viewport != _curViewport) {
cmdBuff->setViewport(viewport);
_curViewport = viewport;
}
if (scissor != _curScissor) {
cmdBuff->setScissor(scissor);
_curScissor = scissor;
}
pass.pass->execute(_resourceTable);
}
next(cmdBuff);
}
end(cmdBuff);
}
void DevicePass::append(const FrameGraph &graph, const PassNode *passNode, std::vector<RenderTargetAttachment> &attachments) noexcept {
_subpasses.emplace_back();
Subpass &subPass = _subpasses.back();
do {
subPass.logicPasses.emplace_back();
LogicPass &logicPass = subPass.logicPasses.back();
logicPass.pass = passNode->_pass.get();
logicPass.customViewport = passNode->_customViewport;
logicPass.viewport = passNode->_viewport;
logicPass.scissor = passNode->_scissor;
std::for_each(passNode->_attachments.begin(), passNode->_attachments.end(), [&, this](const RenderTargetAttachment &attachment) {
append(graph, attachment, attachments);
});
passNode = passNode->_next;
} while (passNode);
}
void DevicePass::append(const FrameGraph &graph, const RenderTargetAttachment &attachment, std::vector<RenderTargetAttachment> &attachments) noexcept {
auto it = std::find_if(attachments.begin(), attachments.end(), [&attachment](const RenderTargetAttachment &x) {
return attachment.desc.usage == x.desc.usage && attachment.desc.slot == x.desc.slot;
});
if (it == attachments.end()) {
attachments.emplace_back(attachment);
_usedRenderTargetSlotMask |= 1 << attachment.desc.slot;
} else {
const ResourceNode &resourceNodeA = graph.getResourceNode(it->textureHandle);
const ResourceNode &resourceNodeB = graph.getResourceNode(attachment.textureHandle);
if (resourceNodeA.virtualResource == resourceNodeB.virtualResource) {
if (attachment.storeOp != gfx::StoreOp::DISCARD) it->storeOp = attachment.storeOp;
} else {
CC_ASSERT(attachment.desc.usage == RenderTargetAttachment::Usage::COLOR);
attachments.emplace_back(attachment);
for (uint8_t i = 0; i < RenderTargetAttachment::DEPTH_STENCIL_SLOT_START; ++i) {
if ((_usedRenderTargetSlotMask & (1 << i)) == 0) {
attachments.back().desc.slot = i;
break;
}
}
}
}
}
void DevicePass::begin(gfx::CommandBuffer *cmdBuff) noexcept {
if (_attachments.empty()) return;
gfx::RenderPassInfo rpInfo;
gfx::FramebufferInfo fboInfo;
float clearDepth = 1.f;
uint clearStencil = 0;
static std::vector<gfx::Color> clearColors;
clearColors.clear();
_viewport = gfx::Viewport();
_scissor = gfx::Rect();
for (uint i = 0; i < _attachments.size(); ++i) {
gfx::Texture *attachment = _attachments[i].renderTarget;
if (_attachments[i].attachment.desc.usage == RenderTargetAttachment::Usage::COLOR) {
rpInfo.colorAttachments.emplace_back();
rpInfo.colorAttachments.back().format = attachment ? attachment->getFormat() : gfx::Device::getInstance()->getColorFormat();
rpInfo.colorAttachments.back().loadOp = _attachments[i].attachment.desc.loadOp;
rpInfo.colorAttachments.back().storeOp = _attachments[i].attachment.storeOp;
rpInfo.colorAttachments.back().beginAccesses = _attachments[i].attachment.desc.beginAccesses;
rpInfo.colorAttachments.back().endAccesses = _attachments[i].attachment.desc.endAccesses;
fboInfo.colorTextures.push_back(_attachments[i].renderTarget);
clearColors.emplace_back(_attachments[i].attachment.desc.clearColor);
_viewport.width = _scissor.width = attachment ? attachment->getWidth() : gfx::Device::getInstance()->getNativeWidth();
_viewport.height = _scissor.height = attachment ? attachment->getHeight() : gfx::Device::getInstance()->getNativeHeight();
} else {
rpInfo.depthStencilAttachment.format = attachment ? attachment->getFormat() : gfx::Device::getInstance()->getDepthStencilFormat();
rpInfo.depthStencilAttachment.depthLoadOp = _attachments[i].attachment.desc.loadOp;
rpInfo.depthStencilAttachment.depthStoreOp = _attachments[i].attachment.storeOp;
rpInfo.depthStencilAttachment.stencilLoadOp = _attachments[i].attachment.desc.loadOp;
rpInfo.depthStencilAttachment.stencilStoreOp = _attachments[i].attachment.storeOp;
rpInfo.depthStencilAttachment.beginAccesses = _attachments[i].attachment.desc.beginAccesses;
rpInfo.depthStencilAttachment.endAccesses = _attachments[i].attachment.desc.endAccesses;
fboInfo.depthStencilTexture = _attachments[i].renderTarget;
clearDepth = _attachments[i].attachment.desc.clearDepth;
clearStencil = _attachments[i].attachment.desc.clearStencil;
}
}
_renderPass = RenderPass(rpInfo);
_renderPass.createTransient();
fboInfo.renderPass = _renderPass.get();
_fbo = Framebuffer(fboInfo);
_fbo.createTransient();
cmdBuff->beginRenderPass(_renderPass.get(), _fbo.get(), _scissor, clearColors.data(), clearDepth, clearStencil);
_curViewport = _viewport;
_curScissor = _scissor;
}
void DevicePass::next(gfx::CommandBuffer *cmdBuff) noexcept {
}
void DevicePass::end(gfx::CommandBuffer *cmdBuff) noexcept {
if (!_renderPass.get() || !_fbo.get()) return;
cmdBuff->endRenderPass();
_renderPass.destroyTransient();
_fbo.destroyTransient();
}
} // namespace framegraph
} // namespace cc
@@ -0,0 +1,87 @@
/****************************************************************************
Copyright (c) 2021 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#pragma once
#include "CallbackPass.h"
#include "DevicePassResourceTable.h"
#include "RenderTargetAttachment.h"
#include "gfx-base/GFXDef.h"
#include <string>
#include <vector>
namespace cc {
namespace framegraph {
class DevicePass final {
public:
DevicePass() = delete;
DevicePass(const FrameGraph &graph, std::vector<PassNode *> const &subPassNodes) noexcept;
DevicePass(const DevicePass &) = delete;
DevicePass(DevicePass &&) = delete;
~DevicePass() = default;
DevicePass &operator=(const DevicePass &) = delete;
DevicePass &operator=(DevicePass &&) = delete;
void execute() noexcept;
private:
struct LogicPass final {
Executable * pass{nullptr};
bool customViewport{false};
gfx::Viewport viewport;
gfx::Rect scissor;
};
struct Subpass final {
std::vector<LogicPass> logicPasses{};
};
struct Attachment final {
RenderTargetAttachment attachment;
gfx::Texture * renderTarget{nullptr};
};
void append(const FrameGraph &graph, const PassNode *passNode, std::vector<RenderTargetAttachment> &attachments) noexcept;
void append(const FrameGraph &graph, const RenderTargetAttachment &attachment, std::vector<RenderTargetAttachment> &attachments) noexcept;
void begin(gfx::CommandBuffer *cmdBuff) noexcept;
void next(gfx::CommandBuffer *cmdBuff) noexcept;
void end(gfx::CommandBuffer *cmdBuff) noexcept;
std::vector<Subpass> _subpasses{};
std::vector<Attachment> _attachments{};
uint16_t _usedRenderTargetSlotMask{0};
DevicePassResourceTable _resourceTable;
gfx::Viewport _viewport;
gfx::Rect _scissor;
gfx::Viewport _curViewport;
gfx::Rect _curScissor;
RenderPass _renderPass;
Framebuffer _fbo;
};
} // namespace framegraph
} // namespace cc
@@ -0,0 +1,91 @@
/****************************************************************************
Copyright (c) 2021 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "DevicePassResourceTable.h"
#include "FrameGraph.h"
#include "PassNode.h"
#include <algorithm>
namespace cc {
namespace framegraph {
gfx::GFXObject *DevicePassResourceTable::get(const ResourceDictionary &from, const Handle handle) noexcept {
const auto it = from.find(handle);
return it == from.cend() ? nullptr : it->second;
}
void DevicePassResourceTable::extract(const FrameGraph & graph,
const PassNode *const passNode,
bool multiSubPass,
std::vector<const gfx::Texture *> const &renderTargets) noexcept {
extract(graph, passNode->_reads, reads, multiSubPass, renderTargets);
extract(graph, passNode->_writes, writes, true, renderTargets);
if (passNode->_next) {
extract(graph, passNode->_next, multiSubPass, renderTargets);
}
}
void DevicePassResourceTable::extract(const FrameGraph & graph,
std::vector<Handle> const & from,
ResourceDictionary & to,
bool ignoreRenderTarget,
std::vector<const gfx::Texture *> const &renderTargets) noexcept {
std::for_each(from.cbegin(), from.cend(), [&](const Handle handle) {
if (to.find(handle) != to.cend()) {
return;
}
const ResourceNode &resourceNode = graph.getResourceNode(handle);
CC_ASSERT(resourceNode.virtualResource);
gfx::GFXObject *const deviceResource = resourceNode.virtualResource->getDeviceResource();
if (!deviceResource) {
return;
}
if (ignoreRenderTarget) {
bool const isRenderTarget =
std::find_if(
renderTargets.cbegin(),
renderTargets.cend(),
[&deviceResource](const gfx::Texture *const x) {
return deviceResource == x;
}) != renderTargets.cend();
if (isRenderTarget) {
return;
}
}
if (deviceResource) {
to.emplace(handle, deviceResource);
}
});
}
} // namespace framegraph
} // namespace cc
@@ -0,0 +1,82 @@
/****************************************************************************
Copyright (c) 2021 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#pragma once
#include "Handle.h"
#include "RenderTargetAttachment.h"
#include "Resource.h"
#include <unordered_map>
namespace cc {
namespace framegraph {
class PassNode;
class FrameGraph;
class DevicePassResourceTable final {
public:
DevicePassResourceTable() = default;
~DevicePassResourceTable() = default;
DevicePassResourceTable(const DevicePassResourceTable &) = delete;
DevicePassResourceTable(DevicePassResourceTable &&) = delete;
DevicePassResourceTable &operator=(const DevicePassResourceTable &) = delete;
DevicePassResourceTable &operator=(DevicePassResourceTable &&) = delete;
template <typename Type>
std::enable_if_t<std::is_base_of<gfx::GFXObject, typename Type::DeviceResource>::value, typename Type::DeviceResource *>
getRead(TypedHandle<Type> const handle) const noexcept;
template <typename Type>
std::enable_if_t<std::is_base_of<gfx::GFXObject, typename Type::DeviceResource>::value, typename Type::DeviceResource *>
getWrite(TypedHandle<Type> const handle) const noexcept;
private:
using ResourceDictionary = std::unordered_map<Handle, gfx::GFXObject *, Handle::Hasher>;
static gfx::GFXObject *get(const ResourceDictionary &from, const Handle handle) noexcept;
void extract(const FrameGraph &graph, const PassNode *const passNode, bool multiSubPass, std::vector<const gfx::Texture *> const &renderTargets) noexcept;
void extract(const FrameGraph &graph, std::vector<Handle> const &from, ResourceDictionary &to, bool ignoreRenderTarget, std::vector<const gfx::Texture *> const &renderTargets) noexcept;
ResourceDictionary reads{};
ResourceDictionary writes{};
friend class DevicePass;
};
template <typename Type>
std::enable_if_t<std::is_base_of<gfx::GFXObject, typename Type::DeviceResource>::value, typename Type::DeviceResource *>
DevicePassResourceTable::getRead(TypedHandle<Type> const handle) const noexcept {
return static_cast<Type::DeviceResource *>(get(reads, handle));
}
template <typename Type>
std::enable_if_t<std::is_base_of<gfx::GFXObject, typename Type::DeviceResource>::value, typename Type::DeviceResource *>
DevicePassResourceTable::getWrite(TypedHandle<Type> const handle) const noexcept {
return static_cast<Type::DeviceResource *>(get(writes, handle));
}
} // namespace framegraph
} // namespace cc
@@ -0,0 +1,623 @@
/****************************************************************************
Copyright (c) 2021 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "FrameGraph.h"
#include "PassNodeBuilder.h"
#include "Resource.h"
#include <algorithm>
#include <fstream>
#include <set>
namespace cc {
namespace framegraph {
namespace {
StringPool stringPool;
}
FrameGraph::~FrameGraph() {
gc(0);
}
StringHandle FrameGraph::stringToHandle(const char *const name) noexcept {
return stringPool.stringToHandle(name);
}
const char *FrameGraph::handleToString(const StringHandle &handle) noexcept {
return stringPool.handleToString(handle);
}
void FrameGraph::present(const Handle &input) noexcept {
struct PassDataPresent {};
static const StringHandle sNamePresent = FrameGraph::stringToHandle("Present");
const ResourceNode & resourceNode = getResourceNode(input);
CC_ASSERT(resourceNode.writer);
addPass<PassDataPresent>(
resourceNode.writer->_insertPoint, sNamePresent,
[&](PassNodeBuilder &builder, PassDataPresent &data) {
builder.read(input);
builder.sideEffect();
},
[](const PassDataPresent &data, const DevicePassResourceTable &table) {
});
}
void FrameGraph::presentLastVersion(const VirtualResource *const virtualResource) noexcept {
const auto it = std::find_if(_resourceNodes.rbegin(), _resourceNodes.rend(), [&virtualResource](const ResourceNode &node) {
return node.virtualResource == virtualResource;
});
CC_ASSERT(it != _resourceNodes.rend());
present(Handle(static_cast<Handle::IndexType>(it.base() - _resourceNodes.begin() - 1)));
}
void FrameGraph::presentFromBlackboard(const StringHandle &inputName) noexcept {
present(Handle(_blackboard.get(inputName)));
}
void FrameGraph::compile() noexcept {
sort();
cull();
computeResourceLifetime();
if (_merge) {
mergePassNodes();
}
computeStoreActionAndMemoryless();
generateDevicePasses();
}
void FrameGraph::execute() noexcept {
for (auto &pass : _devicePasses) {
pass->execute();
}
}
void FrameGraph::reset() noexcept {
_passNodes.clear();
_resourceNodes.clear();
_virtualResources.clear();
_devicePasses.clear();
_blackboard.clear();
}
void FrameGraph::gc(uint32_t const unusedFrameCount) noexcept {
Buffer::Allocator::getInstance().gc(unusedFrameCount);
Framebuffer::Allocator::getInstance().gc(unusedFrameCount);
RenderPass::Allocator::getInstance().gc(unusedFrameCount);
Texture::Allocator::getInstance().gc(unusedFrameCount);
}
Handle FrameGraph::create(VirtualResource *const virtualResource) noexcept {
_virtualResources.emplace_back(virtualResource);
return createResourceNode(virtualResource);
}
void FrameGraph::move(const TextureHandle from, const TextureHandle to, uint8_t mipmapLevel, uint8_t faceId, uint8_t arrayPosition) noexcept {
const ResourceNode &fromResourceNode = getResourceNode(from);
const ResourceNode &toResourceNode = getResourceNode(to);
CC_ASSERT(!fromResourceNode.virtualResource->isImported());
CC_ASSERT(fromResourceNode.writer);
CC_ASSERT(!toResourceNode.writer);
const gfx::TextureInfo &toTextureDesc = static_cast<ResourceEntry<Texture> *>(toResourceNode.virtualResource)->get().getDesc();
uint const toTextureWidth = toTextureDesc.width >> mipmapLevel;
uint const toTextureHeight = toTextureDesc.height >> mipmapLevel;
uint const toTextureDepth = toTextureDesc.depth >> mipmapLevel;
CC_ASSERT(toTextureWidth && toTextureHeight && toTextureDepth);
CC_ASSERT(toTextureDesc.levelCount > mipmapLevel && toTextureDesc.layerCount > arrayPosition);
CC_ASSERT(toTextureDesc.type == gfx::TextureType::CUBE && faceId < 6 || faceId == 0);
for (ResourceNode &resourceNode : _resourceNodes) {
if (resourceNode.virtualResource == fromResourceNode.virtualResource) {
resourceNode.virtualResource = toResourceNode.virtualResource;
}
}
for (const auto &passNode : _passNodes) {
for (auto &attachment : passNode->_attachments) {
const ResourceNode &attachmentResourceNode = getResourceNode(attachment.textureHandle);
if (attachmentResourceNode.virtualResource == toResourceNode.virtualResource) {
const gfx::TextureInfo &attachmentTextureDesc = static_cast<ResourceEntry<Texture> *>(attachmentResourceNode.virtualResource)->get().getDesc();
CC_ASSERT(attachmentTextureDesc.width >> attachment.level == toTextureWidth &&
attachmentTextureDesc.height >> attachment.level == toTextureHeight &&
attachmentTextureDesc.depth >> attachment.level == toTextureDepth);
attachment.level = mipmapLevel;
attachment.layer = faceId;
attachment.index = arrayPosition;
}
}
}
}
PassNode &FrameGraph::createPassNode(const PassInsertPoint insertPoint, const StringHandle &name, Executable *const pass) noexcept {
_passNodes.emplace_back(new PassNode(insertPoint, name, static_cast<ID>(_passNodes.size()), pass));
return *_passNodes.back();
}
Handle FrameGraph::createResourceNode(VirtualResource *const virtualResource) noexcept {
const size_t index = _resourceNodes.size();
ResourceNode resourceNode;
resourceNode.virtualResource = virtualResource;
resourceNode.version = virtualResource->_version;
_resourceNodes.emplace_back(resourceNode);
return Handle{static_cast<Handle::IndexType>(index)};
}
void FrameGraph::sort() noexcept {
std::stable_sort(_passNodes.begin(), _passNodes.end(), [](const auto &x, const auto &y) {
return x->_insertPoint < y->_insertPoint;
});
}
void FrameGraph::cull() noexcept {
for (const auto &passNode : _passNodes) {
passNode->_refCount = static_cast<uint32_t>(passNode->_writes.size()) + passNode->_sideEffect;
for (const Handle handle : passNode->_reads) {
CC_ASSERT(handle.isValid());
++_resourceNodes[handle].readerCount;
}
}
static std::vector<const ResourceNode *> stack;
stack.clear();
stack.reserve(_resourceNodes.size());
for (ResourceNode &resourceNode : _resourceNodes) {
if (resourceNode.readerCount == 0 && resourceNode.writer) {
stack.push_back(&resourceNode);
}
}
while (!stack.empty()) {
PassNode *const writerPassNode = stack.back()->writer;
stack.pop_back();
if (writerPassNode) {
CC_ASSERT(writerPassNode->_refCount);
if (--writerPassNode->_refCount == 0) {
CC_ASSERT(!writerPassNode->_sideEffect);
for (const Handle handle : writerPassNode->_reads) {
ResourceNode &resourceNode = _resourceNodes[handle];
if (--resourceNode.readerCount == 0) {
stack.push_back(&resourceNode);
}
}
}
}
}
for (const ResourceNode &resourceNode : _resourceNodes) {
resourceNode.virtualResource->_refCount += resourceNode.readerCount;
}
}
void FrameGraph::computeResourceLifetime() noexcept {
for (const auto &passNode : _passNodes) {
if (passNode->_refCount == 0) {
continue;
}
for (const Handle handle : passNode->_reads) {
_resourceNodes[handle].virtualResource->updateLifetime(passNode.get());
}
for (const Handle handle : passNode->_writes) {
_resourceNodes[handle].virtualResource->updateLifetime(passNode.get());
++_resourceNodes[handle].virtualResource->_writerCount;
}
std::sort(passNode->_attachments.begin(), passNode->_attachments.end(), RenderTargetAttachment::Sorter());
}
for (const auto &resource : _virtualResources) {
CC_ASSERT(!resource->_firstUsePass == !resource->_lastUsePass);
if (!resource->_firstUsePass || !resource->_lastUsePass) {
continue;
}
if (resource->_refCount == 0 && !resource->_lastUsePass->getRenderTargetAttachment(*this, resource.get())) {
continue;
}
resource->_firstUsePass->_resourceRequestArray.push_back(resource.get());
resource->_lastUsePass->_resourceReleaseArray.push_back(resource.get());
}
}
void FrameGraph::mergePassNodes() noexcept {
const size_t count = _passNodes.size();
size_t currentPassId = 0;
size_t lastPassId = 0;
while (currentPassId < count) {
const auto &currentPassNode = _passNodes[currentPassId];
if (currentPassNode->_refCount) {
break;
}
++currentPassId;
}
lastPassId = currentPassId;
while (++currentPassId < count) {
const auto &currentPassNode = _passNodes[currentPassId];
if (currentPassNode->_refCount == 0) {
continue;
}
const auto &lastPassNode = _passNodes[lastPassId];
if (lastPassNode->canMerge(*this, *currentPassNode)) {
auto *prevPassNode = lastPassNode.get();
uint16_t distance = 1;
while (prevPassNode->_next) {
prevPassNode = prevPassNode->_next;
++distance;
}
prevPassNode->_next = currentPassNode.get();
currentPassNode->_head = lastPassNode.get();
currentPassNode->_distanceToHead = distance;
currentPassNode->_refCount = 0;
const size_t attachmentCount = lastPassNode->_attachments.size();
for (size_t i = 0; i < attachmentCount; ++i) {
const RenderTargetAttachment &attachmentInLastPassNode = lastPassNode->_attachments[i];
const RenderTargetAttachment &attachmentInCurrentPassNode = currentPassNode->_attachments[i];
ResourceNode &resourceNode = _resourceNodes[attachmentInLastPassNode.textureHandle];
uint16_t & writeCount = resourceNode.virtualResource->_writerCount;
CC_ASSERT(writeCount > 1);
--writeCount;
resourceNode.readerCount += _resourceNodes[attachmentInCurrentPassNode.textureHandle].readerCount;
resourceNode.readerCount -= attachmentInCurrentPassNode.desc.loadOp == gfx::LoadOp::LOAD;
}
} else {
lastPassId = currentPassId;
}
}
}
void FrameGraph::computeStoreActionAndMemoryless() noexcept {
ID passId = 0;
bool lastPassSubPassEnable = false;
for (const auto &passNode : _passNodes) {
if (passNode->_refCount == 0) {
continue;
}
ID const oldPassId = passId;
passId += passNode->_subpass == false || lastPassSubPassEnable != passNode->_subpass;
passId += oldPassId == passId ? passNode->_hasClearedAttachment * !passNode->_clearActionIgnoreable : 0;
passNode->setDevicePassId(passId);
lastPassSubPassEnable = passNode->_subpass && !passNode->_subpassEnd;
}
const PassNode * lastPassNode = nullptr;
static std::set<VirtualResource *> renderTargets;
renderTargets.clear();
for (const auto &passNode : _passNodes) {
if (passNode->_refCount == 0) {
continue;
}
for (RenderTargetAttachment &attachment : passNode->_attachments) {
CC_ASSERT(attachment.textureHandle.isValid());
ResourceNode &resourceNode = getResourceNode(attachment.textureHandle);
if (resourceNode.virtualResource->isImported() || resourceNode.readerCount) {
if (passNode->_subpass) {
if (passNode->_devicePassId != resourceNode.virtualResource->_lastUsePass->_devicePassId) {
attachment.storeOp = gfx::StoreOp::STORE;
}
} else {
if (attachment.desc.writeMask) {
attachment.storeOp = gfx::StoreOp::STORE;
}
}
}
if (passNode->_subpass && attachment.desc.loadOp == gfx::LoadOp::LOAD && resourceNode.version > 1) {
ResourceNode *const resourceNodePrevVersion = getResourceNode(resourceNode.virtualResource, resourceNode.version - 1);
CC_ASSERT(resourceNodePrevVersion);
if (resourceNodePrevVersion->writer->_devicePassId == passNode->_devicePassId) {
attachment.desc.loadOp = gfx::LoadOp::DISCARD;
resourceNodePrevVersion->writer->getRenderTargetAttachment(*this, resourceNodePrevVersion->virtualResource)->storeOp = gfx::StoreOp::DISCARD;
}
}
if (attachment.desc.loadOp == gfx::LoadOp::LOAD) {
resourceNode.virtualResource->_neverLoaded = false;
}
if (attachment.storeOp == gfx::StoreOp::STORE) {
resourceNode.virtualResource->_neverStored = false;
}
renderTargets.emplace(resourceNode.virtualResource);
}
lastPassNode = passNode.get();
}
for (VirtualResource *const renderTarget : renderTargets) {
const gfx::TextureInfo &textureDesc = static_cast<ResourceEntry<Texture> *>(renderTarget)->get().getDesc();
renderTarget->_memoryless = renderTarget->_neverLoaded && renderTarget->_neverStored;
renderTarget->_memorylessMSAA = textureDesc.samples != gfx::SampleCount::X1 && renderTarget->_writerCount < 2;
// TODO: memoryless gfx::Texture
}
}
void FrameGraph::generateDevicePasses() noexcept {
Buffer::Allocator::getInstance().tick();
Framebuffer::Allocator::getInstance().tick();
RenderPass::Allocator::getInstance().tick();
Texture::Allocator::getInstance().tick();
ID passId = 1;
static std::vector<PassNode *> subPassNodes;
subPassNodes.clear();
for (const auto &passNode : _passNodes) {
if (passNode->_refCount == 0) {
continue;
}
if (passId != passNode->_devicePassId) {
_devicePasses.emplace_back(new DevicePass(*this, subPassNodes));
for (PassNode *const p : subPassNodes) {
p->releaseTransientResources();
}
subPassNodes.clear();
passId = passNode->_devicePassId;
}
passNode->requestTransientResources();
subPassNodes.emplace_back(passNode.get());
}
CC_ASSERT(subPassNodes.size() == 1);
static const StringHandle sNamePresent = FrameGraph::stringToHandle("Present");
if (subPassNodes.back()->_name != sNamePresent) {
_devicePasses.emplace_back(new DevicePass(*this, subPassNodes));
for (PassNode *const p : subPassNodes) {
p->releaseTransientResources();
}
}
}
// https://dreampuf.github.io/GraphvizOnline/
void FrameGraph::exportGraphViz(const std::string &path) {
std::ofstream out(path, std::ios::out | std::ios::binary);
//out.imbue(std::locale("chs", std::locale::ctype));
if (out.fail()) {
return;
}
out << "digraph framegraph {\n";
out << "rankdir = LR\n";
out << "bgcolor = black\n";
out << "node [shape=rectangle, fontname=\"helvetica\", fontsize=10]\n\n";
for (const auto &node : _passNodes) {
if (node->_head) {
continue;
}
out << "\"P" << node->_id << "\" [label=\"" << node->_name.str();
const PassNode *currPassNode = node.get();
if (currPassNode->_head) {
out << "\\n(merged by pass " << currPassNode->_head->_name.str() << ")";
} else {
while (currPassNode->_next) {
currPassNode = currPassNode->_next;
out << " & " << currPassNode->_name.str();
}
}
out << "\\nrefs: " << node->_refCount
<< "\\nseq: " << node->_id
<< "\\ndevice pass id: " << node->_devicePassId
<< "\", style=filled, fillcolor="
<< (node->_refCount ? "darkorange" : "darkorange4") << "]\n";
}
out << "\n";
for (const ResourceNode &node : _resourceNodes) {
if (node.writer && node.writer->_head) {
continue;
}
out << "\"R" << node.virtualResource->_id << "_" << +node.version << "\""
"[label=\""
<< node.virtualResource->_name.str() << "\\n(version: " << +node.version << ")"
<< "\\nrefs:" << node.virtualResource->_refCount;
if (node.virtualResource->_memoryless) {
out << "\\nMemoryless";
}
if (node.virtualResource->_memorylessMSAA) {
out << "\\nMemorylessMSAA";
}
PassNode *const writer = (node.writer && node.writer->_head) ? node.writer->_head : node.writer;
if (writer) {
out << "\\n";
const RenderTargetAttachment *const attachment = writer->getRenderTargetAttachment(*this, node.virtualResource);
if (attachment) {
switch (attachment->desc.loadOp) {
case gfx::LoadOp::DISCARD:
out << "Discard";
break;
case gfx::LoadOp::CLEAR:
out << "Clear";
break;
default:
out << "Load";
break;
}
out << ", ";
out << (attachment->storeOp == gfx::StoreOp::DISCARD ? "DontCare" : "Store");
out << "\\nWriteMask: 0x" << std::hex << (uint32_t)attachment->desc.writeMask << std::dec;
} else {
out << "Transfer";
}
}
out << "\", style=filled, fillcolor="
<< ((node.virtualResource->isImported()) ? (node.virtualResource->_refCount ? "palegreen" : "palegreen4") : node.version == 0 ? "pink" : (node.virtualResource->_refCount ? "skyblue" : "skyblue4"))
<< "]\n";
}
out << "\n";
for (const auto &node : _passNodes) {
if (node->_head) {
continue;
}
out << "P" << node->_id << " -> { ";
for (const Handle writer : node->_writes) {
out << "R" << _resourceNodes[writer].virtualResource->_id << "_" << +_resourceNodes[writer].version << " ";
}
out << "} [color=red]\n";
}
out << "\n";
for (const ResourceNode &node : _resourceNodes) {
if (node.writer && node.writer->_head) {
continue;
}
out << "R" << node.virtualResource->_id << "_" << +node.version << " -> { ";
for (const auto &passNode : _passNodes) {
if (passNode->_head) {
continue;
}
for (Handle read : passNode->_reads) {
const ResourceNode *readResourceNode = &_resourceNodes[read];
if (readResourceNode->writer && readResourceNode->writer->_head) {
const Handle resourceNodeHandlePrevVersion = readResourceNode->writer->_head->getWriteResourceNodeHandle(*this, readResourceNode->virtualResource);
CC_ASSERT(resourceNodeHandlePrevVersion.isValid());
readResourceNode = &getResourceNode(resourceNodeHandlePrevVersion);
}
if (readResourceNode->virtualResource->_id == node.virtualResource->_id &&
readResourceNode->version == node.version) {
out << "P" << passNode->_id << " ";
}
}
}
out << "} [color=green]\n";
}
for (const ResourceNode &node : _resourceNodes) {
if (node.writer && node.writer->_head) {
continue;
}
out << "R" << node.virtualResource->_id << "_" << +node.version << " -> { ";
for (const auto &passNode : _passNodes) {
if (passNode->_head) {
continue;
}
for (const RenderTargetAttachment &attachment : passNode->_attachments) {
const ResourceNode *readResourceNode = &_resourceNodes[attachment.textureHandle];
uint16_t const distanceToHead = readResourceNode->writer->_distanceToHead;
if (readResourceNode->writer && readResourceNode->writer->_head) {
const Handle resourceNodeHandleHead = readResourceNode->writer->_head->getWriteResourceNodeHandle(*this, readResourceNode->virtualResource);
CC_ASSERT(resourceNodeHandleHead.isValid());
readResourceNode = &getResourceNode(resourceNodeHandleHead);
}
if (readResourceNode->virtualResource == node.virtualResource &&
readResourceNode->version == node.version + 1 - distanceToHead) {
out << "P" << passNode->_id << " ";
}
}
}
out << "} [color=red4]\n";
}
out << "}" << std::endl;
out.close();
}
ResourceNode *FrameGraph::getResourceNode(const VirtualResource *const virtualResource, uint8_t version) noexcept {
const auto it = std::find_if(_resourceNodes.begin(), _resourceNodes.end(), [&](const ResourceNode &node) {
return node.version == version && node.virtualResource == virtualResource;
});
return it == _resourceNodes.end() ? nullptr : &(*it);
}
} // namespace framegraph
} // namespace cc
@@ -0,0 +1,145 @@
/****************************************************************************
Copyright (c) 2021 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#pragma once
#include "Blackboard.h"
#include "CallbackPass.h"
#include "DevicePass.h"
#include "PassNode.h"
#include "PassNodeBuilder.h"
#include "ResourceEntry.h"
#include "ResourceNode.h"
#include <cstdint>
#include <string>
#include <vector>
namespace cc {
namespace framegraph {
class FrameGraph final {
public:
using ResourceHandleBlackboard = Blackboard<StringHandle, Handle::IndexType, Handle::UNINITIALIZED>;
FrameGraph() = default;
~FrameGraph();
FrameGraph(const FrameGraph &) = delete;
FrameGraph(FrameGraph &&) = delete;
FrameGraph &operator=(const FrameGraph &) = delete;
FrameGraph &operator=(FrameGraph &&) = delete;
static StringHandle stringToHandle(const char *const name) noexcept;
static const char * handleToString(const StringHandle &handle) noexcept;
void present(const Handle &input) noexcept;
void presentLastVersion(const VirtualResource *const virtualResource) noexcept;
void presentFromBlackboard(const StringHandle &inputName) noexcept;
void compile() noexcept;
void execute() noexcept;
void reset() noexcept;
static void gc(uint32_t const unusedFrameCount = 30) noexcept;
template <typename Data, typename SetupMethod, typename ExecuteMethod>
CallbackPass<Data, ExecuteMethod> const &addPass(const PassInsertPoint insertPoint, const StringHandle &name, SetupMethod setup, ExecuteMethod &&execute) noexcept;
template <typename ResourceType>
TypedHandle<ResourceType> create(const StringHandle &name, typename const ResourceType::Descriptor &desc) noexcept;
Handle create(VirtualResource *const virtualResource) noexcept;
template <typename ResourceType>
TypedHandle<ResourceType> importExternal(const StringHandle &name, ResourceType &resource) noexcept;
void move(const TextureHandle from, const TextureHandle to, uint8_t mipmapLevel, uint8_t faceId, uint8_t arrayPosition) noexcept;
CC_INLINE ResourceNode &getResourceNode(const Handle handle) noexcept { return _resourceNodes[handle]; }
CC_INLINE const ResourceNode &getResourceNode(const Handle handle) const noexcept { return _resourceNodes[handle]; }
CC_INLINE ResourceHandleBlackboard &getBlackboard() noexcept { return _blackboard; }
void exportGraphViz(const std::string &path);
CC_INLINE void enableMerge(bool const enable) noexcept;
private:
PassNode & createPassNode(const PassInsertPoint insertPoint, const StringHandle &name, Executable *const pass) noexcept;
Handle createResourceNode(VirtualResource *const virtualResource) noexcept;
void sort() noexcept;
void cull() noexcept;
void computeResourceLifetime() noexcept;
void mergePassNodes() noexcept;
void computeStoreActionAndMemoryless() noexcept;
void generateDevicePasses() noexcept;
ResourceNode *getResourceNode(const VirtualResource *const virtualResource, uint8_t version) noexcept;
std::vector<std::unique_ptr<PassNode>> _passNodes{};
std::vector<ResourceNode> _resourceNodes{};
std::vector<std::unique_ptr<VirtualResource>> _virtualResources{};
std::vector<std::unique_ptr<DevicePass>> _devicePasses{};
ResourceHandleBlackboard _blackboard;
bool _merge{false};
friend class PassNode;
friend class PassNodeBuilder;
};
//////////////////////////////////////////////////////////////////////////
template <typename Data, typename SetupMethod, typename ExecuteMethod>
const CallbackPass<Data, ExecuteMethod> &FrameGraph::addPass(const PassInsertPoint insertPoint, const StringHandle &name, SetupMethod setup, ExecuteMethod &&execute) noexcept {
static_assert(sizeof(ExecuteMethod) < 1024, "Execute() lambda is capturing too much data.");
auto *const pass = new CallbackPass<Data, ExecuteMethod>(std::forward<ExecuteMethod>(execute));
PassNode & passNode = createPassNode(insertPoint, name, pass);
PassNodeBuilder builder(*this, passNode);
setup(builder, pass->getData());
return *pass;
}
template <typename ResourceType>
TypedHandle<ResourceType> FrameGraph::create(const StringHandle &name, typename const ResourceType::Descriptor &desc) noexcept {
auto *const virtualResource = new ResourceEntry<ResourceType>(name, static_cast<ID>(_virtualResources.size()), desc);
return TypedHandle<ResourceType>(create(virtualResource));
}
template <typename ResourceType>
TypedHandle<ResourceType> FrameGraph::importExternal(const StringHandle &name, ResourceType &resource) noexcept {
//CC_ASSERT(resource.Get()); // back buffer doesn't have a device resource instance, for now
auto *const virtualResource = new ResourceEntry<ResourceType>(name, static_cast<ID>(_virtualResources.size()), resource);
return TypedHandle<ResourceType>(create(virtualResource));
}
void FrameGraph::enableMerge(bool const enable) noexcept {
_merge = enable;
}
//////////////////////////////////////////////////////////////////////////
template <typename ResourceType>
void PassNodeBuilder::create(TypedHandle<ResourceType> &handle, const StringHandle &name, typename const ResourceType::Descriptor &desc) const noexcept {
handle = _graph.create<ResourceType>(name, desc);
}
template <typename ResourceType>
void PassNodeBuilder::importExternal(TypedHandle<ResourceType> &handle, const StringHandle &name, ResourceType &resource) const noexcept {
handle = _graph.importExternal(name, resource);
}
} // namespace framegraph
} // namespace cc
@@ -0,0 +1,46 @@
/****************************************************************************
Copyright (c) 2021 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#pragma once
#include "base/IndexHandle.h"
#include "base/StringPool.h"
namespace cc {
namespace framegraph {
using Handle = cc::IndexHandle<uint16_t>;
using StringHandle = cc::StringHandle;
using StringPool = cc::StringPool<false>;
template <typename T>
class TypedHandle final : public Handle {
public:
using Type = T;
using Handle::Handle;
};
} // namespace framegraph
} // namespace cc
@@ -0,0 +1,58 @@
/****************************************************************************
Copyright (c) 2021 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "PassInsertPointManager.h"
#include "base/Macros.h"
namespace cc {
namespace framegraph {
PassInsertPointManager &PassInsertPointManager::getInstance() noexcept {
static PassInsertPointManager instance;
return instance;
}
PassInsertPoint PassInsertPointManager::record(const char *const name, const PassInsertPoint point) noexcept {
StringHandle nameHandle = _stringPool.find(name);
if (nameHandle.isValid()) {
CC_ASSERT(point == get(nameHandle));
return get(nameHandle);
} else {
nameHandle = _stringPool.stringToHandle(name);
CC_ASSERT(nameHandle == _insertPoints.size());
_insertPoints.emplace_back(point);
return point;
}
}
PassInsertPoint PassInsertPointManager::get(const char *const name) const noexcept {
const StringHandle nameHandle = _stringPool.find(name);
CC_ASSERT(nameHandle.isValid());
return get(nameHandle);
}
} // namespace framegraph
} // namespace cc
@@ -0,0 +1,66 @@
/****************************************************************************
Copyright (c) 2021 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#pragma once
#include "Handle.h"
#include "base/Macros.h"
#include <vector>
namespace cc {
namespace framegraph {
using PassInsertPoint = uint16_t;
class PassInsertPointManager final {
public:
PassInsertPointManager(const PassInsertPointManager &) = delete;
PassInsertPointManager(PassInsertPointManager &&) = delete;
PassInsertPointManager &operator=(const PassInsertPointManager &) = delete;
PassInsertPointManager &operator=(PassInsertPointManager &&) = delete;
static PassInsertPointManager &getInstance() noexcept;
PassInsertPoint record(const char *const name, const PassInsertPoint point) noexcept;
PassInsertPoint get(const char *const name) const noexcept;
private:
PassInsertPointManager() noexcept = default;
~PassInsertPointManager() = default;
CC_INLINE PassInsertPoint get(const StringHandle name) const noexcept;
StringPool _stringPool;
std::vector<PassInsertPoint> _insertPoints{};
};
//////////////////////////////////////////////////////////////////////////
PassInsertPoint PassInsertPointManager::get(const StringHandle name) const noexcept {
return _insertPoints[name];
}
} // namespace framegraph
} // namespace cc
@@ -0,0 +1,200 @@
/****************************************************************************
Copyright (c) 2021 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "PassNode.h"
#include "FrameGraph.h"
#include "ResourceNode.h"
#include <algorithm>
namespace cc {
namespace framegraph {
PassNode::PassNode(const PassInsertPoint inserPoint, const StringHandle name, const ID &id, Executable *pass) noexcept
: _pass(pass),
_name(name),
_id(id),
_insertPoint(inserPoint) {
CC_ASSERT(_name.isValid());
}
Handle PassNode::read(FrameGraph &graph, const Handle &input) noexcept {
CC_ASSERT(check(graph, input, _writes));
const auto it = std::find_if(_reads.begin(), _reads.end(), [input](const Handle handle) {
return input == handle;
});
if (it == _reads.end()) {
_reads.push_back(input);
}
return input;
}
Handle PassNode::write(FrameGraph &graph, const Handle &output) noexcept {
CC_ASSERT(check(graph, output, _reads));
CC_ASSERT(std::find_if(_writes.begin(), _writes.end(), [output](const Handle handle) {
return output == handle;
}) == _writes.end());
const ResourceNode &nodeOldVersion = graph.getResourceNode(output);
nodeOldVersion.virtualResource->newVersion();
_sideEffect = nodeOldVersion.virtualResource->isImported();
const Handle handle = graph.createResourceNode(nodeOldVersion.virtualResource);
ResourceNode &nodeNewVersion = graph.getResourceNode(handle);
nodeNewVersion.writer = this;
_writes.push_back(handle);
return handle;
}
void PassNode::createRenderTargetAttachment(RenderTargetAttachment &&attachment) noexcept {
if (attachment.desc.usage == RenderTargetAttachment::Usage::COLOR) {
if (attachment.desc.slot == 0xff) {
for (uint8_t i = 0; i < RenderTargetAttachment::DEPTH_STENCIL_SLOT_START; ++i) {
if ((_usedRenderTargetSlotMask & (1 << i)) == 0) {
attachment.desc.slot = i;
break;
}
}
} else {
CC_ASSERT(attachment.desc.slot < RenderTargetAttachment::DEPTH_STENCIL_SLOT_START);
}
} else {
attachment.desc.slot = RenderTargetAttachment::DEPTH_STENCIL_SLOT_START + static_cast<uint8_t>(attachment.desc.usage) - 1;
if (attachment.desc.usage == RenderTargetAttachment::Usage::DEPTH_STENCIL) {
CC_ASSERT((_usedRenderTargetSlotMask & (1 << (RenderTargetAttachment::DEPTH_STENCIL_SLOT_START + static_cast<uint8_t>(RenderTargetAttachment::Usage::DEPTH) - 1))) == 0);
CC_ASSERT((_usedRenderTargetSlotMask & (1 << (RenderTargetAttachment::DEPTH_STENCIL_SLOT_START + static_cast<uint8_t>(RenderTargetAttachment::Usage::STENCIL) - 1))) == 0);
} else {
CC_ASSERT((_usedRenderTargetSlotMask & (1 << (RenderTargetAttachment::DEPTH_STENCIL_SLOT_START + static_cast<uint8_t>(attachment.desc.usage) - 1))) == 0);
}
}
CC_ASSERT((_usedRenderTargetSlotMask & (1 << attachment.desc.slot)) == 0);
_usedRenderTargetSlotMask |= (1 << attachment.desc.slot);
_attachments.emplace_back(attachment);
_hasClearedAttachment = _hasClearedAttachment || (attachment.desc.loadOp == gfx::LoadOp::CLEAR);
}
bool PassNode::canMerge(const FrameGraph &graph, const PassNode &passNode) const noexcept {
const size_t attachmentCount = _attachments.size();
if (passNode._hasClearedAttachment || attachmentCount != passNode._attachments.size()) {
return false;
}
for (size_t i = 0; i < attachmentCount; ++i) {
const RenderTargetAttachment &attachmentInPassNodeA = _attachments[i];
const RenderTargetAttachment &attachmentInPassNodeB = passNode._attachments[i];
if (attachmentInPassNodeA.desc.usage != attachmentInPassNodeB.desc.usage ||
attachmentInPassNodeA.desc.slot != attachmentInPassNodeB.desc.slot ||
attachmentInPassNodeA.desc.writeMask != attachmentInPassNodeB.desc.writeMask ||
attachmentInPassNodeA.level != attachmentInPassNodeB.level ||
attachmentInPassNodeA.layer != attachmentInPassNodeB.layer ||
attachmentInPassNodeA.index != attachmentInPassNodeB.index ||
graph.getResourceNode(attachmentInPassNodeA.textureHandle).virtualResource != graph.getResourceNode(attachmentInPassNodeB.textureHandle).virtualResource) {
return false;
}
}
return true;
}
RenderTargetAttachment *PassNode::getRenderTargetAttachment(const Handle &handle) noexcept {
const auto it = std::find_if(_attachments.begin(), _attachments.end(), [&handle](const RenderTargetAttachment &attachment) {
return attachment.textureHandle == handle;
});
return it == _attachments.end() ? nullptr : &(*it);
}
RenderTargetAttachment *PassNode::getRenderTargetAttachment(const FrameGraph &graph, const VirtualResource *const resource) noexcept {
const auto it = std::find_if(_attachments.begin(), _attachments.end(), [&](const RenderTargetAttachment &attachment) {
return graph.getResourceNode(attachment.textureHandle).virtualResource == resource;
});
return it == _attachments.end() ? nullptr : &(*it);
}
void PassNode::requestTransientResources() noexcept {
std::for_each(_resourceRequestArray.begin(), _resourceRequestArray.end(), [](VirtualResource *const resource) {
if (!resource->isImported()) {
resource->request();
}
});
if (_next) {
_next->requestTransientResources();
}
}
void PassNode::releaseTransientResources() noexcept {
std::for_each(_resourceReleaseArray.begin(), _resourceReleaseArray.end(), [](VirtualResource *const resource) {
if (!resource->isImported()) {
resource->release();
}
});
if (_next) {
_next->releaseTransientResources();
}
}
bool PassNode::check(FrameGraph &graph, const Handle &checkingHandle, std::vector<Handle> const &handles) const noexcept {
// render target can not do both read & write
const VirtualResource *const inputResource = graph.getResourceNode(checkingHandle).virtualResource;
const auto it = std::find_if(handles.begin(), handles.end(), [&](Handle handle) {
return inputResource == graph.getResourceNode(handle).virtualResource;
});
if (it == handles.end()) {
return true;
}
const Handle output = *it;
return std::find_if(_attachments.cbegin(), _attachments.cend(), [&output](const RenderTargetAttachment &attachment) {
return attachment.textureHandle == output;
}) == _attachments.end();
}
void PassNode::setDevicePassId(ID const id) noexcept {
_devicePassId = id;
if (_next) {
_next->setDevicePassId(id);
}
}
Handle PassNode::getWriteResourceNodeHandle(const FrameGraph &graph, const VirtualResource *const resource) const noexcept {
const auto it = std::find_if(_writes.begin(), _writes.end(), [&](const Handle handle) {
return graph.getResourceNode(handle).virtualResource == resource;
});
return it == _writes.end() ? Handle{} : *it;
}
} // namespace framegraph
} // namespace cc
@@ -0,0 +1,116 @@
/****************************************************************************
Copyright (c) 2021 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#pragma once
#include "CallbackPass.h"
#include "Handle.h"
#include "PassInsertPointManager.h"
#include "RenderTargetAttachment.h"
#include "VirtualResource.h"
#include "gfx-base/GFXDef.h"
#include <memory>
namespace cc {
namespace framegraph {
class FrameGraph;
class PassNode final {
public:
PassNode(const PassInsertPoint inserPoint, const StringHandle name, const ID &id, Executable *pass) noexcept;
~PassNode() = default;
PassNode(PassNode &&) noexcept = default;
PassNode(const PassNode &) = delete;
PassNode &operator=(const PassNode &) = delete;
PassNode &operator=(PassNode &&) = delete;
Handle read(FrameGraph &graph, const Handle &input) noexcept;
Handle write(FrameGraph &graph, const Handle &output) noexcept;
void createRenderTargetAttachment(RenderTargetAttachment &&attachment) noexcept;
CC_INLINE void sideEffect() noexcept;
CC_INLINE void subpass(bool clearActionIgnoreable, bool const end) noexcept;
CC_INLINE void setViewport(const gfx::Viewport &viewport, const gfx::Rect &scissor) noexcept;
private:
bool canMerge(const FrameGraph &graph, const PassNode &passNode) const noexcept;
RenderTargetAttachment *getRenderTargetAttachment(const Handle &handle) noexcept;
RenderTargetAttachment *getRenderTargetAttachment(const FrameGraph &graph, const VirtualResource *const resource) noexcept;
void requestTransientResources() noexcept;
void releaseTransientResources() noexcept;
bool check(FrameGraph &graph, const Handle &checkingHandle, std::vector<Handle> const &handles) const noexcept;
void setDevicePassId(ID const id) noexcept;
Handle getWriteResourceNodeHandle(const FrameGraph &graph, const VirtualResource *const resource) const noexcept;
std::unique_ptr<Executable> _pass{nullptr};
std::vector<Handle> _reads{};
std::vector<Handle> _writes{};
std::vector<RenderTargetAttachment> _attachments{};
std::vector<VirtualResource *> _resourceRequestArray{};
std::vector<VirtualResource *> _resourceReleaseArray{};
const StringHandle _name;
uint32_t _refCount{0};
PassNode * _head{nullptr};
PassNode * _next{nullptr};
uint16_t _distanceToHead{0};
uint16_t _usedRenderTargetSlotMask{0};
ID const _id{0};
ID _devicePassId{0};
const PassInsertPoint _insertPoint{0};
bool _sideEffect{false};
bool _subpass{false};
bool _subpassEnd{false};
bool _hasClearedAttachment{false};
bool _clearActionIgnoreable{false};
bool _customViewport{false};
gfx::Viewport _viewport;
gfx::Rect _scissor;
friend class FrameGraph;
friend class DevicePass;
friend class DevicePassResourceTable;
};
//////////////////////////////////////////////////////////////////////////
void PassNode::sideEffect() noexcept {
_sideEffect = true;
}
void PassNode::subpass(bool clearActionIgnoreable, bool const end) noexcept {
_subpass = true;
_clearActionIgnoreable = clearActionIgnoreable;
_subpassEnd = end;
}
void PassNode::setViewport(const gfx::Viewport &viewport, const gfx::Rect &scissor) noexcept {
_customViewport = true;
_viewport = viewport;
_scissor = scissor;
}
} // namespace framegraph
} // namespace cc
@@ -0,0 +1,72 @@
/****************************************************************************
Copyright (c) 2021 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "PassNodeBuilder.h"
#include "FrameGraph.h"
namespace cc {
namespace framegraph {
PassNodeBuilder::PassNodeBuilder(FrameGraph &graph, PassNode &passNode) noexcept
: _graph(graph),
_passNode(passNode) {
}
Handle PassNodeBuilder::read(const Handle &input) const noexcept {
return _passNode.read(_graph, input);
}
TextureHandle PassNodeBuilder::write(const TextureHandle &output, uint8_t mipmapLevel, uint8_t faceId, uint8_t arrayPosition, const RenderTargetAttachment::Descriptor &attachmentDesc) const noexcept {
const TextureHandle handle(_passNode.write(_graph, output));
RenderTargetAttachment attachment;
attachment.textureHandle = handle;
attachment.desc = attachmentDesc;
attachment.level = mipmapLevel;
attachment.layer = faceId;
attachment.index = arrayPosition;
_passNode.createRenderTargetAttachment(std::forward<RenderTargetAttachment>(attachment));
if (attachmentDesc.loadOp == gfx::LoadOp::LOAD) {
ResourceNode &outputResourceNode = _graph.getResourceNode(output);
++outputResourceNode.readerCount;
}
return handle;
}
TextureHandle PassNodeBuilder::write(const TextureHandle &output, const RenderTargetAttachment::Descriptor &attachmentDesc) const noexcept {
return write(output, 0, 0, 0, attachmentDesc);
}
void PassNodeBuilder::writeToBlackboard(const StringHandle &name, const Handle &handle) const noexcept {
_graph.getBlackboard().put(name, handle);
}
Handle PassNodeBuilder::readFromBlackboard(const StringHandle &name) const noexcept {
return Handle(_graph.getBlackboard().get(name));
}
} // namespace framegraph
} // namespace cc
@@ -0,0 +1,92 @@
/****************************************************************************
Copyright (c) 2021 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#pragma once
#include "PassNode.h"
namespace cc {
namespace framegraph {
class PassNodeBuilder final {
public:
PassNodeBuilder(FrameGraph &graph, PassNode &passNode) noexcept;
PassNodeBuilder() = delete;
~PassNodeBuilder() = default;
PassNodeBuilder(const PassNodeBuilder &) = delete;
PassNodeBuilder(PassNodeBuilder &&) = delete;
PassNodeBuilder &operator=(const PassNodeBuilder &) = delete;
PassNodeBuilder &operator=(PassNodeBuilder &&) = delete;
template <typename ResourceType>
void create(TypedHandle<ResourceType> &handle, const StringHandle &name, typename const ResourceType::Descriptor &desc) const noexcept;
template <typename ResourceType>
void importExternal(TypedHandle<ResourceType> &handle, const StringHandle &name, ResourceType &resource) const noexcept;
template <typename ResourceType>
TypedHandle<ResourceType> read(TypedHandle<ResourceType> const &input) const noexcept;
Handle read(const Handle &input) const noexcept;
template <typename ResourceType>
TypedHandle<ResourceType> write(TypedHandle<ResourceType> const &output) const noexcept;
TextureHandle write(const TextureHandle &output, uint8_t mipmapLevel, uint8_t faceId, uint8_t arrayPosition, const RenderTargetAttachment::Descriptor &attachmentDesc) const noexcept;
TextureHandle write(const TextureHandle &output, const RenderTargetAttachment::Descriptor &attachmentDesc) const noexcept;
CC_INLINE void sideEffect() const noexcept;
CC_INLINE void subpass(bool clearActionIgnoreable, bool const end) const noexcept;
CC_INLINE void setViewport(const gfx::Viewport &viewport, const gfx::Rect &scissor) noexcept;
void writeToBlackboard(const StringHandle &name, const Handle &handle) const noexcept;
Handle readFromBlackboard(const StringHandle &name) const noexcept;
private:
FrameGraph &_graph;
PassNode & _passNode;
};
//////////////////////////////////////////////////////////////////////////
template <typename ResourceType>
TypedHandle<ResourceType> PassNodeBuilder::read(TypedHandle<ResourceType> const &input) const noexcept {
return TypedHandle<ResourceType>(read(static_cast<const Handle &>(input)));
}
template <typename ResourceType>
TypedHandle<ResourceType> PassNodeBuilder::write(TypedHandle<ResourceType> const &output) const noexcept {
return TypedHandle<ResourceType>(_passNode.write(_graph, output));
}
void PassNodeBuilder::sideEffect() const noexcept {
_passNode.sideEffect();
}
void PassNodeBuilder::subpass(bool clearActionIgnoreable, bool const end) const noexcept {
_passNode.subpass(clearActionIgnoreable, end);
}
void PassNodeBuilder::setViewport(const gfx::Viewport &viewport, const gfx::Rect &scissor) noexcept {
_passNode.setViewport(viewport, scissor);
}
} // namespace framegraph
} // namespace cc
@@ -0,0 +1,83 @@
/****************************************************************************
Copyright (c) 2021 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#pragma once
#include "Resource.h"
namespace cc {
namespace framegraph {
struct RenderTargetAttachment final {
using StoreOp = gfx::StoreOp;
using LoadOp = gfx::LoadOp;
using Color = gfx::Color;
enum class Usage : uint8_t {
COLOR,
DEPTH,
STENCIL,
DEPTH_STENCIL,
};
struct Descriptor final {
Usage usage{Usage::COLOR};
uint8_t slot{0xff};
uint8_t writeMask{0xff};
LoadOp loadOp{LoadOp::DISCARD};
Color clearColor;
float clearDepth{1.f};
uint8_t clearStencil{0u};
std::vector<gfx::AccessType> beginAccesses;
std::vector<gfx::AccessType> endAccesses;
};
struct Sorter {
CC_INLINE bool operator()(const RenderTargetAttachment &a1, const RenderTargetAttachment &a2) const noexcept;
};
static constexpr uint8_t DEPTH_STENCIL_SLOT_START{13};
TextureHandle textureHandle{};
Descriptor desc;
uint8_t level{0};
uint8_t layer{0};
uint8_t index{0};
StoreOp storeOp{StoreOp::DISCARD};
};
CC_INLINE bool RenderTargetAttachment::Sorter::operator()(const RenderTargetAttachment &a1, const RenderTargetAttachment &a2) const noexcept {
if (a1.desc.usage < a2.desc.usage) {
return true;
} else if (a1.desc.usage == a2.desc.usage) {
return a1.desc.slot < a2.desc.slot;
} else {
return false;
}
}
} // namespace framegraph
} // namespace cc
@@ -0,0 +1,174 @@
/****************************************************************************
Copyright (c) 2021 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#pragma once
#include "ResourceAllocator.h"
#include "Handle.h"
#include "renderer/gfx-base/GFXBuffer.h"
#include "renderer/gfx-base/GFXDevice.h"
#include "renderer/gfx-base/GFXFramebuffer.h"
#include "renderer/gfx-base/GFXGlobalBarrier.h"
#include "renderer/gfx-base/GFXRenderPass.h"
#include "renderer/gfx-base/GFXTexture.h"
#include "renderer/gfx-base/GFXTextureBarrier.h"
namespace cc {
namespace framegraph {
template <typename DescriptorType>
struct ResourceDescriptorHasher final {
CC_INLINE uint32_t operator()(const DescriptorType &desc) const noexcept {
return 1;
}
};
template <typename DeviceResourceType, typename DescriptorType>
struct DeviceResourceCreator final {
CC_INLINE DeviceResourceType *operator()(const DescriptorType &desc) const noexcept {
return nullptr;
}
};
template <typename DeviceResourceType, typename DescriptorType,
typename DeviceResourceCreatorType = DeviceResourceCreator<DeviceResourceType, DescriptorType>,
typename DescriptorHasherType = ResourceDescriptorHasher<DescriptorType>>
class Resource final {
public:
using Allocator = ResourceAllocator<DeviceResourceType, DescriptorType, DeviceResourceCreatorType>;
using DescriptorHash = typename Allocator::DescriptorHash;
using DeviceResource = DeviceResourceType;
using Descriptor = DescriptorType;
using DescriptorHasher = DescriptorHasherType;
Resource() noexcept = default;
explicit Resource(const Descriptor &desc) noexcept;
~Resource() = default;
Resource(const Resource &) = default;
Resource(Resource &&) = default;
Resource &operator=(const Resource &) = default;
Resource &operator=(Resource &&) = default;
void createTransient() noexcept;
void createPersistent() noexcept;
void destroyTransient() noexcept;
void destroyPersistent() noexcept;
CC_INLINE DeviceResourceType *get() const noexcept;
CC_INLINE const Descriptor &getDesc() const noexcept;
private:
void computeHash() noexcept;
Descriptor _desc;
DescriptorHash _hash{0};
DeviceResourceType *_deviceObject{nullptr};
};
//////////////////////////////////////////////////////////////////////////
template <typename DeviceResourceType, typename DescriptorType, typename DeviceResourceCreatorType, typename DescriptorHasherType>
Resource<DeviceResourceType, DescriptorType, DeviceResourceCreatorType, DescriptorHasherType>::Resource(const Descriptor &desc) noexcept
: _desc(desc) {
}
template <typename DeviceResourceType, typename DescriptorType, typename DeviceResourceCreatorType, typename DescriptorHasherType>
void Resource<DeviceResourceType, DescriptorType, DeviceResourceCreatorType, DescriptorHasherType>::createTransient() noexcept {
computeHash();
_deviceObject = Allocator::getInstance().alloc(_desc, _hash);
}
template <typename DeviceResourceType, typename DescriptorType, typename DeviceResourceCreatorType, typename DescriptorHasherType>
void Resource<DeviceResourceType, DescriptorType, DeviceResourceCreatorType, DescriptorHasherType>::createPersistent() noexcept {
computeHash();
if (!_deviceObject) {
DeviceResourceCreatorType creator;
_deviceObject = creator(_desc);
}
}
template <typename DeviceResourceType, typename DescriptorType, typename DeviceResourceCreatorType, typename DescriptorHasherType>
void Resource<DeviceResourceType, DescriptorType, DeviceResourceCreatorType, DescriptorHasherType>::destroyTransient() noexcept {
CC_ASSERT(_hash);
Allocator::getInstance().free(_desc, _hash, _deviceObject);
_deviceObject = nullptr;
}
template <typename DeviceResourceType, typename DescriptorType, typename DeviceResourceCreatorType, typename DescriptorHasherType>
void Resource<DeviceResourceType, DescriptorType, DeviceResourceCreatorType, DescriptorHasherType>::destroyPersistent() noexcept {
if (_deviceObject) {
delete _deviceObject;
_deviceObject = nullptr;
}
}
template <typename DeviceResourceType, typename DescriptorType, typename DeviceResourceCreatorType, typename DescriptorHasherType>
DeviceResourceType *Resource<DeviceResourceType, DescriptorType, DeviceResourceCreatorType, DescriptorHasherType>::get() const noexcept {
return _deviceObject;
}
template <typename DeviceResourceType, typename DescriptorType, typename DeviceResourceCreatorType, typename DescriptorHasherType>
const DescriptorType &Resource<DeviceResourceType, DescriptorType, DeviceResourceCreatorType, DescriptorHasherType>::getDesc() const noexcept {
return _desc;
}
template <typename DeviceResourceType, typename DescriptorType, typename DeviceResourceCreatorType, typename DescriptorHasherType>
void Resource<DeviceResourceType, DescriptorType, DeviceResourceCreatorType, DescriptorHasherType>::computeHash() noexcept {
if (!_hash) {
DescriptorHasher hasher;
_hash = hasher(_desc);
}
}
//////////////////////////////////////////////////////////////////////////
#define DEFINE_GFX_RESOURCE(Type) \
template <> \
struct ResourceDescriptorHasher<gfx::Type##Info> final { \
CC_INLINE uint32_t operator()(const gfx::Type##Info &desc) const noexcept { \
return gfx::Type::computeHash(desc); \
} \
}; \
\
template <> \
struct DeviceResourceCreator<gfx::Type, gfx::Type##Info> final { \
CC_INLINE gfx::Type *operator()(const gfx::Type##Info &desc) const noexcept { \
return gfx::Device::getInstance()->create##Type(desc); \
} \
}; \
\
using Type = Resource<gfx::Type, gfx::Type##Info>; \
using Type##Handle = TypedHandle<Type>;
DEFINE_GFX_RESOURCE(Buffer)
DEFINE_GFX_RESOURCE(Framebuffer)
DEFINE_GFX_RESOURCE(GlobalBarrier)
DEFINE_GFX_RESOURCE(RenderPass)
DEFINE_GFX_RESOURCE(Texture)
DEFINE_GFX_RESOURCE(TextureBarrier)
} // namespace framegraph
} // namespace cc
@@ -0,0 +1,202 @@
/****************************************************************************
Copyright (c) 2021 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#pragma once
#include <algorithm>
#include "base/memory/Memory.h"
namespace cc {
namespace framegraph {
template <typename DeviceResourceType, typename DescriptorType, typename DeviceResourceCreatorType>
class ResourceAllocator final {
public:
using DescriptorHash = uint32_t;
using DeviceResourceCreator = DeviceResourceCreatorType;
ResourceAllocator(const ResourceAllocator &) = delete;
ResourceAllocator(ResourceAllocator &&) = delete;
ResourceAllocator &operator=(const ResourceAllocator &) = delete;
ResourceAllocator &operator=(ResourceAllocator &&) = delete;
static ResourceAllocator &getInstance() noexcept;
DeviceResourceType * alloc(const DescriptorType &desc, DescriptorHash const key) noexcept;
void free(const DescriptorType &desc, DescriptorHash const key, DeviceResourceType *const resource) noexcept;
CC_INLINE void tick() noexcept;
void gc(uint32_t const unusedFrameCount) noexcept;
private:
using DeviceResourcePtr = DeviceResourceType *;
struct Bucket {
explicit Bucket(DescriptorHash const key) noexcept : key(key) {}
using Pool = std::vector<DeviceResourcePtr>;
DescriptorHash key{0};
Pool pool{};
};
struct BucketGC final : public Bucket {
using Bucket::Bucket;
std::vector<uint64_t> ages{};
};
ResourceAllocator() noexcept = default;
~ResourceAllocator() = default;
template <typename Cache>
typename Bucket::Pool *getPool(DescriptorHash const key, Cache &from) noexcept;
BucketGC & getBucketGC(DescriptorHash const key) noexcept;
std::vector<BucketGC> _free{};
std::vector<Bucket> _inUse{};
uint64_t _age{0};
};
//////////////////////////////////////////////////////////////////////////
template <typename DeviceResourceType, typename DescriptorType, typename DeviceResourceCreatorType>
ResourceAllocator<DeviceResourceType, DescriptorType, DeviceResourceCreatorType> &ResourceAllocator<DeviceResourceType, DescriptorType, DeviceResourceCreatorType>::getInstance() noexcept {
static ResourceAllocator instance;
return instance;
}
template <typename DeviceResourceType, typename DescriptorType, typename DeviceResourceCreatorType>
DeviceResourceType *ResourceAllocator<DeviceResourceType, DescriptorType, DeviceResourceCreatorType>::alloc(const DescriptorType &desc, DescriptorHash const key) noexcept {
auto it = std::find_if(_free.begin(), _free.end(), [&key](const BucketGC &x) {
return key == x.key;
});
if (it == _free.end()) {
_free.emplace_back(key);
_inUse.emplace_back(key);
it = _free.end() - 1;
}
DeviceResourcePtr resource = nullptr;
if (it->pool.empty()) {
DeviceResourceCreator creator;
resource = creator(desc);
} else {
resource = it->pool.back();
it->pool.pop_back();
it->ages.pop_back();
}
getPool(key, _inUse)->emplace_back(resource);
return resource;
}
template <typename DeviceResourceType, typename DescriptorType, typename DeviceResourceCreatorType>
void ResourceAllocator<DeviceResourceType, DescriptorType, DeviceResourceCreatorType>::free(const DescriptorType &desc, DescriptorHash const key, DeviceResourceType *const resource) noexcept {
auto *pool = getPool(key, _inUse);
CC_ASSERT(!pool->empty());
auto it = std::find_if(pool->begin(), pool->end(), [&resource](DeviceResourcePtr x) {
return resource == x;
});
CC_ASSERT(it != pool->end());
pool->erase(it);
auto &freeBucket = getBucketGC(key);
freeBucket.pool.emplace_back(resource);
freeBucket.ages.emplace_back(_age);
}
template <typename DeviceResourceType, typename DescriptorType, typename DeviceResourceCreatorType>
void ResourceAllocator<DeviceResourceType, DescriptorType, DeviceResourceCreatorType>::tick() noexcept {
++_age;
}
template <typename DeviceResourceType, typename DescriptorType, typename DeviceResourceCreatorType>
void ResourceAllocator<DeviceResourceType, DescriptorType, DeviceResourceCreatorType>::gc(uint32_t const unusedFrameCount) noexcept {
std::for_each(_free.begin(), _free.end(), [&](BucketGC &bucket) {
const size_t count = bucket.ages.size();
if (!count) {
return;
}
size_t destroyBegin = count - 1;
for (size_t i = 0; i < count; ++i) {
if (_age - bucket.ages[i] < unusedFrameCount) {
continue;
}
size_t j = destroyBegin;
for (; j > i; --j) {
if (_age - bucket.ages[j] < unusedFrameCount) {
std::swap(bucket.ages[i], bucket.ages[j]);
std::swap(bucket.pool[i], bucket.pool[j]);
destroyBegin = j - 1;
break;
}
}
if (i >= j) {
destroyBegin = i - 1;
}
if (i >= destroyBegin) {
break;
}
}
while (++destroyBegin < count) {
CC_SAFE_DESTROY(bucket.pool.back());
bucket.pool.pop_back();
bucket.ages.pop_back();
}
});
}
template <typename DeviceResourceType, typename DescriptorType, typename DeviceResourceCreatorType>
template <typename Cache>
typename ResourceAllocator<DeviceResourceType, DescriptorType, DeviceResourceCreatorType>::Bucket::Pool *
ResourceAllocator<DeviceResourceType, DescriptorType, DeviceResourceCreatorType>::getPool(
DescriptorHash const key, Cache &from) noexcept {
auto it = std::find_if(from.begin(), from.end(), [&key](const Bucket &x) {
return key == x.key;
});
return it == from.end() ? nullptr : &it->pool;
}
template <typename DeviceResourceType, typename DescriptorType, typename DeviceResourceCreatorType>
typename ResourceAllocator<DeviceResourceType, DescriptorType, DeviceResourceCreatorType>::BucketGC &
ResourceAllocator<DeviceResourceType, DescriptorType, DeviceResourceCreatorType>::getBucketGC(DescriptorHash const key) noexcept {
auto it = std::find_if(_free.begin(), _free.end(), [&key](const BucketGC &x) {
return key == x.key;
});
CC_ASSERT(it != _free.end());
return *it;
}
} // namespace framegraph
} // namespace cc
@@ -0,0 +1,85 @@
/****************************************************************************
Copyright (c) 2021 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#pragma once
#include "VirtualResource.h"
namespace cc {
namespace framegraph {
template <typename ResourceType, typename Enable = std::enable_if_t<std::is_base_of<gfx::GFXObject, typename ResourceType::DeviceResource>::value>>
class ResourceEntry final : public VirtualResource {
public:
explicit ResourceEntry(const StringHandle name, ID const id, typename const ResourceType::Descriptor &desc) noexcept;
ResourceEntry(const StringHandle name, ID const id, const ResourceType &resource) noexcept;
ResourceEntry() = delete;
~ResourceEntry() = default;
ResourceEntry(const ResourceEntry &) = delete;
ResourceEntry(ResourceEntry &&) = delete;
ResourceEntry &operator=(const ResourceEntry &) = delete;
ResourceEntry &operator=(ResourceEntry &&) = delete;
void request() noexcept override;
void release() noexcept override;
typename ResourceType::DeviceResource *getDeviceResource() const noexcept override;
CC_INLINE const ResourceType &get() const noexcept { return _resource; }
private:
ResourceType _resource;
};
//////////////////////////////////////////////////////////////////////////
template <typename ResourceType, typename Enable>
ResourceEntry<ResourceType, Enable>::ResourceEntry(const StringHandle name, ID const id, typename const ResourceType::Descriptor &desc) noexcept
: VirtualResource(name, id, false),
_resource(desc) {
}
template <typename ResourceType, typename Enable>
ResourceEntry<ResourceType, Enable>::ResourceEntry(const StringHandle name, ID const id, const ResourceType &resource) noexcept
: VirtualResource(name, id, true),
_resource(resource) {
}
template <typename ResourceType, typename Enable>
void ResourceEntry<ResourceType, Enable>::request() noexcept {
_resource.createTransient();
}
template <typename ResourceType, typename Enable>
void ResourceEntry<ResourceType, Enable>::release() noexcept {
_resource.destroyTransient();
}
template <typename ResourceType, typename Enable>
typename ResourceType::DeviceResource *ResourceEntry<ResourceType, Enable>::getDeviceResource() const noexcept {
return _resource.get();
}
} // namespace framegraph
} // namespace cc
@@ -0,0 +1,39 @@
/****************************************************************************
Copyright (c) 2021 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#pragma once
namespace cc {
namespace framegraph {
struct ResourceNode final {
VirtualResource *virtualResource{nullptr};
PassNode * writer{nullptr};
uint32_t readerCount{0};
uint8_t version{0};
};
} // namespace framegraph
} // namespace cc
@@ -0,0 +1,44 @@
/****************************************************************************
Copyright (c) 2021 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "VirtualResource.h"
namespace cc {
namespace framegraph {
VirtualResource::VirtualResource(const StringHandle name, ID const id, bool const imported) noexcept
: _name(name),
_id(id),
_imported(imported) {
CC_ASSERT(_name.isValid());
}
void VirtualResource::updateLifetime(PassNode *const passNode) noexcept {
_firstUsePass = _firstUsePass ? _firstUsePass : passNode;
_lastUsePass = passNode;
}
} // namespace framegraph
} // namespace cc
@@ -0,0 +1,74 @@
/****************************************************************************
Copyright (c) 2021 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#pragma once
#include "renderer/gfx-base/GFXObject.h"
#include "Handle.h"
namespace cc {
namespace framegraph {
class PassNode;
using ID = uint16_t;
class VirtualResource {
public:
VirtualResource(const StringHandle name, ID const id, bool const imported) noexcept;
VirtualResource() noexcept = delete;
virtual ~VirtualResource() = default;
VirtualResource(const VirtualResource &) = delete;
VirtualResource(VirtualResource &&) = delete;
VirtualResource &operator=(const VirtualResource &) = delete;
VirtualResource &operator=(VirtualResource &&) = delete;
virtual void request() noexcept = 0;
virtual void release() noexcept = 0;
bool isImported() const noexcept { return _imported; }
void updateLifetime(PassNode *const passNode) noexcept;
void newVersion() noexcept { ++_version; }
virtual gfx::GFXObject *getDeviceResource() const noexcept = 0;
private:
PassNode * _firstUsePass{nullptr};
PassNode * _lastUsePass{nullptr};
const StringHandle _name;
uint32_t _refCount{0};
uint16_t _writerCount{0};
ID _id{0};
uint8_t _version{0};
bool const _imported{false};
bool _neverLoaded{true};
bool _neverStored{true};
bool _memoryless{false};
bool _memorylessMSAA{false};
friend class FrameGraph;
};
} // namespace framegraph
} // namespace cc
@@ -738,8 +738,8 @@ struct Offset {
struct Rect {
int x = 0;
int y = 0;
uint width = 1u;
uint height = 1u;
uint width = 0u;
uint height = 0u;
bool operator==(const Rect &rs) {
if (x == rs.x &&
@@ -44,19 +44,19 @@ uint RenderPass::computeHash() {
uint seed = 0;
if (_subpasses.size()) {
for (const SubpassInfo &subPass : _subpasses) {
for (const uint8_t iaIndex : subPass.inputs) {
for (const uint iaIndex : subPass.inputs) {
if (iaIndex >= _colorAttachments.size()) break;
seed += 2;
}
for (const uint8_t caIndex : subPass.colors) {
for (const uint caIndex : subPass.colors) {
if (caIndex >= _colorAttachments.size()) break;
seed += 2;
}
for (const uint8_t raIndex : subPass.resolves) {
for (const uint raIndex : subPass.resolves) {
if (raIndex >= _colorAttachments.size()) break;
seed += 2;
}
for (const uint8_t paIndex : subPass.preserves) {
for (const uint paIndex : subPass.preserves) {
if (paIndex >= _colorAttachments.size()) break;
seed += 2;
}
@@ -65,25 +65,25 @@ uint RenderPass::computeHash() {
}
}
for (const SubpassInfo &subPass : _subpasses) {
for (const uint8_t iaIndex : subPass.inputs) {
for (const uint iaIndex : subPass.inputs) {
if (iaIndex >= _colorAttachments.size()) break;
const ColorAttachment &ia = _colorAttachments[iaIndex];
seed ^= (uint)(ia.format) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
seed ^= (uint)ia.sampleCount + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
for (const uint8_t caIndex : subPass.colors) {
for (const uint caIndex : subPass.colors) {
if (caIndex >= _colorAttachments.size()) break;
const ColorAttachment &ca = _colorAttachments[caIndex];
seed ^= (uint)(ca.format) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
seed ^= (uint)ca.sampleCount + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
for (const uint8_t raIndex : subPass.resolves) {
for (const uint raIndex : subPass.resolves) {
if (raIndex >= _colorAttachments.size()) break;
const ColorAttachment &ca = _colorAttachments[raIndex];
seed ^= (uint)(ca.format) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
seed ^= (uint)ca.sampleCount + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
for (const uint8_t paIndex : subPass.preserves) {
for (const uint paIndex : subPass.preserves) {
if (paIndex >= _colorAttachments.size()) break;
const ColorAttachment &ca = _colorAttachments[paIndex];
seed ^= (uint)(ca.format) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
@@ -124,22 +124,22 @@ uint RenderPass::computeHash(const RenderPassInfo &info) {
uint seed = 0;
if (info.subpasses.size()) {
for (const SubpassInfo &subPass : info.subpasses) {
for (const uint8_t iaIndex : subPass.inputs) {
for (const uint iaIndex : subPass.inputs) {
if (iaIndex >= info.colorAttachments.size()) break;
const ColorAttachment &ia = info.colorAttachments[iaIndex];
seed += 4 + ia.beginAccesses.size() + ia.endAccesses.size();
}
for (const uint8_t caIndex : subPass.colors) {
for (const uint caIndex : subPass.colors) {
if (caIndex >= info.colorAttachments.size()) break;
const ColorAttachment &ca = info.colorAttachments[caIndex];
seed += 4 + ca.beginAccesses.size() + ca.endAccesses.size();
}
for (const uint8_t raIndex : subPass.resolves) {
for (const uint raIndex : subPass.resolves) {
if (raIndex >= info.colorAttachments.size()) break;
const ColorAttachment &ra = info.colorAttachments[raIndex];
seed += 4 + ra.beginAccesses.size() + ra.endAccesses.size();
}
for (const uint8_t paIndex : subPass.preserves) {
for (const uint paIndex : subPass.preserves) {
if (paIndex >= info.colorAttachments.size()) break;
const ColorAttachment &pa = info.colorAttachments[paIndex];
seed += 4 + pa.beginAccesses.size() + pa.endAccesses.size();
@@ -150,19 +150,19 @@ uint RenderPass::computeHash(const RenderPassInfo &info) {
}
}
for (const SubpassInfo &subpass : info.subpasses) {
for (const uint8_t iaIndex : subpass.inputs) {
for (const uint iaIndex : subpass.inputs) {
if (iaIndex >= info.colorAttachments.size()) break;
computeAttachmentHash(info.colorAttachments[iaIndex], seed);
}
for (const uint8_t caIndex : subpass.colors) {
for (const uint caIndex : subpass.colors) {
if (caIndex >= info.colorAttachments.size()) break;
computeAttachmentHash(info.colorAttachments[caIndex], seed);
}
for (const uint8_t raIndex : subpass.resolves) {
for (const uint raIndex : subpass.resolves) {
if (raIndex >= info.colorAttachments.size()) break;
computeAttachmentHash(info.colorAttachments[raIndex], seed);
}
for (const uint8_t paIndex : subpass.preserves) {
for (const uint paIndex : subpass.preserves) {
if (paIndex >= info.colorAttachments.size()) break;
computeAttachmentHash(info.colorAttachments[paIndex], seed);
}