Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(render): the post chain is a declared graph, not two framebuffers

esengine9ae02fa4db87
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 0c722c114..e280157a3 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -29,7 +29,7 @@ env:
test_registry_ondestroy test_view_api_matrix
test_shader_device test_draw_params test_texture_fb test_buffer_device
test_compressed_format test_batch_builder test_boundary_span test_webgpu_device
- test_text_edit
+ test_text_edit test_render_graph
jobs:
build-emscripten:
diff --git a/cmake/ESEngineSources.cmake b/cmake/ESEngineSources.cmake
index 5855bf139..5da82db81 100644
--- a/cmake/ESEngineSources.cmake
+++ b/cmake/ESEngineSources.cmake
@@ -93,7 +93,10 @@ if(ES_ENABLE_WEBGPU)
endif()
if(ES_ENABLE_POSTPROCESS)
- list(APPEND ESENGINE_SOURCES ${ESENGINE_ROOT}/src/esengine/renderer/frame/PostProcessPipeline.cpp)
+ list(APPEND ESENGINE_SOURCES
+ ${ESENGINE_ROOT}/src/esengine/renderer/frame/PostProcessPipeline.cpp
+ ${ESENGINE_ROOT}/src/esengine/renderer/graph/RenderGraph.cpp
+ )
endif()
if(ES_ENABLE_TILEMAP)
diff --git a/src/esengine/renderer/frame/PostProcessPipeline.cpp b/src/esengine/renderer/frame/PostProcessPipeline.cpp
index 1df1ed6a7..77768098b 100644
--- a/src/esengine/renderer/frame/PostProcessPipeline.cpp
+++ b/src/esengine/renderer/frame/PostProcessPipeline.cpp
@@ -78,6 +78,7 @@ GfxPixelFormat PostProcessPipeline::interFormat() const {
void PostProcessPipeline::ensureFBOs() {
const GfxPixelFormat interFmt = interFormat();
+ if (!graph_) graph_ = makeUnique<rg::RenderGraph>(device_);
if (!fboOriginalCreated_) {
FramebufferSpec origSpec;
origSpec.width = width_;
@@ -105,24 +106,6 @@ void PostProcessPipeline::ensureFBOs() {
}
}
- if (fbosCreated_) return;
-
- FramebufferSpec spec;
- spec.width = width_;
- spec.height = height_;
- spec.depthStencil = false;
- spec.colorFormat = interFmt;
- spec.linearFilter = true; // see origSpec above — the blur chain needs bilinear taps
-
- fboA_ = Framebuffer::create(device_, spec);
- fboB_ = Framebuffer::create(device_, spec);
-
- if (!fboA_ || !fboB_) {
- ES_LOG_ERROR("PostProcessPipeline: Failed to create framebuffers");
- return;
- }
-
- fbosCreated_ = true;
}
void PostProcessPipeline::shutdown() {
@@ -143,11 +126,9 @@ void PostProcessPipeline::shutdown() {
screen_quad_layout_ = VertexLayoutHandle::Invalid;
}
- fboA_.reset();
- fboB_.reset();
+ graph_.reset();
fboOriginal_.reset();
screenFBO_.reset();
- fbosCreated_ = false;
fboOriginalCreated_ = false;
screenCaptureActive_ = false;
screenFBOCreated_ = false;
@@ -172,11 +153,9 @@ void PostProcessPipeline::recreateGpuResources() {
for (auto& pass : passes_) { pass.paramUbo = BufferHandle::Invalid; pass.paramDirty = true; }
for (auto& pass : screenPasses_) { pass.paramUbo = BufferHandle::Invalid; pass.paramDirty = true; }
- fboA_.reset();
- fboB_.reset();
+ if (graph_) graph_->releasePool();
fboOriginal_.reset();
screenFBO_.reset();
- fbosCreated_ = false;
fboOriginalCreated_ = false;
screenFBOCreated_ = false;
screenCaptureActive_ = false;
@@ -194,12 +173,9 @@ void PostProcessPipeline::resize(u32 width, u32 height) {
fboOriginal_.reset();
fboOriginalCreated_ = false;
}
-
- if (fbosCreated_) {
- fboA_.reset();
- fboB_.reset();
- fbosCreated_ = false;
- }
+ // The pool is keyed by shape, so targets at the old size would never be
+ // handed out again — they would just sit there holding memory.
+ if (graph_) graph_->releasePool();
ensureFBOs();
@@ -368,7 +344,6 @@ void PostProcessPipeline::begin(const f32* clearColor) {
device_.setViewport(0, 0, width_, height_);
inFrame_ = true;
- currentFBO_ = 0;
}
void PostProcessPipeline::end() {
@@ -376,11 +351,6 @@ void PostProcessPipeline::end() {
auto* device = &device_;
- u32 enabledCount = 0;
- for (const auto& pass : passes_) {
- if (pass.enabled) enabledCount++;
- }
-
// Blend/depth/stencil/color-mask come from the fullscreen pass pipeline;
// scissor is dynamic state and must be dropped explicitly.
device->invalidatePipelineCache();
@@ -389,46 +359,18 @@ void PostProcessPipeline::end() {
sceneTexture_ = fboOriginal_->getColorAttachment();
fboOriginal_->unbind();
- if (enabledCount == 0) {
- blitToOutput(sceneTexture_);
- } else {
- TextureHandle inputTexture = sceneTexture_;
- currentFBO_ = 0;
-
- device->bindTexture(1, sceneTexture_);
- device->bindTexture(0, TextureHandle::Invalid);
-
- for (auto& pass : passes_) {
- if (!pass.enabled) continue;
-
- Framebuffer* targetFBO = (currentFBO_ == 0) ? fboA_.get() : fboB_.get();
- targetFBO->bind();
- device->setViewport(0, 0, width_, height_);
-
- renderPass(pass, inputTexture);
-
- inputTexture = targetFBO->getColorAttachment();
- currentFBO_ = 1 - currentFBO_;
- }
-
- Framebuffer* lastFBO = (currentFBO_ == 0) ? fboA_.get() : fboB_.get();
- lastFBO->unbind();
-
- blitToOutput(inputTexture);
- }
+ runChain(passes_, sceneTexture_);
device->invalidatePipelineCache();
inFrame_ = false;
output_target_fbo_ = FramebufferHandle::Default;
}
-void PostProcessPipeline::renderPass(PostProcessPass& pass, TextureHandle inputTexture) {
+void PostProcessPipeline::renderPass(PostProcessPass& pass, const rg::PassContext& ctx) {
Shader* shader = resourceManager_.getShader(pass.shader);
if (!shader) return;
auto* device = &device_;
- device->bindTexture(0, inputTexture);
-
applyPassPipeline(*shader);
const bool glsl = shader->language() == GfxShaderLanguage::GLSL_ES300;
if (glsl) {
@@ -488,8 +430,10 @@ void PostProcessPipeline::renderPass(PostProcessPass& pass, TextureHandle inputT
// Legacy loose-uniform path for raw-GLSL passes (addPass with a
// hand-created shader): resolution, in-order extra textures, and the
// DrawParams block lifted at creation.
+ // The pass's own size, not the screen's: a chain link that runs at a
+ // fraction of the reference size must sample by ITS texel grid.
if (shader->hasUniform("u_resolution")) {
- shader->setUniform("u_resolution", glm::vec2(static_cast<f32>(width_), static_cast<f32>(height_)));
+ shader->setUniform("u_resolution", glm::vec2(static_cast<f32>(ctx.width), static_cast<f32>(ctx.height)));
}
u32 extraUnit = 2;
for (const auto& [name, glId] : pass.textureUniforms) {
@@ -527,19 +471,17 @@ void PostProcessPipeline::setOutputViewport(u32 x, u32 y, u32 w, u32 h) {
output_vp_h_ = h;
}
-void PostProcessPipeline::blitToOutput(TextureHandle texture) {
+void PostProcessPipeline::blitPass() {
Shader* shader = resourceManager_.getShader(blitShader_);
if (!shader) return;
- auto* device = &device_;
- device->beginRenderPass({output_target_fbo_});
-
+ // The output rect is the one thing a pass does not get from its target: the
+ // graph sized the viewport to the whole target, and a camera writing into a
+ // shared surface owns only part of it.
if (output_vp_w_ > 0 && output_vp_h_ > 0) {
- device->setViewport(output_vp_x_, output_vp_y_, output_vp_w_, output_vp_h_);
+ device_.setViewport(output_vp_x_, output_vp_y_, output_vp_w_, output_vp_h_);
}
- device->bindTexture(0, texture);
-
applyPassPipeline(*shader);
shader->setUniform("u_texture", 0);
shader->commitParams();
@@ -547,14 +489,43 @@ void PostProcessPipeline::blitToOutput(TextureHandle texture) {
drawScreenQuad();
}
-u32 PostProcessPipeline::getSourceTexture() const {
- return fboOriginal_ ? static_cast<u32>(fboOriginal_->getColorAttachment()) : 0;
-}
+void PostProcessPipeline::runChain(std::vector<PostProcessPass>& passes, TextureHandle sceneTexture) {
+ if (!graph_) return;
-u32 PostProcessPipeline::getOutputTexture() const {
- if (!fboA_ || !fboB_) return 0;
- return static_cast<u32>((currentFBO_ == 0) ? fboA_->getColorAttachment()
- : fboB_->getColorAttachment());
+ graph_->begin(width_, height_);
+ const rg::ResourceId scene = graph_->importTexture(sceneTexture, width_, height_);
+ const rg::ResourceId out = graph_->importTarget(output_target_fbo_, width_, height_);
+
+ rg::TargetDesc desc;
+ desc.format = interFormat();
+ // Bilinear intermediates: fullscreen passes sample at texel centers (where
+ // LINEAR == NEAREST), but Kawase blur samples at half-texel offsets, whose
+ // NEAREST rounding is backend-dependent (GL and Dawn diverged visibly).
+ desc.linearFilter = true;
+
+ rg::ResourceId input = scene;
+ for (auto& pass : passes) {
+ if (!pass.enabled) continue;
+ rg::PassDesc node;
+ node.name = pass.name;
+ // The scene rides along as a second read for every pass because a
+ // composite (bloom's last link) needs the un-blurred image, and the
+ // shaders address it as unit 1 — the declaration IS that wiring.
+ node.reads = {input, scene};
+ node.write = graph_->createTarget(desc);
+ node.execute = [this, &pass](const rg::PassContext& ctx) { renderPass(pass, ctx); };
+ input = node.write;
+ graph_->addPass(std::move(node));
+ }
+
+ rg::PassDesc blit;
+ blit.name = "blit";
+ blit.reads = {input};
+ blit.write = out;
+ blit.execute = [this](const rg::PassContext&) { blitPass(); };
+ graph_->addPass(std::move(blit));
+
+ graph_->execute();
}
void PostProcessPipeline::ensureScreenFBO() {
@@ -602,51 +573,15 @@ void PostProcessPipeline::executeScreenPasses() {
if (!initialized_ || !screenFBOCreated_) return;
auto* device = &device_;
-
- u32 enabledCount = 0;
- for (const auto& pass : screenPasses_) {
- if (pass.enabled) enabledCount++;
- }
-
- if (enabledCount == 0) {
- device->invalidatePipelineCache();
- blitToOutput(screenFBO_->getColorAttachment());
- return;
- }
-
device->invalidatePipelineCache();
device->setScissorTest(false);
ensureFBOs();
- if (!fbosCreated_) return;
sceneTexture_ = screenFBO_->getColorAttachment();
screenFBO_->unbind();
- TextureHandle inputTexture = sceneTexture_;
- u32 pingPong = 0;
-
- device->bindTexture(1, sceneTexture_);
- device->bindTexture(0, TextureHandle::Invalid);
-
- for (auto& pass : screenPasses_) {
- if (!pass.enabled) continue;
-
- Framebuffer* targetFBO = (pingPong == 0) ? fboA_.get() : fboB_.get();
- targetFBO->bind();
- device->setViewport(0, 0, width_, height_);
-
- renderPass(pass, inputTexture);
-
- inputTexture = targetFBO->getColorAttachment();
- pingPong = 1 - pingPong;
- }
-
- Framebuffer* lastFBO = (pingPong == 0) ? fboA_.get() : fboB_.get();
- lastFBO->unbind();
- device->endRenderPass();
- device->setViewport(0, 0, width_, height_);
- blitToOutput(inputTexture);
+ runChain(screenPasses_, sceneTexture_);
device->invalidatePipelineCache();
}
diff --git a/src/esengine/renderer/frame/PostProcessPipeline.hpp b/src/esengine/renderer/frame/PostProcessPipeline.hpp
index 3afd0c1cb..bb865074d 100644
--- a/src/esengine/renderer/frame/PostProcessPipeline.hpp
+++ b/src/esengine/renderer/frame/PostProcessPipeline.hpp
@@ -16,6 +16,7 @@
#include "../../resource/Handle.hpp"
#include "../../math/Math.hpp"
#include "../rhi/Framebuffer.hpp"
+#include "../graph/RenderGraph.hpp"
#include <glm/glm.hpp>
#include <string>
@@ -58,8 +59,10 @@ struct PostProcessPass {
/**
* @brief Post-processing effects pipeline
*
- * @details Manages a chain of full-screen post-processing effects using
- * ping-pong framebuffers. Effects are applied in order.
+ * @details Owns the scene capture and the effect chains; the chains themselves
+ * are declared to a RenderGraph, which decides what physical targets
+ * they cost. The per-camera and screen-level chains are the same shape
+ * and go through the same builder.
*/
class PostProcessPipeline {
public:
@@ -156,16 +159,6 @@ public:
*/
void end();
- /**
- * @brief Gets the source framebuffer texture
- */
- u32 getSourceTexture() const;
-
- /**
- * @brief Gets the output framebuffer texture
- */
- u32 getOutputTexture() const;
-
/**
* @brief Checks if pipeline is initialized
*/
@@ -282,8 +275,11 @@ private:
void ensureScreenQuad();
void drawScreenQuad();
void applyPassPipeline(const Shader& shader);
- void renderPass(PostProcessPass& pass, TextureHandle inputTexture);
- void blitToOutput(TextureHandle texture);
+ void renderPass(PostProcessPass& pass, const rg::PassContext& ctx);
+ /// Declares one chain to the graph and runs it, ending in the output target.
+ void runChain(std::vector<PostProcessPass>& passes, TextureHandle sceneTexture);
+ /// The chain's last pass: the copy into the output target's viewport.
+ void blitPass();
/// Frees a pass's GPU-side param UBO (removePass/clearPasses/shutdown).
void releasePassResources(PostProcessPass& pass);
@@ -291,8 +287,7 @@ private:
RenderContext& context_;
resource::ResourceManager& resourceManager_;
- Unique<Framebuffer> fboA_;
- Unique<Framebuffer> fboB_;
+ Unique<rg::RenderGraph> graph_;
Unique<Framebuffer> fboOriginal_;
VertexLayoutHandle screen_quad_layout_ = VertexLayoutHandle::Invalid;
BufferHandle screen_quad_vbo_ = BufferHandle::Invalid;
@@ -302,13 +297,11 @@ private:
u32 width_ = 0;
u32 height_ = 0;
bool initialized_ = false;
- bool fbosCreated_ = false;
bool fboOriginalCreated_ = false;
bool inFrame_ = false;
bool bypass_ = false;
bool linear_output_ = false;
bool scene_needs_depth_ = false;
- u32 currentFBO_ = 0;
TextureHandle sceneTexture_ = TextureHandle::Invalid;
FramebufferHandle output_target_fbo_ = FramebufferHandle::Default;
diff --git a/src/esengine/renderer/graph/RenderGraph.cpp b/src/esengine/renderer/graph/RenderGraph.cpp
new file mode 100644
index 000000000..6b5c2479a
--- /dev/null
+++ b/src/esengine/renderer/graph/RenderGraph.cpp
@@ -0,0 +1,217 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file RenderGraph.cpp
+ * @brief Compile and run a frame's full-screen passes. See RenderGraph.hpp.
+ */
+#include "RenderGraph.hpp"
+
+#include "../../core/Log.hpp"
+#include "../rhi/GfxDevice.hpp"
+
+#include <algorithm>
+
+namespace esengine::rg {
+
+RenderGraph::RenderGraph(GfxDevice& device) : device_(device) {}
+
+RenderGraph::~RenderGraph() = default;
+
+void RenderGraph::begin(u32 refWidth, u32 refHeight) {
+ // Kept, not freed: the vectors' capacity is the whole point of reusing one
+ // graph across frames.
+ resources_.clear();
+ passes_.clear();
+ inputScratch_.clear();
+ for (auto& entry : pool_) entry.inUse = false;
+ finalTarget_ = kNoResource;
+ refWidth_ = refWidth;
+ refHeight_ = refHeight;
+ executed_ = 0;
+}
+
+ResourceId RenderGraph::importTexture(TextureHandle texture, u32 width, u32 height) {
+ Resource res;
+ res.kind = Kind::ImportedTexture;
+ res.texture = texture;
+ res.width = width;
+ res.height = height;
+ resources_.push_back(res);
+ return static_cast<ResourceId>(resources_.size() - 1);
+}
+
+ResourceId RenderGraph::importTarget(FramebufferHandle target, u32 width, u32 height) {
+ Resource res;
+ res.kind = Kind::ImportedTarget;
+ res.target = target;
+ res.width = width;
+ res.height = height;
+ resources_.push_back(res);
+ finalTarget_ = static_cast<ResourceId>(resources_.size() - 1);
+ return finalTarget_;
+}
+
+ResourceId RenderGraph::createTarget(const TargetDesc& desc) {
+ Resource res;
+ res.kind = Kind::Transient;
+ res.desc = desc;
+ resolveSize(res);
+ resources_.push_back(res);
+ return static_cast<ResourceId>(resources_.size() - 1);
+}
+
+void RenderGraph::addPass(PassDesc pass) {
+ passes_.push_back(std::move(pass));
+}
+
+void RenderGraph::resolveSize(Resource& res) const {
+ const f32 scale = res.desc.scale > 0.0f ? res.desc.scale : 1.0f;
+ res.width = std::max(1u, static_cast<u32>(static_cast<f32>(refWidth_) * scale));
+ res.height = std::max(1u, static_cast<u32>(static_cast<f32>(refHeight_) * scale));
+}
+
+void RenderGraph::cull(std::vector<bool>& live) const {
+ live.assign(passes_.size(), false);
+ if (finalTarget_ == kNoResource) return;
+
+ // Walk back from the final target: a resource is wanted if the image needs
+ // it, and a pass is live if it writes one. Reverse order because a pass can
+ // only be fed by a pass before it — the graph is built in submission order.
+ std::vector<bool> wanted(resources_.size(), false);
+ wanted[finalTarget_] = true;
+ for (i32 i = static_cast<i32>(passes_.size()) - 1; i >= 0; --i) {
+ const PassDesc& pass = passes_[static_cast<usize>(i)];
+ if (pass.write >= resources_.size() || !wanted[pass.write]) continue;
+ live[static_cast<usize>(i)] = true;
+ for (ResourceId read : pass.reads) {
+ if (read < resources_.size()) wanted[read] = true;
+ }
+ }
+}
+
+u32 RenderGraph::acquire(const Resource& res) {
+ for (u32 i = 0; i < pool_.size(); ++i) {
+ PooledTarget& entry = pool_[i];
+ if (entry.inUse || !entry.fbo) continue;
+ if (entry.width != res.width || entry.height != res.height) continue;
+ if (entry.format != res.desc.format || entry.linearFilter != res.desc.linearFilter) continue;
+ if (entry.depthStencil != res.desc.depthStencil) continue;
+ entry.inUse = true;
+ return i;
+ }
+
+ FramebufferSpec spec;
+ spec.width = res.width;
+ spec.height = res.height;
+ spec.depthStencil = res.desc.depthStencil;
+ spec.linearFilter = res.desc.linearFilter;
+ spec.colorFormat = res.desc.format;
+ auto fbo = Framebuffer::create(device_, spec);
+ if (!fbo) {
+ ES_LOG_ERROR("RenderGraph: failed to create a {}x{} target", res.width, res.height);
+ return kNoPooled;
+ }
+
+ PooledTarget entry;
+ entry.fbo = std::move(fbo);
+ entry.width = res.width;
+ entry.height = res.height;
+ entry.format = res.desc.format;
+ entry.linearFilter = res.desc.linearFilter;
+ entry.depthStencil = res.desc.depthStencil;
+ entry.inUse = true;
+ pool_.push_back(std::move(entry));
+ return static_cast<u32>(pool_.size() - 1);
+}
+
+void RenderGraph::release(Resource& res) {
+ if (res.pooled == kNoPooled) return;
+ pool_[res.pooled].inUse = false;
+ res.pooled = kNoPooled;
+ res.texture = TextureHandle::Invalid;
+}
+
+void RenderGraph::execute() {
+ std::vector<bool> live;
+ cull(live);
+
+ // Last read decides when a target goes back to the pool. A transient nobody
+ // reads is still written, so its life ends at the pass that wrote it.
+ for (auto& res : resources_) res.lastRead = -1;
+ for (usize i = 0; i < passes_.size(); ++i) {
+ if (!live[i]) continue;
+ for (ResourceId read : passes_[i].reads) {
+ if (read < resources_.size()) resources_[read].lastRead = static_cast<i32>(i);
+ }
+ }
+
+ for (usize i = 0; i < passes_.size(); ++i) {
+ if (!live[i]) continue;
+ PassDesc& pass = passes_[i];
+ Resource& target = resources_[pass.write];
+
+ if (target.kind == Kind::ImportedTexture) {
+ ES_LOG_ERROR("RenderGraph: pass '{}' writes an imported texture", pass.name);
+ continue;
+ }
+
+ FramebufferHandle fbo = FramebufferHandle::Default;
+ if (target.kind == Kind::Transient) {
+ if (target.pooled == kNoPooled) {
+ target.pooled = acquire(target);
+ if (target.pooled == kNoPooled) continue;
+ target.texture = pool_[target.pooled].fbo->getColorAttachment();
+ }
+ fbo = pool_[target.pooled].fbo->handle();
+ } else {
+ fbo = target.target;
+ }
+
+ RenderPassDesc rp{};
+ rp.target = fbo;
+ rp.clearColor = pass.clear;
+ if (pass.clear) {
+ for (u32 c = 0; c < 4; ++c) rp.clearColorValue[c] = pass.clearColor[c];
+ }
+ device_.beginRenderPass(rp);
+ device_.setViewport(0, 0, target.width, target.height);
+
+ inputScratch_.clear();
+ for (u32 unit = 0; unit < pass.reads.size(); ++unit) {
+ const ResourceId id = pass.reads[unit];
+ const TextureHandle tex = textureOf(id);
+ device_.bindTexture(unit, tex);
+ inputScratch_.push_back(tex);
+ }
+
+ if (pass.execute) {
+ PassContext ctx;
+ ctx.width = target.width;
+ ctx.height = target.height;
+ ctx.inputs = &inputScratch_;
+ pass.execute(ctx);
+ }
+ ++executed_;
+
+ // Recycled after the pass that last read it, which is what lets a linear
+ // chain run on two physical targets without anyone arranging it.
+ for (auto& res : resources_) {
+ if (res.kind == Kind::Transient && res.lastRead == static_cast<i32>(i)) release(res);
+ }
+ }
+}
+
+TextureHandle RenderGraph::textureOf(ResourceId id) const {
+ if (id >= resources_.size()) return TextureHandle::Invalid;
+ return resources_[id].texture;
+}
+
+void RenderGraph::releasePool() {
+ for (auto& res : resources_) {
+ res.pooled = kNoPooled;
+ if (res.kind == Kind::Transient) res.texture = TextureHandle::Invalid;
+ }
+ pool_.clear();
+}
+
+} // namespace esengine::rg
diff --git a/src/esengine/renderer/graph/RenderGraph.hpp b/src/esengine/renderer/graph/RenderGraph.hpp
new file mode 100644
index 000000000..5ceb3f4c7
--- /dev/null
+++ b/src/esengine/renderer/graph/RenderGraph.hpp
@@ -0,0 +1,181 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file RenderGraph.hpp
+ * @brief Full-screen passes as a declared graph: what each one reads, what it
+ * writes, and at what size — the graph decides the rest.
+ *
+ * The chain it replaces was two fixed framebuffers ping-ponged in order, which
+ * fixes three things it should not: every pass runs at full resolution, a pass
+ * can only read the one before it (plus the scene, wired to a hard-coded unit),
+ * and a disabled pass still costs its target. Here a pass names its inputs and
+ * its output's SCALE, so a blur chain runs at a quarter size, a composite reads
+ * both the blur and the scene, and a pass nothing reaches is never run.
+ *
+ * Physical targets come from a pool keyed by shape and handed back the moment a
+ * resource is last read, so the two-buffer ping-pong is what the allocator does
+ * on its own for a linear chain rather than something the caller arranges.
+ *
+ * The graph does NOT own scene geometry: the scene is rendered into an imported
+ * texture by the frame, and the graph runs over it. See PostProcessPipeline.
+ */
+#pragma once
+
+#include "../../core/Types.hpp"
+#include "../rhi/Framebuffer.hpp"
+#include "../rhi/GfxEnums.hpp"
+
+#include <functional>
+#include <string>
+#include <vector>
+
+namespace esengine {
+
+class GfxDevice;
+
+namespace rg {
+
+/** Index into the graph's resource table. */
+using ResourceId = u32;
+constexpr ResourceId kNoResource = static_cast<ResourceId>(-1);
+
+/**
+ * @brief Shape of a target the graph allocates.
+ *
+ * @details Size is a fraction of the graph's reference size rather than pixels:
+ * a half-size blur stays half-size when the window resizes, and the
+ * pool can hand the same physical target to any pass asking for that
+ * fraction.
+ */
+struct TargetDesc {
+ f32 scale = 1.0f;
+ GfxPixelFormat format = GfxPixelFormat::RGBA8;
+ bool linearFilter = true;
+ bool depthStencil = false;
+};
+
+/** What a pass's execute() is told: where it is drawing and what it may read. */
+struct PassContext {
+ u32 width = 0;
+ u32 height = 0;
+ /// The pass's declared reads, already bound to units 0..n-1, in order.
+ const std::vector<TextureHandle>* inputs = nullptr;
+
+ TextureHandle input(u32 i) const {
+ return (inputs && i < inputs->size()) ? (*inputs)[i] : TextureHandle::Invalid;
+ }
+};
+
+/**
+ * @brief One full-screen pass.
+ *
+ * @details `reads` are bound to texture units in declaration order, so a pass
+ * that wants the scene as its second sampler declares it second — the
+ * wiring is the declaration, not a convention the shader has to know.
+ */
+struct PassDesc {
+ std::string name;
+ std::vector<ResourceId> reads;
+ ResourceId write = kNoResource;
+ bool clear = false;
+ f32 clearColor[4] = {0.0f, 0.0f, 0.0f, 1.0f};
+ std::function<void(const PassContext&)> execute;
+};
+
+/**
+ * @brief A frame's full-screen passes, compiled and run.
+ *
+ * @details One instance is reused across frames: the graph is rebuilt every
+ * frame (cheap — a handful of passes) while the target pool it draws
+ * from persists, which is what makes reuse possible at all.
+ */
+class RenderGraph {
+public:
+ explicit RenderGraph(GfxDevice& device);
+ ~RenderGraph();
+
+ RenderGraph(const RenderGraph&) = delete;
+ RenderGraph& operator=(const RenderGraph&) = delete;
+
+ /** Starts a new graph. `refWidth`/`refHeight` are what `scale` is a fraction of. */
+ void begin(u32 refWidth, u32 refHeight);
+
+ /** A texture the graph reads but does not own — the scene capture. */
+ ResourceId importTexture(TextureHandle texture, u32 width, u32 height);
+
+ /**
+ * @brief The framebuffer the graph must end in (the screen, an editor FBO).
+ *
+ * @details Also what culling works back from: a pass no path reaches from
+ * here did not contribute to the image and is dropped.
+ */
+ ResourceId importTarget(FramebufferHandle target, u32 width, u32 height);
+
+ /** A target the graph allocates from the pool and recycles after its last read. */
+ ResourceId createTarget(const TargetDesc& desc);
+
+ void addPass(PassDesc pass);
+
+ /** Culls, assigns physical targets, and runs what survives. */
+ void execute();
+
+ /** The texture behind a resource — valid for imports, and for a transient
+ * only while it holds a physical target. */
+ TextureHandle textureOf(ResourceId id) const;
+
+ /** Drops every pooled target. For shutdown and for device loss, after which
+ * the handles the pool holds name nothing. */
+ void releasePool();
+
+ /** How many physical targets the pool is holding. Diagnostics and tests. */
+ u32 pooledTargetCount() const { return static_cast<u32>(pool_.size()); }
+
+ /** Passes the last execute() ran, after culling. Diagnostics and tests. */
+ u32 lastExecutedPassCount() const { return executed_; }
+
+private:
+ enum class Kind : u8 { ImportedTexture, ImportedTarget, Transient };
+
+ struct Resource {
+ Kind kind = Kind::Transient;
+ TargetDesc desc;
+ TextureHandle texture = TextureHandle::Invalid;
+ FramebufferHandle target = FramebufferHandle::Default;
+ u32 width = 0;
+ u32 height = 0;
+ /// Index into pool_ while a transient holds one; kNoPooled otherwise.
+ u32 pooled = kNoPooled;
+ i32 lastRead = -1;
+ };
+
+ struct PooledTarget {
+ Unique<Framebuffer> fbo;
+ u32 width = 0;
+ u32 height = 0;
+ GfxPixelFormat format = GfxPixelFormat::RGBA8;
+ bool linearFilter = true;
+ bool depthStencil = false;
+ bool inUse = false;
+ };
+
+ static constexpr u32 kNoPooled = static_cast<u32>(-1);
+
+ void resolveSize(Resource& res) const;
+ u32 acquire(const Resource& res);
+ void release(Resource& res);
+ /// Marks the passes that reach the imported target; false for everything else.
+ void cull(std::vector<bool>& live) const;
+
+ GfxDevice& device_;
+ std::vector<Resource> resources_;
+ std::vector<PassDesc> passes_;
+ std::vector<PooledTarget> pool_;
+ std::vector<TextureHandle> inputScratch_;
+ ResourceId finalTarget_ = kNoResource;
+ u32 refWidth_ = 0;
+ u32 refHeight_ = 0;
+ u32 executed_ = 0;
+};
+
+} // namespace rg
+} // namespace esengine
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 8bbc02385..614920f0e 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -106,6 +106,22 @@ target_include_directories(test_texture_fb PRIVATE
)
add_test(NAME test_texture_fb COMMAND test_texture_fb)
+# RenderGraph: compiles the graph against a MockGfxDevice and asserts on the
+# SEQUENCE of device calls — which target each pass opened, what it bound, and
+# how many physical targets a chain actually costs.
+add_executable(test_render_graph
+ renderer/test_render_graph.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/graph/RenderGraph.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/Texture.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/Framebuffer.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp
+)
+target_include_directories(test_render_graph PRIVATE
+ ${CMAKE_SOURCE_DIR}/src
+ ${CMAKE_SOURCE_DIR}/third_party/stb
+)
+add_test(NAME test_render_graph COMMAND test_render_graph)
+
# Buffer + CustomGeometry decoupling: compiles the converted classes against a
# MockGfxDevice. Linking proves they contain no GL; asserts confirm create/
# upload/attribute-setup/bind/delete route through GfxDevice.
diff --git a/tests/renderer/MockGfxDevice.hpp b/tests/renderer/MockGfxDevice.hpp
index ab832e255..c1b349c10 100644
--- a/tests/renderer/MockGfxDevice.hpp
+++ b/tests/renderer/MockGfxDevice.hpp
@@ -46,6 +46,12 @@ struct MockGfxDevice final : GfxDevice {
int setTextureParamsCalls = 0;
int generateMipmapsCalls = 0;
int createFramebufferCalls = 0;
+ // Ordered call logs, for harnesses asserting on a SEQUENCE rather than a
+ // count: which target each pass opened, and what was bound where.
+ struct Viewport { i32 x, y; u32 w, h; };
+ std::vector<RenderPassDesc> passLog;
+ std::vector<std::pair<u32, TextureHandle>> bindLog;
+ std::vector<Viewport> viewportLog;
int deleteFramebufferCalls = 0;
int createBufferCalls = 0;
int deleteBufferCalls = 0;
@@ -105,7 +111,7 @@ struct MockGfxDevice final : GfxDevice {
void init() override {}
void shutdown() override {}
- void setViewport(i32, i32, u32, u32) override {}
+ void setViewport(i32 x, i32 y, u32 w, u32 h) override { viewportLog.push_back({x, y, w, h}); }
void clearStencil(i32) override {}
void setScissorTest(bool) override {}
@@ -164,7 +170,10 @@ struct MockGfxDevice final : GfxDevice {
++setTextureParamsCalls;
}
void generateMipmaps(TextureHandle) override { ++generateMipmapsCalls; }
- void bindTexture(u32, TextureHandle) override { ++bindTextureCalls; }
+ void bindTexture(u32 unit, TextureHandle texture) override {
+ ++bindTextureCalls;
+ bindLog.push_back({unit, texture});
+ }
bool supportsCompressedFormat(GfxCompressedFormat) override { return compressedSupported; }
bool supportsFloatTargets() override { return true; }
@@ -220,7 +229,11 @@ struct MockGfxDevice final : GfxDevice {
return FramebufferHandle{nextFramebufferId++};
}
void deleteFramebuffer(FramebufferHandle) override { ++deleteFramebufferCalls; }
- void beginRenderPass(const RenderPassDesc& desc) override { ++beginRenderPassCalls; lastPassDesc = desc; }
+ void beginRenderPass(const RenderPassDesc& desc) override {
+ ++beginRenderPassCalls;
+ lastPassDesc = desc;
+ passLog.push_back(desc);
+ }
void endRenderPass() override { ++endRenderPassCalls; }
// Async readback seam: every request is immediately Ready (the GL shape);
diff --git a/tests/renderer/test_render_graph.cpp b/tests/renderer/test_render_graph.cpp
new file mode 100644
index 000000000..e1bfeb1d7
--- /dev/null
+++ b/tests/renderer/test_render_graph.cpp
@@ -0,0 +1,191 @@
+// Native CTest harness for the full-screen RenderGraph.
+//
+// Reuse, culling and target sizing are all invisible in a correct image, so
+// what this asserts on is the SEQUENCE of device calls a graph produces.
+
+#include "MockGfxDevice.hpp"
+#include "esengine/renderer/graph/RenderGraph.hpp"
+
+#include <cstdio>
+#include <string>
+#include <vector>
+
+using namespace esengine;
+
+static int g_failures = 0;
+#define CHECK(cond, msg) \
+ do { \
+ if (!(cond)) { std::printf("FAIL: %s\n", msg); ++g_failures; } \
+ else { std::printf("ok: %s\n", msg); } \
+ } while (0)
+
+namespace {
+
+rg::PassDesc fullscreen(const char* name, std::vector<rg::ResourceId> reads,
+ rg::ResourceId write, std::vector<std::string>* ran = nullptr) {
+ rg::PassDesc pass;
+ pass.name = name;
+ pass.reads = std::move(reads);
+ pass.write = write;
+ if (ran) {
+ const std::string label = name;
+ pass.execute = [ran, label](const rg::PassContext&) { ran->push_back(label); };
+ }
+ return pass;
+}
+
+} // namespace
+
+int main() {
+ // --- a linear chain runs on two physical targets ---
+ {
+ MockGfxDevice d;
+ rg::RenderGraph graph(d);
+ std::vector<std::string> ran;
+
+ graph.begin(256, 128);
+ const auto scene = graph.importTexture(TextureHandle{7}, 256, 128);
+ const auto out = graph.importTarget(FramebufferHandle{9}, 256, 128);
+ const auto a = graph.createTarget({});
+ const auto b = graph.createTarget({});
+ graph.addPass(fullscreen("extract", {scene}, a, &ran));
+ graph.addPass(fullscreen("blur", {a}, b, &ran));
+ graph.addPass(fullscreen("composite", {b, scene}, out, &ran));
+ graph.execute();
+
+ CHECK(ran.size() == 3, "every pass the image depends on runs");
+ CHECK(graph.pooledTargetCount() == 2, "a linear chain needs two physical targets");
+ CHECK(d.createFramebufferCalls == 2, "and allocates exactly those two");
+ CHECK(d.passLog.size() == 3, "one render pass opened per graph pass");
+ CHECK(d.passLog.back().target == FramebufferHandle{9},
+ "the last pass draws into the imported target");
+ }
+
+ // --- a third link reuses the first target rather than allocating ---
+ {
+ MockGfxDevice d;
+ rg::RenderGraph graph(d);
+
+ graph.begin(256, 128);
+ const auto scene = graph.importTexture(TextureHandle{7}, 256, 128);
+ const auto out = graph.importTarget(FramebufferHandle{9}, 256, 128);
+ const auto a = graph.createTarget({});
+ const auto b = graph.createTarget({});
+ const auto c = graph.createTarget({});
+ graph.addPass(fullscreen("p0", {scene}, a));
+ graph.addPass(fullscreen("p1", {a}, b));
+ graph.addPass(fullscreen("p2", {b}, c));
+ graph.addPass(fullscreen("p3", {c}, out));
+ graph.execute();
+
+ CHECK(graph.pooledTargetCount() == 2, "a longer chain still needs only two");
+ }
+
+ // --- a pass nothing reads is not run ---
+ {
+ MockGfxDevice d;
+ rg::RenderGraph graph(d);
+ std::vector<std::string> ran;
+
+ graph.begin(64, 64);
+ const auto scene = graph.importTexture(TextureHandle{7}, 64, 64);
+ const auto out = graph.importTarget(FramebufferHandle{9}, 64, 64);
+ const auto orphan = graph.createTarget({});
+ graph.addPass(fullscreen("dead", {scene}, orphan, &ran));
+ graph.addPass(fullscreen("blit", {scene}, out, &ran));
+ graph.execute();
+
+ CHECK(ran.size() == 1 && ran[0] == "blit", "the pass no path reaches is culled");
+ CHECK(d.createFramebufferCalls == 0, "and its target is never allocated");
+ }
+
+ // --- a pass declares its own size ---
+ {
+ MockGfxDevice d;
+ rg::RenderGraph graph(d);
+ u32 blurW = 0, blurH = 0;
+
+ graph.begin(200, 100);
+ const auto scene = graph.importTexture(TextureHandle{7}, 200, 100);
+ const auto out = graph.importTarget(FramebufferHandle{9}, 200, 100);
+ rg::TargetDesc half;
+ half.scale = 0.5f;
+ const auto small = graph.createTarget(half);
+ rg::PassDesc blur = fullscreen("blur", {scene}, small);
+ blur.execute = [&](const rg::PassContext& ctx) { blurW = ctx.width; blurH = ctx.height; };
+ graph.addPass(std::move(blur));
+ graph.addPass(fullscreen("composite", {small, scene}, out));
+ graph.execute();
+
+ CHECK(blurW == 100 && blurH == 50, "a half-scale pass runs at half the reference size");
+ CHECK(d.viewportLog.size() >= 1 && d.viewportLog[0].w == 100 && d.viewportLog[0].h == 50,
+ "the viewport follows the target, not the screen");
+ }
+
+ // --- reads bind in declaration order ---
+ {
+ MockGfxDevice d;
+ rg::RenderGraph graph(d);
+ TextureHandle first = TextureHandle::Invalid, second = TextureHandle::Invalid;
+
+ graph.begin(64, 64);
+ const auto scene = graph.importTexture(TextureHandle{7}, 64, 64);
+ const auto out = graph.importTarget(FramebufferHandle{9}, 64, 64);
+ const auto blurred = graph.createTarget({});
+ graph.addPass(fullscreen("blur", {scene}, blurred));
+ rg::PassDesc composite = fullscreen("composite", {blurred, scene}, out);
+ composite.execute = [&](const rg::PassContext& ctx) {
+ first = ctx.input(0);
+ second = ctx.input(1);
+ };
+ graph.addPass(std::move(composite));
+ graph.execute();
+
+ CHECK(second == TextureHandle{7}, "a pass reads the scene because it declared it second");
+ CHECK(first != TextureHandle::Invalid && first != second,
+ "and the blur result as its first input");
+ CHECK(d.bindLog.size() == 3, "each read is bound once, at its declared unit");
+ CHECK(d.bindLog[1].first == 0 && d.bindLog[2].first == 1,
+ "units follow declaration order");
+ }
+
+ // --- the pool outlives the frame ---
+ {
+ MockGfxDevice d;
+ rg::RenderGraph graph(d);
+
+ for (int frame = 0; frame < 3; ++frame) {
+ graph.begin(64, 64);
+ const auto scene = graph.importTexture(TextureHandle{7}, 64, 64);
+ const auto out = graph.importTarget(FramebufferHandle{9}, 64, 64);
+ const auto mid = graph.createTarget({});
+ graph.addPass(fullscreen("blur", {scene}, mid));
+ graph.addPass(fullscreen("blit", {mid}, out));
+ graph.execute();
+ }
+
+ CHECK(d.createFramebufferCalls == 1, "three frames of the same graph allocate once");
+ graph.releasePool();
+ CHECK(graph.pooledTargetCount() == 0, "releasePool drops what device loss invalidated");
+ }
+
+ // --- nothing runs without a declared output ---
+ {
+ MockGfxDevice d;
+ rg::RenderGraph graph(d);
+ std::vector<std::string> ran;
+
+ graph.begin(64, 64);
+ const auto scene = graph.importTexture(TextureHandle{7}, 64, 64);
+ const auto mid = graph.createTarget({});
+ graph.addPass(fullscreen("blur", {scene}, mid, &ran));
+ graph.execute();
+
+ // Not a no-op worth being lenient about: with no imported target, the
+ // default framebuffer is the screen, and a stray pass would draw on it.
+ CHECK(ran.empty(), "a graph with no output runs nothing");
+ }
+
+ std::printf(g_failures == 0 ? "\nALL PASS\n" : "\n%d FAILURE(S)\n", g_failures);
+ return g_failures == 0 ? 0 : 1;
+}