Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
RenderFrameOverlay.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
16#include "./RenderFrame.hpp"
19#include "../../core/Hash.hpp"
20#include <glm/gtc/type_ptr.hpp>
21#include "../../core/Log.hpp"
24
25#include <algorithm>
26#include <unordered_map>
27
28namespace esengine {
29
30void RenderFrame::swapOverlayIn() {
31 if (overlay_swapped_) return;
32 if (!overlay_hold_) {
33 overlay_hold_ = std::make_unique<OverlayHold>(device_);
34 overlay_hold_->pool.init();
35 }
36 pool_.swap(overlay_hold_->pool);
37 std::swap(draw_list_, overlay_hold_->list);
38 // The overlay drew with the frame's list before it had its own: it takes how the frame has that list set.
39 draw_list_.copySettingsFrom(overlay_hold_->list);
40 overlay_swapped_ = true;
41}
42
43void RenderFrame::swapOverlayOut() {
44 if (!overlay_swapped_) return;
45 pool_.swap(overlay_hold_->pool);
46 std::swap(draw_list_, overlay_hold_->list);
47 overlay_swapped_ = false;
48}
49
50void RenderFrame::resetOverlayContents() {
51 overlay_reset_pending_ = false;
52 // The overlay's own pool and list (swapped in): what they held is spent once a pass is built in them.
53 pool_.beginFrame();
54 draw_list_.clear();
55 overlay_valid_ = false;
56}
57
58void RenderFrame::beginScreenOverlay(const glm::mat4& projection,
59 i32 vpX, i32 vpY, u32 vpW, u32 vpH) {
60 if (overlay_active_ || !device_.isDeviceUsable()) return;
61 swapOverlayIn();
62 ++overlay_passes_;
63 overlay_kept_ = false;
64 overlay_reset_pending_ = true;
65 overlay_would_keep_ = false;
66
67 overlay_projection_ = projection;
68 overlay_vp_x_ = vpX;
69 overlay_vp_y_ = vpY;
70 overlay_vp_w_ = vpW;
71 overlay_vp_h_ = vpH;
72 overlay_active_ = true;
73
74 // Emptied by the first collect (resetOverlayContents), not here: keepScreenOverlay may yet find what is held still stands.
75 // Every layer until the caller says otherwise: which layers a frame shows is
76 // the caller's to decide, and a host that never says shows all of them.
77 draw_list_.setCullingMask(0xFFFFFFFFu);
78 draw_list_.setLayerlessVisible(true);
79 overlay_effect_ = 0;
80 clip_state_.clear();
81}
82
84u64 RenderFrame::overlayInputs(ecs::Registry& registry, bool whole) const {
86 const auto mix = [&h](u64 v) { h = hash::combine(h, v); };
87 h = hash::combineWords(h, &overlay_projection_, sizeof(overlay_projection_));
88 mix(static_cast<u32>(overlay_vp_x_));
89 mix(static_cast<u32>(overlay_vp_y_));
90 mix(overlay_vp_w_);
91 mix(overlay_vp_h_);
92 mix(draw_list_.cullingMask());
93 mix(draw_list_.ySortMask());
94 mix(draw_list_.treeMask());
95 mix(draw_list_.depthMask());
96 mix(overlay_effect_);
97 mix(linear_color_ ? 1 : 0);
98 mix(registry.identity());
99 mix(device_.deviceGeneration());
100 mix(device_.textureShapes());
101 mix(resource_manager_.textureMetadataRevision());
102 mix(resource_manager_.meshesRevision());
103 mix(context_.materials().revision());
104 mix(batch_shader_id_);
105 // A segment answers for its own labels and its own share of the domain (keepSegments); the whole overlay, for all of them.
106 if (!whole) return h;
107 // The labels it draws from the store, when it draws them itself.
108 mix(retained_text_collected_ ? retained_text_.revision() : 0);
109 // The domain itself, order-free: an entity that left it (or was destroyed in it) leaves nothing stamped behind.
110 u64 domain = 0;
111 if (screen_domain_) {
112 for (const u32 id : *screen_domain_) domain += hash::combine(0x5bd1e995ull, id);
113 mix(screen_domain_->size());
114 }
115 mix(domain);
116 return h;
117}
118
120bool RenderFrame::overlayRegistryMoved(ecs::Registry& registry) {
121 const auto inDomain = [this](u32 id) { return screen_domain_ && screen_domain_->count(id) != 0; };
122 if (registry.anyComponentChangedSinceWhere(overlay_tick_, [&](Entity e) { return inDomain(e.id()); })) return true;
123 // Structure: an add, a remove, a switch on or off. History is kept only while watched, so a journal that cannot say is a change.
124 static std::vector<ecs::EntityChangeRow> rows(ecs::ENTITY_CHANGE_CAPACITY);
125 const i32 count = registry.readEntityChanges(overlay_journal_, rows);
126 if (count < 0) return true;
127 for (i32 i = 0; i < count; ++i) {
128 const auto& row = rows[static_cast<usize>(i)];
129 if ((row.flags & ecs::ENTITY_CHANGE_RESET) || row.entity == INVALID_ENTITY.id() || inDomain(row.entity)) return true;
130 }
131 return false;
132}
133
134bool RenderFrame::keepScreenOverlay(ecs::Registry& registry, bool hostStill) {
135 if (!overlay_active_ || !overlay_reset_pending_) return false;
136 if (overlay_watched_ != registry.identity()) {
137 overlay_watched_ = registry.identity();
138 overlay_reader_ = registry.watchEntityChanges();
139 overlay_valid_ = false;
140 }
141 overlay_registry_ = &registry;
142 const bool segmentable = hostStill && retained_text_collected_ && overlay_passes_ == 1 && overlay_effect_ == 0
143 && screen_roots_ && screen_root_by_index_ && !screen_roots_->empty()
144 && !(segments_refused_ && segments_refused_roots_ == screenRootsHash());
145 if (segmentable) return keepSegments(registry);
146 segments_trusted_ = false;
147 retained_text_.takeChanged([](u32) {});
148
149 u32 why = 0;
150 const u64 key = overlayInputs(registry, true);
151 if (!hostStill) why |= 1;
152 if (!overlay_valid_) why |= 2;
153 else if (key != overlay_key_) why |= 4;
154 if (overlay_passes_ > 1) why |= 8;
155 bool particles = false;
156 if (screen_domain_ && !screen_domain_->empty()) {
158 if (screen_domain_->count(e.id()) != 0) particles = true;
159 });
160 }
161 if (particles) why |= 32;
162 if (why == 0 && overlayRegistryMoved(registry)) why |= 16;
163 overlay_why_ = why;
164
165 // The tick and the journal row this pass is read at: a write after this is a change to the next.
166 overlay_pending_key_ = key;
167 overlay_pending_tick_ = registry.beginChangeRead();
168 overlay_pending_journal_ = registry.entityChangeSequence();
169
170 if (why == 0 && !registry.changeAuditEnabled()) {
171 overlay_kept_ = true;
172 overlay_reset_pending_ = false;
173 overlay_tick_ = overlay_pending_tick_;
174 overlay_journal_ = overlay_pending_journal_;
175 ++overlay_kept_total_;
176 return true;
177 }
178 overlay_would_keep_ = why == 0;
179 resetOverlayContents();
180 return false;
181}
182
184 if (!overlay_active_ || overlay_kept_) return;
185 if (overlay_segmented_) {
186 ES_PROFILE_SCOPE("render.overlay.collect");
187 processMasks(registry, overlay_projection_, overlay_vp_x_, overlay_vp_y_,
188 static_cast<i32>(overlay_vp_w_), static_cast<i32>(overlay_vp_h_));
189 buildClipState();
190 for (auto& segment : segments_) {
191 if (!segment.dirty) continue;
192 segmentIn(segment);
193 pool_.beginFrame();
194 draw_list_.clear();
195 collectScreenOverlayInto(registry, segment.root);
196 segmentOut(segment);
197 }
198 return;
199 }
200 if (overlay_reset_pending_) {
201 // A host that does not ask keepScreenOverlay builds every pass, as before; one that asks has had its answer.
202 resetOverlayContents();
203 overlay_pending_key_ = 0;
204 overlay_pending_tick_ = registry.beginChangeRead();
205 overlay_pending_journal_ = -1;
206 }
207
208 ES_PROFILE_SCOPE("render.overlay.collect");
209
210 // Masks resolve in the overlay's OWN projection: a scissor rect is pixels,
211 // and which pixels a UI box covers is a question only the projection that
212 // draws it can answer.
213 processMasks(registry, overlay_projection_, overlay_vp_x_, overlay_vp_y_,
214 static_cast<i32>(overlay_vp_w_), static_cast<i32>(overlay_vp_h_));
215 buildClipState();
216 collectScreenOverlayInto(registry, 0);
217}
218
220void RenderFrame::collectScreenOverlayInto(ecs::Registry& registry, u32 onlyRoot) {
221 auto ctx = makeContext();
222 ctx.view_projection = overlay_projection_;
224
225 // Extracted for completeness of the context, never consulted: the overlay
226 // does not cull (RenderCollectContext::visible short-circuits on the purpose).
227 // A screen element is on the screen by construction.
228 Frustum overlayFrustum;
229 overlayFrustum.extractFromMatrix(overlay_projection_);
230
231 RenderCollectContext collectCtx{registry, overlayFrustum, clip_state_, pool_, draw_list_,
232 ctx, computeCameraView(overlay_projection_)};
233 collectCtx.screen_ui = screen_domain_;
234 collectCtx.ui_tree_layers = ui_tree_layers_;
235 collectCtx.screen_root_by_index = screen_root_by_index_;
236 collectCtx.only_root = onlyRoot;
237 // Only the plugins that can draw an entity out of a UI tree. Everything else
238 // draws world content, which by definition is not what this pass is for —
239 // and would land in it at layout-pixel coordinates.
240 for (auto& plugin : plugins_) {
241 if (plugin->drawsScreenUI()) plugin->collect(collectCtx);
242 }
243 if (retained_text_collected_) submitRetainedText(registry, true, glm::value_ptr(overlay_projection_), onlyRoot);
244 stats_.culled += collectCtx.culled;
245}
246
247void RenderFrame::drawScreenOverlay() {
248 context_.updateCameraConstants(overlay_projection_);
249 {
250 ES_PROFILE_SCOPE("render.overlay.submit");
251 draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(),
252 &frame_capture_, context_.perDrawBlocks());
253 }
254 device_.invalidatePipelineCache();
255 device_.setScissorTest(false);
256}
257
258bool RenderFrame::grabOverlayBackdrop(FramebufferHandle source) {
259#ifdef ES_ENABLE_POSTPROCESS
260 if (!post_process_ || width_ == 0 || height_ == 0) return false;
261 if (overlay_grab_ == TextureHandle::Invalid || overlay_grab_w_ != width_ || overlay_grab_h_ != height_) {
262 releaseOverlayBackdrop();
263 TextureDesc desc;
264 desc.width = width_;
265 desc.height = height_;
266 desc.format = GfxPixelFormat::RGB8;
267 overlay_grab_ = device_.createTexture(desc, GfxContent::transient(), nullptr);
268 FramebufferSpec spec;
269 spec.width = width_;
270 spec.height = height_;
271 spec.depthStencil = false;
272 spec.linearFilter = true;
273 spec.mipmaps = true;
274 overlay_backdrop_ = Framebuffer::create(device_, spec);
275 overlay_grab_w_ = width_;
276 overlay_grab_h_ = height_;
277 }
278 if (overlay_grab_ == TextureHandle::Invalid || !overlay_backdrop_) return false;
279 if (!device_.copyFramebufferColor(source, overlay_grab_)) return false;
280
281 device_.invalidatePipelineCache();
282 device_.setScissorTest(false);
283 graph_.begin(width_, height_);
284 rg::PassDesc copy;
285 copy.name = "screen-ui-grab";
286 copy.reads = {graph_.importTexture(overlay_grab_, width_, height_)};
287 copy.write = graph_.importTarget(overlay_backdrop_->handle(), width_, height_);
288 copy.execute = [this](const rg::PassContext&) { post_process_->grabScene(); };
289 graph_.addPass(std::move(copy));
290 executeOverlayGraph();
291 device_.endRenderPass();
292 device_.generateMipmaps(overlay_backdrop_->getColorAttachment());
293 device_.invalidatePipelineCache();
294 return true;
295#else
296 (void)source;
297 return false;
298#endif
299}
300
301void RenderFrame::executeOverlayGraph() {
302 rg::PassTimer* timer = gpu_frame_open_ && gpu_frame_passes_ ? pass_timer_.get() : nullptr;
303 graph_.setPassTimer(timer);
304 graph_.execute();
305 graph_.setPassTimer(nullptr);
306}
307
308void RenderFrame::releaseOverlayBackdrop() {
309 if (overlay_grab_ != TextureHandle::Invalid) device_.deleteTexture(overlay_grab_);
310 overlay_grab_ = TextureHandle::Invalid;
311 overlay_backdrop_.reset();
312 overlay_grab_w_ = overlay_grab_h_ = 0;
313}
314
316 if (!overlay_active_) return;
317 overlay_effect_ = material;
318 draw_list_.setLayerlessVisible(material == 0);
319}
320
322 if (!overlay_active_) return;
323 if (overlay_segmented_) {
324 endSegmentedOverlay(target);
325 return;
326 }
327 // Every way out of the pass gives the frame its own pool and list back.
328 struct SwapBack {
329 RenderFrame& frame;
330 ~SwapBack() { frame.swapOverlayOut(); }
331 } swapBack{*this};
332 overlay_active_ = false;
333 const u32 effect = overlay_effect_;
334 overlay_effect_ = 0;
335 draw_list_.setLayerlessVisible(true);
336 const bool kept = overlay_kept_;
337 overlay_kept_ = false;
338 if (overlay_reset_pending_) {
339 // Opened and closed with nothing collected or asked: an empty pass, held by nobody.
340 resetOverlayContents();
341 overlay_pending_key_ = 0;
342 }
343 ES_PROFILE_COUNTER("render.overlay.kept", kept ? 1u : 0u);
344 ES_PROFILE_COUNTER("render.overlay.keptTotal", overlay_kept_total_);
345 ES_PROFILE_COUNTER("render.overlay.why", overlay_why_);
346 ES_PROFILE_COUNTER("render.overlay.stale", overlay_stale_);
347 if (!device_.isDeviceUsable()) {
348 overlay_valid_ = false;
349 return;
350 }
351
352 if (!kept) {
353 if (linear_color_) {
354 std::unordered_map<u32, u32> shown;
355 draw_list_.remapPrograms([&](u32 program) {
356 auto it = shown.find(program);
357 if (it == shown.end()) it = shown.emplace(program, displayProgram(program)).first;
358 return it->second;
359 });
360 }
361 {
362 ES_PROFILE_SCOPE("render.overlay.finalize");
363 draw_list_.finalize(pool_);
364 pool_.upload();
365 }
366 // Held from here; a pass keyed 0 (from a host that never asked) is never matched.
367 overlay_valid_ = overlay_pending_key_ != 0;
368 overlay_key_ = overlay_pending_key_;
369 overlay_tick_ = overlay_pending_tick_;
370 overlay_journal_ = overlay_pending_journal_;
371 if (overlay_valid_) {
372 u64 content = draw_list_.contentHash(hash::kFnv64Offset);
373 for (u32 l = 0; l < LAYOUT_COUNT; ++l) {
374 const auto layout = static_cast<LayoutId>(l);
375 const u32 bytes = pool_.vertexBytesUsed(layout);
376 if (bytes) content = hash::combineWords(content, pool_.vertexData(layout), bytes);
377 const u32 indices = pool_.indicesUsed(layout);
378 if (indices) content = hash::combineWords(content, pool_.indexData(layout), indices * sizeof(u32));
379 }
380 if (overlay_would_keep_ && content != overlay_content_) {
381 ++overlay_stale_;
382 if (!warned_overlay_stale_) {
383 warned_overlay_stale_ = true;
384 ES_LOG_WARN("change audit: the screen overlay would have been held while what it draws had changed");
385 }
386 }
387 overlay_content_ = content;
388 }
389 }
390 overlay_would_keep_ = false;
391
392 // Nothing to draw is not the same as nothing to do elsewhere, but here it is:
393 // a pass that would write no pixel is one the graph would run anyway.
394 if (draw_list_.commandCount() == 0) return;
395 frame_capture_.beginPass(CapturePass::Overlay);
396
397 accumulateStats(draw_list_);
398 tallyPass(draw_list_);
399
402 if (auto* rt = target_manager_.get(target)) fbo = rt->getFramebuffer();
403 }
404
405 device_.invalidatePipelineCache();
406 device_.setScissorTest(false);
407
408 bool layered = false;
409 bool backdrop = false;
410#ifdef ES_ENABLE_POSTPROCESS
411 layered = effect != 0 && post_process_ && post_process_->canDrawMaterialOver(effect);
412 if (draw_list_.anyUsesScreenColor(context_.materials())
413 || (layered && context_.materials().usesScreenColor(effect))) {
414 ES_PROFILE_SCOPE("render.overlay.grab");
415 backdrop = grabOverlayBackdrop(fbo);
416 }
417#else
418 (void)effect;
419#endif
420 draw_list_.setDeferScreenColor(false);
421 draw_list_.setLayerAlpha(layered);
422 const TextureHandle behind = backdrop ? overlay_backdrop_->getColorAttachment() : TextureHandle::Invalid;
423
424 ES_PROFILE_SCOPE("render.overlay.graph");
425 graph_.begin(width_, height_);
426 rg::PassDesc pass;
427 pass.name = layered ? "screen-ui-layer" : "screen-ui";
428 pass.viewportX = static_cast<u32>(std::max(overlay_vp_x_, 0));
429 pass.viewportY = static_cast<u32>(std::max(overlay_vp_y_, 0));
430 pass.viewportW = overlay_vp_w_;
431 pass.viewportH = overlay_vp_h_;
433 if (layered) {
434 rg::TargetDesc desc;
435 desc.depthStencil = true;
436 layer = graph_.createTarget(desc);
437 pass.write = layer;
438 pass.clear = true;
439 pass.clearDepth = true;
440 pass.clearColor[0] = pass.clearColor[1] = pass.clearColor[2] = pass.clearColor[3] = 0.0f;
441 } else {
442 pass.write = graph_.importTarget(fbo, width_, height_);
443 pass.clear = false;
444 }
445 pass.execute = [this, layered, behind](const rg::PassContext&) {
446 if (layered) device_.clearStencil(0);
447 context_.materials().setScreenColor(behind);
448 drawScreenOverlay();
449 context_.materials().setScreenColor(TextureHandle::Invalid);
450 };
451 graph_.addPass(std::move(pass));
452#ifdef ES_ENABLE_POSTPROCESS
453 if (layered) {
454 rg::PassDesc compose;
455 compose.name = "screen-ui-effect";
456 compose.reads = {layer};
457 compose.write = graph_.importTarget(fbo, width_, height_);
458 compose.clear = false;
459 compose.execute = [this, effect, behind](const rg::PassContext&) {
460 context_.materials().setScreenColor(behind);
461 post_process_->drawMaterialOver(effect);
462 context_.materials().setScreenColor(TextureHandle::Invalid);
463 };
464 graph_.addPass(std::move(compose));
465 }
466#endif
467 executeOverlayGraph();
468 draw_list_.setLayerAlpha(false);
469
470 device_.endRenderPass();
471 device_.invalidatePipelineCache();
472 runPendingReplay(overlay_projection_, overlay_vp_w_, overlay_vp_h_);
473}
474
475// =============================================================================
476// Segments: one held share of the overlay per screen root
477// =============================================================================
478
479u32 RenderFrame::screenRootAt(u32 entity) const {
480 if (!screen_root_by_index_) return 0;
481 const u32 index = Entity::fromRaw(entity).index();
482 return index < screen_root_by_index_->size() ? (*screen_root_by_index_)[index] : 0;
483}
484
485u64 RenderFrame::screenRootsHash() const {
487 if (screen_roots_) for (const u32 root : *screen_roots_) h = hash::combine(h, root);
488 return h;
489}
490
491void RenderFrame::segmentIn(OverlaySegment& segment) {
492 if (!segment.hold) {
493 segment.hold = std::make_unique<OverlayHold>(device_);
494 segment.hold->pool.init();
495 }
496 pool_.swap(segment.hold->pool);
497 std::swap(draw_list_, segment.hold->list);
498 // How this pass was set (its layers, whether layerless content shows) went to the one-list hold, opened by beginScreenOverlay.
499 draw_list_.copySettingsFrom(overlay_hold_->list);
500}
501
502void RenderFrame::segmentOut(OverlaySegment& segment) {
503 pool_.swap(segment.hold->pool);
504 std::swap(draw_list_, segment.hold->list);
505}
506
512bool RenderFrame::keepSegments(ecs::Registry& registry) {
513 overlay_segmented_ = true;
514 overlay_reset_pending_ = false;
515 // The one-list hold is left as it was: this pass draws from the segments.
516 swapOverlayOut();
517
518 std::vector<OverlaySegment> next;
519 next.reserve(screen_roots_->size());
520 for (const u32 root : *screen_roots_) {
521 OverlaySegment segment;
522 for (auto& held : segments_) {
523 if (held.root == root && held.hold) { segment = std::move(held); break; }
524 }
525 segment.root = root;
526 next.push_back(std::move(segment));
527 }
528 std::vector<std::unique_ptr<OverlayHold>> spare;
529 for (auto& left : segments_) if (left.hold) spare.push_back(std::move(left.hold));
530 for (auto& segment : next) {
531 if (segment.hold || spare.empty()) continue;
532 segment.hold = std::move(spare.back());
533 spare.pop_back();
534 }
535 for (auto& hold : spare) hold->pool.shutdown();
536 segments_ = std::move(next);
537
538 std::unordered_map<u32, usize> index;
539 index.reserve(segments_.size());
540 for (usize i = 0; i < segments_.size(); ++i) index.emplace(segments_[i].root, i);
541 const auto inDomain = [this](u32 id) { return screen_domain_ && screen_domain_->count(id) != 0; };
542 const auto mark = [&](u32 id) {
543 if (!inDomain(id)) return;
544 const auto found = index.find(screenRootAt(id));
545 if (found != index.end()) segments_[found->second].dirty = true;
546 };
547
548 const u64 key = overlayInputs(registry, false);
549 const bool fresh = !segments_trusted_ || key != segments_key_;
550 std::vector<u64> domains(segments_.size(), 0);
551 std::vector<u64> counts(segments_.size(), 0);
552 if (screen_domain_) {
553 for (const u32 id : *screen_domain_) {
554 const auto found = index.find(screenRootAt(id));
555 if (found == index.end()) continue;
556 domains[found->second] += hash::combine(0x5bd1e995ull, id);
557 ++counts[found->second];
558 }
559 }
560 for (usize i = 0; i < segments_.size(); ++i) {
561 auto& segment = segments_[i];
562 const u64 domain = hash::combine(domains[i], counts[i]);
563 segment.dirty = fresh || !segment.valid || segment.domain != domain;
564 segment.domain = domain;
565 }
566 bool every = fresh;
567 if (!fresh) {
568 registry.anyComponentChangedSinceWhere(segments_tick_, [&](Entity e) { mark(e.id()); return false; });
569 static std::vector<ecs::EntityChangeRow> rows(ecs::ENTITY_CHANGE_CAPACITY);
570 const i32 count = registry.readEntityChanges(segments_journal_, rows);
571 if (count < 0) every = true;
572 for (i32 i = 0; i < count && !every; ++i) {
573 const auto& row = rows[static_cast<usize>(i)];
574 if ((row.flags & ecs::ENTITY_CHANGE_RESET) || row.entity == INVALID_ENTITY.id()) every = true;
575 else mark(row.entity);
576 }
577 }
578 if (!retained_text_.takeChanged(mark)) every = true;
579 if (screen_domain_ && !screen_domain_->empty()) {
580 registry.each<ecs::ParticleEmitter>([&](Entity e, ecs::ParticleEmitter&) { mark(e.id()); });
581 }
582 const bool audit = registry.changeAuditEnabled();
583 overlay_segments_rebuilt_ = 0;
584 for (auto& segment : segments_) {
585 if (every) segment.dirty = true;
586 segment.wouldKeep = !segment.dirty;
587 if (audit) segment.dirty = true;
588 if (segment.dirty) ++overlay_segments_rebuilt_;
589 }
590
591 // Read here: a write after this is a change to the next pass.
592 segments_key_ = key;
593 segments_tick_ = registry.beginChangeRead();
594 segments_journal_ = registry.entityChangeSequence();
595 segments_trusted_ = true;
596 overlay_why_ = overlay_segments_rebuilt_ ? 64u : 0u;
597 if (overlay_segments_rebuilt_ == 0) {
598 overlay_kept_ = true;
599 ++overlay_kept_total_;
600 return true;
601 }
602 return false;
603}
604
605void RenderFrame::endSegmentedOverlay(RenderTargetManager::Handle target) {
606 overlay_active_ = false;
607 overlay_segmented_ = false;
608 overlay_effect_ = 0;
609 const bool kept = overlay_kept_;
610 overlay_kept_ = false;
611 ES_PROFILE_COUNTER("render.overlay.kept", kept ? 1u : 0u);
612 ES_PROFILE_COUNTER("render.overlay.keptTotal", overlay_kept_total_);
613 ES_PROFILE_COUNTER("render.overlay.why", overlay_why_);
614 ES_PROFILE_COUNTER("render.overlay.stale", overlay_stale_);
615 ES_PROFILE_COUNTER("render.overlay.segments", static_cast<u32>(segments_.size()));
616 ES_PROFILE_COUNTER("render.overlay.rebuilt", kept ? 0u : overlay_segments_rebuilt_);
617 if (!kept) overlay_rebuilt_last_ = overlay_segments_rebuilt_;
618 ES_PROFILE_COUNTER("render.overlay.rebuiltLast", overlay_rebuilt_last_);
619 if (!device_.isDeviceUsable()) {
620 segments_trusted_ = false;
621 return;
622 }
623
624 if (!kept) {
625 ES_PROFILE_SCOPE("render.overlay.finalize");
626 for (auto& segment : segments_) {
627 if (!segment.dirty) continue;
628 segmentIn(segment);
629 if (linear_color_) {
630 std::unordered_map<u32, u32> shown;
631 draw_list_.remapPrograms([&](u32 program) {
632 auto it = shown.find(program);
633 if (it == shown.end()) it = shown.emplace(program, displayProgram(program)).first;
634 return it->second;
635 });
636 }
637 draw_list_.finalize(pool_);
638 pool_.upload();
639 u64 content = draw_list_.contentHash(hash::kFnv64Offset);
640 for (u32 l = 0; l < LAYOUT_COUNT; ++l) {
641 const auto layout = static_cast<LayoutId>(l);
642 const u32 bytes = pool_.vertexBytesUsed(layout);
643 if (bytes) content = hash::combineWords(content, pool_.vertexData(layout), bytes);
644 const u32 indices = pool_.indicesUsed(layout);
645 if (indices) content = hash::combineWords(content, pool_.indexData(layout), indices * sizeof(u32));
646 }
647 if (segment.wouldKeep && segment.valid && content != segment.content) {
648 ++overlay_stale_;
649 if (!warned_overlay_stale_) {
650 warned_overlay_stale_ = true;
651 ES_LOG_WARN("change audit: a screen root's overlay segment would have been held while what it draws had changed");
652 }
653 }
654 segment.content = content;
655 segment.valid = true;
656 segment.dirty = false;
657 segmentOut(segment);
658 }
659
660 // Drawn one after another they draw as one list would only if no key of a later root sorts at or before one of an earlier
661 // root's, and none reads the screen's colour (which the one-list pass grabs once). If not, this pass is drawn as one list,
662 // and so is every pass until the roots change.
663 bool ordered = true;
664 bool any = false;
665 u64 previous = 0;
666 for (auto& segment : segments_) {
667 u64 lo = 0, hi = 0;
668 if (!segment.hold || !segment.hold->list.sortKeyRange(lo, hi)) continue;
669 if ((any && lo <= previous) || segment.hold->list.anyUsesScreenColor(context_.materials())) ordered = false;
670 previous = hi;
671 any = true;
672 }
673 if (!ordered && overlay_registry_) {
674 segments_refused_ = true;
675 segments_refused_roots_ = screenRootsHash();
676 segments_trusted_ = false;
677 swapOverlayIn();
678 resetOverlayContents();
679 collectScreenOverlayInto(*overlay_registry_, 0);
680 overlay_pending_key_ = 0;
681 overlay_would_keep_ = false;
682 overlay_active_ = true;
683 endScreenOverlay(target);
684 return;
685 }
686 }
687
688 u32 commands = 0;
689 for (auto& segment : segments_) if (segment.hold) commands += segment.hold->list.commandCount();
690 if (commands == 0) return;
691 frame_capture_.beginPass(CapturePass::Overlay);
692 for (auto& segment : segments_) {
693 if (!segment.hold) continue;
694 accumulateStats(segment.hold->list);
695 tallyPass(segment.hold->list);
696 segment.hold->list.setDeferScreenColor(false);
697 segment.hold->list.setLayerAlpha(false);
698 }
699
702 if (auto* rt = target_manager_.get(target)) fbo = rt->getFramebuffer();
703 }
704 device_.invalidatePipelineCache();
705 device_.setScissorTest(false);
706
707 ES_PROFILE_SCOPE("render.overlay.graph");
708 graph_.begin(width_, height_);
709 rg::PassDesc pass;
710 pass.name = "screen-ui";
711 pass.viewportX = static_cast<u32>(std::max(overlay_vp_x_, 0));
712 pass.viewportY = static_cast<u32>(std::max(overlay_vp_y_, 0));
713 pass.viewportW = overlay_vp_w_;
714 pass.viewportH = overlay_vp_h_;
715 pass.write = graph_.importTarget(fbo, width_, height_);
716 pass.clear = false;
717 pass.execute = [this](const rg::PassContext&) {
718 context_.materials().setScreenColor(TextureHandle::Invalid);
719 context_.updateCameraConstants(overlay_projection_);
720 ES_PROFILE_SCOPE("render.overlay.submit");
721 // In the roots' order, each from its own buffers: a mask's stencil is back at zero when its list leaves the mask.
722 for (auto& segment : segments_) {
723 if (!segment.hold || segment.hold->list.commandCount() == 0) continue;
724 segment.hold->list.execute(device_, segment.hold->pool, context_.materials(), context_.getWhiteTextureId(),
725 &frame_capture_, context_.perDrawBlocks());
726 }
727 device_.invalidatePipelineCache();
728 device_.setScissorTest(false);
729 };
730 graph_.addPass(std::move(pass));
731 executeOverlayGraph();
732 device_.endRenderPass();
733 device_.invalidatePipelineCache();
734 runPendingReplay(overlay_projection_, overlay_vp_w_, overlay_vp_h_);
735}
736
738 ImmediateDraw* draw = presented_overlay_draw_;
739 if (!draw || !draw->hasDeferred() || !device_.isDeviceUsable() || vpW == 0 || vpH == 0) return;
740
743 if (auto* rt = target_manager_.get(target)) fbo = rt->getFramebuffer();
744 }
745 // The pixels are the display's by now, past the post chain and the screen's UI: a
746 // linear frame's colours go through the variant that encodes them, as the overlay's do.
748 const glm::mat4 viewProjection = draw->viewProjection();
749
750 device_.invalidatePipelineCache();
751 device_.setScissorTest(false);
752 graph_.begin(width_, height_);
753 rg::PassDesc pass;
754 pass.name = "over-screen";
755 pass.viewportX = static_cast<u32>(std::max(vpX, 0));
756 pass.viewportY = static_cast<u32>(std::max(vpY, 0));
757 pass.viewportW = vpW;
758 pass.viewportH = vpH;
759 pass.write = graph_.importTarget(fbo, width_, height_);
760 pass.clear = false;
761 pass.execute = [this, draw, program, viewProjection](const rg::PassContext&) {
762 context_.updateCameraConstants(viewProjection);
763 draw->flushDeferred(program);
764 };
765 graph_.addPass(std::move(pass));
766 graph_.execute();
767 device_.endRenderPass();
768 device_.invalidatePipelineCache();
769}
770
771} // namespace esengine
Per-frame CPU scope timing (ES_PROFILE_SCOPE) read by the editor profiler.
#define ES_PROFILE_SCOPE(name)
#define ES_PROFILE_COUNTER(name, value)
Immediate mode 2D drawing API.
Logging utilities for ESEngine.
#define ES_LOG_WARN(...)
Logs a warning message.
Definition Log.hpp:294
Frame resources and the shared scene rendering contract.
Central resource management system.
u32 ySortMask() const
Definition DrawList.hpp:185
u32 depthMask() const
Definition DrawList.hpp:203
u32 cullingMask() const
Definition DrawList.hpp:218
u32 treeMask() const
Definition DrawList.hpp:192
static Unique< Framebuffer > create(GfxDevice &device, const FramebufferSpec &spec)
Creates a framebuffer from specification.
static constexpr GfxContent transient()
u64 textureShapes() const
Counts every texture made, deleted, or given new storage under its handle (a restore,...
u64 deviceGeneration() const
Which generation of the device the live GPU objects belong to.
Immediate mode 2D drawing API.
const glm::mat4 & viewProjection() const
u64 revision() const
Changes whenever any material does (revisionOf), or one is added or removed.
MaterialStore & materials()
The engine-side material registry (handle -> resolved render state).
void submitScreenOverlay(ecs::Registry &registry)
Collects the screen's renderables. Between this and endScreenOverlay a host may submit its own screen...
void processMasks(ecs::Registry &registry, i32 vpX, i32 vpY, i32 vpW, i32 vpH)
void endScreenOverlay(RenderTargetManager::Handle target)
void drawOverScreen(i32 vpX, i32 vpY, u32 vpW, u32 vpH, RenderTargetManager::Handle target)
Draws the immediate geometry collected since the screen overlay over everything the frame shows,...
bool keepScreenOverlay(ecs::Registry &registry, bool hostStill)
Asked after beginScreenOverlay and the layers: true, and the host submits nothing and endScreenOverla...
u32 displayProgram(u32 program)
void submitRetainedText(ecs::Registry &registry, bool screen, const f32 *projection, u32 onlyRoot=0)
Every retained label laid out for one domain into the open list, culled against projection (world,...
u32 batchProgram(BatchVariant variant)
RenderFrame(GfxDevice &device, RenderContext &context, resource::ResourceManager &resource_manager)
void beginScreenOverlay(const glm::mat4 &projection, i32 vpX, i32 vpY, u32 vpW, u32 vpH)
Opens the overlay: projection maps the layout domain onto the pixel rect vpX/vpY/vpW/vpH of the surfa...
void setScreenOverlayEffect(u32 material)
static constexpr Handle INVALID_HANDLE
u64 revision() const
Moves with every label laid out, given glyphs or let go: what a pass drawn from the store was drawn f...
Central container for all entities and components.
Definition Registry.hpp:73
double entityChangeSequence() const
Definition Registry.hpp:130
void each(Func &&func)
Executes a function for each entity with specified components.
Definition Registry.hpp:881
u32 beginChangeRead()
For a reader about to look: the tick it is looking at, after which the clock moves on.
Definition Registry.hpp:173
u64 identity() const
Which registry this is, never shared with another made in this process (a registry assigned over this...
Definition Registry.hpp:166
bool changeAuditEnabled() const
Definition Registry.hpp:307
u64 textureMetadataRevision() const
Moves whenever a texture's metadata (its nine-slice borders and the rest) is set or dropped.
u64 meshesRevision() const
Changes whenever any mesh is realized (each takes a new Mesh::revision) or released: while it holds,...
static constexpr u32 ENTITY_CHANGE_CAPACITY
static constexpr u32 ENTITY_CHANGE_RESET
constexpr u64 combine(u64 h, u64 v)
Definition Hash.hpp:33
constexpr u64 kFnv64Offset
Definition Hash.hpp:12
u64 combineWords(u64 h, const void *data, usize bytes)
Definition Hash.hpp:37
constexpr ResourceId kNoResource
FramebufferHandle
Handle 0 is the default framebuffer (backbuffer); it cannot be created or deleted.
Definition GfxEnums.hpp:41
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
constexpr Entity INVALID_ENTITY
Invalid entity sentinel value.
Definition Types.hpp:174
static constexpr u32 LAYOUT_COUNT
Definition GfxEnums.hpp:102
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
CameraView computeCameraView(const glm::mat4 &viewProjection)
LayoutId
Identifies a transient vertex stream / vertex format. Each layout has its own VBO+EBO+VAO in Transien...
Definition GfxEnums.hpp:88
static EstellaContext & ctx()
Entity identifier with packed index + generation.
Definition Types.hpp:135
constexpr u32 id() const
Returns the raw packed value for FFI serialization.
Definition Types.hpp:159
static constexpr Entity fromRaw(u32 v)
Reconstructs an Entity from a raw packed value.
Definition Types.hpp:162
constexpr u32 index() const
Gets the entity index.
Definition Types.hpp:150
void extractFromMatrix(const glm::mat4 &vp)
u32 only_root
Nonzero: this collect is one screen root's, and an entity of the domain under any other root is not i...
u32 culled
How many renderables this collect's frustum rejected.
const std::vector< u32 > * screen_root_by_index
With only_root: by entity index, the screen root each entity of the domain draws under (ecs::UISystem...
const std::unordered_map< u32, i32 > * ui_tree_layers
The layer of each emitter and plain Sprite a Canvas holds, by entity id, or null.
const std::unordered_set< u32 > * screen_ui
The entities the SCREEN owns (UISystem::screenDomain), or null.
One full-screen pass.
std::function< void(const PassContext &)> execute
u32 viewportX
The rect of its target this pass draws into. Zero width = all of it.
Shape of a target the graph allocates.