Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
ResourceManager.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
13
14#include "../core/Half.hpp"
15#include "ResourceManager.hpp"
16#include "MeshUvDensity.hpp"
17#include "MeshEdges.hpp"
18#include "ShaderParser.hpp"
20#include "../core/Log.hpp"
21#include "../core/Revision.hpp"
26
27#include <algorithm>
28#include <cstring>
29#include <vector>
30
31namespace esengine::resource {
32
33namespace {
34
35bool meshOwed(const Mesh& mesh, const std::vector<GfxOwedContent>& owed) {
36 for (const GfxOwedContent& entry : owed) {
37 if (entry.kind == GfxOwedContent::Kind::Buffer
38 && (entry.id == static_cast<u32>(mesh.vertexBuffer) || entry.id == static_cast<u32>(mesh.indexBuffer)
39 || (mesh.hasEdges() && entry.id == static_cast<u32>(mesh.edgeIndexBuffer)))) {
40 return true;
41 }
42 if (entry.kind == GfxOwedContent::Kind::Texture && entry.id == static_cast<u32>(mesh.morphTexture)) {
43 return true;
44 }
45 }
46 return false;
47}
48
49} // namespace
50
52 if (initialized_) {
53 ES_LOG_WARN("ResourceManager already initialized");
54 return;
55 }
56
57 device_ = &device;
58 meshArena_.init(device);
59
60 stats_ = {};
61 initialized_ = true;
62}
63
65 if (!initialized_) {
66 return;
67 }
68
69 ES_LOG_INFO("ResourceManager shutting down (shaders: {}, textures: {}, vbos: {}, ibos: {}, fonts: {})",
70 shaders_.size(), textures_.size(), vertexBuffers_.size(), indexBuffers_.size(), fonts_.size());
71
72 guidToTexture_.clear();
73 textureMetadata_.clear();
74 ++texture_metadata_revision_;
75 fonts_.clear();
76 std::vector<ShaderHandle> retiredShaders;
77 shaders_.forEachAlive([&](ShaderHandle handle, const Shader&) { retiredShaders.push_back(handle); });
78 shaders_.clear();
79 if (shaderRetiredCallback_) for (ShaderHandle handle : retiredShaders) shaderRetiredCallback_(shaderRetiredOwner_, handle);
80 textures_.clear();
81 std::vector<MeshHandle> retiredMeshes;
82 meshes_.forEachAlive([&](MeshHandle handle, const Mesh&) { retiredMeshes.push_back(handle); });
83 for (MeshHandle handle : retiredMeshes) releaseMesh(handle);
84 meshArena_.shutdown();
85 vertexBuffers_.clear();
86 indexBuffers_.clear();
87
88 // Drop the device ref so a stray create after shutdown returns an empty
89 // handle instead of dereferencing a freed GfxDevice (A10).
90 device_ = nullptr;
91 initialized_ = false;
92 ES_LOG_INFO("ResourceManager shutdown complete");
93}
94
96 // Hot reload is editor/native-only; no-op on web.
97}
98
99// =============================================================================
100// Shader Resources
101// =============================================================================
102
108
114
116 return device_ && device_->skipPendingPrograms();
117}
118
119ShaderHandle ResourceManager::createShader(const std::string& vertSrc, const std::string& fragSrc,
120 bool rewriteLoose, GfxShaderLanguage language, bool deferLink) {
121 if (!device_) return {};
122
123 // Lift loose non-sampler uniforms into a std140 DrawParams block, so this
124 // shader's parameters flow through the UBO seam (setUniform writes the CPU
125 // shadow; commitParams uploads + binds). ShaderParser-assembled material
126 // sources pass rewriteLoose=false: their params already live in
127 // MaterialConstants and only sampler uniforms remain loose. The rewriter is
128 // a GLSL-source transform — other languages skip it.
129 if (rewriteLoose && language == GfxShaderLanguage::GLSL_ES300) {
130 DrawParamsRewrite rw = rewriteLooseUniforms(vertSrc, fragSrc);
131 if (!rw.layout.empty()) {
132 auto shader = Shader::create(*device_, rw.vertexSrc, rw.fragmentSrc);
133 if (shader) {
134 shader->adoptDrawParams(std::move(rw.layout));
135 return shaders_.add(std::move(shader));
136 }
137 // The unmodified source is the author's ground truth — if the lifted
138 // form fails to compile (a rewriter blind spot), fall back to it
139 // loudly rather than failing a shader that used to work.
140 ES_LOG_WARN("DrawParams rewrite failed to compile; retrying shader with loose uniforms");
141 }
142 }
143
144 // Through createEx for the LOG: the device already answers why it refused, and a
145 // caller that drops it leaves "failed to create" as the only thing anybody sees.
146 auto outcome = Shader::createEx(*device_, vertSrc, fragSrc, {}, language, deferLink);
147 if (!outcome.shader) {
148 ES_LOG_ERROR("Failed to create shader from source: {}",
149 outcome.log.empty() ? "no reason given by the device" : outcome.log.c_str());
150 return ShaderHandle();
151 }
152 return shaders_.add(std::move(outcome.shader));
153}
154
155ShaderHandle ResourceManager::createShaderWithBindings(const std::string& vertSrc, const std::string& fragSrc,
156 std::initializer_list<AttribBinding> bindings,
157 GfxShaderLanguage language, bool deferLink) {
158 if (!device_) return {};
159 auto shader = Shader::createWithBindings(*device_, vertSrc, fragSrc, bindings, language, deferLink);
160 if (!shader) {
161 ES_LOG_ERROR("Failed to create shader with bindings from source");
162 return ShaderHandle();
163 }
164 return shaders_.add(std::move(shader));
165}
166
167ShaderHandle ResourceManager::loadShader(const std::string& vertPath, const std::string& fragPath) {
168 // Create cache key from paths
169 std::string cacheKey = vertPath + ":" + fragPath;
170
171 // Check cache
172 auto cached = shaders_.findByPath(cacheKey);
173 if (cached.isValid()) {
174 shaders_.addRef(cached);
175 stats_.cacheHits++;
176 return cached;
177 }
178
179 // Load from files
180 if (!device_) return {};
181 auto shader = Shader::createFromFile(*device_, vertPath, fragPath);
182 if (!shader) {
183 stats_.cacheMisses++;
184 return ShaderHandle();
185 }
186
187 stats_.cacheMisses++;
188 return shaders_.add(std::move(shader), cacheKey);
189}
190
192 return shaders_.get(handle);
193}
194
196 return shaders_.get(handle);
197}
198
200 if (handle.isValid()) {
201 const bool final = shaders_.getRefCount(handle) == 1;
202 shaders_.release(handle.id());
203 if (final && shaderRetiredCallback_) shaderRetiredCallback_(shaderRetiredOwner_, handle);
204 }
205}
206
208 return shaders_.getRefCount(handle);
209}
210
211// =============================================================================
212// Texture Resources
213// =============================================================================
214
216 switch (content) {
219 default: return GfxContent::sourced(static_cast<u32>(content), 0);
220 }
221}
222
224 if (!device_) return {};
225 auto texture = Texture::create(*device_, toGfxContent(content), spec);
226 if (!texture) {
227 ES_LOG_ERROR("Failed to create texture from spec");
228 return TextureHandle();
229 }
230 const usize bytes = static_cast<usize>(texture->getWidth()) * texture->getHeight() * 4;
231 return textures_.add(std::move(texture), "", bytes);
232}
233
235 ConstSpan<u8> pixels, TextureFormat format, bool flipY) {
236 if (!device_) return {};
237 auto texture = Texture::create(*device_, toGfxContent(content), width, height,
238 std::span<const u8>(pixels.data(), pixels.size()), format, flipY);
239 if (!texture) {
240 ES_LOG_ERROR("Failed to create texture from pixels");
241 return TextureHandle();
242 }
243 const usize bytes = static_cast<usize>(width) * height * 4;
244 return textures_.add(std::move(texture), "", bytes);
245}
246
248 ConstSpan<u8> pixels) {
249 if (!device_) return {};
250 const bool rgba = spec.format == TextureFormat::RGBA8 || spec.format == TextureFormat::SRGB8A8;
251 const usize layerBytes = static_cast<usize>(spec.width) * spec.height * 4;
252 const usize bytes = layerBytes * spec.layers;
253 if (!rgba || spec.layers < 1 || layerBytes == 0 || pixels.size() != bytes) {
254 ES_LOG_ERROR("createTextureArray: {} bytes for {} RGBA8 layers of {}x{} (expected {})",
255 pixels.size(), spec.layers, spec.width, spec.height, bytes);
256 return TextureHandle();
257 }
258 auto texture = Texture::createArray(*device_, toGfxContent(content), spec, pixels.data());
259 if (!texture) {
260 ES_LOG_ERROR("Failed to create texture array");
261 return TextureHandle();
262 }
263 return textures_.add(std::move(texture), "", bytes);
264}
265
268 u32 mipLevels) {
269 if (!device_) return {};
270 auto texture = Texture::createCompressed(*device_, toGfxContent(content), width, height, format,
271 std::span<const u8>(data.data(), data.size()), mipLevels);
272 if (!texture) {
273 ES_LOG_ERROR("Failed to create compressed texture");
274 return TextureHandle();
275 }
276 // Residency cost is the on-GPU compressed size, not the RGBA expansion.
277 return textures_.add(std::move(texture), "", data.size());
278}
279
281 auto cached = textures_.findByPath(path);
282 if (cached.isValid()) {
283 textures_.addRef(cached);
284 stats_.cacheHits++;
285 return cached;
286 }
287
288 // Web decodes images JS-side and uploads via createTexture/registerExternalTexture;
289 // there is no C++ file-decode path.
290 ES_LOG_ERROR("loadTexture from file not supported on Web, use createTexture with pixel data");
291 stats_.cacheMisses++;
292 return TextureHandle();
293}
294
296 return textures_.get(handle);
297}
298
300 return textures_.get(handle);
301}
302
304 if (!handle.isValid()) return;
305 const bool lastRef = textures_.getRefCount(handle) == 1;
306 textures_.release(handle.id());
307 // Drop the sidecar metadata + GUID mapping only when the texture is TRULY gone.
308 // Under an eviction budget the last release keeps it resident and revivable
309 // (findByPath + addRef re-holds the SAME handle), so erasing here would strand
310 // a revived texture without its nine-slice metadata / GUID lookup.
311 if (lastRef && !textures_.isEvictable(handle)) {
312 if (textureMetadata_.erase(handle.id())) ++texture_metadata_revision_;
313 for (auto it = guidToTexture_.begin(); it != guidToTexture_.end(); ) {
314 if (it->second == handle) {
315 it = guidToTexture_.erase(it);
316 } else {
317 ++it;
318 }
319 }
320 }
321}
322
324 return textures_.getRefCount(handle);
325}
326
328 u32 width, u32 height, usize bytes) {
329 if (!device_) return {};
330 auto texture = Texture::createFromExternalId(*device_, toGfxContent(content), glTextureId,
331 width, height, TextureFormat::RGBA8);
332 if (!texture || texture->handle() == ::esengine::TextureHandle::Invalid) {
333 ES_LOG_ERROR("Failed to register external texture (GL ID: {})", glTextureId);
334 return TextureHandle();
335 }
336 if (bytes == 0) {
337 bytes = static_cast<usize>(width) * height * 4;
338 }
339 return textures_.add(std::move(texture), "", bytes);
340}
341
343 if (!device_) return {};
344 auto wrapper = Texture::borrow(*device_, texture, width, height);
345 if (!wrapper) return {};
346 // The owner pays for the memory; a borrow costs the budget nothing.
347 return textures_.add(std::move(wrapper), "", 0);
348}
349
351 Texture* to = textures_.get(target);
352 Texture* from = textures_.get(source);
353 return to && from && to->adoptContent(*from);
354}
355
356std::vector<ResourceManager::OwedTexture> ResourceManager::texturesAwaitingReupload() const {
357 std::vector<OwedTexture> out;
358 if (!device_) return out;
359 const std::vector<GfxOwedContent> owed = device_->owedContent();
360 if (owed.empty()) return out;
361 textures_.forEachAlive([&](TextureHandle handle, const Texture& texture) {
362 for (const GfxOwedContent& entry : owed) {
363 if (entry.kind == GfxOwedContent::Kind::Texture && entry.id == texture.getId()) {
364 out.push_back({handle, static_cast<ResourceContent>(entry.provider)});
365 break;
366 }
367 }
368 });
369 return out;
370}
371
373 const Texture* texture = textures_.get(handle);
374 if (!device_ || !texture) return;
375 for (const GfxOwedContent& entry : device_->owedContent()) {
376 if (entry.kind == GfxOwedContent::Kind::Texture && entry.id == texture->getId()) {
377 device_->forgoContent(entry);
378 return;
379 }
380 }
381}
382
384 const Texture* texture = textures_.get(handle);
385 if (!device_ || !texture) return;
386 for (const GfxOwedContent& entry : device_->owedContent()) {
387 if (entry.kind == GfxOwedContent::Kind::Texture && entry.id == texture->getId()) {
388 device_->restoreContent(entry);
389 return;
390 }
391 }
392}
393
395 const Texture* texture = textures_.get(handle);
396 return device_ && texture ? device_->nativeTextureName(texture->handle()) : 0;
397}
398
399void ResourceManager::registerTextureWithPath(TextureHandle handle, const std::string& path) {
400 if (handle.isValid() && !path.empty()) {
401 textures_.setPath(handle, path);
402 }
403}
404
405const std::string& ResourceManager::getTexturePath(TextureHandle handle) const {
406 return textures_.getPath(handle);
407}
408
410 textures_.setBudget(bytes);
411}
412
414 if (device_) device_->setRetainedBudget(bytes);
415}
416
418 auto handle = textures_.findByPath(path);
419 if (!handle.isValid()) {
420 ++stats_.cacheMisses;
421 return handle;
422 }
423 // A texture still owed its content does not hold this path's pixels, so a
424 // residency hit would answer the re-upload with the very thing it replaces —
425 // a recovery that confirms itself and draws blank. Empty at rest.
426 const Texture* texture = textures_.get(handle);
427 for (const GfxOwedContent& entry : device_ ? device_->owedContent() : std::vector<GfxOwedContent>{}) {
428 if (texture && entry.kind == GfxOwedContent::Kind::Texture && entry.id == texture->getId()) {
429 ++stats_.cacheMisses;
430 return TextureHandle{};
431 }
432 }
433 // The cache decision a shipped build makes: it decodes in the host and
434 // registers an id, so this is the one place a texture request avoids an
435 // upload. loadTexture, which also counts, is a path only BitmapFont takes.
436 ++stats_.cacheHits;
437 textures_.addRef(handle);
438 return handle;
439}
440
441bool ResourceManager::invalidateTexturePath(const std::string& path) {
442 return textures_.invalidatePath(path);
443}
444
446 return textures_.trimEvictables();
447}
448
449TextureHandle ResourceManager::loadTextureByGUID(const std::string& guid, const std::string& path) {
450 auto it = guidToTexture_.find(guid);
451 if (it != guidToTexture_.end() && it->second.isValid()) {
452 textures_.addRef(it->second);
453 stats_.cacheHits++;
454 return it->second;
455 }
456
457 TextureHandle handle = loadTexture(path);
458 if (handle.isValid()) {
459 guidToTexture_[guid] = handle;
460 }
461 return handle;
462}
463
464TextureHandle ResourceManager::getTextureByGUID(const std::string& guid) const {
465 auto it = guidToTexture_.find(guid);
466 if (it != guidToTexture_.end()) {
467 return it->second;
468 }
469 return TextureHandle();
470}
471
472void ResourceManager::releaseTextureByGUID(const std::string& guid) {
473 auto it = guidToTexture_.find(guid);
474 if (it != guidToTexture_.end()) {
475 releaseTexture(it->second);
476 guidToTexture_.erase(it);
477 }
478}
479
480// =============================================================================
481// Texture Metadata
482// =============================================================================
483
485 if (handle.isValid()) {
486 textureMetadata_[handle.id()] = metadata;
487 ++texture_metadata_revision_;
488 }
489}
490
492 if (!handle.isValid()) return nullptr;
493 auto it = textureMetadata_.find(handle.id());
494 if (it != textureMetadata_.end()) {
495 return &it->second;
496 }
497 return nullptr;
498}
499
501 if (!handle.isValid()) return false;
502 return textureMetadata_.find(handle.id()) != textureMetadata_.end();
503}
504
506 if (handle.isValid()) {
507 if (textureMetadata_.erase(handle.id())) ++texture_metadata_revision_;
508 }
509}
510
511// =============================================================================
512// Vertex Buffer Resources
513// =============================================================================
514
516 if (!device_) return {};
517 auto buffer = VertexBuffer::create(*device_, content, sizeBytes);
518 if (!buffer) {
519 ES_LOG_ERROR("Failed to create dynamic vertex buffer");
520 return VertexBufferHandle();
521 }
522 return vertexBuffers_.add(std::move(buffer));
523}
524
526 return vertexBuffers_.get(handle);
527}
528
530 return vertexBuffers_.get(handle);
531}
532
534 if (handle.isValid()) {
535 vertexBuffers_.release(handle.id());
536 }
537}
538
539// =============================================================================
540// Mesh Resources
541// =============================================================================
542
543namespace {
544
545} // namespace
546
547bool ResourceManager::realizeMesh(Mesh& mesh, ConstSpan<u8> vertexBytes, ConstSpan<u32> indices,
548 ConstSpan<GfxVertexAttribute> channels, u32 vertexStride,
549 const glm::vec3& localMin, const glm::vec3& localMax,
550 ConstSpan<f32> inverseBind, const MeshMorphSource& morph) {
551 if (!device_ || vertexBytes.empty() || indices.empty() || channels.empty()) return false;
552
553 // Every mesh shader reads a colour, and a layout without one is a pipeline WebGPU
554 // refuses (WebGL2 reads black). A producer that wrote none meant white, so the
555 // channel is added here, where every mesh reaches the device.
556 std::vector<u8> coloredBytes;
557 std::vector<GfxVertexAttribute> coloredChannels;
558 const bool hasColor = std::any_of(channels.begin(), channels.end(), [](const GfxVertexAttribute& c) {
559 return c.location == static_cast<u32>(MeshChannel::Color);
560 });
561 if (!hasColor && vertexStride > 0) {
562 const usize count = vertexBytes.size() / vertexStride;
563 const u32 colorOffset = (vertexStride + 3u) & ~3u;
564 const u32 stride = colorOffset + 4u;
565 coloredBytes.assign(count * stride, 0);
566 for (usize v = 0; v < count; ++v) {
567 std::memcpy(&coloredBytes[v * stride], &vertexBytes[v * vertexStride], vertexStride);
568 std::memset(&coloredBytes[v * stride + colorOffset], 0xFF, 4);
569 }
570 coloredChannels.assign(channels.begin(), channels.end());
571 GfxVertexAttribute color;
572 color.location = static_cast<u32>(MeshChannel::Color);
573 color.components = 4;
574 color.type = GfxDataType::UnsignedByte;
575 color.normalized = true;
576 color.offset = colorOffset;
577 coloredChannels.push_back(color);
578 vertexBytes = ConstSpan<u8>(coloredBytes);
579 channels = ConstSpan<GfxVertexAttribute>(coloredChannels);
580 vertexStride = stride;
581 }
582
583 // The mesh describes its own vertices and nothing else: the per-object
584 // transform reaches the shader through the frame's record texture, which is
585 // what leaves every slot above the mesh channels free.
586 VertexLayoutDesc layout;
587 // A channel no shader reads stays out of the layout (meshShaderReads): it
588 // would spend an attribute slot and a fetch per vertex. The stride is
589 // unchanged, so the bytes remain for whoever starts reading them.
590 u32 bound = 0;
591 for (const GfxVertexAttribute& c : channels) {
592 if (!meshShaderReads(static_cast<MeshChannel>(c.location))) continue;
593 if (bound >= MAX_VERTEX_ATTRIBUTES) {
594 ES_LOG_ERROR("realizeMesh: {} bound channels exceeds the layout budget", bound + 1);
595 return false;
596 }
597 layout.attributes[bound] = c;
598 layout.attributes[bound].bufferSlot = 0;
599 ++bound;
600 }
601 bool hasNormals = false;
602 bool skinned = false;
603 bool lightmapUV = false;
604 bool tangentChannel = false;
605 for (const GfxVertexAttribute& c : channels) {
606 if (c.location == static_cast<u32>(MeshChannel::Normal)) hasNormals = true;
607 if (c.location == static_cast<u32>(MeshChannel::Joints)) skinned = true;
608 if (c.location == static_cast<u32>(MeshChannel::TexCoord1)) lightmapUV = true;
609 if (c.location == static_cast<u32>(MeshChannel::Tangent)) tangentChannel = true;
610 }
611 skinned = skinned && !inverseBind.empty();
612 // Bones move a character and a bake cannot hold one still, so a skinned mesh
613 // reads no atlas however many UV sets it carries — and its record stays the
614 // tint alone.
615 const bool lightmapped = lightmapUV && !skinned;
616
617 layout.strides[0] = vertexStride;
618 layout.attributeCount = bound;
619
620 // The old records go only once the new ones stand: a rematerialization that
621 // fails half-way must leave the mesh as it found it, not stripped of the
622 // realization it still had.
623 const VertexBufferHandle previousVertices = mesh.vertices;
624 const IndexBufferHandle previousIndices = mesh.indices;
625 const IndexBufferHandle previousEdges = mesh.edges;
626 const VertexLayoutHandle previousLayout = mesh.layout;
627 const u32 previousPage = mesh.arenaPage, previousFirstVertex = mesh.arenaFirstVertex, previousVertexCount = mesh.vertexCount;
628 const u32 previousFirstIndex = mesh.firstIndex, previousIndexCount = mesh.indexCount;
629
630 // A replayable mesh is refilled by its source; one built in this process has
631 // no other copy, so the device keeps it.
632 const GfxContent content = mesh.recovery == MeshRecovery::SourceReplayable
634 : GfxContent::retained();
635
636 // A page shared with the meshes of its vertex shape, where it can have one: drawn one after another, they switch no vertex
637 // array, buffer or pipeline. Not a mesh that reads its own vertex number (morph deltas are found by gl_VertexID, which a
638 // page's numbering would shift), and not one the device has to keep the bytes of (a page is written in parts, and kept
639 // whole would keep every mesh in it twice).
640 const bool morphs = morph.targetCount > 0 && !morph.deltas.empty();
641 MeshArena::Slot slot;
642 MeshArena::Binding shared;
643 // Not a skinned one either: the skin cache draws it from a copy of its own vertices alone, which a page's numbering
644 // would not index.
645 const bool placed = mesh.recovery == MeshRecovery::SourceReplayable && !morphs && !skinned
646 && meshArena_.place(layout, content, vertexBytes, vertexStride, indices, slot, shared);
647
648 VertexBufferHandle vertices;
649 IndexBufferHandle indices_handle;
650 BufferHandle vertexBufferId = shared.vertexBuffer;
651 BufferHandle indexBufferId = shared.indexBuffer;
652 VertexLayoutHandle layoutHandle = shared.layout;
653 if (!placed) {
654 vertices = createVertexBuffer(content, vertexBytes);
655 indices_handle = createIndexBuffer(content, indices);
656 const VertexBuffer* vb = getVertexBuffer(vertices);
657 const IndexBuffer* ib = getIndexBuffer(indices_handle);
658 layoutHandle = device_->createVertexLayout(layout);
659 // A pool record is not a GPU object. An allocation the device refused still
660 // lands in the pool, so its handle reads as valid while naming nothing — the
661 // shape in which a failure becomes a mesh that silently draws no triangles.
662 if (!vb || !ib || vb->handle() == BufferHandle::Invalid
663 || ib->handle() == BufferHandle::Invalid || layoutHandle == VertexLayoutHandle::Invalid) {
664 releaseVertexBuffer(vertices);
665 releaseIndexBuffer(indices_handle);
666 device_->deleteVertexLayout(layoutHandle);
667 return false;
668 }
669 vertexBufferId = vb->handle();
670 indexBufferId = ib->handle();
671 }
672
673 // The edges follow the triangles' own content policy, and a failure to make them
674 // costs the wireframe view, never the mesh.
675 IndexBufferHandle edgeHandle;
676 u32 edgeCount = 0;
677 if (meshEdges_) {
678 std::vector<u32> lines = distinctMeshEdges(indices);
679 // The edges index the same vertices as the triangles, so they are rebased onto a page's as the triangles were.
680 if (placed) for (u32& index : lines) index += slot.firstVertex;
681 edgeHandle = createIndexBuffer(content, ConstSpan<u32>(lines));
682 const IndexBuffer* eb = getIndexBuffer(edgeHandle);
683 if (eb && eb->handle() != BufferHandle::Invalid) {
684 edgeCount = static_cast<u32>(lines.size());
685 } else {
686 releaseIndexBuffer(edgeHandle);
687 edgeHandle = IndexBufferHandle();
688 }
689 }
690
691 releaseMeshGeometry(previousVertices, previousIndices, previousLayout, previousPage, previousFirstVertex,
692 previousVertexCount, previousFirstIndex, previousIndexCount);
693 releaseIndexBuffer(previousEdges);
694
695 mesh.edges = edgeHandle;
696 mesh.edgeIndexBuffer = edgeCount > 0 ? getIndexBuffer(edgeHandle)->handle() : BufferHandle::Invalid;
697 mesh.edgeIndexCount = edgeCount;
698 mesh.vertices = vertices;
699 mesh.indices = indices_handle;
700 mesh.vertexBuffer = vertexBufferId;
701 mesh.indexBuffer = indexBufferId;
702 mesh.layout = layoutHandle;
703 mesh.indexCount = static_cast<u32>(indices.size());
704 mesh.firstIndex = placed ? slot.firstIndex : 0;
705 mesh.arenaPage = placed ? slot.page : 0;
706 mesh.arenaFirstVertex = placed ? slot.firstVertex : 0;
707 mesh.hasNormals = hasNormals;
708 mesh.hasLightmapUV = lightmapped;
709 // A tangent frame is a frame OF the normal: one without a normal to square it to is not read.
710 mesh.hasTangents = tangentChannel && hasNormals;
711 mesh.localMin = localMin;
712 mesh.localMax = localMax;
713 {
714 const GfxVertexAttribute* position = nullptr;
715 const GfxVertexAttribute* uv = nullptr;
716 for (const GfxVertexAttribute& c : channels) {
717 if (c.location == static_cast<u32>(MeshChannel::Position) && c.type == GfxDataType::Float && c.components >= 3) position = &c;
718 if (c.location == static_cast<u32>(MeshChannel::TexCoord0) && c.type == GfxDataType::Float && c.components >= 2) uv = &c;
719 }
720 mesh.uvDensity = position && uv
721 ? meshUvDensity(vertexBytes.data(), vertexBytes.size(), vertexStride, position->offset, uv->offset, indices.data(), indices.size())
722 : 0.0f;
723 }
724 mesh.inverseBind.clear();
725 if (skinned) {
726 const usize joints = inverseBind.size() / 16;
727 mesh.inverseBind.resize(joints);
728 std::memcpy(mesh.inverseBind.data(), inverseBind.data(), joints * sizeof(glm::mat4));
729 }
730 mesh.vertexCount = vertexStride > 0 ? static_cast<u32>(vertexBytes.size()) / vertexStride : 0;
731 // What the skin cache skins (SkinCache.hpp): the vertices as uploaded, and where in one each channel it reads sits.
732 mesh.skinSource.reset();
733 mesh.skinIndices.reset();
734 mesh.skinLayout = MeshSkinLayout{};
735 if (skinned) {
736 mesh.skinSource = std::make_shared<const std::vector<u8>>(vertexBytes.data(), vertexBytes.data() + vertexBytes.size());
737 mesh.skinIndices = std::make_shared<const std::vector<u32>>(indices.data(), indices.data() + indices.size());
738 mesh.skinLayout.stride = vertexStride;
739 for (const GfxVertexAttribute& c : channels) {
740 const auto at = static_cast<i32>(c.offset);
741 switch (static_cast<MeshChannel>(c.location)) {
742 case MeshChannel::Position: if (c.type == GfxDataType::Float && c.components >= 3) mesh.skinLayout.position = at; break;
743 case MeshChannel::Normal: if (c.type == GfxDataType::Float && c.components >= 3) mesh.skinLayout.normal = at; break;
744 case MeshChannel::Tangent: if (c.type == GfxDataType::Float && c.components >= 4) mesh.skinLayout.tangent = at; break;
746 mesh.skinLayout.joints = at;
747 mesh.skinLayout.jointBytes = c.type == GfxDataType::UnsignedByte ? 1 : 2;
748 break;
750 mesh.skinLayout.weights = at;
751 mesh.skinLayout.weightKind = c.type == GfxDataType::Float ? 2 : c.type == GfxDataType::UnsignedShort ? 1 : 0;
752 break;
753 default: break;
754 }
755 }
756 }
757 mesh.clusters.reset();
758 mesh.skinChunks.clear();
759 mesh.skinChunkBones.clear();
760 mesh.revision = nextRevision();
761 meshes_revision_ = mesh.revision;
762
763 // The shapes, last: geometry that draws is worth having even when the deltas
764 // behind it are refused, and the refusal leaves a mesh in its authored shape
765 // rather than no mesh at all.
766 const esengine::TextureHandle previousMorph = mesh.morphTexture;
768 mesh.morphTargetCount = 0;
769 mesh.morphHasNormals = false;
770 if (morph.targetCount > 0 && !morph.deltas.empty()) {
771 mesh.morphTexture = createMorphTexture(content, morph, mesh.vertexCount);
773 mesh.morphTargetCount = morph.targetCount;
774 mesh.morphHasNormals = morph.hasNormals;
775 }
776 }
777 if (previousMorph != esengine::TextureHandle::Invalid) device_->deleteTexture(previousMorph);
778 return true;
779}
780
789esengine::TextureHandle ResourceManager::createMorphTexture(GfxContent content, const MeshMorphSource& morph,
790 u32 vertexCount) {
791 if (!device_ || vertexCount == 0) return esengine::TextureHandle::Invalid;
792 const u32 perVertex = morph.hasNormals ? 2u : 1u;
793 const u32 components = morph.hasNormals ? 6u : 3u;
794 const u64 texels = static_cast<u64>(morph.targetCount) * vertexCount * perVertex;
795 if (morph.deltas.size() < static_cast<u64>(morph.targetCount) * vertexCount * components) {
796 ES_LOG_WARN("mesh morph: {} deltas describe fewer than {} targets over {} vertices;"
797 " drawing the authored shape",
798 morph.deltas.size(), morph.targetCount, vertexCount);
800 }
801 if (texels > MORPH_MAX_TEXELS) {
802 ES_LOG_WARN("mesh morph: {} targets over {} vertices needs {} texels and the largest"
803 " texture here holds {}; drawing the authored shape",
804 morph.targetCount, vertexCount, texels, MORPH_MAX_TEXELS);
806 }
807
808 const u32 height = static_cast<u32>((texels + MORPH_TEXTURE_WIDTH - 1) / MORPH_TEXTURE_WIDTH);
809 std::vector<u16> pixels(static_cast<usize>(MORPH_TEXTURE_WIDTH) * height * 4, 0);
810 for (u32 t = 0; t < morph.targetCount; ++t) {
811 for (u32 v = 0; v < vertexCount; ++v) {
812 const usize src = (static_cast<usize>(t) * vertexCount + v) * components;
813 const usize dst = (static_cast<usize>(t) * vertexCount + v) * perVertex * 4;
814 for (u32 c = 0; c < 3; ++c) pixels[dst + c] = packHalf(morph.deltas[src + c]);
815 if (!morph.hasNormals) continue;
816 for (u32 c = 0; c < 3; ++c) pixels[dst + 4 + c] = packHalf(morph.deltas[src + 3 + c]);
817 }
818 }
819
820 TextureDesc desc;
821 desc.width = MORPH_TEXTURE_WIDTH;
822 desc.height = height;
823 desc.format = GfxPixelFormat::RGBA16F;
824 // Fetched by texel index, never filtered: a value between two deltas belongs
825 // to no vertex, and asking for one is how a half-texel offset gets invented.
826 desc.minFilter = TextureFilter::Nearest;
827 desc.magFilter = TextureFilter::Nearest;
828 desc.wrapS = TextureWrap::ClampToEdge;
829 desc.wrapT = TextureWrap::ClampToEdge;
830 desc.mipmaps = false;
831 return device_->createTexture(desc, content, pixels.data());
832}
833
835 ConstSpan<GfxVertexAttribute> channels, u32 vertexStride,
836 const glm::vec3& localMin, const glm::vec3& localMax,
837 MeshRecovery recovery, ConstSpan<f32> inverseBind,
838 const MeshMorphSource& morph) {
839 auto mesh = makeUnique<Mesh>();
840 mesh->recovery = recovery;
841 if (!realizeMesh(*mesh, vertexBytes, indices, channels, vertexStride,
842 localMin, localMax, inverseBind, morph)) {
843 return MeshHandle();
844 }
845 return meshes_.add(std::move(mesh));
846}
847
849 ConstSpan<u32> indices,
850 ConstSpan<GfxVertexAttribute> channels, u32 vertexStride,
851 const glm::vec3& localMin, const glm::vec3& localMax,
852 ConstSpan<f32> inverseBind, const MeshMorphSource& morph) {
853 Mesh* mesh = meshes_.get(target);
854 if (!mesh) {
855 ES_LOG_ERROR("rematerializeMesh: handle {} names no live mesh", target.id());
856 return false;
857 }
858 // A producer's answer is given once, at mint. Recovery replaces geometry; it
859 // never gets to decide that geometry is recoverable.
861 ES_LOG_ERROR("rematerializeMesh: mesh {} is host-only and has no source to replay",
862 target.id());
863 return false;
864 }
865 if (!realizeMesh(*mesh, vertexBytes, indices, channels, vertexStride,
866 localMin, localMax, inverseBind, morph)) {
867 ES_LOG_ERROR("rematerializeMesh: mesh {} could not be rebuilt; it stays owed",
868 target.id());
869 return false;
870 }
871 return true;
872}
873
874bool ResourceManager::setMeshSkinChunks(MeshHandle target, std::vector<MeshSkinChunk> chunks, std::vector<u16> bones) {
875 Mesh* mesh = meshes_.get(target);
876 if (!mesh || !mesh->isSkinned()) {
877 ES_LOG_ERROR("setMeshSkinChunks: handle {} names no live skinned mesh", target.id());
878 return false;
879 }
880 u32 next = 0;
881 for (const MeshSkinChunk& chunk : chunks) {
882 const bool ok = chunk.firstIndex == next && chunk.indexCount > 0 && chunk.indexCount % 3 == 0
883 && chunk.boneCount > 0 && chunk.boneCount <= MESH_MAX_BONES
884 && static_cast<usize>(chunk.boneOffset) + chunk.boneCount <= bones.size();
885 if (!ok) {
886 ES_LOG_ERROR("setMeshSkinChunks: mesh {} was given a chunk at index {} of {} indices and {} bones; drawn as before",
887 target.id(), chunk.firstIndex, chunk.indexCount, chunk.boneCount);
888 return false;
889 }
890 next += chunk.indexCount;
891 }
892 if (next != mesh->indexCount) {
893 ES_LOG_ERROR("setMeshSkinChunks: mesh {}'s chunks cover {} of its {} indices; drawn as before", target.id(), next, mesh->indexCount);
894 return false;
895 }
896 for (const u16 bone : bones) {
897 if (bone >= mesh->inverseBind.size()) {
898 ES_LOG_ERROR("setMeshSkinChunks: mesh {} has {} joints and a chunk names joint {}; drawn as before",
899 target.id(), mesh->inverseBind.size(), bone);
900 return false;
901 }
902 }
903 mesh->skinChunks = std::move(chunks);
904 mesh->skinChunkBones = std::move(bones);
905 mesh->revision = nextRevision();
906 meshes_revision_ = mesh->revision;
907 return true;
908}
909
911 Mesh* mesh = meshes_.get(target);
912 if (!mesh) {
913 ES_LOG_ERROR("setMeshClusters: handle {} names no live mesh", target.id());
914 return false;
915 }
916 if (!lod::clusterHierarchyValid(hierarchy, mesh->vertexCount)) {
917 ES_LOG_ERROR("setMeshClusters: mesh {} was given a hierarchy that names what it does not have; it is drawn whole",
918 target.id());
919 return false;
920 }
921 mesh->clusters = std::make_shared<const lod::ClusterHierarchy>(std::move(hierarchy));
922 mesh->revision = nextRevision();
923 meshes_revision_ = mesh->revision;
924 return true;
925}
926
928 return meshes_.get(handle);
929}
930
932 return meshes_.get(handle);
933}
934
935std::vector<ResourceManager::MeshRealization> ResourceManager::meshRealizations() {
936 std::vector<MeshRealization> out;
937 const std::vector<GfxOwedContent> owed = device_ ? device_->owedContent() : std::vector<GfxOwedContent>{};
938 meshes_.forEachAlive([&](MeshHandle handle, Mesh& mesh) {
939 out.push_back({handle.id(), mesh.hasRealization() && !meshOwed(mesh, owed)});
940 });
941 return out;
942}
943
945 std::vector<MeshHandle> out;
946 if (!device_) return out;
947 const std::vector<GfxOwedContent> owed = device_->owedContent();
948 if (owed.empty()) return out;
949 meshes_.forEachAlive([&](MeshHandle handle, const Mesh& mesh) {
950 if (meshOwed(mesh, owed)) out.push_back(handle);
951 });
952 return out;
953}
954
955void ResourceManager::releaseMeshGeometry(VertexBufferHandle vertices, IndexBufferHandle indices, VertexLayoutHandle layout,
956 u32 arenaPage, u32 arenaFirstVertex, u32 vertexCount, u32 firstIndex,
957 u32 indexCount) {
958 if (arenaPage != 0) {
959 // The page's buffers and layout are the page's: the mesh gives back its ranges, and the last one out deletes the page.
960 meshArena_.free({arenaPage, arenaFirstVertex, vertexCount, firstIndex, indexCount});
961 return;
962 }
963 // The RHI creates a distinct layout for each realization, owned by this mesh.
964 if (device_) device_->deleteVertexLayout(layout);
965 releaseVertexBuffer(vertices);
966 releaseIndexBuffer(indices);
967}
968
970 Mesh* mesh = meshes_.get(handle);
971 if (!mesh) return;
972 meshes_revision_ = nextRevision();
973 releaseMeshGeometry(mesh->vertices, mesh->indices, mesh->layout, mesh->arenaPage, mesh->arenaFirstVertex,
974 mesh->vertexCount, mesh->firstIndex, mesh->indexCount);
976 // The delta texture IS the mesh's own — nothing shares it, unlike the layout.
977 if (mesh->morphTexture != esengine::TextureHandle::Invalid && device_) {
978 device_->deleteTexture(mesh->morphTexture);
979 }
980 meshes_.release(handle.id());
981}
982
983// =============================================================================
984// Environment Resources
985// =============================================================================
986
988 TextureHandle specular, f32 faceSize,
989 u32 mipCount, f32 maxRange, u32 columns) {
990 if (irradiance.size() != 27) {
991 ES_LOG_ERROR("createEnvironment: {} coefficients, want 27", irradiance.size());
992 return EnvironmentHandle();
993 }
994 auto environment = std::make_unique<Environment>();
995 for (usize i = 0; i < 9; ++i) {
996 environment->irradiance[i] = {irradiance[i * 3], irradiance[i * 3 + 1],
997 irradiance[i * 3 + 2]};
998 }
999 environment->specular = specular;
1000 environment->faceSize = faceSize;
1001 environment->mipCount = mipCount;
1002 environment->maxRange = maxRange;
1003 environment->columns = std::max(columns, 1u);
1004 return environments_.add(std::move(environment));
1005}
1006
1008 return environments_.get(handle);
1009}
1010
1012 return environments_.get(handle);
1013}
1014
1016 environments_.release(handle.id());
1017}
1018
1020 ConstSpan<f32> irradiance) {
1021 auto volume = std::make_unique<ProbeVolume>();
1022 volume->resolution = resolution;
1023 const usize want = static_cast<usize>(volume->probeCount()) * 27;
1024 if (want == 0 || irradiance.size() != want) {
1025 ES_LOG_ERROR("createProbeVolume: {}x{}x{} probes want {} coefficients, got {}",
1026 resolution.x, resolution.y, resolution.z, want, irradiance.size());
1027 return ProbeVolumeHandle();
1028 }
1029 volume->irradiance.resize(want / 3);
1030 for (usize i = 0; i < volume->irradiance.size(); ++i) {
1031 volume->irradiance[i] = {irradiance[i * 3], irradiance[i * 3 + 1], irradiance[i * 3 + 2]};
1032 }
1033 volume->revision = ProbeVolume::nextRevision();
1034 return probeVolumes_.add(std::move(volume));
1035}
1036
1038 ConstSpan<f32> irradiance) {
1039 auto volume = std::make_unique<ProbeVolume>();
1040 volume->resolution = resolution;
1041 std::vector<glm::ivec4> list(bricks.size() / 4);
1042 for (usize b = 0; b < list.size(); ++b) {
1043 list[b] = {bricks[b * 4], bricks[b * 4 + 1], bricks[b * 4 + 2], bricks[b * 4 + 3]};
1044 }
1045 if (bricks.size() % 4 != 0 || !volume->setBricks(std::move(list))) {
1046 ES_LOG_ERROR("createProbeVolumeBricks: {} brick ints do not tile a {}x{}x{} grid",
1047 bricks.size(), resolution.x, resolution.y, resolution.z);
1048 return ProbeVolumeHandle();
1049 }
1050 const usize want = static_cast<usize>(volume->probeCount()) * 27;
1051 if (irradiance.size() != want) {
1052 ES_LOG_ERROR("createProbeVolumeBricks: {} bricks want {} coefficients, got {}",
1053 volume->bricks.size(), want, irradiance.size());
1054 return ProbeVolumeHandle();
1055 }
1056 volume->irradiance.resize(want / 3);
1057 for (usize i = 0; i < volume->irradiance.size(); ++i) {
1058 volume->irradiance[i] = {irradiance[i * 3], irradiance[i * 3 + 1], irradiance[i * 3 + 2]};
1059 }
1060 volume->revision = ProbeVolume::nextRevision();
1061 return probeVolumes_.add(std::move(volume));
1062}
1063
1065 return probeVolumes_.get(handle);
1066}
1067
1069 return probeVolumes_.get(handle);
1070}
1071
1073 probeVolumes_.release(handle.id());
1074}
1075
1076// =============================================================================
1077// Index Buffer Resources
1078// =============================================================================
1079
1081 if (!device_) return {};
1082 auto buffer = IndexBuffer::create(*device_, content, indices.data(), static_cast<u32>(indices.size()));
1083 if (!buffer) {
1084 ES_LOG_ERROR("Failed to create index buffer (u32)");
1085 return IndexBufferHandle();
1086 }
1087 return indexBuffers_.add(std::move(buffer));
1088}
1089
1091 if (!device_) return {};
1092 auto buffer = IndexBuffer::create(*device_, content, indices.data(), static_cast<u32>(indices.size()));
1093 if (!buffer) {
1094 ES_LOG_ERROR("Failed to create index buffer (u16)");
1095 return IndexBufferHandle();
1096 }
1097 return indexBuffers_.add(std::move(buffer));
1098}
1099
1101 return indexBuffers_.get(handle);
1102}
1103
1105 return indexBuffers_.get(handle);
1106}
1107
1109 if (handle.isValid()) {
1110 indexBuffers_.release(handle.id());
1111 }
1112}
1113
1114// =============================================================================
1115// Bitmap Font Resources
1116// =============================================================================
1117
1119 auto cached = fonts_.findByPath(fntPath);
1120 if (cached.isValid()) {
1121 fonts_.addRef(cached);
1122 stats_.cacheHits++;
1123 return cached;
1124 }
1125
1126 // Web has no filesystem font-decode path; fonts come via createBitmapFont
1127 // with content + texture already supplied from JS.
1128 ES_LOG_ERROR("loadBitmapFont from file not supported on Web");
1129 stats_.cacheMisses++;
1130 return BitmapFontHandle();
1131}
1132
1134 TextureHandle texture,
1135 u32 texWidth, u32 texHeight) {
1136 auto font = makeUnique<text::BitmapFont>();
1137 if (!font->loadFromFntText(fntContent, texture, texWidth, texHeight)) {
1138 return BitmapFontHandle();
1139 }
1140 return fonts_.add(std::move(font));
1141}
1142
1144 u32 texWidth, u32 texHeight,
1145 const std::string& chars,
1146 u32 charWidth, u32 charHeight) {
1147 auto font = makeUnique<text::BitmapFont>();
1148 font->createLabelAtlas(texture, texWidth, texHeight, chars, charWidth, charHeight);
1149 return fonts_.add(std::move(font));
1150}
1151
1153 return fonts_.get(handle);
1154}
1155
1157 return fonts_.get(handle);
1158}
1159
1161 if (handle.isValid()) {
1162 fonts_.release(handle.id());
1163 }
1164}
1165
1167 return fonts_.getRefCount(handle);
1168}
1169
1170// =============================================================================
1171// Statistics
1172// =============================================================================
1173
1175 stats_.shaderCount = shaders_.size();
1176 stats_.textureCount = textures_.size();
1177 stats_.vertexBufferCount = vertexBuffers_.size();
1178 stats_.indexBufferCount = indexBuffers_.size();
1179 stats_.textureBytes = textures_.residentBytes();
1180 stats_.textureBudget = textures_.budget();
1181 stats_.textureEvictableCount = textures_.evictableCount();
1182 stats_.retainedBytes = device_ ? device_->retainedBytes() : 0;
1183 return stats_;
1184}
1185
1187 stats_.cacheHits = 0;
1188 stats_.cacheMisses = 0;
1189}
1190
1191} // namespace esengine::resource
GPU buffer abstractions for vertex and index data.
Abstract graphics device interface.
IEEE binary32 → binary16, for the data the GPU takes at half width.
Logging utilities for ESEngine.
#define ES_LOG_WARN(...)
Logs a warning message.
Definition Log.hpp:294
#define ES_LOG_ERROR(...)
Logs an error message.
Definition Log.hpp:296
#define ES_LOG_INFO(...)
Logs an info message.
Definition Log.hpp:292
The distinct edges of a triangle list, as the line list a wireframe draws.
How much texture a mesh's surface holds: UV units per world unit of its own surface.
Central resource management system.
What a resource's content is, as a number that changes whenever it does.
Parser for unified .esshader file format.
GPU shader program abstraction.
GPU texture abstraction for 2D images.
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...
static constexpr GfxContent transient()
static constexpr GfxContent retained()
static constexpr GfxContent sourced(u32 provider, u32 key)
Abstract graphics device interface.
Definition GfxDevice.hpp:75
void deleteVertexLayout(VertexLayoutHandle layout)
Deletes a vertex layout (no pipeline may reference it afterwards).
GPU buffer for index data.
Definition Buffer.hpp:337
BufferHandle handle() const
Gets the device buffer handle.
Definition Buffer.hpp:390
static Unique< IndexBuffer > create(GfxDevice &device, GfxContent content, std::span< const u32 > indices)
Creates an index buffer from a span of 32-bit indices.
Definition Buffer.hpp:353
Buffers, the layout that describes them, and the bounds culling reads.
Definition Mesh.hpp:85
glm::vec3 localMin
Definition Mesh.hpp:143
bool isSkinned() const
Definition Mesh.hpp:150
std::vector< MeshSkinChunk > skinChunks
Definition Mesh.hpp:178
VertexLayoutHandle layout
Definition Mesh.hpp:93
MeshRecovery recovery
Definition Mesh.hpp:123
std::vector< glm::mat4 > inverseBind
Definition Mesh.hpp:148
u32 arenaFirstVertex
Definition Mesh.hpp:105
BufferHandle vertexBuffer
Definition Mesh.hpp:91
bool hasTangents
Definition Mesh.hpp:136
bool morphHasNormals
Definition Mesh.hpp:157
resource::VertexBufferHandle vertices
Definition Mesh.hpp:87
resource::IndexBufferHandle edges
Definition Mesh.hpp:113
std::shared_ptr< const std::vector< u32 > > skinIndices
Definition Mesh.hpp:183
bool hasLightmapUV
Definition Mesh.hpp:132
glm::vec3 localMax
Definition Mesh.hpp:144
resource::IndexBufferHandle indices
Definition Mesh.hpp:88
std::shared_ptr< const lod::ClusterHierarchy > clusters
Definition Mesh.hpp:171
u32 indexCount
Definition Mesh.hpp:95
bool hasRealization() const
Definition Mesh.hpp:192
bool hasNormals
Definition Mesh.hpp:127
BufferHandle edgeIndexBuffer
Definition Mesh.hpp:114
u32 edgeIndexCount
Definition Mesh.hpp:115
MeshSkinLayout skinLayout
Definition Mesh.hpp:184
u32 vertexCount
Definition Mesh.hpp:160
std::shared_ptr< const std::vector< u8 > > skinSource
Definition Mesh.hpp:181
std::vector< u16 > skinChunkBones
Definition Mesh.hpp:185
u32 morphTargetCount
Definition Mesh.hpp:156
TextureHandle morphTexture
Definition Mesh.hpp:155
BufferHandle indexBuffer
Definition Mesh.hpp:92
Irradiance at a grid of points — an Environment sampled, not held.
static u64 nextRevision()
GPU shader program for rendering.
Definition Shader.hpp:86
static ShaderCompileOutcome createEx(GfxDevice &device, const std::string &vertexSrc, const std::string &fragmentSrc, std::initializer_list< AttribBinding > bindings={}, GfxShaderLanguage language=GfxShaderLanguage::GLSL_ES300, bool deferLink=false)
Creates a shader and exposes the driver log on failure.
Definition Shader.cpp:326
static Unique< Shader > create(GfxDevice &device, const std::string &vertexSrc, const std::string &fragmentSrc, GfxShaderLanguage language=GfxShaderLanguage::GLSL_ES300)
Creates a shader from source code strings.
Definition Shader.cpp:90
static Unique< Shader > createFromFile(GfxDevice &device, const std::string &vertexPath, const std::string &fragmentPath)
Creates a shader from file paths.
Definition Shader.cpp:112
static Unique< Shader > createWithBindings(GfxDevice &device, const std::string &vertexSrc, const std::string &fragmentSrc, std::initializer_list< AttribBinding > bindings, GfxShaderLanguage language=GfxShaderLanguage::GLSL_ES300, bool deferLink=false)
Creates a shader with explicit attribute bindings applied before linking.
Definition Shader.cpp:100
2D texture for GPU rendering
Definition Texture.hpp:116
static Unique< Texture > createCompressed(GfxDevice &device, GfxContent content, u32 width, u32 height, GfxCompressedFormat format, std::span< const u8 > data, u32 mipLevels=1)
Creates a block-compressed texture (KTX2 → ETC2/ASTC/BC), uploading the pre-compressed blocks in one ...
Definition Texture.cpp:152
static Unique< Texture > createFromExternalId(GfxDevice &device, GfxContent content, u32 glTextureId, u32 width, u32 height, TextureFormat format=TextureFormat::RGBA8)
Hands the device a texture the host made with its own API; the device owns it from here.
Definition Texture.cpp:179
static Unique< Texture > createArray(GfxDevice &device, GfxContent content, const TextureSpecification &spec, const void *pixels)
Creates a 2D texture array from spec.layers layers of spec.width x spec.height.
Definition Texture.cpp:92
static Unique< Texture > create(GfxDevice &device, GfxContent content, const TextureSpecification &spec)
Creates an empty texture from specification.
Definition Texture.cpp:83
u32 getId() const
Gets the texture handle's raw value, for command payloads and the WASM boundary.
Definition Texture.hpp:236
TextureHandle handle() const
Gets the device texture handle.
Definition Texture.hpp:233
static Unique< Texture > borrow(GfxDevice &device, TextureHandle texture, u32 width, u32 height)
Names a texture the device already holds for another owner (a render target's colour plane),...
Definition Texture.cpp:195
bool adoptContent(Texture &from)
Takes from's pixels behind this texture's handle; from is empty afterwards.
Definition Texture.cpp:207
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
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
void free(const Slot &slot)
void update()
Updates resource manager (processes hot reload, call once per frame).
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.
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.
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.
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.
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,...
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)
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...
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.
bool clusterHierarchyValid(const ClusterHierarchy &hierarchy, u32 vertexCount)
Whether hierarchy is one a cut can be assembled from: every run inside the indices,...
ShaderTargetLanguage
Target language for stage assembly (REARCH_WGSL dual emission).
ResourceContent
Who refills a resource's GPU content after a device loss.
@ Retained
The device keeps the bytes (a tile collection composed at load).
@ Mesh
Geometry the asset layer replays (MeshRecovery::SourceReplayable).
@ 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
f32 meshUvDensity(const u8 *vertexBytes, usize vertexByteCount, u32 vertexStride, u32 positionOffset, u32 uvOffset, const u32 *indices, usize indexCount)
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
static constexpr u32 MORPH_TEXTURE_WIDTH
Definition GfxEnums.hpp:145
constexpr bool meshShaderReads(MeshChannel c)
Whether the mesh shaders READ a channel, as opposed to the file carrying it.
Definition GfxEnums.hpp:177
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
@ ClampToEdge
Clamp to edge pixels.
Definition GfxEnums.hpp:64
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
u16 packHalf(f32 value)
IEEE binary32 to binary16.
Definition Half.hpp:25
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
@ SourceReplayable
Replayable from an asset the loader can load again.
Definition Mesh.hpp:29
GfxShaderLanguage
Shader source language a backend consumes.
Definition GfxEnums.hpp:654
static constexpr u32 MAX_VERTEX_ATTRIBUTES
Definition GfxEnums.hpp:217
@ Nearest
No interpolation (pixelated look).
Definition GfxEnums.hpp:58
TextureFormat
Texture pixel format.
Definition Texture.hpp:45
@ SRGB8A8
sRGB-encoded RGBA8: hardware-linearized on sample (32 bpp)
Definition Texture.hpp:49
@ RGBA8
4 channels, 8 bits each (32 bpp)
Definition Texture.hpp:48
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::vector< u32 > distinctMeshEdges(ConstSpan< u32 > indices)
Index pairs, one per distinct edge, in ascending order of (low, high) vertex.
Definition MeshEdges.hpp:22
DrawParamsRewrite rewriteLooseUniforms(const std::string &vertexSrc, const std::string &fragmentSrc)
Lifts loose non-sampler uniform declarations out of both stages into one shared std140 DrawParams blo...
std::uint16_t u16
Unsigned 16-bit integer.
Definition Types.hpp:43
MeshChannel
What a mesh vertex channel MEANS, and the attribute location it binds to.
Definition GfxEnums.hpp:158
static constexpr u32 MORPH_MAX_TEXELS
Definition GfxEnums.hpp:149
u64 nextRevision()
A revision no content has had before. Never 0, which reads as "none".
Definition Revision.hpp:24
float f32
32-bit floating point
Definition Types.hpp:59
static constexpr u32 MESH_MAX_BONES
Definition GfxEnums.hpp:138
Result of rewriteLooseUniforms; layout.empty() ⇒ sources unchanged.
A Sourced object that has storage again and is waiting for its contents.
The shapes handed to a realization: the deltas, and how to read them.
Definition Mesh.hpp:39
ConstSpan< f32 > deltas
targetCount * vertexCount * (hasNormals ? 6 : 3) floats.
Definition Mesh.hpp:41
One piece a skinned mesh is drawn in, when its bones are more than one draw can carry.
Definition Mesh.hpp:68
Texture creation parameters.
Definition Texture.hpp:74
u32 height
Texture height in pixels.
Definition Texture.hpp:78
TextureFormat format
Pixel format.
Definition Texture.hpp:80
u32 width
Texture width in pixels.
Definition Texture.hpp:76
u32 layers
Above 1, a 2D texture array of this many layers (see TextureDesc::layers).
Definition Texture.hpp:92
A mesh's clusters and the indices they name, every level together.
Statistics about resource usage.
usize shaderCount
Number of active shaders.
Metadata associated with a texture resource.