Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
ResourceManager.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#include "ResourcePool.hpp"
25#include "TextureMetadata.hpp"
29#include "Mesh.hpp"
30#include "MeshArena.hpp"
31#include "Environment.hpp"
32#include "ProbeVolume.hpp"
34
35// Standard library
36#include <string>
37#include <unordered_map>
38
39namespace esengine { class GfxDevice; }
40
41namespace esengine::resource {
42
43enum class ShaderTargetLanguage : u8; // ShaderParser.hpp
44
50enum class ResourceContent : u32 {
53 Asset = 2,
54 Canvas = 3,
55 Video = 4,
56 Mesh = 5,
60};
61
64
65// =============================================================================
66// Resource Manager Statistics
67// =============================================================================
68
84
85// =============================================================================
86// ResourceManager Class
87// =============================================================================
88
113public:
114 ResourceManager() = default;
115 ~ResourceManager() = default;
116
117 // Non-copyable, movable
122
123 // =========================================================================
124 // Lifecycle
125 // =========================================================================
126
134 void init(GfxDevice& device);
135
138 GfxDevice* device() const { return device_; }
139
143 void shutdown();
144
149 bool isInitialized() const { return initialized_; }
150
154 void update();
155
156 // =========================================================================
157 // Shader Resources
158 // =========================================================================
159
168
176
188 bool deferLinks() const;
189
190 ShaderHandle createShader(const std::string& vertSrc, const std::string& fragSrc,
191 bool rewriteLoose = true,
193 bool deferLink = false);
194 ShaderHandle createShaderWithBindings(const std::string& vertSrc, const std::string& fragSrc,
195 std::initializer_list<AttribBinding> bindings,
197 bool deferLink = false);
198
205 ShaderHandle loadShader(const std::string& vertPath, const std::string& fragPath);
206
213
219 const Shader* getShader(ShaderHandle handle) const;
220
225 void releaseShader(ShaderHandle handle);
226
228 using ShaderRetiredCallback = void (*)(void*, ShaderHandle);
230 shaderRetiredOwner_ = owner; shaderRetiredCallback_ = callback;
231 }
232 void clearShaderRetiredCallback(void* owner) {
233 if (shaderRetiredOwner_ == owner) { shaderRetiredOwner_ = nullptr; shaderRetiredCallback_ = nullptr; }
234 }
235
241 u32 getShaderRefCount(ShaderHandle handle) const;
242
243 // =========================================================================
244 // Texture Resources
245 // =========================================================================
246
253
262 TextureHandle createTexture(ResourceContent content, u32 width, u32 height, ConstSpan<u8> pixels,
263 TextureFormat format, bool flipY = false);
264
272 ConstSpan<u8> pixels);
273
284 u32 mipLevels = 1);
285
291 TextureHandle loadTexture(const std::string& path);
292
299
305 const Texture* getTexture(TextureHandle handle) const;
306
311 void releaseTexture(TextureHandle handle);
312
319
331 TextureHandle registerExternalTexture(ResourceContent content, u32 glTextureId, u32 width, u32 height,
332 usize bytes = 0);
333
339
345 void registerTextureWithPath(TextureHandle handle, const std::string& path);
346
347 // =========================================================================
348 // Device Loss
349 // =========================================================================
350
358
364 std::vector<OwedTexture> texturesAwaitingReupload() const;
365
371
378
381 u32 textureNativeId(TextureHandle handle) const;
382
388 const std::string& getTexturePath(TextureHandle handle) const;
389
396 TextureHandle loadTextureByGUID(const std::string& guid, const std::string& path);
397
403 TextureHandle getTextureByGUID(const std::string& guid) const;
404
409 void releaseTextureByGUID(const std::string& guid);
410
415 void setTextureBudget(usize bytes);
416
418 void setRetainedBudget(usize bytes);
419
425 TextureHandle acquireTextureByPath(const std::string& path);
426
434 bool invalidateTexturePath(const std::string& path);
435
442
443 // =========================================================================
444 // Texture Metadata
445 // =========================================================================
446
452 void setTextureMetadata(TextureHandle handle, const TextureMetadata& metadata);
453
460
466 bool hasTextureMetadata(TextureHandle handle) const;
467
473
474 // =========================================================================
475 // Vertex Buffer Resources
476 // =========================================================================
477
484 template<typename T>
486
493
513 bool setMeshClusters(MeshHandle target, lod::ClusterHierarchy hierarchy);
514
520 bool setMeshSkinChunks(MeshHandle target, std::vector<MeshSkinChunk> chunks, std::vector<u16> bones);
521
523 ConstSpan<GfxVertexAttribute> channels, u32 vertexStride,
524 const glm::vec3& localMin, const glm::vec3& localMax,
525 MeshRecovery recovery, ConstSpan<f32> inverseBind = {},
526 const MeshMorphSource& morph = {});
527
537 bool rematerializeMesh(MeshHandle target, ConstSpan<u8> vertexBytes, ConstSpan<u32> indices,
538 ConstSpan<GfxVertexAttribute> channels, u32 vertexStride,
539 const glm::vec3& localMin, const glm::vec3& localMax,
540 ConstSpan<f32> inverseBind = {}, const MeshMorphSource& morph = {});
541
548 void setMeshEdgeBuffers(bool enabled) { meshEdges_ = enabled; }
549 bool meshEdgeBuffers() const { return meshEdges_; }
550
552 Mesh* getMesh(MeshHandle handle);
553 const Mesh* getMesh(MeshHandle handle) const;
554
556 void releaseMesh(MeshHandle handle);
557
562 u64 meshesRevision() const { return meshes_revision_; }
564 u64 textureMetadataRevision() const { return texture_metadata_revision_; }
565
571 std::vector<MeshHandle> meshesAwaitingRematerialization() const;
572
576 bool realized = false;
577 };
578
580 std::vector<MeshRealization> meshRealizations();
581
582 // =========================================================================
583 // Environment Resources
584 // =========================================================================
585
594 f32 faceSize, u32 mipCount, f32 maxRange,
595 u32 columns = 1);
596
599 const Environment* getEnvironment(EnvironmentHandle handle) const;
600
604
610 ProbeVolumeHandle createProbeVolume(const glm::ivec3& resolution, ConstSpan<f32> irradiance);
611
618 ProbeVolumeHandle createProbeVolumeBricks(const glm::ivec3& resolution, ConstSpan<i32> bricks,
619 ConstSpan<f32> irradiance);
620
623 const ProbeVolume* getProbeVolume(ProbeVolumeHandle handle) const;
624
627
634
641
647
648 // =========================================================================
649 // Index Buffer Resources
650 // =========================================================================
651
658
665
672
678 const IndexBuffer* getIndexBuffer(IndexBufferHandle handle) const;
679
685
686 // =========================================================================
687 // Bitmap Font Resources
688 // =========================================================================
689
690 BitmapFontHandle loadBitmapFont(const std::string& fntPath);
691
692 BitmapFontHandle createBitmapFont(const std::string& fntContent,
693 TextureHandle texture,
694 u32 texWidth, u32 texHeight);
695
697 u32 texWidth, u32 texHeight,
698 const std::string& chars,
699 u32 charWidth, u32 charHeight);
700
704
711
712 // =========================================================================
713 // Statistics
714 // =========================================================================
715
720 ResourceStats getStats() const;
721
725 void resetCacheStats();
726
727private:
728 void* shaderRetiredOwner_ = nullptr;
729 ShaderRetiredCallback shaderRetiredCallback_ = nullptr;
730 ResourcePool<Shader> shaders_;
731 ResourcePool<Texture> textures_;
732 ResourcePool<VertexBuffer> vertexBuffers_;
733 ResourcePool<IndexBuffer> indexBuffers_;
734 bool meshEdges_ = false;
735 ResourcePool<Mesh> meshes_;
737 MeshArena meshArena_;
739 u64 meshes_revision_ = 0;
740 u64 texture_metadata_revision_ = 0;
742 void releaseMeshGeometry(VertexBufferHandle vertices, IndexBufferHandle indices, VertexLayoutHandle layout,
743 u32 arenaPage, u32 arenaFirstVertex, u32 vertexCount, u32 firstIndex, u32 indexCount);
744
745public:
747 u32 meshPageCount() const { return meshArena_.pageCount(); }
748 u64 meshPageBytes() const { return meshArena_.pageBytes(); }
749
750private:
751 ResourcePool<Environment> environments_;
752 ResourcePool<ProbeVolume> probeVolumes_;
757 bool realizeMesh(Mesh& mesh, ConstSpan<u8> vertexBytes, ConstSpan<u32> indices,
758 ConstSpan<GfxVertexAttribute> channels, u32 vertexStride,
759 const glm::vec3& localMin, const glm::vec3& localMax,
760 ConstSpan<f32> inverseBind, const MeshMorphSource& morph);
763 esengine::TextureHandle createMorphTexture(GfxContent content, const MeshMorphSource& morph,
764 u32 vertexCount);
765
766 std::unordered_map<std::string, TextureHandle> guidToTexture_;
767 std::unordered_map<TextureHandle::IdType, TextureMetadata> textureMetadata_;
768 mutable ResourceStats stats_;
769 GfxDevice* device_ = nullptr;
770 bool initialized_ = false;
771};
772
773// =============================================================================
774// Template Implementations
775// =============================================================================
776
777template<typename T>
779 auto buffer = VertexBuffer::create(*device_, content, data);
780 if (!buffer) return VertexBufferHandle();
781 return vertexBuffers_.add(std::move(buffer));
782}
783
784} // namespace esengine::resource
GPU buffer abstractions for vertex and index data.
A baked environment: what a surface sees when no light faces it.
Type-safe resource handle system.
Meshes of one vertex shape sharing a vertex buffer, an index buffer and a layout.
Geometry that lives on the GPU rather than in a frame.
A baked environment sampled on a grid, rather than held at one value.
Type-erased resource pool with reference counting.
GPU shader program abstraction.
Texture metadata structures for nine-slice and other settings.
GPU texture abstraction for 2D images.
Core type definitions and utilities for ESEngine.
The two halves of an image-based light, as the importer baked them.
A content policy. provider names who refills a Sourced object and key what it refills; both are the p...
Abstract graphics device interface.
Definition GfxDevice.hpp:75
GPU buffer for index data.
Definition Buffer.hpp:337
Buffers, the layout that describes them, and the bounds culling reads.
Definition Mesh.hpp:85
Irradiance at a grid of points — an Environment sampled, not held.
GPU shader program for rendering.
Definition Shader.hpp:86
2D texture for GPU rendering
Definition Texture.hpp:116
GPU buffer for vertex data, static or dynamic; all GPU work goes through the device.
Definition Buffer.hpp:188
static Unique< VertexBuffer > create(GfxDevice &device, GfxContent content, std::span< const T > data)
Creates a static buffer from a span.
Definition Buffer.hpp:211
u64 textureMetadataRevision() const
Moves whenever a texture's metadata (its nine-slice borders and the rest) is set or dropped.
void update()
Updates resource manager (processes hot reload, call once per frame).
void(*)(void *, ShaderHandle) ShaderRetiredCallback
One renderer owns shader-derived metadata. Notify after final pool retirement.
ShaderHandle loadShader(const std::string &vertPath, const std::string &fragPath)
Loads a shader from file paths (with caching).
Texture * getTexture(TextureHandle handle)
Gets a texture by handle.
ShaderTargetLanguage preferredShaderTarget() const
preferredShaderLanguage() as a ShaderParser assembly target.
u32 getTextureRefCount(TextureHandle handle) const
Gets the current reference count for a texture.
ProbeVolumeHandle createProbeVolumeBricks(const glm::ivec3 &resolution, ConstSpan< i32 > bricks, ConstSpan< f32 > irradiance)
Registers a SPARSE grid: bricks at their own spacing (see ProbeVolume).
ShaderHandle createShaderWithBindings(const std::string &vertSrc, const std::string &fragSrc, std::initializer_list< AttribBinding > bindings, GfxShaderLanguage language=GfxShaderLanguage::GLSL_ES300, bool deferLink=false)
bool deferLinks() const
Creates a shader from source strings.
u32 textureNativeId(TextureHandle handle) const
The backend's own name for a texture's object, for a host that writes its pixels itself; 0 when there...
void forgoTextureContent(TextureHandle handle)
Gives up on an owed texture's content: it keeps blank storage.
void releaseVertexBuffer(VertexBufferHandle handle)
Releases a vertex buffer (decrements ref count).
void releaseIndexBuffer(IndexBufferHandle handle)
Releases an index buffer (decrements ref count).
BitmapFontHandle createLabelAtlasFont(TextureHandle texture, u32 texWidth, u32 texHeight, const std::string &chars, u32 charWidth, u32 charHeight)
BitmapFontHandle loadBitmapFont(const std::string &fntPath)
u32 getBitmapFontRefCount(BitmapFontHandle handle) const
Gets the current reference count for a bitmap font.
const std::string & getTexturePath(TextureHandle handle) const
Gets the cached path for a texture.
ResourceManager & operator=(ResourceManager &&)=default
EnvironmentHandle createEnvironment(ConstSpan< f32 > irradiance, TextureHandle specular, f32 faceSize, u32 mipCount, f32 maxRange, u32 columns=1)
Registers a baked environment.
BitmapFontHandle createBitmapFont(const std::string &fntContent, TextureHandle texture, u32 texWidth, u32 texHeight)
IndexBufferHandle createIndexBuffer(GfxContent content, ConstSpan< u32 > indices)
Creates an index buffer from 32-bit indices.
void registerTextureWithPath(TextureHandle handle, const std::string &path)
Registers a texture with a path for cache lookup.
std::vector< OwedTexture > texturesAwaitingReupload() const
void resetCacheStats()
Resets cache hit/miss counters.
bool isInitialized() const
Checks if the manager is initialized.
std::vector< MeshHandle > meshesAwaitingRematerialization() const
Replayable meshes whose geometry the device is still waiting for.
void releaseMesh(MeshHandle handle)
Releases a mesh and the buffers it owns.
const TextureMetadata * getTextureMetadata(TextureHandle handle) const
Gets metadata for a texture.
TextureHandle createTextureArray(ResourceContent content, const TextureSpecification &spec, ConstSpan< u8 > pixels)
Creates a 2D texture array from spec.layers same-size RGBA8 (or SRGB8A8) layers.
TextureHandle wrapDeviceTexture(::esengine::TextureHandle texture, u32 width, u32 height)
Names a texture the device holds for another owner (a render target's colour plane) by a resource han...
MeshHandle createMesh(ConstSpan< u8 > vertexBytes, ConstSpan< u32 > indices, ConstSpan< GfxVertexAttribute > channels, u32 vertexStride, const glm::vec3 &localMin, const glm::vec3 &localMax, MeshRecovery recovery, ConstSpan< f32 > inverseBind={}, const MeshMorphSource &morph={})
GfxShaderLanguage preferredShaderLanguage() const
The language embedded pipelines must author their sources in.
void releaseTextureByGUID(const std::string &guid)
Releases a texture by GUID.
bool setMeshSkinChunks(MeshHandle target, std::vector< MeshSkinChunk > chunks, std::vector< u16 > bones)
Gives a realized skinned mesh the chunks it is drawn in (Mesh::skinChunks).
TextureHandle loadTexture(const std::string &path)
Loads a texture from file (with caching).
bool setMeshClusters(MeshHandle target, lod::ClusterHierarchy hierarchy)
Uploads geometry that stays on the GPU, drawn from its own buffers.
void releaseShader(ShaderHandle handle)
Releases a shader (decrements ref count).
VertexBuffer * getVertexBuffer(VertexBufferHandle handle)
Gets a vertex buffer by handle.
ProbeVolumeHandle createProbeVolume(const glm::ivec3 &resolution, ConstSpan< f32 > irradiance)
Registers a grid of baked irradiance.
Shader * getShader(ShaderHandle handle)
Gets a shader by handle.
void shutdown()
Shuts down and releases all resources.
ProbeVolume * getProbeVolume(ProbeVolumeHandle handle)
The probe volume a handle names, or null.
TextureHandle createCompressedTexture(ResourceContent content, u32 width, u32 height, GfxCompressedFormat format, ConstSpan< u8 > data, u32 mipLevels=1)
Creates a block-compressed texture (KTX2 → ETC2/ASTC/BC), uploading the pre-compressed blocks for mip...
text::BitmapFont * getBitmapFont(BitmapFontHandle handle)
ShaderHandle createShader(const std::string &vertSrc, const std::string &fragSrc, bool rewriteLoose=true, GfxShaderLanguage language=GfxShaderLanguage::GLSL_ES300, bool deferLink=false)
u32 getShaderRefCount(ShaderHandle handle) const
Gets the current reference count for a shader.
ResourceManager(ResourceManager &&)=default
void removeTextureMetadata(TextureHandle handle)
Removes metadata for a texture.
Mesh * getMesh(MeshHandle handle)
The mesh a handle names, or null.
std::vector< MeshRealization > meshRealizations()
Every live mesh, for a recovery criterion to read.
u64 meshesRevision() const
Changes whenever any mesh is realized (each takes a new Mesh::revision) or released: while it holds,...
ResourceManager(const ResourceManager &)=delete
void releaseProbeVolume(ProbeVolumeHandle handle)
Releases a probe volume.
bool rematerializeMesh(MeshHandle target, ConstSpan< u8 > vertexBytes, ConstSpan< u32 > indices, ConstSpan< GfxVertexAttribute > channels, u32 vertexStride, const glm::vec3 &localMin, const glm::vec3 &localMax, ConstSpan< f32 > inverseBind={}, const MeshMorphSource &morph={})
Puts new geometry behind an EXISTING mesh handle.
void restoreTextureContent(TextureHandle handle)
Settles an owed texture whose provider wrote the pixels itself.
ResourceStats getStats() const
Gets current resource statistics.
void releaseEnvironment(EnvironmentHandle handle)
Releases an environment. The atlas is an ordinary texture asset with its own lifetime,...
bool adoptTextureContent(TextureHandle target, TextureHandle source)
Moves a freshly loaded texture's pixels behind an owed handle.
bool invalidateTexturePath(const std::string &path)
Severs a path's texture-cache identity (hot reload). The next acquireTextureByPath for it misses,...
void setMeshEdgeBuffers(bool enabled)
Whether meshes realized FROM NOW ON also get an edge buffer.
Environment * getEnvironment(EnvironmentHandle handle)
The environment a handle names, or null.
TextureHandle createTexture(ResourceContent content, const TextureSpecification &spec)
Creates a texture from specification.
void setTextureMetadata(TextureHandle handle, const TextureMetadata &metadata)
Sets metadata for a texture.
IndexBuffer * getIndexBuffer(IndexBufferHandle handle)
Gets an index buffer by handle.
void init(GfxDevice &device)
Initializes the resource manager.
void releaseBitmapFont(BitmapFontHandle handle)
ResourceManager & operator=(const ResourceManager &)=delete
VertexBufferHandle createVertexBuffer(GfxContent content, ConstSpan< T > data)
Creates a vertex buffer from typed data.
void setRetainedBudget(usize bytes)
See GfxDevice::setRetainedBudget.
TextureHandle getTextureByGUID(const std::string &guid) const
Gets a texture handle by GUID if already loaded.
void releaseTexture(TextureHandle handle)
Releases a texture (decrements ref count).
TextureHandle registerExternalTexture(ResourceContent content, u32 glTextureId, u32 width, u32 height, usize bytes=0)
Registers an externally-created GL texture.
usize trimTextureCache()
Frees every evictable cached texture now (memory pressure). Held textures and the budget are untouche...
void setTextureBudget(usize bytes)
Sets the texture pool's resident-byte budget (0 = no eviction). Over budget, refCount==0 textures are...
TextureHandle acquireTextureByPath(const std::string &path)
Reuses a cached texture by its build path: returns its handle with an added reference (reviving an ev...
void setShaderRetiredCallback(void *owner, ShaderRetiredCallback callback)
TextureHandle loadTextureByGUID(const std::string &guid, const std::string &path)
Loads a texture by GUID (with caching).
bool hasTextureMetadata(TextureHandle handle) const
Checks if a texture has metadata.
Typed resource pool with reference counting.
ShaderTargetLanguage
Target language for stage assembly (REARCH_WGSL dual emission).
ResourceContent
Who refills a resource's GPU content after a device loss.
@ Asset
The asset layer loads it again from its path.
@ Retained
The device keeps the bytes (a tile collection composed at load).
@ Video
Refilled by the next decoded frame.
@ GlyphPage
Repainted from the glyphs placed on it.
@ Canvas
Redrawn from the canvas it mirrors.
@ AtlasPage
A skeleton's atlas page, decoded again from its image.
@ Composed
Composed again by its creator from its sources (a terrain's layer arrays).
@ Transient
Rewritten by its owner before every use (a video frame).
GfxContent toGfxContent(ResourceContent content)
The device's policy for a content code; unknown codes are Asset, the one that asks.
Handle< esengine::Shader > ShaderHandle
Handle to a shader resource.
Definition Handle.hpp:214
Handle< esengine::text::BitmapFont > BitmapFontHandle
Handle to a bitmap font resource.
Definition Handle.hpp:238
Handle< esengine::Environment > EnvironmentHandle
Handle to a baked environment (irradiance + prefiltered reflection).
Definition Handle.hpp:229
Handle< esengine::IndexBuffer > IndexBufferHandle
Handle to an index buffer resource.
Definition Handle.hpp:223
Handle< esengine::VertexBuffer > VertexBufferHandle
Handle to a vertex buffer resource.
Definition Handle.hpp:220
Handle< esengine::Texture > TextureHandle
Handle to a texture resource.
Definition Handle.hpp:217
Handle< esengine::ProbeVolume > ProbeVolumeHandle
Handle to a grid of baked irradiance.
Definition Handle.hpp:232
Handle< esengine::Mesh > MeshHandle
Handle to GPU-resident geometry.
Definition Handle.hpp:226
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
MeshRecovery
How a mesh's geometry comes back after a device generation ends.
Definition Mesh.hpp:28
GfxShaderLanguage
Shader source language a backend consumes.
Definition GfxEnums.hpp:654
TextureFormat
Texture pixel format.
Definition Texture.hpp:45
GfxCompressedFormat
GPU-compressed texture internal formats for createCompressedTexture.
Definition GfxEnums.hpp:326
std::span< const T > ConstSpan
Definition Types.hpp:242
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
std::uint8_t u8
Unsigned 8-bit integer.
Definition Types.hpp:41
float f32
32-bit floating point
Definition Types.hpp:59
The shapes handed to a realization: the deltas, and how to read them.
Definition Mesh.hpp:39
Texture creation parameters.
Definition Texture.hpp:74
A mesh's clusters and the indices they name, every level together.
One live mesh and whether its geometry is on the device.
Textures the device is waiting for content for, with who refills them.
Statistics about resource usage.
usize indexBufferCount
Number of active index buffers.
usize shaderCount
Number of active shaders.
usize vertexBufferCount
Number of active vertex buffers.
usize retainedBytes
CPU copies the device keeps to restore content after a loss.
usize textureCount
Number of active textures.
usize cacheMisses
Number of cache misses since reset.
usize cacheHits
Number of cache hits since reset.
usize textureBytes
Resident texture bytes (RGBA8 estimate) — VRAM usage.
usize textureEvictableCount
Cached refCount==0 textures awaiting revive/evict.
usize textureBudget
Texture pool resident-byte budget (0 = eviction off).
Metadata associated with a texture resource.