Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
ResourcePool.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
15#pragma once
16
17// =============================================================================
18// Includes
19// =============================================================================
20
21// Project includes
22#include "../core/Types.hpp"
23#include "Handle.hpp"
24
25// Standard library
26#include <string>
27#include <unordered_map>
28#include <vector>
29
30namespace esengine::resource {
31
32// =============================================================================
33// ResourcePoolBase
34// =============================================================================
35
44public:
45 virtual ~ResourcePoolBase() = default;
46
51 virtual void release(u32 id) = 0;
52
57 virtual usize size() const = 0;
58
62 virtual void clear() = 0;
63};
64
65// =============================================================================
66// ResourcePool Template
67// =============================================================================
68
84template<typename T>
86public:
90 struct Entry {
93 std::string path;
96 bool evictable = false;
99 };
100
102 entries_.push_back({nullptr, 0, "", 0});
103 }
104 ~ResourcePool() override = default;
105
106 // Non-copyable, movable
107 ResourcePool(const ResourcePool&) = delete;
111
119 Handle<T> add(Unique<T> resource, const std::string& path = "", usize bytes = 0) {
120 u32 index;
121 u32 gen;
122 if (!freeList_.empty()) {
123 index = freeList_.back();
124 freeList_.pop_back();
125 gen = entries_[index].generation;
126 entries_[index] = {std::move(resource), 1, path, gen, bytes, false, 0, 0};
127 } else {
128 index = static_cast<u32>(entries_.size());
129 gen = 0;
130 entries_.push_back({std::move(resource), 1, path, 0, bytes, false, 0, 0});
131 }
132 residentBytes_ += bytes;
133 auto handle = Handle<T>::fromParts(index, gen);
134 if (!path.empty()) {
135 pathToId_[path] = handle.id();
136 }
137 enforceBudget_(); // the new resource is held; this evicts OTHER evictables if over budget
138 return handle;
139 }
140
146 template<typename Fn>
147 void forEachAlive(Fn&& fn) {
148 for (usize i = 1; i < entries_.size(); ++i) {
149 Entry& entry = entries_[i];
150 if (!entry.resource) continue;
151 fn(Handle<T>::fromParts(static_cast<u32>(i), entry.generation), *entry.resource);
152 }
153 }
154
155 template<typename Fn>
156 void forEachAlive(Fn&& fn) const {
157 for (usize i = 1; i < entries_.size(); ++i) {
158 const Entry& entry = entries_[i];
159 if (!entry.resource) continue;
160 fn(Handle<T>::fromParts(static_cast<u32>(i), entry.generation),
161 static_cast<const T&>(*entry.resource));
162 }
163 }
164
170 T* get(Handle<T> handle) {
171 if (!handle.isValid()) return nullptr;
172 u32 idx = handle.index();
173 if (idx >= entries_.size()) return nullptr;
174 auto& entry = entries_[idx];
175 if (entry.refCount == 0 || entry.generation != handle.generation()) {
176 return nullptr;
177 }
178 return entry.resource.get();
179 }
180
186 const T* get(Handle<T> handle) const {
187 if (!handle.isValid()) return nullptr;
188 u32 idx = handle.index();
189 if (idx >= entries_.size()) return nullptr;
190 const auto& entry = entries_[idx];
191 if (entry.refCount == 0 || entry.generation != handle.generation()) {
192 return nullptr;
193 }
194 return entry.resource.get();
195 }
196
202 Handle<T> findByPath(const std::string& path) const {
203 auto it = pathToId_.find(path);
204 if (it == pathToId_.end()) return Handle<T>();
205 auto handle = Handle<T>(it->second);
206 u32 idx = handle.index();
207 if (idx < entries_.size() && entries_[idx].generation == handle.generation()) {
208 return handle;
209 }
210 return Handle<T>();
211 }
212
218 void setPath(Handle<T> handle, const std::string& path) {
219 if (!handle.isValid()) return;
220 u32 idx = handle.index();
221 if (idx >= entries_.size()) return;
222 auto& entry = entries_[idx];
223 if (entry.refCount > 0 && entry.generation == handle.generation() && !path.empty()) {
224 if (!entry.path.empty()) {
225 pathToId_.erase(entry.path);
226 }
227 entry.path = path;
228 pathToId_[path] = handle.id();
229 }
230 }
231
236 void addRef(Handle<T> handle) {
237 if (!handle.isValid()) return;
238 u32 idx = handle.index();
239 if (idx >= entries_.size()) return;
240 auto& entry = entries_[idx];
241 if (entry.generation != handle.generation()) return;
242 if (entry.evictable) {
243 // Reviving a cached (refCount==0) entry: pull it out of the LRU back
244 // into the held state. This is the cache-hit path (findByPath → addRef).
245 lruRemove_(idx);
246 entry.evictable = false;
247 entry.refCount = 1;
248 } else if (entry.refCount > 0) {
249 entry.refCount++;
250 }
251 }
252
257 void release(u32 id) override {
258 u32 index = Handle<T>::extractIndex(id);
260 if (index >= entries_.size()) return;
261 auto& entry = entries_[index];
262 if (entry.refCount == 0 || entry.generation != gen) return;
263 if (--entry.refCount == 0) {
264 if (budget_ == 0 || entry.path.empty()) {
265 // No budget → free immediately. Same for pathless entries even
266 // under a budget: findByPath is the only revive channel, so a
267 // cached entry nobody can find would just squat on the budget.
268 freeEntry_(index);
269 } else {
270 // 3-state lifecycle: held → evictable (cached in the LRU, still
271 // findByPath-able for cache hits) → evicted. Drop the oldest
272 // evictable entries if this pushed us over the byte budget.
273 entry.evictable = true;
274 lruPushBack_(index);
275 enforceBudget_();
276 }
277 }
278 }
279
284 usize size() const override {
285 return entries_.size() - freeList_.size() - 1;
286 }
287
291 void clear() override {
292 entries_.clear();
293 freeList_.clear();
294 pathToId_.clear();
295 residentBytes_ = 0;
296 lruHead_ = 0;
297 lruTail_ = 0;
298 entries_.push_back({nullptr, 0, "", 0, 0, false, 0, 0}); // reserved sentinel (index 0)
299 }
300
301 // =========================================================================
302 // Eviction budget: held → evictable → evicted
303 // =========================================================================
304
311 void setBudget(usize bytes) {
312 budget_ = bytes;
313 enforceBudget_();
314 }
315
317 usize budget() const { return budget_; }
318
328 usize freed = 0;
329 while (lruHead_ != 0) {
330 freeEntry_(lruHead_); // freeEntry_ → lruRemove_ advances lruHead_
331 ++freed;
332 }
333 return freed;
334 }
335
346 bool invalidatePath(const std::string& path) {
347 auto it = pathToId_.find(path);
348 if (it == pathToId_.end()) return false;
349 u32 index = Handle<T>::extractIndex(it->second);
350 u32 gen = Handle<T>::extractGeneration(it->second);
351 pathToId_.erase(it);
352 if (index >= entries_.size()) return true;
353 auto& entry = entries_[index];
354 if (entry.generation != gen) return true;
355 entry.path.clear();
356 if (entry.evictable) {
357 freeEntry_(index);
358 }
359 return true;
360 }
361
363 usize residentBytes() const { return residentBytes_; }
364
367 usize n = 0;
368 for (u32 i = lruHead_; i != 0; i = entries_[i].lruNext) ++n;
369 return n;
370 }
371
373 bool isEvictable(Handle<T> handle) const {
374 if (!handle.isValid()) return false;
375 u32 idx = handle.index();
376 if (idx >= entries_.size()) return false;
377 const auto& entry = entries_[idx];
378 return entry.generation == handle.generation() && entry.evictable;
379 }
380
386 u32 getRefCount(Handle<T> handle) const {
387 if (!handle.isValid()) return 0;
388 u32 idx = handle.index();
389 if (idx >= entries_.size()) return 0;
390 const auto& entry = entries_[idx];
391 if (entry.generation != handle.generation()) return 0;
392 return entry.refCount;
393 }
394
400 const std::string& getPath(Handle<T> handle) const {
401 static const std::string empty;
402 if (!handle.isValid()) return empty;
403 u32 idx = handle.index();
404 if (idx >= entries_.size()) return empty;
405 const auto& entry = entries_[idx];
406 if (entry.generation != handle.generation()) return empty;
407 return entry.path;
408 }
409
410private:
412 void freeEntry_(u32 index) {
413 auto& entry = entries_[index];
414 if (entry.evictable) lruRemove_(index);
415 // Only drop the path mapping if it still points here — a later add() of the
416 // same path (while this entry lingered evictable) may have re-bound it.
417 if (!entry.path.empty()) {
418 auto it = pathToId_.find(entry.path);
419 if (it != pathToId_.end() && Handle<T>::extractIndex(it->second) == index) {
420 pathToId_.erase(it);
421 }
422 }
423 residentBytes_ -= entry.bytes;
424 entry.resource.reset();
425 entry.path.clear();
426 entry.bytes = 0;
427 entry.evictable = false;
428 entry.generation = (entry.generation + 1) & Handle<T>::GEN_MASK;
429 freeList_.push_back(index);
430 }
431
435 void enforceBudget_() {
436 if (budget_ == 0) return;
437 while (residentBytes_ > budget_ && lruHead_ != 0) {
438 freeEntry_(lruHead_); // freeEntry_ → lruRemove_ advances lruHead_
439 }
440 }
441
443 void lruPushBack_(u32 index) {
444 auto& e = entries_[index];
445 e.lruNext = 0;
446 e.lruPrev = lruTail_;
447 if (lruTail_ != 0) entries_[lruTail_].lruNext = index;
448 else lruHead_ = index;
449 lruTail_ = index;
450 }
451
453 void lruRemove_(u32 index) {
454 auto& e = entries_[index];
455 if (e.lruPrev != 0) entries_[e.lruPrev].lruNext = e.lruNext;
456 else lruHead_ = e.lruNext;
457 if (e.lruNext != 0) entries_[e.lruNext].lruPrev = e.lruPrev;
458 else lruTail_ = e.lruPrev;
459 e.lruPrev = 0;
460 e.lruNext = 0;
461 }
462
463 std::vector<Entry> entries_;
464 std::vector<u32> freeList_;
465 std::unordered_map<std::string, u32> pathToId_;
466 usize budget_ = 0;
467 usize residentBytes_ = 0;
468 u32 lruHead_ = 0;
469 u32 lruTail_ = 0;
470};
471
472} // namespace esengine::resource
Type-safe resource handle system.
Core type definitions and utilities for ESEngine.
Type-safe resource handle.
Definition Handle.hpp:50
static u32 extractIndex(IdType packed)
Extracts index from a raw packed ID.
Definition Handle.hpp:94
u32 index() const
Extracts the slot index from the packed handle.
Definition Handle.hpp:88
static Handle fromParts(u32 index, u32 generation)
Creates a handle from separate index and generation.
Definition Handle.hpp:77
bool isValid() const
Checks if the handle references a valid resource.
Definition Handle.hpp:82
IdType id() const
Gets the packed identifier (index + generation).
Definition Handle.hpp:85
u32 generation() const
Extracts the generation from the packed handle.
Definition Handle.hpp:91
static constexpr u32 GEN_MASK
Definition Handle.hpp:60
static u32 extractGeneration(IdType packed)
Extracts generation from a raw packed ID.
Definition Handle.hpp:97
Abstract base class for resource pools.
virtual void clear()=0
Releases all resources.
virtual usize size() const =0
Gets the number of active resources.
virtual void release(u32 id)=0
Releases a resource by ID.
Handle< T > add(Unique< T > resource, const std::string &path="", usize bytes=0)
Adds a resource to the pool.
usize budget() const
The current resident-byte budget (0 = caching disabled).
u32 getRefCount(Handle< T > handle) const
Gets the current reference count for a resource.
bool invalidatePath(const std::string &path)
Severs a path's cache identity so the entry can't be revived.
void clear() override
Releases all resources.
usize evictableCount() const
Number of evictable (refCount==0, cached) entries.
const T * get(Handle< T > handle) const
Gets a resource by handle (const).
bool isEvictable(Handle< T > handle) const
True if the handle's entry is alive but evictable (cached).
void setPath(Handle< T > handle, const std::string &path)
Associates a path with an existing resource.
void addRef(Handle< T > handle)
Increments the reference count for a resource.
Handle< T > findByPath(const std::string &path) const
Finds a resource by its cached path.
usize trimEvictables()
Frees every evictable (refCount==0) cache entry immediately.
ResourcePool(const ResourcePool &)=delete
const std::string & getPath(Handle< T > handle) const
Gets the cached path for a resource.
ResourcePool(ResourcePool &&)=default
void setBudget(usize bytes)
Sets the resident-byte budget. 0 (default) disables caching — a resource is freed the instant its ref...
usize size() const override
Gets the number of active resources.
ResourcePool & operator=(const ResourcePool &)=delete
T * get(Handle< T > handle)
Gets a resource by handle.
usize residentBytes() const
Bytes currently resident (held + evictable entries).
ResourcePool & operator=(ResourcePool &&)=default
void release(u32 id) override
Decrements the reference count and frees if zero.
void forEachAlive(Fn &&fn)
Visits every live resource, with the handle naming it.
~ResourcePool() override=default
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
std::unique_ptr< T > Unique
Unique ownership smart pointer.
Definition Types.hpp:75
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
Entry storing a resource with metadata.
std::string path
Optional path for caching.
usize bytes
Resource size, for the eviction budget (0 = untracked).
bool evictable
refCount==0 but retained as a cache entry (in the LRU)
u32 generation
Reuse counter for stale handle detection.
u32 lruNext
Intrusive LRU links (entry index; 0 = sentinel/none).
u32 lruPrev
Intrusive LRU links (entry index; 0 = sentinel/none).
Unique< T > resource
The owned resource.
u32 refCount
Reference count (0 = freed or evictable).