35bool meshOwed(
const Mesh& mesh,
const std::vector<GfxOwedContent>& owed) {
36 for (
const GfxOwedContent& entry : owed) {
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)))) {
69 ES_LOG_INFO(
"ResourceManager shutting down (shaders: {}, textures: {}, vbos: {}, ibos: {}, fonts: {})",
70 shaders_.size(), textures_.size(), vertexBuffers_.size(), indexBuffers_.size(), fonts_.size());
72 guidToTexture_.clear();
73 textureMetadata_.clear();
74 ++texture_metadata_revision_;
76 std::vector<ShaderHandle> retiredShaders;
77 shaders_.forEachAlive([&](
ShaderHandle handle,
const Shader&) { retiredShaders.push_back(handle); });
79 if (shaderRetiredCallback_)
for (
ShaderHandle handle : retiredShaders) shaderRetiredCallback_(shaderRetiredOwner_, handle);
81 std::vector<MeshHandle> retiredMeshes;
82 meshes_.forEachAlive([&](
MeshHandle handle,
const Mesh&) { retiredMeshes.push_back(handle); });
84 meshArena_.shutdown();
85 vertexBuffers_.clear();
86 indexBuffers_.clear();
116 return device_ && device_->skipPendingPrograms();
121 if (!device_)
return {};
134 shader->adoptDrawParams(std::move(rw.
layout));
135 return shaders_.add(std::move(shader));
140 ES_LOG_WARN(
"DrawParams rewrite failed to compile; retrying shader with loose uniforms");
146 auto outcome =
Shader::createEx(*device_, vertSrc, fragSrc, {}, language, deferLink);
147 if (!outcome.shader) {
149 outcome.log.empty() ?
"no reason given by the device" : outcome.log.c_str());
152 return shaders_.add(std::move(outcome.shader));
156 std::initializer_list<AttribBinding> bindings,
158 if (!device_)
return {};
161 ES_LOG_ERROR(
"Failed to create shader with bindings from source");
164 return shaders_.add(std::move(shader));
169 std::string cacheKey = vertPath +
":" + fragPath;
172 auto cached = shaders_.findByPath(cacheKey);
173 if (cached.isValid()) {
174 shaders_.addRef(cached);
180 if (!device_)
return {};
183 stats_.cacheMisses++;
187 stats_.cacheMisses++;
188 return shaders_.add(std::move(shader), cacheKey);
192 return shaders_.get(handle);
196 return shaders_.get(handle);
201 const bool final = shaders_.getRefCount(handle) == 1;
202 shaders_.release(handle.
id());
203 if (
final && shaderRetiredCallback_) shaderRetiredCallback_(shaderRetiredOwner_, handle);
208 return shaders_.getRefCount(handle);
224 if (!device_)
return {};
230 const usize bytes =
static_cast<usize>(texture->getWidth()) * texture->getHeight() * 4;
231 return textures_.add(std::move(texture),
"", bytes);
236 if (!device_)
return {};
238 std::span<const u8>(pixels.data(), pixels.size()), format, flipY);
243 const usize bytes =
static_cast<usize>(width) * height * 4;
244 return textures_.add(std::move(texture),
"", bytes);
249 if (!device_)
return {};
253 if (!rgba || spec.
layers < 1 || layerBytes == 0 || pixels.size() != bytes) {
254 ES_LOG_ERROR(
"createTextureArray: {} bytes for {} RGBA8 layers of {}x{} (expected {})",
263 return textures_.add(std::move(texture),
"", bytes);
269 if (!device_)
return {};
271 std::span<const u8>(data.data(), data.size()), mipLevels);
277 return textures_.add(std::move(texture),
"", data.size());
281 auto cached = textures_.findByPath(path);
282 if (cached.isValid()) {
283 textures_.addRef(cached);
290 ES_LOG_ERROR(
"loadTexture from file not supported on Web, use createTexture with pixel data");
291 stats_.cacheMisses++;
296 return textures_.get(handle);
300 return textures_.get(handle);
305 const bool lastRef = textures_.getRefCount(handle) == 1;
306 textures_.release(handle.
id());
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);
324 return textures_.getRefCount(handle);
329 if (!device_)
return {};
333 ES_LOG_ERROR(
"Failed to register external texture (GL ID: {})", glTextureId);
337 bytes =
static_cast<usize>(width) * height * 4;
339 return textures_.add(std::move(texture),
"", bytes);
343 if (!device_)
return {};
345 if (!wrapper)
return {};
347 return textures_.add(std::move(wrapper),
"", 0);
351 Texture* to = textures_.get(target);
352 Texture* from = textures_.get(source);
357 std::vector<OwedTexture> out;
358 if (!device_)
return out;
359 const std::vector<GfxOwedContent> owed = device_->owedContent();
360 if (owed.empty())
return out;
373 const Texture* texture = textures_.get(handle);
374 if (!device_ || !texture)
return;
377 device_->forgoContent(entry);
384 const Texture* texture = textures_.get(handle);
385 if (!device_ || !texture)
return;
388 device_->restoreContent(entry);
395 const Texture* texture = textures_.get(handle);
396 return device_ && texture ? device_->nativeTextureName(texture->
handle()) : 0;
400 if (handle.
isValid() && !path.empty()) {
401 textures_.setPath(handle, path);
406 return textures_.getPath(handle);
410 textures_.setBudget(bytes);
414 if (device_) device_->setRetainedBudget(bytes);
418 auto handle = textures_.findByPath(path);
419 if (!handle.isValid()) {
420 ++stats_.cacheMisses;
426 const Texture* texture = textures_.get(handle);
427 for (
const GfxOwedContent& entry : device_ ? device_->owedContent() : std::vector<GfxOwedContent>{}) {
429 ++stats_.cacheMisses;
437 textures_.addRef(handle);
442 return textures_.invalidatePath(path);
446 return textures_.trimEvictables();
450 auto it = guidToTexture_.find(guid);
451 if (it != guidToTexture_.end() && it->second.isValid()) {
452 textures_.addRef(it->second);
459 guidToTexture_[guid] = handle;
465 auto it = guidToTexture_.find(guid);
466 if (it != guidToTexture_.end()) {
473 auto it = guidToTexture_.find(guid);
474 if (it != guidToTexture_.end()) {
476 guidToTexture_.erase(it);
486 textureMetadata_[handle.
id()] = metadata;
487 ++texture_metadata_revision_;
492 if (!handle.
isValid())
return nullptr;
493 auto it = textureMetadata_.find(handle.
id());
494 if (it != textureMetadata_.end()) {
501 if (!handle.
isValid())
return false;
502 return textureMetadata_.find(handle.
id()) != textureMetadata_.end();
507 if (textureMetadata_.erase(handle.
id())) ++texture_metadata_revision_;
516 if (!device_)
return {};
522 return vertexBuffers_.add(std::move(buffer));
526 return vertexBuffers_.get(handle);
530 return vertexBuffers_.get(handle);
535 vertexBuffers_.release(handle.
id());
549 const glm::vec3& localMin,
const glm::vec3& localMax,
551 if (!device_ || vertexBytes.empty() || indices.empty() || channels.empty())
return false;
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);
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);
570 coloredChannels.assign(channels.begin(), channels.end());
571 GfxVertexAttribute color;
573 color.components = 4;
575 color.normalized =
true;
576 color.offset = colorOffset;
577 coloredChannels.push_back(color);
580 vertexStride = stride;
586 VertexLayoutDesc layout;
591 for (
const GfxVertexAttribute& c : channels) {
594 ES_LOG_ERROR(
"realizeMesh: {} bound channels exceeds the layout budget", bound + 1);
597 layout.attributes[bound] = c;
598 layout.attributes[bound].bufferSlot = 0;
601 bool hasNormals =
false;
602 bool skinned =
false;
603 bool lightmapUV =
false;
604 bool tangentChannel =
false;
605 for (
const GfxVertexAttribute& c : channels) {
611 skinned = skinned && !inverseBind.empty();
615 const bool lightmapped = lightmapUV && !skinned;
617 layout.strides[0] = vertexStride;
618 layout.attributeCount = bound;
634 : GfxContent::retained();
641 MeshArena::Slot slot;
642 MeshArena::Binding shared;
646 && meshArena_.place(layout, content, vertexBytes, vertexStride, indices, slot, shared);
658 layoutHandle = device_->createVertexLayout(layout);
666 device_->deleteVertexLayout(layoutHandle);
669 vertexBufferId = vb->handle();
670 indexBufferId = ib->handle();
680 if (placed)
for (
u32& index : lines) index += slot.firstVertex;
684 edgeCount =
static_cast<u32>(lines.size());
691 releaseMeshGeometry(previousVertices, previousIndices, previousLayout, previousPage, previousFirstVertex,
692 previousVertexCount, previousFirstIndex, previousIndexCount);
695 mesh.
edges = edgeHandle;
702 mesh.
layout = layoutHandle;
704 mesh.
firstIndex = placed ? slot.firstIndex : 0;
714 const GfxVertexAttribute* position =
nullptr;
715 const GfxVertexAttribute* uv =
nullptr;
716 for (
const GfxVertexAttribute& c : channels) {
721 ?
meshUvDensity(vertexBytes.data(), vertexBytes.size(), vertexStride, position->offset, uv->offset, indices.data(), indices.size())
726 const usize joints = inverseBind.size() / 16;
728 std::memcpy(mesh.
inverseBind.data(), inverseBind.data(), joints *
sizeof(glm::mat4));
730 mesh.
vertexCount = vertexStride > 0 ?
static_cast<u32>(vertexBytes.size()) / vertexStride : 0;
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());
739 for (
const GfxVertexAttribute& c : channels) {
740 const auto at =
static_cast<i32>(c.offset);
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);
802 ES_LOG_WARN(
"mesh morph: {} targets over {} vertices needs {} texels and the largest"
803 " texture here holds {}; drawing the authored shape",
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]);
822 desc.height = height;
830 desc.mipmaps =
false;
831 return device_->createTexture(desc, content, pixels.data());
836 const glm::vec3& localMin,
const glm::vec3& localMax,
841 if (!realizeMesh(*mesh, vertexBytes, indices, channels, vertexStride,
842 localMin, localMax, inverseBind, morph)) {
845 return meshes_.add(std::move(mesh));
851 const glm::vec3& localMin,
const glm::vec3& localMax,
853 Mesh* mesh = meshes_.get(target);
855 ES_LOG_ERROR(
"rematerializeMesh: handle {} names no live mesh", target.
id());
861 ES_LOG_ERROR(
"rematerializeMesh: mesh {} is host-only and has no source to replay",
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",
875 Mesh* mesh = meshes_.get(target);
877 ES_LOG_ERROR(
"setMeshSkinChunks: handle {} names no live skinned mesh", target.
id());
882 const bool ok = chunk.firstIndex == next && chunk.indexCount > 0 && chunk.indexCount % 3 == 0
884 &&
static_cast<usize>(chunk.boneOffset) + chunk.boneCount <= bones.size();
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);
890 next += chunk.indexCount;
893 ES_LOG_ERROR(
"setMeshSkinChunks: mesh {}'s chunks cover {} of its {} indices; drawn as before", target.
id(), next, mesh->
indexCount);
896 for (
const u16 bone : bones) {
898 ES_LOG_ERROR(
"setMeshSkinChunks: mesh {} has {} joints and a chunk names joint {}; drawn as before",
911 Mesh* mesh = meshes_.get(target);
913 ES_LOG_ERROR(
"setMeshClusters: handle {} names no live mesh", target.
id());
917 ES_LOG_ERROR(
"setMeshClusters: mesh {} was given a hierarchy that names what it does not have; it is drawn whole",
921 mesh->
clusters = std::make_shared<const lod::ClusterHierarchy>(std::move(hierarchy));
928 return meshes_.get(handle);
932 return meshes_.get(handle);
936 std::vector<MeshRealization> out;
937 const std::vector<GfxOwedContent> owed = device_ ? device_->owedContent() : std::vector<GfxOwedContent>{};
939 out.push_back({handle.
id(), mesh.
hasRealization() && !meshOwed(mesh, owed)});
945 std::vector<MeshHandle> out;
946 if (!device_)
return out;
947 const std::vector<GfxOwedContent> owed = device_->owedContent();
948 if (owed.empty())
return out;
950 if (meshOwed(mesh, owed)) out.push_back(handle);
956 u32 arenaPage,
u32 arenaFirstVertex,
u32 vertexCount,
u32 firstIndex,
958 if (arenaPage != 0) {
960 meshArena_.
free({arenaPage, arenaFirstVertex, vertexCount, firstIndex, indexCount});
970 Mesh* mesh = meshes_.get(handle);
980 meshes_.release(handle.
id());
989 u32 mipCount,
f32 maxRange,
u32 columns) {
990 if (irradiance.size() != 27) {
991 ES_LOG_ERROR(
"createEnvironment: {} coefficients, want 27", irradiance.size());
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]};
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));
1008 return environments_.get(handle);
1012 return environments_.get(handle);
1016 environments_.release(handle.
id());
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());
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]};
1034 return probeVolumes_.add(std::move(volume));
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]};
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);
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());
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]};
1061 return probeVolumes_.add(std::move(volume));
1065 return probeVolumes_.get(handle);
1069 return probeVolumes_.get(handle);
1073 probeVolumes_.release(handle.
id());
1081 if (!device_)
return {};
1087 return indexBuffers_.add(std::move(buffer));
1091 if (!device_)
return {};
1097 return indexBuffers_.add(std::move(buffer));
1101 return indexBuffers_.get(handle);
1105 return indexBuffers_.get(handle);
1110 indexBuffers_.release(handle.
id());
1119 auto cached = fonts_.findByPath(fntPath);
1120 if (cached.isValid()) {
1121 fonts_.addRef(cached);
1128 ES_LOG_ERROR(
"loadBitmapFont from file not supported on Web");
1129 stats_.cacheMisses++;
1135 u32 texWidth,
u32 texHeight) {
1137 if (!font->loadFromFntText(fntContent, texture, texWidth, texHeight)) {
1140 return fonts_.add(std::move(font));
1144 u32 texWidth,
u32 texHeight,
1145 const std::string& chars,
1146 u32 charWidth,
u32 charHeight) {
1148 font->createLabelAtlas(texture, texWidth, texHeight, chars, charWidth, charHeight);
1149 return fonts_.add(std::move(font));
1153 return fonts_.get(handle);
1157 return fonts_.get(handle);
1162 fonts_.release(handle.
id());
1167 return fonts_.getRefCount(handle);
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;
1187 stats_.cacheHits = 0;
1188 stats_.cacheMisses = 0;
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.
#define ES_LOG_ERROR(...)
Logs an error message.
#define ES_LOG_INFO(...)
Logs an info message.
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.
void deleteVertexLayout(VertexLayoutHandle layout)
Deletes a vertex layout (no pipeline may reference it afterwards).
GPU buffer for index data.
BufferHandle handle() const
Gets the device buffer handle.
static Unique< IndexBuffer > create(GfxDevice &device, GfxContent content, std::span< const u32 > indices)
Creates an index buffer from a span of 32-bit indices.
Buffers, the layout that describes them, and the bounds culling reads.
std::vector< MeshSkinChunk > skinChunks
VertexLayoutHandle layout
std::vector< glm::mat4 > inverseBind
BufferHandle vertexBuffer
resource::VertexBufferHandle vertices
resource::IndexBufferHandle edges
std::shared_ptr< const std::vector< u32 > > skinIndices
resource::IndexBufferHandle indices
std::shared_ptr< const lod::ClusterHierarchy > clusters
bool hasRealization() const
BufferHandle edgeIndexBuffer
MeshSkinLayout skinLayout
std::shared_ptr< const std::vector< u8 > > skinSource
std::vector< u16 > skinChunkBones
TextureHandle morphTexture
Irradiance at a grid of points — an Environment sampled, not held.
static u64 nextRevision()
GPU shader program for rendering.
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.
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.
static Unique< Shader > createFromFile(GfxDevice &device, const std::string &vertexPath, const std::string &fragmentPath)
Creates a shader from file paths.
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.
2D texture for GPU rendering
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 ...
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.
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.
static Unique< Texture > create(GfxDevice &device, GfxContent content, const TextureSpecification &spec)
Creates an empty texture from specification.
u32 getId() const
Gets the texture handle's raw value, for command payloads and the WASM boundary.
TextureHandle handle() const
Gets the device texture handle.
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),...
bool adoptContent(Texture &from)
Takes from's pixels behind this texture's handle; from is empty afterwards.
GPU buffer for vertex data, static or dynamic; all GPU work goes through the device.
static Unique< VertexBuffer > create(GfxDevice &device, GfxContent content, std::span< const T > data)
Creates a static buffer from a span.
bool isValid() const
Checks if the handle references a valid resource.
IdType id() const
Gets the packed identifier (index + generation).
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.
GfxDevice * device() const
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.
Handle< esengine::text::BitmapFont > BitmapFontHandle
Handle to a bitmap font resource.
Handle< esengine::Environment > EnvironmentHandle
Handle to a baked environment (irradiance + prefiltered reflection).
Handle< esengine::IndexBuffer > IndexBufferHandle
Handle to an index buffer resource.
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.
Handle< esengine::Texture > TextureHandle
Handle to a texture resource.
Handle< esengine::ProbeVolume > ProbeVolumeHandle
Handle to a grid of baked irradiance.
Handle< esengine::Mesh > MeshHandle
Handle to GPU-resident geometry.
static constexpr u32 MORPH_TEXTURE_WIDTH
constexpr bool meshShaderReads(MeshChannel c)
Whether the mesh shaders READ a channel, as opposed to the file carrying it.
constexpr Unique< T > makeUnique(Args &&... args)
Creates a Unique pointer with the given arguments.
std::int32_t i32
Signed 32-bit integer.
@ ClampToEdge
Clamp to edge pixels.
std::uint64_t u64
Unsigned 64-bit integer.
u16 packHalf(f32 value)
IEEE binary32 to binary16.
std::size_t usize
Size type for indexing and sizes.
MeshRecovery
How a mesh's geometry comes back after a device generation ends.
@ SourceReplayable
Replayable from an asset the loader can load again.
GfxShaderLanguage
Shader source language a backend consumes.
static constexpr u32 MAX_VERTEX_ATTRIBUTES
@ Nearest
No interpolation (pixelated look).
TextureFormat
Texture pixel format.
@ SRGB8A8
sRGB-encoded RGBA8: hardware-linearized on sample (32 bpp)
@ RGBA8
4 channels, 8 bits each (32 bpp)
GfxCompressedFormat
GPU-compressed texture internal formats for createCompressedTexture.
std::span< const T > ConstSpan
std::uint32_t u32
Unsigned 32-bit integer.
std::vector< u32 > distinctMeshEdges(ConstSpan< u32 > indices)
Index pairs, one per distinct edge, in ascending order of (low, high) vertex.
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.
MeshChannel
What a mesh vertex channel MEANS, and the attribute location it binds to.
static constexpr u32 MORPH_MAX_TEXELS
u64 nextRevision()
A revision no content has had before. Never 0, which reads as "none".
float f32
32-bit floating point
static constexpr u32 MESH_MAX_BONES
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.
ConstSpan< f32 > deltas
targetCount * vertexCount * (hasNormals ? 6 : 3) floats.
One piece a skinned mesh is drawn in, when its bones are more than one draw can carry.
Texture creation parameters.
u32 height
Texture height in pixels.
TextureFormat format
Pixel format.
u32 width
Texture width in pixels.
u32 layers
Above 1, a 2D texture array of this many layers (see TextureDesc::layers).
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.