Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
RenderGraph.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
7#include "RenderGraph.hpp"
8
9#include "../../core/Log.hpp"
10#include "../rhi/GfxDevice.hpp"
11
12#include <algorithm>
13
14namespace esengine::rg {
15
17 : device_(device), pool_(pool) {}
18
20 : device_(device), ownedPool_(makeUnique<TargetPool>(device)), pool_(*ownedPool_) {}
21
23
24// =============================================================================
25// PassTimer
26// =============================================================================
27
29 if (state_ == 0) {
30 // The device says whether it can time by whether it will make a query.
31 const u32 probe = device_.createTimerQuery();
32 state_ = probe != 0 ? 1 : 2;
33 arming_ = device_.timesPassesByArming();
34 if (probe != 0) queries_.push_back(probe); // kept: it is the first slot's query
35 }
36 return state_ == 1;
37}
38
39u32 PassTimer::queryFor(u32 frame, u32 index) {
40 const usize at = static_cast<usize>(frame) * kMaxPasses + index;
41 if (queries_.size() <= at) queries_.resize(at + 1, 0);
42 if (queries_[at] == 0) queries_[at] = device_.createTimerQuery();
43 return queries_[at];
44}
45
46bool PassTimer::poll(Frame& frame) {
47 bool all = true;
48 for (Slot& slot : frame.slots) {
49 if (slot.done) continue;
50 u64 ns = 0;
51 if (device_.getTimerQueryNs(slot.query, &ns)) {
52 slot.done = true;
53 slot.ms = static_cast<f32>(ns) / 1.0e6f;
54 } else {
55 all = false;
56 }
57 }
58 return all;
59}
60
62 if (state_ != 1) return;
63 if (device_.timerDisjoint()) {
64 // Timing was disturbed: what is in flight is meaningless.
65 ++framesDisjoint_;
66 for (Frame& f : frames_) f.inflight = false;
67 }
68 for (u32 i = 0; i < kFrames; ++i) {
69 Frame& f = frames_[i];
70 if (!f.inflight || !poll(f)) continue;
71 f.inflight = false;
72 ++framesRead_;
73 if (frameNo_[i] <= lastNo_) continue; // an older frame finishing after a newer one: skip
74 lastNo_ = frameNo_[i];
75 last_.clear();
76 lastTotal_ = 0.0f;
77 for (const Slot& slot : f.slots) {
78 lastTotal_ += slot.ms;
79 bool merged = false;
80 for (Entry& e : last_) {
81 if (e.name == slot.name) { e.ms += slot.ms; merged = true; break; }
82 }
83 if (!merged) last_.push_back({slot.name, slot.ms});
84 }
85 }
86 ++counter_;
87 // Every slot still waiting on the device: this frame is not timed, and the device answers for the ones it has. Overwriting
88 // the oldest instead, a renderer that hands the device frames faster than it finishes them (a GPU-bound game, a page with no
89 // frame cap) dropped every frame before its answer came, and read the first frame's times for as long as it ran. A slot the
90 // device has not answered in a long while is given up on, so a lost query does not stop the timer.
91 const u32 next = (cur_ + 1) % kFrames;
92 if (frames_[next].inflight && counter_ - frameNo_[next] < kGiveUpFrames) {
93 timing_ = false;
94 ++framesSkipped_;
95 return;
96 }
97 if (frames_[next].inflight) ++framesDropped_;
98 cur_ = next;
99 frames_[cur_].slots.clear();
100 frames_[cur_].inflight = false;
101 frameNo_[cur_] = counter_;
102 timing_ = true;
103}
104
106 if (state_ != 1 || !timing_) return;
107 end();
108 frames_[cur_].inflight = !frames_[cur_].slots.empty();
109}
110
111void PassTimer::segment(const std::string& name) {
112 if (state_ != 1 || !timing_ || arming_ || !open_) return;
113 const std::string label = pass_ + "/" + name;
114 end();
115 Frame& f = frames_[cur_];
116 if (f.slots.size() >= kMaxPasses) return;
117 const u32 query = queryFor(cur_, static_cast<u32>(f.slots.size()));
118 if (query == 0) return;
119 Slot slot;
120 slot.name = names_.insert(label).first->c_str();
121 slot.query = query;
122 f.slots.push_back(slot);
123 device_.beginTimerQuery(query);
124 open_ = true;
125}
126
127void PassTimer::begin(const std::string& name) {
128 if (state_ != 1 || !timing_) return;
129 end();
130 pass_ = name;
131 Frame& f = frames_[cur_];
132 if (f.slots.size() >= kMaxPasses) return;
133 const u32 query = queryFor(cur_, static_cast<u32>(f.slots.size()));
134 if (query == 0) return;
135 Slot slot;
136 slot.name = names_.insert(name).first->c_str();
137 slot.query = query;
138 f.slots.push_back(slot);
139 if (arming_) device_.armPassTimer(query);
140 else device_.beginTimerQuery(query);
141 open_ = true;
142}
143
145 if (!open_) return;
146 open_ = false;
147 if (arming_) device_.armPassTimer(0);
148 else device_.endTimerQuery();
149}
150
151
152void RenderGraph::begin(u32 refWidth, u32 refHeight) {
153 // Kept, not freed: the vectors' capacity is the whole point of reusing one
154 // graph across frames.
155 resources_.clear();
156 passes_.clear();
157 inputScratch_.clear();
158 finalTarget_ = kNoResource;
159
160 // Only what THIS graph borrowed goes back: the pool is shared with the
161 // frame's other chains and with whatever holds a target across them.
162 for (const TargetHandle handle : borrowed_) pool_.release(handle);
163 borrowed_.clear();
164 // The pool's OWNER ticks its clock. A borrowed one is ticked once per frame
165 // by the frame; ticking it per chain would age a target faster on a scene
166 // that happens to have more cameras.
167 if (ownedPool_) pool_.age();
168
169 refWidth_ = refWidth;
170 refHeight_ = refHeight;
171 executed_ = 0;
172}
173
175 Resource res;
176 res.kind = Kind::ImportedTexture;
177 res.texture = texture;
178 res.width = width;
179 res.height = height;
180 resources_.push_back(res);
181 return static_cast<ResourceId>(resources_.size() - 1);
182}
183
185 TextureHandle readable) {
186 Resource res;
187 res.kind = Kind::ImportedTarget;
188 res.target = target;
189 res.texture = readable;
190 res.width = width;
191 res.height = height;
192 resources_.push_back(res);
193 const ResourceId id = static_cast<ResourceId>(resources_.size() - 1);
194 if (output) finalTarget_ = id;
195 return id;
196}
197
199 Resource res;
200 res.kind = Kind::Transient;
201 res.desc = desc;
202 resolveSize(res);
203 resources_.push_back(res);
204 return static_cast<ResourceId>(resources_.size() - 1);
205}
206
208 const ResourceId id = createTarget(desc);
209 Resource& res = resources_[id];
210 res.pooled = acquire(res);
211 if (res.pooled == kNoTarget) return kNoResource;
212 res.texture = pool_.textureOf(res.pooled);
213 return id;
214}
215
217 if (id >= resources_.size()) return FramebufferHandle::Default;
218 const Resource& res = resources_[id];
219 if (res.kind == Kind::ImportedTarget) return res.target;
220 if (res.pooled == kNoTarget) return FramebufferHandle::Default;
221 return pool_.framebufferOf(res.pooled);
222}
223
225 passes_.push_back(std::move(pass));
226}
227
228void RenderGraph::resolveSize(Resource& res) const {
229 // An absolute size is the target saying its texels are its own — a shadow
230 // atlas divides into tiles of a fixed size, so a fraction of the window
231 // would change how many maps fit when the window changed.
232 if (res.desc.width > 0 && res.desc.height > 0) {
233 res.width = res.desc.width;
234 res.height = res.desc.height;
235 return;
236 }
237 const f32 scale = res.desc.scale > 0.0f ? res.desc.scale : 1.0f;
238 res.width = std::max(1u, static_cast<u32>(static_cast<f32>(refWidth_) * scale));
239 res.height = std::max(1u, static_cast<u32>(static_cast<f32>(refHeight_) * scale));
240}
241
242void RenderGraph::cull() {
243 std::vector<bool>& live = live_;
244 live.assign(passes_.size(), false);
245 if (finalTarget_ == kNoResource) return;
246
247 // Walk back from the final target: a resource is wanted if the image needs
248 // it, and a pass is live if it writes one. Reverse order because a pass can
249 // only be fed by a pass before it — the graph is built in submission order.
250 std::vector<bool>& wanted = wanted_;
251 wanted.assign(resources_.size(), false);
252 wanted[finalTarget_] = true;
253 for (i32 i = static_cast<i32>(passes_.size()) - 1; i >= 0; --i) {
254 const PassDesc& pass = passes_[static_cast<usize>(i)];
255 if (!pass.keep && (pass.write >= resources_.size() || !wanted[pass.write])) continue;
256 live[static_cast<usize>(i)] = true;
257 for (ResourceId read : pass.reads) {
258 if (read < resources_.size()) wanted[read] = true;
259 }
260 // A dependency is wanted on the same terms as a read: the pass that
261 // produces it contributed to the image even though nothing binds it.
262 for (ResourceId dep : pass.dependencies) {
263 if (dep < resources_.size()) wanted[dep] = true;
264 }
265 }
266}
267
268TargetHandle RenderGraph::acquire(const Resource& res) {
269 TargetShape shape;
270 shape.width = res.width;
271 shape.height = res.height;
272 shape.format = res.desc.format;
273 shape.linearFilter = res.desc.linearFilter;
274 shape.depthStencil = res.desc.depthStencil;
275 shape.samples = res.desc.samples;
276 shape.gbuffer = res.desc.gbuffer;
277 shape.storage = res.desc.storage;
278 const TargetHandle handle = pool_.acquire(shape);
279 if (handle != kNoTarget) borrowed_.push_back(handle);
280 return handle;
281}
282
283void RenderGraph::release(Resource& res) {
284 if (res.pooled == kNoTarget) return;
285 pool_.release(res.pooled);
286 res.pooled = kNoTarget;
287 res.texture = TextureHandle::Invalid;
288}
289
291 cull();
292 const std::vector<bool>& live = live_;
293
294 // Last read decides when a target goes back to the pool. A transient nobody
295 // reads is still written, so its life ends at the pass that wrote it.
296 for (auto& res : resources_) res.lastRead = -1;
297 for (usize i = 0; i < passes_.size(); ++i) {
298 if (!live[i]) continue;
299 for (ResourceId read : passes_[i].reads) {
300 if (read < resources_.size()) resources_[read].lastRead = static_cast<i32>(i);
301 }
302 for (ResourceId dep : passes_[i].dependencies) {
303 if (dep < resources_.size()) resources_[dep].lastRead = static_cast<i32>(i);
304 }
305 }
306
307 // The last live pass to draw on each resource: after it nothing continues on that target, so its multisampled attachments, resolved by
308 // then, need not be kept.
309 std::vector<i32>& lastWriter = last_writer_;
310 lastWriter.assign(resources_.size(), -1);
311 for (usize i = 0; i < passes_.size(); ++i) {
312 if (live[i] && passes_[i].write < resources_.size()) lastWriter[passes_[i].write] = static_cast<i32>(i);
313 }
314
316 std::vector<ResourceId> inFlight;
317 std::vector<TextureHandle> inFlightTextures;
318 auto touchesPending = [&](ResourceId id) {
319 if (id >= resources_.size()) return false;
320 const Resource& resource = resources_[id];
321 // An opaque external framebuffer can alias a pooled attachment. The backbuffer cannot.
322 if (resource.kind == Kind::ImportedTarget && resource.target != FramebufferHandle::Default &&
323 resource.texture == TextureHandle::Invalid) return true;
324 const auto tex = resource.texture;
325 return std::find(inFlight.begin(), inFlight.end(), id) != inFlight.end() ||
326 (tex != TextureHandle::Invalid &&
327 std::find(inFlightTextures.begin(), inFlightTextures.end(), tex) != inFlightTextures.end());
328 };
329
330 for (usize i = 0; i < passes_.size(); ++i) {
331 if (!live[i]) continue;
332 PassDesc& pass = passes_[i];
333 Resource& target = resources_[pass.write];
334
335 if (target.kind == Kind::ImportedTexture) {
336 ES_LOG_ERROR("RenderGraph: pass '{}' writes an imported texture", pass.name);
337 continue;
338 }
339
341 if (target.kind == Kind::Transient) {
342 if (target.pooled == kNoTarget) {
343 target.pooled = acquire(target);
344 if (target.pooled == kNoTarget) continue;
345 target.texture = pool_.textureOf(target.pooled);
346 }
347 fbo = pool_.framebufferOf(target.pooled);
348 } else {
349 fbo = target.target;
350 }
351
352 // The pool can give the same texture a different graph id before the next pass.
353 if (pending != kNoAsyncComputeFence &&
354 (pass.compute || touchesPending(pass.write) ||
355 std::any_of(pass.reads.begin(), pass.reads.end(), touchesPending) ||
356 std::any_of(pass.dependencies.begin(), pass.dependencies.end(), touchesPending))) {
357 device_.graphicsWaitOnAsyncComputeJob(pending);
358 pending = kNoAsyncComputeFence;
359 }
360
361 if (timer_) timer_->begin(pass.name);
362 if (pass.compute) {
363 // A dispatch is not a draw: it runs between render passes, with nothing bound for it by the graph.
364 // The pass before it is still open on a device that leaves one open until the next begins; a dispatch needs it closed.
365 device_.endRenderPass();
366 inputScratch_.clear();
367 for (const ResourceId id : pass.reads) inputScratch_.push_back(textureOf(id));
368 if (pass.execute) {
370 ctx.width = target.width;
371 ctx.height = target.height;
372 ctx.inputs = &inputScratch_;
373 ctx.output = target.texture;
374 const bool scoped = pass.asyncCompute && !timer_ && device_.asyncComputeEnabled() &&
375 device_.supportsAsyncCompute() && device_.beginAsyncComputeJob(pass.computePriority);
376 pass.execute(ctx);
377 if (scoped) {
378 pending = device_.endAsyncComputeJob();
379 if (pending != kNoAsyncComputeFence) {
380 inFlight = pass.reads;
381 inFlight.insert(inFlight.end(), pass.dependencies.begin(), pass.dependencies.end());
382 inFlight.push_back(pass.write);
383 inFlightTextures.clear();
384 for (ResourceId id : inFlight) inFlightTextures.push_back(textureOf(id));
385 }
386 }
387 }
388 ++executed_;
389 if (timer_) timer_->end();
390 for (auto& res : resources_) {
391 if (res.kind == Kind::Transient && res.lastRead == static_cast<i32>(i)) release(res);
392 }
393 continue;
394 }
395
396 RenderPassDesc rp{};
397 rp.target = fbo;
398 rp.discardMultisampled = target.kind == Kind::Transient && lastWriter[pass.write] == static_cast<i32>(i);
399 rp.discardDepth = pass.discardDepth;
400 rp.clearColor = pass.clear;
401 rp.clearDepth = pass.clearDepth;
402 if (pass.clear) {
403 for (u32 c = 0; c < 4; ++c) rp.clearColorValue[c] = pass.clearColor[c];
404 }
405 if (pass.clearViewportOnly && pass.viewportW > 0 && pass.viewportH > 0) {
406 rp.clearX = static_cast<i32>(pass.viewportX);
407 rp.clearY = static_cast<i32>(pass.viewportY);
408 rp.clearW = pass.viewportW;
409 rp.clearH = pass.viewportH;
410 }
411 device_.beginRenderPass(rp);
412 if (pass.viewportW > 0 && pass.viewportH > 0) {
413 device_.setViewport(pass.viewportX, pass.viewportY, pass.viewportW, pass.viewportH);
414 } else {
415 device_.setViewport(0, 0, target.width, target.height);
416 }
417
418 inputScratch_.clear();
419 for (u32 unit = 0; unit < pass.reads.size(); ++unit) {
420 const ResourceId id = pass.reads[unit];
421 const TextureHandle tex = textureOf(id);
422 device_.bindTexture(unit, tex);
423 inputScratch_.push_back(tex);
424 }
425
426 if (pass.execute) {
428 ctx.width = target.width;
429 ctx.height = target.height;
430 ctx.inputs = &inputScratch_;
431 pass.execute(ctx);
432 }
433 ++executed_;
434 if (timer_) timer_->end();
435
436 // Recycled after the pass that last read it, which is what lets a linear
437 // chain run on two physical targets without anyone arranging it.
438 for (auto& res : resources_) {
439 if (res.kind == Kind::Transient && res.lastRead == static_cast<i32>(i)) release(res);
440 }
441 }
442 device_.graphicsWaitOnAsyncComputeJob(pending);
443}
444
446 if (id >= resources_.size()) return TextureHandle::Invalid;
447 return resources_[id].texture;
448}
449
451 if (id >= resources_.size()) return TextureHandle::Invalid;
452 const Resource& res = resources_[id];
453 if (res.kind != Kind::Transient || res.pooled == kNoTarget) return TextureHandle::Invalid;
454 return pool_.depthTextureOf(res.pooled);
455}
456
458 if (id >= resources_.size()) return TextureHandle::Invalid;
459 const Resource& res = resources_[id];
460 if (res.kind != Kind::Transient || res.pooled == kNoTarget) return TextureHandle::Invalid;
461 return pool_.gbufferTextureOf(res.pooled);
462}
463
465 if (id >= resources_.size()) return TextureHandle::Invalid;
466 const Resource& res = resources_[id];
467 if (res.kind != Kind::Transient || res.pooled == kNoTarget) return TextureHandle::Invalid;
468 return pool_.albedoTextureOf(res.pooled);
469}
470
472 for (auto& res : resources_) {
473 res.pooled = kNoTarget;
474 if (res.kind == Kind::Transient) res.texture = TextureHandle::Invalid;
475 }
476 borrowed_.clear();
477 pool_.clear();
478}
479
480} // namespace esengine::rg
Abstract graphics device interface.
Logging utilities for ESEngine.
#define ES_LOG_ERROR(...)
Logs an error message.
Definition Log.hpp:296
Full-screen passes as a declared graph: what each one reads, what it writes, and at what size — the g...
Abstract graphics device interface.
Definition GfxDevice.hpp:75
u32 createTimerQuery()
Creates a GPU elapsed-time query, or 0 when the backend cannot time GPU work.
virtual bool getTimerQueryNs(u32 query, u64 *outNanoseconds)=0
Fetches a completed query's elapsed nanoseconds; false while still pending.
void begin(const std::string &name)
void segment(const std::string &name)
TextureHandle albedoTextureOf(ResourceId id) const
The third attachment of a gbuffer target: the surface's diffuse colour (alpha 1 where one was written...
ResourceId importTexture(TextureHandle texture, u32 width, u32 height)
ResourceId importTarget(FramebufferHandle target, u32 width, u32 height, bool output=true, TextureHandle readable=TextureHandle::Invalid)
The framebuffer the graph must end in (the screen, an editor FBO).
void addPass(PassDesc pass)
void begin(u32 refWidth, u32 refHeight)
RenderGraph(GfxDevice &device, TargetPool &pool)
FramebufferHandle framebufferOf(ResourceId id) const
TextureHandle textureOf(ResourceId id) const
ResourceId createTarget(const TargetDesc &desc)
TextureHandle gbufferTextureOf(ResourceId id) const
TextureHandle depthTextureOf(ResourceId id) const
ResourceId createExternalTarget(const TargetDesc &desc)
A pooled target filled by a producer OUTSIDE any pass callback.
u32 TargetHandle
A borrowed target: a slot index, and the generation of what is in it.
constexpr ResourceId kNoResource
constexpr TargetHandle kNoTarget
FramebufferHandle
Handle 0 is the default framebuffer (backbuffer); it cannot be created or deleted.
Definition GfxEnums.hpp:41
constexpr AsyncComputeFence kNoAsyncComputeFence
Definition GfxEnums.hpp:25
constexpr Unique< T > makeUnique(Args &&... args)
Creates a Unique pointer with the given arguments.
Definition Types.hpp:99
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
i32 AsyncComputeFence
Definition GfxEnums.hpp:24
static EstellaContext & ctx()
float f32
32-bit floating point
Definition Types.hpp:59
One render pass: a target, which attachments to clear on entry, and the clear values — full load-op s...
Definition GfxEnums.hpp:485
u32 clearH
Clear region size; 0 = the whole target.
Definition GfxEnums.hpp:493
i32 clearY
Clear region origin (pixels).
Definition GfxEnums.hpp:492
FramebufferHandle target
Definition GfxEnums.hpp:486
One full-screen pass.
std::function< void(const PassContext &)> execute
std::vector< ResourceId > reads
bool compute
A compute pass: no render pass is opened and no unit is bound — execute dispatches,...
AsyncComputePriority computePriority
std::vector< ResourceId > dependencies
Resources the pass uses but the graph must not bind.
u32 viewportX
The rect of its target this pass draws into. Zero width = all of it.
bool asyncCompute
The compute callback only accesses the graph resources it declares and private uniforms.
bool discardDepth
Its target's depth is only for testing while it draws, and nothing reads it afterwards (see RenderPas...
Shape of a target the graph allocates.