Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
TargetPool.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 "TargetPool.hpp"
8
9#include "../../core/Log.hpp"
10#include "../rhi/GfxDevice.hpp"
11
12namespace esengine::rg {
13
14namespace {
15
17u64 texelBytes(const TargetShape& shape) {
18 // A colour attachment stored as RGB8 still occupies four bytes on both
19 // backends (WebGPU has no 24-bit colour target and WebGL2 pads), so the
20 // upload-side gfxBytesPerPixel would under-report a target by a quarter.
21 u64 bytes = shape.format == GfxPixelFormat::RGBA16F ? 8u : 4u;
22 // Depth24Stencil8 is what a depth-stencil attachment costs; the colour above
23 // is separate storage, not a second view of it.
24 if (shape.depthStencil) bytes += 4u;
25 // A multisampled target is that many times over, PLUS the single-sample
26 // attachments it resolves into — it is two targets in one object, and a
27 // budget that counted only the shape would under-report it fivefold.
28 if (shape.samples > 1) bytes *= (shape.samples + 1);
29 return bytes;
30}
31
32bool sameShape(const TargetShape& a, const TargetShape& b) {
33 return a.width == b.width && a.height == b.height && a.format == b.format
34 && a.linearFilter == b.linearFilter && a.depthStencil == b.depthStencil
35 && a.samples == b.samples && a.gbuffer == b.gbuffer && a.storage == b.storage;
36}
37
38} // namespace
39
40TargetPool::TargetPool(GfxDevice& device) : device_(device) {}
41
42TargetPool::~TargetPool() = default;
43
44const TargetPool::Entry* TargetPool::resolve(TargetHandle handle) const {
45 if (handle == kNoTarget) return nullptr;
46 const u32 slot = handle & kSlotMask;
47 if (slot >= entries_.size()) return nullptr;
48 const Entry& entry = entries_[slot];
49 // The generation is what tells a live handle from one whose target was freed
50 // and whose slot something else has since taken.
51 if (!entry.fbo || entry.generation != (handle >> kSlotBits)) return nullptr;
52 return &entry;
53}
54
56 auto handleFor = [&](usize slot) {
57 return static_cast<TargetHandle>((entries_[slot].generation << kSlotBits)
58 | static_cast<u32>(slot));
59 };
60
61 for (usize i = 0; i < entries_.size(); ++i) {
62 Entry& entry = entries_[i];
63 if (entry.inUse || !entry.fbo || !sameShape(entry.shape, shape)) continue;
64 entry.inUse = true;
65 // Borrowed, so it is not idle. The only place age is reset.
66 entry.idle = 0;
67 return handleFor(i);
68 }
69
70 FramebufferSpec spec;
71 spec.width = shape.width;
72 spec.height = shape.height;
73 spec.depthStencil = shape.depthStencil;
74 spec.linearFilter = shape.linearFilter;
75 spec.colorFormat = shape.format;
76 spec.samples = shape.samples;
77 spec.gbuffer = shape.gbuffer;
78 spec.storage = shape.storage;
79 auto fbo = Framebuffer::create(device_, spec);
80 if (!fbo) {
81 ES_LOG_ERROR("TargetPool: failed to create a {}x{} target", shape.width, shape.height);
82 return kNoTarget;
83 }
84
85 // An emptied slot is refilled before a new one is appended: the generation
86 // in it has already moved on, so no handle from its last occupant matches.
87 for (usize i = 0; i < entries_.size(); ++i) {
88 if (entries_[i].fbo) continue;
89 entries_[i].fbo = std::move(fbo);
90 entries_[i].shape = shape;
91 entries_[i].inUse = true;
92 entries_[i].idle = 0;
93 return handleFor(i);
94 }
95
96 if (entries_.size() > kSlotMask) {
97 ES_LOG_ERROR("TargetPool: {} targets is past what a handle can name", entries_.size());
98 return kNoTarget;
99 }
100
101 Entry entry;
102 entry.fbo = std::move(fbo);
103 entry.shape = shape;
104 entry.inUse = true;
105 entries_.push_back(std::move(entry));
106 return handleFor(entries_.size() - 1);
107}
108
110 if (!resolve(handle)) return;
111 entries_[handle & kSlotMask].inUse = false;
112}
113
114bool TargetPool::holds(TargetHandle handle) const {
115 return resolve(handle) != nullptr;
116}
117
119 const Entry* entry = resolve(handle);
120 return entry ? entry->fbo->handle() : FramebufferHandle::Default;
121}
122
124 const Entry* entry = resolve(handle);
125 return entry ? entry->fbo->getColorAttachment() : TextureHandle::Invalid;
126}
127
129 const Entry* entry = resolve(handle);
130 return entry ? entry->fbo->getDepthAttachment() : TextureHandle::Invalid;
131}
132
134 const Entry* entry = resolve(handle);
135 return entry ? entry->fbo->getGBufferAttachment() : TextureHandle::Invalid;
136}
137
139 const Entry* entry = resolve(handle);
140 return entry ? entry->fbo->getAlbedoAttachment() : TextureHandle::Invalid;
141}
142
144 for (auto& entry : entries_) {
145 if (!entry.fbo || entry.inUse) continue;
146 if (++entry.idle >= kIdleTicksBeforeEvict) {
147 // The slot stays and the generation moves on: the memory goes, and
148 // every handle that named it stops naming anything.
149 entry.fbo.reset();
150 entry.idle = 0;
151 ++entry.generation;
152 }
153 }
154 // A viewport that is being resized borrows a new shape every tick and leaves the last one idle: two seconds of that is a hundred
155 // sets of targets. What sits idle past the budget goes at once, the longest idle first, whatever its age. Only what has really been
156 // left: everything a frame borrows has just been given back when this runs, so counting that too destroyed and rebuilt a frame's own
157 // targets every frame once they added up past the budget (a 4096 shadow atlas and a 4x scene target at 2670x1200: 40 ms on a phone).
158 u64 idleBytes = 0;
159 for (const auto& entry : entries_) {
160 if (entry.fbo && !entry.inUse && entry.idle >= kBudgetGraceTicks) idleBytes += static_cast<u64>(entry.shape.width) * entry.shape.height * texelBytes(entry.shape);
161 }
162 while (idleBytes > idle_byte_budget_) {
163 Entry* oldest = nullptr;
164 for (auto& entry : entries_) {
165 if (entry.fbo && !entry.inUse && entry.idle >= kBudgetGraceTicks && (!oldest || entry.idle > oldest->idle)) oldest = &entry;
166 }
167 if (!oldest) break;
168 idleBytes -= static_cast<u64>(oldest->shape.width) * oldest->shape.height * texelBytes(oldest->shape);
169 oldest->fbo.reset();
170 oldest->idle = 0;
171 ++oldest->generation;
172 }
173}
174
176 // Same bargain as an eviction, for every slot at once. The slots themselves
177 // are kept — a handle held across a device loss has to come back stale, not
178 // come back naming whatever refills its index.
179 for (auto& entry : entries_) {
180 if (!entry.fbo) continue;
181 entry.fbo.reset();
182 entry.inUse = false;
183 entry.idle = 0;
184 ++entry.generation;
185 }
186}
187
189 u32 live = 0;
190 for (const auto& entry : entries_) {
191 if (entry.fbo) ++live;
192 }
193 return live;
194}
195
197 u64 total = 0;
198 for (const auto& entry : entries_) {
199 if (!entry.fbo) continue;
200 total += static_cast<u64>(entry.shape.width) * entry.shape.height * texelBytes(entry.shape);
201 }
202 return total;
203}
204
205} // namespace esengine::rg
Abstract graphics device interface.
Logging utilities for ESEngine.
#define ES_LOG_ERROR(...)
Logs an error message.
Definition Log.hpp:296
The render targets a frame borrows from, keyed by shape — owned by the frame, not by any one graph th...
static Unique< Framebuffer > create(GfxDevice &device, const FramebufferSpec &spec)
Creates a framebuffer from specification.
Abstract graphics device interface.
Definition GfxDevice.hpp:75
void release(TargetHandle handle)
TargetPool(GfxDevice &device)
TextureHandle gbufferTextureOf(TargetHandle handle) const
TextureHandle albedoTextureOf(TargetHandle handle) const
static constexpr u32 kIdleTicksBeforeEvict
Ticks a target may go unborrowed before the pool destroys it.
TextureHandle textureOf(TargetHandle handle) const
bool holds(TargetHandle handle) const
TargetHandle acquire(const TargetShape &shape)
Borrow a target of this shape, reusing one or creating it.
static constexpr u32 kBudgetGraceTicks
Ticks unborrowed before a target counts against that budget. More than one, since age runs once per g...
TextureHandle depthTextureOf(TargetHandle handle) const
FramebufferHandle framebufferOf(TargetHandle handle) const
void age()
One tick of the clock every borrowed target is aged against.
u32 TargetHandle
A borrowed target: a slot index, and the generation of what is in it.
constexpr TargetHandle kNoTarget
FramebufferHandle
Handle 0 is the default framebuffer (backbuffer); it cannot be created or deleted.
Definition GfxEnums.hpp:41
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
Framebuffer creation parameters.
GfxPixelFormat colorFormat
Color attachment format. RGBA16F needs GfxDevice::supportsFloatTargets.
bool gbuffer
A second colour attachment (RGBA8) drawn in the same pass: the surface's material,...
bool depthStencil
Whether to create depth/stencil attachment.
bool linearFilter
Texture filter mode: false=GL_NEAREST, true=GL_LINEAR.
u32 samples
Number of samples for MSAA (1 = no multisampling).
u32 height
Framebuffer height in pixels.
bool storage
The colour attachment can also be written by a compute shader (GfxDevice::supportsCompute).
u32 width
Framebuffer width in pixels.
bool gbuffer
A second colour attachment for the surface's material (see FramebufferSpec::gbuffer).
bool storage
Written by a compute shader as a storage texture, and sampled after.