Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

perf(renderer): a draw's uniform blocks are ranges of shared pages, uploaded once per pass

esenginee99456d52e5a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 030a62846..5092e49a6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -32,6 +32,8 @@ published separately; it ships inside the editor.
- **A large project opens in minutes, not half an hour.** The editor uploaded every texture as decoded pixels. ORCA Bistro's 224 2K textures came to 4.7 GiB of video memory, past what an 8 GB card had free, so Windows paged them in and out while the GPU sat idle. One frame stalled for up to 25 minutes, and Chromium's GPU watchdog then restarted the GPU process and the whole load began again. The editor, and the play realm beside it, now draw textures GPU-compressed, as a build does: the same KTX2, from the same cook cache, so the editor pays nothing for art an export already compressed and an export after an editing session encodes nothing. A texture the cache does not hold yet is drawn from a preview no larger than 1024 while it compresses in the background, then reloaded, and the editor does not report idle until it is. Textures with Compress off stay as they are. The editor draws each texture as the build ships it, by the same Compression rule. Bistro now opens with a cold GPU cache in about two minutes, where it took 20 to 36.
+- **A scene of thousands of meshes draws its first frame in seconds.** Every mesh draw wrote its probe and instance blocks into a uniform buffer of its own, so a frame's first appearance created one per draw: ORCA Bistro's 8,000 draws made 16,000 buffers, 128 MB of them, and on Windows the GPU process spent 30 s of a 43 s project open creating them. A draw's blocks are now ranges of a few shared pages — a range starts where the last draw's bytes end, not a whole block later — and a pass stages every draw's blocks before it uploads each page once, where each draw had written its own. Bistro's frame now holds 18 pages and makes 56 uploads, where it made 15,924; it opens to idle in about 16 s.
+
- **`bake-scene` refuses a scene made of prefab instances instead of crashing on it.** It cannot expand an instance, so it found nothing to bake and then threw on the instance entity; it now says to bake such a scene in the editor, as it already did for parented entities.
- **An environment is no longer mirrored.** A panorama was read with its left and right swapped, so a camera facing its centre saw what the photographer saw on the left on its right — in the sky, in reflections and in the light the environment casts. ORCA Bistro's HDRI put its sun on the wrong side of the street. The sky, reflections and irradiance now read a panorama as it was shot, through one mapping, and a gate draws a panorama that is red left of its centre and blue right of it. Reimport a `.hdr` to pick it up; a scene that was turned to suit the mirror needs its `environmentRotation` set again.
diff --git a/src/esengine/renderer/draw/DrawList.cpp b/src/esengine/renderer/draw/DrawList.cpp
index 5e5356ee1..320fc566b 100644
--- a/src/esengine/renderer/draw/DrawList.cpp
+++ b/src/esengine/renderer/draw/DrawList.cpp
@@ -201,6 +201,60 @@ std::span<const Entity> DrawList::runEntities(u32 index) const {
return {run_entities_.data() + first, end - first};
}
+void DrawList::stageBlocks(const PerDrawBlockSet& blocks) {
+ staged_.assign(merged_draw_calls_, StagedBlocks{});
+ for (u32 i = 0; i < merged_draw_calls_; ++i) {
+ const auto& cmd = commands_[i];
+ StagedBlocks& staged = staged_[i];
+
+ // The pose, for a draw that has one — in a range of this draw's own. A
+ // block shared between two draws of one pass is read by both with what
+ // the last wrote, which is a room of characters in one pose.
+ if (cmd.skin_count > 0 && blocks.skin) {
+ staged.skin = blocks.skin->stage(skin_matrices_.data() + cmd.skin_offset,
+ cmd.skin_count * static_cast<u32>(sizeof(glm::mat4)));
+ }
+
+ // The shapes, the same way — and a draw with none binds the zeroed block
+ // rather than erasing the last one's, so "unshaped" is an object instead
+ // of an erasure someone has to remember to perform.
+ if (blocks.morph && cmd.morph_index > 0) {
+ staged.morph = blocks.morph->stage(&morph_shapes_[cmd.morph_index - 1], sizeof(MorphConstants));
+ }
+
+ // WHERE this draw's instances read their irradiance, not what it is: the
+ // coefficients are in the frame's texture, one run per instance, so a
+ // merged draw holding objects in many places still says one thing here.
+ if (blocks.probe) {
+ // Every instance of this run, in the order it draws them, capped at
+ // what the block holds — a longer run carries no irradiance at all,
+ // so its tail reads zeroes and takes the environment.
+ const u32 runs = std::min(cmd.instance_count > 0 ? cmd.instance_count : 1u,
+ PROBE_MAX_INSTANCES);
+ probe_run_.assign(static_cast<size_t>(runs) * PROBE_TEXELS, glm::vec4(0.0f));
+ for (u32 n = 0; n < runs; ++n) {
+ const size_t at = static_cast<size_t>(cmd.probe_base) + n;
+ const u32 index = at < probe_slots_.size() ? probe_slots_[at] : 0u;
+ if (index == 0) continue;
+ std::memcpy(&probe_run_[static_cast<size_t>(n) * PROBE_TEXELS],
+ &probes_[index - 1], sizeof(ProbeConstants));
+ }
+ staged.probe = blocks.probe->stage(
+ probe_run_.data(), static_cast<u32>(probe_run_.size() * sizeof(glm::vec4)));
+ }
+
+ // gl_InstanceID restarts at zero every draw while the frame's records are
+ // one continuous run, so a draw has to say where its own run begins in them.
+ if (blocks.instance && cmd.hasPersistentGeometry()) {
+ const InstanceConstants at{cmd.vertex_byte_offset / MESH_INSTANCE_STRIDE, {}};
+ staged.instance = blocks.instance->stage(&at, sizeof(at));
+ }
+ }
+ for (PerDrawBlocks* pool : {blocks.skin, blocks.morph, blocks.probe, blocks.instance}) {
+ if (pool) pool->upload();
+ }
+}
+
void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,
MaterialStore& materials, u32 white_texture_id,
FrameCapture* capture, const PerDrawBlockSet& blocks) {
@@ -213,8 +267,11 @@ void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,
device.bindTexture(MESH_INSTANCE_TEXTURE_UNIT, buffers.instanceTexture());
}
+ stageBlocks(blocks);
+
for (u32 i = 0; i < merged_draw_calls_; ++i) {
const auto& cmd = commands_[i];
+ const StagedBlocks& staged = staged_[i];
const GfxStencilMode stencil = stencilModeOf(cmd.state_flags);
@@ -254,48 +311,14 @@ void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,
materials.bindForDraw(cmd.material_id);
}
- // The pose, for a draw that has one — in a buffer of this draw's own. A
- // block shared between two draws of one pass is read by both with what
- // the last wrote, which is a room of characters in one pose.
if (cmd.skin_count > 0 && blocks.skin) {
- device.setUniformBuffer(
- SKIN_CONSTANTS_BINDING,
- blocks.skin->write(skin_matrices_.data() + cmd.skin_offset,
- cmd.skin_count * static_cast<u32>(sizeof(glm::mat4))));
+ blocks.skin->bind(SKIN_CONSTANTS_BINDING, staged.skin);
}
-
- // The shapes, the same way — and a draw with none binds the zeroed block
- // rather than erasing the last one's, so "unshaped" is an object instead
- // of an erasure someone has to remember to perform.
if (blocks.morph) {
- device.setUniformBuffer(MORPH_CONSTANTS_BINDING,
- cmd.morph_index > 0
- ? blocks.morph->write(&morph_shapes_[cmd.morph_index - 1],
- sizeof(MorphConstants))
- : blocks.morph->zero());
+ blocks.morph->bind(MORPH_CONSTANTS_BINDING, staged.morph);
}
-
- // WHERE this draw's instances read their irradiance, not what it is: the
- // coefficients are in the frame's texture, one run per instance, so a
- // merged draw holding objects in many places still says one thing here.
if (blocks.probe) {
- // Every instance of this run, in the order it draws them, capped at
- // what the block holds — a longer run carries no irradiance at all,
- // so its tail reads zeroes and takes the environment.
- const u32 runs = std::min(cmd.instance_count > 0 ? cmd.instance_count : 1u,
- PROBE_MAX_INSTANCES);
- probe_run_.assign(static_cast<size_t>(runs) * PROBE_TEXELS, glm::vec4(0.0f));
- for (u32 n = 0; n < runs; ++n) {
- const size_t at = static_cast<size_t>(cmd.probe_base) + n;
- const u32 index = at < probe_slots_.size() ? probe_slots_[at] : 0u;
- if (index == 0) continue;
- std::memcpy(&probe_run_[static_cast<size_t>(n) * PROBE_TEXELS],
- &probes_[index - 1], sizeof(ProbeConstants));
- }
- device.setUniformBuffer(
- PROBE_CONSTANTS_BINDING,
- blocks.probe->write(probe_run_.data(),
- static_cast<u32>(probe_run_.size() * sizeof(glm::vec4))));
+ blocks.probe->bind(PROBE_CONSTANTS_BINDING, staged.probe);
}
// Dynamic per-draw state (sorted+merged draws already group these coarsely).
@@ -326,13 +349,8 @@ void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,
}
if (cmd.hasPersistentGeometry()) {
- // gl_InstanceID restarts at zero every draw while the frame's
- // records are one continuous run, so a draw has to say where its own
- // run begins in them.
if (blocks.instance) {
- const InstanceConstants at{cmd.vertex_byte_offset / MESH_INSTANCE_STRIDE, {}};
- device.setUniformBuffer(INSTANCE_CONSTANTS_BINDING,
- blocks.instance->write(&at, sizeof(at)));
+ blocks.instance->bind(INSTANCE_CONSTANTS_BINDING, staged.instance);
}
device.setVertexBuffer(0, cmd.vertex_buffer, 0);
device.setIndexBuffer(cmd.index_buffer);
diff --git a/src/esengine/renderer/draw/DrawList.hpp b/src/esengine/renderer/draw/DrawList.hpp
index dd145396a..491d715ec 100644
--- a/src/esengine/renderer/draw/DrawList.hpp
+++ b/src/esengine/renderer/draw/DrawList.hpp
@@ -207,6 +207,12 @@ private:
/// One draw's run of coefficients, rebuilt per draw — reused so a frame of
/// merged draws does not allocate per draw.
std::vector<glm::vec4> probe_run_;
+ /// Each merged draw's per-draw blocks, staged for the pass before it draws.
+ struct StagedBlocks {
+ PerDrawBlocks::Range skin, morph, probe, instance;
+ };
+ std::vector<StagedBlocks> staged_;
+ void stageBlocks(const PerDrawBlockSet& blocks);
std::vector<SortEntry> sort_entries_;
std::vector<DrawCommand> sorted_scratch_; // reused across frames to avoid a
// per-frame heap alloc in finalize()
diff --git a/src/esengine/renderer/frame/RenderContext.cpp b/src/esengine/renderer/frame/RenderContext.cpp
index 146d9e847..3d9ee6681 100644
--- a/src/esengine/renderer/frame/RenderContext.cpp
+++ b/src/esengine/renderer/frame/RenderContext.cpp
@@ -141,9 +141,9 @@ void RenderContext::initFrameUbo() {
instanceBlocks_.init(device_, static_cast<u32>(sizeof(InstanceConstants)));
// What a draw with no shapes and no volume reads. A pose has no zero: geometry
// without one is drawn by a shader that does not declare the block.
- device_.setUniformBuffer(MORPH_CONSTANTS_BINDING, morphBlocks_.zero());
- device_.setUniformBuffer(PROBE_CONSTANTS_BINDING, probeBlocks_.zero());
- device_.setUniformBuffer(INSTANCE_CONSTANTS_BINDING, instanceBlocks_.zero());
+ morphBlocks_.bindZero(MORPH_CONSTANTS_BINDING);
+ probeBlocks_.bindZero(PROBE_CONSTANTS_BINDING);
+ instanceBlocks_.bindZero(INSTANCE_CONSTANTS_BINDING);
ES_LOG_DEBUG("FrameConstants UBO created (handle: {})", static_cast<u32>(frameUbo_));
}
diff --git a/src/esengine/renderer/rhi/GLDevice.cpp b/src/esengine/renderer/rhi/GLDevice.cpp
index bc4b6149c..7f2f04700 100644
--- a/src/esengine/renderer/rhi/GLDevice.cpp
+++ b/src/esengine/renderer/rhi/GLDevice.cpp
@@ -800,7 +800,7 @@ bool GLDevice::backendCreateBuffer(u32 id, const BufferDesc& desc, const void* d
uploadBufferStore(id, 0, data, desc.size, /*respec=*/true);
// A slot keeps naming the buffer across a rebuild; the context it was bound in does not.
for (usize slot = 0; slot < uniform_slots_.size(); ++slot) {
- if (uniform_slots_[slot] == id) glBindBufferBase(GL_UNIFORM_BUFFER, static_cast<GLuint>(slot), name);
+ if (uniform_slots_[slot] == id) bindUniformSlot(static_cast<u32>(slot), name);
}
return true;
}
@@ -820,9 +820,20 @@ void GLDevice::backendResizeBuffer(u32 id, const BufferDesc& desc, const void* d
uploadBufferStore(id, 0, data, desc.size, /*respec=*/true);
}
-void GLDevice::setUniformBuffer(u32 slot, BufferHandle buffer) {
+void GLDevice::backendSetUniformBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes, u32 sizeBytes) {
setName(uniform_slots_, slot, static_cast<u32>(buffer));
- glBindBufferBase(GL_UNIFORM_BUFFER, slot, nameOf(buffer_names_, static_cast<u32>(buffer)));
+ if (slot >= uniform_ranges_.size()) uniform_ranges_.resize(static_cast<usize>(slot) + 1);
+ uniform_ranges_[slot] = {offsetBytes, sizeBytes};
+ bindUniformSlot(slot, nameOf(buffer_names_, static_cast<u32>(buffer)));
+}
+
+void GLDevice::bindUniformSlot(u32 slot, u32 name) {
+ const UniformRange range = slot < uniform_ranges_.size() ? uniform_ranges_[slot] : UniformRange{};
+ if (name && range.size) {
+ glBindBufferRange(GL_UNIFORM_BUFFER, slot, name, range.offset, range.size);
+ } else {
+ glBindBufferBase(GL_UNIFORM_BUFFER, slot, name);
+ }
}
// =============================================================================
diff --git a/src/esengine/renderer/rhi/GLDevice.hpp b/src/esengine/renderer/rhi/GLDevice.hpp
index 15546a8cd..eb6d10654 100644
--- a/src/esengine/renderer/rhi/GLDevice.hpp
+++ b/src/esengine/renderer/rhi/GLDevice.hpp
@@ -51,7 +51,6 @@ public:
void setScissorTest(bool enabled) override;
void setScissor(i32 x, i32 y, i32 w, i32 h) override;
- void setUniformBuffer(u32 slot, BufferHandle buffer) override;
void setVertexBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes) override;
void setIndexBuffer(BufferHandle buffer) override;
@@ -105,6 +104,7 @@ protected:
void backendDeleteBuffer(u32 id) override;
void backendUpdateBuffer(u32 id, u32 offsetBytes, const void* data, u32 sizeBytes) override;
void backendResizeBuffer(u32 id, const BufferDesc& desc, const void* data) override;
+ void backendSetUniformBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes, u32 sizeBytes) override;
bool backendCreateTexture(u32 id, const TextureDesc& desc, const void* pixels) override;
bool backendCreateCompressedTexture(u32 id, const TextureDesc& desc, GfxCompressedFormat format,
@@ -204,6 +204,10 @@ private:
std::vector<u32> query_names_;
/** Buffer id per uniform binding slot, as the renderer set it. */
std::vector<u32> uniform_slots_;
+ /** The range of that buffer each slot reads; a size of 0 is the whole buffer. */
+ struct UniformRange { u32 offset = 0; u32 size = 0; };
+ std::vector<UniformRange> uniform_ranges_;
+ void bindUniformSlot(u32 slot, u32 name);
u32 current_pipeline_id_ = 0;
GfxStencilMode current_stencil_mode_ = GfxStencilMode::Off;
diff --git a/src/esengine/renderer/rhi/GfxDevice.hpp b/src/esengine/renderer/rhi/GfxDevice.hpp
index cdae0994a..ff93d0488 100644
--- a/src/esengine/renderer/rhi/GfxDevice.hpp
+++ b/src/esengine/renderer/rhi/GfxDevice.hpp
@@ -43,6 +43,9 @@ namespace esengine {
/** @brief Sentinel returned by getUniformBlockIndex when a program has no such block (GL_INVALID_INDEX). */
static constexpr u32 GFX_INVALID_UNIFORM_BLOCK = 0xFFFFFFFFu;
+/** @brief What a uniform binding's offset must be a multiple of: the largest either API may ask. */
+static constexpr u32 GFX_UNIFORM_OFFSET_ALIGNMENT = 256;
+
/**
* @brief GPU objects the device has created and not yet destroyed.
*
@@ -316,8 +319,14 @@ public:
/** @brief A buffer's description as it stands, or null for a handle that names none. */
const BufferDesc* bufferDesc(BufferHandle buffer) const;
- /** @brief Binds a buffer to a uniform binding slot (the block index shaders are linked to). */
- virtual void setUniformBuffer(u32 slot, BufferHandle buffer) = 0;
+ /**
+ * @brief Binds a buffer to a uniform binding slot (the block index shaders are linked to).
+ * @details @p sizeBytes of it from @p offsetBytes, a multiple of
+ * GFX_UNIFORM_OFFSET_ALIGNMENT; a size of 0 is the whole buffer.
+ */
+ void setUniformBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes = 0, u32 sizeBytes = 0) {
+ backendSetUniformBuffer(slot, buffer, offsetBytes, sizeBytes);
+ }
// =========================================================================
// Vertex Input (layout in the pipeline, buffers bound per draw)
@@ -732,6 +741,7 @@ protected:
virtual void backendDeleteBuffer(u32 id) = 0;
virtual void backendUpdateBuffer(u32 id, u32 offsetBytes, const void* data, u32 sizeBytes) = 0;
virtual void backendResizeBuffer(u32 id, const BufferDesc& desc, const void* data) = 0;
+ virtual void backendSetUniformBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes, u32 sizeBytes) = 0;
virtual bool backendCreateTexture(u32 id, const TextureDesc& desc, const void* pixels) = 0;
virtual bool backendCreateCompressedTexture(u32 id, const TextureDesc& desc, GfxCompressedFormat format,
diff --git a/src/esengine/renderer/rhi/PerDrawBlocks.hpp b/src/esengine/renderer/rhi/PerDrawBlocks.hpp
index 74f449e84..553c95dfd 100644
--- a/src/esengine/renderer/rhi/PerDrawBlocks.hpp
+++ b/src/esengine/renderer/rhi/PerDrawBlocks.hpp
@@ -2,64 +2,142 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file PerDrawBlocks.hpp
- * @brief A uniform buffer per draw, so two draws never write into one block.
+ * @brief A uniform range per draw, so two draws never write into one block.
*
* @details A queue write lands where the pass is SUBMITTED, not where it was
* called, so a block shared between two draws is read by both with what
- * the last wrote. Buffers are handed out per FRAME and not per pass: one
+ * the last wrote. Ranges are handed out per FRAME and not per pass: one
* submission stands behind a frame's several passes.
+ *
+ * The ranges are carved from a few large pages rather than a buffer each,
+ * and a pass stages all of its draws' blocks before it uploads them once
+ * per page: creating a buffer costs the GPU process far more than writing
+ * one, and a first frame of eight thousand draws once spent half a minute
+ * creating them.
*/
#pragma once
#include "../../core/Types.hpp"
#include "./GfxDevice.hpp"
+#include <algorithm>
+#include <cstring>
#include <vector>
namespace esengine {
class PerDrawBlocks {
public:
+ /** @brief Where one draw's block was staged; a default one binds the zero block. */
+ struct Range {
+ u32 page = NONE;
+ u32 offset = 0;
+ };
+
/** @brief Claims the pool for blocks of @p blockSize bytes, plus the zero one. */
void init(GfxDevice& device, u32 blockSize) {
device_ = &device;
blockSize_ = blockSize;
- pool_.clear();
+ pageBytes_ = std::max(PAGE_BYTES, alignUp(blockSize));
+ pages_.clear();
+ page_ = 0;
+ cursor_ = 0;
used_ = 0;
const std::vector<u8> zeros(blockSize, 0);
zero_ = device.createBuffer({GfxBufferUsage::Uniform, blockSize, /*dynamic=*/false},
GfxContent::retained(), zeros.data());
}
- /** @brief Hands every buffer back. Called once per FRAME — see the file note. */
- void beginFrame() { used_ = 0; }
-
- /** @brief A buffer of this frame's holding @p size bytes of @p bytes. Grows
- * rather than wraps: wrapping hands one buffer to two draws. */
- BufferHandle write(const void* bytes, u32 size) {
- if (!device_ || !bytes || size == 0 || size > blockSize_) return BufferHandle::Invalid;
- if (used_ == pool_.size()) {
- const std::vector<u8> zeros(blockSize_, 0);
- pool_.push_back(device_->createBuffer(
- {GfxBufferUsage::Uniform, blockSize_, /*dynamic=*/true}, GfxContent::transient(),
- zeros.data()));
+ /** @brief Hands every range back. Called once per FRAME — see the file note. */
+ void beginFrame() {
+ page_ = 0;
+ cursor_ = 0;
+ used_ = 0;
+ }
+
+ /**
+ * @brief Copies @p size bytes of @p bytes into a range of this frame's, to reach
+ * the GPU at the next upload(); a block it cannot hold stages nothing.
+ *
+ * @details The next range starts after the bytes staged: a draw reads only
+ * what it was given, so the rest of its binding may be the next
+ * draw's. Grows rather than wraps, which would share a range.
+ */
+ Range stage(const void* bytes, u32 size) {
+ if (!device_ || !bytes || size == 0 || size > blockSize_) return {};
+ if (page_ < pages_.size() && cursor_ + blockSize_ > pageBytes_) {
+ ++page_;
+ cursor_ = 0;
+ }
+ if (page_ == pages_.size()) {
+ Page page;
+ page.buffer = device_->createBuffer(
+ {GfxBufferUsage::Uniform, pageBytes_, /*dynamic=*/true}, GfxContent::transient(),
+ nullptr);
+ page.bytes.assign(pageBytes_, 0);
+ pages_.push_back(std::move(page));
+ }
+ Page& page = pages_[page_];
+ std::memcpy(page.bytes.data() + cursor_, bytes, size);
+ page.dirtyFrom = std::min(page.dirtyFrom, cursor_);
+ page.dirtyTo = std::max(page.dirtyTo, cursor_ + size);
+ const Range range{static_cast<u32>(page_), cursor_};
+ cursor_ += alignUp(size);
+ ++used_;
+ return range;
+ }
+
+ /** @brief Sends what was staged since the last upload, one write per page. */
+ void upload() {
+ for (Page& page : pages_) {
+ if (page.dirtyFrom >= page.dirtyTo) continue;
+ device_->updateBuffer(page.buffer, page.dirtyFrom, page.bytes.data() + page.dirtyFrom,
+ page.dirtyTo - page.dirtyFrom);
+ page.dirtyFrom = NONE;
+ page.dirtyTo = 0;
+ }
+ }
+
+ /** @brief Binds @p range to @p slot — the zero block for a range staging refused. */
+ void bind(u32 slot, Range range) const {
+ if (!device_) return;
+ if (range.page >= pages_.size()) {
+ bindZero(slot);
+ return;
}
- const BufferHandle handle = pool_[used_++];
- if (handle != BufferHandle::Invalid) device_->updateBuffer(handle, 0, bytes, size);
- return handle;
+ device_->setUniformBuffer(slot, pages_[range.page].buffer, range.offset, blockSize_);
}
- /** @brief What a draw with nothing to say reads: zeroed once and never
+ /** @brief Binds what a draw with nothing to say reads: zeroed once and never
* written, so "none" is an object rather than an erasure. */
- BufferHandle zero() const { return zero_; }
+ void bindZero(u32 slot) const {
+ if (device_) device_->setUniformBuffer(slot, zero_);
+ }
- /** @brief Buffers this frame has handed out — a per-frame cost, for the profile. */
+ /** @brief Ranges this frame has handed out — a per-frame cost, for the profile. */
u32 used() const { return used_; }
private:
+ static constexpr u32 NONE = 0xFFFFFFFFu;
+ static constexpr u32 PAGE_BYTES = 128 * 1024;
+ static u32 alignUp(u32 n) {
+ return (n + GFX_UNIFORM_OFFSET_ALIGNMENT - 1) / GFX_UNIFORM_OFFSET_ALIGNMENT *
+ GFX_UNIFORM_OFFSET_ALIGNMENT;
+ }
+
+ struct Page {
+ BufferHandle buffer = BufferHandle::Invalid;
+ std::vector<u8> bytes;
+ u32 dirtyFrom = NONE;
+ u32 dirtyTo = 0;
+ };
+
GfxDevice* device_ = nullptr;
u32 blockSize_ = 0;
- std::vector<BufferHandle> pool_;
+ u32 pageBytes_ = 0;
+ std::vector<Page> pages_;
+ usize page_ = 0;
+ u32 cursor_ = 0;
u32 used_ = 0;
BufferHandle zero_ = BufferHandle::Invalid;
};
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.cpp b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
index c3a4d8c6e..58b31307f 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.cpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
@@ -774,11 +774,14 @@ void WebGPUDevice::backendResizeBuffer(u32 id, const BufferDesc& desc, const voi
it->second.size = desc.size;
}
-void WebGPUDevice::setUniformBuffer(u32 slot, BufferHandle buffer) {
+void WebGPUDevice::backendSetUniformBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes, u32 sizeBytes) {
if (slot >= kUniformSlots) return;
const u32 id = static_cast<u32>(buffer);
- if (uniform_slots_[slot] != id) {
+ if (uniform_slots_[slot] != id || uniform_offsets_[slot] != offsetBytes ||
+ uniform_sizes_[slot] != sizeBytes) {
uniform_slots_[slot] = id;
+ uniform_offsets_[slot] = offsetBytes;
+ uniform_sizes_[slot] = sizeBytes;
bind_group_dirty_ = true;
}
}
@@ -1935,13 +1938,14 @@ void WebGPUDevice::flushBindGroup() {
for (u32 slot = 0; slot < kUniformSlots; ++slot) {
if ((prog->group0Mask & (1u << slot)) == 0) continue;
auto it = buffers_.find(uniform_slots_[slot]);
- const BufferRec& bound = it != buffers_.end() && it->second.buffer ? it->second : dummy_ubo_;
+ const bool armed = it != buffers_.end() && it->second.buffer;
+ const BufferRec& bound = armed ? it->second : dummy_ubo_;
if (!bound.buffer) continue;
WGPUBindGroupEntry e{};
e.binding = slot;
e.buffer = bound.buffer;
- e.offset = 0;
- e.size = bound.size;
+ e.offset = armed ? uniform_offsets_[slot] : 0;
+ e.size = armed && uniform_sizes_[slot] ? uniform_sizes_[slot] : bound.size;
entries[count++] = e;
}
@@ -1949,10 +1953,14 @@ void WebGPUDevice::flushBindGroup() {
bgd.layout = groupLayoutFor(0, prog->group0Mask);
bgd.entryCount = count;
bgd.entries = entries;
- u64 ids[kUniformSlots];
- for (u32 i = 0; i < count; ++i)
- ids[i] = static_cast<u64>(reinterpret_cast<uintptr_t>(entries[i].buffer));
- bind_group_ = cachedBindGroup(0, prog->group0Mask, ids, count, bgd);
+ // An offset is keyed with its top bit set, so it never equals the buffer
+ // pointer evictBindGroups looks for.
+ u64 ids[kUniformSlots * 2];
+ for (u32 i = 0; i < count; ++i) {
+ ids[i * 2] = static_cast<u64>(reinterpret_cast<uintptr_t>(entries[i].buffer));
+ ids[i * 2 + 1] = (u64{1} << 63) | (entries[i].offset << 20) | entries[i].size;
+ }
+ bind_group_ = cachedBindGroup(0, prog->group0Mask, ids, count * 2, bgd);
if (bind_group_) wgpuRenderPassEncoderSetBindGroup(pass_, 0, bind_group_, 0, nullptr);
}
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.hpp b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
index a86b8f4d2..33dc2cc99 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.hpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
@@ -112,7 +112,6 @@ public:
void setScissorTest(bool enabled) override;
void setScissor(i32 x, i32 y, i32 w, i32 h) override;
- void setUniformBuffer(u32 slot, BufferHandle buffer) override;
void setVertexBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes) override;
void setIndexBuffer(BufferHandle buffer) override;
@@ -177,6 +176,7 @@ protected:
void backendDeleteBuffer(u32 id) override;
void backendUpdateBuffer(u32 id, u32 offsetBytes, const void* data, u32 sizeBytes) override;
void backendResizeBuffer(u32 id, const BufferDesc& desc, const void* data) override;
+ void backendSetUniformBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes, u32 sizeBytes) override;
bool backendCreateTexture(u32 id, const TextureDesc& desc, const void* pixels) override;
bool backendCreateCompressedTexture(u32 id, const TextureDesc& desc, GfxCompressedFormat format,
@@ -568,6 +568,8 @@ private:
/// WebGL2 grants 12 blocks a stage, so nine is inside both.
static constexpr u32 kUniformSlots = 9;
u32 uniform_slots_[kUniformSlots] = {}; ///< BufferHandle id per UBO binding slot.
+ u32 uniform_offsets_[kUniformSlots] = {};
+ u32 uniform_sizes_[kUniformSlots] = {}; ///< 0 = the whole buffer.
/// Engine units 0..7 (batch multi-texture) + material-param units 8..15
/// (== webgpu::kGroup1TextureUnits, static_asserted in the .cpp).
static constexpr u32 kTextureSlots = 16;
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 286455a56..6c317d1a2 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -187,6 +187,18 @@ target_include_directories(test_draw_params PRIVATE
)
add_test(NAME test_draw_params COMMAND test_draw_params)
+# Per-draw uniform ranges: a frame of thousands of draws is a few pages, not a buffer each.
+add_executable(test_per_draw_blocks
+ renderer/test_per_draw_blocks.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/GfxDevice.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp
+)
+target_include_directories(test_per_draw_blocks PRIVATE
+ ${CMAKE_SOURCE_DIR}/src
+ ${CMAKE_SOURCE_DIR}/third_party/glm
+)
+add_test(NAME test_per_draw_blocks COMMAND test_per_draw_blocks)
+
# Which SpriteMask cuts a sprite — the reach rule, apart from a frame. Header-only.
add_executable(test_sprite_mask_range renderer/test_sprite_mask_range.cpp)
target_include_directories(test_sprite_mask_range PRIVATE
diff --git a/tests/renderer/MockGfxDevice.hpp b/tests/renderer/MockGfxDevice.hpp
index 27c3b1360..f381b81a6 100644
--- a/tests/renderer/MockGfxDevice.hpp
+++ b/tests/renderer/MockGfxDevice.hpp
@@ -99,6 +99,8 @@ struct MockGfxDevice final : GfxDevice {
i32 lastUniform1iLoc = -999, lastUniform1iVal = 0;
u32 lastUniformBufferSlot = 0xFFFFFFFFu;
BufferHandle lastUniformBuffer = BufferHandle::Invalid;
+ u32 lastUniformOffset = 0;
+ u32 lastUniformSize = 0;
std::vector<u8> lastUpdateData;
BufferDesc lastBufferDesc{};
bool lastCreateBufferHadData = false;
@@ -133,10 +135,12 @@ struct MockGfxDevice final : GfxDevice {
* path a caller's "leaves it as it found it" promise is only true along. */
bool createBufferSucceeds = true;
- void setUniformBuffer(u32 slot, BufferHandle buffer) override {
+ void backendSetUniformBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes, u32 sizeBytes) override {
++setUniformBufferCalls;
lastUniformBufferSlot = slot;
lastUniformBuffer = buffer;
+ lastUniformOffset = offsetBytes;
+ lastUniformSize = sizeBytes;
}
void setVertexBuffer(u32, BufferHandle buffer, u32) override { ++setVertexBufferCalls; lastVbo = buffer; }
void setIndexBuffer(BufferHandle buffer) override { ++setIndexBufferCalls; lastIbo = buffer; }
diff --git a/tests/renderer/test_per_draw_blocks.cpp b/tests/renderer/test_per_draw_blocks.cpp
new file mode 100644
index 000000000..58485b2dc
--- /dev/null
+++ b/tests/renderer/test_per_draw_blocks.cpp
@@ -0,0 +1,76 @@
+// PerDrawBlocks: every draw gets a range of its own, carved from a few pages
+// that a pass uploads once each.
+
+#include "MockGfxDevice.hpp"
+#include "esengine/renderer/rhi/PerDrawBlocks.hpp"
+
+#include <cstdio>
+#include <vector>
+
+using namespace esengine;
+
+static int g_failures = 0;
+#define CHECK(cond, msg) \
+ do { \
+ if (!(cond)) { std::printf("FAIL: %s\n", msg); ++g_failures; } \
+ else { std::printf("ok: %s\n", msg); } \
+ } while (0)
+
+struct Bound { BufferHandle buffer; u32 offset; u32 size; };
+
+int main() {
+ MockGfxDevice device;
+ PerDrawBlocks blocks;
+ constexpr u32 BLOCK = 16016;
+ constexpr u32 WRITTEN = 160;
+ constexpr u32 DRAWS = 8000;
+ blocks.init(device, BLOCK);
+ const int afterInit = device.createBufferCalls;
+
+ const std::vector<u8> bytes(BLOCK, 7);
+ int uploads = 0;
+ const auto frame = [&](std::vector<Bound>& out) {
+ blocks.beginFrame();
+ std::vector<PerDrawBlocks::Range> staged;
+ for (u32 i = 0; i < DRAWS; ++i) staged.push_back(blocks.stage(bytes.data(), WRITTEN));
+ const int writesBefore = device.updateBufferCalls;
+ blocks.upload();
+ uploads = device.updateBufferCalls - writesBefore;
+ for (const auto& range : staged) {
+ blocks.bind(3, range);
+ out.push_back({device.lastUniformBuffer, device.lastUniformOffset, device.lastUniformSize});
+ }
+ };
+
+ std::vector<Bound> first;
+ frame(first);
+ const int created = device.createBufferCalls - afterInit;
+ std::printf(" %u draws took %d buffers\n", DRAWS, created);
+ CHECK(created > 0 && created <= 32, "a frame of thousands of draws is a few pages");
+ CHECK(uploads == created, "a pass uploads once per page, not once per draw");
+
+ bool aligned = true, fits = true, disjoint = true, sized = true;
+ for (usize i = 0; i < first.size(); ++i) {
+ const Bound& b = first[i];
+ aligned &= b.offset % GFX_UNIFORM_OFFSET_ALIGNMENT == 0;
+ fits &= b.offset + BLOCK <= 128u * 1024u;
+ sized &= b.size == BLOCK;
+ if (i > 0 && first[i - 1].buffer == b.buffer) disjoint &= b.offset >= first[i - 1].offset + WRITTEN;
+ }
+ CHECK(aligned, "every range starts on the uniform offset alignment");
+ CHECK(fits, "every range's whole block lies inside its page");
+ CHECK(sized, "every range is bound as the block the shader declares");
+ CHECK(disjoint, "no draw's bytes are overwritten by the next draw's");
+
+ std::vector<Bound> second;
+ frame(second);
+ CHECK(device.createBufferCalls - afterInit == created, "a second frame reuses the pages");
+
+ blocks.bind(3, blocks.stage(bytes.data(), BLOCK + 16));
+ CHECK(device.lastUniformOffset == 0 && device.lastUniformSize == 0 &&
+ device.lastUniformBuffer != second.back().buffer,
+ "a write the block cannot hold binds the zero block");
+
+ if (g_failures) std::printf("%d failure(s)\n", g_failures);
+ return g_failures ? 1 : 0;
+}