Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
TransientBufferPool.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
4#include "../../core/Log.hpp"
6
7#include <cstring>
8#include <algorithm>
9
10namespace esengine {
11
15
16void TransientBufferPool::init(u32 initialVertexBytes, u32 initialIndexCount) {
17 if (initialized_) return;
18 initial_vertex_bytes_ = initialVertexBytes;
19 initial_index_count_ = initialIndexCount;
20
24 setupStream(layout);
25 }
26
27 initialized_ = true;
28}
29
31 if (!initialized_) return;
32
33 for (auto& s : streams_) {
34 if (s.layout != VertexLayoutHandle::Invalid) {
35 device_.deleteVertexLayout(s.layout);
37 }
38 if (s.vbo != BufferHandle::Invalid) { device_.deleteBuffer(s.vbo); s.vbo = BufferHandle::Invalid; }
39 if (s.ebo != BufferHandle::Invalid) { device_.deleteBuffer(s.ebo); s.ebo = BufferHandle::Invalid; }
40 if (s.quad_vbo != BufferHandle::Invalid) { device_.deleteBuffer(s.quad_vbo); s.quad_vbo = BufferHandle::Invalid; }
41 if (s.texture != TextureHandle::Invalid) {
42 device_.deleteTexture(s.texture);
43 s.texture = TextureHandle::Invalid;
44 }
45 s.texture_rows = 0;
46 s.vertex_staging.clear();
47 s.index_staging.clear();
48 s.vertex_write_pos = 0;
49 s.index_write_pos = 0;
50 s.vbo_capacity = 0;
51 s.ebo_capacity = 0;
52 }
53 initialized_ = false;
54}
55
57 for (auto& s : streams_) {
58 s.vertex_write_pos = 0;
59 s.index_write_pos = 0;
60 }
61}
62
63TransientBufferPool::Stream& TransientBufferPool::stream(LayoutId layout) {
64 return streams_[static_cast<u32>(layout)];
65}
66
67const TransientBufferPool::Stream& TransientBufferPool::stream(LayoutId layout) const {
68 return streams_[static_cast<u32>(layout)];
69}
70
78void TransientBufferPool::uploadInstanceRows(Stream& s, u32& grows, u32& writes) {
79 const u32 rowBytes = instanceRowBytes();
80 const u32 rows = (s.vertex_write_pos + rowBytes - 1) / rowBytes;
81 if (static_cast<u64>(s.vertex_staging.size()) < static_cast<u64>(rows) * rowBytes) {
82 s.vertex_staging.resize(static_cast<usize>(rows) * rowBytes);
83 }
84 if (rows > s.texture_rows) {
85 // Doubling, the way the staging grows: a workload creeping upward
86 // otherwise reallocates a texture every frame.
87 // The texture is created from the staging, so the staging is as tall as the texture, and neither is taller than a device guarantees.
89 const u32 want = std::min(std::max(rows, s.texture_rows * 2), std::max(rows, limit));
90 if (s.vertex_staging.size() < static_cast<usize>(want) * rowBytes) {
91 s.vertex_staging.resize(static_cast<usize>(want) * rowBytes);
92 }
93 if (s.texture != TextureHandle::Invalid) device_.deleteTexture(s.texture);
94 TextureDesc desc;
95 desc.width = MESH_INSTANCE_TEXTURE_WIDTH;
96 desc.height = want;
97 desc.format = GfxPixelFormat::RGBA32F;
98 // Fetched by index, never filtered: a value between two records belongs
99 // to no object, and full floats are not filterable everywhere anyway.
100 desc.minFilter = TextureFilter::Nearest;
101 desc.magFilter = TextureFilter::Nearest;
102 desc.wrapS = TextureWrap::ClampToEdge;
103 desc.wrapT = TextureWrap::ClampToEdge;
104 desc.mipmaps = false;
105 s.texture = device_.createTexture(desc, GfxContent::transient(), s.vertex_staging.data());
106 s.texture_rows = s.texture == TextureHandle::Invalid ? 0 : want;
107 s.texture_mirror.assign(s.vertex_staging.begin(), s.vertex_staging.begin() + static_cast<std::ptrdiff_t>(static_cast<usize>(s.texture_rows) * rowBytes));
108 s.mirror_rows = s.texture_rows;
109 s.mirror_generation = device_.deviceGeneration();
110 ++grows;
111 if (FrameProfiler::get().enabled()) FrameProfiler::get().add("render.upload.recordRows", rows);
112 return;
113 }
114 if (s.mirror_generation != device_.deviceGeneration()) {
115 s.mirror_rows = 0;
116 s.mirror_generation = device_.deviceGeneration();
117 }
118 if (s.texture_mirror.size() < static_cast<usize>(s.texture_rows) * rowBytes) {
119 s.texture_mirror.resize(static_cast<usize>(s.texture_rows) * rowBytes);
120 }
121 const u8* staged = s.vertex_staging.data();
122 u8* held = s.texture_mirror.data();
123 const auto differs = [&](u32 row) {
124 return row >= s.mirror_rows || std::memcmp(staged + static_cast<usize>(row) * rowBytes, held + static_cast<usize>(row) * rowBytes, rowBytes) != 0;
125 };
126 u32 first = 0;
127 while (first < rows && !differs(first)) ++first;
128 if (first == rows) {
129 if (FrameProfiler::get().enabled()) FrameProfiler::get().add("render.upload.recordRowsKept", rows);
130 return;
131 }
132 u32 last = rows - 1;
133 while (last > first && !differs(last)) --last;
134 const u32 band = last - first + 1;
135 device_.updateTexture(s.texture, 0, static_cast<i32>(first), MESH_INSTANCE_TEXTURE_WIDTH, band,
136 staged + static_cast<usize>(first) * rowBytes, /*flipY=*/false);
137 std::memcpy(held + static_cast<usize>(first) * rowBytes, staged + static_cast<usize>(first) * rowBytes, static_cast<usize>(band) * rowBytes);
138 s.mirror_rows = std::max(s.mirror_rows, last + 1);
139 ++writes;
140 if (FrameProfiler::get().enabled()) {
141 FrameProfiler::get().add("render.upload.recordRows", band);
142 FrameProfiler::get().add("render.upload.recordRowsKept", rows - band);
143 }
144}
145
147 Stream& s = stream(layout);
148 if (byteSize) ensureStorage(layout);
149 u32 offset = s.vertex_write_pos;
150 u32 newPos = s.vertex_write_pos + byteSize;
151 if (newPos > static_cast<u32>(s.vertex_staging.size())) {
152 growVertexStaging(s, newPos);
153 }
154 s.vertex_write_pos = newPos;
155 return offset;
156}
157
159 Stream& s = stream(layout);
160 if (count) ensureStorage(layout);
161 u32 offset = s.index_write_pos;
162 u32 newPos = s.index_write_pos + count;
163 if (newPos > static_cast<u32>(s.index_staging.size())) {
164 growIndexStaging(s, newPos);
165 }
166 s.index_write_pos = newPos;
167 return offset;
168}
169
170void TransientBufferPool::writeVertices(LayoutId layout, u32 byteOffset, const void* data, u32 byteSize) {
171 std::memcpy(stream(layout).vertex_staging.data() + byteOffset, data, byteSize);
172}
173
174void TransientBufferPool::writeIndices(LayoutId layout, u32 indexOffset, const u32* data, u32 count) {
175 std::memcpy(stream(layout).index_staging.data() + indexOffset, data, count * sizeof(u32));
176}
177
178u32 TransientBufferPool::appendVertices(LayoutId layout, const void* data, u32 byteSize) {
179 u32 offset = allocVertices(layout, byteSize);
180 writeVertices(layout, offset, data, byteSize);
181 return offset;
182}
183
185 u32 offset = allocIndices(layout, count);
186 writeIndices(layout, offset, data, count);
187 return offset;
188}
189
191 // What the upload was ASKED to move, beside what it cost. A spike that tracks
192 // bytes is workload; a spike at unchanged bytes is the allocation or driver
193 // path, and one number cannot tell those apart.
194 u32 streams = 0, vertexBytes = 0, indexBytes = 0, grows = 0, writes = 0;
195 // Growth goes through resizeBuffer, which keeps the handle stable, so per-draw
196 // buffer bindings and the backend's cached vertex state stay valid.
197 for (auto& s : streams_) {
198 if (&s == &stream(LayoutId::MeshInstance)) {
199 if (s.vertex_write_pos == 0) continue;
200 ++streams;
201 vertexBytes += s.vertex_write_pos;
202 uploadInstanceRows(s, grows, writes);
203 continue;
204 }
205 if (s.vbo == BufferHandle::Invalid) continue;
206 if (s.vertex_write_pos == 0 && s.index_write_pos == 0) continue;
207 ++streams;
208 vertexBytes += s.vertex_write_pos;
209 indexBytes += s.index_write_pos * static_cast<u32>(sizeof(u32));
210
211 // Grow to the STAGING capacity, which already doubles — not to what this
212 // frame needed, which reallocates every frame for a workload creeping
213 // upward (2.1MB, 2.2MB, 2.3MB). One growth rule, in growVertexStaging.
214 if (s.vertex_write_pos > s.vbo_capacity) {
215 s.vbo_capacity = static_cast<u32>(s.vertex_staging.size());
216 device_.resizeBuffer(s.vbo, s.vbo_capacity, s.vertex_staging.data());
217 ++grows;
218 } else if (s.vertex_write_pos > 0) {
219 device_.updateBuffer(s.vbo, 0, s.vertex_staging.data(), s.vertex_write_pos);
220 ++writes;
221 }
222
223 u32 eboBytes = s.index_write_pos * sizeof(u32);
224 u32 eboCapBytes = s.ebo_capacity * sizeof(u32);
225 if (eboBytes > eboCapBytes) {
226 s.ebo_capacity = static_cast<u32>(s.index_staging.size());
227 device_.resizeBuffer(s.ebo, static_cast<u32>(s.ebo_capacity * sizeof(u32)),
228 s.index_staging.data());
229 ++grows;
230 } else if (eboBytes > 0) {
231 device_.updateBuffer(s.ebo, 0, s.index_staging.data(), eboBytes);
232 ++writes;
233 }
234 }
235 ES_PROFILE_COUNTER("render.upload.streams", streams);
236 ES_PROFILE_COUNTER("render.upload.vertexBytes", vertexBytes);
237 ES_PROFILE_COUNTER("render.upload.indexBytes", indexBytes);
238 ES_PROFILE_COUNTER("render.upload.grows", grows);
239 ES_PROFILE_COUNTER("render.upload.writes", writes);
240}
241
243 const Stream& s = stream(layout);
244 if (layout == LayoutId::ParticleInstance) {
245 bindInstanceLayout(layout, 0);
246 return;
247 }
248 device_.setVertexBuffer(0, s.vbo, 0);
249 device_.setIndexBuffer(s.ebo);
250}
251
252void TransientBufferPool::bindInstanceLayout(LayoutId layout, u32 instanceByteOffset) {
253 const Stream& s = stream(layout);
254 device_.setVertexBuffer(0, s.quad_vbo, 0);
255 device_.setVertexBuffer(1, s.vbo, instanceByteOffset);
256 device_.setIndexBuffer(s.ebo);
257}
258
260 const Stream& s = stream(layout);
261 device_.setVertexBuffer(0, s.quad_vbo, 0);
262 device_.setVertexBuffer(1, instances, 0);
263 device_.setIndexBuffer(s.ebo);
264}
265
267 return stream(layout).layout;
268}
269
271 return stream(layout).vertex_staging.data();
272}
273
275 return stream(layout).vertex_write_pos;
276}
277
279 return stream(layout).index_write_pos;
280}
281
283 return stream(layout).index_staging.data();
284}
285
286bool TransientBufferPool::copyIndexRange(LayoutId layout, u32 offset, u32 count, u32& copiedAt) {
287 auto& s = stream(layout);
288 if (count == 0 || offset > s.index_write_pos || count > s.index_write_pos - offset
289 || count > ~u32{0} - s.index_write_pos) return false;
290 copiedAt = allocIndices(layout, count);
291 // Allocation can grow the vector; resolve both addresses afterwards.
292 std::memmove(s.index_staging.data() + copiedAt, s.index_staging.data() + offset,
293 static_cast<usize>(count) * sizeof(u32));
294 return true;
295}
296
298 return stream(layout).vbo;
299}
300
302 return stream(layout).ebo;
303}
304
306 return stream(layout).vertex_stride;
307}
308
309void TransientBufferPool::ensureStorage(LayoutId layout) {
310 Stream& s = stream(layout);
311 if (layout == LayoutId::MeshInstance || s.vbo != BufferHandle::Invalid) return;
312 if (layout == LayoutId::ParticleInstance) {
313 // Per-instance (per-particle) stream: dynamic, streamed each frame.
314 s.vertex_staging.resize(initial_vertex_bytes_);
315 s.vbo_capacity = initial_vertex_bytes_;
316 s.vbo = device_.createBuffer({GfxBufferUsage::Vertex, s.vbo_capacity, /*dynamic=*/true},
317 GfxContent::transient(), nullptr);
318
319 // Static unit quad (pos + uv) and its 6 indices, uploaded once. UVs are laid out
320 // so the instance shader's a_texCoord*uvScale+uvOffset reproduces the prior
321 // per-corner particle UVs.
322 struct QuadV { f32 px, py, u, v; };
323 const QuadV quad[4] = {
324 { -0.5f, -0.5f, 0.0f, 1.0f },
325 { 0.5f, -0.5f, 1.0f, 1.0f },
326 { 0.5f, 0.5f, 1.0f, 0.0f },
327 { -0.5f, 0.5f, 0.0f, 0.0f },
328 };
329 const u32 quadIdx[6] = { 0, 1, 2, 2, 3, 0 };
330 s.quad_vbo = device_.createBuffer(
331 {GfxBufferUsage::Vertex, static_cast<u32>(sizeof(quad)), /*dynamic=*/false},
332 GfxContent::retained(), quad);
333 s.ebo = device_.createBuffer(
334 {GfxBufferUsage::Index, static_cast<u32>(sizeof(quadIdx)), /*dynamic=*/false},
335 GfxContent::retained(), quadIdx);
336
337 return;
338 }
339 s.vertex_staging.resize(initial_vertex_bytes_);
340 s.index_staging.resize(initial_index_count_);
341 s.vbo_capacity = initial_vertex_bytes_;
342 s.ebo_capacity = initial_index_count_;
343
344 s.vbo = device_.createBuffer({GfxBufferUsage::Vertex, s.vbo_capacity, /*dynamic=*/true},
345 GfxContent::transient(), nullptr);
346 s.ebo = device_.createBuffer(
347 {GfxBufferUsage::Index, static_cast<u32>(s.ebo_capacity * sizeof(u32)), /*dynamic=*/true},
348 GfxContent::transient(), nullptr);
349}
350
351void TransientBufferPool::setupStream(LayoutId layout) {
352 Stream& s = stream(layout);
353
354 if (layout == LayoutId::MeshInstance) {
355 // Only a stream, and not a vertex one: the frame's per-object records go
356 // in a texture, so a shader can reach any record by index rather than only
357 // the one the hardware happens to be on.
358 s.vertex_stride = MESH_INSTANCE_STRIDE;
359 s.texture_rows = 0;
360 return;
361 }
362
363 if (layout == LayoutId::ParticleInstance) {
364 // Slot 0: the static quad (per vertex). Slot 1: the instance stream (per instance),
365 // rebased per draw in bindInstanceLayout.
366 VertexLayoutDesc desc;
367 desc.attributeCount = 8;
368 desc.strides[0] = 16;
369 desc.strides[1] = PARTICLE_INSTANCE_STRIDE;
370 desc.instanceStep[1] = true;
371 desc.attributes[0] = {0, 2, GfxDataType::Float, false, 0, 0};
372 desc.attributes[1] = {1, 2, GfxDataType::Float, false, 8, 0};
373 // The instance position carries all three axes: a particle simulated in
374 // depth and uploaded as a pair is drawn on the plane it left.
375 desc.attributes[2] = {2, 3, GfxDataType::Float, false, 0, 1};
376 desc.attributes[3] = {3, 2, GfxDataType::Float, false, 12, 1};
377 desc.attributes[4] = {4, 1, GfxDataType::Float, false, 20, 1};
378 desc.attributes[5] = {5, 4, GfxDataType::UnsignedByte, true, 24, 1};
379 desc.attributes[6] = {6, 4, GfxDataType::Float, false, 28, 1};
380 desc.attributes[7] = {7, 4, GfxDataType::Float, false, 44, 1};
381 s.vertex_stride = desc.strides[1];
382 s.layout = device_.createVertexLayout(desc);
383 return;
384 }
385
386 VertexLayoutDesc desc;
387 switch (layout) {
388 case LayoutId::Batch:
389 // BatchVertex: pos(12) + color(4) + uv(8) + texIndex(4) + sdfBias(4)
390 desc.attributeCount = 5;
391 desc.strides[0] = 32;
392 desc.attributes[0] = {0, 3, GfxDataType::Float, false, 0, 0};
393 desc.attributes[1] = {1, 4, GfxDataType::UnsignedByte, true, 12, 0};
394 desc.attributes[2] = {2, 2, GfxDataType::Float, false, 16, 0};
395 desc.attributes[3] = {3, 1, GfxDataType::Float, false, 24, 0};
396 desc.attributes[4] = {4, 1, GfxDataType::Float, false, 28, 0};
397 break;
398 case LayoutId::Shape:
399 desc.attributeCount = 4;
400 desc.strides[0] = 48;
401 desc.attributes[0] = {0, 2, GfxDataType::Float, false, 0, 0};
402 desc.attributes[1] = {1, 2, GfxDataType::Float, false, 8, 0};
403 desc.attributes[2] = {2, 4, GfxDataType::Float, false, 16, 0};
404 desc.attributes[3] = {3, 4, GfxDataType::Float, false, 32, 0};
405 break;
406 case LayoutId::Sky:
407 // One vec3 and nothing else: a layout may not declare an attribute its
408 // shader does not consume, which is why this is not the Batch one.
409 desc.attributeCount = 1;
410 desc.strides[0] = 12;
411 desc.attributes[0] = {0, 3, GfxDataType::Float, false, 0, 0};
412 break;
413 default:
414 break;
415 }
416 s.vertex_stride = desc.strides[0];
417 s.layout = device_.createVertexLayout(desc);
418}
419
420void TransientBufferPool::growVertexStaging(Stream& s, u32 requiredBytes) {
421 u32 newSize = static_cast<u32>(s.vertex_staging.size());
422 if (newSize == 0) newSize = 1024;
423 while (newSize < requiredBytes) {
424 newSize = newSize * 2;
425 }
426 s.vertex_staging.resize(newSize);
427 // Growing to fit a frame is what the pool is for, not a fault.
428 ES_LOG_DEBUG("TransientBufferPool: vertex staging grown to {}KB", newSize / 1024);
429}
430
431void TransientBufferPool::growIndexStaging(Stream& s, u32 requiredCount) {
432 u32 newSize = static_cast<u32>(s.index_staging.size());
433 if (newSize == 0) newSize = 1024;
434 while (newSize < requiredCount) {
435 newSize = newSize * 2;
436 }
437 s.index_staging.resize(newSize);
438 ES_LOG_DEBUG("TransientBufferPool: index staging grown to {} indices", newSize);
439}
440
441} // namespace esengine
Per-frame CPU scope timing (ES_PROFILE_SCOPE) read by the editor profiler.
#define ES_PROFILE_COUNTER(name, value)
Logging utilities for ESEngine.
#define ES_LOG_DEBUG(...)
Definition Log.hpp:282
void add(const char *name, double ms)
static FrameProfiler & get()
static constexpr GfxContent transient()
static constexpr GfxContent retained()
Abstract graphics device interface.
Definition GfxDevice.hpp:75
BufferHandle createBuffer(const BufferDesc &desc, GfxContent content, const void *initialData)
Creates a buffer with fixed capacity and optional initial contents.
VertexLayoutHandle layoutHandle(LayoutId layout) const
bool copyIndexRange(LayoutId layout, u32 offset, u32 count, u32 &copiedAt)
u32 appendVertices(LayoutId layout, const void *data, u32 byteSize)
const u32 * indexData(LayoutId layout) const
BufferHandle vertexBuffer(LayoutId layout) const
GfxDevice & device()
The device the pool's buffers live on, for a plugin that keeps geometry of its own on it.
void bindInstanceLayout(LayoutId layout, u32 instanceByteOffset)
u32 allocIndices(LayoutId layout, u32 count)
u32 vertexStride(LayoutId layout) const
BufferHandle indexBuffer(LayoutId layout) const
void init(u32 initialVertexBytes=2 *1024 *1024, u32 initialIndexCount=256 *1024)
u32 vertexBytesUsed(LayoutId layout) const
u32 indicesUsed(LayoutId layout) const
u32 appendIndices(LayoutId layout, const u32 *data, u32 count)
void writeVertices(LayoutId layout, u32 byteOffset, const void *data, u32 byteSize)
u32 allocVertices(LayoutId layout, u32 byteSize)
void bindInstanceBuffer(LayoutId layout, BufferHandle instances)
void writeIndices(LayoutId layout, u32 indexOffset, const u32 *data, u32 count)
static constexpr u32 MESH_INSTANCE_STRIDE
Definition GfxEnums.hpp:121
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
static constexpr u32 MESH_INSTANCE_TEXELS
Definition GfxEnums.hpp:108
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
static constexpr u32 MESH_INSTANCE_MAX_RECORDS
Definition GfxEnums.hpp:128
@ Nearest
No interpolation (pixelated look).
Definition GfxEnums.hpp:58
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
static constexpr u32 MESH_INSTANCE_TEXTURE_WIDTH
Definition GfxEnums.hpp:125
std::uint8_t u8
Unsigned 8-bit integer.
Definition Types.hpp:41
LayoutId
Identifies a transient vertex stream / vertex format. Each layout has its own VBO+EBO+VAO in Transien...
Definition GfxEnums.hpp:88
@ ParticleInstance
Instanced: a static unit quad + a per-particle instance stream.
Definition GfxEnums.hpp:90
static constexpr u32 PARTICLE_INSTANCE_STRIDE
Definition GfxEnums.hpp:122