Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
SkinCache.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
7#include "SkinCache.hpp"
8
9#include "../../core/Log.hpp"
11#include "../rhi/GfxDevice.hpp"
12
13#include <algorithm>
14#include <cstring>
15
16namespace esengine {
17
18namespace {
19
23constexpr const char* kSkinKernel = R"WGSL(
24struct Params {
25 count : u32, stride : u32, position : i32, normal : i32,
26 tangent : i32, joints : i32, jointBytes : u32, weights : i32,
27 weightKind : u32, chunked : u32, pad0 : u32, pad1 : u32,
28};
29@group(0) @binding(0) var<uniform> P : Params;
30@group(0) @binding(1) var<storage, read> src : array<u32>;
31@group(0) @binding(2) var<storage, read_write> dst : array<u32>;
32@group(0) @binding(3) var<storage, read> pose : array<mat4x4f>;
33@group(0) @binding(4) var<storage, read> base : array<u32>;
34@group(0) @binding(5) var<storage, read> bones : array<u32>;
35
36fn byteAt(b : u32) -> u32 { return (src[b >> 2u] >> ((b & 3u) * 8u)) & 0xffu; }
37fn halfAt(b : u32) -> u32 { return byteAt(b) | (byteAt(b + 1u) << 8u); }
38fn word(w : u32) -> f32 { return bitcast<f32>(src[w]); }
39
40fn jointOf(v : u32, k : u32) -> u32 {
41 let at = v * P.stride * 4u + u32(P.joints) + k * P.jointBytes;
42 var j = halfAt(at);
43 if (P.jointBytes == 1u) { j = byteAt(at); }
44 if (P.chunked != 0u) { j = bones[base[v] + j]; }
45 return j;
46}
47
48fn weightOf(v : u32, k : u32) -> f32 {
49 let at = v * P.stride * 4u + u32(P.weights);
50 if (P.weightKind == 2u) { return bitcast<f32>(src[(at >> 2u) + k]); }
51 if (P.weightKind == 1u) { return f32(halfAt(at + k * 2u)) / 65535.0; }
52 return f32(byteAt(at + k)) / 255.0;
53}
54
55fn put(w : u32, value : vec3f) {
56 dst[w] = bitcast<u32>(value.x);
57 dst[w + 1u] = bitcast<u32>(value.y);
58 dst[w + 2u] = bitcast<u32>(value.z);
59}
60
61@compute @workgroup_size(64)
62fn main(@builtin(global_invocation_id) id : vec3u) {
63 let v = id.x;
64 if (v >= P.count) { return; }
65 var m = mat4x4f(vec4f(0.0), vec4f(0.0), vec4f(0.0), vec4f(0.0));
66 for (var k = 0u; k < 4u; k = k + 1u) {
67 let w = weightOf(v, k);
68 if (w > 0.0) { m = m + pose[jointOf(v, k)] * w; }
69 }
70 let row = v * P.stride;
71 let r = mat3x3f(m[0].xyz, m[1].xyz, m[2].xyz);
72 if (P.position >= 0) {
73 let o = row + u32(P.position) / 4u;
74 put(o, (m * vec4f(word(o), word(o + 1u), word(o + 2u), 1.0)).xyz);
75 }
76 if (P.normal >= 0) {
77 let o = row + u32(P.normal) / 4u;
78 put(o, r * vec3f(word(o), word(o + 1u), word(o + 2u)));
79 }
80 if (P.tangent >= 0) {
81 let o = row + u32(P.tangent) / 4u;
82 put(o, r * vec3f(word(o), word(o + 1u), word(o + 2u)));
83 }
84}
85)WGSL";
86
87constexpr u32 kWorkgroup = 64;
89constexpr u64 kIdleFrames = 120;
90constexpr u32 kParamsBytes = 48;
91
92} // namespace
93
94SkinCache::SkinCache(GfxDevice& device) : device_(device) {}
95
97 for (auto& [id, entry] : entries_) release(entry);
98 if (kernel_ != ComputeHandle::Invalid) device_.deleteCompute(kernel_);
99}
100
101bool SkinCache::active() const {
102 return settings_.enabled && device_.supportsCompute() && !kernelFailed_;
103}
104
106 if (!active() || usage == SkinCacheUsage::Disabled) return false;
107 return usage == SkinCacheUsage::Enabled || settings_.behavior == SkinCacheBehavior::Inclusive;
108}
109
111 if (frame == frame_) return;
112 frame_ = frame;
113 scheduled_ = 0;
114 refused_ = 0;
115 drawn_ = 0;
116 for (auto it = entries_.begin(); it != entries_.end();) {
117 it->second.scheduled = false;
118 if (it->second.lastFrame + kIdleFrames < frame) {
119 release(it->second);
120 it = entries_.erase(it);
121 } else {
122 ++it;
123 }
124 }
125 // A budget turned down gives back what is over it, the longest unasked first.
126 const u64 budget = static_cast<u64>(std::max(settings_.maxMegabytes, 0.0f) * 1024.0f * 1024.0f);
127 while (bytes_ > budget && !entries_.empty()) {
128 auto oldest = std::min_element(entries_.begin(), entries_.end(),
129 [](const auto& a, const auto& b) { return a.second.lastFrame < b.second.lastFrame; });
130 release(oldest->second);
131 entries_.erase(oldest);
132 }
133}
134
135void SkinCache::release(Entry& entry) {
136 for (BufferHandle* b : {&entry.sourceBuffer, &entry.output, &entry.boneBase, &entry.bones, &entry.pose, &entry.params}) {
137 if (*b != BufferHandle::Invalid) device_.deleteBuffer(*b);
139 }
140 bytes_ -= std::min(bytes_, entry.bytes);
141 entry.bytes = 0;
142}
143
144bool SkinCache::build(Entry& entry, const Mesh& mesh) {
145 const MeshSkinLayout& layout = mesh.skinLayout;
146 const auto& bytes = *mesh.skinSource;
147 const u32 size = static_cast<u32>(bytes.size());
148 entry.vertexCount = mesh.vertexCount;
149 entry.source = mesh.skinSource;
150 entry.meshRevision = mesh.revision;
151 // The copy starts as the vertices themselves: what the kernel does not write (uv, colour, the bake's uv) stays theirs.
152 entry.sourceBuffer = device_.createBuffer({GfxBufferUsage::Storage, size, false}, GfxContent::transient(), bytes.data());
153 entry.output = device_.createBuffer({GfxBufferUsage::Storage, size, false}, GfxContent::transient(), bytes.data());
154
155 // Each vertex's chunk's first bone, where the mesh is chunked: a chunk is a run of indices, and each vertex is in one.
156 std::vector<u32> base(std::max<u32>(mesh.vertexCount, 1u), 0u);
157 std::vector<u32> bones(1, 0u);
158 if (mesh.isChunked() && mesh.skinIndices) {
159 const auto& indices = *mesh.skinIndices;
160 for (const MeshSkinChunk& chunk : mesh.skinChunks) {
161 for (u32 i = chunk.firstIndex; i < chunk.firstIndex + chunk.indexCount && i < indices.size(); ++i) {
162 if (indices[i] < base.size()) base[indices[i]] = chunk.boneOffset;
163 }
164 }
165 bones.assign(mesh.skinChunkBones.begin(), mesh.skinChunkBones.end());
166 }
167 entry.boneBase = device_.createBuffer({GfxBufferUsage::Storage, static_cast<u32>(base.size() * 4), false},
168 GfxContent::transient(), base.data());
169 entry.bones = device_.createBuffer({GfxBufferUsage::Storage, static_cast<u32>(bones.size() * 4), false},
170 GfxContent::transient(), bones.data());
171 const i32 params[12] = {
172 static_cast<i32>(mesh.vertexCount), static_cast<i32>(layout.stride / 4), layout.position, layout.normal,
173 layout.tangent, layout.joints, static_cast<i32>(layout.jointBytes), layout.weights,
174 static_cast<i32>(layout.weightKind), mesh.isChunked() ? 1 : 0, 0, 0,
175 };
176 entry.params = device_.createBuffer({GfxBufferUsage::Uniform, kParamsBytes, false}, GfxContent::transient(), params);
177 entry.bytes = static_cast<u64>(size) * 2 + base.size() * 4 + bones.size() * 4 + kParamsBytes;
178 bytes_ += entry.bytes;
179 return entry.sourceBuffer != BufferHandle::Invalid && entry.output != BufferHandle::Invalid
180 && entry.boneBase != BufferHandle::Invalid && entry.bones != BufferHandle::Invalid && entry.params != BufferHandle::Invalid;
181}
182
183BufferHandle SkinCache::schedule(Entity entity, const Mesh& mesh, const glm::mat4* pose, u32 joints) {
184 if (!active() || joints == 0 || !mesh.skinSource || mesh.skinLayout.position < 0 || mesh.skinLayout.joints < 0
185 || mesh.skinLayout.weights < 0 || mesh.skinLayout.stride % 4 != 0 || mesh.isMorphable()) {
187 }
188 auto found = entries_.find(entity.raw);
189 if (found != entries_.end() && found->second.meshRevision != mesh.revision) {
190 // The mesh was realized again (a reload, a device loss): its copy is built anew.
191 release(found->second);
192 entries_.erase(found);
193 found = entries_.end();
194 }
195 if (found == entries_.end()) {
196 const u64 budget = static_cast<u64>(std::max(settings_.maxMegabytes, 0.0f) * 1024.0f * 1024.0f);
197 const u64 needs = static_cast<u64>(mesh.skinSource->size()) * 2 + static_cast<u64>(mesh.vertexCount) * 4;
198 if (bytes_ + needs > budget) {
199 ++refused_;
201 }
202 Entry entry;
203 if (!build(entry, mesh)) {
204 release(entry);
206 }
207 found = entries_.emplace(entity.raw, std::move(entry)).first;
208 }
209 Entry& entry = found->second;
210 if (entry.scheduled) return entry.output;
211 entry.pendingPose.assign(pose, pose + joints);
212 entry.scheduled = true;
213 entry.lastFrame = frame_;
214 ++scheduled_;
215 return entry.output;
216}
217
219 const auto found = entries_.find(entity.raw);
220 return found != entries_.end() && found->second.scheduled ? found->second.output : BufferHandle::Invalid;
221}
222
224 if (scheduled_ == 0) return;
225 if (kernel_ == ComputeHandle::Invalid && !kernelFailed_) {
226 std::string log;
227 kernel_ = device_.createCompute(GfxComputeSource{GfxShaderLanguage::WGSL, kSkinKernel, "main"}, &log);
228 if (kernel_ == ComputeHandle::Invalid) {
229 kernelFailed_ = true;
230 ES_LOG_ERROR("SkinCache: the skinning kernel did not compile, skins are posed in the vertex stage: {}", log);
231 return;
232 }
233 }
234 for (auto& [id, entry] : entries_) {
235 if (!entry.scheduled || entry.pendingPose.empty()) continue;
236 const u32 joints = static_cast<u32>(entry.pendingPose.size());
237 if (joints > entry.poseCapacity || entry.pose == BufferHandle::Invalid) {
238 if (entry.pose != BufferHandle::Invalid) {
239 device_.deleteBuffer(entry.pose);
240 entry.bytes -= static_cast<u64>(entry.poseCapacity) * sizeof(glm::mat4);
241 bytes_ -= static_cast<u64>(entry.poseCapacity) * sizeof(glm::mat4);
242 }
243 entry.poseCapacity = joints;
244 entry.pose = device_.createBuffer({GfxBufferUsage::Storage, joints * static_cast<u32>(sizeof(glm::mat4)), true},
245 GfxContent::transient(), nullptr);
246 entry.bytes += static_cast<u64>(joints) * sizeof(glm::mat4);
247 bytes_ += static_cast<u64>(joints) * sizeof(glm::mat4);
248 if (entry.pose == BufferHandle::Invalid) continue;
249 }
250 device_.updateBuffer(entry.pose, 0, entry.pendingPose.data(), joints * static_cast<u32>(sizeof(glm::mat4)));
251 const GfxComputeBinding bindings[6] = {
252 GfxComputeBinding::uniform(0, entry.params),
253 GfxComputeBinding::storageRead(1, entry.sourceBuffer),
254 GfxComputeBinding::storage(2, entry.output),
255 GfxComputeBinding::storageRead(3, entry.pose),
256 GfxComputeBinding::storageRead(4, entry.boneBase),
257 GfxComputeBinding::storageRead(5, entry.bones),
258 };
259 device_.dispatchCompute(kernel_, bindings, 6, (entry.vertexCount + kWorkgroup - 1) / kWorkgroup);
260 }
261}
262
263} // namespace esengine
Abstract graphics device interface.
Logging utilities for ESEngine.
#define ES_LOG_ERROR(...)
Logs an error message.
Definition Log.hpp:296
Geometry that lives on the GPU rather than in a frame.
Skinned meshes posed once a frame by a compute shader, into vertices every pass then draws as they ar...
static constexpr GfxContent transient()
Abstract graphics device interface.
Definition GfxDevice.hpp:75
void deleteBuffer(BufferHandle buffer)
Deletes a buffer.
Buffers, the layout that describes them, and the bounds culling reads.
Definition Mesh.hpp:85
bool isMorphable() const
Definition Mesh.hpp:162
MeshSkinLayout skinLayout
Definition Mesh.hpp:184
u32 vertexCount
Definition Mesh.hpp:160
std::shared_ptr< const std::vector< u8 > > skinSource
Definition Mesh.hpp:181
bool active() const
bool wants(SkinCacheUsage usage) const
BufferHandle bufferFor(Entity entity) const
void beginFrame(u64 frame)
SkinCache(GfxDevice &device)
Definition SkinCache.cpp:94
BufferHandle schedule(Entity entity, const Mesh &mesh, const glm::mat4 *pose, u32 joints)
Schedules entity's skin for this frame, posed by pose (one matrix a joint: joint world times inverse ...
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
@ Storage
Read and written by compute shaders (var<storage, read_write>), and readable back....
Definition GfxEnums.hpp:77
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
SkinCacheUsage
A mesh's own word on the cache (MeshSkin::skinCache).
Definition SkinCache.hpp:43
Entity identifier with packed index + generation.
Definition Types.hpp:135
One resource a compute dispatch binds, at @group(0) @binding(binding).
Definition GfxEnums.hpp:689
static GfxComputeBinding uniform(u32 binding, BufferHandle buffer, u32 offset=0, u32 size=0)
Definition GfxEnums.hpp:701
static GfxComputeBinding storageRead(u32 binding, BufferHandle buffer, u32 offset=0, u32 size=0)
Definition GfxEnums.hpp:704
static GfxComputeBinding storage(u32 binding, BufferHandle buffer, u32 offset=0, u32 size=0)
Definition GfxEnums.hpp:707
A compute program's source. Compute is WGSL only: GLSL ES 3.00 has no compute stage.
Definition GfxEnums.hpp:673